lang
stringclasses
2 values
license
stringclasses
13 values
stderr
stringlengths
0
343
commit
stringlengths
40
40
returncode
int64
0
128
repos
stringlengths
6
87.7k
new_contents
stringlengths
0
6.23M
new_file
stringlengths
3
311
old_contents
stringlengths
0
6.23M
message
stringlengths
6
9.1k
old_file
stringlengths
3
311
subject
stringlengths
0
4k
git_diff
stringlengths
0
6.31M
JavaScript
mit
0c8a62e37f0d26e215aa0165a6aa78977debdcf1
0
Aedificem/ontrac,Aedificem/ontrac
function sockets() { var chat_notification = new Audio('/sounds/ding.mp3'); var full = location.protocol+'//'+location.hostname+(location.port ? ':'+location.port: ''); var socket = io.connect(full); var username = $('#send-message').data("username"); var online = []; var list = $("#online-list"); var advlist= $("#advchat-online"); var title = $("title").text(); var advisement = ( $("#advchat").length > 0 ? $("#advchat").data('adv') : ''); var advchatmessages = []; if (!localStorage['user-status']){ localStorage['user-status'] = "online"; } var status = localStorage['user-status']; $("#user-status b").html(status.charAt(0).toUpperCase() + status.substring(1)+"<span class='caret'></span>"); socket.emit('setstatus', {status: status}); socket.on('connect', function () { sessionId = socket.io.engine.id; console.log('Connected ' + sessionId); }); socket.on('error', function (reason) { console.log('Unable to connect to server', reason); }); socket.on('online-list', function(data) { online = data.users; //console.log(data.users); update_online_lists(); }); socket.on('refresh', function(data) { location.reload(); }); socket.on('new-login', function(data) { //alert("WOW"); sendNotification('info', 'User Login', data.username+' has just logged in!'); }); socket.on('new-logout', function(data) { //alert("WOW"); sendNotification('error', 'User Login', data.username+' has just logged out!'); }); // Online User List function update_online_lists() { list.html(""); if(advlist.length) advlist.html("<span>Nobody!</span>"); var names = []; var advnames = []; var count = 0; online.forEach(function(user) { if(user.status != "offline") count +=1; if(user.status != "offline") names.push("<span class='user-badge' data-username='"+user.username+"'>"+(user.username == username ? "<b>You</b>" : user.username)+" <i class='right'>"+user.status+"</i></span><br>"); if(user.status == "offline" && user.username == username) names.push("<span class='user-badge text-muted' data-username='"+username+"'><b>You</b><i class='right'>offline</i></span><br>"); console.log(user.advisement +" vs "+advisement); if(user.advisement == advisement && user.status != "offline"){ advnames.push("<span class='user-badge' data-username='"+user.username+"'>"+user.username+" <i>("+user.status+")</i></span>"); } }); $("#users-online").text(count+" user(s)"); list.html(names.join('')); if(advlist.length && advnames.length > 0) advlist.html(advnames.join(', ')); userbadges(); } // RECENT ACTIVITY if($("#recent-activity").length){ socket.on('recent-action', function(data) { alert(data); }); } // USER STATUS BUTTONS $("#user-status li a").click(function() { var status = $(this).text().toLowerCase().trim(); //alert(status); localStorage['user-status'] = status; socket.emit('setstatus', {status: status}); $("#user-status b").html($(this).text()+"<span class='caret'></span>"); }); // ADVISEMENT CHAT SYSTEM function sendAdvMessage() { var message = $('#advchat-message').val(); socket.emit("advchat-message", {message: message, when: moment().toDate()}); $('#advchat-message').val(''); } function outgoingAdvMessageKeyDown(event) { if (event.which == 13) { if ($('#advchat-message').val().trim().length <= 0) { return; } sendAdvMessage(); } } function outgoingAdvMessageKeyUp() { var message = $('#advchat-message').val(); $('#advchat-send').attr('disabled', (message.trim()).length > 0 ? false : true); } socket.emit('join-advchat'); socket.on('advchat-pastmessages', function(data) { advchatmessages = data.messages; if($("#advchat-messages").length) showAdvMessages(); }); var showAdvMessages = function() { var html = '<br>'; for(var i=0; i<advchatmessages.length; i++) { var user = advchatmessages[i].username; var message = advchatmessages[i].message; var when = moment(advchatmessages[i].when); var part = "<b class='user-badge' data-username='"+user+"'>"+user+": </b>"; part += "<span title='"+when.fromNow()+" | "+when.format("dddd, MMMM Do YYYY, h:mm:ss a")+"'>"+message+"</span><br>"; html += part; } $("#advchat-messages").html(html); $("#advchat-messages").scrollTop($("#advchat-messages")[0].scrollHeight); userbadges(); }; if($("#advchat").length){ sessionStorage.advunread = 0; socket.on('advchat-message', function(data) { console.log("New message from "+data.username+": "+data.message); if(data.message) { advchatmessages.push(data); if(data.username != username) chat_notification.play(); showAdvMessages(); } else { console.log("There is a problem:", data); } }); $('#advchat-message').on('keydown', outgoingAdvMessageKeyDown); $('#advchat-message').on('keyup', outgoingAdvMessageKeyUp); $('#advchat-send').on('click', sendAdvMessage); }else{ socket.on('advchat-message', function(data) { console.log("New message from "+data.username+": "+data.message); if(data.message) { advchatmessages.push(data); if(data.username != username) chat_notification.play(); if(!sessionStorage.advunread) sessionStorage.advunread = 0; sessionStorage.advunread = Number(sessionStorage.advunread) + 1; $("#advchat-badge").show(); $("#advchat-badge-mobile").show(); if(sessionStorage.advunread >= 50){ $("#advchat-badge").text("50+"); $("#advchat-badge-mobile").text("50+"); }else{ $("#advchat-badge").text(sessionStorage.advunread); $("#advchat-badge-mobile").text(sessionStorage.advunread); } } else { console.log("There is a problem:", data); } updateTitle(); }); } // GLOBAL CHAT SYSTEM if(sessionStorage.mute == "true") $("#mute-toggle").text("(Unmute)"); else $("#mute-toggle").text("(Mute)"); $("#mute-toggle").click(function() { sessionStorage.mute = ($(this).text() == "(Mute)" ? "true" : "false"); $(this).text( ($(this).text() == "(Mute)" ? "(Unmute)" : "(Mute)")); console.log("Chat volume is now: "+(sessionStorage.mute == "true" ? "Muted" : "Unmuted")); }); var messages = []; $("#chat-box").submit(function(e){ return false; }); socket.on('pastMessages', function(data) { messages = data.messages; showMessages(); }); var showMessages = function() { var html = '<br>'; for(var i=0; i<messages.length; i++) { var user = messages[i].username; var message = messages[i].message; var when = moment(messages[i].when); var part = "<b class='user-badge' data-username='"+user+"'>"+user+": </b>"; part += "<span title='"+when.fromNow()+" | "+when.format("dddd, MMMM Do YYYY, h:mm:ss a")+"'>"+message+"</span><br>"; html += part; } $("#chat-messages").html(html); $("#chat-messages").scrollTop($("#chat-messages")[0].scrollHeight); userbadges(); }; socket.on('message', function (data) { if(data.message) { messages.push(data); if(data.username != username && sessionStorage.mute != "true") chat_notification.play(); if(!sessionStorage.unread) sessionStorage.unread = 0; if($("#chat-box").data("hidden") == "true"){ sessionStorage.unread = Number(sessionStorage.unread)+1; updateTitle(); }else{ sessionStorage.unread = 0; } showMessages(); } else { console.log("There is a problem:", data); } }); function sendMessage() { var message = $('#chat-message').val(); socket.emit("message", {message: message, when: moment().toDate()}); } function outgoingMessageKeyDown(event) { if (event.which == 13) { if ($('#chat-message').val().trim().length <= 0) { return; } sendMessage(); $('#chat-message').val(''); } } function outgoingMessageKeyUp() { var message = $('#chat-message').val(); $('#send-message').attr('disabled', (message.trim()).length > 0 ? false : true); } $('#chat-message').on('keydown', outgoingMessageKeyDown); $('#chat-message').on('keyup', outgoingMessageKeyUp); $('#send-message').on('click', sendMessage); }
assets/js/sockets.js
function sockets() { var chat_notification = new Audio('/sounds/ding.mp3'); var full = location.protocol+'//'+location.hostname+(location.port ? ':'+location.port: ''); var socket = io.connect(full); var username = $('#send-message').data("username"); var online = []; var list = $("#online-list"); var advlist= $("#advchat-online"); var title = $("title").text(); var advisement = ( $("#advchat").length > 0 ? $("#advchat").data('adv') : ''); var advchatmessages = []; if (!localStorage['user-status']){ localStorage['user-status'] = "online"; } var status = localStorage['user-status']; $("#user-status b").html(status.charAt(0).toUpperCase() + status.substring(1)+"<span class='caret'></span>"); socket.emit('setstatus', {status: status}); socket.on('connect', function () { sessionId = socket.io.engine.id; console.log('Connected ' + sessionId); }); socket.on('error', function (reason) { console.log('Unable to connect to server', reason); }); socket.on('online-list', function(data) { online = data.users; console.log(data.users); $("#users-online").text(online.length+" user(s)"); update_online_lists(); }); socket.on('refresh', function(data) { location.reload(); }); socket.on('new-login', function(data) { //alert("WOW"); sendNotification('info', 'User Login', data.username+' has just logged in!'); }); socket.on('new-logout', function(data) { //alert("WOW"); sendNotification('error', 'User Login', data.username+' has just logged out!'); }); // Online User List function update_online_lists() { list.html(""); if(advlist.length) advlist.html(""); var names = []; var advnames = []; online.forEach(function(user) { if(user.status != "offline") names.push("<span class='user-badge' data-username='"+user.username+"'>"+(user.username == username ? "<b>You</b>" : user.username)+" <i class='right'>"+user.status+"</i></span><br>"); console.log(user.advisement +" vs "+advisement); if(user.advisement == advisement){ advnames.push("<span class='user-badge' data-username='"+user.username+"'>"+user.username+" <i>("+user.status+")</i></span>"); } }); list.html(names.join('')); if(advlist.length) advlist.html(advnames.join(', ')); userbadges(); } // RECENT ACTIVITY if($("#recent-activity").length){ socket.on('recent-action', function(data) { alert(data); }); } // USER STATUS BUTTONS $("#user-status li a").click(function() { var status = $(this).text().toLowerCase().trim(); //alert(status); localStorage['user-status'] = status; socket.emit('setstatus', {status: status}); $("#user-status b").html($(this).text()+"<span class='caret'></span>"); }); // ADVISEMENT CHAT SYSTEM function sendAdvMessage() { var message = $('#advchat-message').val(); socket.emit("advchat-message", {message: message, when: moment().toDate()}); $('#advchat-message').val(''); } function outgoingAdvMessageKeyDown(event) { if (event.which == 13) { if ($('#advchat-message').val().trim().length <= 0) { return; } sendAdvMessage(); } } function outgoingAdvMessageKeyUp() { var message = $('#advchat-message').val(); $('#advchat-send').attr('disabled', (message.trim()).length > 0 ? false : true); } socket.emit('join-advchat'); socket.on('advchat-pastmessages', function(data) { advchatmessages = data.messages; if($("#advchat-messages").length) showAdvMessages(); }); var showAdvMessages = function() { var html = '<br>'; for(var i=0; i<advchatmessages.length; i++) { var user = advchatmessages[i].username; var message = advchatmessages[i].message; var when = moment(advchatmessages[i].when); var part = "<b class='user-badge' data-username='"+user+"'>"+user+": </b>"; part += "<span title='"+when.fromNow()+" | "+when.format("dddd, MMMM Do YYYY, h:mm:ss a")+"'>"+message+"</span><br>"; html += part; } $("#advchat-messages").html(html); $("#advchat-messages").scrollTop($("#advchat-messages")[0].scrollHeight); userbadges(); }; if($("#advchat").length){ sessionStorage.advunread = 0; socket.on('advchat-message', function(data) { console.log("New message from "+data.username+": "+data.message); if(data.message) { advchatmessages.push(data); if(data.username != username) chat_notification.play(); showAdvMessages(); } else { console.log("There is a problem:", data); } }); $('#advchat-message').on('keydown', outgoingAdvMessageKeyDown); $('#advchat-message').on('keyup', outgoingAdvMessageKeyUp); $('#advchat-send').on('click', sendAdvMessage); }else{ socket.on('advchat-message', function(data) { console.log("New message from "+data.username+": "+data.message); if(data.message) { advchatmessages.push(data); if(data.username != username) chat_notification.play(); if(!sessionStorage.advunread) sessionStorage.advunread = 0; sessionStorage.advunread = Number(sessionStorage.advunread) + 1; $("#advchat-badge").show(); $("#advchat-badge-mobile").show(); if(sessionStorage.advunread >= 50){ $("#advchat-badge").text("50+"); $("#advchat-badge-mobile").text("50+"); }else{ $("#advchat-badge").text(sessionStorage.advunread); $("#advchat-badge-mobile").text(sessionStorage.advunread); } } else { console.log("There is a problem:", data); } updateTitle(); }); } // GLOBAL CHAT SYSTEM if(sessionStorage.mute == "true") $("#mute-toggle").text("(Unmute)"); else $("#mute-toggle").text("(Mute)"); $("#mute-toggle").click(function() { sessionStorage.mute = ($(this).text() == "(Mute)" ? "true" : "false"); $(this).text( ($(this).text() == "(Mute)" ? "(Unmute)" : "(Mute)")); console.log("Chat volume is now: "+(sessionStorage.mute == "true" ? "Muted" : "Unmuted")); }); var messages = []; $("#chat-box").submit(function(e){ return false; }); socket.on('pastMessages', function(data) { messages = data.messages; showMessages(); }); var showMessages = function() { var html = '<br>'; for(var i=0; i<messages.length; i++) { var user = messages[i].username; var message = messages[i].message; var when = moment(messages[i].when); var part = "<b class='user-badge' data-username='"+user+"'>"+user+": </b>"; part += "<span title='"+when.fromNow()+" | "+when.format("dddd, MMMM Do YYYY, h:mm:ss a")+"'>"+message+"</span><br>"; html += part; } $("#chat-messages").html(html); $("#chat-messages").scrollTop($("#chat-messages")[0].scrollHeight); userbadges(); }; socket.on('message', function (data) { if(data.message) { messages.push(data); if(data.username != username && sessionStorage.mute != "true") chat_notification.play(); if(!sessionStorage.unread) sessionStorage.unread = 0; if($("#chat-box").data("hidden") == "true"){ sessionStorage.unread = Number(sessionStorage.unread)+1; updateTitle(); }else{ sessionStorage.unread = 0; } showMessages(); } else { console.log("There is a problem:", data); } }); function sendMessage() { var message = $('#chat-message').val(); socket.emit("message", {message: message, when: moment().toDate()}); } function outgoingMessageKeyDown(event) { if (event.which == 13) { if ($('#chat-message').val().trim().length <= 0) { return; } sendMessage(); $('#chat-message').val(''); } } function outgoingMessageKeyUp() { var message = $('#chat-message').val(); $('#send-message').attr('disabled', (message.trim()).length > 0 ? false : true); } $('#chat-message').on('keydown', outgoingMessageKeyDown); $('#chat-message').on('keyup', outgoingMessageKeyUp); $('#send-message').on('click', sendMessage); }
Improved online user lists (closes #58 and closes #59)
assets/js/sockets.js
Improved online user lists (closes #58 and closes #59)
<ide><path>ssets/js/sockets.js <ide> }); <ide> socket.on('online-list', function(data) { <ide> online = data.users; <del> console.log(data.users); <del> $("#users-online").text(online.length+" user(s)"); <del> <add> //console.log(data.users); <ide> update_online_lists(); <del> <ide> }); <ide> socket.on('refresh', function(data) { <ide> location.reload(); <ide> function update_online_lists() { <ide> list.html(""); <ide> if(advlist.length) <del> advlist.html(""); <add> advlist.html("<span>Nobody!</span>"); <add> <ide> var names = []; <ide> var advnames = []; <add> var count = 0; <add> <ide> online.forEach(function(user) { <add> if(user.status != "offline") <add> count +=1; <ide> <ide> if(user.status != "offline") <ide> names.push("<span class='user-badge' data-username='"+user.username+"'>"+(user.username == username ? "<b>You</b>" : user.username)+" <i class='right'>"+user.status+"</i></span><br>"); <ide> <add> if(user.status == "offline" && user.username == username) <add> names.push("<span class='user-badge text-muted' data-username='"+username+"'><b>You</b><i class='right'>offline</i></span><br>"); <add> <ide> console.log(user.advisement +" vs "+advisement); <del> if(user.advisement == advisement){ <add> if(user.advisement == advisement && user.status != "offline"){ <ide> advnames.push("<span class='user-badge' data-username='"+user.username+"'>"+user.username+" <i>("+user.status+")</i></span>"); <ide> } <ide> }); <ide> <add> $("#users-online").text(count+" user(s)"); <add> <ide> list.html(names.join('')); <del> if(advlist.length) <add> if(advlist.length && advnames.length > 0) <ide> advlist.html(advnames.join(', ')); <ide> userbadges(); <ide> }
Java
apache-2.0
f46a880b65cf782d63fba98bf10d9a0c4c3cb592
0
temyers/cucumber-jvm-parallel-plugin
package com.github.timm.cucumber.generate; import com.github.timm.cucumber.generate.filter.TagFilter; import com.github.timm.cucumber.generate.name.ClassNamingScheme; import gherkin.AstBuilder; import gherkin.Parser; import gherkin.TokenMatcher; import gherkin.ast.Feature; import gherkin.ast.ScenarioDefinition; import org.apache.commons.io.FilenameUtils; import org.apache.maven.plugin.MojoExecutionException; import org.apache.velocity.Template; import org.apache.velocity.VelocityContext; import org.apache.velocity.app.VelocityEngine; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.Writer; import java.util.Collection; import java.util.Properties; /** * Generates Cucumber runner files using configuration from FileGeneratorConfig containing parameters passed into the * Maven Plugin configuration. * * @deprecated Generating runners by feature is deprecated, creating runners per scenario is preferred. This class shall * be removed in a future version. */ @Deprecated public class CucumberITGeneratorByFeature implements CucumberITGenerator { private final FileGeneratorConfig config; private final OverriddenCucumberOptionsParameters overriddenParameters; int fileCounter = 1; private String featureFileLocation; private Template velocityTemplate; private String outputFileName; private final ClassNamingScheme classNamingScheme; /** * @param config The configuration parameters passed to the Maven Mojo * @param overriddenParameters Parameters overridden from Cucumber options VM parameter (-Dcucumber.options) * @param classNamingScheme The naming scheme to use for the generated class files */ public CucumberITGeneratorByFeature(final FileGeneratorConfig config, final OverriddenCucumberOptionsParameters overriddenParameters, final ClassNamingScheme classNamingScheme) { this.config = config; this.overriddenParameters = overriddenParameters; this.classNamingScheme = classNamingScheme; initTemplate(); } private void initTemplate() { final Properties props = new Properties(); props.put("resource.loader", "class"); props.put("class.resource.loader.class", "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader"); final VelocityEngine engine = new VelocityEngine(props); engine.init(); if (config.useTestNG()) { velocityTemplate = engine.getTemplate("cucumber-testng-runner.vm", config.getEncoding()); } else { velocityTemplate = engine.getTemplate("cucumber-junit-runner.vm", config.getEncoding()); } } /** * Generates a single Cucumber runner for each separate feature file. * * @param outputDirectory the output directory to place generated files * @param featureFiles The feature files to create runners for * @throws MojoExecutionException if something goes wrong */ public void generateCucumberITFiles(final File outputDirectory, final Collection<File> featureFiles) throws MojoExecutionException { final Parser<Feature> parser = new Parser<Feature>(new AstBuilder()); Feature feature = null; for (final File file : featureFiles) { try { feature = parser.parse(new FileReader(file), new TokenMatcher()); } catch (final FileNotFoundException e) { // should never happen // TODO - proper logging System.out.println(String.format("WARNING: Failed to parse '%s'...IGNORING", file.getName())); } if (shouldSkipFeature(feature)) { continue; } // TODO - refactor - not implemented for (final ScenarioDefinition scenario : feature.getScenarioDefinitions()) { outputFileName = classNamingScheme.generate(file.getName()); setFeatureFileLocation(file); final File outputFile = new File(outputDirectory, outputFileName + ".java"); FileWriter w = null; try { w = new FileWriter(outputFile); writeContentFromTemplate(w); } catch (final IOException e) { throw new MojoExecutionException("Error creating file " + outputFile, e); } finally { if (w != null) { try { w.close(); } catch (final IOException e) { // ignore System.out.println("Failed to close file: " + outputFile); } } } fileCounter++; } } } private boolean shouldSkipFeature(final Feature feature) { if (config.filterFeaturesByTags()) { final TagFilter tagFilter = new TagFilter(overriddenParameters.getTags()); if (tagFilter.matchingScenariosAndExamples(feature).isEmpty()) { return true; } // // if (!featureContainsMatchingTags(feature)) { // return true; // } } return false; } /** * Sets the feature file location based on the given file. The full file path is trimmed to only include the * featuresDirectory. E.g. /myproject/src/test/resources/features/feature1.feature will be saved as * features/feature1.feature * * @param file The feature file */ private void setFeatureFileLocation(final File file) { final File featuresDirectory = config.getFeaturesDirectory(); featureFileLocation = file.getPath() .replace(featuresDirectory.getPath(), featuresDirectory.getName()) .replace(File.separatorChar, '/'); } private void writeContentFromTemplate(final Writer writer) { final VelocityContext context = new VelocityContext(); context.put("strict", overriddenParameters.isStrict()); context.put("featureFile", featureFileLocation); context.put("reports", createFormatStrings()); context.put("tags", overriddenParameters.getTags()); context.put("monochrome", overriddenParameters.isMonochrome()); context.put("cucumberOutputDir", config.getCucumberOutputDir()); context.put("glue", quoteGlueStrings()); context.put("className", FilenameUtils.removeExtension(outputFileName)); velocityTemplate.merge(context, writer); } /** * Create the format string used for the output. */ private String createFormatStrings() { final String[] formatStrs = overriddenParameters.getFormat().split(","); final StringBuilder sb = new StringBuilder(); for (int i = 0; i < formatStrs.length; i++) { final String formatStr = formatStrs[i].trim(); sb.append(String.format("\"%s:%s/%s.%s\"", formatStr, config.getCucumberOutputDir().replace('\\', '/'), fileCounter, formatStr)); if (i < formatStrs.length - 1) { sb.append(", "); } } return sb.toString(); } /** * Wraps each package in quotes for use in the template. */ private String quoteGlueStrings() { final String[] packageStrs = overriddenParameters.getGlue().split(","); final StringBuilder sb = new StringBuilder(); for (int i = 0; i < packageStrs.length; i++) { final String packageStr = packageStrs[i]; sb.append(String.format("\"%s\"", packageStr.trim())); if (i < packageStrs.length - 1) { sb.append(", "); } } return sb.toString(); } }
src/main/java/com/github/timm/cucumber/generate/CucumberITGeneratorByFeature.java
package com.github.timm.cucumber.generate; import com.github.timm.cucumber.generate.filter.TagFilter; import com.github.timm.cucumber.generate.name.ClassNamingScheme; import com.github.timm.cucumber.options.TagParser; import gherkin.AstBuilder; import gherkin.Parser; import gherkin.TokenMatcher; import gherkin.ast.Feature; import gherkin.ast.ScenarioDefinition; import gherkin.ast.Tag; import org.apache.commons.io.FilenameUtils; import org.apache.maven.plugin.MojoExecutionException; import org.apache.velocity.Template; import org.apache.velocity.VelocityContext; import org.apache.velocity.app.VelocityEngine; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.Writer; import java.util.Collection; import java.util.List; import java.util.Properties; /** * Generates Cucumber runner files using configuration from FileGeneratorConfig containing parameters passed into the * Maven Plugin configuration. * * @deprecated Generating runners by feature is deprecated, creating runners per scenario is preferred. This class shall * be removed in a future version. */ @Deprecated public class CucumberITGeneratorByFeature implements CucumberITGenerator { private final FileGeneratorConfig config; private final OverriddenCucumberOptionsParameters overriddenParameters; int fileCounter = 1; private String featureFileLocation; private Template velocityTemplate; private String outputFileName; private final ClassNamingScheme classNamingScheme; /** * @param config The configuration parameters passed to the Maven Mojo * @param overriddenParameters Parameters overridden from Cucumber options VM parameter (-Dcucumber.options) * @param classNamingScheme The naming scheme to use for the generated class files */ public CucumberITGeneratorByFeature(final FileGeneratorConfig config, final OverriddenCucumberOptionsParameters overriddenParameters, final ClassNamingScheme classNamingScheme) { this.config = config; this.overriddenParameters = overriddenParameters; this.classNamingScheme = classNamingScheme; initTemplate(); } private void initTemplate() { final Properties props = new Properties(); props.put("resource.loader", "class"); props.put("class.resource.loader.class", "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader"); final VelocityEngine engine = new VelocityEngine(props); engine.init(); if (config.useTestNG()) { velocityTemplate = engine.getTemplate("cucumber-testng-runner.vm", config.getEncoding()); } else { velocityTemplate = engine.getTemplate("cucumber-junit-runner.vm", config.getEncoding()); } } /** * Generates a single Cucumber runner for each separate feature file. * * @param outputDirectory the output directory to place generated files * @param featureFiles The feature files to create runners for * @throws MojoExecutionException if something goes wrong */ public void generateCucumberITFiles(final File outputDirectory, final Collection<File> featureFiles) throws MojoExecutionException { final Parser<Feature> parser = new Parser<Feature>(new AstBuilder()); Feature feature = null; for (final File file : featureFiles) { try { feature = parser.parse(new FileReader(file), new TokenMatcher()); } catch (final FileNotFoundException e) { // should never happen // TODO - proper logging System.out.println(String.format("WARNING: Failed to parse '%s'...IGNORING", file.getName())); } if (shouldSkipFeature(feature)) { continue; } // TODO - refactor - not implemented for (final ScenarioDefinition scenario : feature.getScenarioDefinitions()) { outputFileName = classNamingScheme.generate(file.getName()); setFeatureFileLocation(file); final File outputFile = new File(outputDirectory, outputFileName + ".java"); FileWriter w = null; try { w = new FileWriter(outputFile); writeContentFromTemplate(w); } catch (final IOException e) { throw new MojoExecutionException("Error creating file " + outputFile, e); } finally { if (w != null) { try { w.close(); } catch (final IOException e) { // ignore System.out.println("Failed to close file: " + outputFile); } } } fileCounter++; } } } private boolean shouldSkipFeature(final Feature feature) { if (config.filterFeaturesByTags()) { final TagFilter tagFilter = new TagFilter(overriddenParameters.getTags()); if (tagFilter.matchingScenariosAndExamples(feature).isEmpty()) { return true; } // // if (!featureContainsMatchingTags(feature)) { // return true; // } } return false; } private boolean featureContainsMatchingTags(final Feature feature) { final List<List<String>> tagGroupsAnded = TagParser.splitQuotedTagsIntoParts(overriddenParameters.getTags()); // Tag groups are and'd together for (final List<String> tagGroup : tagGroupsAnded) { // individual tags are or'd together if (!featureContainsAnyTags(feature, tagGroup)) { return false; } } return true; } private boolean featureContainsAnyTags(final Feature feature, final List<String> expectedTags) { final List<ScenarioDefinition> scenarios = feature.getScenarioDefinitions(); for (final String tag : expectedTags) { if (tag.startsWith("~")) { // not tags must be ignored - cannot guarantee that a feature // file containing an ignored tag does not contain scenarios // that // should be included return true; } for (final Tag actualTag : feature.getTags()) { if (actualTag.getName().equals(tag)) { return true; } } for (final ScenarioDefinition scenario : scenarios) { for (final Tag actualTag : scenario.getTags()) { if (actualTag.getName().equals(tag)) { return true; } } } } return false; } /** * Sets the feature file location based on the given file. The full file path is trimmed to only include the * featuresDirectory. E.g. /myproject/src/test/resources/features/feature1.feature will be saved as * features/feature1.feature * * @param file The feature file */ private void setFeatureFileLocation(final File file) { final File featuresDirectory = config.getFeaturesDirectory(); featureFileLocation = file.getPath() .replace(featuresDirectory.getPath(), featuresDirectory.getName()) .replace(File.separatorChar, '/'); } private void writeContentFromTemplate(final Writer writer) { final VelocityContext context = new VelocityContext(); context.put("strict", overriddenParameters.isStrict()); context.put("featureFile", featureFileLocation); context.put("reports", createFormatStrings()); context.put("tags", overriddenParameters.getTags()); context.put("monochrome", overriddenParameters.isMonochrome()); context.put("cucumberOutputDir", config.getCucumberOutputDir()); context.put("glue", quoteGlueStrings()); context.put("className", FilenameUtils.removeExtension(outputFileName)); velocityTemplate.merge(context, writer); } /** * Create the format string used for the output. */ private String createFormatStrings() { final String[] formatStrs = overriddenParameters.getFormat().split(","); final StringBuilder sb = new StringBuilder(); for (int i = 0; i < formatStrs.length; i++) { final String formatStr = formatStrs[i].trim(); sb.append(String.format("\"%s:%s/%s.%s\"", formatStr, config.getCucumberOutputDir().replace('\\', '/'), fileCounter, formatStr)); if (i < formatStrs.length - 1) { sb.append(", "); } } return sb.toString(); } /** * Wraps each package in quotes for use in the template. */ private String quoteGlueStrings() { final String[] packageStrs = overriddenParameters.getGlue().split(","); final StringBuilder sb = new StringBuilder(); for (int i = 0; i < packageStrs.length; i++) { final String packageStr = packageStrs[i]; sb.append(String.format("\"%s\"", packageStr.trim())); if (i < packageStrs.length - 1) { sb.append(", "); } } return sb.toString(); } }
refactor - remove dead code
src/main/java/com/github/timm/cucumber/generate/CucumberITGeneratorByFeature.java
refactor - remove dead code
<ide><path>rc/main/java/com/github/timm/cucumber/generate/CucumberITGeneratorByFeature.java <ide> <ide> import com.github.timm.cucumber.generate.filter.TagFilter; <ide> import com.github.timm.cucumber.generate.name.ClassNamingScheme; <del>import com.github.timm.cucumber.options.TagParser; <ide> import gherkin.AstBuilder; <ide> import gherkin.Parser; <ide> import gherkin.TokenMatcher; <ide> import gherkin.ast.Feature; <ide> import gherkin.ast.ScenarioDefinition; <del>import gherkin.ast.Tag; <ide> import org.apache.commons.io.FilenameUtils; <ide> import org.apache.maven.plugin.MojoExecutionException; <ide> import org.apache.velocity.Template; <ide> import java.io.IOException; <ide> import java.io.Writer; <ide> import java.util.Collection; <del>import java.util.List; <ide> import java.util.Properties; <ide> <ide> /** <ide> System.out.println(String.format("WARNING: Failed to parse '%s'...IGNORING", <ide> file.getName())); <ide> } <del> <ide> <ide> if (shouldSkipFeature(feature)) { <ide> continue; <ide> return false; <ide> } <ide> <del> private boolean featureContainsMatchingTags(final Feature feature) { <del> final List<List<String>> tagGroupsAnded = <del> TagParser.splitQuotedTagsIntoParts(overriddenParameters.getTags()); <del> // Tag groups are and'd together <del> for (final List<String> tagGroup : tagGroupsAnded) { <del> // individual tags are or'd together <del> if (!featureContainsAnyTags(feature, tagGroup)) { <del> return false; <del> } <del> } <del> return true; <del> } <del> <del> private boolean featureContainsAnyTags(final Feature feature, final List<String> expectedTags) { <del> final List<ScenarioDefinition> scenarios = feature.getScenarioDefinitions(); <del> for (final String tag : expectedTags) { <del> if (tag.startsWith("~")) { <del> // not tags must be ignored - cannot guarantee that a feature <del> // file containing an ignored tag does not contain scenarios <del> // that <del> // should be included <del> return true; <del> } <del> for (final Tag actualTag : feature.getTags()) { <del> if (actualTag.getName().equals(tag)) { <del> return true; <del> } <del> } <del> for (final ScenarioDefinition scenario : scenarios) { <del> <del> for (final Tag actualTag : scenario.getTags()) { <del> if (actualTag.getName().equals(tag)) { <del> return true; <del> } <del> } <del> } <del> <del> } <del> return false; <del> } <del> <ide> /** <ide> * Sets the feature file location based on the given file. The full file path is trimmed to only include the <ide> * featuresDirectory. E.g. /myproject/src/test/resources/features/feature1.feature will be saved as
Java
apache-2.0
b637b0c7888c065ccce144f1e02af5ebaac2c0b2
0
TopQuadrant/shacl,TopQuadrant/shacl
package org.topbraid.shacl.compact; import java.io.OutputStream; import java.io.Writer; import java.util.Collections; import java.util.Comparator; import java.util.LinkedList; import java.util.List; import java.util.Set; import org.apache.jena.atlas.io.IndentedWriter; import org.apache.jena.ext.com.google.common.collect.Sets; import org.apache.jena.graph.Graph; import org.apache.jena.rdf.model.Model; import org.apache.jena.rdf.model.ModelFactory; import org.apache.jena.rdf.model.Property; import org.apache.jena.rdf.model.RDFNode; import org.apache.jena.rdf.model.Resource; import org.apache.jena.rdf.model.Statement; import org.apache.jena.riot.Lang; import org.apache.jena.riot.system.PrefixMap; import org.apache.jena.riot.system.RiotLib; import org.apache.jena.riot.writer.WriterGraphRIOTBase; import org.apache.jena.sparql.util.Context; import org.apache.jena.sparql.util.FmtUtils; import org.apache.jena.vocabulary.OWL; import org.apache.jena.vocabulary.RDF; import org.topbraid.jenax.util.JenaUtil; import org.topbraid.shacl.arq.SHACLPaths; import org.topbraid.shacl.vocabulary.SH; /** * This is an incomplete converter from RDF graphs to SHACLC format that is barely tested. * SHACLC only covers a subset of RDF and SHACL, so not all SHACL graphs can be meaningfully represented. * * @author Holger Knublauch */ public class SHACLCWriter extends WriterGraphRIOTBase { private static Set<Property> specialPropertyProperties = Sets.newHashSet( RDF.type, SH.path, SH.datatype, SH.class_, SH.minCount, SH.maxCount, SH.node, SH.nodeKind ); private static Set<Property> specialShapeProperties = Sets.newHashSet( RDF.type, SH.property, SH.node ); @Override public Lang getLang() { return SHACLC.lang; } protected void warn(String message) { System.err.println("Warning: " + message); } @Override public void write(Writer out, Graph graph, PrefixMap prefixMap, String baseURI, Context context) { IndentedWriter iOut = RiotLib.create(out); iOut.setUnitIndent(1); iOut.setPadChar('\t'); write(iOut, graph, prefixMap, baseURI, context); } @Override public void write(OutputStream out, Graph graph, PrefixMap prefixMap, String baseURI, Context context) { IndentedWriter iOut = new IndentedWriter(out); iOut.setUnitIndent(1); iOut.setPadChar('\t'); write(iOut, graph, prefixMap, baseURI, context); } private void write(IndentedWriter out, Graph graph, PrefixMap prefixMap, String baseURI, Context context) { Model model = ModelFactory.createModelForGraph(graph); if(baseURI != null) { out.println("BASE <" + baseURI + ">"); out.println(); } writeImports(out, model.getResource(baseURI)); writePrefixes(out, prefixMap); writeShapes(out, model); out.flush(); } private void writeImports(IndentedWriter out, Resource ontology) { List<Resource> imports = JenaUtil.getResourceProperties(ontology, OWL.imports); Collections.sort(imports, new Comparator<Resource>() { @Override public int compare(Resource o1, Resource o2) { return o1.getURI().compareTo(o2.getURI()); } }); if(!imports.isEmpty()) { for(Resource imp : imports) { out.println("IMPORTS <" + imp.getURI() + ">"); } out.println(); } } private void writePrefixes(IndentedWriter out, PrefixMap prefixMap) { List<String> prefixes = new LinkedList<String>(prefixMap.getMapping().keySet()); if(!prefixes.isEmpty()) { Collections.sort(prefixes); for(String prefix : prefixes) { if(SHACLC.getDefaultPrefixURI(prefix) == null) { out.println("PREFIX " + prefix + ": <" + prefixMap.expand(prefix + ":") + ">"); } } out.println(); } } private void writeShapes(IndentedWriter out, Model model) { List<Resource> shapes = new LinkedList<>(); for(Resource shape : JenaUtil.getAllInstances(SH.NodeShape.inModel(model))) { if(shape.isURIResource()) { shapes.add(shape); } } // Collections.sort(shapes, ResourceComparator.get()); for(int i = 0; i < shapes.size(); i++) { if(i > 0) { out.println(); } writeShape(out, shapes.get(i)); } } private void writeShape(IndentedWriter out, Resource shape) { out.print("shape " + iri(shape)); writeShapeBody(out, shape); } private void writeShapeBody(IndentedWriter out, Resource shape) { writeExtraStatements(out, shape, specialShapeProperties, false); out.println(" {"); out.incIndent(); List<Resource> properties = new LinkedList<>(); for(Resource property : JenaUtil.getResourceProperties(shape, SH.property)) { properties.add(property); } Collections.sort(properties, new Comparator<Resource>() { @Override public int compare(Resource arg1, Resource arg2) { String path1 = getPathString(arg1); String path2 = getPathString(arg2); return path1.compareTo(path2); } }); for(Resource property : properties) { writeProperty(out, property); } out.decIndent(); out.println("}"); } private void writeProperty(IndentedWriter out, Resource property) { out.print(getPathString(property)); out.print(" "); out.print(getPropertyTypes(property)); // Count block out.print(" "); out.print("["); Statement minCountS = property.getProperty(SH.minCount); if(minCountS != null) { out.print("" + minCountS.getInt()); } else { out.print("0"); } out.print(".."); Statement maxCountS = property.getProperty(SH.maxCount); if(maxCountS != null) { out.print("" + maxCountS.getInt()); } else { out.print("*"); } out.print("]"); writeExtraStatements(out, property, specialPropertyProperties, false); writeNestedShapes(out, property); out.println(" ;"); } private void writeExtraStatements(IndentedWriter out, Resource subject, Set<Property> specialProperties, boolean wrapped) { List<Statement> extras = getExtraStatements(subject, specialProperties); if(!extras.isEmpty()) { if(wrapped) { out.print("( "); } for(Statement s : extras) { out.print(" " + getPredicateName(s.getPredicate())); out.print("="); out.print(node(s.getObject())); } if(wrapped) { out.print(" )"); } } } private void writeNestedShapes(IndentedWriter out, Resource subject) { for(Resource node : JenaUtil.getResourceProperties(subject, SH.node)) { if(node.isAnon()) { writeShapeBody(out, node); } } } private List<Statement> getExtraStatements(Resource subject, Set<Property> specialProperties) { List<Statement> results = new LinkedList<>(); for(Statement s : subject.listProperties().toList()) { if(SH.NS.equals(s.getPredicate().getNameSpace()) && !specialProperties.contains(s.getPredicate()) && !s.getObject().isAnon()) { results.add(s); } } Collections.sort(results, new Comparator<Statement>() { @Override public int compare(Statement o1, Statement o2) { String pred1 = getPredicateName(o1.getPredicate()); String pred2 = getPredicateName(o2.getPredicate()); int preds = pred1.compareTo(pred2); if(preds != 0) { return preds; } else { String lex1 = node(o1.getObject()); String lex2 = node(o2.getObject()); return lex1.compareTo(lex2); } } }); return results; } private String getPathString(Resource property) { Resource path = property.getPropertyResourceValue(SH.path); return SHACLPaths.getPathString(path); } private String getPredicateName(Property predicate) { return predicate.getLocalName(); } private String getPropertyTypes(Resource property) { List<String> types = new LinkedList<>(); for(Resource clas : JenaUtil.getResourceProperties(property, SH.class_)) { types.add(iri(clas)); } for(Resource datatype : JenaUtil.getResourceProperties(property, SH.datatype)) { types.add(iri(datatype)); } for(Resource node : JenaUtil.getResourceProperties(property, SH.node)) { if(node.isURIResource()) { types.add("@" + iri(node)); } } Resource nodeKind = property.getPropertyResourceValue(SH.nodeKind); if(nodeKind != null) { types.add(nodeKind.getLocalName()); } Collections.sort(types); StringBuffer sb = new StringBuffer(); for(int i = 0; i < types.size(); i++) { if(i > 0) { sb.append(" "); } sb.append(types.get(i)); } return sb.toString(); } private String iri(Resource resource) { String qname = resource.getModel().qnameFor(resource.getURI()); if(qname != null) { return qname; } else { return "<" + resource.getURI() + ">"; } } private String node(RDFNode node) { if(node.isURIResource()) { return iri((Resource)node); } else if(node.isLiteral()) { return FmtUtils.stringForNode(node.asNode()); } else { // TODO? return null; } } }
src/main/java/org/topbraid/shacl/compact/SHACLCWriter.java
package org.topbraid.shacl.compact; import java.io.OutputStream; import java.io.Writer; import java.util.Collections; import java.util.Comparator; import java.util.LinkedList; import java.util.List; import java.util.Set; import org.apache.jena.atlas.io.IndentedWriter; import org.apache.jena.ext.com.google.common.collect.Sets; import org.apache.jena.graph.Graph; import org.apache.jena.rdf.model.Model; import org.apache.jena.rdf.model.ModelFactory; import org.apache.jena.rdf.model.Property; import org.apache.jena.rdf.model.RDFNode; import org.apache.jena.rdf.model.Resource; import org.apache.jena.rdf.model.Statement; import org.apache.jena.riot.Lang; import org.apache.jena.riot.system.PrefixMap; import org.apache.jena.riot.system.RiotLib; import org.apache.jena.riot.writer.WriterGraphRIOTBase; import org.apache.jena.sparql.util.Context; import org.apache.jena.sparql.util.FmtUtils; import org.apache.jena.vocabulary.OWL; import org.apache.jena.vocabulary.RDF; import org.topbraid.jenax.util.JenaUtil; import org.topbraid.shacl.arq.SHACLPaths; import org.topbraid.shacl.vocabulary.SH; /** * This is an incomplete converter from RDF graphs to SHACLC format that is barely tested. * SHACLC only covers a subset of RDF and SHACL, so not all SHACL graphs can be meaningfully represented. * * @author Holger Knublauch */ public class SHACLCWriter extends WriterGraphRIOTBase { private static Set<Property> specialPropertyProperties = Sets.newHashSet( RDF.type, SH.path, SH.datatype, SH.class_, SH.minCount, SH.maxCount, SH.node, SH.nodeKind ); private static Set<Property> specialShapeProperties = Sets.newHashSet( RDF.type, SH.property, SH.node ); @Override public Lang getLang() { return SHACLC.lang; } protected void warn(String message) { System.err.println("Warning: " + message); } @Override public void write(Writer out, Graph graph, PrefixMap prefixMap, String baseURI, Context context) { IndentedWriter iOut = RiotLib.create(out); iOut.setUnitIndent(1); iOut.setPadChar('\t'); write(iOut, graph, prefixMap, baseURI, context); } @Override public void write(OutputStream out, Graph graph, PrefixMap prefixMap, String baseURI, Context context) { IndentedWriter iOut = new IndentedWriter(out); iOut.setUnitIndent(1); iOut.setPadChar('\t'); write(iOut, graph, prefixMap, baseURI, context); } private void write(IndentedWriter out, Graph graph, PrefixMap prefixMap, String baseURI, Context context) { Model model = ModelFactory.createModelForGraph(graph); out.println("BASE <" + baseURI + ">"); out.println(); writeImports(out, model.getResource(baseURI)); writePrefixes(out, prefixMap); writeShapes(out, model); out.flush(); } private void writeImports(IndentedWriter out, Resource ontology) { List<Resource> imports = JenaUtil.getResourceProperties(ontology, OWL.imports); Collections.sort(imports, new Comparator<Resource>() { @Override public int compare(Resource o1, Resource o2) { return o1.getURI().compareTo(o2.getURI()); } }); if(!imports.isEmpty()) { for(Resource imp : imports) { out.println("IMPORTS <" + imp.getURI() + ">"); } out.println(); } } private void writePrefixes(IndentedWriter out, PrefixMap prefixMap) { List<String> prefixes = new LinkedList<String>(prefixMap.getMapping().keySet()); if(!prefixes.isEmpty()) { Collections.sort(prefixes); for(String prefix : prefixes) { if(SHACLC.getDefaultPrefixURI(prefix) == null) { out.println("PREFIX " + prefix + ": <" + prefixMap.expand(prefix + ":") + ">"); } } out.println(); } } private void writeShapes(IndentedWriter out, Model model) { List<Resource> shapes = new LinkedList<>(); for(Resource shape : JenaUtil.getAllInstances(SH.NodeShape.inModel(model))) { if(shape.isURIResource()) { shapes.add(shape); } } // Collections.sort(shapes, ResourceComparator.get()); for(int i = 0; i < shapes.size(); i++) { if(i > 0) { out.println(); } writeShape(out, shapes.get(i)); } } private void writeShape(IndentedWriter out, Resource shape) { out.print("" + iri(shape)); writeShapeBody(out, shape); } private void writeShapeBody(IndentedWriter out, Resource shape) { writeExtraStatements(out, shape, specialShapeProperties, false); out.println(" {"); out.incIndent(); List<Resource> properties = new LinkedList<>(); for(Resource property : JenaUtil.getResourceProperties(shape, SH.property)) { properties.add(property); } Collections.sort(properties, new Comparator<Resource>() { @Override public int compare(Resource arg1, Resource arg2) { String path1 = getPathString(arg1); String path2 = getPathString(arg2); return path1.compareTo(path2); } }); for(Resource property : properties) { writeProperty(out, property); } out.decIndent(); out.println("}"); } private void writeProperty(IndentedWriter out, Resource property) { out.print(getPathString(property)); out.print(" "); out.print(getPropertyTypes(property)); // Count block out.print(" "); out.print("["); Statement minCountS = property.getProperty(SH.minCount); if(minCountS != null) { out.print("" + minCountS.getInt()); } else { out.print("0"); } out.print(".."); Statement maxCountS = property.getProperty(SH.maxCount); if(maxCountS != null) { out.print("" + maxCountS.getInt()); } else { out.print("*"); } out.print("]"); writeExtraStatements(out, property, specialPropertyProperties, false); writeNestedShapes(out, property); out.println(" ;"); } private void writeExtraStatements(IndentedWriter out, Resource subject, Set<Property> specialProperties, boolean wrapped) { List<Statement> extras = getExtraStatements(subject, specialProperties); if(!extras.isEmpty()) { if(wrapped) { out.print("( "); } for(Statement s : extras) { out.print(" " + getPredicateName(s.getPredicate())); out.print("="); out.print(node(s.getObject())); } if(wrapped) { out.print(" )"); } } } private void writeNestedShapes(IndentedWriter out, Resource subject) { for(Resource node : JenaUtil.getResourceProperties(subject, SH.node)) { if(node.isAnon()) { writeShapeBody(out, node); } } } private List<Statement> getExtraStatements(Resource subject, Set<Property> specialProperties) { List<Statement> results = new LinkedList<>(); for(Statement s : subject.listProperties().toList()) { if(SH.NS.equals(s.getPredicate().getNameSpace()) && !specialProperties.contains(s.getPredicate()) && !s.getObject().isAnon()) { results.add(s); } } Collections.sort(results, new Comparator<Statement>() { @Override public int compare(Statement o1, Statement o2) { String pred1 = getPredicateName(o1.getPredicate()); String pred2 = getPredicateName(o2.getPredicate()); int preds = pred1.compareTo(pred2); if(preds != 0) { return preds; } else { String lex1 = node(o1.getObject()); String lex2 = node(o2.getObject()); return lex1.compareTo(lex2); } } }); return results; } private String getPathString(Resource property) { Resource path = property.getPropertyResourceValue(SH.path); return SHACLPaths.getPathString(path); } private String getPredicateName(Property predicate) { return predicate.getLocalName(); } private String getPropertyTypes(Resource property) { List<String> types = new LinkedList<>(); for(Resource clas : JenaUtil.getResourceProperties(property, SH.class_)) { types.add(iri(clas)); } for(Resource datatype : JenaUtil.getResourceProperties(property, SH.datatype)) { types.add(iri(datatype)); } for(Resource node : JenaUtil.getResourceProperties(property, SH.node)) { if(node.isURIResource()) { types.add("@" + iri(node)); } } Resource nodeKind = property.getPropertyResourceValue(SH.nodeKind); if(nodeKind != null) { types.add(nodeKind.getLocalName()); } Collections.sort(types); StringBuffer sb = new StringBuffer(); for(int i = 0; i < types.size(); i++) { if(i > 0) { sb.append(" "); } sb.append(types.get(i)); } return sb.toString(); } private String iri(Resource resource) { String qname = resource.getModel().qnameFor(resource.getURI()); if(qname != null) { return qname; } else { return "<" + resource.getURI() + ">"; } } private String node(RDFNode node) { if(node.isURIResource()) { return iri((Resource)node); } else if(node.isLiteral()) { return FmtUtils.stringForNode(node.asNode()); } else { // TODO? return null; } } }
Restored accidentally overwritten changes to SHACLCWriter (incomplete anyway)
src/main/java/org/topbraid/shacl/compact/SHACLCWriter.java
Restored accidentally overwritten changes to SHACLCWriter (incomplete anyway)
<ide><path>rc/main/java/org/topbraid/shacl/compact/SHACLCWriter.java <ide> <ide> private void write(IndentedWriter out, Graph graph, PrefixMap prefixMap, String baseURI, Context context) { <ide> Model model = ModelFactory.createModelForGraph(graph); <del> out.println("BASE <" + baseURI + ">"); <del> out.println(); <add> if(baseURI != null) { <add> out.println("BASE <" + baseURI + ">"); <add> out.println(); <add> } <ide> writeImports(out, model.getResource(baseURI)); <ide> writePrefixes(out, prefixMap); <ide> writeShapes(out, model); <ide> <ide> <ide> private void writeShape(IndentedWriter out, Resource shape) { <del> out.print("" + iri(shape)); <add> out.print("shape " + iri(shape)); <ide> writeShapeBody(out, shape); <ide> } <ide>
Java
lgpl-2.1
e9eee5449216295a52a5d3ee833ead3f058d5d1f
0
ethaneldridge/vassal,ethaneldridge/vassal,ethaneldridge/vassal
/* * * Copyright (c) 2000-2003 by Rodney Kinney, Jim Urbas * Refactoring of DragHandler Copyright 2011 Pieter Geerkens * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License (LGPL) as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public * License along with this library; if not, copies are available * at http://www.opensource.org. */ package VASSAL.build.module.map; import VASSAL.i18n.Resources; import VASSAL.tools.ProblemDialog; import java.awt.AlphaComposite; import java.awt.Color; import java.awt.Component; import java.awt.Cursor; import java.awt.Graphics2D; import java.awt.Image; import java.awt.Point; import java.awt.Rectangle; import java.awt.RenderingHints; import java.awt.datatransfer.StringSelection; import java.awt.dnd.DragGestureEvent; import java.awt.dnd.DragGestureListener; import java.awt.dnd.DragSource; import java.awt.dnd.DragSourceDragEvent; import java.awt.dnd.DragSourceDropEvent; import java.awt.dnd.DragSourceEvent; import java.awt.dnd.DragSourceListener; import java.awt.dnd.DragSourceMotionListener; import java.awt.dnd.DropTarget; import java.awt.dnd.DropTargetDragEvent; import java.awt.dnd.DropTargetDropEvent; import java.awt.dnd.DropTargetEvent; import java.awt.dnd.DropTargetListener; import java.awt.dnd.InvalidDnDOperationException; import java.awt.event.ActionListener; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.awt.image.BufferedImage; import java.util.ArrayList; import java.util.Collection; import java.util.Comparator; import java.util.HashMap; import java.util.List; import javax.swing.ImageIcon; import javax.swing.JLabel; import javax.swing.JLayeredPane; import javax.swing.JRootPane; import javax.swing.KeyStroke; import javax.swing.SwingUtilities; import org.apache.commons.lang3.SystemUtils; import VASSAL.build.AbstractBuildable; import VASSAL.build.Buildable; import VASSAL.build.GameModule; import VASSAL.build.module.GameComponent; import VASSAL.build.module.GlobalOptions; import VASSAL.build.module.Map; import VASSAL.build.module.map.boardPicker.Board; import VASSAL.command.ChangeTracker; import VASSAL.command.Command; import VASSAL.command.NullCommand; import VASSAL.configure.BooleanConfigurer; import VASSAL.counters.BasicPiece; import VASSAL.counters.BoundsTracker; import VASSAL.counters.Deck; import VASSAL.counters.DeckVisitor; import VASSAL.counters.DeckVisitorDispatcher; import VASSAL.counters.Decorator; import VASSAL.counters.DragBuffer; import VASSAL.counters.EventFilter; import VASSAL.counters.GamePiece; import VASSAL.counters.Highlighter; import VASSAL.counters.KeyBuffer; import VASSAL.counters.PieceFinder; import VASSAL.counters.PieceIterator; import VASSAL.counters.PieceSorter; import VASSAL.counters.PieceVisitorDispatcher; import VASSAL.counters.Properties; import VASSAL.counters.PropertyExporter; import VASSAL.counters.Stack; import VASSAL.tools.LaunchButton; import VASSAL.tools.image.ImageUtils; import VASSAL.tools.imageop.Op; import VASSAL.tools.swing.SwingUtils; /** * PieceMover handles the "Drag and Drop" of pieces and stacks, onto or within a Map window. It implements * MouseListener and handles dragging and dropping of both individual pieces, stacks, and groups of * pieces/stacks. It is a subcomponent of Map. * <br><br> * For the selection/deselection of pieces and band-selecting pieces by "dragging a lasso around them", * see {@link KeyBufferer}. */ public class PieceMover extends AbstractBuildable implements MouseListener, GameComponent, Comparator<GamePiece> { /** The Preferences key for auto-reporting moves. */ public static final String AUTO_REPORT = "autoReport"; //$NON-NLS-1$ public static final String NAME = "name"; //NON-NLS public static final String HOTKEY = "hotkey"; //NON-NLS protected Map map; // Map we're the PieceMover for. protected Point dragBegin; // Anchor point for drag and drop protected GamePiece dragging; // Anchor piece that we're dragging (along with everything else in DragBuffer) // PieceMover provides the "clear move history" button for Map - the configurer dialog is found there. protected LaunchButton markUnmovedButton; protected String markUnmovedText; protected String markUnmovedIcon; public static final String ICON_NAME = "icon"; //$NON-NLS-1$ protected String iconName; protected PieceFinder dragTargetSelector; // Selects drag target from mouse click on the Map protected PieceFinder dropTargetSelector; // Selects piece to merge with at the drop destination protected PieceVisitorDispatcher selectionProcessor; // Processes drag target after having been selected protected Comparator<GamePiece> pieceSorter = new PieceSorter(); /** * Adds this component to its parent map. Add ourselves as a mouse listener, drag gesture listener, etc. * @param b Map to add to */ @Override public void addTo(Buildable b) { // Create our target selection filters dragTargetSelector = createDragTargetSelector(); dropTargetSelector = createDropTargetSelector(); selectionProcessor = createSelectionProcessor(); // Register with our parent map map = (Map) b; map.addLocalMouseListener(this); GameModule.getGameModule().getGameState().addGameComponent(this); map.setDragGestureListener(DragHandler.getTheDragHandler()); map.setPieceMover(this); // Because of the strange legacy scheme of halfway-running a Toolbar button "on behalf of Map", we have to set some its attributes setAttribute(Map.MARK_UNMOVED_TEXT, map.getAttributeValueString(Map.MARK_UNMOVED_TEXT)); setAttribute(Map.MARK_UNMOVED_ICON, map.getAttributeValueString(Map.MARK_UNMOVED_ICON)); } /** * Creates a {@link MovementReporter} for a collection of commands containing AddPiece and MovePiece commands, which * will supply auto-report messages corresponding to those commands * @param c Command -- presumably including some AddPiece and MovePiece commands. * @return MovementReporter to auto-report the command(s) */ protected MovementReporter createMovementReporter(Command c) { return new MovementReporter(c); } /** * Reports the image files we use (forremove-unwanted-image-files and/or search) * @param s Collection to add image names to */ @Override public void addLocalImageNames(Collection<String> s) { if (iconName != null) s.add(iconName); if (markUnmovedIcon != null) s.add(markUnmovedIcon); } /** * When the user *completes* a drag-and-drop operation, the pieces being dragged will either be: * <br>(1) combined in a stack with an existing piece (or stack, or deck) on the map * <br>(2) placed alone in a brand new stack * <br>(3) or, in the case of non-stacking pieces, placed on the map without stack. * <br><br> * For <i>each</i> of the stacks/pieces being dragged, we need to determine which of those outcomes * applies. This "drop target selector" will be fed, one by one, all of the pieces on the map, and for * each one must check whether it would make a valid "merge target" for the current dragged piece under * consideration (the PieceFinder's {@link PieceFinder#select} method provides the map and location, and * the PieceMover's {@link PieceMover#dragging} field tells the "dragged piece under consideration". Each * method is to returns the target piece/stack/deck to merge with if it has been passed a valid target, or * null if it is not a valid match. * <br><br> * The Map's {@link Map#findAnyPiece(Point, PieceFinder)} method, which feeds this, will be responsible for * iterating through the list of possible pieces in proper visual order so that we check the pieces "visually * on top" first. * <br><br> * @return a {@link PieceFinder} instance that determines which {@link GamePiece} (if any) to * combine the being-dragged pieces with. */ protected PieceFinder createDropTargetSelector() { return new PieceFinder.Movable() { /** * When a deck exists on the map, and we need to find out if our piece was dragged to the deck * @param d Potential target {@link Deck} * @return the Deck if our target location is inside the footprint of the Deck, or null if not */ @Override public Object visitDeck(Deck d) { final Point pos = d.getPosition(); final Point p = new Point(pt.x - pos.x, pt.y - pos.y); return d.getShape().contains(p) ? d : null; } /** * When an unstacked piece exists on the map, we see if this is a piece we could * form a stack with -- if it is at our precise location (or the location we would * be getting snapped to). We must also check if stacking is enabled and if both * the target "piece" and the "dragging" piece fit all the usual "can merge" requirements * (both are "stacking" pieces, and in the same visual layer) * @param piece Potential target piece on the map. * @return The piece to stack with, if we should, otherwise null. */ @Override public Object visitDefault(GamePiece piece) { GamePiece selected = null; if (this.map.getStackMetrics().isStackingEnabled() && this.map.getPieceCollection().canMerge(dragging, piece)) { if (this.map.isLocationRestricted(pt)) { final Point snap = this.map.snapTo(pt); if (piece.getPosition().equals(snap)) { selected = piece; } } else { // The "super" visitDefault checks if our point is inside the visual boundaries of the piece. selected = (GamePiece) super.visitDefault(piece); } } // We don't drag a piece "to itself". if (selected != null && DragBuffer.getBuffer().contains(selected) && selected.getParent() != null && selected.getParent().topPiece() == selected) { //NOTE: topPiece() returns the top VISIBLE piece (not hidden by Invisible trait) selected = null; } return selected; } /** * When a stack already exists on the map, we see if this piece could be added to it. * @param s Stack to check if we're appropriately configured to merge with * @return The piece to stack with, if we should, otherwise null. */ @Override public Object visitStack(Stack s) { GamePiece selected = null; if (this.map.getStackMetrics().isStackingEnabled() && this.map.getPieceCollection().canMerge(dragging, s) && !DragBuffer.getBuffer().contains(s) && !DragBuffer.getBuffer().containsAllMembers(s) && //BR// Don't merge back into a stack we are in the act of emptying s.topPiece() != null) { //NOTE: topPiece() returns the top VISIBLE piece (not hidden by Invisible trait) if (this.map.isLocationRestricted(pt) && !s.isExpanded()) { if (s.getPosition().equals(this.map.snapTo(pt))) { selected = s; } } else { // The super's visitStack handles checking to see if our point is inside the visual "shape" of the stack selected = (GamePiece) super.visitStack(s); } } return selected; } }; } /** * When the user *starts* a potential drag-and-drop operation by clicking * on the map, a piece from the map is selected by the dragTargetSelector. * What happens to that piece is determined by the {@link PieceVisitorDispatcher} * instance returned by this method. The default implementation does the following: * <br>(1) If a Deck, add the (single) top piece to the drag buffer * <br>(2) If a stack, add it to the drag buffer. If the stack is a member of the "currently selected pieces" * (i.e. {@link KeyBuffer}), then add any other already-selected pieces and stacks to the drag buffer as well. * <br>(3) Otherwise, add the piece and any other multi-selected pieces and stacks to the drag buffer. * * @see #createDragTargetSelector * @return Dispatcher */ protected PieceVisitorDispatcher createSelectionProcessor() { return new DeckVisitorDispatcher(new DeckVisitor() { /** * We've picked a Deck - Clear the drag buffer and add Deck's top piece to the drag buffer. * @param d Deck we clicked on * @return null */ @Override public Object visitDeck(Deck d) { final DragBuffer dbuf = DragBuffer.getBuffer(); dbuf.clear(); for (final PieceIterator it = d.drawCards(); it.hasMoreElements();) { final GamePiece p = it.nextPiece(); p.setProperty(Properties.OBSCURED_BY, p.getProperty(Properties.OBSCURED_BY_PRE_DRAW)); // Bug 13433 restore correct OBSCURED_BY dbuf.add(p); } return null; } /** * We've picked a Stack. Clear the drag buffer and add the stack's pieces to it. If the stack is part of the * "currently selected pieces" (i.e. {@link KeyBuffer}), then add any other pieces/stacks as well. * @param s Stack we clicked on * @return null */ @Override public Object visitStack(Stack s) { final DragBuffer dbuf = DragBuffer.getBuffer(); dbuf.clear(); // RFE 1629255 - Only add selected pieces within the stack to the DragBuffer, // except when global pref "MOVING_STACKS_PICKUP_UNITS" is set final boolean selectAllUnitsInStackRegardlessOfSelection = (Boolean) GameModule.getGameModule().getPrefs().getValue(Map.MOVING_STACKS_PICKUP_UNITS); s.asList().forEach( selectAllUnitsInStackRegardlessOfSelection ? dbuf::add : (p) -> { if (Boolean.TRUE.equals(p.getProperty(Properties.SELECTED))) { dbuf.add(p); } } ); // End RFE 1629255 final KeyBuffer kbuf = KeyBuffer.getBuffer(); if (kbuf.containsChild(s)) { // If clicking on a stack with a selected piece, put all selected // pieces in other stacks into the drag buffer kbuf.sort(PieceMover.this); for (final GamePiece piece : kbuf.asList()) { if (piece.getParent() != s) { dbuf.add(piece); } } } return null; } /** * We've clicked a regular (non-stacked) piece. Clear drag buffer and the piece. * @param selected piece clicked on * @return null */ @Override public Object visitDefault(GamePiece selected) { final DragBuffer dbuf = DragBuffer.getBuffer(); dbuf.clear(); final KeyBuffer kbuf = KeyBuffer.getBuffer(); if (kbuf.contains(selected)) { // If clicking on a selected piece, put all selected pieces into the // drag buffer kbuf.sort(PieceMover.this); for (final GamePiece piece : kbuf.asList()) { dbuf.add(piece); } } else { dbuf.add(selected); } return null; } }); } /** * Returns the {@link PieceFinder} instance that will select a * {@link GamePiece} for processing when the user clicks on the map. * The default implementation is to return the first piece whose shape * contains the point clicked on. * * @return Piece Finder */ protected PieceFinder createDragTargetSelector() { return new PieceFinder.Movable() { @Override public Object visitDeck(Deck d) { final Point pos = d.getPosition(); final Point p = new Point(pt.x - pos.x, pt.y - pos.y); return d.boundingBox().contains(p) && d.getPieceCount() > 0 ? d : null; } }; } /** * Detects when a game is starting, for purposes of managing the mark-unmoved button. * @param gameStarting if true, a game is starting. If false, then a game is ending */ @Override public void setup(boolean gameStarting) { if (gameStarting) { initButton(); } } /** * PieceMover has nothing to save/restore in a save file. * @return null */ @Override public Command getRestoreCommand() { return null; } /** * @param name Name of icon file * @return Image for button icon */ private Image loadIcon(String name) { if (name == null || name.length() == 0) return null; return Op.load(name).getImage(); } /** * PieceMover manages the "Mark All Pieces Unmoved" button for the map. */ protected void initButton() { final String value = getMarkOption(); if (GlobalOptions.PROMPT.equals(value)) { final BooleanConfigurer config = new BooleanConfigurer( Map.MARK_MOVED, Resources.getString("Editor.PieceMover.mark_moved_pieces"), Boolean.TRUE); GameModule.getGameModule().getPrefs().addOption(config); } if (!GlobalOptions.NEVER.equals(value)) { if (markUnmovedButton == null) { final ActionListener al = e -> { final GamePiece[] p = map.getAllPieces(); final Command c = new NullCommand(); for (final GamePiece gamePiece : p) { c.append(markMoved(gamePiece, false)); } GameModule.getGameModule().sendAndLog(c); map.repaint(); }; markUnmovedButton = new LaunchButton("", NAME, HOTKEY, Map.MARK_UNMOVED_ICON, al); Image img = null; if (iconName != null && iconName.length() > 0) { img = loadIcon(iconName); if (img != null) { markUnmovedButton.setAttribute(Map.MARK_UNMOVED_ICON, iconName); } } if (img == null) { img = loadIcon(markUnmovedIcon); if (img != null) { markUnmovedButton.setAttribute(Map.MARK_UNMOVED_ICON, markUnmovedIcon); } } markUnmovedButton.setAlignmentY(0.0F); markUnmovedButton.setText(markUnmovedText); markUnmovedButton.setToolTipText( map.getAttributeValueString(Map.MARK_UNMOVED_TOOLTIP)); map.getToolBar().add(markUnmovedButton); } } else if (markUnmovedButton != null) { map.getToolBar().remove(markUnmovedButton); markUnmovedButton = null; } } /** * @return Our setting w/ regard to marking pieces moved. */ private String getMarkOption() { String value = map.getAttributeValueString(Map.MARK_MOVED); if (value == null) { value = GlobalOptions.getInstance() .getAttributeValueString(GlobalOptions.MARK_MOVED); } return value; } @Override public String[] getAttributeNames() { return new String[]{ICON_NAME}; } @Override public String getAttributeValueString(String key) { return ICON_NAME.equals(key) ? iconName : null; } @Override public void setAttribute(String key, Object value) { if (ICON_NAME.equals(key)) { iconName = (String) value; } else if (Map.MARK_UNMOVED_TEXT.equals(key)) { if (markUnmovedButton != null) { markUnmovedButton.setAttribute(NAME, value); } markUnmovedText = (String) value; } else if (Map.MARK_UNMOVED_ICON.equals(key)) { if (markUnmovedButton != null) { markUnmovedButton.setAttribute(Map.MARK_UNMOVED_ICON, value); } markUnmovedIcon = (String) value; } } protected boolean isMultipleSelectionEvent(MouseEvent e) { return e.isShiftDown(); } /** * Invoked just BEFORE a piece is moved. Sets the "OldLocations" properties for the piece. Marks the piece * as "moved" if it has changed positions, and removes the piece from its old stack, if any. * @return Command encapsulating anything this method did, for replay in log file or on other clients */ protected Command movedPiece(GamePiece p, Point loc) { Command c = new NullCommand(); c = c.append(setOldLocations(p)); if (!loc.equals(p.getPosition())) { c = c.append(markMoved(p, true)); } if (p.getParent() != null) { final Command removedCommand = p.getParent().pieceRemoved(p); c = c.append(removedCommand); } return c; } /** * @deprecated {@link #setOldLocations(GamePiece)} to return generated Commands * @param p Piece */ @Deprecated(since = "2020-08-06", forRemoval = true) protected void setOldLocation(GamePiece p) { ProblemDialog.showDeprecated("2020-08-06"); setOldLocations(p); } /** * Populates the "OldLocations" properties (e.g. OldMap, OldZone, etc) for the piece (or for a stack, for all * the pieces contained in it), based on their present locations, in preparation for moving them to a new location. * @param p Piece (could be a stack) * @return Command encapsulating any changes made, for replay in log file or on other clients */ protected Command setOldLocations(GamePiece p) { Command comm = new NullCommand(); if (p instanceof Stack) { for (final GamePiece gamePiece : ((Stack) p).asList()) { comm = comm.append(Decorator.putOldProperties(gamePiece)); } } else { comm = comm.append(Decorator.putOldProperties(p)); } return comm; } /** * Handles marking pieces as "moved" or "not moved", based on Global Options settings. Updates the * "moved" property of the pieces, if they have one. * @param p Piece (could be a Stack) * @param hasMoved True if piece has just moved, false if it is to be reset to not-moved status * @return Command encapsulating any changes made, for replay in log file or on other clients */ public Command markMoved(GamePiece p, boolean hasMoved) { if (GlobalOptions.NEVER.equals(getMarkOption())) { hasMoved = false; } Command c = new NullCommand(); if (!hasMoved || shouldMarkMoved()) { if (p instanceof Stack) { for (final GamePiece gamePiece : ((Stack) p).asList()) { c = c.append(markMoved(gamePiece, hasMoved)); } } else if (p.getProperty(Properties.MOVED) != null) { if (p.getId() != null) { final ChangeTracker comm = new ChangeTracker(p); p.setProperty(Properties.MOVED, hasMoved ? Boolean.TRUE : Boolean.FALSE); c = c.append(comm.getChangeCommand()); } } } return c; } /** * Checks Global Options settings (and if necessary, the user preference) about whether we mark moved * pieces as "moved" or not. * @return true if we should mark a moved piece as "moved", false if not. */ protected boolean shouldMarkMoved() { final String option = getMarkOption(); if (GlobalOptions.ALWAYS.equals(option)) { return true; } else if (GlobalOptions.NEVER.equals(option)) { return false; } else { return Boolean.TRUE.equals( GameModule.getGameModule().getPrefs().getValue(Map.MARK_MOVED)); } } /** * This is the key method for handling the "Drop" part of Drag and Drop. * <br>(1) Moves each piece in the {@link DragBuffer} to its proper destination, * based on the mouse having been released at point "p" (if multiple pieces * were being dragged after being e.g. band-selected, each individual piece's * destination point will vary with the piece's offset from the anhor point * that started the drag). This also involves removing each piece from any * stacks/decks it was part of, and possibly removing it from its old map if * it is changing maps. * <br>(2) As each piece is moved, finds appropriate "merge targets" (pieces * that should be combined with it in a stack) if they exist, or forms new stacks * where needed. Adds the piece to old or new stacks as appropriate, or directly * to the map if non-stacking. If the piece has been moved between maps (or onto * a map for the first time), the piece is also added to the map's piece collection. * <br>(3) If auto-reporting of moves is enabled, creates the report. * <br>(4) Applies any apply-on-move keystroke (from the "Key command to apply * to all units ending movement on this map" field of the map) to each piece, as * appropriate. * <br>(5) Returns a command to encapsulate any and all changes made, for replay * in log file or on other clients * * @param map Map * @param p Point mouse released * @return Command encapsulating all changes, for replay in log file or on other clients. */ public Command movePieces(Map map, Point p) { // The DragBuffer contains the list of all pieces being dragged final PieceIterator it = DragBuffer.getBuffer().getIterator(); if (!it.hasMoreElements()) return null; // This will be a list of every piece we end up moving somewhere, and thus the list of pieces to receive "apply-on-move" key command final List<GamePiece> allDraggedPieces = new ArrayList<>(); Point offset = null; Command comm = new NullCommand(); // This will track the area of the screen we need to repaint final BoundsTracker tracker = new BoundsTracker(); // Map of Point->List<GamePiece> of pieces/stacks to merge with at a given // location. There is potentially a piece (stack) for each Game Piece Layer, // since stacks are only formed from pieces at the same visual Layer. See // LayeredPieceCollection for further details on visual layers. final HashMap<Point, List<GamePiece>> mergeTargets = new HashMap<>(); while (it.hasMoreElements()) { // Get the next piece or stack to deal with. dragging = it.nextPiece(); tracker.addPiece(dragging); /* * Since the next "piece" might be a stack, make a list of * any pieces to be dragged in this loop. If we're dragging * a stack, the "stack" item itself will end up being emptied * and cleared in the coming merge process. */ final ArrayList<GamePiece> draggedPieces = new ArrayList<>(0); if (dragging instanceof Stack) { draggedPieces.addAll(((Stack) dragging).asList()); } else { draggedPieces.add(dragging); } if (offset != null) { p = new Point(dragging.getPosition().x + offset.x, dragging.getPosition().y + offset.y); } // Retrieve any list of merge candidates we've already cached for the destination point List<GamePiece> mergeCandidates = mergeTargets.get(p); // Assume, for the moment, that we don't have anything to form a stack with. GamePiece mergeWith = null; // Find a piece (already moved in the same drag operation) that we can merge with at the destination point if (mergeCandidates != null) { final int n = mergeCandidates.size(); for (int i = 0; i < n; ++i) { final GamePiece candidate = mergeCandidates.get(i); if (map.getPieceCollection().canMerge(candidate, dragging)) { mergeWith = candidate; // We have found an eligible piece to form a stack with! //FIXME I can't find a code path where this statement ever has any effect -- BR //FIXME Conceivably mergeCandidates is supposed to get "put" back to mergeTargets? //FIXME But since we're about to successfully merge with the piece already in there, //FIXME I'm not sure how adding "dragging" would change future mergability at all. mergeCandidates.set(i, dragging); break; } } } // If we're not forming a stack with one of our pieces that just moved, we now look for an already-existing // piece at the destination point if (mergeWith == null) { // This will now process through every "piece" (including stacks & decks) on the map, feeding each to the // dropTargetSelector (see our createDropTargetSelector method above). The dropTargetSelector will return // non-null if it finds a piece (including stack or deck) at this piece's drop location that is suitable to // merge with/into. mergeWith = map.findAnyPiece(p, dropTargetSelector); // If we get here with no merge target, we know we'll either be starting a new stack or putting the // piece by itself, so check if we need to do a "snap-to" of the grid. if (mergeWith == null && !Boolean.TRUE.equals( dragging.getProperty(Properties.IGNORE_GRID))) { p = map.snapTo(p); } if (offset == null) { offset = new Point(p.x - dragging.getPosition().x, p.y - dragging.getPosition().y); } // If we've HAVE found a piece to merge with, and we're going to a map that allows stacking, then // add our current piece & the mergable one to our cached list of merge targets. if (mergeWith != null && map.getStackMetrics().isStackingEnabled()) { mergeCandidates = new ArrayList<>(); mergeCandidates.add(dragging); mergeCandidates.add(mergeWith); mergeTargets.put(p, mergeCandidates); } } if (mergeWith == null) { // Now, if we never found a good merge target, we simply put the piece in the new position. comm = comm.append(movedPiece(dragging, p)); // Sets "old" locations, marks piece moved comm = comm.append(map.placeAt(dragging, p)); // Adds piece to destination map (removes from old map/stack) // If it was a stackable piece, we also need to start a new stack for it. if (!(dragging instanceof Stack) && !Boolean.TRUE.equals(dragging.getProperty(Properties.NO_STACK))) { final Stack parent = map.getStackMetrics().createStack(dragging); if (parent != null) { comm = comm.append(map.placeAt(parent, p)); //BR// We've made a new stack, so put it on the list of merge targets, in case more pieces land here too mergeCandidates = new ArrayList<>(); mergeCandidates.add(dragging); mergeCandidates.add(parent); mergeTargets.put(p, mergeCandidates); } } } else { // If we get here, we DID find a piece (possibly Deck or Stack) to merge with/into, so we handle that. // Do not add pieces to a Deck that are Obscured to us, or that the Deck does not want to contain. // Removing them from the draggedPieces list will cause them to be left behind where the drag started. // NB. Pieces that have been dragged from a face-down Deck will be be Obscured to us, but will be Obscured // by the dummy user Deck.NO_USER if (mergeWith instanceof Deck) { final ArrayList<GamePiece> newList = new ArrayList<>(0); for (final GamePiece piece : draggedPieces) { if (((Deck) mergeWith).mayContain(piece)) { final boolean isObscuredToMe = Boolean.TRUE.equals(piece.getProperty(Properties.OBSCURED_TO_ME)); if (!isObscuredToMe || Deck.NO_USER.equals(piece.getProperty(Properties.OBSCURED_BY))) { newList.add(piece); } } } // If we rejected any dragged pieces for merging with the deck, update our list of dragged pieces for this iteration of the loop if (newList.size() != draggedPieces.size()) { draggedPieces.clear(); draggedPieces.addAll(newList); } } // Add the remaining dragged counters to the target. If mergeWith is a single piece (not a Stack or Deck), then // we are merging into an expanded Stack and the merge order must be reversed to maintain the order of the merging // pieces. if (mergeWith instanceof Stack) { // Note - this could also be a Deck. for (final GamePiece draggedPiece : draggedPieces) { comm = comm.append(movedPiece(draggedPiece, mergeWith.getPosition())); comm = comm.append(map.getStackMetrics().merge(mergeWith, draggedPiece)); } } else { for (int i = draggedPieces.size() - 1; i >= 0; --i) { comm = comm.append(movedPiece(draggedPieces.get(i), mergeWith.getPosition())); comm = comm.append(map.getStackMetrics().merge(mergeWith, draggedPieces.get(i))); } } } // Any piece we successfully moved, make sure is now considered a "selected piece" (i.e. a member of KeyBuffer) for (final GamePiece piece : draggedPieces) { KeyBuffer.getBuffer().add(piece); } // Record each individual piece moved this iteration into our master list for this move allDraggedPieces.addAll(draggedPieces); // Add our piece's bounds to the bounds tracker tracker.addPiece(dragging); } // We've finished the actual drag and drop of pieces, so we now create any auto-report message that is appropriate. if (GlobalOptions.getInstance().autoReportEnabled()) { final Command report = createMovementReporter(comm).getReportCommand().append(new MovementReporter.HiddenMovementReporter(comm).getReportCommand()); report.execute(); comm = comm.append(report); } // Applies any apply-on-move keystroke (from the "Key command to apply to all units ending movement on this map" field of the Map) to each piece if (map.getMoveKey() != null) { comm = comm.append(applyKeyAfterMove(allDraggedPieces, map.getMoveKey())); } // Repaint any areas of the map window changed by our move tracker.repaint(); return comm; // A command that, if executed, will fully replay the effects of this drag-and-drop on another client, or via a logfile. } /** * @deprecated Use {@link #applyKeyAfterMove(List, KeyStroke)} to return Commands */ @Deprecated(since = "2020-08-06", forRemoval = true) protected void applyKeyAfterMove(List<GamePiece> pieces, Command comm, KeyStroke key) { ProblemDialog.showDeprecated("2020-08-06"); comm.append(applyKeyAfterMove(pieces, key)); } /** * Applies a key command to each of a list of pieces. * @param pieces List of pieces * @param key keystroke to apply * @return Command that encapsulates the effects of the key command applied. */ protected Command applyKeyAfterMove(List<GamePiece> pieces, KeyStroke key) { Command comm = new NullCommand(); for (final GamePiece piece : pieces) { if (piece.getProperty(Properties.SNAPSHOT) == null) { piece.setProperty(Properties.SNAPSHOT, ((PropertyExporter) piece).getProperties()); } comm = comm.append(piece.keyEvent(key)); } return comm; } /** * This "deep legacy" listener is used for faking drag-and-drop on Java 1.1 systems. * On most systems, the mouse event will be "consumed" by the Drag Gesture Recognizer, * causing canHandleEvent() to return false. * * @param e Event */ @Override public void mousePressed(MouseEvent e) { if (canHandleEvent(e)) { selectMovablePieces(e); } } /** * When doing a "deep legacy" fake drag-and-drop, * place the clicked-on piece into the {@link DragBuffer} */ protected void selectMovablePieces(MouseEvent e) { final GamePiece p = map.findPiece(e.getPoint(), dragTargetSelector); dragBegin = e.getPoint(); if (p != null) { final EventFilter filter = (EventFilter) p.getProperty(Properties.MOVE_EVENT_FILTER); if (filter == null || !filter.rejectEvent(e)) { selectionProcessor.accept(p); } else { DragBuffer.getBuffer().clear(); } } else { DragBuffer.getBuffer().clear(); } // show/hide selection boxes map.repaint(); } /** @deprecated Use {@link #selectMovablePieces(MouseEvent)}. */ @Deprecated(since = "2020-08-06", forRemoval = true) protected void selectMovablePieces(Point point) { ProblemDialog.showDeprecated("2020-08-06"); final GamePiece p = map.findPiece(point, dragTargetSelector); dragBegin = point; selectionProcessor.accept(p); // show/hide selection boxes map.repaint(); } /** * Checks if event has already been consumed -- so we will return false if this event * has already been handled by one of the fancier Drag Gesture Recognizers. Also screens * out double-clicks and anything with modifier keys down. * @param e mouse event * @return Should we treat this event as part of a "deep legacy" drag and drop? */ protected boolean canHandleEvent(MouseEvent e) { return !e.isConsumed() && !e.isShiftDown() && !SwingUtils.isSelectionToggle(e) && e.getClickCount() < 2 && (e.getButton() == MouseEvent.NOBUTTON || SwingUtils.isMainMouseButtonDown(e)); } /** * @return true if this point is "close enough" to the point at which * the user initially pressed the mouse button to be considered a mouse * click (such that no drag-and-drop moves are processed) */ public boolean isClick(Point pt) { boolean isClick = false; if (dragBegin != null) { final Board b = map.findBoard(pt); boolean useGrid = b != null && b.getGrid() != null; if (useGrid) { final PieceIterator it = DragBuffer.getBuffer().getIterator(); final GamePiece dragging = it.hasMoreElements() ? it.nextPiece() : null; useGrid = dragging != null && !Boolean.TRUE.equals(dragging.getProperty(Properties.IGNORE_GRID)) && (dragging.getParent() == null || !dragging.getParent().isExpanded()); } if (useGrid) { if (map.equals(DragBuffer.getBuffer().getFromMap())) { if (map.snapTo(pt).equals(map.snapTo(dragBegin))) { isClick = true; } } } if (map.mapToComponent(Math.abs(pt.x - dragBegin.x)) <= GlobalOptions.getInstance().getDragThreshold() && map.mapToComponent(Math.abs(pt.y - dragBegin.y)) <= GlobalOptions.getInstance().getDragThreshold()) { isClick = true; } } return isClick; } /** * Mouse button has been released -- if we can still handle the event (i.e. we haven't picked up some exotic * modifier key during the drag, etc), then we perform the drop. * @param e Mouse Event */ @Override public void mouseReleased(MouseEvent e) { if (canHandleEvent(e)) { if (!isClick(e.getPoint())) { if (!isClick(e.getPoint())) { performDrop(e.getPoint()); } } } dragBegin = null; map.getView().setCursor(null); } /** * Moves the group of dragged (in the DragBuffer) pieces to the target point (p). * @param p Point that mouse has been dragged to. */ protected void performDrop(Point p) { final Command move = movePieces(map, p); GameModule.getGameModule().sendAndLog(move); // Sends the command over the wire (and/or into the logfile) if (move != null) { DragBuffer.getBuffer().clear(); // If we did anything, clear the drag buffer, as the DnD operation is complete. } } @Override public void mouseEntered(MouseEvent e) { } @Override public void mouseExited(MouseEvent e) { } @Override public void mouseClicked(MouseEvent e) { } /** * Implement Comparator to sort the contents of the drag buffer before * completing the drag. This sorts the contents to be in the same order * as the pieces were in their original parent stack. */ @Override public int compare(GamePiece p1, GamePiece p2) { return pieceSorter.compare(p1, p2); } // We force the loading of these classes because otherwise they would // be loaded when the user initiates the first drag, which makes the // start of the drag choppy. static { try { Class.forName(MovementReporter.class.getName()); Class.forName(KeyBuffer.class.getName()); } catch (ClassNotFoundException e) { throw new IllegalStateException(e); // impossible } } /** * Common functionality for DragHandler for cases with and without drag image support. * <p> * NOTE: DragSource.isDragImageSupported() returns false for j2sdk1.4.2_02 on Windows 2000 * * @author Pieter Geerkens */ public abstract static class AbstractDragHandler implements DragGestureListener, DragSourceListener, DragSourceMotionListener, DropTargetListener { private static AbstractDragHandler theDragHandler = DragSource.isDragImageSupported() ? (SystemUtils.IS_OS_MAC ? new DragHandlerMacOSX() : new DragHandler()) : new DragHandlerNoImage(); /** returns the singleton DragHandler instance */ public static AbstractDragHandler getTheDragHandler() { return theDragHandler; } public static void setTheDragHandler(AbstractDragHandler myHandler) { theDragHandler = myHandler; } static final int CURSOR_ALPHA = 127; // pseudo cursor is 50% transparent static final int EXTRA_BORDER = 4; // pseudo cursor is includes a 4 pixel border protected JLabel dragCursor; // An image label. Lives on current DropTarget's LayeredPane. private final Point drawOffset = new Point(); // translates event coords to local drawing coords private Rectangle boundingBox; // image bounds private int originalPieceOffsetX; // How far drag STARTED from GamePiece's center (on original map) private int originalPieceOffsetY; protected double dragPieceOffCenterZoom = 1.0; // zoom at start of drag private int currentPieceOffsetX; // How far cursor is CURRENTLY off-center, a function of dragPieceOffCenter{X,Y,Zoom} private int currentPieceOffsetY; // I.e. on current map (which may have different zoom) protected double dragCursorZoom = 1.0; // Current cursor scale (zoom) Component dragWin; // the component that initiated the drag operation Component dropWin; // the drop target the mouse is currently over JLayeredPane drawWin; // the component that owns our pseudo-cursor // Seems there can be only one DropTargetListener per drop target. After we // process a drop target event, we manually pass the event on to this listener. java.util.Map<Component, DropTargetListener> dropTargetListeners = new HashMap<>(); /** * @return platform-dependent offset multiplier */ protected abstract int getOffsetMult(); /** * @param dge DG event * @return platform-dependent device scale */ protected abstract double getDeviceScale(DragGestureEvent dge); /** * Creates a new DropTarget and hooks us into the beginning of a * DropTargetListener chain. DropTarget events are not multicast; * there can be only one "true" listener. */ public static DropTarget makeDropTarget(Component theComponent, int dndContants, DropTargetListener dropTargetListener) { if (dropTargetListener != null) { DragHandler.getTheDragHandler() .dropTargetListeners.put(theComponent, dropTargetListener); } return new DropTarget(theComponent, dndContants, DragHandler.getTheDragHandler()); } /** * Removes a dropTarget component * @param theComponent component to remove */ public static void removeDropTarget(Component theComponent) { DragHandler.getTheDragHandler().dropTargetListeners.remove(theComponent); } /** * @param e DropTargetEvent * @return associated DropTargetListener */ protected DropTargetListener getListener(DropTargetEvent e) { final Component component = e.getDropTargetContext().getComponent(); return dropTargetListeners.get(component); } /** * Moves the drag cursor on the current draw window * @param dragX x position * @param dragY y position */ protected void moveDragCursor(int dragX, int dragY) { if (drawWin != null) { dragCursor.setLocation(dragX - drawOffset.x, dragY - drawOffset.y); } } /** * Removes the drag cursor from the current draw window */ protected void removeDragCursor() { if (drawWin != null) { if (dragCursor != null) { dragCursor.setVisible(false); drawWin.remove(dragCursor); } drawWin = null; } } /** calculates the offset between cursor dragCursor positions */ private void calcDrawOffset() { if (drawWin != null) { // drawOffset is the offset between the mouse location during a drag // and the upper-left corner of the cursor // accounts for difference between event point (screen coords) // and Layered Pane position, boundingBox and off-center drag drawOffset.x = -boundingBox.x - currentPieceOffsetX + EXTRA_BORDER; drawOffset.y = -boundingBox.y - currentPieceOffsetY + EXTRA_BORDER; SwingUtilities.convertPointToScreen(drawOffset, drawWin); } } /** * creates or moves cursor object to given JLayeredPane. Usually called by setDrawWinToOwnerOf() * @param newDrawWin JLayeredPane that is to be our new drawWin */ private void setDrawWin(JLayeredPane newDrawWin) { if (newDrawWin != drawWin) { // remove cursor from old window if (dragCursor.getParent() != null) { dragCursor.getParent().remove(dragCursor); } if (drawWin != null) { drawWin.repaint(dragCursor.getBounds()); } drawWin = newDrawWin; calcDrawOffset(); dragCursor.setVisible(false); drawWin.add(dragCursor, JLayeredPane.DRAG_LAYER); } } /** * creates or moves cursor object to given window. Called when drag operation begins in a window or the cursor is * dragged over a new drop-target window * @param newDropWin window component to be our new draw window. */ public void setDrawWinToOwnerOf(Component newDropWin) { if (newDropWin != null) { final JRootPane rootWin = SwingUtilities.getRootPane(newDropWin); if (rootWin != null) { setDrawWin(rootWin.getLayeredPane()); } } } /** * Common functionality abstracted from makeDragImage and makeDragCursor * * @param zoom Zoom Level * @param doOffset Drag Offset * @param target Target Component * @param setSize Set Size * @return Drag Image */ BufferedImage makeDragImageCursorCommon(double zoom, boolean doOffset, Component target, boolean setSize) { // FIXME: Should be an ImageOp. dragCursorZoom = zoom; final List<Point> relativePositions = buildBoundingBox(zoom, doOffset); final int w = boundingBox.width + EXTRA_BORDER * 2; final int h = boundingBox.height + EXTRA_BORDER * 2; BufferedImage image = ImageUtils.createCompatibleTranslucentImage(w, h); drawDragImage(image, target, relativePositions, zoom); if (setSize) dragCursor.setSize(w, h); image = featherDragImage(image, w, h, EXTRA_BORDER); return image; } /** * Creates the image to use when dragging based on the zoom factor * passed in. * * @param zoom DragBuffer.getBuffer * @return dragImage */ private BufferedImage makeDragImage(double zoom) { return makeDragImageCursorCommon(zoom, false, null, false); } /** * Installs the cursor image into our dragCursor JLabel. * Sets current zoom. Should be called at beginning of drag * and whenever zoom changes. INPUT: DragBuffer.getBuffer OUTPUT: * dragCursorZoom cursorOffCenterX cursorOffCenterY boundingBox * @param zoom DragBuffer.getBuffer * */ protected void makeDragCursor(double zoom) { // create the cursor if necessary if (dragCursor == null) { dragCursor = new JLabel(); dragCursor.setVisible(false); } dragCursor.setIcon(new ImageIcon( makeDragImageCursorCommon(zoom, true, dragCursor, true))); } private List<Point> buildBoundingBox(double zoom, boolean doOffset) { final ArrayList<Point> relativePositions = new ArrayList<>(); final PieceIterator dragContents = DragBuffer.getBuffer().getIterator(); final GamePiece firstPiece = dragContents.nextPiece(); GamePiece lastPiece = firstPiece; currentPieceOffsetX = (int) (originalPieceOffsetX / dragPieceOffCenterZoom * zoom + 0.5); currentPieceOffsetY = (int) (originalPieceOffsetY / dragPieceOffCenterZoom * zoom + 0.5); boundingBox = firstPiece.getShape().getBounds(); boundingBox.width *= zoom; boundingBox.height *= zoom; boundingBox.x *= zoom; boundingBox.y *= zoom; if (doOffset) { calcDrawOffset(); } relativePositions.add(new Point(0, 0)); int stackCount = 0; while (dragContents.hasMoreElements()) { final GamePiece nextPiece = dragContents.nextPiece(); final Rectangle r = nextPiece.getShape().getBounds(); r.width *= zoom; r.height *= zoom; r.x *= zoom; r.y *= zoom; final Point p = new Point( (int) Math.round( zoom * (nextPiece.getPosition().x - firstPiece.getPosition().x)), (int) Math.round( zoom * (nextPiece.getPosition().y - firstPiece.getPosition().y))); r.translate(p.x, p.y); if (nextPiece.getPosition().equals(lastPiece.getPosition())) { stackCount++; final StackMetrics sm = getStackMetrics(nextPiece); r.translate( (int) Math.round(sm.unexSepX * stackCount * zoom), (int) Math.round(-sm.unexSepY * stackCount * zoom) ); } boundingBox.add(r); relativePositions.add(p); lastPiece = nextPiece; } return relativePositions; } private void drawDragImage(BufferedImage image, Component target, List<Point> relativePositions, double zoom) { final Graphics2D g = image.createGraphics(); int index = 0; Point lastPos = null; int stackCount = 0; for (final PieceIterator dragContents = DragBuffer.getBuffer().getIterator(); dragContents.hasMoreElements(); ) { final GamePiece piece = dragContents.nextPiece(); final Point pos = relativePositions.get(index++); final Map map = piece.getMap(); if (piece instanceof Stack) { stackCount = 0; piece.draw(g, EXTRA_BORDER - boundingBox.x + pos.x, EXTRA_BORDER - boundingBox.y + pos.y, map == null ? target : map.getView(), zoom); } else { final Point offset = new Point(0, 0); if (pos.equals(lastPos)) { stackCount++; final StackMetrics sm = getStackMetrics(piece); offset.x = (int) Math.round(sm.unexSepX * stackCount * zoom); offset.y = (int) Math.round(sm.unexSepY * stackCount * zoom); } else { stackCount = 0; } final int x = EXTRA_BORDER - boundingBox.x + pos.x + offset.x; final int y = EXTRA_BORDER - boundingBox.y + pos.y - offset.y; String owner = ""; if (piece.getParent() instanceof Deck) { owner = (String)piece.getProperty(Properties.OBSCURED_BY); piece.setProperty(Properties.OBSCURED_BY, ((Deck) piece.getParent()).isFaceDown() ? Deck.NO_USER : null); } piece.draw(g, x, y, map == null ? target : map.getView(), zoom); if (piece.getParent() instanceof Deck) { piece.setProperty(Properties.OBSCURED_BY, owner); } final Highlighter highlighter = map == null ? BasicPiece.getHighlighter() : map.getHighlighter(); highlighter.draw(piece, g, x, y, null, zoom); } lastPos = pos; } g.dispose(); } private StackMetrics getStackMetrics(GamePiece piece) { StackMetrics sm = null; final Map map = piece.getMap(); if (map != null) { sm = map.getStackMetrics(); } if (sm == null) { sm = new StackMetrics(); } return sm; } private BufferedImage featherDragImage(BufferedImage src, int w, int h, int b) { // FIXME: This should be redone so that we draw the feathering onto the // destination first, and then pass the Graphics2D on to draw the pieces // directly over it. Presently this doesn't work because some of the // pieces screw up the Graphics2D when passed it... The advantage to doing // it this way is that we create only one BufferedImage instead of two. final BufferedImage dst = ImageUtils.createCompatibleTranslucentImage(w, h); final Graphics2D g = dst.createGraphics(); g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); // paint the rectangle occupied by the piece at specified alpha g.setColor(new Color(0xff, 0xff, 0xff, CURSOR_ALPHA)); g.fillRect(0, 0, w, h); // feather outwards for (int f = 0; f < b; ++f) { final int alpha = CURSOR_ALPHA * (f + 1) / b; g.setColor(new Color(0xff, 0xff, 0xff, alpha)); g.drawRect(f, f, w - 2 * f, h - 2 * f); } // paint in the source image g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_IN)); g.drawImage(src, 0, 0, null); g.dispose(); return dst; } /****************************************************************************** * DRAG GESTURE LISTENER INTERFACE * * EVENT uses SCALED, DRAG-SOURCE coordinate system. ("component coordinates") * PIECE uses SCALED, OWNER (arbitrary) coordinate system ("map coordinates") * * Fires after user begins moving the mouse several pixels over a map. This * method will be overridden, but called as a super(), by the Drag Gesture * extension that is used, which will either be {@link DragHandler} if DragImage * is supported by the JRE, or {@link DragHandlerNoImage} if not. Either one will * have called {@link dragGestureRecognizedPrep}, immediately below, before it * calls this method. ******************************************************************************/ @Override public void dragGestureRecognized(DragGestureEvent dge) { try { beginDragging(dge); } // FIXME: Fix by replacing AWT Drag 'n Drop with Swing DnD. // Catch and ignore spurious DragGestures catch (InvalidDnDOperationException ignored) { } } /** * Sets things up at the beginning of a drag-and-drop operation: * <br> - Screen out any immovable pieces * <br> - Account for any offsets on in the window * <br> - Sets dragWin to our source window * * @param dge dg event * @return mousePosition if we processed, or null if we bailed. */ protected Point dragGestureRecognizedPrep(DragGestureEvent dge) { // Ensure the user has dragged on a counter before starting the drag. final DragBuffer db = DragBuffer.getBuffer(); if (db.isEmpty()) return null; // Remove any Immovable pieces from the DragBuffer that were // selected in a selection rectangle, unless they are being // dragged from a piece palette (i.e., getMap() == null). final List<GamePiece> pieces = new ArrayList<>(); for (final PieceIterator i = db.getIterator(); i.hasMoreElements(); pieces.add(i.nextPiece())); for (final GamePiece piece : pieces) { if (piece.getMap() != null && Boolean.TRUE.equals(piece.getProperty(Properties.NON_MOVABLE))) { db.remove(piece); } } // Bail out if this leaves no pieces to drag. if (db.isEmpty()) return null; final GamePiece piece = db.getIterator().nextPiece(); final Map map = dge.getComponent() instanceof Map.View ? ((Map.View) dge.getComponent()).getMap() : null; final Point mousePosition = dge.getDragOrigin(); //BR// Bug13137 - now that we're not pre-adulterating dge's event, it already arrives in component coordinates Point piecePosition = (map == null) ? piece.getPosition() : map.mapToComponent(piece.getPosition()); // If DragBuffer holds a piece with invalid coordinates (for example, a // card drawn from a deck), drag from center of piece if (piecePosition.x <= 0 || piecePosition.y <= 0) { piecePosition = mousePosition; } // Account for offset of piece within stack. We do this even for un-expanded stacks, since the offset can // still be significant if the stack is large dragPieceOffCenterZoom = (map == null ? 1.0 : map.getZoom()) * getDeviceScale(dge); if (piece.getParent() != null && map != null) { final Point offset = piece.getParent() .getStackMetrics() .relativePosition(piece.getParent(), piece); piecePosition.translate( (int) Math.round(offset.x * dragPieceOffCenterZoom), (int) Math.round(offset.y * dragPieceOffCenterZoom)); } // dragging from UL results in positive offsets originalPieceOffsetX = piecePosition.x - mousePosition.x; originalPieceOffsetY = piecePosition.y - mousePosition.y; dragWin = dge.getComponent(); drawWin = null; dropWin = null; return mousePosition; } /** * The the Drag Gesture Recognizer that we're officially beginning a drag. * @param dge DG event */ protected void beginDragging(DragGestureEvent dge) { // this call is needed to instantiate the boundingBox object final BufferedImage bImage = makeDragImage(dragPieceOffCenterZoom); final Point dragPointOffset = new Point( getOffsetMult() * (boundingBox.x + currentPieceOffsetX - EXTRA_BORDER), getOffsetMult() * (boundingBox.y + currentPieceOffsetY - EXTRA_BORDER) ); dge.startDrag( Cursor.getPredefinedCursor(Cursor.HAND_CURSOR), bImage, dragPointOffset, new StringSelection(""), this ); dge.getDragSource().addDragSourceMotionListener(this); } /************************************************************************** * DRAG SOURCE LISTENER INTERFACE * @param e **************************************************************************/ @Override public void dragDropEnd(DragSourceDropEvent e) { final DragSource ds = e.getDragSourceContext().getDragSource(); ds.removeDragSourceMotionListener(this); } @Override public void dragEnter(DragSourceDragEvent e) {} @Override public void dragExit(DragSourceEvent e) {} @Override public void dragOver(DragSourceDragEvent e) {} @Override public void dropActionChanged(DragSourceDragEvent e) {} /************************************************************************************** * DRAG SOURCE MOTION LISTENER INTERFACE * * EVENT uses UNSCALED, SCREEN coordinate system * * Moves cursor after mouse. Used to check for real mouse movement. * Warning: dragMouseMoved fires 8 times for each point on development system (Win2k) **************************************************************************************/ @Override public abstract void dragMouseMoved(DragSourceDragEvent e); protected Point lastDragLocation = new Point(); /************************************************************************** * DROP TARGET INTERFACE * * EVENT uses UNSCALED, DROP-TARGET coordinate system * * dragEnter - switches current drawWin when mouse enters a new DropTarget **************************************************************************/ @Override public void dragEnter(DropTargetDragEvent e) { final DropTargetListener forward = getListener(e); if (forward != null) { forward.dragEnter(e); } } /************************************************************************** * DROP TARGET INTERFACE * * EVENT uses UNSCALED, DROP-TARGET coordinate system * * drop() - Last event of the drop operation. We adjust the drop point for * off-center drag, remove the cursor, and pass the event along * listener chain. **************************************************************************/ @Override public void drop(DropTargetDropEvent e) { // EVENT uses UNSCALED, DROP-TARGET coordinate system e.getLocation().translate(currentPieceOffsetX, currentPieceOffsetY); final DropTargetListener forward = getListener(e); if (forward != null) { forward.drop(e); } } /** ineffectual. Passes event along listener chain */ @Override public void dragExit(DropTargetEvent e) { final DropTargetListener forward = getListener(e); if (forward != null) forward.dragExit(e); } /** ineffectual. Passes event along listener chain */ @Override public void dragOver(DropTargetDragEvent e) { final DropTargetListener forward = getListener(e); if (forward != null) forward.dragOver(e); } /** ineffectual. Passes event along listener chain */ @Override public void dropActionChanged(DropTargetDragEvent e) { final DropTargetListener forward = getListener(e); if (forward != null) forward.dropActionChanged(e); } } /********************************************************************************** * VASSAL's front-line drag handler for drag-and-drop of pieces. * * Implementation of AbstractDragHandler when DragImage is supported by JRE. * {@link DragHandlerMacOSX} extends this for special Mac platform * * @author Pieter Geerkens **********************************************************************************/ public static class DragHandler extends AbstractDragHandler { @Override public void dragGestureRecognized(DragGestureEvent dge) { if (dragGestureRecognizedPrep(dge) == null) return; super.dragGestureRecognized(dge); } @Override protected int getOffsetMult() { return -1; } @Override protected double getDeviceScale(DragGestureEvent dge) { // Get the OS scaling; note that this is _probably_ running only on Windows. final Graphics2D g2d = (Graphics2D) dge.getComponent().getGraphics(); final double os_scale = g2d.getDeviceConfiguration().getDefaultTransform().getScaleX(); g2d.dispose(); return os_scale; } @Override public void dragMouseMoved(DragSourceDragEvent e) {} } /** * Special MacOSX variant of DragHandler, because of differences in how device scaling is handled. */ public static class DragHandlerMacOSX extends DragHandler { @Override protected int getOffsetMult() { return 1; } @Override protected double getDeviceScale(DragGestureEvent dge) { // Retina Macs account for the device scaling for the drag icon, so we don't have to. return 1.0; } } /**************************************************************************************** * Fallback drag-handler when DragImage not supported by JRE. Implements a pseudo-cursor * that follows the mouse cursor when user drags game pieces. Supports map zoom by * resizing cursor when it enters a drop target of type Map.View. * <br> * @author Jim Urbas * @version 0.4.2 ****************************************************************************************/ public static class DragHandlerNoImage extends AbstractDragHandler { @Override public void dragGestureRecognized(DragGestureEvent dge) { final Point mousePosition = dragGestureRecognizedPrep(dge); if (mousePosition == null) return; makeDragCursor(dragPieceOffCenterZoom); setDrawWinToOwnerOf(dragWin); SwingUtilities.convertPointToScreen(mousePosition, drawWin); moveDragCursor(mousePosition.x, mousePosition.y); super.dragGestureRecognized(dge); } @Override protected int getOffsetMult() { return 1; } @Override protected double getDeviceScale(DragGestureEvent dge) { return 1.0; } @Override public void dragDropEnd(DragSourceDropEvent e) { removeDragCursor(); super.dragDropEnd(e); } @Override public void dragMouseMoved(DragSourceDragEvent e) { if (!e.getLocation().equals(lastDragLocation)) { lastDragLocation = e.getLocation(); moveDragCursor(e.getX(), e.getY()); if (dragCursor != null && !dragCursor.isVisible()) { dragCursor.setVisible(true); } } } @Override public void dragEnter(DropTargetDragEvent e) { final Component newDropWin = e.getDropTargetContext().getComponent(); if (newDropWin != dropWin) { final double newZoom = newDropWin instanceof Map.View ? ((Map.View) newDropWin).getMap().getZoom() : 1.0; if (Math.abs(newZoom - dragCursorZoom) > 0.01) { makeDragCursor(newZoom); } setDrawWinToOwnerOf(e.getDropTargetContext().getComponent()); dropWin = newDropWin; } super.dragEnter(e); } @Override public void drop(DropTargetDropEvent e) { removeDragCursor(); super.drop(e); } } }
vassal-app/src/main/java/VASSAL/build/module/map/PieceMover.java
/* * * Copyright (c) 2000-2003 by Rodney Kinney, Jim Urbas * Refactoring of DragHandler Copyright 2011 Pieter Geerkens * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License (LGPL) as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public * License along with this library; if not, copies are available * at http://www.opensource.org. */ package VASSAL.build.module.map; import VASSAL.i18n.Resources; import VASSAL.tools.ProblemDialog; import java.awt.AlphaComposite; import java.awt.Color; import java.awt.Component; import java.awt.Cursor; import java.awt.Graphics2D; import java.awt.Image; import java.awt.Point; import java.awt.Rectangle; import java.awt.RenderingHints; import java.awt.datatransfer.StringSelection; import java.awt.dnd.DragGestureEvent; import java.awt.dnd.DragGestureListener; import java.awt.dnd.DragSource; import java.awt.dnd.DragSourceDragEvent; import java.awt.dnd.DragSourceDropEvent; import java.awt.dnd.DragSourceEvent; import java.awt.dnd.DragSourceListener; import java.awt.dnd.DragSourceMotionListener; import java.awt.dnd.DropTarget; import java.awt.dnd.DropTargetDragEvent; import java.awt.dnd.DropTargetDropEvent; import java.awt.dnd.DropTargetEvent; import java.awt.dnd.DropTargetListener; import java.awt.dnd.InvalidDnDOperationException; import java.awt.event.ActionListener; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.awt.image.BufferedImage; import java.util.ArrayList; import java.util.Collection; import java.util.Comparator; import java.util.HashMap; import java.util.List; import javax.swing.ImageIcon; import javax.swing.JLabel; import javax.swing.JLayeredPane; import javax.swing.JRootPane; import javax.swing.KeyStroke; import javax.swing.SwingUtilities; import org.apache.commons.lang3.SystemUtils; import VASSAL.build.AbstractBuildable; import VASSAL.build.Buildable; import VASSAL.build.GameModule; import VASSAL.build.module.GameComponent; import VASSAL.build.module.GlobalOptions; import VASSAL.build.module.Map; import VASSAL.build.module.map.boardPicker.Board; import VASSAL.command.ChangeTracker; import VASSAL.command.Command; import VASSAL.command.NullCommand; import VASSAL.configure.BooleanConfigurer; import VASSAL.counters.BasicPiece; import VASSAL.counters.BoundsTracker; import VASSAL.counters.Deck; import VASSAL.counters.DeckVisitor; import VASSAL.counters.DeckVisitorDispatcher; import VASSAL.counters.Decorator; import VASSAL.counters.DragBuffer; import VASSAL.counters.EventFilter; import VASSAL.counters.GamePiece; import VASSAL.counters.Highlighter; import VASSAL.counters.KeyBuffer; import VASSAL.counters.PieceFinder; import VASSAL.counters.PieceIterator; import VASSAL.counters.PieceSorter; import VASSAL.counters.PieceVisitorDispatcher; import VASSAL.counters.Properties; import VASSAL.counters.PropertyExporter; import VASSAL.counters.Stack; import VASSAL.tools.LaunchButton; import VASSAL.tools.image.ImageUtils; import VASSAL.tools.imageop.Op; import VASSAL.tools.swing.SwingUtils; /** * PieceMover handles the "Drag and Drop" of pieces and stacks, onto or within a Map window. It implements * MouseListener and handles dragging and dropping of both individual pieces, stacks, and groups of * pieces/stacks. It is a subcomponent of Map. * <br><br> * For the selection/deselection of pieces and band-selecting pieces by "dragging a lasso around them", * see {@link KeyBufferer}. */ public class PieceMover extends AbstractBuildable implements MouseListener, GameComponent, Comparator<GamePiece> { /** The Preferences key for auto-reporting moves. */ public static final String AUTO_REPORT = "autoReport"; //$NON-NLS-1$ public static final String NAME = "name"; //NON-NLS public static final String HOTKEY = "hotkey"; //NON-NLS protected Map map; // Map we're the PieceMover for. protected Point dragBegin; // Anchor point for drag and drop protected GamePiece dragging; // Anchor piece that we're dragging (along with everything else in DragBuffer) // PieceMover provides the "clear move history" button for Map - the configurer dialog is found there. protected LaunchButton markUnmovedButton; protected String markUnmovedText; protected String markUnmovedIcon; public static final String ICON_NAME = "icon"; //$NON-NLS-1$ protected String iconName; protected PieceFinder dragTargetSelector; // Selects drag target from mouse click on the Map protected PieceFinder dropTargetSelector; // Selects piece to merge with at the drop destination protected PieceVisitorDispatcher selectionProcessor; // Processes drag target after having been selected protected Comparator<GamePiece> pieceSorter = new PieceSorter(); /** * Adds this component to its parent map. Add ourselves as a mouse listener, drag gesture listener, etc. * @param b Map to add to */ @Override public void addTo(Buildable b) { // Create our target selection filters dragTargetSelector = createDragTargetSelector(); dropTargetSelector = createDropTargetSelector(); selectionProcessor = createSelectionProcessor(); // Register with our parent map map = (Map) b; map.addLocalMouseListener(this); GameModule.getGameModule().getGameState().addGameComponent(this); map.setDragGestureListener(DragHandler.getTheDragHandler()); map.setPieceMover(this); // Because of the strange legacy scheme of halfway-running a Toolbar button "on behalf of Map", we have to set some its attributes setAttribute(Map.MARK_UNMOVED_TEXT, map.getAttributeValueString(Map.MARK_UNMOVED_TEXT)); setAttribute(Map.MARK_UNMOVED_ICON, map.getAttributeValueString(Map.MARK_UNMOVED_ICON)); } /** * Creates a {@link MovementReporter} for a collection of commands containing AddPiece and MovePiece commands, which * will supply auto-report messages corresponding to those commands * @param c Command -- presumably including some AddPiece and MovePiece commands. * @return MovementReporter to auto-report the command(s) */ protected MovementReporter createMovementReporter(Command c) { return new MovementReporter(c); } /** * Reports the image files we use (forremove-unwanted-image-files and/or search) * @param s Collection to add image names to */ @Override public void addLocalImageNames(Collection<String> s) { if (iconName != null) s.add(iconName); if (markUnmovedIcon != null) s.add(markUnmovedIcon); } /** * When the user *completes* a drag-and-drop operation, the pieces being dragged will either be: * <br>(1) combined in a stack with an existing piece (or stack, or deck) on the map * <br>(2) placed alone in a brand new stack * <br>(3) or, in the case of non-stacking pieces, placed on the map without stack. * <br><br> * For <i>each</i> of the stacks/pieces being dragged, we need to determine which of those outcomes * applies. This "drop target selector" will be fed, one by one, all of the pieces on the map, and for * each one must check whether it would make a valid "merge target" for the current dragged piece under * consideration (the PieceFinder's {@link PieceFinder#select} method provides the map and location, and * the PieceMover's {@link PieceMover#dragging} field tells the "dragged piece under consideration". Each * method is to returns the target piece/stack/deck to merge with if it has been passed a valid target, or * null if it is not a valid match. * <br><br> * The Map's {@link Map#findAnyPiece(Point, PieceFinder)} method, which feeds this, will be responsible for * iterating through the list of possible pieces in proper visual order so that we check the pieces "visually * on top" first. * <br><br> * @return a {@link PieceFinder} instance that determines which {@link GamePiece} (if any) to * combine the being-dragged pieces with. */ protected PieceFinder createDropTargetSelector() { return new PieceFinder.Movable() { /** * When a deck exists on the map, and we need to find out if our piece was dragged to the deck * @param d Potential target {@link Deck} * @return the Deck if our target location is inside the footprint of the Deck, or null if not */ @Override public Object visitDeck(Deck d) { final Point pos = d.getPosition(); final Point p = new Point(pt.x - pos.x, pt.y - pos.y); return d.getShape().contains(p) ? d : null; } /** * When an unstacked piece exists on the map, we see if this is a piece we could * form a stack with -- if it is at our precise location (or the location we would * be getting snapped to). We must also check if stacking is enabled and if both * the target "piece" and the "dragging" piece fit all the usual "can merge" requirements * (both are "stacking" pieces, and in the same visual layer) * @param piece Potential target piece on the map. * @return The piece to stack with, if we should, otherwise null. */ @Override public Object visitDefault(GamePiece piece) { GamePiece selected = null; if (this.map.getStackMetrics().isStackingEnabled() && this.map.getPieceCollection().canMerge(dragging, piece)) { if (this.map.isLocationRestricted(pt)) { final Point snap = this.map.snapTo(pt); if (piece.getPosition().equals(snap)) { selected = piece; } } else { // The "super" visitDefault checks if our point is inside the visual boundaries of the piece. selected = (GamePiece) super.visitDefault(piece); } } // We don't drag a piece "to itself". if (selected != null && DragBuffer.getBuffer().contains(selected) && selected.getParent() != null && selected.getParent().topPiece() == selected) { //NOTE: topPiece() returns the top VISIBLE piece (not hidden by Invisible trait) selected = null; } return selected; } /** * When a stack already exists on the map, we see if this piece could be added to it. * @param s Stack to check if we're appropriately configured to merge with * @return The piece to stack with, if we should, otherwise null. */ @Override public Object visitStack(Stack s) { GamePiece selected = null; if (this.map.getStackMetrics().isStackingEnabled() && this.map.getPieceCollection().canMerge(dragging, s) && !DragBuffer.getBuffer().contains(s) && !DragBuffer.getBuffer().containsAllMembers(s) && //BR// Don't merge back into a stack we are in the act of emptying s.topPiece() != null) { //NOTE: topPiece() returns the top VISIBLE piece (not hidden by Invisible trait) if (this.map.isLocationRestricted(pt) && !s.isExpanded()) { if (s.getPosition().equals(this.map.snapTo(pt))) { selected = s; } } else { // The super's visitStack handles checking to see if our point is inside the visual "shape" of the stack selected = (GamePiece) super.visitStack(s); } } return selected; } }; } /** * When the user *starts* a potential drag-and-drop operation by clicking * on the map, a piece from the map is selected by the dragTargetSelector. * What happens to that piece is determined by the {@link PieceVisitorDispatcher} * instance returned by this method. The default implementation does the following: * <br>(1) If a Deck, add the (single) top piece to the drag buffer * <br>(2) If a stack, add it to the drag buffer. If the stack is a member of the "currently selected pieces" * (i.e. {@link KeyBuffer}), then add any other already-selected pieces and stacks to the drag buffer as well. * <br>(3) Otherwise, add the piece and any other multi-selected pieces and stacks to the drag buffer. * * @see #createDragTargetSelector * @return Dispatcher */ protected PieceVisitorDispatcher createSelectionProcessor() { return new DeckVisitorDispatcher(new DeckVisitor() { /** * We've picked a Deck - Clear the drag buffer and add Deck's top piece to the drag buffer. * @param d Deck we clicked on * @return null */ @Override public Object visitDeck(Deck d) { final DragBuffer dbuf = DragBuffer.getBuffer(); dbuf.clear(); for (final PieceIterator it = d.drawCards(); it.hasMoreElements();) { final GamePiece p = it.nextPiece(); p.setProperty(Properties.OBSCURED_BY, p.getProperty(Properties.OBSCURED_BY_PRE_DRAW)); // Bug 13433 restore correct OBSCURED_BY dbuf.add(p); } return null; } /** * We've picked a Stack. Clear the drag buffer and add the stack's pieces to it. If the stack is part of the * "currently selected pieces" (i.e. {@link KeyBuffer}), then add any other pieces/stacks as well. * @param s Stack we clicked on * @return null */ @Override public Object visitStack(Stack s) { final DragBuffer dbuf = DragBuffer.getBuffer(); dbuf.clear(); // RFE 1629255 - Only add selected pieces within the stack to the DragBuffer, // except when global pref "MOVING_STACKS_PICKUP_UNITS" is set final boolean selectAllUnitsInStackRegardlessOfSelection = (Boolean) GameModule.getGameModule().getPrefs().getValue(Map.MOVING_STACKS_PICKUP_UNITS); s.asList().forEach( selectAllUnitsInStackRegardlessOfSelection ? dbuf::add : (p) -> { if (Boolean.TRUE.equals(p.getProperty(Properties.SELECTED))) { dbuf.add(p); } } ); // End RFE 1629255 final KeyBuffer kbuf = KeyBuffer.getBuffer(); if (kbuf.containsChild(s)) { // If clicking on a stack with a selected piece, put all selected // pieces in other stacks into the drag buffer kbuf.sort(PieceMover.this); for (final GamePiece piece : kbuf.asList()) { if (piece.getParent() != s) { dbuf.add(piece); } } } return null; } /** * We've clicked a regular (non-stacked) piece. Clear drag buffer and the piece. * @param selected piece clicked on * @return null */ @Override public Object visitDefault(GamePiece selected) { final DragBuffer dbuf = DragBuffer.getBuffer(); dbuf.clear(); final KeyBuffer kbuf = KeyBuffer.getBuffer(); if (kbuf.contains(selected)) { // If clicking on a selected piece, put all selected pieces into the // drag buffer kbuf.sort(PieceMover.this); for (final GamePiece piece : kbuf.asList()) { dbuf.add(piece); } } else { dbuf.add(selected); } return null; } }); } /** * Returns the {@link PieceFinder} instance that will select a * {@link GamePiece} for processing when the user clicks on the map. * The default implementation is to return the first piece whose shape * contains the point clicked on. * * @return Piece Finder */ protected PieceFinder createDragTargetSelector() { return new PieceFinder.Movable() { @Override public Object visitDeck(Deck d) { final Point pos = d.getPosition(); final Point p = new Point(pt.x - pos.x, pt.y - pos.y); return d.boundingBox().contains(p) && d.getPieceCount() > 0 ? d : null; } }; } /** * Detects when a game is starting, for purposes of managing the mark-unmoved button. * @param gameStarting if true, a game is starting. If false, then a game is ending */ @Override public void setup(boolean gameStarting) { if (gameStarting) { initButton(); } } /** * PieceMover has nothing to save/restore in a save file. * @return null */ @Override public Command getRestoreCommand() { return null; } /** * @param name Name of icon file * @return Image for button icon */ private Image loadIcon(String name) { if (name == null || name.length() == 0) return null; return Op.load(name).getImage(); } /** * PieceMover manages the "Mark All Pieces Unmoved" button for the map. */ protected void initButton() { final String value = getMarkOption(); if (GlobalOptions.PROMPT.equals(value)) { final BooleanConfigurer config = new BooleanConfigurer( Map.MARK_MOVED, Resources.getString("Editor.PieceMover.mark_moved_pieces"), Boolean.TRUE); GameModule.getGameModule().getPrefs().addOption(config); } if (!GlobalOptions.NEVER.equals(value)) { if (markUnmovedButton == null) { final ActionListener al = e -> { final GamePiece[] p = map.getAllPieces(); final Command c = new NullCommand(); for (final GamePiece gamePiece : p) { c.append(markMoved(gamePiece, false)); } GameModule.getGameModule().sendAndLog(c); map.repaint(); }; markUnmovedButton = new LaunchButton("", NAME, HOTKEY, Map.MARK_UNMOVED_ICON, al); Image img = null; if (iconName != null && iconName.length() > 0) { img = loadIcon(iconName); if (img != null) { markUnmovedButton.setAttribute(Map.MARK_UNMOVED_ICON, iconName); } } if (img == null) { img = loadIcon(markUnmovedIcon); if (img != null) { markUnmovedButton.setAttribute(Map.MARK_UNMOVED_ICON, markUnmovedIcon); } } markUnmovedButton.setAlignmentY(0.0F); markUnmovedButton.setText(markUnmovedText); markUnmovedButton.setToolTipText( map.getAttributeValueString(Map.MARK_UNMOVED_TOOLTIP)); map.getToolBar().add(markUnmovedButton); } } else if (markUnmovedButton != null) { map.getToolBar().remove(markUnmovedButton); markUnmovedButton = null; } } /** * @return Our setting w/ regard to marking pieces moved. */ private String getMarkOption() { String value = map.getAttributeValueString(Map.MARK_MOVED); if (value == null) { value = GlobalOptions.getInstance() .getAttributeValueString(GlobalOptions.MARK_MOVED); } return value; } @Override public String[] getAttributeNames() { return new String[]{ICON_NAME}; } @Override public String getAttributeValueString(String key) { return ICON_NAME.equals(key) ? iconName : null; } @Override public void setAttribute(String key, Object value) { if (ICON_NAME.equals(key)) { iconName = (String) value; } else if (Map.MARK_UNMOVED_TEXT.equals(key)) { if (markUnmovedButton != null) { markUnmovedButton.setAttribute(NAME, value); } markUnmovedText = (String) value; } else if (Map.MARK_UNMOVED_ICON.equals(key)) { if (markUnmovedButton != null) { markUnmovedButton.setAttribute(Map.MARK_UNMOVED_ICON, value); } markUnmovedIcon = (String) value; } } protected boolean isMultipleSelectionEvent(MouseEvent e) { return e.isShiftDown(); } /** * Invoked just BEFORE a piece is moved. Sets the "OldLocations" properties for the piece. Marks the piece * as "moved" if it has changed positions, and removes the piece from its old stack, if any. * @return Command encapsulating anything this method did, for replay in log file or on other clients */ protected Command movedPiece(GamePiece p, Point loc) { Command c = new NullCommand(); c = c.append(setOldLocations(p)); if (!loc.equals(p.getPosition())) { c = c.append(markMoved(p, true)); } if (p.getParent() != null) { final Command removedCommand = p.getParent().pieceRemoved(p); c = c.append(removedCommand); } return c; } /** * @deprecated {@link #setOldLocations(GamePiece)} to return generated Commands * @param p Piece */ @Deprecated(since = "2020-08-06", forRemoval = true) protected void setOldLocation(GamePiece p) { ProblemDialog.showDeprecated("2020-08-06"); setOldLocations(p); } /** * Populates the "OldLocations" properties (e.g. OldMap, OldZone, etc) for the piece (or for a stack, for all * the pieces contained in it), based on their present locations, in preparation for moving them to a new location. * @param p Piece (could be a stack) * @return Command encapsulating any changes made, for replay in log file or on other clients */ protected Command setOldLocations(GamePiece p) { Command comm = new NullCommand(); if (p instanceof Stack) { for (final GamePiece gamePiece : ((Stack) p).asList()) { comm = comm.append(Decorator.putOldProperties(gamePiece)); } } else { comm = comm.append(Decorator.putOldProperties(p)); } return comm; } /** * Handles marking pieces as "moved" or "not moved", based on Global Options settings. Updates the * "moved" property of the pieces, if they have one. * @param p Piece (could be a Stack) * @param hasMoved True if piece has just moved, false if it is to be reset to not-moved status * @return Command encapsulating any changes made, for replay in log file or on other clients */ public Command markMoved(GamePiece p, boolean hasMoved) { if (GlobalOptions.NEVER.equals(getMarkOption())) { hasMoved = false; } Command c = new NullCommand(); if (!hasMoved || shouldMarkMoved()) { if (p instanceof Stack) { for (final GamePiece gamePiece : ((Stack) p).asList()) { c = c.append(markMoved(gamePiece, hasMoved)); } } else if (p.getProperty(Properties.MOVED) != null) { if (p.getId() != null) { final ChangeTracker comm = new ChangeTracker(p); p.setProperty(Properties.MOVED, hasMoved ? Boolean.TRUE : Boolean.FALSE); c = c.append(comm.getChangeCommand()); } } } return c; } /** * Checks Global Options settings (and if necessary, the user preference) about whether we mark moved * pieces as "moved" or not. * @return true if we should mark a moved piece as "moved", false if not. */ protected boolean shouldMarkMoved() { final String option = getMarkOption(); if (GlobalOptions.ALWAYS.equals(option)) { return true; } else if (GlobalOptions.NEVER.equals(option)) { return false; } else { return Boolean.TRUE.equals( GameModule.getGameModule().getPrefs().getValue(Map.MARK_MOVED)); } } /** * This is the key method for handling the "Drop" part of Drag and Drop. * <br>(1) Moves each piece in the {@link DragBuffer} to its proper destination, * based on the mouse having been released at point "p" (if multiple pieces * were being dragged after being e.g. band-selected, each individual piece's * destination point will vary with the piece's offset from the anhor point * that started the drag). This also involves removing each piece from any * stacks/decks it was part of, and possibly removing it from its old map if * it is changing maps. * <br>(2) As each piece is moved, finds appropriate "merge targets" (pieces * that should be combined with it in a stack) if they exist, or forms new stacks * where needed. Adds the piece to old or new stacks as appropriate, or directly * to the map if non-stacking. If the piece has been moved between maps (or onto * a map for the first time), the piece is also added to the map's piece collection. * <br>(3) If auto-reporting of moves is enabled, creates the report. * <br>(4) Applies any apply-on-move keystroke (from the "Key command to apply * to all units ending movement on this map" field of the map) to each piece, as * appropriate. * <br>(5) Returns a command to encapsulate any and all changes made, for replay * in log file or on other clients * * @param map Map * @param p Point mouse released * @return Command encapsulating all changes, for replay in log file or on other clients. */ public Command movePieces(Map map, Point p) { // The DragBuffer contains the list of all pieces being dragged final PieceIterator it = DragBuffer.getBuffer().getIterator(); if (!it.hasMoreElements()) return null; // This will be a list of every piece we end up moving somewhere, and thus the list of pieces to receive "apply-on-move" key command final List<GamePiece> allDraggedPieces = new ArrayList<>(); Point offset = null; Command comm = new NullCommand(); // This will track the area of the screen we need to repaint final BoundsTracker tracker = new BoundsTracker(); // Map of Point->List<GamePiece> of pieces/stacks to merge with at a given // location. There is potentially a piece (stack) for each Game Piece Layer, // since stacks are only formed from pieces at the same visual Layer. See // LayeredPieceCollection for further details on visual layers. final HashMap<Point, List<GamePiece>> mergeTargets = new HashMap<>(); while (it.hasMoreElements()) { // Get the next piece or stack to deal with. dragging = it.nextPiece(); tracker.addPiece(dragging); /* * Since the next "piece" might be a stack, make a list of * any pieces to be dragged in this loop. If we're dragging * a stack, the "stack" item itself will end up being emptied * and cleared in the coming merge process. */ final ArrayList<GamePiece> draggedPieces = new ArrayList<>(0); if (dragging instanceof Stack) { draggedPieces.addAll(((Stack) dragging).asList()); } else { draggedPieces.add(dragging); } if (offset != null) { p = new Point(dragging.getPosition().x + offset.x, dragging.getPosition().y + offset.y); } // Retrieve any list of merge candidates we've already cached for the destination point List<GamePiece> mergeCandidates = mergeTargets.get(p); // Assume, for the moment, that we don't have anything to form a stack with. GamePiece mergeWith = null; // Find a piece (already moved in the same drag operation) that we can merge with at the destination point if (mergeCandidates != null) { final int n = mergeCandidates.size(); for (int i = 0; i < n; ++i) { final GamePiece candidate = mergeCandidates.get(i); if (map.getPieceCollection().canMerge(candidate, dragging)) { mergeWith = candidate; // We have found an eligible piece to form a stack with! //FIXME I can't find a code path where this statement ever has any effect -- BR //FIXME Conceivably mergeCandidates is supposed to get "put" back to mergeTargets? //FIXME But since we're about to successfully merge with the piece already in there, //FIXME I'm not sure how adding "dragging" would change future mergability at all. mergeCandidates.set(i, dragging); break; } } } // If we're not forming a stack with one of our pieces that just moved, we now look for an already-existing // piece at the destination point if (mergeWith == null) { // This will now process through every "piece" (including stacks & decks) on the map, feeding each to the // dropTargetSelector (see our createDropTargetSelector method above). The dropTargetSelector will return // non-null if it finds a piece (including stack or deck) at this piece's drop location that is suitable to // merge with/into. mergeWith = map.findAnyPiece(p, dropTargetSelector); // If we get here with no merge target, we know we'll either be starting a new stack or putting the // piece by itself, so check if we need to do a "snap-to" of the grid. if (mergeWith == null && !Boolean.TRUE.equals( dragging.getProperty(Properties.IGNORE_GRID))) { p = map.snapTo(p); } if (offset == null) { offset = new Point(p.x - dragging.getPosition().x, p.y - dragging.getPosition().y); } // If we've HAVE found a piece to merge with, and we're going to a map that allows stacking, then // add our current piece & the mergable one to our cached list of merge targets. if (mergeWith != null && map.getStackMetrics().isStackingEnabled()) { mergeCandidates = new ArrayList<>(); mergeCandidates.add(dragging); mergeCandidates.add(mergeWith); mergeTargets.put(p, mergeCandidates); } } if (mergeWith == null) { // Now, if we never found a good merge target, we simply put the piece in the new position. comm = comm.append(movedPiece(dragging, p)); // Sets "old" locations, marks piece moved comm = comm.append(map.placeAt(dragging, p)); // Adds piece to destination map (removes from old map/stack) // If it was a stackable piece, we also need to start a new stack for it. if (!(dragging instanceof Stack) && !Boolean.TRUE.equals(dragging.getProperty(Properties.NO_STACK))) { final Stack parent = map.getStackMetrics().createStack(dragging); if (parent != null) { comm = comm.append(map.placeAt(parent, p)); //BR// We've made a new stack, so put it on the list of merge targets, in case more pieces land here too mergeCandidates = new ArrayList<>(); mergeCandidates.add(dragging); mergeCandidates.add(parent); mergeTargets.put(p, mergeCandidates); } } } else { // If we get here, we DID find a piece (possibly Deck or Stack) to merge with/into, so we handle that. // Do not add pieces to a Deck that are Obscured to us, or that the Deck does not want to contain. // Removing them from the draggedPieces list will cause them to be left behind where the drag started. // NB. Pieces that have been dragged from a face-down Deck will be be Obscured to us, but will be Obscured // by the dummy user Deck.NO_USER if (mergeWith instanceof Deck) { final ArrayList<GamePiece> newList = new ArrayList<>(0); for (final GamePiece piece : draggedPieces) { if (((Deck) mergeWith).mayContain(piece)) { final boolean isObscuredToMe = Boolean.TRUE.equals(piece.getProperty(Properties.OBSCURED_TO_ME)); if (!isObscuredToMe || Deck.NO_USER.equals(piece.getProperty(Properties.OBSCURED_BY))) { newList.add(piece); } } } // If we rejected any dragged pieces for merging with the deck, update our list of dragged pieces for this iteration of the loop if (newList.size() != draggedPieces.size()) { draggedPieces.clear(); draggedPieces.addAll(newList); } } // Add the remaining dragged counters to the target. If mergeWith is a single piece (not a Stack or Deck), then // we are merging into an expanded Stack and the merge order must be reversed to maintain the order of the merging // pieces. if (mergeWith instanceof Stack) { // Note - this could also be a Deck. for (final GamePiece draggedPiece : draggedPieces) { comm = comm.append(movedPiece(draggedPiece, mergeWith.getPosition())); comm = comm.append(map.getStackMetrics().merge(mergeWith, draggedPiece)); } } else { for (int i = draggedPieces.size() - 1; i >= 0; --i) { comm = comm.append(movedPiece(draggedPieces.get(i), mergeWith.getPosition())); comm = comm.append(map.getStackMetrics().merge(mergeWith, draggedPieces.get(i))); } } } // Any piece we successfully moved, make sure is now considered a "selected piece" (i.e. a member of KeyBuffer) for (final GamePiece piece : draggedPieces) { KeyBuffer.getBuffer().add(piece); } // Record each individual piece moved this iteration into our master list for this move allDraggedPieces.addAll(draggedPieces); // Add our piece's bounds to the bounds tracker tracker.addPiece(dragging); } // We've finished the actual drag and drop of pieces, so we now create any auto-report message that is appropriate. if (GlobalOptions.getInstance().autoReportEnabled()) { final Command report = createMovementReporter(comm).getReportCommand().append(new MovementReporter.HiddenMovementReporter(comm).getReportCommand()); report.execute(); comm = comm.append(report); } // Applies any apply-on-move keystroke (from the "Key command to apply to all units ending movement on this map" field of the Map) to each piece if (map.getMoveKey() != null) { comm = comm.append(applyKeyAfterMove(allDraggedPieces, map.getMoveKey())); } // Repaint any areas of the map window changed by our move tracker.repaint(); return comm; // A command that, if executed, will fully replay the effects of this drag-and-drop on another client, or via a logfile. } /** * @deprecated Use {@link #applyKeyAfterMove(List, KeyStroke)} to return Commands */ @Deprecated(since = "2020-08-06", forRemoval = true) protected void applyKeyAfterMove(List<GamePiece> pieces, Command comm, KeyStroke key) { ProblemDialog.showDeprecated("2020-08-06"); comm.append(applyKeyAfterMove(pieces, key)); } /** * Applies a key command to each of a list of pieces. * @param pieces List of pieces * @param key keystroke to apply * @return Command that encapsulates the effects of the key command applied. */ protected Command applyKeyAfterMove(List<GamePiece> pieces, KeyStroke key) { Command comm = new NullCommand(); for (final GamePiece piece : pieces) { if (piece.getProperty(Properties.SNAPSHOT) == null) { piece.setProperty(Properties.SNAPSHOT, ((PropertyExporter) piece).getProperties()); } comm = comm.append(piece.keyEvent(key)); } return comm; } /** * This "deep legacy" listener is used for faking drag-and-drop on Java 1.1 systems. * On most systems, the mouse event will be "consumed" by the Drag Gesture Recognizer, * causing canHandleEvent() to return false. * * @param e Event */ @Override public void mousePressed(MouseEvent e) { if (canHandleEvent(e)) { selectMovablePieces(e); } } /** * When doing a "deep legacy" fake drag-and-drop, * place the clicked-on piece into the {@link DragBuffer} */ protected void selectMovablePieces(MouseEvent e) { final GamePiece p = map.findPiece(e.getPoint(), dragTargetSelector); dragBegin = e.getPoint(); if (p != null) { final EventFilter filter = (EventFilter) p.getProperty(Properties.MOVE_EVENT_FILTER); if (filter == null || !filter.rejectEvent(e)) { selectionProcessor.accept(p); } else { DragBuffer.getBuffer().clear(); } } else { DragBuffer.getBuffer().clear(); } // show/hide selection boxes map.repaint(); } /** @deprecated Use {@link #selectMovablePieces(MouseEvent)}. */ @Deprecated(since = "2020-08-06", forRemoval = true) protected void selectMovablePieces(Point point) { ProblemDialog.showDeprecated("2020-08-06"); final GamePiece p = map.findPiece(point, dragTargetSelector); dragBegin = point; selectionProcessor.accept(p); // show/hide selection boxes map.repaint(); } /** * Checks if event has already been consumed -- so we will return false if this event * has already been handled by one of the fancier Drag Gesture Recognizers. Also screens * out double-clicks and anything with modifier keys down. * @param e mouse event * @return Should we treat this event as part of a "deep legacy" drag and drop? */ protected boolean canHandleEvent(MouseEvent e) { return !e.isConsumed() && !e.isShiftDown() && !SwingUtils.isSelectionToggle(e) && e.getClickCount() < 2 && (e.getButton() == MouseEvent.NOBUTTON || SwingUtils.isMainMouseButtonDown(e)); } /** * @return true if this point is "close enough" to the point at which * the user initially pressed the mouse button to be considered a mouse * click (such that no drag-and-drop moves are processed) */ public boolean isClick(Point pt) { boolean isClick = false; if (dragBegin != null) { final Board b = map.findBoard(pt); boolean useGrid = b != null && b.getGrid() != null; if (useGrid) { final PieceIterator it = DragBuffer.getBuffer().getIterator(); final GamePiece dragging = it.hasMoreElements() ? it.nextPiece() : null; useGrid = dragging != null && !Boolean.TRUE.equals(dragging.getProperty(Properties.IGNORE_GRID)) && (dragging.getParent() == null || !dragging.getParent().isExpanded()); } if (useGrid) { if (map.equals(DragBuffer.getBuffer().getFromMap())) { if (map.snapTo(pt).equals(map.snapTo(dragBegin))) { isClick = true; } } } else { if (Math.abs(pt.x - dragBegin.x) <= 5 && Math.abs(pt.y - dragBegin.y) <= 5) { isClick = true; } } } return isClick; } /** * Mouse button has been released -- if we can still handle the event (i.e. we haven't picked up some exotic * modifier key during the drag, etc), then we perform the drop. * @param e Mouse Event */ @Override public void mouseReleased(MouseEvent e) { if (canHandleEvent(e)) { if (!isClick(e.getPoint())) { performDrop(e.getPoint()); } } dragBegin = null; map.getView().setCursor(null); } /** * Moves the group of dragged (in the DragBuffer) pieces to the target point (p). * @param p Point that mouse has been dragged to. */ protected void performDrop(Point p) { final Command move = movePieces(map, p); GameModule.getGameModule().sendAndLog(move); // Sends the command over the wire (and/or into the logfile) if (move != null) { DragBuffer.getBuffer().clear(); // If we did anything, clear the drag buffer, as the DnD operation is complete. } } @Override public void mouseEntered(MouseEvent e) { } @Override public void mouseExited(MouseEvent e) { } @Override public void mouseClicked(MouseEvent e) { } /** * Implement Comparator to sort the contents of the drag buffer before * completing the drag. This sorts the contents to be in the same order * as the pieces were in their original parent stack. */ @Override public int compare(GamePiece p1, GamePiece p2) { return pieceSorter.compare(p1, p2); } // We force the loading of these classes because otherwise they would // be loaded when the user initiates the first drag, which makes the // start of the drag choppy. static { try { Class.forName(MovementReporter.class.getName()); Class.forName(KeyBuffer.class.getName()); } catch (ClassNotFoundException e) { throw new IllegalStateException(e); // impossible } } /** * Common functionality for DragHandler for cases with and without drag image support. * <p> * NOTE: DragSource.isDragImageSupported() returns false for j2sdk1.4.2_02 on Windows 2000 * * @author Pieter Geerkens */ public abstract static class AbstractDragHandler implements DragGestureListener, DragSourceListener, DragSourceMotionListener, DropTargetListener { private static AbstractDragHandler theDragHandler = DragSource.isDragImageSupported() ? (SystemUtils.IS_OS_MAC ? new DragHandlerMacOSX() : new DragHandler()) : new DragHandlerNoImage(); /** returns the singleton DragHandler instance */ public static AbstractDragHandler getTheDragHandler() { return theDragHandler; } public static void setTheDragHandler(AbstractDragHandler myHandler) { theDragHandler = myHandler; } static final int CURSOR_ALPHA = 127; // pseudo cursor is 50% transparent static final int EXTRA_BORDER = 4; // pseudo cursor is includes a 4 pixel border protected JLabel dragCursor; // An image label. Lives on current DropTarget's LayeredPane. private final Point drawOffset = new Point(); // translates event coords to local drawing coords private Rectangle boundingBox; // image bounds private int originalPieceOffsetX; // How far drag STARTED from GamePiece's center (on original map) private int originalPieceOffsetY; protected double dragPieceOffCenterZoom = 1.0; // zoom at start of drag private int currentPieceOffsetX; // How far cursor is CURRENTLY off-center, a function of dragPieceOffCenter{X,Y,Zoom} private int currentPieceOffsetY; // I.e. on current map (which may have different zoom) protected double dragCursorZoom = 1.0; // Current cursor scale (zoom) Component dragWin; // the component that initiated the drag operation Component dropWin; // the drop target the mouse is currently over JLayeredPane drawWin; // the component that owns our pseudo-cursor // Seems there can be only one DropTargetListener per drop target. After we // process a drop target event, we manually pass the event on to this listener. java.util.Map<Component, DropTargetListener> dropTargetListeners = new HashMap<>(); /** * @return platform-dependent offset multiplier */ protected abstract int getOffsetMult(); /** * @param dge DG event * @return platform-dependent device scale */ protected abstract double getDeviceScale(DragGestureEvent dge); /** * Creates a new DropTarget and hooks us into the beginning of a * DropTargetListener chain. DropTarget events are not multicast; * there can be only one "true" listener. */ public static DropTarget makeDropTarget(Component theComponent, int dndContants, DropTargetListener dropTargetListener) { if (dropTargetListener != null) { DragHandler.getTheDragHandler() .dropTargetListeners.put(theComponent, dropTargetListener); } return new DropTarget(theComponent, dndContants, DragHandler.getTheDragHandler()); } /** * Removes a dropTarget component * @param theComponent component to remove */ public static void removeDropTarget(Component theComponent) { DragHandler.getTheDragHandler().dropTargetListeners.remove(theComponent); } /** * @param e DropTargetEvent * @return associated DropTargetListener */ protected DropTargetListener getListener(DropTargetEvent e) { final Component component = e.getDropTargetContext().getComponent(); return dropTargetListeners.get(component); } /** * Moves the drag cursor on the current draw window * @param dragX x position * @param dragY y position */ protected void moveDragCursor(int dragX, int dragY) { if (drawWin != null) { dragCursor.setLocation(dragX - drawOffset.x, dragY - drawOffset.y); } } /** * Removes the drag cursor from the current draw window */ protected void removeDragCursor() { if (drawWin != null) { if (dragCursor != null) { dragCursor.setVisible(false); drawWin.remove(dragCursor); } drawWin = null; } } /** calculates the offset between cursor dragCursor positions */ private void calcDrawOffset() { if (drawWin != null) { // drawOffset is the offset between the mouse location during a drag // and the upper-left corner of the cursor // accounts for difference between event point (screen coords) // and Layered Pane position, boundingBox and off-center drag drawOffset.x = -boundingBox.x - currentPieceOffsetX + EXTRA_BORDER; drawOffset.y = -boundingBox.y - currentPieceOffsetY + EXTRA_BORDER; SwingUtilities.convertPointToScreen(drawOffset, drawWin); } } /** * creates or moves cursor object to given JLayeredPane. Usually called by setDrawWinToOwnerOf() * @param newDrawWin JLayeredPane that is to be our new drawWin */ private void setDrawWin(JLayeredPane newDrawWin) { if (newDrawWin != drawWin) { // remove cursor from old window if (dragCursor.getParent() != null) { dragCursor.getParent().remove(dragCursor); } if (drawWin != null) { drawWin.repaint(dragCursor.getBounds()); } drawWin = newDrawWin; calcDrawOffset(); dragCursor.setVisible(false); drawWin.add(dragCursor, JLayeredPane.DRAG_LAYER); } } /** * creates or moves cursor object to given window. Called when drag operation begins in a window or the cursor is * dragged over a new drop-target window * @param newDropWin window component to be our new draw window. */ public void setDrawWinToOwnerOf(Component newDropWin) { if (newDropWin != null) { final JRootPane rootWin = SwingUtilities.getRootPane(newDropWin); if (rootWin != null) { setDrawWin(rootWin.getLayeredPane()); } } } /** * Common functionality abstracted from makeDragImage and makeDragCursor * * @param zoom Zoom Level * @param doOffset Drag Offset * @param target Target Component * @param setSize Set Size * @return Drag Image */ BufferedImage makeDragImageCursorCommon(double zoom, boolean doOffset, Component target, boolean setSize) { // FIXME: Should be an ImageOp. dragCursorZoom = zoom; final List<Point> relativePositions = buildBoundingBox(zoom, doOffset); final int w = boundingBox.width + EXTRA_BORDER * 2; final int h = boundingBox.height + EXTRA_BORDER * 2; BufferedImage image = ImageUtils.createCompatibleTranslucentImage(w, h); drawDragImage(image, target, relativePositions, zoom); if (setSize) dragCursor.setSize(w, h); image = featherDragImage(image, w, h, EXTRA_BORDER); return image; } /** * Creates the image to use when dragging based on the zoom factor * passed in. * * @param zoom DragBuffer.getBuffer * @return dragImage */ private BufferedImage makeDragImage(double zoom) { return makeDragImageCursorCommon(zoom, false, null, false); } /** * Installs the cursor image into our dragCursor JLabel. * Sets current zoom. Should be called at beginning of drag * and whenever zoom changes. INPUT: DragBuffer.getBuffer OUTPUT: * dragCursorZoom cursorOffCenterX cursorOffCenterY boundingBox * @param zoom DragBuffer.getBuffer * */ protected void makeDragCursor(double zoom) { // create the cursor if necessary if (dragCursor == null) { dragCursor = new JLabel(); dragCursor.setVisible(false); } dragCursor.setIcon(new ImageIcon( makeDragImageCursorCommon(zoom, true, dragCursor, true))); } private List<Point> buildBoundingBox(double zoom, boolean doOffset) { final ArrayList<Point> relativePositions = new ArrayList<>(); final PieceIterator dragContents = DragBuffer.getBuffer().getIterator(); final GamePiece firstPiece = dragContents.nextPiece(); GamePiece lastPiece = firstPiece; currentPieceOffsetX = (int) (originalPieceOffsetX / dragPieceOffCenterZoom * zoom + 0.5); currentPieceOffsetY = (int) (originalPieceOffsetY / dragPieceOffCenterZoom * zoom + 0.5); boundingBox = firstPiece.getShape().getBounds(); boundingBox.width *= zoom; boundingBox.height *= zoom; boundingBox.x *= zoom; boundingBox.y *= zoom; if (doOffset) { calcDrawOffset(); } relativePositions.add(new Point(0, 0)); int stackCount = 0; while (dragContents.hasMoreElements()) { final GamePiece nextPiece = dragContents.nextPiece(); final Rectangle r = nextPiece.getShape().getBounds(); r.width *= zoom; r.height *= zoom; r.x *= zoom; r.y *= zoom; final Point p = new Point( (int) Math.round( zoom * (nextPiece.getPosition().x - firstPiece.getPosition().x)), (int) Math.round( zoom * (nextPiece.getPosition().y - firstPiece.getPosition().y))); r.translate(p.x, p.y); if (nextPiece.getPosition().equals(lastPiece.getPosition())) { stackCount++; final StackMetrics sm = getStackMetrics(nextPiece); r.translate( (int) Math.round(sm.unexSepX * stackCount * zoom), (int) Math.round(-sm.unexSepY * stackCount * zoom) ); } boundingBox.add(r); relativePositions.add(p); lastPiece = nextPiece; } return relativePositions; } private void drawDragImage(BufferedImage image, Component target, List<Point> relativePositions, double zoom) { final Graphics2D g = image.createGraphics(); int index = 0; Point lastPos = null; int stackCount = 0; for (final PieceIterator dragContents = DragBuffer.getBuffer().getIterator(); dragContents.hasMoreElements(); ) { final GamePiece piece = dragContents.nextPiece(); final Point pos = relativePositions.get(index++); final Map map = piece.getMap(); if (piece instanceof Stack) { stackCount = 0; piece.draw(g, EXTRA_BORDER - boundingBox.x + pos.x, EXTRA_BORDER - boundingBox.y + pos.y, map == null ? target : map.getView(), zoom); } else { final Point offset = new Point(0, 0); if (pos.equals(lastPos)) { stackCount++; final StackMetrics sm = getStackMetrics(piece); offset.x = (int) Math.round(sm.unexSepX * stackCount * zoom); offset.y = (int) Math.round(sm.unexSepY * stackCount * zoom); } else { stackCount = 0; } final int x = EXTRA_BORDER - boundingBox.x + pos.x + offset.x; final int y = EXTRA_BORDER - boundingBox.y + pos.y - offset.y; String owner = ""; if (piece.getParent() instanceof Deck) { owner = (String)piece.getProperty(Properties.OBSCURED_BY); piece.setProperty(Properties.OBSCURED_BY, ((Deck) piece.getParent()).isFaceDown() ? Deck.NO_USER : null); } piece.draw(g, x, y, map == null ? target : map.getView(), zoom); if (piece.getParent() instanceof Deck) { piece.setProperty(Properties.OBSCURED_BY, owner); } final Highlighter highlighter = map == null ? BasicPiece.getHighlighter() : map.getHighlighter(); highlighter.draw(piece, g, x, y, null, zoom); } lastPos = pos; } g.dispose(); } private StackMetrics getStackMetrics(GamePiece piece) { StackMetrics sm = null; final Map map = piece.getMap(); if (map != null) { sm = map.getStackMetrics(); } if (sm == null) { sm = new StackMetrics(); } return sm; } private BufferedImage featherDragImage(BufferedImage src, int w, int h, int b) { // FIXME: This should be redone so that we draw the feathering onto the // destination first, and then pass the Graphics2D on to draw the pieces // directly over it. Presently this doesn't work because some of the // pieces screw up the Graphics2D when passed it... The advantage to doing // it this way is that we create only one BufferedImage instead of two. final BufferedImage dst = ImageUtils.createCompatibleTranslucentImage(w, h); final Graphics2D g = dst.createGraphics(); g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); // paint the rectangle occupied by the piece at specified alpha g.setColor(new Color(0xff, 0xff, 0xff, CURSOR_ALPHA)); g.fillRect(0, 0, w, h); // feather outwards for (int f = 0; f < b; ++f) { final int alpha = CURSOR_ALPHA * (f + 1) / b; g.setColor(new Color(0xff, 0xff, 0xff, alpha)); g.drawRect(f, f, w - 2 * f, h - 2 * f); } // paint in the source image g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_IN)); g.drawImage(src, 0, 0, null); g.dispose(); return dst; } /****************************************************************************** * DRAG GESTURE LISTENER INTERFACE * * EVENT uses SCALED, DRAG-SOURCE coordinate system. ("component coordinates") * PIECE uses SCALED, OWNER (arbitrary) coordinate system ("map coordinates") * * Fires after user begins moving the mouse several pixels over a map. This * method will be overridden, but called as a super(), by the Drag Gesture * extension that is used, which will either be {@link DragHandler} if DragImage * is supported by the JRE, or {@link DragHandlerNoImage} if not. Either one will * have called {@link dragGestureRecognizedPrep}, immediately below, before it * calls this method. ******************************************************************************/ @Override public void dragGestureRecognized(DragGestureEvent dge) { try { beginDragging(dge); } // FIXME: Fix by replacing AWT Drag 'n Drop with Swing DnD. // Catch and ignore spurious DragGestures catch (InvalidDnDOperationException ignored) { } } /** * Sets things up at the beginning of a drag-and-drop operation: * <br> - Screen out any immovable pieces * <br> - Account for any offsets on in the window * <br> - Sets dragWin to our source window * * @param dge dg event * @return mousePosition if we processed, or null if we bailed. */ protected Point dragGestureRecognizedPrep(DragGestureEvent dge) { // Ensure the user has dragged on a counter before starting the drag. final DragBuffer db = DragBuffer.getBuffer(); if (db.isEmpty()) return null; // Remove any Immovable pieces from the DragBuffer that were // selected in a selection rectangle, unless they are being // dragged from a piece palette (i.e., getMap() == null). final List<GamePiece> pieces = new ArrayList<>(); for (final PieceIterator i = db.getIterator(); i.hasMoreElements(); pieces.add(i.nextPiece())); for (final GamePiece piece : pieces) { if (piece.getMap() != null && Boolean.TRUE.equals(piece.getProperty(Properties.NON_MOVABLE))) { db.remove(piece); } } // Bail out if this leaves no pieces to drag. if (db.isEmpty()) return null; final GamePiece piece = db.getIterator().nextPiece(); final Map map = dge.getComponent() instanceof Map.View ? ((Map.View) dge.getComponent()).getMap() : null; final Point mousePosition = dge.getDragOrigin(); //BR// Bug13137 - now that we're not pre-adulterating dge's event, it already arrives in component coordinates Point piecePosition = (map == null) ? piece.getPosition() : map.mapToComponent(piece.getPosition()); // If DragBuffer holds a piece with invalid coordinates (for example, a // card drawn from a deck), drag from center of piece if (piecePosition.x <= 0 || piecePosition.y <= 0) { piecePosition = mousePosition; } // Account for offset of piece within stack. We do this even for un-expanded stacks, since the offset can // still be significant if the stack is large dragPieceOffCenterZoom = (map == null ? 1.0 : map.getZoom()) * getDeviceScale(dge); if (piece.getParent() != null && map != null) { final Point offset = piece.getParent() .getStackMetrics() .relativePosition(piece.getParent(), piece); piecePosition.translate( (int) Math.round(offset.x * dragPieceOffCenterZoom), (int) Math.round(offset.y * dragPieceOffCenterZoom)); } // dragging from UL results in positive offsets originalPieceOffsetX = piecePosition.x - mousePosition.x; originalPieceOffsetY = piecePosition.y - mousePosition.y; dragWin = dge.getComponent(); drawWin = null; dropWin = null; return mousePosition; } /** * The the Drag Gesture Recognizer that we're officially beginning a drag. * @param dge DG event */ protected void beginDragging(DragGestureEvent dge) { // this call is needed to instantiate the boundingBox object final BufferedImage bImage = makeDragImage(dragPieceOffCenterZoom); final Point dragPointOffset = new Point( getOffsetMult() * (boundingBox.x + currentPieceOffsetX - EXTRA_BORDER), getOffsetMult() * (boundingBox.y + currentPieceOffsetY - EXTRA_BORDER) ); dge.startDrag( Cursor.getPredefinedCursor(Cursor.HAND_CURSOR), bImage, dragPointOffset, new StringSelection(""), this ); dge.getDragSource().addDragSourceMotionListener(this); } /************************************************************************** * DRAG SOURCE LISTENER INTERFACE * @param e **************************************************************************/ @Override public void dragDropEnd(DragSourceDropEvent e) { final DragSource ds = e.getDragSourceContext().getDragSource(); ds.removeDragSourceMotionListener(this); } @Override public void dragEnter(DragSourceDragEvent e) {} @Override public void dragExit(DragSourceEvent e) {} @Override public void dragOver(DragSourceDragEvent e) {} @Override public void dropActionChanged(DragSourceDragEvent e) {} /************************************************************************************** * DRAG SOURCE MOTION LISTENER INTERFACE * * EVENT uses UNSCALED, SCREEN coordinate system * * Moves cursor after mouse. Used to check for real mouse movement. * Warning: dragMouseMoved fires 8 times for each point on development system (Win2k) **************************************************************************************/ @Override public abstract void dragMouseMoved(DragSourceDragEvent e); protected Point lastDragLocation = new Point(); /************************************************************************** * DROP TARGET INTERFACE * * EVENT uses UNSCALED, DROP-TARGET coordinate system * * dragEnter - switches current drawWin when mouse enters a new DropTarget **************************************************************************/ @Override public void dragEnter(DropTargetDragEvent e) { final DropTargetListener forward = getListener(e); if (forward != null) { forward.dragEnter(e); } } /************************************************************************** * DROP TARGET INTERFACE * * EVENT uses UNSCALED, DROP-TARGET coordinate system * * drop() - Last event of the drop operation. We adjust the drop point for * off-center drag, remove the cursor, and pass the event along * listener chain. **************************************************************************/ @Override public void drop(DropTargetDropEvent e) { // EVENT uses UNSCALED, DROP-TARGET coordinate system e.getLocation().translate(currentPieceOffsetX, currentPieceOffsetY); final DropTargetListener forward = getListener(e); if (forward != null) { forward.drop(e); } } /** ineffectual. Passes event along listener chain */ @Override public void dragExit(DropTargetEvent e) { final DropTargetListener forward = getListener(e); if (forward != null) forward.dragExit(e); } /** ineffectual. Passes event along listener chain */ @Override public void dragOver(DropTargetDragEvent e) { final DropTargetListener forward = getListener(e); if (forward != null) forward.dragOver(e); } /** ineffectual. Passes event along listener chain */ @Override public void dropActionChanged(DropTargetDragEvent e) { final DropTargetListener forward = getListener(e); if (forward != null) forward.dropActionChanged(e); } } /********************************************************************************** * VASSAL's front-line drag handler for drag-and-drop of pieces. * * Implementation of AbstractDragHandler when DragImage is supported by JRE. * {@link DragHandlerMacOSX} extends this for special Mac platform * * @author Pieter Geerkens **********************************************************************************/ public static class DragHandler extends AbstractDragHandler { @Override public void dragGestureRecognized(DragGestureEvent dge) { if (dragGestureRecognizedPrep(dge) == null) return; super.dragGestureRecognized(dge); } @Override protected int getOffsetMult() { return -1; } @Override protected double getDeviceScale(DragGestureEvent dge) { // Get the OS scaling; note that this is _probably_ running only on Windows. final Graphics2D g2d = (Graphics2D) dge.getComponent().getGraphics(); final double os_scale = g2d.getDeviceConfiguration().getDefaultTransform().getScaleX(); g2d.dispose(); return os_scale; } @Override public void dragMouseMoved(DragSourceDragEvent e) {} } /** * Special MacOSX variant of DragHandler, because of differences in how device scaling is handled. */ public static class DragHandlerMacOSX extends DragHandler { @Override protected int getOffsetMult() { return 1; } @Override protected double getDeviceScale(DragGestureEvent dge) { // Retina Macs account for the device scaling for the drag icon, so we don't have to. return 1.0; } } /**************************************************************************************** * Fallback drag-handler when DragImage not supported by JRE. Implements a pseudo-cursor * that follows the mouse cursor when user drags game pieces. Supports map zoom by * resizing cursor when it enters a drop target of type Map.View. * <br> * @author Jim Urbas * @version 0.4.2 ****************************************************************************************/ public static class DragHandlerNoImage extends AbstractDragHandler { @Override public void dragGestureRecognized(DragGestureEvent dge) { final Point mousePosition = dragGestureRecognizedPrep(dge); if (mousePosition == null) return; makeDragCursor(dragPieceOffCenterZoom); setDrawWinToOwnerOf(dragWin); SwingUtilities.convertPointToScreen(mousePosition, drawWin); moveDragCursor(mousePosition.x, mousePosition.y); super.dragGestureRecognized(dge); } @Override protected int getOffsetMult() { return 1; } @Override protected double getDeviceScale(DragGestureEvent dge) { return 1.0; } @Override public void dragDropEnd(DragSourceDropEvent e) { removeDragCursor(); super.dragDropEnd(e); } @Override public void dragMouseMoved(DragSourceDragEvent e) { if (!e.getLocation().equals(lastDragLocation)) { lastDragLocation = e.getLocation(); moveDragCursor(e.getX(), e.getY()); if (dragCursor != null && !dragCursor.isVisible()) { dragCursor.setVisible(true); } } } @Override public void dragEnter(DropTargetDragEvent e) { final Component newDropWin = e.getDropTargetContext().getComponent(); if (newDropWin != dropWin) { final double newZoom = newDropWin instanceof Map.View ? ((Map.View) newDropWin).getMap().getZoom() : 1.0; if (Math.abs(newZoom - dragCursorZoom) > 0.01) { makeDragCursor(newZoom); } setDrawWinToOwnerOf(e.getDropTargetContext().getComponent()); dropWin = newDropWin; } super.dragEnter(e); } @Override public void drop(DropTargetDropEvent e) { removeDragCursor(); super.drop(e); } } }
14187 - Repress 'Deep Legacy' mouse listeners. They were violating drag thresholds.
vassal-app/src/main/java/VASSAL/build/module/map/PieceMover.java
14187 - Repress 'Deep Legacy' mouse listeners. They were violating drag thresholds.
<ide><path>assal-app/src/main/java/VASSAL/build/module/map/PieceMover.java <ide> !Boolean.TRUE.equals(dragging.getProperty(Properties.IGNORE_GRID)) && <ide> (dragging.getParent() == null || !dragging.getParent().isExpanded()); <ide> } <add> <ide> if (useGrid) { <ide> if (map.equals(DragBuffer.getBuffer().getFromMap())) { <ide> if (map.snapTo(pt).equals(map.snapTo(dragBegin))) { <ide> } <ide> } <ide> } <del> else { <del> if (Math.abs(pt.x - dragBegin.x) <= 5 && <del> Math.abs(pt.y - dragBegin.y) <= 5) { <del> isClick = true; <del> } <add> <add> if (map.mapToComponent(Math.abs(pt.x - dragBegin.x)) <= GlobalOptions.getInstance().getDragThreshold() && <add> map.mapToComponent(Math.abs(pt.y - dragBegin.y)) <= GlobalOptions.getInstance().getDragThreshold()) { <add> isClick = true; <ide> } <ide> } <ide> return isClick; <ide> public void mouseReleased(MouseEvent e) { <ide> if (canHandleEvent(e)) { <ide> if (!isClick(e.getPoint())) { <del> performDrop(e.getPoint()); <add> if (!isClick(e.getPoint())) { <add> performDrop(e.getPoint()); <add> } <ide> } <ide> } <ide> dragBegin = null;
Java
apache-2.0
86fdf19118d38683f834890ebe08698127f9c131
0
dbrant/apps-android-wikipedia,dbrant/apps-android-wikipedia,wikimedia/apps-android-wikipedia,wikimedia/apps-android-wikipedia,dbrant/apps-android-wikipedia,wikimedia/apps-android-wikipedia,wikimedia/apps-android-wikipedia,dbrant/apps-android-wikipedia,dbrant/apps-android-wikipedia
package org.wikipedia; public final class Constants { // Keep loader IDs unique to each loader. If the loader specified by the ID already exists, the // last created loader is reused. public static final int HISTORY_FRAGMENT_LOADER_ID = 100; public static final int RECENT_SEARCHES_FRAGMENT_LOADER_ID = 101; public static final String PLAIN_TEXT_MIME_TYPE = "text/plain"; public static final int ACTIVITY_REQUEST_SETTINGS = 41; public static final int ACTIVITY_REQUEST_CREATE_ACCOUNT = 42; public static final int ACTIVITY_REQUEST_RESET_PASSWORD = 43; public static final int ACTIVITY_REQUEST_WRITE_EXTERNAL_STORAGE_PERMISSION = 44; public static final int ACTIVITY_REQUEST_VOICE_SEARCH = 45; public static final int ACTIVITY_REQUEST_LANGLINKS = 50; public static final int ACTIVITY_REQUEST_EDIT_SECTION = 51; public static final int ACTIVITY_REQUEST_GALLERY = 52; public static final int ACTIVITY_REQUEST_LOGIN = 53; public static final int ACTIVITY_REQUEST_DESCRIPTION_EDIT_SUCCESS = 54; public static final int ACTIVITY_REQUEST_DESCRIPTION_EDIT = 55; public static final int ACTIVITY_REQUEST_DESCRIPTION_EDIT_TUTORIAL = 56; public static final int ACTIVITY_REQUEST_INITIAL_ONBOARDING = 57; public static final int ACTIVITY_REQUEST_FEED_CONFIGURE = 58; public static final int ACTIVITY_REQUEST_ADD_A_LANGUAGE = 59; public static final int ACTIVITY_REQUEST_ADD_A_LANGUAGE_FROM_SEARCH = 60; public static final int ACTIVITY_REQUEST_BROWSE_TABS = 61; public static final int ACTIVITY_REQUEST_OPEN_SEARCH_ACTIVITY = 62; public static final int ACTIVITY_REQUEST_SUGGESTED_EDITS_ONBOARDING = 63; public static final String INTENT_RETURN_TO_MAIN = "returnToMain"; public static final String INTENT_FEATURED_ARTICLE_FROM_WIDGET = "featuredArticleFromWidget"; public static final String INTENT_APP_SHORTCUT_CONTINUE_READING = "appShortcutContinueReading"; public static final String INTENT_APP_SHORTCUT_RANDOM = "appShortcutRandom"; public static final String INTENT_EXTRA_REVERT_QNUMBER = "revertQNumber"; public static final String INTENT_EXTRA_DELETE_READING_LIST = "deleteReadingList"; public static final String INTENT_EXTRA_VIEW_FROM_NOTIFICATION = "viewFromNotification"; public static final String INTENT_EXTRA_NOTIFICATION_SYNC_PAUSE_RESUME = "syncPauseResume"; public static final String INTENT_EXTRA_NOTIFICATION_SYNC_CANCEL = "syncCancel"; public static final String INTENT_EXTRA_GO_TO_MAIN_TAB = "goToMainTab"; public static final String INTENT_EXTRA_INVOKE_SOURCE = "invokeSource"; public static final int MAX_SUGGESTION_RESULTS = 3; public static final int SUGGESTION_REQUEST_ITEMS = 5; public static final int API_QUERY_MAX_TITLES = 50; public static final int PREFERRED_GALLERY_IMAGE_SIZE = 1280; public static final int MAX_TABS = 100; public static final int MAX_READING_LIST_ARTICLE_LIMIT = 5000; public static final int MAX_READING_LISTS_LIMIT = 100; public static final int MIN_LANGUAGES_TO_UNLOCK_TRANSLATION = 2; public enum InvokeSource { CONTEXT_MENU, LINK_PREVIEW_MENU, PAGE_OVERFLOW_MENU, NAV_MENU, MAIN_ACTIVITY, PAGE_ACTIVITY, NEWS_ACTIVITY, READING_LIST_ACTIVITY, MOST_READ_ACTIVITY, RANDOM_ACTIVITY, ON_THIS_DAY_ACTIVITY, READ_MORE_BOOKMARK_BUTTON, BOOKMARK_BUTTON, EDIT_FEED_TITLE_DESC, EDIT_FEED_TRANSLATE_TITLE_DESC, FEED_CARD_SUGGESTED_EDITS_ADD_DESC, FEED_CARD_SUGGESTED_EDITS_TRANSLATE_DESC, SUGGESTED_EDITS_ONBOARDING, ONBOARDING_DIALOG, FEED, NOTIFICATION } private Constants() { } }
app/src/main/java/org/wikipedia/Constants.java
package org.wikipedia; public final class Constants { // Keep loader IDs unique to each loader. If the loader specified by the ID already exists, the // last created loader is reused. public static final int HISTORY_FRAGMENT_LOADER_ID = 100; public static final int RECENT_SEARCHES_FRAGMENT_LOADER_ID = 101; public static final String PLAIN_TEXT_MIME_TYPE = "text/plain"; public static final int ACTIVITY_REQUEST_SETTINGS = 41; public static final int ACTIVITY_REQUEST_CREATE_ACCOUNT = 42; public static final int ACTIVITY_REQUEST_RESET_PASSWORD = 43; public static final int ACTIVITY_REQUEST_WRITE_EXTERNAL_STORAGE_PERMISSION = 44; public static final int ACTIVITY_REQUEST_VOICE_SEARCH = 45; public static final int ACTIVITY_REQUEST_LANGLINKS = 50; public static final int ACTIVITY_REQUEST_EDIT_SECTION = 51; public static final int ACTIVITY_REQUEST_GALLERY = 52; public static final int ACTIVITY_REQUEST_LOGIN = 53; public static final int ACTIVITY_REQUEST_DESCRIPTION_EDIT_SUCCESS = 54; public static final int ACTIVITY_REQUEST_DESCRIPTION_EDIT = 55; public static final int ACTIVITY_REQUEST_DESCRIPTION_EDIT_TUTORIAL = 56; public static final int ACTIVITY_REQUEST_INITIAL_ONBOARDING = 57; public static final int ACTIVITY_REQUEST_FEED_CONFIGURE = 58; public static final int ACTIVITY_REQUEST_ADD_A_LANGUAGE = 59; public static final int ACTIVITY_REQUEST_ADD_A_LANGUAGE_FROM_SEARCH = 60; public static final int ACTIVITY_REQUEST_BROWSE_TABS = 61; public static final int ACTIVITY_REQUEST_OPEN_SEARCH_ACTIVITY = 62; public static final int ACTIVITY_REQUEST_SUGGESTED_EDITS_ONBOARDING = 63; public static final String INTENT_RETURN_TO_MAIN = "returnToMain"; public static final String INTENT_FEATURED_ARTICLE_FROM_WIDGET = "featuredArticleFromWidget"; public static final String INTENT_APP_SHORTCUT_CONTINUE_READING = "appShortcutContinueReading"; public static final String INTENT_APP_SHORTCUT_RANDOM = "appShortcutRandom"; public static final String INTENT_EXTRA_REVERT_QNUMBER = "revertQNumber"; public static final String INTENT_EXTRA_DELETE_READING_LIST = "deleteReadingList"; public static final String INTENT_EXTRA_VIEW_FROM_NOTIFICATION = "viewFromNotification"; public static final String INTENT_EXTRA_NOTIFICATION_SYNC_PAUSE_RESUME = "syncPauseResume"; public static final String INTENT_EXTRA_NOTIFICATION_SYNC_CANCEL = "syncCancel"; public static final String INTENT_EXTRA_GO_TO_MAIN_TAB = "goToMainTab"; public static final String INTENT_EXTRA_INVOKE_SOURCE = "invokeSource"; public static final int MAX_SUGGESTION_RESULTS = 3; public static final int SUGGESTION_REQUEST_ITEMS = 5; public static final int API_QUERY_MAX_TITLES = 50; public static final int PREFERRED_GALLERY_IMAGE_SIZE = 1280; public static final int MAX_TABS = 100; public static final int MAX_READING_LIST_ARTICLE_LIMIT = 5000; public static final int MAX_READING_LISTS_LIMIT = 100; public static final int MIN_LANGUAGES_TO_UNLOCK_TRANSLATION = 2; public enum InvokeSource { BOOKMARK_BUTTON, CONTEXT_MENU, LINK_PREVIEW_MENU, PAGE_OVERFLOW_MENU, FEED, NEWS_ACTIVITY, READING_LIST_ACTIVITY, MOST_READ_ACTIVITY, RANDOM_ACTIVITY, ON_THIS_DAY_ACTIVITY, READ_MORE_BOOKMARK_BUTTON, PAGE_ACTIVITY, EDIT_FEED_TITLE_DESC, EDIT_FEED_TRANSLATE_TITLE_DESC, FEED_CARD_SUGGESTED_EDITS_ADD_DESC, FEED_CARD_SUGGESTED_EDITS_TRANSLATE_DESC, SUGGESTED_EDITS_ONBOARDING, MAIN_ACTIVITY, ONBOARDING_DIALOG, NOTIFICATION, NAV_MENU } private Constants() { } }
reorganize the order of invokeSources
app/src/main/java/org/wikipedia/Constants.java
reorganize the order of invokeSources
<ide><path>pp/src/main/java/org/wikipedia/Constants.java <ide> public static final int MIN_LANGUAGES_TO_UNLOCK_TRANSLATION = 2; <ide> <ide> public enum InvokeSource { <del> BOOKMARK_BUTTON, <ide> CONTEXT_MENU, <ide> LINK_PREVIEW_MENU, <ide> PAGE_OVERFLOW_MENU, <del> FEED, <add> NAV_MENU, <add> MAIN_ACTIVITY, <add> PAGE_ACTIVITY, <ide> NEWS_ACTIVITY, <ide> READING_LIST_ACTIVITY, <ide> MOST_READ_ACTIVITY, <ide> RANDOM_ACTIVITY, <ide> ON_THIS_DAY_ACTIVITY, <ide> READ_MORE_BOOKMARK_BUTTON, <del> PAGE_ACTIVITY, <add> BOOKMARK_BUTTON, <ide> EDIT_FEED_TITLE_DESC, <ide> EDIT_FEED_TRANSLATE_TITLE_DESC, <ide> FEED_CARD_SUGGESTED_EDITS_ADD_DESC, <ide> FEED_CARD_SUGGESTED_EDITS_TRANSLATE_DESC, <ide> SUGGESTED_EDITS_ONBOARDING, <del> MAIN_ACTIVITY, <ide> ONBOARDING_DIALOG, <del> NOTIFICATION, <del> NAV_MENU <add> FEED, <add> NOTIFICATION <ide> } <ide> <ide> private Constants() { }
Java
mit
18271aa1f4b38fefa859412ce2624351cec55485
0
iontorrent/Torrent-Variant-Caller-stable,iontorrent/Torrent-Variant-Caller-stable,iontorrent/Torrent-Variant-Caller-stable,iontorrent/Torrent-Variant-Caller-stable,iontorrent/Torrent-Variant-Caller-stable,iontorrent/Torrent-Variant-Caller-stable,iontorrent/Torrent-Variant-Caller-stable,iontorrent/Torrent-Variant-Caller-stable
/* * Copyright (c) 2010 The Broad Institute * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without * restriction, including without limitation the rights to use, * copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following * conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR * THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package org.broadinstitute.sting.utils.sam; import net.sf.samtools.CigarOperator; import net.sf.samtools.SAMRecord; import net.sf.samtools.Cigar; import net.sf.samtools.CigarElement; import org.broadinstitute.sting.gatk.contexts.ReferenceContext; import org.broadinstitute.sting.utils.exceptions.ReviewedStingException; import org.broadinstitute.sting.utils.pileup.*; import org.broadinstitute.sting.utils.Utils; import java.util.ArrayList; import java.util.Arrays; import java.util.BitSet; public class AlignmentUtils { public static class MismatchCount { public int numMismatches = 0; public long mismatchQualities = 0; } public static long mismatchingQualities(SAMRecord r, byte[] refSeq, int refIndex) { return getMismatchCount(r, refSeq, refIndex).mismatchQualities; } public static MismatchCount getMismatchCount(SAMRecord r, byte[] refSeq, int refIndex) { return getMismatchCount(r,refSeq,refIndex,0,r.getReadLength()); } // todo -- this code and mismatchesInRefWindow should be combined and optimized into a single // todo -- high performance implementation. We can do a lot better than this right now public static MismatchCount getMismatchCount(SAMRecord r, byte[] refSeq, int refIndex, int startOnRead, int nReadBases) { MismatchCount mc = new MismatchCount(); int readIdx = 0; int endOnRead = startOnRead + nReadBases - 1; // index of the last base on read we want to count byte[] readSeq = r.getReadBases(); Cigar c = r.getCigar(); for (int i = 0 ; i < c.numCigarElements() ; i++) { if ( readIdx > endOnRead ) break; CigarElement ce = c.getCigarElement(i); switch ( ce.getOperator() ) { case M: for (int j = 0 ; j < ce.getLength() ; j++, refIndex++, readIdx++ ) { if ( refIndex >= refSeq.length ) continue; if ( readIdx < startOnRead ) continue; if ( readIdx > endOnRead ) break; byte refChr = refSeq[refIndex]; byte readChr = readSeq[readIdx]; // Note: we need to count X/N's as mismatches because that's what SAM requires //if ( BaseUtils.simpleBaseToBaseIndex(readChr) == -1 || // BaseUtils.simpleBaseToBaseIndex(refChr) == -1 ) // continue; // do not count Ns/Xs/etc ? if ( readChr != refChr ) { mc.numMismatches++; mc.mismatchQualities += r.getBaseQualities()[readIdx]; } } break; case I: case S: readIdx += ce.getLength(); break; case D: case N: refIndex += ce.getLength(); break; case H: case P: break; default: throw new ReviewedStingException("The " + ce.getOperator() + " cigar element is not currently supported"); } } return mc; } /** Returns the number of mismatches in the pileup within the given reference context. * * @param pileup the pileup with reads * @param ref the reference context * @param ignoreTargetSite if true, ignore mismatches at the target locus (i.e. the center of the window) * @return the number of mismatches */ public static int mismatchesInRefWindow(ReadBackedPileup pileup, ReferenceContext ref, boolean ignoreTargetSite) { int mismatches = 0; for ( PileupElement p : pileup ) mismatches += mismatchesInRefWindow(p, ref, ignoreTargetSite); return mismatches; } /** Returns the number of mismatches in the pileup element within the given reference context. * * @param p the pileup element * @param ref the reference context * @param ignoreTargetSite if true, ignore mismatches at the target locus (i.e. the center of the window) * @return the number of mismatches */ public static int mismatchesInRefWindow(PileupElement p, ReferenceContext ref, boolean ignoreTargetSite) { return mismatchesInRefWindow(p, ref, ignoreTargetSite, false); } /** Returns the number of mismatches in the pileup element within the given reference context. * * @param p the pileup element * @param ref the reference context * @param ignoreTargetSite if true, ignore mismatches at the target locus (i.e. the center of the window) * @param qualitySumInsteadOfMismatchCount if true, return the quality score sum of the mismatches rather than the count * @return the number of mismatches */ public static int mismatchesInRefWindow(PileupElement p, ReferenceContext ref, boolean ignoreTargetSite, boolean qualitySumInsteadOfMismatchCount) { int sum = 0; int windowStart = ref.getWindow().getStart(); int windowStop = ref.getWindow().getStop(); byte[] refBases = ref.getBases(); byte[] readBases = p.getRead().getReadBases(); byte[] readQualities = p.getRead().getBaseQualities(); Cigar c = p.getRead().getCigar(); int readIndex = 0; int currentPos = p.getRead().getAlignmentStart(); int refIndex = Math.max(0, currentPos - windowStart); for (int i = 0 ; i < c.numCigarElements() ; i++) { CigarElement ce = c.getCigarElement(i); int cigarElementLength = ce.getLength(); switch ( ce.getOperator() ) { case M: for (int j = 0; j < cigarElementLength; j++, readIndex++, currentPos++) { // are we past the ref window? if ( currentPos > windowStop ) break; // are we before the ref window? if ( currentPos < windowStart ) continue; byte refChr = refBases[refIndex++]; // do we need to skip the target site? if ( ignoreTargetSite && ref.getLocus().getStart() == currentPos ) continue; byte readChr = readBases[readIndex]; if ( readChr != refChr ) sum += (qualitySumInsteadOfMismatchCount) ? readQualities[readIndex] : 1; } break; case I: case S: readIndex += cigarElementLength; break; case D: case N: currentPos += cigarElementLength; if ( currentPos > windowStart ) refIndex += Math.min(cigarElementLength, currentPos - windowStart); break; case H: case P: break; } } return sum; } /** Returns the number of mismatches in the pileup element within the given reference context. * * @param read the SAMRecord * @param ref the reference context * @param maxMismatches the maximum number of surrounding mismatches we tolerate to consider a base good * @param windowSize window size (on each side) to test * @return a bitset representing which bases are good */ public static BitSet mismatchesInRefWindow(SAMRecord read, ReferenceContext ref, int maxMismatches, int windowSize) { // first determine the positions with mismatches int readLength = read.getReadLength(); BitSet mismatches = new BitSet(readLength); // it's possible we aren't starting at the beginning of a read, // and we don't need to look at any of the previous context outside our window // (although we do need future context) int readStartPos = Math.max(read.getAlignmentStart(), ref.getLocus().getStart() - windowSize); int currentReadPos = read.getAlignmentStart(); byte[] refBases = ref.getBases(); int refIndex = readStartPos - ref.getWindow().getStart(); if ( refIndex < 0 ) { throw new IllegalStateException("When calculating mismatches, we somehow don't have enough previous reference context for read " + read.getReadName() + " at position " + ref.getLocus()); } byte[] readBases = read.getReadBases(); int readIndex = 0; Cigar c = read.getCigar(); for (int i = 0 ; i < c.numCigarElements() ; i++) { CigarElement ce = c.getCigarElement(i); int cigarElementLength = ce.getLength(); switch ( ce.getOperator() ) { case M: for (int j = 0; j < cigarElementLength; j++, readIndex++) { // skip over unwanted bases if ( currentReadPos++ < readStartPos ) continue; // this is possible if reads extend beyond the contig end if ( refIndex >= refBases.length ) break; byte refChr = refBases[refIndex]; byte readChr = readBases[readIndex]; if ( readChr != refChr ) mismatches.set(readIndex); refIndex++; } break; case I: case S: readIndex += cigarElementLength; break; case D: case N: if ( currentReadPos >= readStartPos ) refIndex += cigarElementLength; currentReadPos += cigarElementLength; break; case H: case P: break; } } // all bits are set to false by default BitSet result = new BitSet(readLength); int currentPos = 0, leftPos = 0, rightPos; int mismatchCount = 0; // calculate how many mismatches exist in the windows to the left/right for ( rightPos = 1; rightPos <= windowSize && rightPos < readLength; rightPos++) { if ( mismatches.get(rightPos) ) mismatchCount++; } if ( mismatchCount <= maxMismatches ) result.set(currentPos); // now, traverse over the read positions while ( currentPos < readLength ) { // add a new rightmost position if ( rightPos < readLength && mismatches.get(rightPos++) ) mismatchCount++; // re-penalize the previous position if ( mismatches.get(currentPos++) ) mismatchCount++; // don't penalize the current position if ( mismatches.get(currentPos) ) mismatchCount--; // subtract the leftmost position if ( leftPos < currentPos - windowSize && mismatches.get(leftPos++) ) mismatchCount--; if ( mismatchCount <= maxMismatches ) result.set(currentPos); } return result; } /** Returns number of alignment blocks (continuous stretches of aligned bases) in the specified alignment. * This method follows closely the SAMRecord::getAlignmentBlocks() implemented in samtools library, but * it only counts blocks without actually allocating and filling the list of blocks themselves. Hence, this method is * a much more efficient alternative to r.getAlignmentBlocks.size() in the situations when this number is all that is needed. * Formally, this method simply returns the number of M elements in the cigar. * @param r alignment * @return number of continuous alignment blocks (i.e. 'M' elements of the cigar; all indel and clipping elements are ignored). */ public static int getNumAlignmentBlocks(final SAMRecord r) { int n = 0; final Cigar cigar = r.getCigar(); if (cigar == null) return 0; for (final CigarElement e : cigar.getCigarElements()) { if (e.getOperator() == CigarOperator.M ) n++; } return n; } public static int getNumAlignedBases(final SAMRecord r) { int n = 0; final Cigar cigar = r.getCigar(); if (cigar == null) return 0; for (final CigarElement e : cigar.getCigarElements()) { if (e.getOperator() == CigarOperator.M ) { n += e.getLength(); } } return n; } public static byte[] alignmentToByteArray( final Cigar cigar, final byte[] read, final byte[] ref ) { final byte[] alignment = new byte[read.length]; int refPos = 0; int alignPos = 0; for ( int iii = 0 ; iii < cigar.numCigarElements() ; iii++ ) { final CigarElement ce = cigar.getCigarElement(iii); final int elementLength = ce.getLength(); switch( ce.getOperator() ) { case I: case S: for ( int jjj = 0; jjj < elementLength; jjj++ ) { alignment[alignPos++] = '+'; } break; case D: case N: refPos++; break; case M: for ( int jjj = 0; jjj < elementLength; jjj++ ) { alignment[alignPos] = ref[refPos]; alignPos++; refPos++; } break; case H: case P: break; default: throw new ReviewedStingException( "Unsupported cigar operator: " + ce.getOperator() ); } } return alignment; } public static int calcAlignmentByteArrayOffset( final Cigar cigar, int pileupOffset, final int alignmentStart, final int refLocus ) { boolean atDeletion = false; if(pileupOffset == -1) { atDeletion = true; pileupOffset = refLocus - alignmentStart; final CigarElement ce = cigar.getCigarElement(0); if( ce.getOperator() == CigarOperator.S ) { pileupOffset += ce.getLength(); } } int pos = 0; int alignmentPos = 0; for ( int iii = 0 ; iii < cigar.numCigarElements() ; iii++ ) { final CigarElement ce = cigar.getCigarElement(iii); final int elementLength = ce.getLength(); switch( ce.getOperator() ) { case I: case S: pos += elementLength; if( pos >= pileupOffset ) { return alignmentPos; } break; case D: case N: if(!atDeletion) { alignmentPos += elementLength; } else { if( pos + elementLength - 1 >= pileupOffset ) { return alignmentPos + (pileupOffset - pos); } else { pos += elementLength; alignmentPos += elementLength; } } break; case M: if( pos + elementLength - 1 >= pileupOffset ) { return alignmentPos + (pileupOffset - pos); } else { pos += elementLength; alignmentPos += elementLength; } break; case H: case P: break; default: throw new ReviewedStingException( "Unsupported cigar operator: " + ce.getOperator() ); } } return alignmentPos; } public static byte[] readToAlignmentByteArray( final Cigar cigar, final byte[] read ) { int alignmentLength = 0; for ( int iii = 0 ; iii < cigar.numCigarElements() ; iii++ ) { final CigarElement ce = cigar.getCigarElement(iii); final int elementLength = ce.getLength(); switch( ce.getOperator() ) { case I: case S: break; case D: case N: alignmentLength += elementLength; break; case M: alignmentLength += elementLength; break; case H: case P: break; default: throw new ReviewedStingException( "Unsupported cigar operator: " + ce.getOperator() ); } } final byte[] alignment = new byte[alignmentLength]; int alignPos = 0; int readPos = 0; for ( int iii = 0 ; iii < cigar.numCigarElements() ; iii++ ) { final CigarElement ce = cigar.getCigarElement(iii); final int elementLength = ce.getLength(); switch( ce.getOperator() ) { case I: /* if( alignPos > 0 ) { if( alignment[alignPos-1] == BaseUtils.A ) { alignment[alignPos-1] = PileupElement.A_FOLLOWED_BY_INSERTION_BASE; } else if( alignment[alignPos-1] == BaseUtils.C ) { alignment[alignPos-1] = PileupElement.C_FOLLOWED_BY_INSERTION_BASE; } else if( alignment[alignPos-1] == BaseUtils.T ) { alignment[alignPos-1] = PileupElement.T_FOLLOWED_BY_INSERTION_BASE; } else if( alignment[alignPos-1] == BaseUtils.G ) { alignment[alignPos-1] = PileupElement.G_FOLLOWED_BY_INSERTION_BASE; } } */ case S: for ( int jjj = 0; jjj < elementLength; jjj++ ) { readPos++; } break; case D: case N: for ( int jjj = 0; jjj < elementLength; jjj++ ) { alignment[alignPos] = PileupElement.DELETION_BASE; alignPos++; } break; case M: for ( int jjj = 0; jjj < elementLength; jjj++ ) { alignment[alignPos] = read[readPos]; alignPos++; readPos++; } break; case H: case P: break; default: throw new ReviewedStingException( "Unsupported cigar operator: " + ce.getOperator() ); } } return alignment; } /** * Due to (unfortunate) multiple ways to indicate that read is unmapped allowed by SAM format * specification, one may need this convenience shortcut. Checks both 'read unmapped' flag and * alignment reference index/start. * @param r record * @return true if read is unmapped */ public static boolean isReadUnmapped(final SAMRecord r) { if ( r.getReadUnmappedFlag() ) return true; // our life would be so much easier if all sam files followed the specs. In reality, // sam files (including those generated by maq or bwa) miss headers altogether. When // reading such a SAM file, reference name is set, but since there is no sequence dictionary, // null is always returned for referenceIndex. Let's be paranoid here, and make sure that // we do not call the read "unmapped" when it has only reference name set with ref. index missing // or vice versa. if ( ( r.getReferenceIndex() != null && r.getReferenceIndex() != SAMRecord.NO_ALIGNMENT_REFERENCE_INDEX || r.getReferenceName() != null && r.getReferenceName() != SAMRecord.NO_ALIGNMENT_REFERENCE_NAME ) && r.getAlignmentStart() != SAMRecord.NO_ALIGNMENT_START ) return false ; return true; } /** * Due to (unfortunate) multiple ways to indicate that read/mate is unmapped allowed by SAM format * specification, one may need this convenience shortcut. Checks both 'mate unmapped' flag and * alignment reference index/start of the mate. * @param r sam record for the read * @return true if read's mate is unmapped */ public static boolean isMateUnmapped(final SAMRecord r) { if ( r.getMateUnmappedFlag() ) return true; // our life would be so much easier if all sam files followed the specs. In reality, // sam files (including those generated by maq or bwa) miss headers altogether. When // reading such a SAM file, reference name is set, but since there is no sequence dictionary, // null is always returned for referenceIndex. Let's be paranoid here, and make sure that // we do not call the read "unmapped" when it has only reference name set with ref. index missing // or vice versa. if ( ( r.getMateReferenceIndex() != null && r.getMateReferenceIndex() != SAMRecord.NO_ALIGNMENT_REFERENCE_INDEX || r.getMateReferenceName() != null && r.getMateReferenceName() != SAMRecord.NO_ALIGNMENT_REFERENCE_NAME ) && r.getMateAlignmentStart() != SAMRecord.NO_ALIGNMENT_START ) return false ; return true; } /** Returns true is read is mapped and mapped uniquely (Q>0). * * @param read * @return */ public static boolean isReadUniquelyMapped(SAMRecord read) { return ( ! AlignmentUtils.isReadUnmapped(read) ) && read.getMappingQuality() > 0; } /** Returns the array of base qualitites in the order the bases were read on the machine (i.e. always starting from * cycle 1). In other words, if the read is unmapped or aligned in the forward direction, the read's own base * qualities are returned as stored in the SAM record; if the read is aligned in the reverse direction, the array * of read's base qualitites is inverted (in this case new array is allocated and returned). * @param read * @return */ public static byte [] getQualsInCycleOrder(SAMRecord read) { if ( isReadUnmapped(read) || ! read.getReadNegativeStrandFlag() ) return read.getBaseQualities(); return Utils.reverse(read.getBaseQualities()); } /** Returns the array of original base qualitites (before recalibration) in the order the bases were read on the machine (i.e. always starting from * cycle 1). In other words, if the read is unmapped or aligned in the forward direction, the read's own base * qualities are returned as stored in the SAM record; if the read is aligned in the reverse direction, the array * of read's base qualitites is inverted (in this case new array is allocated and returned). If no original base qualities * are available this method will throw a runtime exception. * @param read * @return */ public static byte [] getOriginalQualsInCycleOrder(SAMRecord read) { if ( isReadUnmapped(read) || ! read.getReadNegativeStrandFlag() ) return read.getOriginalBaseQualities(); return Utils.reverse(read.getOriginalBaseQualities()); } /** Takes the alignment of the read sequence <code>readSeq</code> to the reference sequence <code>refSeq</code> * starting at 0-based position <code>refIndex</code> on the <code>refSeq</code> and specified by its <code>cigar</code>. * The last argument <code>readIndex</code> specifies 0-based position on the read where the alignment described by the * <code>cigar</code> starts. Usually cigars specify alignments of the whole read to the ref, so that readIndex is normally 0. * Use non-zero readIndex only when the alignment cigar represents alignment of a part of the read. The refIndex in this case * should be the position where the alignment of that part of the read starts at. In other words, both refIndex and readIndex are * always the positions where the cigar starts on the ref and on the read, respectively. * * If the alignment has an indel, then this method attempts moving this indel left across a stretch of repetitive bases. For instance, if the original cigar * specifies that (any) one AT is deleted from a repeat sequence TATATATA, the output cigar will always mark the leftmost AT * as deleted. If there is no indel in the original cigar, or the indel position is determined unambiguously (i.e. inserted/deleted sequence * is not repeated), the original cigar is returned. * @param cigar structure of the original alignment * @param refSeq reference sequence the read is aligned to * @param readSeq read sequence * @param refIndex 0-based alignment start position on ref * @param readIndex 0-based alignment start position on read * @return a cigar, in which indel is guaranteed to be placed at the leftmost possible position across a repeat (if any) */ public static Cigar leftAlignIndel(Cigar cigar, final byte[] refSeq, final byte[] readSeq, final int refIndex, final int readIndex) { int indexOfIndel = -1; for ( int i = 0; i < cigar.numCigarElements(); i++ ) { CigarElement ce = cigar.getCigarElement(i); if ( ce.getOperator() == CigarOperator.D || ce.getOperator() == CigarOperator.I ) { // if there is more than 1 indel, don't left align if ( indexOfIndel != -1 ) return cigar; indexOfIndel = i; } } // if there is no indel or if the alignment starts with an insertion (so that there // is no place on the read to move that insertion further left), we are done if ( indexOfIndel < 1 ) return cigar; final int indelLength = cigar.getCigarElement(indexOfIndel).getLength(); byte[] altString = createIndelString(cigar, indexOfIndel, refSeq, readSeq, refIndex, readIndex); if ( altString == null ) return cigar; Cigar newCigar = cigar; for ( int i = 0; i < indelLength; i++ ) { newCigar = moveCigarLeft(newCigar, indexOfIndel); byte[] newAltString = createIndelString(newCigar, indexOfIndel, refSeq, readSeq, refIndex, readIndex); // check to make sure we haven't run off the end of the read boolean reachedEndOfRead = cigarHasZeroSizeElement(newCigar); if ( Arrays.equals(altString, newAltString) ) { cigar = newCigar; i = -1; if ( reachedEndOfRead ) cigar = cleanUpCigar(cigar); } if ( reachedEndOfRead ) break; } return cigar; } private static boolean cigarHasZeroSizeElement(Cigar c) { for ( CigarElement ce : c.getCigarElements() ) { if ( ce.getLength() == 0 ) return true; } return false; } private static Cigar cleanUpCigar(Cigar c) { ArrayList<CigarElement> elements = new ArrayList<CigarElement>(c.numCigarElements()-1); for ( CigarElement ce : c.getCigarElements() ) { if ( ce.getLength() != 0 && (elements.size() != 0 || ce.getOperator() != CigarOperator.D) ) { elements.add(ce); } } return new Cigar(elements); } private static Cigar moveCigarLeft(Cigar cigar, int indexOfIndel) { // get the first few elements ArrayList<CigarElement> elements = new ArrayList<CigarElement>(cigar.numCigarElements()); for ( int i = 0; i < indexOfIndel - 1; i++) elements.add(cigar.getCigarElement(i)); // get the indel element and move it left one base CigarElement ce = cigar.getCigarElement(indexOfIndel-1); elements.add(new CigarElement(ce.getLength()-1, ce.getOperator())); elements.add(cigar.getCigarElement(indexOfIndel)); if ( indexOfIndel+1 < cigar.numCigarElements() ) { ce = cigar.getCigarElement(indexOfIndel+1); elements.add(new CigarElement(ce.getLength()+1, ce.getOperator())); } else { elements.add(new CigarElement(1, CigarOperator.M)); } // get the last few elements for ( int i = indexOfIndel + 2; i < cigar.numCigarElements(); i++) elements.add(cigar.getCigarElement(i)); return new Cigar(elements); } private static byte[] createIndelString(final Cigar cigar, final int indexOfIndel, final byte[] refSeq, final byte[] readSeq, int refIndex, int readIndex) { CigarElement indel = cigar.getCigarElement(indexOfIndel); int indelLength = indel.getLength(); int totalRefBases = 0; for ( int i = 0; i < indexOfIndel; i++ ) { CigarElement ce = cigar.getCigarElement(i); int length = ce.getLength(); switch( ce.getOperator() ) { case M: readIndex += length; refIndex += length; totalRefBases += length; break; case S: readIndex += length; break; case N: refIndex += length; totalRefBases += length; break; default: break; } } // sometimes, when there are very large known indels, we won't have enough reference sequence to cover them if ( totalRefBases + indelLength > refSeq.length ) indelLength -= (totalRefBases + indelLength - refSeq.length); // the indel-based reference string byte[] alt = new byte[refSeq.length + (indelLength * (indel.getOperator() == CigarOperator.D ? -1 : 1))]; // add the bases before the indel, making sure it's not aligned off the end of the reference if ( refIndex > alt.length || refIndex > refSeq.length ) return null; System.arraycopy(refSeq, 0, alt, 0, refIndex); int currentPos = refIndex; // take care of the indel if ( indel.getOperator() == CigarOperator.D ) { refIndex += indelLength; } else { System.arraycopy(readSeq, readIndex, alt, currentPos, indelLength); currentPos += indelLength; } // add the bases after the indel, making sure it's not aligned off the end of the reference if ( refSeq.length - refIndex > alt.length - currentPos ) return null; System.arraycopy(refSeq, refIndex, alt, currentPos, refSeq.length - refIndex); return alt; } }
java/src/org/broadinstitute/sting/utils/sam/AlignmentUtils.java
/* * Copyright (c) 2010 The Broad Institute * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without * restriction, including without limitation the rights to use, * copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following * conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR * THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package org.broadinstitute.sting.utils.sam; import net.sf.samtools.CigarOperator; import net.sf.samtools.SAMRecord; import net.sf.samtools.Cigar; import net.sf.samtools.CigarElement; import org.broadinstitute.sting.gatk.contexts.ReferenceContext; import org.broadinstitute.sting.utils.exceptions.ReviewedStingException; import org.broadinstitute.sting.utils.pileup.*; import org.broadinstitute.sting.utils.Utils; import java.util.ArrayList; import java.util.Arrays; import java.util.BitSet; public class AlignmentUtils { public static class MismatchCount { public int numMismatches = 0; public long mismatchQualities = 0; } public static long mismatchingQualities(SAMRecord r, byte[] refSeq, int refIndex) { return getMismatchCount(r, refSeq, refIndex).mismatchQualities; } public static MismatchCount getMismatchCount(SAMRecord r, byte[] refSeq, int refIndex) { return getMismatchCount(r,refSeq,refIndex,0,r.getReadLength()); } // todo -- this code and mismatchesInRefWindow should be combined and optimized into a single // todo -- high performance implementation. We can do a lot better than this right now public static MismatchCount getMismatchCount(SAMRecord r, byte[] refSeq, int refIndex, int startOnRead, int nReadBases) { MismatchCount mc = new MismatchCount(); int readIdx = 0; int endOnRead = startOnRead + nReadBases - 1; // index of the last base on read we want to count byte[] readSeq = r.getReadBases(); Cigar c = r.getCigar(); for (int i = 0 ; i < c.numCigarElements() ; i++) { if ( readIdx > endOnRead ) break; CigarElement ce = c.getCigarElement(i); switch ( ce.getOperator() ) { case M: for (int j = 0 ; j < ce.getLength() ; j++, refIndex++, readIdx++ ) { if ( refIndex >= refSeq.length ) continue; if ( readIdx < startOnRead ) continue; if ( readIdx > endOnRead ) break; byte refChr = refSeq[refIndex]; byte readChr = readSeq[readIdx]; // Note: we need to count X/N's as mismatches because that's what SAM requires //if ( BaseUtils.simpleBaseToBaseIndex(readChr) == -1 || // BaseUtils.simpleBaseToBaseIndex(refChr) == -1 ) // continue; // do not count Ns/Xs/etc ? if ( readChr != refChr ) { mc.numMismatches++; mc.mismatchQualities += r.getBaseQualities()[readIdx]; } } break; case I: case S: readIdx += ce.getLength(); break; case D: case N: refIndex += ce.getLength(); break; case H: case P: break; default: throw new ReviewedStingException("The " + ce.getOperator() + " cigar element is not currently supported"); } } return mc; } /** Returns the number of mismatches in the pileup within the given reference context. * * @param pileup the pileup with reads * @param ref the reference context * @param ignoreTargetSite if true, ignore mismatches at the target locus (i.e. the center of the window) * @return the number of mismatches */ public static int mismatchesInRefWindow(ReadBackedPileup pileup, ReferenceContext ref, boolean ignoreTargetSite) { int mismatches = 0; for ( PileupElement p : pileup ) mismatches += mismatchesInRefWindow(p, ref, ignoreTargetSite); return mismatches; } /** Returns the number of mismatches in the pileup element within the given reference context. * * @param p the pileup element * @param ref the reference context * @param ignoreTargetSite if true, ignore mismatches at the target locus (i.e. the center of the window) * @return the number of mismatches */ public static int mismatchesInRefWindow(PileupElement p, ReferenceContext ref, boolean ignoreTargetSite) { return mismatchesInRefWindow(p, ref, ignoreTargetSite, false); } /** Returns the number of mismatches in the pileup element within the given reference context. * * @param p the pileup element * @param ref the reference context * @param ignoreTargetSite if true, ignore mismatches at the target locus (i.e. the center of the window) * @param qualitySumInsteadOfMismatchCount if true, return the quality score sum of the mismatches rather than the count * @return the number of mismatches */ public static int mismatchesInRefWindow(PileupElement p, ReferenceContext ref, boolean ignoreTargetSite, boolean qualitySumInsteadOfMismatchCount) { int sum = 0; int windowStart = ref.getWindow().getStart(); int windowStop = ref.getWindow().getStop(); byte[] refBases = ref.getBases(); byte[] readBases = p.getRead().getReadBases(); byte[] readQualities = p.getRead().getBaseQualities(); Cigar c = p.getRead().getCigar(); int readIndex = 0; int currentPos = p.getRead().getAlignmentStart(); int refIndex = Math.max(0, currentPos - windowStart); for (int i = 0 ; i < c.numCigarElements() ; i++) { CigarElement ce = c.getCigarElement(i); int cigarElementLength = ce.getLength(); switch ( ce.getOperator() ) { case M: for (int j = 0; j < cigarElementLength; j++, readIndex++, currentPos++) { // are we past the ref window? if ( currentPos > windowStop ) break; // are we before the ref window? if ( currentPos < windowStart ) continue; byte refChr = refBases[refIndex++]; // do we need to skip the target site? if ( ignoreTargetSite && ref.getLocus().getStart() == currentPos ) continue; byte readChr = readBases[readIndex]; if ( readChr != refChr ) sum += (qualitySumInsteadOfMismatchCount) ? readQualities[readIndex] : 1; } break; case I: case S: readIndex += cigarElementLength; break; case D: case N: currentPos += cigarElementLength; if ( currentPos > windowStart ) refIndex += Math.min(cigarElementLength, currentPos - windowStart); break; case H: case P: break; } } return sum; } /** Returns the number of mismatches in the pileup element within the given reference context. * * @param read the SAMRecord * @param ref the reference context * @param maxMismatches the maximum number of surrounding mismatches we tolerate to consider a base good * @param windowSize window size (on each side) to test * @return a bitset representing which bases are good */ public static BitSet mismatchesInRefWindow(SAMRecord read, ReferenceContext ref, int maxMismatches, int windowSize) { // first determine the positions with mismatches int readLength = read.getReadLength(); BitSet mismatches = new BitSet(readLength); // it's possible we aren't starting at the beginning of a read, // and we don't need to look at any of the previous context outside our window // (although we do need future context) int readStartPos = Math.max(read.getAlignmentStart(), ref.getLocus().getStart() - windowSize); int currentReadPos = read.getAlignmentStart(); byte[] refBases = ref.getBases(); int refIndex = readStartPos - ref.getWindow().getStart(); if ( refIndex < 0 ) { throw new IllegalStateException("When calculating mismatches, we somehow don't have enough previous reference context for read " + read.getReadName() + " at position " + ref.getLocus()); } byte[] readBases = read.getReadBases(); int readIndex = 0; Cigar c = read.getCigar(); for (int i = 0 ; i < c.numCigarElements() ; i++) { CigarElement ce = c.getCigarElement(i); int cigarElementLength = ce.getLength(); switch ( ce.getOperator() ) { case M: for (int j = 0; j < cigarElementLength; j++, readIndex++) { // skip over unwanted bases if ( currentReadPos++ < readStartPos ) continue; // this is possible if reads extend beyond the contig end if ( refIndex >= refBases.length ) break; byte refChr = refBases[refIndex]; byte readChr = readBases[readIndex]; if ( readChr != refChr ) mismatches.set(readIndex); refIndex++; } break; case I: case S: readIndex += cigarElementLength; break; case D: case N: if ( currentReadPos >= readStartPos ) refIndex += cigarElementLength; currentReadPos += cigarElementLength; break; case H: case P: break; } } // all bits are set to false by default BitSet result = new BitSet(readLength); int currentPos = 0, leftPos = 0, rightPos; int mismatchCount = 0; // calculate how many mismatches exist in the windows to the left/right for ( rightPos = 1; rightPos <= windowSize && rightPos < readLength; rightPos++) { if ( mismatches.get(rightPos) ) mismatchCount++; } if ( mismatchCount <= maxMismatches ) result.set(currentPos); // now, traverse over the read positions while ( currentPos < readLength ) { // add a new rightmost position if ( rightPos < readLength && mismatches.get(rightPos++) ) mismatchCount++; // re-penalize the previous position if ( mismatches.get(currentPos++) ) mismatchCount++; // don't penalize the current position if ( mismatches.get(currentPos) ) mismatchCount--; // subtract the leftmost position if ( leftPos < currentPos - windowSize && mismatches.get(leftPos++) ) mismatchCount--; if ( mismatchCount <= maxMismatches ) result.set(currentPos); } return result; } /** Returns number of alignment blocks (continuous stretches of aligned bases) in the specified alignment. * This method follows closely the SAMRecord::getAlignmentBlocks() implemented in samtools library, but * it only counts blocks without actually allocating and filling the list of blocks themselves. Hence, this method is * a much more efficient alternative to r.getAlignmentBlocks.size() in the situations when this number is all that is needed. * Formally, this method simply returns the number of M elements in the cigar. * @param r alignment * @return number of continuous alignment blocks (i.e. 'M' elements of the cigar; all indel and clipping elements are ignored). */ public static int getNumAlignmentBlocks(final SAMRecord r) { int n = 0; final Cigar cigar = r.getCigar(); if (cigar == null) return 0; for (final CigarElement e : cigar.getCigarElements()) { if (e.getOperator() == CigarOperator.M ) n++; } return n; } public static int getNumAlignedBases(final SAMRecord r) { int n = 0; final Cigar cigar = r.getCigar(); if (cigar == null) return 0; for (final CigarElement e : cigar.getCigarElements()) { if (e.getOperator() == CigarOperator.M ) { n += e.getLength(); } } return n; } public static byte[] alignmentToByteArray( final Cigar cigar, final byte[] read, final byte[] ref ) { final byte[] alignment = new byte[read.length]; int refPos = 0; int alignPos = 0; for ( int iii = 0 ; iii < cigar.numCigarElements() ; iii++ ) { final CigarElement ce = cigar.getCigarElement(iii); final int elementLength = ce.getLength(); switch( ce.getOperator() ) { case I: case S: for ( int jjj = 0; jjj < elementLength; jjj++ ) { alignment[alignPos++] = '+'; } break; case D: case N: refPos++; break; case M: for ( int jjj = 0; jjj < elementLength; jjj++ ) { alignment[alignPos] = ref[refPos]; alignPos++; refPos++; } break; case H: case P: break; default: throw new ReviewedStingException( "Unsupported cigar operator: " + ce.getOperator() ); } } return alignment; } public static int calcAlignmentByteArrayOffset( final Cigar cigar, int pileupOffset, final int alignmentStart, final int refLocus ) { boolean atDeletion = false; if(pileupOffset == -1) { atDeletion = true; pileupOffset = refLocus - alignmentStart; final CigarElement ce = cigar.getCigarElement(0); if( ce.getOperator() == CigarOperator.S ) { pileupOffset += ce.getLength(); } } int pos = 0; int alignmentPos = 0; for ( int iii = 0 ; iii < cigar.numCigarElements() ; iii++ ) { final CigarElement ce = cigar.getCigarElement(iii); final int elementLength = ce.getLength(); switch( ce.getOperator() ) { case I: case S: pos += elementLength; if( pos >= pileupOffset ) { return alignmentPos; } break; case D: case N: if(!atDeletion) { alignmentPos += elementLength; } else { if( pos + elementLength - 1 >= pileupOffset ) { return alignmentPos + (pileupOffset - pos); } else { pos += elementLength; alignmentPos += elementLength; } } break; case M: if( pos + elementLength - 1 >= pileupOffset ) { return alignmentPos + (pileupOffset - pos); } else { pos += elementLength; alignmentPos += elementLength; } break; case H: case P: break; default: throw new ReviewedStingException( "Unsupported cigar operator: " + ce.getOperator() ); } } return alignmentPos; } public static byte[] readToAlignmentByteArray( final Cigar cigar, final byte[] read ) { int alignmentLength = 0; for ( int iii = 0 ; iii < cigar.numCigarElements() ; iii++ ) { final CigarElement ce = cigar.getCigarElement(iii); final int elementLength = ce.getLength(); switch( ce.getOperator() ) { case I: case S: break; case D: case N: alignmentLength += elementLength; break; case M: alignmentLength += elementLength; break; case H: case P: break; default: throw new ReviewedStingException( "Unsupported cigar operator: " + ce.getOperator() ); } } final byte[] alignment = new byte[alignmentLength]; int alignPos = 0; int readPos = 0; for ( int iii = 0 ; iii < cigar.numCigarElements() ; iii++ ) { final CigarElement ce = cigar.getCigarElement(iii); final int elementLength = ce.getLength(); switch( ce.getOperator() ) { case I: /* if( alignPos > 0 ) { if( alignment[alignPos-1] == BaseUtils.A ) { alignment[alignPos-1] = PileupElement.A_FOLLOWED_BY_INSERTION_BASE; } else if( alignment[alignPos-1] == BaseUtils.C ) { alignment[alignPos-1] = PileupElement.C_FOLLOWED_BY_INSERTION_BASE; } else if( alignment[alignPos-1] == BaseUtils.T ) { alignment[alignPos-1] = PileupElement.T_FOLLOWED_BY_INSERTION_BASE; } else if( alignment[alignPos-1] == BaseUtils.G ) { alignment[alignPos-1] = PileupElement.G_FOLLOWED_BY_INSERTION_BASE; } } */ case S: for ( int jjj = 0; jjj < elementLength; jjj++ ) { readPos++; } break; case D: case N: for ( int jjj = 0; jjj < elementLength; jjj++ ) { alignment[alignPos] = PileupElement.DELETION_BASE; alignPos++; } break; case M: for ( int jjj = 0; jjj < elementLength; jjj++ ) { alignment[alignPos] = read[readPos]; alignPos++; readPos++; } break; case H: case P: break; default: throw new ReviewedStingException( "Unsupported cigar operator: " + ce.getOperator() ); } } return alignment; } /** * Due to (unfortunate) multiple ways to indicate that read is unmapped allowed by SAM format * specification, one may need this convenience shortcut. Checks both 'read unmapped' flag and * alignment reference index/start. * @param r record * @return true if read is unmapped */ public static boolean isReadUnmapped(final SAMRecord r) { if ( r.getReadUnmappedFlag() ) return true; // our life would be so much easier if all sam files followed the specs. In reality, // sam files (including those generated by maq or bwa) miss headers altogether. When // reading such a SAM file, reference name is set, but since there is no sequence dictionary, // null is always returned for referenceIndex. Let's be paranoid here, and make sure that // we do not call the read "unmapped" when it has only reference name set with ref. index missing // or vice versa. if ( ( r.getReferenceIndex() != null && r.getReferenceIndex() != SAMRecord.NO_ALIGNMENT_REFERENCE_INDEX || r.getReferenceName() != null && r.getReferenceName() != SAMRecord.NO_ALIGNMENT_REFERENCE_NAME ) && r.getAlignmentStart() != SAMRecord.NO_ALIGNMENT_START ) return false ; return true; } /** * Due to (unfortunate) multiple ways to indicate that read/mate is unmapped allowed by SAM format * specification, one may need this convenience shortcut. Checks both 'mate unmapped' flag and * alignment reference index/start of the mate. * @param r sam record for the read * @return true if read's mate is unmapped */ public static boolean isMateUnmapped(final SAMRecord r) { if ( r.getMateUnmappedFlag() ) return true; // our life would be so much easier if all sam files followed the specs. In reality, // sam files (including those generated by maq or bwa) miss headers altogether. When // reading such a SAM file, reference name is set, but since there is no sequence dictionary, // null is always returned for referenceIndex. Let's be paranoid here, and make sure that // we do not call the read "unmapped" when it has only reference name set with ref. index missing // or vice versa. if ( ( r.getMateReferenceIndex() != null && r.getMateReferenceIndex() != SAMRecord.NO_ALIGNMENT_REFERENCE_INDEX || r.getMateReferenceName() != null && r.getMateReferenceName() != SAMRecord.NO_ALIGNMENT_REFERENCE_NAME ) && r.getMateAlignmentStart() != SAMRecord.NO_ALIGNMENT_START ) return false ; return true; } /** Returns true is read is mapped and mapped uniquely (Q>0). * * @param read * @return */ public static boolean isReadUniquelyMapped(SAMRecord read) { return ( ! AlignmentUtils.isReadUnmapped(read) ) && read.getMappingQuality() > 0; } /** Returns the array of base qualitites in the order the bases were read on the machine (i.e. always starting from * cycle 1). In other words, if the read is unmapped or aligned in the forward direction, the read's own base * qualities are returned as stored in the SAM record; if the read is aligned in the reverse direction, the array * of read's base qualitites is inverted (in this case new array is allocated and returned). * @param read * @return */ public static byte [] getQualsInCycleOrder(SAMRecord read) { if ( isReadUnmapped(read) || ! read.getReadNegativeStrandFlag() ) return read.getBaseQualities(); return Utils.reverse(read.getBaseQualities()); } /** Returns the array of original base qualitites (before recalibration) in the order the bases were read on the machine (i.e. always starting from * cycle 1). In other words, if the read is unmapped or aligned in the forward direction, the read's own base * qualities are returned as stored in the SAM record; if the read is aligned in the reverse direction, the array * of read's base qualitites is inverted (in this case new array is allocated and returned). If no original base qualities * are available this method will throw a runtime exception. * @param read * @return */ public static byte [] getOriginalQualsInCycleOrder(SAMRecord read) { if ( isReadUnmapped(read) || ! read.getReadNegativeStrandFlag() ) return read.getOriginalBaseQualities(); return Utils.reverse(read.getOriginalBaseQualities()); } /** Takes the alignment of the read sequence <code>readSeq</code> to the reference sequence <code>refSeq</code> * starting at 0-based position <code>refIndex</code> on the <code>refSeq</code> and specified by its <code>cigar</code>. * The last argument <code>readIndex</code> specifies 0-based position on the read where the alignment described by the * <code>cigar</code> starts. Usually cigars specify alignments of the whole read to the ref, so that readIndex is normally 0. * Use non-zero readIndex only when the alignment cigar represents alignment of a part of the read. The refIndex in this case * should be the position where the alignment of that part of the read starts at. In other words, both refIndex and readIndex are * always the positions where the cigar starts on the ref and on the read, respectively. * * If the alignment has an indel, then this method attempts moving this indel left across a stretch of repetitive bases. For instance, if the original cigar * specifies that (any) one AT is deleted from a repeat sequence TATATATA, the output cigar will always mark the leftmost AT * as deleted. If there is no indel in the original cigar, or the indel position is determined unambiguously (i.e. inserted/deleted sequence * is not repeated), the original cigar is returned. * @param cigar structure of the original alignment * @param refSeq reference sequence the read is aligned to * @param readSeq read sequence * @param refIndex 0-based alignment start position on ref * @param readIndex 0-based alignment start position on read * @return a cigar, in which indel is guaranteed to be placed at the leftmost possible position across a repeat (if any) */ public static Cigar leftAlignIndel(Cigar cigar, final byte[] refSeq, final byte[] readSeq, final int refIndex, final int readIndex) { int indexOfIndel = -1; for ( int i = 0; i < cigar.numCigarElements(); i++ ) { CigarElement ce = cigar.getCigarElement(i); if ( ce.getOperator() == CigarOperator.D || ce.getOperator() == CigarOperator.I ) { // if there is more than 1 indel, don't left align if ( indexOfIndel != -1 ) return cigar; indexOfIndel = i; } } // if there is no indel or if the alignment starts with an insertion (so that there // is no place on the read to move that insertion further left), we are done if ( indexOfIndel < 1 ) return cigar; final int indelLength = cigar.getCigarElement(indexOfIndel).getLength(); byte[] altString = createIndelString(cigar, indexOfIndel, refSeq, readSeq, refIndex, readIndex); if ( altString == null ) return cigar; Cigar newCigar = cigar; for ( int i = 0; i < indelLength; i++ ) { newCigar = moveCigarLeft(newCigar, indexOfIndel); byte[] newAltString = createIndelString(newCigar, indexOfIndel, refSeq, readSeq, refIndex, readIndex); // check to make sure we haven't run off the end of the read boolean reachedEndOfRead = cigarHasZeroSizeElement(newCigar); if ( Arrays.equals(altString, newAltString) ) { cigar = newCigar; i = -1; if ( reachedEndOfRead ) cigar = cleanUpCigar(cigar); } if ( reachedEndOfRead ) break; } return cigar; } private static boolean cigarHasZeroSizeElement(Cigar c) { for ( CigarElement ce : c.getCigarElements() ) { if ( ce.getLength() == 0 ) return true; } return false; } private static Cigar cleanUpCigar(Cigar c) { ArrayList<CigarElement> elements = new ArrayList<CigarElement>(c.numCigarElements()-1); for ( CigarElement ce : c.getCigarElements() ) { if ( ce.getLength() != 0 && (elements.size() != 0 || ce.getOperator() != CigarOperator.D) ) { elements.add(ce); } } return new Cigar(elements); } private static Cigar moveCigarLeft(Cigar cigar, int indexOfIndel) { // get the first few elements ArrayList<CigarElement> elements = new ArrayList<CigarElement>(cigar.numCigarElements()); for ( int i = 0; i < indexOfIndel - 1; i++) elements.add(cigar.getCigarElement(i)); // get the indel element and move it left one base CigarElement ce = cigar.getCigarElement(indexOfIndel-1); elements.add(new CigarElement(ce.getLength()-1, ce.getOperator())); elements.add(cigar.getCigarElement(indexOfIndel)); if ( indexOfIndel+1 < cigar.numCigarElements() ) { ce = cigar.getCigarElement(indexOfIndel+1); elements.add(new CigarElement(ce.getLength()+1, ce.getOperator())); } else { elements.add(new CigarElement(1, CigarOperator.M)); } // get the last few elements for ( int i = indexOfIndel + 2; i < cigar.numCigarElements(); i++) elements.add(cigar.getCigarElement(i)); return new Cigar(elements); } private static byte[] createIndelString(final Cigar cigar, final int indexOfIndel, final byte[] refSeq, final byte[] readSeq, int refIndex, int readIndex) { CigarElement indel = cigar.getCigarElement(indexOfIndel); int indelLength = indel.getLength(); int totalRefBases = 0; for ( int i = 0; i < indexOfIndel; i++ ) { CigarElement ce = cigar.getCigarElement(i); int length = ce.getLength(); switch( ce.getOperator() ) { case M: readIndex += length; refIndex += length; totalRefBases += length; break; case S: readIndex += length; break; case N: refIndex += length; totalRefBases += length; break; default: break; } } // sometimes, when there are very large known indels, we won't have enough reference sequence to cover them if ( totalRefBases + indelLength > refSeq.length ) indelLength -= (totalRefBases + indelLength - refSeq.length); // the indel-based reference string byte[] alt = new byte[refSeq.length + (indelLength * (indel.getOperator() == CigarOperator.D ? -1 : 1))]; // add the bases before the indel, making sure it's not aligned off the end of the reference if ( refIndex > alt.length ) return null; System.arraycopy(refSeq, 0, alt, 0, refIndex); int currentPos = refIndex; // take care of the indel if ( indel.getOperator() == CigarOperator.D ) { refIndex += indelLength; } else { System.arraycopy(readSeq, readIndex, alt, currentPos, indelLength); currentPos += indelLength; } // add the bases after the indel, making sure it's not aligned off the end of the reference if ( refSeq.length - refIndex > alt.length - currentPos ) return null; System.arraycopy(refSeq, refIndex, alt, currentPos, refSeq.length - refIndex); return alt; } }
It never fails to amaze me that aligners can find so many different ways to place indels off the ends of contigs git-svn-id: 4561c0a8f080806b19201efb9525134c00b76d40@5503 348d0f76-0448-11de-a6fe-93d51630548a
java/src/org/broadinstitute/sting/utils/sam/AlignmentUtils.java
It never fails to amaze me that aligners can find so many different ways to place indels off the ends of contigs
<ide><path>ava/src/org/broadinstitute/sting/utils/sam/AlignmentUtils.java <ide> byte[] alt = new byte[refSeq.length + (indelLength * (indel.getOperator() == CigarOperator.D ? -1 : 1))]; <ide> <ide> // add the bases before the indel, making sure it's not aligned off the end of the reference <del> if ( refIndex > alt.length ) <add> if ( refIndex > alt.length || refIndex > refSeq.length ) <ide> return null; <ide> System.arraycopy(refSeq, 0, alt, 0, refIndex); <ide> int currentPos = refIndex;
Java
apache-2.0
9beac7cb585a0d00fecc45ac7db3739798f7e1d0
0
Nethmi-Pathirana/carbon-analytics,grainier/carbon-analytics,wso2/carbon-analytics,mohanvive/carbon-analytics,minudika/carbon-analytics,minudika/carbon-analytics,wso2/carbon-analytics,Anoukh/carbon-analytics,Niveathika92/carbon-analytics,tishan89/carbon-analytics,tishan89/carbon-analytics,Niveathika92/carbon-analytics,wso2/carbon-analytics,tishan89/carbon-analytics,Anoukh/carbon-analytics,grainier/carbon-analytics,mohanvive/carbon-analytics,wso2/carbon-analytics,mohanvive/carbon-analytics,tishan89/carbon-analytics,Nethmi-Pathirana/carbon-analytics,Niveathika92/carbon-analytics,erangatl/carbon-analytics,minudika/carbon-analytics,Anoukh/carbon-analytics,Nethmi-Pathirana/carbon-analytics,Niveathika92/carbon-analytics,grainier/carbon-analytics,Anoukh/carbon-analytics,Anoukh/carbon-analytics,Nethmi-Pathirana/carbon-analytics,mohanvive/carbon-analytics,wso2/carbon-analytics,erangatl/carbon-analytics,grainier/carbon-analytics,mohanvive/carbon-analytics,erangatl/carbon-analytics,minudika/carbon-analytics,Nethmi-Pathirana/carbon-analytics,erangatl/carbon-analytics,Niveathika92/carbon-analytics,erangatl/carbon-analytics,grainier/carbon-analytics,minudika/carbon-analytics,tishan89/carbon-analytics
/* * Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * WSO2 Inc. licenses this file to you under the Apache License, * Version 2.0 (the "License"); you may not use this file except * in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.wso2.carbon.das.jobmanager.core.util; /** * This class contains constants needed for the Topology creation */ public class SiddhiTopologyCreatorConstants { public static final String INNERSTREAM_IDENTIFIER= "#"; public static final String SINK_IDENTIFIER = "@sink"; public static final String SOURCE_IDENTIFIER = "@source"; public static final String PERSISTENCETABLE_IDENTIFIER = "store"; public static final String DEFAULT_SIDDHIAPP_NAME="SiddhiApp"; public static final String DISTRIBUTED_IDENTIFIER="dist"; public static final String PARALLEL_IDENTIFIER ="parallel"; public static final String EXECGROUP_IDENTIFIER ="execGroup"; }
components/org.wso2.carbon.das.jobmanager.core/src/main/java/org/wso2/carbon/das/jobmanager/core/util/SiddhiTopologyCreatorConstants.java
/* * Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * WSO2 Inc. licenses this file to you under the Apache License, * Version 2.0 (the "License"); you may not use this file except * in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.wso2.carbon.das.jobmanager.core.util; /** * This class contains constants needed for the Topology creation */ public class SiddhiTopologyCreatorConstants { public static final String innerStreamIdentifier= "#"; public static final String sinkIdentifier = "@sink"; public static final String sourceIdentifier = "@source"; public static final String persistenceTableIdentifier = "store"; public static final String defaultSiddhiAppName ="SiddhiApp"; public static final String distributedIdentifier ="dist"; public static final String parallelIdentifier ="parallel"; public static final String execGroupIdentifier ="execGroup"; }
formatting constant naming
components/org.wso2.carbon.das.jobmanager.core/src/main/java/org/wso2/carbon/das/jobmanager/core/util/SiddhiTopologyCreatorConstants.java
formatting constant naming
<ide><path>omponents/org.wso2.carbon.das.jobmanager.core/src/main/java/org/wso2/carbon/das/jobmanager/core/util/SiddhiTopologyCreatorConstants.java <ide> * This class contains constants needed for the Topology creation <ide> */ <ide> public class SiddhiTopologyCreatorConstants { <del> public static final String innerStreamIdentifier= "#"; <add> public static final String INNERSTREAM_IDENTIFIER= "#"; <ide> <del> public static final String sinkIdentifier = "@sink"; <add> public static final String SINK_IDENTIFIER = "@sink"; <ide> <del> public static final String sourceIdentifier = "@source"; <add> public static final String SOURCE_IDENTIFIER = "@source"; <ide> <del> public static final String persistenceTableIdentifier = "store"; <add> public static final String PERSISTENCETABLE_IDENTIFIER = "store"; <ide> <del> public static final String defaultSiddhiAppName ="SiddhiApp"; <add> public static final String DEFAULT_SIDDHIAPP_NAME="SiddhiApp"; <ide> <del> public static final String distributedIdentifier ="dist"; <add> public static final String DISTRIBUTED_IDENTIFIER="dist"; <ide> <del> public static final String parallelIdentifier ="parallel"; <add> public static final String PARALLEL_IDENTIFIER ="parallel"; <ide> <del> public static final String execGroupIdentifier ="execGroup"; <add> public static final String EXECGROUP_IDENTIFIER ="execGroup"; <ide> }
Java
bsd-3-clause
58c7ddba6ec571533b895dfd25e83fb03b870e76
0
BayesianLogic/blog,BayesianLogic/blog,BayesianLogic/blog,BayesianLogic/blog,BayesianLogic/blog
package blog.common.numerical; /** * Exposes different matrix libraries to BLOG using a consistent set of * methods. Different libraries may be used with BLOG without significant * code modifications. * * @author awong * @date November 5, 2012 */ public interface MatrixLib { /** * Gives the value of an element of this matrix * * @param x the row index * @param y the column index * @return */ public double elementAt(int x, int y); /** * Sets the value of the given element of this matrix * * @param x the row index * @param y the column index * @param val the value to set mat[x][y] to * @return null */ public void setElement(int x, int y, double val); /** * Returns the contents of this matrix */ public String toString(); /** * Returns number of rows in this matrix */ public int rowLen(); /** * Returns number of columns in this matrix */ public int colLen(); /** * Returns a row of the matrix as specified * * @param i the index of the row */ public MatrixLib sliceRow(int i); /** * Returns the sum of this matrix with the one provided */ public MatrixLib plus(MatrixLib otherMat); /** * Returns the difference of this matrix with the one provided */ public MatrixLib minus(MatrixLib otherMat); /** * Returns the scalar product of this matrix with the given value */ public MatrixLib timesScale(double scale); /** * Returns the matrix product of this matrix with the one provided */ public MatrixLib timesMat(MatrixLib otherMat); /** * Returns the determinant of this matrix */ public double det(); /** * Returns the transpose of this matrix */ public MatrixLib transpose(); /** * Returns the inverse of this matrix */ public MatrixLib inverse(); /** * Returns a lower triangular matrix representing the Cholesky * decomposition of this matrix */ public MatrixLib choleskyFactor(); }
src/blog/common/numerical/MatrixLib.java
package blog.common.numerical; /** * Exposes different matrix libraries to BLOG using a consistent set of * methods. Different libraries may be used with BLOG without significant * code modifications. * * @author awong * @date November 5, 2012 */ public interface MatrixLib { /** * Gives the value of an element of this matrix * * @param x the x-index * @param y the y-index * @return */ public double elementAt(int x, int y); /** * Sets the value of the given element of this matrix * * @param x the x-index * @param y the y-index * @param val the value to set mat[x][y] to * @return null */ public void setElement(int x, int y, double val); /** * Returns the contents of this matrix */ public String toString(); /** * Returns number of rows in this matrix */ public int rowLen(); /** * Returns number of columns in this matrix */ public int colLen(); /** * Returns a row of the matrix as specified * * @param i the index of the row */ public MatrixLib sliceRow(int i); /** * Returns the sum of this matrix with the one provided */ public MatrixLib plus(MatrixLib otherMat); /** * Returns the difference of this matrix with the one provided */ public MatrixLib minus(MatrixLib otherMat); /** * Returns the scalar product of this matrix with the given value */ public MatrixLib timesScale(double scale); /** * Returns the matrix product of this matrix with the one provided */ public MatrixLib timesMat(MatrixLib otherMat); /** * Returns the determinant of this matrix */ public double det(); /** * Returns the transpose of this matrix */ public MatrixLib transpose(); /** * Returns the inverse of this matrix */ public MatrixLib inverse(); /** * Returns a lower triangular matrix representing the Cholesky * decomposition of this matrix */ public MatrixLib choleskyFactor(); }
clarify what coords mean
src/blog/common/numerical/MatrixLib.java
clarify what coords mean
<ide><path>rc/blog/common/numerical/MatrixLib.java <ide> /** <ide> * Gives the value of an element of this matrix <ide> * <del> * @param x the x-index <del> * @param y the y-index <add> * @param x the row index <add> * @param y the column index <ide> * @return <ide> */ <ide> public double elementAt(int x, int y); <ide> /** <ide> * Sets the value of the given element of this matrix <ide> * <del> * @param x the x-index <del> * @param y the y-index <add> * @param x the row index <add> * @param y the column index <ide> * @param val the value to set mat[x][y] to <ide> * @return null <ide> */
JavaScript
mit
627df4657c4fe3d822d3b56b00a6fe3f647e7bbf
0
kopfnicker2008/kopfnicker2008.github.io,kopfnicker2008/kopfnicker2008.github.io
"use strict"; angular.module('myApp.login', ['firebase.utils', 'firebase.auth', 'ngRoute']) .config(['$routeProvider', function($routeProvider) { $routeProvider.when('/login', { controller: 'LoginCtrl', templateUrl: 'login/login.html' }); }]) .controller('LoginCtrl', ['$scope', 'Auth', '$location', 'fbutil', function($scope, Auth, $location, fbutil) { $scope.email = null; $scope.pass = null; $scope.confirm = null; $scope.createMode = false; $scope.login = function(email, pass) { $scope.err = null; //Auth.$authWithOAuthPopup({ email: email, password: pass }, {rememberMe: true}) // .then(function(/* user */) { // //$location.path('/account'); // $location.path('/account'); // }, function(err) { // $scope.err = errMessage(err); // }); var provider = 'google'; var scope = {scope:'email'}; Auth.$authWithOAuthRedirect(provider, scope).then(function (authObject) { $location.path('/account'); }, function (err) { $scope.err = errMessage(err); }); }; $scope.createAccount = function() { $scope.err = null; if( assertValidAccountProps() ) { var email = $scope.email; var pass = $scope.pass; // create user credentials in Firebase auth system Auth.$createUser({email: email, password: pass}) .then(function() { // authenticate so we have permission to write to Firebase return Auth.$authWithPassword({ email: email, password: pass }); }) .then(function(user) { // create a user profile in our data store var ref = fbutil.ref('users', user.uid); return fbutil.handler(function(cb) { ref.set({email: email, name: name||firstPartOfEmail(email)}, cb); }); }) .then(function(/* user */) { // redirect to the account page $location.path('/account'); }, function(err) { $scope.err = errMessage(err); }); } }; function assertValidAccountProps() { if( !$scope.email ) { $scope.err = 'Please enter an email address'; } else if( !$scope.pass || !$scope.confirm ) { $scope.err = 'Please enter a password'; } else if( $scope.createMode && $scope.pass !== $scope.confirm ) { $scope.err = 'Passwords do not match'; } return !$scope.err; } function errMessage(err) { return angular.isObject(err) && err.code? err.code : err + ''; } function firstPartOfEmail(email) { return ucfirst(email.substr(0, email.indexOf('@'))||''); } function ucfirst (str) { // inspired by: http://kevin.vanzonneveld.net str += ''; var f = str.charAt(0).toUpperCase(); return f + str.substr(1); } }]);
app/login/login.js
"use strict"; angular.module('myApp.login', ['firebase.utils', 'firebase.auth', 'ngRoute']) .config(['$routeProvider', function($routeProvider) { $routeProvider.when('/login', { controller: 'LoginCtrl', templateUrl: 'login/login.html' }); }]) .controller('LoginCtrl', ['$scope', 'Auth', '$location', 'fbutil', function($scope, Auth, $location, fbutil) { $scope.email = null; $scope.pass = null; $scope.confirm = null; $scope.createMode = false; $scope.login = function(email, pass) { $scope.err = null; //Auth.$authWithPassword({ email: email, password: pass }, {rememberMe: true}) // .then(function(/* user */) { // //$location.path('/account'); // $location.path('/account'); // }, function(err) { // $scope.err = errMessage(err); // }); Auth.authWithOAuthPopup("google", function(error, authData) { if (error) { console.log("Authentication Failed!", error); } else { console.log("Authenticated successfully with payload:", authData); } }); }; $scope.createAccount = function() { $scope.err = null; if( assertValidAccountProps() ) { var email = $scope.email; var pass = $scope.pass; // create user credentials in Firebase auth system Auth.$createUser({email: email, password: pass}) .then(function() { // authenticate so we have permission to write to Firebase return Auth.$authWithPassword({ email: email, password: pass }); }) .then(function(user) { // create a user profile in our data store var ref = fbutil.ref('users', user.uid); return fbutil.handler(function(cb) { ref.set({email: email, name: name||firstPartOfEmail(email)}, cb); }); }) .then(function(/* user */) { // redirect to the account page $location.path('/account'); }, function(err) { $scope.err = errMessage(err); }); } }; function assertValidAccountProps() { if( !$scope.email ) { $scope.err = 'Please enter an email address'; } else if( !$scope.pass || !$scope.confirm ) { $scope.err = 'Please enter a password'; } else if( $scope.createMode && $scope.pass !== $scope.confirm ) { $scope.err = 'Passwords do not match'; } return !$scope.err; } function errMessage(err) { return angular.isObject(err) && err.code? err.code : err + ''; } function firstPartOfEmail(email) { return ucfirst(email.substr(0, email.indexOf('@'))||''); } function ucfirst (str) { // inspired by: http://kevin.vanzonneveld.net str += ''; var f = str.charAt(0).toUpperCase(); return f + str.substr(1); } }]);
no message
app/login/login.js
no message
<ide><path>pp/login/login.js <ide> <ide> $scope.login = function(email, pass) { <ide> $scope.err = null; <del> //Auth.$authWithPassword({ email: email, password: pass }, {rememberMe: true}) <add> //Auth.$authWithOAuthPopup({ email: email, password: pass }, {rememberMe: true}) <ide> // .then(function(/* user */) { <ide> // //$location.path('/account'); <ide> // $location.path('/account'); <ide> // }, function(err) { <ide> // $scope.err = errMessage(err); <ide> // }); <del> Auth.authWithOAuthPopup("google", function(error, authData) { <del> if (error) { <del> console.log("Authentication Failed!", error); <del> } else { <del> console.log("Authenticated successfully with payload:", authData); <del> } <add> var provider = 'google'; <add> var scope = {scope:'email'}; <add> Auth.$authWithOAuthRedirect(provider, scope).then(function (authObject) { <add> $location.path('/account'); <add> }, function (err) { <add> $scope.err = errMessage(err); <ide> }); <ide> }; <ide>
Java
apache-2.0
941f7c2ae6b79904a632493d098a0110ef87c05f
0
linqs/psl,linqs/psl,linqs/psl
/* * This file is part of the PSL software. * Copyright 2011-2015 University of Maryland * Copyright 2013-2018 The Regents of the University of California * * 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.linqs.psl.evaluation.statistics; import org.linqs.psl.application.learning.weight.TrainingMap; import org.linqs.psl.config.Config; import org.linqs.psl.model.atom.GroundAtom; import org.linqs.psl.model.atom.ObservedAtom; import org.linqs.psl.model.predicate.StandardPredicate; import org.linqs.psl.model.term.Constant; import org.linqs.psl.util.StringUtils; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; /** * Compute various statistics on data known to be categorical. * * Categorical atoms are normal atoms that are interpreted to have two parts: the base and the category. * Ex: HasOS(x, 'Linux'), HasOS(x, 'BSD'), HasOS(x, 'Mac'), ... * Both the base and category can consist of more than one variable. * Ex: HasClimate(location, time, 'Cold', 'Rain'), HasClimate(location, time, 'Cold', 'Snow'), ... * However, each atom can only have one category. * Any arguments not in a category will be considered to be in the base. * * The best (highest truth value) category for each base will be chosen. * Then the truth database will be iterated over for atoms with a 1.0 truth value. * If the truth atom was chosen as the best category in the predicted data, then that is a hit. * Anything else is a miss. */ public class CategoricalEvaluator extends Evaluator { public enum RepresentativeMetric { ACCURACY } public static final String DELIM = ":"; /** * Prefix of property keys used by this class. */ public static final String CONFIG_PREFIX = "categoricalevaluator"; /** * The index of the arguments in the predicate (delimited by colons). * The other arguments are treated as identifiers. * Zero-indexed. */ public static final String CATEGORY_INDEXES_KEY = CONFIG_PREFIX + ".categoryindexes"; public static final String DEFAULT_CATEGORY_INDEXES = "1"; /** * The representative metric. * Default to accuracy. * Must match a string from the RepresentativeMetric enum. */ public static final String REPRESENTATIVE_KEY = CONFIG_PREFIX + ".representative"; public static final String DEFAULT_REPRESENTATIVE = "ACCURACY"; /** * The default predicate to use when none are supplied. */ public static final String DEFAULT_PREDICATE_KEY = CONFIG_PREFIX + ".defaultpredicate"; private Set<Integer> categoryIndexes; private RepresentativeMetric representative; private String defaultPredicate; private int hits; private int misses; public CategoricalEvaluator() { this(RepresentativeMetric.valueOf(Config.getString(REPRESENTATIVE_KEY, DEFAULT_REPRESENTATIVE)), StringUtils.splitInt(Config.getString(CATEGORY_INDEXES_KEY, DEFAULT_CATEGORY_INDEXES), DELIM)); } public CategoricalEvaluator(int... rawCategoryIndexes) { this(DEFAULT_REPRESENTATIVE, rawCategoryIndexes); } public CategoricalEvaluator(String representative, int... rawCategoryIndexes) { this(RepresentativeMetric.valueOf(representative.toUpperCase()), rawCategoryIndexes); } public CategoricalEvaluator(RepresentativeMetric representative, int... rawCategoryIndexes) { this.representative = representative; setCategoryIndexes(rawCategoryIndexes); defaultPredicate = Config.getString(DEFAULT_PREDICATE_KEY, null); hits = 0; misses = 0; } public void setCategoryIndexes(int... rawCategoryIndexes) { if (rawCategoryIndexes == null || rawCategoryIndexes.length == 0) { throw new IllegalArgumentException("Found no category indexes."); } categoryIndexes = new HashSet<Integer>(rawCategoryIndexes.length); for (int catIndex : rawCategoryIndexes) { if (catIndex < 0) { throw new IllegalArgumentException("Category indexes must be non-negative. Found: " + catIndex); } categoryIndexes.add(new Integer(catIndex)); } } @Override public void compute(TrainingMap trainingMap) { if (defaultPredicate == null) { throw new UnsupportedOperationException("CategoricalEvaluators must have a default predicate set (through config)."); } compute(trainingMap, StandardPredicate.get(defaultPredicate)); } @Override public void compute(TrainingMap trainingMap, StandardPredicate predicate) { hits = 0; misses = 0; Set<GroundAtom> predictedCategories = getPredictedCategories(trainingMap, predicate); for (GroundAtom truthAtom : trainingMap.getTruthAtoms()) { if (predicate != null && truthAtom.getPredicate() != predicate) { continue; } if (truthAtom.getValue() < 1.0) { continue; } if (predictedCategories.contains(truthAtom)) { hits++; } else { misses++; } } } @Override public double getRepresentativeMetric() { switch (representative) { case ACCURACY: return accuracy(); default: throw new IllegalStateException("Unknown representative metric: " + representative); } } @Override public boolean isHigherRepresentativeBetter() { return true; } public double accuracy() { if (hits + misses == 0) { return 0.0; } return hits / (double)(hits + misses); } @Override public String getAllStats() { return String.format("Categorical Accuracy: %f", accuracy()); } /** * Build up a set that has all the atoms that represet the best categorical assignments. */ private Set<GroundAtom> getPredictedCategories(TrainingMap trainingMap, StandardPredicate predicate) { int numArgs = predicate.getArity(); // This map will be as deep as the number of category arguments. // The value will either be a GroundAtom representing the current best category, // or another Map<Constant, Object>, and so on. Map<Constant, Object> predictedCategories = null; for (GroundAtom atom : trainingMap.getTargetAtoms()) { if (atom.getPredicate() != predicate) { continue; } @SuppressWarnings("unchecked") Map<Constant, Object> ignoreWarning = (Map<Constant, Object>)putPredictedCategories(predictedCategories, atom, 0); predictedCategories = ignoreWarning; } Set<GroundAtom> rtn = new HashSet<GroundAtom>(); collectPredictedCategories(predictedCategories, rtn); return rtn; } /** * Recursively descend into the map and put the atom in if it is a best category. * Return what should be at the map where we descended (classic tree building style). */ private Object putPredictedCategories(Object currentNode, GroundAtom atom, int argIndex) { assert(argIndex <= atom.getArity()); // Skip this arg if it is a category. if (categoryIndexes.contains(argIndex)) { return putPredictedCategories(currentNode, atom, argIndex + 1); } // If we have coverd all the arguments, then we are either looking at a null // if there was no previous best or the previous best. if (argIndex == atom.getArity()) { if (currentNode == null) { return atom; } @SuppressWarnings("unchecked") GroundAtom oldBest = (GroundAtom)currentNode; if (atom.getValue() > oldBest.getValue()) { return atom; } else { return oldBest; } } // We still have further to descend. Map<Constant, Object> predictedCategories; if (currentNode == null) { predictedCategories = new HashMap<Constant, Object>(); } else { @SuppressWarnings("unchecked") Map<Constant, Object> ignoreWarning = (Map<Constant, Object>)currentNode; predictedCategories = ignoreWarning; } Constant arg = atom.getArguments()[argIndex]; predictedCategories.put(arg, putPredictedCategories(predictedCategories.get(arg), atom, argIndex + 1)); return predictedCategories; } private void collectPredictedCategories(Map<Constant, Object> predictedCategories, Set<GroundAtom> result) { for (Object value : predictedCategories.values()) { if (value instanceof GroundAtom) { result.add((GroundAtom)value); } else { @SuppressWarnings("unchecked") Map<Constant, Object> ignoreWarning = (Map<Constant, Object>)value; collectPredictedCategories(ignoreWarning, result); } } } }
psl-core/src/main/java/org/linqs/psl/evaluation/statistics/CategoricalEvaluator.java
/* * This file is part of the PSL software. * Copyright 2011-2015 University of Maryland * Copyright 2013-2018 The Regents of the University of California * * 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.linqs.psl.evaluation.statistics; import org.linqs.psl.application.learning.weight.TrainingMap; import org.linqs.psl.config.Config; import org.linqs.psl.model.atom.GroundAtom; import org.linqs.psl.model.atom.ObservedAtom; import org.linqs.psl.model.predicate.StandardPredicate; import org.linqs.psl.model.term.Constant; import org.linqs.psl.util.StringUtils; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; /** * Compute various statistics on data known to be categorical. * * Categorical atoms are normal atoms that are interpreted to have two parts: the base and the category. * Ex: HasOS(x, 'Linux'), HasOS(x, 'BSD'), HasOS(x, 'Mac'), ... * Both the base and category can consist of more than one variable. * Ex: HasClimate(location, time, 'Cold', 'Rain'), HasClimate(location, time, 'Cold', 'Snow'), ... * However, each atom can only have one category. * Any arguments not in a category will be considered to be in the base. * * The best (highest truth value) category for each base will be chosen. * Then the truth database will be iterated over for atoms with a 1.0 truth value. * If the truth atom was chosen as the best category in the predicted data, then that is a hit. * Anything else is a miss. */ public class CategoricalEvaluator extends Evaluator { public enum RepresentativeMetric { ACCURACY } public static final String DELIM = ":"; /** * Prefix of property keys used by this class. */ public static final String CONFIG_PREFIX = "categoricalevaluator"; /** * The index of the arguments in the predicate (delimited by colons). */ public static final String CATEGORY_INDEXES_KEY = CONFIG_PREFIX + ".categoryindexes"; public static final String DEFAULT_CATEGORY_INDEXES = "1"; /** * The representative metric. * Default to accuracy. * Must match a string from the RepresentativeMetric enum. */ public static final String REPRESENTATIVE_KEY = CONFIG_PREFIX + ".representative"; public static final String DEFAULT_REPRESENTATIVE = "ACCURACY"; /** * The default predicate to use when none are supplied. */ public static final String DEFAULT_PREDICATE_KEY = CONFIG_PREFIX + ".defaultpredicate"; private Set<Integer> categoryIndexes; private RepresentativeMetric representative; private String defaultPredicate; private int hits; private int misses; public CategoricalEvaluator() { this(RepresentativeMetric.valueOf(Config.getString(REPRESENTATIVE_KEY, DEFAULT_REPRESENTATIVE)), StringUtils.splitInt(Config.getString(CATEGORY_INDEXES_KEY, DEFAULT_CATEGORY_INDEXES), DELIM)); } public CategoricalEvaluator(int... rawCategoryIndexes) { this(DEFAULT_REPRESENTATIVE, rawCategoryIndexes); } public CategoricalEvaluator(String representative, int... rawCategoryIndexes) { this(RepresentativeMetric.valueOf(representative.toUpperCase()), rawCategoryIndexes); } public CategoricalEvaluator(RepresentativeMetric representative, int... rawCategoryIndexes) { this.representative = representative; setCategoryIndexes(rawCategoryIndexes); defaultPredicate = Config.getString(DEFAULT_PREDICATE_KEY, null); hits = 0; misses = 0; } public void setCategoryIndexes(int... rawCategoryIndexes) { if (rawCategoryIndexes == null || rawCategoryIndexes.length == 0) { throw new IllegalArgumentException("Found no category indexes."); } categoryIndexes = new HashSet<Integer>(rawCategoryIndexes.length); for (int catIndex : rawCategoryIndexes) { if (catIndex < 0) { throw new IllegalArgumentException("Category indexes must be non-negative. Found: " + catIndex); } categoryIndexes.add(new Integer(catIndex)); } } @Override public void compute(TrainingMap trainingMap) { if (defaultPredicate == null) { throw new UnsupportedOperationException("CategoricalEvaluators must have a default predicate set (through config)."); } compute(trainingMap, StandardPredicate.get(defaultPredicate)); } @Override public void compute(TrainingMap trainingMap, StandardPredicate predicate) { hits = 0; misses = 0; Set<GroundAtom> predictedCategories = getPredictedCategories(trainingMap, predicate); for (GroundAtom truthAtom : trainingMap.getTruthAtoms()) { if (predicate != null && truthAtom.getPredicate() != predicate) { continue; } if (truthAtom.getValue() < 1.0) { continue; } if (predictedCategories.contains(truthAtom)) { hits++; } else { misses++; } } } @Override public double getRepresentativeMetric() { switch (representative) { case ACCURACY: return accuracy(); default: throw new IllegalStateException("Unknown representative metric: " + representative); } } @Override public boolean isHigherRepresentativeBetter() { return true; } public double accuracy() { if (hits + misses == 0) { return 0.0; } return hits / (double)(hits + misses); } @Override public String getAllStats() { return String.format("Categorical Accuracy: %f", accuracy()); } /** * Build up a set that has all the atoms that represet the best categorical assignments. */ private Set<GroundAtom> getPredictedCategories(TrainingMap trainingMap, StandardPredicate predicate) { int numArgs = predicate.getArity(); // This map will be as deep as the number of category arguments. // The value will either be a GroundAtom representing the current best category, // or another Map<Constant, Object>, and so on. Map<Constant, Object> predictedCategories = null; for (GroundAtom atom : trainingMap.getTargetAtoms()) { if (atom.getPredicate() != predicate) { continue; } @SuppressWarnings("unchecked") Map<Constant, Object> ignoreWarning = (Map<Constant, Object>)putPredictedCategories(predictedCategories, atom, 0); predictedCategories = ignoreWarning; } Set<GroundAtom> rtn = new HashSet<GroundAtom>(); collectPredictedCategories(predictedCategories, rtn); return rtn; } /** * Recursively descend into the map and put the atom in if it is a best category. * Return what should be at the map where we descended (classic tree building style). */ private Object putPredictedCategories(Object currentNode, GroundAtom atom, int argIndex) { assert(argIndex <= atom.getArity()); // Skip this arg if it is a category. if (categoryIndexes.contains(argIndex)) { return putPredictedCategories(currentNode, atom, argIndex + 1); } // If we have coverd all the arguments, then we are either looking at a null // if there was no previous best or the previous best. if (argIndex == atom.getArity()) { if (currentNode == null) { return atom; } @SuppressWarnings("unchecked") GroundAtom oldBest = (GroundAtom)currentNode; if (atom.getValue() > oldBest.getValue()) { return atom; } else { return oldBest; } } // We still have further to descend. Map<Constant, Object> predictedCategories; if (currentNode == null) { predictedCategories = new HashMap<Constant, Object>(); } else { @SuppressWarnings("unchecked") Map<Constant, Object> ignoreWarning = (Map<Constant, Object>)currentNode; predictedCategories = ignoreWarning; } Constant arg = atom.getArguments()[argIndex]; predictedCategories.put(arg, putPredictedCategories(predictedCategories.get(arg), atom, argIndex + 1)); return predictedCategories; } private void collectPredictedCategories(Map<Constant, Object> predictedCategories, Set<GroundAtom> result) { for (Object value : predictedCategories.values()) { if (value instanceof GroundAtom) { result.add((GroundAtom)value); } else { @SuppressWarnings("unchecked") Map<Constant, Object> ignoreWarning = (Map<Constant, Object>)value; collectPredictedCategories(ignoreWarning, result); } } } }
Expanded a comment.
psl-core/src/main/java/org/linqs/psl/evaluation/statistics/CategoricalEvaluator.java
Expanded a comment.
<ide><path>sl-core/src/main/java/org/linqs/psl/evaluation/statistics/CategoricalEvaluator.java <ide> <ide> /** <ide> * The index of the arguments in the predicate (delimited by colons). <add> * The other arguments are treated as identifiers. <add> * Zero-indexed. <ide> */ <ide> public static final String CATEGORY_INDEXES_KEY = CONFIG_PREFIX + ".categoryindexes"; <ide> public static final String DEFAULT_CATEGORY_INDEXES = "1";
Java
apache-2.0
c7fb83dd47cd4c19acd890238087ee5fdd4362e9
0
alphafoobar/intellij-community,da1z/intellij-community,fengbaicanhe/intellij-community,lucafavatella/intellij-community,samthor/intellij-community,ryano144/intellij-community,youdonghai/intellij-community,adedayo/intellij-community,SerCeMan/intellij-community,MichaelNedzelsky/intellij-community,fnouama/intellij-community,supersven/intellij-community,petteyg/intellij-community,fengbaicanhe/intellij-community,allotria/intellij-community,diorcety/intellij-community,ryano144/intellij-community,pwoodworth/intellij-community,MER-GROUP/intellij-community,semonte/intellij-community,wreckJ/intellij-community,slisson/intellij-community,lucafavatella/intellij-community,amith01994/intellij-community,akosyakov/intellij-community,vladmm/intellij-community,blademainer/intellij-community,vladmm/intellij-community,orekyuu/intellij-community,TangHao1987/intellij-community,Distrotech/intellij-community,slisson/intellij-community,wreckJ/intellij-community,ahb0327/intellij-community,retomerz/intellij-community,amith01994/intellij-community,TangHao1987/intellij-community,petteyg/intellij-community,signed/intellij-community,apixandru/intellij-community,suncycheng/intellij-community,mglukhikh/intellij-community,clumsy/intellij-community,ftomassetti/intellij-community,ahb0327/intellij-community,MichaelNedzelsky/intellij-community,pwoodworth/intellij-community,ThiagoGarciaAlves/intellij-community,akosyakov/intellij-community,suncycheng/intellij-community,akosyakov/intellij-community,kool79/intellij-community,michaelgallacher/intellij-community,alphafoobar/intellij-community,ibinti/intellij-community,gnuhub/intellij-community,youdonghai/intellij-community,idea4bsd/idea4bsd,holmes/intellij-community,vladmm/intellij-community,Distrotech/intellij-community,robovm/robovm-studio,xfournet/intellij-community,kdwink/intellij-community,orekyuu/intellij-community,holmes/intellij-community,blademainer/intellij-community,kool79/intellij-community,retomerz/intellij-community,tmpgit/intellij-community,jagguli/intellij-community,Distrotech/intellij-community,caot/intellij-community,ahb0327/intellij-community,semonte/intellij-community,samthor/intellij-community,adedayo/intellij-community,SerCeMan/intellij-community,ivan-fedorov/intellij-community,diorcety/intellij-community,lucafavatella/intellij-community,retomerz/intellij-community,adedayo/intellij-community,ftomassetti/intellij-community,nicolargo/intellij-community,nicolargo/intellij-community,youdonghai/intellij-community,da1z/intellij-community,fitermay/intellij-community,lucafavatella/intellij-community,SerCeMan/intellij-community,kool79/intellij-community,ibinti/intellij-community,slisson/intellij-community,vvv1559/intellij-community,alphafoobar/intellij-community,FHannes/intellij-community,salguarnieri/intellij-community,kdwink/intellij-community,SerCeMan/intellij-community,tmpgit/intellij-community,apixandru/intellij-community,asedunov/intellij-community,samthor/intellij-community,gnuhub/intellij-community,ftomassetti/intellij-community,fengbaicanhe/intellij-community,alphafoobar/intellij-community,youdonghai/intellij-community,samthor/intellij-community,michaelgallacher/intellij-community,amith01994/intellij-community,blademainer/intellij-community,slisson/intellij-community,apixandru/intellij-community,idea4bsd/idea4bsd,orekyuu/intellij-community,supersven/intellij-community,apixandru/intellij-community,caot/intellij-community,ftomassetti/intellij-community,muntasirsyed/intellij-community,allotria/intellij-community,orekyuu/intellij-community,alphafoobar/intellij-community,MichaelNedzelsky/intellij-community,MER-GROUP/intellij-community,semonte/intellij-community,FHannes/intellij-community,adedayo/intellij-community,gnuhub/intellij-community,hurricup/intellij-community,signed/intellij-community,wreckJ/intellij-community,caot/intellij-community,samthor/intellij-community,vvv1559/intellij-community,allotria/intellij-community,alphafoobar/intellij-community,dslomov/intellij-community,caot/intellij-community,MichaelNedzelsky/intellij-community,MER-GROUP/intellij-community,akosyakov/intellij-community,nicolargo/intellij-community,dslomov/intellij-community,blademainer/intellij-community,tmpgit/intellij-community,pwoodworth/intellij-community,ryano144/intellij-community,FHannes/intellij-community,michaelgallacher/intellij-community,slisson/intellij-community,muntasirsyed/intellij-community,ol-loginov/intellij-community,michaelgallacher/intellij-community,samthor/intellij-community,MER-GROUP/intellij-community,salguarnieri/intellij-community,da1z/intellij-community,Distrotech/intellij-community,robovm/robovm-studio,idea4bsd/idea4bsd,vladmm/intellij-community,da1z/intellij-community,hurricup/intellij-community,xfournet/intellij-community,dslomov/intellij-community,holmes/intellij-community,pwoodworth/intellij-community,vvv1559/intellij-community,clumsy/intellij-community,MER-GROUP/intellij-community,vvv1559/intellij-community,allotria/intellij-community,MichaelNedzelsky/intellij-community,retomerz/intellij-community,hurricup/intellij-community,TangHao1987/intellij-community,idea4bsd/idea4bsd,supersven/intellij-community,ol-loginov/intellij-community,jagguli/intellij-community,youdonghai/intellij-community,clumsy/intellij-community,ivan-fedorov/intellij-community,adedayo/intellij-community,jagguli/intellij-community,MER-GROUP/intellij-community,petteyg/intellij-community,Distrotech/intellij-community,vvv1559/intellij-community,clumsy/intellij-community,allotria/intellij-community,ryano144/intellij-community,MER-GROUP/intellij-community,SerCeMan/intellij-community,alphafoobar/intellij-community,lucafavatella/intellij-community,kool79/intellij-community,ftomassetti/intellij-community,salguarnieri/intellij-community,vladmm/intellij-community,fnouama/intellij-community,mglukhikh/intellij-community,holmes/intellij-community,mglukhikh/intellij-community,retomerz/intellij-community,ryano144/intellij-community,vvv1559/intellij-community,Lekanich/intellij-community,ahb0327/intellij-community,hurricup/intellij-community,FHannes/intellij-community,fnouama/intellij-community,slisson/intellij-community,nicolargo/intellij-community,pwoodworth/intellij-community,signed/intellij-community,jagguli/intellij-community,da1z/intellij-community,clumsy/intellij-community,allotria/intellij-community,orekyuu/intellij-community,muntasirsyed/intellij-community,ahb0327/intellij-community,kdwink/intellij-community,asedunov/intellij-community,slisson/intellij-community,ol-loginov/intellij-community,akosyakov/intellij-community,petteyg/intellij-community,apixandru/intellij-community,diorcety/intellij-community,FHannes/intellij-community,tmpgit/intellij-community,ibinti/intellij-community,vladmm/intellij-community,akosyakov/intellij-community,da1z/intellij-community,holmes/intellij-community,michaelgallacher/intellij-community,amith01994/intellij-community,caot/intellij-community,salguarnieri/intellij-community,Distrotech/intellij-community,Lekanich/intellij-community,allotria/intellij-community,xfournet/intellij-community,Distrotech/intellij-community,xfournet/intellij-community,semonte/intellij-community,salguarnieri/intellij-community,mglukhikh/intellij-community,caot/intellij-community,asedunov/intellij-community,diorcety/intellij-community,mglukhikh/intellij-community,Lekanich/intellij-community,MER-GROUP/intellij-community,fnouama/intellij-community,fitermay/intellij-community,adedayo/intellij-community,fengbaicanhe/intellij-community,caot/intellij-community,fitermay/intellij-community,MichaelNedzelsky/intellij-community,ftomassetti/intellij-community,Distrotech/intellij-community,idea4bsd/idea4bsd,izonder/intellij-community,dslomov/intellij-community,orekyuu/intellij-community,adedayo/intellij-community,robovm/robovm-studio,MichaelNedzelsky/intellij-community,semonte/intellij-community,holmes/intellij-community,mglukhikh/intellij-community,ryano144/intellij-community,blademainer/intellij-community,vvv1559/intellij-community,Lekanich/intellij-community,dslomov/intellij-community,idea4bsd/idea4bsd,muntasirsyed/intellij-community,salguarnieri/intellij-community,gnuhub/intellij-community,kool79/intellij-community,michaelgallacher/intellij-community,blademainer/intellij-community,hurricup/intellij-community,hurricup/intellij-community,mglukhikh/intellij-community,alphafoobar/intellij-community,clumsy/intellij-community,orekyuu/intellij-community,dslomov/intellij-community,ryano144/intellij-community,signed/intellij-community,vladmm/intellij-community,vladmm/intellij-community,tmpgit/intellij-community,ivan-fedorov/intellij-community,gnuhub/intellij-community,robovm/robovm-studio,wreckJ/intellij-community,ThiagoGarciaAlves/intellij-community,youdonghai/intellij-community,apixandru/intellij-community,apixandru/intellij-community,kool79/intellij-community,ibinti/intellij-community,gnuhub/intellij-community,apixandru/intellij-community,ivan-fedorov/intellij-community,Distrotech/intellij-community,ThiagoGarciaAlves/intellij-community,ivan-fedorov/intellij-community,nicolargo/intellij-community,petteyg/intellij-community,gnuhub/intellij-community,holmes/intellij-community,fnouama/intellij-community,pwoodworth/intellij-community,salguarnieri/intellij-community,adedayo/intellij-community,michaelgallacher/intellij-community,gnuhub/intellij-community,SerCeMan/intellij-community,jagguli/intellij-community,SerCeMan/intellij-community,fitermay/intellij-community,suncycheng/intellij-community,FHannes/intellij-community,slisson/intellij-community,akosyakov/intellij-community,robovm/robovm-studio,vladmm/intellij-community,ThiagoGarciaAlves/intellij-community,amith01994/intellij-community,holmes/intellij-community,dslomov/intellij-community,kdwink/intellij-community,gnuhub/intellij-community,hurricup/intellij-community,caot/intellij-community,kool79/intellij-community,petteyg/intellij-community,akosyakov/intellij-community,orekyuu/intellij-community,ivan-fedorov/intellij-community,kool79/intellij-community,TangHao1987/intellij-community,muntasirsyed/intellij-community,ryano144/intellij-community,fengbaicanhe/intellij-community,muntasirsyed/intellij-community,izonder/intellij-community,alphafoobar/intellij-community,suncycheng/intellij-community,gnuhub/intellij-community,adedayo/intellij-community,Lekanich/intellij-community,vvv1559/intellij-community,lucafavatella/intellij-community,clumsy/intellij-community,asedunov/intellij-community,ol-loginov/intellij-community,retomerz/intellij-community,michaelgallacher/intellij-community,salguarnieri/intellij-community,ol-loginov/intellij-community,asedunov/intellij-community,allotria/intellij-community,signed/intellij-community,ThiagoGarciaAlves/intellij-community,supersven/intellij-community,amith01994/intellij-community,fengbaicanhe/intellij-community,vladmm/intellij-community,tmpgit/intellij-community,asedunov/intellij-community,fengbaicanhe/intellij-community,blademainer/intellij-community,mglukhikh/intellij-community,mglukhikh/intellij-community,fitermay/intellij-community,retomerz/intellij-community,youdonghai/intellij-community,pwoodworth/intellij-community,ol-loginov/intellij-community,muntasirsyed/intellij-community,Lekanich/intellij-community,youdonghai/intellij-community,lucafavatella/intellij-community,idea4bsd/idea4bsd,ol-loginov/intellij-community,allotria/intellij-community,ftomassetti/intellij-community,salguarnieri/intellij-community,robovm/robovm-studio,Lekanich/intellij-community,diorcety/intellij-community,xfournet/intellij-community,holmes/intellij-community,pwoodworth/intellij-community,fnouama/intellij-community,TangHao1987/intellij-community,izonder/intellij-community,xfournet/intellij-community,Lekanich/intellij-community,lucafavatella/intellij-community,holmes/intellij-community,FHannes/intellij-community,MichaelNedzelsky/intellij-community,ivan-fedorov/intellij-community,TangHao1987/intellij-community,adedayo/intellij-community,ol-loginov/intellij-community,jagguli/intellij-community,mglukhikh/intellij-community,FHannes/intellij-community,akosyakov/intellij-community,caot/intellij-community,fnouama/intellij-community,da1z/intellij-community,allotria/intellij-community,suncycheng/intellij-community,izonder/intellij-community,samthor/intellij-community,mglukhikh/intellij-community,semonte/intellij-community,retomerz/intellij-community,SerCeMan/intellij-community,fengbaicanhe/intellij-community,Lekanich/intellij-community,xfournet/intellij-community,retomerz/intellij-community,kdwink/intellij-community,vvv1559/intellij-community,asedunov/intellij-community,apixandru/intellij-community,jagguli/intellij-community,samthor/intellij-community,holmes/intellij-community,tmpgit/intellij-community,ibinti/intellij-community,wreckJ/intellij-community,fnouama/intellij-community,supersven/intellij-community,mglukhikh/intellij-community,mglukhikh/intellij-community,da1z/intellij-community,TangHao1987/intellij-community,muntasirsyed/intellij-community,hurricup/intellij-community,adedayo/intellij-community,youdonghai/intellij-community,izonder/intellij-community,tmpgit/intellij-community,petteyg/intellij-community,tmpgit/intellij-community,amith01994/intellij-community,apixandru/intellij-community,suncycheng/intellij-community,samthor/intellij-community,blademainer/intellij-community,izonder/intellij-community,tmpgit/intellij-community,clumsy/intellij-community,akosyakov/intellij-community,amith01994/intellij-community,ol-loginov/intellij-community,signed/intellij-community,FHannes/intellij-community,holmes/intellij-community,muntasirsyed/intellij-community,semonte/intellij-community,salguarnieri/intellij-community,lucafavatella/intellij-community,kdwink/intellij-community,izonder/intellij-community,apixandru/intellij-community,blademainer/intellij-community,MichaelNedzelsky/intellij-community,kool79/intellij-community,nicolargo/intellij-community,semonte/intellij-community,TangHao1987/intellij-community,clumsy/intellij-community,dslomov/intellij-community,slisson/intellij-community,ivan-fedorov/intellij-community,hurricup/intellij-community,ftomassetti/intellij-community,ftomassetti/intellij-community,slisson/intellij-community,ol-loginov/intellij-community,lucafavatella/intellij-community,ol-loginov/intellij-community,ryano144/intellij-community,supersven/intellij-community,ThiagoGarciaAlves/intellij-community,jagguli/intellij-community,TangHao1987/intellij-community,ahb0327/intellij-community,fengbaicanhe/intellij-community,muntasirsyed/intellij-community,petteyg/intellij-community,wreckJ/intellij-community,xfournet/intellij-community,michaelgallacher/intellij-community,clumsy/intellij-community,tmpgit/intellij-community,Distrotech/intellij-community,ibinti/intellij-community,orekyuu/intellij-community,dslomov/intellij-community,fitermay/intellij-community,salguarnieri/intellij-community,MichaelNedzelsky/intellij-community,ThiagoGarciaAlves/intellij-community,supersven/intellij-community,vvv1559/intellij-community,ivan-fedorov/intellij-community,suncycheng/intellij-community,hurricup/intellij-community,ryano144/intellij-community,nicolargo/intellij-community,asedunov/intellij-community,clumsy/intellij-community,FHannes/intellij-community,nicolargo/intellij-community,fitermay/intellij-community,fnouama/intellij-community,kdwink/intellij-community,Lekanich/intellij-community,pwoodworth/intellij-community,asedunov/intellij-community,diorcety/intellij-community,semonte/intellij-community,idea4bsd/idea4bsd,fengbaicanhe/intellij-community,tmpgit/intellij-community,signed/intellij-community,lucafavatella/intellij-community,clumsy/intellij-community,ThiagoGarciaAlves/intellij-community,ivan-fedorov/intellij-community,ahb0327/intellij-community,ahb0327/intellij-community,fitermay/intellij-community,petteyg/intellij-community,signed/intellij-community,lucafavatella/intellij-community,nicolargo/intellij-community,kdwink/intellij-community,MichaelNedzelsky/intellij-community,suncycheng/intellij-community,vladmm/intellij-community,muntasirsyed/intellij-community,lucafavatella/intellij-community,retomerz/intellij-community,robovm/robovm-studio,kdwink/intellij-community,kdwink/intellij-community,retomerz/intellij-community,TangHao1987/intellij-community,suncycheng/intellij-community,idea4bsd/idea4bsd,xfournet/intellij-community,izonder/intellij-community,MER-GROUP/intellij-community,retomerz/intellij-community,fnouama/intellij-community,amith01994/intellij-community,petteyg/intellij-community,youdonghai/intellij-community,idea4bsd/idea4bsd,petteyg/intellij-community,orekyuu/intellij-community,ThiagoGarciaAlves/intellij-community,ThiagoGarciaAlves/intellij-community,ibinti/intellij-community,SerCeMan/intellij-community,pwoodworth/intellij-community,supersven/intellij-community,wreckJ/intellij-community,ahb0327/intellij-community,fitermay/intellij-community,fitermay/intellij-community,apixandru/intellij-community,vvv1559/intellij-community,izonder/intellij-community,fnouama/intellij-community,ibinti/intellij-community,asedunov/intellij-community,ThiagoGarciaAlves/intellij-community,signed/intellij-community,nicolargo/intellij-community,xfournet/intellij-community,nicolargo/intellij-community,signed/intellij-community,pwoodworth/intellij-community,semonte/intellij-community,kool79/intellij-community,robovm/robovm-studio,TangHao1987/intellij-community,ryano144/intellij-community,ibinti/intellij-community,FHannes/intellij-community,alphafoobar/intellij-community,fengbaicanhe/intellij-community,nicolargo/intellij-community,ivan-fedorov/intellij-community,supersven/intellij-community,asedunov/intellij-community,wreckJ/intellij-community,allotria/intellij-community,diorcety/intellij-community,wreckJ/intellij-community,hurricup/intellij-community,idea4bsd/idea4bsd,blademainer/intellij-community,blademainer/intellij-community,youdonghai/intellij-community,supersven/intellij-community,da1z/intellij-community,gnuhub/intellij-community,ftomassetti/intellij-community,vvv1559/intellij-community,MER-GROUP/intellij-community,kdwink/intellij-community,diorcety/intellij-community,izonder/intellij-community,amith01994/intellij-community,signed/intellij-community,xfournet/intellij-community,robovm/robovm-studio,amith01994/intellij-community,signed/intellij-community,slisson/intellij-community,allotria/intellij-community,ftomassetti/intellij-community,SerCeMan/intellij-community,slisson/intellij-community,samthor/intellij-community,da1z/intellij-community,Lekanich/intellij-community,semonte/intellij-community,MER-GROUP/intellij-community,FHannes/intellij-community,suncycheng/intellij-community,ol-loginov/intellij-community,diorcety/intellij-community,Distrotech/intellij-community,fitermay/intellij-community,kdwink/intellij-community,da1z/intellij-community,wreckJ/intellij-community,dslomov/intellij-community,diorcety/intellij-community,blademainer/intellij-community,fitermay/intellij-community,salguarnieri/intellij-community,robovm/robovm-studio,suncycheng/intellij-community,kool79/intellij-community,apixandru/intellij-community,supersven/intellij-community,semonte/intellij-community,asedunov/intellij-community,michaelgallacher/intellij-community,adedayo/intellij-community,SerCeMan/intellij-community,Lekanich/intellij-community,diorcety/intellij-community,caot/intellij-community,izonder/intellij-community,supersven/intellij-community,TangHao1987/intellij-community,petteyg/intellij-community,samthor/intellij-community,apixandru/intellij-community,da1z/intellij-community,jagguli/intellij-community,wreckJ/intellij-community,fnouama/intellij-community,vladmm/intellij-community,allotria/intellij-community,ahb0327/intellij-community,vvv1559/intellij-community,fitermay/intellij-community,ThiagoGarciaAlves/intellij-community,hurricup/intellij-community,ryano144/intellij-community,alphafoobar/intellij-community,da1z/intellij-community,amith01994/intellij-community,retomerz/intellij-community,jagguli/intellij-community,dslomov/intellij-community,youdonghai/intellij-community,xfournet/intellij-community,hurricup/intellij-community,ibinti/intellij-community,youdonghai/intellij-community,samthor/intellij-community,signed/intellij-community,robovm/robovm-studio,idea4bsd/idea4bsd,jagguli/intellij-community,robovm/robovm-studio,semonte/intellij-community,ahb0327/intellij-community,ftomassetti/intellij-community,muntasirsyed/intellij-community,izonder/intellij-community,caot/intellij-community,suncycheng/intellij-community,jagguli/intellij-community,wreckJ/intellij-community,orekyuu/intellij-community,gnuhub/intellij-community,michaelgallacher/intellij-community,asedunov/intellij-community,ivan-fedorov/intellij-community,ibinti/intellij-community,diorcety/intellij-community,MichaelNedzelsky/intellij-community,MER-GROUP/intellij-community,fengbaicanhe/intellij-community,Distrotech/intellij-community,dslomov/intellij-community,akosyakov/intellij-community,akosyakov/intellij-community,pwoodworth/intellij-community,orekyuu/intellij-community,ibinti/intellij-community,kool79/intellij-community,idea4bsd/idea4bsd,caot/intellij-community,SerCeMan/intellij-community,xfournet/intellij-community,alphafoobar/intellij-community,FHannes/intellij-community,ibinti/intellij-community,ahb0327/intellij-community,michaelgallacher/intellij-community
/* * Copyright 2000-2014 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.openapi.project; import com.intellij.ide.DataManager; import com.intellij.openapi.actionSystem.CommonDataKeys; import com.intellij.openapi.actionSystem.DataContext; import com.intellij.openapi.fileEditor.UniqueVFilePathBuilder; import com.intellij.openapi.fileTypes.FileType; import com.intellij.openapi.fileTypes.FileTypeManager; import com.intellij.openapi.roots.ProjectRootManager; import com.intellij.openapi.util.io.FileUtil; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.openapi.vfs.VirtualFilePathWrapper; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.swing.*; /** * @author max */ public class ProjectUtil { private ProjectUtil() { } @Nullable public static String getProjectLocationString(@NotNull final Project project) { return FileUtil.getLocationRelativeToUserHome(project.getBasePath()); } @NotNull public static String calcRelativeToProjectPath(@NotNull final VirtualFile file, @Nullable final Project project, final boolean includeFilePath) { return calcRelativeToProjectPath(file, project, includeFilePath, false, false); } @NotNull public static String calcRelativeToProjectPath(@NotNull final VirtualFile file, @Nullable final Project project, final boolean includeFilePath, final boolean includeUniqueFilePath, final boolean keepModuleAlwaysOnTheLeft) { if (file instanceof VirtualFilePathWrapper && ((VirtualFilePathWrapper)file).enforcePresentableName()) { return includeFilePath ? ((VirtualFilePathWrapper)file).getPresentablePath() : file.getName(); } String url; if (includeFilePath) { url = file.getPresentableUrl(); } else if (includeUniqueFilePath) { url = UniqueVFilePathBuilder.getInstance().getUniqueVirtualFilePath(project, file); } else { url = file.getName(); } if (project == null) { return url; } return ProjectUtilCore.displayUrlRelativeToProject(file, url, project, includeFilePath, keepModuleAlwaysOnTheLeft); } public static String calcRelativeToProjectPath(final VirtualFile file, final Project project) { return calcRelativeToProjectPath(file, project, true); } @Nullable public static Project guessProjectForFile(VirtualFile file) { return ProjectLocator.getInstance().guessProjectForFile(file); } @Nullable public static Project guessProjectForContentFile(@NotNull VirtualFile file) { return guessProjectForContentFile(file, file.getFileType()); } @Nullable /*** * guessProjectForFile works incorrectly - even if file is config (idea config file) first opened project will be returned */ public static Project guessProjectForContentFile(@NotNull VirtualFile file, @NotNull FileType fileType) { if (isProjectOrWorkspaceFile(file, fileType)) { return null; } for (Project project : ProjectManager.getInstance().getOpenProjects()) { if (!project.isDefault() && project.isInitialized() && !project.isDisposed() && ProjectRootManager.getInstance(project).getFileIndex().isInContent(file)) { return project; } } return null; } public static boolean isProjectOrWorkspaceFile(final VirtualFile file) { // do not use file.getFileType() to avoid autodetection by content loading for arbitrary files return isProjectOrWorkspaceFile(file, FileTypeManager.getInstance().getFileTypeByFileName(file.getName())); } public static boolean isProjectOrWorkspaceFile(@NotNull VirtualFile file, @Nullable FileType fileType) { return ProjectCoreUtil.isProjectOrWorkspaceFile(file, fileType); } @NotNull public static Project guessCurrentProject(@Nullable JComponent component) { Project project = null; if (component != null) { project = CommonDataKeys.PROJECT.getData(DataManager.getInstance().getDataContext(component)); } if (project == null) { Project[] openProjects = ProjectManager.getInstance().getOpenProjects(); if (openProjects.length > 0) project = openProjects[0]; if (project == null) { DataContext dataContext = DataManager.getInstance().getDataContext(); project = CommonDataKeys.PROJECT.getData(dataContext); } if (project == null) { project = ProjectManager.getInstance().getDefaultProject(); } } return project; } }
platform/lang-api/src/com/intellij/openapi/project/ProjectUtil.java
/* * Copyright 2000-2014 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.openapi.project; import com.intellij.ide.DataManager; import com.intellij.openapi.actionSystem.CommonDataKeys; import com.intellij.openapi.actionSystem.DataContext; import com.intellij.openapi.fileEditor.UniqueVFilePathBuilder; import com.intellij.openapi.fileTypes.FileType; import com.intellij.openapi.fileTypes.InternalFileType; import com.intellij.openapi.roots.ProjectRootManager; import com.intellij.openapi.util.Comparing; import com.intellij.openapi.util.SystemInfoRt; import com.intellij.openapi.util.io.FileUtil; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.openapi.vfs.VirtualFilePathWrapper; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.swing.*; /** * @author max */ public class ProjectUtil { private ProjectUtil() { } @Nullable public static String getProjectLocationString(@NotNull final Project project) { return FileUtil.getLocationRelativeToUserHome(project.getBasePath()); } @NotNull public static String calcRelativeToProjectPath(@NotNull final VirtualFile file, @Nullable final Project project, final boolean includeFilePath) { return calcRelativeToProjectPath(file, project, includeFilePath, false, false); } @NotNull public static String calcRelativeToProjectPath(@NotNull final VirtualFile file, @Nullable final Project project, final boolean includeFilePath, final boolean includeUniqueFilePath, final boolean keepModuleAlwaysOnTheLeft) { if (file instanceof VirtualFilePathWrapper && ((VirtualFilePathWrapper)file).enforcePresentableName()) { return includeFilePath ? ((VirtualFilePathWrapper)file).getPresentablePath() : file.getName(); } String url; if (includeFilePath) { url = file.getPresentableUrl(); } else if (includeUniqueFilePath) { url = UniqueVFilePathBuilder.getInstance().getUniqueVirtualFilePath(project, file); } else { url = file.getName(); } if (project == null) { return url; } return ProjectUtilCore.displayUrlRelativeToProject(file, url, project, includeFilePath, keepModuleAlwaysOnTheLeft); } public static String calcRelativeToProjectPath(final VirtualFile file, final Project project) { return calcRelativeToProjectPath(file, project, true); } @Nullable public static Project guessProjectForFile(VirtualFile file) { return ProjectLocator.getInstance().guessProjectForFile(file); } @Nullable public static Project guessProjectForContentFile(@NotNull VirtualFile file) { return guessProjectForContentFile(file, file.getFileType()); } @Nullable /*** * guessProjectForFile works incorrectly - even if file is config (idea config file) first opened project will be returned */ public static Project guessProjectForContentFile(@NotNull VirtualFile file, @NotNull FileType fileType) { if (isProjectOrWorkspaceFile(file, fileType)) { return null; } for (Project project : ProjectManager.getInstance().getOpenProjects()) { if (!project.isDefault() && project.isInitialized() && !project.isDisposed() && ProjectRootManager.getInstance(project).getFileIndex().isInContent(file)) { return project; } } return null; } public static boolean isProjectOrWorkspaceFile(final VirtualFile file) { return isProjectOrWorkspaceFile(file, file.getFileType()); } public static boolean isProjectOrWorkspaceFile(@NotNull VirtualFile file, @Nullable FileType fileType) { if (fileType instanceof InternalFileType) return true; VirtualFile parent = file.isDirectory() ? file: file.getParent(); while (parent != null) { if (Comparing.equal(parent.getNameSequence(), ProjectCoreUtil.DIRECTORY_BASED_PROJECT_DIR, SystemInfoRt.isFileSystemCaseSensitive)) return true; parent = parent.getParent(); } return false; } @NotNull public static Project guessCurrentProject(@Nullable JComponent component) { Project project = null; if (component != null) { project = CommonDataKeys.PROJECT.getData(DataManager.getInstance().getDataContext(component)); } if (project == null) { Project[] openProjects = ProjectManager.getInstance().getOpenProjects(); if (openProjects.length > 0) project = openProjects[0]; if (project == null) { DataContext dataContext = DataManager.getInstance().getDataContext(); project = CommonDataKeys.PROJECT.getData(dataContext); } if (project == null) { project = ProjectManager.getInstance().getDefaultProject(); } } return project; } }
- do not file.getFileType() to avoid autodetection by content loading for arbitrary files - use ProjectCoreUtil when possible
platform/lang-api/src/com/intellij/openapi/project/ProjectUtil.java
- do not file.getFileType() to avoid autodetection by content loading for arbitrary files - use ProjectCoreUtil when possible
<ide><path>latform/lang-api/src/com/intellij/openapi/project/ProjectUtil.java <ide> import com.intellij.openapi.actionSystem.DataContext; <ide> import com.intellij.openapi.fileEditor.UniqueVFilePathBuilder; <ide> import com.intellij.openapi.fileTypes.FileType; <del>import com.intellij.openapi.fileTypes.InternalFileType; <add>import com.intellij.openapi.fileTypes.FileTypeManager; <ide> import com.intellij.openapi.roots.ProjectRootManager; <del>import com.intellij.openapi.util.Comparing; <del>import com.intellij.openapi.util.SystemInfoRt; <ide> import com.intellij.openapi.util.io.FileUtil; <ide> import com.intellij.openapi.vfs.VirtualFile; <ide> import com.intellij.openapi.vfs.VirtualFilePathWrapper; <ide> } <ide> <ide> public static boolean isProjectOrWorkspaceFile(final VirtualFile file) { <del> return isProjectOrWorkspaceFile(file, file.getFileType()); <add> // do not use file.getFileType() to avoid autodetection by content loading for arbitrary files <add> return isProjectOrWorkspaceFile(file, FileTypeManager.getInstance().getFileTypeByFileName(file.getName())); <ide> } <ide> <ide> public static boolean isProjectOrWorkspaceFile(@NotNull VirtualFile file, @Nullable FileType fileType) { <del> if (fileType instanceof InternalFileType) return true; <del> VirtualFile parent = file.isDirectory() ? file: file.getParent(); <del> while (parent != null) { <del> if (Comparing.equal(parent.getNameSequence(), ProjectCoreUtil.DIRECTORY_BASED_PROJECT_DIR, SystemInfoRt.isFileSystemCaseSensitive)) return true; <del> parent = parent.getParent(); <del> } <del> return false; <add> return ProjectCoreUtil.isProjectOrWorkspaceFile(file, fileType); <ide> } <ide> <ide> @NotNull
Java
apache-2.0
51c46a92c2161a31959f5f53bb3348b925251ec9
0
chinmay-gupte/blueflood,goru97/blueflood,izrik/blueflood,shintasmith/blueflood,shintasmith/blueflood,izrik/blueflood,rackerlabs/blueflood,GeorgeJahad/blueflood,GeorgeJahad/blueflood,tilogaat/blueflood,ChandraAddala/blueflood,goru97/blueflood,menchauser/blueflood,ChandraAddala/blueflood,goru97/blueflood,izrik/blueflood,tilogaat/blueflood,VinnyQ/blueflood,rackerlabs/blueflood,menchauser/blueflood,ChandraAddala/blueflood,VinnyQ/blueflood,goru97/blueflood,shintasmith/blueflood,GeorgeJahad/blueflood,btravers/blueflood,tilogaat/blueflood,ChandraAddala/blueflood,menchauser/blueflood,btravers/blueflood,goru97/blueflood,chinmay-gupte/blueflood,VinnyQ/blueflood,shintasmith/blueflood,VinnyQ/blueflood,rackerlabs/blueflood,rackerlabs/blueflood,shintasmith/blueflood,izrik/blueflood,btravers/blueflood,ChandraAddala/blueflood,GeorgeJahad/blueflood,chinmay-gupte/blueflood,chinmay-gupte/blueflood,menchauser/blueflood,menchauser/blueflood,chinmay-gupte/blueflood,tilogaat/blueflood,izrik/blueflood,VinnyQ/blueflood,goru97/blueflood,shintasmith/blueflood,rackerlabs/blueflood,izrik/blueflood,GeorgeJahad/blueflood,ChandraAddala/blueflood,rackerlabs/blueflood,VinnyQ/blueflood,btravers/blueflood,btravers/blueflood,tilogaat/blueflood
/* * Copyright 2013 Rackspace * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.rackspacecloud.blueflood.concurrent; import com.google.common.util.concurrent.AsyncFunction; import com.google.common.util.concurrent.ListenableFuture; import com.google.common.util.concurrent.ListeningExecutorService; import com.google.common.util.concurrent.MoreExecutors; import org.slf4j.LoggerFactory; import org.slf4j.Logger; import java.util.concurrent.ThreadPoolExecutor; /** * Does asynchronous work using a specified threadpool. * @param <I> * @param <O> */ public abstract class AsyncFunctionWithThreadPool<I, O> implements AsyncFunction<I, O> { private final ThreadPoolExecutor executor; // listieningExecutor wraps the above executor. private final ListeningExecutorService listeningExecutor; private Logger log = LoggerFactory.getLogger(getClass()); public AsyncFunctionWithThreadPool(ThreadPoolExecutor executor) { this.executor = executor; this.listeningExecutor = MoreExecutors.listeningDecorator(executor); } public <I, O> AsyncFunctionWithThreadPool<I, O> withLogger(Logger log) { this.log = log; return (AsyncFunctionWithThreadPool<I,O>) this; } public ListeningExecutorService getThreadPool() { return listeningExecutor; } public Logger getLogger() { return log; } public abstract ListenableFuture<O> apply(I input) throws Exception; public void setPoolSize(int size) { this.executor.setCorePoolSize(size); this.executor.setMaximumPoolSize(size); } public int getPoolSize() { return this.executor.getCorePoolSize(); } }
blueflood-core/src/main/java/com/rackspacecloud/blueflood/concurrent/AsyncFunctionWithThreadPool.java
/* * Copyright 2013 Rackspace * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.rackspacecloud.blueflood.concurrent; import com.google.common.util.concurrent.AsyncFunction; import com.google.common.util.concurrent.ListenableFuture; import com.google.common.util.concurrent.ListeningExecutorService; import com.google.common.util.concurrent.MoreExecutors; import org.slf4j.LoggerFactory; import org.slf4j.Logger; import java.util.concurrent.ThreadPoolExecutor; /** * Does asynchronous work using a specified threadpool. * @param <I> * @param <O> */ public abstract class AsyncFunctionWithThreadPool<I, O> implements AsyncFunction<I, O> { private final ThreadPoolExecutor executor; // listieningExecutor wraps the above executor. private final ListeningExecutorService listeningExecutor; private Logger log = LoggerFactory.getLogger(getClass()); public AsyncFunctionWithThreadPool(ThreadPoolExecutor executor) { this.executor = executor; this.listeningExecutor = MoreExecutors.listeningDecorator(executor); } public <I, O> AsyncFunctionWithThreadPool<I, O> withLogger(Logger log) { this.log = log; return (AsyncFunctionWithThreadPool<I,O>) this; } // todo: this method could be made uneeded if apply where implemented to always send work to this threadpool. // there would also need to be an abstract function that actually did the work asked for (transform I->O). public ListeningExecutorService getThreadPool() { return listeningExecutor; } public Logger getLogger() { return log; } public abstract ListenableFuture<O> apply(I input) throws Exception; public void setPoolSize(int size) { this.executor.setCorePoolSize(size); this.executor.setMaximumPoolSize(size); } public int getPoolSize() { return this.executor.getCorePoolSize(); } }
remove comment. getThreadpool() will be necessary. BatchWriter is a good example of why. That code could never be encapsulated in a method that returns a single Callable (since it sends multiple Callables into the threadpool).
blueflood-core/src/main/java/com/rackspacecloud/blueflood/concurrent/AsyncFunctionWithThreadPool.java
remove comment. getThreadpool() will be necessary. BatchWriter is a good example of why. That code could never be encapsulated in a method that returns a single Callable (since it sends multiple Callables into the threadpool).
<ide><path>lueflood-core/src/main/java/com/rackspacecloud/blueflood/concurrent/AsyncFunctionWithThreadPool.java <ide> return (AsyncFunctionWithThreadPool<I,O>) this; <ide> } <ide> <del> // todo: this method could be made uneeded if apply where implemented to always send work to this threadpool. <del> // there would also need to be an abstract function that actually did the work asked for (transform I->O). <ide> public ListeningExecutorService getThreadPool() { return listeningExecutor; } <add> <ide> public Logger getLogger() { return log; } <ide> <ide> public abstract ListenableFuture<O> apply(I input) throws Exception;
JavaScript
mit
0896badcdf174f5ef56015d77d4a3363a116ea2a
0
sackio/mongoo
/* Add a path that represents a location - address and geojson */ 'use strict'; var Belt = require('jsbelt') , _ = require('underscore') , Async = require('async') , Locup = require('locup'); module.exports = function(schema, options){ var a = Belt.argulint(arguments, { 'validators': { 'options': [ { 'validator': function(){ return this.path; } , 'error': new Error('path is required') } ] } , 'options': options || {} }); a.o = _.defaults(a.o, { 'path': false , 'schema': { 'given_string': {type: String} , 'normalized_string': {type: String} , 'address': {type: Object} , 'coordinates': { 'Longitude': {type: Number} , 'Latitude': {type: Number} } } , 'array': false , 'geocoder_api': new Locup(a.o) , 'auto_geocode': true , 'fail_on_geocode_error': false , 'virtual_prefix': '__' }); var def = [a.o.schema]; if (a.o.array) def = [def]; schema.add(_.object([a.o.path], def)); //schema.index(_.object([a.o.path + '.coordinates'], ['2d'])); var vp = schema.virtual(a.o.path + '_no_geocode'); vp.get(function(){ return this[a.o.virtual_prefix + a.o.path + '_no_geocode']; }); vp.set(function(val){ return this[a.o.virtual_prefix + a.o.path + '_no_geocode'] = val; }); //Attempt to produce a normalized address based on the address components present schema.method('normalize_address', function(path){ if (_.isArray(this.get(path))){ var addrs = [] , self = this; _.each(this.get(path), function(p, i){ return addrs.push(_.compact([self.get(path + '.' + i + '.address.street_number') , self.get(path + '.' + i + '.address.route'), self.get(path + '.' + i + '.address.city'), self.get(path + '.' + i + '.address.state') , self.get(path + '.' + i + '.address.country'), self.get(path + '.' + i + '.address.zip')]).join(', ')); }); return addrs; } return _.compact([this.get(path + '.address.street_number'), this.get(path + '.address.route') , this.get(path + '.address.city'), this.get(path + '.address.state'), this.get(path + '.address.country'), this.get(path + '.address.zip')]).join(', '); }); if (a.o.geocoder_api){ //Use the given string to geocode the address, setting coordinates, formatted address, and address components schema.method('geocode', function(path, options, callback){ var self = this , b = Belt.argulint(arguments); b.o = _.defaults(b.o, { 'address_string': 'given_string' , 'reverse_geocode': false }); if (_.isArray(this.get(path))){ var geos = [] , index = 0; return Async.eachSeries(this.get(path), function(l, cb){ index++; var args = b.o.reverse_geocode ? [self.get(path + '.' + (index - 1) + '.geo.coordinates.1'), self.get(path + '.' + (index - 1) + '.geo.coordinates.0')] : [self.get(path + '.' + (index - 1) + '.' + b.o.address_string)]; return a.o.geocoder_api[b.o.reverse_geocode ? 'reverse_geocode' : 'geocode'].apply(null, args.concat([function(err, geocoding){ if (err) return cb(new Error('Error geocoding location: [' + args.join(', ') + '] - ' + err.message)); geocoding = _.isArray(geocoding) ? geocoding[0] : geocoding; //set coordinates self.set(path + '.' + (index - 1) + '.coordinates', { 'Longitude': Belt.get(geocoding, 'geometry.location.lng') , 'Latitude': Belt.get(geocoding, 'geometry.location.lat') }); //set normalized_address self.set(path + '.' + (index - 1) + '.normalized_string', Belt._get(geocoding, 'formatted_address')); var components = a.o.geocoder_api.address_components_to_obj(Belt._get(geocoding, 'address_components')) || {}; //set address components _.each(components, function(v, k){ return self.set(path + '.' + (index - 1) + '.address.' + k, v); }); self.set(path + '.' + (index - 1) + '.address.city', components.locality); self.set(path + '.' + (index - 1) + '.address.state', components.administrative_area_level_1); self.set(path + '.' + (index - 1) + '.address.zip', components.postal_code); geos.push(geocoding); return cb(); }])); }, function(err){ return b.cb(err, geos); }); } var args = b.o.reverse_geocode ? [this.get(path + '.geo.coordinates.1'), this.get(path + '.geo.coordinates.0')] : [this.get(path + '.' + b.o.address_string)]; return a.o.geocoder_api[b.o.reverse_geocode ? 'reverse_geocode' : 'geocode'].apply(null, args.concat([function(err, geocoding){ if (err) return b.cb(new Error('Error geocoding location: [' + args.join(', ') + '] - ' + err.message)); geocoding = _.isArray(geocoding) ? geocoding[0] : geocoding; //set coordinates self.set(path + '.coordinates', { 'Longitude': Belt.get(geocoding, 'geometry.location.lng') , 'Latitude': Belt.get(geocoding, 'geometry.location.lat') }); //set normalized_address self.set(path + '.normalized_string', Belt._get(geocoding, 'formatted_address')); var components = a.o.geocoder_api.address_components_to_obj(Belt._get(geocoding, 'address_components')) || {}; //set address components _.each(components, function(v, k){ return self.set(path + '.address.' + k, v); }); self.set(path + '.address.city', components.locality); self.set(path + '.address.state', components.administrative_area_level_1); self.set(path + '.address.zip', components.postal_code); return b.cb(err, geocoding); }])); }); //Use the given coordinates to look up an address schema.method('reverse_geocode', function(path, options, callback){ var b = Belt.argulint(arguments); b.o = _.defaults(b.o, { 'reverse_geocode': true }); return this.geocode(path, b.o, b.cb); }); if (a.o.auto_geocode) schema.pre('save', function(next){ if (!this.isNew && !this.isModified(a.o.path) || this.get(a.o.path + '_no_geocode')) return next(); if (!a.o.array){ if ((this.isNew && (this.get(a.o.path + '.coordinates.Longitude') || this.get(a.o.path + '.coordinates.Latitude'))) || this.isModified(a.o.path + '.coordinates.Longitude') || this.isModified(a.o.path + '.coordinates.Latitude')){ return this.reverse_geocode(a.o.path, function(err){ if (err) console.error(err); return next() }); } if ((this.isNew && this.get(a.o.path + '.given_string')) || this.isModified(a.o.path + '.given_string')){ return this.geocode(a.o.path, function(err){ if (err) console.error(err); return next() }); } return next(); } /* var index = 0 , self = this; return Async.eachSeries(self.get(a.o.path), function(p, cb){ index++; if (!self.isNew && !self.isModified(a.o.path + '.' + (index - 1))) return cb(); if ((self.isNew && (self.get(a.o.path + '.' + (index - 1) + '.coordinates.Longitude') || self.get(a.o.path + '.' + (index - 1) + '.coordinates.Latitude'))) || self.isModified(a.o.path + '.' + (index - 1) + '.coordinates.Longitude') || self.isModified(a.o.path + '.' + (index - 1) + '.coordinates.Latitude')){ return self.reverse_geocode(a.o.path + '.' + (index -1), Belt.cw(cb)); if ((self.isNew && self.get(a.o.path + '.' + (index -1) + '.given_string')) || self.isModified(a.o.path + '.' + (index -1) + '.given_string')) return self.geocode(a.o.path + '.' + (index -1), Belt.cw(cb)); return cb(); }, Belt.cw(next, 0));*/ }); } return schema; };
lib/plugins/location_path.js
/* Add a path that represents a location - address and geojson */ 'use strict'; var Belt = require('jsbelt') , _ = require('underscore') , Async = require('async') , Locup = require('locup'); module.exports = function(schema, options){ var a = Belt.argulint(arguments, { 'validators': { 'options': [ { 'validator': function(){ return this.path; } , 'error': new Error('path is required') } ] } , 'options': options || {} }); a.o = _.defaults(a.o, { 'path': false , 'schema': { 'given_string': {type: String} , 'normalized_string': {type: String} , 'address': {type: Object} , 'geo': { 'type': {type: String, default: 'Point'} , 'coordinates': {type: Array} } } , 'array': false , 'geocoder_api': new Locup(a.o) , 'auto_geocode': true , 'fail_on_geocode_error': false , 'virtual_prefix': '__' }); var def = [a.o.schema]; if (a.o.array) def = [def]; schema.add(_.object([a.o.path], def)); if (!a.o.sparse) schema.index(_.object([a.o.path + '.geo'], ['2dsphere'])); var vp = schema.virtual(a.o.path + '_no_geocode'); vp.get(function(){ return this[a.o.virtual_prefix + a.o.path + '_no_geocode']; }); vp.set(function(val){ return this[a.o.virtual_prefix + a.o.path + '_no_geocode'] = val; }); //Attempt to produce a normalized address based on the address components present schema.method('normalize_address', function(path){ if (_.isArray(this.get(path))){ var addrs = [] , self = this; _.each(this.get(path), function(p, i){ return addrs.push(_.compact([self.get(path + '.' + i + '.address.street_number') , self.get(path + '.' + i + '.address.route'), self.get(path + '.' + i + '.address.city'), self.get(path + '.' + i + '.address.state') , self.get(path + '.' + i + '.address.country'), self.get(path + '.' + i + '.address.zip')]).join(', ')); }); return addrs; } return _.compact([this.get(path + '.address.street_number'), this.get(path + '.address.route') , this.get(path + '.address.city'), this.get(path + '.address.state'), this.get(path + '.address.country'), this.get(path + '.address.zip')]).join(', '); }); if (a.o.geocoder_api){ //Use the given string to geocode the address, setting coordinates, formatted address, and address components schema.method('geocode', function(path, options, callback){ var self = this , b = Belt.argulint(arguments); b.o = _.defaults(b.o, { 'address_string': 'given_string' , 'reverse_geocode': false }); if (_.isArray(this.get(path))){ var geos = [] , index = 0; return Async.eachSeries(this.get(path), function(l, cb){ index++; var args = b.o.reverse_geocode ? [self.get(path + '.' + (index - 1) + '.geo.coordinates.1'), self.get(path + '.' + (index - 1) + '.geo.coordinates.0')] : [self.get(path + '.' + (index - 1) + '.' + b.o.address_string)]; return a.o.geocoder_api[b.o.reverse_geocode ? 'reverse_geocode' : 'geocode'].apply(null, args.concat([function(err, geocoding){ if (err) return cb(new Error('Error geocoding location: [' + args.join(', ') + '] - ' + err.message)); geocoding = _.isArray(geocoding) ? geocoding[0] : geocoding; //set coordinates self.set(path + '.' + (index - 1) + '.geo.coordinates', [Belt._get(geocoding, 'geometry.location.lng'), Belt._get(geocoding, 'geometry.location.lat')]); //set normalized_address self.set(path + '.' + (index - 1) + '.normalized_string', Belt._get(geocoding, 'formatted_address')); var components = a.o.geocoder_api.address_components_to_obj(Belt._get(geocoding, 'address_components')) || {}; //set address components _.each(components, function(v, k){ return self.set(path + '.' + (index - 1) + '.address.' + k, v); }); self.set(path + '.' + (index - 1) + '.address.city', components.locality); self.set(path + '.' + (index - 1) + '.address.state', components.administrative_area_level_1); self.set(path + '.' + (index - 1) + '.address.zip', components.postal_code); geos.push(geocoding); return cb(); }])); }, function(err){ return b.cb(err, geos); }); } var args = b.o.reverse_geocode ? [this.get(path + '.geo.coordinates.1'), this.get(path + '.geo.coordinates.0')] : [this.get(path + '.' + b.o.address_string)]; return a.o.geocoder_api[b.o.reverse_geocode ? 'reverse_geocode' : 'geocode'].apply(null, args.concat([function(err, geocoding){ if (err) return b.cb(new Error('Error geocoding location: [' + args.join(', ') + '] - ' + err.message)); geocoding = _.isArray(geocoding) ? geocoding[0] : geocoding; //set coordinates self.set(path + '.geo.coordinates', [Belt._get(geocoding, 'geometry.location.lng'), Belt._get(geocoding, 'geometry.location.lat')]); //set normalized_address self.set(path + '.normalized_string', Belt._get(geocoding, 'formatted_address')); var components = a.o.geocoder_api.address_components_to_obj(Belt._get(geocoding, 'address_components')) || {}; //set address components _.each(components, function(v, k){ return self.set(path + '.address.' + k, v); }); self.set(path + '.address.city', components.locality); self.set(path + '.address.state', components.administrative_area_level_1); self.set(path + '.address.zip', components.postal_code); return b.cb(err, geocoding); }])); }); //Use the given coordinates to look up an address schema.method('reverse_geocode', function(path, options, callback){ var b = Belt.argulint(arguments); b.o = _.defaults(b.o, { 'reverse_geocode': true }); return this.geocode(path, b.o, b.cb); }); if (a.o.auto_geocode) schema.pre('save', function(next){ if (!this.isNew && !this.isModified(a.o.path) || this.get(a.o.path + '_no_geocode')) return next(); if (!a.o.array){ if ((this.isNew && _.any(this.get(a.o.path + '.geo.coordinates'))) || this.isModified(a.o.path + '.geo.coordinates')){ return this.reverse_geocode(a.o.path, function(err){ if (err) console.error(err); return next() }); } if ((this.isNew && this.get(a.o.path + '.given_string')) || this.isModified(a.o.path + '.given_string')){ return this.geocode(a.o.path, function(err){ if (err) console.error(err); return next() }); } return next(); } var index = 0 , self = this; return Async.eachSeries(self.get(a.o.path), function(p, cb){ index++; if (!self.isNew && !self.isModified(a.o.path + '.' + (index - 1))) return cb(); if ((self.isNew && _.any(self.get(a.o.path + '.' + (index -1) + '.geo.coordinates'))) || self.isModified(a.o.path + '.' + (index -1) + '.geo.coordinates')) return self.reverse_geocode(a.o.path + '.' + (index -1), Belt.cw(cb)); if ((self.isNew && self.get(a.o.path + '.' + (index -1) + '.given_string')) || self.isModified(a.o.path + '.' + (index -1) + '.given_string')) return self.geocode(a.o.path + '.' + (index -1), Belt.cw(cb)); return cb(); }, Belt.cw(next, 0)); }); } return schema; };
new location path plugin
lib/plugins/location_path.js
new location path plugin
<ide><path>ib/plugins/location_path.js <ide> 'given_string': {type: String} <ide> , 'normalized_string': {type: String} <ide> , 'address': {type: Object} <del> , 'geo': { <del> 'type': {type: String, default: 'Point'} <del> , 'coordinates': {type: Array} <add> , 'coordinates': { <add> 'Longitude': {type: Number} <add> , 'Latitude': {type: Number} <ide> } <ide> } <ide> , 'array': false <ide> if (a.o.array) def = [def]; <ide> <ide> schema.add(_.object([a.o.path], def)); <del> if (!a.o.sparse) schema.index(_.object([a.o.path + '.geo'], ['2dsphere'])); <add> //schema.index(_.object([a.o.path + '.coordinates'], ['2d'])); <ide> <ide> var vp = schema.virtual(a.o.path + '_no_geocode'); <ide> vp.get(function(){ <ide> geocoding = _.isArray(geocoding) ? geocoding[0] : geocoding; <ide> <ide> //set coordinates <del> self.set(path + '.' + (index - 1) + '.geo.coordinates', [Belt._get(geocoding, 'geometry.location.lng'), Belt._get(geocoding, 'geometry.location.lat')]); <add> self.set(path + '.' + (index - 1) + '.coordinates', { <add> 'Longitude': Belt.get(geocoding, 'geometry.location.lng') <add> , 'Latitude': Belt.get(geocoding, 'geometry.location.lat') <add> }); <ide> <ide> //set normalized_address <ide> self.set(path + '.' + (index - 1) + '.normalized_string', Belt._get(geocoding, 'formatted_address')); <ide> geocoding = _.isArray(geocoding) ? geocoding[0] : geocoding; <ide> <ide> //set coordinates <del> self.set(path + '.geo.coordinates', [Belt._get(geocoding, 'geometry.location.lng'), Belt._get(geocoding, 'geometry.location.lat')]); <add> self.set(path + '.coordinates', { <add> 'Longitude': Belt.get(geocoding, 'geometry.location.lng') <add> , 'Latitude': Belt.get(geocoding, 'geometry.location.lat') <add> }); <ide> <ide> //set normalized_address <ide> self.set(path + '.normalized_string', Belt._get(geocoding, 'formatted_address')); <ide> if (!this.isNew && !this.isModified(a.o.path) || this.get(a.o.path + '_no_geocode')) return next(); <ide> <ide> if (!a.o.array){ <del> if ((this.isNew && _.any(this.get(a.o.path + '.geo.coordinates'))) || this.isModified(a.o.path + '.geo.coordinates')){ <add> if ((this.isNew && <add> (this.get(a.o.path + '.coordinates.Longitude') || this.get(a.o.path + '.coordinates.Latitude'))) <add> || this.isModified(a.o.path + '.coordinates.Longitude') || this.isModified(a.o.path + '.coordinates.Latitude')){ <ide> return this.reverse_geocode(a.o.path, function(err){ <ide> if (err) console.error(err); <ide> return next() <ide> return next(); <ide> } <ide> <add> /* <ide> var index = 0 <ide> , self = this; <ide> <ide> <ide> if (!self.isNew && !self.isModified(a.o.path + '.' + (index - 1))) return cb(); <ide> <del> if ((self.isNew && _.any(self.get(a.o.path + '.' + (index -1) + '.geo.coordinates'))) <del> || self.isModified(a.o.path + '.' + (index -1) + '.geo.coordinates')) <add> if ((self.isNew && <add> (self.get(a.o.path + '.' + (index - 1) + '.coordinates.Longitude') <add> || self.get(a.o.path + '.' + (index - 1) + '.coordinates.Latitude'))) <add> || self.isModified(a.o.path + '.' + (index - 1) + '.coordinates.Longitude') <add> || self.isModified(a.o.path + '.' + (index - 1) + '.coordinates.Latitude')){ <ide> return self.reverse_geocode(a.o.path + '.' + (index -1), Belt.cw(cb)); <add> <ide> if ((self.isNew && self.get(a.o.path + '.' + (index -1) + '.given_string')) <ide> || self.isModified(a.o.path + '.' + (index -1) + '.given_string')) <ide> return self.geocode(a.o.path + '.' + (index -1), Belt.cw(cb)); <ide> <ide> return cb(); <del> }, Belt.cw(next, 0)); <add> }, Belt.cw(next, 0));*/ <ide> }); <ide> } <ide>
Java
apache-2.0
25f64b0cd254d7a00cd0c9350919b9ac352c5f3d
0
kidaa/maven-1,keith-turner/maven,ChristianSchulte/maven,aheritier/maven,mcculls/maven,Tibor17/maven,wangyuesong0/maven,trajano/maven,karthikjaps/maven,mizdebsk/maven,njuneau/maven,changbai1980/maven,mizdebsk/maven,lbndev/maven,josephw/maven,Mounika-Chirukuri/maven,runepeter/maven-deploy-plugin-2.8.1,kidaa/maven-1,mcculls/maven,cstamas/maven,Distrotech/maven,ChristianSchulte/maven,runepeter/maven-deploy-plugin-2.8.1,keith-turner/maven,wangyuesong0/maven,rogerchina/maven,aheritier/maven,Distrotech/maven,olamy/maven,ChristianSchulte/maven,skitt/maven,wangyuesong0/maven,changbai1980/maven,mcculls/maven,skitt/maven,barthel/maven,atanasenko/maven,josephw/maven,olamy/maven,changbai1980/maven,gorcz/maven,skitt/maven,vedmishr/demo1,kidaa/maven-1,stephenc/maven,dsyer/maven,lbndev/maven,karthikjaps/maven,barthel/maven,cstamas/maven,lbndev/maven,wangyuesong/maven,stephenc/maven,wangyuesong/maven,likaiwalkman/maven,gorcz/maven,josephw/maven,atanasenko/maven,xasx/maven,Mounika-Chirukuri/maven,vedmishr/demo1,karthikjaps/maven,apache/maven,xasx/maven,rogerchina/maven,atanasenko/maven,njuneau/maven,trajano/maven,vedmishr/demo1,cstamas/maven,trajano/maven,olamy/maven,likaiwalkman/maven,wangyuesong/maven,pkozelka/maven,stephenc/maven,pkozelka/maven,likaiwalkman/maven,mizdebsk/maven,xasx/maven,rogerchina/maven,dsyer/maven,aheritier/maven,njuneau/maven,apache/maven,pkozelka/maven,barthel/maven,keith-turner/maven,Tibor17/maven,Mounika-Chirukuri/maven,dsyer/maven,gorcz/maven,apache/maven
package org.apache.maven.plugin; /* * Copyright 2001-2005 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import org.apache.maven.model.Plugin; import org.apache.maven.plugin.descriptor.PluginDescriptor; import org.codehaus.plexus.component.discovery.ComponentDiscoveryEvent; import org.codehaus.plexus.component.discovery.ComponentDiscoveryListener; import org.codehaus.plexus.component.repository.ComponentSetDescriptor; import org.codehaus.plexus.logging.AbstractLogEnabled; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; public class MavenPluginCollector extends AbstractLogEnabled implements ComponentDiscoveryListener { private Set pluginsInProcess = new HashSet(); private Map pluginDescriptors = new HashMap(); private Map pluginIdsByPrefix = new HashMap(); // ---------------------------------------------------------------------- // Mojo discovery // ---------------------------------------------------------------------- public void componentDiscovered( ComponentDiscoveryEvent event ) { ComponentSetDescriptor componentSetDescriptor = event.getComponentSetDescriptor(); if ( componentSetDescriptor instanceof PluginDescriptor ) { PluginDescriptor pluginDescriptor = (PluginDescriptor) componentSetDescriptor; // TODO: see comment in getPluginDescriptor String key = Plugin.constructKey( pluginDescriptor.getGroupId(), pluginDescriptor.getArtifactId() ); if ( !pluginsInProcess.contains( key ) ) { pluginsInProcess.add( key ); pluginDescriptors.put( key, pluginDescriptor ); // TODO: throw an (not runtime) exception if there is a prefix overlap - means doing so elsewhere // we also need to deal with multiple versions somehow - currently, first wins if ( !pluginIdsByPrefix.containsKey( pluginDescriptor.getGoalPrefix() ) ) { pluginIdsByPrefix.put( pluginDescriptor.getGoalPrefix(), pluginDescriptor ); } } } } public PluginDescriptor getPluginDescriptor( Plugin plugin ) { // TODO: include version, but can't do this in the plugin manager as it is not resolved to the right version // at that point. Instead, move the duplication check to the artifact container, or store it locally based on // the unresolved version? return (PluginDescriptor) pluginDescriptors.get( plugin.getKey() ); } public boolean isPluginInstalled( Plugin plugin ) { // TODO: see comment in getPluginDescriptor return pluginDescriptors.containsKey( plugin.getKey() ); } public PluginDescriptor getPluginDescriptorForPrefix( String prefix ) { return (PluginDescriptor) pluginIdsByPrefix.get( prefix ); } }
maven-core/src/main/java/org/apache/maven/plugin/MavenPluginCollector.java
package org.apache.maven.plugin; import org.apache.maven.model.Plugin; import org.apache.maven.plugin.descriptor.PluginDescriptor; import org.codehaus.plexus.component.discovery.ComponentDiscoveryEvent; import org.codehaus.plexus.component.discovery.ComponentDiscoveryListener; import org.codehaus.plexus.component.repository.ComponentSetDescriptor; import org.codehaus.plexus.logging.AbstractLogEnabled; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; public class MavenPluginCollector extends AbstractLogEnabled implements ComponentDiscoveryListener { private Set pluginsInProcess = new HashSet(); private Map pluginDescriptors = new HashMap(); private Map pluginIdsByPrefix = new HashMap(); // ---------------------------------------------------------------------- // Mojo discovery // ---------------------------------------------------------------------- public void componentDiscovered( ComponentDiscoveryEvent event ) { ComponentSetDescriptor componentSetDescriptor = event.getComponentSetDescriptor(); if ( componentSetDescriptor instanceof PluginDescriptor ) { PluginDescriptor pluginDescriptor = (PluginDescriptor) componentSetDescriptor; // TODO: see comment in getPluginDescriptor String key = Plugin.constructKey( pluginDescriptor.getGroupId(), pluginDescriptor.getArtifactId() ); if ( !pluginsInProcess.contains( key ) ) { pluginsInProcess.add( key ); pluginDescriptors.put( key, pluginDescriptor ); // TODO: throw an (not runtime) exception if there is a prefix overlap - means doing so elsewhere // we also need to deal with multiple versions somehow - currently, first wins if ( !pluginIdsByPrefix.containsKey( pluginDescriptor.getGoalPrefix() ) ) { pluginIdsByPrefix.put( pluginDescriptor.getGoalPrefix(), pluginDescriptor ); } } } } public PluginDescriptor getPluginDescriptor( Plugin plugin ) { // TODO: include version, but can't do this in the plugin manager as it is not resolved to the right version // at that point. Instead, move the duplication check to the artifact container, or store it locally based on // the unresolved version? return (PluginDescriptor) pluginDescriptors.get( plugin.getKey() ); } public boolean isPluginInstalled( Plugin plugin ) { // TODO: see comment in getPluginDescriptor return pluginDescriptors.containsKey( plugin.getKey() ); } public PluginDescriptor getPluginDescriptorForPrefix( String prefix ) { return (PluginDescriptor) pluginIdsByPrefix.get( prefix ); } }
add copyright git-svn-id: 2c527eb49caa05e19d6b2be874bf74fa9d7ea670@314767 13f79535-47bb-0310-9956-ffa450edef68
maven-core/src/main/java/org/apache/maven/plugin/MavenPluginCollector.java
add copyright
<ide><path>aven-core/src/main/java/org/apache/maven/plugin/MavenPluginCollector.java <ide> package org.apache.maven.plugin; <add> <add>/* <add> * Copyright 2001-2005 The Apache Software Foundation. <add> * <add> * Licensed under the Apache License, Version 2.0 (the "License"); <add> * you may not use this file except in compliance with the License. <add> * You may obtain a copy of the License at <add> * <add> * http://www.apache.org/licenses/LICENSE-2.0 <add> * <add> * Unless required by applicable law or agreed to in writing, software <add> * distributed under the License is distributed on an "AS IS" BASIS, <add> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. <add> * See the License for the specific language governing permissions and <add> * limitations under the License. <add> */ <ide> <ide> import org.apache.maven.model.Plugin; <ide> import org.apache.maven.plugin.descriptor.PluginDescriptor;
JavaScript
agpl-3.0
8a6574e81a7c0d44c908ce2b4740f004124f63c8
0
nextcloud/server,IljaN/core,IljaN/core,endsguy/server,xx621998xx/server,sharidas/core,Ardinis/server,sharidas/core,lrytz/core,xx621998xx/server,pixelipo/server,xx621998xx/server,lrytz/core,pmattern/server,pmattern/server,Ardinis/server,bluelml/core,IljaN/core,endsguy/server,pollopolea/core,jbicha/server,Ardinis/server,Ardinis/server,pollopolea/core,nextcloud/server,cernbox/core,jbicha/server,IljaN/core,whitekiba/server,whitekiba/server,nextcloud/server,cernbox/core,Ardinis/server,andreas-p/nextcloud-server,endsguy/server,jbicha/server,michaelletzgus/nextcloud-server,owncloud/core,pmattern/server,cernbox/core,pmattern/server,IljaN/core,owncloud/core,xx621998xx/server,michaelletzgus/nextcloud-server,bluelml/core,michaelletzgus/nextcloud-server,michaelletzgus/nextcloud-server,sharidas/core,nextcloud/server,pixelipo/server,pmattern/server,andreas-p/nextcloud-server,owncloud/core,pollopolea/core,bluelml/core,pixelipo/server,lrytz/core,andreas-p/nextcloud-server,sharidas/core,whitekiba/server,xx621998xx/server,endsguy/server,cernbox/core,owncloud/core,bluelml/core,pollopolea/core,andreas-p/nextcloud-server,pollopolea/core,phil-davis/core,endsguy/server,andreas-p/nextcloud-server,jbicha/server,owncloud/core,whitekiba/server,cernbox/core,jbicha/server,lrytz/core,pixelipo/server,sharidas/core,lrytz/core,pixelipo/server,bluelml/core,whitekiba/server
/* * Copyright (c) 2014 * * This file is licensed under the Affero General Public License version 3 * or later. * * See the COPYING-README file. * */ (function() { var TEMPLATE_ADDBUTTON = '<a href="#" class="button new" title="{{addText}}"><img src="{{iconUrl}}"></img></a>'; /** * @class OCA.Files.FileList * @classdesc * * The FileList class manages a file list view. * A file list view consists of a controls bar and * a file list table. * * @param $el container element with existing markup for the #controls * and a table * @param [options] map of options, see other parameters * @param [options.scrollContainer] scrollable container, defaults to $(window) * @param [options.dragOptions] drag options, disabled by default * @param [options.folderDropOptions] folder drop options, disabled by default * @param [options.detailsViewEnabled=true] whether to enable details view */ var FileList = function($el, options) { this.initialize($el, options); }; /** * @memberof OCA.Files */ FileList.prototype = { SORT_INDICATOR_ASC_CLASS: 'icon-triangle-n', SORT_INDICATOR_DESC_CLASS: 'icon-triangle-s', id: 'files', appName: t('files', 'Files'), isEmpty: true, useUndo:true, /** * Top-level container with controls and file list */ $el: null, /** * Files table */ $table: null, /** * List of rows (table tbody) */ $fileList: null, /** * @type OCA.Files.BreadCrumb */ breadcrumb: null, /** * @type OCA.Files.FileSummary */ fileSummary: null, /** * @type OCA.Files.DetailsView */ _detailsView: null, /** * Whether the file list was initialized already. * @type boolean */ initialized: false, /** * Number of files per page * * @return {int} page size */ pageSize: function() { return Math.ceil(this.$container.height() / 50); }, /** * Array of files in the current folder. * The entries are of file data. * * @type Array.<Object> */ files: [], /** * File actions handler, defaults to OCA.Files.FileActions * @type OCA.Files.FileActions */ fileActions: null, /** * Whether selection is allowed, checkboxes and selection overlay will * be rendered */ _allowSelection: true, /** * Map of file id to file data * @type Object.<int, Object> */ _selectedFiles: {}, /** * Summary of selected files. * @type OCA.Files.FileSummary */ _selectionSummary: null, /** * If not empty, only files containing this string will be shown * @type String */ _filter: '', /** * Sort attribute * @type String */ _sort: 'name', /** * Sort direction: 'asc' or 'desc' * @type String */ _sortDirection: 'asc', /** * Sort comparator function for the current sort * @type Function */ _sortComparator: null, /** * Whether to do a client side sort. * When false, clicking on a table header will call reload(). * When true, clicking on a table header will simply resort the list. */ _clientSideSort: false, /** * Current directory * @type String */ _currentDirectory: null, _dragOptions: null, _folderDropOptions: null, /** * Initialize the file list and its components * * @param $el container element with existing markup for the #controls * and a table * @param options map of options, see other parameters * @param options.scrollContainer scrollable container, defaults to $(window) * @param options.dragOptions drag options, disabled by default * @param options.folderDropOptions folder drop options, disabled by default * @param options.scrollTo name of file to scroll to after the first load * @private */ initialize: function($el, options) { var self = this; options = options || {}; if (this.initialized) { return; } if (options.dragOptions) { this._dragOptions = options.dragOptions; } if (options.folderDropOptions) { this._folderDropOptions = options.folderDropOptions; } this.$el = $el; if (options.id) { this.id = options.id; } this.$container = options.scrollContainer || $(window); this.$table = $el.find('table:first'); this.$fileList = $el.find('#fileList'); this._initFileActions(options.fileActions); this.files = []; this._selectedFiles = {}; this._selectionSummary = new OCA.Files.FileSummary(); this.fileSummary = this._createSummary(); this.setSort('name', 'asc'); var breadcrumbOptions = { onClick: _.bind(this._onClickBreadCrumb, this), getCrumbUrl: function(part) { return self.linkTo(part.dir); } }; // if dropping on folders is allowed, then also allow on breadcrumbs if (this._folderDropOptions) { breadcrumbOptions.onDrop = _.bind(this._onDropOnBreadCrumb, this); } this.breadcrumb = new OCA.Files.BreadCrumb(breadcrumbOptions); if (_.isUndefined(options.detailsViewEnabled) || options.detailsViewEnabled) { this._detailsView = new OCA.Files.DetailsView(); this._detailsView.addDetailView(new OCA.Files.MainFileInfoDetailView({fileList: this, fileActions: this.fileActions})); this._detailsView.$el.insertBefore(this.$el); this._detailsView.$el.addClass('disappear'); this.fileActions.registerAction({ name: 'Details', mime: 'all', permissions: OC.PERMISSION_READ, actionHandler: function(fileName, context) { var fileInfo = self.elementToFile(context.$file); self._updateDetailsView(fileInfo); OC.Apps.showAppSidebar(); } }); } this.$el.find('#controls').prepend(this.breadcrumb.$el); this._renderNewButton(); this.$el.find('thead th .columntitle').click(_.bind(this._onClickHeader, this)); this._onResize = _.debounce(_.bind(this._onResize, this), 100); $(window).resize(this._onResize); this.$el.on('show', this._onResize); this.updateSearch(); this.$el.on('click', function(event) { var $target = $(event.target); // click outside file row ? if (!$target.closest('tbody').length && !$target.closest('#app-sidebar').length) { self._updateDetailsView(null); } }); this.$fileList.on('click','td.filename>a.name', _.bind(this._onClickFile, this)); this.$fileList.on('change', 'td.filename>.selectCheckBox', _.bind(this._onClickFileCheckbox, this)); this.$el.on('urlChanged', _.bind(this._onUrlChanged, this)); this.$el.find('.select-all').click(_.bind(this._onClickSelectAll, this)); this.$el.find('.download').click(_.bind(this._onClickDownloadSelected, this)); this.$el.find('.delete-selected').click(_.bind(this._onClickDeleteSelected, this)); this.$el.find('.selectedActions a').tooltip({placement:'top'}); this.setupUploadEvents(); this.$container.on('scroll', _.bind(this._onScroll, this)); if (options.scrollTo) { this.$fileList.one('updated', function() { self.scrollTo(options.scrollTo); }); } OC.Plugins.attach('OCA.Files.FileList', this); }, /** * Destroy / uninitialize this instance. */ destroy: function() { if (this._newFileMenu) { this._newFileMenu.remove(); } if (this._newButton) { this._newButton.remove(); } // TODO: also unregister other event handlers this.fileActions.off('registerAction', this._onFileActionsUpdated); this.fileActions.off('setDefault', this._onFileActionsUpdated); OC.Plugins.detach('OCA.Files.FileList', this); }, /** * Initializes the file actions, set up listeners. * * @param {OCA.Files.FileActions} fileActions file actions */ _initFileActions: function(fileActions) { this.fileActions = fileActions; if (!this.fileActions) { this.fileActions = new OCA.Files.FileActions(); this.fileActions.registerDefaultActions(); } this._onFileActionsUpdated = _.debounce(_.bind(this._onFileActionsUpdated, this), 100); this.fileActions.on('registerAction', this._onFileActionsUpdated); this.fileActions.on('setDefault', this._onFileActionsUpdated); }, /** * Returns a unique model for the given file name. * * @param {string|object} fileName file name or jquery row * @return {OCA.Files.FileInfoModel} file info model */ getModelForFile: function(fileName) { var self = this; var $tr; // jQuery object ? if (fileName.is) { $tr = fileName; fileName = $tr.attr('data-file'); } else { $tr = this.findFileEl(fileName); } if (!$tr || !$tr.length) { return null; } // if requesting the selected model, return it if (this._currentFileModel && this._currentFileModel.get('name') === fileName) { return this._currentFileModel; } // TODO: note, this is a temporary model required for synchronising // state between different views. // In the future the FileList should work with Backbone.Collection // and contain existing models that can be used. // This method would in the future simply retrieve the matching model from the collection. var model = new OCA.Files.FileInfoModel(this.elementToFile($tr)); if (!model.has('path')) { model.set('path', this.getCurrentDirectory(), {silent: true}); } model.on('change', function(model) { // re-render row var highlightState = $tr.hasClass('highlighted'); $tr = self.updateRow( $tr, _.extend({isPreviewAvailable: true}, model.toJSON()), {updateSummary: true, silent: false, animate: true} ); $tr.toggleClass('highlighted', highlightState); }); model.on('busy', function(model, state) { self.showFileBusyState($tr, state); }); return model; }, /** * Update the details view to display the given file * * @param {string} fileName file name from the current list */ _updateDetailsView: function(fileName) { if (!this._detailsView) { return; } var oldFileInfo = this._detailsView.getFileInfo(); if (oldFileInfo) { // TODO: use more efficient way, maybe track the highlight this.$fileList.children().filterAttr('data-id', '' + oldFileInfo.get('id')).removeClass('highlighted'); oldFileInfo.off('change', this._onSelectedModelChanged, this); } if (!fileName) { this._detailsView.setFileInfo(null); if (this._currentFileModel) { this._currentFileModel.off(); } this._currentFileModel = null; return; } var $tr = this.findFileEl(fileName); var model = this.getModelForFile($tr); this._currentFileModel = model; $tr.addClass('highlighted'); this._detailsView.setFileInfo(model); this._detailsView.$el.scrollTop(0); }, /** * Event handler for when the window size changed */ _onResize: function() { var containerWidth = this.$el.width(); var actionsWidth = 0; $.each(this.$el.find('#controls .actions'), function(index, action) { actionsWidth += $(action).outerWidth(); }); // substract app navigation toggle when visible containerWidth -= $('#app-navigation-toggle').width(); this.breadcrumb.setMaxWidth(containerWidth - actionsWidth - 10); this.updateSearch(); }, /** * Event handler for when the URL changed */ _onUrlChanged: function(e) { if (e && e.dir) { this.changeDirectory(e.dir, false, true); } }, /** * Selected/deselects the given file element and updated * the internal selection cache. * * @param $tr single file row element * @param state true to select, false to deselect */ _selectFileEl: function($tr, state) { var $checkbox = $tr.find('td.filename>.selectCheckBox'); var oldData = !!this._selectedFiles[$tr.data('id')]; var data; $checkbox.prop('checked', state); $tr.toggleClass('selected', state); // already selected ? if (state === oldData) { return; } data = this.elementToFile($tr); if (state) { this._selectedFiles[$tr.data('id')] = data; this._selectionSummary.add(data); } else { delete this._selectedFiles[$tr.data('id')]; this._selectionSummary.remove(data); } if (this._selectionSummary.getTotal() === 1) { this._updateDetailsView(_.values(this._selectedFiles)[0].name); } else { // show nothing when multiple files are selected this._updateDetailsView(null); } this.$el.find('.select-all').prop('checked', this._selectionSummary.getTotal() === this.files.length); }, /** * Event handler for when clicking on files to select them */ _onClickFile: function(event) { var $tr = $(event.target).closest('tr'); if (this._allowSelection && (event.ctrlKey || event.shiftKey)) { event.preventDefault(); if (event.shiftKey) { var $lastTr = $(this._lastChecked); var lastIndex = $lastTr.index(); var currentIndex = $tr.index(); var $rows = this.$fileList.children('tr'); // last clicked checkbox below current one ? if (lastIndex > currentIndex) { var aux = lastIndex; lastIndex = currentIndex; currentIndex = aux; } // auto-select everything in-between for (var i = lastIndex + 1; i < currentIndex; i++) { this._selectFileEl($rows.eq(i), true); } } else { this._lastChecked = $tr; } var $checkbox = $tr.find('td.filename>.selectCheckBox'); this._selectFileEl($tr, !$checkbox.prop('checked')); this.updateSelectionSummary(); } else { // clicked directly on the name if (!this._detailsView || $(event.target).is('.nametext') || $(event.target).closest('.nametext').length) { var filename = $tr.attr('data-file'); var renaming = $tr.data('renaming'); if (!renaming) { this.fileActions.currentFile = $tr.find('td'); var mime = this.fileActions.getCurrentMimeType(); var type = this.fileActions.getCurrentType(); var permissions = this.fileActions.getCurrentPermissions(); var action = this.fileActions.getDefault(mime,type, permissions); if (action) { event.preventDefault(); // also set on global object for legacy apps window.FileActions.currentFile = this.fileActions.currentFile; action(filename, { $file: $tr, fileList: this, fileActions: this.fileActions, dir: $tr.attr('data-path') || this.getCurrentDirectory() }); } // deselect row $(event.target).closest('a').blur(); } } else { this._updateDetailsView($tr.attr('data-file')); event.preventDefault(); } } }, /** * Event handler for when clicking on a file's checkbox */ _onClickFileCheckbox: function(e) { var $tr = $(e.target).closest('tr'); this._selectFileEl($tr, !$tr.hasClass('selected')); this._lastChecked = $tr; this.updateSelectionSummary(); }, /** * Event handler for when selecting/deselecting all files */ _onClickSelectAll: function(e) { var checked = $(e.target).prop('checked'); this.$fileList.find('td.filename>.selectCheckBox').prop('checked', checked) .closest('tr').toggleClass('selected', checked); this._selectedFiles = {}; this._selectionSummary.clear(); if (checked) { for (var i = 0; i < this.files.length; i++) { var fileData = this.files[i]; this._selectedFiles[fileData.id] = fileData; this._selectionSummary.add(fileData); } } this.updateSelectionSummary(); }, /** * Event handler for when clicking on "Download" for the selected files */ _onClickDownloadSelected: function(event) { var files; var dir = this.getCurrentDirectory(); if (this.isAllSelected()) { files = OC.basename(dir); dir = OC.dirname(dir) || '/'; } else { files = _.pluck(this.getSelectedFiles(), 'name'); } var downloadFileaction = $('#selectedActionsList').find('.download'); // don't allow a second click on the download action if(downloadFileaction.hasClass('disabled')) { event.preventDefault(); return; } var disableLoadingState = function(){ OCA.Files.FileActions.updateFileActionSpinner(downloadFileaction, false); }; OCA.Files.FileActions.updateFileActionSpinner(downloadFileaction, true); OCA.Files.Files.handleDownload(this.getDownloadUrl(files, dir), disableLoadingState); return false; }, /** * Event handler for when clicking on "Delete" for the selected files */ _onClickDeleteSelected: function(event) { var files = null; if (!this.isAllSelected()) { files = _.pluck(this.getSelectedFiles(), 'name'); } this.do_delete(files); event.preventDefault(); return false; }, /** * Event handler when clicking on a table header */ _onClickHeader: function(e) { var $target = $(e.target); var sort; if (!$target.is('a')) { $target = $target.closest('a'); } sort = $target.attr('data-sort'); if (sort) { if (this._sort === sort) { this.setSort(sort, (this._sortDirection === 'desc')?'asc':'desc', true); } else { if ( sort === 'name' ) { //default sorting of name is opposite to size and mtime this.setSort(sort, 'asc', true); } else { this.setSort(sort, 'desc', true); } } } }, /** * Event handler when clicking on a bread crumb */ _onClickBreadCrumb: function(e) { var $el = $(e.target).closest('.crumb'), $targetDir = $el.data('dir'); if ($targetDir !== undefined && e.which === 1) { e.preventDefault(); this.changeDirectory($targetDir); this.updateSearch(); } }, /** * Event handler for when scrolling the list container. * This appends/renders the next page of entries when reaching the bottom. */ _onScroll: function(e) { if (this.$container.scrollTop() + this.$container.height() > this.$el.height() - 300) { this._nextPage(true); } }, /** * Event handler when dropping on a breadcrumb */ _onDropOnBreadCrumb: function( event, ui ) { var self = this; var $target = $(event.target); if (!$target.is('.crumb')) { $target = $target.closest('.crumb'); } var targetPath = $(event.target).data('dir'); var dir = this.getCurrentDirectory(); while (dir.substr(0,1) === '/') {//remove extra leading /'s dir = dir.substr(1); } dir = '/' + dir; if (dir.substr(-1,1) !== '/') { dir = dir + '/'; } // do nothing if dragged on current dir if (targetPath === dir || targetPath + '/' === dir) { return; } var files = this.getSelectedFiles(); if (files.length === 0) { // single one selected without checkbox? files = _.map(ui.helper.find('tr'), function(el) { return self.elementToFile($(el)); }); } this.move(_.pluck(files, 'name'), targetPath); }, /** * Sets a new page title */ setPageTitle: function(title){ if (title) { title += ' - '; } else { title = ''; } title += this.appName; // Sets the page title with the " - ownCloud" suffix as in templates window.document.title = title + ' - ' + oc_defaults.title; return true; }, /** * Returns the tr element for a given file name * @param fileName file name */ findFileEl: function(fileName){ // use filterAttr to avoid escaping issues return this.$fileList.find('tr').filterAttr('data-file', fileName); }, /** * Returns the file data from a given file element. * @param $el file tr element * @return file data */ elementToFile: function($el){ $el = $($el); return { id: parseInt($el.attr('data-id'), 10), name: $el.attr('data-file'), mimetype: $el.attr('data-mime'), mtime: parseInt($el.attr('data-mtime'), 10), type: $el.attr('data-type'), size: parseInt($el.attr('data-size'), 10), etag: $el.attr('data-etag'), permissions: parseInt($el.attr('data-permissions'), 10) }; }, /** * Appends the next page of files into the table * @param animate true to animate the new elements * @return array of DOM elements of the newly added files */ _nextPage: function(animate) { var index = this.$fileList.children().length, count = this.pageSize(), hidden, tr, fileData, newTrs = [], isAllSelected = this.isAllSelected(); if (index >= this.files.length) { return false; } while (count > 0 && index < this.files.length) { fileData = this.files[index]; if (this._filter) { hidden = fileData.name.toLowerCase().indexOf(this._filter.toLowerCase()) === -1; } else { hidden = false; } tr = this._renderRow(fileData, {updateSummary: false, silent: true, hidden: hidden}); this.$fileList.append(tr); if (isAllSelected || this._selectedFiles[fileData.id]) { tr.addClass('selected'); tr.find('.selectCheckBox').prop('checked', true); } if (animate) { tr.addClass('appear transparent'); } newTrs.push(tr); index++; count--; } // trigger event for newly added rows if (newTrs.length > 0) { this.$fileList.trigger($.Event('fileActionsReady', {fileList: this, $files: newTrs})); } if (animate) { // defer, for animation window.setTimeout(function() { for (var i = 0; i < newTrs.length; i++ ) { newTrs[i].removeClass('transparent'); } }, 0); } return newTrs; }, /** * Event handler for when file actions were updated. * This will refresh the file actions on the list. */ _onFileActionsUpdated: function() { var self = this; var $files = this.$fileList.find('tr'); if (!$files.length) { return; } $files.each(function() { self.fileActions.display($(this).find('td.filename'), false, self); }); this.$fileList.trigger($.Event('fileActionsReady', {fileList: this, $files: $files})); }, /** * Sets the files to be displayed in the list. * This operation will re-render the list and update the summary. * @param filesArray array of file data (map) */ setFiles: function(filesArray) { var self = this; // detach to make adding multiple rows faster this.files = filesArray; this.$fileList.empty(); // clear "Select all" checkbox this.$el.find('.select-all').prop('checked', false); this.isEmpty = this.files.length === 0; this._nextPage(); this.updateEmptyContent(); this.fileSummary.calculate(filesArray); this._selectedFiles = {}; this._selectionSummary.clear(); this.updateSelectionSummary(); $(window).scrollTop(0); this.$fileList.trigger(jQuery.Event('updated')); _.defer(function() { self.$el.closest('#app-content').trigger(jQuery.Event('apprendered')); }); }, /** * Creates a new table row element using the given file data. * @param {OCA.Files.FileInfo} fileData file info attributes * @param options map of attributes * @return new tr element (not appended to the table) */ _createRow: function(fileData, options) { var td, simpleSize, basename, extension, sizeColor, icon = OC.MimeType.getIconUrl(fileData.mimetype), name = fileData.name, type = fileData.type || 'file', mtime = parseInt(fileData.mtime, 10), mime = fileData.mimetype, path = fileData.path, linkUrl; options = options || {}; if (isNaN(mtime)) { mtime = new Date().getTime() } if (type === 'dir') { mime = mime || 'httpd/unix-directory'; if (fileData.mountType && fileData.mountType.indexOf('external') === 0) { icon = OC.MimeType.getIconUrl('dir-external'); } } //containing tr var tr = $('<tr></tr>').attr({ "data-id" : fileData.id, "data-type": type, "data-size": fileData.size, "data-file": name, "data-mime": mime, "data-mtime": mtime, "data-etag": fileData.etag, "data-permissions": fileData.permissions || this.getDirectoryPermissions() }); if (fileData.mountType) { tr.attr('data-mounttype', fileData.mountType); } if (!_.isUndefined(path)) { tr.attr('data-path', path); } else { path = this.getCurrentDirectory(); } if (type === 'dir') { // use default folder icon icon = icon || OC.imagePath('core', 'filetypes/folder'); } else { icon = icon || OC.imagePath('core', 'filetypes/file'); } // filename td td = $('<td class="filename"></td>'); // linkUrl if (type === 'dir') { linkUrl = this.linkTo(path + '/' + name); } else { linkUrl = this.getDownloadUrl(name, path); } if (this._allowSelection) { td.append( '<input id="select-' + this.id + '-' + fileData.id + '" type="checkbox" class="selectCheckBox"/><label for="select-' + this.id + '-' + fileData.id + '">' + '<div class="thumbnail" style="background-image:url(' + icon + '); background-size: 32px;"></div>' + '<span class="hidden-visually">' + t('files', 'Select') + '</span>' + '</label>' ); } else { td.append('<div class="thumbnail" style="background-image:url(' + icon + '); background-size: 32px;"></div>'); } var linkElem = $('<a></a>').attr({ "class": "name", "href": linkUrl }); // from here work on the display name name = fileData.displayName || name; // show hidden files (starting with a dot) completely in gray if(name.indexOf('.') === 0) { basename = ''; extension = name; // split extension from filename for non dirs } else if (type !== 'dir' && name.indexOf('.') !== -1) { basename = name.substr(0, name.lastIndexOf('.')); extension = name.substr(name.lastIndexOf('.')); } else { basename = name; extension = false; } var nameSpan=$('<span></span>').addClass('nametext'); var innernameSpan = $('<span></span>').addClass('innernametext').text(basename); nameSpan.append(innernameSpan); linkElem.append(nameSpan); if (extension) { nameSpan.append($('<span></span>').addClass('extension').text(extension)); } if (fileData.extraData) { if (fileData.extraData.charAt(0) === '/') { fileData.extraData = fileData.extraData.substr(1); } nameSpan.addClass('extra-data').attr('title', fileData.extraData); nameSpan.tooltip({placement: 'right'}); } // dirs can show the number of uploaded files if (type === 'dir') { linkElem.append($('<span></span>').attr({ 'class': 'uploadtext', 'currentUploads': 0 })); } td.append(linkElem); tr.append(td); // size column if (typeof(fileData.size) !== 'undefined' && fileData.size >= 0) { simpleSize = humanFileSize(parseInt(fileData.size, 10), true); sizeColor = Math.round(160-Math.pow((fileData.size/(1024*1024)),2)); } else { simpleSize = t('files', 'Pending'); } td = $('<td></td>').attr({ "class": "filesize", "style": 'color:rgb(' + sizeColor + ',' + sizeColor + ',' + sizeColor + ')' }).text(simpleSize); tr.append(td); // date column (1000 milliseconds to seconds, 60 seconds, 60 minutes, 24 hours) // difference in days multiplied by 5 - brightest shade for files older than 32 days (160/5) var modifiedColor = Math.round(((new Date()).getTime() - mtime )/1000/60/60/24*5 ); // ensure that the brightest color is still readable if (modifiedColor >= '160') { modifiedColor = 160; } var formatted; var text; if (mtime > 0) { formatted = OC.Util.formatDate(mtime); text = OC.Util.relativeModifiedDate(mtime); } else { formatted = t('files', 'Unable to determine date'); text = '?'; } td = $('<td></td>').attr({ "class": "date" }); td.append($('<span></span>').attr({ "class": "modified", "title": formatted, "style": 'color:rgb('+modifiedColor+','+modifiedColor+','+modifiedColor+')' }).text(text) .tooltip({placement: 'top'}) ); tr.find('.filesize').text(simpleSize); tr.append(td); return tr; }, /** * Adds an entry to the files array and also into the DOM * in a sorted manner. * * @param {OCA.Files.FileInfo} fileData map of file attributes * @param {Object} [options] map of attributes * @param {boolean} [options.updateSummary] true to update the summary * after adding (default), false otherwise. Defaults to true. * @param {boolean} [options.silent] true to prevent firing events like "fileActionsReady", * defaults to false. * @param {boolean} [options.animate] true to animate the thumbnail image after load * defaults to true. * @return new tr element (not appended to the table) */ add: function(fileData, options) { var index = -1; var $tr; var $rows; var $insertionPoint; options = _.extend({animate: true}, options || {}); // there are three situations to cover: // 1) insertion point is visible on the current page // 2) insertion point is on a not visible page (visible after scrolling) // 3) insertion point is at the end of the list $rows = this.$fileList.children(); index = this._findInsertionIndex(fileData); if (index > this.files.length) { index = this.files.length; } else { $insertionPoint = $rows.eq(index); } // is the insertion point visible ? if ($insertionPoint.length) { // only render if it will really be inserted $tr = this._renderRow(fileData, options); $insertionPoint.before($tr); } else { // if insertion point is after the last visible // entry, append if (index === $rows.length) { $tr = this._renderRow(fileData, options); this.$fileList.append($tr); } } this.isEmpty = false; this.files.splice(index, 0, fileData); if ($tr && options.animate) { $tr.addClass('appear transparent'); window.setTimeout(function() { $tr.removeClass('transparent'); }); } if (options.scrollTo) { this.scrollTo(fileData.name); } // defaults to true if not defined if (typeof(options.updateSummary) === 'undefined' || !!options.updateSummary) { this.fileSummary.add(fileData, true); this.updateEmptyContent(); } return $tr; }, /** * Creates a new row element based on the given attributes * and returns it. * * @param {OCA.Files.FileInfo} fileData map of file attributes * @param {Object} [options] map of attributes * @param {int} [options.index] index at which to insert the element * @param {boolean} [options.updateSummary] true to update the summary * after adding (default), false otherwise. Defaults to true. * @param {boolean} [options.animate] true to animate the thumbnail image after load * defaults to true. * @return new tr element (not appended to the table) */ _renderRow: function(fileData, options) { options = options || {}; var type = fileData.type || 'file', mime = fileData.mimetype, path = fileData.path || this.getCurrentDirectory(), permissions = parseInt(fileData.permissions, 10) || 0; if (fileData.isShareMountPoint) { permissions = permissions | OC.PERMISSION_UPDATE; } if (type === 'dir') { mime = mime || 'httpd/unix-directory'; } var tr = this._createRow( fileData, options ); var filenameTd = tr.find('td.filename'); // TODO: move dragging to FileActions ? // enable drag only for deletable files if (this._dragOptions && permissions & OC.PERMISSION_DELETE) { filenameTd.draggable(this._dragOptions); } // allow dropping on folders if (this._folderDropOptions && fileData.type === 'dir') { filenameTd.droppable(this._folderDropOptions); } if (options.hidden) { tr.addClass('hidden'); } // display actions this.fileActions.display(filenameTd, !options.silent, this); if (fileData.isPreviewAvailable) { var iconDiv = filenameTd.find('.thumbnail'); // lazy load / newly inserted td ? // the typeof check ensures that the default value of animate is true if (typeof(options.animate) === 'undefined' || !!options.animate) { this.lazyLoadPreview({ path: path + '/' + fileData.name, mime: mime, etag: fileData.etag, callback: function(url) { iconDiv.css('background-image', 'url("' + url + '")'); } }); } else { // set the preview URL directly var urlSpec = { file: path + '/' + fileData.name, c: fileData.etag }; var previewUrl = this.generatePreviewUrl(urlSpec); previewUrl = previewUrl.replace('(', '%28').replace(')', '%29'); iconDiv.css('background-image', 'url("' + previewUrl + '")'); } } return tr; }, /** * Returns the current directory * @method getCurrentDirectory * @return current directory */ getCurrentDirectory: function(){ return this._currentDirectory || this.$el.find('#dir').val() || '/'; }, /** * Returns the directory permissions * @return permission value as integer */ getDirectoryPermissions: function() { return parseInt(this.$el.find('#permissions').val(), 10); }, /** * @brief Changes the current directory and reload the file list. * @param targetDir target directory (non URL encoded) * @param changeUrl false if the URL must not be changed (defaults to true) * @param {boolean} force set to true to force changing directory */ changeDirectory: function(targetDir, changeUrl, force) { var self = this; var currentDir = this.getCurrentDirectory(); targetDir = targetDir || '/'; if (!force && currentDir === targetDir) { return; } this._setCurrentDir(targetDir, changeUrl); this.reload().then(function(success){ if (!success) { self.changeDirectory(currentDir, true); } }); }, linkTo: function(dir) { return OC.linkTo('files', 'index.php')+"?dir="+ encodeURIComponent(dir).replace(/%2F/g, '/'); }, /** * Sets the current directory name and updates the breadcrumb. * @param targetDir directory to display * @param changeUrl true to also update the URL, false otherwise (default) */ _setCurrentDir: function(targetDir, changeUrl) { targetDir = targetDir.replace(/\\/g, '/'); var previousDir = this.getCurrentDirectory(), baseDir = OC.basename(targetDir); if (baseDir !== '') { this.setPageTitle(baseDir); } else { this.setPageTitle(); } this._currentDirectory = targetDir; // legacy stuff this.$el.find('#dir').val(targetDir); if (changeUrl !== false) { this.$el.trigger(jQuery.Event('changeDirectory', { dir: targetDir, previousDir: previousDir })); } this.breadcrumb.setDirectory(this.getCurrentDirectory()); }, /** * Sets the current sorting and refreshes the list * * @param sort sort attribute name * @param direction sort direction, one of "asc" or "desc" * @param update true to update the list, false otherwise (default) */ setSort: function(sort, direction, update) { var comparator = FileList.Comparators[sort] || FileList.Comparators.name; this._sort = sort; this._sortDirection = (direction === 'desc')?'desc':'asc'; this._sortComparator = comparator; if (direction === 'desc') { this._sortComparator = function(fileInfo1, fileInfo2) { return -comparator(fileInfo1, fileInfo2); }; } this.$el.find('thead th .sort-indicator') .removeClass(this.SORT_INDICATOR_ASC_CLASS) .removeClass(this.SORT_INDICATOR_DESC_CLASS) .toggleClass('hidden', true) .addClass(this.SORT_INDICATOR_DESC_CLASS); this.$el.find('thead th.column-' + sort + ' .sort-indicator') .removeClass(this.SORT_INDICATOR_ASC_CLASS) .removeClass(this.SORT_INDICATOR_DESC_CLASS) .toggleClass('hidden', false) .addClass(direction === 'desc' ? this.SORT_INDICATOR_DESC_CLASS : this.SORT_INDICATOR_ASC_CLASS); if (update) { if (this._clientSideSort) { this.files.sort(this._sortComparator); this.setFiles(this.files); } else { this.reload(); } } }, /** * Reloads the file list using ajax call * * @return ajax call object */ reload: function() { this._selectedFiles = {}; this._selectionSummary.clear(); if (this._currentFileModel) { this._currentFileModel.off(); } this._currentFileModel = null; this.$el.find('.select-all').prop('checked', false); this.showMask(); if (this._reloadCall) { this._reloadCall.abort(); } this._reloadCall = $.ajax({ url: this.getAjaxUrl('list'), data: { dir : this.getCurrentDirectory(), sort: this._sort, sortdirection: this._sortDirection } }); // close sidebar this._updateDetailsView(null); var callBack = this.reloadCallback.bind(this); return this._reloadCall.then(callBack, callBack); }, reloadCallback: function(result) { delete this._reloadCall; this.hideMask(); if (!result || result.status === 'error') { // if the error is not related to folder we're trying to load, reload the page to handle logout etc if (result.data.error === 'authentication_error' || result.data.error === 'token_expired' || result.data.error === 'application_not_enabled' ) { OC.redirect(OC.generateUrl('apps/files')); } OC.Notification.show(result.data.message); return false; } // Firewall Blocked request? if (result.status === 403) { // Go home this.changeDirectory('/'); OC.Notification.show(t('files', 'This operation is forbidden')); return false; } // Did share service die or something else fail? if (result.status === 500) { // Go home this.changeDirectory('/'); OC.Notification.show(t('files', 'This directory is unavailable, please check the logs or contact the administrator')); return false; } if (result.status === 404) { // go back home this.changeDirectory('/'); return false; } // aborted ? if (result.status === 0){ return true; } // TODO: should rather return upload file size through // the files list ajax call this.updateStorageStatistics(true); if (result.data.permissions) { this.setDirectoryPermissions(result.data.permissions); } this.setFiles(result.data.files); return true; }, updateStorageStatistics: function(force) { OCA.Files.Files.updateStorageStatistics(this.getCurrentDirectory(), force); }, getAjaxUrl: function(action, params) { return OCA.Files.Files.getAjaxUrl(action, params); }, getDownloadUrl: function(files, dir) { return OCA.Files.Files.getDownloadUrl(files, dir || this.getCurrentDirectory()); }, /** * Generates a preview URL based on the URL space. * @param urlSpec attributes for the URL * @param {int} urlSpec.x width * @param {int} urlSpec.y height * @param {String} urlSpec.file path to the file * @return preview URL */ generatePreviewUrl: function(urlSpec) { urlSpec = urlSpec || {}; if (!urlSpec.x) { urlSpec.x = this.$table.data('preview-x') || 36; } if (!urlSpec.y) { urlSpec.y = this.$table.data('preview-y') || 36; } urlSpec.x *= window.devicePixelRatio; urlSpec.y *= window.devicePixelRatio; urlSpec.x = Math.floor(urlSpec.x); urlSpec.y = Math.floor(urlSpec.y); urlSpec.forceIcon = 0; return OC.generateUrl('/core/preview.png?') + $.param(urlSpec); }, /** * Lazy load a file's preview. * * @param path path of the file * @param mime mime type * @param callback callback function to call when the image was loaded * @param etag file etag (for caching) */ lazyLoadPreview : function(options) { var self = this; var path = options.path; var mime = options.mime; var ready = options.callback; var etag = options.etag; // get mime icon url var iconURL = OC.MimeType.getIconUrl(mime); var previewURL, urlSpec = {}; ready(iconURL); // set mimeicon URL urlSpec.file = OCA.Files.Files.fixPath(path); if (options.x) { urlSpec.x = options.x; } if (options.y) { urlSpec.y = options.y; } if (options.a) { urlSpec.a = options.a; } if (options.mode) { urlSpec.mode = options.mode; } if (etag){ // use etag as cache buster urlSpec.c = etag; } else { console.warn('OCA.Files.FileList.lazyLoadPreview(): missing etag argument'); } previewURL = self.generatePreviewUrl(urlSpec); previewURL = previewURL.replace('(', '%28'); previewURL = previewURL.replace(')', '%29'); // preload image to prevent delay // this will make the browser cache the image var img = new Image(); img.onload = function(){ // if loading the preview image failed (no preview for the mimetype) then img.width will < 5 if (img.width > 5) { ready(previewURL, img); } else if (options.error) { options.error(); } }; if (options.error) { img.onerror = options.error; } img.src = previewURL; }, setDirectoryPermissions: function(permissions) { var isCreatable = (permissions & OC.PERMISSION_CREATE) !== 0; this.$el.find('#permissions').val(permissions); this.$el.find('.creatable').toggleClass('hidden', !isCreatable); this.$el.find('.notCreatable').toggleClass('hidden', isCreatable); }, /** * Shows/hides action buttons * * @param show true for enabling, false for disabling */ showActions: function(show){ this.$el.find('.actions,#file_action_panel').toggleClass('hidden', !show); if (show){ // make sure to display according to permissions var permissions = this.getDirectoryPermissions(); var isCreatable = (permissions & OC.PERMISSION_CREATE) !== 0; this.$el.find('.creatable').toggleClass('hidden', !isCreatable); this.$el.find('.notCreatable').toggleClass('hidden', isCreatable); // remove old style breadcrumbs (some apps might create them) this.$el.find('#controls .crumb').remove(); // refresh breadcrumbs in case it was replaced by an app this.breadcrumb.render(); } else{ this.$el.find('.creatable, .notCreatable').addClass('hidden'); } }, /** * Enables/disables viewer mode. * In viewer mode, apps can embed themselves under the controls bar. * In viewer mode, the actions of the file list will be hidden. * @param show true for enabling, false for disabling */ setViewerMode: function(show){ this.showActions(!show); this.$el.find('#filestable').toggleClass('hidden', show); this.$el.trigger(new $.Event('changeViewerMode', {viewerModeEnabled: show})); }, /** * Removes a file entry from the list * @param name name of the file to remove * @param {Object} [options] map of attributes * @param {boolean} [options.updateSummary] true to update the summary * after removing, false otherwise. Defaults to true. * @return deleted element */ remove: function(name, options){ options = options || {}; var fileEl = this.findFileEl(name); var index = fileEl.index(); if (!fileEl.length) { return null; } if (this._selectedFiles[fileEl.data('id')]) { // remove from selection first this._selectFileEl(fileEl, false); this.updateSelectionSummary(); } if (this._dragOptions && (fileEl.data('permissions') & OC.PERMISSION_DELETE)) { // file is only draggable when delete permissions are set fileEl.find('td.filename').draggable('destroy'); } this.files.splice(index, 1); fileEl.remove(); // TODO: improve performance on batch update this.isEmpty = !this.files.length; if (typeof(options.updateSummary) === 'undefined' || !!options.updateSummary) { this.updateEmptyContent(); this.fileSummary.remove({type: fileEl.attr('data-type'), size: fileEl.attr('data-size')}, true); } var lastIndex = this.$fileList.children().length; // if there are less elements visible than one page // but there are still pending elements in the array, // then directly append the next page if (lastIndex < this.files.length && lastIndex < this.pageSize()) { this._nextPage(true); } return fileEl; }, /** * Finds the index of the row before which the given * fileData should be inserted, considering the current * sorting * * @param {OCA.Files.FileInfo} fileData file info */ _findInsertionIndex: function(fileData) { var index = 0; while (index < this.files.length && this._sortComparator(fileData, this.files[index]) > 0) { index++; } return index; }, /** * Moves a file to a given target folder. * * @param fileNames array of file names to move * @param targetPath absolute target path */ move: function(fileNames, targetPath) { var self = this; var dir = this.getCurrentDirectory(); var target = OC.basename(targetPath); if (!_.isArray(fileNames)) { fileNames = [fileNames]; } _.each(fileNames, function(fileName) { var $tr = self.findFileEl(fileName); self.showFileBusyState($tr, true); // TODO: improve performance by sending all file names in a single call $.post( OC.filePath('files', 'ajax', 'move.php'), { dir: dir, file: fileName, target: targetPath }, function(result) { if (result) { if (result.status === 'success') { // if still viewing the same directory if (self.getCurrentDirectory() === dir) { // recalculate folder size var oldFile = self.findFileEl(target); var newFile = self.findFileEl(fileName); var oldSize = oldFile.data('size'); var newSize = oldSize + newFile.data('size'); oldFile.data('size', newSize); oldFile.find('td.filesize').text(OC.Util.humanFileSize(newSize)); // TODO: also update entry in FileList.files self.remove(fileName); } } else { OC.Notification.hide(); if (result.status === 'error' && result.data.message) { OC.Notification.show(result.data.message); } else { OC.Notification.show(t('files', 'Error moving file.')); } // hide notification after 10 sec setTimeout(function() { OC.Notification.hide(); }, 10000); } } else { OC.dialogs.alert(t('files', 'Error moving file'), t('files', 'Error')); } self.showFileBusyState($tr, false); } ); }); }, /** * Updates the given row with the given file info * * @param {Object} $tr row element * @param {OCA.Files.FileInfo} fileInfo file info * @param {Object} options options * * @return {Object} new row element */ updateRow: function($tr, fileInfo, options) { this.files.splice($tr.index(), 1); $tr.remove(); $tr = this.add(fileInfo, _.extend({updateSummary: false, silent: true}, options)); this.$fileList.trigger($.Event('fileActionsReady', {fileList: this, $files: $tr})); return $tr; }, /** * Triggers file rename input field for the given file name. * If the user enters a new name, the file will be renamed. * * @param oldname file name of the file to rename */ rename: function(oldname) { var self = this; var tr, td, input, form; tr = this.findFileEl(oldname); var oldFileInfo = this.files[tr.index()]; tr.data('renaming',true); td = tr.children('td.filename'); input = $('<input type="text" class="filename"/>').val(oldname); form = $('<form></form>'); form.append(input); td.children('a.name').hide(); td.append(form); input.focus(); //preselect input var len = input.val().lastIndexOf('.'); if ( len === -1 || tr.data('type') === 'dir' ) { len = input.val().length; } input.selectRange(0, len); var checkInput = function () { var filename = input.val(); if (filename !== oldname) { // Files.isFileNameValid(filename) throws an exception itself OCA.Files.Files.isFileNameValid(filename); if (self.inList(filename)) { throw t('files', '{new_name} already exists', {new_name: filename}); } } return true; }; function restore() { input.tooltip('hide'); tr.data('renaming',false); form.remove(); td.children('a.name').show(); } form.submit(function(event) { event.stopPropagation(); event.preventDefault(); if (input.hasClass('error')) { return; } try { var newName = input.val(); input.tooltip('hide'); form.remove(); if (newName !== oldname) { checkInput(); // mark as loading (temp element) self.showFileBusyState(tr, true); tr.attr('data-file', newName); var basename = newName; if (newName.indexOf('.') > 0 && tr.data('type') !== 'dir') { basename = newName.substr(0, newName.lastIndexOf('.')); } td.find('a.name span.nametext').text(basename); td.children('a.name').show(); $.ajax({ url: OC.filePath('files','ajax','rename.php'), data: { dir : tr.attr('data-path') || self.getCurrentDirectory(), newname: newName, file: oldname }, success: function(result) { var fileInfo; if (!result || result.status === 'error') { OC.dialogs.alert(result.data.message, t('files', 'Could not rename file')); fileInfo = oldFileInfo; if (result.data.code === 'sourcenotfound') { self.remove(result.data.newname, {updateSummary: true}); return; } } else { fileInfo = result.data; } // reinsert row self.files.splice(tr.index(), 1); tr.remove(); tr = self.add(fileInfo, {updateSummary: false, silent: true}); self.$fileList.trigger($.Event('fileActionsReady', {fileList: self, $files: $(tr)})); self._updateDetailsView(fileInfo.name); } }); } else { // add back the old file info when cancelled self.files.splice(tr.index(), 1); tr.remove(); tr = self.add(oldFileInfo, {updateSummary: false, silent: true}); self.$fileList.trigger($.Event('fileActionsReady', {fileList: self, $files: $(tr)})); } } catch (error) { input.attr('title', error); input.tooltip({placement: 'left', trigger: 'manual'}); input.tooltip('show'); input.addClass('error'); } return false; }); input.keyup(function(event) { // verify filename on typing try { checkInput(); input.tooltip('hide'); input.removeClass('error'); } catch (error) { input.attr('title', error); input.tooltip({placement: 'left', trigger: 'manual'}); input.tooltip('show'); input.addClass('error'); } if (event.keyCode === 27) { restore(); } }); input.click(function(event) { event.stopPropagation(); event.preventDefault(); }); input.blur(function() { form.trigger('submit'); }); }, /** * Create an empty file inside the current directory. * * @param {string} name name of the file * * @return {Promise} promise that will be resolved after the * file was created * * @since 8.2 */ createFile: function(name) { var self = this; var deferred = $.Deferred(); var promise = deferred.promise(); OCA.Files.Files.isFileNameValid(name); name = this.getUniqueName(name); if (this.lastAction) { this.lastAction(); } $.post( OC.generateUrl('/apps/files/ajax/newfile.php'), { dir: this.getCurrentDirectory(), filename: name }, function(result) { if (result.status === 'success') { self.add(result.data, {animate: true, scrollTo: true}); deferred.resolve(result.status, result.data); } else { if (result.data && result.data.message) { OC.Notification.showTemporary(result.data.message); } else { OC.Notification.showTemporary(t('core', 'Could not create file')); } deferred.reject(result.status, result.data); } } ); return promise; }, /** * Create a directory inside the current directory. * * @param {string} name name of the directory * * @return {Promise} promise that will be resolved after the * directory was created * * @since 8.2 */ createDirectory: function(name) { var self = this; var deferred = $.Deferred(); var promise = deferred.promise(); OCA.Files.Files.isFileNameValid(name); name = this.getUniqueName(name); if (this.lastAction) { this.lastAction(); } $.post( OC.generateUrl('/apps/files/ajax/newfolder.php'), { dir: this.getCurrentDirectory(), foldername: name }, function(result) { if (result.status === 'success') { self.add(result.data, {animate: true, scrollTo: true}); deferred.resolve(result.status, result.data); } else { if (result.data && result.data.message) { OC.Notification.showTemporary(result.data.message); } else { OC.Notification.showTemporary(t('core', 'Could not create folder')); } deferred.reject(result.status); } } ); return promise; }, /** * Returns whether the given file name exists in the list * * @param {string} file file name * * @return {bool} true if the file exists in the list, false otherwise */ inList:function(file) { return this.findFileEl(file).length; }, /** * Shows busy state on a given file row or multiple * * @param {string|Array.<string>} files file name or array of file names * @param {bool} [busy=true] busy state, true for busy, false to remove busy state * * @since 8.2 */ showFileBusyState: function(files, state) { var self = this; if (!_.isArray(files)) { files = [files]; } if (_.isUndefined(state)) { state = true; } _.each(files, function($tr) { // jquery element already ? if (!$tr.is) { $tr = self.findFileEl($tr); } var $thumbEl = $tr.find('.thumbnail'); $tr.toggleClass('busy', state); if (state) { $thumbEl.attr('data-oldimage', $thumbEl.css('background-image')); $thumbEl.css('background-image', 'url('+ OC.imagePath('core', 'loading.gif') + ')'); } else { $thumbEl.css('background-image', $thumbEl.attr('data-oldimage')); $thumbEl.removeAttr('data-oldimage'); } }); }, /** * Delete the given files from the given dir * @param files file names list (without path) * @param dir directory in which to delete the files, defaults to the current * directory */ do_delete:function(files, dir) { var self = this; var params; if (files && files.substr) { files=[files]; } if (files) { this.showFileBusyState(files, true); for (var i=0; i<files.length; i++) { } } // Finish any existing actions if (this.lastAction) { this.lastAction(); } params = { dir: dir || this.getCurrentDirectory() }; if (files) { params.files = JSON.stringify(files); } else { // no files passed, delete all in current dir params.allfiles = true; // show spinner for all files this.showFileBusyState(this.$fileList.find('tr'), true); } $.post(OC.filePath('files', 'ajax', 'delete.php'), params, function(result) { if (result.status === 'success') { if (params.allfiles) { self.setFiles([]); } else { $.each(files,function(index,file) { var fileEl = self.remove(file, {updateSummary: false}); // FIXME: not sure why we need this after the // element isn't even in the DOM any more fileEl.find('.selectCheckBox').prop('checked', false); fileEl.removeClass('selected'); self.fileSummary.remove({type: fileEl.attr('data-type'), size: fileEl.attr('data-size')}); }); } // TODO: this info should be returned by the ajax call! self.updateEmptyContent(); self.fileSummary.update(); self.updateSelectionSummary(); self.updateStorageStatistics(); } else { if (result.status === 'error' && result.data.message) { OC.Notification.show(result.data.message); } else { OC.Notification.show(t('files', 'Error deleting file.')); } // hide notification after 10 sec setTimeout(function() { OC.Notification.hide(); }, 10000); if (params.allfiles) { // reload the page as we don't know what files were deleted // and which ones remain self.reload(); } else { $.each(files,function(index,file) { self.showFileBusyState(file, false); }); } } }); }, /** * Creates the file summary section */ _createSummary: function() { var $tr = $('<tr class="summary"></tr>'); this.$el.find('tfoot').append($tr); return new OCA.Files.FileSummary($tr); }, updateEmptyContent: function() { var permissions = this.getDirectoryPermissions(); var isCreatable = (permissions & OC.PERMISSION_CREATE) !== 0; this.$el.find('#emptycontent').toggleClass('hidden', !this.isEmpty); this.$el.find('#emptycontent .uploadmessage').toggleClass('hidden', !isCreatable || !this.isEmpty); this.$el.find('#filestable thead th').toggleClass('hidden', this.isEmpty); }, /** * Shows the loading mask. * * @see OCA.Files.FileList#hideMask */ showMask: function() { // in case one was shown before var $mask = this.$el.find('.mask'); if ($mask.exists()) { return; } this.$table.addClass('hidden'); this.$el.find('#emptycontent').addClass('hidden'); $mask = $('<div class="mask transparent"></div>'); $mask.css('background-image', 'url('+ OC.imagePath('core', 'loading.gif') + ')'); $mask.css('background-repeat', 'no-repeat'); this.$el.append($mask); $mask.removeClass('transparent'); }, /** * Hide the loading mask. * @see OCA.Files.FileList#showMask */ hideMask: function() { this.$el.find('.mask').remove(); this.$table.removeClass('hidden'); }, scrollTo:function(file) { if (!_.isArray(file)) { file = [file]; } this.highlightFiles(file, function($tr) { $tr.addClass('searchresult'); $tr.one('hover', function() { $tr.removeClass('searchresult'); }); }); }, /** * @deprecated use setFilter(filter) */ filter:function(query) { this.setFilter(''); }, /** * @deprecated use setFilter('') */ unfilter:function() { this.setFilter(''); }, /** * hide files matching the given filter * @param filter */ setFilter:function(filter) { this._filter = filter; this.fileSummary.setFilter(filter, this.files); if (!this.$el.find('.mask').exists()) { this.hideIrrelevantUIWhenNoFilesMatch(); } var that = this; this.$fileList.find('tr').each(function(i,e) { var $e = $(e); if ($e.data('file').toString().toLowerCase().indexOf(filter.toLowerCase()) === -1) { $e.addClass('hidden'); that.$container.trigger('scroll'); } else { $e.removeClass('hidden'); } }); }, hideIrrelevantUIWhenNoFilesMatch:function() { if (this._filter && this.fileSummary.summary.totalDirs + this.fileSummary.summary.totalFiles === 0) { this.$el.find('#filestable thead th').addClass('hidden'); this.$el.find('#emptycontent').addClass('hidden'); $('#searchresults').addClass('filter-empty'); if ( $('#searchresults').length === 0 || $('#searchresults').hasClass('hidden') ) { this.$el.find('.nofilterresults').removeClass('hidden'). find('p').text(t('files', "No entries in this folder match '{filter}'", {filter:this._filter}, null, {'escape': false})); } } else { $('#searchresults').removeClass('filter-empty'); this.$el.find('#filestable thead th').toggleClass('hidden', this.isEmpty); if (!this.$el.find('.mask').exists()) { this.$el.find('#emptycontent').toggleClass('hidden', !this.isEmpty); } this.$el.find('.nofilterresults').addClass('hidden'); } }, /** * get the current filter * @param filter */ getFilter:function(filter) { return this._filter; }, /** * update the search object to use this filelist when filtering */ updateSearch:function() { if (OCA.Search.files) { OCA.Search.files.setFileList(this); } if (OC.Search) { OC.Search.clear(); } }, /** * Update UI based on the current selection */ updateSelectionSummary: function() { var summary = this._selectionSummary.summary; var canDelete; var selection; if (summary.totalFiles === 0 && summary.totalDirs === 0) { this.$el.find('#headerName a.name>span:first').text(t('files','Name')); this.$el.find('#headerSize a>span:first').text(t('files','Size')); this.$el.find('#modified a>span:first').text(t('files','Modified')); this.$el.find('table').removeClass('multiselect'); this.$el.find('.selectedActions').addClass('hidden'); } else { canDelete = (this.getDirectoryPermissions() & OC.PERMISSION_DELETE) && this.isSelectedDeletable(); this.$el.find('.selectedActions').removeClass('hidden'); this.$el.find('#headerSize a>span:first').text(OC.Util.humanFileSize(summary.totalSize)); var directoryInfo = n('files', '%n folder', '%n folders', summary.totalDirs); var fileInfo = n('files', '%n file', '%n files', summary.totalFiles); if (summary.totalDirs > 0 && summary.totalFiles > 0) { var selectionVars = { dirs: directoryInfo, files: fileInfo }; selection = t('files', '{dirs} and {files}', selectionVars); } else if (summary.totalDirs > 0) { selection = directoryInfo; } else { selection = fileInfo; } this.$el.find('#headerName a.name>span:first').text(selection); this.$el.find('#modified a>span:first').text(''); this.$el.find('table').addClass('multiselect'); this.$el.find('.delete-selected').toggleClass('hidden', !canDelete); } }, /** * Check whether all selected files are deletable */ isSelectedDeletable: function() { return _.reduce(this.getSelectedFiles(), function(deletable, file) { return deletable && (file.permissions & OC.PERMISSION_DELETE); }, true); }, /** * Returns whether all files are selected * @return true if all files are selected, false otherwise */ isAllSelected: function() { return this.$el.find('.select-all').prop('checked'); }, /** * Returns the file info of the selected files * * @return array of file names */ getSelectedFiles: function() { return _.values(this._selectedFiles); }, getUniqueName: function(name) { if (this.findFileEl(name).exists()) { var numMatch; var parts=name.split('.'); var extension = ""; if (parts.length > 1) { extension=parts.pop(); } var base=parts.join('.'); numMatch=base.match(/\((\d+)\)/); var num=2; if (numMatch && numMatch.length>0) { num=parseInt(numMatch[numMatch.length-1], 10)+1; base=base.split('('); base.pop(); base=$.trim(base.join('(')); } name=base+' ('+num+')'; if (extension) { name = name+'.'+extension; } // FIXME: ugly recursion return this.getUniqueName(name); } return name; }, /** * Shows a "permission denied" notification */ _showPermissionDeniedNotification: function() { var message = t('core', 'You don’t have permission to upload or create files here'); OC.Notification.show(message); //hide notification after 10 sec setTimeout(function() { OC.Notification.hide(); }, 5000); }, /** * Setup file upload events related to the file-upload plugin */ setupUploadEvents: function() { var self = this; // handle upload events var fileUploadStart = this.$el.find('#file_upload_start'); // detect the progress bar resize fileUploadStart.on('resized', this._onResize); fileUploadStart.on('fileuploaddrop', function(e, data) { OC.Upload.log('filelist handle fileuploaddrop', e, data); if (self.$el.hasClass('hidden')) { // do not upload to invisible lists return false; } var dropTarget = $(e.originalEvent.target); // check if dropped inside this container and not another one if (dropTarget.length && !self.$el.is(dropTarget) // dropped on list directly && !self.$el.has(dropTarget).length // dropped inside list && !dropTarget.is(self.$container) // dropped on main container ) { return false; } // find the closest tr or crumb to use as target dropTarget = dropTarget.closest('tr, .crumb'); // if dropping on tr or crumb, drag&drop upload to folder if (dropTarget && (dropTarget.data('type') === 'dir' || dropTarget.hasClass('crumb'))) { // remember as context data.context = dropTarget; // if permissions are specified, only allow if create permission is there var permissions = dropTarget.data('permissions'); if (!_.isUndefined(permissions) && (permissions & OC.PERMISSION_CREATE) === 0) { self._showPermissionDeniedNotification(); return false; } var dir = dropTarget.data('file'); // if from file list, need to prepend parent dir if (dir) { var parentDir = self.getCurrentDirectory(); if (parentDir[parentDir.length - 1] !== '/') { parentDir += '/'; } dir = parentDir + dir; } else{ // read full path from crumb dir = dropTarget.data('dir') || '/'; } // add target dir data.targetDir = dir; } else { // we are dropping somewhere inside the file list, which will // upload the file to the current directory data.targetDir = self.getCurrentDirectory(); // cancel uploads to current dir if no permission var isCreatable = (self.getDirectoryPermissions() & OC.PERMISSION_CREATE) !== 0; if (!isCreatable) { self._showPermissionDeniedNotification(); return false; } } }); fileUploadStart.on('fileuploadadd', function(e, data) { OC.Upload.log('filelist handle fileuploadadd', e, data); //finish delete if we are uploading a deleted file if (self.deleteFiles && self.deleteFiles.indexOf(data.files[0].name)!==-1) { self.finishDelete(null, true); //delete file before continuing } // add ui visualization to existing folder if (data.context && data.context.data('type') === 'dir') { // add to existing folder // update upload counter ui var uploadText = data.context.find('.uploadtext'); var currentUploads = parseInt(uploadText.attr('currentUploads'), 10); currentUploads += 1; uploadText.attr('currentUploads', currentUploads); var translatedText = n('files', 'Uploading %n file', 'Uploading %n files', currentUploads); if (currentUploads === 1) { var img = OC.imagePath('core', 'loading.gif'); data.context.find('.thumbnail').css('background-image', 'url(' + img + ')'); uploadText.text(translatedText); uploadText.show(); } else { uploadText.text(translatedText); } } }); /* * when file upload done successfully add row to filelist * update counter when uploading to sub folder */ fileUploadStart.on('fileuploaddone', function(e, data) { OC.Upload.log('filelist handle fileuploaddone', e, data); var response; if (typeof data.result === 'string') { response = data.result; } else { // fetch response from iframe response = data.result[0].body.innerText; } var result=$.parseJSON(response); if (typeof result[0] !== 'undefined' && result[0].status === 'success') { var file = result[0]; var size = 0; if (data.context && data.context.data('type') === 'dir') { // update upload counter ui var uploadText = data.context.find('.uploadtext'); var currentUploads = parseInt(uploadText.attr('currentUploads'), 10); currentUploads -= 1; uploadText.attr('currentUploads', currentUploads); var translatedText = n('files', 'Uploading %n file', 'Uploading %n files', currentUploads); if (currentUploads === 0) { var img = OC.imagePath('core', 'filetypes/folder'); data.context.find('.thumbnail').css('background-image', 'url(' + img + ')'); uploadText.text(translatedText); uploadText.hide(); } else { uploadText.text(translatedText); } // update folder size size = parseInt(data.context.data('size'), 10); size += parseInt(file.size, 10); data.context.attr('data-size', size); data.context.find('td.filesize').text(humanFileSize(size)); } else { // only append new file if uploaded into the current folder if (file.directory !== self.getCurrentDirectory()) { // Uploading folders actually uploads a list of files // for which the target directory (file.directory) might lie deeper // than the current directory var fileDirectory = file.directory.replace('/','').replace(/\/$/, ""); var currentDirectory = self.getCurrentDirectory().replace('/','').replace(/\/$/, "") + '/'; if (currentDirectory !== '/') { // abort if fileDirectory does not start with current one if (fileDirectory.indexOf(currentDirectory) !== 0) { return; } // remove the current directory part fileDirectory = fileDirectory.substr(currentDirectory.length); } // only take the first section of the path fileDirectory = fileDirectory.split('/'); var fd; // if the first section exists / is a subdir if (fileDirectory.length) { fileDirectory = fileDirectory[0]; // See whether it is already in the list fd = self.findFileEl(fileDirectory); if (fd.length === 0) { var dir = { name: fileDirectory, type: 'dir', mimetype: 'httpd/unix-directory', permissions: file.permissions, size: 0, id: file.parentId }; fd = self.add(dir, {insert: true}); } // update folder size size = parseInt(fd.attr('data-size'), 10); size += parseInt(file.size, 10); fd.attr('data-size', size); fd.find('td.filesize').text(OC.Util.humanFileSize(size)); } return; } // add as stand-alone row to filelist size = t('files', 'Pending'); if (data.files[0].size>=0) { size=data.files[0].size; } //should the file exist in the list remove it self.remove(file.name); // create new file context data.context = self.add(file, {animate: true}); } } }); fileUploadStart.on('fileuploadstop', function(e, data) { OC.Upload.log('filelist handle fileuploadstop', e, data); //if user pressed cancel hide upload chrome if (data.errorThrown === 'abort') { //cleanup uploading to a dir var uploadText = $('tr .uploadtext'); var img = OC.imagePath('core', 'filetypes/folder'); uploadText.parents('td.filename').find('.thumbnail').css('background-image', 'url(' + img + ')'); uploadText.fadeOut(); uploadText.attr('currentUploads', 0); } self.updateStorageStatistics(); }); fileUploadStart.on('fileuploadfail', function(e, data) { OC.Upload.log('filelist handle fileuploadfail', e, data); //if user pressed cancel hide upload chrome if (data.errorThrown === 'abort') { //cleanup uploading to a dir var uploadText = $('tr .uploadtext'); var img = OC.imagePath('core', 'filetypes/folder'); uploadText.parents('td.filename').find('.thumbnail').css('background-image', 'url(' + img + ')'); uploadText.fadeOut(); uploadText.attr('currentUploads', 0); } self.updateStorageStatistics(); }); }, /** * Scroll to the last file of the given list * Highlight the list of files * @param files array of filenames, * @param {Function} [highlightFunction] optional function * to be called after the scrolling is finished */ highlightFiles: function(files, highlightFunction) { // Detection of the uploaded element var filename = files[files.length - 1]; var $fileRow = this.findFileEl(filename); while(!$fileRow.exists() && this._nextPage(false) !== false) { // Checking element existence $fileRow = this.findFileEl(filename); } if (!$fileRow.exists()) { // Element not present in the file list return; } var currentOffset = this.$container.scrollTop(); var additionalOffset = this.$el.find("#controls").height()+this.$el.find("#controls").offset().top; // Animation var _this = this; var $scrollContainer = this.$container; if ($scrollContainer[0] === window) { // need to use "body" to animate scrolling // when the scroll container is the window $scrollContainer = $('body'); } $scrollContainer.animate({ // Scrolling to the top of the new element scrollTop: currentOffset + $fileRow.offset().top - $fileRow.height() * 2 - additionalOffset }, { duration: 500, complete: function() { // Highlighting function var highlightRow = highlightFunction; if (!highlightRow) { highlightRow = function($fileRow) { $fileRow.addClass("highlightUploaded"); setTimeout(function() { $fileRow.removeClass("highlightUploaded"); }, 2500); }; } // Loop over uploaded files for(var i=0; i<files.length; i++) { var $fileRow = _this.findFileEl(files[i]); if($fileRow.length !== 0) { // Checking element existence highlightRow($fileRow); } } } }); }, _renderNewButton: function() { // if an upload button (legacy) already exists, skip if ($('#controls .button.upload').length) { return; } if (!this._addButtonTemplate) { this._addButtonTemplate = Handlebars.compile(TEMPLATE_ADDBUTTON); } var $newButton = $(this._addButtonTemplate({ addText: t('files', 'New'), iconUrl: OC.imagePath('core', 'actions/add') })); $('#controls .actions').prepend($newButton); $newButton.tooltip({'placement': 'bottom'}); $newButton.click(_.bind(this._onClickNewButton, this)); this._newButton = $newButton; }, _onClickNewButton: function(event) { var $target = $(event.target); if (!$target.hasClass('.button')) { $target = $target.closest('.button'); } this._newButton.tooltip('hide'); event.preventDefault(); if ($target.hasClass('disabled')) { return false; } if (!this._newFileMenu) { this._newFileMenu = new OCA.Files.NewFileMenu({ fileList: this }); $('body').append(this._newFileMenu.$el); } this._newFileMenu.showAt($target); return false; }, /** * Register a tab view to be added to all views */ registerTabView: function(tabView) { this._detailsView.addTabView(tabView); }, /** * Register a detail view to be added to all views */ registerDetailView: function(detailView) { this._detailsView.addDetailView(detailView); } }; /** * Sort comparators. * @namespace OCA.Files.FileList.Comparators * @private */ FileList.Comparators = { /** * Compares two file infos by name, making directories appear * first. * * @param {OCA.Files.FileInfo} fileInfo1 file info * @param {OCA.Files.FileInfo} fileInfo2 file info * @return {int} -1 if the first file must appear before the second one, * 0 if they are identify, 1 otherwise. */ name: function(fileInfo1, fileInfo2) { if (fileInfo1.type === 'dir' && fileInfo2.type !== 'dir') { return -1; } if (fileInfo1.type !== 'dir' && fileInfo2.type === 'dir') { return 1; } return OC.Util.naturalSortCompare(fileInfo1.name, fileInfo2.name); }, /** * Compares two file infos by size. * * @param {OCA.Files.FileInfo} fileInfo1 file info * @param {OCA.Files.FileInfo} fileInfo2 file info * @return {int} -1 if the first file must appear before the second one, * 0 if they are identify, 1 otherwise. */ size: function(fileInfo1, fileInfo2) { return fileInfo1.size - fileInfo2.size; }, /** * Compares two file infos by timestamp. * * @param {OCA.Files.FileInfo} fileInfo1 file info * @param {OCA.Files.FileInfo} fileInfo2 file info * @return {int} -1 if the first file must appear before the second one, * 0 if they are identify, 1 otherwise. */ mtime: function(fileInfo1, fileInfo2) { return fileInfo1.mtime - fileInfo2.mtime; } }; /** * File info attributes. * * @todo make this a real class in the future * @typedef {Object} OCA.Files.FileInfo * * @property {int} id file id * @property {String} name file name * @property {String} [path] file path, defaults to the list's current path * @property {String} mimetype mime type * @property {String} type "file" for files or "dir" for directories * @property {int} permissions file permissions * @property {int} mtime modification time in milliseconds * @property {boolean} [isShareMountPoint] whether the file is a share mount * point * @property {boolean} [isPreviewAvailable] whether a preview is available * for the given file type * @property {String} [icon] path to the mime type icon * @property {String} etag etag of the file */ OCA.Files.FileList = FileList; })(); $(document).ready(function() { // FIXME: unused ? OCA.Files.FileList.useUndo = (window.onbeforeunload)?true:false; $(window).bind('beforeunload', function () { if (OCA.Files.FileList.lastAction) { OCA.Files.FileList.lastAction(); } }); $(window).unload(function () { $(window).trigger('beforeunload'); }); });
apps/files/js/filelist.js
/* * Copyright (c) 2014 * * This file is licensed under the Affero General Public License version 3 * or later. * * See the COPYING-README file. * */ (function() { var TEMPLATE_ADDBUTTON = '<a href="#" class="button new" title="{{addText}}"><img src="{{iconUrl}}"></img></a>'; /** * @class OCA.Files.FileList * @classdesc * * The FileList class manages a file list view. * A file list view consists of a controls bar and * a file list table. * * @param $el container element with existing markup for the #controls * and a table * @param [options] map of options, see other parameters * @param [options.scrollContainer] scrollable container, defaults to $(window) * @param [options.dragOptions] drag options, disabled by default * @param [options.folderDropOptions] folder drop options, disabled by default * @param [options.detailsViewEnabled=true] whether to enable details view */ var FileList = function($el, options) { this.initialize($el, options); }; /** * @memberof OCA.Files */ FileList.prototype = { SORT_INDICATOR_ASC_CLASS: 'icon-triangle-n', SORT_INDICATOR_DESC_CLASS: 'icon-triangle-s', id: 'files', appName: t('files', 'Files'), isEmpty: true, useUndo:true, /** * Top-level container with controls and file list */ $el: null, /** * Files table */ $table: null, /** * List of rows (table tbody) */ $fileList: null, /** * @type OCA.Files.BreadCrumb */ breadcrumb: null, /** * @type OCA.Files.FileSummary */ fileSummary: null, /** * @type OCA.Files.DetailsView */ _detailsView: null, /** * Whether the file list was initialized already. * @type boolean */ initialized: false, /** * Number of files per page * * @return {int} page size */ pageSize: function() { return Math.ceil(this.$container.height() / 50); }, /** * Array of files in the current folder. * The entries are of file data. * * @type Array.<Object> */ files: [], /** * File actions handler, defaults to OCA.Files.FileActions * @type OCA.Files.FileActions */ fileActions: null, /** * Whether selection is allowed, checkboxes and selection overlay will * be rendered */ _allowSelection: true, /** * Map of file id to file data * @type Object.<int, Object> */ _selectedFiles: {}, /** * Summary of selected files. * @type OCA.Files.FileSummary */ _selectionSummary: null, /** * If not empty, only files containing this string will be shown * @type String */ _filter: '', /** * Sort attribute * @type String */ _sort: 'name', /** * Sort direction: 'asc' or 'desc' * @type String */ _sortDirection: 'asc', /** * Sort comparator function for the current sort * @type Function */ _sortComparator: null, /** * Whether to do a client side sort. * When false, clicking on a table header will call reload(). * When true, clicking on a table header will simply resort the list. */ _clientSideSort: false, /** * Current directory * @type String */ _currentDirectory: null, _dragOptions: null, _folderDropOptions: null, /** * Initialize the file list and its components * * @param $el container element with existing markup for the #controls * and a table * @param options map of options, see other parameters * @param options.scrollContainer scrollable container, defaults to $(window) * @param options.dragOptions drag options, disabled by default * @param options.folderDropOptions folder drop options, disabled by default * @param options.scrollTo name of file to scroll to after the first load * @private */ initialize: function($el, options) { var self = this; options = options || {}; if (this.initialized) { return; } if (options.dragOptions) { this._dragOptions = options.dragOptions; } if (options.folderDropOptions) { this._folderDropOptions = options.folderDropOptions; } this.$el = $el; if (options.id) { this.id = options.id; } this.$container = options.scrollContainer || $(window); this.$table = $el.find('table:first'); this.$fileList = $el.find('#fileList'); this._initFileActions(options.fileActions); this.files = []; this._selectedFiles = {}; this._selectionSummary = new OCA.Files.FileSummary(); this.fileSummary = this._createSummary(); this.setSort('name', 'asc'); var breadcrumbOptions = { onClick: _.bind(this._onClickBreadCrumb, this), getCrumbUrl: function(part) { return self.linkTo(part.dir); } }; // if dropping on folders is allowed, then also allow on breadcrumbs if (this._folderDropOptions) { breadcrumbOptions.onDrop = _.bind(this._onDropOnBreadCrumb, this); } this.breadcrumb = new OCA.Files.BreadCrumb(breadcrumbOptions); if (_.isUndefined(options.detailsViewEnabled) || options.detailsViewEnabled) { this._detailsView = new OCA.Files.DetailsView(); this._detailsView.addDetailView(new OCA.Files.MainFileInfoDetailView({fileList: this, fileActions: this.fileActions})); this._detailsView.$el.insertBefore(this.$el); this._detailsView.$el.addClass('disappear'); } this.$el.find('#controls').prepend(this.breadcrumb.$el); this._renderNewButton(); this.$el.find('thead th .columntitle').click(_.bind(this._onClickHeader, this)); this._onResize = _.debounce(_.bind(this._onResize, this), 100); $(window).resize(this._onResize); this.$el.on('show', this._onResize); this.updateSearch(); this.$el.on('click', function(event) { var $target = $(event.target); // click outside file row ? if (!$target.closest('tbody').length && !$target.closest('#app-sidebar').length) { self._updateDetailsView(null); } }); this.$fileList.on('click','td.filename>a.name', _.bind(this._onClickFile, this)); this.$fileList.on('change', 'td.filename>.selectCheckBox', _.bind(this._onClickFileCheckbox, this)); this.$el.on('urlChanged', _.bind(this._onUrlChanged, this)); this.$el.find('.select-all').click(_.bind(this._onClickSelectAll, this)); this.$el.find('.download').click(_.bind(this._onClickDownloadSelected, this)); this.$el.find('.delete-selected').click(_.bind(this._onClickDeleteSelected, this)); this.$el.find('.selectedActions a').tooltip({placement:'top'}); this.setupUploadEvents(); this.$container.on('scroll', _.bind(this._onScroll, this)); if (options.scrollTo) { this.$fileList.one('updated', function() { self.scrollTo(options.scrollTo); }); } OC.Plugins.attach('OCA.Files.FileList', this); }, /** * Destroy / uninitialize this instance. */ destroy: function() { if (this._newFileMenu) { this._newFileMenu.remove(); } if (this._newButton) { this._newButton.remove(); } // TODO: also unregister other event handlers this.fileActions.off('registerAction', this._onFileActionsUpdated); this.fileActions.off('setDefault', this._onFileActionsUpdated); OC.Plugins.detach('OCA.Files.FileList', this); }, /** * Initializes the file actions, set up listeners. * * @param {OCA.Files.FileActions} fileActions file actions */ _initFileActions: function(fileActions) { this.fileActions = fileActions; if (!this.fileActions) { this.fileActions = new OCA.Files.FileActions(); this.fileActions.registerDefaultActions(); } this._onFileActionsUpdated = _.debounce(_.bind(this._onFileActionsUpdated, this), 100); this.fileActions.on('registerAction', this._onFileActionsUpdated); this.fileActions.on('setDefault', this._onFileActionsUpdated); }, /** * Returns a unique model for the given file name. * * @param {string|object} fileName file name or jquery row * @return {OCA.Files.FileInfoModel} file info model */ getModelForFile: function(fileName) { var self = this; var $tr; // jQuery object ? if (fileName.is) { $tr = fileName; fileName = $tr.attr('data-file'); } else { $tr = this.findFileEl(fileName); } if (!$tr || !$tr.length) { return null; } // if requesting the selected model, return it if (this._currentFileModel && this._currentFileModel.get('name') === fileName) { return this._currentFileModel; } // TODO: note, this is a temporary model required for synchronising // state between different views. // In the future the FileList should work with Backbone.Collection // and contain existing models that can be used. // This method would in the future simply retrieve the matching model from the collection. var model = new OCA.Files.FileInfoModel(this.elementToFile($tr)); if (!model.has('path')) { model.set('path', this.getCurrentDirectory(), {silent: true}); } model.on('change', function(model) { // re-render row var highlightState = $tr.hasClass('highlighted'); $tr = self.updateRow( $tr, _.extend({isPreviewAvailable: true}, model.toJSON()), {updateSummary: true, silent: false, animate: true} ); $tr.toggleClass('highlighted', highlightState); }); model.on('busy', function(model, state) { self.showFileBusyState($tr, state); }); return model; }, /** * Update the details view to display the given file * * @param {string} fileName file name from the current list */ _updateDetailsView: function(fileName) { if (!this._detailsView) { return; } var oldFileInfo = this._detailsView.getFileInfo(); if (oldFileInfo) { // TODO: use more efficient way, maybe track the highlight this.$fileList.children().filterAttr('data-id', '' + oldFileInfo.get('id')).removeClass('highlighted'); oldFileInfo.off('change', this._onSelectedModelChanged, this); } if (!fileName) { OC.Apps.hideAppSidebar(this._detailsView.$el); this._detailsView.setFileInfo(null); if (this._currentFileModel) { this._currentFileModel.off(); } this._currentFileModel = null; return; } var $tr = this.findFileEl(fileName); var model = this.getModelForFile($tr); this._currentFileModel = model; $tr.addClass('highlighted'); this._detailsView.setFileInfo(model); this._detailsView.$el.scrollTop(0); _.defer(OC.Apps.showAppSidebar, this._detailsView.$el); }, /** * Event handler for when the window size changed */ _onResize: function() { var containerWidth = this.$el.width(); var actionsWidth = 0; $.each(this.$el.find('#controls .actions'), function(index, action) { actionsWidth += $(action).outerWidth(); }); // substract app navigation toggle when visible containerWidth -= $('#app-navigation-toggle').width(); this.breadcrumb.setMaxWidth(containerWidth - actionsWidth - 10); this.updateSearch(); }, /** * Event handler for when the URL changed */ _onUrlChanged: function(e) { if (e && e.dir) { this.changeDirectory(e.dir, false, true); } }, /** * Selected/deselects the given file element and updated * the internal selection cache. * * @param $tr single file row element * @param state true to select, false to deselect */ _selectFileEl: function($tr, state) { var $checkbox = $tr.find('td.filename>.selectCheckBox'); var oldData = !!this._selectedFiles[$tr.data('id')]; var data; $checkbox.prop('checked', state); $tr.toggleClass('selected', state); // already selected ? if (state === oldData) { return; } data = this.elementToFile($tr); if (state) { this._selectedFiles[$tr.data('id')] = data; this._selectionSummary.add(data); } else { delete this._selectedFiles[$tr.data('id')]; this._selectionSummary.remove(data); } if (this._selectionSummary.getTotal() === 1) { this._updateDetailsView(_.values(this._selectedFiles)[0].name); } else { // show nothing when multiple files are selected this._updateDetailsView(null); } this.$el.find('.select-all').prop('checked', this._selectionSummary.getTotal() === this.files.length); }, /** * Event handler for when clicking on files to select them */ _onClickFile: function(event) { var $tr = $(event.target).closest('tr'); if (this._allowSelection && (event.ctrlKey || event.shiftKey)) { event.preventDefault(); if (event.shiftKey) { var $lastTr = $(this._lastChecked); var lastIndex = $lastTr.index(); var currentIndex = $tr.index(); var $rows = this.$fileList.children('tr'); // last clicked checkbox below current one ? if (lastIndex > currentIndex) { var aux = lastIndex; lastIndex = currentIndex; currentIndex = aux; } // auto-select everything in-between for (var i = lastIndex + 1; i < currentIndex; i++) { this._selectFileEl($rows.eq(i), true); } } else { this._lastChecked = $tr; } var $checkbox = $tr.find('td.filename>.selectCheckBox'); this._selectFileEl($tr, !$checkbox.prop('checked')); this.updateSelectionSummary(); } else { // clicked directly on the name if (!this._detailsView || $(event.target).is('.nametext') || $(event.target).closest('.nametext').length) { var filename = $tr.attr('data-file'); var renaming = $tr.data('renaming'); if (!renaming) { this.fileActions.currentFile = $tr.find('td'); var mime = this.fileActions.getCurrentMimeType(); var type = this.fileActions.getCurrentType(); var permissions = this.fileActions.getCurrentPermissions(); var action = this.fileActions.getDefault(mime,type, permissions); if (action) { event.preventDefault(); // also set on global object for legacy apps window.FileActions.currentFile = this.fileActions.currentFile; action(filename, { $file: $tr, fileList: this, fileActions: this.fileActions, dir: $tr.attr('data-path') || this.getCurrentDirectory() }); } // deselect row $(event.target).closest('a').blur(); } } else { this._updateDetailsView($tr.attr('data-file')); event.preventDefault(); } } }, /** * Event handler for when clicking on a file's checkbox */ _onClickFileCheckbox: function(e) { var $tr = $(e.target).closest('tr'); this._selectFileEl($tr, !$tr.hasClass('selected')); this._lastChecked = $tr; this.updateSelectionSummary(); }, /** * Event handler for when selecting/deselecting all files */ _onClickSelectAll: function(e) { var checked = $(e.target).prop('checked'); this.$fileList.find('td.filename>.selectCheckBox').prop('checked', checked) .closest('tr').toggleClass('selected', checked); this._selectedFiles = {}; this._selectionSummary.clear(); if (checked) { for (var i = 0; i < this.files.length; i++) { var fileData = this.files[i]; this._selectedFiles[fileData.id] = fileData; this._selectionSummary.add(fileData); } } this.updateSelectionSummary(); }, /** * Event handler for when clicking on "Download" for the selected files */ _onClickDownloadSelected: function(event) { var files; var dir = this.getCurrentDirectory(); if (this.isAllSelected()) { files = OC.basename(dir); dir = OC.dirname(dir) || '/'; } else { files = _.pluck(this.getSelectedFiles(), 'name'); } var downloadFileaction = $('#selectedActionsList').find('.download'); // don't allow a second click on the download action if(downloadFileaction.hasClass('disabled')) { event.preventDefault(); return; } var disableLoadingState = function(){ OCA.Files.FileActions.updateFileActionSpinner(downloadFileaction, false); }; OCA.Files.FileActions.updateFileActionSpinner(downloadFileaction, true); OCA.Files.Files.handleDownload(this.getDownloadUrl(files, dir), disableLoadingState); return false; }, /** * Event handler for when clicking on "Delete" for the selected files */ _onClickDeleteSelected: function(event) { var files = null; if (!this.isAllSelected()) { files = _.pluck(this.getSelectedFiles(), 'name'); } this.do_delete(files); event.preventDefault(); return false; }, /** * Event handler when clicking on a table header */ _onClickHeader: function(e) { var $target = $(e.target); var sort; if (!$target.is('a')) { $target = $target.closest('a'); } sort = $target.attr('data-sort'); if (sort) { if (this._sort === sort) { this.setSort(sort, (this._sortDirection === 'desc')?'asc':'desc', true); } else { if ( sort === 'name' ) { //default sorting of name is opposite to size and mtime this.setSort(sort, 'asc', true); } else { this.setSort(sort, 'desc', true); } } } }, /** * Event handler when clicking on a bread crumb */ _onClickBreadCrumb: function(e) { var $el = $(e.target).closest('.crumb'), $targetDir = $el.data('dir'); if ($targetDir !== undefined && e.which === 1) { e.preventDefault(); this.changeDirectory($targetDir); this.updateSearch(); } }, /** * Event handler for when scrolling the list container. * This appends/renders the next page of entries when reaching the bottom. */ _onScroll: function(e) { if (this.$container.scrollTop() + this.$container.height() > this.$el.height() - 300) { this._nextPage(true); } }, /** * Event handler when dropping on a breadcrumb */ _onDropOnBreadCrumb: function( event, ui ) { var self = this; var $target = $(event.target); if (!$target.is('.crumb')) { $target = $target.closest('.crumb'); } var targetPath = $(event.target).data('dir'); var dir = this.getCurrentDirectory(); while (dir.substr(0,1) === '/') {//remove extra leading /'s dir = dir.substr(1); } dir = '/' + dir; if (dir.substr(-1,1) !== '/') { dir = dir + '/'; } // do nothing if dragged on current dir if (targetPath === dir || targetPath + '/' === dir) { return; } var files = this.getSelectedFiles(); if (files.length === 0) { // single one selected without checkbox? files = _.map(ui.helper.find('tr'), function(el) { return self.elementToFile($(el)); }); } this.move(_.pluck(files, 'name'), targetPath); }, /** * Sets a new page title */ setPageTitle: function(title){ if (title) { title += ' - '; } else { title = ''; } title += this.appName; // Sets the page title with the " - ownCloud" suffix as in templates window.document.title = title + ' - ' + oc_defaults.title; return true; }, /** * Returns the tr element for a given file name * @param fileName file name */ findFileEl: function(fileName){ // use filterAttr to avoid escaping issues return this.$fileList.find('tr').filterAttr('data-file', fileName); }, /** * Returns the file data from a given file element. * @param $el file tr element * @return file data */ elementToFile: function($el){ $el = $($el); return { id: parseInt($el.attr('data-id'), 10), name: $el.attr('data-file'), mimetype: $el.attr('data-mime'), mtime: parseInt($el.attr('data-mtime'), 10), type: $el.attr('data-type'), size: parseInt($el.attr('data-size'), 10), etag: $el.attr('data-etag'), permissions: parseInt($el.attr('data-permissions'), 10) }; }, /** * Appends the next page of files into the table * @param animate true to animate the new elements * @return array of DOM elements of the newly added files */ _nextPage: function(animate) { var index = this.$fileList.children().length, count = this.pageSize(), hidden, tr, fileData, newTrs = [], isAllSelected = this.isAllSelected(); if (index >= this.files.length) { return false; } while (count > 0 && index < this.files.length) { fileData = this.files[index]; if (this._filter) { hidden = fileData.name.toLowerCase().indexOf(this._filter.toLowerCase()) === -1; } else { hidden = false; } tr = this._renderRow(fileData, {updateSummary: false, silent: true, hidden: hidden}); this.$fileList.append(tr); if (isAllSelected || this._selectedFiles[fileData.id]) { tr.addClass('selected'); tr.find('.selectCheckBox').prop('checked', true); } if (animate) { tr.addClass('appear transparent'); } newTrs.push(tr); index++; count--; } // trigger event for newly added rows if (newTrs.length > 0) { this.$fileList.trigger($.Event('fileActionsReady', {fileList: this, $files: newTrs})); } if (animate) { // defer, for animation window.setTimeout(function() { for (var i = 0; i < newTrs.length; i++ ) { newTrs[i].removeClass('transparent'); } }, 0); } return newTrs; }, /** * Event handler for when file actions were updated. * This will refresh the file actions on the list. */ _onFileActionsUpdated: function() { var self = this; var $files = this.$fileList.find('tr'); if (!$files.length) { return; } $files.each(function() { self.fileActions.display($(this).find('td.filename'), false, self); }); this.$fileList.trigger($.Event('fileActionsReady', {fileList: this, $files: $files})); }, /** * Sets the files to be displayed in the list. * This operation will re-render the list and update the summary. * @param filesArray array of file data (map) */ setFiles: function(filesArray) { var self = this; // detach to make adding multiple rows faster this.files = filesArray; this.$fileList.empty(); // clear "Select all" checkbox this.$el.find('.select-all').prop('checked', false); this.isEmpty = this.files.length === 0; this._nextPage(); this.updateEmptyContent(); this.fileSummary.calculate(filesArray); this._selectedFiles = {}; this._selectionSummary.clear(); this.updateSelectionSummary(); $(window).scrollTop(0); this.$fileList.trigger(jQuery.Event('updated')); _.defer(function() { self.$el.closest('#app-content').trigger(jQuery.Event('apprendered')); }); }, /** * Creates a new table row element using the given file data. * @param {OCA.Files.FileInfo} fileData file info attributes * @param options map of attributes * @return new tr element (not appended to the table) */ _createRow: function(fileData, options) { var td, simpleSize, basename, extension, sizeColor, icon = OC.MimeType.getIconUrl(fileData.mimetype), name = fileData.name, type = fileData.type || 'file', mtime = parseInt(fileData.mtime, 10), mime = fileData.mimetype, path = fileData.path, linkUrl; options = options || {}; if (isNaN(mtime)) { mtime = new Date().getTime() } if (type === 'dir') { mime = mime || 'httpd/unix-directory'; if (fileData.mountType && fileData.mountType.indexOf('external') === 0) { icon = OC.MimeType.getIconUrl('dir-external'); } } //containing tr var tr = $('<tr></tr>').attr({ "data-id" : fileData.id, "data-type": type, "data-size": fileData.size, "data-file": name, "data-mime": mime, "data-mtime": mtime, "data-etag": fileData.etag, "data-permissions": fileData.permissions || this.getDirectoryPermissions() }); if (fileData.mountType) { tr.attr('data-mounttype', fileData.mountType); } if (!_.isUndefined(path)) { tr.attr('data-path', path); } else { path = this.getCurrentDirectory(); } if (type === 'dir') { // use default folder icon icon = icon || OC.imagePath('core', 'filetypes/folder'); } else { icon = icon || OC.imagePath('core', 'filetypes/file'); } // filename td td = $('<td class="filename"></td>'); // linkUrl if (type === 'dir') { linkUrl = this.linkTo(path + '/' + name); } else { linkUrl = this.getDownloadUrl(name, path); } if (this._allowSelection) { td.append( '<input id="select-' + this.id + '-' + fileData.id + '" type="checkbox" class="selectCheckBox"/><label for="select-' + this.id + '-' + fileData.id + '">' + '<div class="thumbnail" style="background-image:url(' + icon + '); background-size: 32px;"></div>' + '<span class="hidden-visually">' + t('files', 'Select') + '</span>' + '</label>' ); } else { td.append('<div class="thumbnail" style="background-image:url(' + icon + '); background-size: 32px;"></div>'); } var linkElem = $('<a></a>').attr({ "class": "name", "href": linkUrl }); // from here work on the display name name = fileData.displayName || name; // show hidden files (starting with a dot) completely in gray if(name.indexOf('.') === 0) { basename = ''; extension = name; // split extension from filename for non dirs } else if (type !== 'dir' && name.indexOf('.') !== -1) { basename = name.substr(0, name.lastIndexOf('.')); extension = name.substr(name.lastIndexOf('.')); } else { basename = name; extension = false; } var nameSpan=$('<span></span>').addClass('nametext'); var innernameSpan = $('<span></span>').addClass('innernametext').text(basename); nameSpan.append(innernameSpan); linkElem.append(nameSpan); if (extension) { nameSpan.append($('<span></span>').addClass('extension').text(extension)); } if (fileData.extraData) { if (fileData.extraData.charAt(0) === '/') { fileData.extraData = fileData.extraData.substr(1); } nameSpan.addClass('extra-data').attr('title', fileData.extraData); nameSpan.tooltip({placement: 'right'}); } // dirs can show the number of uploaded files if (type === 'dir') { linkElem.append($('<span></span>').attr({ 'class': 'uploadtext', 'currentUploads': 0 })); } td.append(linkElem); tr.append(td); // size column if (typeof(fileData.size) !== 'undefined' && fileData.size >= 0) { simpleSize = humanFileSize(parseInt(fileData.size, 10), true); sizeColor = Math.round(160-Math.pow((fileData.size/(1024*1024)),2)); } else { simpleSize = t('files', 'Pending'); } td = $('<td></td>').attr({ "class": "filesize", "style": 'color:rgb(' + sizeColor + ',' + sizeColor + ',' + sizeColor + ')' }).text(simpleSize); tr.append(td); // date column (1000 milliseconds to seconds, 60 seconds, 60 minutes, 24 hours) // difference in days multiplied by 5 - brightest shade for files older than 32 days (160/5) var modifiedColor = Math.round(((new Date()).getTime() - mtime )/1000/60/60/24*5 ); // ensure that the brightest color is still readable if (modifiedColor >= '160') { modifiedColor = 160; } var formatted; var text; if (mtime > 0) { formatted = OC.Util.formatDate(mtime); text = OC.Util.relativeModifiedDate(mtime); } else { formatted = t('files', 'Unable to determine date'); text = '?'; } td = $('<td></td>').attr({ "class": "date" }); td.append($('<span></span>').attr({ "class": "modified", "title": formatted, "style": 'color:rgb('+modifiedColor+','+modifiedColor+','+modifiedColor+')' }).text(text) .tooltip({placement: 'top'}) ); tr.find('.filesize').text(simpleSize); tr.append(td); return tr; }, /** * Adds an entry to the files array and also into the DOM * in a sorted manner. * * @param {OCA.Files.FileInfo} fileData map of file attributes * @param {Object} [options] map of attributes * @param {boolean} [options.updateSummary] true to update the summary * after adding (default), false otherwise. Defaults to true. * @param {boolean} [options.silent] true to prevent firing events like "fileActionsReady", * defaults to false. * @param {boolean} [options.animate] true to animate the thumbnail image after load * defaults to true. * @return new tr element (not appended to the table) */ add: function(fileData, options) { var index = -1; var $tr; var $rows; var $insertionPoint; options = _.extend({animate: true}, options || {}); // there are three situations to cover: // 1) insertion point is visible on the current page // 2) insertion point is on a not visible page (visible after scrolling) // 3) insertion point is at the end of the list $rows = this.$fileList.children(); index = this._findInsertionIndex(fileData); if (index > this.files.length) { index = this.files.length; } else { $insertionPoint = $rows.eq(index); } // is the insertion point visible ? if ($insertionPoint.length) { // only render if it will really be inserted $tr = this._renderRow(fileData, options); $insertionPoint.before($tr); } else { // if insertion point is after the last visible // entry, append if (index === $rows.length) { $tr = this._renderRow(fileData, options); this.$fileList.append($tr); } } this.isEmpty = false; this.files.splice(index, 0, fileData); if ($tr && options.animate) { $tr.addClass('appear transparent'); window.setTimeout(function() { $tr.removeClass('transparent'); }); } if (options.scrollTo) { this.scrollTo(fileData.name); } // defaults to true if not defined if (typeof(options.updateSummary) === 'undefined' || !!options.updateSummary) { this.fileSummary.add(fileData, true); this.updateEmptyContent(); } return $tr; }, /** * Creates a new row element based on the given attributes * and returns it. * * @param {OCA.Files.FileInfo} fileData map of file attributes * @param {Object} [options] map of attributes * @param {int} [options.index] index at which to insert the element * @param {boolean} [options.updateSummary] true to update the summary * after adding (default), false otherwise. Defaults to true. * @param {boolean} [options.animate] true to animate the thumbnail image after load * defaults to true. * @return new tr element (not appended to the table) */ _renderRow: function(fileData, options) { options = options || {}; var type = fileData.type || 'file', mime = fileData.mimetype, path = fileData.path || this.getCurrentDirectory(), permissions = parseInt(fileData.permissions, 10) || 0; if (fileData.isShareMountPoint) { permissions = permissions | OC.PERMISSION_UPDATE; } if (type === 'dir') { mime = mime || 'httpd/unix-directory'; } var tr = this._createRow( fileData, options ); var filenameTd = tr.find('td.filename'); // TODO: move dragging to FileActions ? // enable drag only for deletable files if (this._dragOptions && permissions & OC.PERMISSION_DELETE) { filenameTd.draggable(this._dragOptions); } // allow dropping on folders if (this._folderDropOptions && fileData.type === 'dir') { filenameTd.droppable(this._folderDropOptions); } if (options.hidden) { tr.addClass('hidden'); } // display actions this.fileActions.display(filenameTd, !options.silent, this); if (fileData.isPreviewAvailable) { var iconDiv = filenameTd.find('.thumbnail'); // lazy load / newly inserted td ? // the typeof check ensures that the default value of animate is true if (typeof(options.animate) === 'undefined' || !!options.animate) { this.lazyLoadPreview({ path: path + '/' + fileData.name, mime: mime, etag: fileData.etag, callback: function(url) { iconDiv.css('background-image', 'url("' + url + '")'); } }); } else { // set the preview URL directly var urlSpec = { file: path + '/' + fileData.name, c: fileData.etag }; var previewUrl = this.generatePreviewUrl(urlSpec); previewUrl = previewUrl.replace('(', '%28').replace(')', '%29'); iconDiv.css('background-image', 'url("' + previewUrl + '")'); } } return tr; }, /** * Returns the current directory * @method getCurrentDirectory * @return current directory */ getCurrentDirectory: function(){ return this._currentDirectory || this.$el.find('#dir').val() || '/'; }, /** * Returns the directory permissions * @return permission value as integer */ getDirectoryPermissions: function() { return parseInt(this.$el.find('#permissions').val(), 10); }, /** * @brief Changes the current directory and reload the file list. * @param targetDir target directory (non URL encoded) * @param changeUrl false if the URL must not be changed (defaults to true) * @param {boolean} force set to true to force changing directory */ changeDirectory: function(targetDir, changeUrl, force) { var self = this; var currentDir = this.getCurrentDirectory(); targetDir = targetDir || '/'; if (!force && currentDir === targetDir) { return; } this._setCurrentDir(targetDir, changeUrl); this.reload().then(function(success){ if (!success) { self.changeDirectory(currentDir, true); } }); }, linkTo: function(dir) { return OC.linkTo('files', 'index.php')+"?dir="+ encodeURIComponent(dir).replace(/%2F/g, '/'); }, /** * Sets the current directory name and updates the breadcrumb. * @param targetDir directory to display * @param changeUrl true to also update the URL, false otherwise (default) */ _setCurrentDir: function(targetDir, changeUrl) { targetDir = targetDir.replace(/\\/g, '/'); var previousDir = this.getCurrentDirectory(), baseDir = OC.basename(targetDir); if (baseDir !== '') { this.setPageTitle(baseDir); } else { this.setPageTitle(); } this._currentDirectory = targetDir; // legacy stuff this.$el.find('#dir').val(targetDir); if (changeUrl !== false) { this.$el.trigger(jQuery.Event('changeDirectory', { dir: targetDir, previousDir: previousDir })); } this.breadcrumb.setDirectory(this.getCurrentDirectory()); }, /** * Sets the current sorting and refreshes the list * * @param sort sort attribute name * @param direction sort direction, one of "asc" or "desc" * @param update true to update the list, false otherwise (default) */ setSort: function(sort, direction, update) { var comparator = FileList.Comparators[sort] || FileList.Comparators.name; this._sort = sort; this._sortDirection = (direction === 'desc')?'desc':'asc'; this._sortComparator = comparator; if (direction === 'desc') { this._sortComparator = function(fileInfo1, fileInfo2) { return -comparator(fileInfo1, fileInfo2); }; } this.$el.find('thead th .sort-indicator') .removeClass(this.SORT_INDICATOR_ASC_CLASS) .removeClass(this.SORT_INDICATOR_DESC_CLASS) .toggleClass('hidden', true) .addClass(this.SORT_INDICATOR_DESC_CLASS); this.$el.find('thead th.column-' + sort + ' .sort-indicator') .removeClass(this.SORT_INDICATOR_ASC_CLASS) .removeClass(this.SORT_INDICATOR_DESC_CLASS) .toggleClass('hidden', false) .addClass(direction === 'desc' ? this.SORT_INDICATOR_DESC_CLASS : this.SORT_INDICATOR_ASC_CLASS); if (update) { if (this._clientSideSort) { this.files.sort(this._sortComparator); this.setFiles(this.files); } else { this.reload(); } } }, /** * Reloads the file list using ajax call * * @return ajax call object */ reload: function() { this._selectedFiles = {}; this._selectionSummary.clear(); if (this._currentFileModel) { this._currentFileModel.off(); } this._currentFileModel = null; this.$el.find('.select-all').prop('checked', false); this.showMask(); if (this._reloadCall) { this._reloadCall.abort(); } this._reloadCall = $.ajax({ url: this.getAjaxUrl('list'), data: { dir : this.getCurrentDirectory(), sort: this._sort, sortdirection: this._sortDirection } }); // close sidebar this._updateDetailsView(null); var callBack = this.reloadCallback.bind(this); return this._reloadCall.then(callBack, callBack); }, reloadCallback: function(result) { delete this._reloadCall; this.hideMask(); if (!result || result.status === 'error') { // if the error is not related to folder we're trying to load, reload the page to handle logout etc if (result.data.error === 'authentication_error' || result.data.error === 'token_expired' || result.data.error === 'application_not_enabled' ) { OC.redirect(OC.generateUrl('apps/files')); } OC.Notification.show(result.data.message); return false; } // Firewall Blocked request? if (result.status === 403) { // Go home this.changeDirectory('/'); OC.Notification.show(t('files', 'This operation is forbidden')); return false; } // Did share service die or something else fail? if (result.status === 500) { // Go home this.changeDirectory('/'); OC.Notification.show(t('files', 'This directory is unavailable, please check the logs or contact the administrator')); return false; } if (result.status === 404) { // go back home this.changeDirectory('/'); return false; } // aborted ? if (result.status === 0){ return true; } // TODO: should rather return upload file size through // the files list ajax call this.updateStorageStatistics(true); if (result.data.permissions) { this.setDirectoryPermissions(result.data.permissions); } this.setFiles(result.data.files); return true; }, updateStorageStatistics: function(force) { OCA.Files.Files.updateStorageStatistics(this.getCurrentDirectory(), force); }, getAjaxUrl: function(action, params) { return OCA.Files.Files.getAjaxUrl(action, params); }, getDownloadUrl: function(files, dir) { return OCA.Files.Files.getDownloadUrl(files, dir || this.getCurrentDirectory()); }, /** * Generates a preview URL based on the URL space. * @param urlSpec attributes for the URL * @param {int} urlSpec.x width * @param {int} urlSpec.y height * @param {String} urlSpec.file path to the file * @return preview URL */ generatePreviewUrl: function(urlSpec) { urlSpec = urlSpec || {}; if (!urlSpec.x) { urlSpec.x = this.$table.data('preview-x') || 36; } if (!urlSpec.y) { urlSpec.y = this.$table.data('preview-y') || 36; } urlSpec.x *= window.devicePixelRatio; urlSpec.y *= window.devicePixelRatio; urlSpec.x = Math.floor(urlSpec.x); urlSpec.y = Math.floor(urlSpec.y); urlSpec.forceIcon = 0; return OC.generateUrl('/core/preview.png?') + $.param(urlSpec); }, /** * Lazy load a file's preview. * * @param path path of the file * @param mime mime type * @param callback callback function to call when the image was loaded * @param etag file etag (for caching) */ lazyLoadPreview : function(options) { var self = this; var path = options.path; var mime = options.mime; var ready = options.callback; var etag = options.etag; // get mime icon url var iconURL = OC.MimeType.getIconUrl(mime); var previewURL, urlSpec = {}; ready(iconURL); // set mimeicon URL urlSpec.file = OCA.Files.Files.fixPath(path); if (options.x) { urlSpec.x = options.x; } if (options.y) { urlSpec.y = options.y; } if (options.a) { urlSpec.a = options.a; } if (options.mode) { urlSpec.mode = options.mode; } if (etag){ // use etag as cache buster urlSpec.c = etag; } else { console.warn('OCA.Files.FileList.lazyLoadPreview(): missing etag argument'); } previewURL = self.generatePreviewUrl(urlSpec); previewURL = previewURL.replace('(', '%28'); previewURL = previewURL.replace(')', '%29'); // preload image to prevent delay // this will make the browser cache the image var img = new Image(); img.onload = function(){ // if loading the preview image failed (no preview for the mimetype) then img.width will < 5 if (img.width > 5) { ready(previewURL, img); } else if (options.error) { options.error(); } }; if (options.error) { img.onerror = options.error; } img.src = previewURL; }, setDirectoryPermissions: function(permissions) { var isCreatable = (permissions & OC.PERMISSION_CREATE) !== 0; this.$el.find('#permissions').val(permissions); this.$el.find('.creatable').toggleClass('hidden', !isCreatable); this.$el.find('.notCreatable').toggleClass('hidden', isCreatable); }, /** * Shows/hides action buttons * * @param show true for enabling, false for disabling */ showActions: function(show){ this.$el.find('.actions,#file_action_panel').toggleClass('hidden', !show); if (show){ // make sure to display according to permissions var permissions = this.getDirectoryPermissions(); var isCreatable = (permissions & OC.PERMISSION_CREATE) !== 0; this.$el.find('.creatable').toggleClass('hidden', !isCreatable); this.$el.find('.notCreatable').toggleClass('hidden', isCreatable); // remove old style breadcrumbs (some apps might create them) this.$el.find('#controls .crumb').remove(); // refresh breadcrumbs in case it was replaced by an app this.breadcrumb.render(); } else{ this.$el.find('.creatable, .notCreatable').addClass('hidden'); } }, /** * Enables/disables viewer mode. * In viewer mode, apps can embed themselves under the controls bar. * In viewer mode, the actions of the file list will be hidden. * @param show true for enabling, false for disabling */ setViewerMode: function(show){ this.showActions(!show); this.$el.find('#filestable').toggleClass('hidden', show); this.$el.trigger(new $.Event('changeViewerMode', {viewerModeEnabled: show})); }, /** * Removes a file entry from the list * @param name name of the file to remove * @param {Object} [options] map of attributes * @param {boolean} [options.updateSummary] true to update the summary * after removing, false otherwise. Defaults to true. * @return deleted element */ remove: function(name, options){ options = options || {}; var fileEl = this.findFileEl(name); var index = fileEl.index(); if (!fileEl.length) { return null; } if (this._selectedFiles[fileEl.data('id')]) { // remove from selection first this._selectFileEl(fileEl, false); this.updateSelectionSummary(); } if (this._dragOptions && (fileEl.data('permissions') & OC.PERMISSION_DELETE)) { // file is only draggable when delete permissions are set fileEl.find('td.filename').draggable('destroy'); } this.files.splice(index, 1); fileEl.remove(); // TODO: improve performance on batch update this.isEmpty = !this.files.length; if (typeof(options.updateSummary) === 'undefined' || !!options.updateSummary) { this.updateEmptyContent(); this.fileSummary.remove({type: fileEl.attr('data-type'), size: fileEl.attr('data-size')}, true); } var lastIndex = this.$fileList.children().length; // if there are less elements visible than one page // but there are still pending elements in the array, // then directly append the next page if (lastIndex < this.files.length && lastIndex < this.pageSize()) { this._nextPage(true); } return fileEl; }, /** * Finds the index of the row before which the given * fileData should be inserted, considering the current * sorting * * @param {OCA.Files.FileInfo} fileData file info */ _findInsertionIndex: function(fileData) { var index = 0; while (index < this.files.length && this._sortComparator(fileData, this.files[index]) > 0) { index++; } return index; }, /** * Moves a file to a given target folder. * * @param fileNames array of file names to move * @param targetPath absolute target path */ move: function(fileNames, targetPath) { var self = this; var dir = this.getCurrentDirectory(); var target = OC.basename(targetPath); if (!_.isArray(fileNames)) { fileNames = [fileNames]; } _.each(fileNames, function(fileName) { var $tr = self.findFileEl(fileName); self.showFileBusyState($tr, true); // TODO: improve performance by sending all file names in a single call $.post( OC.filePath('files', 'ajax', 'move.php'), { dir: dir, file: fileName, target: targetPath }, function(result) { if (result) { if (result.status === 'success') { // if still viewing the same directory if (self.getCurrentDirectory() === dir) { // recalculate folder size var oldFile = self.findFileEl(target); var newFile = self.findFileEl(fileName); var oldSize = oldFile.data('size'); var newSize = oldSize + newFile.data('size'); oldFile.data('size', newSize); oldFile.find('td.filesize').text(OC.Util.humanFileSize(newSize)); // TODO: also update entry in FileList.files self.remove(fileName); } } else { OC.Notification.hide(); if (result.status === 'error' && result.data.message) { OC.Notification.show(result.data.message); } else { OC.Notification.show(t('files', 'Error moving file.')); } // hide notification after 10 sec setTimeout(function() { OC.Notification.hide(); }, 10000); } } else { OC.dialogs.alert(t('files', 'Error moving file'), t('files', 'Error')); } self.showFileBusyState($tr, false); } ); }); }, /** * Updates the given row with the given file info * * @param {Object} $tr row element * @param {OCA.Files.FileInfo} fileInfo file info * @param {Object} options options * * @return {Object} new row element */ updateRow: function($tr, fileInfo, options) { this.files.splice($tr.index(), 1); $tr.remove(); $tr = this.add(fileInfo, _.extend({updateSummary: false, silent: true}, options)); this.$fileList.trigger($.Event('fileActionsReady', {fileList: this, $files: $tr})); return $tr; }, /** * Triggers file rename input field for the given file name. * If the user enters a new name, the file will be renamed. * * @param oldname file name of the file to rename */ rename: function(oldname) { var self = this; var tr, td, input, form; tr = this.findFileEl(oldname); var oldFileInfo = this.files[tr.index()]; tr.data('renaming',true); td = tr.children('td.filename'); input = $('<input type="text" class="filename"/>').val(oldname); form = $('<form></form>'); form.append(input); td.children('a.name').hide(); td.append(form); input.focus(); //preselect input var len = input.val().lastIndexOf('.'); if ( len === -1 || tr.data('type') === 'dir' ) { len = input.val().length; } input.selectRange(0, len); var checkInput = function () { var filename = input.val(); if (filename !== oldname) { // Files.isFileNameValid(filename) throws an exception itself OCA.Files.Files.isFileNameValid(filename); if (self.inList(filename)) { throw t('files', '{new_name} already exists', {new_name: filename}); } } return true; }; function restore() { input.tooltip('hide'); tr.data('renaming',false); form.remove(); td.children('a.name').show(); } form.submit(function(event) { event.stopPropagation(); event.preventDefault(); if (input.hasClass('error')) { return; } try { var newName = input.val(); input.tooltip('hide'); form.remove(); if (newName !== oldname) { checkInput(); // mark as loading (temp element) self.showFileBusyState(tr, true); tr.attr('data-file', newName); var basename = newName; if (newName.indexOf('.') > 0 && tr.data('type') !== 'dir') { basename = newName.substr(0, newName.lastIndexOf('.')); } td.find('a.name span.nametext').text(basename); td.children('a.name').show(); $.ajax({ url: OC.filePath('files','ajax','rename.php'), data: { dir : tr.attr('data-path') || self.getCurrentDirectory(), newname: newName, file: oldname }, success: function(result) { var fileInfo; if (!result || result.status === 'error') { OC.dialogs.alert(result.data.message, t('files', 'Could not rename file')); fileInfo = oldFileInfo; if (result.data.code === 'sourcenotfound') { self.remove(result.data.newname, {updateSummary: true}); return; } } else { fileInfo = result.data; } // reinsert row self.files.splice(tr.index(), 1); tr.remove(); tr = self.add(fileInfo, {updateSummary: false, silent: true}); self.$fileList.trigger($.Event('fileActionsReady', {fileList: self, $files: $(tr)})); self._updateDetailsView(fileInfo.name); } }); } else { // add back the old file info when cancelled self.files.splice(tr.index(), 1); tr.remove(); tr = self.add(oldFileInfo, {updateSummary: false, silent: true}); self.$fileList.trigger($.Event('fileActionsReady', {fileList: self, $files: $(tr)})); } } catch (error) { input.attr('title', error); input.tooltip({placement: 'left', trigger: 'manual'}); input.tooltip('show'); input.addClass('error'); } return false; }); input.keyup(function(event) { // verify filename on typing try { checkInput(); input.tooltip('hide'); input.removeClass('error'); } catch (error) { input.attr('title', error); input.tooltip({placement: 'left', trigger: 'manual'}); input.tooltip('show'); input.addClass('error'); } if (event.keyCode === 27) { restore(); } }); input.click(function(event) { event.stopPropagation(); event.preventDefault(); }); input.blur(function() { form.trigger('submit'); }); }, /** * Create an empty file inside the current directory. * * @param {string} name name of the file * * @return {Promise} promise that will be resolved after the * file was created * * @since 8.2 */ createFile: function(name) { var self = this; var deferred = $.Deferred(); var promise = deferred.promise(); OCA.Files.Files.isFileNameValid(name); name = this.getUniqueName(name); if (this.lastAction) { this.lastAction(); } $.post( OC.generateUrl('/apps/files/ajax/newfile.php'), { dir: this.getCurrentDirectory(), filename: name }, function(result) { if (result.status === 'success') { self.add(result.data, {animate: true, scrollTo: true}); deferred.resolve(result.status, result.data); } else { if (result.data && result.data.message) { OC.Notification.showTemporary(result.data.message); } else { OC.Notification.showTemporary(t('core', 'Could not create file')); } deferred.reject(result.status, result.data); } } ); return promise; }, /** * Create a directory inside the current directory. * * @param {string} name name of the directory * * @return {Promise} promise that will be resolved after the * directory was created * * @since 8.2 */ createDirectory: function(name) { var self = this; var deferred = $.Deferred(); var promise = deferred.promise(); OCA.Files.Files.isFileNameValid(name); name = this.getUniqueName(name); if (this.lastAction) { this.lastAction(); } $.post( OC.generateUrl('/apps/files/ajax/newfolder.php'), { dir: this.getCurrentDirectory(), foldername: name }, function(result) { if (result.status === 'success') { self.add(result.data, {animate: true, scrollTo: true}); deferred.resolve(result.status, result.data); } else { if (result.data && result.data.message) { OC.Notification.showTemporary(result.data.message); } else { OC.Notification.showTemporary(t('core', 'Could not create folder')); } deferred.reject(result.status); } } ); return promise; }, /** * Returns whether the given file name exists in the list * * @param {string} file file name * * @return {bool} true if the file exists in the list, false otherwise */ inList:function(file) { return this.findFileEl(file).length; }, /** * Shows busy state on a given file row or multiple * * @param {string|Array.<string>} files file name or array of file names * @param {bool} [busy=true] busy state, true for busy, false to remove busy state * * @since 8.2 */ showFileBusyState: function(files, state) { var self = this; if (!_.isArray(files)) { files = [files]; } if (_.isUndefined(state)) { state = true; } _.each(files, function($tr) { // jquery element already ? if (!$tr.is) { $tr = self.findFileEl($tr); } var $thumbEl = $tr.find('.thumbnail'); $tr.toggleClass('busy', state); if (state) { $thumbEl.attr('data-oldimage', $thumbEl.css('background-image')); $thumbEl.css('background-image', 'url('+ OC.imagePath('core', 'loading.gif') + ')'); } else { $thumbEl.css('background-image', $thumbEl.attr('data-oldimage')); $thumbEl.removeAttr('data-oldimage'); } }); }, /** * Delete the given files from the given dir * @param files file names list (without path) * @param dir directory in which to delete the files, defaults to the current * directory */ do_delete:function(files, dir) { var self = this; var params; if (files && files.substr) { files=[files]; } if (files) { this.showFileBusyState(files, true); for (var i=0; i<files.length; i++) { } } // Finish any existing actions if (this.lastAction) { this.lastAction(); } params = { dir: dir || this.getCurrentDirectory() }; if (files) { params.files = JSON.stringify(files); } else { // no files passed, delete all in current dir params.allfiles = true; // show spinner for all files this.showFileBusyState(this.$fileList.find('tr'), true); } $.post(OC.filePath('files', 'ajax', 'delete.php'), params, function(result) { if (result.status === 'success') { if (params.allfiles) { self.setFiles([]); } else { $.each(files,function(index,file) { var fileEl = self.remove(file, {updateSummary: false}); // FIXME: not sure why we need this after the // element isn't even in the DOM any more fileEl.find('.selectCheckBox').prop('checked', false); fileEl.removeClass('selected'); self.fileSummary.remove({type: fileEl.attr('data-type'), size: fileEl.attr('data-size')}); }); } // TODO: this info should be returned by the ajax call! self.updateEmptyContent(); self.fileSummary.update(); self.updateSelectionSummary(); self.updateStorageStatistics(); } else { if (result.status === 'error' && result.data.message) { OC.Notification.show(result.data.message); } else { OC.Notification.show(t('files', 'Error deleting file.')); } // hide notification after 10 sec setTimeout(function() { OC.Notification.hide(); }, 10000); if (params.allfiles) { // reload the page as we don't know what files were deleted // and which ones remain self.reload(); } else { $.each(files,function(index,file) { self.showFileBusyState(file, false); }); } } }); }, /** * Creates the file summary section */ _createSummary: function() { var $tr = $('<tr class="summary"></tr>'); this.$el.find('tfoot').append($tr); return new OCA.Files.FileSummary($tr); }, updateEmptyContent: function() { var permissions = this.getDirectoryPermissions(); var isCreatable = (permissions & OC.PERMISSION_CREATE) !== 0; this.$el.find('#emptycontent').toggleClass('hidden', !this.isEmpty); this.$el.find('#emptycontent .uploadmessage').toggleClass('hidden', !isCreatable || !this.isEmpty); this.$el.find('#filestable thead th').toggleClass('hidden', this.isEmpty); }, /** * Shows the loading mask. * * @see OCA.Files.FileList#hideMask */ showMask: function() { // in case one was shown before var $mask = this.$el.find('.mask'); if ($mask.exists()) { return; } this.$table.addClass('hidden'); this.$el.find('#emptycontent').addClass('hidden'); $mask = $('<div class="mask transparent"></div>'); $mask.css('background-image', 'url('+ OC.imagePath('core', 'loading.gif') + ')'); $mask.css('background-repeat', 'no-repeat'); this.$el.append($mask); $mask.removeClass('transparent'); }, /** * Hide the loading mask. * @see OCA.Files.FileList#showMask */ hideMask: function() { this.$el.find('.mask').remove(); this.$table.removeClass('hidden'); }, scrollTo:function(file) { if (!_.isArray(file)) { file = [file]; } this.highlightFiles(file, function($tr) { $tr.addClass('searchresult'); $tr.one('hover', function() { $tr.removeClass('searchresult'); }); }); }, /** * @deprecated use setFilter(filter) */ filter:function(query) { this.setFilter(''); }, /** * @deprecated use setFilter('') */ unfilter:function() { this.setFilter(''); }, /** * hide files matching the given filter * @param filter */ setFilter:function(filter) { this._filter = filter; this.fileSummary.setFilter(filter, this.files); if (!this.$el.find('.mask').exists()) { this.hideIrrelevantUIWhenNoFilesMatch(); } var that = this; this.$fileList.find('tr').each(function(i,e) { var $e = $(e); if ($e.data('file').toString().toLowerCase().indexOf(filter.toLowerCase()) === -1) { $e.addClass('hidden'); that.$container.trigger('scroll'); } else { $e.removeClass('hidden'); } }); }, hideIrrelevantUIWhenNoFilesMatch:function() { if (this._filter && this.fileSummary.summary.totalDirs + this.fileSummary.summary.totalFiles === 0) { this.$el.find('#filestable thead th').addClass('hidden'); this.$el.find('#emptycontent').addClass('hidden'); $('#searchresults').addClass('filter-empty'); if ( $('#searchresults').length === 0 || $('#searchresults').hasClass('hidden') ) { this.$el.find('.nofilterresults').removeClass('hidden'). find('p').text(t('files', "No entries in this folder match '{filter}'", {filter:this._filter}, null, {'escape': false})); } } else { $('#searchresults').removeClass('filter-empty'); this.$el.find('#filestable thead th').toggleClass('hidden', this.isEmpty); if (!this.$el.find('.mask').exists()) { this.$el.find('#emptycontent').toggleClass('hidden', !this.isEmpty); } this.$el.find('.nofilterresults').addClass('hidden'); } }, /** * get the current filter * @param filter */ getFilter:function(filter) { return this._filter; }, /** * update the search object to use this filelist when filtering */ updateSearch:function() { if (OCA.Search.files) { OCA.Search.files.setFileList(this); } if (OC.Search) { OC.Search.clear(); } }, /** * Update UI based on the current selection */ updateSelectionSummary: function() { var summary = this._selectionSummary.summary; var canDelete; var selection; if (summary.totalFiles === 0 && summary.totalDirs === 0) { this.$el.find('#headerName a.name>span:first').text(t('files','Name')); this.$el.find('#headerSize a>span:first').text(t('files','Size')); this.$el.find('#modified a>span:first').text(t('files','Modified')); this.$el.find('table').removeClass('multiselect'); this.$el.find('.selectedActions').addClass('hidden'); } else { canDelete = (this.getDirectoryPermissions() & OC.PERMISSION_DELETE) && this.isSelectedDeletable(); this.$el.find('.selectedActions').removeClass('hidden'); this.$el.find('#headerSize a>span:first').text(OC.Util.humanFileSize(summary.totalSize)); var directoryInfo = n('files', '%n folder', '%n folders', summary.totalDirs); var fileInfo = n('files', '%n file', '%n files', summary.totalFiles); if (summary.totalDirs > 0 && summary.totalFiles > 0) { var selectionVars = { dirs: directoryInfo, files: fileInfo }; selection = t('files', '{dirs} and {files}', selectionVars); } else if (summary.totalDirs > 0) { selection = directoryInfo; } else { selection = fileInfo; } this.$el.find('#headerName a.name>span:first').text(selection); this.$el.find('#modified a>span:first').text(''); this.$el.find('table').addClass('multiselect'); this.$el.find('.delete-selected').toggleClass('hidden', !canDelete); } }, /** * Check whether all selected files are deletable */ isSelectedDeletable: function() { return _.reduce(this.getSelectedFiles(), function(deletable, file) { return deletable && (file.permissions & OC.PERMISSION_DELETE); }, true); }, /** * Returns whether all files are selected * @return true if all files are selected, false otherwise */ isAllSelected: function() { return this.$el.find('.select-all').prop('checked'); }, /** * Returns the file info of the selected files * * @return array of file names */ getSelectedFiles: function() { return _.values(this._selectedFiles); }, getUniqueName: function(name) { if (this.findFileEl(name).exists()) { var numMatch; var parts=name.split('.'); var extension = ""; if (parts.length > 1) { extension=parts.pop(); } var base=parts.join('.'); numMatch=base.match(/\((\d+)\)/); var num=2; if (numMatch && numMatch.length>0) { num=parseInt(numMatch[numMatch.length-1], 10)+1; base=base.split('('); base.pop(); base=$.trim(base.join('(')); } name=base+' ('+num+')'; if (extension) { name = name+'.'+extension; } // FIXME: ugly recursion return this.getUniqueName(name); } return name; }, /** * Shows a "permission denied" notification */ _showPermissionDeniedNotification: function() { var message = t('core', 'You don’t have permission to upload or create files here'); OC.Notification.show(message); //hide notification after 10 sec setTimeout(function() { OC.Notification.hide(); }, 5000); }, /** * Setup file upload events related to the file-upload plugin */ setupUploadEvents: function() { var self = this; // handle upload events var fileUploadStart = this.$el.find('#file_upload_start'); // detect the progress bar resize fileUploadStart.on('resized', this._onResize); fileUploadStart.on('fileuploaddrop', function(e, data) { OC.Upload.log('filelist handle fileuploaddrop', e, data); if (self.$el.hasClass('hidden')) { // do not upload to invisible lists return false; } var dropTarget = $(e.originalEvent.target); // check if dropped inside this container and not another one if (dropTarget.length && !self.$el.is(dropTarget) // dropped on list directly && !self.$el.has(dropTarget).length // dropped inside list && !dropTarget.is(self.$container) // dropped on main container ) { return false; } // find the closest tr or crumb to use as target dropTarget = dropTarget.closest('tr, .crumb'); // if dropping on tr or crumb, drag&drop upload to folder if (dropTarget && (dropTarget.data('type') === 'dir' || dropTarget.hasClass('crumb'))) { // remember as context data.context = dropTarget; // if permissions are specified, only allow if create permission is there var permissions = dropTarget.data('permissions'); if (!_.isUndefined(permissions) && (permissions & OC.PERMISSION_CREATE) === 0) { self._showPermissionDeniedNotification(); return false; } var dir = dropTarget.data('file'); // if from file list, need to prepend parent dir if (dir) { var parentDir = self.getCurrentDirectory(); if (parentDir[parentDir.length - 1] !== '/') { parentDir += '/'; } dir = parentDir + dir; } else{ // read full path from crumb dir = dropTarget.data('dir') || '/'; } // add target dir data.targetDir = dir; } else { // we are dropping somewhere inside the file list, which will // upload the file to the current directory data.targetDir = self.getCurrentDirectory(); // cancel uploads to current dir if no permission var isCreatable = (self.getDirectoryPermissions() & OC.PERMISSION_CREATE) !== 0; if (!isCreatable) { self._showPermissionDeniedNotification(); return false; } } }); fileUploadStart.on('fileuploadadd', function(e, data) { OC.Upload.log('filelist handle fileuploadadd', e, data); //finish delete if we are uploading a deleted file if (self.deleteFiles && self.deleteFiles.indexOf(data.files[0].name)!==-1) { self.finishDelete(null, true); //delete file before continuing } // add ui visualization to existing folder if (data.context && data.context.data('type') === 'dir') { // add to existing folder // update upload counter ui var uploadText = data.context.find('.uploadtext'); var currentUploads = parseInt(uploadText.attr('currentUploads'), 10); currentUploads += 1; uploadText.attr('currentUploads', currentUploads); var translatedText = n('files', 'Uploading %n file', 'Uploading %n files', currentUploads); if (currentUploads === 1) { var img = OC.imagePath('core', 'loading.gif'); data.context.find('.thumbnail').css('background-image', 'url(' + img + ')'); uploadText.text(translatedText); uploadText.show(); } else { uploadText.text(translatedText); } } }); /* * when file upload done successfully add row to filelist * update counter when uploading to sub folder */ fileUploadStart.on('fileuploaddone', function(e, data) { OC.Upload.log('filelist handle fileuploaddone', e, data); var response; if (typeof data.result === 'string') { response = data.result; } else { // fetch response from iframe response = data.result[0].body.innerText; } var result=$.parseJSON(response); if (typeof result[0] !== 'undefined' && result[0].status === 'success') { var file = result[0]; var size = 0; if (data.context && data.context.data('type') === 'dir') { // update upload counter ui var uploadText = data.context.find('.uploadtext'); var currentUploads = parseInt(uploadText.attr('currentUploads'), 10); currentUploads -= 1; uploadText.attr('currentUploads', currentUploads); var translatedText = n('files', 'Uploading %n file', 'Uploading %n files', currentUploads); if (currentUploads === 0) { var img = OC.imagePath('core', 'filetypes/folder'); data.context.find('.thumbnail').css('background-image', 'url(' + img + ')'); uploadText.text(translatedText); uploadText.hide(); } else { uploadText.text(translatedText); } // update folder size size = parseInt(data.context.data('size'), 10); size += parseInt(file.size, 10); data.context.attr('data-size', size); data.context.find('td.filesize').text(humanFileSize(size)); } else { // only append new file if uploaded into the current folder if (file.directory !== self.getCurrentDirectory()) { // Uploading folders actually uploads a list of files // for which the target directory (file.directory) might lie deeper // than the current directory var fileDirectory = file.directory.replace('/','').replace(/\/$/, ""); var currentDirectory = self.getCurrentDirectory().replace('/','').replace(/\/$/, "") + '/'; if (currentDirectory !== '/') { // abort if fileDirectory does not start with current one if (fileDirectory.indexOf(currentDirectory) !== 0) { return; } // remove the current directory part fileDirectory = fileDirectory.substr(currentDirectory.length); } // only take the first section of the path fileDirectory = fileDirectory.split('/'); var fd; // if the first section exists / is a subdir if (fileDirectory.length) { fileDirectory = fileDirectory[0]; // See whether it is already in the list fd = self.findFileEl(fileDirectory); if (fd.length === 0) { var dir = { name: fileDirectory, type: 'dir', mimetype: 'httpd/unix-directory', permissions: file.permissions, size: 0, id: file.parentId }; fd = self.add(dir, {insert: true}); } // update folder size size = parseInt(fd.attr('data-size'), 10); size += parseInt(file.size, 10); fd.attr('data-size', size); fd.find('td.filesize').text(OC.Util.humanFileSize(size)); } return; } // add as stand-alone row to filelist size = t('files', 'Pending'); if (data.files[0].size>=0) { size=data.files[0].size; } //should the file exist in the list remove it self.remove(file.name); // create new file context data.context = self.add(file, {animate: true}); } } }); fileUploadStart.on('fileuploadstop', function(e, data) { OC.Upload.log('filelist handle fileuploadstop', e, data); //if user pressed cancel hide upload chrome if (data.errorThrown === 'abort') { //cleanup uploading to a dir var uploadText = $('tr .uploadtext'); var img = OC.imagePath('core', 'filetypes/folder'); uploadText.parents('td.filename').find('.thumbnail').css('background-image', 'url(' + img + ')'); uploadText.fadeOut(); uploadText.attr('currentUploads', 0); } self.updateStorageStatistics(); }); fileUploadStart.on('fileuploadfail', function(e, data) { OC.Upload.log('filelist handle fileuploadfail', e, data); //if user pressed cancel hide upload chrome if (data.errorThrown === 'abort') { //cleanup uploading to a dir var uploadText = $('tr .uploadtext'); var img = OC.imagePath('core', 'filetypes/folder'); uploadText.parents('td.filename').find('.thumbnail').css('background-image', 'url(' + img + ')'); uploadText.fadeOut(); uploadText.attr('currentUploads', 0); } self.updateStorageStatistics(); }); }, /** * Scroll to the last file of the given list * Highlight the list of files * @param files array of filenames, * @param {Function} [highlightFunction] optional function * to be called after the scrolling is finished */ highlightFiles: function(files, highlightFunction) { // Detection of the uploaded element var filename = files[files.length - 1]; var $fileRow = this.findFileEl(filename); while(!$fileRow.exists() && this._nextPage(false) !== false) { // Checking element existence $fileRow = this.findFileEl(filename); } if (!$fileRow.exists()) { // Element not present in the file list return; } var currentOffset = this.$container.scrollTop(); var additionalOffset = this.$el.find("#controls").height()+this.$el.find("#controls").offset().top; // Animation var _this = this; var $scrollContainer = this.$container; if ($scrollContainer[0] === window) { // need to use "body" to animate scrolling // when the scroll container is the window $scrollContainer = $('body'); } $scrollContainer.animate({ // Scrolling to the top of the new element scrollTop: currentOffset + $fileRow.offset().top - $fileRow.height() * 2 - additionalOffset }, { duration: 500, complete: function() { // Highlighting function var highlightRow = highlightFunction; if (!highlightRow) { highlightRow = function($fileRow) { $fileRow.addClass("highlightUploaded"); setTimeout(function() { $fileRow.removeClass("highlightUploaded"); }, 2500); }; } // Loop over uploaded files for(var i=0; i<files.length; i++) { var $fileRow = _this.findFileEl(files[i]); if($fileRow.length !== 0) { // Checking element existence highlightRow($fileRow); } } } }); }, _renderNewButton: function() { // if an upload button (legacy) already exists, skip if ($('#controls .button.upload').length) { return; } if (!this._addButtonTemplate) { this._addButtonTemplate = Handlebars.compile(TEMPLATE_ADDBUTTON); } var $newButton = $(this._addButtonTemplate({ addText: t('files', 'New'), iconUrl: OC.imagePath('core', 'actions/add') })); $('#controls .actions').prepend($newButton); $newButton.tooltip({'placement': 'bottom'}); $newButton.click(_.bind(this._onClickNewButton, this)); this._newButton = $newButton; }, _onClickNewButton: function(event) { var $target = $(event.target); if (!$target.hasClass('.button')) { $target = $target.closest('.button'); } this._newButton.tooltip('hide'); event.preventDefault(); if ($target.hasClass('disabled')) { return false; } if (!this._newFileMenu) { this._newFileMenu = new OCA.Files.NewFileMenu({ fileList: this }); $('body').append(this._newFileMenu.$el); } this._newFileMenu.showAt($target); return false; }, /** * Register a tab view to be added to all views */ registerTabView: function(tabView) { this._detailsView.addTabView(tabView); }, /** * Register a detail view to be added to all views */ registerDetailView: function(detailView) { this._detailsView.addDetailView(detailView); } }; /** * Sort comparators. * @namespace OCA.Files.FileList.Comparators * @private */ FileList.Comparators = { /** * Compares two file infos by name, making directories appear * first. * * @param {OCA.Files.FileInfo} fileInfo1 file info * @param {OCA.Files.FileInfo} fileInfo2 file info * @return {int} -1 if the first file must appear before the second one, * 0 if they are identify, 1 otherwise. */ name: function(fileInfo1, fileInfo2) { if (fileInfo1.type === 'dir' && fileInfo2.type !== 'dir') { return -1; } if (fileInfo1.type !== 'dir' && fileInfo2.type === 'dir') { return 1; } return OC.Util.naturalSortCompare(fileInfo1.name, fileInfo2.name); }, /** * Compares two file infos by size. * * @param {OCA.Files.FileInfo} fileInfo1 file info * @param {OCA.Files.FileInfo} fileInfo2 file info * @return {int} -1 if the first file must appear before the second one, * 0 if they are identify, 1 otherwise. */ size: function(fileInfo1, fileInfo2) { return fileInfo1.size - fileInfo2.size; }, /** * Compares two file infos by timestamp. * * @param {OCA.Files.FileInfo} fileInfo1 file info * @param {OCA.Files.FileInfo} fileInfo2 file info * @return {int} -1 if the first file must appear before the second one, * 0 if they are identify, 1 otherwise. */ mtime: function(fileInfo1, fileInfo2) { return fileInfo1.mtime - fileInfo2.mtime; } }; /** * File info attributes. * * @todo make this a real class in the future * @typedef {Object} OCA.Files.FileInfo * * @property {int} id file id * @property {String} name file name * @property {String} [path] file path, defaults to the list's current path * @property {String} mimetype mime type * @property {String} type "file" for files or "dir" for directories * @property {int} permissions file permissions * @property {int} mtime modification time in milliseconds * @property {boolean} [isShareMountPoint] whether the file is a share mount * point * @property {boolean} [isPreviewAvailable] whether a preview is available * for the given file type * @property {String} [icon] path to the mime type icon * @property {String} etag etag of the file */ OCA.Files.FileList = FileList; })(); $(document).ready(function() { // FIXME: unused ? OCA.Files.FileList.useUndo = (window.onbeforeunload)?true:false; $(window).bind('beforeunload', function () { if (OCA.Files.FileList.lastAction) { OCA.Files.FileList.lastAction(); } }); $(window).unload(function () { $(window).trigger('beforeunload'); }); });
Keep right sidebar open, add Details action
apps/files/js/filelist.js
Keep right sidebar open, add Details action
<ide><path>pps/files/js/filelist.js <ide> this._detailsView.addDetailView(new OCA.Files.MainFileInfoDetailView({fileList: this, fileActions: this.fileActions})); <ide> this._detailsView.$el.insertBefore(this.$el); <ide> this._detailsView.$el.addClass('disappear'); <add> <add> this.fileActions.registerAction({ <add> name: 'Details', <add> mime: 'all', <add> permissions: OC.PERMISSION_READ, <add> actionHandler: function(fileName, context) { <add> var fileInfo = self.elementToFile(context.$file); <add> self._updateDetailsView(fileInfo); <add> OC.Apps.showAppSidebar(); <add> } <add> }); <ide> } <ide> <ide> this.$el.find('#controls').prepend(this.breadcrumb.$el); <ide> } <ide> <ide> if (!fileName) { <del> OC.Apps.hideAppSidebar(this._detailsView.$el); <ide> this._detailsView.setFileInfo(null); <ide> if (this._currentFileModel) { <ide> this._currentFileModel.off(); <ide> <ide> this._detailsView.setFileInfo(model); <ide> this._detailsView.$el.scrollTop(0); <del> _.defer(OC.Apps.showAppSidebar, this._detailsView.$el); <ide> }, <ide> <ide> /**
Java
apache-2.0
0ade2baa2776be55332b76ae6fe49932fa6d07a1
0
allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.xml; import com.intellij.codeInsight.daemon.impl.HighlightInfoType; import com.intellij.ide.highlighter.XHtmlFileType; import com.intellij.lang.ASTNode; import com.intellij.openapi.extensions.ExtensionPointName; import com.intellij.openapi.fileTypes.FileType; import com.intellij.openapi.fileTypes.StdFileTypes; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiFile; import com.intellij.psi.html.HtmlTag; import com.intellij.psi.impl.source.html.dtd.HtmlNSDescriptorImpl; import com.intellij.psi.impl.source.xml.SchemaPrefix; import com.intellij.psi.impl.source.xml.TagNameReference; import com.intellij.psi.impl.source.xml.XmlDocumentImpl; import com.intellij.psi.search.LocalSearchScope; import com.intellij.psi.search.SearchScope; import com.intellij.psi.util.CachedValueProvider; import com.intellij.psi.util.CachedValuesManager; import com.intellij.psi.util.PsiModificationTracker; import com.intellij.psi.xml.XmlAttribute; import com.intellij.psi.xml.XmlDocument; import com.intellij.psi.xml.XmlFile; import com.intellij.psi.xml.XmlTag; import com.intellij.util.containers.ContainerUtil; import com.intellij.xml.impl.schema.AnyXmlElementDescriptor; import com.intellij.xml.util.HtmlUtil; import com.intellij.xml.util.XmlUtil; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.Collections; import java.util.List; /** * @author Dmitry Avdeev */ public abstract class XmlExtension { public static final ExtensionPointName<XmlExtension> EP_NAME = new ExtensionPointName<>("com.intellij.xml.xmlExtension"); public static XmlExtension getExtension(@NotNull final PsiFile file) { return CachedValuesManager.getCachedValue(file, () -> CachedValueProvider.Result.create(calcExtension(file), PsiModificationTracker.MODIFICATION_COUNT)); } public interface AttributeValuePresentation { @NotNull String getPrefix(); @NotNull String getPostfix(); default boolean showAutoPopup() { return true; } } private static XmlExtension calcExtension(PsiFile file) { for (XmlExtension extension : EP_NAME.getExtensionList()) { if (extension.isAvailable(file)) { return extension; } } return DefaultXmlExtension.DEFAULT_EXTENSION; } public static XmlExtension getExtensionByElement(PsiElement element) { final PsiFile psiFile = element.getContainingFile(); if (psiFile != null) { return getExtension(psiFile); } return null; } public abstract boolean isAvailable(PsiFile file); public static class TagInfo { public final String name; public final String namespace; public TagInfo(String name, String namespace) { this.name = name; this.namespace = namespace; } @Nullable public PsiElement getDeclaration() { return null; } } @NotNull public abstract List<TagInfo> getAvailableTagNames(@NotNull final XmlFile file, @NotNull final XmlTag context); @Nullable public TagNameReference createTagNameReference(final ASTNode nameElement, final boolean startTagFlag) { return new TagNameReference(nameElement, startTagFlag); } public String[] @Nullable [] getNamespacesFromDocument(final XmlDocument parent, boolean declarationsExist) { return declarationsExist ? null : XmlUtil.getDefaultNamespaces(parent); } public boolean canBeDuplicated(XmlAttribute attribute) { return false; } public boolean isRequiredAttributeImplicitlyPresent(XmlTag tag, String attrName) { return false; } public HighlightInfoType getHighlightInfoType(XmlFile file) { return HighlightInfoType.ERROR; } @Nullable public abstract SchemaPrefix getPrefixDeclaration(final XmlTag context, String namespacePrefix); public SearchScope getNsPrefixScope(XmlAttribute declaration) { return new LocalSearchScope(declaration.getParent()); } public boolean shouldBeHighlightedAsTag(XmlTag tag) { return true; } @Nullable public XmlElementDescriptor getElementDescriptor(XmlTag tag, XmlTag contextTag, final XmlElementDescriptor parentDescriptor) { return parentDescriptor.getElementDescriptor(tag, contextTag); } @Nullable public XmlNSDescriptor getNSDescriptor(final XmlTag element, final String namespace, final boolean strict) { return element.getNSDescriptor(namespace, strict); } public @NotNull XmlNSDescriptor wrapNSDescriptor(@NotNull XmlTag element, @NotNull String namespacePrefix, @NotNull XmlNSDescriptor descriptor) { if (element instanceof HtmlTag && !(descriptor instanceof HtmlNSDescriptorImpl)) { XmlFile obj = descriptor.getDescriptorFile(); XmlNSDescriptor result = obj == null ? null : XmlDocumentImpl.getCachedHtmlNsDescriptor(obj, namespacePrefix); return result == null ? new HtmlNSDescriptorImpl(descriptor) : result; } return descriptor; } @Nullable public XmlTag getParentTagForNamespace(XmlTag tag, XmlNSDescriptor namespace) { return tag.getParentTag(); } @Nullable public XmlFile getContainingFile(PsiElement element) { if (element == null) { return null; } final PsiFile psiFile = element.getContainingFile(); return psiFile instanceof XmlFile ? (XmlFile)psiFile : null; } public XmlNSDescriptor getDescriptorFromDoctype(final XmlFile containingFile, XmlNSDescriptor descr) { return descr; } public boolean hasDynamicComponents(final PsiElement element) { return false; } public boolean isIndirectSyntax(final XmlAttributeDescriptor descriptor) { return false; } public boolean shouldBeInserted(final XmlAttributeDescriptor descriptor) { return descriptor.isRequired(); } public boolean shouldCompleteTag(XmlTag context) { return true; } @NotNull public AttributeValuePresentation getAttributeValuePresentation(@Nullable XmlTag tag, @NotNull String attributeName, @NotNull String defaultAttributeQuote) { return new AttributeValuePresentation() { @NotNull @Override public String getPrefix() { return defaultAttributeQuote; } @NotNull @Override public String getPostfix() { return defaultAttributeQuote; } }; } public boolean isCustomTagAllowed(final XmlTag tag) { return false; } public boolean useXmlTagInsertHandler() { return true; } public boolean isCollapsibleTag(XmlTag tag) { return false; } public boolean isSelfClosingTagAllowed(@NotNull XmlTag tag) { return false; } public boolean isSingleTagException(@NotNull XmlTag tag) { return false; } public boolean isValidTagNameChar(final char c) { return false; } /** * @return list of files containing char entity definitions to be used for completion and resolution within a specified XML file */ public @NotNull List<@NotNull XmlFile> getCharEntitiesDTDs(@NotNull XmlFile file) { XmlDocument document = file.getDocument(); if (HtmlUtil.isHtml5Document(document)) { return ContainerUtil.packNullables(XmlUtil.findXmlFile(file, Html5SchemaProvider.getCharsDtdLocation())); } else if (document != null) { final XmlTag rootTag = document.getRootTag(); if (rootTag != null) { final XmlElementDescriptor descriptor = rootTag.getDescriptor(); if (descriptor != null && !(descriptor instanceof AnyXmlElementDescriptor)) { PsiElement element = descriptor.getDeclaration(); final PsiFile containingFile = element != null ? element.getContainingFile() : null; if (containingFile instanceof XmlFile) { return Collections.singletonList((XmlFile)containingFile); } } } final FileType ft = file.getFileType(); final String namespace = ft == XHtmlFileType.INSTANCE || ft == StdFileTypes.JSPX ? XmlUtil.XHTML_URI : XmlUtil.HTML_URI; final XmlNSDescriptor nsDescriptor = document.getDefaultNSDescriptor(namespace, true); if (nsDescriptor != null) { return ContainerUtil.packNullables(nsDescriptor.getDescriptorFile()); } } return Collections.emptyList(); } public static boolean shouldIgnoreSelfClosingTag(@NotNull XmlTag tag) { final XmlExtension extension = getExtensionByElement(tag); return extension != null && extension.isSelfClosingTagAllowed(tag); } public static boolean isCollapsible(XmlTag tag) { final XmlExtension extension = getExtensionByElement(tag); return extension == null || extension.isCollapsibleTag(tag); } }
xml/xml-psi-impl/src/com/intellij/xml/XmlExtension.java
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.xml; import com.intellij.codeInsight.daemon.impl.HighlightInfoType; import com.intellij.ide.highlighter.XHtmlFileType; import com.intellij.lang.ASTNode; import com.intellij.openapi.extensions.ExtensionPointName; import com.intellij.openapi.fileTypes.FileType; import com.intellij.openapi.fileTypes.StdFileTypes; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiFile; import com.intellij.psi.html.HtmlTag; import com.intellij.psi.impl.source.html.dtd.HtmlNSDescriptorImpl; import com.intellij.psi.impl.source.xml.SchemaPrefix; import com.intellij.psi.impl.source.xml.TagNameReference; import com.intellij.psi.impl.source.xml.XmlDocumentImpl; import com.intellij.psi.search.LocalSearchScope; import com.intellij.psi.search.SearchScope; import com.intellij.psi.util.CachedValueProvider; import com.intellij.psi.util.CachedValuesManager; import com.intellij.psi.util.PsiModificationTracker; import com.intellij.psi.xml.XmlAttribute; import com.intellij.psi.xml.XmlDocument; import com.intellij.psi.xml.XmlFile; import com.intellij.psi.xml.XmlTag; import com.intellij.util.containers.ContainerUtil; import com.intellij.xml.impl.schema.AnyXmlElementDescriptor; import com.intellij.xml.util.HtmlUtil; import com.intellij.xml.util.XmlUtil; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.Collections; import java.util.List; /** * @author Dmitry Avdeev */ public abstract class XmlExtension { public static final ExtensionPointName<XmlExtension> EP_NAME = new ExtensionPointName<>("com.intellij.xml.xmlExtension"); public static XmlExtension getExtension(@NotNull final PsiFile file) { return CachedValuesManager.getCachedValue(file, () -> CachedValueProvider.Result.create(calcExtension(file), PsiModificationTracker.MODIFICATION_COUNT)); } public interface AttributeValuePresentation { @NotNull String getPrefix(); @NotNull String getPostfix(); default boolean showAutoPopup() { return true; } } private static XmlExtension calcExtension(PsiFile file) { for (XmlExtension extension : EP_NAME.getExtensionList()) { if (extension.isAvailable(file)) { return extension; } } return DefaultXmlExtension.DEFAULT_EXTENSION; } public static XmlExtension getExtensionByElement(PsiElement element) { final PsiFile psiFile = element.getContainingFile(); if (psiFile != null) { return getExtension(psiFile); } return null; } public abstract boolean isAvailable(PsiFile file); public static class TagInfo { public final String name; public final String namespace; public TagInfo(String name, String namespace) { this.name = name; this.namespace = namespace; } @Nullable public PsiElement getDeclaration() { return null; } } @NotNull public abstract List<TagInfo> getAvailableTagNames(@NotNull final XmlFile file, @NotNull final XmlTag context); @Nullable public TagNameReference createTagNameReference(final ASTNode nameElement, final boolean startTagFlag) { return new TagNameReference(nameElement, startTagFlag); } public String[] @Nullable [] getNamespacesFromDocument(final XmlDocument parent, boolean declarationsExist) { return declarationsExist ? null : XmlUtil.getDefaultNamespaces(parent); } public boolean canBeDuplicated(XmlAttribute attribute) { return false; } public boolean isRequiredAttributeImplicitlyPresent(XmlTag tag, String attrName) { return false; } public boolean isImplicitlyLabelledTag(@NotNull XmlTag tag) { return false; } public HighlightInfoType getHighlightInfoType(XmlFile file) { return HighlightInfoType.ERROR; } @Nullable public abstract SchemaPrefix getPrefixDeclaration(final XmlTag context, String namespacePrefix); public SearchScope getNsPrefixScope(XmlAttribute declaration) { return new LocalSearchScope(declaration.getParent()); } public boolean shouldBeHighlightedAsTag(XmlTag tag) { return true; } @Nullable public XmlElementDescriptor getElementDescriptor(XmlTag tag, XmlTag contextTag, final XmlElementDescriptor parentDescriptor) { return parentDescriptor.getElementDescriptor(tag, contextTag); } @Nullable public XmlNSDescriptor getNSDescriptor(final XmlTag element, final String namespace, final boolean strict) { return element.getNSDescriptor(namespace, strict); } public @NotNull XmlNSDescriptor wrapNSDescriptor(@NotNull XmlTag element, @NotNull String namespacePrefix, @NotNull XmlNSDescriptor descriptor) { if (element instanceof HtmlTag && !(descriptor instanceof HtmlNSDescriptorImpl)) { XmlFile obj = descriptor.getDescriptorFile(); XmlNSDescriptor result = obj == null ? null : XmlDocumentImpl.getCachedHtmlNsDescriptor(obj, namespacePrefix); return result == null ? new HtmlNSDescriptorImpl(descriptor) : result; } return descriptor; } @Nullable public XmlTag getParentTagForNamespace(XmlTag tag, XmlNSDescriptor namespace) { return tag.getParentTag(); } @Nullable public XmlFile getContainingFile(PsiElement element) { if (element == null) { return null; } final PsiFile psiFile = element.getContainingFile(); return psiFile instanceof XmlFile ? (XmlFile)psiFile : null; } public XmlNSDescriptor getDescriptorFromDoctype(final XmlFile containingFile, XmlNSDescriptor descr) { return descr; } public boolean hasDynamicComponents(final PsiElement element) { return false; } public boolean isIndirectSyntax(final XmlAttributeDescriptor descriptor) { return false; } public boolean shouldBeInserted(final XmlAttributeDescriptor descriptor) { return descriptor.isRequired(); } public boolean shouldCompleteTag(XmlTag context) { return true; } @NotNull public AttributeValuePresentation getAttributeValuePresentation(@Nullable XmlTag tag, @NotNull String attributeName, @NotNull String defaultAttributeQuote) { return new AttributeValuePresentation() { @NotNull @Override public String getPrefix() { return defaultAttributeQuote; } @NotNull @Override public String getPostfix() { return defaultAttributeQuote; } }; } public boolean isCustomTagAllowed(final XmlTag tag) { return false; } public boolean useXmlTagInsertHandler() { return true; } public boolean isCollapsibleTag(XmlTag tag) { return false; } public boolean isSelfClosingTagAllowed(@NotNull XmlTag tag) { return false; } public boolean isSingleTagException(@NotNull XmlTag tag) { return false; } public boolean isValidTagNameChar(final char c) { return false; } /** * @return list of files containing char entity definitions to be used for completion and resolution within a specified XML file */ public @NotNull List<@NotNull XmlFile> getCharEntitiesDTDs(@NotNull XmlFile file) { XmlDocument document = file.getDocument(); if (HtmlUtil.isHtml5Document(document)) { return ContainerUtil.packNullables(XmlUtil.findXmlFile(file, Html5SchemaProvider.getCharsDtdLocation())); } else if (document != null) { final XmlTag rootTag = document.getRootTag(); if (rootTag != null) { final XmlElementDescriptor descriptor = rootTag.getDescriptor(); if (descriptor != null && !(descriptor instanceof AnyXmlElementDescriptor)) { PsiElement element = descriptor.getDeclaration(); final PsiFile containingFile = element != null ? element.getContainingFile() : null; if (containingFile instanceof XmlFile) { return Collections.singletonList((XmlFile)containingFile); } } } final FileType ft = file.getFileType(); final String namespace = ft == XHtmlFileType.INSTANCE || ft == StdFileTypes.JSPX ? XmlUtil.XHTML_URI : XmlUtil.HTML_URI; final XmlNSDescriptor nsDescriptor = document.getDefaultNSDescriptor(namespace, true); if (nsDescriptor != null) { return ContainerUtil.packNullables(nsDescriptor.getDescriptorFile()); } } return Collections.emptyList(); } public static boolean shouldIgnoreSelfClosingTag(@NotNull XmlTag tag) { final XmlExtension extension = getExtensionByElement(tag); return extension != null && extension.isSelfClosingTagAllowed(tag); } public static boolean isCollapsible(XmlTag tag) { final XmlExtension extension = getExtensionByElement(tag); return extension == null || extension.isCollapsibleTag(tag); } }
angular: WEB-43748 fix input missing associated label inspection with Angular Material - code review changes GitOrigin-RevId: ddea18ab64162f6c4c08d817ff8914b8ffead9d2
xml/xml-psi-impl/src/com/intellij/xml/XmlExtension.java
angular: WEB-43748 fix input missing associated label inspection with Angular Material - code review changes
<ide><path>ml/xml-psi-impl/src/com/intellij/xml/XmlExtension.java <ide> return false; <ide> } <ide> <del> public boolean isImplicitlyLabelledTag(@NotNull XmlTag tag) { <del> return false; <del> } <del> <ide> public HighlightInfoType getHighlightInfoType(XmlFile file) { <ide> return HighlightInfoType.ERROR; <ide> }
JavaScript
bsd-2-clause
9946ee8493fe48198dfd974669747a6a401a4b3e
0
campbellwmorgan/nunjucks,atorkhov/nunjucks,vigetlabs/nunjucks,kevinschaul/nunjucks,AaronO/nunjucks,node-modules/nunjucks,campbellwmorgan/nunjucks,mozilla/nunjucks,santoshsahoo/nunjucks,rhengles/nunjucks,node-modules/nunjucks,carljm/nunjucks,rhengles/nunjucks,robgraeber/nunjucks,campbellwmorgan/nunjucks,kevinschaul/nunjucks,node-modules/nunjucks,vigetlabs/nunjucks,internalfx/nunjucks,punkave/nunjucks,atorkhov/nunjucks,internalfx/nunjucks,carljm/nunjucks,internalfx/nunjucks,AaronO/nunjucks,fabien/nunjucks,internalfx/nunjucks,devoidfury/nunjucks,robgraeber/nunjucks,mozilla/nunjucks,oddbird/nunjucks,pardo/nunjucks,santoshsahoo/nunjucks,fabien/nunjucks,pardo/nunjucks,atorkhov/nunjucks,carljm/nunjucks,punkave/nunjucks,atorkhov/nunjucks,carljm/nunjucks,pardo/nunjucks,fabien/nunjucks,punkave/nunjucks,santoshsahoo/nunjucks,pardo/nunjucks,robgraeber/nunjucks,fabien/nunjucks,AaronO/nunjucks,campbellwmorgan/nunjucks,oddbird/nunjucks,rhengles/nunjucks,kevinschaul/nunjucks,santoshsahoo/nunjucks,vigetlabs/nunjucks,AaronO/nunjucks,node-modules/nunjucks,devoidfury/nunjucks,mozilla/nunjucks,punkave/nunjucks,kevinschaul/nunjucks,devoidfury/nunjucks,robgraeber/nunjucks,rhengles/nunjucks,oddbird/nunjucks,oddbird/nunjucks,vigetlabs/nunjucks
var fs = require('fs'); var path = require('path'); var lib = require('./lib'); var Loader = require('./loader'); var chokidar = require('chokidar'); // Node <0.7.1 compatibility var existsSync = fs.existsSync || path.existsSync; var FileSystemLoader = Loader.extend({ init: function(searchPaths, noWatch, noCache) { this.pathsToNames = {}; this.noCache = !!noCache; if(searchPaths) { searchPaths = lib.isArray(searchPaths) ? searchPaths : [searchPaths]; // For windows, convert to forward slashes this.searchPaths = searchPaths.map(path.normalize); } else { this.searchPaths = ['.']; } if(!noWatch) { // Watch all the templates in the paths and fire an event when // they change lib.each(this.searchPaths, function(p) { if(existsSync(p)) { var watcher = chokidar.watch(p, { ignoreInitial: true }); watcher.on("all", function(event, fullname) { if(event == "change" && fullname in this.pathsToNames) { this.emit('update', this.pathsToNames[fullname]); } }.bind(this)); } }.bind(this)); } }, getSource: function(name) { var fullpath = null; var paths = this.searchPaths; for(var i=0; i<paths.length; i++) { var basePath = path.resolve(paths[i]); var p = path.resolve(paths[i], name); // Only allow the current directory and anything // underneath it to be searched if(p.indexOf(basePath) === 0 && existsSync(p)) { fullpath = p; break; } } if(!fullpath) { return null; } this.pathsToNames[fullpath] = name; return { src: fs.readFileSync(fullpath, 'utf-8'), path: fullpath, noCache: this.noCache }; } }); module.exports = { FileSystemLoader: FileSystemLoader };
src/node-loaders.js
var fs = require('fs'); var path = require('path'); var lib = require('./lib'); var Loader = require('./loader'); var chokidar = require('chokidar'); // Node <0.7.1 compatibility var existsSync = fs.existsSync || path.existsSync; var FileSystemLoader = Loader.extend({ init: function(searchPaths, noWatch, noCache) { this.pathsToNames = {}; this.noCache = !!noCache; if(searchPaths) { searchPaths = lib.isArray(searchPaths) ? searchPaths : [searchPaths]; // For windows, convert to forward slashes this.searchPaths = searchPaths.map(path.normalize); } else { this.searchPaths = ['.']; } if(!noWatch) { // Watch all the templates in the paths and fire an event when // they change lib.each(this.searchPaths, function(p) { if(existsSync(p)) { var watcher = chokidar.watch(p, { ignoreInitial: true }); watcher.on("all", function(event, fullname) { if(event == "change" && fullname in this.pathsToNames) { this.emit('update', this.pathsToNames[fullname]); } }.bind(this)); } }.bind(this)); } }, getSource: function(name) { var fullpath = null; var paths = this.searchPaths; for(var i=0; i<paths.length; i++) { var p = path.resolve(paths[i], name); // Only allow the current directory and anything // underneath it to be searched if((paths[i] == '.' || p.indexOf(paths[i]) === 0) && existsSync(p)) { fullpath = p; break; } } if(!fullpath) { return null; } this.pathsToNames[fullpath] = name; return { src: fs.readFileSync(fullpath, 'utf-8'), path: fullpath, noCache: this.noCache }; } }); module.exports = { FileSystemLoader: FileSystemLoader };
Fix test of position of template file
src/node-loaders.js
Fix test of position of template file
<ide><path>rc/node-loaders.js <ide> var paths = this.searchPaths; <ide> <ide> for(var i=0; i<paths.length; i++) { <add> var basePath = path.resolve(paths[i]); <ide> var p = path.resolve(paths[i], name); <ide> <ide> // Only allow the current directory and anything <ide> // underneath it to be searched <del> if((paths[i] == '.' || p.indexOf(paths[i]) === 0) && <del> existsSync(p)) { <add> if(p.indexOf(basePath) === 0 && existsSync(p)) { <ide> fullpath = p; <ide> break; <ide> }
Java
apache-2.0
14111c0e697d26b4695058218abc0091eb2ffca9
0
3sidedcube/Android-LightningUi
package com.cube.storm.ui.view.holder; import android.text.TextUtils; import android.view.LayoutInflater; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.widget.Button; import android.widget.LinearLayout; import android.widget.TextView; import com.cube.storm.UiSettings; import com.cube.storm.ui.R; import com.cube.storm.ui.model.list.ButtonListItem; import com.cube.storm.ui.model.property.LinkProperty; /** * View holder for {@link com.cube.storm.ui.model.list.ButtonListItem} in the adapter * * @author Alan Le Fournis * @project Storm */ public class ButtonListItemHolder extends ViewHolderController { @Override public ViewHolder createViewHolder(ViewGroup parent) { View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.button_list_item_view, parent, false); mViewHolder = new ButtonListItemViewHolder(view); return mViewHolder; } private class ButtonListItemViewHolder extends ViewHolder<ButtonListItem> { protected TextView title; protected Button button; protected LinearLayout embeddedLinksContainer; public ButtonListItemViewHolder(View view) { super(view); title = (TextView)view.findViewById(R.id.title); button = (Button)view.findViewById(R.id.button); embeddedLinksContainer = (LinearLayout)view.findViewById(R.id.embedded_links_container); } @Override public void populateView(ButtonListItem model) { title.setVisibility(View.GONE); button.setVisibility(View.GONE); if (model.getTitle() != null) { String titleContent = UiSettings.getInstance().getTextProcessor().process(model.getTitle().getContent()); if (!TextUtils.isEmpty(titleContent)) { title.setText(titleContent); title.setVisibility(View.VISIBLE); } else { title.setVisibility(View.GONE); } } if (model.getButton() != null && model.getButton().getTitle() != null) { String buttonContent = UiSettings.getInstance().getTextProcessor().process(model.getButton().getTitle().getContent()); if (!TextUtils.isEmpty(buttonContent)) { button.setText(UiSettings.getInstance().getTextProcessor().process(model.getButton().getTitle().getContent())); button.setVisibility(View.VISIBLE); } else { button.setVisibility(View.GONE); } } if (model.getEmbeddedLinks() != null) { embeddedLinksContainer.removeAllViews(); for (LinkProperty linkProperty : model.getEmbeddedLinks()) { final LinkProperty property = linkProperty; View embeddedLinkView = LayoutInflater.from(embeddedLinksContainer.getContext()).inflate(R.layout.button_embedded_link, embeddedLinksContainer, false); if (embeddedLinkView != null) { Button button = (Button)embeddedLinkView.findViewById(R.id.button); button.setVisibility(View.GONE); String embeddedContent = UiSettings.getInstance().getTextProcessor().process(linkProperty.getTitle().getContent()); if (!TextUtils.isEmpty(embeddedContent)) { button.setText(embeddedContent); button.setVisibility(View.VISIBLE); } button.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { UiSettings.getInstance().getLinkHandler().handleLink(v.getContext(), property); } }); embeddedLinksContainer.setVisibility(View.VISIBLE); embeddedLinksContainer.addView(button); } } } } } }
src/main/java/com/cube/storm/ui/view/holder/ButtonListItemHolder.java
package com.cube.storm.ui.view.holder; import android.text.TextUtils; import android.view.LayoutInflater; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.widget.Button; import android.widget.LinearLayout; import android.widget.TextView; import com.cube.storm.UiSettings; import com.cube.storm.ui.R; import com.cube.storm.ui.model.list.ButtonListItem; import com.cube.storm.ui.model.property.LinkProperty; /** * View holder for {@link com.cube.storm.ui.model.list.ButtonListItem} in the adapter * * @author Alan Le Fournis * @project Storm */ public class ButtonListItemHolder extends ViewHolderController { @Override public ViewHolder createViewHolder(ViewGroup parent) { View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.button_list_item_view, parent, false); mViewHolder = new ButtonListItemViewHolder(view); return mViewHolder; } private class ButtonListItemViewHolder extends ViewHolder<ButtonListItem> { protected TextView title; protected Button button; protected LinearLayout embeddedLinksContainer; public ButtonListItemViewHolder(View view) { super(view); title = (TextView)view.findViewById(R.id.title); button = (Button)view.findViewById(R.id.button); embeddedLinksContainer = (LinearLayout)view.findViewById(R.id.embedded_links_container); } @Override public void populateView(ButtonListItem model) { title.setVisibility(View.GONE); button.setVisibility(View.GONE); String content = UiSettings.getInstance().getTextProcessor().process(model.getButton().getTitle().getContent()); if (!TextUtils.isEmpty(content)) { button.setText(content); button.setVisibility(View.VISIBLE); } else { title.setVisibility(View.GONE); } if (model.getButton() != null) { button.setText(UiSettings.getInstance().getTextProcessor().process(model.getButton().getTitle().getContent())); } if (model.getEmbeddedLinks() != null) { embeddedLinksContainer.removeAllViews(); for (LinkProperty linkProperty : model.getEmbeddedLinks()) { final LinkProperty property = linkProperty; View embeddedLinkView = LayoutInflater.from(embeddedLinksContainer.getContext()).inflate(R.layout.button_embedded_link, embeddedLinksContainer, false); if (embeddedLinkView != null) { Button button = (Button)embeddedLinkView.findViewById(R.id.button); button.setVisibility(View.GONE); String embeddedContent = UiSettings.getInstance().getTextProcessor().process(linkProperty.getTitle().getContent()); if (!TextUtils.isEmpty(content)) { button.setText(embeddedContent); button.setVisibility(View.VISIBLE); } button.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { UiSettings.getInstance().getLinkHandler().handleLink(v.getContext(), property); } }); embeddedLinksContainer.setVisibility(View.VISIBLE); embeddedLinksContainer.addView(button); } } } } } }
Fixed incorrect implementation in button list item holder
src/main/java/com/cube/storm/ui/view/holder/ButtonListItemHolder.java
Fixed incorrect implementation in button list item holder
<ide><path>rc/main/java/com/cube/storm/ui/view/holder/ButtonListItemHolder.java <ide> title.setVisibility(View.GONE); <ide> button.setVisibility(View.GONE); <ide> <del> String content = UiSettings.getInstance().getTextProcessor().process(model.getButton().getTitle().getContent()); <add> if (model.getTitle() != null) <add> { <add> String titleContent = UiSettings.getInstance().getTextProcessor().process(model.getTitle().getContent()); <ide> <del> if (!TextUtils.isEmpty(content)) <del> { <del> button.setText(content); <del> button.setVisibility(View.VISIBLE); <del> } <del> else <del> { <del> title.setVisibility(View.GONE); <add> if (!TextUtils.isEmpty(titleContent)) <add> { <add> title.setText(titleContent); <add> title.setVisibility(View.VISIBLE); <add> } <add> else <add> { <add> title.setVisibility(View.GONE); <add> } <ide> } <ide> <del> if (model.getButton() != null) <add> if (model.getButton() != null && model.getButton().getTitle() != null) <ide> { <del> button.setText(UiSettings.getInstance().getTextProcessor().process(model.getButton().getTitle().getContent())); <add> String buttonContent = UiSettings.getInstance().getTextProcessor().process(model.getButton().getTitle().getContent()); <add> <add> if (!TextUtils.isEmpty(buttonContent)) <add> { <add> button.setText(UiSettings.getInstance().getTextProcessor().process(model.getButton().getTitle().getContent())); <add> button.setVisibility(View.VISIBLE); <add> } <add> else <add> { <add> button.setVisibility(View.GONE); <add> } <ide> } <ide> <ide> if (model.getEmbeddedLinks() != null) <ide> button.setVisibility(View.GONE); <ide> String embeddedContent = UiSettings.getInstance().getTextProcessor().process(linkProperty.getTitle().getContent()); <ide> <del> if (!TextUtils.isEmpty(content)) <add> if (!TextUtils.isEmpty(embeddedContent)) <ide> { <ide> button.setText(embeddedContent); <ide> button.setVisibility(View.VISIBLE);
Java
apache-2.0
3a392609e176e8e5321dc8d18d1d955375d1bc64
0
nizhikov/ignite,andrey-kuznetsov/ignite,SomeFire/ignite,ilantukh/ignite,andrey-kuznetsov/ignite,SomeFire/ignite,xtern/ignite,apache/ignite,nizhikov/ignite,SomeFire/ignite,ilantukh/ignite,SomeFire/ignite,nizhikov/ignite,ilantukh/ignite,NSAmelchev/ignite,ilantukh/ignite,chandresh-pancholi/ignite,ilantukh/ignite,chandresh-pancholi/ignite,xtern/ignite,ilantukh/ignite,apache/ignite,apache/ignite,ascherbakoff/ignite,ilantukh/ignite,xtern/ignite,xtern/ignite,nizhikov/ignite,NSAmelchev/ignite,samaitra/ignite,samaitra/ignite,xtern/ignite,SomeFire/ignite,NSAmelchev/ignite,chandresh-pancholi/ignite,nizhikov/ignite,daradurvs/ignite,ilantukh/ignite,NSAmelchev/ignite,nizhikov/ignite,SomeFire/ignite,chandresh-pancholi/ignite,ascherbakoff/ignite,samaitra/ignite,samaitra/ignite,samaitra/ignite,andrey-kuznetsov/ignite,chandresh-pancholi/ignite,ilantukh/ignite,apache/ignite,apache/ignite,xtern/ignite,samaitra/ignite,shroman/ignite,andrey-kuznetsov/ignite,shroman/ignite,nizhikov/ignite,daradurvs/ignite,andrey-kuznetsov/ignite,chandresh-pancholi/ignite,shroman/ignite,shroman/ignite,daradurvs/ignite,shroman/ignite,andrey-kuznetsov/ignite,ascherbakoff/ignite,ascherbakoff/ignite,xtern/ignite,apache/ignite,ascherbakoff/ignite,daradurvs/ignite,SomeFire/ignite,SomeFire/ignite,NSAmelchev/ignite,andrey-kuznetsov/ignite,ascherbakoff/ignite,shroman/ignite,daradurvs/ignite,chandresh-pancholi/ignite,NSAmelchev/ignite,ascherbakoff/ignite,andrey-kuznetsov/ignite,nizhikov/ignite,SomeFire/ignite,NSAmelchev/ignite,xtern/ignite,apache/ignite,shroman/ignite,shroman/ignite,daradurvs/ignite,daradurvs/ignite,andrey-kuznetsov/ignite,daradurvs/ignite,apache/ignite,daradurvs/ignite,NSAmelchev/ignite,shroman/ignite,NSAmelchev/ignite,apache/ignite,samaitra/ignite,SomeFire/ignite,ilantukh/ignite,daradurvs/ignite,samaitra/ignite,shroman/ignite,ascherbakoff/ignite,nizhikov/ignite,chandresh-pancholi/ignite,andrey-kuznetsov/ignite,xtern/ignite,ascherbakoff/ignite,samaitra/ignite,samaitra/ignite,chandresh-pancholi/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.distributed; import java.util.Map; import java.util.UUID; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import org.apache.ignite.IgniteCheckedException; import org.apache.ignite.IgniteLogger; import org.apache.ignite.internal.IgniteClientDisconnectedCheckedException; import org.apache.ignite.internal.IgniteInternalFuture; import org.apache.ignite.internal.processors.cache.GridCacheSharedContext; import org.apache.ignite.internal.util.future.GridFinishedFuture; import org.apache.ignite.internal.util.future.GridFutureAdapter; import org.apache.ignite.lang.IgniteFuture; import org.jetbrains.annotations.Nullable; /** * Synchronization structure for asynchronous waiting for near tx finish responses based on per-node per-thread * basis. */ public class GridCacheTxFinishSync<K, V> { /** Cache context. */ private GridCacheSharedContext<K, V> cctx; /** Logger. */ private IgniteLogger log; /** Nodes map. */ private ConcurrentMap<Long, ThreadFinishSync> threadMap = new ConcurrentHashMap<>(); /** * @param cctx Cache context. */ public GridCacheTxFinishSync(GridCacheSharedContext<K, V> cctx) { this.cctx = cctx; log = cctx.logger(GridCacheTxFinishSync.class); } /** * Callback invoked before finish request is sent to remote node. * * @param nodeId Node ID request being sent to. * @param threadId Thread ID started transaction. */ public void onFinishSend(UUID nodeId, long threadId) { ThreadFinishSync threadSync = threadMap.get(threadId); if (threadSync == null) threadMap.put(threadId, threadSync = new ThreadFinishSync(threadId)); synchronized (threadSync) { //thread has to create new ThreadFinishSync //if other thread executing onAckReceived method removed previous threadSync object if (threadMap.get(threadId) == null) threadMap.put(threadId, threadSync = new ThreadFinishSync(threadId)); threadSync.onSend(nodeId); } } /** * @param nodeId Node ID to wait ack from. * @param threadId Thread ID to wait ack. * @return {@code null} if ack was received or future that will be completed when ack is received. */ public IgniteInternalFuture<?> awaitAckAsync(UUID nodeId, long threadId) { ThreadFinishSync threadSync = threadMap.get(threadId); if (threadSync == null) return null; return threadSync.awaitAckAsync(nodeId); } /** * @param reconnectFut Reconnect future. */ public void onDisconnected(IgniteFuture<?> reconnectFut) { for (ThreadFinishSync threadSync : threadMap.values()) threadSync.onDisconnected(reconnectFut); threadMap.clear(); } /** * Callback invoked when finish response is received from remote node. * * @param nodeId Node ID response was received from. * @param threadId Thread ID started transaction. */ public void onAckReceived(UUID nodeId, long threadId) { ThreadFinishSync threadSync = threadMap.get(threadId); if (threadSync != null) { threadSync.onReceive(nodeId); synchronized (threadSync) { if (threadSync.isEmpty()) threadMap.remove(threadId); } } } /** * Callback invoked when node leaves grid. * * @param nodeId Left node ID. */ public void onNodeLeft(UUID nodeId) { for (ThreadFinishSync threadSync : threadMap.values()) { threadSync.onNodeLeft(nodeId); synchronized (threadSync) { if (threadSync.isEmpty()) threadMap.remove(threadSync); } } } /** * Per-node sync. */ private class ThreadFinishSync { /** Thread ID. */ private long threadId; /** Thread map. */ private final Map<UUID, TxFinishSync> nodeMap = new ConcurrentHashMap<>(); /** * @param threadId Thread ID. */ private ThreadFinishSync(long threadId) { this.threadId = threadId; } /** * @param nodeId Node ID request being sent to. */ public void onSend(UUID nodeId) { TxFinishSync sync = nodeMap.get(nodeId); if (sync == null) { sync = new TxFinishSync(nodeId, threadId); TxFinishSync old = nodeMap.put(nodeId, sync); assert old == null : "Only user thread can add sync objects to the map."; // Recheck discovery only if added new sync. if (cctx.discovery().node(nodeId) == null) { sync.onNodeLeft(); nodeMap.remove(nodeId); } else if (cctx.kernalContext().clientDisconnected()) { sync.onDisconnected(cctx.kernalContext().cluster().clientReconnectFuture()); nodeMap.remove(nodeId); } } sync.onSend(); } /** * Asynchronously awaits ack from node with given node ID. * * @param nodeId Node ID to wait ack from. * @return {@code null} if ack has been received or future that will be completed when ack is received. */ public IgniteInternalFuture<?> awaitAckAsync(UUID nodeId) { TxFinishSync sync = nodeMap.get(nodeId); if (sync == null) return null; return sync.awaitAckAsync(); } /** * @param reconnectFut Reconnect future. */ public void onDisconnected(IgniteFuture<?> reconnectFut) { for (TxFinishSync sync : nodeMap.values()) sync.onDisconnected(reconnectFut); nodeMap.clear(); } /** * @param nodeId Node ID response received from. */ public void onReceive(UUID nodeId) { TxFinishSync sync = nodeMap.remove(nodeId); if (sync != null) sync.onReceive(); } /** * @param nodeId Left node ID. */ public void onNodeLeft(UUID nodeId) { TxFinishSync sync = nodeMap.remove(nodeId); if (sync != null) sync.onNodeLeft(); } /** * */ private boolean isEmpty() { return nodeMap.isEmpty(); } } /** * Tx sync. Allocated per-node per-thread. */ private class TxFinishSync { /** Node ID. */ private final UUID nodeId; /** Thread ID. */ private final long threadId; /** Number of awaiting messages. */ private int cnt; /** Node left flag. */ private boolean nodeLeft; /** Pending await future. */ private GridFutureAdapter<?> pendingFut; /** * @param nodeId Sync node ID. Used to construct correct error message. * @param threadId Thread ID. */ private TxFinishSync(UUID nodeId, long threadId) { this.nodeId = nodeId; this.threadId = threadId; } /** * Callback invoked before sending finish request to remote nodes. * Will synchronously wait for previous finish response. */ public void onSend() { synchronized (this) { if (log.isTraceEnabled()) log.trace("Moved transaction synchronizer to waiting state [nodeId=" + nodeId + ", threadId=" + threadId + ']'); assert cnt == 0 || nodeLeft : cnt; if (nodeLeft) return; // Do not create future for every send operation. cnt = 1; } } /** * Asynchronously waits for ack to be received from node. * * @return {@code null} if ack has been received, or future that will be completed when ack is received. */ @Nullable public IgniteInternalFuture<?> awaitAckAsync() { synchronized (this) { if (cnt == 0) return null; if (nodeLeft) return new GridFinishedFuture<>(new IgniteCheckedException("Failed to wait for finish synchronizer " + "state (node left grid): " + nodeId)); if (pendingFut == null) { if (log.isTraceEnabled()) log.trace("Creating transaction synchronizer future [nodeId=" + nodeId + ", threadId=" + threadId + ']'); pendingFut = new GridFutureAdapter<>(); } return pendingFut; } } /** * Callback for received response. */ public void onReceive() { synchronized (this) { if (log.isTraceEnabled()) log.trace("Moving transaction synchronizer to completed state [nodeId=" + nodeId + ", threadId=" + threadId + ']'); cnt = 0; if (pendingFut != null) { pendingFut.onDone(); pendingFut = null; } } } /** * Callback for node leave event. */ public void onNodeLeft() { synchronized (this) { nodeLeft = true; if (pendingFut != null) { pendingFut.onDone(new IgniteCheckedException("Failed to wait for transaction synchronizer " + "completed state (node left grid): " + nodeId)); pendingFut = null; } } } /** * Client disconnected callback. * * @param reconnectFut Reconnect future. */ public void onDisconnected(IgniteFuture<?> reconnectFut) { synchronized (this) { nodeLeft = true; if (pendingFut != null) { IgniteClientDisconnectedCheckedException err = new IgniteClientDisconnectedCheckedException( reconnectFut, "Failed to wait for transaction synchronizer, client node disconnected: " + nodeId); pendingFut.onDone(err); pendingFut = null; } } } } }
modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/GridCacheTxFinishSync.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.distributed; import java.util.Map; import java.util.UUID; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import org.apache.ignite.IgniteCheckedException; import org.apache.ignite.IgniteLogger; import org.apache.ignite.internal.IgniteClientDisconnectedCheckedException; import org.apache.ignite.internal.IgniteInternalFuture; import org.apache.ignite.internal.processors.cache.GridCacheSharedContext; import org.apache.ignite.internal.util.future.GridFinishedFuture; import org.apache.ignite.internal.util.future.GridFutureAdapter; import org.apache.ignite.internal.util.typedef.F; import org.apache.ignite.lang.IgniteFuture; import org.jetbrains.annotations.Nullable; /** * Synchronization structure for asynchronous waiting for near tx finish responses based on per-node per-thread * basis. */ public class GridCacheTxFinishSync<K, V> { /** Cache context. */ private GridCacheSharedContext<K, V> cctx; /** Logger. */ private IgniteLogger log; /** Nodes map. */ private ConcurrentMap<Long, ThreadFinishSync> threadMap = new ConcurrentHashMap<>(); /** * @param cctx Cache context. */ public GridCacheTxFinishSync(GridCacheSharedContext<K, V> cctx) { this.cctx = cctx; log = cctx.logger(GridCacheTxFinishSync.class); } /** * Callback invoked before finish request is sent to remote node. * * @param nodeId Node ID request being sent to. * @param threadId Thread ID started transaction. */ public void onFinishSend(UUID nodeId, long threadId) { ThreadFinishSync threadSync = threadMap.get(threadId); if (threadSync == null) threadSync = F.addIfAbsent(threadMap, threadId, new ThreadFinishSync(threadId)); threadSync.onSend(nodeId); } /** * @param nodeId Node ID to wait ack from. * @param threadId Thread ID to wait ack. * @return {@code null} if ack was received or future that will be completed when ack is received. */ public IgniteInternalFuture<?> awaitAckAsync(UUID nodeId, long threadId) { ThreadFinishSync threadSync = threadMap.get(threadId); if (threadSync == null) return null; return threadSync.awaitAckAsync(nodeId); } /** * @param reconnectFut Reconnect future. */ public void onDisconnected(IgniteFuture<?> reconnectFut) { for (ThreadFinishSync threadSync : threadMap.values()) threadSync.onDisconnected(reconnectFut); threadMap.clear(); } /** * Callback invoked when finish response is received from remote node. * * @param nodeId Node ID response was received from. * @param threadId Thread ID started transaction. */ public void onAckReceived(UUID nodeId, long threadId) { ThreadFinishSync threadSync = threadMap.get(threadId); if (threadSync != null) threadSync.onReceive(nodeId); } /** * Callback invoked when node leaves grid. * * @param nodeId Left node ID. */ public void onNodeLeft(UUID nodeId) { for (ThreadFinishSync threadSync : threadMap.values()) threadSync.onNodeLeft(nodeId); } /** * Per-node sync. */ private class ThreadFinishSync { /** Thread ID. */ private long threadId; /** Thread map. */ private final Map<UUID, TxFinishSync> nodeMap = new ConcurrentHashMap<>(); /** * @param threadId Thread ID. */ private ThreadFinishSync(long threadId) { this.threadId = threadId; } /** * @param nodeId Node ID request being sent to. */ public void onSend(UUID nodeId) { TxFinishSync sync = nodeMap.get(nodeId); if (sync == null) { sync = new TxFinishSync(nodeId, threadId); TxFinishSync old = nodeMap.put(nodeId, sync); assert old == null : "Only user thread can add sync objects to the map."; // Recheck discovery only if added new sync. if (cctx.discovery().node(nodeId) == null) { sync.onNodeLeft(); nodeMap.remove(nodeId); } else if (cctx.kernalContext().clientDisconnected()) { sync.onDisconnected(cctx.kernalContext().cluster().clientReconnectFuture()); nodeMap.remove(nodeId); } } sync.onSend(); } /** * Asynchronously awaits ack from node with given node ID. * * @param nodeId Node ID to wait ack from. * @return {@code null} if ack has been received or future that will be completed when ack is received. */ public IgniteInternalFuture<?> awaitAckAsync(UUID nodeId) { TxFinishSync sync = nodeMap.get(nodeId); if (sync == null) return null; return sync.awaitAckAsync(); } /** * @param reconnectFut Reconnect future. */ public void onDisconnected(IgniteFuture<?> reconnectFut) { for (TxFinishSync sync : nodeMap.values()) sync.onDisconnected(reconnectFut); nodeMap.clear(); } /** * @param nodeId Node ID response received from. */ public void onReceive(UUID nodeId) { TxFinishSync sync = nodeMap.get(nodeId); if (sync != null) sync.onReceive(); } /** * @param nodeId Left node ID. */ public void onNodeLeft(UUID nodeId) { TxFinishSync sync = nodeMap.remove(nodeId); if (sync != null) sync.onNodeLeft(); } } /** * Tx sync. Allocated per-node per-thread. */ private class TxFinishSync { /** Node ID. */ private final UUID nodeId; /** Thread ID. */ private final long threadId; /** Number of awaiting messages. */ private int cnt; /** Node left flag. */ private boolean nodeLeft; /** Pending await future. */ private GridFutureAdapter<?> pendingFut; /** * @param nodeId Sync node ID. Used to construct correct error message. * @param threadId Thread ID. */ private TxFinishSync(UUID nodeId, long threadId) { this.nodeId = nodeId; this.threadId = threadId; } /** * Callback invoked before sending finish request to remote nodes. * Will synchronously wait for previous finish response. */ public void onSend() { synchronized (this) { if (log.isTraceEnabled()) log.trace("Moved transaction synchronizer to waiting state [nodeId=" + nodeId + ", threadId=" + threadId + ']'); assert cnt == 0 || nodeLeft : cnt; if (nodeLeft) return; // Do not create future for every send operation. cnt = 1; } } /** * Asynchronously waits for ack to be received from node. * * @return {@code null} if ack has been received, or future that will be completed when ack is received. */ @Nullable public IgniteInternalFuture<?> awaitAckAsync() { synchronized (this) { if (cnt == 0) return null; if (nodeLeft) return new GridFinishedFuture<>(new IgniteCheckedException("Failed to wait for finish synchronizer " + "state (node left grid): " + nodeId)); if (pendingFut == null) { if (log.isTraceEnabled()) log.trace("Creating transaction synchronizer future [nodeId=" + nodeId + ", threadId=" + threadId + ']'); pendingFut = new GridFutureAdapter<>(); } return pendingFut; } } /** * Callback for received response. */ public void onReceive() { synchronized (this) { if (log.isTraceEnabled()) log.trace("Moving transaction synchronizer to completed state [nodeId=" + nodeId + ", threadId=" + threadId + ']'); cnt = 0; if (pendingFut != null) { pendingFut.onDone(); pendingFut = null; } } } /** * Callback for node leave event. */ public void onNodeLeft() { synchronized (this) { nodeLeft = true; if (pendingFut != null) { pendingFut.onDone(new IgniteCheckedException("Failed to wait for transaction synchronizer " + "completed state (node left grid): " + nodeId)); pendingFut = null; } } } /** * Client disconnected callback. * * @param reconnectFut Reconnect future. */ public void onDisconnected(IgniteFuture<?> reconnectFut) { synchronized (this) { nodeLeft = true; if (pendingFut != null) { IgniteClientDisconnectedCheckedException err = new IgniteClientDisconnectedCheckedException( reconnectFut, "Failed to wait for transaction synchronizer, client node disconnected: " + nodeId); pendingFut.onDone(err); pendingFut = null; } } } } }
IGNITE-11754 Fixed memory leak in TxFinishSync - Fixes #6462. Signed-off-by: Alexey Goncharuk <[email protected]>
modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/GridCacheTxFinishSync.java
IGNITE-11754 Fixed memory leak in TxFinishSync - Fixes #6462.
<ide><path>odules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/GridCacheTxFinishSync.java <ide> import org.apache.ignite.internal.processors.cache.GridCacheSharedContext; <ide> import org.apache.ignite.internal.util.future.GridFinishedFuture; <ide> import org.apache.ignite.internal.util.future.GridFutureAdapter; <del>import org.apache.ignite.internal.util.typedef.F; <ide> import org.apache.ignite.lang.IgniteFuture; <ide> import org.jetbrains.annotations.Nullable; <ide> <ide> ThreadFinishSync threadSync = threadMap.get(threadId); <ide> <ide> if (threadSync == null) <del> threadSync = F.addIfAbsent(threadMap, threadId, new ThreadFinishSync(threadId)); <del> <del> threadSync.onSend(nodeId); <add> threadMap.put(threadId, threadSync = new ThreadFinishSync(threadId)); <add> <add> synchronized (threadSync) { <add> //thread has to create new ThreadFinishSync <add> //if other thread executing onAckReceived method removed previous threadSync object <add> if (threadMap.get(threadId) == null) <add> threadMap.put(threadId, threadSync = new ThreadFinishSync(threadId)); <add> <add> threadSync.onSend(nodeId); <add> } <ide> } <ide> <ide> /** <ide> public void onAckReceived(UUID nodeId, long threadId) { <ide> ThreadFinishSync threadSync = threadMap.get(threadId); <ide> <del> if (threadSync != null) <add> if (threadSync != null) { <ide> threadSync.onReceive(nodeId); <add> <add> synchronized (threadSync) { <add> if (threadSync.isEmpty()) <add> threadMap.remove(threadId); <add> } <add> } <ide> } <ide> <ide> /** <ide> * @param nodeId Left node ID. <ide> */ <ide> public void onNodeLeft(UUID nodeId) { <del> for (ThreadFinishSync threadSync : threadMap.values()) <add> for (ThreadFinishSync threadSync : threadMap.values()) { <ide> threadSync.onNodeLeft(nodeId); <add> <add> synchronized (threadSync) { <add> if (threadSync.isEmpty()) <add> threadMap.remove(threadSync); <add> } <add> } <ide> } <ide> <ide> /** <ide> * @param nodeId Node ID response received from. <ide> */ <ide> public void onReceive(UUID nodeId) { <del> TxFinishSync sync = nodeMap.get(nodeId); <add> TxFinishSync sync = nodeMap.remove(nodeId); <ide> <ide> if (sync != null) <ide> sync.onReceive(); <ide> <ide> if (sync != null) <ide> sync.onNodeLeft(); <add> } <add> <add> /** <add> * <add> */ <add> private boolean isEmpty() { <add> return nodeMap.isEmpty(); <ide> } <ide> } <ide>
Java
mit
c080f3751983d5f95bbb736597eb9d47a12e8f08
0
ChaseYaoCong/main,CS2103AUG2016-F11-C1/main,CS2103AUG2016-F11-C1/main
package seedu.todo.commons.util; import java.time.LocalDate; import java.time.LocalDateTime; import java.time.ZoneId; import java.time.format.DateTimeFormatter; import java.time.format.TextStyle; import java.time.temporal.ChronoUnit; import java.util.Date; import java.util.Locale; /** * A utility class for Dates and LocalDateTimes */ public class DateUtil { private static final String FROM_NOW = "later"; private static final String TILL_NOW = "ago"; private static final String TODAY = "Today"; private static final String TOMORROW = "Tomorrow"; private static final String DAY = "day"; private static final String DAYS = "days"; /** * Converts a LocalDateTime object to a legacy java.util.Date object. * * @param dateTime LocalDateTime object. * @return Date object. */ public static Date toDate(LocalDateTime dateTime) { return Date.from(dateTime.atZone(ZoneId.systemDefault()).toInstant()); } /** * Performs a "floor" operation on a LocalDateTime, and returns a new LocalDateTime * with time set to 00:00. * * @param dateTime LocalDateTime for operation to be performed on. * @return "Floored" LocalDateTime. */ public static LocalDateTime floorDate(LocalDateTime dateTime) { return dateTime.toLocalDate().atTime(0, 0); } /** * Formats a LocalDateTime to a relative date. * Prefers DayOfWeek format, for dates up to 6 days from today. * Otherwise, returns a relative time (e.g. 13 days from now). * * @param dateTime LocalDateTime to format. * @return Formatted relative day. */ public static String formatDay(LocalDateTime dateTime) { LocalDate date = dateTime.toLocalDate(); long daysDifference = LocalDate.now().until(date, ChronoUnit.DAYS); // Consider today's date. if (date.isEqual(LocalDate.now())) { return TODAY; } if (daysDifference == 1) { return TOMORROW; } // Consider dates up to 6 days from today. if (daysDifference > 1 && daysDifference <= 6) { return date.getDayOfWeek().getDisplayName(TextStyle.FULL, Locale.US); } // Otherwise, dates should be a relative days ago/from now format. return String.format("%d %s %s", Math.abs(daysDifference), StringUtil.pluralizer((int) Math.abs(daysDifference), DAY, DAYS), daysDifference > 0 ? FROM_NOW : TILL_NOW); } /** * Formats a LocalDateTime to a short date. Excludes the day of week only if * the date is within 2-6 days from now. * * @param dateTime LocalDateTime to format, withDaysOfWeek. * @return Formatted shorten day. */ public static String formatShortDate(LocalDateTime dateTime) { LocalDate date = dateTime.toLocalDate(); long daysDifference = LocalDate.now().until(date, ChronoUnit.DAYS); String dateFormat; // Don't show dayOfWeek for days d, such that d = {n+2,...,n+6}, where n = date now if (daysDifference >= 2 && daysDifference <= 6) { dateFormat = "dd MMM"; } else { dateFormat = "E dd MMM"; } return date.format(DateTimeFormatter.ofPattern(dateFormat)); } }
src/main/java/seedu/todo/commons/util/DateUtil.java
package seedu.todo.commons.util; import java.time.LocalDate; import java.time.LocalDateTime; import java.time.ZoneId; import java.time.format.DateTimeFormatter; import java.time.format.TextStyle; import java.time.temporal.ChronoUnit; import java.util.Date; import java.util.Locale; /** * A utility class for Dates and LocalDateTimes */ public class DateUtil { private static final String FROM_NOW = "later"; private static final String TILL_NOW = "ago"; private static final String TODAY = "Today"; private static final String TOMORROW = "Tomorrow"; private static final String DAY = "day"; private static final String DAYS = "days"; /** * Converts a LocalDateTime object to a legacy java.util.Date object. * * @param dateTime LocalDateTime object. * @return Date object. */ public static Date toDate(LocalDateTime dateTime) { return Date.from(dateTime.atZone(ZoneId.systemDefault()).toInstant()); } /** * Performs a "floor" operation on a LocalDateTime, and returns a new LocalDateTime * with time set to 00:00. * * @param dateTime LocalDateTime for operation to be performed on. * @return "Floored" LocalDateTime. */ public static LocalDateTime floorDate(LocalDateTime dateTime) { return dateTime.toLocalDate().atTime(0, 0); } /** * Formats a LocalDateTime to a relative date. * Prefers DayOfWeek format, for dates up to 6 days from today. * Otherwise, returns a relative time (e.g. 13 days from now). * * @param dateTime LocalDateTime to format. * @return Formatted relative day. */ public static String formatDay(LocalDateTime dateTime) { LocalDate date = dateTime.toLocalDate(); long daysDifference = LocalDate.now().until(date, ChronoUnit.DAYS); // Consider today's date. if (date.isEqual(LocalDate.now())) { return TODAY; } if (daysDifference == 1) { return TOMORROW; } // Consider dates up to 6 days from today. if (daysDifference > 1 && daysDifference <= 6) { return date.getDayOfWeek().getDisplayName(TextStyle.FULL, Locale.US); } // Otherwise, dates should be a relative days ago/from now format. return String.format("%d %s %s", Math.abs(daysDifference), StringUtil.pluralizer((int) Math.abs(daysDifference), DAY, DAYS), daysDifference > 0 ? FROM_NOW : TILL_NOW); } /** * Formats a LocalDateTime to a short date. Excludes the day of week only if * the date is within 2-6 days from now. * * @param dateTime LocalDateTime to format, withDaysOfWeek. * @return Formatted shorten day. */ public static String formatShortDate(LocalDateTime dateTime) { LocalDate date = dateTime.toLocalDate(); long daysDifference = LocalDate.now().until(date, ChronoUnit.DAYS); String dayOfWeek = date.getDayOfWeek().getDisplayName(TextStyle.SHORT, Locale.US); String shortDate = date.format(DateTimeFormatter.ofPattern("dd MMM")); // Don't show dayOfWeek for days d, such that d = {n+2,...,n+6}, where n = date now if (daysDifference >= 2 && daysDifference <= 6) { return String.format("%s", shortDate); } else { return String.format("%s %s", dayOfWeek, shortDate); } } }
Use more concise DateTimeFormatter for formatShortDate
src/main/java/seedu/todo/commons/util/DateUtil.java
Use more concise DateTimeFormatter for formatShortDate
<ide><path>rc/main/java/seedu/todo/commons/util/DateUtil.java <ide> public static String formatShortDate(LocalDateTime dateTime) { <ide> LocalDate date = dateTime.toLocalDate(); <ide> long daysDifference = LocalDate.now().until(date, ChronoUnit.DAYS); <del> String dayOfWeek = date.getDayOfWeek().getDisplayName(TextStyle.SHORT, Locale.US); <del> String shortDate = date.format(DateTimeFormatter.ofPattern("dd MMM")); <add> String dateFormat; <ide> <ide> // Don't show dayOfWeek for days d, such that d = {n+2,...,n+6}, where n = date now <ide> if (daysDifference >= 2 && daysDifference <= 6) { <del> return String.format("%s", shortDate); <add> dateFormat = "dd MMM"; <ide> } else { <del> return String.format("%s %s", dayOfWeek, shortDate); <add> dateFormat = "E dd MMM"; <ide> } <add> <add> return date.format(DateTimeFormatter.ofPattern(dateFormat)); <ide> } <ide> <ide> }
Java
agpl-3.0
5fbbc9328b0a4a191b9ff9d598b42c6553d12aae
0
UniversityOfHawaii/kfs,quikkian-ua-devops/will-financials,kuali/kfs,ua-eas/kfs-devops-automation-fork,quikkian-ua-devops/kfs,quikkian-ua-devops/kfs,kuali/kfs,bhutchinson/kfs,kuali/kfs,quikkian-ua-devops/will-financials,quikkian-ua-devops/kfs,quikkian-ua-devops/will-financials,quikkian-ua-devops/will-financials,ua-eas/kfs-devops-automation-fork,quikkian-ua-devops/kfs,ua-eas/kfs,bhutchinson/kfs,ua-eas/kfs-devops-automation-fork,UniversityOfHawaii/kfs,quikkian-ua-devops/will-financials,ua-eas/kfs,ua-eas/kfs,UniversityOfHawaii/kfs,quikkian-ua-devops/kfs,smith750/kfs,smith750/kfs,kuali/kfs,UniversityOfHawaii/kfs,kkronenb/kfs,bhutchinson/kfs,ua-eas/kfs-devops-automation-fork,ua-eas/kfs,bhutchinson/kfs,quikkian-ua-devops/will-financials,kkronenb/kfs,ua-eas/kfs,smith750/kfs,smith750/kfs,UniversityOfHawaii/kfs,kkronenb/kfs,ua-eas/kfs-devops-automation-fork,quikkian-ua-devops/kfs,kkronenb/kfs,kuali/kfs
/* * Copyright 2011 The Kuali Foundation. * * Licensed under the Educational Community License, Version 1.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.opensource.org/licenses/ecl1.php * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.kuali.kfs.module.tem.document.web.bean; import java.util.List; import org.kuali.kfs.module.tem.businessobject.Attendee; import org.kuali.kfs.module.tem.businessobject.ActualExpense; /** * This class... */ public interface TravelEntertainmentMvcWrapperBean extends TravelMvcWrapperBean { Attendee getNewAttendeeLine(); void setNewAttendeeLines(final List<Attendee> newAttendeeLines); List<Attendee> getNewAttendeeLines(); void setNewAttendeeLine(final Attendee newAttendeeLine); @Override ActualExpense getNewActualExpenseLine(); @Override void setNewActualExpenseLines(final List<ActualExpense> newActualExpenseLines); @Override List<ActualExpense> getNewActualExpenseLines(); @Override void setNewActualExpenseLine(final ActualExpense newActualExpenseLine); }
work/src/org/kuali/kfs/module/tem/document/web/bean/TravelEntertainmentMvcWrapperBean.java
/* * Copyright 2011 The Kuali Foundation. * * Licensed under the Educational Community License, Version 1.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.opensource.org/licenses/ecl1.php * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.kuali.kfs.module.tem.document.web.bean; import java.util.List; import org.kuali.kfs.module.tem.businessobject.Attendee; import org.kuali.kfs.module.tem.businessobject.ActualExpense; /** * This class... */ public interface TravelEntertainmentMVCWrapperBean extends TravelMvcWrapperBean { Attendee getNewAttendeeLine(); void setNewAttendeeLines(final List<Attendee> newAttendeeLines); List<Attendee> getNewAttendeeLines(); void setNewAttendeeLine(final Attendee newAttendeeLine); @Override ActualExpense getNewActualExpenseLine(); @Override void setNewActualExpenseLines(final List<ActualExpense> newActualExpenseLines); @Override List<ActualExpense> getNewActualExpenseLines(); @Override void setNewActualExpenseLine(final ActualExpense newActualExpenseLine); }
KFSCONTRB-937 renaming to be more consistent
work/src/org/kuali/kfs/module/tem/document/web/bean/TravelEntertainmentMvcWrapperBean.java
KFSCONTRB-937 renaming to be more consistent
<ide><path>ork/src/org/kuali/kfs/module/tem/document/web/bean/TravelEntertainmentMvcWrapperBean.java <ide> /** <ide> * This class... <ide> */ <del>public interface TravelEntertainmentMVCWrapperBean extends TravelMvcWrapperBean { <add>public interface TravelEntertainmentMvcWrapperBean extends TravelMvcWrapperBean { <ide> <ide> Attendee getNewAttendeeLine(); <ide>
Java
apache-2.0
fcb2c0a04242c2cebb12c9abc3405b43158c8cfd
0
stelar7/L4J8
package no.stelar7.api.l4j8.basic.constants.api; import java.util.*; import java.util.stream.Stream; public enum Platform { /** * Unknown platform, used for bots in participant identities */ UNKNOWN(""), /** * BRAZIL platform. */ BR1("BR1"), /** * Europe Nordic & East platform. */ EUN1("EUN1"), /** * Europe West platform. */ EUW1("EUW1"), /** * Japan platform. */ JP1("JP1"), /** * Korea platform. */ KR("KR"), /** * Latin America North platform. */ LA1("LA1"), /** * Latin America South platform. */ LA2("LA2"), /** * North America platform. */ NA1("NA1", "NA"), /** * Oceania platform. */ OC1("OC1"), /** * Turkey platform. */ TR1("TR1"), /** * Russia platform. */ RU("RU"), /** * Public Beta Environment platform. */ PBE1("PBE1"), /** * Singapore platform */ SG("SG"), /** * Philippines platform */ PH("PH"), /** * Indonesia platform */ ID1("ID1"), /** * Vietnam platform */ VN("VN"), /** * Thailand platform */ TH("TH"), /** * Taiwan platform */ TW("TW"); private String[] keys; Platform(String... s) { this.keys = s; } /** * Returns a Platform from the provided code * * @param code the lookup key * @return Platform from code */ public static Optional<Platform> getFromCode(final String code) { return Stream.of(Platform.values()).filter(t -> Stream.of(t.keys).anyMatch(s -> s.equalsIgnoreCase(code))).findFirst(); } /** * Used internaly in the api... * * @return the value */ public String getValue() { return this.keys[0]; } @Override public String toString() { return this.keys[0].toLowerCase(Locale.ENGLISH); } }
src/main/java/no/stelar7/api/l4j8/basic/constants/api/Platform.java
package no.stelar7.api.l4j8.basic.constants.api; import java.util.*; import java.util.stream.Stream; public enum Platform { /** * Unknown platform, used for bots in participant identities */ UNKNOWN(""), /** * BR platform. */ BR1("BR1"), /** * EUNE platform. */ EUN1("EUN1"), /** * EUW platform. */ EUW1("EUW1"), /** * JP platform. */ JP1("JP1"), /** * KR platform. */ KR("KR"), /** * LAN platform. */ LA1("LA1"), /** * LAS platform. */ LA2("LA2"), /** * NA platform. */ NA1("NA1", "NA"), /** * OC platform. */ OC1("OC1"), /** * TR platform. */ TR1("TR1"), /** * RU platform. */ RU("RU"), /** * PBE platform. */ PBE1("PBE1"); private String[] keys; Platform(String... s) { this.keys = s; } /** * Returns a Platform from the provided code * * @param code the lookup key * @return Platform from code */ public static Optional<Platform> getFromCode(final String code) { return Stream.of(Platform.values()).filter(t -> Stream.of(t.keys).anyMatch(s -> s.equalsIgnoreCase(code))).findFirst(); } /** * Used internaly in the api... * * @return the value */ public String getValue() { return this.keys[0]; } @Override public String toString() { return this.keys[0].toLowerCase(Locale.ENGLISH); } }
Add garena regions
src/main/java/no/stelar7/api/l4j8/basic/constants/api/Platform.java
Add garena regions
<ide><path>rc/main/java/no/stelar7/api/l4j8/basic/constants/api/Platform.java <ide> */ <ide> UNKNOWN(""), <ide> /** <del> * BR platform. <add> * BRAZIL platform. <ide> */ <ide> BR1("BR1"), <ide> /** <del> * EUNE platform. <add> * Europe Nordic & East platform. <ide> */ <ide> EUN1("EUN1"), <ide> /** <del> * EUW platform. <add> * Europe West platform. <ide> */ <ide> EUW1("EUW1"), <ide> /** <del> * JP platform. <add> * Japan platform. <ide> */ <ide> JP1("JP1"), <ide> /** <del> * KR platform. <add> * Korea platform. <ide> */ <ide> KR("KR"), <ide> /** <del> * LAN platform. <add> * Latin America North platform. <ide> */ <ide> LA1("LA1"), <ide> /** <del> * LAS platform. <add> * Latin America South platform. <ide> */ <ide> LA2("LA2"), <ide> /** <del> * NA platform. <add> * North America platform. <ide> */ <ide> NA1("NA1", "NA"), <ide> /** <del> * OC platform. <add> * Oceania platform. <ide> */ <ide> OC1("OC1"), <ide> /** <del> * TR platform. <add> * Turkey platform. <ide> */ <ide> TR1("TR1"), <ide> /** <del> * RU platform. <add> * Russia platform. <ide> */ <ide> RU("RU"), <ide> /** <del> * PBE platform. <add> * Public Beta Environment platform. <ide> */ <del> PBE1("PBE1"); <add> PBE1("PBE1"), <add> /** <add> * Singapore platform <add> */ <add> SG("SG"), <add> /** <add> * Philippines platform <add> */ <add> PH("PH"), <add> /** <add> * Indonesia platform <add> */ <add> ID1("ID1"), <add> /** <add> * Vietnam platform <add> */ <add> VN("VN"), <add> /** <add> * Thailand platform <add> */ <add> TH("TH"), <add> /** <add> * Taiwan platform <add> */ <add> TW("TW"); <ide> <ide> <ide> private String[] keys;
Java
mit
8a9879ea887a3af3ab1dd9755ae81333ce1e8e62
0
sake/bouncycastle-java
package org.bouncycastle.crypto.modes; import org.bouncycastle.crypto.BlockCipher; import org.bouncycastle.crypto.CipherParameters; import org.bouncycastle.crypto.DataLengthException; import org.bouncycastle.crypto.InvalidCipherTextException; /** * A block cipher mode that includes authenticated encryption with a streaming mode and optional associated data. * @see org.bouncycastle.crypto.params.AEADParameters */ public interface AEADBlockCipher { /** * initialise the underlying cipher. Parameter can either be an AEADParameters or a ParametersWithIV object. * * @param forEncryption true if we are setting up for encryption, false otherwise. * @param params the necessary parameters for the underlying cipher to be initialised. * @exception IllegalArgumentException if the params argument is inappropriate. */ public void init(boolean forEncryption, CipherParameters params) throws IllegalArgumentException; /** * Return the name of the algorithm. * * @return the algorithm name. */ public String getAlgorithmName(); /** * return the cipher this object wraps. * * @return the cipher this object wraps. */ public BlockCipher getUnderlyingCipher(); /** * encrypt/decrypt a single byte. * * @param in the byte to be processed. * @param out the output buffer the processed byte goes into. * @param outOff the offset into the output byte array the processed data starts at. * @return the number of bytes written to out. * @exception DataLengthException if the output buffer is too small. */ public int processByte(byte in, byte[] out, int outOff) throws DataLengthException; /** * process a block of bytes from in putting the result into out. * * @param in the input byte array. * @param inOff the offset into the in array where the data to be processed starts. * @param len the number of bytes to be processed. * @param out the output buffer the processed bytes go into. * @param outOff the offset into the output byte array the processed data starts at. * @return the number of bytes written to out. * @exception DataLengthException if the output buffer is too small. */ public int processBytes(byte[] in, int inOff, int len, byte[] out, int outOff) throws DataLengthException; /** * Finish the operation either appending or verifying the MAC at the end of the data. * * @param out space for any resulting output data. * @param outOff offset into out to start copying the data at. * @return number of bytes written into out. * @throws IllegalStateException if the cipher is in an inappropriate state. * @throws org.bouncycastle.crypto.InvalidCipherTextException if the MAC fails to match. */ public int doFinal(byte[] out, int outOff) throws IllegalStateException, InvalidCipherTextException; /** * Return the value of the MAC associated with the last stream processed. * * @return MAC for plaintext data. */ public byte[] getMac(); /** * return the size of the output buffer required for a processBytes * an input of len bytes. * * @param len the length of the input. * @return the space required to accommodate a call to processBytes * with len bytes of input. */ public int getUpdateOutputSize(int len); /** * return the size of the output buffer required for a processBytes plus a * doFinal with an input of len bytes. * * @param len the length of the input. * @return the space required to accommodate a call to processBytes and doFinal * with len bytes of input. */ public int getOutputSize(int len); /** * Reset the cipher. After resetting the cipher is in the same state * as it was after the last init (if there was one). */ public void reset(); }
src/org/bouncycastle/crypto/modes/AEADBlockCipher.java
package org.bouncycastle.crypto.modes; import org.bouncycastle.crypto.BlockCipher; import org.bouncycastle.crypto.CipherParameters; import org.bouncycastle.crypto.DataLengthException; import org.bouncycastle.crypto.InvalidCipherTextException; /** * A block cipher mode that includes authenticated encryption with a streaming mode and optional associated data. * @see org.bouncycastle.crypto.params.AEADParameters */ public interface AEADBlockCipher { /** * initialise the underlying cipher. Parameter can either be an AEADParameters or a ParametersWithIV object. * * @param forEncryption true if we are setting up for encryption, false otherwise. * @param params the necessary parameters for the underlying cipher to be initialised. * @exception IllegalArgumentException if the params argument is inappropriate. */ public void init(boolean forEncryption, CipherParameters params) throws IllegalArgumentException; /** * Return the name of the algorithm. * * @return the algorithm name. */ public String getAlgorithmName(); /** * return the cipher this object wraps. * * @return the cipher this object wraps. */ public BlockCipher getUnderlyingCipher(); /** * encrypt/decrypt a single byte. * * @param in the byte to be processed. * @param out the output buffer the processed byte goes into. * @param outOff the offset into the output byte array the processed data starts at. * @return the number of bytes written to out. * @exception DataLengthException if the output buffer is too small. */ public int processByte(byte in, byte[] out, int outOff) throws DataLengthException; /** * process a block of bytes from in putting the result into out. * * @param in the input byte array. * @param inOff the offset into the in array where the data to be processed starts. * @param len the number of bytes to be processed. * @param out the output buffer the processed bytes go into. * @param outOff the offset into the output byte array the processed data starts at. * @return the number of bytes written to out. * @exception DataLengthException if the output buffer is too small. */ public int processBytes(byte[] in, int inOff, int len, byte[] out, int outOff) throws DataLengthException; /** * Finish the operation either appending or verifying the MAC at the end of the data. * * @param out space for any resulting output data. * @param outOff offset into out to start copying the data at. * @return number of bytes written into out. * @throws IllegalStateException if the cipher is in an inappropriate state. * @throws org.bouncycastle.crypto.InvalidCipherTextException if the MAC fails to match. */ public int doFinal(byte[] out, int outOff) throws IllegalStateException, InvalidCipherTextException; /** * Return the value of the MAC associated with the last stream processed. * * @return MAC for plaintext data. */ public byte[] getMac(); /** * return the size of the output buffer required for a processBytes * an input of len bytes. * * @param len the length of the input. * @return the space required to accommodate a call to processBytes * with len bytes of input. */ public int getUpdateOutputSize(int len); /** * return the size of the output buffer required for a processBytes plus a * doFinal with an input of len bytes. * * @param len the length of the input. * @return the space required to accommodate a call to processBytes and doFinal * with len bytes of input. */ public int getOutputSize(int len); }
Include reset() method as part of interface
src/org/bouncycastle/crypto/modes/AEADBlockCipher.java
Include reset() method as part of interface
<ide><path>rc/org/bouncycastle/crypto/modes/AEADBlockCipher.java <ide> * with len bytes of input. <ide> */ <ide> public int getOutputSize(int len); <add> <add> /** <add> * Reset the cipher. After resetting the cipher is in the same state <add> * as it was after the last init (if there was one). <add> */ <add> public void reset(); <ide> }
Java
apache-2.0
4bd821646eb24245b2c39fe1551a0a4920a22e6c
0
thomasjungblut/thomasjungblut-common
package de.jungblut.nlp; import java.util.Arrays; import java.util.HashSet; import java.util.Iterator; import java.util.Random; import java.util.Set; import com.google.common.base.Preconditions; import de.jungblut.math.DoubleVector; import de.jungblut.math.DoubleVector.DoubleVectorElement; /** * Linear MinHash algorithm to find near duplicates faster or to speedup nearest * neighbour searches. * * @author thomas.jungblut * */ public final class MinHash { private final int numHashes; private final int[] seed1; private final int[] seed2; private MinHash(int numHashes) { this(numHashes, System.currentTimeMillis()); } private MinHash(int numHashes, long seed) { this.numHashes = numHashes; this.seed1 = new int[numHashes]; this.seed2 = new int[numHashes]; Random r = new Random(seed); for (int i = 0; i < numHashes; i++) { this.seed1[i] = r.nextInt(); this.seed2[i] = r.nextInt(); } } /** * Minhashes the given vector by iterating over all non zero items and hashing * each byte in its value (as an integer). So it will end up with 4 bytes to * be hashed into a single integer by a linear hash function. * * @param vector a arbitrary vector. * @return a int array of min hashes based on how many hashes were configured. */ public int[] minHashVector(DoubleVector vector) { int[] minHashes = new int[numHashes]; byte[] bytesToHash = new byte[4]; Arrays.fill(minHashes, Integer.MAX_VALUE); for (int i = 0; i < numHashes; i++) { Iterator<DoubleVectorElement> iterateNonZero = vector.iterateNonZero(); while (iterateNonZero.hasNext()) { DoubleVectorElement next = iterateNonZero.next(); int value = (int) next.getValue(); bytesToHash[0] = (byte) (value >> 24); bytesToHash[1] = (byte) (value >> 16); bytesToHash[2] = (byte) (value >> 8); bytesToHash[3] = (byte) value; int hash = hash(bytesToHash, seed1[i], seed2[i]); if (minHashes[i] > hash) { minHashes[i] = hash; } } } return minHashes; } /** * Measures the similarity between two min hash arrays by comparing the hashes * at the same index. This is assuming that both arrays having the same size. * * @return a similarity between 0 and 1, where 1 is very similar. */ public double measureSimilarity(int[] left, int[] right) { Preconditions.checkArgument(left.length == right.length, "Left length was not equal to right length! " + left.length + " != " + right.length); double identicalMinHashes = 0.0d; for (int i = 0; i < left.length; i++) { if (left[i] == right[i]) { identicalMinHashes++; } } return identicalMinHashes / left.length; } /** * Generates cluster keys from the minhashes. Make sure that if you are going * to lookup the ids in a hashtable, sort out these that don't have a specific * minimum occurence. Also make sure that if you're using this in parallel, * you have to make sure that the seeds of the minhash should be consistent * across each task. Otherwise this key will be completely random. * * @param keyGroups how many keygroups there should be, normally it's just a * single per hash. * @return a set of string IDs that can refer as cluster identifiers. */ public Set<String> createClusterKeys(int[] minHashes, int keyGroups) { HashSet<String> set = new HashSet<>(); for (int i = 0; i < numHashes; i++) { StringBuilder clusterIdBuilder = new StringBuilder(); for (int j = 0; j < keyGroups; j++) { clusterIdBuilder.append(minHashes[(i + j) % minHashes.length]).append( '_'); } String clusterId = clusterIdBuilder.toString(); clusterId = clusterId.substring(0, clusterId.lastIndexOf('_')); set.add(clusterId); } return set; } /** * Creates a {@link MinHash} instance with the given number of hash functions. */ public static MinHash create(int numHashes) { return new MinHash(numHashes); } /** * Creates a {@link MinHash} instance with the given number of hash functions * and a seed to be used in parallel systems. */ public static MinHash create(int numHashes, long seed) { return new MinHash(numHashes, seed); } /** * Linear hashfunction with two random seeds. */ private static int hash(byte[] bytes, int seed1, int seed2) { long hashValue = 31; for (byte byteVal : bytes) { hashValue *= seed1 * byteVal; hashValue += seed2; } return Math.abs((int) (hashValue % 2147482949)); } }
src/de/jungblut/nlp/MinHash.java
package de.jungblut.nlp; import java.util.Arrays; import java.util.Iterator; import java.util.Random; import com.google.common.base.Preconditions; import de.jungblut.math.DoubleVector; import de.jungblut.math.DoubleVector.DoubleVectorElement; /** * Linear MinHash algorithm to find near duplicates faster or to speedup nearest * neighbour searches. * * @author thomas.jungblut * */ public final class MinHash { private final int numHashes; private final int[] seed1; private final int[] seed2; private MinHash(int numHashes) { this.numHashes = numHashes; this.seed1 = new int[numHashes]; this.seed2 = new int[numHashes]; Random r = new Random(); for (int i = 0; i < numHashes; i++) { this.seed1[i] = r.nextInt(); this.seed2[i] = r.nextInt(); } } /** * Minhashes the given vector by iterating over all non zero items and hashing * each byte in its value (as an integer). So it will end up with 4 bytes to * be hashed into a single integer by a linear hash function. * * @param vector a arbitrary vector. * @return a int array of min hashes based on how many hashes were configured. */ public int[] minHashVector(DoubleVector vector) { int[] minHashes = new int[numHashes]; byte[] bytesToHash = new byte[4]; Arrays.fill(minHashes, Integer.MAX_VALUE); for (int i = 0; i < numHashes; i++) { Iterator<DoubleVectorElement> iterateNonZero = vector.iterateNonZero(); while (iterateNonZero.hasNext()) { DoubleVectorElement next = iterateNonZero.next(); int value = (int) next.getValue(); bytesToHash[0] = (byte) (value >> 24); bytesToHash[1] = (byte) (value >> 16); bytesToHash[2] = (byte) (value >> 8); bytesToHash[3] = (byte) value; int hash = hash(bytesToHash, seed1[i], seed2[i]); if (minHashes[i] > hash) { minHashes[i] = hash; } } } return minHashes; } /** * Measures the similarity between two min hash arrays by comparing the hashes * at the same index. This is assuming that both arrays having the same size. * * @return a similarity between 0 and 1, where 1 is very similar. */ public double measureSimilarity(int[] left, int[] right) { Preconditions.checkArgument(left.length == right.length, "Left length was not equal to right length! " + left.length + " != " + right.length); double identicalMinHashes = 0.0d; for (int i = 0; i < left.length; i++) { if (left[i] == right[i]) { identicalMinHashes++; } } return identicalMinHashes / left.length; } /** * Creates a {@link MinHash} instance with the given number of hash functions. */ public static MinHash create(int numHashes) { return new MinHash(numHashes); } /** * Linear hashfunction with two random seeds. */ private static int hash(byte[] bytes, int seed1, int seed2) { long hashValue = 31; for (byte byteVal : bytes) { hashValue *= seed1 * byteVal; hashValue += seed2; } return Math.abs((int) (hashValue % 2147482949)); } }
generate cluster keys from a minhash
src/de/jungblut/nlp/MinHash.java
generate cluster keys from a minhash
<ide><path>rc/de/jungblut/nlp/MinHash.java <ide> package de.jungblut.nlp; <ide> <ide> import java.util.Arrays; <add>import java.util.HashSet; <ide> import java.util.Iterator; <ide> import java.util.Random; <add>import java.util.Set; <ide> <ide> import com.google.common.base.Preconditions; <ide> <ide> private final int[] seed2; <ide> <ide> private MinHash(int numHashes) { <add> this(numHashes, System.currentTimeMillis()); <add> } <add> <add> private MinHash(int numHashes, long seed) { <ide> this.numHashes = numHashes; <ide> this.seed1 = new int[numHashes]; <ide> this.seed2 = new int[numHashes]; <ide> <del> Random r = new Random(); <add> Random r = new Random(seed); <ide> for (int i = 0; i < numHashes; i++) { <ide> this.seed1[i] = r.nextInt(); <ide> this.seed2[i] = r.nextInt(); <ide> } <ide> <ide> /** <add> * Generates cluster keys from the minhashes. Make sure that if you are going <add> * to lookup the ids in a hashtable, sort out these that don't have a specific <add> * minimum occurence. Also make sure that if you're using this in parallel, <add> * you have to make sure that the seeds of the minhash should be consistent <add> * across each task. Otherwise this key will be completely random. <add> * <add> * @param keyGroups how many keygroups there should be, normally it's just a <add> * single per hash. <add> * @return a set of string IDs that can refer as cluster identifiers. <add> */ <add> public Set<String> createClusterKeys(int[] minHashes, int keyGroups) { <add> HashSet<String> set = new HashSet<>(); <add> <add> for (int i = 0; i < numHashes; i++) { <add> StringBuilder clusterIdBuilder = new StringBuilder(); <add> for (int j = 0; j < keyGroups; j++) { <add> clusterIdBuilder.append(minHashes[(i + j) % minHashes.length]).append( <add> '_'); <add> } <add> String clusterId = clusterIdBuilder.toString(); <add> clusterId = clusterId.substring(0, clusterId.lastIndexOf('_')); <add> set.add(clusterId); <add> } <add> <add> return set; <add> } <add> <add> /** <ide> * Creates a {@link MinHash} instance with the given number of hash functions. <ide> */ <ide> public static MinHash create(int numHashes) { <ide> return new MinHash(numHashes); <add> } <add> <add> /** <add> * Creates a {@link MinHash} instance with the given number of hash functions <add> * and a seed to be used in parallel systems. <add> */ <add> public static MinHash create(int numHashes, long seed) { <add> return new MinHash(numHashes, seed); <ide> } <ide> <ide> /**
JavaScript
bsd-3-clause
3ebb4155a4f6bfbb8549e3805d31a4115380728a
0
Migweld/spree,volpejoaquin/spree,cutefrank/spree,madetech/spree,miyazawatomoka/spree,degica/spree,groundctrl/spree,dru/pokupalka,Boomkat/spree,carlesjove/spree,jimblesm/spree,jordan-brough/solidus,devilcoders/solidus,shaywood2/spree,tesserakt/clean_spree,brchristian/spree,JDutil/spree,beni55/spree,hifly/spree,trigrass2/spree,firman/spree,paulcc/spree,pulkit21/spree,patdec/spree,watg/spree,kitwalker12/spree,Nevensoft/spree,net2b/spree,KMikhaylovCTG/spree,alepore/spree,yushine/spree,bonobos/solidus,fahidnasir/spree,PhoenixTeam/spree_phoenix,LBRapid/spree,dafontaine/spree,dotandbo/spree,reinaris/spree,Kagetsuki/spree,jeffboulet/spree,jeffboulet/spree,Migweld/spree,vmatekole/spree,beni55/spree,bricesanchez/spree,net2b/spree,ayb/spree,Ropeney/spree,shaywood2/spree,edgward/spree,forkata/solidus,nooysters/spree,caiqinghua/spree,shekibobo/spree,brchristian/spree,imella/spree,devilcoders/solidus,wolfieorama/spree,tomash/spree,njerrywerry/spree,softr8/spree,jaspreet21anand/spree,shaywood2/spree,NerdsvilleCEO/spree,Boomkat/spree,dru/pokupalka,tomash/spree,jimblesm/spree,bjornlinder/Spree,freerunningtech/spree,zaeznet/spree,edgward/spree,quentinuys/spree,builtbybuffalo/spree,ramkumar-kr/spree,tailic/spree,omarsar/spree,builtbybuffalo/spree,sanjay1185/mystore,JuandGirald/spree,madetech/spree,locomotivapro/spree,codesavvy/sandbox,vinsol/spree,richardnuno/solidus,ckk-scratch/solidus,gautamsawhney/spree,lsirivong/solidus,richardnuno/solidus,abhishekjain16/spree,hifly/spree,NerdsvilleCEO/spree,lsirivong/spree,DarkoP/spree,Ropeney/spree,PhoenixTeam/spree_phoenix,alejandromangione/spree,wolfieorama/spree,grzlus/spree,kitwalker12/spree,ujai/spree,rakibulislam/spree,thogg4/spree,zamiang/spree,JuandGirald/spree,vmatekole/spree,piousbox/spree,tancnle/spree,jimblesm/spree,CJMrozek/spree,brchristian/spree,assembledbrands/spree,Mayvenn/spree,lyzxsc/spree,calvinl/spree,Boomkat/spree,pervino/spree,jordan-brough/spree,vinsol/spree,derekluo/spree,camelmasa/spree,jhawthorn/spree,knuepwebdev/FloatTubeRodHolders,archSeer/spree,jaspreet21anand/spree,rajeevriitm/spree,rakibulislam/spree,rbngzlv/spree,biagidp/spree,vmatekole/spree,sfcgeorge/spree,thogg4/spree,kitwalker12/spree,joanblake/spree,carlesjove/spree,ckk-scratch/solidus,ahmetabdi/spree,Machpowersystems/spree_mach,mleglise/spree,paulcc/spree,forkata/solidus,degica/spree,pronix/kenigtorg,RatioClothing/spree,Antdesk/karpal-spree,DarkoP/spree,vcavallo/spree,SadTreeFriends/spree,thogg4/spree,odk211/spree,dotandbo/spree,progsri/spree,HealthWave/spree,KMikhaylovCTG/spree,agient/agientstorefront,forkata/solidus,hoanghiep90/spree,radarseesradar/spree,fahidnasir/spree,TrialGuides/spree,Engeltj/spree,sunny2601/spree,jparr/spree,raow/spree,JDutil/spree,jparr/spree,gregoryrikson/spree-sample,alejandromangione/spree,adaddeo/spree,pulkit21/spree,pjmj777/spree,gregoryrikson/spree-sample,berkes/spree,bonobos/solidus,Nevensoft/spree,njerrywerry/spree,berkes/spree,jhnsntmthy/tgs_store,CiscoCloud/spree,ujai/spree,keatonrow/spree,scottcrawford03/solidus,volpejoaquin/spree,LBRapid/spree,azclick/spree,vinsol/spree,surfdome/spree,dafontaine/spree,delphsoft/spree-store-ballchair,Senjai/solidus,reidblomquist/spree,groundctrl/spree,azclick/spree,devilcoders/solidus,jasonfb/spree,project-eutopia/spree,bonobos/solidus,trigrass2/spree,yushine/spree,urimikhli/spree,locomotivapro/spree,vivekamn/spree,zaeznet/spree,Engeltj/spree,delphsoft/spree-store-ballchair,volpejoaquin/spree,Kagetsuki/spree,rakibulislam/spree,xuewenfei/solidus,lzcabrera/spree-1-3-stable,edgward/spree,njerrywerry/spree,joanblake/spree,NerdsvilleCEO/spree,sliaquat/spree,calvinl/spree,Mayvenn/spree,jeffboulet/spree,maybii/spree,omarsar/spree,jhnsntmthy/tgs_store,miyazawatomoka/spree,alejandromangione/spree,Mayvenn/spree,TrialGuides/spree,jsurdilla/solidus,derekluo/spree,hoanghiep90/spree,gautamsawhney/spree,sfcgeorge/spree,judaro13/spree-fork,lzcabrera/spree-1-3-stable,devilcoders/solidus,vulk/spree,gotoAndBliss/True-Jersey,APohio/spree,miyazawatomoka/spree,odk211/spree,ahmetabdi/spree,vmatekole/spree,net2b/spree,Engeltj/spree,agient/agientstorefront,berkes/spree,lzcabrera/spree-1-3-stable,surfdome/spree,mleglise/spree,JDutil/spree,kewaunited/spree,lyzxsc/spree,Nevensoft/spree,piousbox/spree,TrialGuides/spree,CiscoCloud/spree,priyank-gupta/spree,FadliKun/spree,StemboltHQ/spree,APohio/spree,hoanghiep90/spree,LBRapid/spree,TimurTarasenko/spree,fahidnasir/spree,rakibulislam/spree,vulk/spree,softr8/spree,pulkit21/spree,shekibobo/spree,jhnsntmthy/tgs_store,athal7/solidus,hifly/spree,pjmj777/spree,Lostmyname/spree,codesavvy/sandbox,HealthWave/spree,Senjai/solidus,woboinc/spree,ahmetabdi/spree,Arpsara/solidus,yiqing95/spree,Antdesk/karpal-spree,firman/spree,welitonfreitas/spree,quentinuys/spree,dandanwei/spree,raow/spree,bricesanchez/spree,Antdesk/karpal-spree,tancnle/spree,reidblomquist/spree,mindvolt/spree,ayb/spree,cutefrank/spree,StemboltHQ/spree,yomishra/pce,assembledbrands/spree,jhawthorn/spree,builtbybuffalo/spree,azclick/spree,locomotivapro/spree,JDutil/spree,DynamoMTL/spree,reinaris/spree,alvinjean/spree,CJMrozek/spree,project-eutopia/spree,codesavvy/sandbox,tomash/spree,gautamsawhney/spree,hifly/spree,archSeer/spree,dotandbo/spree,kewaunited/spree,net2b/spree,scottcrawford03/solidus,pervino/solidus,CiscoCloud/spree,mindvolt/spree,Arpsara/solidus,tesserakt/clean_spree,dafontaine/spree,pervino/spree,yiqing95/spree,gregoryrikson/spree-sample,FadliKun/spree,raow/spree,vinayvinsol/spree,maybii/spree,Kagetsuki/spree,grzlus/solidus,madetech/spree,vcavallo/spree,keatonrow/spree,StemboltHQ/spree,pervino/solidus,lsirivong/solidus,SadTreeFriends/spree,karlitxo/spree,Arpsara/solidus,imella/spree,judaro13/spree-fork,DarkoP/spree,calvinl/spree,progsri/spree,useiichi/spree,moneyspyder/spree,pervino/solidus,Boomkat/spree,TimurTarasenko/spree,Hates/spree,alvinjean/spree,hoanghiep90/spree,PhoenixTeam/spree_phoenix,ujai/spree,gregoryrikson/spree-sample,vinsol/spree,project-eutopia/spree,yomishra/pce,ramkumar-kr/spree,vcavallo/spree,joanblake/spree,delphsoft/spree-store-ballchair,grzlus/spree,progsri/spree,softr8/spree,shekibobo/spree,freerunningtech/spree,quentinuys/spree,grzlus/solidus,forkata/solidus,zamiang/spree,gautamsawhney/spree,lyzxsc/spree,Lostmyname/spree,FadliKun/spree,KMikhaylovCTG/spree,AgilTec/spree,azclick/spree,jasonfb/spree,lsirivong/spree,siddharth28/spree,jasonfb/spree,useiichi/spree,sideci-sample/sideci-sample-spree,karlitxo/spree,RatioClothing/spree,yiqing95/spree,jasonfb/spree,reinaris/spree,SadTreeFriends/spree,reidblomquist/spree,softr8/spree,Migweld/spree,priyank-gupta/spree,athal7/solidus,Kagetsuki/spree,pervino/spree,jaspreet21anand/spree,lsirivong/spree,firman/spree,useiichi/spree,caiqinghua/spree,firman/spree,madetech/spree,CiscoCloud/spree,shioyama/spree,patdec/spree,tancnle/spree,NerdsvilleCEO/spree,pjmj777/spree,thogg4/spree,derekluo/spree,AgilTec/spree,alvinjean/spree,progsri/spree,urimikhli/spree,jordan-brough/spree,beni55/spree,yushine/spree,caiqinghua/spree,Hawaiideveloper/shoppingcart,priyank-gupta/spree,trigrass2/spree,ayb/spree,sunny2601/spree,keatonrow/spree,richardnuno/solidus,orenf/spree,Hawaiideveloper/shoppingcart,Hates/spree,JuandGirald/spree,TimurTarasenko/spree,volpejoaquin/spree,carlesjove/spree,rajeevriitm/spree,njerrywerry/spree,abhishekjain16/spree,jsurdilla/solidus,Senjai/solidus,xuewenfei/solidus,robodisco/spree,azranel/spree,athal7/solidus,ramkumar-kr/spree,priyank-gupta/spree,groundctrl/spree,omarsar/spree,CJMrozek/spree,shioyama/spree,siddharth28/spree,jspizziri/spree,assembledbrands/spree,Lostmyname/spree,jordan-brough/spree,pervino/solidus,ayb/spree,nooysters/spree,codesavvy/sandbox,rbngzlv/spree,archSeer/spree,pronix/kenigtorg,TrialGuides/spree,Senjai/spree,watg/spree,alepore/spree,SadTreeFriends/spree,moneyspyder/spree,orenf/spree,woboinc/spree,yushine/spree,jordan-brough/solidus,omarsar/spree,knuepwebdev/FloatTubeRodHolders,richardnuno/solidus,scottcrawford03/solidus,degica/spree,moneyspyder/spree,judaro13/spree-fork,project-eutopia/spree,ckk-scratch/solidus,raow/spree,builtbybuffalo/spree,beni55/spree,tesserakt/clean_spree,patdec/spree,sunny2601/spree,Arpsara/solidus,tesserakt/clean_spree,Hates/spree,trigrass2/spree,bjornlinder/Spree,preston-scott/spree,Hawaiideveloper/shoppingcart,brchristian/spree,alejandromangione/spree,jsurdilla/solidus,edgward/spree,carlesjove/spree,ramkumar-kr/spree,gotoAndBliss/True-Jersey,sideci-sample/sideci-sample-spree,lsirivong/solidus,vulk/spree,radarseesradar/spree,karlitxo/spree,kewaunited/spree,sideci-sample/sideci-sample-spree,wolfieorama/spree,jspizziri/spree,jhawthorn/spree,camelmasa/spree,lsirivong/spree,grzlus/spree,JuandGirald/spree,odk211/spree,rbngzlv/spree,preston-scott/spree,adaddeo/spree,grzlus/spree,imella/spree,grzlus/solidus,DarkoP/spree,Nevensoft/spree,cutefrank/spree,caiqinghua/spree,adaddeo/spree,zaeznet/spree,reidblomquist/spree,lsirivong/solidus,siddharth28/spree,watg/spree,zamiang/spree,sliaquat/spree,shekibobo/spree,archSeer/spree,bonobos/solidus,sliaquat/spree,Machpowersystems/spree_mach,piousbox/spree,siddharth28/spree,DynamoMTL/spree,HealthWave/spree,Ropeney/spree,freerunningtech/spree,AgilTec/spree,Machpowersystems/spree_mach,camelmasa/spree,PhoenixTeam/spree_phoenix,azranel/spree,grzlus/solidus,jordan-brough/solidus,jparr/spree,Senjai/solidus,Ropeney/spree,Engeltj/spree,CJMrozek/spree,rajeevriitm/spree,maybii/spree,reinaris/spree,alvinjean/spree,orenf/spree,calvinl/spree,robodisco/spree,welitonfreitas/spree,welitonfreitas/spree,athal7/solidus,berkes/spree,azranel/spree,alepore/spree,DynamoMTL/spree,tomash/spree,xuewenfei/solidus,Hawaiideveloper/shoppingcart,tailic/spree,yiqing95/spree,vinayvinsol/spree,joanblake/spree,derekluo/spree,robodisco/spree,bricesanchez/spree,AgilTec/spree,groundctrl/spree,mindvolt/spree,locomotivapro/spree,abhishekjain16/spree,pulkit21/spree,kewaunited/spree,vulk/spree,camelmasa/spree,lyzxsc/spree,xuewenfei/solidus,sfcgeorge/spree,dandanwei/spree,rbngzlv/spree,jeffboulet/spree,DynamoMTL/spree,bjornlinder/Spree,KMikhaylovCTG/spree,APohio/spree,agient/agientstorefront,ckk-scratch/solidus,knuepwebdev/FloatTubeRodHolders,radarseesradar/spree,radarseesradar/spree,mleglise/spree,yomishra/pce,biagidp/spree,karlitxo/spree,useiichi/spree,FadliKun/spree,jaspreet21anand/spree,tancnle/spree,zaeznet/spree,jspizziri/spree,jparr/spree,piousbox/spree,shaywood2/spree,fahidnasir/spree,odk211/spree,sfcgeorge/spree,surfdome/spree,surfdome/spree,zamiang/spree,jordan-brough/solidus,Migweld/spree,delphsoft/spree-store-ballchair,wolfieorama/spree,urimikhli/spree,sliaquat/spree,nooysters/spree,cutefrank/spree,vcavallo/spree,APohio/spree,maybii/spree,woboinc/spree,jspizziri/spree,dotandbo/spree,bryanmtl/spree_clear2pay,josephholsten/plain-sight,vinayvinsol/spree,agient/agientstorefront,dandanwei/spree,ahmetabdi/spree,orenf/spree,shioyama/spree,mleglise/spree,Hates/spree,tailic/spree,josephholsten/plain-sight,vivekamn/spree,Senjai/spree,patdec/spree,abhishekjain16/spree,nooysters/spree,adaddeo/spree,keatonrow/spree,Mayvenn/spree,Senjai/spree,RatioClothing/spree,TimurTarasenko/spree,sunny2601/spree,dandanwei/spree,rajeevriitm/spree,mindvolt/spree,pervino/spree,azranel/spree,robodisco/spree,miyazawatomoka/spree,Lostmyname/spree,jsurdilla/solidus,vinayvinsol/spree,biagidp/spree,quentinuys/spree,dafontaine/spree,jimblesm/spree,scottcrawford03/solidus,moneyspyder/spree,welitonfreitas/spree
var regions = new Array('billing', 'shipping', 'shipping_method', 'creditcard', 'confirm_order'); $(document).ajaxSend(function(event, request, settings) { if (typeof(AUTH_TOKEN) == "undefined") return; // settings.data is a serialized string like "foo=bar&baz=boink" (or null) settings.data = settings.data || ""; settings.data += (settings.data ? "&" : "") + "authenticity_token=" + encodeURIComponent(AUTH_TOKEN); }); // public/javascripts/application.js jQuery.ajaxSetup({ 'beforeSend': function(xhr) {xhr.setRequestHeader("Accept", "text/javascript")} }) jQuery.fn.submitWithAjax = function() { this.change(function() { $.post('select_country', $(this).serialize(), null, "script"); return false; }) return this; }; jQuery.fn.sameAddress = function() { this.click(function() { if(!$(this).attr('checked')) { //Clear ship values? return; } $('input#hidden_sstate').val($('input#hidden_bstate').val()); $("#billing input, #billing select").each(function() { $("#shipping #"+ $(this).attr('id').replace('bill', 'ship')).val($(this).val()); }) update_state('s'); }) } //On page load $(function() { //$("#checkout_presenter_bill_address_country_id").submitWithAjax(); $('#checkout_presenter_same_address').sameAddress(); $('span#bcountry select').change(function() { update_state('b'); }); $('span#scountry select').change(function() { update_state('s'); }); get_states(); $('#validate_billing').click(function() { if(validate_section('billing')) { submit_billing(); }}); $('#validate_shipping').click(function() { if(validate_section('shipping')) { submit_shipping(); }}); $('#select_shipping_method').click(function() { submit_shipping_method(); }); $('#confirm_payment').click(function() { if(validate_section('creditcard')) { confirm_payment(); }}); $('form#checkout_form').submit(function() { return !($('div#confirm_order').hasClass('checkout_disabled')); }); }) //Initial state mapper on page load var state_mapper; var get_states = function() { $.getJSON('/states.js', function(json) { state_mapper = json; $('span#bcountry select').val($('input#hidden_bcountry').val()); update_state('b'); $('span#bstate :only-child').val($('input#hidden_bstate').val()); $('span#scountry select').val($('input#hidden_scountry').val()); update_state('s'); $('span#sstate :only-child').val($('input#hidden_sstate').val()); }); }; // replace the :only child of the parent with the given html, and transfer // {name,id} attributes over, returning the new child var chg_state_input_element = function (parent, html) { var child = parent.find(':only-child'); html.addClass('required') .attr('name', child.attr('name')) .attr('id', child.attr('id')); child.remove(); // better as parent-relative? parent.append(html); return html; }; // TODO: better as sibling dummy state ? // Update the input method for address.state // var update_state = function(region) { var country = $('span#' + region + 'country :only-child').val(); var states = state_mapper[country]; var hidden_element = $('input#hidden_' + region + 'state'); var replacement; if(states) { // recreate state selection list replacement = $(document.createElement('select')); $.each(states, function(id,nm) { var opt = $(document.createElement('option')) .attr('value', id) .html(nm); replacement.append(opt) if (id == hidden_element.val()) { opt.attr('selected', 'true') } // set this directly IFF the old value is still valid }); } else { // recreate an input box replacement = $(document.createElement('input')); if (! hidden_element.val().match(/^\d+$/)) { replacement.val(hidden_element.val()) } } chg_state_input_element($('span#' + region + 'state'), replacement); hidden_element.val(replacement.val()); // callback to update val when form object is changed // This is only needed if we want to preserve state when someone refreshes the checkout page // Or... if someone changes between countries with no given states replacement.change(function() { $('input#hidden_' + region + 'state').val($(this).val()); }); }; var validate_section = function(region) { var validator = $('form#checkout_form').validate(); var valid = true; $('div#' + region + ' input, div#' + region + ' select, div#' + region + ' textarea').each(function() { if(!validator.element(this)) { valid = false; } }); return valid; }; var shift_to_region = function(active) { $('div#flash-errors').remove(); var found = 0; for(var i=0; i<regions.length; i++) { if(!found) { if(active == regions[i]) { $('div#' + regions[i] + ' h2').unbind('click').css('cursor', 'default'); $('div#' + regions[i] + ' div.inner').show('fast'); $('div#' + regions[i]).removeClass('checkout_disabled'); found = 1; } else { $('div#' + regions[i] + ' h2').unbind('click').css('cursor', 'pointer').click(function() {shift_to_region($(this).parent().attr('id'));}); $('div#' + regions[i] + ' div.inner').hide('fast'); } } else { $('div#' + regions[i] + ' h2').unbind('click').css('cursor', 'default'); $('div#' + regions[i] + ' div.inner').hide('fast'); $('div#' + regions[i]).addClass('checkout_disabled'); } } if (active == 'confirm_order') { $("input#final_answer").attr("value", "yes"); } else { // indicates order is ready to be processed (as opposed to simply updated) $("input#final_answer").attr("value", ""); } return; }; var submit_billing = function() { shift_to_region('shipping'); build_address('Billing Address', 'b'); return; }; var build_address = function(title, region) { var address = '<h3>' + title + '</h3>'; address += $('p#' + region + 'fname input').val() + ' ' + $('p#blname input').val() + '<br />'; address += $('p#' + region + 'address input').val() + '<br />'; if($('p#' + region + 'address2').val() != '') { address += $('p#' + region + 'address2').val() + '<br />'; } address += $('p#' + region + 'city input').val() + ', '; if($('span#' + region + 'state input').length > 0) { address += $('span#' + region + 'state input').val(); } else { address += $('span#' + region + 'state :selected').html(); } address += ' ' + $('p#' + region + 'zip input').val() + '<br />'; address += $('p#' + region + 'country :selected').html() + '<br />'; address += $('p#' + region + 'phone input').val(); $('div#' + region + 'display').html(address); return; }; var submit_shipping = function() { $('div#methods :child').remove(); $('div#methods').append($(document.createElement('img')).attr('src', '/images/ajax_loader.gif').attr('id', 'shipping_loader')); // Save what we have so far and get the list of shipping methods via AJAX $.ajax({ type: "POST", url: 'complete', beforeSend : function (xhr) { xhr.setRequestHeader('Accept-Encoding', 'identity'); }, dataType: "json", data: $('#checkout_form').serialize(), success: function(json) { update_shipping_methods(json.available_methods); }, error: function (XMLHttpRequest, textStatus, errorThrown) { // TODO - put some real error handling in here $("#error").html(XMLHttpRequest.responseText); } }); shift_to_region('shipping_method'); build_address('Shipping Address', 's'); return; }; var submit_shipping_method = function() { //TODO: Move to validate_section('shipping_method'), but must debug how to validate radio buttons var valid = false; $('div#methods :child input').each(function() { if($(this).attr('checked')) { valid = true; } }); if(valid) { // Save what we have so far and get the updated order totals via AJAX $.ajax({ type: "POST", url: 'complete', beforeSend : function (xhr) { xhr.setRequestHeader('Accept-Encoding', 'identity'); }, dataType: "json", data: $('#checkout_form').serialize(), success: function(json) { update_confirmation(json.order); }, error: function (XMLHttpRequest, textStatus, errorThrown) { // TODO - put some real error handling in here //$("#error").html(XMLHttpRequest.responseText); } }); shift_to_region('creditcard'); } else { var p = document.createElement('p'); $(p).append($(document.createElement('label')).addClass('error').html('Please select a shipping method').css('width', '300px').css('top', '0px')); $('div#methods').append(p); } }; var update_shipping_methods = function(methods) { $(methods).each( function(i) { $('div$methods img#shipping_loader').remove(); var p = document.createElement('p'); var s = this.name + ' ' + this.rate; $(p).append($(document.createElement('input')) .attr('id', s) .attr('type', 'radio') .attr('name', 'method_id') .attr(1 == $(methods).length ? 'checked' : 'notchecked', 'foo') .val(this.id) ); $(p).append($(document.createElement('label')) .attr('for', s) .html(s) .css('top', '-1px')); $('div#methods').append(p); }); $('div#methods input:first').attr('validate', 'required:true'); return; } var update_confirmation = function(order) { $('span#order_total').html(order.order_total); $('span#ship_amount').html(order.ship_amount); $('span#tax_amount').html(order.tax_amount); $('span#ship_method').html(order.ship_method); } var confirm_payment = function() { shift_to_region('confirm_order'); };
public/javascripts/checkout.js
var regions = new Array('billing', 'shipping', 'shipping_method', 'creditcard', 'confirm_order'); $(document).ajaxSend(function(event, request, settings) { if (typeof(AUTH_TOKEN) == "undefined") return; // settings.data is a serialized string like "foo=bar&baz=boink" (or null) settings.data = settings.data || ""; settings.data += (settings.data ? "&" : "") + "authenticity_token=" + encodeURIComponent(AUTH_TOKEN); }); // public/javascripts/application.js jQuery.ajaxSetup({ 'beforeSend': function(xhr) {xhr.setRequestHeader("Accept", "text/javascript")} }) jQuery.fn.submitWithAjax = function() { this.change(function() { $.post('select_country', $(this).serialize(), null, "script"); return false; }) return this; }; jQuery.fn.sameAddress = function() { this.click(function() { if(!$(this).attr('checked')) { //Clear ship values? return; } $('input#hidden_sstate').val($('input#hidden_bstate').val()); $("#billing input, #billing select").each(function() { $("#shipping #"+ $(this).attr('id').replace('bill', 'ship')).val($(this).val()); }) update_state('s'); }) } //On page load $(function() { //$("#checkout_presenter_bill_address_country_id").submitWithAjax(); $('#checkout_presenter_same_address').sameAddress(); $('span#bcountry select').change(function() { update_state('b'); }); $('span#scountry select').change(function() { update_state('s'); }); get_states(); $('#validate_billing').click(function() { if(validate_section('billing')) { submit_billing(); }}); $('#validate_shipping').click(function() { if(validate_section('shipping')) { submit_shipping(); }}); $('#select_shipping_method').click(function() { submit_shipping_method(); }); $('#confirm_payment').click(function() { if(validate_section('creditcard')) { confirm_payment(); }}); $('form#checkout_form').submit(function() { return !($('div#confirm_order').hasClass('checkout_disabled')); }); }) //Initial state mapper on page load var state_mapper; var get_states = function() { $.getJSON('/states.js', function(json) { state_mapper = json; $('span#bcountry select').val($('input#hidden_bcountry').val()); update_state('b'); $('span#bstate :only-child').val($('input#hidden_bstate').val()); $('span#scountry select').val($('input#hidden_scountry').val()); update_state('s'); $('span#sstate :only-child').val($('input#hidden_sstate').val()); }); }; // replace the :only child of the parent with the given html, and transfer // {name,id} attributes over, returning the new child var chg_state_input_element = function (parent, html) { var child = parent.find(':only-child'); html.addClass('required') .attr('name', child.attr('name')) .attr('id', child.attr('id')); child.remove(); // better as parent-relative? parent.append(html); return html; }; // TODO: better as sibling dummy state ? // Update the input method for address.state // var update_state = function(region) { var country = $('span#' + region + 'country :only-child').val(); var states = state_mapper[country]; var hidden_element = $('input#hidden_' + region + 'state'); var replacement; if(states) { // recreate state selection list replacement = $(document.createElement('select')); $.each(states, function(id,nm) { var opt = $(document.createElement('option')) .attr('value', id) .html(nm); replacement.append(opt) if (id == hidden_element.val()) { opt.attr('selected', 'true') } // query - should opt.val(...) work too? was used in original // probably will when states are fixed... }); } else { // recreate an input box replacement = $(document.createElement('input')); if (! hidden_element.val().match(/\d+/)) { replacement.val(hidden_element.val()) } } chg_state_input_element($('span#' + region + 'state'), replacement); // callback to update val when form object is changed // This is only needed if we want to preserve state when someone refreshes the checkout page // Or... if someone changes between countries with no given states replacement.change(function() { $('input#hidden_' + region + 'state').val($(this).val()); }); }; var validate_section = function(region) { var validator = $('form#checkout_form').validate(); var valid = true; $('div#' + region + ' input, div#' + region + ' select, div#' + region + ' textarea').each(function() { if(!validator.element(this)) { valid = false; } }); return valid; }; var shift_to_region = function(active) { $('div#flash-errors').remove(); var found = 0; for(var i=0; i<regions.length; i++) { if(!found) { if(active == regions[i]) { $('div#' + regions[i] + ' h2').unbind('click').css('cursor', 'default'); $('div#' + regions[i] + ' div.inner').show('fast'); $('div#' + regions[i]).removeClass('checkout_disabled'); found = 1; } else { $('div#' + regions[i] + ' h2').unbind('click').css('cursor', 'pointer').click(function() {shift_to_region($(this).parent().attr('id'));}); $('div#' + regions[i] + ' div.inner').hide('fast'); } } else { $('div#' + regions[i] + ' h2').unbind('click').css('cursor', 'default'); $('div#' + regions[i] + ' div.inner').hide('fast'); $('div#' + regions[i]).addClass('checkout_disabled'); } } if (active == 'confirm_order') { $("input#final_answer").attr("value", "yes"); } else { // indicates order is ready to be processed (as opposed to simply updated) $("input#final_answer").attr("value", ""); } return; }; var submit_billing = function() { shift_to_region('shipping'); build_address('Billing Address', 'b'); return; }; var build_address = function(title, region) { var address = '<h3>' + title + '</h3>'; address += $('p#' + region + 'fname input').val() + ' ' + $('p#blname input').val() + '<br />'; address += $('p#' + region + 'address input').val() + '<br />'; if($('p#' + region + 'address2').val() != '') { address += $('p#' + region + 'address2').val() + '<br />'; } address += $('p#' + region + 'city input').val() + ', '; if($('span#' + region + 'state input').length > 0) { address += $('span#' + region + 'state input').val(); } else { address += $('span#' + region + 'state :selected').html(); } address += ' ' + $('p#' + region + 'zip input').val() + '<br />'; address += $('p#' + region + 'country :selected').html() + '<br />'; address += $('p#' + region + 'phone input').val(); $('div#' + region + 'display').html(address); return; }; var submit_shipping = function() { $('div#methods :child').remove(); $('div#methods').append($(document.createElement('img')).attr('src', '/images/ajax_loader.gif').attr('id', 'shipping_loader')); // Save what we have so far and get the list of shipping methods via AJAX $.ajax({ type: "POST", url: 'complete', beforeSend : function (xhr) { xhr.setRequestHeader('Accept-Encoding', 'identity'); }, dataType: "json", data: $('#checkout_form').serialize(), success: function(json) { update_shipping_methods(json.available_methods); }, error: function (XMLHttpRequest, textStatus, errorThrown) { // TODO - put some real error handling in here $("#error").html(XMLHttpRequest.responseText); } }); shift_to_region('shipping_method'); build_address('Shipping Address', 's'); return; }; var submit_shipping_method = function() { //TODO: Move to validate_section('shipping_method'), but must debug how to validate radio buttons var valid = false; $('div#methods :child input').each(function() { if($(this).attr('checked')) { valid = true; } }); if(valid) { // Save what we have so far and get the updated order totals via AJAX $.ajax({ type: "POST", url: 'complete', beforeSend : function (xhr) { xhr.setRequestHeader('Accept-Encoding', 'identity'); }, dataType: "json", data: $('#checkout_form').serialize(), success: function(json) { update_confirmation(json.order); }, error: function (XMLHttpRequest, textStatus, errorThrown) { // TODO - put some real error handling in here //$("#error").html(XMLHttpRequest.responseText); } }); shift_to_region('creditcard'); } else { var p = document.createElement('p'); $(p).append($(document.createElement('label')).addClass('error').html('Please select a shipping method').css('width', '300px').css('top', '0px')); $('div#methods').append(p); } }; var update_shipping_methods = function(methods) { $(methods).each( function(i) { $('div$methods img#shipping_loader').remove(); var p = document.createElement('p'); var s = this.name + ' ' + this.rate; $(p).append($(document.createElement('input')) .attr('id', s) .attr('type', 'radio') .attr('name', 'method_id') .attr(1 == $(methods).length ? 'checked' : 'notchecked', 'foo') .val(this.id) ); $(p).append($(document.createElement('label')) .attr('for', s) .html(s) .css('top', '-1px')); $('div#methods').append(p); }); $('div#methods input:first').attr('validate', 'required:true'); return; } var update_confirmation = function(order) { $('span#order_total').html(order.order_total); $('span#ship_amount').html(order.ship_amount); $('span#tax_amount').html(order.tax_amount); $('span#ship_method').html(order.ship_method); } var confirm_payment = function() { shift_to_region('confirm_order'); };
refined the update_state mechanism * the hidden value is only copied to a combo if there's an option which matches in the new list * the hidden value is only copied to a textbox if it isn't ^\d+$ * the hidden value is always set from the combo/textbox after any change I've also reinstated the change callback in update_state to ensure that any changes are pushed to hidden value immediately (is this being over-careful?)
public/javascripts/checkout.js
refined the update_state mechanism
<ide><path>ublic/javascripts/checkout.js <ide> .html(nm); <ide> replacement.append(opt) <ide> if (id == hidden_element.val()) { opt.attr('selected', 'true') } <del> // query - should opt.val(...) work too? was used in original <del> // probably will when states are fixed... <add> // set this directly IFF the old value is still valid <ide> }); <ide> } else { <ide> // recreate an input box <ide> replacement = $(document.createElement('input')); <del> if (! hidden_element.val().match(/\d+/)) { replacement.val(hidden_element.val()) } <add> if (! hidden_element.val().match(/^\d+$/)) { replacement.val(hidden_element.val()) } <ide> } <ide> <ide> chg_state_input_element($('span#' + region + 'state'), replacement); <add> hidden_element.val(replacement.val()); <ide> <ide> // callback to update val when form object is changed <ide> // This is only needed if we want to preserve state when someone refreshes the checkout page
Java
agpl-3.0
2e203de0f4026ec179fd6695d1e198f03670981a
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
bac07080-2e60-11e5-9284-b827eb9e62be
hello.java
babaf628-2e60-11e5-9284-b827eb9e62be
bac07080-2e60-11e5-9284-b827eb9e62be
hello.java
bac07080-2e60-11e5-9284-b827eb9e62be
<ide><path>ello.java <del>babaf628-2e60-11e5-9284-b827eb9e62be <add>bac07080-2e60-11e5-9284-b827eb9e62be
Java
isc
2172dfa1bf84d79af2cf431eebc9709ba03a8a3a
0
Tetr4/Spacecurl
package de.klimek.spacecurl.game.pong; import android.content.res.Resources; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Canvas; import de.klimek.spacecurl.R; /** * Lives */ public class Lives { private static final int RADIUS = 32; private static final int PADDING_TOP = 8; private static final int PADDING_SIDE = 8; private int mLiveCount; private Bitmap mSmileyBitmap; public Lives(int lives, Resources res) { mLiveCount = lives; // mSource.set(0, // 0, // RADIUS * 2, // RADIUS * 2); Bitmap smiley = BitmapFactory.decodeResource(res, R.drawable.smiley_normal); mSmileyBitmap = Bitmap.createScaledBitmap(smiley, RADIUS * 2, RADIUS * 2, true); } public void setLives(int lives) { mLiveCount = lives; } public int getLives() { return mLiveCount; } protected void draw(Canvas canvas) { for (int i = 0; i < mLiveCount; i++) { canvas.drawBitmap(mSmileyBitmap, i * RADIUS * 2 + PADDING_SIDE * (i + 1), PADDING_TOP, null); } } }
SpaceCurl/src/de/klimek/spacecurl/game/pong/Lives.java
package de.klimek.spacecurl.game.pong; import android.content.res.Resources; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Canvas; import de.klimek.spacecurl.R; /** * Lives */ public class Lives { private static final int RADIUS = 32; private static final int PADDING_TOP = 8; private static final int PADDING_SIDE = 8; private int mLiveCount; private Bitmap mSmileyBitmap; public Lives(int lives, Resources res) { mLiveCount = lives; // mSource.set(0, // 0, // RADIUS * 2, // RADIUS * 2); Bitmap smiley = BitmapFactory.decodeResource(res, R.drawable.smiley_normal); mSmileyBitmap = Bitmap.createScaledBitmap(smiley, RADIUS * 2, RADIUS * 2, true); } public void setLives(int lives) { mLiveCount = lives; } public int getLives() { return mLiveCount; } protected void draw(Canvas canvas) { for (int i = 0; i < mLiveCount; i++) { canvas.drawBitmap(mSmileyBitmap, i * RADIUS * 2 + PADDING_SIDE, PADDING_TOP, null); } } }
fixed wrong offset for lives in pong
SpaceCurl/src/de/klimek/spacecurl/game/pong/Lives.java
fixed wrong offset for lives in pong
<ide><path>paceCurl/src/de/klimek/spacecurl/game/pong/Lives.java <ide> <ide> protected void draw(Canvas canvas) { <ide> for (int i = 0; i < mLiveCount; i++) { <del> canvas.drawBitmap(mSmileyBitmap, i * RADIUS * 2 + PADDING_SIDE, PADDING_TOP, <add> canvas.drawBitmap(mSmileyBitmap, i * RADIUS * 2 + PADDING_SIDE * (i + 1), PADDING_TOP, <ide> null); <ide> } <ide> }
Java
mit
927d04fcd07a8589451abfec0efeee2cea8f3d41
0
greboid/DMDirc,ShaneMcC/DMDirc-Client,DMDirc/DMDirc,ShaneMcC/DMDirc-Client,DMDirc/DMDirc,ShaneMcC/DMDirc-Client,DMDirc/DMDirc,csmith/DMDirc,csmith/DMDirc,DMDirc/DMDirc,ShaneMcC/DMDirc-Client,csmith/DMDirc,greboid/DMDirc,greboid/DMDirc,csmith/DMDirc,greboid/DMDirc
/* * Copyright (c) 2006-2010 Chris Smith, Shane Mc Cormack, Gregory Holmes * * 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.dmdirc; import com.dmdirc.actions.ActionManager; import com.dmdirc.actions.CoreActionType; import com.dmdirc.actions.wrappers.AliasWrapper; import com.dmdirc.commandparser.CommandManager; import com.dmdirc.commandparser.CommandType; import com.dmdirc.commandparser.parsers.RawCommandParser; import com.dmdirc.config.ConfigManager; import com.dmdirc.config.Identity; import com.dmdirc.config.IdentityManager; import com.dmdirc.interfaces.AwayStateListener; import com.dmdirc.interfaces.ConfigChangeListener; import com.dmdirc.interfaces.InviteListener; import com.dmdirc.logger.ErrorLevel; import com.dmdirc.logger.Logger; import com.dmdirc.parser.common.ChannelJoinRequest; import com.dmdirc.parser.common.DefaultStringConverter; import com.dmdirc.parser.common.IgnoreList; import com.dmdirc.parser.common.ParserError; import com.dmdirc.parser.interfaces.ChannelInfo; import com.dmdirc.parser.interfaces.ClientInfo; import com.dmdirc.parser.interfaces.Parser; import com.dmdirc.parser.interfaces.SecureParser; import com.dmdirc.parser.interfaces.StringConverter; import com.dmdirc.parser.common.MyInfo; import com.dmdirc.parser.irc.IRCParser; import com.dmdirc.ui.WindowManager; import com.dmdirc.ui.input.TabCompleter; import com.dmdirc.ui.input.TabCompletionType; import com.dmdirc.ui.interfaces.InputWindow; import com.dmdirc.ui.interfaces.ServerWindow; import com.dmdirc.ui.interfaces.Window; import com.dmdirc.ui.messages.Formatter; import java.net.URI; import java.util.ArrayList; import java.util.Hashtable; import java.util.List; import java.util.Map; import java.util.Random; import java.util.Timer; import java.util.TimerTask; import javax.net.ssl.TrustManager; /** * The Server class represents the client's view of a server. It maintains * a list of all channels, queries, etc, and handles parser callbacks pertaining * to the server. * * @author chris */ public class Server extends WritableFrameContainer implements ConfigChangeListener { // <editor-fold defaultstate="collapsed" desc="Properties"> // <editor-fold defaultstate="collapsed" desc="Static"> /** The name of the general domain. */ private static final String DOMAIN_GENERAL = "general".intern(); /** The name of the profile domain. */ private static final String DOMAIN_PROFILE = "profile".intern(); /** The name of the server domain. */ private static final String DOMAIN_SERVER = "server".intern(); // </editor-fold> // <editor-fold defaultstate="collapsed" desc="Instance"> /** Open channels that currently exist on the server. */ private final Map<String, Channel> channels = new Hashtable<String, Channel>(); /** Open query windows on the server. */ private final List<Query> queries = new ArrayList<Query>(); /** The Parser instance handling this server. */ private transient Parser parser; /** The Parser instance that used to be handling this server. */ private transient Parser oldParser; /** * Object used to synchronoise access to parser. This object should be * locked by anything requiring that the parser reference remains the same * for a duration of time, or by anything which is updating the parser * reference. * * If used in conjunction with myStateLock, the parserLock must always be * locked INSIDE the myStateLock to prevent deadlocks. */ private final Object parserLock = new Object(); /** The IRC Parser Thread. */ private transient Thread parserThread; /** The raw frame used for this server instance. */ private Raw raw; /** The ServerWindow corresponding to this server. */ private ServerWindow window; /** The address of the server we're connecting to. */ private URI address; /** The profile we're using. */ private transient Identity profile; /** Object used to synchronise access to myState. */ private final Object myStateLock = new Object(); /** The current state of this server. */ private final ServerStatus myState = new ServerStatus(this, myStateLock); /** The timer we're using to delay reconnects. */ private Timer reconnectTimer; /** The tabcompleter used for this server. */ private final TabCompleter tabCompleter = new TabCompleter(); /** The last activated internal frame for this server. */ private FrameContainer activeFrame = this; /** Our reason for being away, if any. */ private String awayMessage; /** Our event handler. */ private final ServerEventHandler eventHandler = new ServerEventHandler(this); /** A list of outstanding invites. */ private final List<Invite> invites = new ArrayList<Invite>(); /** Our ignore list. */ private final IgnoreList ignoreList = new IgnoreList(); /** Our string convertor. */ private StringConverter converter = new DefaultStringConverter(); // </editor-fold> // </editor-fold> // <editor-fold defaultstate="collapsed" desc="Constructors"> /** * Creates a new server which will connect to the specified URL with * the specified profile. * * @since 0.6.3 * @param uri The address of the server to connect to * @param profile The profile to use */ public Server(final URI uri, final Identity profile) { super("server-disconnected", uri.getHost(), new ConfigManager(uri.getScheme(), "", "", uri.getHost())); this.address = uri; this.profile = profile; window = Main.getUI().getServer(this); ServerManager.getServerManager().registerServer(this); WindowManager.addWindow(window); tabCompleter.addEntries(TabCompletionType.COMMAND, AliasWrapper.getAliasWrapper().getAliases()); tabCompleter.addEntries(TabCompletionType.COMMAND, CommandManager.getCommandNames(CommandType.TYPE_SERVER)); tabCompleter.addEntries(TabCompletionType.COMMAND, CommandManager.getCommandNames(CommandType.TYPE_GLOBAL)); window.getInputHandler().setTabCompleter(tabCompleter); updateIcon(); window.open(); new Timer("Server Who Timer").schedule(new TimerTask() { @Override public void run() { for (Channel channel : channels.values()) { channel.checkWho(); } } }, 0, getConfigManager().getOptionInt(DOMAIN_GENERAL, "whotime")); if (getConfigManager().getOptionBool(DOMAIN_GENERAL, "showrawwindow")) { addRaw(); } getConfigManager().addChangeListener("formatter", "serverName", this); getConfigManager().addChangeListener("formatter", "serverTitle", this); } // </editor-fold> // <editor-fold defaultstate="collapsed" desc="Connection, disconnection & reconnection"> /** * Connects to a new server with the previously supplied address and profile. * * @since 0.6.3m2 */ public void connect() { connect(address, profile); } /** * Connects to a new server with the specified details. * * @param address The address of the server to connect to * @param profile The profile to use * @since 0.6.3 */ @Precondition({ "The current parser is null or not connected", "The specified profile is not null" }) @SuppressWarnings("fallthrough") public void connect(final URI address, final Identity profile) { assert profile != null; synchronized (myStateLock) { switch (myState.getState()) { case RECONNECT_WAIT: reconnectTimer.cancel(); break; case CLOSING: // Ignore the connection attempt return; case CONNECTED: case CONNECTING: disconnect(getConfigManager().getOption(DOMAIN_GENERAL, "quitmessage")); case DISCONNECTING: while (!myState.getState().isDisconnected()) { try { myStateLock.wait(); } catch (InterruptedException ex) { return; } } break; default: // Do nothing break; } synchronized (parserLock) { if (parser != null) { throw new IllegalArgumentException("Connection attempt while parser " + "is still connected.\n\nMy state:" + getState()); } getConfigManager().migrate(address.getScheme(), "", "", address.getHost()); this.address = address; this.profile = profile; updateTitle(); updateIcon(); parser = buildParser(); final URI connectAddress; if (parser != null) { connectAddress = parser.getURI(); } else { connectAddress = address; } if (parser == null) { addLine("serverUnknownProtocol", connectAddress.getScheme()); return; } addLine("serverConnecting", connectAddress.getHost(), connectAddress.getPort()); myState.transition(ServerState.CONNECTING); doCallbacks(); awayMessage = null; removeInvites(); window.setAwayIndicator(false); try { parserThread = new Thread(parser, "IRC Parser thread"); parserThread.start(); } catch (IllegalThreadStateException ex) { Logger.appError(ErrorLevel.FATAL, "Unable to start IRC Parser", ex); } } } ActionManager.processEvent(CoreActionType.SERVER_CONNECTING, null, this); } /** * Reconnects to the IRC server with a specified reason. * * @param reason The quit reason to send */ public void reconnect(final String reason) { synchronized (myStateLock) { if (myState.getState() == ServerState.CLOSING) { return; } disconnect(reason); connect(address, profile); } } /** * Reconnects to the IRC server. */ public void reconnect() { reconnect(getConfigManager().getOption(DOMAIN_GENERAL, "reconnectmessage")); } /** * Disconnects from the server with the default quit message. */ public void disconnect() { disconnect(getConfigManager().getOption(DOMAIN_GENERAL, "quitmessage")); } /** * Disconnects from the server. * * @param reason disconnect reason */ public void disconnect(final String reason) { synchronized (myStateLock) { switch (myState.getState()) { case CLOSING: case DISCONNECTING: case DISCONNECTED: case TRANSIENTLY_DISCONNECTED: return; case RECONNECT_WAIT: reconnectTimer.cancel(); break; default: break; } clearChannels(); synchronized (parserLock) { if (parser == null) { myState.transition(ServerState.DISCONNECTED); } else { myState.transition(ServerState.DISCONNECTING); removeInvites(); updateIcon(); parserThread.interrupt(); parser.disconnect(reason); } } if (getConfigManager().getOptionBool(DOMAIN_GENERAL, "closechannelsonquit")) { closeChannels(); } if (getConfigManager().getOptionBool(DOMAIN_GENERAL, "closequeriesonquit")) { closeQueries(); } } } /** * Schedules a reconnect attempt to be performed after a user-defiend delay. */ @Precondition("The server state is transiently disconnected") private void doDelayedReconnect() { synchronized (myStateLock) { if (myState.getState() != ServerState.TRANSIENTLY_DISCONNECTED) { throw new IllegalStateException("doDelayedReconnect when not " + "transiently disconnected\n\nState: " + myState); } final int delay = Math.max(1000, getConfigManager().getOptionInt(DOMAIN_GENERAL, "reconnectdelay")); handleNotification("connectRetry", getName(), delay / 1000); reconnectTimer = new Timer("Server Reconnect Timer"); reconnectTimer.schedule(new TimerTask() { @Override public void run() { synchronized (myStateLock) { if (myState.getState() == ServerState.RECONNECT_WAIT) { myState.transition(ServerState.TRANSIENTLY_DISCONNECTED); reconnect(); } } } }, delay); myState.transition(ServerState.RECONNECT_WAIT); updateIcon(); } } // </editor-fold> // <editor-fold defaultstate="collapsed" desc="Child windows"> /** * Determines whether the server knows of the specified channel. * * @param channel The channel to be checked * @return True iff the channel is known, false otherwise */ public boolean hasChannel(final String channel) { return channels.containsKey(converter.toLowerCase(channel)); } /** * Retrieves the specified channel belonging to this server. * * @param channel The channel to be retrieved * @return The appropriate channel object */ public Channel getChannel(final String channel) { return channels.get(converter.toLowerCase(channel)); } /** * Retrieves a list of channel names belonging to this server. * * @return list of channel names belonging to this server */ public List<String> getChannels() { final ArrayList<String> res = new ArrayList<String>(); for (String channel : channels.keySet()) { res.add(channel); } return res; } /** * Determines whether the server knows of the specified query. * * @param host The host of the query to look for * @return True iff the query is known, false otherwise */ public boolean hasQuery(final String host) { if (parser == null) { return false; } final String nick = parser.parseHostmask(host)[0]; for (Query query : queries) { if (converter.equalsIgnoreCase(parser.parseHostmask(query.getHost())[0], nick)) { return true; } } return false; } /** * Retrieves the specified query belonging to this server. * * @param host The host of the query to look for * @return The appropriate query object */ public Query getQuery(final String host) { if (parser == null) { throw new IllegalArgumentException("No such query: " + host); } final String nick = parser.parseHostmask(host)[0]; for (Query query : queries) { if (converter.equalsIgnoreCase(parser.parseHostmask(query.getHost())[0], nick)) { return query; } } throw new IllegalArgumentException("No such query: " + host); } /** * Retrieves a list of queries belonging to this server. * * @return list of queries belonging to this server */ public List<Query> getQueries() { return new ArrayList<Query>(queries); } /** * Adds a raw window to this server. */ public void addRaw() { if (raw == null) { raw = new Raw(this, new RawCommandParser(this)); synchronized (parserLock) { if (parser != null) { raw.registerCallbacks(); } } } else { raw.activateFrame(); } } /** * Retrieves the raw window associated with this server. * * @return The raw window associated with this server. */ public Raw getRaw() { return raw; } /** * Removes our reference to the raw object (presumably after it has been * closed). */ public void delRaw() { raw = null; //NOPMD } /** * Removes a specific channel and window from this server. * * @param chan channel to remove */ public void delChannel(final String chan) { tabCompleter.removeEntry(TabCompletionType.CHANNEL, chan); channels.remove(converter.toLowerCase(chan)); } /** * Adds a specific channel and window to this server. * * @param chan channel to add * @return The channel that was added (may be null if closing) */ public Channel addChannel(final ChannelInfo chan) { synchronized (myStateLock) { if (myState.getState() == ServerState.CLOSING) { // Can't join channels while the server is closing return null; } } if (hasChannel(chan.getName())) { getChannel(chan.getName()).setChannelInfo(chan); getChannel(chan.getName()).selfJoin(); } else { final Channel newChan = new Channel(this, chan); tabCompleter.addEntry(TabCompletionType.CHANNEL, chan.getName()); channels.put(converter.toLowerCase(chan.getName()), newChan); newChan.show(); } return getChannel(chan.getName()); } /** * Adds a query to this server. * * @param host host of the remote client being queried * @return The query that was added (may be null if closing) */ public Query addQuery(final String host) { synchronized (myStateLock) { if (myState.getState() == ServerState.CLOSING) { // Can't open queries while the server is closing return null; } } if (!hasQuery(host)) { final Query newQuery = new Query(this, host); tabCompleter.addEntry(TabCompletionType.QUERY_NICK, parser.parseHostmask(host)[0]); queries.add(newQuery); } return getQuery(host); } /** * Deletes a query from this server. * * @param query The query that should be removed. */ public void delQuery(final Query query) { tabCompleter.removeEntry(TabCompletionType.QUERY_NICK, query.getNickname()); queries.remove(query); } /** {@inheritDoc} */ @Override public boolean ownsFrame(final Window target) { // Check if it's our server frame if (window != null && window.equals(target)) { return true; } // Check if it's the raw frame if (raw != null && raw.ownsFrame(target)) { return true; } // Check if it's a channel frame for (Channel channel : channels.values()) { if (channel.ownsFrame(target)) { return true; } } // Check if it's a query frame for (Query query : queries) { if (query.ownsFrame(target)) { return true; } } return false; } /** * Sets the specified frame as the most-recently activated. * * @param source The frame that was activated */ public void setActiveFrame(final FrameContainer source) { activeFrame = source; } /** * Retrieves a list of all children of this server instance. * * @return A list of this server's children */ public List<WritableFrameContainer> getChildren() { final List<WritableFrameContainer> res = new ArrayList<WritableFrameContainer>(); if (raw != null) { res.add(raw); } res.addAll(channels.values()); res.addAll(queries); return res; } /** * Closes all open channel windows associated with this server. */ private void closeChannels() { for (Channel channel : new ArrayList<Channel>(channels.values())) { channel.close(); } } /** * Clears the nicklist of all open channels. */ private void clearChannels() { for (Channel channel : channels.values()) { channel.resetWindow(); } } /** * Closes all open query windows associated with this server. */ private void closeQueries() { for (Query query : new ArrayList<Query>(queries)) { query.close(); } } // </editor-fold> // <editor-fold defaultstate="collapsed" desc="Miscellaneous methods"> /** * Builds an appropriately configured {@link IRCParser} for this server. * * @return A configured IRC parser. */ private Parser buildParser() { final CertificateManager certManager = new CertificateManager(address.getHost(), getConfigManager()); final MyInfo myInfo = buildMyInfo(); final Parser myParser = new ParserFactory().getParser(myInfo, address); if (myParser instanceof SecureParser) { final SecureParser secureParser = (SecureParser) myParser; secureParser.setTrustManagers(new TrustManager[]{certManager}); secureParser.setKeyManagers(certManager.getKeyManager()); } if (myParser != null) { myParser.setIgnoreList(ignoreList); myParser.setPingTimerInterval(getConfigManager().getOptionInt(DOMAIN_SERVER, "pingtimer")); myParser.setPingTimerFraction((int) (getConfigManager().getOptionInt(DOMAIN_SERVER, "pingfrequency") / myParser.getPingTimerInterval())); if (getConfigManager().hasOptionString(DOMAIN_GENERAL, "bindip")) { myParser.setBindIP(getConfigManager().getOption(DOMAIN_GENERAL, "bindip")); } } return myParser; } /** * Compare the given URI to the URI we are currently using to see if they * would both result in the server connecting to the same place, even if the * URIs do not match exactly. * * @param uri URI to compare with the Servers own URI. * @return True if the Given URI is the "same" as the one we are using. * @since 0.6.3 */ public boolean compareURI(final URI uri) { if (parser != null) { return parser.compareURI(uri); } if (oldParser != null) { return oldParser.compareURI(uri); } return false; } /** * Retrieves the MyInfo object used for the IRC Parser. * * @return The MyInfo object for our profile */ @Precondition({ "The current profile is not null", "The current profile specifies at least one nickname" }) private MyInfo buildMyInfo() { Logger.assertTrue(profile != null); Logger.assertTrue(!profile.getOptionList(DOMAIN_PROFILE, "nicknames").isEmpty()); final MyInfo myInfo = new MyInfo(); myInfo.setNickname(profile.getOptionList(DOMAIN_PROFILE, "nicknames").get(0)); myInfo.setRealname(profile.getOption(DOMAIN_PROFILE, "realname")); if (profile.hasOptionString(DOMAIN_PROFILE, "ident")) { myInfo.setUsername(profile.getOption(DOMAIN_PROFILE, "ident")); } return myInfo; } /** * Updates this server's icon. */ private void updateIcon() { final String icon = myState.getState() == ServerState.CONNECTED ? address.getScheme().endsWith("s") ? "secure-server" : "server" : "server-disconnected"; setIcon(icon); } /** * Registers callbacks. */ private void doCallbacks() { if (raw != null) { raw.registerCallbacks(); } eventHandler.registerCallbacks(); for (Query query : queries) { query.reregister(); } } /** * Joins the specified channel with the specified key. * * @since 0.6.3m1 * @param channel The channel to be joined * @param key The key for the channel * @deprecated Use {@link #join(com.dmdirc.parser.common.ChannelJoinRequest[])} */ @Deprecated public void join(final String channel, final String key) { join(new ChannelJoinRequest(channel, key)); } /** * Attempts to join the specified channels. If channels with the same name * already exist, they are (re)joined and their windows activated. * * @param requests The channel join requests to process * @since 0.6.4 */ public void join(final ChannelJoinRequest ... requests) { synchronized (myStateLock) { if (myState.getState() == ServerState.CONNECTED) { final List<ChannelJoinRequest> pending = new ArrayList<ChannelJoinRequest>(); for (ChannelJoinRequest request : requests) { removeInvites(request.getName()); final String name; if (parser.isValidChannelName(request.getName())) { name = request.getName(); } else { name = parser.getChannelPrefixes().substring(0, 1) + request.getName(); } if (hasChannel(name)) { getChannel(name).activateFrame(); } if (!hasChannel(name) || !getChannel(name).isOnChannel()) { pending.add(request); } } parser.joinChannels(pending.toArray(new ChannelJoinRequest[0])); } else { // TODO: Need to pass key // TODO (uris): address.getChannels().add(channel); } } } /** * Joins the specified channel, or adds it to the auto-join list if the * server is not connected. * * @param channel The channel to be joined * @deprecated Use {@link #join(com.dmdirc.parser.common.ChannelJoinRequest[])} */ @Deprecated public void join(final String channel) { join(new ChannelJoinRequest(channel)); } /** {@inheritDoc} */ @Override public void sendLine(final String line) { synchronized (myStateLock) { synchronized (parserLock) { if (parser != null && !line.isEmpty() && myState.getState() == ServerState.CONNECTED) { parser.sendRawMessage(window.getTranscoder().encode(line)); } } } } /** {@inheritDoc} */ @Override public int getMaxLineLength() { synchronized (parserLock) { return parser == null ? -1 : parser.getMaxLength(); } } /** * Retrieves the parser used for this connection. * * @return IRCParser this connection's parser */ public Parser getParser() { return parser; } /** * Retrieves the profile that's in use for this server. * * @return The profile in use by this server */ public Identity getProfile() { return profile; } /** * Retrieves the possible channel prefixes in use on this server. * * @return This server's possible channel prefixes */ public String getChannelPrefixes() { synchronized (parserLock) { return parser == null ? "#&" : parser.getChannelPrefixes(); } } /** * Retrieves the name of this server's network. The network name is * determined using the following rules: * * 1. If the server includes its network name in the 005 information, we * use that * 2. If the server's name ends in biz, com, info, net or org, we use the * second level domain (e.g., foo.com) * 3. If the server's name contains more than two dots, we drop everything * up to and including the first part, and use the remainder * 4. In all other cases, we use the full server name * * @return The name of this server's network */ public String getNetwork() { synchronized (parserLock) { if (parser == null) { throw new IllegalStateException("getNetwork called when " + "parser is null (state: " + getState() + ")"); } else if (parser.getNetworkName().isEmpty()) { return getNetworkFromServerName(parser.getServerName()); } else { return parser.getNetworkName(); } } } /** * Determines whether this server is currently connected to the specified * network. * * @param target The network to check for * @return True if this server is connected to the network, false otherwise * @since 0.6.3m1rc3 */ public boolean isNetwork(String target) { synchronized (myStateLock) { synchronized (parserLock) { if (parser == null) { return false; } else { return getNetwork().equalsIgnoreCase(target); } } } } /** * Calculates a network name from the specified server name. This method * implements parts 2-4 of the procedure documented at getNetwork(). * * @param serverName The server name to parse * @return A network name for the specified server */ protected static String getNetworkFromServerName(final String serverName) { final String[] parts = serverName.split("\\."); final String[] tlds = {"biz", "com", "info", "net", "org"}; boolean isTLD = false; for (String tld : tlds) { if (serverName.endsWith("." + tld)) { isTLD = true; } } if (isTLD && parts.length > 2) { return parts[parts.length - 2] + "." + parts[parts.length - 1]; } else if (parts.length > 2) { final StringBuilder network = new StringBuilder(); for (int i = 1; i < parts.length; i++) { if (network.length() > 0) { network.append('.'); } network.append(parts[i]); } return network.toString(); } else { return serverName; } } /** * Retrieves the name of this server's IRCd. * * @return The name of this server's IRCd */ public String getIrcd() { return parser.getServerSoftwareType(); } /** * Retrieves the protocol used by this server. * * @return This server's protocol * @since 0.6.3 */ public String getProtocol() { return address.getScheme(); } /** * Returns the current away status. * * @return True if the client is marked as away, false otherwise */ public boolean isAway() { return awayMessage != null; } /** * Gets the current away message. * * @return Null if the client isn't away, or a textual away message if it is */ public String getAwayMessage() { return awayMessage; } /** * Returns the tab completer for this connection. * * @return The tab completer for this server */ public TabCompleter getTabCompleter() { return tabCompleter; } /** {@inheritDoc} */ @Override public InputWindow getFrame() { return window; } /** * Retrieves the current state for this server. * * @return This server's state */ public ServerState getState() { return myState.getState(); } /** * Retrieves the status object for this server. Effecting state transitions * on the object returned by this method will almost certainly cause * problems. * * @since 0.6.3m1 * @return This server's status object. */ public ServerStatus getStatus() { return myState; } /** {@inheritDoc} */ @Override public void windowClosing() { synchronized (myStateLock) { // 1: Make the window non-visible window.setVisible(false); // 2: Remove any callbacks or listeners eventHandler.unregisterCallbacks(); // 3: Trigger any actions neccessary disconnect(); myState.transition(ServerState.CLOSING); } closeChannels(); closeQueries(); removeInvites(); if (raw != null) { raw.close(); } // 4: Trigger action for the window closing // 5: Inform any parents that the window is closing ServerManager.getServerManager().unregisterServer(this); // 6: Remove the window from the window manager WindowManager.removeWindow(window); } /** {@inheritDoc} */ @Override public void windowClosed() { // 7: Remove any references to the window and parents window = null; //NOPMD oldParser = null; //NOPMD parser = null; //NOPMD } /** * Passes the arguments to the most recently activated frame for this * server. If the frame isn't know, or isn't visible, use this frame * instead. * * @param messageType The type of message to send * @param args The arguments for the message */ public void addLineToActive(final String messageType, final Object... args) { if (activeFrame == null || !activeFrame.getFrame().isVisible()) { activeFrame = this; } activeFrame.getFrame().addLine(messageType, args); } /** * Passes the arguments to all frames for this server. * * @param messageType The type of message to send * @param args The arguments of the message */ public void addLineToAll(final String messageType, final Object... args) { for (Channel channel : channels.values()) { channel.getFrame().addLine(messageType, args); } for (Query query : queries) { query.getFrame().addLine(messageType, args); } addLine(messageType, args); } /** * Replies to an incoming CTCP message. * * @param source The source of the message * @param type The CTCP type * @param args The CTCP arguments */ public void sendCTCPReply(final String source, final String type, final String args) { if (getConfigManager().getOptionBool(DOMAIN_GENERAL, "sendctcpreplies")) { if (type.equalsIgnoreCase("VERSION")) { parser.sendCTCPReply(source, "VERSION", "DMDirc " + getConfigManager().getOption("version", "version") + " - http://www.dmdirc.com/"); } else if (type.equalsIgnoreCase("PING")) { parser.sendCTCPReply(source, "PING", args); } else if (type.equalsIgnoreCase("CLIENTINFO")) { parser.sendCTCPReply(source, "CLIENTINFO", "VERSION PING CLIENTINFO"); } } } /** * Determines if the specified channel name is valid. A channel name is * valid if we already have an existing Channel with the same name, or * we have a valid parser instance and the parser says it's valid. * * @param channelName The name of the channel to test * @return True if the channel name is valid, false otherwise */ public boolean isValidChannelName(final String channelName) { synchronized (parserLock) { return hasChannel(channelName) || (parser != null && parser.isValidChannelName(channelName)); } } /** * Returns the server instance associated with this frame. * * @return the associated server connection */ @Override public Server getServer() { return this; } /** {@inheritDoc} */ @Override protected boolean processNotificationArg(final Object arg, final List<Object> args) { if (arg instanceof ClientInfo) { final ClientInfo clientInfo = (ClientInfo) arg; args.add(clientInfo.getNickname()); args.add(clientInfo.getUsername()); args.add(clientInfo.getHostname()); return true; } else { return super.processNotificationArg(arg, args); } } /** * Updates the name and title of this window. */ public void updateTitle() { synchronized (myStateLock) { if (myState.getState() == ServerState.CLOSING) { return; } synchronized (parserLock) { final Object[] arguments = new Object[]{ address.getHost(), parser == null ? "Unknown" : parser.getServerName(), address.getPort(), parser == null ? "Unknown" : getNetwork(), parser == null ? "Unknown" : parser.getLocalClient().getNickname() }; setName(Formatter.formatMessage(getConfigManager(), "serverName", arguments)); window.setTitle(Formatter.formatMessage(getConfigManager(), "serverTitle", arguments)); } } } /** {@inheritDoc} */ @Override public void configChanged(final String domain, final String key) { if ("formatter".equals(domain)) { updateTitle(); } } // </editor-fold> // <editor-fold defaultstate="collapsed" desc="Parser callbacks"> /** * Called when the server says that the nickname we're trying to use is * already in use. * * @param nickname The nickname that we were trying to use */ public void onNickInUse(final String nickname) { final String lastNick = parser.getLocalClient().getNickname(); // If our last nick is still valid, ignore the in use message if (!converter.equalsIgnoreCase(lastNick, nickname)) { return; } String newNick = lastNick + new Random().nextInt(10); final List<String> alts = profile.getOptionList(DOMAIN_PROFILE, "nicknames"); int offset = 0; // Loop so we can check case sensitivity for (String alt : alts) { offset++; if (converter.equalsIgnoreCase(alt, lastNick)) { break; } } if (offset < alts.size() && !alts.get(offset).isEmpty()) { newNick = alts.get(offset); } parser.getLocalClient().setNickname(newNick); } /** * Called when the server sends a numeric event. * * @param numeric The numeric code for the event * @param tokens The (tokenised) arguments of the event */ public void onNumeric(final int numeric, final String[] tokens) { String snumeric = String.valueOf(numeric); if (numeric < 10) { snumeric = "00" + snumeric; } else if (numeric < 100) { snumeric = "0" + snumeric; } final String sansIrcd = "numeric_" + snumeric; StringBuffer target = new StringBuffer(""); if (getConfigManager().hasOptionString("formatter", sansIrcd)) { target = new StringBuffer(sansIrcd); } else if (getConfigManager().hasOptionString("formatter", "numeric_unknown")) { target = new StringBuffer("numeric_unknown"); } ActionManager.processEvent(CoreActionType.SERVER_NUMERIC, target, this, Integer.valueOf(numeric), tokens); handleNotification(target.toString(), (Object[]) tokens); } /** * Called when the socket has been closed. */ public void onSocketClosed() { if (Thread.holdsLock(myState)) { new Thread(new Runnable() { /** {@inheritDoc} */ @Override public void run() { onSocketClosed(); } }, "Socket closed deferred thread").start(); return; } handleNotification("socketClosed", getName()); ActionManager.processEvent(CoreActionType.SERVER_DISCONNECTED, null, this); eventHandler.unregisterCallbacks(); synchronized (myStateLock) { if (myState.getState() == ServerState.CLOSING || myState.getState() == ServerState.DISCONNECTED) { // This has been triggered via .disconect() return; } if (myState.getState() == ServerState.DISCONNECTING) { myState.transition(ServerState.DISCONNECTED); } else { myState.transition(ServerState.TRANSIENTLY_DISCONNECTED); } clearChannels(); synchronized (parserLock) { oldParser = parser; parser = null; } updateIcon(); if (getConfigManager().getOptionBool(DOMAIN_GENERAL, "closechannelsondisconnect")) { closeChannels(); } if (getConfigManager().getOptionBool(DOMAIN_GENERAL, "closequeriesondisconnect")) { closeQueries(); } removeInvites(); updateAwayState(null); if (getConfigManager().getOptionBool(DOMAIN_GENERAL, "reconnectondisconnect") && myState.getState() == ServerState.TRANSIENTLY_DISCONNECTED) { doDelayedReconnect(); } } } /** * Called when an error was encountered while connecting. * * @param errorInfo The parser's error information */ @Precondition("The current server state is CONNECTING") public void onConnectError(final ParserError errorInfo) { synchronized (myStateLock) { if (myState.getState() == ServerState.CLOSING || myState.getState() == ServerState.DISCONNECTING) { // Do nothing return; } else if (myState.getState() != ServerState.CONNECTING) { // Shouldn't happen throw new IllegalStateException("Connect error when not " + "connecting\n\n" + getStatus().getTransitionHistory()); } myState.transition(ServerState.TRANSIENTLY_DISCONNECTED); synchronized (parserLock) { oldParser = parser; parser = null; } updateIcon(); String description; if (errorInfo.getException() == null) { description = errorInfo.getData(); } else { final Exception exception = errorInfo.getException(); if (exception instanceof java.net.UnknownHostException) { description = "Unknown host (unable to resolve)"; } else if (exception instanceof java.net.NoRouteToHostException) { description = "No route to host"; } else if (exception instanceof java.net.SocketTimeoutException) { description = "Connection attempt timed out"; } else if (exception instanceof java.net.SocketException || exception instanceof javax.net.ssl.SSLException) { description = exception.getMessage(); } else { Logger.appError(ErrorLevel.LOW, "Unknown socket error", new IllegalArgumentException(exception)); description = "Unknown error: " + exception.getMessage(); } } ActionManager.processEvent(CoreActionType.SERVER_CONNECTERROR, null, this, description); handleNotification("connectError", getName(), description); if (getConfigManager().getOptionBool(DOMAIN_GENERAL, "reconnectonconnectfailure")) { doDelayedReconnect(); } } } /** * Called when we fail to receive a ping reply within a set period of time. */ public void onPingFailed() { Main.getUI().getStatusBar().setMessage("No ping reply from " + getName() + " for over " + ((int) (Math.floor(parser.getPingTime() / 1000.0))) + " seconds.", null, 10); ActionManager.processEvent(CoreActionType.SERVER_NOPING, null, this, Long.valueOf(parser.getPingTime())); if (parser.getPingTime() >= getConfigManager().getOptionInt(DOMAIN_SERVER, "pingtimeout")) { handleNotification("stonedServer", getName()); reconnect(); } } /** * Called after the parser receives the 005 headers from the server. */ @Precondition("State is CONNECTING") public void onPost005() { synchronized (myStateLock) { if (myState.getState() != ServerState.CONNECTING) { // Shouldn't happen throw new IllegalStateException("Received onPost005 while not " + "connecting\n\n" + myState.getTransitionHistory()); } if (myState.getState() != ServerState.CONNECTING) { // We've transitioned while waiting for the lock. Just abort. return; } myState.transition(ServerState.CONNECTED); getConfigManager().migrate(address.getScheme(), parser.getServerSoftwareType(), getNetwork(), parser.getServerName()); updateIcon(); updateTitle(); updateIgnoreList(); converter = parser.getStringConverter(); final List<ChannelJoinRequest> requests = new ArrayList<ChannelJoinRequest>(); if (getConfigManager().getOptionBool(DOMAIN_GENERAL, "rejoinchannels")) { for (Channel chan : channels.values()) { requests.add(new ChannelJoinRequest(chan.getName())); } } join(requests.toArray(new ChannelJoinRequest[0])); checkModeAliases(); } ActionManager.processEvent(CoreActionType.SERVER_CONNECTED, null, this); } /** * Checks that we have the neccessary mode aliases for this server. */ private void checkModeAliases() { // Check we have mode aliases final String modes = parser.getBooleanChannelModes() + parser.getListChannelModes() + parser.getParameterChannelModes() + parser.getDoubleParameterChannelModes(); final String umodes = parser.getUserModes(); final StringBuffer missingModes = new StringBuffer(); final StringBuffer missingUmodes = new StringBuffer(); for (char mode : modes.toCharArray()) { if (!getConfigManager().hasOptionString(DOMAIN_SERVER, "mode" + mode)) { missingModes.append(mode); } } for (char mode : umodes.toCharArray()) { if (!getConfigManager().hasOptionString(DOMAIN_SERVER, "umode" + mode)) { missingUmodes.append(mode); } } if (missingModes.length() + missingUmodes.length() > 0) { final StringBuffer missing = new StringBuffer("Missing mode aliases: "); if (missingModes.length() > 0) { missing.append("channel: +"); missing.append(missingModes); } if (missingUmodes.length() > 0) { if (missingModes.length() > 0) { missing.append(' '); } missing.append("user: +"); missing.append(missingUmodes); } Logger.appError(ErrorLevel.LOW, missing.toString() + " [" + parser.getServerSoftwareType() + "]", new Exception(missing.toString() + "\n" // NOPMD + "Network: " + getNetwork() + "\n" + "IRCd: " + parser.getServerSoftware() + " (" + parser.getServerSoftwareType() + ")\n" + "Mode alias version: " + getConfigManager().getOption("identity", "modealiasversion") + "\n\n")); } } // </editor-fold> // <editor-fold defaultstate="collapsed" desc="Ignore lists"> /** * Retrieves this server's ignore list. * * @return This server's ignore list */ public IgnoreList getIgnoreList() { return ignoreList; } /** * Updates this server's ignore list to use the entries stored in the * config manager. */ public void updateIgnoreList() { ignoreList.clear(); ignoreList.addAll(getConfigManager().getOptionList("network", "ignorelist")); } /** * Saves the contents of our ignore list to the network identity. */ public void saveIgnoreList() { getNetworkIdentity().setOption("network", "ignorelist", ignoreList.getRegexList()); } // </editor-fold> // <editor-fold defaultstate="collapsed" desc="Identity handling"> /** * Retrieves the identity for this server. * * @return This server's identity */ public Identity getServerIdentity() { return IdentityManager.getServerConfig(getName()); } /** * Retrieves the identity for this server's network. * * @return This server's network identity */ public Identity getNetworkIdentity() { return IdentityManager.getNetworkConfig(getNetwork()); } // </editor-fold> // <editor-fold defaultstate="collapsed" desc="Invite handling"> /** * Adds an invite listener to this server. * * @param listener The listener to be added */ public void addInviteListener(final InviteListener listener) { synchronized (listeners) { listeners.add(InviteListener.class, listener); } } /** * Removes an invite listener from this server. * * @param listener The listener to be removed */ public void removeInviteListener(final InviteListener listener) { synchronized (listeners) { listeners.remove(InviteListener.class, listener); } } /** * Adds an invite to this server, and fires the appropriate listeners. * * @param invite The invite to be added */ public void addInvite(final Invite invite) { synchronized (invites) { for (Invite oldInvite : new ArrayList<Invite>(invites)) { if (oldInvite.getChannel().equals(invite.getChannel())) { removeInvite(oldInvite); } } invites.add(invite); synchronized (listeners) { for (InviteListener listener : listeners.get(InviteListener.class)) { listener.inviteReceived(this, invite); } } } } /** * Removes all invites for the specified channel. * * @param channel The channel to remove invites for */ public void removeInvites(final String channel) { for (Invite invite : new ArrayList<Invite>(invites)) { if (invite.getChannel().equals(channel)) { removeInvite(invite); } } } /** * Removes all invites for all channels. */ private void removeInvites() { for (Invite invite : new ArrayList<Invite>(invites)) { removeInvite(invite); } } /** * Removes an invite from this server, and fires the appropriate listeners. * * @param invite The invite to be removed */ public void removeInvite(final Invite invite) { synchronized (invites) { invites.remove(invite); synchronized (listeners) { for (InviteListener listener : listeners.get(InviteListener.class)) { listener.inviteExpired(this, invite); } } } } /** * Retusnt the list of invites for this server. * * @return Invite list */ public List<Invite> getInvites() { return invites; } // </editor-fold> // <editor-fold defaultstate="collapsed" desc="Away state handling"> /** * Adds an away state lisener to this server. * * @param listener The listener to be added */ public void addAwayStateListener(final AwayStateListener listener) { synchronized (listeners) { listeners.add(AwayStateListener.class, listener); } } /** * Removes an away state lisener from this server. * * @param listener The listener to be removed */ public void removeAwayStateListener(final AwayStateListener listener) { synchronized (listeners) { listeners.remove(AwayStateListener.class, listener); } } /** * Updates our away state and fires the relevant listeners. * * @param message The away message to use, or null if we're not away. */ public void updateAwayState(final String message) { if ((awayMessage != null && awayMessage.equals(message)) || (awayMessage == null && message == null)) { return; } awayMessage = message; new Thread(new Runnable() { /** {@inheritDoc} */ @Override public void run() { synchronized (listeners) { if (message == null) { for (AwayStateListener listener : listeners.get(AwayStateListener.class)) { listener.onBack(); } } else { for (AwayStateListener listener : listeners.get(AwayStateListener.class)) { listener.onAway(message); } } } } }, "Away state listener runner").start(); } // </editor-fold> }
src/com/dmdirc/Server.java
/* * Copyright (c) 2006-2010 Chris Smith, Shane Mc Cormack, Gregory Holmes * * 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.dmdirc; import com.dmdirc.actions.ActionManager; import com.dmdirc.actions.CoreActionType; import com.dmdirc.actions.wrappers.AliasWrapper; import com.dmdirc.commandparser.CommandManager; import com.dmdirc.commandparser.CommandType; import com.dmdirc.commandparser.parsers.RawCommandParser; import com.dmdirc.config.ConfigManager; import com.dmdirc.config.Identity; import com.dmdirc.config.IdentityManager; import com.dmdirc.interfaces.AwayStateListener; import com.dmdirc.interfaces.ConfigChangeListener; import com.dmdirc.interfaces.InviteListener; import com.dmdirc.logger.ErrorLevel; import com.dmdirc.logger.Logger; import com.dmdirc.parser.common.ChannelJoinRequest; import com.dmdirc.parser.common.DefaultStringConverter; import com.dmdirc.parser.common.IgnoreList; import com.dmdirc.parser.common.ParserError; import com.dmdirc.parser.interfaces.ChannelInfo; import com.dmdirc.parser.interfaces.ClientInfo; import com.dmdirc.parser.interfaces.Parser; import com.dmdirc.parser.interfaces.SecureParser; import com.dmdirc.parser.interfaces.StringConverter; import com.dmdirc.parser.common.MyInfo; import com.dmdirc.parser.irc.IRCParser; import com.dmdirc.ui.WindowManager; import com.dmdirc.ui.input.TabCompleter; import com.dmdirc.ui.input.TabCompletionType; import com.dmdirc.ui.interfaces.InputWindow; import com.dmdirc.ui.interfaces.ServerWindow; import com.dmdirc.ui.interfaces.Window; import com.dmdirc.ui.messages.Formatter; import java.net.URI; import java.util.ArrayList; import java.util.Hashtable; import java.util.List; import java.util.Map; import java.util.Random; import java.util.Timer; import java.util.TimerTask; import javax.net.ssl.TrustManager; /** * The Server class represents the client's view of a server. It maintains * a list of all channels, queries, etc, and handles parser callbacks pertaining * to the server. * * @author chris */ public class Server extends WritableFrameContainer implements ConfigChangeListener { // <editor-fold defaultstate="collapsed" desc="Properties"> // <editor-fold defaultstate="collapsed" desc="Static"> /** The name of the general domain. */ private static final String DOMAIN_GENERAL = "general".intern(); /** The name of the profile domain. */ private static final String DOMAIN_PROFILE = "profile".intern(); /** The name of the server domain. */ private static final String DOMAIN_SERVER = "server".intern(); // </editor-fold> // <editor-fold defaultstate="collapsed" desc="Instance"> /** Open channels that currently exist on the server. */ private final Map<String, Channel> channels = new Hashtable<String, Channel>(); /** Open query windows on the server. */ private final List<Query> queries = new ArrayList<Query>(); /** The Parser instance handling this server. */ private transient Parser parser; /** The Parser instance that used to be handling this server. */ private transient Parser oldParser; /** * Object used to synchronoise access to parser. This object should be * locked by anything requiring that the parser reference remains the same * for a duration of time, or by anything which is updating the parser * reference. * * If used in conjunction with myStateLock, the parserLock must always be * locked INSIDE the myStateLock to prevent deadlocks. */ private final Object parserLock = new Object(); /** The IRC Parser Thread. */ private transient Thread parserThread; /** The raw frame used for this server instance. */ private Raw raw; /** The ServerWindow corresponding to this server. */ private ServerWindow window; /** The address of the server we're connecting to. */ private URI address; /** The profile we're using. */ private transient Identity profile; /** Object used to synchronise access to myState. */ private final Object myStateLock = new Object(); /** The current state of this server. */ private final ServerStatus myState = new ServerStatus(this, myStateLock); /** The timer we're using to delay reconnects. */ private Timer reconnectTimer; /** The tabcompleter used for this server. */ private final TabCompleter tabCompleter = new TabCompleter(); /** The last activated internal frame for this server. */ private FrameContainer activeFrame = this; /** Our reason for being away, if any. */ private String awayMessage; /** Our event handler. */ private final ServerEventHandler eventHandler = new ServerEventHandler(this); /** A list of outstanding invites. */ private final List<Invite> invites = new ArrayList<Invite>(); /** Our ignore list. */ private final IgnoreList ignoreList = new IgnoreList(); /** Our string convertor. */ private StringConverter converter = new DefaultStringConverter(); // </editor-fold> // </editor-fold> // <editor-fold defaultstate="collapsed" desc="Constructors"> /** * Creates a new server which will connect to the specified URL with * the specified profile. * * @since 0.6.3 * @param uri The address of the server to connect to * @param profile The profile to use */ public Server(final URI uri, final Identity profile) { super("server-disconnected", uri.getHost(), new ConfigManager(uri.getScheme(), "", "", uri.getHost())); this.address = uri; this.profile = profile; window = Main.getUI().getServer(this); ServerManager.getServerManager().registerServer(this); WindowManager.addWindow(window); tabCompleter.addEntries(TabCompletionType.COMMAND, AliasWrapper.getAliasWrapper().getAliases()); tabCompleter.addEntries(TabCompletionType.COMMAND, CommandManager.getCommandNames(CommandType.TYPE_SERVER)); tabCompleter.addEntries(TabCompletionType.COMMAND, CommandManager.getCommandNames(CommandType.TYPE_GLOBAL)); window.getInputHandler().setTabCompleter(tabCompleter); updateIcon(); window.open(); new Timer("Server Who Timer").schedule(new TimerTask() { @Override public void run() { for (Channel channel : channels.values()) { channel.checkWho(); } } }, 0, getConfigManager().getOptionInt(DOMAIN_GENERAL, "whotime")); if (getConfigManager().getOptionBool(DOMAIN_GENERAL, "showrawwindow")) { addRaw(); } getConfigManager().addChangeListener("formatter", "serverName", this); getConfigManager().addChangeListener("formatter", "serverTitle", this); } // </editor-fold> // <editor-fold defaultstate="collapsed" desc="Connection, disconnection & reconnection"> /** * Connects to a new server with the previously supplied address and profile. * * @since 0.6.3m2 */ public void connect() { connect(address, profile); } /** * Connects to a new server with the specified details. * * @param address The address of the server to connect to * @param profile The profile to use * @since 0.6.3 */ @Precondition({ "The current parser is null or not connected", "The specified profile is not null" }) @SuppressWarnings("fallthrough") public void connect(final URI address, final Identity profile) { assert profile != null; synchronized (myStateLock) { switch (myState.getState()) { case RECONNECT_WAIT: reconnectTimer.cancel(); break; case CLOSING: // Ignore the connection attempt return; case CONNECTED: case CONNECTING: disconnect(getConfigManager().getOption(DOMAIN_GENERAL, "quitmessage")); case DISCONNECTING: while (!myState.getState().isDisconnected()) { try { myStateLock.wait(); } catch (InterruptedException ex) { return; } } break; default: // Do nothing break; } synchronized (parserLock) { if (parser != null) { throw new IllegalArgumentException("Connection attempt while parser " + "is still connected.\n\nMy state:" + getState()); } getConfigManager().migrate(address.getScheme(), "", "", address.getHost()); this.address = address; this.profile = profile; updateTitle(); updateIcon(); parser = buildParser(); final URI connectAddress; if (parser != null) { connectAddress = parser.getURI(); } else { connectAddress = address; } if (parser == null) { addLine("serverUnknownProtocol", connectAddress.getScheme()); return; } addLine("serverConnecting", connectAddress.getHost(), connectAddress.getPort()); myState.transition(ServerState.CONNECTING); doCallbacks(); awayMessage = null; removeInvites(); window.setAwayIndicator(false); try { parserThread = new Thread(parser, "IRC Parser thread"); parserThread.start(); } catch (IllegalThreadStateException ex) { Logger.appError(ErrorLevel.FATAL, "Unable to start IRC Parser", ex); } } } ActionManager.processEvent(CoreActionType.SERVER_CONNECTING, null, this); } /** * Reconnects to the IRC server with a specified reason. * * @param reason The quit reason to send */ public void reconnect(final String reason) { synchronized (myStateLock) { if (myState.getState() == ServerState.CLOSING) { return; } disconnect(reason); connect(address, profile); } } /** * Reconnects to the IRC server. */ public void reconnect() { reconnect(getConfigManager().getOption(DOMAIN_GENERAL, "reconnectmessage")); } /** * Disconnects from the server with the default quit message. */ public void disconnect() { disconnect(getConfigManager().getOption(DOMAIN_GENERAL, "quitmessage")); } /** * Disconnects from the server. * * @param reason disconnect reason */ public void disconnect(final String reason) { synchronized (myStateLock) { switch (myState.getState()) { case CLOSING: case DISCONNECTING: case DISCONNECTED: case TRANSIENTLY_DISCONNECTED: return; case RECONNECT_WAIT: reconnectTimer.cancel(); break; default: break; } clearChannels(); synchronized (parserLock) { if (parser == null) { myState.transition(ServerState.DISCONNECTED); } else { myState.transition(ServerState.DISCONNECTING); removeInvites(); updateIcon(); parserThread.interrupt(); parser.disconnect(reason); } } if (getConfigManager().getOptionBool(DOMAIN_GENERAL, "closechannelsonquit")) { closeChannels(); } if (getConfigManager().getOptionBool(DOMAIN_GENERAL, "closequeriesonquit")) { closeQueries(); } } } /** * Schedules a reconnect attempt to be performed after a user-defiend delay. */ @Precondition("The server state is transiently disconnected") private void doDelayedReconnect() { synchronized (myStateLock) { if (myState.getState() != ServerState.TRANSIENTLY_DISCONNECTED) { throw new IllegalStateException("doDelayedReconnect when not " + "transiently disconnected\n\nState: " + myState); } final int delay = Math.max(1000, getConfigManager().getOptionInt(DOMAIN_GENERAL, "reconnectdelay")); handleNotification("connectRetry", getName(), delay / 1000); reconnectTimer = new Timer("Server Reconnect Timer"); reconnectTimer.schedule(new TimerTask() { @Override public void run() { synchronized (myStateLock) { if (myState.getState() == ServerState.RECONNECT_WAIT) { myState.transition(ServerState.TRANSIENTLY_DISCONNECTED); reconnect(); } } } }, delay); myState.transition(ServerState.RECONNECT_WAIT); updateIcon(); } } // </editor-fold> // <editor-fold defaultstate="collapsed" desc="Child windows"> /** * Determines whether the server knows of the specified channel. * * @param channel The channel to be checked * @return True iff the channel is known, false otherwise */ public boolean hasChannel(final String channel) { return channels.containsKey(converter.toLowerCase(channel)); } /** * Retrieves the specified channel belonging to this server. * * @param channel The channel to be retrieved * @return The appropriate channel object */ public Channel getChannel(final String channel) { return channels.get(converter.toLowerCase(channel)); } /** * Retrieves a list of channel names belonging to this server. * * @return list of channel names belonging to this server */ public List<String> getChannels() { final ArrayList<String> res = new ArrayList<String>(); for (String channel : channels.keySet()) { res.add(channel); } return res; } /** * Determines whether the server knows of the specified query. * * @param host The host of the query to look for * @return True iff the query is known, false otherwise */ public boolean hasQuery(final String host) { if (parser == null) { return false; } final String nick = parser.parseHostmask(host)[0]; for (Query query : queries) { if (converter.equalsIgnoreCase(parser.parseHostmask(query.getHost())[0], nick)) { return true; } } return false; } /** * Retrieves the specified query belonging to this server. * * @param host The host of the query to look for * @return The appropriate query object */ public Query getQuery(final String host) { if (parser == null) { throw new IllegalArgumentException("No such query: " + host); } final String nick = parser.parseHostmask(host)[0]; for (Query query : queries) { if (converter.equalsIgnoreCase(parser.parseHostmask(query.getHost())[0], nick)) { return query; } } throw new IllegalArgumentException("No such query: " + host); } /** * Retrieves a list of queries belonging to this server. * * @return list of queries belonging to this server */ public List<Query> getQueries() { return new ArrayList<Query>(queries); } /** * Adds a raw window to this server. */ public void addRaw() { if (raw == null) { raw = new Raw(this, new RawCommandParser(this)); synchronized (parserLock) { if (parser != null) { raw.registerCallbacks(); } } } else { raw.activateFrame(); } } /** * Retrieves the raw window associated with this server. * * @return The raw window associated with this server. */ public Raw getRaw() { return raw; } /** * Removes our reference to the raw object (presumably after it has been * closed). */ public void delRaw() { raw = null; //NOPMD } /** * Removes a specific channel and window from this server. * * @param chan channel to remove */ public void delChannel(final String chan) { tabCompleter.removeEntry(TabCompletionType.CHANNEL, chan); channels.remove(converter.toLowerCase(chan)); } /** * Adds a specific channel and window to this server. * * @param chan channel to add */ public void addChannel(final ChannelInfo chan) { synchronized (myStateLock) { if (myState.getState() == ServerState.CLOSING) { // Can't join channels while the server is closing return; } } if (hasChannel(chan.getName())) { getChannel(chan.getName()).setChannelInfo(chan); getChannel(chan.getName()).selfJoin(); } else { final Channel newChan = new Channel(this, chan); tabCompleter.addEntry(TabCompletionType.CHANNEL, chan.getName()); channels.put(converter.toLowerCase(chan.getName()), newChan); newChan.show(); } } /** * Adds a query to this server. * * @param host host of the remote client being queried */ public void addQuery(final String host) { synchronized (myStateLock) { if (myState.getState() == ServerState.CLOSING) { // Can't open queries while the server is closing return; } } if (!hasQuery(host)) { final Query newQuery = new Query(this, host); tabCompleter.addEntry(TabCompletionType.QUERY_NICK, parser.parseHostmask(host)[0]); queries.add(newQuery); } } /** * Deletes a query from this server. * * @param query The query that should be removed. */ public void delQuery(final Query query) { tabCompleter.removeEntry(TabCompletionType.QUERY_NICK, query.getNickname()); queries.remove(query); } /** {@inheritDoc} */ @Override public boolean ownsFrame(final Window target) { // Check if it's our server frame if (window != null && window.equals(target)) { return true; } // Check if it's the raw frame if (raw != null && raw.ownsFrame(target)) { return true; } // Check if it's a channel frame for (Channel channel : channels.values()) { if (channel.ownsFrame(target)) { return true; } } // Check if it's a query frame for (Query query : queries) { if (query.ownsFrame(target)) { return true; } } return false; } /** * Sets the specified frame as the most-recently activated. * * @param source The frame that was activated */ public void setActiveFrame(final FrameContainer source) { activeFrame = source; } /** * Retrieves a list of all children of this server instance. * * @return A list of this server's children */ public List<WritableFrameContainer> getChildren() { final List<WritableFrameContainer> res = new ArrayList<WritableFrameContainer>(); if (raw != null) { res.add(raw); } res.addAll(channels.values()); res.addAll(queries); return res; } /** * Closes all open channel windows associated with this server. */ private void closeChannels() { for (Channel channel : new ArrayList<Channel>(channels.values())) { channel.close(); } } /** * Clears the nicklist of all open channels. */ private void clearChannels() { for (Channel channel : channels.values()) { channel.resetWindow(); } } /** * Closes all open query windows associated with this server. */ private void closeQueries() { for (Query query : new ArrayList<Query>(queries)) { query.close(); } } // </editor-fold> // <editor-fold defaultstate="collapsed" desc="Miscellaneous methods"> /** * Builds an appropriately configured {@link IRCParser} for this server. * * @return A configured IRC parser. */ private Parser buildParser() { final CertificateManager certManager = new CertificateManager(address.getHost(), getConfigManager()); final MyInfo myInfo = buildMyInfo(); final Parser myParser = new ParserFactory().getParser(myInfo, address); if (myParser instanceof SecureParser) { final SecureParser secureParser = (SecureParser) myParser; secureParser.setTrustManagers(new TrustManager[]{certManager}); secureParser.setKeyManagers(certManager.getKeyManager()); } if (myParser != null) { myParser.setIgnoreList(ignoreList); myParser.setPingTimerInterval(getConfigManager().getOptionInt(DOMAIN_SERVER, "pingtimer")); myParser.setPingTimerFraction((int) (getConfigManager().getOptionInt(DOMAIN_SERVER, "pingfrequency") / myParser.getPingTimerInterval())); if (getConfigManager().hasOptionString(DOMAIN_GENERAL, "bindip")) { myParser.setBindIP(getConfigManager().getOption(DOMAIN_GENERAL, "bindip")); } } return myParser; } /** * Compare the given URI to the URI we are currently using to see if they * would both result in the server connecting to the same place, even if the * URIs do not match exactly. * * @param uri URI to compare with the Servers own URI. * @return True if the Given URI is the "same" as the one we are using. * @since 0.6.3 */ public boolean compareURI(final URI uri) { if (parser != null) { return parser.compareURI(uri); } if (oldParser != null) { return oldParser.compareURI(uri); } return false; } /** * Retrieves the MyInfo object used for the IRC Parser. * * @return The MyInfo object for our profile */ @Precondition({ "The current profile is not null", "The current profile specifies at least one nickname" }) private MyInfo buildMyInfo() { Logger.assertTrue(profile != null); Logger.assertTrue(!profile.getOptionList(DOMAIN_PROFILE, "nicknames").isEmpty()); final MyInfo myInfo = new MyInfo(); myInfo.setNickname(profile.getOptionList(DOMAIN_PROFILE, "nicknames").get(0)); myInfo.setRealname(profile.getOption(DOMAIN_PROFILE, "realname")); if (profile.hasOptionString(DOMAIN_PROFILE, "ident")) { myInfo.setUsername(profile.getOption(DOMAIN_PROFILE, "ident")); } return myInfo; } /** * Updates this server's icon. */ private void updateIcon() { final String icon = myState.getState() == ServerState.CONNECTED ? address.getScheme().endsWith("s") ? "secure-server" : "server" : "server-disconnected"; setIcon(icon); } /** * Registers callbacks. */ private void doCallbacks() { if (raw != null) { raw.registerCallbacks(); } eventHandler.registerCallbacks(); for (Query query : queries) { query.reregister(); } } /** * Joins the specified channel with the specified key. * * @since 0.6.3m1 * @param channel The channel to be joined * @param key The key for the channel * @deprecated Use {@link #join(com.dmdirc.parser.common.ChannelJoinRequest[])} */ @Deprecated public void join(final String channel, final String key) { join(new ChannelJoinRequest(channel, key)); } /** * Attempts to join the specified channels. If channels with the same name * already exist, they are (re)joined and their windows activated. * * @param requests The channel join requests to process * @since 0.6.4 */ public void join(final ChannelJoinRequest ... requests) { synchronized (myStateLock) { if (myState.getState() == ServerState.CONNECTED) { final List<ChannelJoinRequest> pending = new ArrayList<ChannelJoinRequest>(); for (ChannelJoinRequest request : requests) { removeInvites(request.getName()); final String name; if (parser.isValidChannelName(request.getName())) { name = request.getName(); } else { name = parser.getChannelPrefixes().substring(0, 1) + request.getName(); } if (hasChannel(name)) { getChannel(name).activateFrame(); } if (!hasChannel(name) || !getChannel(name).isOnChannel()) { pending.add(request); } } parser.joinChannels(pending.toArray(new ChannelJoinRequest[0])); } else { // TODO: Need to pass key // TODO (uris): address.getChannels().add(channel); } } } /** * Joins the specified channel, or adds it to the auto-join list if the * server is not connected. * * @param channel The channel to be joined * @deprecated Use {@link #join(com.dmdirc.parser.common.ChannelJoinRequest[])} */ @Deprecated public void join(final String channel) { join(new ChannelJoinRequest(channel)); } /** {@inheritDoc} */ @Override public void sendLine(final String line) { synchronized (myStateLock) { synchronized (parserLock) { if (parser != null && !line.isEmpty() && myState.getState() == ServerState.CONNECTED) { parser.sendRawMessage(window.getTranscoder().encode(line)); } } } } /** {@inheritDoc} */ @Override public int getMaxLineLength() { synchronized (parserLock) { return parser == null ? -1 : parser.getMaxLength(); } } /** * Retrieves the parser used for this connection. * * @return IRCParser this connection's parser */ public Parser getParser() { return parser; } /** * Retrieves the profile that's in use for this server. * * @return The profile in use by this server */ public Identity getProfile() { return profile; } /** * Retrieves the possible channel prefixes in use on this server. * * @return This server's possible channel prefixes */ public String getChannelPrefixes() { synchronized (parserLock) { return parser == null ? "#&" : parser.getChannelPrefixes(); } } /** * Retrieves the name of this server's network. The network name is * determined using the following rules: * * 1. If the server includes its network name in the 005 information, we * use that * 2. If the server's name ends in biz, com, info, net or org, we use the * second level domain (e.g., foo.com) * 3. If the server's name contains more than two dots, we drop everything * up to and including the first part, and use the remainder * 4. In all other cases, we use the full server name * * @return The name of this server's network */ public String getNetwork() { synchronized (parserLock) { if (parser == null) { throw new IllegalStateException("getNetwork called when " + "parser is null (state: " + getState() + ")"); } else if (parser.getNetworkName().isEmpty()) { return getNetworkFromServerName(parser.getServerName()); } else { return parser.getNetworkName(); } } } /** * Determines whether this server is currently connected to the specified * network. * * @param target The network to check for * @return True if this server is connected to the network, false otherwise * @since 0.6.3m1rc3 */ public boolean isNetwork(String target) { synchronized (myStateLock) { synchronized (parserLock) { if (parser == null) { return false; } else { return getNetwork().equalsIgnoreCase(target); } } } } /** * Calculates a network name from the specified server name. This method * implements parts 2-4 of the procedure documented at getNetwork(). * * @param serverName The server name to parse * @return A network name for the specified server */ protected static String getNetworkFromServerName(final String serverName) { final String[] parts = serverName.split("\\."); final String[] tlds = {"biz", "com", "info", "net", "org"}; boolean isTLD = false; for (String tld : tlds) { if (serverName.endsWith("." + tld)) { isTLD = true; } } if (isTLD && parts.length > 2) { return parts[parts.length - 2] + "." + parts[parts.length - 1]; } else if (parts.length > 2) { final StringBuilder network = new StringBuilder(); for (int i = 1; i < parts.length; i++) { if (network.length() > 0) { network.append('.'); } network.append(parts[i]); } return network.toString(); } else { return serverName; } } /** * Retrieves the name of this server's IRCd. * * @return The name of this server's IRCd */ public String getIrcd() { return parser.getServerSoftwareType(); } /** * Retrieves the protocol used by this server. * * @return This server's protocol * @since 0.6.3 */ public String getProtocol() { return address.getScheme(); } /** * Returns the current away status. * * @return True if the client is marked as away, false otherwise */ public boolean isAway() { return awayMessage != null; } /** * Gets the current away message. * * @return Null if the client isn't away, or a textual away message if it is */ public String getAwayMessage() { return awayMessage; } /** * Returns the tab completer for this connection. * * @return The tab completer for this server */ public TabCompleter getTabCompleter() { return tabCompleter; } /** {@inheritDoc} */ @Override public InputWindow getFrame() { return window; } /** * Retrieves the current state for this server. * * @return This server's state */ public ServerState getState() { return myState.getState(); } /** * Retrieves the status object for this server. Effecting state transitions * on the object returned by this method will almost certainly cause * problems. * * @since 0.6.3m1 * @return This server's status object. */ public ServerStatus getStatus() { return myState; } /** {@inheritDoc} */ @Override public void windowClosing() { synchronized (myStateLock) { // 1: Make the window non-visible window.setVisible(false); // 2: Remove any callbacks or listeners eventHandler.unregisterCallbacks(); // 3: Trigger any actions neccessary disconnect(); myState.transition(ServerState.CLOSING); } closeChannels(); closeQueries(); removeInvites(); if (raw != null) { raw.close(); } // 4: Trigger action for the window closing // 5: Inform any parents that the window is closing ServerManager.getServerManager().unregisterServer(this); // 6: Remove the window from the window manager WindowManager.removeWindow(window); } /** {@inheritDoc} */ @Override public void windowClosed() { // 7: Remove any references to the window and parents window = null; //NOPMD oldParser = null; //NOPMD parser = null; //NOPMD } /** * Passes the arguments to the most recently activated frame for this * server. If the frame isn't know, or isn't visible, use this frame * instead. * * @param messageType The type of message to send * @param args The arguments for the message */ public void addLineToActive(final String messageType, final Object... args) { if (activeFrame == null || !activeFrame.getFrame().isVisible()) { activeFrame = this; } activeFrame.getFrame().addLine(messageType, args); } /** * Passes the arguments to all frames for this server. * * @param messageType The type of message to send * @param args The arguments of the message */ public void addLineToAll(final String messageType, final Object... args) { for (Channel channel : channels.values()) { channel.getFrame().addLine(messageType, args); } for (Query query : queries) { query.getFrame().addLine(messageType, args); } addLine(messageType, args); } /** * Replies to an incoming CTCP message. * * @param source The source of the message * @param type The CTCP type * @param args The CTCP arguments */ public void sendCTCPReply(final String source, final String type, final String args) { if (getConfigManager().getOptionBool(DOMAIN_GENERAL, "sendctcpreplies")) { if (type.equalsIgnoreCase("VERSION")) { parser.sendCTCPReply(source, "VERSION", "DMDirc " + getConfigManager().getOption("version", "version") + " - http://www.dmdirc.com/"); } else if (type.equalsIgnoreCase("PING")) { parser.sendCTCPReply(source, "PING", args); } else if (type.equalsIgnoreCase("CLIENTINFO")) { parser.sendCTCPReply(source, "CLIENTINFO", "VERSION PING CLIENTINFO"); } } } /** * Determines if the specified channel name is valid. A channel name is * valid if we already have an existing Channel with the same name, or * we have a valid parser instance and the parser says it's valid. * * @param channelName The name of the channel to test * @return True if the channel name is valid, false otherwise */ public boolean isValidChannelName(final String channelName) { synchronized (parserLock) { return hasChannel(channelName) || (parser != null && parser.isValidChannelName(channelName)); } } /** * Returns the server instance associated with this frame. * * @return the associated server connection */ @Override public Server getServer() { return this; } /** {@inheritDoc} */ @Override protected boolean processNotificationArg(final Object arg, final List<Object> args) { if (arg instanceof ClientInfo) { final ClientInfo clientInfo = (ClientInfo) arg; args.add(clientInfo.getNickname()); args.add(clientInfo.getUsername()); args.add(clientInfo.getHostname()); return true; } else { return super.processNotificationArg(arg, args); } } /** * Updates the name and title of this window. */ public void updateTitle() { synchronized (myStateLock) { if (myState.getState() == ServerState.CLOSING) { return; } synchronized (parserLock) { final Object[] arguments = new Object[]{ address.getHost(), parser == null ? "Unknown" : parser.getServerName(), address.getPort(), parser == null ? "Unknown" : getNetwork(), parser == null ? "Unknown" : parser.getLocalClient().getNickname() }; setName(Formatter.formatMessage(getConfigManager(), "serverName", arguments)); window.setTitle(Formatter.formatMessage(getConfigManager(), "serverTitle", arguments)); } } } /** {@inheritDoc} */ @Override public void configChanged(final String domain, final String key) { if ("formatter".equals(domain)) { updateTitle(); } } // </editor-fold> // <editor-fold defaultstate="collapsed" desc="Parser callbacks"> /** * Called when the server says that the nickname we're trying to use is * already in use. * * @param nickname The nickname that we were trying to use */ public void onNickInUse(final String nickname) { final String lastNick = parser.getLocalClient().getNickname(); // If our last nick is still valid, ignore the in use message if (!converter.equalsIgnoreCase(lastNick, nickname)) { return; } String newNick = lastNick + new Random().nextInt(10); final List<String> alts = profile.getOptionList(DOMAIN_PROFILE, "nicknames"); int offset = 0; // Loop so we can check case sensitivity for (String alt : alts) { offset++; if (converter.equalsIgnoreCase(alt, lastNick)) { break; } } if (offset < alts.size() && !alts.get(offset).isEmpty()) { newNick = alts.get(offset); } parser.getLocalClient().setNickname(newNick); } /** * Called when the server sends a numeric event. * * @param numeric The numeric code for the event * @param tokens The (tokenised) arguments of the event */ public void onNumeric(final int numeric, final String[] tokens) { String snumeric = String.valueOf(numeric); if (numeric < 10) { snumeric = "00" + snumeric; } else if (numeric < 100) { snumeric = "0" + snumeric; } final String sansIrcd = "numeric_" + snumeric; StringBuffer target = new StringBuffer(""); if (getConfigManager().hasOptionString("formatter", sansIrcd)) { target = new StringBuffer(sansIrcd); } else if (getConfigManager().hasOptionString("formatter", "numeric_unknown")) { target = new StringBuffer("numeric_unknown"); } ActionManager.processEvent(CoreActionType.SERVER_NUMERIC, target, this, Integer.valueOf(numeric), tokens); handleNotification(target.toString(), (Object[]) tokens); } /** * Called when the socket has been closed. */ public void onSocketClosed() { if (Thread.holdsLock(myState)) { new Thread(new Runnable() { /** {@inheritDoc} */ @Override public void run() { onSocketClosed(); } }, "Socket closed deferred thread").start(); return; } handleNotification("socketClosed", getName()); ActionManager.processEvent(CoreActionType.SERVER_DISCONNECTED, null, this); eventHandler.unregisterCallbacks(); synchronized (myStateLock) { if (myState.getState() == ServerState.CLOSING || myState.getState() == ServerState.DISCONNECTED) { // This has been triggered via .disconect() return; } if (myState.getState() == ServerState.DISCONNECTING) { myState.transition(ServerState.DISCONNECTED); } else { myState.transition(ServerState.TRANSIENTLY_DISCONNECTED); } clearChannels(); synchronized (parserLock) { oldParser = parser; parser = null; } updateIcon(); if (getConfigManager().getOptionBool(DOMAIN_GENERAL, "closechannelsondisconnect")) { closeChannels(); } if (getConfigManager().getOptionBool(DOMAIN_GENERAL, "closequeriesondisconnect")) { closeQueries(); } removeInvites(); updateAwayState(null); if (getConfigManager().getOptionBool(DOMAIN_GENERAL, "reconnectondisconnect") && myState.getState() == ServerState.TRANSIENTLY_DISCONNECTED) { doDelayedReconnect(); } } } /** * Called when an error was encountered while connecting. * * @param errorInfo The parser's error information */ @Precondition("The current server state is CONNECTING") public void onConnectError(final ParserError errorInfo) { synchronized (myStateLock) { if (myState.getState() == ServerState.CLOSING || myState.getState() == ServerState.DISCONNECTING) { // Do nothing return; } else if (myState.getState() != ServerState.CONNECTING) { // Shouldn't happen throw new IllegalStateException("Connect error when not " + "connecting\n\n" + getStatus().getTransitionHistory()); } myState.transition(ServerState.TRANSIENTLY_DISCONNECTED); synchronized (parserLock) { oldParser = parser; parser = null; } updateIcon(); String description; if (errorInfo.getException() == null) { description = errorInfo.getData(); } else { final Exception exception = errorInfo.getException(); if (exception instanceof java.net.UnknownHostException) { description = "Unknown host (unable to resolve)"; } else if (exception instanceof java.net.NoRouteToHostException) { description = "No route to host"; } else if (exception instanceof java.net.SocketTimeoutException) { description = "Connection attempt timed out"; } else if (exception instanceof java.net.SocketException || exception instanceof javax.net.ssl.SSLException) { description = exception.getMessage(); } else { Logger.appError(ErrorLevel.LOW, "Unknown socket error", new IllegalArgumentException(exception)); description = "Unknown error: " + exception.getMessage(); } } ActionManager.processEvent(CoreActionType.SERVER_CONNECTERROR, null, this, description); handleNotification("connectError", getName(), description); if (getConfigManager().getOptionBool(DOMAIN_GENERAL, "reconnectonconnectfailure")) { doDelayedReconnect(); } } } /** * Called when we fail to receive a ping reply within a set period of time. */ public void onPingFailed() { Main.getUI().getStatusBar().setMessage("No ping reply from " + getName() + " for over " + ((int) (Math.floor(parser.getPingTime() / 1000.0))) + " seconds.", null, 10); ActionManager.processEvent(CoreActionType.SERVER_NOPING, null, this, Long.valueOf(parser.getPingTime())); if (parser.getPingTime() >= getConfigManager().getOptionInt(DOMAIN_SERVER, "pingtimeout")) { handleNotification("stonedServer", getName()); reconnect(); } } /** * Called after the parser receives the 005 headers from the server. */ @Precondition("State is CONNECTING") public void onPost005() { synchronized (myStateLock) { if (myState.getState() != ServerState.CONNECTING) { // Shouldn't happen throw new IllegalStateException("Received onPost005 while not " + "connecting\n\n" + myState.getTransitionHistory()); } if (myState.getState() != ServerState.CONNECTING) { // We've transitioned while waiting for the lock. Just abort. return; } myState.transition(ServerState.CONNECTED); getConfigManager().migrate(address.getScheme(), parser.getServerSoftwareType(), getNetwork(), parser.getServerName()); updateIcon(); updateTitle(); updateIgnoreList(); converter = parser.getStringConverter(); final List<ChannelJoinRequest> requests = new ArrayList<ChannelJoinRequest>(); if (getConfigManager().getOptionBool(DOMAIN_GENERAL, "rejoinchannels")) { for (Channel chan : channels.values()) { requests.add(new ChannelJoinRequest(chan.getName())); } } join(requests.toArray(new ChannelJoinRequest[0])); checkModeAliases(); } ActionManager.processEvent(CoreActionType.SERVER_CONNECTED, null, this); } /** * Checks that we have the neccessary mode aliases for this server. */ private void checkModeAliases() { // Check we have mode aliases final String modes = parser.getBooleanChannelModes() + parser.getListChannelModes() + parser.getParameterChannelModes() + parser.getDoubleParameterChannelModes(); final String umodes = parser.getUserModes(); final StringBuffer missingModes = new StringBuffer(); final StringBuffer missingUmodes = new StringBuffer(); for (char mode : modes.toCharArray()) { if (!getConfigManager().hasOptionString(DOMAIN_SERVER, "mode" + mode)) { missingModes.append(mode); } } for (char mode : umodes.toCharArray()) { if (!getConfigManager().hasOptionString(DOMAIN_SERVER, "umode" + mode)) { missingUmodes.append(mode); } } if (missingModes.length() + missingUmodes.length() > 0) { final StringBuffer missing = new StringBuffer("Missing mode aliases: "); if (missingModes.length() > 0) { missing.append("channel: +"); missing.append(missingModes); } if (missingUmodes.length() > 0) { if (missingModes.length() > 0) { missing.append(' '); } missing.append("user: +"); missing.append(missingUmodes); } Logger.appError(ErrorLevel.LOW, missing.toString() + " [" + parser.getServerSoftwareType() + "]", new Exception(missing.toString() + "\n" // NOPMD + "Network: " + getNetwork() + "\n" + "IRCd: " + parser.getServerSoftware() + " (" + parser.getServerSoftwareType() + ")\n" + "Mode alias version: " + getConfigManager().getOption("identity", "modealiasversion") + "\n\n")); } } // </editor-fold> // <editor-fold defaultstate="collapsed" desc="Ignore lists"> /** * Retrieves this server's ignore list. * * @return This server's ignore list */ public IgnoreList getIgnoreList() { return ignoreList; } /** * Updates this server's ignore list to use the entries stored in the * config manager. */ public void updateIgnoreList() { ignoreList.clear(); ignoreList.addAll(getConfigManager().getOptionList("network", "ignorelist")); } /** * Saves the contents of our ignore list to the network identity. */ public void saveIgnoreList() { getNetworkIdentity().setOption("network", "ignorelist", ignoreList.getRegexList()); } // </editor-fold> // <editor-fold defaultstate="collapsed" desc="Identity handling"> /** * Retrieves the identity for this server. * * @return This server's identity */ public Identity getServerIdentity() { return IdentityManager.getServerConfig(getName()); } /** * Retrieves the identity for this server's network. * * @return This server's network identity */ public Identity getNetworkIdentity() { return IdentityManager.getNetworkConfig(getNetwork()); } // </editor-fold> // <editor-fold defaultstate="collapsed" desc="Invite handling"> /** * Adds an invite listener to this server. * * @param listener The listener to be added */ public void addInviteListener(final InviteListener listener) { synchronized (listeners) { listeners.add(InviteListener.class, listener); } } /** * Removes an invite listener from this server. * * @param listener The listener to be removed */ public void removeInviteListener(final InviteListener listener) { synchronized (listeners) { listeners.remove(InviteListener.class, listener); } } /** * Adds an invite to this server, and fires the appropriate listeners. * * @param invite The invite to be added */ public void addInvite(final Invite invite) { synchronized (invites) { for (Invite oldInvite : new ArrayList<Invite>(invites)) { if (oldInvite.getChannel().equals(invite.getChannel())) { removeInvite(oldInvite); } } invites.add(invite); synchronized (listeners) { for (InviteListener listener : listeners.get(InviteListener.class)) { listener.inviteReceived(this, invite); } } } } /** * Removes all invites for the specified channel. * * @param channel The channel to remove invites for */ public void removeInvites(final String channel) { for (Invite invite : new ArrayList<Invite>(invites)) { if (invite.getChannel().equals(channel)) { removeInvite(invite); } } } /** * Removes all invites for all channels. */ private void removeInvites() { for (Invite invite : new ArrayList<Invite>(invites)) { removeInvite(invite); } } /** * Removes an invite from this server, and fires the appropriate listeners. * * @param invite The invite to be removed */ public void removeInvite(final Invite invite) { synchronized (invites) { invites.remove(invite); synchronized (listeners) { for (InviteListener listener : listeners.get(InviteListener.class)) { listener.inviteExpired(this, invite); } } } } /** * Retusnt the list of invites for this server. * * @return Invite list */ public List<Invite> getInvites() { return invites; } // </editor-fold> // <editor-fold defaultstate="collapsed" desc="Away state handling"> /** * Adds an away state lisener to this server. * * @param listener The listener to be added */ public void addAwayStateListener(final AwayStateListener listener) { synchronized (listeners) { listeners.add(AwayStateListener.class, listener); } } /** * Removes an away state lisener from this server. * * @param listener The listener to be removed */ public void removeAwayStateListener(final AwayStateListener listener) { synchronized (listeners) { listeners.remove(AwayStateListener.class, listener); } } /** * Updates our away state and fires the relevant listeners. * * @param message The away message to use, or null if we're not away. */ public void updateAwayState(final String message) { if ((awayMessage != null && awayMessage.equals(message)) || (awayMessage == null && message == null)) { return; } awayMessage = message; new Thread(new Runnable() { /** {@inheritDoc} */ @Override public void run() { synchronized (listeners) { if (message == null) { for (AwayStateListener listener : listeners.get(AwayStateListener.class)) { listener.onBack(); } } else { for (AwayStateListener listener : listeners.get(AwayStateListener.class)) { listener.onAway(message); } } } } }, "Away state listener runner").start(); } // </editor-fold> }
addQuery and addChannel now return the added objects Fixes issue 3880 Change-Id: If19373c7c662b7532dfa814fdad25667585cbc35 Reviewed-on: http://gerrit.dmdirc.com/991 Reviewed-by: Shane Mc Cormack <[email protected]> Automatic-Compile: Shane Mc Cormack <[email protected]>
src/com/dmdirc/Server.java
addQuery and addChannel now return the added objects
<ide><path>rc/com/dmdirc/Server.java <ide> * Adds a specific channel and window to this server. <ide> * <ide> * @param chan channel to add <del> */ <del> public void addChannel(final ChannelInfo chan) { <add> * @return The channel that was added (may be null if closing) <add> */ <add> public Channel addChannel(final ChannelInfo chan) { <ide> synchronized (myStateLock) { <ide> if (myState.getState() == ServerState.CLOSING) { <ide> // Can't join channels while the server is closing <del> return; <add> return null; <ide> } <ide> } <ide> <ide> channels.put(converter.toLowerCase(chan.getName()), newChan); <ide> newChan.show(); <ide> } <add> <add> return getChannel(chan.getName()); <ide> } <ide> <ide> /** <ide> * Adds a query to this server. <ide> * <ide> * @param host host of the remote client being queried <del> */ <del> public void addQuery(final String host) { <add> * @return The query that was added (may be null if closing) <add> */ <add> public Query addQuery(final String host) { <ide> synchronized (myStateLock) { <ide> if (myState.getState() == ServerState.CLOSING) { <ide> // Can't open queries while the server is closing <del> return; <add> return null; <ide> } <ide> } <ide> <ide> tabCompleter.addEntry(TabCompletionType.QUERY_NICK, parser.parseHostmask(host)[0]); <ide> queries.add(newQuery); <ide> } <add> <add> return getQuery(host); <ide> } <ide> <ide> /**
Java
apache-2.0
d8ddc4487fe04a46d3db550b49c2578f1e514e06
0
jyemin/mongo-java-driver,PSCGroup/mongo-java-driver,davydotcom/mongo-java-driver,eltimn/mongo-java-driver,kevinsawicki/mongo-java-driver,rozza/mongo-java-driver,eltimn/mongo-java-driver,kevinsawicki/mongo-java-driver,jsonking/mongo-java-driver,jyemin/mongo-java-driver,rozza/mongo-java-driver,kay-kim/mongo-java-driver,wanggc/mongo-java-driver,gianpaj/mongo-java-driver,wanggc/mongo-java-driver,davydotcom/mongo-java-driver,jsonking/mongo-java-driver,eltimn/mongo-java-driver,kevinsawicki/mongo-java-driver
// DBCollection.java package ed.db; import java.util.*; import java.lang.reflect.*; import ed.util.*; /** DB Collection * * Class for database collection objects. When you invoke something like: * var my_coll = db.students; * you get back a collection which can be used to perform various database operations. */ public abstract class DBCollection { /** @unexpose */ final static boolean DEBUG = Boolean.getBoolean( "DEBUG.DB" ); /** Saves an object to the database. * @param o object to save * @return the new database object */ protected abstract DBObject doSave( DBObject o ); /** Performs an update operation. * @param q search query for old object to update * @param o object with which to update <tt>q</tt> * @param upsert if the database should create the element if it does not exist * @param apply if an _id field should be added to the new object * See www.10gen.com/wiki/db.update */ public abstract DBObject update( DBObject q , DBObject o , boolean upsert , boolean apply ); /** Adds any necessary fields to a given object before saving it to the collection. * @param o object to which to add the fields */ protected abstract void doapply( DBObject o ); /** Removes an object from the database collection. * @return -1 */ public abstract int remove( DBObject o ); /** Finds an object by its id. * @param id the id of the object * @return the object, if found */ protected abstract DBObject dofind( ObjectId id ); /** Finds an object. * @param ref query used to search * @param fields the fields of matching objects to return * @param numToSkip will not return the first <tt>numToSkip</tt> matches * @param numToReturn limit the results to this number * @return the objects, if found */ public abstract Iterator<DBObject> find( DBObject ref , DBObject fields , int numToSkip , int numToReturn ); /** Ensures an index on this collection (that is, the index will be created if it does not exist). * ensureIndex is optimized and is inexpensive if the index already exists. * @param keys fields to use for index * @param name an identifier for the index */ public abstract void ensureIndex( DBObject keys , String name ); // ------ /** Finds an object by its id. * @param id the id of the object * @return the object, if found */ public final DBObject find( ObjectId id ){ ensureIDIndex(); DBObject ret = dofind( id ); if ( ret == null ) return null; apply( ret , false ); return ret; } public final DBObject find( String id ){ if ( ! ObjectId.isValid( id ) ) throw new IllegalArgumentException( "invalid object id [" + id + "]" ); return find( new ObjectId( id ) ); } /** Ensures an index on the id field, if one does not already exist. * @param key an object with an _id field. */ public void checkForIDIndex( DBObject key ){ if ( _checkedIdIndex ) // we already created it, so who cares return; if ( key.get( "_id" ) == null ) return; if ( key.keySet().size() > 1 ) return; ensureIDIndex(); } /** Creates an index on the id field, if one does not already exist. * @param key an object with an _id field. */ public void ensureIDIndex(){ if ( _checkedIdIndex ) return; ensureIndex( _idKey ); _checkedIdIndex = true; } /** Creates an index on a set of fields, if one does not already exist. * @param keys an object with a key set of the fields desired for the index */ public final void ensureIndex( final DBObject keys ){ ensureIndex( keys , false ); } /** Forces creation of an index on a set of fields, if one does not already exist. * @param keys an object with a key set of the fields desired for the index */ public final void createIndex( final DBObject keys ){ ensureIndex( keys , true ); } /** Creates an index on a set of fields, if one does not already exist. * @param keys an object with a key set of the fields desired for the index * @param force if index creation should be forced, even if it is unnecessary */ public final void ensureIndex( final DBObject keys , final boolean force ){ if ( checkReadOnly( false ) ) return; final String name = genIndexName( keys ); boolean doEnsureIndex = false; if ( Math.random() > 0.999 ) doEnsureIndex = true; else if ( ! _createIndexes.contains( name ) ) doEnsureIndex = true; else if ( _anyUpdateSave && ! _createIndexesAfterSave.contains( name ) ) doEnsureIndex = true; if ( ! ( force || doEnsureIndex ) ) return; ensureIndex( keys , name ); _createIndexes.add( name ); if ( _anyUpdateSave ) _createIndexesAfterSave.add( name ); } /** Clear all indices on this collection. */ public void resetIndexCache(){ _createIndexes.clear(); } /** Generate an index name from the set of fields it is over. * @param keys the names of the fields used in this index * @return a string representation of this index's fields */ public static String genIndexName( DBObject keys ){ String name = ""; for ( String s : keys.keySet() ){ if ( name.length() > 0 ) name += "_"; name += s + "_"; Object val = keys.get( s ); if ( val instanceof Number ) name += val.toString().replace( ' ' , '_' ); } return name; } public void setHintFields( List<DBObject> lst ){ _hintFields = lst; } /** Queries for an object in this collection. * @param ref object for which to search * @return an iterator over the results */ public final Iterator<DBObject> find( DBObject ref ){ return find( ref == null ? new BasicDBObject() : ref , null , 0 , 0 ); } public final Iterator<DBObject> find(){ Iterator<DBObject> i = find( new BasicDBObject() , null , 0 , 0 ); if ( i == null ) return (new LinkedList<DBObject>()).iterator(); return i; } public final DBObject findOne(){ return findOne( new BasicDBObject() ); } public final DBObject findOne( DBObject o ){ Iterator<DBObject> i = find( o , null , 0 , 1 ); if ( i == null || ! i.hasNext() ) return null; return i.next(); } /** */ public final ObjectId apply( DBObject o ){ return apply( o , true ); } /** Adds the "private" fields _save, _update, and _id to an object. * @param o object to which to add fields * @param ensureID if an _id field is needed * @return the _id assigned to the object * @throws RuntimeException if <tt>o</tt> is not a DBObject */ public final ObjectId apply( DBObject jo , boolean ensureID ){ ObjectId id = (ObjectId)jo.get( "_id" ); if ( ensureID && id == null ){ id = ObjectId.get(); jo.put( "_id" , id ); } doapply( jo ); return id; } /** Saves an object to this collection executing the preSave function in a given scope. * @param s scope to use (can be null) * @param o the object to save * @return the new object from the collection */ public final DBObject save( DBObject jo ){ if ( checkReadOnly( true ) ) return jo; _checkObject( jo , false , false ); //_findSubObject( s , jo , null ); ObjectId id = null; { Object temp = jo.get( "_id" ); if ( temp != null && ! ( temp instanceof ObjectId ) ) throw new RuntimeException( "_id has to be an ObjectId" ); id = (ObjectId)temp; } if ( DEBUG ) System.out.println( "id : " + id ); if ( id == null || id._new ){ if ( DEBUG ) System.out.println( "saving new object" ); if ( id != null ) id._new = false; doSave( jo ); return jo; } if ( DEBUG ) System.out.println( "doing implicit upsert : " + jo.get( "_id" ) ); DBObject q = new BasicDBObject(); q.put( "_id" , id ); return update( q , jo , true , false ); } // ---- DB COMMANDS ---- public void dropIndexes(){ BasicDBObject res = (BasicDBObject)_base.command( BasicDBObjectBuilder.start().add( "deleteIndexes" , getName() ).add( "index" , "*" ).get() ); if ( res.getInt( "ok" , 0 ) != 1 ) throw new RuntimeException( "error dropping indexes : " + res ); resetIndexCache(); } public void drop(){ dropIndexes(); BasicDBObject res = (BasicDBObject)_base.command( BasicDBObjectBuilder.start().add( "drop" , getName() ).get() ); if ( res.getInt( "ok" , 0 ) != 1 ) throw new RuntimeException( "error dropping : " + res ); } // ------ /** Initializes a new collection. * @param base database in which to create the collection * @param name the name of the collection */ protected DBCollection( DBBase base , String name ){ _base = base; _name = name; _fullName = _base.getName() + "." + name; } private final DBObject _checkObject( DBObject o , boolean canBeNull , boolean query ){ if ( o == null ){ if ( canBeNull ) return null; throw new NullPointerException( "can't be null" ); } if ( o.isPartialObject() && ! query ) throw new IllegalArgumentException( "can't save partial objects" ); if ( ! query ){ for ( String s : o.keySet() ){ if ( s.contains( "." ) ) throw new IllegalArgumentException( "fields stored in the db can't have . in them" ); if ( s.contains( "$" ) ) throw new IllegalArgumentException( "fields stored in the db can't have $ in them" ); } } return o; } /* private void _findSubObject( Scope scope , DBObject jo , IdentitySet seenSubs ){ if ( seenSubs == null ) seenSubs = new IdentitySet(); if ( seenSubs.contains( jo ) ) return; seenSubs.add( jo ); if ( DEBUG ) System.out.println( "_findSubObject on : " + jo.get( "_id" ) ); LinkedList<DBObject> toSearch = new LinkedList(); Map<DBObject,String> seen = new IdentityHashMap<DBObject,String>(); toSearch.add( jo ); while ( toSearch.size() > 0 ){ Map<DBObject,String> seenNow = new IdentityHashMap<DBObject,String>( seen ); DBObject n = toSearch.remove(0); for ( String name : n.keySet() ){ Object foo = Bytes.safeGet( n , name ); if ( foo == null ) continue; if ( ! ( foo instanceof DBObject ) ) continue; if ( foo instanceof DBRef ){ DBRef ref = (DBRef)foo; if ( ! ref.isDirty() ) continue; foo = ref.getRealObject(); } if ( foo instanceof JSFunction ) continue; if ( foo instanceof JSString || foo instanceof JSRegex || foo instanceof JSDate ) continue; if ( foo instanceof DBCollection || foo instanceof DBBase ) continue; DBObject e = (DBObject)foo; if ( e instanceof BasicDBObject ) ((BasicDBObject)e).prefunc(); if ( n.get( name ) == null ) continue; if ( e instanceof JSFileChunk ){ _base.getCollection( "_chunks" ).apply( e ); } if ( e.get( "_ns" ) == null ){ if ( seen.containsKey( e ) ) throw new RuntimeException( "you have a loop. key : " + name + " from a " + n.getClass() + " which is a : " + e.getClass() ); seenNow.put( e , "a" ); toSearch.add( e ); continue; } // ok - now we knows its a reference if ( e instanceof BasicDBObject && ((BasicDBObject)e).isPartialObject() ){ // TODO: i think this is correct // this means you have a reference to an object that was retrieved with only some objects // maybe this should do a extend, or throw an exception // but certainly shouldn't overwrite continue; } if ( e.get( "_id" ) == null ){ // new object, lets save it JSFunction otherSave = e.getFunction( "_save" ); if ( otherSave == null ) throw new RuntimeException( "no save :(" ); otherSave.call( scope , e , null ); continue; } // old object, lets update TODO: dirty tracking DBObject lookup = new BasicDBObject(); lookup.set( "_id" , e.get( "_id" ) ); JSFunction otherUpdate = e.getFunction( "_update" ); if ( otherUpdate == null ){ // already taken care of if ( e instanceof DBRef ) continue; throw new RuntimeException( "_update is null class: " + e.getClass().getName() + " keyset : " + e.keySet() + " ns:" + e.get( "_ns" ) ); } if ( e instanceof BasicDBObject && ! ((BasicDBObject)e).isDirty() ) continue; otherUpdate.call( scope , lookup , e , _upsertOptions , seenSubs ); } seen.putAll( seenNow ); } } */ /** Find a collection that is prefixed with this collection's name. * @param n the name of the collection to find * @return the matching collection */ public DBCollection getCollection( String n ){ return _base.getCollection( _name + "." + n ); } /** Returns the name of this collection. * @return the name of this collection */ public String getName(){ return _name; } /** Returns the full name of this collection, with the database name as a prefix. * @return the name of this collection */ public String getFullName(){ return _fullName; } /** Returns the database this collection is a member of. * @return this collection's database */ public DBBase getDB(){ return _base; } /** Returns the database this collection is a member of. * @return this collection's database */ public DBBase getBase(){ return _base; } /** Returns if this collection can be modified. * @return if this collection can be modified */ protected boolean checkReadOnly( boolean strict ){ if ( ! _base._readOnly ) return false; if ( ! strict ) return true; throw new RuntimeException( "db is read only" ); } /** Calculates the hash code for this collection. * @return the hash code */ public int hashCode(){ return _fullName.hashCode(); } /** Checks if this collection is equal to another object. * @param o object with which to compare this collection * @return if the two collections are equal */ public boolean equals( Object o ){ return o == this; } /** Returns name of the collection. * @return name of the collection. */ public String toString(){ return _name; } final DBBase _base; final protected String _name; final protected String _fullName; protected List<DBObject> _hintFields; private boolean _anyUpdateSave = false; private boolean _checkedIdIndex = false; final private Set<String> _createIndexes = new HashSet<String>(); final private Set<String> _createIndexesAfterSave = new HashSet<String>(); private final static DBObject _upsertOptions = BasicDBObjectBuilder.start().add( "upsert" , true ).get(); private final static DBObject _idKey = BasicDBObjectBuilder.start().add( "_id" , ObjectId.get() ).get(); }
src/main/ed/db/DBCollection.java
// DBCollection.java package ed.db; import java.util.*; import java.lang.reflect.*; import ed.util.*; /** DB Collection * * Class for database collection objects. When you invoke something like: * var my_coll = db.students; * you get back a collection which can be used to perform various database operations. */ public abstract class DBCollection { /** @unexpose */ final static boolean DEBUG = Boolean.getBoolean( "DEBUG.DB" ); /** Saves an object to the database. * @param o object to save * @return the new database object */ protected abstract DBObject doSave( DBObject o ); /** Performs an update operation. * @param q search query for old object to update * @param o object with which to update <tt>q</tt> * @param upsert if the database should create the element if it does not exist * @param apply if an _id field should be added to the new object * See www.10gen.com/wiki/db.update */ public abstract DBObject update( DBObject q , DBObject o , boolean upsert , boolean apply ); /** Adds any necessary fields to a given object before saving it to the collection. * @param o object to which to add the fields */ protected abstract void doapply( DBObject o ); /** Removes an object from the database collection. * @param id The _id of the object to be removed * @return -1 */ public abstract int remove( DBObject id ); /** Finds an object by its id. * @param id the id of the object * @return the object, if found */ protected abstract DBObject dofind( ObjectId id ); /** Finds an object. * @param ref query used to search * @param fields the fields of matching objects to return * @param numToSkip will not return the first <tt>numToSkip</tt> matches * @param numToReturn limit the results to this number * @return the objects, if found */ public abstract Iterator<DBObject> find( DBObject ref , DBObject fields , int numToSkip , int numToReturn ); /** Ensures an index on this collection (that is, the index will be created if it does not exist). * ensureIndex is optimized and is inexpensive if the index already exists. * @param keys fields to use for index * @param name an identifier for the index */ public abstract void ensureIndex( DBObject keys , String name ); // ------ /** Finds an object by its id. * @param id the id of the object * @return the object, if found */ public final DBObject find( ObjectId id ){ ensureIDIndex(); DBObject ret = dofind( id ); if ( ret == null ) return null; apply( ret , false ); return ret; } public final DBObject find( String id ){ if ( ! ObjectId.isValid( id ) ) throw new IllegalArgumentException( "invalid object id [" + id + "]" ); return find( new ObjectId( id ) ); } /** Ensures an index on the id field, if one does not already exist. * @param key an object with an _id field. */ public void checkForIDIndex( DBObject key ){ if ( _checkedIdIndex ) // we already created it, so who cares return; if ( key.get( "_id" ) == null ) return; if ( key.keySet().size() > 1 ) return; ensureIDIndex(); } /** Creates an index on the id field, if one does not already exist. * @param key an object with an _id field. */ public void ensureIDIndex(){ if ( _checkedIdIndex ) return; ensureIndex( _idKey ); _checkedIdIndex = true; } /** Creates an index on a set of fields, if one does not already exist. * @param keys an object with a key set of the fields desired for the index */ public final void ensureIndex( final DBObject keys ){ ensureIndex( keys , false ); } /** Forces creation of an index on a set of fields, if one does not already exist. * @param keys an object with a key set of the fields desired for the index */ public final void createIndex( final DBObject keys ){ ensureIndex( keys , true ); } /** Creates an index on a set of fields, if one does not already exist. * @param keys an object with a key set of the fields desired for the index * @param force if index creation should be forced, even if it is unnecessary */ public final void ensureIndex( final DBObject keys , final boolean force ){ if ( checkReadOnly( false ) ) return; final String name = genIndexName( keys ); boolean doEnsureIndex = false; if ( Math.random() > 0.999 ) doEnsureIndex = true; else if ( ! _createIndexes.contains( name ) ) doEnsureIndex = true; else if ( _anyUpdateSave && ! _createIndexesAfterSave.contains( name ) ) doEnsureIndex = true; if ( ! ( force || doEnsureIndex ) ) return; ensureIndex( keys , name ); _createIndexes.add( name ); if ( _anyUpdateSave ) _createIndexesAfterSave.add( name ); } /** Clear all indices on this collection. */ public void resetIndexCache(){ _createIndexes.clear(); } /** Generate an index name from the set of fields it is over. * @param keys the names of the fields used in this index * @return a string representation of this index's fields */ public static String genIndexName( DBObject keys ){ String name = ""; for ( String s : keys.keySet() ){ if ( name.length() > 0 ) name += "_"; name += s + "_"; Object val = keys.get( s ); if ( val instanceof Number ) name += val.toString().replace( ' ' , '_' ); } return name; } public void setHintFields( List<DBObject> lst ){ _hintFields = lst; } /** Queries for an object in this collection. * @param ref object for which to search * @return an iterator over the results */ public final Iterator<DBObject> find( DBObject ref ){ return find( ref == null ? new BasicDBObject() : ref , null , 0 , 0 ); } public final Iterator<DBObject> find(){ Iterator<DBObject> i = find( new BasicDBObject() , null , 0 , 0 ); if ( i == null ) return (new LinkedList<DBObject>()).iterator(); return i; } public final DBObject findOne(){ return findOne( new BasicDBObject() ); } public final DBObject findOne( DBObject o ){ Iterator<DBObject> i = find( o , null , 0 , 1 ); if ( i == null || ! i.hasNext() ) return null; return i.next(); } /** */ public final ObjectId apply( DBObject o ){ return apply( o , true ); } /** Adds the "private" fields _save, _update, and _id to an object. * @param o object to which to add fields * @param ensureID if an _id field is needed * @return the _id assigned to the object * @throws RuntimeException if <tt>o</tt> is not a DBObject */ public final ObjectId apply( DBObject jo , boolean ensureID ){ ObjectId id = (ObjectId)jo.get( "_id" ); if ( ensureID && id == null ){ id = ObjectId.get(); jo.put( "_id" , id ); } doapply( jo ); return id; } /** Saves an object to this collection executing the preSave function in a given scope. * @param s scope to use (can be null) * @param o the object to save * @return the new object from the collection */ public final DBObject save( DBObject jo ){ if ( checkReadOnly( true ) ) return jo; _checkObject( jo , false , false ); //_findSubObject( s , jo , null ); ObjectId id = null; { Object temp = jo.get( "_id" ); if ( temp != null && ! ( temp instanceof ObjectId ) ) throw new RuntimeException( "_id has to be an ObjectId" ); id = (ObjectId)temp; } if ( DEBUG ) System.out.println( "id : " + id ); if ( id == null || id._new ){ if ( DEBUG ) System.out.println( "saving new object" ); if ( id != null ) id._new = false; doSave( jo ); return jo; } if ( DEBUG ) System.out.println( "doing implicit upsert : " + jo.get( "_id" ) ); DBObject q = new BasicDBObject(); q.put( "_id" , id ); return update( q , jo , true , false ); } // ------ /** Initializes a new collection. * @param base database in which to create the collection * @param name the name of the collection */ protected DBCollection( DBBase base , String name ){ _base = base; _name = name; _fullName = _base.getName() + "." + name; } private final DBObject _checkObject( DBObject o , boolean canBeNull , boolean query ){ if ( o == null ){ if ( canBeNull ) return null; throw new NullPointerException( "can't be null" ); } if ( o.isPartialObject() && ! query ) throw new IllegalArgumentException( "can't save partial objects" ); if ( ! query ){ for ( String s : o.keySet() ){ if ( s.contains( "." ) ) throw new IllegalArgumentException( "fields stored in the db can't have . in them" ); if ( s.contains( "$" ) ) throw new IllegalArgumentException( "fields stored in the db can't have $ in them" ); } } return o; } /* private void _findSubObject( Scope scope , DBObject jo , IdentitySet seenSubs ){ if ( seenSubs == null ) seenSubs = new IdentitySet(); if ( seenSubs.contains( jo ) ) return; seenSubs.add( jo ); if ( DEBUG ) System.out.println( "_findSubObject on : " + jo.get( "_id" ) ); LinkedList<DBObject> toSearch = new LinkedList(); Map<DBObject,String> seen = new IdentityHashMap<DBObject,String>(); toSearch.add( jo ); while ( toSearch.size() > 0 ){ Map<DBObject,String> seenNow = new IdentityHashMap<DBObject,String>( seen ); DBObject n = toSearch.remove(0); for ( String name : n.keySet() ){ Object foo = Bytes.safeGet( n , name ); if ( foo == null ) continue; if ( ! ( foo instanceof DBObject ) ) continue; if ( foo instanceof DBRef ){ DBRef ref = (DBRef)foo; if ( ! ref.isDirty() ) continue; foo = ref.getRealObject(); } if ( foo instanceof JSFunction ) continue; if ( foo instanceof JSString || foo instanceof JSRegex || foo instanceof JSDate ) continue; if ( foo instanceof DBCollection || foo instanceof DBBase ) continue; DBObject e = (DBObject)foo; if ( e instanceof BasicDBObject ) ((BasicDBObject)e).prefunc(); if ( n.get( name ) == null ) continue; if ( e instanceof JSFileChunk ){ _base.getCollection( "_chunks" ).apply( e ); } if ( e.get( "_ns" ) == null ){ if ( seen.containsKey( e ) ) throw new RuntimeException( "you have a loop. key : " + name + " from a " + n.getClass() + " which is a : " + e.getClass() ); seenNow.put( e , "a" ); toSearch.add( e ); continue; } // ok - now we knows its a reference if ( e instanceof BasicDBObject && ((BasicDBObject)e).isPartialObject() ){ // TODO: i think this is correct // this means you have a reference to an object that was retrieved with only some objects // maybe this should do a extend, or throw an exception // but certainly shouldn't overwrite continue; } if ( e.get( "_id" ) == null ){ // new object, lets save it JSFunction otherSave = e.getFunction( "_save" ); if ( otherSave == null ) throw new RuntimeException( "no save :(" ); otherSave.call( scope , e , null ); continue; } // old object, lets update TODO: dirty tracking DBObject lookup = new BasicDBObject(); lookup.set( "_id" , e.get( "_id" ) ); JSFunction otherUpdate = e.getFunction( "_update" ); if ( otherUpdate == null ){ // already taken care of if ( e instanceof DBRef ) continue; throw new RuntimeException( "_update is null class: " + e.getClass().getName() + " keyset : " + e.keySet() + " ns:" + e.get( "_ns" ) ); } if ( e instanceof BasicDBObject && ! ((BasicDBObject)e).isDirty() ) continue; otherUpdate.call( scope , lookup , e , _upsertOptions , seenSubs ); } seen.putAll( seenNow ); } } */ /** Find a collection that is prefixed with this collection's name. * @param n the name of the collection to find * @return the matching collection */ public DBCollection getCollection( String n ){ return _base.getCollection( _name + "." + n ); } /** Returns the name of this collection. * @return the name of this collection */ public String getName(){ return _name; } /** Returns the full name of this collection, with the database name as a prefix. * @return the name of this collection */ public String getFullName(){ return _fullName; } /** Returns the database this collection is a member of. * @return this collection's database */ public DBBase getDB(){ return _base; } /** Returns the database this collection is a member of. * @return this collection's database */ public DBBase getBase(){ return _base; } /** Returns if this collection can be modified. * @return if this collection can be modified */ protected boolean checkReadOnly( boolean strict ){ if ( ! _base._readOnly ) return false; if ( ! strict ) return true; throw new RuntimeException( "db is read only" ); } /** Calculates the hash code for this collection. * @return the hash code */ public int hashCode(){ return _fullName.hashCode(); } /** Checks if this collection is equal to another object. * @param o object with which to compare this collection * @return if the two collections are equal */ public boolean equals( Object o ){ return o == this; } /** Returns name of the collection. * @return name of the collection. */ public String toString(){ return _name; } final DBBase _base; final protected String _name; final protected String _fullName; protected List<DBObject> _hintFields; private boolean _anyUpdateSave = false; private boolean _checkedIdIndex = false; final private Set<String> _createIndexes = new HashSet<String>(); final private Set<String> _createIndexesAfterSave = new HashSet<String>(); private final static DBObject _upsertOptions = BasicDBObjectBuilder.start().add( "upsert" , true ).get(); private final static DBObject _idKey = BasicDBObjectBuilder.start().add( "_id" , ObjectId.get() ).get(); }
drop/dropIndexes
src/main/ed/db/DBCollection.java
drop/dropIndexes
<ide><path>rc/main/ed/db/DBCollection.java <ide> protected abstract void doapply( DBObject o ); <ide> <ide> /** Removes an object from the database collection. <del> * @param id The _id of the object to be removed <ide> * @return -1 <ide> */ <del> public abstract int remove( DBObject id ); <add> public abstract int remove( DBObject o ); <ide> <ide> /** Finds an object by its id. <ide> * @param id the id of the object <ide> DBObject q = new BasicDBObject(); <ide> q.put( "_id" , id ); <ide> return update( q , jo , true , false ); <add> } <add> <add> // ---- DB COMMANDS ---- <add> <add> public void dropIndexes(){ <add> BasicDBObject res = (BasicDBObject)_base.command( BasicDBObjectBuilder.start().add( "deleteIndexes" , getName() ).add( "index" , "*" ).get() ); <add> if ( res.getInt( "ok" , 0 ) != 1 ) <add> throw new RuntimeException( "error dropping indexes : " + res ); <add> <add> resetIndexCache(); <add> } <add> <add> public void drop(){ <add> dropIndexes(); <add> BasicDBObject res = (BasicDBObject)_base.command( BasicDBObjectBuilder.start().add( "drop" , getName() ).get() ); <add> if ( res.getInt( "ok" , 0 ) != 1 ) <add> throw new RuntimeException( "error dropping : " + res ); <ide> } <ide> <ide> // ------
Java
apache-2.0
e77324dec29fee27c77dd107f51a07bbef1848e9
0
bastiaanb/carbon-identity,bastiaanb/carbon-identity,liurl3/carbon-identity,darshanasbg/carbon-identity,laki88/carbon-identity,godwinamila/carbon-identity,JKAUSHALYA/carbon-identity,0xkasun/carbon-identity,johannnallathamby/carbon-identity,jacklotusho/carbon-identity,kesavany/carbon-identity,madurangasiriwardena/carbon-identity,isharak/carbon-identity,thilina27/carbon-identity,dulanjal/carbon-identity,omindu/carbon-identity,hasinthaindrajee/carbon-identity,thilina27/carbon-identity,nuwandi-is/carbon-identity,thusithathilina/carbon-identity,nuwand/carbon-identity,thariyarox/carbon-identity,dulanjal/carbon-identity,kasungayan/carbon-identity,Shakila/carbon-identity,keerthu/carbon-identity,prabathabey/carbon-identity,IsuraD/carbon-identity,virajsenevirathne/carbon-identity,damithsenanayake/carbon-identity,JKAUSHALYA/carbon-identity,prabathabey/carbon-identity,DMHP/carbon-identity,ChamaraPhilipsuom/carbon-identity,ChamaraPhilipsuom/carbon-identity,mefarazath/carbon-identity,thanujalk/carbon-identity,virajsenevirathne/carbon-identity,Niranjan-K/carbon-identity,harsha1979/carbon-identity,ashalya/carbon-identity,hpmtissera/carbon-identity,dracusds123/carbon-identity,laki88/carbon-identity,thanujalk/carbon-identity,liurl3/carbon-identity,wso2/carbon-identity,supunmalinga/carbon-identity,Pushpalanka/carbon-identity,johannnallathamby/carbon-identity,kesavany/carbon-identity,ashalya/carbon-identity,ravihansa3000/carbon-identity,godwinamila/carbon-identity,ashalya/carbon-identity,jacklotusho/carbon-identity,malithie/carbon-identity,mefarazath/carbon-identity,darshanasbg/carbon-identity,Shakila/carbon-identity,hasinthaindrajee/carbon-identity,hasinthaindrajee/carbon-identity,IndunilRathnayake/carbon-identity,dulanjal/carbon-identity,mefarazath/carbon-identity,madurangasiriwardena/carbon-identity,thusithathilina/carbon-identity,nuwandi-is/carbon-identity,chanukaranaba/carbon-identity,ChamaraPhilipsuom/carbon-identity,harsha1979/carbon-identity,dracusds123/carbon-identity,chanukaranaba/carbon-identity,malithie/carbon-identity,damithsenanayake/carbon-identity,pulasthi7/carbon-identity,harsha1979/carbon-identity,jacklotusho/carbon-identity,dracusds123/carbon-identity,hpmtissera/carbon-identity,nuwand/carbon-identity,keerthu/carbon-identity,Niranjan-K/carbon-identity,isharak/carbon-identity,GayanM/carbon-identity,ravihansa3000/carbon-identity,madurangasiriwardena/carbon-identity,Pushpalanka/carbon-identity,uvindra/carbon-identity,pulasthi7/carbon-identity,bastiaanb/carbon-identity,uvindra/carbon-identity,pulasthi7/carbon-identity,omindu/carbon-identity,0xkasun/carbon-identity,kasungayan/carbon-identity,thariyarox/carbon-identity,thusithathilina/carbon-identity,isharak/carbon-identity,0xkasun/carbon-identity,nuwand/carbon-identity,laki88/carbon-identity,chanukaranaba/carbon-identity,JKAUSHALYA/carbon-identity,kesavany/carbon-identity,kasungayan/carbon-identity,damithsenanayake/carbon-identity,uvindra/carbon-identity,liurl3/carbon-identity,DMHP/carbon-identity,hpmtissera/carbon-identity,wso2/carbon-identity,Niranjan-K/carbon-identity,keerthu/carbon-identity,godwinamila/carbon-identity,IsuraD/carbon-identity,nuwandi-is/carbon-identity,Shakila/carbon-identity,IndunilRathnayake/carbon-identity,darshanasbg/carbon-identity,virajsenevirathne/carbon-identity,GayanM/carbon-identity,johannnallathamby/carbon-identity,thilina27/carbon-identity,IsuraD/carbon-identity,ravihansa3000/carbon-identity,wso2/carbon-identity,GayanM/carbon-identity,IndunilRathnayake/carbon-identity,malithie/carbon-identity,DMHP/carbon-identity,prabathabey/carbon-identity,thariyarox/carbon-identity,supunmalinga/carbon-identity,thanujalk/carbon-identity,Pushpalanka/carbon-identity,omindu/carbon-identity,supunmalinga/carbon-identity
/* * Copyright (c) 2014, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.wso2.carbon.identity.application.authenticator.openid.ext.internal; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.osgi.service.component.ComponentContext; import org.wso2.carbon.identity.application.authentication.framework.ApplicationAuthenticator; import org.wso2.carbon.identity.application.authenticator.openid.ext.GoogleOpenIDAuthenticator; import org.wso2.carbon.identity.application.authenticator.openid.ext.YahooOpenIDAuthenticator; /** * @scr.component name="identity.application.authenticator.openid.ext.component" immediate="true" */ public class SampleAuthenticatorServiceComponent { private static Log log = LogFactory.getLog(SampleAuthenticatorServiceComponent.class); protected void activate(ComponentContext ctxt) { GoogleOpenIDAuthenticator googleOpenIDAuthenticator = new GoogleOpenIDAuthenticator(); ctxt.getBundleContext().registerService(ApplicationAuthenticator.class.getName(), googleOpenIDAuthenticator, null); YahooOpenIDAuthenticator yahooOpenIDAuthenticator = new YahooOpenIDAuthenticator(); ctxt.getBundleContext().registerService(ApplicationAuthenticator.class.getName(), yahooOpenIDAuthenticator, null); if (log.isDebugEnabled()) { log.info("Sample Authenticator bundle is activated"); } } protected void deactivate(ComponentContext ctxt) { if (log.isDebugEnabled()) { log.info("Sample Authenticator bundle is deactivated"); } } }
components/application-authenticators/org.wso2.carbon.identity.application.authenticator.openid.ext/src/main/java/org/wso2/carbon/identity/application/authenticator/openid/ext/internal/SampleAuthenticatorServiceComponent.java
/* * Copyright (c) 2014, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.wso2.carbon.identity.application.authenticator.openid.ext.internal; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.osgi.service.component.ComponentContext; import org.wso2.carbon.identity.application.authentication.framework.ApplicationAuthenticator; import org.wso2.carbon.identity.application.authenticator.openid.ext.GoogleOpenIDAuthenticator; import org.wso2.carbon.identity.application.authenticator.openid.ext.YahooOpenIDAuthenticator; import java.util.Hashtable; /** * @scr.component name="identity.application.authenticator.openid.ext.component" immediate="true" */ public class SampleAuthenticatorServiceComponent { private static Log log = LogFactory.getLog(SampleAuthenticatorServiceComponent.class); protected void activate(ComponentContext ctxt) { GoogleOpenIDAuthenticator googleOpenIDAuthenticator = new GoogleOpenIDAuthenticator(); ctxt.getBundleContext().registerService(ApplicationAuthenticator.class.getName(), googleOpenIDAuthenticator, null); YahooOpenIDAuthenticator yahooOpenIDAuthenticator = new YahooOpenIDAuthenticator(); ctxt.getBundleContext().registerService(ApplicationAuthenticator.class.getName(), yahooOpenIDAuthenticator, null); if (log.isDebugEnabled()) { log.info("Sample Authenticator bundle is activated"); } } protected void deactivate() { if (log.isDebugEnabled()) { log.info("Sample Authenticator bundle is deactivated"); } } }
code quality improvement oidc ext
components/application-authenticators/org.wso2.carbon.identity.application.authenticator.openid.ext/src/main/java/org/wso2/carbon/identity/application/authenticator/openid/ext/internal/SampleAuthenticatorServiceComponent.java
code quality improvement oidc ext
<ide><path>omponents/application-authenticators/org.wso2.carbon.identity.application.authenticator.openid.ext/src/main/java/org/wso2/carbon/identity/application/authenticator/openid/ext/internal/SampleAuthenticatorServiceComponent.java <ide> import org.wso2.carbon.identity.application.authenticator.openid.ext.GoogleOpenIDAuthenticator; <ide> import org.wso2.carbon.identity.application.authenticator.openid.ext.YahooOpenIDAuthenticator; <ide> <del>import java.util.Hashtable; <ide> <ide> /** <ide> * @scr.component name="identity.application.authenticator.openid.ext.component" immediate="true" <ide> } <ide> } <ide> <del> protected void deactivate() { <add> protected void deactivate(ComponentContext ctxt) { <ide> if (log.isDebugEnabled()) { <ide> log.info("Sample Authenticator bundle is deactivated"); <ide> }
JavaScript
mit
7481d632174782ca5c696bc4a00c92d238011656
0
lukecahill/Note-keeper,lukecahill/Note-keeper,lukecahill/Note-keeper
(function() { // load the available notes and tags. var showingComplete = false; var $noteList = $('#note-list'); var $completedNoteButton = $('#complete-notes-button'); var $newNoteSection = $('#new-note-section'); var $tagChooser = $('#tag-chooser'); var $noteTags = $('#add-note-tags'); var color = 'red'; var dropdownTags = []; // configuration for toastr notificiations. toastr.options = { "timeOut": "2000", "preventDuplicates": false, "closeButton": true }; var initialLoad = { userId : userId, complete: 0, action: 'loadnote', auth: auth }; loadNotes(initialLoad); /** * @function String format * * Add functionality to String object, for C# style string formatting. * Usage: "{0} is dead, but {1} is alive! {0} {2}".format("ASP", "ASP.NET") * From; http://stackoverflow.com/a/4673436 **/ if (!String.prototype.format) { String.prototype.format = function() { var args = arguments; return this.replace(/{(\d+)}/g, function(match, number) { return typeof args[number] != 'undefined' ? args[number] : match; }); }; } /** * @function loadNotes * * Load the notes from the database * @param {object} toSend **/ function loadNotes(toSend) { $.ajax({ url: 'includes/load-note.php', method: 'POST', data: toSend, action: 'loadnote' }) .done(function(data, result) { loadNotesSuccess(data, result, toSend); }) .fail(function(error) { console.log('It failed: ', error); }); } /** * @function loadNotesSuccess * * Function which occurs when the loading of the from the database is successful. * @param {object} data * @param {string} result * @param {object} toSend **/ function loadNotesSuccess(data, result, toSend) { if(result === 'success') { if(toSend.action === 'searchnote') { $noteList.empty(); } data = $.parseJSON(data); if(data !== 'none' && data !== 'no_results') { $('#no-results').remove(); if(toSend.complete === 0) { $noteTags.empty(); $.each(data[0], function(index, value) { $noteTags.append('<div class="checkbox"><label><input type="checkbox" name="new-tag" data-tag="{0}" value="{0}">{0}</label></div>'.format(value)); }); } $tagChooser.empty(); $tagChooser.append($('<option></option>').attr('value', 'showall').attr('selected', true).text('-- Show all --')); $.each(data[1], function(key, value) { $tagChooser .append($('<option></option>') .attr('value', value) .attr('data-tag', value) .text(value)); dropdownTags.push(value); }); buildNote(data[2]); color = data[3]; } else if(data === 'no_results') { // no search results found $noteList.append('<p id="no-results">No note with that search could be found!</p>'); } else { $noteList.append('<p id="first-note">It appears that you have not yet created any notes. Create your first one.</p>'); } if(toSend.complete !== 1) { $completedNoteButton.html('<span class="glyphicon glyphicon-asterisk"></span>'); } else { $completedNoteButton.html('<span class="glyphicon glyphicon-asterisk"></span>'); } } } /** * @function searchNotes * * Searches the notes in the database * @param {string} search **/ function searchNotes(search) { var data = { userId: userId, complete: 0, action: 'searchnote', search: search, auth: auth }; loadNotes(data); } /** * @function addTag * * Add a new checkbox for tags to the DOM * @param {string} where * @param {string} input * @param {bool} edit **/ function addTag(where, input, edit) { var newTag = $(input).val(); if(newTag.trim() !== '') { if(edit === 1) { $(where).append('<div class="checkbox"><label><input type="checkbox" checked name="edit-tag" data-tag="{0}" value="{0}">{0}</label></div>'.format(newTag)); } else if(edit === 0) { $(where).append('<div class="checkbox"><label><input type="checkbox" checked name="new-tag" data-tag="{0}" value="{0}">{0}</label></div>'.format(newTag)); } else if(edit === 2) { $(where).append('<div class="checkbox new-note-checkbox"><label><input type="checkbox" checked name="new-tag" data-tag="{0}" value="{0}">{0}</label></div>'.format(newTag)); } $(input).val(''); } } /** * @function showTags * * Show all of the notes with the same tag as the one chosen * @param {string} tag **/ function showTags(tag) { var notes = $('.note'); var hide = []; $('.note').show(); tag = tag.toLowerCase(); $.each(notes, function(index, value) { $value = $(value); var tags = $value.find('.note-tags'); var tagData = []; $.each(tags, function(i, childTag) { $this = $(childTag); var data = $this.data('tag'); tagData.push(data.toLowerCase()); }); if(tagData.indexOf(tag) === -1) { hide.push(value); } }); $.each(hide, function(index, value) { $(value).hide(); }); toastr.info('Showing all notes with the tag "{0}"'.format(tag)); } /** * @function buildNote * * Build the note and then append it to the DOMs notelist * @param {object} data **/ function buildNote(data) { var note = ''; $.each(data, function(index, value) { note = '<div class="note" data-id="{0}">'.format(value.id); note += '<h4 class="note-title">{0}</h4><p class="note-text">{1}</p>'.format(value.title, value.text); if(data[index][0].length > 0) { note += '<div class="tag-container">'; $.each(data[index][0], function(i, v) { note += '<span class="note-tags note-tags-{0}" title="Click to show all notes with this tag." data-tag="{1}">{1}</span>'.format(value.color, v); }); note += '</div>'; } if(value.complete === '0') { if(data[index][0].length > 0) { note += '<div class="note-glyphicons"><span class="glyphicon glyphicon-remove remove-note" title="Delete this note"></span>'; } else { note += '<div class="note-glyphicons note-glyphicons-empty"><span class="glyphicon glyphicon-remove remove-note" title="Delete this note"></span>'; } note += '<span class="glyphicon glyphicon-edit edit-note" title="Edit this note"></span><span class="glyphicon glyphicon-ok note-done" title="Mark as done"></span></div>'; } else { note +='<div class="note-glyphicons"><span class="glyphicon glyphicon-remove remove-note" title="Delete this note"></span>'; note += '<span class="glyphicon glyphicon-asterisk mark-note-active" title="Mark as active"></span></div>'; } $noteList.append(note); }); } /** * @function * * Hide these sections until they are clicked to show **/ $('.note-text-validation, .edit-note-text-validation, #search-input, #tag-chooser-input').hide(); $newNoteSection.hide(); /** * @function * * Show the section to add a new note **/ $('#new-note-button').on('click', function(){ $newNoteSection.toggle(); }); /** * @function * * The function which is run to add a new note to the database. * Also then appends the note to the DOM - this could be changed to refresh the whole DOM via AJAX instead. * Hides the new note section after success. **/ $('#add-note-button').on('click', function() { var noteText = $('#add-note-text').val(); var noteTitle = $('#add-note-title').val(); var tagArray = []; if(noteText.trim() === '' && noteTitle.trim() === '') { $('.note-text-validation').show(); return; } $('input:checkbox[name=new-tag]:checked').each(function() { tagArray.push($(this).val()); }); $.ajax({ url: 'includes/note-api.php', method: 'POST', data: { noteText: noteText, noteTags: tagArray, noteTitle: noteTitle, userId: userId, action: 'addnote' } }) .done(function(data, result) { var tags = ''; $.each(tagArray, function(index, value) { tags += '<span class="note-tags note-tags-{0}" title="Click to show all notes with this tag." data-tag="{1}">{1}</span>'.format(color, value); }); noteText = noteText.replace(/\n/g, '<br>'); $noteList.append('<div class="note" data-id="{0}"><h4 class="note-title">{1}</h4><p class="note-text">{2}</p>{3}<div class="note-glyphicons"><span class="glyphicon glyphicon-remove remove-note" title="Delete this note"></span><span class="glyphicon glyphicon-edit edit-note" title="Edit this note"></span><span class="glyphicon glyphicon-ok note-done" title="Mark as done"></span></div></div>'.format(data, noteTitle, noteText, tags)); // Reset and confirmation. $('#add-note-title').val(''); $('#add-note-text').val(''); $('input:checkbox[name=new-tag]').removeAttr('checked'); $('.new-note-checkbox').remove(); $('#first-note').remove(); tagsToAdd = []; toastr.success('Note has been added successfully!'); $newNoteSection.hide(); }) .fail(function(error) { console.log('There was a failure: ', error); }); }); $('#show-new-tag-button').on('click', function() { addTag('#add-note-tags', '#add-new-tag-text', 2); }); $('#edit-new-tag-button').on('click', function() { addTag('#edit-note-tags', '#edit-new-tag-text', 1); }); /** * @function * * Allow the user to click on the notes tags to show notes with the same tag. * This will run the showTags() function. **/ $noteList.on('click', '.note-tags', function() { var tag = $(this).data('tag'); showTags(tag); }); /** * @function * * Function to run when the user clicks to delete the note. * This will both remove the note from the database and the DOM. **/ $noteList.on('click', '.remove-note', function() { if(!confirm('Are you sure you wish to remove this note?')) { return; } $this = $(this); var deleteId = $this.closest('.note').data('id'); $.ajax({ method: 'POST', url: 'includes/note-api.php', data: { deleteNote: deleteId, action: 'deletenote' } }) .done(function(data, result) { $this.closest('.note').remove(); toastr.success('Note has been deleted!'); }) .fail(function(error) { console.log('An error has occurred: ', error); }); }); /** * @function * * Function to run when the user clicks to edit the note. * This will show a modal which contains the note information for editing. * This will both edit the note in the database and the DOM. **/ $noteList.on('click', '.edit-note', function() { $this = $(this); var noteId = $this.closest('.note').data('id'); $('#save-note-button').data('id', noteId); var parent = $this.closest('.note'); var $parent = $(parent); var title = $parent.find('.note-title')[0].textContent; var text = $parent.find('.note-text')[0].textContent; var tags = $parent.find('.note-tags'); var tagArray = []; $.each(tags, function(index, value) { tagArray.push(value.textContent); }); $('#note-edit-modal').modal('show'); $('#edit-note-tags').empty(); $('#edit-note-title').val(title); $('#edit-note-text').val(text); $.each(tagArray, function(index, value) { $('#edit-note-tags').append('<div class="checkbox"><label><input type="checkbox" checked name="edit-tag" data-tag="{0}" value="{0}">{0}</label></div>'.format(value)); }); }); /** * @function * * Mark the note as complete in the database. * This note will then not appear on the active notes screen. **/ $noteList.on('click', '.note-done', function() { $this = $(this); var noteId = $this.closest('.note').data('id'); $.ajax({ method: 'POST', url: 'includes/note-done.php', data: { noteId: noteId, complete: 1 } }) .done(function(data, result) { $this.closest('.note').remove(); toastr.success('Note marked as complete!'); }) .fail(function(error) { console.log('An error has occurred: ', error); }); }); /** * @function * * Toggle to show the active or completed notes. **/ $completedNoteButton.on('click', function() { var data = { userId : userId, complete: 0, action: 'loadnote', auth: auth }; if(showingComplete) { $noteList.empty(); showingComplete = false; data.complete = 0; loadNotes(data); } else { $noteList.empty(); showingComplete = true; data.complete = 1; loadNotes(data); } }); /** * @function * * Remove a note from the completed notes section, and mark it as active. **/ $noteList.on('click', '.mark-note-active', function() { $this = $(this); var noteId = $this.closest('.note').data('id'); $.ajax({ method: 'POST', url: 'includes/note-done.php', data: { noteId: noteId, complete: 0 } }) .done(function(data, result) { $this.closest('.note').remove(); toastr.success('Note marked as active!'); }) .fail(function(error) { console.log('An error has occurred: ', error); }); }); /** * @function * * Save the note after editing via the modal. **/ $('#save-note-button').on('click', function() { var title = $('#edit-note-title').val(); var text = $('#edit-note-text').val(); var tagArray = []; var noteId = $('#save-note-button').data('id'); $('input:checkbox[name=edit-tag]:checked').each(function() { tagArray.push($(this).val()); }); $.ajax({ method: 'POST', url: 'includes/note-api.php', data: { noteText: text, noteId: noteId, noteTitle: title, noteTags: tagArray, action: 'editnote' } }) .done(function(data, result) { // update the DOM here. var note = $('[data-id="' + noteId + '"]'); $(note).children('.note-title')[0].textContent = title; $(note).children('.note-text')[0].textContent = text; var newText = $(note).children('.note-text')[0]; $(note).find('.note-tags').remove(); var tags = ''; $.each(tagArray, function(index, value) { tags += '<span class="note-tags note-tags-{0}" title="Click to show all notes with this tag." data-tag="{1}">{1}</span>'.format(color, value); }); $(newText).after(tags); $('#note-edit-modal').modal('hide'); toastr.success('Note successfully updated!'); }) .fail(function(error) { console.log('An error has occurred: ', error); }); }); /** * @function * * Fired when an option in the dropdown is chosen. * Will show all notes with the chosen tag, or all if they have chosen to show all. **/ $('#tag-chooser').on('change', function() { var value = this.value; if(value !== 'showall') { showTags(this.value); } else { $('.note').show(); toastr.info('Showing all notes'); } }); /** * @function * * Fired when the search button is clicked. * Passes the value to the searchNotes function. **/ $('#search-note-button').on('click', function() { var text = $('#search-note-text').val(); searchNotes(text); }); /** * @function * * Fire the searchNotes function when the return key is pressed in the search note input * @param {event} event **/ $('#search-note-text').on('keyup', function(event) { if(event.keyCode == 13) { var text = $('#search-note-text').val(); searchNotes(text); } }); /** * @function * * Fire the searchNotes function when the return key is pressed in the search note input box * @param {event} event **/ $('#show-search-button').on('click', function() { $('#search-input').toggle(); $('#tag-chooser-input').hide(); }); /** * @function * * Fire the searchNotes function when the return key is pressed in the search note input box * @param {event} event **/ $('#show-tag-chooser-button').on('click', function() { $('#search-input').hide(); $('#tag-chooser-input').toggle(); }); /** * @function * * Delegate to show the edit modal. **/ $noteList.on('click', '#note-edit-modal', function() { $('#note-edit-modal').show(); }); /** * @function * * Hides the section to add a new note when the close button is clicked. **/ $('#close-new-note').on('click', function() { $newNoteSection.hide(); }); /** * @function * * Hides the validate notice displayed on the note text input when a character is entered **/ $('#add-note-text').on('keyup', function() { $('.note-text-validation').hide(); }); /** * @function * * Hides the validate notice displayed on the edit note text input when a character is entered **/ $('#edit-note-text').on('keyup', function() { $('.edit-note-text-validation').hide(); }); /** * @function * * Fire the searchNotes function when the return key is pressed in the add new tag input box * @param {event} event **/ $('#add-new-tag-text').on('keyup', function(event) { if(event.keyCode == 13) { addTag('#add-note-tags', '#add-new-tag-text', 2); } }); /** * @function * * Fire the searchNotes function when the return key is pressed in the edit note tag input box * @param {event} event **/ $('#edit-new-tag-text').on('keyup', function(event) { if(event.keyCode == 13) { addTag('#edit-note-tags', '#edit-new-tag-text', 1); } }); /** * @function * * Refresh the note list - empties the DOM notelist * Then fires the loadNotes() function to re-populate the DOM **/ $('#refresh-button').on('click', function() { $noteList.empty(); $('.checkbox').remove(); loadNotes(initialLoad); }); })();
js/script.js
(function() { // load the available notes and tags. var showingComplete = false; var $noteList = $('#note-list'); var $completedNoteButton = $('#complete-notes-button'); var $newNoteSection = $('#new-note-section'); var $tagChooser = $('#tag-chooser'); var $noteTags = $('#add-note-tags'); var color = 'red'; // configuration for toastr notificiations. toastr.options = { "timeOut": "2000", "preventDuplicates": false, "closeButton": true }; var initialLoad = { userId : userId, complete: 0, action: 'loadnote', auth: auth }; loadNotes(initialLoad); /** * @function String format * * Add functionality to String object, for C# style string formatting. * Useage: "{0} is dead, but {1} is alive! {0} {2}".format("ASP", "ASP.NET") * From; http://stackoverflow.com/a/4673436 **/ if (!String.prototype.format) { String.prototype.format = function() { var args = arguments; return this.replace(/{(\d+)}/g, function(match, number) { return typeof args[number] != 'undefined' ? args[number] : match; }); }; } /** * @function loadNotes * * Load the notes from the database * @param {object} toSend **/ function loadNotes(toSend) { $.ajax({ url: 'includes/load-note.php', method: 'POST', data: toSend, action: 'loadnote' }) .done(function(data, result) { loadNotesSuccess(data, result, toSend); }) .fail(function(error) { console.log('It failed: ', error); }); } /** * @function loadNotesSuccess * * Function which occurs when the loading of the from the database is successful. * @param {object} data * @param {string} result * @param {object} toSend **/ function loadNotesSuccess(data, result, toSend) { if(result === 'success') { if(toSend.action === 'searchnote') { $noteList.empty(); } data = $.parseJSON(data); if(data !== 'none' && data !== 'no_results') { $('#no-results').remove(); if(toSend.complete === 0) { $noteTags.empty(); $.each(data[0], function(index, value) { $noteTags.append('<div class="checkbox"><label><input type="checkbox" name="new-tag" data-tag="{0}" value="{0}">{0}</label></div>'.format(value)); }); } $tagChooser.empty(); $tagChooser.append($('<option></option>').attr('value', 'showall').attr('selected', true).text('-- Show all --')); $.each(data[1], function(key, value) { $tagChooser .append($('<option></option>') .attr('value', value) .attr('data-tag', value) .text(value)); }); buildNote(data[2]); color = data[3]; } else if(data === 'no_results') { // no search results found $noteList.append('<p id="no-results">No note with that search could be found!</p>'); } else { $noteList.append('<p id="first-note">It appears that you have not yet created any notes. Create your first one.</p>'); } if(toSend.complete !== 1) { $completedNoteButton.html('<span class="glyphicon glyphicon-asterisk"></span>'); } else { $completedNoteButton.html('<span class="glyphicon glyphicon-asterisk"></span>'); } } } /** * @function searchNotes * * Searches the notes in the database * @param {string} search **/ function searchNotes(search) { var data = { userId: userId, complete: 0, action: 'searchnote', search: search, auth: auth }; loadNotes(data); } /** * @function addTag * * Add a new checkbox for tags to the DOM * @param {string} where * @param {string} input * @param {bool} edit **/ function addTag(where, input, edit) { var newTag = $(input).val(); if(newTag.trim() !== '') { if(edit === 1) { $(where).append('<div class="checkbox"><label><input type="checkbox" checked name="edit-tag" data-tag="{0}" value="{0}">{0}</label></div>'.format(newTag)); } else if(edit === 0) { $(where).append('<div class="checkbox"><label><input type="checkbox" checked name="new-tag" data-tag="{0}" value="{0}">{0}</label></div>'.format(newTag)); } else if(edit === 2) { $(where).append('<div class="checkbox new-note-checkbox"><label><input type="checkbox" checked name="new-tag" data-tag="{0}" value="{0}">{0}</label></div>'.format(newTag)); } $(input).val(''); } } /** * @function showTags * * Show all of the notes with the same tag as the one chosen * @param {string} tag **/ function showTags(tag) { var notes = $('.note'); var hide = []; $('.note').show(); tag = tag.toLowerCase(); $.each(notes, function(index, value) { $value = $(value); var tags = $value.find('.note-tags'); var tagData = []; $.each(tags, function(i, childTag) { $this = $(childTag); var data = $this.data('tag'); tagData.push(data.toLowerCase()); }); if(tagData.indexOf(tag) === -1) { hide.push(value); } }); $.each(hide, function(index, value) { $(value).hide(); }); toastr.info('Showing all notes with the tag "{0}"'.format(tag)); } /** * @function buildNote * * Build the note and then append it to the DOMs notelist * @param {object} data **/ function buildNote(data) { var note = ''; $.each(data, function(index, value) { note = '<div class="note" data-id="{0}">'.format(value.id); note += '<h4 class="note-title">{0}</h4><p class="note-text">{1}</p>'.format(value.title, value.text); if(data[index][0].length > 0) { note += '<div class="tag-container">'; $.each(data[index][0], function(i, v) { note += '<span class="note-tags note-tags-{0}" title="Click to show all notes with this tag." data-tag="{1}">{1}</span>'.format(value.color, v); }); note += '</div>'; } if(value.complete === '0') { if(data[index][0].length > 0) { note += '<div class="note-glyphicons"><span class="glyphicon glyphicon-remove remove-note" title="Delete this note"></span>'; } else { note += '<div class="note-glyphicons note-glyphicons-empty"><span class="glyphicon glyphicon-remove remove-note" title="Delete this note"></span>'; } note += '<span class="glyphicon glyphicon-edit edit-note" title="Edit this note"></span><span class="glyphicon glyphicon-ok note-done" title="Mark as done"></span></div>'; } else { note +='<div class="note-glyphicons"><span class="glyphicon glyphicon-remove remove-note" title="Delete this note"></span>'; note += '<span class="glyphicon glyphicon-asterisk mark-note-active" title="Mark as active"></span></div>'; } $noteList.append(note); }); } /** * @function * * Hide these sections until they are clicked to show **/ $('.note-text-validation, .edit-note-text-validation, #search-input, #tag-chooser-input').hide(); $newNoteSection.hide(); /** * @function * * Show the section to add a new note **/ $('#new-note-button').on('click', function(){ $newNoteSection.toggle(); }); /** * @function * * The function which is run to add a new note to the database. * Also then appends the note to the DOM - this could be changed to refresh the whole DOM via AJAX instead. * Hides the new note section after success. **/ $('#add-note-button').on('click', function() { var noteText = $('#add-note-text').val(); var noteTitle = $('#add-note-title').val(); var tagArray = []; if(noteText.trim() === '' && noteTitle.trim() === '') { $('.note-text-validation').show(); return; } $('input:checkbox[name=new-tag]:checked').each(function() { tagArray.push($(this).val()); }); $.ajax({ url: 'includes/note-api.php', method: 'POST', data: { noteText: noteText, noteTags: tagArray, noteTitle: noteTitle, userId: userId, action: 'addnote' } }) .done(function(data, result) { var tags = ''; $.each(tagArray, function(index, value) { tags += '<span class="note-tags note-tags-{0}" title="Click to show all notes with this tag." data-tag="{1}">{1}</span>'.format(color, value); }); noteText = noteText.replace(/\n/g, '<br>'); $noteList.append('<div class="note" data-id="{0}"><h4 class="note-title">{1}</h4><p class="note-text">{2}</p>{3}<div class="note-glyphicons"><span class="glyphicon glyphicon-remove remove-note" title="Delete this note"></span><span class="glyphicon glyphicon-edit edit-note" title="Edit this note"></span><span class="glyphicon glyphicon-ok note-done" title="Mark as done"></span></div></div>'.format(data, noteTitle, noteText, tags)); // Reset and confirmation. $('#add-note-title').val(''); $('#add-note-text').val(''); $('input:checkbox[name=new-tag]').removeAttr('checked'); $('.new-note-checkbox').remove(); $('#first-note').remove(); tagsToAdd = []; toastr.success('Note has been added successfully!'); $newNoteSection.hide(); }) .fail(function(error) { console.log('There was a failure: ', error); }); }); $('#show-new-tag-button').on('click', function() { addTag('#add-note-tags', '#add-new-tag-text', 2); }); $('#edit-new-tag-button').on('click', function() { addTag('#edit-note-tags', '#edit-new-tag-text', 1); }); /** * @function * * Allow the user to click on the notes tags to show notes with the same tag. * This will run the showTags() function. **/ $noteList.on('click', '.note-tags', function() { var tag = $(this).data('tag'); showTags(tag); }); /** * @function * * Function to run when the user clicks to delete the note. * This will both remove the note from the database and the DOM. **/ $noteList.on('click', '.remove-note', function() { if(!confirm('Are you sure you wish to remove this note?')) { return; } $this = $(this); var deleteId = $this.closest('.note').data('id'); $.ajax({ method: 'POST', url: 'includes/note-api.php', data: { deleteNote: deleteId, action: 'deletenote' } }) .done(function(data, result) { $this.closest('.note').remove(); toastr.success('Note has been deleted!'); }) .fail(function(error) { console.log('An error has occurred: ', error); }); }); /** * @function * * Function to run when the user clicks to edit the note. * This will show a modal which contains the note information for editing. * This will both edit the note in the database and the DOM. **/ $noteList.on('click', '.edit-note', function() { $this = $(this); var noteId = $this.closest('.note').data('id'); $('#save-note-button').data('id', noteId); var parent = $this.closest('.note'); var $parent = $(parent); var title = $parent.find('.note-title')[0].textContent; var text = $parent.find('.note-text')[0].textContent; var tags = $parent.find('.note-tags'); var tagArray = []; $.each(tags, function(index, value) { tagArray.push(value.textContent); }); $('#note-edit-modal').modal('show'); $('#edit-note-tags').empty(); $('#edit-note-title').val(title); $('#edit-note-text').val(text); $.each(tagArray, function(index, value) { $('#edit-note-tags').append('<div class="checkbox"><label><input type="checkbox" checked name="edit-tag" data-tag="{0}" value="{0}">{0}</label></div>'.format(value)); }); }); /** * @function * * Mark the note as complete in the database. * This note will then not appear on the active notes screen. **/ $noteList.on('click', '.note-done', function() { $this = $(this); var noteId = $this.closest('.note').data('id'); $.ajax({ method: 'POST', url: 'includes/note-done.php', data: { noteId: noteId, complete: 1 } }) .done(function(data, result) { $this.closest('.note').remove(); toastr.success('Note marked as complete!'); }) .fail(function(error) { console.log('An error has occurred: ', error); }); }); /** * @function * * Toggle to show the active or completed notes. **/ $completedNoteButton.on('click', function() { var data = { userId : userId, complete: 0, action: 'loadnote', auth: auth }; if(showingComplete) { $noteList.empty(); showingComplete = false; data.complete = 0; loadNotes(data); } else { $noteList.empty(); showingComplete = true; data.complete = 1; loadNotes(data); } }); /** * @function * * Remove a note from the completed notes section, and mark it as active. **/ $noteList.on('click', '.mark-note-active', function() { $this = $(this); var noteId = $this.closest('.note').data('id'); $.ajax({ method: 'POST', url: 'includes/note-done.php', data: { noteId: noteId, complete: 0 } }) .done(function(data, result) { $this.closest('.note').remove(); toastr.success('Note marked as active!'); }) .fail(function(error) { console.log('An error has occurred: ', error); }); }); /** * @function * * Save the note after editing via the modal. **/ $('#save-note-button').on('click', function() { var title = $('#edit-note-title').val(); var text = $('#edit-note-text').val(); var tagArray = []; var noteId = $('#save-note-button').data('id'); $('input:checkbox[name=edit-tag]:checked').each(function() { tagArray.push($(this).val()); }); $.ajax({ method: 'POST', url: 'includes/note-api.php', data: { noteText: text, noteId: noteId, noteTitle: title, noteTags: tagArray, action: 'editnote' } }) .done(function(data, result) { // update the DOM here. var note = $('[data-id="' + noteId + '"]'); $(note).children('.note-title')[0].textContent = title; $(note).children('.note-text')[0].textContent = text; var newText = $(note).children('.note-text')[0]; $(note).find('.note-tags').remove(); var tags = ''; $.each(tagArray, function(index, value) { tags += '<span class="note-tags note-tags-{0}" title="Click to show all notes with this tag." data-tag="{1}">{1}</span>'.format(color, value); }); $(newText).after(tags); $('#note-edit-modal').modal('hide'); toastr.success('Note successfully updated!'); }) .fail(function(error) { console.log('An error has occurred: ', error); }); }); /** * @function * * Fired when an option in the dropdown is chosen. * Will show all notes with the chosen tag, or all if they have chosen to show all. **/ $('#tag-chooser').on('change', function() { var value = this.value; if(value !== 'showall') { showTags(this.value); } else { $('.note').show(); toastr.info('Showing all notes'); } }); /** * @function * * Fired when the search button is clicked. * Passes the value to the searchNotes function. **/ $('#search-note-button').on('click', function() { var text = $('#search-note-text').val(); searchNotes(text); }); /** * @function * * Fire the searchNotes function when the return key is pressed in the search note input * @param {event} event **/ $('#search-note-text').on('keyup', function(event) { if(event.keyCode == 13) { var text = $('#search-note-text').val(); searchNotes(text); } }); /** * @function * * Fire the searchNotes function when the return key is pressed in the search note input box * @param {event} event **/ $('#show-search-button').on('click', function() { $('#search-input').toggle(); //$tagChooser.toggle(); //$('label[for=tag-chooser').toggle(); $('#tag-chooser-input').hide(); }); /** * @function * * Fire the searchNotes function when the return key is pressed in the search note input box * @param {event} event **/ $('#show-tag-chooser-button').on('click', function() { $('#search-input').hide(); $('#tag-chooser-input').toggle(); }); /** * @function * * Delegate to show the edit modal. **/ $noteList.on('click', '#note-edit-modal', function() { $('#note-edit-modal').show(); }); /** * @function * * Hides the section to add a new note when the close button is clicked. **/ $('#close-new-note').on('click', function() { $newNoteSection.hide(); }); /** * @function * * Hides the validate notice displayed on the note text input when a character is entered **/ $('#add-note-text').on('keyup', function() { $('.note-text-validation').hide(); }); /** * @function * * Hides the validate notice displayed on the edit note text input when a character is entered **/ $('#edit-note-text').on('keyup', function() { $('.edit-note-text-validation').hide(); }); /** * @function * * Fire the searchNotes function when the return key is pressed in the add new tag input box * @param {event} event **/ $('#add-new-tag-text').on('keyup', function(event) { if(event.keyCode == 13) { addTag('#add-note-tags', '#add-new-tag-text', 2); } }); /** * @function * * Fire the searchNotes function when the return key is pressed in the edit note tag input box * @param {event} event **/ $('#edit-new-tag-text').on('keyup', function(event) { if(event.keyCode == 13) { addTag('#edit-note-tags', '#edit-new-tag-text', 1); } }); /** * @function * * Refresh the note list - empties the DOM notelist * Then fires the loadNotes() function to re-populate the DOM **/ $('#refresh-button').on('click', function() { $noteList.empty(); $('.checkbox').remove(); loadNotes(initialLoad); }); })();
Remove old code. Add dropdown items to array for future use
js/script.js
Remove old code. Add dropdown items to array for future use
<ide><path>s/script.js <ide> var $tagChooser = $('#tag-chooser'); <ide> var $noteTags = $('#add-note-tags'); <ide> var color = 'red'; <add> var dropdownTags = []; <ide> <ide> // configuration for toastr notificiations. <ide> toastr.options = { <ide> * @function String format <ide> * <ide> * Add functionality to String object, for C# style string formatting. <del> * Useage: "{0} is dead, but {1} is alive! {0} {2}".format("ASP", "ASP.NET") <add> * Usage: "{0} is dead, but {1} is alive! {0} {2}".format("ASP", "ASP.NET") <ide> * From; http://stackoverflow.com/a/4673436 <ide> **/ <ide> if (!String.prototype.format) { <ide> .attr('value', value) <ide> .attr('data-tag', value) <ide> .text(value)); <add> dropdownTags.push(value); <ide> }); <ide> <ide> buildNote(data[2]); <ide> **/ <ide> $('#show-search-button').on('click', function() { <ide> $('#search-input').toggle(); <del> //$tagChooser.toggle(); <del> //$('label[for=tag-chooser').toggle(); <ide> $('#tag-chooser-input').hide(); <ide> }); <ide>
Java
mit
error: pathspec 'tests.java' did not match any file(s) known to git
007f7c0ab55e435e68e15d44c80ffd9316f6a30f
1
jonnysdavis/textedu
//no comment
tests.java
Create tests.java
tests.java
Create tests.java
<ide><path>ests.java <add>//no comment
Java
apache-2.0
f87be0e4f37b38bb5e22207cca2b22c64bad39d5
0
SpineEventEngine/base,SpineEventEngine/base,SpineEventEngine/base
/* * Copyright 2019, TeamDev. All rights reserved. * * Redistribution and use in source and/or binary forms, with or without * modification, must retain the above copyright notice and the following * disclaimer. * * 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 io.spine.code.proto; import com.google.common.base.Objects; import com.google.errorprone.annotations.Immutable; import com.google.protobuf.Descriptors.GenericDescriptor; import com.google.protobuf.Message; import io.spine.annotation.Internal; import io.spine.code.java.ClassName; import io.spine.code.java.PackageName; import io.spine.code.java.SimpleClassName; import io.spine.type.TypeName; import io.spine.type.TypeUrl; import io.spine.type.UnknownTypeException; import static com.google.common.base.Preconditions.checkNotNull; /** * A Protobuf type, such as a message or an enum. * * @param <T> the type of the type descriptor * @param <P> the type of the proto message of the descriptor */ @Immutable(containerOf = {"T", "P"}) @Internal public abstract class Type<T extends GenericDescriptor, P extends Message> { private final T descriptor; private final boolean supportsBuilders; protected Type(T descriptor, boolean supportsBuilders) { this.descriptor = checkNotNull(descriptor); this.supportsBuilders = supportsBuilders; } /** * Obtains the descriptor of the type. */ public T descriptor() { return this.descriptor; } /** * Obtains the proto message of the type descriptor. */ public abstract P toProto(); /** * Obtains the {@linkplain TypeName name} of this type. */ public TypeName name() { return url().toName(); } /** * Obtains the {@link TypeUrl} of this type. */ public abstract TypeUrl url(); /** * Loads the Java class representing this Protobuf type. */ public Class<?> javaClass() { String clsName = javaClassName().value(); try { return Class.forName(clsName); } catch (ClassNotFoundException e) { throw new UnknownTypeException(descriptor.getName(), e); } } /** * Obtains the name of the Java class representing this Protobuf type. */ public abstract ClassName javaClassName(); /** * Obtains package for the corresponding Java type. */ public PackageName javaPackage() { PackageName result = PackageName.resolve(descriptor.getFile() .toProto()); return result; } /** * Obtains simple class name for corresponding Java type. */ public abstract SimpleClassName simpleJavaClassName(); /** * Defines whether or not the Java class generated from this type has a builder. * * @return {@code true} if the generated Java class has corresponding * {@link com.google.protobuf.Message.Builder} and * {@link com.google.protobuf.MessageOrBuilder} */ public final boolean supportsBuilders() { return supportsBuilders; } /** * Returns a fully-qualified name of the proto type. */ @Override public String toString() { return descriptor.getFullName(); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (!(o instanceof Type)) { return false; } Type<?, ?> type = (Type<?, ?>) o; return Objects.equal(descriptor.getFullName(), type.descriptor.getFullName()); } @Override public int hashCode() { return Objects.hashCode(descriptor); } }
base/src/main/java/io/spine/code/proto/Type.java
/* * Copyright 2019, TeamDev. All rights reserved. * * Redistribution and use in source and/or binary forms, with or without * modification, must retain the above copyright notice and the following * disclaimer. * * 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 io.spine.code.proto; import com.google.common.base.Objects; import com.google.errorprone.annotations.Immutable; import com.google.protobuf.Descriptors; import com.google.protobuf.Descriptors.GenericDescriptor; import com.google.protobuf.Message; import io.spine.annotation.Internal; import io.spine.code.java.ClassName; import io.spine.code.java.PackageName; import io.spine.code.java.SimpleClassName; import io.spine.type.TypeName; import io.spine.type.TypeUrl; import io.spine.type.UnknownTypeException; import static com.google.common.base.Preconditions.checkNotNull; /** * A Protobuf type, such as a message or an enum. * * @param <T> the type of the type descriptor * @param <P> the type of the proto message of the descriptor */ @Immutable(containerOf = {"T", "P"}) @Internal public abstract class Type<T extends GenericDescriptor, P extends Message> { private final T descriptor; private final boolean supportsBuilders; protected Type(T descriptor, boolean supportsBuilders) { this.descriptor = checkNotNull(descriptor); this.supportsBuilders = supportsBuilders; } /** * Obtains the descriptor of the type. */ public T descriptor() { return this.descriptor; } /** * Obtains the proto message of the type descriptor. */ public abstract P toProto(); /** * Obtains the {@linkplain TypeName name} of this type. */ public TypeName name() { return url().toName(); } /** * Obtains the {@link TypeUrl} of this type. */ public abstract TypeUrl url(); /** * Loads the Java class representing this Protobuf type. */ public Class<?> javaClass() { String clsName = javaClassName().value(); try { return Class.forName(clsName); } catch (ClassNotFoundException e) { throw new UnknownTypeException(descriptor.getName(), e); } } /** * Obtains the name of the Java class representing this Protobuf type. */ public abstract ClassName javaClassName(); /** * Obtains package for the corresponding Java type. */ public PackageName javaPackage() { PackageName result = PackageName.resolve(descriptor.getFile() .toProto()); return result; } /** * Obtains simple class name for corresponding Java type. */ public abstract SimpleClassName simpleJavaClassName(); /** * Defines whether or not the Java class generated from this type has a builder. * * @return {@code true} if the generated Java class has corresponding * {@link com.google.protobuf.Message.Builder} and * {@link com.google.protobuf.MessageOrBuilder} */ public final boolean supportsBuilders() { return supportsBuilders; } /** * Returns a fully-qualified name of the proto type. */ @Override public String toString() { return descriptor.getFullName(); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (!(o instanceof Type)) { return false; } Type<?, ?> type = (Type<?, ?>) o; return Objects.equal(descriptor, type.descriptor); } @Override public int hashCode() { return Objects.hashCode(descriptor); } }
Fix flawed `equals`.
base/src/main/java/io/spine/code/proto/Type.java
Fix flawed `equals`.
<ide><path>ase/src/main/java/io/spine/code/proto/Type.java <ide> <ide> import com.google.common.base.Objects; <ide> import com.google.errorprone.annotations.Immutable; <del>import com.google.protobuf.Descriptors; <ide> import com.google.protobuf.Descriptors.GenericDescriptor; <ide> import com.google.protobuf.Message; <ide> import io.spine.annotation.Internal; <ide> return false; <ide> } <ide> Type<?, ?> type = (Type<?, ?>) o; <del> return Objects.equal(descriptor, type.descriptor); <add> return Objects.equal(descriptor.getFullName(), type.descriptor.getFullName()); <ide> } <ide> <ide> @Override
JavaScript
mit
9a04c70bd31b7530c13d30cb432a608eacd81ebb
0
fmoliveira/fmoliveira.github.io,fmoliveira/fmoliveira.github.io
module.exports = { siteMetadata: { title: `fmoliveira.dev`, description: `I'm a Freelance Software Engineer who loves writing clean and well-tested code. My favourite tech stack at the moment is React, TypeScript, Jest and Testing Library. Always hungry for learning and happy to help!`, author: `@fmoliveira`, }, plugins: [ `gatsby-plugin-typescript`, `gatsby-plugin-react-helmet`, { resolve: `gatsby-source-filesystem`, options: { name: `images`, path: `${__dirname}/src/images`, }, }, `gatsby-transformer-sharp`, `gatsby-plugin-sharp`, { resolve: `gatsby-plugin-manifest`, options: { name: `fmoliveira.dev`, short_name: `fmoliveira`, start_url: `/`, background_color: `#20222e`, theme_color: `#20222e`, display: `minimal-ui`, icon: `src/images/gatsby-icon.png`, // This path is relative to the root of the site. }, }, // this (optional) plugin enables Progressive Web App + Offline functionality // To learn more, visit: https://gatsby.dev/offline // `gatsby-plugin-offline`, ], }
gatsby-config.js
module.exports = { siteMetadata: { title: `Gatsby Default Starter`, description: `Kick off your next, great Gatsby project with this default starter. This barebones starter ships with the main Gatsby configuration files you might need.`, author: `@gatsbyjs`, }, plugins: [ `gatsby-plugin-typescript`, `gatsby-plugin-react-helmet`, { resolve: `gatsby-source-filesystem`, options: { name: `images`, path: `${__dirname}/src/images`, }, }, `gatsby-transformer-sharp`, `gatsby-plugin-sharp`, { resolve: `gatsby-plugin-manifest`, options: { name: `gatsby-starter-default`, short_name: `starter`, start_url: `/`, background_color: `#663399`, theme_color: `#663399`, display: `minimal-ui`, icon: `src/images/gatsby-icon.png`, // This path is relative to the root of the site. }, }, // this (optional) plugin enables Progressive Web App + Offline functionality // To learn more, visit: https://gatsby.dev/offline // `gatsby-plugin-offline`, ], }
Replace initial config for personal info.
gatsby-config.js
Replace initial config for personal info.
<ide><path>atsby-config.js <ide> module.exports = { <ide> siteMetadata: { <del> title: `Gatsby Default Starter`, <del> description: `Kick off your next, great Gatsby project with this default starter. This barebones starter ships with the main Gatsby configuration files you might need.`, <del> author: `@gatsbyjs`, <add> title: `fmoliveira.dev`, <add> description: `I'm a Freelance Software Engineer who loves writing clean and well-tested code. My favourite tech stack at the moment is React, TypeScript, Jest and Testing Library. Always hungry for learning and happy to help!`, <add> author: `@fmoliveira`, <ide> }, <ide> plugins: [ <ide> `gatsby-plugin-typescript`, <ide> { <ide> resolve: `gatsby-plugin-manifest`, <ide> options: { <del> name: `gatsby-starter-default`, <del> short_name: `starter`, <add> name: `fmoliveira.dev`, <add> short_name: `fmoliveira`, <ide> start_url: `/`, <del> background_color: `#663399`, <del> theme_color: `#663399`, <add> background_color: `#20222e`, <add> theme_color: `#20222e`, <ide> display: `minimal-ui`, <ide> icon: `src/images/gatsby-icon.png`, // This path is relative to the root of the site. <ide> },
Java
mit
222af5fd5f74870e97cd3d7482e0359c61bb8bfb
0
nking/curvature-scale-space-corners-and-transformations,nking/curvature-scale-space-corners-and-transformations
package algorithms.imageProcessing.features; import algorithms.MultiArrayMergeSort; import algorithms.compGeometry.MedialAxis; import algorithms.compGeometry.PerimeterFinder2; import algorithms.compGeometry.RotatedOffsets; import algorithms.compGeometry.clustering.KMeansHSV; import algorithms.compGeometry.clustering.KMeansPlusPlus; import algorithms.compGeometry.clustering.KMeansPlusPlusColor; import algorithms.imageProcessing.AdaptiveThresholding; import algorithms.imageProcessing.CIEChromaticity; import algorithms.imageProcessing.CannyEdgeFilterAdaptive; import algorithms.imageProcessing.ColorHistogram; import algorithms.imageProcessing.DFSContiguousIntValueFinder; import algorithms.imageProcessing.DFSContiguousValueFinder; import algorithms.imageProcessing.EdgeFilterProducts; import algorithms.imageProcessing.GreyscaleImage; import algorithms.imageProcessing.GroupPixelColors; import algorithms.imageProcessing.GroupPixelRGB; import algorithms.imageProcessing.GroupPixelRGB0; import algorithms.imageProcessing.Image; import algorithms.imageProcessing.ImageDisplayer; import algorithms.imageProcessing.ImageExt; import algorithms.imageProcessing.ImageIOHelper; import algorithms.imageProcessing.ImageProcessor; import algorithms.imageProcessing.ImageProcessor.Colors; import algorithms.imageProcessing.ImageSegmentation; import algorithms.imageProcessing.ImageSegmentation.DecimatedData; import algorithms.imageProcessing.PixelColors; import algorithms.imageProcessing.matching.PartialShapeMatcher; import algorithms.imageProcessing.SIGMA; import algorithms.imageProcessing.SegmentationMergeThreshold; import algorithms.imageProcessing.features.ORB.Descriptors; import algorithms.imageProcessing.features.ObjectMatcher.Settings; import algorithms.imageProcessing.matching.PartialShapeMatcher.Result; import algorithms.imageProcessing.matching.SegmentedCellDescriptorMatcher; import algorithms.imageProcessing.matching.ShapeFinder; import algorithms.imageProcessing.segmentation.ColorSpace; import algorithms.imageProcessing.segmentation.LabelToColorHelper; import algorithms.imageProcessing.segmentation.NormalizedCuts; import algorithms.imageProcessing.segmentation.SLICSuperPixels; import algorithms.imageProcessing.transform.TransformationParameters; import algorithms.imageProcessing.transform.Transformer; import algorithms.imageProcessing.util.AngleUtil; import algorithms.imageProcessing.util.GroupAverageColors; import algorithms.imageProcessing.util.MiscStats; import algorithms.imageProcessing.util.RANSACAlgorithmIterations; import algorithms.misc.Misc; import algorithms.misc.MiscDebug; import algorithms.misc.MiscMath; import algorithms.util.CorrespondencePlotter; import algorithms.util.PairInt; import algorithms.util.PairIntArray; import algorithms.util.PairIntPair; import algorithms.util.PolygonAndPointPlotter; import algorithms.util.QuadInt; import algorithms.util.ResourceFinder; import algorithms.util.TwoDFloatArray; import algorithms.util.TwoDIntArray; import algorithms.util.VeryLongBitString; import gnu.trove.iterator.TIntIterator; import gnu.trove.iterator.TIntObjectIterator; import gnu.trove.list.TDoubleList; import gnu.trove.list.TFloatList; import gnu.trove.list.TIntList; import gnu.trove.list.array.TDoubleArrayList; import gnu.trove.list.array.TFloatArrayList; import gnu.trove.list.array.TIntArrayList; import gnu.trove.map.TIntIntMap; import gnu.trove.map.TIntObjectMap; import gnu.trove.map.TObjectIntMap; import gnu.trove.map.hash.TIntIntHashMap; import gnu.trove.map.hash.TIntObjectHashMap; import gnu.trove.map.hash.TObjectIntHashMap; import gnu.trove.set.TIntSet; import gnu.trove.set.hash.TIntHashSet; import java.awt.image.ImageObserver; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.logging.Logger; import junit.framework.TestCase; import org.ejml.data.Complex64F; import org.ejml.simple.SimpleEVD; import org.ejml.simple.SimpleMatrix; import static org.junit.Assert.*; /** * * @author nichole */ public class AndroidStatuesTest extends TestCase { private Logger log = Logger.getLogger(this.getClass().getName()); public AndroidStatuesTest() { } public void est0() throws Exception { int maxDimension = 256;//512; String fileName1 = ""; //for (int i = 0; i < 1; ++i) { for (int i = 0; i < 37; ++i) { switch(i) { case 0: { fileName1 = "android_statues_01.jpg"; break; } case 1: { fileName1 = "android_statues_02.jpg"; break; } case 2: { fileName1 = "android_statues_03.jpg"; break; } case 3: { fileName1 = "android_statues_04.jpg"; break; } case 4: { fileName1 = "seattle.jpg"; break; } case 5: { fileName1 = "stonehenge.jpg"; break; } case 6: { fileName1 = "cloudy_san_jose.jpg"; break; } case 7: { fileName1 = "patagonia_snowy_foreground.jpg"; break; } case 8: { fileName1 = "mt_rainier_snowy_field.jpg"; break; } case 9: { fileName1 = "brown_lowe_2003_image1.jpg"; break; } case 10: { fileName1 = "brown_lowe_2003_image2.jpg"; break; } case 11: { fileName1 = "venturi_mountain_j6_0001.png"; break; } case 12: { fileName1 = "venturi_mountain_j6_0010.png"; break; } case 13: { fileName1 = "campus_010.jpg"; break; } case 14: { fileName1 = "campus_011.jpg"; break; } case 15: { fileName1 = "merton_college_I_001.jpg"; break; } case 16: { fileName1 = "merton_college_I_002.jpg"; break; } case 17: { fileName1 = "arches.jpg"; break; } case 18: { fileName1 = "stinson_beach.jpg"; break; } case 19: { fileName1 = "norwegian_mtn_range.jpg"; break; } case 20: { fileName1 = "halfdome.jpg"; break; } case 21: { fileName1 = "halfdome2.jpg"; break; } case 22: { fileName1 = "halfdome3.jpg"; break; } case 23: { fileName1 = "costa_rica.jpg"; break; } case 24: { fileName1 = "new-mexico-sunrise_w725_h490.jpg"; break; } case 25: { fileName1 = "arizona-sunrise-1342919937GHz.jpg"; break; } case 26: { fileName1 = "sky_with_rainbow.jpg"; break; } case 27: { fileName1 = "sky_with_rainbow2.jpg"; break; } case 28: { fileName1 = "books_illum3_v0_695x555.png"; break; } case 29: { fileName1 = "books_illum3_v6_695x555.png"; break; } case 30: { fileName1 = "klein_matterhorn_snowy_foreground.jpg"; break; } case 31: { fileName1 = "30.jpg"; break; } case 32: { fileName1 = "arches_sun_01.jpg"; break; } case 33: { fileName1 = "stlouis_arch.jpg"; break; } case 34: { fileName1 = "contrail.jpg"; break; } case 35: { fileName1 = "checkerboard_01.jpg"; break; } default: { fileName1 = "checkerboard_02.jpg"; break; } } int idx = fileName1.lastIndexOf("."); String fileName1Root = fileName1.substring(0, idx); String filePath1 = ResourceFinder.findFileInTestResources(fileName1); ImageExt img = ImageIOHelper.readImageExt(filePath1); ImageProcessor imageProcessor = new ImageProcessor(); ImageSegmentation imageSegmentation = new ImageSegmentation(); int w1 = img.getWidth(); int h1 = img.getHeight(); int binFactor1 = (int) Math.ceil(Math.max( (float) w1 / maxDimension, (float) h1 / maxDimension)); img = imageProcessor.binImage(img, binFactor1); int[] labels4 = imageSegmentation.objectSegmentation(img); ImageExt img11 = img.createWithDimensions(); ImageIOHelper.addAlternatingColorLabelsToRegion( img11, labels4); MiscDebug.writeImage(img11, "_final_" + fileName1Root); //LabelToColorHelper.applyLabels(img, labels4); //MiscDebug.writeImage(img, "_final_" + fileName1Root); {// --- a look at the angles of phase and orientation plotted ---- List<Set<PairInt>> contigSets = LabelToColorHelper.extractContiguousLabelPoints( img, labels4); List<PairIntArray> orderedBoundaries = new ArrayList<PairIntArray>(); int w = img.getWidth(); int h = img.getHeight(); SIGMA sigma = SIGMA.ZEROPOINTFIVE;//SIGMA.ONE; for (int ii = 0; ii < contigSets.size(); ++ii) { Set<PairInt> set = contigSets.get(ii); Set<PairInt> medialAxis = new HashSet<PairInt>(); PairIntArray p = imageProcessor.extractSmoothedOrderedBoundary( set, sigma, w, h, medialAxis); if (p.getN() > 24) { orderedBoundaries.add(p); } } EdgeFilterProducts products = imageSegmentation .createPhaseCongruencyGradient( img.copyToGreyscale()); img11 = img.copyToImageExt(); for (int ii = 0; ii < orderedBoundaries.size(); ++ii) { PairIntArray a = orderedBoundaries.get(ii); for (int j = 0; j < a.getN(); j += 10) { int x = a.getX(j); int y = a.getY(j); double or = products.getTheta().getValue(x, y) * Math.PI/180.; double pa = products.getPhaseAngle().getValue(x, y) * Math.PI/180.; int dx0 = (int)Math.round(3. * Math.cos(or)); int dy0 = (int)Math.round(3. * Math.sin(or)); int dx1 = (int)Math.round(3. * Math.cos(pa)); int dy1 = (int)Math.round(3. * Math.sin(pa)); ImageIOHelper.addPointToImage(x, y, img11, 1, 255, 0, 0); int x2, y2; x2 = x + dx0; y2 = y + dy0; if (x2 >= 0 && x2 < w && y2 >= 0 && y2 < h) { ImageIOHelper.drawLineInImage(x, y, x2, y2, img11, 0, 255, 255, 0); } x2 = x + dx1; y2 = y + dy1; if (x2 >= 0 && x2 < w && y2 >= 0 && y2 < h) { ImageIOHelper.drawLineInImage(x, y, x2, y2, img11, 0, 0, 0, 255); } } } MiscDebug.writeImage(img11, "_aa_" + fileName1Root); } } } public void estORBMatcher() throws Exception { /* this demonstrates ORB followed by filtering of search image keypoints by color. then matching by descriptors and evaluation of pair combinations of best mathing keypoints from which euclidean transformaions are derived. */ int maxDimension = 256;//512; SIGMA sigma = SIGMA.ZEROPOINTFIVE;//SIGMA.ONE; ImageProcessor imageProcessor = new ImageProcessor(); ImageSegmentation imageSegmentation = new ImageSegmentation(); String[] fileNames0 = new String[]{ "android_statues_03_sz1", "android_statues_03_sz3" }; String[] fileNames1 = new String[]{ "android_statues_01.jpg", "android_statues_02.jpg", "android_statues_04.jpg", "android_statues_03.jpg" }; int fn0 = 0; for (String fileNameRoot0 : fileNames0) { fn0++; for (String fileName1 : fileNames1) { long t0 = System.currentTimeMillis(); Set<PairInt> shape0 = new HashSet<PairInt>(); // to compare to "android_statues_01.jpg", // set this to '2' int binFactor0 = 1; // 1st image is color image, 2nd is masked color image // 218 X 163... full size is 1280 X 960 ImageExt[] imgs0 = maskAndBin(fileNameRoot0, binFactor0, shape0); int nShape0_0 = shape0.size(); System.out.println("shape0 nPts=" + nShape0_0); String fileName1Root = fileName1.substring(0, fileName1.lastIndexOf(".")); String filePath1 = ResourceFinder.findFileInTestResources( fileName1); ImageExt img = ImageIOHelper.readImageExt(filePath1); // template img size is 218 163 //img = (ImageExt) imageProcessor.bilinearDownSampling( // img, 218, 163, 0, 255); long ts = MiscDebug.getCurrentTimeFormatted(); int w1 = img.getWidth(); int h1 = img.getHeight(); int binFactor1 = (int) Math.ceil(Math.max( (float) w1 / maxDimension, (float) h1 / maxDimension)); img = imageProcessor.binImage(img, binFactor1); int w = img.getWidth(); int h = img.getHeight(); /*RANSACAlgorithmIterations nsIter = new RANSACAlgorithmIterations(); long nnn = nsIter.estimateNIterFor99PercentConfidence( 300, 7, 20./300.); System.out.println("99 percent nIter for RANSAC=" + nnn);*/ Settings settings = new Settings(); ObjectMatcher objMatcher = new ObjectMatcher(); if (fileName1Root.contains("_01")) { settings.setToUseSmallObjectMethod(); } //settings.setToUseLargerPyramid0(); objMatcher.setToDebug(); CorrespondenceList cor = objMatcher.findObject(imgs0[0], shape0, img, settings); long t1 = System.currentTimeMillis(); System.out.println("matching took " + ((t1 - t0)/1000.) + " sec"); CorrespondencePlotter plotter = new CorrespondencePlotter( imgs0[1], img.copyImage()); for (int ii = 0; ii < cor.getPoints1().size(); ++ii) { PairInt p1 = cor.getPoints1().get(ii); PairInt p2 = cor.getPoints2().get(ii); //System.out.println("orb matched: " + p1 + " " + p2); //if (p2.getX() > 160) plotter.drawLineInAlternatingColors(p1.getX(), p1.getY(), p2.getX(), p2.getY(), 0); } plotter.writeImage("_orb_corres_final_" + "_" + fileName1Root + "_" + fn0); System.out.println(cor.getPoints1().size() + " matches " + fileName1Root); //MiscDebug.writeImage(img11, "_orb_matched_" + str // + "_" + fileName1Root); } } } public void testORBMatcher2() throws Exception { // TODO: this one either needs more keypoints across the cupcake in // android statues 02 image, // or it needs an algorithm similar to matchSmall which does not // use descriptors, but instead uses color histograms and partial // shape matching, but with the addition of aggregated shape // comparisons (== the unfinished ShapeFinder) // // and as always, improved segmentation would help, but the cupcake is // in partly shaded locations. int maxDimension = 256;//512; SIGMA sigma = SIGMA.ZEROPOINTFIVE;//SIGMA.ONE; ImageProcessor imageProcessor = new ImageProcessor(); ImageSegmentation imageSegmentation = new ImageSegmentation(); String[] fileNames0 = new String[]{ "android_statues_04.jpg", "android_statues_04_cupcake_mask.png", }; String[] fileNames1 = new String[]{ // "android_statues_01.jpg", // needs aggregated shape matching "android_statues_02.jpg", // needs aggregated shape matching // "android_statues_04.jpg", // descr are fine }; for (String fileName1 : fileNames1) { long t0 = System.currentTimeMillis(); Set<PairInt> shape0 = new HashSet<PairInt>(); ImageExt[] imgs0 = maskAndBin2(fileNames0, maxDimension, shape0); int nShape0_0 = shape0.size(); System.out.println("shape0 nPts=" + nShape0_0); String fileName1Root = fileName1.substring(0, fileName1.lastIndexOf(".")); String filePath1 = ResourceFinder.findFileInTestResources( fileName1); ImageExt img = ImageIOHelper.readImageExt(filePath1); long ts = MiscDebug.getCurrentTimeFormatted(); int w1 = img.getWidth(); int h1 = img.getHeight(); int binFactor1 = (int) Math.ceil(Math.max( (float) w1 / maxDimension, (float) h1 / maxDimension)); img = imageProcessor.binImage(img, binFactor1); int w = img.getWidth(); int h = img.getHeight(); /*RANSACAlgorithmIterations nsIter = new RANSACAlgorithmIterations(); long nnn = nsIter.estimateNIterFor99PercentConfidence( 300, 7, 20./300.); System.out.println("99 percent nIter for RANSAC=" + nnn);*/ //GreyscaleImage theta1 = imageProcessor.createCIELABTheta(imgs0[0], 255); //MiscDebug.writeImage(theta1, fileName1Root + "_theta_0"); //theta1 = imageProcessor.createCIELABTheta(img, 255); //MiscDebug.writeImage(theta1, fileName1Root + "_theta_1"); Settings settings = new Settings(); ObjectMatcher objMatcher = new ObjectMatcher(); if (fileName1Root.contains("_01")) { settings.setToUseSmallObjectMethod(); } //settings.setToUseLargerPyramid0(); objMatcher.setToDebug(); CorrespondenceList cor = objMatcher.findObject(imgs0[0], shape0, img, settings); long t1 = System.currentTimeMillis(); System.out.println("matching took " + ((t1 - t0)/1000.) + " sec"); CorrespondencePlotter plotter = new CorrespondencePlotter( imgs0[1], img.copyImage()); for (int ii = 0; ii < cor.getPoints1().size(); ++ii) { PairInt p1 = cor.getPoints1().get(ii); PairInt p2 = cor.getPoints2().get(ii); //System.out.println("orb matched: " + p1 + " " + p2); //if (p2.getX() > 160) plotter.drawLineInAlternatingColors(p1.getX(), p1.getY(), p2.getX(), p2.getY(), 0); } plotter.writeImage("_orb_corres_final_" + "_" + fileName1Root); System.out.println(cor.getPoints1().size() + " matches " + fileName1Root + " test2"); //MiscDebug.writeImage(img11, "_orb_matched_" + str // + "_" + fileName1Root); } } public void estMkImgs() throws Exception { String fileName1 = ""; for (int i = 0; i < 4; ++i) { switch(i) { case 0: { fileName1 = "android_statues_01.jpg"; break;} case 1: { fileName1 = "android_statues_02.jpg"; break;} case 2: { fileName1 = "android_statues_03.jpg"; break;} case 3: { fileName1 = "android_statues_04.jpg"; break;} default: {break;} } int idx = fileName1.lastIndexOf("."); String fileName1Root = fileName1.substring(0, idx); String filePath1 = ResourceFinder.findFileInTestResources(fileName1); ImageExt img = ImageIOHelper.readImageExt(filePath1); int w1 = img.getWidth(); int h1 = img.getHeight(); int maxDimension = 512; int binFactor1 = (int) Math.ceil(Math.max((float) w1 / maxDimension, (float) h1 / maxDimension)); ImageProcessor imageProcessor = new ImageProcessor(); img = imageProcessor.binImage(img, binFactor1); ImageExt imgCp = img.copyToImageExt(); int nClusters = 200;//100; //int clrNorm = 5; SLICSuperPixels slic = new SLICSuperPixels(img, nClusters); slic.calculate(); int[] labels = slic.getLabels(); ImageIOHelper.addAlternatingColorLabelsToRegion( //LabelToColorHelper.applyLabels( img, labels); MiscDebug.writeImage(img, "_slic_" + fileName1Root); NormalizedCuts normCuts = new NormalizedCuts(); normCuts.setColorSpaceToHSV(); int[] labels2 = normCuts.normalizedCut(imgCp, labels); labels = labels2; ImageIOHelper.addAlternatingColorLabelsToRegion( imgCp, labels); MiscDebug.writeImage(imgCp, "_norm_cuts_" + fileName1Root); //img = ImageIOHelper.readImageExt(filePath1); //img = imageProcessor.binImage(img, binFactor1); //MiscDebug.writeImage(img, "_512_img_" + fileName1Root); } } public void estColorLayout() throws Exception { String[] fileNames = new String[]{ "android_statues_01.jpg", "android_statues_02.jpg", "android_statues_03.jpg", "android_statues_04.jpg" }; // paused here. editing to use super pixels // and a pattern of color aggregation // w/ voronoi cells for comparison to model, // then a partial shape matching algorithm. ImageProcessor imageProcessor = new ImageProcessor(); ImageSegmentation imageSegmentation = new ImageSegmentation(); List<ImageExt> images = new ArrayList<ImageExt>(); for (int i = 0; i < fileNames.length; ++i) { String fileName = fileNames[i]; String filePath = ResourceFinder.findFileInTestResources(fileName); String fileNameRoot = fileName.substring(0, fileName.lastIndexOf(".")); ImageExt img = ImageIOHelper.readImageExt(filePath); images.add(img); /* wanting to look at color similarity of pixels holding known objects that have different orientation and lighting in different images. -- android -- ice cream -- eclair -- cupcake bigger goal is to use segmentation to find object outlines then identify the object in other images and follow that with detailed feature matching. the method has to work on objects that have changed position and possibly also lighting. the method may need some form of contour matching for pure sillouhette conditions but would need to allow for occlusion. deltaE for gingerbread man in the 4 images is at most 5, else 3.7 and 1.8. */ } } private PairIntArray extractOrderedBoundary(ImageExt image) { return extractOrderedBoundary(image, SIGMA.TWO); } private PairIntArray extractOrderedBoundary(ImageExt image, SIGMA sigma) { GreyscaleImage img = image.copyToGreyscale(); Set<PairInt> blob = new HashSet<PairInt>(); for (int i = 0; i < img.getNPixels(); ++i) { if (img.getValue(i) > 0) { int x = img.getCol(i); int y = img.getRow(i); blob.add(new PairInt(x, y)); } } ImageProcessor imageProcessor = new ImageProcessor(); PairIntArray ordered = imageProcessor.extractSmoothedOrderedBoundary( blob, sigma, img.getWidth(), img.getHeight()); return ordered; } private void sortByDecrSize(List<Set<PairInt>> clusterSets) { int n = clusterSets.size(); int[] sizes = new int[n]; int[] indexes = new int[n]; for (int i = 0; i < n; ++i) { sizes[i] = clusterSets.get(i).size(); indexes[i] = i; } MultiArrayMergeSort.sortByDecr(sizes, indexes); List<Set<PairInt>> out = new ArrayList<Set<PairInt>>(); for (int i = 0; i < n; ++i) { int idx = indexes[i]; out.add(clusterSets.get(idx)); } clusterSets.clear(); clusterSets.addAll(out); } private void printGradients(ImageExt img, String fileNameRoot) { GreyscaleImage gsImg = img.copyToGreyscale(); GreyscaleImage gsImg1 = gsImg.copyImage(); GreyscaleImage gsImg2 = gsImg.copyImage(); CannyEdgeFilterAdaptive canny = new CannyEdgeFilterAdaptive(); canny.overrideToNotUseLineThinner(); canny.applyFilter(gsImg); for (int i = 0; i < gsImg.getNPixels(); ++i) { if (gsImg.getValue(i) > 0) { gsImg.setValue(i, 255); } } MiscDebug.writeImage(gsImg, "_canny_" + fileNameRoot); ImageProcessor imageProcessor = new ImageProcessor(); imageProcessor.applyFirstDerivGaussian(gsImg1, SIGMA.ONE, 0, 255); for (int i = 0; i < gsImg1.getNPixels(); ++i) { if (gsImg1.getValue(i) > 0) { gsImg1.setValue(i, 255); } } MiscDebug.writeImage(gsImg1, "_firstderiv_" + fileNameRoot); PhaseCongruencyDetector pcd = new PhaseCongruencyDetector(); PhaseCongruencyDetector.PhaseCongruencyProducts product = pcd.phaseCongMono(gsImg2); MiscDebug.writeImage(product.getThinned(), "_pcd_" + fileNameRoot); } private TIntList addIntersection(GreyscaleImage gradient, int[] labels) { assert(gradient.getNPixels() == labels.length); int maxLabel = MiscMath.findMax(labels) + 1; int[] dxs = Misc.dx8; int[] dys = Misc.dy8; int w = gradient.getWidth(); int h = gradient.getHeight(); TIntList change = new TIntArrayList(); for (int i = 0; i < gradient.getNPixels(); ++i) { if (gradient.getValue(i) < 1) { continue; } int x = gradient.getCol(i); int y = gradient.getRow(i); int l0 = labels[i]; int l1 = -1; for (int k = 0; k < dxs.length; ++k) { int x2 = x + dxs[k]; int y2 = y + dys[k]; if (x2 < 0 || y2 < 0 || (x2 > (w - 1)) || (y2 > (h - 1))) { continue; } int j = gradient.getInternalIndex(x2, y2); int lt = labels[j]; if (lt != l0) { if (l1 == -1) { l1 = lt; } } } if (l1 != -1) { // gradient is on edge of superpixels change.add(i); System.out.println( "x=" + x + " y=" + y + " pixIdx=" + i); } } return change; } private int[] desegment(ImageExt img, TIntList gradSP, int[] labels, int[] labels2) { int[] dxs = Misc.dx8; int[] dys = Misc.dy8; int w = img.getWidth(); int h = img.getHeight(); TIntSet restore = new TIntHashSet(); for (int i = 0; i < gradSP.size(); ++i) { int pixIdx = gradSP.get(i); int l0 = labels2[pixIdx]; int l1 = -1; int x = img.getCol(pixIdx); int y = img.getRow(pixIdx); for (int k = 0; k < dxs.length; ++k) { int x2 = x + dxs[k]; int y2 = y + dys[k]; if (x2 < 0 || y2 < 0 || (x2 > (w - 1)) || (y2 > (h - 1))) { continue; } int j = img.getInternalIndex(x2, y2); int lt = labels2[j]; if (lt != l0) { if (l1 == -1) { l1 = lt; } } } if (l1 == -1) { // these need boundaries restored ImageIOHelper.addPointToImage(x, y, img, 1, 255, 0, 0); restore.add(labels[pixIdx]); } } MiscDebug.writeImage(img, "restore"); if (restore.isEmpty()) { return labels2; } TIntObjectMap<Set<PairInt>> label1PointMap = LabelToColorHelper.extractLabelPoints(img, labels); int[] labels3 = Arrays.copyOf(labels2, labels2.length); int maxLabel = MiscMath.findMax(labels2); maxLabel++; TIntIterator iter = restore.iterator(); while (iter.hasNext()) { int label = iter.next(); Set<PairInt> pts = label1PointMap.get(label); for (PairInt pt : pts) { int x = pt.getX(); int y = pt.getY(); int pixIdx = img.getInternalIndex(x, y); labels3[pixIdx] = maxLabel; } maxLabel++; } return labels3; } private ImageExt[] maskAndBin(String fileNamePrefix, int binFactor, Set<PairInt> outputShape) throws IOException, Exception { ImageProcessor imageProcessor = new ImageProcessor(); String fileNameMask0 = fileNamePrefix + "_mask.png"; String filePathMask0 = ResourceFinder .findFileInTestResources(fileNameMask0); ImageExt imgMask0 = ImageIOHelper.readImageExt(filePathMask0); String fileName0 = fileNamePrefix + ".jpg"; String filePath0 = ResourceFinder .findFileInTestResources(fileName0); ImageExt img0 = ImageIOHelper.readImageExt(filePath0); if (binFactor != 1) { img0 = imageProcessor.binImage(img0, binFactor); imgMask0 = imageProcessor.binImage(imgMask0, binFactor); } ImageExt img0Masked = img0.copyToImageExt(); assertEquals(imgMask0.getNPixels(), img0.getNPixels()); for (int i = 0; i < imgMask0.getNPixels(); ++i) { if (imgMask0.getR(i) == 0) { img0Masked.setRGB(i, 0, 0, 0); } else { outputShape.add(new PairInt(imgMask0.getCol(i), imgMask0.getRow(i))); } } //MiscDebug.writeImage(img0Masked, "_MASKED"); return new ImageExt[]{img0, img0Masked}; } public void estMatching() throws Exception { String fileName1, fileName2; FeatureMatcherSettings settings = new FeatureMatcherSettings(); settings.setDebug(true); settings.setStartWithBinnedImages(true); settings.setToUse2ndDerivCorners(); //for (int i = 0; i < 7; ++i) { for (int i = 0; i < 3; ++i) { switch(i) { case 0: { fileName1 = "android_statues_02.jpg"; fileName2 = "android_statues_04.jpg"; //fileName1 = "android_statues_02_gingerbreadman.jpg"; //fileName2 = "android_statues_04_gingerbreadman.jpg"; settings.setUseNormalizedFeatures(true); break; } case 1: { fileName1 = "android_statues_01.jpg"; fileName2 = "android_statues_03.jpg"; settings.setUseNormalizedFeatures(true); break; } case 2: { fileName1 = "brown_lowe_2003_image1.jpg"; fileName2 = "brown_lowe_2003_image2.jpg"; settings.setUseNormalizedFeatures(true); break; } case 3: { fileName2 = "brown_lowe_2003_image1.jpg"; fileName1 = "brown_lowe_2003_image2.jpg"; break; } case 4: { fileName1 = "venturi_mountain_j6_0001.png"; fileName2 = "venturi_mountain_j6_0010.png"; settings.setUseNormalizedFeatures(true); break; } case 5: { fileName1 = "campus_010.jpg"; fileName2 = "campus_011.jpg"; settings.setUseNormalizedFeatures(true); break; } case 6: { fileName1 = "merton_college_I_001.jpg"; fileName2 = "merton_college_I_002.jpg"; settings.setUseNormalizedFeatures(true); break; } default: { fileName1 = "checkerboard_01.jpg"; fileName2 = "checkerboard_02.jpg"; settings.setUseNormalizedFeatures(true); break; } } runCorrespondenceList(fileName1, fileName2, settings, false); } } public void estRot90() throws Exception { String fileName1, fileName2; FeatureMatcherSettings settings = new FeatureMatcherSettings(); settings.setDebug(true); settings.setStartWithBinnedImages(true); for (int i = 0; i < 5; ++i) { fileName1 = null; fileName2 = null; switch(i) { case 0: { fileName1 = "android_statues_02.jpg"; fileName2 = "android_statues_04.jpg"; //fileName1 = "campus_010.jpg"; //fileName2 = "campus_011.jpg"; settings.setUseNormalizedFeatures(true); settings.setToUse2ndDerivCorners(); break; } default: { fileName1 = "android_statues_01.jpg"; fileName2 = "android_statues_03.jpg"; settings.setUseNormalizedFeatures(true); settings.setToUse2ndDerivCorners(); break; } } runCorrespondenceList(fileName1, fileName2, settings, true); } } private void runCorrespondenceList(String fileName1, String fileName2, FeatureMatcherSettings settings, boolean rotateBy90) throws Exception { if (fileName1 == null) { return; } int idx = fileName1.lastIndexOf("."); String fileName1Root = fileName1.substring(0, idx); idx = fileName2.lastIndexOf("."); String fileName2Root = fileName2.substring(0, idx); settings.setDebugTag(fileName1Root); String filePath1 = ResourceFinder.findFileInTestResources(fileName1); ImageExt img1 = ImageIOHelper.readImageExt(filePath1); String filePath2 = ResourceFinder.findFileInTestResources(fileName2); ImageExt img2 = ImageIOHelper.readImageExt(filePath2); ImageProcessor imageProcessor = new ImageProcessor(); ImageSegmentation imageSegmentation = new ImageSegmentation(); int w1 = img1.getWidth(); int h1 = img1.getHeight(); int w2 = img2.getWidth(); int h2 = img2.getHeight(); int maxDimension = 350; int binFactor1 = (int) Math.ceil(Math.max((float)w1/maxDimension, (float)h1/ maxDimension)); int binFactor2 = (int) Math.ceil(Math.max((float)w2/maxDimension, (float)h2/ maxDimension)); ImageExt img1Binned = imageProcessor.binImage(img1, binFactor1); ImageExt img2Binned = imageProcessor.binImage(img2, binFactor2); if (rotateBy90) { TransformationParameters params90 = new TransformationParameters(); params90.setRotationInDegrees(90); params90.setOriginX(0); params90.setOriginY(0); params90.setTranslationX(0); params90.setTranslationY(img1.getWidth() - 1); Transformer transformer = new Transformer(); img1 = (ImageExt) transformer.applyTransformation(img1, params90, img1.getHeight(), img1.getWidth()); /* MatchedPointsTransformationCalculator tc = new MatchedPointsTransformationCalculator(); TransformationParameters revParams = tc.swapReferenceFrames(params90); transformer.transformToOrigin(0, 0, revParams); revParams.setTranslationX(revParams.getTranslationX() + -74); revParams.setTranslationY(revParams.getTranslationY() + -0); revParams.setRotationInDegrees(revParams.getRotationInDegrees() - 0); log.info("revParams: " + revParams.toString()); ImageExt img1RevTr = img1.copyToImageExt(); img1RevTr = (ImageExt) transformer.applyTransformation(img1RevTr, revParams, img1RevTr.getHeight(), img1RevTr.getWidth()); MiscDebug.writeImage(img1RevTr, "rot90_rev_trans"); */ } RotatedOffsets rotatedOffsets = RotatedOffsets.getInstance(); log.info("fileName1Root=" + fileName1Root); EpipolarColorSegmentedSolver solver = new EpipolarColorSegmentedSolver(img1, img2, settings); boolean solved = solver.solve(); assertTrue(solved); //MiscDebug.writeImagesInAlternatingColor(img1, img2, stats, // fileName1Root + "_matched_non_euclid", 2); } public static void main(String[] args) { try { AndroidStatuesTest test = new AndroidStatuesTest(); //test.test0(); //test.testRot90(); } catch(Exception e) { e.printStackTrace(); System.err.println(e.getMessage()); fail(e.getMessage()); } } public void estColor() throws Exception { //String fileName1 = "android_statues_02.jpg"; //String fileName2 = "android_statues_04.jpg"; String fileName1 = "android_statues_02_gingerbreadman.jpg"; String fileName2 = "android_statues_04_gingerbreadman.jpg"; int idx = fileName1.lastIndexOf("."); String fileName1Root = fileName1.substring(0, idx); idx = fileName2.lastIndexOf("."); String fileName2Root = fileName2.substring(0, idx); String filePath1 = ResourceFinder.findFileInTestResources(fileName1); ImageExt img1 = ImageIOHelper.readImageExt(filePath1); String filePath2 = ResourceFinder.findFileInTestResources(fileName2); ImageExt img2 = ImageIOHelper.readImageExt(filePath2); CIEChromaticity cieC = new CIEChromaticity(); int binnedImageMaxDimension = 512; int binFactor1 = (int) Math.ceil( Math.max((float) img1.getWidth() / (float)binnedImageMaxDimension, (float) img1.getHeight() / (float)binnedImageMaxDimension)); int binFactor2 = (int) Math.ceil( Math.max((float) img2.getWidth() / (float)binnedImageMaxDimension, (float) img2.getHeight() / (float)binnedImageMaxDimension)); ImageProcessor imageProcessor = new ImageProcessor(); ImageExt imgBinned1 = imageProcessor.binImage(img1, binFactor1); ImageExt imgBinned2 = imageProcessor.binImage(img2, binFactor2); /* HistogramEqualizationForColor hEq = new HistogramEqualizationForColor(imgBinned1); hEq.applyFilter(); hEq = new HistogramEqualizationForColor(imgBinned2); hEq.applyFilter(); */ RotatedOffsets rotatedOffsets = RotatedOffsets.getInstance(); GreyscaleImage redBinnedImg1 = imgBinned1.copyRedToGreyscale(); GreyscaleImage greenBinnedImg1 = imgBinned1.copyGreenToGreyscale(); GreyscaleImage blueBinnedImg1 = imgBinned1.copyBlueToGreyscale(); GreyscaleImage redBinnedImg2 = imgBinned2.copyRedToGreyscale(); GreyscaleImage greenBinnedImg2 = imgBinned2.copyGreenToGreyscale(); GreyscaleImage blueBinnedImg2 = imgBinned2.copyBlueToGreyscale(); GreyscaleImage gsImg1 = imgBinned1.copyToGreyscale(); GreyscaleImage gsImg2 = imgBinned2.copyToGreyscale(); IntensityClrFeatures clrFeaturesBinned1 = new IntensityClrFeatures(gsImg1.copyImage(), 5, rotatedOffsets); IntensityClrFeatures clrFeaturesBinned2 = new IntensityClrFeatures(gsImg2.copyImage(), 5, rotatedOffsets); IntensityFeatures features1 = new IntensityFeatures(5, true, rotatedOffsets); IntensityFeatures features2 = new IntensityFeatures(5, true, rotatedOffsets); /* looking at trace/determinant of autocorrelation and eigenvalues of greyscale, autocorrelation, and lab colors for selected points in both images statues subsets: 0 (64, 100) (96, 109) 1 (67, 103) (103, 111) 2 (68, 78) (113, 86) 3 (66, 49) (106, 50) 4 (92, 108) (157, 118) 5 (92, 111) (160, 122) delta e = 28.9 6 (69, 129) (108, 142) delta e = 26.4 is the edelta for the gingerbread man's white stripes and shadows the same for shadow and higher illumination? */ // single values of edelta List<PairInt> points1 = new ArrayList<PairInt>(); List<PairInt> points2 = new ArrayList<PairInt>(); points1.add(new PairInt(64, 100)); points2.add(new PairInt(96, 109)); points1.add(new PairInt(67, 103)); points2.add(new PairInt(103, 111)); points1.add(new PairInt(68, 78)); points2.add(new PairInt(113, 86)); points1.add(new PairInt(66, 49)); points2.add(new PairInt(106, 50)); points1.add(new PairInt(92, 108)); points2.add(new PairInt(157, 118)); points1.add(new PairInt(92, 111)); points2.add(new PairInt(160, 122)); points1.add(new PairInt(69, 129)); points2.add(new PairInt(108, 142)); // this one is too look at localizability: points1.add(new PairInt(46, 65)); points2.add(new PairInt(6, 4)); int n = points1.size(); for (int i = 0; i < n; ++i) { StringBuilder sb = new StringBuilder(); PairInt p1 = points1.get(i); PairInt p2 = points2.get(i); sb.append(p1.toString()).append(p2.toString()); int r1 = redBinnedImg1.getValue(p1.getX(), p1.getY()); int g1 = greenBinnedImg1.getValue(p1.getX(), p1.getY()); int b1 = blueBinnedImg1.getValue(p1.getX(), p1.getY()); int r2 = redBinnedImg2.getValue(p2.getX(), p2.getY()); int g2 = greenBinnedImg2.getValue(p2.getX(), p2.getY()); int b2 = blueBinnedImg2.getValue(p2.getX(), p2.getY()); float[] lab1 = cieC.rgbToCIELAB(r1, g1, b1); float[] lab2 = cieC.rgbToCIELAB(r2, g2, b2); float[] cieXY1 = cieC.rgbToCIEXYZ(r1, g1, b1); float[] cieXY2 = cieC.rgbToCIEXYZ(r2, g2, b2); double deltaE = cieC.calcDeltaECIE94(lab1, lab2); sb.append(String.format(" dE=%.1f", (float)deltaE)); int rot1 = clrFeaturesBinned1.calculateOrientation(p1.getX(), p1.getY()); int rot2 = clrFeaturesBinned2.calculateOrientation(p2.getX(), p2.getY()); IntensityDescriptor desc_l1 = clrFeaturesBinned1.extractIntensityLOfCIELAB( redBinnedImg1, greenBinnedImg1, blueBinnedImg1, p1.getX(), p1.getY(), rot1); IntensityDescriptor desc_a1 = clrFeaturesBinned1.extractIntensityAOfCIELAB( redBinnedImg1, greenBinnedImg1, blueBinnedImg1, p1.getX(), p1.getY(), rot1); IntensityDescriptor desc_b1 = clrFeaturesBinned1.extractIntensityBOfCIELAB( redBinnedImg1, greenBinnedImg1, blueBinnedImg1, p1.getX(), p1.getY(), rot1); IntensityDescriptor desc_l2 = clrFeaturesBinned2.extractIntensityLOfCIELAB( redBinnedImg2, greenBinnedImg2, blueBinnedImg2, p2.getX(), p2.getY(), rot2); IntensityDescriptor desc_a2 = clrFeaturesBinned2.extractIntensityAOfCIELAB( redBinnedImg2, greenBinnedImg2, blueBinnedImg2, p2.getX(), p2.getY(), rot2); IntensityDescriptor desc_b2 = clrFeaturesBinned2.extractIntensityBOfCIELAB( redBinnedImg2, greenBinnedImg2, blueBinnedImg2, p2.getX(), p2.getY(), rot2); IntensityDescriptor desc1 = features1.extractIntensity(gsImg1, p1.getX(), p1.getY(), rot1); IntensityDescriptor desc2 = features2.extractIntensity(gsImg2, p2.getX(), p2.getY(), rot2); double det, trace; SimpleMatrix a_l1 = clrFeaturesBinned1.createAutoCorrelationMatrix(desc_l1); det = a_l1.determinant(); trace = a_l1.trace(); sb.append(String.format("\n L1_det(A)/trace=%.1f", (float)(det/trace))); SimpleMatrix a_l2 = clrFeaturesBinned2.createAutoCorrelationMatrix(desc_l2); det = a_l2.determinant(); trace = a_l2.trace(); sb.append(String.format(" L2_det(A)/trace=%.1f", (float)(det/trace))); try { sb.append("\n eigen values:\n"); SimpleEVD eigen1 = a_l1.eig(); for (int j = 0; j < eigen1.getNumberOfEigenvalues(); ++j) { Complex64F eigen = eigen1.getEigenvalue(j); sb.append(String.format(" [1] %d %.1f %.1f\n", j, (float)eigen.getReal(), (float)eigen.getMagnitude())); } sb.append("\n"); SimpleEVD eigen2 = a_l2.eig(); for (int j = 0; j < eigen2.getNumberOfEigenvalues(); ++j) { Complex64F eigen = eigen2.getEigenvalue(j); sb.append(String.format(" [1] %d %.1f %.1f\n", j, (float)eigen.getReal(), (float)eigen.getMagnitude())); } } catch (Throwable t) { } if (desc1 != null && desc2 != null) { SimpleMatrix gs_l1 = features1.createAutoCorrelationMatrix(desc1); det = gs_l1.determinant(); trace = gs_l1.trace(); sb.append(String.format("\n Grey_det(A)/trace=%.1f", (float)(det/trace))); SimpleMatrix gs_l2 = features2.createAutoCorrelationMatrix(desc2); det = gs_l2.determinant(); trace = gs_l2.trace(); sb.append(String.format(" Grey_det(A)/trace=%.1f", (float)(det/trace))); try { sb.append("\n eigen values:\n"); SimpleEVD eigen1 = gs_l1.eig(); for (int j = 0; j < eigen1.getNumberOfEigenvalues(); ++j) { Complex64F eigen = eigen1.getEigenvalue(j); sb.append(String.format(" [1] %d %.1f %.1f\n", j, (float) eigen.getReal(), (float) eigen.getMagnitude())); } sb.append("\n"); SimpleEVD eigen2 = gs_l2.eig(); for (int j = 0; j < eigen2.getNumberOfEigenvalues(); ++j) { Complex64F eigen = eigen2.getEigenvalue(j); sb.append(String.format(" [2] %d %.1f %.1f\n", j, (float) eigen.getReal(), (float) eigen.getMagnitude())); } } catch (Throwable t) { } } log.info(sb.toString()); } } private void populateClasses(Set<PairIntPair> similarClass, Set<PairIntPair> differentClass, String fileNameRoot) throws IOException { BufferedReader bReader = null; FileReader reader = null; String fileName = "label_" + fileNameRoot + "_coords.csv"; String filePath = ResourceFinder.findFileInTestResources(fileName); try { reader = new FileReader(new File(filePath)); bReader = new BufferedReader(reader); //read comment line and discard String line = bReader.readLine(); line = bReader.readLine(); while (line != null) { String[] items = line.split(","); if (items.length != 5) { throw new IllegalStateException("Error while reading " + fileName + " expecting 5 items in a line"); } PairIntPair pp = new PairIntPair( Integer.valueOf(items[0]).intValue(), Integer.valueOf(items[1]).intValue(), Integer.valueOf(items[2]).intValue(), Integer.valueOf(items[3]).intValue()); int classValue = Integer.valueOf(items[4]).intValue(); if (classValue == 0) { similarClass.add(pp); } else { differentClass.add(pp); } line = bReader.readLine(); } } catch (IOException e) { log.severe(e.getMessage()); } finally { if (reader == null) { reader.close(); } if (bReader == null) { bReader.close(); } } } private void plot(PairIntArray p, int fn) throws Exception { float[] x = new float[p.getN()]; float[] y = new float[p.getN()]; for (int i = 0; i < x.length; ++i) { x[i] = p.getX(i); y[i] = p.getY(i); } float xMax = MiscMath.findMax(x) + 1; float yMax = MiscMath.findMax(y) + 1; PolygonAndPointPlotter plot = new PolygonAndPointPlotter(); plot.addPlot(0, xMax, 0, yMax, x, y, x, y, ""); plot.writeFile(fn); } private void extractTemplateKeypoints(String fileNameRoot0, Set<PairInt> shape0, PairIntArray template, List<PairInt> templateKP, TDoubleList templateOrientations, Descriptors templateDescriptors) throws IOException, Exception { String fileName0 = fileNameRoot0 + ".jpg"; String filePath0 = ResourceFinder .findFileInTestResources(fileName0); ImageExt img0 = ImageIOHelper.readImageExt(filePath0); int[] minMaxXY = MiscMath.findMinMaxXY(template); int w = img0.getWidth(); int h = img0.getHeight(); int xLL = minMaxXY[0] - 5; if (xLL < 0) { xLL = 0; } int yLL = minMaxXY[2] - 5; if (yLL < 0) { yLL = 0; } int xUR = minMaxXY[1] + 5; if (xUR > (w - 1)) { xUR = w - 1; } int yUR = minMaxXY[3] + 5; if (yUR > (h - 1)) { yUR = h - 1; } ORB.DescriptorDithers descrOffsets = ORB.DescriptorDithers.NONE; // = ORB.DescriptorDithers.FORTY_FIVE; // = ORB.DescriptorDithers.FIFTEEN; ORBWrapper.extractKeypointsFromSubImage( img0, xLL, yLL, xUR, yUR, 200, templateKP, templateOrientations, templateDescriptors, //0.01f, 0.001f, true, descrOffsets); for (int i = 0; i < templateKP.size(); ++i) { PairInt p = templateKP.get(i); if (shape0.contains(p)) { ImageIOHelper.addPointToImage(p.getX(), p.getY(), img0, 1, 255, 0, 0); } } MiscDebug.writeImage(img0, "_template_orb"); } private void extractTemplateORBKeypoints(ImageExt img, Set<PairInt> shape0, List<PairInt> templateKP, TDoubleList templateOrientations, Descriptors templateDescriptorsH, Descriptors templateDescriptorsS, Descriptors templateDescriptorsV) throws IOException, Exception { int[] minMaxXY = MiscMath.findMinMaxXY(shape0); int w = img.getWidth(); int h = img.getHeight(); int buffer = 20; int xLL = minMaxXY[0] - buffer; if (xLL < 0) { xLL = 0; } int yLL = minMaxXY[2] - buffer; if (yLL < 0) { yLL = 0; } int xUR = minMaxXY[1] + buffer; if (xUR > (w - 1)) { xUR = w - 1; } int yUR = minMaxXY[3] + buffer; if (yUR > (h - 1)) { yUR = h - 1; } ORBWrapper.extractKeypointsFromSubImage( img, xLL, yLL, xUR, yUR, 200, //100, templateKP, templateOrientations, templateDescriptorsH, templateDescriptorsS, templateDescriptorsV, //0.01f, 0.001f, true); ImageExt imgCp = img.copyToImageExt(); TIntList rm = new TIntArrayList(); for (int i = 0; i < templateKP.size(); ++i) { PairInt p = templateKP.get(i); if (shape0.contains(p)) { ImageIOHelper.addPointToImage(p.getX(), p.getY(), imgCp, 1, 255, 0, 0); } else { rm.add(i); System.out.println("removing " + p); } } if (!rm.isEmpty()) { for (int i = (rm.size() - 1); i > -1; --i) { int rmIdx = rm.get(i); templateKP.remove(rmIdx); templateOrientations.removeAt(rmIdx); // move up operations. everything with index > i moves up by 1 for (int j = (i + 1); j < templateDescriptorsH.descriptors.length; ++j) { templateDescriptorsH.descriptors[j - 1] = templateDescriptorsH.descriptors[j]; templateDescriptorsS.descriptors[j - 1] = templateDescriptorsS.descriptors[j]; templateDescriptorsV.descriptors[j - 1] = templateDescriptorsV.descriptors[j]; } } int count = templateDescriptorsH.descriptors.length - rm.size(); templateDescriptorsH.descriptors = Arrays.copyOf(templateDescriptorsH.descriptors, count); templateDescriptorsS.descriptors = Arrays.copyOf(templateDescriptorsS.descriptors, count); templateDescriptorsV.descriptors = Arrays.copyOf(templateDescriptorsV.descriptors, count); } MiscDebug.writeImage(imgCp, "_template_orb"); } private ORB extractTemplateORBKeypoints(ImageExt img, Set<PairInt> shape0, int nKeypoints, float fastThresh, boolean useSmallPyramid, boolean createFirstDerivPts, boolean createCurvaturePts) throws IOException, Exception { int[] minMaxXY = MiscMath.findMinMaxXY(shape0); int w = img.getWidth(); int h = img.getHeight(); int buffer = 20; int xLL = minMaxXY[0] - buffer; if (xLL < 0) { xLL = 0; } int yLL = minMaxXY[2] - buffer; if (yLL < 0) { yLL = 0; } int xUR = minMaxXY[1] + buffer; if (xUR > (w - 1)) { xUR = w - 1; } int yUR = minMaxXY[3] + buffer; if (yUR > (h - 1)) { yUR = h - 1; } boolean overrideToCreateSmallestPyramid = useSmallPyramid; ORB orb = ORBWrapper.extractHSVKeypointsFromSubImage( img, xLL, yLL, xUR, yUR, nKeypoints, fastThresh, createFirstDerivPts, createCurvaturePts, overrideToCreateSmallestPyramid); // trim orb data that is outside of shape int ns = orb.getKeyPoint0List().size(); for (int i = 0; i < ns; ++i) { TIntList kp0 = orb.getKeyPoint0List().get(i); TIntList kp1 = orb.getKeyPoint1List().get(i); TDoubleList or = orb.getOrientationsList().get(i); TFloatList s = orb.getScalesList().get(i); Descriptors dH = orb.getDescriptorsH().get(i); Descriptors dS = orb.getDescriptorsS().get(i); Descriptors dV = orb.getDescriptorsV().get(i); int n0 = kp0.size(); TIntList rm = new TIntArrayList(); for (int j = 0; j < n0; ++j) { PairInt p = new PairInt(kp1.get(j), kp0.get(j)); if (!shape0.contains(p)) { rm.add(j); } } if (!rm.isEmpty()) { int nb = n0 - rm.size(); Descriptors dH2 = new Descriptors(); dH2.descriptors = new VeryLongBitString[nb]; Descriptors dS2 = new Descriptors(); dS2.descriptors = new VeryLongBitString[nb]; Descriptors dV2 = new Descriptors(); dV2.descriptors = new VeryLongBitString[nb]; TIntSet rmSet = new TIntHashSet(rm); for (int j = (rm.size() - 1); j > -1; --j) { int idx = rm.get(j); kp0.removeAt(idx); kp1.removeAt(idx); or.removeAt(idx); s.removeAt(idx); } int count = 0; for (int j = 0; j < n0; ++j) { if (rmSet.contains(j)) { continue; } dH2.descriptors[count] = dH.descriptors[j]; dS2.descriptors[count] = dS.descriptors[j]; dV2.descriptors[count] = dV.descriptors[j]; count++; } assert(count == nb); dH.descriptors = dH2.descriptors; dS.descriptors = dS2.descriptors; dV.descriptors = dV2.descriptors; } } {// DEBUG print each pyramid to see if has matchable points // might need to change the ORb response filter to scale by scale level for (int i0 = 0; i0 < orb.getKeyPoint0List().size(); ++i0) { Image img0Cp = img.copyImage(); float scale = orb.getScalesList().get(i0).get(0); for (int i = 0; i < orb.getKeyPoint0List().get(i0).size(); ++i) { int y = orb.getKeyPoint0List().get(i0).get(i); int x = orb.getKeyPoint1List().get(i0).get(i); ImageIOHelper.addPointToImage(x, y, img0Cp, 1, 255, 0, 0); } String str = Integer.toString(i0); if (str.length() < 2) { str = "0" + str; } MiscDebug.writeImage(img0Cp, "_template_orb" + str); } } return orb; } private TDoubleList extractKeypoints(ImageExt img, List<Set<PairInt>> listOfPointSets, List<PairInt> keypoints, Descriptors descriptors) throws IOException, Exception { // bins of size template size across image int w = img.getWidth(); int h = img.getHeight(); ORB orb = new ORB(1000); //orb.overrideFastThreshold(0.01f); orb.overrideFastThreshold(0.001f); orb.overrideToCreateHSVDescriptors(); orb.overrideToAlsoCreate1stDerivKeypoints(); orb.detectAndExtract(img); List<PairInt> kp = orb.getAllKeyPoints(); Descriptors d = orb.getAllDescriptors(); TDoubleList or = orb.getAllOrientations(); ImageExt img0 = img.copyToImageExt(); Set<PairInt> points = new HashSet<PairInt>(); for (Set<PairInt> set : listOfPointSets) { points.addAll(set); } Set<PairInt> exists = new HashSet<PairInt>(); TDoubleList orientations = new TDoubleArrayList(); for (int i = 0; i < kp.size(); ++i) { PairInt p = kp.get(i); if (exists.contains(p) || !points.contains(p)) { continue; } exists.add(p); keypoints.add(p); orientations.add(or.get(i)); ImageIOHelper.addPointToImage(p.getX(), p.getY(), img0, 1, 255, 0, 0); } exists.clear(); VeryLongBitString[] outD = new VeryLongBitString[keypoints.size()]; int count = 0; for (int i = 0; i < kp.size(); ++i) { PairInt p = kp.get(i); if (exists.contains(p) || !points.contains(p)) { continue; } exists.add(p); outD[count] = d.descriptors[i]; count++; } descriptors.descriptors = outD; MiscDebug.writeImage(img0, "_srch_orb"); return orientations; } private TDoubleList extractORBKeypoints(ImageExt img, List<Set<PairInt>> listOfPointSets, List<PairInt> keypoints, Descriptors descriptorsH, Descriptors descriptorsS, Descriptors descriptorsV) throws IOException, Exception { // bins of size template size across image int w = img.getWidth(); int h = img.getHeight(); ORB orb = new ORB(2000);//10000 //orb.overrideFastThreshold(0.01f); orb.overrideFastThreshold(0.001f); orb.overrideToCreateHSVDescriptors(); orb.overrideToAlsoCreate1stDerivKeypoints(); orb.overrideToCreateCurvaturePoints(); //orb.overrideToCreateOffsetsToDescriptors(ORB.DescriptorDithers.FIFTEEN); orb.detectAndExtract(img); List<PairInt> kp = orb.getAllKeyPoints(); Descriptors[] dHSV = orb.getAllDescriptorsHSV(); TDoubleList or = orb.getAllOrientations(); ImageExt img0 = img.copyToImageExt(); Set<PairInt> points = new HashSet<PairInt>(); for (Set<PairInt> set : listOfPointSets) { points.addAll(set); } Set<PairInt> exists = new HashSet<PairInt>(); TDoubleList orientations = new TDoubleArrayList(); for (int i = 0; i < kp.size(); ++i) { PairInt p = kp.get(i); if (exists.contains(p) || !points.contains(p)) { continue; } exists.add(p); keypoints.add(p); orientations.add(or.get(i)); ImageIOHelper.addPointToImage(p.getX(), p.getY(), img0, 1, 255, 0, 0); } exists.clear(); VeryLongBitString[] outH = new VeryLongBitString[keypoints.size()]; VeryLongBitString[] outS = new VeryLongBitString[keypoints.size()]; VeryLongBitString[] outV = new VeryLongBitString[keypoints.size()]; int count = 0; for (int i = 0; i < kp.size(); ++i) { PairInt p = kp.get(i); if (exists.contains(p) || !points.contains(p)) { continue; } exists.add(p); outH[count] = dHSV[0].descriptors[i]; outS[count] = dHSV[1].descriptors[i]; outV[count] = dHSV[2].descriptors[i]; count++; } descriptorsH.descriptors = outH; descriptorsS.descriptors = outS; descriptorsV.descriptors = outV; MiscDebug.writeImage(img0, "_srch_orb"); return orientations; } private Set<PairInt> createMedialAxis(Set<PairInt> points, Set<PairInt> perimeter) { MedialAxis medAxis = new MedialAxis(points, perimeter); medAxis.fastFindMedialAxis(); Set<PairInt> medAxisPts = medAxis.getMedialAxisPoints(); return medAxisPts; } public void estCIETheta() throws Exception { int maxDimension = 256;//512; SIGMA sigma = SIGMA.ZEROPOINTFIVE;//SIGMA.ONE; ImageProcessor imageProcessor = new ImageProcessor(); String[] fileNames1 = new String[]{ "android_statues_01.jpg", "android_statues_02.jpg", "android_statues_04.jpg", "android_statues_03.jpg" }; for (String fileName1 : fileNames1) { String fileName1Root = fileName1.substring(0, fileName1.lastIndexOf(".")); String filePath1 = ResourceFinder.findFileInTestResources(fileName1); ImageExt img = ImageIOHelper.readImageExt(filePath1); // template img size is 218 163 //img = (ImageExt) imageProcessor.bilinearDownSampling( // img, 218, 163, 0, 255); long ts = MiscDebug.getCurrentTimeFormatted(); int w1 = img.getWidth(); int h1 = img.getHeight(); int binFactor1 = (int) Math.ceil(Math.max( (float) w1 / maxDimension, (float) h1 / maxDimension)); img = imageProcessor.binImage(img, binFactor1); int w = img.getWidth(); int h = img.getHeight(); long t0 = System.currentTimeMillis(); // descriptors w/ masks /*corList = ORB.match2( orb0, orb, tempListOfPointSets, listOfPointSets2, 1.5f, 0.1f, false); */ /* GreyscaleImage theta1 = imageProcessor.createCIELABTheta(img, 255); MiscDebug.writeImage(theta1, fileName1Root + "_theta_"); GreyscaleImage theta_15 = imageProcessor.createCIELABTheta(img, 255, 15); MiscDebug.writeImage(theta_15, fileName1Root + "_theta_15_"); */ ImageSegmentation imageSegmentation = new ImageSegmentation(); ImageExt imgCp = img.copyToImageExt(); int[] labels = imageSegmentation.objectSegmentation3(imgCp); ImageIOHelper.addAlternatingColorLabelsToRegion( //LabelToColorHelper.applyLabels( imgCp, labels); MiscDebug.writeImage(imgCp, "_theta_segmentation_" + fileName1Root); imgCp = img.copyToImageExt(); labels = imageSegmentation.objectSegmentation(imgCp); ImageIOHelper.addAlternatingColorLabelsToRegion( //LabelToColorHelper.applyLabels( imgCp, labels); MiscDebug.writeImage(imgCp, "_hsv_segmentation_" + fileName1Root); } } private ImageExt[] maskAndBin2(String[] fileNames, int maxDimension, Set<PairInt> outputShape) throws IOException { ImageProcessor imageProcessor = new ImageProcessor(); String fileNameMask0 = fileNames[1]; String filePathMask0 = ResourceFinder .findFileInTestResources(fileNameMask0); ImageExt imgMask0 = ImageIOHelper.readImageExt(filePathMask0); String fileName0 = fileNames[0]; String filePath0 = ResourceFinder .findFileInTestResources(fileName0); ImageExt img0 = ImageIOHelper.readImageExt(filePath0); int w0 = img0.getWidth(); int h0 = img0.getHeight(); int binFactor0 = (int) Math.ceil(Math.max( (float) w0 / maxDimension, (float) h0 / maxDimension)); img0 = imageProcessor.binImage(img0, binFactor0); imgMask0 = imageProcessor.binImage(imgMask0, binFactor0); ImageExt img0Masked = img0.copyToImageExt(); assertEquals(imgMask0.getNPixels(), img0.getNPixels()); for (int i = 0; i < imgMask0.getNPixels(); ++i) { if (imgMask0.getR(i) == 0) { img0Masked.setRGB(i, 0, 0, 0); } else { outputShape.add(new PairInt(imgMask0.getCol(i), imgMask0.getRow(i))); } } return new ImageExt[]{img0, img0Masked}; } }
tests/algorithms/imageProcessing/features/AndroidStatuesTest.java
package algorithms.imageProcessing.features; import algorithms.MultiArrayMergeSort; import algorithms.compGeometry.MedialAxis; import algorithms.compGeometry.PerimeterFinder2; import algorithms.compGeometry.RotatedOffsets; import algorithms.compGeometry.clustering.KMeansHSV; import algorithms.compGeometry.clustering.KMeansPlusPlus; import algorithms.compGeometry.clustering.KMeansPlusPlusColor; import algorithms.imageProcessing.AdaptiveThresholding; import algorithms.imageProcessing.CIEChromaticity; import algorithms.imageProcessing.CannyEdgeFilterAdaptive; import algorithms.imageProcessing.ColorHistogram; import algorithms.imageProcessing.DFSContiguousIntValueFinder; import algorithms.imageProcessing.DFSContiguousValueFinder; import algorithms.imageProcessing.EdgeFilterProducts; import algorithms.imageProcessing.GreyscaleImage; import algorithms.imageProcessing.GroupPixelColors; import algorithms.imageProcessing.GroupPixelRGB; import algorithms.imageProcessing.GroupPixelRGB0; import algorithms.imageProcessing.Image; import algorithms.imageProcessing.ImageDisplayer; import algorithms.imageProcessing.ImageExt; import algorithms.imageProcessing.ImageIOHelper; import algorithms.imageProcessing.ImageProcessor; import algorithms.imageProcessing.ImageProcessor.Colors; import algorithms.imageProcessing.ImageSegmentation; import algorithms.imageProcessing.ImageSegmentation.DecimatedData; import algorithms.imageProcessing.PixelColors; import algorithms.imageProcessing.matching.PartialShapeMatcher; import algorithms.imageProcessing.SIGMA; import algorithms.imageProcessing.SegmentationMergeThreshold; import algorithms.imageProcessing.features.ORB.Descriptors; import algorithms.imageProcessing.features.ObjectMatcher.Settings; import algorithms.imageProcessing.matching.PartialShapeMatcher.Result; import algorithms.imageProcessing.matching.SegmentedCellDescriptorMatcher; import algorithms.imageProcessing.matching.ShapeFinder; import algorithms.imageProcessing.segmentation.ColorSpace; import algorithms.imageProcessing.segmentation.LabelToColorHelper; import algorithms.imageProcessing.segmentation.NormalizedCuts; import algorithms.imageProcessing.segmentation.SLICSuperPixels; import algorithms.imageProcessing.transform.TransformationParameters; import algorithms.imageProcessing.transform.Transformer; import algorithms.imageProcessing.util.AngleUtil; import algorithms.imageProcessing.util.GroupAverageColors; import algorithms.imageProcessing.util.MiscStats; import algorithms.imageProcessing.util.RANSACAlgorithmIterations; import algorithms.misc.Misc; import algorithms.misc.MiscDebug; import algorithms.misc.MiscMath; import algorithms.util.CorrespondencePlotter; import algorithms.util.PairInt; import algorithms.util.PairIntArray; import algorithms.util.PairIntPair; import algorithms.util.PolygonAndPointPlotter; import algorithms.util.QuadInt; import algorithms.util.ResourceFinder; import algorithms.util.TwoDFloatArray; import algorithms.util.TwoDIntArray; import algorithms.util.VeryLongBitString; import gnu.trove.iterator.TIntIterator; import gnu.trove.iterator.TIntObjectIterator; import gnu.trove.list.TDoubleList; import gnu.trove.list.TFloatList; import gnu.trove.list.TIntList; import gnu.trove.list.array.TDoubleArrayList; import gnu.trove.list.array.TFloatArrayList; import gnu.trove.list.array.TIntArrayList; import gnu.trove.map.TIntIntMap; import gnu.trove.map.TIntObjectMap; import gnu.trove.map.TObjectIntMap; import gnu.trove.map.hash.TIntIntHashMap; import gnu.trove.map.hash.TIntObjectHashMap; import gnu.trove.map.hash.TObjectIntHashMap; import gnu.trove.set.TIntSet; import gnu.trove.set.hash.TIntHashSet; import java.awt.image.ImageObserver; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.logging.Logger; import junit.framework.TestCase; import org.ejml.data.Complex64F; import org.ejml.simple.SimpleEVD; import org.ejml.simple.SimpleMatrix; import static org.junit.Assert.*; /** * * @author nichole */ public class AndroidStatuesTest extends TestCase { private Logger log = Logger.getLogger(this.getClass().getName()); public AndroidStatuesTest() { } public void est0() throws Exception { int maxDimension = 256;//512; String fileName1 = ""; //for (int i = 0; i < 1; ++i) { for (int i = 0; i < 37; ++i) { switch(i) { case 0: { fileName1 = "android_statues_01.jpg"; break; } case 1: { fileName1 = "android_statues_02.jpg"; break; } case 2: { fileName1 = "android_statues_03.jpg"; break; } case 3: { fileName1 = "android_statues_04.jpg"; break; } case 4: { fileName1 = "seattle.jpg"; break; } case 5: { fileName1 = "stonehenge.jpg"; break; } case 6: { fileName1 = "cloudy_san_jose.jpg"; break; } case 7: { fileName1 = "patagonia_snowy_foreground.jpg"; break; } case 8: { fileName1 = "mt_rainier_snowy_field.jpg"; break; } case 9: { fileName1 = "brown_lowe_2003_image1.jpg"; break; } case 10: { fileName1 = "brown_lowe_2003_image2.jpg"; break; } case 11: { fileName1 = "venturi_mountain_j6_0001.png"; break; } case 12: { fileName1 = "venturi_mountain_j6_0010.png"; break; } case 13: { fileName1 = "campus_010.jpg"; break; } case 14: { fileName1 = "campus_011.jpg"; break; } case 15: { fileName1 = "merton_college_I_001.jpg"; break; } case 16: { fileName1 = "merton_college_I_002.jpg"; break; } case 17: { fileName1 = "arches.jpg"; break; } case 18: { fileName1 = "stinson_beach.jpg"; break; } case 19: { fileName1 = "norwegian_mtn_range.jpg"; break; } case 20: { fileName1 = "halfdome.jpg"; break; } case 21: { fileName1 = "halfdome2.jpg"; break; } case 22: { fileName1 = "halfdome3.jpg"; break; } case 23: { fileName1 = "costa_rica.jpg"; break; } case 24: { fileName1 = "new-mexico-sunrise_w725_h490.jpg"; break; } case 25: { fileName1 = "arizona-sunrise-1342919937GHz.jpg"; break; } case 26: { fileName1 = "sky_with_rainbow.jpg"; break; } case 27: { fileName1 = "sky_with_rainbow2.jpg"; break; } case 28: { fileName1 = "books_illum3_v0_695x555.png"; break; } case 29: { fileName1 = "books_illum3_v6_695x555.png"; break; } case 30: { fileName1 = "klein_matterhorn_snowy_foreground.jpg"; break; } case 31: { fileName1 = "30.jpg"; break; } case 32: { fileName1 = "arches_sun_01.jpg"; break; } case 33: { fileName1 = "stlouis_arch.jpg"; break; } case 34: { fileName1 = "contrail.jpg"; break; } case 35: { fileName1 = "checkerboard_01.jpg"; break; } default: { fileName1 = "checkerboard_02.jpg"; break; } } int idx = fileName1.lastIndexOf("."); String fileName1Root = fileName1.substring(0, idx); String filePath1 = ResourceFinder.findFileInTestResources(fileName1); ImageExt img = ImageIOHelper.readImageExt(filePath1); ImageProcessor imageProcessor = new ImageProcessor(); ImageSegmentation imageSegmentation = new ImageSegmentation(); int w1 = img.getWidth(); int h1 = img.getHeight(); int binFactor1 = (int) Math.ceil(Math.max( (float) w1 / maxDimension, (float) h1 / maxDimension)); img = imageProcessor.binImage(img, binFactor1); int[] labels4 = imageSegmentation.objectSegmentation(img); ImageExt img11 = img.createWithDimensions(); ImageIOHelper.addAlternatingColorLabelsToRegion( img11, labels4); MiscDebug.writeImage(img11, "_final_" + fileName1Root); //LabelToColorHelper.applyLabels(img, labels4); //MiscDebug.writeImage(img, "_final_" + fileName1Root); {// --- a look at the angles of phase and orientation plotted ---- List<Set<PairInt>> contigSets = LabelToColorHelper.extractContiguousLabelPoints( img, labels4); List<PairIntArray> orderedBoundaries = new ArrayList<PairIntArray>(); int w = img.getWidth(); int h = img.getHeight(); SIGMA sigma = SIGMA.ZEROPOINTFIVE;//SIGMA.ONE; for (int ii = 0; ii < contigSets.size(); ++ii) { Set<PairInt> set = contigSets.get(ii); Set<PairInt> medialAxis = new HashSet<PairInt>(); PairIntArray p = imageProcessor.extractSmoothedOrderedBoundary( set, sigma, w, h, medialAxis); if (p.getN() > 24) { orderedBoundaries.add(p); } } EdgeFilterProducts products = imageSegmentation .createPhaseCongruencyGradient( img.copyToGreyscale()); img11 = img.copyToImageExt(); for (int ii = 0; ii < orderedBoundaries.size(); ++ii) { PairIntArray a = orderedBoundaries.get(ii); for (int j = 0; j < a.getN(); j += 10) { int x = a.getX(j); int y = a.getY(j); double or = products.getTheta().getValue(x, y) * Math.PI/180.; double pa = products.getPhaseAngle().getValue(x, y) * Math.PI/180.; int dx0 = (int)Math.round(3. * Math.cos(or)); int dy0 = (int)Math.round(3. * Math.sin(or)); int dx1 = (int)Math.round(3. * Math.cos(pa)); int dy1 = (int)Math.round(3. * Math.sin(pa)); ImageIOHelper.addPointToImage(x, y, img11, 1, 255, 0, 0); int x2, y2; x2 = x + dx0; y2 = y + dy0; if (x2 >= 0 && x2 < w && y2 >= 0 && y2 < h) { ImageIOHelper.drawLineInImage(x, y, x2, y2, img11, 0, 255, 255, 0); } x2 = x + dx1; y2 = y + dy1; if (x2 >= 0 && x2 < w && y2 >= 0 && y2 < h) { ImageIOHelper.drawLineInImage(x, y, x2, y2, img11, 0, 0, 0, 255); } } } MiscDebug.writeImage(img11, "_aa_" + fileName1Root); } } } public void testORBMatcher2() throws Exception { /* this demonstrates ORB followed by filtering of search image keypoints by color. then matching by descriptors and evaluation of pair combinations of best mathing keypoints from which euclidean transformaions are derived. */ int maxDimension = 256;//512; SIGMA sigma = SIGMA.ZEROPOINTFIVE;//SIGMA.ONE; ImageProcessor imageProcessor = new ImageProcessor(); ImageSegmentation imageSegmentation = new ImageSegmentation(); String[] fileNames0 = new String[]{ "android_statues_03_sz1", "android_statues_03_sz3" }; String[] fileNames1 = new String[]{ "android_statues_01.jpg", "android_statues_02.jpg", "android_statues_04.jpg", "android_statues_03.jpg" }; int fn0 = 0; for (String fileNameRoot0 : fileNames0) { fn0++; for (String fileName1 : fileNames1) { long t0 = System.currentTimeMillis(); Set<PairInt> shape0 = new HashSet<PairInt>(); // to compare to "android_statues_01.jpg", // set this to '2' int binFactor0 = 1; // 1st image is color image, 2nd is masked color image // 218 X 163... full size is 1280 X 960 ImageExt[] imgs0 = maskAndBin(fileNameRoot0, binFactor0, shape0); int nShape0_0 = shape0.size(); System.out.println("shape0 nPts=" + nShape0_0); String fileName1Root = fileName1.substring(0, fileName1.lastIndexOf(".")); String filePath1 = ResourceFinder.findFileInTestResources( fileName1); ImageExt img = ImageIOHelper.readImageExt(filePath1); // template img size is 218 163 //img = (ImageExt) imageProcessor.bilinearDownSampling( // img, 218, 163, 0, 255); long ts = MiscDebug.getCurrentTimeFormatted(); int w1 = img.getWidth(); int h1 = img.getHeight(); int binFactor1 = (int) Math.ceil(Math.max( (float) w1 / maxDimension, (float) h1 / maxDimension)); img = imageProcessor.binImage(img, binFactor1); int w = img.getWidth(); int h = img.getHeight(); /*RANSACAlgorithmIterations nsIter = new RANSACAlgorithmIterations(); long nnn = nsIter.estimateNIterFor99PercentConfidence( 300, 7, 20./300.); System.out.println("99 percent nIter for RANSAC=" + nnn);*/ Settings settings = new Settings(); ObjectMatcher objMatcher = new ObjectMatcher(); if (fileName1Root.contains("_01")) { settings.setToUseSmallObjectMethod(); } //settings.setToUseLargerPyramid0(); objMatcher.setToDebug(); CorrespondenceList cor = objMatcher.findObject(imgs0[0], shape0, img, settings); long t1 = System.currentTimeMillis(); System.out.println("matching took " + ((t1 - t0)/1000.) + " sec"); CorrespondencePlotter plotter = new CorrespondencePlotter( imgs0[1], img.copyImage()); for (int ii = 0; ii < cor.getPoints1().size(); ++ii) { PairInt p1 = cor.getPoints1().get(ii); PairInt p2 = cor.getPoints2().get(ii); //System.out.println("orb matched: " + p1 + " " + p2); //if (p2.getX() > 160) plotter.drawLineInAlternatingColors(p1.getX(), p1.getY(), p2.getX(), p2.getY(), 0); } plotter.writeImage("_orb_corres_final_" + "_" + fileName1Root + "_" + fn0); System.out.println(cor.getPoints1().size() + " matches " + fileName1Root); //MiscDebug.writeImage(img11, "_orb_matched_" + str // + "_" + fileName1Root); } } } public void estMkImgs() throws Exception { String fileName1 = ""; for (int i = 0; i < 4; ++i) { switch(i) { case 0: { fileName1 = "android_statues_01.jpg"; break;} case 1: { fileName1 = "android_statues_02.jpg"; break;} case 2: { fileName1 = "android_statues_03.jpg"; break;} case 3: { fileName1 = "android_statues_04.jpg"; break;} default: {break;} } int idx = fileName1.lastIndexOf("."); String fileName1Root = fileName1.substring(0, idx); String filePath1 = ResourceFinder.findFileInTestResources(fileName1); ImageExt img = ImageIOHelper.readImageExt(filePath1); int w1 = img.getWidth(); int h1 = img.getHeight(); int maxDimension = 512; int binFactor1 = (int) Math.ceil(Math.max((float) w1 / maxDimension, (float) h1 / maxDimension)); ImageProcessor imageProcessor = new ImageProcessor(); img = imageProcessor.binImage(img, binFactor1); ImageExt imgCp = img.copyToImageExt(); int nClusters = 200;//100; //int clrNorm = 5; SLICSuperPixels slic = new SLICSuperPixels(img, nClusters); slic.calculate(); int[] labels = slic.getLabels(); ImageIOHelper.addAlternatingColorLabelsToRegion( //LabelToColorHelper.applyLabels( img, labels); MiscDebug.writeImage(img, "_slic_" + fileName1Root); NormalizedCuts normCuts = new NormalizedCuts(); normCuts.setColorSpaceToHSV(); int[] labels2 = normCuts.normalizedCut(imgCp, labels); labels = labels2; ImageIOHelper.addAlternatingColorLabelsToRegion( imgCp, labels); MiscDebug.writeImage(imgCp, "_norm_cuts_" + fileName1Root); //img = ImageIOHelper.readImageExt(filePath1); //img = imageProcessor.binImage(img, binFactor1); //MiscDebug.writeImage(img, "_512_img_" + fileName1Root); } } public void estColorLayout() throws Exception { String[] fileNames = new String[]{ "android_statues_01.jpg", "android_statues_02.jpg", "android_statues_03.jpg", "android_statues_04.jpg" }; // paused here. editing to use super pixels // and a pattern of color aggregation // w/ voronoi cells for comparison to model, // then a partial shape matching algorithm. ImageProcessor imageProcessor = new ImageProcessor(); ImageSegmentation imageSegmentation = new ImageSegmentation(); List<ImageExt> images = new ArrayList<ImageExt>(); for (int i = 0; i < fileNames.length; ++i) { String fileName = fileNames[i]; String filePath = ResourceFinder.findFileInTestResources(fileName); String fileNameRoot = fileName.substring(0, fileName.lastIndexOf(".")); ImageExt img = ImageIOHelper.readImageExt(filePath); images.add(img); /* wanting to look at color similarity of pixels holding known objects that have different orientation and lighting in different images. -- android -- ice cream -- eclair -- cupcake bigger goal is to use segmentation to find object outlines then identify the object in other images and follow that with detailed feature matching. the method has to work on objects that have changed position and possibly also lighting. the method may need some form of contour matching for pure sillouhette conditions but would need to allow for occlusion. deltaE for gingerbread man in the 4 images is at most 5, else 3.7 and 1.8. */ } } private PairIntArray extractOrderedBoundary(ImageExt image) { return extractOrderedBoundary(image, SIGMA.TWO); } private PairIntArray extractOrderedBoundary(ImageExt image, SIGMA sigma) { GreyscaleImage img = image.copyToGreyscale(); Set<PairInt> blob = new HashSet<PairInt>(); for (int i = 0; i < img.getNPixels(); ++i) { if (img.getValue(i) > 0) { int x = img.getCol(i); int y = img.getRow(i); blob.add(new PairInt(x, y)); } } ImageProcessor imageProcessor = new ImageProcessor(); PairIntArray ordered = imageProcessor.extractSmoothedOrderedBoundary( blob, sigma, img.getWidth(), img.getHeight()); return ordered; } private void sortByDecrSize(List<Set<PairInt>> clusterSets) { int n = clusterSets.size(); int[] sizes = new int[n]; int[] indexes = new int[n]; for (int i = 0; i < n; ++i) { sizes[i] = clusterSets.get(i).size(); indexes[i] = i; } MultiArrayMergeSort.sortByDecr(sizes, indexes); List<Set<PairInt>> out = new ArrayList<Set<PairInt>>(); for (int i = 0; i < n; ++i) { int idx = indexes[i]; out.add(clusterSets.get(idx)); } clusterSets.clear(); clusterSets.addAll(out); } private void printGradients(ImageExt img, String fileNameRoot) { GreyscaleImage gsImg = img.copyToGreyscale(); GreyscaleImage gsImg1 = gsImg.copyImage(); GreyscaleImage gsImg2 = gsImg.copyImage(); CannyEdgeFilterAdaptive canny = new CannyEdgeFilterAdaptive(); canny.overrideToNotUseLineThinner(); canny.applyFilter(gsImg); for (int i = 0; i < gsImg.getNPixels(); ++i) { if (gsImg.getValue(i) > 0) { gsImg.setValue(i, 255); } } MiscDebug.writeImage(gsImg, "_canny_" + fileNameRoot); ImageProcessor imageProcessor = new ImageProcessor(); imageProcessor.applyFirstDerivGaussian(gsImg1, SIGMA.ONE, 0, 255); for (int i = 0; i < gsImg1.getNPixels(); ++i) { if (gsImg1.getValue(i) > 0) { gsImg1.setValue(i, 255); } } MiscDebug.writeImage(gsImg1, "_firstderiv_" + fileNameRoot); PhaseCongruencyDetector pcd = new PhaseCongruencyDetector(); PhaseCongruencyDetector.PhaseCongruencyProducts product = pcd.phaseCongMono(gsImg2); MiscDebug.writeImage(product.getThinned(), "_pcd_" + fileNameRoot); } private TIntList addIntersection(GreyscaleImage gradient, int[] labels) { assert(gradient.getNPixels() == labels.length); int maxLabel = MiscMath.findMax(labels) + 1; int[] dxs = Misc.dx8; int[] dys = Misc.dy8; int w = gradient.getWidth(); int h = gradient.getHeight(); TIntList change = new TIntArrayList(); for (int i = 0; i < gradient.getNPixels(); ++i) { if (gradient.getValue(i) < 1) { continue; } int x = gradient.getCol(i); int y = gradient.getRow(i); int l0 = labels[i]; int l1 = -1; for (int k = 0; k < dxs.length; ++k) { int x2 = x + dxs[k]; int y2 = y + dys[k]; if (x2 < 0 || y2 < 0 || (x2 > (w - 1)) || (y2 > (h - 1))) { continue; } int j = gradient.getInternalIndex(x2, y2); int lt = labels[j]; if (lt != l0) { if (l1 == -1) { l1 = lt; } } } if (l1 != -1) { // gradient is on edge of superpixels change.add(i); System.out.println( "x=" + x + " y=" + y + " pixIdx=" + i); } } return change; } private int[] desegment(ImageExt img, TIntList gradSP, int[] labels, int[] labels2) { int[] dxs = Misc.dx8; int[] dys = Misc.dy8; int w = img.getWidth(); int h = img.getHeight(); TIntSet restore = new TIntHashSet(); for (int i = 0; i < gradSP.size(); ++i) { int pixIdx = gradSP.get(i); int l0 = labels2[pixIdx]; int l1 = -1; int x = img.getCol(pixIdx); int y = img.getRow(pixIdx); for (int k = 0; k < dxs.length; ++k) { int x2 = x + dxs[k]; int y2 = y + dys[k]; if (x2 < 0 || y2 < 0 || (x2 > (w - 1)) || (y2 > (h - 1))) { continue; } int j = img.getInternalIndex(x2, y2); int lt = labels2[j]; if (lt != l0) { if (l1 == -1) { l1 = lt; } } } if (l1 == -1) { // these need boundaries restored ImageIOHelper.addPointToImage(x, y, img, 1, 255, 0, 0); restore.add(labels[pixIdx]); } } MiscDebug.writeImage(img, "restore"); if (restore.isEmpty()) { return labels2; } TIntObjectMap<Set<PairInt>> label1PointMap = LabelToColorHelper.extractLabelPoints(img, labels); int[] labels3 = Arrays.copyOf(labels2, labels2.length); int maxLabel = MiscMath.findMax(labels2); maxLabel++; TIntIterator iter = restore.iterator(); while (iter.hasNext()) { int label = iter.next(); Set<PairInt> pts = label1PointMap.get(label); for (PairInt pt : pts) { int x = pt.getX(); int y = pt.getY(); int pixIdx = img.getInternalIndex(x, y); labels3[pixIdx] = maxLabel; } maxLabel++; } return labels3; } private ImageExt[] maskAndBin(String fileNamePrefix, int binFactor, Set<PairInt> outputShape) throws IOException, Exception { ImageProcessor imageProcessor = new ImageProcessor(); String fileNameMask0 = fileNamePrefix + "_mask.png"; String filePathMask0 = ResourceFinder .findFileInTestResources(fileNameMask0); ImageExt imgMask0 = ImageIOHelper.readImageExt(filePathMask0); String fileName0 = fileNamePrefix + ".jpg"; String filePath0 = ResourceFinder .findFileInTestResources(fileName0); ImageExt img0 = ImageIOHelper.readImageExt(filePath0); if (binFactor != 1) { img0 = imageProcessor.binImage(img0, binFactor); imgMask0 = imageProcessor.binImage(imgMask0, binFactor); } ImageExt img0Masked = img0.copyToImageExt(); assertEquals(imgMask0.getNPixels(), img0.getNPixels()); for (int i = 0; i < imgMask0.getNPixels(); ++i) { if (imgMask0.getR(i) == 0) { img0Masked.setRGB(i, 0, 0, 0); } else { outputShape.add(new PairInt(imgMask0.getCol(i), imgMask0.getRow(i))); } } //MiscDebug.writeImage(img0Masked, "_MASKED"); return new ImageExt[]{img0, img0Masked}; } public void estMatching() throws Exception { String fileName1, fileName2; FeatureMatcherSettings settings = new FeatureMatcherSettings(); settings.setDebug(true); settings.setStartWithBinnedImages(true); settings.setToUse2ndDerivCorners(); //for (int i = 0; i < 7; ++i) { for (int i = 0; i < 3; ++i) { switch(i) { case 0: { fileName1 = "android_statues_02.jpg"; fileName2 = "android_statues_04.jpg"; //fileName1 = "android_statues_02_gingerbreadman.jpg"; //fileName2 = "android_statues_04_gingerbreadman.jpg"; settings.setUseNormalizedFeatures(true); break; } case 1: { fileName1 = "android_statues_01.jpg"; fileName2 = "android_statues_03.jpg"; settings.setUseNormalizedFeatures(true); break; } case 2: { fileName1 = "brown_lowe_2003_image1.jpg"; fileName2 = "brown_lowe_2003_image2.jpg"; settings.setUseNormalizedFeatures(true); break; } case 3: { fileName2 = "brown_lowe_2003_image1.jpg"; fileName1 = "brown_lowe_2003_image2.jpg"; break; } case 4: { fileName1 = "venturi_mountain_j6_0001.png"; fileName2 = "venturi_mountain_j6_0010.png"; settings.setUseNormalizedFeatures(true); break; } case 5: { fileName1 = "campus_010.jpg"; fileName2 = "campus_011.jpg"; settings.setUseNormalizedFeatures(true); break; } case 6: { fileName1 = "merton_college_I_001.jpg"; fileName2 = "merton_college_I_002.jpg"; settings.setUseNormalizedFeatures(true); break; } default: { fileName1 = "checkerboard_01.jpg"; fileName2 = "checkerboard_02.jpg"; settings.setUseNormalizedFeatures(true); break; } } runCorrespondenceList(fileName1, fileName2, settings, false); } } public void estRot90() throws Exception { String fileName1, fileName2; FeatureMatcherSettings settings = new FeatureMatcherSettings(); settings.setDebug(true); settings.setStartWithBinnedImages(true); for (int i = 0; i < 5; ++i) { fileName1 = null; fileName2 = null; switch(i) { case 0: { fileName1 = "android_statues_02.jpg"; fileName2 = "android_statues_04.jpg"; //fileName1 = "campus_010.jpg"; //fileName2 = "campus_011.jpg"; settings.setUseNormalizedFeatures(true); settings.setToUse2ndDerivCorners(); break; } default: { fileName1 = "android_statues_01.jpg"; fileName2 = "android_statues_03.jpg"; settings.setUseNormalizedFeatures(true); settings.setToUse2ndDerivCorners(); break; } } runCorrespondenceList(fileName1, fileName2, settings, true); } } private void runCorrespondenceList(String fileName1, String fileName2, FeatureMatcherSettings settings, boolean rotateBy90) throws Exception { if (fileName1 == null) { return; } int idx = fileName1.lastIndexOf("."); String fileName1Root = fileName1.substring(0, idx); idx = fileName2.lastIndexOf("."); String fileName2Root = fileName2.substring(0, idx); settings.setDebugTag(fileName1Root); String filePath1 = ResourceFinder.findFileInTestResources(fileName1); ImageExt img1 = ImageIOHelper.readImageExt(filePath1); String filePath2 = ResourceFinder.findFileInTestResources(fileName2); ImageExt img2 = ImageIOHelper.readImageExt(filePath2); ImageProcessor imageProcessor = new ImageProcessor(); ImageSegmentation imageSegmentation = new ImageSegmentation(); int w1 = img1.getWidth(); int h1 = img1.getHeight(); int w2 = img2.getWidth(); int h2 = img2.getHeight(); int maxDimension = 350; int binFactor1 = (int) Math.ceil(Math.max((float)w1/maxDimension, (float)h1/ maxDimension)); int binFactor2 = (int) Math.ceil(Math.max((float)w2/maxDimension, (float)h2/ maxDimension)); ImageExt img1Binned = imageProcessor.binImage(img1, binFactor1); ImageExt img2Binned = imageProcessor.binImage(img2, binFactor2); if (rotateBy90) { TransformationParameters params90 = new TransformationParameters(); params90.setRotationInDegrees(90); params90.setOriginX(0); params90.setOriginY(0); params90.setTranslationX(0); params90.setTranslationY(img1.getWidth() - 1); Transformer transformer = new Transformer(); img1 = (ImageExt) transformer.applyTransformation(img1, params90, img1.getHeight(), img1.getWidth()); /* MatchedPointsTransformationCalculator tc = new MatchedPointsTransformationCalculator(); TransformationParameters revParams = tc.swapReferenceFrames(params90); transformer.transformToOrigin(0, 0, revParams); revParams.setTranslationX(revParams.getTranslationX() + -74); revParams.setTranslationY(revParams.getTranslationY() + -0); revParams.setRotationInDegrees(revParams.getRotationInDegrees() - 0); log.info("revParams: " + revParams.toString()); ImageExt img1RevTr = img1.copyToImageExt(); img1RevTr = (ImageExt) transformer.applyTransformation(img1RevTr, revParams, img1RevTr.getHeight(), img1RevTr.getWidth()); MiscDebug.writeImage(img1RevTr, "rot90_rev_trans"); */ } RotatedOffsets rotatedOffsets = RotatedOffsets.getInstance(); log.info("fileName1Root=" + fileName1Root); EpipolarColorSegmentedSolver solver = new EpipolarColorSegmentedSolver(img1, img2, settings); boolean solved = solver.solve(); assertTrue(solved); //MiscDebug.writeImagesInAlternatingColor(img1, img2, stats, // fileName1Root + "_matched_non_euclid", 2); } public static void main(String[] args) { try { AndroidStatuesTest test = new AndroidStatuesTest(); //test.test0(); //test.testRot90(); } catch(Exception e) { e.printStackTrace(); System.err.println(e.getMessage()); fail(e.getMessage()); } } public void estColor() throws Exception { //String fileName1 = "android_statues_02.jpg"; //String fileName2 = "android_statues_04.jpg"; String fileName1 = "android_statues_02_gingerbreadman.jpg"; String fileName2 = "android_statues_04_gingerbreadman.jpg"; int idx = fileName1.lastIndexOf("."); String fileName1Root = fileName1.substring(0, idx); idx = fileName2.lastIndexOf("."); String fileName2Root = fileName2.substring(0, idx); String filePath1 = ResourceFinder.findFileInTestResources(fileName1); ImageExt img1 = ImageIOHelper.readImageExt(filePath1); String filePath2 = ResourceFinder.findFileInTestResources(fileName2); ImageExt img2 = ImageIOHelper.readImageExt(filePath2); CIEChromaticity cieC = new CIEChromaticity(); int binnedImageMaxDimension = 512; int binFactor1 = (int) Math.ceil( Math.max((float) img1.getWidth() / (float)binnedImageMaxDimension, (float) img1.getHeight() / (float)binnedImageMaxDimension)); int binFactor2 = (int) Math.ceil( Math.max((float) img2.getWidth() / (float)binnedImageMaxDimension, (float) img2.getHeight() / (float)binnedImageMaxDimension)); ImageProcessor imageProcessor = new ImageProcessor(); ImageExt imgBinned1 = imageProcessor.binImage(img1, binFactor1); ImageExt imgBinned2 = imageProcessor.binImage(img2, binFactor2); /* HistogramEqualizationForColor hEq = new HistogramEqualizationForColor(imgBinned1); hEq.applyFilter(); hEq = new HistogramEqualizationForColor(imgBinned2); hEq.applyFilter(); */ RotatedOffsets rotatedOffsets = RotatedOffsets.getInstance(); GreyscaleImage redBinnedImg1 = imgBinned1.copyRedToGreyscale(); GreyscaleImage greenBinnedImg1 = imgBinned1.copyGreenToGreyscale(); GreyscaleImage blueBinnedImg1 = imgBinned1.copyBlueToGreyscale(); GreyscaleImage redBinnedImg2 = imgBinned2.copyRedToGreyscale(); GreyscaleImage greenBinnedImg2 = imgBinned2.copyGreenToGreyscale(); GreyscaleImage blueBinnedImg2 = imgBinned2.copyBlueToGreyscale(); GreyscaleImage gsImg1 = imgBinned1.copyToGreyscale(); GreyscaleImage gsImg2 = imgBinned2.copyToGreyscale(); IntensityClrFeatures clrFeaturesBinned1 = new IntensityClrFeatures(gsImg1.copyImage(), 5, rotatedOffsets); IntensityClrFeatures clrFeaturesBinned2 = new IntensityClrFeatures(gsImg2.copyImage(), 5, rotatedOffsets); IntensityFeatures features1 = new IntensityFeatures(5, true, rotatedOffsets); IntensityFeatures features2 = new IntensityFeatures(5, true, rotatedOffsets); /* looking at trace/determinant of autocorrelation and eigenvalues of greyscale, autocorrelation, and lab colors for selected points in both images statues subsets: 0 (64, 100) (96, 109) 1 (67, 103) (103, 111) 2 (68, 78) (113, 86) 3 (66, 49) (106, 50) 4 (92, 108) (157, 118) 5 (92, 111) (160, 122) delta e = 28.9 6 (69, 129) (108, 142) delta e = 26.4 is the edelta for the gingerbread man's white stripes and shadows the same for shadow and higher illumination? */ // single values of edelta List<PairInt> points1 = new ArrayList<PairInt>(); List<PairInt> points2 = new ArrayList<PairInt>(); points1.add(new PairInt(64, 100)); points2.add(new PairInt(96, 109)); points1.add(new PairInt(67, 103)); points2.add(new PairInt(103, 111)); points1.add(new PairInt(68, 78)); points2.add(new PairInt(113, 86)); points1.add(new PairInt(66, 49)); points2.add(new PairInt(106, 50)); points1.add(new PairInt(92, 108)); points2.add(new PairInt(157, 118)); points1.add(new PairInt(92, 111)); points2.add(new PairInt(160, 122)); points1.add(new PairInt(69, 129)); points2.add(new PairInt(108, 142)); // this one is too look at localizability: points1.add(new PairInt(46, 65)); points2.add(new PairInt(6, 4)); int n = points1.size(); for (int i = 0; i < n; ++i) { StringBuilder sb = new StringBuilder(); PairInt p1 = points1.get(i); PairInt p2 = points2.get(i); sb.append(p1.toString()).append(p2.toString()); int r1 = redBinnedImg1.getValue(p1.getX(), p1.getY()); int g1 = greenBinnedImg1.getValue(p1.getX(), p1.getY()); int b1 = blueBinnedImg1.getValue(p1.getX(), p1.getY()); int r2 = redBinnedImg2.getValue(p2.getX(), p2.getY()); int g2 = greenBinnedImg2.getValue(p2.getX(), p2.getY()); int b2 = blueBinnedImg2.getValue(p2.getX(), p2.getY()); float[] lab1 = cieC.rgbToCIELAB(r1, g1, b1); float[] lab2 = cieC.rgbToCIELAB(r2, g2, b2); float[] cieXY1 = cieC.rgbToCIEXYZ(r1, g1, b1); float[] cieXY2 = cieC.rgbToCIEXYZ(r2, g2, b2); double deltaE = cieC.calcDeltaECIE94(lab1, lab2); sb.append(String.format(" dE=%.1f", (float)deltaE)); int rot1 = clrFeaturesBinned1.calculateOrientation(p1.getX(), p1.getY()); int rot2 = clrFeaturesBinned2.calculateOrientation(p2.getX(), p2.getY()); IntensityDescriptor desc_l1 = clrFeaturesBinned1.extractIntensityLOfCIELAB( redBinnedImg1, greenBinnedImg1, blueBinnedImg1, p1.getX(), p1.getY(), rot1); IntensityDescriptor desc_a1 = clrFeaturesBinned1.extractIntensityAOfCIELAB( redBinnedImg1, greenBinnedImg1, blueBinnedImg1, p1.getX(), p1.getY(), rot1); IntensityDescriptor desc_b1 = clrFeaturesBinned1.extractIntensityBOfCIELAB( redBinnedImg1, greenBinnedImg1, blueBinnedImg1, p1.getX(), p1.getY(), rot1); IntensityDescriptor desc_l2 = clrFeaturesBinned2.extractIntensityLOfCIELAB( redBinnedImg2, greenBinnedImg2, blueBinnedImg2, p2.getX(), p2.getY(), rot2); IntensityDescriptor desc_a2 = clrFeaturesBinned2.extractIntensityAOfCIELAB( redBinnedImg2, greenBinnedImg2, blueBinnedImg2, p2.getX(), p2.getY(), rot2); IntensityDescriptor desc_b2 = clrFeaturesBinned2.extractIntensityBOfCIELAB( redBinnedImg2, greenBinnedImg2, blueBinnedImg2, p2.getX(), p2.getY(), rot2); IntensityDescriptor desc1 = features1.extractIntensity(gsImg1, p1.getX(), p1.getY(), rot1); IntensityDescriptor desc2 = features2.extractIntensity(gsImg2, p2.getX(), p2.getY(), rot2); double det, trace; SimpleMatrix a_l1 = clrFeaturesBinned1.createAutoCorrelationMatrix(desc_l1); det = a_l1.determinant(); trace = a_l1.trace(); sb.append(String.format("\n L1_det(A)/trace=%.1f", (float)(det/trace))); SimpleMatrix a_l2 = clrFeaturesBinned2.createAutoCorrelationMatrix(desc_l2); det = a_l2.determinant(); trace = a_l2.trace(); sb.append(String.format(" L2_det(A)/trace=%.1f", (float)(det/trace))); try { sb.append("\n eigen values:\n"); SimpleEVD eigen1 = a_l1.eig(); for (int j = 0; j < eigen1.getNumberOfEigenvalues(); ++j) { Complex64F eigen = eigen1.getEigenvalue(j); sb.append(String.format(" [1] %d %.1f %.1f\n", j, (float)eigen.getReal(), (float)eigen.getMagnitude())); } sb.append("\n"); SimpleEVD eigen2 = a_l2.eig(); for (int j = 0; j < eigen2.getNumberOfEigenvalues(); ++j) { Complex64F eigen = eigen2.getEigenvalue(j); sb.append(String.format(" [1] %d %.1f %.1f\n", j, (float)eigen.getReal(), (float)eigen.getMagnitude())); } } catch (Throwable t) { } if (desc1 != null && desc2 != null) { SimpleMatrix gs_l1 = features1.createAutoCorrelationMatrix(desc1); det = gs_l1.determinant(); trace = gs_l1.trace(); sb.append(String.format("\n Grey_det(A)/trace=%.1f", (float)(det/trace))); SimpleMatrix gs_l2 = features2.createAutoCorrelationMatrix(desc2); det = gs_l2.determinant(); trace = gs_l2.trace(); sb.append(String.format(" Grey_det(A)/trace=%.1f", (float)(det/trace))); try { sb.append("\n eigen values:\n"); SimpleEVD eigen1 = gs_l1.eig(); for (int j = 0; j < eigen1.getNumberOfEigenvalues(); ++j) { Complex64F eigen = eigen1.getEigenvalue(j); sb.append(String.format(" [1] %d %.1f %.1f\n", j, (float) eigen.getReal(), (float) eigen.getMagnitude())); } sb.append("\n"); SimpleEVD eigen2 = gs_l2.eig(); for (int j = 0; j < eigen2.getNumberOfEigenvalues(); ++j) { Complex64F eigen = eigen2.getEigenvalue(j); sb.append(String.format(" [2] %d %.1f %.1f\n", j, (float) eigen.getReal(), (float) eigen.getMagnitude())); } } catch (Throwable t) { } } log.info(sb.toString()); } } private void populateClasses(Set<PairIntPair> similarClass, Set<PairIntPair> differentClass, String fileNameRoot) throws IOException { BufferedReader bReader = null; FileReader reader = null; String fileName = "label_" + fileNameRoot + "_coords.csv"; String filePath = ResourceFinder.findFileInTestResources(fileName); try { reader = new FileReader(new File(filePath)); bReader = new BufferedReader(reader); //read comment line and discard String line = bReader.readLine(); line = bReader.readLine(); while (line != null) { String[] items = line.split(","); if (items.length != 5) { throw new IllegalStateException("Error while reading " + fileName + " expecting 5 items in a line"); } PairIntPair pp = new PairIntPair( Integer.valueOf(items[0]).intValue(), Integer.valueOf(items[1]).intValue(), Integer.valueOf(items[2]).intValue(), Integer.valueOf(items[3]).intValue()); int classValue = Integer.valueOf(items[4]).intValue(); if (classValue == 0) { similarClass.add(pp); } else { differentClass.add(pp); } line = bReader.readLine(); } } catch (IOException e) { log.severe(e.getMessage()); } finally { if (reader == null) { reader.close(); } if (bReader == null) { bReader.close(); } } } private void plot(PairIntArray p, int fn) throws Exception { float[] x = new float[p.getN()]; float[] y = new float[p.getN()]; for (int i = 0; i < x.length; ++i) { x[i] = p.getX(i); y[i] = p.getY(i); } float xMax = MiscMath.findMax(x) + 1; float yMax = MiscMath.findMax(y) + 1; PolygonAndPointPlotter plot = new PolygonAndPointPlotter(); plot.addPlot(0, xMax, 0, yMax, x, y, x, y, ""); plot.writeFile(fn); } private void extractTemplateKeypoints(String fileNameRoot0, Set<PairInt> shape0, PairIntArray template, List<PairInt> templateKP, TDoubleList templateOrientations, Descriptors templateDescriptors) throws IOException, Exception { String fileName0 = fileNameRoot0 + ".jpg"; String filePath0 = ResourceFinder .findFileInTestResources(fileName0); ImageExt img0 = ImageIOHelper.readImageExt(filePath0); int[] minMaxXY = MiscMath.findMinMaxXY(template); int w = img0.getWidth(); int h = img0.getHeight(); int xLL = minMaxXY[0] - 5; if (xLL < 0) { xLL = 0; } int yLL = minMaxXY[2] - 5; if (yLL < 0) { yLL = 0; } int xUR = minMaxXY[1] + 5; if (xUR > (w - 1)) { xUR = w - 1; } int yUR = minMaxXY[3] + 5; if (yUR > (h - 1)) { yUR = h - 1; } ORB.DescriptorDithers descrOffsets = ORB.DescriptorDithers.NONE; // = ORB.DescriptorDithers.FORTY_FIVE; // = ORB.DescriptorDithers.FIFTEEN; ORBWrapper.extractKeypointsFromSubImage( img0, xLL, yLL, xUR, yUR, 200, templateKP, templateOrientations, templateDescriptors, //0.01f, 0.001f, true, descrOffsets); for (int i = 0; i < templateKP.size(); ++i) { PairInt p = templateKP.get(i); if (shape0.contains(p)) { ImageIOHelper.addPointToImage(p.getX(), p.getY(), img0, 1, 255, 0, 0); } } MiscDebug.writeImage(img0, "_template_orb"); } private void extractTemplateORBKeypoints(ImageExt img, Set<PairInt> shape0, List<PairInt> templateKP, TDoubleList templateOrientations, Descriptors templateDescriptorsH, Descriptors templateDescriptorsS, Descriptors templateDescriptorsV) throws IOException, Exception { int[] minMaxXY = MiscMath.findMinMaxXY(shape0); int w = img.getWidth(); int h = img.getHeight(); int buffer = 20; int xLL = minMaxXY[0] - buffer; if (xLL < 0) { xLL = 0; } int yLL = minMaxXY[2] - buffer; if (yLL < 0) { yLL = 0; } int xUR = minMaxXY[1] + buffer; if (xUR > (w - 1)) { xUR = w - 1; } int yUR = minMaxXY[3] + buffer; if (yUR > (h - 1)) { yUR = h - 1; } ORBWrapper.extractKeypointsFromSubImage( img, xLL, yLL, xUR, yUR, 200, //100, templateKP, templateOrientations, templateDescriptorsH, templateDescriptorsS, templateDescriptorsV, //0.01f, 0.001f, true); ImageExt imgCp = img.copyToImageExt(); TIntList rm = new TIntArrayList(); for (int i = 0; i < templateKP.size(); ++i) { PairInt p = templateKP.get(i); if (shape0.contains(p)) { ImageIOHelper.addPointToImage(p.getX(), p.getY(), imgCp, 1, 255, 0, 0); } else { rm.add(i); System.out.println("removing " + p); } } if (!rm.isEmpty()) { for (int i = (rm.size() - 1); i > -1; --i) { int rmIdx = rm.get(i); templateKP.remove(rmIdx); templateOrientations.removeAt(rmIdx); // move up operations. everything with index > i moves up by 1 for (int j = (i + 1); j < templateDescriptorsH.descriptors.length; ++j) { templateDescriptorsH.descriptors[j - 1] = templateDescriptorsH.descriptors[j]; templateDescriptorsS.descriptors[j - 1] = templateDescriptorsS.descriptors[j]; templateDescriptorsV.descriptors[j - 1] = templateDescriptorsV.descriptors[j]; } } int count = templateDescriptorsH.descriptors.length - rm.size(); templateDescriptorsH.descriptors = Arrays.copyOf(templateDescriptorsH.descriptors, count); templateDescriptorsS.descriptors = Arrays.copyOf(templateDescriptorsS.descriptors, count); templateDescriptorsV.descriptors = Arrays.copyOf(templateDescriptorsV.descriptors, count); } MiscDebug.writeImage(imgCp, "_template_orb"); } private ORB extractTemplateORBKeypoints(ImageExt img, Set<PairInt> shape0, int nKeypoints, float fastThresh, boolean useSmallPyramid, boolean createFirstDerivPts, boolean createCurvaturePts) throws IOException, Exception { int[] minMaxXY = MiscMath.findMinMaxXY(shape0); int w = img.getWidth(); int h = img.getHeight(); int buffer = 20; int xLL = minMaxXY[0] - buffer; if (xLL < 0) { xLL = 0; } int yLL = minMaxXY[2] - buffer; if (yLL < 0) { yLL = 0; } int xUR = minMaxXY[1] + buffer; if (xUR > (w - 1)) { xUR = w - 1; } int yUR = minMaxXY[3] + buffer; if (yUR > (h - 1)) { yUR = h - 1; } boolean overrideToCreateSmallestPyramid = useSmallPyramid; ORB orb = ORBWrapper.extractHSVKeypointsFromSubImage( img, xLL, yLL, xUR, yUR, nKeypoints, fastThresh, createFirstDerivPts, createCurvaturePts, overrideToCreateSmallestPyramid); // trim orb data that is outside of shape int ns = orb.getKeyPoint0List().size(); for (int i = 0; i < ns; ++i) { TIntList kp0 = orb.getKeyPoint0List().get(i); TIntList kp1 = orb.getKeyPoint1List().get(i); TDoubleList or = orb.getOrientationsList().get(i); TFloatList s = orb.getScalesList().get(i); Descriptors dH = orb.getDescriptorsH().get(i); Descriptors dS = orb.getDescriptorsS().get(i); Descriptors dV = orb.getDescriptorsV().get(i); int n0 = kp0.size(); TIntList rm = new TIntArrayList(); for (int j = 0; j < n0; ++j) { PairInt p = new PairInt(kp1.get(j), kp0.get(j)); if (!shape0.contains(p)) { rm.add(j); } } if (!rm.isEmpty()) { int nb = n0 - rm.size(); Descriptors dH2 = new Descriptors(); dH2.descriptors = new VeryLongBitString[nb]; Descriptors dS2 = new Descriptors(); dS2.descriptors = new VeryLongBitString[nb]; Descriptors dV2 = new Descriptors(); dV2.descriptors = new VeryLongBitString[nb]; TIntSet rmSet = new TIntHashSet(rm); for (int j = (rm.size() - 1); j > -1; --j) { int idx = rm.get(j); kp0.removeAt(idx); kp1.removeAt(idx); or.removeAt(idx); s.removeAt(idx); } int count = 0; for (int j = 0; j < n0; ++j) { if (rmSet.contains(j)) { continue; } dH2.descriptors[count] = dH.descriptors[j]; dS2.descriptors[count] = dS.descriptors[j]; dV2.descriptors[count] = dV.descriptors[j]; count++; } assert(count == nb); dH.descriptors = dH2.descriptors; dS.descriptors = dS2.descriptors; dV.descriptors = dV2.descriptors; } } {// DEBUG print each pyramid to see if has matchable points // might need to change the ORb response filter to scale by scale level for (int i0 = 0; i0 < orb.getKeyPoint0List().size(); ++i0) { Image img0Cp = img.copyImage(); float scale = orb.getScalesList().get(i0).get(0); for (int i = 0; i < orb.getKeyPoint0List().get(i0).size(); ++i) { int y = orb.getKeyPoint0List().get(i0).get(i); int x = orb.getKeyPoint1List().get(i0).get(i); ImageIOHelper.addPointToImage(x, y, img0Cp, 1, 255, 0, 0); } String str = Integer.toString(i0); if (str.length() < 2) { str = "0" + str; } MiscDebug.writeImage(img0Cp, "_template_orb" + str); } } return orb; } private TDoubleList extractKeypoints(ImageExt img, List<Set<PairInt>> listOfPointSets, List<PairInt> keypoints, Descriptors descriptors) throws IOException, Exception { // bins of size template size across image int w = img.getWidth(); int h = img.getHeight(); ORB orb = new ORB(1000); //orb.overrideFastThreshold(0.01f); orb.overrideFastThreshold(0.001f); orb.overrideToCreateHSVDescriptors(); orb.overrideToAlsoCreate1stDerivKeypoints(); orb.detectAndExtract(img); List<PairInt> kp = orb.getAllKeyPoints(); Descriptors d = orb.getAllDescriptors(); TDoubleList or = orb.getAllOrientations(); ImageExt img0 = img.copyToImageExt(); Set<PairInt> points = new HashSet<PairInt>(); for (Set<PairInt> set : listOfPointSets) { points.addAll(set); } Set<PairInt> exists = new HashSet<PairInt>(); TDoubleList orientations = new TDoubleArrayList(); for (int i = 0; i < kp.size(); ++i) { PairInt p = kp.get(i); if (exists.contains(p) || !points.contains(p)) { continue; } exists.add(p); keypoints.add(p); orientations.add(or.get(i)); ImageIOHelper.addPointToImage(p.getX(), p.getY(), img0, 1, 255, 0, 0); } exists.clear(); VeryLongBitString[] outD = new VeryLongBitString[keypoints.size()]; int count = 0; for (int i = 0; i < kp.size(); ++i) { PairInt p = kp.get(i); if (exists.contains(p) || !points.contains(p)) { continue; } exists.add(p); outD[count] = d.descriptors[i]; count++; } descriptors.descriptors = outD; MiscDebug.writeImage(img0, "_srch_orb"); return orientations; } private TDoubleList extractORBKeypoints(ImageExt img, List<Set<PairInt>> listOfPointSets, List<PairInt> keypoints, Descriptors descriptorsH, Descriptors descriptorsS, Descriptors descriptorsV) throws IOException, Exception { // bins of size template size across image int w = img.getWidth(); int h = img.getHeight(); ORB orb = new ORB(2000);//10000 //orb.overrideFastThreshold(0.01f); orb.overrideFastThreshold(0.001f); orb.overrideToCreateHSVDescriptors(); orb.overrideToAlsoCreate1stDerivKeypoints(); orb.overrideToCreateCurvaturePoints(); //orb.overrideToCreateOffsetsToDescriptors(ORB.DescriptorDithers.FIFTEEN); orb.detectAndExtract(img); List<PairInt> kp = orb.getAllKeyPoints(); Descriptors[] dHSV = orb.getAllDescriptorsHSV(); TDoubleList or = orb.getAllOrientations(); ImageExt img0 = img.copyToImageExt(); Set<PairInt> points = new HashSet<PairInt>(); for (Set<PairInt> set : listOfPointSets) { points.addAll(set); } Set<PairInt> exists = new HashSet<PairInt>(); TDoubleList orientations = new TDoubleArrayList(); for (int i = 0; i < kp.size(); ++i) { PairInt p = kp.get(i); if (exists.contains(p) || !points.contains(p)) { continue; } exists.add(p); keypoints.add(p); orientations.add(or.get(i)); ImageIOHelper.addPointToImage(p.getX(), p.getY(), img0, 1, 255, 0, 0); } exists.clear(); VeryLongBitString[] outH = new VeryLongBitString[keypoints.size()]; VeryLongBitString[] outS = new VeryLongBitString[keypoints.size()]; VeryLongBitString[] outV = new VeryLongBitString[keypoints.size()]; int count = 0; for (int i = 0; i < kp.size(); ++i) { PairInt p = kp.get(i); if (exists.contains(p) || !points.contains(p)) { continue; } exists.add(p); outH[count] = dHSV[0].descriptors[i]; outS[count] = dHSV[1].descriptors[i]; outV[count] = dHSV[2].descriptors[i]; count++; } descriptorsH.descriptors = outH; descriptorsS.descriptors = outS; descriptorsV.descriptors = outV; MiscDebug.writeImage(img0, "_srch_orb"); return orientations; } private Set<PairInt> createMedialAxis(Set<PairInt> points, Set<PairInt> perimeter) { MedialAxis medAxis = new MedialAxis(points, perimeter); medAxis.fastFindMedialAxis(); Set<PairInt> medAxisPts = medAxis.getMedialAxisPoints(); return medAxisPts; } public void estCIETheta() throws Exception { int maxDimension = 256;//512; SIGMA sigma = SIGMA.ZEROPOINTFIVE;//SIGMA.ONE; ImageProcessor imageProcessor = new ImageProcessor(); String[] fileNames1 = new String[]{ "android_statues_01.jpg", "android_statues_02.jpg", "android_statues_04.jpg", "android_statues_03.jpg" }; for (String fileName1 : fileNames1) { String fileName1Root = fileName1.substring(0, fileName1.lastIndexOf(".")); String filePath1 = ResourceFinder.findFileInTestResources(fileName1); ImageExt img = ImageIOHelper.readImageExt(filePath1); // template img size is 218 163 //img = (ImageExt) imageProcessor.bilinearDownSampling( // img, 218, 163, 0, 255); long ts = MiscDebug.getCurrentTimeFormatted(); int w1 = img.getWidth(); int h1 = img.getHeight(); int binFactor1 = (int) Math.ceil(Math.max( (float) w1 / maxDimension, (float) h1 / maxDimension)); img = imageProcessor.binImage(img, binFactor1); int w = img.getWidth(); int h = img.getHeight(); long t0 = System.currentTimeMillis(); // descriptors w/ masks /*corList = ORB.match2( orb0, orb, tempListOfPointSets, listOfPointSets2, 1.5f, 0.1f, false); */ /* GreyscaleImage theta1 = imageProcessor.createCIELABTheta(img, 255); MiscDebug.writeImage(theta1, fileName1Root + "_theta_"); GreyscaleImage theta_15 = imageProcessor.createCIELABTheta(img, 255, 15); MiscDebug.writeImage(theta_15, fileName1Root + "_theta_15_"); */ ImageSegmentation imageSegmentation = new ImageSegmentation(); ImageExt imgCp = img.copyToImageExt(); int[] labels = imageSegmentation.objectSegmentation3(imgCp); ImageIOHelper.addAlternatingColorLabelsToRegion( //LabelToColorHelper.applyLabels( imgCp, labels); MiscDebug.writeImage(imgCp, "_theta_segmentation_" + fileName1Root); imgCp = img.copyToImageExt(); labels = imageSegmentation.objectSegmentation(imgCp); ImageIOHelper.addAlternatingColorLabelsToRegion( //LabelToColorHelper.applyLabels( imgCp, labels); MiscDebug.writeImage(imgCp, "_hsv_segmentation_" + fileName1Root); } } }
adding a cupcake statues test
tests/algorithms/imageProcessing/features/AndroidStatuesTest.java
adding a cupcake statues test
<ide><path>ests/algorithms/imageProcessing/features/AndroidStatuesTest.java <ide> } <ide> } <ide> <del> public void testORBMatcher2() throws Exception { <add> public void estORBMatcher() throws Exception { <ide> <ide> /* <ide> this demonstrates ORB <ide> } <ide> } <ide> <add> public void testORBMatcher2() throws Exception { <add> <add> // TODO: this one either needs more keypoints across the cupcake in <add> // android statues 02 image, <add> // or it needs an algorithm similar to matchSmall which does not <add> // use descriptors, but instead uses color histograms and partial <add> // shape matching, but with the addition of aggregated shape <add> // comparisons (== the unfinished ShapeFinder) <add> // <add> // and as always, improved segmentation would help, but the cupcake is <add> // in partly shaded locations. <add> <add> int maxDimension = 256;//512; <add> SIGMA sigma = SIGMA.ZEROPOINTFIVE;//SIGMA.ONE; <add> <add> ImageProcessor imageProcessor = new ImageProcessor(); <add> ImageSegmentation imageSegmentation = new ImageSegmentation(); <add> <add> String[] fileNames0 = new String[]{ <add> "android_statues_04.jpg", <add> "android_statues_04_cupcake_mask.png", <add> }; <add> <add> String[] fileNames1 = new String[]{ <add> // "android_statues_01.jpg", // needs aggregated shape matching <add> "android_statues_02.jpg", // needs aggregated shape matching <add> // "android_statues_04.jpg", // descr are fine <add> }; <add> <add> for (String fileName1 : fileNames1) { <add> <add> long t0 = System.currentTimeMillis(); <add> <add> Set<PairInt> shape0 = new HashSet<PairInt>(); <add> <add> ImageExt[] imgs0 = maskAndBin2(fileNames0, <add> maxDimension, shape0); <add> int nShape0_0 = shape0.size(); <add> <add> System.out.println("shape0 nPts=" + nShape0_0); <add> <add> <add> String fileName1Root = fileName1.substring(0, <add> fileName1.lastIndexOf(".")); <add> String filePath1 = ResourceFinder.findFileInTestResources( <add> fileName1); <add> ImageExt img = ImageIOHelper.readImageExt(filePath1); <add> <add> long ts = MiscDebug.getCurrentTimeFormatted(); <add> <add> int w1 = img.getWidth(); <add> int h1 = img.getHeight(); <add> <add> int binFactor1 = (int) Math.ceil(Math.max( <add> (float) w1 / maxDimension, <add> (float) h1 / maxDimension)); <add> <add> img = imageProcessor.binImage(img, binFactor1); <add> <add> int w = img.getWidth(); <add> int h = img.getHeight(); <add> <add> /*RANSACAlgorithmIterations nsIter = new <add> RANSACAlgorithmIterations(); <add> long nnn = nsIter.estimateNIterFor99PercentConfidence( <add> 300, 7, 20./300.); <add> System.out.println("99 percent nIter for RANSAC=" <add> + nnn);*/ <add> <add> //GreyscaleImage theta1 = imageProcessor.createCIELABTheta(imgs0[0], 255); <add> //MiscDebug.writeImage(theta1, fileName1Root + "_theta_0"); <add> //theta1 = imageProcessor.createCIELABTheta(img, 255); <add> //MiscDebug.writeImage(theta1, fileName1Root + "_theta_1"); <add> <add> Settings settings = new Settings(); <add> <add> ObjectMatcher objMatcher = new ObjectMatcher(); <add> if (fileName1Root.contains("_01")) { <add> settings.setToUseSmallObjectMethod(); <add> } <add> //settings.setToUseLargerPyramid0(); <add> objMatcher.setToDebug(); <add> CorrespondenceList cor = objMatcher.findObject(imgs0[0], shape0, <add> img, settings); <add> <add> long t1 = System.currentTimeMillis(); <add> System.out.println("matching took " + ((t1 - t0)/1000.) + " sec"); <add> <add> CorrespondencePlotter plotter = new CorrespondencePlotter( <add> imgs0[1], img.copyImage()); <add> for (int ii = 0; ii < cor.getPoints1().size(); ++ii) { <add> PairInt p1 = cor.getPoints1().get(ii); <add> PairInt p2 = cor.getPoints2().get(ii); <add> <add> //System.out.println("orb matched: " + p1 + " " + p2); <add> //if (p2.getX() > 160) <add> plotter.drawLineInAlternatingColors(p1.getX(), p1.getY(), <add> p2.getX(), p2.getY(), 0); <add> } <add> <add> plotter.writeImage("_orb_corres_final_" + <add> "_" + fileName1Root); <add> System.out.println(cor.getPoints1().size() + <add> " matches " + fileName1Root + " test2"); <add> //MiscDebug.writeImage(img11, "_orb_matched_" + str <add> // + "_" + fileName1Root); <add> } <add> } <ide> <ide> public void estMkImgs() throws Exception { <ide> <ide> <ide> } <ide> } <add> <add> private ImageExt[] maskAndBin2(String[] fileNames, <add> int maxDimension, Set<PairInt> outputShape) throws IOException { <add> <add> ImageProcessor imageProcessor = new ImageProcessor(); <add> <add> String fileNameMask0 = fileNames[1]; <add> String filePathMask0 = ResourceFinder <add> .findFileInTestResources(fileNameMask0); <add> ImageExt imgMask0 = ImageIOHelper.readImageExt(filePathMask0); <add> <add> String fileName0 = fileNames[0]; <add> String filePath0 = ResourceFinder <add> .findFileInTestResources(fileName0); <add> ImageExt img0 = ImageIOHelper.readImageExt(filePath0); <add> <add> int w0 = img0.getWidth(); <add> int h0 = img0.getHeight(); <add> <add> int binFactor0 = (int) Math.ceil(Math.max( <add> (float) w0 / maxDimension, <add> (float) h0 / maxDimension)); <add> <add> img0 = imageProcessor.binImage(img0, binFactor0); <add> imgMask0 = imageProcessor.binImage(imgMask0, binFactor0); <add> <add> ImageExt img0Masked = img0.copyToImageExt(); <add> <add> assertEquals(imgMask0.getNPixels(), img0.getNPixels()); <add> <add> for (int i = 0; i < imgMask0.getNPixels(); ++i) { <add> if (imgMask0.getR(i) == 0) { <add> img0Masked.setRGB(i, 0, 0, 0); <add> } else { <add> outputShape.add(new PairInt(imgMask0.getCol(i), <add> imgMask0.getRow(i))); <add> } <add> } <add> <add> return new ImageExt[]{img0, img0Masked}; <add> } <ide> }
Java
apache-2.0
3c28492525b14477f7eca3dc753ac2e3e6745189
0
ChadKillingsworth/closure-compiler,nawawi/closure-compiler,GerHobbelt/closure-compiler,GerHobbelt/closure-compiler,monetate/closure-compiler,google/closure-compiler,MatrixFrog/closure-compiler,vobruba-martin/closure-compiler,ChadKillingsworth/closure-compiler,tdelmas/closure-compiler,GerHobbelt/closure-compiler,Yannic/closure-compiler,monetate/closure-compiler,tiobe/closure-compiler,vobruba-martin/closure-compiler,MatrixFrog/closure-compiler,MatrixFrog/closure-compiler,monetate/closure-compiler,mprobst/closure-compiler,nawawi/closure-compiler,mprobst/closure-compiler,ChadKillingsworth/closure-compiler,vobruba-martin/closure-compiler,Yannic/closure-compiler,nawawi/closure-compiler,vobruba-martin/closure-compiler,tdelmas/closure-compiler,google/closure-compiler,tdelmas/closure-compiler,tiobe/closure-compiler,mprobst/closure-compiler,tiobe/closure-compiler,nawawi/closure-compiler,MatrixFrog/closure-compiler,shantanusharma/closure-compiler,google/closure-compiler,tdelmas/closure-compiler,shantanusharma/closure-compiler,tiobe/closure-compiler,monetate/closure-compiler,ChadKillingsworth/closure-compiler,Yannic/closure-compiler,google/closure-compiler,mprobst/closure-compiler,GerHobbelt/closure-compiler,shantanusharma/closure-compiler,shantanusharma/closure-compiler,Yannic/closure-compiler
/* * Copyright 2004 The Closure Compiler 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.javascript.jscomp; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.base.Preconditions.checkState; import com.google.javascript.rhino.Node; import com.google.javascript.rhino.StaticScope; import java.io.Serializable; import java.util.Collections; import java.util.LinkedHashMap; import java.util.Map; /** * Scope contains information about a variable scope in JavaScript. * Scopes can be nested, a scope points back to its parent scope. * A Scope contains information about variables defined in that scope. * * @see NodeTraversal * */ public class Scope implements StaticScope, Serializable { protected final Map<String, Var> vars = new LinkedHashMap<>(); protected Scope parent; protected int depth; protected final Node rootNode; private Var arguments; /** * Creates a Scope given the parent Scope and the root node of the current scope. * * @param parent The parent Scope. Cannot be null. * @param rootNode The root node of the curent scope. Cannot be null. */ Scope(Scope parent, Node rootNode) { checkNotNull(parent); checkArgument(NodeUtil.createsScope(rootNode), rootNode); checkArgument( rootNode != parent.rootNode, "rootNode should not be the parent's root node", rootNode); this.parent = parent; this.rootNode = rootNode; this.depth = parent.depth + 1; } protected Scope(Node rootNode) { // TODO(tbreisacher): Can we tighten this to just NodeUtil.createsScope? checkArgument( NodeUtil.createsScope(rootNode) || rootNode.isScript() || rootNode.isRoot(), rootNode); this.parent = null; this.rootNode = rootNode; this.depth = 0; } @Override public String toString() { return "Scope@" + rootNode; } static Scope createGlobalScope(Node rootNode) { // TODO(tbreisacher): Can we tighten this to allow only ROOT nodes? checkArgument(rootNode.isRoot() || rootNode.isScript(), rootNode); return new Scope(rootNode); } /** The depth of the scope. The global scope has depth 0. */ public int getDepth() { return depth; } /** * Gets the container node of the scope. This is typically the FUNCTION * node or the global BLOCK/SCRIPT node. */ @Override public Node getRootNode() { return rootNode; } public Scope getParent() { return parent; } Scope getGlobalScope() { Scope result = this; while (result.getParent() != null) { result = result.getParent(); } return result; } @Override public StaticScope getParentScope() { return parent; } /** * Declares a variable. * * @param name name of the variable * @param nameNode the NAME node declaring the variable * @param input the input in which this variable is defined. */ Var declare(String name, Node nameNode, CompilerInput input) { checkState(name != null && !name.isEmpty(), name); // Make sure that it's declared only once checkState(vars.get(name) == null); Var var = new Var(name, nameNode, this, vars.size(), input); vars.put(name, var); return var; } /** * Undeclares a variable, to be used when the compiler optimizes out * a variable and removes it from the scope. */ void undeclare(Var var) { checkState(var.scope == this); checkState(vars.get(var.name).equals(var)); undeclareInteral(var); } /** Without any safety checks */ void undeclareInteral(Var var) { vars.remove(var.name); } @Override public Var getSlot(String name) { return getVar(name); } @Override public Var getOwnSlot(String name) { return vars.get(name); } /** * Returns the variable, may be null */ public Var getVar(String name) { Scope scope = this; while (scope != null) { Var var = scope.vars.get(name); if (var != null) { return var; } if ("arguments".equals(name) && NodeUtil.isVanillaFunction(scope.getRootNode())) { return scope.getArgumentsVar(); } // Recurse up the parent Scope scope = scope.parent; } return null; } /** * Get a unique VAR object to represents "arguments" within this scope */ public Var getArgumentsVar() { if (isGlobal() || isModuleScope()) { throw new IllegalStateException("No arguments var for scope: " + this); } if (!isFunctionScope() || rootNode.isArrowFunction()) { return parent.getArgumentsVar(); } if (arguments == null) { arguments = Var.makeArgumentsVar(this); } return arguments; } /** * @deprecated use #isDeclared instead */ @Deprecated public boolean isDeclaredSloppy(String name, boolean recurse) { // In ES6, we create a separate "function parameter scope" above the function block scope to // handle default parameters. Since nothing in the function block scope is allowed to shadow // the variables in the function scope, we treat the two scopes as one in this method. checkState(recurse == false); if (!isDeclared(name, false)) { if (parent != null && isFunctionBlockScope()) { return parent.isDeclared(name, false); } return false; } else { return true; } } /** * Returns true if a variable is declared. */ public boolean isDeclared(String name, boolean recurse) { Scope scope = this; while (true) { if (scope.vars.containsKey(name)) { return true; } if (scope.parent != null && recurse) { scope = scope.parent; continue; } return false; } } /** * Return an iterable over all of the variables declared in this scope * (except the special 'arguments' variable). */ public Iterable<? extends Var> getVarIterable() { return vars.values(); } public Iterable<? extends Var> getAllSymbols() { return Collections.unmodifiableCollection(vars.values()); } /** * Returns number of variables in this scope (excluding the special 'arguments' variable) */ public int getVarCount() { return vars.size(); } /** * Returns whether this is the global scope. */ public boolean isGlobal() { return parent == null; } /** * Returns whether this is a local scope (i.e. not the global scope). */ public boolean isLocal() { return parent != null; } public boolean isBlockScope() { return NodeUtil.createsBlockScope(rootNode); } public boolean isFunctionBlockScope() { return NodeUtil.isFunctionBlock(getRootNode()); } public boolean isFunctionScope() { return getRootNode().isFunction(); } public boolean isModuleScope() { return getRootNode().isModuleBody(); } public boolean isCatchScope() { return getRootNode().isNormalBlock() && getRootNode().hasOneChild() && getRootNode().getFirstChild().isCatch(); } /** * If a var were declared in this scope, would it belong to this scope (as opposed to some * enclosing scope)? * * We consider function scopes to be hoist scopes. Even though it's impossible to declare a var * inside function parameters, it would make less sense to say that if you did declare one in * the function parameters, it would be hoisted somewhere else. */ boolean isHoistScope() { return isFunctionScope() || isFunctionBlockScope() || isGlobal() || isModuleScope(); } /** * If a var were declared in this scope, return the scope it would be hoisted to. * * For function scopes, we return back the scope itself, since even though there is no way * to declare a var inside function parameters, it would make even less sense to say that * such declarations would be "hoisted" somewhere else. */ public Scope getClosestHoistScope() { Scope current = this; while (current != null) { if (current.isHoistScope()) { return current; } current = current.parent; } return null; } }
src/com/google/javascript/jscomp/Scope.java
/* * Copyright 2004 The Closure Compiler 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.javascript.jscomp; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.base.Preconditions.checkState; import com.google.javascript.rhino.Node; import com.google.javascript.rhino.StaticScope; import java.io.Serializable; import java.util.Collections; import java.util.LinkedHashMap; import java.util.Map; /** * Scope contains information about a variable scope in JavaScript. * Scopes can be nested, a scope points back to its parent scope. * A Scope contains information about variables defined in that scope. * * @see NodeTraversal * */ public class Scope implements StaticScope, Serializable { protected final Map<String, Var> vars = new LinkedHashMap<>(); protected Scope parent; protected int depth; protected final Node rootNode; private Var arguments; /** * Creates a Scope given the parent Scope and the root node of the current scope. * * @param parent The parent Scope. Cannot be null. * @param rootNode The root node of the curent scope. Cannot be null. */ Scope(Scope parent, Node rootNode) { checkNotNull(parent); checkArgument(NodeUtil.createsScope(rootNode), rootNode); checkArgument( rootNode != parent.rootNode, "rootNode should not be the parent's root node", rootNode); this.parent = parent; this.rootNode = rootNode; this.depth = parent.depth + 1; } protected Scope(Node rootNode) { // TODO(tbreisacher): Can we tighten this to just NodeUtil.createsScope? checkArgument( NodeUtil.createsScope(rootNode) || rootNode.isScript() || rootNode.isRoot(), rootNode); this.parent = null; this.rootNode = rootNode; this.depth = 0; } @Override public String toString() { return "Scope@" + rootNode; } static Scope createGlobalScope(Node rootNode) { // TODO(tbreisacher): Can we tighten this to allow only ROOT nodes? checkArgument(rootNode.isRoot() || rootNode.isScript(), rootNode); return new Scope(rootNode); } /** The depth of the scope. The global scope has depth 0. */ public int getDepth() { return depth; } /** * Gets the container node of the scope. This is typically the FUNCTION * node or the global BLOCK/SCRIPT node. */ @Override public Node getRootNode() { return rootNode; } public Scope getParent() { return parent; } Scope getGlobalScope() { Scope result = this; while (result.getParent() != null) { result = result.getParent(); } return result; } @Override public StaticScope getParentScope() { return parent; } /** * Declares a variable. * * @param name name of the variable * @param nameNode the NAME node declaring the variable * @param input the input in which this variable is defined. */ Var declare(String name, Node nameNode, CompilerInput input) { checkState(name != null && !name.isEmpty()); // Make sure that it's declared only once checkState(vars.get(name) == null); Var var = new Var(name, nameNode, this, vars.size(), input); vars.put(name, var); return var; } /** * Undeclares a variable, to be used when the compiler optimizes out * a variable and removes it from the scope. */ void undeclare(Var var) { checkState(var.scope == this); checkState(vars.get(var.name).equals(var)); undeclareInteral(var); } /** Without any safety checks */ void undeclareInteral(Var var) { vars.remove(var.name); } @Override public Var getSlot(String name) { return getVar(name); } @Override public Var getOwnSlot(String name) { return vars.get(name); } /** * Returns the variable, may be null */ public Var getVar(String name) { Scope scope = this; while (scope != null) { Var var = scope.vars.get(name); if (var != null) { return var; } if ("arguments".equals(name) && NodeUtil.isVanillaFunction(scope.getRootNode())) { return scope.getArgumentsVar(); } // Recurse up the parent Scope scope = scope.parent; } return null; } /** * Get a unique VAR object to represents "arguments" within this scope */ public Var getArgumentsVar() { if (isGlobal() || isModuleScope()) { throw new IllegalStateException("No arguments var for scope: " + this); } if (!isFunctionScope() || rootNode.isArrowFunction()) { return parent.getArgumentsVar(); } if (arguments == null) { arguments = Var.makeArgumentsVar(this); } return arguments; } /** * @deprecated use #isDeclared instead */ @Deprecated public boolean isDeclaredSloppy(String name, boolean recurse) { // In ES6, we create a separate "function parameter scope" above the function block scope to // handle default parameters. Since nothing in the function block scope is allowed to shadow // the variables in the function scope, we treat the two scopes as one in this method. checkState(recurse == false); if (!isDeclared(name, false)) { if (parent != null && isFunctionBlockScope()) { return parent.isDeclared(name, false); } return false; } else { return true; } } /** * Returns true if a variable is declared. */ public boolean isDeclared(String name, boolean recurse) { Scope scope = this; while (true) { if (scope.vars.containsKey(name)) { return true; } if (scope.parent != null && recurse) { scope = scope.parent; continue; } return false; } } /** * Return an iterable over all of the variables declared in this scope * (except the special 'arguments' variable). */ public Iterable<? extends Var> getVarIterable() { return vars.values(); } public Iterable<? extends Var> getAllSymbols() { return Collections.unmodifiableCollection(vars.values()); } /** * Returns number of variables in this scope (excluding the special 'arguments' variable) */ public int getVarCount() { return vars.size(); } /** * Returns whether this is the global scope. */ public boolean isGlobal() { return parent == null; } /** * Returns whether this is a local scope (i.e. not the global scope). */ public boolean isLocal() { return parent != null; } public boolean isBlockScope() { return NodeUtil.createsBlockScope(rootNode); } public boolean isFunctionBlockScope() { return NodeUtil.isFunctionBlock(getRootNode()); } public boolean isFunctionScope() { return getRootNode().isFunction(); } public boolean isModuleScope() { return getRootNode().isModuleBody(); } public boolean isCatchScope() { return getRootNode().isNormalBlock() && getRootNode().hasOneChild() && getRootNode().getFirstChild().isCatch(); } /** * If a var were declared in this scope, would it belong to this scope (as opposed to some * enclosing scope)? * * We consider function scopes to be hoist scopes. Even though it's impossible to declare a var * inside function parameters, it would make less sense to say that if you did declare one in * the function parameters, it would be hoisted somewhere else. */ boolean isHoistScope() { return isFunctionScope() || isFunctionBlockScope() || isGlobal() || isModuleScope(); } /** * If a var were declared in this scope, return the scope it would be hoisted to. * * For function scopes, we return back the scope itself, since even though there is no way * to declare a var inside function parameters, it would make even less sense to say that * such declarations would be "hoisted" somewhere else. */ public Scope getClosestHoistScope() { Scope current = this; while (current != null) { if (current.isHoistScope()) { return current; } current = current.parent; } return null; } }
Gives the name value when checkState fails ------------- Created by MOE: https://github.com/google/moe MOE_MIGRATED_REVID=159613530
src/com/google/javascript/jscomp/Scope.java
Gives the name value when checkState fails
<ide><path>rc/com/google/javascript/jscomp/Scope.java <ide> * @param input the input in which this variable is defined. <ide> */ <ide> Var declare(String name, Node nameNode, CompilerInput input) { <del> checkState(name != null && !name.isEmpty()); <add> checkState(name != null && !name.isEmpty(), name); <ide> // Make sure that it's declared only once <ide> checkState(vars.get(name) == null); <ide> Var var = new Var(name, nameNode, this, vars.size(), input);
Java
lgpl-2.1
2e7d75463200cd205d3443360c09bb1635b6873a
0
ethaneldridge/vassal,ethaneldridge/vassal,ethaneldridge/vassal
/* * * Copyright (c) 2000-2003 by Rodney Kinney * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License (LGPL) as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public * License along with this library; if not, copies are available * at http://www.opensource.org. */ package VASSAL.preferences; import java.awt.Dimension; import java.awt.Frame; import java.awt.Toolkit; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.ComponentAdapter; import java.awt.event.ComponentEvent; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.swing.AbstractAction; import javax.swing.Action; import javax.swing.Box; import javax.swing.BoxLayout; import javax.swing.JButton; import javax.swing.JDialog; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JTabbedPane; import javax.swing.WindowConstants; import net.miginfocom.swing.MigLayout; import VASSAL.configure.Configurer; import VASSAL.i18n.Resources; import VASSAL.tools.SplashScreen; import VASSAL.tools.WriteErrorDialog; public class PrefsEditor { private JDialog dialog; private List<Configurer> options = new ArrayList<>(); private List<Configurer> extras = new ArrayList<>(); private boolean iterating = false; private Map<Configurer, Object> savedValues = new HashMap<>(); private List<Prefs> prefs = new ArrayList<>(); private JTabbedPane optionsTab = new JTabbedPane(); private JDialog setupDialog; private File pfile; private Action editAction; public PrefsEditor() {} public void initDialog(Frame parent) { if (dialog == null) { dialog = new JDialog(parent, true); dialog.setTitle(Resources.getString("Prefs.preferences")); //$NON-NLS-1$ dialog.setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE); // Handle window closing correctly. dialog.addWindowListener(new WindowAdapter() { @Override public void windowClosing(WindowEvent we) { cancel(); } }); final JButton ok = new JButton(Resources.getString(Resources.OK)); ok.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { save(); } }); final JButton cancel = new JButton(Resources.getString(Resources.CANCEL)); cancel.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { cancel(); } }); dialog.setLayout(new MigLayout("insets dialog")); dialog.add(optionsTab, "push, grow, wrap unrelated"); dialog.add(ok, "tag ok, split"); dialog.add(cancel, "tag cancel"); } } public JDialog getDialog() { return dialog; } public void addPrefs(Prefs p) { prefs.add(p); } public void addOption(String category, Configurer c, String prompt) { if (prompt != null) { if (setupDialog == null) { setupDialog = new JDialog((Frame) null, true); setupDialog.setTitle(Resources.getString("Prefs.initial_setup")); //$NON-NLS-1$ setupDialog.setLayout(new BoxLayout(setupDialog.getContentPane(), BoxLayout.Y_AXIS)); setupDialog.setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE); setupDialog.addComponentListener(new ComponentAdapter() { @Override public void componentShown(ComponentEvent e) { SplashScreen.sendAllToBack(); } }); } JPanel p = new JPanel(); p.add(new JLabel(prompt)); setupDialog.add(p); setupDialog.add(c.getControls()); JButton b = new JButton(Resources.getString(Resources.OK)); b.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent evt) { setupDialog.setVisible(false); } }); p = new JPanel(); p.add(b); setupDialog.add(p); setupDialog.pack(); Dimension d = Toolkit.getDefaultToolkit().getScreenSize(); setupDialog.setLocation( d.width / 2 - setupDialog.getSize().width / 2, d.height / 2 - setupDialog.getSize().height / 2 ); setupDialog.setVisible(true); setupDialog.removeAll(); } addOption(category, c); } public synchronized void addOption(String category, Configurer c) { if (category == null) { category = Resources.getString("Prefs.general_tab"); //$NON-NLS-1$ } JPanel pan = null; int i = optionsTab.indexOfTab(category); if (i == -1) { // No match pan = new JPanel(); pan.setLayout(new BoxLayout(pan, BoxLayout.Y_AXIS)); optionsTab.addTab(category, pan); } else { pan = (JPanel) optionsTab.getComponentAt(i); } if (iterating) { extras.add(c); } else { options.add(c); } final Box b = Box.createHorizontalBox(); b.add(c.getControls()); b.add(Box.createHorizontalGlue()); pan.add(b); } private synchronized void storeValues() { savedValues.clear(); for (Configurer c : options) { c.setFrozen(true); if (c.getValue() != null) { savedValues.put(c, c.getValue()); } } } protected synchronized void cancel() { for (Configurer c : options) { Object o = savedValues.get(c); if (o != null) { c.setValue(o); } c.setFrozen(false); } dialog.setVisible(false); } protected synchronized void save() { iterating = true; for (Configurer c : options) { if ((savedValues.get(c) == null && c.getValue() != null) || (savedValues.get(c) != null && !savedValues.get(c).equals(c.getValue()))) { c.fireUpdate(); } c.setFrozen(false); } iterating = false; options.addAll(extras); extras.clear(); write(); dialog.setVisible(false); } public Action getEditAction() { if (editAction == null) { editAction = new AbstractAction( Resources.getString("Prefs.edit_preferences")) { //$NON-NLS-1$ private static final long serialVersionUID = 1L; @Override public void actionPerformed(ActionEvent e) { storeValues(); dialog.pack(); final Dimension d = Toolkit.getDefaultToolkit().getScreenSize(); dialog.setLocation(d.width / 2 - dialog.getWidth() / 2, 0); dialog.setVisible(true); } }; // FIMXE: setting nmemonic from first letter could cause collisions in // some languages editAction.putValue(Action.MNEMONIC_KEY, (int) Resources.getString("Prefs.edit_preferences").charAt(0)); } return editAction; } public void write() { for (Prefs p : prefs) { try { p.save(); } catch (IOException e) { WriteErrorDialog.error(e, p.getFile()); } } } public void close() { write(); } }
vassal-app/src/main/java/VASSAL/preferences/PrefsEditor.java
/* * * Copyright (c) 2000-2003 by Rodney Kinney * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License (LGPL) as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public * License along with this library; if not, copies are available * at http://www.opensource.org. */ package VASSAL.preferences; import java.awt.Dimension; import java.awt.Frame; import java.awt.Toolkit; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.ComponentAdapter; import java.awt.event.ComponentEvent; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.swing.AbstractAction; import javax.swing.Action; import javax.swing.Box; import javax.swing.BoxLayout; import javax.swing.JButton; import javax.swing.JDialog; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JTabbedPane; import javax.swing.WindowConstants; import net.miginfocom.swing.MigLayout; import VASSAL.configure.Configurer; import VASSAL.i18n.Resources; import VASSAL.tools.SplashScreen; import VASSAL.tools.WriteErrorDialog; public class PrefsEditor { private JDialog dialog; private List<Configurer> options = new ArrayList<>(); private List<Configurer> extras = new ArrayList<>(); private boolean iterating = false; private Map<Configurer, Object> savedValues = new HashMap<>(); private List<Prefs> prefs = new ArrayList<>(); private JTabbedPane optionsTab = new JTabbedPane(); private JDialog setupDialog; private File pfile; private Action editAction; public PrefsEditor() {} public void initDialog(Frame parent) { if (dialog == null) { dialog = new JDialog(parent, true); dialog.setTitle(Resources.getString("Prefs.preferences")); //$NON-NLS-1$ dialog.setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE); // Handle window closing correctly. dialog.addWindowListener(new WindowAdapter() { @Override public void windowClosing(WindowEvent we) { cancel(); } }); final JButton ok = new JButton(Resources.getString(Resources.OK)); ok.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { save(); } }); final JButton cancel = new JButton(Resources.getString(Resources.CANCEL)); cancel.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { cancel(); } }); dialog.setLayout(new MigLayout("insets dialog")); dialog.add(optionsTab, "push, grow, wrap unrelated"); dialog.add(ok, "tag ok, split"); dialog.add(cancel, "tag cancel"); } } public JDialog getDialog() { return dialog; } public void addPrefs(Prefs p) { prefs.add(p); } public void addOption(String category, Configurer c, String prompt) { if (prompt != null) { if (setupDialog == null) { setupDialog = new JDialog((Frame) null, true); setupDialog.setTitle(Resources.getString("Prefs.initial_setup")); //$NON-NLS-1$ setupDialog.setLayout(new BoxLayout(setupDialog.getContentPane(), BoxLayout.Y_AXIS)); setupDialog.setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE); setupDialog.addComponentListener(new ComponentAdapter() { @Override public void componentShown(ComponentEvent e) { SplashScreen.sendAllToBack(); } }); } JPanel p = new JPanel(); p.add(new JLabel(prompt)); setupDialog.add(p); setupDialog.add(c.getControls()); JButton b = new JButton(Resources.getString(Resources.OK)); b.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent evt) { setupDialog.setVisible(false); } }); p = new JPanel(); p.add(b); setupDialog.add(p); setupDialog.pack(); Dimension d = Toolkit.getDefaultToolkit().getScreenSize(); setupDialog.setLocation( d.width / 2 - setupDialog.getSize().width / 2, d.height / 2 - setupDialog.getSize().height / 2 ); setupDialog.setVisible(true); setupDialog.removeAll(); } addOption(category, c); } public synchronized void addOption(String category, Configurer c) { if (category == null) { category = Resources.getString("Prefs.general_tab"); //$NON-NLS-1$ } JPanel pan = null; int i = optionsTab.indexOfTab(category); if (i == -1) { // No match pan = new JPanel(); pan.setLayout(new BoxLayout(pan, BoxLayout.Y_AXIS)); optionsTab.addTab(category, pan); } else { pan = (JPanel) optionsTab.getComponentAt(i); } if (iterating) { extras.add(c); } else { options.add(c); } final Box b = Box.createHorizontalBox(); b.add(c.getControls()); b.add(Box.createHorizontalGlue()); pan.add(b); } private synchronized void storeValues() { savedValues.clear(); for (Configurer c : options) { c.setFrozen(true); if (c.getValue() != null) { savedValues.put(c, c.getValue()); } } } protected synchronized void cancel() { for (Configurer c : options) { c.setValue(savedValues.get(c)); c.setFrozen(false); } dialog.setVisible(false); } protected synchronized void save() { iterating = true; for (Configurer c : options) { if ((savedValues.get(c) == null && c.getValue() != null) || (savedValues.get(c) != null && !savedValues.get(c).equals(c.getValue()))) { c.fireUpdate(); } c.setFrozen(false); } iterating = false; options.addAll(extras); extras.clear(); write(); dialog.setVisible(false); } public Action getEditAction() { if (editAction == null) { editAction = new AbstractAction( Resources.getString("Prefs.edit_preferences")) { //$NON-NLS-1$ private static final long serialVersionUID = 1L; @Override public void actionPerformed(ActionEvent e) { storeValues(); dialog.pack(); final Dimension d = Toolkit.getDefaultToolkit().getScreenSize(); dialog.setLocation(d.width / 2 - dialog.getWidth() / 2, 0); dialog.setVisible(true); } }; // FIMXE: setting nmemonic from first letter could cause collisions in // some languages editAction.putValue(Action.MNEMONIC_KEY, (int) Resources.getString("Prefs.edit_preferences").charAt(0)); } return editAction; } public void write() { for (Prefs p : prefs) { try { p.save(); } catch (IOException e) { WriteErrorDialog.error(e, p.getFile()); } } } public void close() { write(); } }
12888 - PrefsEditor - when cancelling, possibility of trying to set value of object to null (see also: BAD)
vassal-app/src/main/java/VASSAL/preferences/PrefsEditor.java
12888 - PrefsEditor - when cancelling, possibility of trying to set value of object to null (see also: BAD)
<ide><path>assal-app/src/main/java/VASSAL/preferences/PrefsEditor.java <ide> <ide> protected synchronized void cancel() { <ide> for (Configurer c : options) { <del> c.setValue(savedValues.get(c)); <add> Object o = savedValues.get(c); <add> if (o != null) { <add> c.setValue(o); <add> } <ide> c.setFrozen(false); <ide> } <ide> dialog.setVisible(false);
Java
apache-2.0
b3a70c788f3a0e9dec1cc4dda0bb8bcead216364
0
ivan-fedorov/intellij-community,vvv1559/intellij-community,muntasirsyed/intellij-community,kdwink/intellij-community,apixandru/intellij-community,idea4bsd/idea4bsd,ivan-fedorov/intellij-community,ryano144/intellij-community,gnuhub/intellij-community,blademainer/intellij-community,MER-GROUP/intellij-community,allotria/intellij-community,suncycheng/intellij-community,suncycheng/intellij-community,da1z/intellij-community,tmpgit/intellij-community,TangHao1987/intellij-community,asedunov/intellij-community,ernestp/consulo,Lekanich/intellij-community,idea4bsd/idea4bsd,dslomov/intellij-community,adedayo/intellij-community,ol-loginov/intellij-community,robovm/robovm-studio,retomerz/intellij-community,ftomassetti/intellij-community,supersven/intellij-community,ThiagoGarciaAlves/intellij-community,asedunov/intellij-community,kool79/intellij-community,amith01994/intellij-community,blademainer/intellij-community,orekyuu/intellij-community,alphafoobar/intellij-community,blademainer/intellij-community,youdonghai/intellij-community,da1z/intellij-community,xfournet/intellij-community,consulo/consulo,salguarnieri/intellij-community,tmpgit/intellij-community,fengbaicanhe/intellij-community,slisson/intellij-community,hurricup/intellij-community,TangHao1987/intellij-community,FHannes/intellij-community,clumsy/intellij-community,nicolargo/intellij-community,kdwink/intellij-community,orekyuu/intellij-community,robovm/robovm-studio,fengbaicanhe/intellij-community,mglukhikh/intellij-community,xfournet/intellij-community,ol-loginov/intellij-community,ibinti/intellij-community,dslomov/intellij-community,alphafoobar/intellij-community,Distrotech/intellij-community,clumsy/intellij-community,MER-GROUP/intellij-community,salguarnieri/intellij-community,ibinti/intellij-community,ol-loginov/intellij-community,ftomassetti/intellij-community,akosyakov/intellij-community,holmes/intellij-community,FHannes/intellij-community,amith01994/intellij-community,ahb0327/intellij-community,idea4bsd/idea4bsd,samthor/intellij-community,Distrotech/intellij-community,lucafavatella/intellij-community,ernestp/consulo,caot/intellij-community,mglukhikh/intellij-community,supersven/intellij-community,petteyg/intellij-community,supersven/intellij-community,nicolargo/intellij-community,diorcety/intellij-community,clumsy/intellij-community,diorcety/intellij-community,ryano144/intellij-community,apixandru/intellij-community,holmes/intellij-community,hurricup/intellij-community,pwoodworth/intellij-community,jagguli/intellij-community,salguarnieri/intellij-community,ol-loginov/intellij-community,TangHao1987/intellij-community,fnouama/intellij-community,apixandru/intellij-community,vvv1559/intellij-community,MichaelNedzelsky/intellij-community,tmpgit/intellij-community,caot/intellij-community,akosyakov/intellij-community,jagguli/intellij-community,xfournet/intellij-community,clumsy/intellij-community,Distrotech/intellij-community,holmes/intellij-community,jagguli/intellij-community,SerCeMan/intellij-community,consulo/consulo,clumsy/intellij-community,tmpgit/intellij-community,ahb0327/intellij-community,pwoodworth/intellij-community,akosyakov/intellij-community,semonte/intellij-community,gnuhub/intellij-community,Distrotech/intellij-community,michaelgallacher/intellij-community,ol-loginov/intellij-community,muntasirsyed/intellij-community,gnuhub/intellij-community,MichaelNedzelsky/intellij-community,signed/intellij-community,da1z/intellij-community,blademainer/intellij-community,dslomov/intellij-community,ivan-fedorov/intellij-community,mglukhikh/intellij-community,xfournet/intellij-community,kool79/intellij-community,holmes/intellij-community,MER-GROUP/intellij-community,FHannes/intellij-community,michaelgallacher/intellij-community,mglukhikh/intellij-community,tmpgit/intellij-community,tmpgit/intellij-community,nicolargo/intellij-community,Distrotech/intellij-community,signed/intellij-community,gnuhub/intellij-community,kdwink/intellij-community,kdwink/intellij-community,retomerz/intellij-community,blademainer/intellij-community,gnuhub/intellij-community,diorcety/intellij-community,ivan-fedorov/intellij-community,asedunov/intellij-community,jagguli/intellij-community,blademainer/intellij-community,akosyakov/intellij-community,caot/intellij-community,vladmm/intellij-community,semonte/intellij-community,salguarnieri/intellij-community,idea4bsd/idea4bsd,ibinti/intellij-community,FHannes/intellij-community,caot/intellij-community,da1z/intellij-community,signed/intellij-community,MER-GROUP/intellij-community,slisson/intellij-community,consulo/consulo,fengbaicanhe/intellij-community,holmes/intellij-community,samthor/intellij-community,allotria/intellij-community,hurricup/intellij-community,vladmm/intellij-community,vladmm/intellij-community,orekyuu/intellij-community,consulo/consulo,youdonghai/intellij-community,salguarnieri/intellij-community,ol-loginov/intellij-community,apixandru/intellij-community,orekyuu/intellij-community,fitermay/intellij-community,petteyg/intellij-community,ivan-fedorov/intellij-community,ThiagoGarciaAlves/intellij-community,lucafavatella/intellij-community,orekyuu/intellij-community,Distrotech/intellij-community,kool79/intellij-community,supersven/intellij-community,asedunov/intellij-community,xfournet/intellij-community,ibinti/intellij-community,fnouama/intellij-community,blademainer/intellij-community,samthor/intellij-community,vvv1559/intellij-community,nicolargo/intellij-community,signed/intellij-community,TangHao1987/intellij-community,apixandru/intellij-community,fitermay/intellij-community,ahb0327/intellij-community,pwoodworth/intellij-community,lucafavatella/intellij-community,samthor/intellij-community,ryano144/intellij-community,mglukhikh/intellij-community,amith01994/intellij-community,vladmm/intellij-community,lucafavatella/intellij-community,da1z/intellij-community,jagguli/intellij-community,ol-loginov/intellij-community,xfournet/intellij-community,alphafoobar/intellij-community,caot/intellij-community,hurricup/intellij-community,hurricup/intellij-community,idea4bsd/idea4bsd,ryano144/intellij-community,ol-loginov/intellij-community,nicolargo/intellij-community,fitermay/intellij-community,clumsy/intellij-community,caot/intellij-community,signed/intellij-community,retomerz/intellij-community,ryano144/intellij-community,xfournet/intellij-community,samthor/intellij-community,Lekanich/intellij-community,blademainer/intellij-community,ibinti/intellij-community,wreckJ/intellij-community,muntasirsyed/intellij-community,wreckJ/intellij-community,holmes/intellij-community,alphafoobar/intellij-community,izonder/intellij-community,idea4bsd/idea4bsd,semonte/intellij-community,SerCeMan/intellij-community,ivan-fedorov/intellij-community,MichaelNedzelsky/intellij-community,asedunov/intellij-community,kool79/intellij-community,suncycheng/intellij-community,fitermay/intellij-community,TangHao1987/intellij-community,allotria/intellij-community,signed/intellij-community,asedunov/intellij-community,ftomassetti/intellij-community,xfournet/intellij-community,pwoodworth/intellij-community,vladmm/intellij-community,apixandru/intellij-community,amith01994/intellij-community,MichaelNedzelsky/intellij-community,da1z/intellij-community,dslomov/intellij-community,alphafoobar/intellij-community,apixandru/intellij-community,ibinti/intellij-community,vladmm/intellij-community,youdonghai/intellij-community,TangHao1987/intellij-community,idea4bsd/idea4bsd,TangHao1987/intellij-community,retomerz/intellij-community,signed/intellij-community,fnouama/intellij-community,retomerz/intellij-community,asedunov/intellij-community,supersven/intellij-community,tmpgit/intellij-community,TangHao1987/intellij-community,wreckJ/intellij-community,hurricup/intellij-community,clumsy/intellij-community,wreckJ/intellij-community,fitermay/intellij-community,allotria/intellij-community,ol-loginov/intellij-community,ibinti/intellij-community,adedayo/intellij-community,adedayo/intellij-community,suncycheng/intellij-community,muntasirsyed/intellij-community,ivan-fedorov/intellij-community,ftomassetti/intellij-community,clumsy/intellij-community,izonder/intellij-community,caot/intellij-community,robovm/robovm-studio,kool79/intellij-community,ivan-fedorov/intellij-community,muntasirsyed/intellij-community,diorcety/intellij-community,salguarnieri/intellij-community,fengbaicanhe/intellij-community,izonder/intellij-community,vladmm/intellij-community,supersven/intellij-community,hurricup/intellij-community,ibinti/intellij-community,fengbaicanhe/intellij-community,FHannes/intellij-community,holmes/intellij-community,FHannes/intellij-community,jagguli/intellij-community,apixandru/intellij-community,caot/intellij-community,kool79/intellij-community,MER-GROUP/intellij-community,suncycheng/intellij-community,ernestp/consulo,signed/intellij-community,semonte/intellij-community,ryano144/intellij-community,caot/intellij-community,vvv1559/intellij-community,asedunov/intellij-community,tmpgit/intellij-community,dslomov/intellij-community,vvv1559/intellij-community,slisson/intellij-community,allotria/intellij-community,fitermay/intellij-community,idea4bsd/idea4bsd,michaelgallacher/intellij-community,fitermay/intellij-community,petteyg/intellij-community,ftomassetti/intellij-community,ahb0327/intellij-community,ibinti/intellij-community,ftomassetti/intellij-community,fnouama/intellij-community,robovm/robovm-studio,FHannes/intellij-community,orekyuu/intellij-community,youdonghai/intellij-community,asedunov/intellij-community,apixandru/intellij-community,samthor/intellij-community,kdwink/intellij-community,semonte/intellij-community,adedayo/intellij-community,mglukhikh/intellij-community,FHannes/intellij-community,izonder/intellij-community,SerCeMan/intellij-community,tmpgit/intellij-community,muntasirsyed/intellij-community,michaelgallacher/intellij-community,michaelgallacher/intellij-community,Distrotech/intellij-community,tmpgit/intellij-community,slisson/intellij-community,vvv1559/intellij-community,apixandru/intellij-community,orekyuu/intellij-community,ftomassetti/intellij-community,akosyakov/intellij-community,kool79/intellij-community,adedayo/intellij-community,youdonghai/intellij-community,idea4bsd/idea4bsd,fengbaicanhe/intellij-community,Lekanich/intellij-community,ol-loginov/intellij-community,diorcety/intellij-community,supersven/intellij-community,suncycheng/intellij-community,MichaelNedzelsky/intellij-community,ernestp/consulo,pwoodworth/intellij-community,slisson/intellij-community,kool79/intellij-community,apixandru/intellij-community,amith01994/intellij-community,alphafoobar/intellij-community,semonte/intellij-community,gnuhub/intellij-community,youdonghai/intellij-community,kdwink/intellij-community,allotria/intellij-community,gnuhub/intellij-community,caot/intellij-community,Lekanich/intellij-community,TangHao1987/intellij-community,kool79/intellij-community,FHannes/intellij-community,diorcety/intellij-community,dslomov/intellij-community,fitermay/intellij-community,amith01994/intellij-community,idea4bsd/idea4bsd,fnouama/intellij-community,vladmm/intellij-community,youdonghai/intellij-community,izonder/intellij-community,ftomassetti/intellij-community,suncycheng/intellij-community,izonder/intellij-community,wreckJ/intellij-community,akosyakov/intellij-community,mglukhikh/intellij-community,lucafavatella/intellij-community,michaelgallacher/intellij-community,adedayo/intellij-community,wreckJ/intellij-community,wreckJ/intellij-community,adedayo/intellij-community,gnuhub/intellij-community,suncycheng/intellij-community,ThiagoGarciaAlves/intellij-community,blademainer/intellij-community,consulo/consulo,fitermay/intellij-community,muntasirsyed/intellij-community,dslomov/intellij-community,MER-GROUP/intellij-community,samthor/intellij-community,petteyg/intellij-community,akosyakov/intellij-community,retomerz/intellij-community,youdonghai/intellij-community,supersven/intellij-community,samthor/intellij-community,youdonghai/intellij-community,nicolargo/intellij-community,supersven/intellij-community,suncycheng/intellij-community,ThiagoGarciaAlves/intellij-community,vladmm/intellij-community,vvv1559/intellij-community,robovm/robovm-studio,asedunov/intellij-community,Lekanich/intellij-community,amith01994/intellij-community,fnouama/intellij-community,MichaelNedzelsky/intellij-community,xfournet/intellij-community,fitermay/intellij-community,vvv1559/intellij-community,kool79/intellij-community,retomerz/intellij-community,pwoodworth/intellij-community,wreckJ/intellij-community,MER-GROUP/intellij-community,dslomov/intellij-community,nicolargo/intellij-community,dslomov/intellij-community,ahb0327/intellij-community,supersven/intellij-community,youdonghai/intellij-community,slisson/intellij-community,vladmm/intellij-community,izonder/intellij-community,semonte/intellij-community,adedayo/intellij-community,ThiagoGarciaAlves/intellij-community,fnouama/intellij-community,Distrotech/intellij-community,clumsy/intellij-community,SerCeMan/intellij-community,adedayo/intellij-community,MER-GROUP/intellij-community,gnuhub/intellij-community,holmes/intellij-community,holmes/intellij-community,lucafavatella/intellij-community,suncycheng/intellij-community,akosyakov/intellij-community,idea4bsd/idea4bsd,amith01994/intellij-community,lucafavatella/intellij-community,gnuhub/intellij-community,jagguli/intellij-community,Lekanich/intellij-community,MichaelNedzelsky/intellij-community,hurricup/intellij-community,idea4bsd/idea4bsd,slisson/intellij-community,ftomassetti/intellij-community,dslomov/intellij-community,salguarnieri/intellij-community,orekyuu/intellij-community,ftomassetti/intellij-community,orekyuu/intellij-community,diorcety/intellij-community,fengbaicanhe/intellij-community,fengbaicanhe/intellij-community,ivan-fedorov/intellij-community,tmpgit/intellij-community,fnouama/intellij-community,retomerz/intellij-community,fnouama/intellij-community,vvv1559/intellij-community,apixandru/intellij-community,izonder/intellij-community,nicolargo/intellij-community,alphafoobar/intellij-community,michaelgallacher/intellij-community,muntasirsyed/intellij-community,ivan-fedorov/intellij-community,alphafoobar/intellij-community,caot/intellij-community,nicolargo/intellij-community,ibinti/intellij-community,xfournet/intellij-community,petteyg/intellij-community,amith01994/intellij-community,blademainer/intellij-community,ryano144/intellij-community,xfournet/intellij-community,fitermay/intellij-community,slisson/intellij-community,MER-GROUP/intellij-community,idea4bsd/idea4bsd,amith01994/intellij-community,petteyg/intellij-community,ryano144/intellij-community,clumsy/intellij-community,allotria/intellij-community,allotria/intellij-community,MichaelNedzelsky/intellij-community,salguarnieri/intellij-community,ThiagoGarciaAlves/intellij-community,retomerz/intellij-community,alphafoobar/intellij-community,xfournet/intellij-community,consulo/consulo,SerCeMan/intellij-community,vvv1559/intellij-community,samthor/intellij-community,ahb0327/intellij-community,apixandru/intellij-community,wreckJ/intellij-community,SerCeMan/intellij-community,Lekanich/intellij-community,allotria/intellij-community,fengbaicanhe/intellij-community,mglukhikh/intellij-community,clumsy/intellij-community,slisson/intellij-community,adedayo/intellij-community,ol-loginov/intellij-community,TangHao1987/intellij-community,robovm/robovm-studio,petteyg/intellij-community,diorcety/intellij-community,alphafoobar/intellij-community,signed/intellij-community,caot/intellij-community,akosyakov/intellij-community,SerCeMan/intellij-community,allotria/intellij-community,ibinti/intellij-community,samthor/intellij-community,ftomassetti/intellij-community,wreckJ/intellij-community,vvv1559/intellij-community,mglukhikh/intellij-community,FHannes/intellij-community,lucafavatella/intellij-community,adedayo/intellij-community,ryano144/intellij-community,michaelgallacher/intellij-community,allotria/intellij-community,petteyg/intellij-community,kdwink/intellij-community,suncycheng/intellij-community,gnuhub/intellij-community,ibinti/intellij-community,vvv1559/intellij-community,michaelgallacher/intellij-community,signed/intellij-community,nicolargo/intellij-community,da1z/intellij-community,semonte/intellij-community,slisson/intellij-community,ahb0327/intellij-community,ryano144/intellij-community,orekyuu/intellij-community,ThiagoGarciaAlves/intellij-community,jagguli/intellij-community,akosyakov/intellij-community,kdwink/intellij-community,mglukhikh/intellij-community,hurricup/intellij-community,ahb0327/intellij-community,ahb0327/intellij-community,pwoodworth/intellij-community,Distrotech/intellij-community,ahb0327/intellij-community,salguarnieri/intellij-community,retomerz/intellij-community,MichaelNedzelsky/intellij-community,kdwink/intellij-community,muntasirsyed/intellij-community,michaelgallacher/intellij-community,asedunov/intellij-community,vladmm/intellij-community,tmpgit/intellij-community,fitermay/intellij-community,MER-GROUP/intellij-community,supersven/intellij-community,robovm/robovm-studio,MichaelNedzelsky/intellij-community,MichaelNedzelsky/intellij-community,supersven/intellij-community,Lekanich/intellij-community,ryano144/intellij-community,hurricup/intellij-community,orekyuu/intellij-community,Lekanich/intellij-community,semonte/intellij-community,mglukhikh/intellij-community,SerCeMan/intellij-community,da1z/intellij-community,holmes/intellij-community,hurricup/intellij-community,semonte/intellij-community,FHannes/intellij-community,pwoodworth/intellij-community,slisson/intellij-community,pwoodworth/intellij-community,MER-GROUP/intellij-community,pwoodworth/intellij-community,izonder/intellij-community,retomerz/intellij-community,robovm/robovm-studio,da1z/intellij-community,Distrotech/intellij-community,dslomov/intellij-community,amith01994/intellij-community,pwoodworth/intellij-community,michaelgallacher/intellij-community,alphafoobar/intellij-community,Lekanich/intellij-community,samthor/intellij-community,fnouama/intellij-community,MichaelNedzelsky/intellij-community,jagguli/intellij-community,SerCeMan/intellij-community,lucafavatella/intellij-community,jagguli/intellij-community,vvv1559/intellij-community,adedayo/intellij-community,petteyg/intellij-community,mglukhikh/intellij-community,diorcety/intellij-community,blademainer/intellij-community,diorcety/intellij-community,ThiagoGarciaAlves/intellij-community,hurricup/intellij-community,vladmm/intellij-community,TangHao1987/intellij-community,Lekanich/intellij-community,nicolargo/intellij-community,kool79/intellij-community,pwoodworth/intellij-community,signed/intellij-community,izonder/intellij-community,asedunov/intellij-community,ThiagoGarciaAlves/intellij-community,asedunov/intellij-community,ivan-fedorov/intellij-community,mglukhikh/intellij-community,ahb0327/intellij-community,ernestp/consulo,youdonghai/intellij-community,salguarnieri/intellij-community,fitermay/intellij-community,semonte/intellij-community,holmes/intellij-community,lucafavatella/intellij-community,robovm/robovm-studio,semonte/intellij-community,youdonghai/intellij-community,akosyakov/intellij-community,kdwink/intellij-community,holmes/intellij-community,allotria/intellij-community,blademainer/intellij-community,wreckJ/intellij-community,SerCeMan/intellij-community,youdonghai/intellij-community,lucafavatella/intellij-community,ibinti/intellij-community,salguarnieri/intellij-community,gnuhub/intellij-community,muntasirsyed/intellij-community,alphafoobar/intellij-community,lucafavatella/intellij-community,SerCeMan/intellij-community,jagguli/intellij-community,clumsy/intellij-community,wreckJ/intellij-community,jagguli/intellij-community,Lekanich/intellij-community,ThiagoGarciaAlves/intellij-community,petteyg/intellij-community,da1z/intellij-community,kdwink/intellij-community,xfournet/intellij-community,nicolargo/intellij-community,ivan-fedorov/intellij-community,robovm/robovm-studio,FHannes/intellij-community,FHannes/intellij-community,lucafavatella/intellij-community,semonte/intellij-community,dslomov/intellij-community,kdwink/intellij-community,Distrotech/intellij-community,Distrotech/intellij-community,fengbaicanhe/intellij-community,da1z/intellij-community,suncycheng/intellij-community,ThiagoGarciaAlves/intellij-community,diorcety/intellij-community,fnouama/intellij-community,ryano144/intellij-community,izonder/intellij-community,ThiagoGarciaAlves/intellij-community,diorcety/intellij-community,da1z/intellij-community,MER-GROUP/intellij-community,muntasirsyed/intellij-community,fnouama/intellij-community,SerCeMan/intellij-community,petteyg/intellij-community,hurricup/intellij-community,fengbaicanhe/intellij-community,da1z/intellij-community,signed/intellij-community,salguarnieri/intellij-community,TangHao1987/intellij-community,slisson/intellij-community,muntasirsyed/intellij-community,samthor/intellij-community,ahb0327/intellij-community,ftomassetti/intellij-community,allotria/intellij-community,michaelgallacher/intellij-community,akosyakov/intellij-community,fengbaicanhe/intellij-community,kool79/intellij-community,signed/intellij-community,retomerz/intellij-community,orekyuu/intellij-community,robovm/robovm-studio,apixandru/intellij-community,izonder/intellij-community,petteyg/intellij-community,ol-loginov/intellij-community,ernestp/consulo,retomerz/intellij-community,amith01994/intellij-community,robovm/robovm-studio
plugins/svn4idea/src/org/jetbrains/idea/svn/dialogs/SelectIgnorePatternsToRemoveOnDeleteDialog.java
/* * Copyright 2000-2009 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jetbrains.idea.svn.dialogs; import com.intellij.ide.CommonActionsManager; import com.intellij.ide.TreeExpander; import com.intellij.openapi.actionSystem.*; import com.intellij.openapi.keymap.KeymapManager; import com.intellij.openapi.project.Project; import com.intellij.openapi.ui.DialogWrapper; import com.intellij.openapi.ui.MultiLineLabelUI; import com.intellij.openapi.util.IconLoader; import com.intellij.openapi.util.SystemInfo; import com.intellij.openapi.util.io.FileUtil; import com.intellij.openapi.vcs.FileStatus; import com.intellij.ui.*; import com.intellij.util.Consumer; import com.intellij.util.Icons; import com.intellij.util.ui.UIUtil; import com.intellij.util.ui.tree.TreeUtil; import org.jetbrains.idea.svn.IgnoredFileInfo; import org.jetbrains.idea.svn.SvnBundle; import javax.swing.*; import javax.swing.tree.TreeModel; import java.awt.*; import java.awt.event.KeyEvent; import java.io.File; import java.util.*; import java.util.List; public class SelectIgnorePatternsToRemoveOnDeleteDialog extends DialogWrapper { private final JPanel myPanel; private final CheckboxTree myTree; private final Collection<IgnoredFileInfo> myResult; public SelectIgnorePatternsToRemoveOnDeleteDialog(final Project project, final Map<String, IgnoredFileInfo> data) { super(project, true); myResult = new ArrayList<IgnoredFileInfo>(); myPanel = new JPanel(new GridBagLayout()); myTree = new CheckboxTree(new MyRenderer(), createTree(data), new CheckboxTreeBase.CheckPolicy(false, false, true, true)); myTree.setBorder(BorderFactory.createLineBorder(UIUtil.getHeaderActiveColor(), 1)); final JLabel prompt = new JLabel(SvnBundle.message("svn.dialog.select.ignore.patterns.to.remove.prompt")); prompt.setUI(new MultiLineLabelUI()); final GridBagConstraints gb = new GridBagConstraints(0, 0, 1, 1, 0, 0, GridBagConstraints.NORTHWEST, GridBagConstraints.NONE, new Insets(1, 1, 1, 1), 0, 0); gb.insets.bottom = 5; myPanel.add(prompt, gb); gb.insets.top = 5; ++ gb.gridy; gb.anchor = GridBagConstraints.WEST; gb.fill = GridBagConstraints.BOTH; gb.weightx = 1; gb.weighty = 1; myPanel.add(myTree, gb); ++ gb.gridx; gb.anchor = GridBagConstraints.EAST; gb.fill = GridBagConstraints.NONE; gb.weightx = 0; gb.weighty = 0; myPanel.add(createTreeToolbarPanel().getComponent(), gb); setTitle(SvnBundle.message("svn.dialog.select.ignore.patterns.to.remove.title")); init(); TreeUtil.expandAll(myTree); } @Override protected void doOKAction() { final TreeModel treeModel = myTree.getModel(); final CheckedTreeNode root = (CheckedTreeNode)treeModel.getRoot(); final Enumeration files = root.children(); while (files.hasMoreElements()) { final MyFileNode fileNode = (MyFileNode) files.nextElement(); final IgnoredFileInfo info = new IgnoredFileInfo(fileNode.myFile, fileNode.myPropValue); final Enumeration patterns = fileNode.children(); while (patterns.hasMoreElements()) { final MyPatternNode patternNode = (MyPatternNode) patterns.nextElement(); if (patternNode.isChecked()) { info.addPattern(patternNode.myPattern); } } if (! info.getPatterns().isEmpty()) { myResult.add(info); } } super.doOKAction(); } public Collection<IgnoredFileInfo> getResult() { return myResult; } private ActionToolbar createTreeToolbarPanel() { final CommonActionsManager actionManager = CommonActionsManager.getInstance(); TreeExpander treeExpander = new TreeExpander() { public void expandAll() { TreeUtil.expandAll(myTree); } public boolean canExpand() { return true; } public void collapseAll() { TreeUtil.collapseAll(myTree, 3); } public boolean canCollapse() { return true; } }; final AnAction expandAllAction = actionManager.createExpandAllAction(treeExpander, myTree); final AnAction collapseAllAction = actionManager.createCollapseAllAction(treeExpander, myTree); final SelectAllAction selectAllAction = new SelectAllAction(true); final SelectAllAction unSelectAllAction = new SelectAllAction(false); expandAllAction.registerCustomShortcutSet( new CustomShortcutSet(KeymapManager.getInstance().getActiveKeymap().getShortcuts(IdeActions.ACTION_EXPAND_ALL)), myTree); collapseAllAction.registerCustomShortcutSet( new CustomShortcutSet(KeymapManager.getInstance().getActiveKeymap().getShortcuts(IdeActions.ACTION_COLLAPSE_ALL)), myTree); selectAllAction.registerCustomShortcutSet( new CustomShortcutSet(KeyStroke.getKeyStroke(KeyEvent.VK_A, SystemInfo.isMac ? KeyEvent.META_DOWN_MASK : KeyEvent.CTRL_DOWN_MASK)), myTree); DefaultActionGroup actions = new DefaultActionGroup(); actions.add(expandAllAction); actions.add(collapseAllAction); actions.add(selectAllAction); actions.add(unSelectAllAction); return ActionManager.getInstance().createActionToolbar(ActionPlaces.UNKNOWN, actions, false); } private CheckedTreeNode createTree(final Map<String, IgnoredFileInfo> data) { final CheckedTreeNode root = new CheckedTreeNode("root"); final List<String> dirs = new ArrayList<String>(data.keySet()); Collections.sort(dirs); for (String dir : dirs) { final IgnoredFileInfo info = data.get(dir); final MyFileNode fileNode = new MyFileNode(info.getFile(), info.getOldPatterns()); root.add(fileNode); final List<String> patterns = info.getPatterns(); Collections.sort(patterns); for (String pattern : patterns) { final MyPatternNode patternNode = new MyPatternNode(pattern); fileNode.add(patternNode); } } return root; } protected JComponent createCenterPanel() { return myPanel; } private class MyRenderer extends CheckboxTree.CheckboxTreeCellRenderer { public void customizeCellRenderer(JTree tree, Object value, boolean selected, boolean expanded, boolean leaf, int row, boolean hasFocus) { // Fix GTK background if (UIUtil.isUnderGTKLookAndFeel()){ final Color background = selected ? UIUtil.getTreeSelectionBackground() : UIUtil.getTreeTextBackground(); UIUtil.changeBackGround(this, background); } final ColoredTreeCellRenderer textRenderer = getTextRenderer(); if (value instanceof MyConsumer) { ((MyConsumer) value).consume(textRenderer); } } } private interface MyConsumer extends Consumer<ColoredTreeCellRenderer> {} private final static SimpleTextAttributes ourIgnoredAttributes = new SimpleTextAttributes(SimpleTextAttributes.STYLE_PLAIN, FileStatus.IGNORED.getColor()); private class MyFileNode extends CheckedTreeNode implements MyConsumer, Comparable<MyFileNode> { private final File myFile; private final Set<String> myPropValue; private final String myParentPath; private MyFileNode(final File file, final Set<String> propValue) { super(file); myPropValue = propValue; myFile = file; myParentPath = FileUtil.toSystemIndependentName(file.getParent()); setEnabled(false); } public void consume(ColoredTreeCellRenderer renderer) { renderer.append(myFile.getName(), ourIgnoredAttributes); renderer.append(" (" + myParentPath + ")", SimpleTextAttributes.GRAYED_ATTRIBUTES); renderer.setIcon(Icons.DIRECTORY_CLOSED_ICON); } public int compareTo(MyFileNode o) { final int parentCompare = myParentPath.compareTo(o.myParentPath); if (parentCompare == 0) { return myFile.compareTo(o.myFile); } return parentCompare; } } public class MyPatternNode extends CheckedTreeNode implements MyConsumer { private final String myPattern; private MyPatternNode(final String pattern) { super(pattern); myPattern = pattern; } public void consume(ColoredTreeCellRenderer coloredTreeCellRenderer) { coloredTreeCellRenderer.append(myPattern, SimpleTextAttributes.REGULAR_ATTRIBUTES); } public String getPattern() { return myPattern; } public File getFile() { return (File) ((MyFileNode) getParent()).getUserObject(); } } private class SelectAllAction extends AnAction { private final boolean mySelect; private SelectAllAction(boolean select) { super(select ? "Select All" : "Unselect All", select ? "Select all items" : "Unselect all items", IconLoader.getIcon(select ? "/actions/selectall.png" : "/actions/unselectall.png")); mySelect = select; } public void actionPerformed(AnActionEvent e) { final TreeModel treeModel = myTree.getModel(); final CheckedTreeNode root = (CheckedTreeNode) treeModel.getRoot(); select(root); myTree.repaint(); } private void select(final CheckedTreeNode node) { if (node instanceof MyPatternNode) { node.setChecked(mySelect); } else { final int cnt = node.getChildCount(); for (int i = 0; i < cnt; i++) { select((CheckedTreeNode) node.getChildAt(i)); } } } } }
IDEA-55104 Select svn:ignore patterns to remove usability (do not suggest to delete ignore patterns on ignore target deletion)
plugins/svn4idea/src/org/jetbrains/idea/svn/dialogs/SelectIgnorePatternsToRemoveOnDeleteDialog.java
IDEA-55104 Select svn:ignore patterns to remove usability (do not suggest to delete ignore patterns on ignore target deletion)
<ide><path>lugins/svn4idea/src/org/jetbrains/idea/svn/dialogs/SelectIgnorePatternsToRemoveOnDeleteDialog.java <del>/* <del> * Copyright 2000-2009 JetBrains s.r.o. <del> * <del> * Licensed under the Apache License, Version 2.0 (the "License"); <del> * you may not use this file except in compliance with the License. <del> * You may obtain a copy of the License at <del> * <del> * http://www.apache.org/licenses/LICENSE-2.0 <del> * <del> * Unless required by applicable law or agreed to in writing, software <del> * distributed under the License is distributed on an "AS IS" BASIS, <del> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. <del> * See the License for the specific language governing permissions and <del> * limitations under the License. <del> */ <del>package org.jetbrains.idea.svn.dialogs; <del> <del>import com.intellij.ide.CommonActionsManager; <del>import com.intellij.ide.TreeExpander; <del>import com.intellij.openapi.actionSystem.*; <del>import com.intellij.openapi.keymap.KeymapManager; <del>import com.intellij.openapi.project.Project; <del>import com.intellij.openapi.ui.DialogWrapper; <del>import com.intellij.openapi.ui.MultiLineLabelUI; <del>import com.intellij.openapi.util.IconLoader; <del>import com.intellij.openapi.util.SystemInfo; <del>import com.intellij.openapi.util.io.FileUtil; <del>import com.intellij.openapi.vcs.FileStatus; <del>import com.intellij.ui.*; <del>import com.intellij.util.Consumer; <del>import com.intellij.util.Icons; <del>import com.intellij.util.ui.UIUtil; <del>import com.intellij.util.ui.tree.TreeUtil; <del>import org.jetbrains.idea.svn.IgnoredFileInfo; <del>import org.jetbrains.idea.svn.SvnBundle; <del> <del>import javax.swing.*; <del>import javax.swing.tree.TreeModel; <del>import java.awt.*; <del>import java.awt.event.KeyEvent; <del>import java.io.File; <del>import java.util.*; <del>import java.util.List; <del> <del>public class SelectIgnorePatternsToRemoveOnDeleteDialog extends DialogWrapper { <del> private final JPanel myPanel; <del> private final CheckboxTree myTree; <del> private final Collection<IgnoredFileInfo> myResult; <del> <del> public SelectIgnorePatternsToRemoveOnDeleteDialog(final Project project, final Map<String, IgnoredFileInfo> data) { <del> super(project, true); <del> <del> myResult = new ArrayList<IgnoredFileInfo>(); <del> <del> myPanel = new JPanel(new GridBagLayout()); <del> myTree = new CheckboxTree(new MyRenderer(), createTree(data), new CheckboxTreeBase.CheckPolicy(false, false, true, true)); <del> myTree.setBorder(BorderFactory.createLineBorder(UIUtil.getHeaderActiveColor(), 1)); <del> <del> final JLabel prompt = new JLabel(SvnBundle.message("svn.dialog.select.ignore.patterns.to.remove.prompt")); <del> prompt.setUI(new MultiLineLabelUI()); <del> <del> final GridBagConstraints gb = <del> new GridBagConstraints(0, 0, 1, 1, 0, 0, GridBagConstraints.NORTHWEST, GridBagConstraints.NONE, new Insets(1, 1, 1, 1), 0, 0); <del> <del> gb.insets.bottom = 5; <del> myPanel.add(prompt, gb); <del> <del> gb.insets.top = 5; <del> ++ gb.gridy; <del> gb.anchor = GridBagConstraints.WEST; <del> gb.fill = GridBagConstraints.BOTH; <del> gb.weightx = 1; <del> gb.weighty = 1; <del> myPanel.add(myTree, gb); <del> <del> ++ gb.gridx; <del> gb.anchor = GridBagConstraints.EAST; <del> gb.fill = GridBagConstraints.NONE; <del> gb.weightx = 0; <del> gb.weighty = 0; <del> myPanel.add(createTreeToolbarPanel().getComponent(), gb); <del> <del> setTitle(SvnBundle.message("svn.dialog.select.ignore.patterns.to.remove.title")); <del> <del> init(); <del> TreeUtil.expandAll(myTree); <del> } <del> <del> @Override <del> protected void doOKAction() { <del> final TreeModel treeModel = myTree.getModel(); <del> final CheckedTreeNode root = (CheckedTreeNode)treeModel.getRoot(); <del> final Enumeration files = root.children(); <del> <del> while (files.hasMoreElements()) { <del> final MyFileNode fileNode = (MyFileNode) files.nextElement(); <del> final IgnoredFileInfo info = new IgnoredFileInfo(fileNode.myFile, fileNode.myPropValue); <del> final Enumeration patterns = fileNode.children(); <del> <del> while (patterns.hasMoreElements()) { <del> final MyPatternNode patternNode = (MyPatternNode) patterns.nextElement(); <del> if (patternNode.isChecked()) { <del> info.addPattern(patternNode.myPattern); <del> } <del> } <del> if (! info.getPatterns().isEmpty()) { <del> myResult.add(info); <del> } <del> } <del> <del> super.doOKAction(); <del> } <del> <del> public Collection<IgnoredFileInfo> getResult() { <del> return myResult; <del> } <del> <del> private ActionToolbar createTreeToolbarPanel() { <del> final CommonActionsManager actionManager = CommonActionsManager.getInstance(); <del> <del> TreeExpander treeExpander = new TreeExpander() { <del> public void expandAll() { <del> TreeUtil.expandAll(myTree); <del> } <del> <del> public boolean canExpand() { <del> return true; <del> } <del> <del> public void collapseAll() { <del> TreeUtil.collapseAll(myTree, 3); <del> } <del> <del> public boolean canCollapse() { <del> return true; <del> } <del> }; <del> <del> final AnAction expandAllAction = actionManager.createExpandAllAction(treeExpander, myTree); <del> final AnAction collapseAllAction = actionManager.createCollapseAllAction(treeExpander, myTree); <del> final SelectAllAction selectAllAction = new SelectAllAction(true); <del> final SelectAllAction unSelectAllAction = new SelectAllAction(false); <del> <del> expandAllAction.registerCustomShortcutSet( <del> new CustomShortcutSet(KeymapManager.getInstance().getActiveKeymap().getShortcuts(IdeActions.ACTION_EXPAND_ALL)), myTree); <del> collapseAllAction.registerCustomShortcutSet( <del> new CustomShortcutSet(KeymapManager.getInstance().getActiveKeymap().getShortcuts(IdeActions.ACTION_COLLAPSE_ALL)), myTree); <del> selectAllAction.registerCustomShortcutSet( <del> new CustomShortcutSet(KeyStroke.getKeyStroke(KeyEvent.VK_A, SystemInfo.isMac ? KeyEvent.META_DOWN_MASK : KeyEvent.CTRL_DOWN_MASK)), <del> myTree); <del> <del> DefaultActionGroup actions = new DefaultActionGroup(); <del> actions.add(expandAllAction); <del> actions.add(collapseAllAction); <del> actions.add(selectAllAction); <del> actions.add(unSelectAllAction); <del> <del> return ActionManager.getInstance().createActionToolbar(ActionPlaces.UNKNOWN, actions, false); <del> } <del> <del> private CheckedTreeNode createTree(final Map<String, IgnoredFileInfo> data) { <del> final CheckedTreeNode root = new CheckedTreeNode("root"); <del> <del> final List<String> dirs = new ArrayList<String>(data.keySet()); <del> Collections.sort(dirs); <del> for (String dir : dirs) { <del> final IgnoredFileInfo info = data.get(dir); <del> <del> final MyFileNode fileNode = new MyFileNode(info.getFile(), info.getOldPatterns()); <del> root.add(fileNode); <del> final List<String> patterns = info.getPatterns(); <del> Collections.sort(patterns); <del> for (String pattern : patterns) { <del> final MyPatternNode patternNode = new MyPatternNode(pattern); <del> fileNode.add(patternNode); <del> } <del> } <del> return root; <del> } <del> <del> protected JComponent createCenterPanel() { <del> return myPanel; <del> } <del> <del> private class MyRenderer extends CheckboxTree.CheckboxTreeCellRenderer { <del> public void customizeCellRenderer(JTree tree, Object value, boolean selected, boolean expanded, boolean leaf, int row, boolean hasFocus) { <del> // Fix GTK background <del> if (UIUtil.isUnderGTKLookAndFeel()){ <del> final Color background = selected ? UIUtil.getTreeSelectionBackground() : UIUtil.getTreeTextBackground(); <del> UIUtil.changeBackGround(this, background); <del> } <del> final ColoredTreeCellRenderer textRenderer = getTextRenderer(); <del> if (value instanceof MyConsumer) { <del> ((MyConsumer) value).consume(textRenderer); <del> } <del> } <del> } <del> <del> private interface MyConsumer extends Consumer<ColoredTreeCellRenderer> {} <del> <del> private final static SimpleTextAttributes ourIgnoredAttributes = <del> new SimpleTextAttributes(SimpleTextAttributes.STYLE_PLAIN, FileStatus.IGNORED.getColor()); <del> <del> private class MyFileNode extends CheckedTreeNode implements MyConsumer, Comparable<MyFileNode> { <del> private final File myFile; <del> private final Set<String> myPropValue; <del> private final String myParentPath; <del> <del> private MyFileNode(final File file, final Set<String> propValue) { <del> super(file); <del> myPropValue = propValue; <del> myFile = file; <del> myParentPath = FileUtil.toSystemIndependentName(file.getParent()); <del> <del> setEnabled(false); <del> } <del> <del> public void consume(ColoredTreeCellRenderer renderer) { <del> renderer.append(myFile.getName(), ourIgnoredAttributes); <del> renderer.append(" (" + myParentPath + ")", SimpleTextAttributes.GRAYED_ATTRIBUTES); <del> renderer.setIcon(Icons.DIRECTORY_CLOSED_ICON); <del> } <del> <del> public int compareTo(MyFileNode o) { <del> final int parentCompare = myParentPath.compareTo(o.myParentPath); <del> if (parentCompare == 0) { <del> return myFile.compareTo(o.myFile); <del> } <del> return parentCompare; <del> } <del> } <del> <del> public class MyPatternNode extends CheckedTreeNode implements MyConsumer { <del> private final String myPattern; <del> <del> private MyPatternNode(final String pattern) { <del> super(pattern); <del> myPattern = pattern; <del> } <del> <del> public void consume(ColoredTreeCellRenderer coloredTreeCellRenderer) { <del> coloredTreeCellRenderer.append(myPattern, SimpleTextAttributes.REGULAR_ATTRIBUTES); <del> } <del> <del> public String getPattern() { <del> return myPattern; <del> } <del> <del> public File getFile() { <del> return (File) ((MyFileNode) getParent()).getUserObject(); <del> } <del> } <del> <del> private class SelectAllAction extends AnAction { <del> private final boolean mySelect; <del> <del> private SelectAllAction(boolean select) { <del> super(select ? "Select All" : "Unselect All", select ? "Select all items" : "Unselect all items", <del> IconLoader.getIcon(select ? "/actions/selectall.png" : "/actions/unselectall.png")); <del> mySelect = select; <del> } <del> <del> public void actionPerformed(AnActionEvent e) { <del> final TreeModel treeModel = myTree.getModel(); <del> final CheckedTreeNode root = (CheckedTreeNode) treeModel.getRoot(); <del> select(root); <del> myTree.repaint(); <del> } <del> <del> private void select(final CheckedTreeNode node) { <del> if (node instanceof MyPatternNode) { <del> node.setChecked(mySelect); <del> } else { <del> final int cnt = node.getChildCount(); <del> for (int i = 0; i < cnt; i++) { <del> select((CheckedTreeNode) node.getChildAt(i)); <del> } <del> } <del> } <del> } <del>}
Java
lgpl-2.1
a643dd52b7dbf4ed858dc58f4828e943432965f1
0
tomck/intermine,Arabidopsis-Information-Portal/intermine,tomck/intermine,zebrafishmine/intermine,JoeCarlson/intermine,joshkh/intermine,drhee/toxoMine,elsiklab/intermine,drhee/toxoMine,elsiklab/intermine,JoeCarlson/intermine,elsiklab/intermine,drhee/toxoMine,Arabidopsis-Information-Portal/intermine,zebrafishmine/intermine,drhee/toxoMine,zebrafishmine/intermine,Arabidopsis-Information-Portal/intermine,Arabidopsis-Information-Portal/intermine,tomck/intermine,zebrafishmine/intermine,justincc/intermine,JoeCarlson/intermine,joshkh/intermine,justincc/intermine,tomck/intermine,drhee/toxoMine,joshkh/intermine,Arabidopsis-Information-Portal/intermine,kimrutherford/intermine,elsiklab/intermine,drhee/toxoMine,justincc/intermine,joshkh/intermine,JoeCarlson/intermine,elsiklab/intermine,kimrutherford/intermine,tomck/intermine,tomck/intermine,Arabidopsis-Information-Portal/intermine,elsiklab/intermine,kimrutherford/intermine,justincc/intermine,kimrutherford/intermine,tomck/intermine,kimrutherford/intermine,tomck/intermine,elsiklab/intermine,drhee/toxoMine,joshkh/intermine,kimrutherford/intermine,kimrutherford/intermine,justincc/intermine,JoeCarlson/intermine,drhee/toxoMine,Arabidopsis-Information-Portal/intermine,JoeCarlson/intermine,JoeCarlson/intermine,JoeCarlson/intermine,justincc/intermine,JoeCarlson/intermine,zebrafishmine/intermine,elsiklab/intermine,joshkh/intermine,justincc/intermine,joshkh/intermine,joshkh/intermine,joshkh/intermine,Arabidopsis-Information-Portal/intermine,justincc/intermine,Arabidopsis-Information-Portal/intermine,justincc/intermine,zebrafishmine/intermine,elsiklab/intermine,tomck/intermine,zebrafishmine/intermine,kimrutherford/intermine,zebrafishmine/intermine,kimrutherford/intermine,zebrafishmine/intermine,drhee/toxoMine
package org.intermine.webservice.server.output; import java.util.ArrayList; import java.util.Arrays; import java.util.Calendar; import java.util.Collections; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Set; import java.util.TimeZone; import java.util.TreeMap; import org.intermine.api.query.MainHelper; import org.intermine.api.results.ExportResultsIterator; import org.intermine.api.results.ResultElement; import org.intermine.metadata.Model; import org.intermine.model.testmodel.Address; import org.intermine.model.testmodel.CEO; import org.intermine.model.testmodel.Company; import org.intermine.model.testmodel.Contractor; import org.intermine.model.testmodel.Department; import org.intermine.model.testmodel.Employee; import org.intermine.model.testmodel.Manager; import org.intermine.model.testmodel.Types; import org.intermine.objectstore.dummy.DummyResults; import org.intermine.objectstore.dummy.ObjectStoreDummyImpl; import org.intermine.objectstore.query.Query; import org.intermine.objectstore.query.Results; import org.intermine.objectstore.query.ResultsRow; import org.intermine.pathquery.OuterJoinStatus; import org.intermine.pathquery.Path; import org.intermine.pathquery.PathException; import org.intermine.pathquery.PathQuery; import org.intermine.util.DynamicUtil; import org.intermine.util.IteratorIterable; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import junit.framework.AssertionFailedError; import junit.framework.TestCase; /** * Tests for the JSONResultsIterator class * * @author Alexis Kalderimis */ public class JSONResultsIteratorTest extends TestCase { /** * Compare two JSONObjects for equality * @param left The reference JSONObject (this is referred to as "expected" in any messages) * @param right The candidate object to check. * @return a String with messages explaining the problems if there are any, otherwise null (equal) * @throws JSONException */ private static String getProblemsComparing(JSONObject left, Object right) throws JSONException { List<String> problems = new ArrayList<String>(); if (left == null ) { if (right != null) { return "Expected null, but got " + right; } else { return null; } } if (! (right instanceof JSONObject)) { if (right == null) { return "Didn't expect null, but got null"; } else { return "Expected a JSONObject, is got a " + right.getClass(); } } JSONObject rjo = (JSONObject) right; Set<String> leftNames = new HashSet<String>(Arrays.asList(JSONObject.getNames(left))); Set<String> rightNames = new HashSet<String>(Arrays.asList(JSONObject.getNames(rjo))); if (! leftNames.equals(rightNames)) { problems.add("Expected the keys " + leftNames + ", but got these: " + rightNames); } for (String name : leftNames) { Object leftValue = left.get(name); String problem = null; try { if (leftValue == null) { if ( rjo.get(name) != null ) { problem = "Expected null, but got " + rjo.get(name); } } else if (leftValue instanceof JSONObject) { problem = getProblemsComparing((JSONObject) leftValue, rjo.get(name)); } else if (leftValue instanceof JSONArray) { problem = getProblemsComparing((JSONArray) leftValue, rjo.get(name)); } else { if (! leftValue.toString().equals(rjo.get(name).toString())) { problem = "Expected " + leftValue + " but got " + rjo.get(name); } } } catch (Throwable e) { problem = e.toString(); } if (problem != null) { problems.add("Problem with " + name + ": " + problem); } } if (problems.isEmpty()) { return null; } return problems.toString(); } /** * Compare two JSONArrays for equality * @param left The reference array (referred to as "expected" in any messages) * @param right The candidate object to check. * @return a String with messages explaining the problems if there are any, otherwise null (equal) * @throws JSONException */ private static String getProblemsComparing(JSONArray left, Object right) throws JSONException { List<String> problems = new ArrayList<String>(); if (left == null ) { if (right != null) { return "Expected null, but got " + right; } else { return null; } } if (! (right instanceof JSONArray)) { return "Expected a JSONArray, but got a " + right.getClass(); } JSONArray rja = (JSONArray) right; if (left.length() != rja.length()) { problems.add("Expected the size of this array to be " + left.length() + " but got " + rja.length()); } for (int index = 0; index < left.length(); index++) { Object leftMember = left.get(index); String problem = null; try { if (leftMember== null) { if ( rja.get(index) != null ) { problem = "Expected null, but got " + rja.get(index); } } else if (leftMember instanceof JSONObject) { problem = getProblemsComparing((JSONObject) leftMember, rja.get(index)); } else if (leftMember instanceof JSONArray) { problem = getProblemsComparing((JSONArray) leftMember, rja.get(index)); } else { if (! leftMember.toString().equals(rja.get(index).toString())) { problem = "Expected " + leftMember + " but got " + rja.get(index); } } } catch (Throwable e) { problem = e.toString(); } if (problem != null) { problems.add("Problem with index " + index + ": " + problem); } } if (problems.isEmpty()) { return null; } return problems.toString(); } private ObjectStoreDummyImpl os; private Company wernhamHogg; private CEO jennifer; private Manager david; private Manager taffy; private Employee tim; private Employee gareth; private Employee dawn; private Employee keith; private Employee lee; private Employee alex; private Department sales; private Department reception; private Department accounts; private Department distribution; private Address address; private Contractor rowan; private Contractor ray; private Contractor jude; private Department swindon; private Manager neil; private Employee rachel; private Employee trudy; protected void setUp() { os = new ObjectStoreDummyImpl(); wernhamHogg = (Company) DynamicUtil.createObject(Collections.singleton(Company.class)); wernhamHogg.setId(new Integer(1)); wernhamHogg.setName("Wernham-Hogg"); wernhamHogg.setVatNumber(101); jennifer = new CEO(); jennifer.setId(new Integer(2)); jennifer.setName("Jennifer Taylor-Clarke"); jennifer.setAge(42); david = new Manager(); david.setId(new Integer(3)); david.setName("David Brent"); david.setAge(39); taffy = new Manager(); taffy.setId(new Integer(4)); taffy.setName("Glynn"); taffy.setAge(38); tim = new Employee(); tim.setId(new Integer(5)); tim.setName("Tim Canterbury"); tim.setAge(30); gareth = new Employee(); gareth.setId(new Integer(6)); gareth.setName("Gareth Keenan"); gareth.setAge(32); dawn = new Employee(); dawn.setId(new Integer(7)); dawn.setName("Dawn Tinsley"); dawn.setAge(26); keith = new Employee(); keith.setId(new Integer(8)); keith.setName("Keith Bishop"); keith.setAge(41); lee = new Employee(); lee.setId(new Integer(9)); lee.setName("Lee"); lee.setAge(28); alex = new Employee(); alex.setId(new Integer(10)); alex.setName("Alex"); alex.setAge(24); sales = new Department(); sales.setId(new Integer(11)); sales.setName("Sales"); accounts = new Department(); accounts.setId(new Integer(12)); accounts.setName("Accounts"); distribution = new Department(); distribution.setId(new Integer(13)); distribution.setName("Warehouse"); reception = new Department(); reception.setId(new Integer(14)); reception.setName("Reception"); address = new Address(); address.setId(new Integer(15)); address.setAddress("42 Some St, Slough"); rowan = new Contractor(); rowan.setId(new Integer(16)); rowan.setName("Rowan"); ray = new Contractor(); ray.setId(new Integer(17)); ray.setName("Ray"); jude = new Contractor(); jude.setId(new Integer(18)); jude.setName("Jude"); swindon = new Department(); swindon.setId(new Integer(19)); swindon.setName("Swindon"); neil = new Manager(); neil.setId(new Integer(20)); neil.setName("Neil Godwin"); neil.setAge(35); rachel = new Employee(); rachel.setId(new Integer(21)); rachel.setName("Rachel"); rachel.setAge(34); trudy = new Employee(); trudy.setId(new Integer(22)); trudy.setName("Trudy"); trudy.setAge(25); } private final Model model = Model.getInstanceByName("testmodel"); public JSONResultsIteratorTest(String arg) { super(arg); } public void testSingleSimpleObject() throws Exception { os.setResultsSize(1); String jsonString = "{ 'class': 'Manager', 'objectId': 3, 'age': 39, 'name': 'David Brent' }"; JSONObject expected = new JSONObject(jsonString); ResultsRow row = new ResultsRow(); row.add(david); os.addRow(row); PathQuery pq = new PathQuery(model); pq.addViews("Manager.name", "Manager.age"); Map pathToQueryNode = new HashMap(); Query q = MainHelper.makeQuery(pq, new HashMap(), pathToQueryNode, null, null); List resultList = os.execute(q, 0, 5, true, true, new HashMap()); Results results = new DummyResults(q, resultList); ExportResultsIterator iter = new ExportResultsIterator(pq, results, pathToQueryNode); JSONResultsIterator jsonIter = new JSONResultsIterator(iter); List<JSONObject> got = new ArrayList<JSONObject>(); for (JSONObject gotRow : new IteratorIterable<JSONObject>(jsonIter)) { got.add(gotRow); } assertEquals(1, got.size()); assertEquals(null, getProblemsComparing(expected, got.get(0))); } public void testMultipleSimpleObjects() throws Exception { os.setResultsSize(5); List<String> jsonStrings = new ArrayList<String>(); jsonStrings.add("{ 'class':'Employee', 'objectId':5, 'age':30, 'name': 'Tim Canterbury' }"); jsonStrings.add("{ 'class':'Employee', 'objectId':6, 'age':32, 'name': 'Gareth Keenan' }"); jsonStrings.add("{ 'class':'Employee', 'objectId':7, 'age':26, 'name': 'Dawn Tinsley' }"); jsonStrings.add("{ 'class':'Employee', 'objectId':8, 'age':41, 'name': 'Keith Bishop' }"); jsonStrings.add("{ 'class':'Employee', 'objectId':9, 'age':28, 'name': 'Lee' }"); ResultsRow row1 = new ResultsRow(); row1.add(tim); ResultsRow row2 = new ResultsRow(); row2.add(gareth); ResultsRow row3 = new ResultsRow(); row3.add(dawn); ResultsRow row4 = new ResultsRow(); row4.add(keith); ResultsRow row5 = new ResultsRow(); row5.add(lee); os.addRow(row1); os.addRow(row2); os.addRow(row3); os.addRow(row4); os.addRow(row5); PathQuery pq = new PathQuery(model); pq.addViews("Employee.name", "Employee.age", "Employee.id"); Map pathToQueryNode = new HashMap(); Query q = MainHelper.makeQuery(pq, new HashMap(), pathToQueryNode, null, null); List resultList = os.execute(q, 0, 5, true, true, new HashMap()); Results results = new DummyResults(q, resultList); ExportResultsIterator iter = new ExportResultsIterator(pq, results, pathToQueryNode); JSONResultsIterator jsonIter = new JSONResultsIterator(iter); List<JSONObject> got = new ArrayList<JSONObject>(); for (JSONObject gotRow : new IteratorIterable<JSONObject>(jsonIter)) { got.add(gotRow); } assertEquals(5, got.size()); for (int i = 0; i < jsonStrings.size(); i++) { JSONObject jo = new JSONObject(jsonStrings.get(i)); assertEquals(null, getProblemsComparing(jo, got.get(i))); } } public void testSingleObjectWithNestedCollections() throws Exception { os.setResultsSize(1); ResultsRow row = new ResultsRow(); row.add(wernhamHogg); List sub1 = new ArrayList(); ResultsRow subRow1 = new ResultsRow(); subRow1.add(sales); List sub2 = new ArrayList(); ResultsRow subRow2 = new ResultsRow(); subRow2.add(tim); sub2.add(subRow2); subRow2 = new ResultsRow(); subRow2.add(gareth); sub2.add(subRow2); subRow1.add(sub2); sub1.add(subRow1); subRow1 = new ResultsRow(); subRow1.add(distribution); sub2 = new ArrayList(); subRow2 = new ResultsRow(); subRow2.add(lee); sub2.add(subRow2); subRow2 = new ResultsRow(); subRow2.add(alex); sub2.add(subRow2); subRow1.add(sub2); sub1.add(subRow1); row.add(sub1); os.addRow(row); PathQuery pq = new PathQuery(model); pq.addViews("Company.name", "Company.vatNumber", "Company.departments.name", "Company.departments.employees.name"); pq.setOuterJoinStatus("Company.departments", OuterJoinStatus.OUTER); pq.setOuterJoinStatus("Company.departments.employees", OuterJoinStatus.OUTER); Map pathToQueryNode = new HashMap(); Query q = MainHelper.makeQuery(pq, new HashMap(), pathToQueryNode, null, null); List resultList = os.execute(q, 0, 1, true, true, new HashMap()); Results results = new DummyResults(q, resultList); ExportResultsIterator iter = new ExportResultsIterator(pq, results, pathToQueryNode); JSONResultsIterator jsonIter = new JSONResultsIterator(iter); List<JSONObject> got = new ArrayList<JSONObject>(); for (JSONObject gotRow : new IteratorIterable<JSONObject>(jsonIter)) { got.add(gotRow); } assertEquals(got.size(), 1); String jsonString = "{" + " 'objectId' : 1," + " 'class' : 'Company'," + " 'name' : 'Wernham-Hogg'," + " 'vatNumber' : 101," + " 'departments' : [" + " {" + " 'objectId' : 11," + " 'class' : 'Department'," + " 'name' : 'Sales'," + " 'employees' : [" + " { " + " 'objectId' : 5," + " 'class' : 'Employee'," + " 'name' : 'Tim Canterbury'" + " }, " + " { " + " 'objectId' : 6," + " 'class' : 'Employee'," + " 'name' : 'Gareth Keenan'" + " }" + " ]" + " }," + " {" + " 'objectId' : 13," + " 'class' : 'Department'," + " 'name' : 'Warehouse', " + " 'employees' : [" + " {" + " 'objectId' : 9," + " 'class' : 'Employee'," + " 'name' : 'Lee'" + " }," + " {" + " 'objectId' : 10," + " 'class' : 'Employee'," + " 'name' : 'Alex'" + " }" + " ]" + " }" + " ]" + "}"; JSONObject expected = new JSONObject(jsonString); assertEquals(null, getProblemsComparing(expected, got.get(0))); } public void testSingleObjectWithNestedCollectionsAndMultipleAttributes() throws Exception { os.setResultsSize(1); ResultsRow row = new ResultsRow(); row.add(wernhamHogg); List sub1 = new ArrayList(); ResultsRow subRow1 = new ResultsRow(); subRow1.add(sales); List sub2 = new ArrayList(); ResultsRow subRow2 = new ResultsRow(); subRow2.add(tim); sub2.add(subRow2); subRow2 = new ResultsRow(); subRow2.add(gareth); sub2.add(subRow2); subRow1.add(sub2); sub1.add(subRow1); subRow1 = new ResultsRow(); subRow1.add(distribution); sub2 = new ArrayList(); subRow2 = new ResultsRow(); subRow2.add(lee); sub2.add(subRow2); subRow2 = new ResultsRow(); subRow2.add(alex); sub2.add(subRow2); subRow1.add(sub2); sub1.add(subRow1); row.add(sub1); os.addRow(row); PathQuery pq = new PathQuery(model); pq.addViews("Company.name", "Company.vatNumber", "Company.departments.name", "Company.departments.employees.name", "Company.departments.employees.age"); pq.setOuterJoinStatus("Company.departments", OuterJoinStatus.OUTER); pq.setOuterJoinStatus("Company.departments.employees", OuterJoinStatus.OUTER); Map pathToQueryNode = new HashMap(); Query q = MainHelper.makeQuery(pq, new HashMap(), pathToQueryNode, null, null); List resultList = os.execute(q, 0, 1, true, true, new HashMap()); Results results = new DummyResults(q, resultList); ExportResultsIterator iter = new ExportResultsIterator(pq, results, pathToQueryNode); JSONResultsIterator jsonIter = new JSONResultsIterator(iter); List<JSONObject> got = new ArrayList<JSONObject>(); for (JSONObject gotRow : new IteratorIterable<JSONObject>(jsonIter)) { got.add(gotRow); } assertEquals(got.size(), 1); String jsonString = "{" + " 'objectId' : 1," + " 'class' : 'Company'," + " 'name' : 'Wernham-Hogg'," + " 'vatNumber' : 101," + " 'departments' : [" + " {" + " 'objectId' : 11," + " 'class' : 'Department'," + " 'name' : 'Sales'," + " 'employees' : [" + " { " + " 'objectId' : 5," + " 'class' : 'Employee'," + " 'name' : 'Tim Canterbury'," + " 'age' : 30" + " }, " + " { " + " 'objectId' : 6," + " 'class' : 'Employee'," + " 'name' : 'Gareth Keenan'," + " 'age' : 32" + " }" + " ]" + " }," + " {" + " 'objectId' : 13," + " 'class' : 'Department'," + " 'name' : 'Warehouse', " + " 'employees' : [" + " {" + " 'objectId' : 9," + " 'class' : 'Employee'," + " 'name' : 'Lee'," + " 'age' : 28" + " }," + " {" + " 'objectId' : 10," + " 'class' : 'Employee'," + " 'name' : 'Alex'," + " 'age' : 24" + " }" + " ]" + " }" + " ]" + "}"; JSONObject expected = new JSONObject(jsonString); assertEquals(null, getProblemsComparing(expected, got.get(0))); } // Attributes on references should precede references on references // The dummy attribute "id" can be used without populating the object with // unwanted stuff. public void testSingleObjectWithTrailOfReferences() throws Exception { os.setResultsSize(1); PathQuery pq = new PathQuery(model); pq.addViews("Department.name", "Department.company.id", "Department.company.CEO.name", "Department.company.CEO.address.address"); String jsonString = "{" + " 'class' : 'Department'," + " 'objectId' : 11," + " 'name' : 'Sales'," + " 'company' : {" + " 'class' : 'Company'," + " 'objectId' : 1," + " 'CEO' : {" + " 'class' : 'CEO'," + " 'objectId' : 2," + " 'name' : 'Jennifer Taylor-Clarke'," + " 'address' : {" + " 'class' : 'Address'," + " 'objectId' : 15," + " 'address' : '42 Some St, Slough'" + " }" + " }" + " }" + " }"; JSONObject expected = new JSONObject(jsonString); ResultsRow row = new ResultsRow(); row.add(sales); row.add(wernhamHogg); row.add(jennifer); row.add(address); os.addRow(row); Map pathToQueryNode = new HashMap(); Query q = MainHelper.makeQuery(pq, new HashMap(), pathToQueryNode, null, null); List resultList = os.execute(q, 0, 1, true, true, new HashMap()); Results results = new DummyResults(q, resultList); ExportResultsIterator iter = new ExportResultsIterator(pq, results, pathToQueryNode); JSONResultsIterator jsonIter = new JSONResultsIterator(iter); List<JSONObject> got = new ArrayList<JSONObject>(); for (JSONObject gotRow : new IteratorIterable<JSONObject>(jsonIter)) { got.add(gotRow); } assertEquals(got.size(), 1); assertEquals(null, getProblemsComparing(expected, got.get(0))); } // Attributes on references should precede references on references // Not doing so causes an error public void testBadReferenceTrail() throws Exception { os.setResultsSize(1); ResultsRow row = new ResultsRow(); row.add(sales); row.add(jennifer); row.add(address); os.addRow(row); PathQuery pq = new PathQuery(model); pq.addViews("Department.name", "Department.company.CEO.name", "Department.company.CEO.address.address"); Map pathToQueryNode = new HashMap(); Query q = MainHelper.makeQuery(pq, new HashMap(), pathToQueryNode, null, null); List resultList = os.execute(q, 0, 1, true, true, new HashMap()); Results results = new DummyResults(q, resultList); ExportResultsIterator iter = new ExportResultsIterator(pq, results, pathToQueryNode); JSONResultsIterator jsonIter = new JSONResultsIterator(iter); try { List<JSONObject> got = new ArrayList<JSONObject>(); for (JSONObject gotRow : new IteratorIterable<JSONObject>(jsonIter)) { got.add(gotRow); } fail("No exception was thrown dealing with bad query - got this list: " + got); } catch (AssertionFailedError e) { // rethrow the fail from within the try throw e; } catch (JSONFormattingException e) { // Test that this is what we thought would happen. assertEquals("This node is not fully initialised: it has no objectId", e.getMessage()); } catch (Throwable e){ // All other exceptions are failures fail("Got unexpected error: " + e); } } // Attributes on references should precede references on references public void testSingleObjectWithACollection() throws Exception { os.setResultsSize(2); ResultsRow row = new ResultsRow(); row.add(david); row.add(sales); row.add(tim); os.addRow(row); ResultsRow row2 = new ResultsRow(); row2.add(david); row2.add(sales); row2.add(gareth); os.addRow(row2); String jsonString = "{" + " 'objectId' : 3," + " 'class' : 'Manager'," + " 'name' : 'David Brent'," + " 'age' : 39," + " 'department' : {" + " 'objectId' : 11," + " 'class' : 'Department'," + " 'name' : 'Sales'," + " 'employees' : [" + " { " + " 'objectId' : 5," + " 'class' : 'Employee'," + " 'name' : 'Tim Canterbury'," + " 'age' : 30" + " }, " + " { " + " 'objectId' : 6," + " 'class' : 'Employee'," + " 'name' : 'Gareth Keenan'," + " 'age' : 32" + " }" + " ]" + " }" + "}"; PathQuery pq = new PathQuery(model); pq.addViews("Manager.name", "Manager.age", "Manager.department.name", "Manager.department.employees.name", "Manager.department.employees.age"); Map pathToQueryNode = new HashMap(); Query q = MainHelper.makeQuery(pq, new HashMap(), pathToQueryNode, null, null); List resultList = os.execute(q, 0, 2, true, true, new HashMap()); Results results = new DummyResults(q, resultList); ExportResultsIterator iter = new ExportResultsIterator(pq, results, pathToQueryNode); JSONResultsIterator jsonIter = new JSONResultsIterator(iter); List<JSONObject> got = new ArrayList<JSONObject>(); for (JSONObject gotRow : new IteratorIterable<JSONObject>(jsonIter)) { got.add(gotRow); } assertEquals(got.size(), 1); JSONObject expected = new JSONObject(jsonString); assertEquals(null, getProblemsComparing(expected, got.get(0))); } // Attributes on references should precede references on references // Not doing so causes an error public void testBadCollectionTrail() throws Exception { os.setResultsSize(2); ResultsRow row = new ResultsRow(); row.add(david); row.add(tim); os.addRow(row); ResultsRow row2 = new ResultsRow(); row2.add(david); row2.add(gareth); os.addRow(row2); PathQuery pq = new PathQuery(model); pq.addViews("Manager.name", "Manager.department.employees.name"); Map pathToQueryNode = new HashMap(); Query q = MainHelper.makeQuery(pq, new HashMap(), pathToQueryNode, null, null); List resultList = os.execute(q, 0, 2, true, true, new HashMap()); Results results = new DummyResults(q, resultList); ExportResultsIterator iter = new ExportResultsIterator(pq, results, pathToQueryNode); JSONResultsIterator jsonIter = new JSONResultsIterator(iter); try { List<JSONObject> got = new ArrayList<JSONObject>(); for (JSONObject gotRow : new IteratorIterable<JSONObject>(jsonIter)) { got.add(gotRow); } fail("No exception was thrown dealing with bad query - got this list: " + got); } catch (AssertionFailedError e) { // rethrow the fail from within the try throw e; } catch (JSONFormattingException e) { // Test that this is what we thought would happen. assertEquals("This node is not properly initialised (it doesn't have an objectId) - is the view in the right order?", e.getMessage()); } catch (Throwable e){ // All other exceptions are failures fail("Got unexpected error: " + e); } } public void testHeadlessQuery() throws Exception { os.setResultsSize(2); ResultsRow row = new ResultsRow(); row.add(tim); os.addRow(row); ResultsRow row2 = new ResultsRow(); row2.add(gareth); os.addRow(row2); PathQuery pq = new PathQuery(model); pq.addViews("Manager.department.employees.name", "Manager.department.employees.age"); Map pathToQueryNode = new HashMap(); Query q = MainHelper.makeQuery(pq, new HashMap(), pathToQueryNode, null, null); List resultList = os.execute(q, 0, 2, true, true, new HashMap()); Results results = new DummyResults(q, resultList); ExportResultsIterator iter = new ExportResultsIterator(pq, results, pathToQueryNode); JSONResultsIterator jsonIter = new JSONResultsIterator(iter); try { List<JSONObject> got = new ArrayList<JSONObject>(); for (JSONObject gotRow : new IteratorIterable<JSONObject>(jsonIter)) { got.add(gotRow); } fail("No exception was thrown dealing with bad query - got this list: " + got); } catch (AssertionFailedError e) { // rethrow the fail from within the try throw e; } catch (JSONFormattingException e) { // Test that this is what we thought would happen. assertEquals("Head of the object is missing", e.getMessage()); } catch (Throwable e){ // All other exceptions are failures fail("Got unexpected error: " + e); } } public void testParallelCollection() throws Exception { os.setResultsSize(1); String jsonString = "{" + " 'class' : 'Company'," + " 'objectId' : 1," + " 'name' : 'Wernham-Hogg'," + " 'vatNumber' : 101," + " departments : [" + " {" + " 'class' : 'Department'," + " 'objectId' : 11," + " 'name' : 'Sales'" + " }," + " {" + " 'class' : 'Department'," + " 'objectId' : 12," + " 'name' : 'Accounts'" + " }" + " ]," + " contractors : [" + " {" + " 'class' : 'Contractor'," + " 'objectId' : 16," + " 'name' : 'Rowan'" + " }," + " {" + " 'class' : 'Contractor'," + " 'objectId' : 17," + " 'name' : 'Ray'" + " }," + " {" + " 'class' : 'Contractor'," + " 'objectId' : 18," + " 'name' : 'Jude'" + " }" + " ]" + "}"; ResultsRow row = new ResultsRow(); row.add(wernhamHogg); List sub1 = new ArrayList(); ResultsRow subRow1 = new ResultsRow(); subRow1.add(sales); sub1.add(subRow1); subRow1 = new ResultsRow(); subRow1.add(accounts); sub1.add(subRow1); row.add(sub1); sub1 = new ArrayList(); subRow1 = new ResultsRow(); subRow1.add(rowan); sub1.add(subRow1); subRow1 = new ResultsRow(); subRow1.add(ray); sub1.add(subRow1); subRow1 = new ResultsRow(); subRow1.add(jude); sub1.add(subRow1); row.add(sub1); os.addRow(row); PathQuery pq = new PathQuery(model); pq.addViews("Company.name", "Company.vatNumber", "Company.departments.name", "Company.contractors.name"); pq.setOuterJoinStatus("Company.departments", OuterJoinStatus.OUTER); pq.setOuterJoinStatus("Company.contractors", OuterJoinStatus.OUTER); Map pathToQueryNode = new HashMap(); Query q = MainHelper.makeQuery(pq, new HashMap(), pathToQueryNode, null, null); List resultList = os.execute(q, 0, 1, true, true, new HashMap()); Results results = new DummyResults(q, resultList); ExportResultsIterator iter = new ExportResultsIterator(pq, results, pathToQueryNode); JSONResultsIterator jsonIter = new JSONResultsIterator(iter); List<JSONObject> got = new ArrayList<JSONObject>(); for (JSONObject gotRow : new IteratorIterable<JSONObject>(jsonIter)) { got.add(gotRow); } JSONObject expected = new JSONObject(jsonString); assertEquals(got.size(), 1); assertEquals(null, getProblemsComparing(expected, got.get(0))); } public void testHeadInWrongPlace() throws Exception { os.setResultsSize(2); ResultsRow row1 = new ResultsRow(); row1.add(tim); row1.add(sales); os.addRow(row1); ResultsRow row2 = new ResultsRow(); row2.add(gareth); row2.add(sales); os.addRow(row2); PathQuery pq = new PathQuery(model); pq.addViews("Department.employees.name", "Department.name"); Map pathToQueryNode = new HashMap(); Query q = MainHelper.makeQuery(pq, new HashMap(), pathToQueryNode, null, null); List resultList = os.execute(q, 0, 2, true, true, new HashMap()); Results results = new DummyResults(q, resultList); ExportResultsIterator iter = new ExportResultsIterator(pq, results, pathToQueryNode); JSONResultsIterator jsonIter = new JSONResultsIterator(iter); try { List<JSONObject> got = new ArrayList<JSONObject>(); for (JSONObject gotRow : new IteratorIterable<JSONObject>(jsonIter)) { got.add(gotRow); } fail("No exception was thrown dealing with bad query - got this list: " + got); } catch (AssertionFailedError e) { // rethrow the fail from within the try throw e; } catch (JSONFormattingException e) { // Test that this is what we thought would happen. assertEquals("Head of the object is missing", e.getMessage()); } catch (Throwable e){ // All other exceptions are failures fail("Got unexpected error: " + e); } } public void testRefBeforeItsParentCollectionOrder() throws Exception { os.setResultsSize(2); ResultsRow row1 = new ResultsRow(); row1.add(wernhamHogg); row1.add(tim); row1.add(sales); os.addRow(row1); ResultsRow row2 = new ResultsRow(); row2.add(wernhamHogg); row2.add(gareth); row2.add(sales); os.addRow(row2); PathQuery pq = new PathQuery(model); pq.addViews("Company.name", "Company.departments.employees.name", "Company.departments.name"); Map pathToQueryNode = new HashMap(); Query q = MainHelper.makeQuery(pq, new HashMap(), pathToQueryNode, null, null); List resultList = os.execute(q, 0, 2, true, true, new HashMap()); Results results = new DummyResults(q, resultList); ExportResultsIterator iter = new ExportResultsIterator(pq, results, pathToQueryNode); JSONResultsIterator jsonIter = new JSONResultsIterator(iter); try { List<JSONObject> got = new ArrayList<JSONObject>(); for (JSONObject gotRow : new IteratorIterable<JSONObject>(jsonIter)) { got.add(gotRow); } fail("No exception was thrown dealing with bad query - got this list: " + got); } catch (AssertionFailedError e) { // rethrow the fail from within the try throw e; } catch (JSONFormattingException e) { // Test that this is what we thought would happen. assertEquals("This array is empty - is the view in the wrong order?", e.getMessage()); } catch (Throwable e){ // All other exceptions are failures fail("Got unexpected error: " + e); } } public void testColBeforeItsParentRefOrder() throws Exception { os.setResultsSize(2); ResultsRow row1 = new ResultsRow(); row1.add(david); row1.add(tim); row1.add(sales); os.addRow(row1); ResultsRow row2 = new ResultsRow(); row2.add(david); row2.add(gareth); row2.add(sales); os.addRow(row2); PathQuery pq = new PathQuery(model); pq.addViews("Manager.name", "Manager.department.employees.name", "Manager.department.name"); Map pathToQueryNode = new HashMap(); Query q = MainHelper.makeQuery(pq, new HashMap(), pathToQueryNode, null, null); List resultList = os.execute(q, 0, 2, true, true, new HashMap()); Results results = new DummyResults(q, resultList); ExportResultsIterator iter = new ExportResultsIterator(pq, results, pathToQueryNode); JSONResultsIterator jsonIter = new JSONResultsIterator(iter); try { List<JSONObject> got = new ArrayList<JSONObject>(); for (JSONObject gotRow : new IteratorIterable<JSONObject>(jsonIter)) { got.add(gotRow); } fail("No exception was thrown dealing with bad query - got this list: " + got); } catch (AssertionFailedError e) { // rethrow the fail from within the try throw e; } catch (JSONFormattingException e) { // Test that this is what we thought would happen. assertEquals("This node is not properly initialised (it doesn't have an objectId) - is the view in the right order?", e.getMessage()); } catch (Throwable e){ // All other exceptions are failures fail("Got unexpected error: " + e); } } public void testMultipleObjectsWithColls() throws Exception { os.setResultsSize(6); List<String> jsonStrings = new ArrayList<String>(); jsonStrings.add( " {" + " 'objectId' : 11," + " 'class' : 'Department'," + " 'name' : 'Sales'," + " 'employees' : [" + " { " + " 'objectId' : 5," + " 'class' : 'Employee'," + " 'name' : 'Tim Canterbury'," + " 'age' : 30" + " }, " + " { " + " 'objectId' : 6," + " 'class' : 'Employee'," + " 'name' : 'Gareth Keenan'," + " 'age' : 32" + " }" + " ]" + " }"); jsonStrings.add( " {" + " 'objectId' : 12," + " 'class' : 'Department'," + " 'name' : 'Accounts'," + " 'employees' : [" + " { " + " 'objectId' : 8," + " 'class' : 'Employee'," + " 'name' : 'Keith Bishop'," + " 'age' : 41" + " } " + " ]" + " }"); jsonStrings.add( " {" + " 'objectId' : 13," + " 'class' : 'Department'," + " 'name' : 'Warehouse', " + " 'employees' : [" + " {" + " 'objectId' : 9," + " 'class' : 'Employee'," + " 'name' : 'Lee'," + " 'age' : 28" + " }," + " {" + " 'objectId' : 10," + " 'class' : 'Employee'," + " 'name' : 'Alex'," + " 'age' : 24" + " }" + " ]" + " }"); jsonStrings.add( " {" + " 'objectId' : 14," + " 'class' : 'Department'," + " 'name' : 'Reception'," + " 'employees' : [" + " { " + " 'objectId' : 7," + " 'class' : 'Employee'," + " 'name' : 'Dawn Tinsley'," + " 'age' : 26" + " } " + " ]" + " }"); ResultsRow row1 = new ResultsRow(); row1.add(sales); row1.add(tim); ResultsRow row2 = new ResultsRow(); row2.add(sales); row2.add(gareth); ResultsRow row3 = new ResultsRow(); row3.add(accounts); row3.add(keith); ResultsRow row4 = new ResultsRow(); row4.add(distribution); row4.add(lee); ResultsRow row5 = new ResultsRow(); row5.add(distribution); row5.add(alex); ResultsRow row6 = new ResultsRow(); row6.add(reception); row6.add(dawn); os.addRow(row1); os.addRow(row2); os.addRow(row3); os.addRow(row4); os.addRow(row5); os.addRow(row6); PathQuery pq = new PathQuery(model); pq.addViews("Department.name", "Department.employees.name", "Department.employees.age"); Map pathToQueryNode = new HashMap(); Query q = MainHelper.makeQuery(pq, new HashMap(), pathToQueryNode, null, null); List resultList = os.execute(q, 0, 6, true, true, new HashMap()); Results results = new DummyResults(q, resultList); ExportResultsIterator iter = new ExportResultsIterator(pq, results, pathToQueryNode); JSONResultsIterator jsonIter = new JSONResultsIterator(iter); List<JSONObject> got = new ArrayList<JSONObject>(); for (JSONObject gotRow : new IteratorIterable<JSONObject>(jsonIter)) { got.add(gotRow); } assertEquals(4, got.size()); for (int i = 0; i < jsonStrings.size(); i++) { JSONObject jo = new JSONObject(jsonStrings.get(i)); assertEquals(null, getProblemsComparing(jo, got.get(i))); } } public void testMultipleObjectsWithRefs() throws Exception { os.setResultsSize(6); List<String> jsonStrings = new ArrayList<String>(); jsonStrings.add( " {" + " objectId : 11," + " class : 'Department'," + " name : 'Sales'," + " manager : { class: 'Manager', objectId: 3, age: 39, name: 'David Brent' }," + " company : { class: 'Company', objectId: 1, vatNumber: 101, name: 'Wernham-Hogg' }" + " }"); jsonStrings.add( " {" + " objectId : 12," + " class : 'Department'," + " name : 'Accounts'," + " manager : { class: 'Manager', objectId: 3, age: 39, name: 'David Brent' }," + " company : { class: 'Company', objectId: 1, vatNumber: 101, name: 'Wernham-Hogg' }" + " }"); jsonStrings.add( " {" + " objectId : 13," + " class : 'Department'," + " name : 'Warehouse', " + " manager : { class: 'Manager', objectId: 4, age: 38, name: 'Glynn' }," + " company : { class: 'Company', objectId: 1, vatNumber: 101, name: 'Wernham-Hogg' }" + " }"); jsonStrings.add( " {" + " objectId : 19," + " class : 'Department'," + " name : 'Swindon', " + " manager : { class: 'Manager', objectId: 20, age: 35, name: 'Neil Godwin' }," + " company : { class: 'Company', objectId: 1, vatNumber: 101, name: 'Wernham-Hogg' }" + " }"); ResultsRow row1 = new ResultsRow(); row1.add(sales); row1.add(david); row1.add(wernhamHogg); ResultsRow row2 = new ResultsRow(); row2.add(accounts); row2.add(david); row2.add(wernhamHogg); ResultsRow row3 = new ResultsRow(); row3.add(distribution); row3.add(taffy); row3.add(wernhamHogg); ResultsRow row4 = new ResultsRow(); row4.add(swindon); row4.add(neil); row4.add(wernhamHogg); os.addRow(row1); os.addRow(row2); os.addRow(row3); os.addRow(row4); PathQuery pq = new PathQuery(model); pq.addViews("Department.name", "Department.manager.name", "Department.manager.age", "Department.company.name", "Department.company.vatNumber"); Map pathToQueryNode = new HashMap(); Query q = MainHelper.makeQuery(pq, new HashMap(), pathToQueryNode, null, null); List resultList = os.execute(q, 0, 4, true, true, new HashMap()); Results results = new DummyResults(q, resultList); ExportResultsIterator iter = new ExportResultsIterator(pq, results, pathToQueryNode); JSONResultsIterator jsonIter = new JSONResultsIterator(iter); List<JSONObject> got = new ArrayList<JSONObject>(); for (JSONObject gotRow : new IteratorIterable<JSONObject>(jsonIter)) { got.add(gotRow); } assertEquals(4, got.size()); for (int i = 0; i < jsonStrings.size(); i++) { JSONObject jo = new JSONObject(jsonStrings.get(i)); assertEquals(null, getProblemsComparing(jo, got.get(i))); } } public void testMultipleObjectsWithRefsAndCols() throws Exception { os.setResultsSize(7); List<String> jsonStrings = new ArrayList<String>(); jsonStrings.add( " {" + " objectId : 11," + " class : 'Department'," + " name : 'Sales'," + " manager : { class: 'Manager', objectId: 3, age: 39, name: 'David Brent' }," + " company : { class: 'Company', objectId: 1, vatNumber: 101, name: 'Wernham-Hogg' }," + " 'employees' : [" + " { " + " objectId : 5," + " class : 'Employee'," + " name : 'Tim Canterbury'," + " age : 30" + " }, " + " { " + " objectId : 6," + " class : 'Employee'," + " name : 'Gareth Keenan'," + " age : 32" + " }" + " ]" + " }"); jsonStrings.add( " {" + " objectId : 12," + " class : 'Department'," + " name : 'Accounts'," + " manager : { class: 'Manager', objectId: 3, age: 39, name: 'David Brent' }," + " company : { class: 'Company', objectId: 1, vatNumber: 101, name: 'Wernham-Hogg' }," + " employees : [" + " { " + " objectId : 8," + " class : 'Employee'," + " name : 'Keith Bishop'," + " age : 41" + " } " + " ]" + " }"); jsonStrings.add( " {" + " objectId : 13," + " class : 'Department'," + " name : 'Warehouse', " + " manager : { class: 'Manager', objectId: 4, age: 38, name: 'Glynn' }," + " company : { class: 'Company', objectId: 1, vatNumber: 101, name: 'Wernham-Hogg' }," + " employees : [" + " {" + " objectId : 9," + " class : 'Employee'," + " name : 'Lee'," + " age : 28" + " }," + " {" + " objectId : 10," + " class : 'Employee'," + " name : 'Alex'," + " age : 24" + " }" + " ]" + " }"); jsonStrings.add( " {" + " objectId : 19," + " class : 'Department'," + " name : 'Swindon', " + " manager : { class: 'Manager', objectId: 20, age: 35, name: 'Neil Godwin' }," + " company : { class: 'Company', objectId: 1, vatNumber: 101, name: 'Wernham-Hogg' }," + " employees : [" + " {" + " objectId : 21," + " class : 'Employee'," + " name : 'Rachel'," + " age : 34" + " }," + " {" + " objectId : 22," + " class : 'Employee'," + " name : 'Trudy'," + " age : 25" + " }" + " ]" + " }"); ResultsRow row1a = new ResultsRow(); row1a.add(sales); row1a.add(david); row1a.add(wernhamHogg); row1a.add(tim); ResultsRow row1b = new ResultsRow(); row1b.add(sales); row1b.add(david); row1b.add(wernhamHogg); row1b.add(gareth); ResultsRow row2 = new ResultsRow(); row2.add(accounts); row2.add(david); row2.add(wernhamHogg); row2.add(keith); ResultsRow row3a = new ResultsRow(); row3a.add(distribution); row3a.add(taffy); row3a.add(wernhamHogg); row3a.add(lee); ResultsRow row3b = new ResultsRow(); row3b.add(distribution); row3b.add(taffy); row3b.add(wernhamHogg); row3b.add(alex); ResultsRow row4a = new ResultsRow(); row4a.add(swindon); row4a.add(neil); row4a.add(wernhamHogg); row4a.add(rachel); ResultsRow row4b = new ResultsRow(); row4b.add(swindon); row4b.add(neil); row4b.add(wernhamHogg); row4b.add(trudy); os.addRow(row1a); os.addRow(row1b); os.addRow(row2); os.addRow(row3a); os.addRow(row3b); os.addRow(row4a); os.addRow(row4b); PathQuery pq = new PathQuery(model); pq.addViews("Department.name", "Department.manager.name", "Department.manager.age", "Department.company.name", "Department.company.vatNumber", "Department.employees.name", "Department.employees.age"); Map pathToQueryNode = new HashMap(); Query q = MainHelper.makeQuery(pq, new HashMap(), pathToQueryNode, null, null); List resultList = os.execute(q, 0, 7, true, true, new HashMap()); Results results = new DummyResults(q, resultList); ExportResultsIterator iter = new ExportResultsIterator(pq, results, pathToQueryNode); JSONResultsIterator jsonIter = new JSONResultsIterator(iter); List<JSONObject> got = new ArrayList<JSONObject>(); for (JSONObject gotRow : new IteratorIterable<JSONObject>(jsonIter)) { got.add(gotRow); } assertEquals(4, got.size()); for (int i = 0; i < jsonStrings.size(); i++) { JSONObject jo = new JSONObject(jsonStrings.get(i)); assertEquals(null, getProblemsComparing(jo, got.get(i))); } } public void testUnsupportedOperations() throws Exception { os.setResultsSize(1); ResultsRow row = new ResultsRow(); row.add(wernhamHogg); os.addRow(row); PathQuery pq = new PathQuery(model); pq.addViews("Company.name"); Map pathToQueryNode = new HashMap(); Query q = MainHelper.makeQuery(pq, new HashMap(), pathToQueryNode, null, null); List resultList = os.execute(q, 0, 1, true, true, new HashMap()); Results results = new DummyResults(q, resultList); ExportResultsIterator iter = new ExportResultsIterator(pq, results, pathToQueryNode); JSONResultsIterator jsonIter = new JSONResultsIterator(iter); try { jsonIter.remove(); fail("No exception was thrown when calling the unsupported method remove"); } catch (AssertionFailedError e) { // rethrow the fail from within the try throw e; } catch (UnsupportedOperationException e) { // Test that this is what we thought would happen. assertEquals("Remove is not implemented in this class", e.getMessage()); } catch (Throwable e){ // All other exceptions are failures fail("Got unexpected error: " + e); } } public void testCurrentArrayIsEmpty() throws Exception { os.setResultsSize(1); ResultsRow row = new ResultsRow(); row.add(wernhamHogg); row.add(david); os.addRow(row); PathQuery pq = new PathQuery(model); pq.addViews("Company.name", "Company.contractors.oldComs.departments.manager.name"); Map pathToQueryNode = new HashMap(); Query q = MainHelper.makeQuery(pq, new HashMap(), pathToQueryNode, null, null); List resultList = os.execute(q, 0, 1, true, true, new HashMap()); Results results = new DummyResults(q, resultList); ExportResultsIterator iter = new ExportResultsIterator(pq, results, pathToQueryNode); JSONResultsIterator jsonIter = new JSONResultsIterator(iter); try { List<JSONObject> got = new ArrayList<JSONObject>(); for (JSONObject gotRow : new IteratorIterable<JSONObject>(jsonIter)) { got.add(gotRow); } fail("No exception was thrown when calling the unsupported method remove"); } catch (AssertionFailedError e) { // rethrow the fail from within the try throw e; } catch (JSONFormattingException e) { // Test that this is what we thought would happen. assertEquals("This array is empty - is the view in the wrong order?", e.getMessage()); } catch (Throwable e){ // All other exceptions are failures fail("Got unexpected error: " + e); } } public void testCurrentMapIsNull() throws Exception { os.setResultsSize(1); ResultsRow row = new ResultsRow(); row.add(sales); row.add(address); os.addRow(row); PathQuery pq = new PathQuery(model); pq.addViews("Department.name", "Department.company.contractors.personalAddress.address"); Map pathToQueryNode = new HashMap(); Query q = MainHelper.makeQuery(pq, new HashMap(), pathToQueryNode, null, null); List resultList = os.execute(q, 0, 1, true, true, new HashMap()); Results results = new DummyResults(q, resultList); ExportResultsIterator iter = new ExportResultsIterator(pq, results, pathToQueryNode); JSONResultsIterator jsonIter = new JSONResultsIterator(iter); try { List<JSONObject> got = new ArrayList<JSONObject>(); for (JSONObject gotRow : new IteratorIterable<JSONObject>(jsonIter)) { got.add(gotRow); } fail("No exception was thrown when calling the unsupported method remove"); } catch (AssertionFailedError e) { // rethrow the fail from within the try throw e; } catch (JSONFormattingException e) { // Test that this is what we thought would happen. assertEquals("This node is not properly initialised (it doesn't have an objectId) - is the view in the right order?", e.getMessage()); } catch (Throwable e){ // All other exceptions are failures fail("Got unexpected error: " + e); } } public void testDateConversion() throws Exception { os.setResultsSize(1); Types typeContainer = new Types(); typeContainer.setId(new Integer(100)); Calendar cal = Calendar.getInstance(); cal.set(108 + 1900, 6, 6); typeContainer.setDateObjType(cal.getTime()); ResultsRow row = new ResultsRow(); row.add(typeContainer); os.addRow(row); PathQuery pq = new PathQuery(model); pq.addViews("Types.dateObjType"); String jsonString = "{ class: 'Types', objectId: 100, dateObjType: '2008-07-06' }"; Map pathToQueryNode = new HashMap(); Query q = MainHelper.makeQuery(pq, new HashMap(), pathToQueryNode, null, null); List resultList = os.execute(q, 0, 1, true, true, new HashMap()); Results results = new DummyResults(q, resultList); ExportResultsIterator iter = new ExportResultsIterator(pq, results, pathToQueryNode); JSONResultsIterator jsonIter = new JSONResultsIterator(iter); List<JSONObject> got = new ArrayList<JSONObject>(); for (JSONObject gotRow : new IteratorIterable<JSONObject>(jsonIter)) { got.add(gotRow); } assertEquals(1, got.size()); JSONObject expected = new JSONObject(jsonString); assertEquals(null, getProblemsComparing(expected, got.get(0))); } public void testThosePlacesOtherTestsCannotReach() throws Exception { // In normal circumstances these exceptions will never be thrown. // These tests are just to check that they will be // should abnormal circumstances ever occur. Path p = null; Path depP = null; Path empsP = null; Path badP = null; try { p = new Path(model, "Manager.name"); depP = new Path(model, "Manager.department"); empsP = new Path(model, "Manager.department.employees"); badP = new BadPath(model, "Manager.name"); } catch (PathException e) { e.printStackTrace(); } ResultElement re = new ResultElement(david, p, false); Map<String, Object> jsonMap = new TreeMap<String, Object>(); ResultsRow row = new ResultsRow(); row.add(david); os.addRow(row); PathQuery pq = new PathQuery(model); pq.addViews("Manager.name"); Map pathToQueryNode = new HashMap(); Query q = MainHelper.makeQuery(pq, new HashMap(), pathToQueryNode, null, null); List resultList = os.execute(q, 0, 1, true, true, new HashMap()); Results results = new DummyResults(q, resultList); ExportResultsIterator iter = new ExportResultsIterator(pq, results, pathToQueryNode); JSONResultsIterator jsonIter = new JSONResultsIterator(iter); jsonMap.put("objectId", 1000); try { jsonIter.setOrCheckClassAndId(re, jsonMap); fail("No exception was thrown, although I tried very hard indeed to cause one"); } catch (AssertionFailedError e) { // rethrow the fail from within the try throw e; } catch (JSONFormattingException e) { // Test that this is what we thought would happen. assertEquals( "This result element ( David Brent 3 Manager) " + "does not belong on this map ({class=Manager, objectId=1000}) - " + "objectIds don't match (1000 != 3)", e.getMessage()); } catch (Throwable e){ // All other exceptions are failures fail("Got unexpected error: " + e); } jsonMap.put("class", "Fool"); try { jsonIter.setOrCheckClassAndId(re, jsonMap); fail("No exception was thrown, although I tried very hard indeed to cause one"); } catch (AssertionFailedError e) { // rethrow the fail from within the try throw e; } catch (JSONFormattingException e) { // Test that this is what we thought would happen. assertEquals( "This result element ( David Brent 3 Manager) " + "does not belong on this map ({class=Fool, objectId=1000}) - " + "classes don't match (Fool != Manager)", e.getMessage()); } catch (Throwable e){ // All other exceptions are failures fail("Got unexpected error: " + e); } jsonMap.clear(); jsonMap.put("name", "Neil"); try { jsonIter.addFieldToMap(re, p, jsonMap); fail("No exception was thrown, although I tried very hard indeed to cause one"); } catch (AssertionFailedError e) { // rethrow the fail from within the try throw e; } catch (JSONFormattingException e) { // Test that this is what we thought would happen. assertEquals( "Trying to set key name as David Brent in {class=Manager, name=Neil, objectId=3} " + "but it already has the value Neil", e.getMessage()); } catch (Throwable e){ // All other exceptions are failures fail("Got unexpected error: " + e); } jsonIter.currentArray = null; try { jsonIter.setCurrentMapFromCurrentArray(re); fail("No exception was thrown, although I tried very hard indeed to cause one"); } catch (AssertionFailedError e) { // rethrow the fail from within the try throw e; } catch (JSONFormattingException e) { // Test that this is what we thought would happen. assertEquals( "Nowhere to put this field", e.getMessage()); } catch (Throwable e){ // All other exceptions are failures fail("Got unexpected error: " + e); } jsonIter.currentArray = null; try { jsonIter.setCurrentMapFromCurrentArray(); fail("No exception was thrown, although I tried very hard indeed to cause one"); } catch (AssertionFailedError e) { // rethrow the fail from within the try throw e; } catch (JSONFormattingException e) { // Test that this is what we thought would happen. assertEquals( "Nowhere to put this reference", e.getMessage()); } catch (Throwable e){ // All other exceptions are failures fail("Got unexpected error: " + e); } jsonMap.put("department", "Clowning About"); jsonIter.currentMap = jsonMap; try { jsonIter.addReferenceToCurrentNode(depP); fail("No exception was thrown, although I tried very hard indeed to cause one"); } catch (AssertionFailedError e) { // rethrow the fail from within the try throw e; } catch (JSONFormattingException e) { // Test that this is what we thought would happen. assertEquals( "Trying to set a reference on department, " + "but this node " + "{class=Manager, department=Clowning About, name=Neil, objectId=3} " + "already has this key set, " + "and to something other than a map " + "(java.lang.String: Clowning About)", e.getMessage()); } catch (Throwable e){ // All other exceptions are failures fail("Got unexpected error: " + e); } jsonIter.currentMap = null; try { jsonIter.addReferenceToCurrentNode(depP); fail("No exception was thrown, although I tried very hard indeed to cause one"); } catch (AssertionFailedError e) { // rethrow the fail from within the try throw e; } catch (JSONFormattingException e) { // Test that this is what we thought would happen. assertEquals( "The current map should have been set " + "by a preceding attribute - " + "is the view in the right order?", e.getMessage()); } catch (Throwable e){ // All other exceptions are failures fail("Got unexpected error: " + e); } jsonMap.put("employees", "Poor Fools"); jsonIter.currentMap = jsonMap; try { jsonIter.addCollectionToCurrentNode(empsP); fail("No exception was thrown, although I tried very hard indeed to cause one"); } catch (AssertionFailedError e) { // rethrow the fail from within the try throw e; } catch (JSONFormattingException e) { // Test that this is what we thought would happen. assertEquals( "Trying to set a collection on employees, " + "but this node " + "{class=Manager, department=Clowning About, employees=Poor Fools, name=Neil, objectId=3} " + "already has this key set to something other than a list " + "(java.lang.String: Poor Fools)", e.getMessage()); } catch (Throwable e){ // All other exceptions are failures fail("Got unexpected error: " + e); } try { jsonIter.addReferencedCellToJsonMap(re, badP, jsonMap); fail("No exception was thrown, although I tried very hard indeed to cause one"); } catch (AssertionFailedError e) { // rethrow the fail from within the try throw e; } catch (JSONFormattingException e) { // Test that this is what we thought would happen. assertEquals( "Bad path type: Manager.name", e.getMessage()); } catch (Throwable e){ // All other exceptions are failures fail("Got unexpected error: " + e); } } private class BadPath extends Path { public BadPath(Model m, String s) throws PathException { super(m, s); } @Override public List<Path> decomposePath() { return Arrays.asList((Path) this); } @Override public boolean endIsAttribute() { return false; } @Override public boolean endIsReference() { return false; } @Override public boolean endIsCollection() { return false; } @Override public boolean isRootPath() { return false; } } }
intermine/web/test/src/org/intermine/webservice/server/output/JSONResultsIteratorTest.java
package org.intermine.webservice.server.output; import java.util.ArrayList; import java.util.Arrays; 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 org.intermine.api.query.MainHelper; import org.intermine.api.results.ExportResultsIterator; import org.intermine.api.results.ResultElement; import org.intermine.metadata.Model; import org.intermine.model.testmodel.Company; import org.intermine.model.testmodel.Department; import org.intermine.model.testmodel.Employee; import org.intermine.objectstore.dummy.DummyResults; import org.intermine.objectstore.dummy.ObjectStoreDummyImpl; import org.intermine.objectstore.query.Query; import org.intermine.objectstore.query.Results; import org.intermine.objectstore.query.ResultsRow; import org.intermine.pathquery.OuterJoinStatus; import org.intermine.pathquery.PathQuery; import org.intermine.util.DynamicUtil; import org.intermine.util.IteratorIterable; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import junit.framework.TestCase; /** * Tests for the JSONResultsIterator class * * @author Alexis Kalderimis */ public class JSONResultsIteratorTest extends TestCase { /** * Compare two JSONObjects for equality * @param left The reference JSONObject (this is referred to as "expected" in any messages) * @param right The candidate object to check. * @return a String with messages explaining the problems if there are any, otherwise null (equal) * @throws JSONException */ private static String getProblemsComparing(JSONObject left, Object right) throws JSONException { List<String> problems = new ArrayList<String>(); if (left == null ) { if (right != null) { return "Expected null, but got " + right; } else { return null; } } if (! (right instanceof JSONObject)) { if (right == null) { return "Didn't expect null, but got null"; } else { return "Expected a JSONObject, is got a " + right.getClass(); } } JSONObject rjo = (JSONObject) right; Set<String> leftNames = new HashSet<String>(Arrays.asList(JSONObject.getNames(left))); Set<String> rightNames = new HashSet<String>(Arrays.asList(JSONObject.getNames(rjo))); if (! leftNames.equals(rightNames)) { problems.add("Expected the keys " + leftNames + ", but got these: " + rightNames); } for (String name : leftNames) { Object leftValue = left.get(name); String problem = null; try { if (leftValue == null) { if ( rjo.get(name) != null ) { problem = "Expected null, but got " + rjo.get(name); } } else if (leftValue instanceof JSONObject) { problem = getProblemsComparing((JSONObject) leftValue, rjo.get(name)); } else if (leftValue instanceof JSONArray) { problem = getProblemsComparing((JSONArray) leftValue, rjo.get(name)); } else { if (! leftValue.toString().equals(rjo.get(name).toString())) { problem = "Expected " + leftValue + " but got " + rjo.get(name); } } } catch (Throwable e) { problem = e.toString(); } if (problem != null) { problems.add("Problem with " + name + ": " + problem); } } if (problems.isEmpty()) { return null; } return problems.toString(); } /** * Compare two JSONArrays for equality * @param left The reference array (referred to as "expected" in any messages) * @param right The candidate object to check. * @return a String with messages explaining the problems if there are any, otherwise null (equal) * @throws JSONException */ private static String getProblemsComparing(JSONArray left, Object right) throws JSONException { List<String> problems = new ArrayList<String>(); if (left == null ) { if (right != null) { return "Expected null, but got " + right; } else { return null; } } if (! (right instanceof JSONArray)) { return "Expected a JSONArray, but got a " + right.getClass(); } JSONArray rja = (JSONArray) right; if (left.length() != rja.length()) { problems.add("Expected the size of this array to be " + left.length() + " but got " + rja.length()); } for (int index = 0; index < left.length(); index++) { Object leftMember = left.get(index); String problem = null; try { if (leftMember== null) { if ( rja.get(index) != null ) { problem = "Expected null, but got " + rja.get(index); } } else if (leftMember instanceof JSONObject) { problem = getProblemsComparing((JSONObject) leftMember, rja.get(index)); } else if (leftMember instanceof JSONArray) { problem = getProblemsComparing((JSONArray) leftMember, rja.get(index)); } else { if (! leftMember.toString().equals(rja.get(index).toString())) { problem = "Expected " + leftMember + " but got " + rja.get(index); } } } catch (Throwable e) { problem = e.toString(); } if (problem != null) { problems.add("Problem with index " + index + ": " + problem); } } if (problems.isEmpty()) { return null; } return problems.toString(); } private final Model model = Model.getInstanceByName("testmodel"); public JSONResultsIteratorTest(String arg) { super(arg); } public void testNestedCollection() throws Exception { ObjectStoreDummyImpl os = new ObjectStoreDummyImpl(); os.setResultsSize(1); // Set up some known objects in the first 3 results rows Company company1 = (Company) DynamicUtil.createObject(Collections.singleton(Company.class)); company1.setName("Company1"); company1.setVatNumber(101); company1.setId(new Integer(1)); Department department1 = new Department(); department1.setName("Department1"); department1.setId(new Integer(2)); Department department2 = new Department(); department2.setName("Department2"); department2.setId(new Integer(3)); Employee employee1 = new Employee(); employee1.setName("Employee1"); employee1.setId(new Integer(4)); employee1.setAge(42); Employee employee2 = new Employee(); employee2.setName("Employee2"); employee2.setId(new Integer(5)); employee2.setAge(43); Employee employee3 = new Employee(); employee3.setName("Employee3"); employee3.setId(new Integer(6)); employee3.setAge(44); Employee employee4 = new Employee(); employee4.setName("Employee4"); employee4.setId(new Integer(7)); employee4.setAge(45); ResultsRow row = new ResultsRow(); row.add(company1); List sub1 = new ArrayList(); ResultsRow subRow1 = new ResultsRow(); subRow1.add(department1); List sub2 = new ArrayList(); ResultsRow subRow2 = new ResultsRow(); subRow2.add(employee1); sub2.add(subRow2); subRow2 = new ResultsRow(); subRow2.add(employee2); sub2.add(subRow2); subRow1.add(sub2); sub1.add(subRow1); subRow1 = new ResultsRow(); subRow1.add(department2); sub2 = new ArrayList(); subRow2 = new ResultsRow(); subRow2.add(employee3); sub2.add(subRow2); subRow2 = new ResultsRow(); subRow2.add(employee4); sub2.add(subRow2); subRow1.add(sub2); sub1.add(subRow1); row.add(sub1); os.addRow(row); PathQuery pq = new PathQuery(model); pq.addViews("Company.name", "Company.vatNumber", "Company.departments.name", "Company.departments.employees.name"); pq.setOuterJoinStatus("Company.departments", OuterJoinStatus.OUTER); pq.setOuterJoinStatus("Company.departments.employees", OuterJoinStatus.OUTER); Map pathToQueryNode = new HashMap(); Query q = MainHelper.makeQuery(pq, new HashMap(), pathToQueryNode, null, null); List resultList = os.execute(q, 0, 1, true, true, new HashMap()); Results results = new DummyResults(q, resultList); ExportResultsIterator iter = new ExportResultsIterator(pq, results, pathToQueryNode); JsonResultsIterator jsonIter = new JsonResultsIterator(iter); List<JSONObject> got = new ArrayList<JSONObject>(); for (JSONObject gotRow : new IteratorIterable<JSONObject>(jsonIter)) { got.add(gotRow); } assertEquals(got.size(), 1); String jsonString = "{" + "\"objectId\" : 1," + "\"name\" : \"Company1\"," + "\"class\" : \"Company\"," + "\"departments\" : [" + "{" + "\"objectId\" : 2," + "\"name\":\"Department1\"," + "\"class\":\"Department\"," + "\"employees\" : [" + "{" + "\"objectId\" : 4," + "\"name\" : \"Employee1\"," + "\"class\" : \"Employee\"" + "}," + "{" + " \"objectId\" : 5," + " \"name\" : \"Employee2\"," + " \"class\":\"Employee\"" + "}" + "]" + "}," + "{" + " \"objectId\" : 3," + " \"name\" : \"Department2\", " + " \"class\" : \"Department\"," + " \"employees\" : [" + " {" + " \"objectId\" : 6," + " \"name\" : \"Employee3\"," + " \"class\" : \"Employee\"" + " }," + " {" + " \"objectId\" : 7," + " \"name\" : \"Employee4\"," + " \"class\" : \"Employee\"" + " }" + " ]" + "}" + "]," + "\"vatNumber\" : \"101\"" + "}"; JSONObject expected = new JSONObject(jsonString); assertEquals(null, getProblemsComparing(expected, got.get(0))); } }
All tests now pass, and coverage is 100%
intermine/web/test/src/org/intermine/webservice/server/output/JSONResultsIteratorTest.java
All tests now pass, and coverage is 100%
<ide><path>ntermine/web/test/src/org/intermine/webservice/server/output/JSONResultsIteratorTest.java <ide> <ide> import java.util.ArrayList; <ide> import java.util.Arrays; <add>import java.util.Calendar; <ide> import java.util.Collections; <add>import java.util.Date; <ide> import java.util.HashMap; <ide> import java.util.HashSet; <ide> import java.util.List; <add>import java.util.Locale; <ide> import java.util.Map; <ide> import java.util.Set; <add>import java.util.TimeZone; <add>import java.util.TreeMap; <ide> <ide> import org.intermine.api.query.MainHelper; <ide> import org.intermine.api.results.ExportResultsIterator; <ide> import org.intermine.api.results.ResultElement; <ide> import org.intermine.metadata.Model; <add>import org.intermine.model.testmodel.Address; <add>import org.intermine.model.testmodel.CEO; <ide> import org.intermine.model.testmodel.Company; <add>import org.intermine.model.testmodel.Contractor; <ide> import org.intermine.model.testmodel.Department; <ide> import org.intermine.model.testmodel.Employee; <add>import org.intermine.model.testmodel.Manager; <add>import org.intermine.model.testmodel.Types; <ide> import org.intermine.objectstore.dummy.DummyResults; <ide> import org.intermine.objectstore.dummy.ObjectStoreDummyImpl; <ide> import org.intermine.objectstore.query.Query; <ide> import org.intermine.objectstore.query.Results; <ide> import org.intermine.objectstore.query.ResultsRow; <ide> import org.intermine.pathquery.OuterJoinStatus; <add>import org.intermine.pathquery.Path; <add>import org.intermine.pathquery.PathException; <ide> import org.intermine.pathquery.PathQuery; <ide> import org.intermine.util.DynamicUtil; <ide> import org.intermine.util.IteratorIterable; <ide> import org.json.JSONException; <ide> import org.json.JSONObject; <ide> <add>import junit.framework.AssertionFailedError; <ide> import junit.framework.TestCase; <ide> <ide> /** <ide> <ide> } <ide> <add> private ObjectStoreDummyImpl os; <add> private Company wernhamHogg; <add> private CEO jennifer; <add> private Manager david; <add> private Manager taffy; <add> private Employee tim; <add> private Employee gareth; <add> private Employee dawn; <add> private Employee keith; <add> private Employee lee; <add> private Employee alex; <add> private Department sales; <add> private Department reception; <add> private Department accounts; <add> private Department distribution; <add> private Address address; <add> private Contractor rowan; <add> private Contractor ray; <add> private Contractor jude; <add> private Department swindon; <add> private Manager neil; <add> private Employee rachel; <add> private Employee trudy; <add> <add> <add> protected void setUp() { <add> os = new ObjectStoreDummyImpl(); <add> <add> wernhamHogg = (Company) DynamicUtil.createObject(Collections.singleton(Company.class)); <add> wernhamHogg.setId(new Integer(1)); <add> wernhamHogg.setName("Wernham-Hogg"); <add> wernhamHogg.setVatNumber(101); <add> <add> jennifer = new CEO(); <add> jennifer.setId(new Integer(2)); <add> jennifer.setName("Jennifer Taylor-Clarke"); <add> jennifer.setAge(42); <add> <add> david = new Manager(); <add> david.setId(new Integer(3)); <add> david.setName("David Brent"); <add> david.setAge(39); <add> <add> taffy = new Manager(); <add> taffy.setId(new Integer(4)); <add> taffy.setName("Glynn"); <add> taffy.setAge(38); <add> <add> tim = new Employee(); <add> tim.setId(new Integer(5)); <add> tim.setName("Tim Canterbury"); <add> tim.setAge(30); <add> <add> gareth = new Employee(); <add> gareth.setId(new Integer(6)); <add> gareth.setName("Gareth Keenan"); <add> gareth.setAge(32); <add> <add> dawn = new Employee(); <add> dawn.setId(new Integer(7)); <add> dawn.setName("Dawn Tinsley"); <add> dawn.setAge(26); <add> <add> keith = new Employee(); <add> keith.setId(new Integer(8)); <add> keith.setName("Keith Bishop"); <add> keith.setAge(41); <add> <add> lee = new Employee(); <add> lee.setId(new Integer(9)); <add> lee.setName("Lee"); <add> lee.setAge(28); <add> <add> alex = new Employee(); <add> alex.setId(new Integer(10)); <add> alex.setName("Alex"); <add> alex.setAge(24); <add> <add> sales = new Department(); <add> sales.setId(new Integer(11)); <add> sales.setName("Sales"); <add> <add> accounts = new Department(); <add> accounts.setId(new Integer(12)); <add> accounts.setName("Accounts"); <add> <add> distribution = new Department(); <add> distribution.setId(new Integer(13)); <add> distribution.setName("Warehouse"); <add> <add> reception = new Department(); <add> reception.setId(new Integer(14)); <add> reception.setName("Reception"); <add> <add> address = new Address(); <add> address.setId(new Integer(15)); <add> address.setAddress("42 Some St, Slough"); <add> <add> rowan = new Contractor(); <add> rowan.setId(new Integer(16)); <add> rowan.setName("Rowan"); <add> <add> ray = new Contractor(); <add> ray.setId(new Integer(17)); <add> ray.setName("Ray"); <add> <add> jude = new Contractor(); <add> jude.setId(new Integer(18)); <add> jude.setName("Jude"); <add> <add> swindon = new Department(); <add> swindon.setId(new Integer(19)); <add> swindon.setName("Swindon"); <add> <add> neil = new Manager(); <add> neil.setId(new Integer(20)); <add> neil.setName("Neil Godwin"); <add> neil.setAge(35); <add> <add> rachel = new Employee(); <add> rachel.setId(new Integer(21)); <add> rachel.setName("Rachel"); <add> rachel.setAge(34); <add> <add> trudy = new Employee(); <add> trudy.setId(new Integer(22)); <add> trudy.setName("Trudy"); <add> trudy.setAge(25); <add> <add> <add> } <add> <ide> private final Model model = Model.getInstanceByName("testmodel"); <ide> <ide> public JSONResultsIteratorTest(String arg) { <ide> super(arg); <ide> } <ide> <del> public void testNestedCollection() throws Exception { <del> ObjectStoreDummyImpl os = new ObjectStoreDummyImpl(); <add> public void testSingleSimpleObject() throws Exception { <add> os.setResultsSize(1); <add> <add> String jsonString = "{ 'class': 'Manager', 'objectId': 3, 'age': 39, 'name': 'David Brent' }"; <add> JSONObject expected = new JSONObject(jsonString); <add> <add> ResultsRow row = new ResultsRow(); <add> row.add(david); <add> <add> os.addRow(row); <add> <add> PathQuery pq = new PathQuery(model); <add> pq.addViews("Manager.name", "Manager.age"); <add> <add> Map pathToQueryNode = new HashMap(); <add> Query q = MainHelper.makeQuery(pq, new HashMap(), pathToQueryNode, null, null); <add> List resultList = os.execute(q, 0, 5, true, true, new HashMap()); <add> Results results = new DummyResults(q, resultList); <add> <add> ExportResultsIterator iter = new ExportResultsIterator(pq, results, pathToQueryNode); <add> <add> JSONResultsIterator jsonIter = new JSONResultsIterator(iter); <add> <add> List<JSONObject> got = new ArrayList<JSONObject>(); <add> for (JSONObject gotRow : new IteratorIterable<JSONObject>(jsonIter)) { <add> got.add(gotRow); <add> } <add> <add> assertEquals(1, got.size()); <add> <add> assertEquals(null, getProblemsComparing(expected, got.get(0))); <add> <add> } <add> <add> public void testMultipleSimpleObjects() throws Exception { <add> os.setResultsSize(5); <add> <add> List<String> jsonStrings = new ArrayList<String>(); <add> jsonStrings.add("{ 'class':'Employee', 'objectId':5, 'age':30, 'name': 'Tim Canterbury' }"); <add> jsonStrings.add("{ 'class':'Employee', 'objectId':6, 'age':32, 'name': 'Gareth Keenan' }"); <add> jsonStrings.add("{ 'class':'Employee', 'objectId':7, 'age':26, 'name': 'Dawn Tinsley' }"); <add> jsonStrings.add("{ 'class':'Employee', 'objectId':8, 'age':41, 'name': 'Keith Bishop' }"); <add> jsonStrings.add("{ 'class':'Employee', 'objectId':9, 'age':28, 'name': 'Lee' }"); <add> <add> ResultsRow row1 = new ResultsRow(); <add> row1.add(tim); <add> ResultsRow row2 = new ResultsRow(); <add> row2.add(gareth); <add> ResultsRow row3 = new ResultsRow(); <add> row3.add(dawn); <add> ResultsRow row4 = new ResultsRow(); <add> row4.add(keith); <add> ResultsRow row5 = new ResultsRow(); <add> row5.add(lee); <add> <add> os.addRow(row1); <add> os.addRow(row2); <add> os.addRow(row3); <add> os.addRow(row4); <add> os.addRow(row5); <add> <add> PathQuery pq = new PathQuery(model); <add> pq.addViews("Employee.name", "Employee.age", "Employee.id"); <add> <add> Map pathToQueryNode = new HashMap(); <add> Query q = MainHelper.makeQuery(pq, new HashMap(), pathToQueryNode, null, null); <add> List resultList = os.execute(q, 0, 5, true, true, new HashMap()); <add> Results results = new DummyResults(q, resultList); <add> <add> ExportResultsIterator iter = new ExportResultsIterator(pq, results, pathToQueryNode); <add> <add> JSONResultsIterator jsonIter = new JSONResultsIterator(iter); <add> <add> List<JSONObject> got = new ArrayList<JSONObject>(); <add> for (JSONObject gotRow : new IteratorIterable<JSONObject>(jsonIter)) { <add> got.add(gotRow); <add> } <add> <add> assertEquals(5, got.size()); <add> for (int i = 0; i < jsonStrings.size(); i++) { <add> JSONObject jo = new JSONObject(jsonStrings.get(i)); <add> assertEquals(null, getProblemsComparing(jo, got.get(i))); <add> } <add> <add> } <add> <add> public void testSingleObjectWithNestedCollections() throws Exception { <ide> os.setResultsSize(1); <del> <del> // Set up some known objects in the first 3 results rows <del> Company company1 = (Company) DynamicUtil.createObject(Collections.singleton(Company.class)); <del> company1.setName("Company1"); <del> company1.setVatNumber(101); <del> company1.setId(new Integer(1)); <del> <del> Department department1 = new Department(); <del> department1.setName("Department1"); <del> department1.setId(new Integer(2)); <del> Department department2 = new Department(); <del> department2.setName("Department2"); <del> department2.setId(new Integer(3)); <del> <del> Employee employee1 = new Employee(); <del> employee1.setName("Employee1"); <del> employee1.setId(new Integer(4)); <del> employee1.setAge(42); <del> Employee employee2 = new Employee(); <del> employee2.setName("Employee2"); <del> employee2.setId(new Integer(5)); <del> employee2.setAge(43); <del> Employee employee3 = new Employee(); <del> employee3.setName("Employee3"); <del> employee3.setId(new Integer(6)); <del> employee3.setAge(44); <del> Employee employee4 = new Employee(); <del> employee4.setName("Employee4"); <del> employee4.setId(new Integer(7)); <del> employee4.setAge(45); <del> <add> <ide> ResultsRow row = new ResultsRow(); <del> row.add(company1); <add> row.add(wernhamHogg); <ide> List sub1 = new ArrayList(); <ide> ResultsRow subRow1 = new ResultsRow(); <del> subRow1.add(department1); <add> subRow1.add(sales); <ide> List sub2 = new ArrayList(); <ide> ResultsRow subRow2 = new ResultsRow(); <del> subRow2.add(employee1); <add> subRow2.add(tim); <ide> sub2.add(subRow2); <ide> subRow2 = new ResultsRow(); <del> subRow2.add(employee2); <add> subRow2.add(gareth); <ide> sub2.add(subRow2); <ide> subRow1.add(sub2); <ide> sub1.add(subRow1); <ide> subRow1 = new ResultsRow(); <del> subRow1.add(department2); <add> subRow1.add(distribution); <ide> sub2 = new ArrayList(); <ide> subRow2 = new ResultsRow(); <del> subRow2.add(employee3); <add> subRow2.add(lee); <ide> sub2.add(subRow2); <ide> subRow2 = new ResultsRow(); <del> subRow2.add(employee4); <add> subRow2.add(alex); <ide> sub2.add(subRow2); <ide> subRow1.add(sub2); <ide> sub1.add(subRow1); <ide> <ide> ExportResultsIterator iter = new ExportResultsIterator(pq, results, pathToQueryNode); <ide> <del> JsonResultsIterator jsonIter = new JsonResultsIterator(iter); <add> JSONResultsIterator jsonIter = new JSONResultsIterator(iter); <ide> <ide> List<JSONObject> got = new ArrayList<JSONObject>(); <ide> for (JSONObject gotRow : new IteratorIterable<JSONObject>(jsonIter)) { <ide> assertEquals(got.size(), 1); <ide> <ide> String jsonString = "{" + <del> "\"objectId\" : 1," + <del> "\"name\" : \"Company1\"," + <del> "\"class\" : \"Company\"," + <del> "\"departments\" : [" + <del> "{" + <del> "\"objectId\" : 2," + <del> "\"name\":\"Department1\"," + <del> "\"class\":\"Department\"," + <del> "\"employees\" : [" + <del> "{" + <del> "\"objectId\" : 4," + <del> "\"name\" : \"Employee1\"," + <del> "\"class\" : \"Employee\"" + <del> "}," + <del> "{" + <del> " \"objectId\" : 5," + <del> " \"name\" : \"Employee2\"," + <del> " \"class\":\"Employee\"" + <del> "}" + <del> "]" + <del> "}," + <del> "{" + <del> " \"objectId\" : 3," + <del> " \"name\" : \"Department2\", " + <del> " \"class\" : \"Department\"," + <del> " \"employees\" : [" + <del> " {" + <del> " \"objectId\" : 6," + <del> " \"name\" : \"Employee3\"," + <del> " \"class\" : \"Employee\"" + <del> " }," + <del> " {" + <del> " \"objectId\" : 7," + <del> " \"name\" : \"Employee4\"," + <del> " \"class\" : \"Employee\"" + <del> " }" + <del> " ]" + <del> "}" + <del> "]," + <del> "\"vatNumber\" : \"101\"" + <del> "}"; <add> " 'objectId' : 1," + <add> " 'class' : 'Company'," + <add> " 'name' : 'Wernham-Hogg'," + <add> " 'vatNumber' : 101," + <add> " 'departments' : [" + <add> " {" + <add> " 'objectId' : 11," + <add> " 'class' : 'Department'," + <add> " 'name' : 'Sales'," + <add> " 'employees' : [" + <add> " { " + <add> " 'objectId' : 5," + <add> " 'class' : 'Employee'," + <add> " 'name' : 'Tim Canterbury'" + <add> " }, " + <add> " { " + <add> " 'objectId' : 6," + <add> " 'class' : 'Employee'," + <add> " 'name' : 'Gareth Keenan'" + <add> " }" + <add> " ]" + <add> " }," + <add> " {" + <add> " 'objectId' : 13," + <add> " 'class' : 'Department'," + <add> " 'name' : 'Warehouse', " + <add> " 'employees' : [" + <add> " {" + <add> " 'objectId' : 9," + <add> " 'class' : 'Employee'," + <add> " 'name' : 'Lee'" + <add> " }," + <add> " {" + <add> " 'objectId' : 10," + <add> " 'class' : 'Employee'," + <add> " 'name' : 'Alex'" + <add> " }" + <add> " ]" + <add> " }" + <add> " ]" + <add> "}"; <ide> <ide> <ide> JSONObject expected = new JSONObject(jsonString); <ide> assertEquals(null, getProblemsComparing(expected, got.get(0))); <ide> <ide> } <del> <add> public void testSingleObjectWithNestedCollectionsAndMultipleAttributes() throws Exception { <add> os.setResultsSize(1); <add> <add> ResultsRow row = new ResultsRow(); <add> row.add(wernhamHogg); <add> List sub1 = new ArrayList(); <add> ResultsRow subRow1 = new ResultsRow(); <add> subRow1.add(sales); <add> List sub2 = new ArrayList(); <add> ResultsRow subRow2 = new ResultsRow(); <add> subRow2.add(tim); <add> sub2.add(subRow2); <add> subRow2 = new ResultsRow(); <add> subRow2.add(gareth); <add> sub2.add(subRow2); <add> subRow1.add(sub2); <add> sub1.add(subRow1); <add> subRow1 = new ResultsRow(); <add> subRow1.add(distribution); <add> sub2 = new ArrayList(); <add> subRow2 = new ResultsRow(); <add> subRow2.add(lee); <add> sub2.add(subRow2); <add> subRow2 = new ResultsRow(); <add> subRow2.add(alex); <add> sub2.add(subRow2); <add> subRow1.add(sub2); <add> sub1.add(subRow1); <add> row.add(sub1); <add> os.addRow(row); <add> <add> PathQuery pq = new PathQuery(model); <add> pq.addViews("Company.name", "Company.vatNumber", <add> "Company.departments.name", <add> "Company.departments.employees.name", "Company.departments.employees.age"); <add> pq.setOuterJoinStatus("Company.departments", OuterJoinStatus.OUTER); <add> pq.setOuterJoinStatus("Company.departments.employees", OuterJoinStatus.OUTER); <add> <add> Map pathToQueryNode = new HashMap(); <add> Query q = MainHelper.makeQuery(pq, new HashMap(), pathToQueryNode, null, null); <add> List resultList = os.execute(q, 0, 1, true, true, new HashMap()); <add> Results results = new DummyResults(q, resultList); <add> <add> ExportResultsIterator iter = new ExportResultsIterator(pq, results, pathToQueryNode); <add> <add> JSONResultsIterator jsonIter = new JSONResultsIterator(iter); <add> <add> List<JSONObject> got = new ArrayList<JSONObject>(); <add> for (JSONObject gotRow : new IteratorIterable<JSONObject>(jsonIter)) { <add> got.add(gotRow); <add> } <add> <add> assertEquals(got.size(), 1); <add> <add> String jsonString = "{" + <add> " 'objectId' : 1," + <add> " 'class' : 'Company'," + <add> " 'name' : 'Wernham-Hogg'," + <add> " 'vatNumber' : 101," + <add> " 'departments' : [" + <add> " {" + <add> " 'objectId' : 11," + <add> " 'class' : 'Department'," + <add> " 'name' : 'Sales'," + <add> " 'employees' : [" + <add> " { " + <add> " 'objectId' : 5," + <add> " 'class' : 'Employee'," + <add> " 'name' : 'Tim Canterbury'," + <add> " 'age' : 30" + <add> " }, " + <add> " { " + <add> " 'objectId' : 6," + <add> " 'class' : 'Employee'," + <add> " 'name' : 'Gareth Keenan'," + <add> " 'age' : 32" + <add> " }" + <add> " ]" + <add> " }," + <add> " {" + <add> " 'objectId' : 13," + <add> " 'class' : 'Department'," + <add> " 'name' : 'Warehouse', " + <add> " 'employees' : [" + <add> " {" + <add> " 'objectId' : 9," + <add> " 'class' : 'Employee'," + <add> " 'name' : 'Lee'," + <add> " 'age' : 28" + <add> " }," + <add> " {" + <add> " 'objectId' : 10," + <add> " 'class' : 'Employee'," + <add> " 'name' : 'Alex'," + <add> " 'age' : 24" + <add> " }" + <add> " ]" + <add> " }" + <add> " ]" + <add> "}"; <add> <add> <add> JSONObject expected = new JSONObject(jsonString); <add> assertEquals(null, getProblemsComparing(expected, got.get(0))); <add> <add> } <add> <add> <add> // Attributes on references should precede references on references <add> // The dummy attribute "id" can be used without populating the object with <add> // unwanted stuff. <add> public void testSingleObjectWithTrailOfReferences() throws Exception { <add> os.setResultsSize(1); <add> <add> PathQuery pq = new PathQuery(model); <add> pq.addViews("Department.name", "Department.company.id", "Department.company.CEO.name", "Department.company.CEO.address.address"); <add> <add> String jsonString = "{" + <add> " 'class' : 'Department'," + <add> " 'objectId' : 11," + <add> " 'name' : 'Sales'," + <add> " 'company' : {" + <add> " 'class' : 'Company'," + <add> " 'objectId' : 1," + <add> " 'CEO' : {" + <add> " 'class' : 'CEO'," + <add> " 'objectId' : 2," + <add> " 'name' : 'Jennifer Taylor-Clarke'," + <add> " 'address' : {" + <add> " 'class' : 'Address'," + <add> " 'objectId' : 15," + <add> " 'address' : '42 Some St, Slough'" + <add> " }" + <add> " }" + <add> " }" + <add> " }"; <add> JSONObject expected = new JSONObject(jsonString); <add> <add> ResultsRow row = new ResultsRow(); <add> row.add(sales); <add> row.add(wernhamHogg); <add> row.add(jennifer); <add> row.add(address); <add> os.addRow(row); <add> <add> Map pathToQueryNode = new HashMap(); <add> Query q = MainHelper.makeQuery(pq, new HashMap(), pathToQueryNode, null, null); <add> List resultList = os.execute(q, 0, 1, true, true, new HashMap()); <add> Results results = new DummyResults(q, resultList); <add> <add> ExportResultsIterator iter = new ExportResultsIterator(pq, results, pathToQueryNode); <add> <add> JSONResultsIterator jsonIter = new JSONResultsIterator(iter); <add> <add> List<JSONObject> got = new ArrayList<JSONObject>(); <add> for (JSONObject gotRow : new IteratorIterable<JSONObject>(jsonIter)) { <add> got.add(gotRow); <add> } <add> <add> assertEquals(got.size(), 1); <add> <add> assertEquals(null, getProblemsComparing(expected, got.get(0))); <add> <add> } <add> <add> // Attributes on references should precede references on references <add> // Not doing so causes an error <add> public void testBadReferenceTrail() throws Exception { <add> os.setResultsSize(1); <add> <add> ResultsRow row = new ResultsRow(); <add> row.add(sales); <add> row.add(jennifer); <add> row.add(address); <add> os.addRow(row); <add> <add> PathQuery pq = new PathQuery(model); <add> pq.addViews("Department.name", "Department.company.CEO.name", "Department.company.CEO.address.address"); <add> <add> Map pathToQueryNode = new HashMap(); <add> Query q = MainHelper.makeQuery(pq, new HashMap(), pathToQueryNode, null, null); <add> List resultList = os.execute(q, 0, 1, true, true, new HashMap()); <add> Results results = new DummyResults(q, resultList); <add> <add> ExportResultsIterator iter = new ExportResultsIterator(pq, results, pathToQueryNode); <add> <add> JSONResultsIterator jsonIter = new JSONResultsIterator(iter); <add> <add> try { <add> List<JSONObject> got = new ArrayList<JSONObject>(); <add> for (JSONObject gotRow : new IteratorIterable<JSONObject>(jsonIter)) { <add> got.add(gotRow); <add> } <add> fail("No exception was thrown dealing with bad query - got this list: " + got); <add> } catch (AssertionFailedError e) { <add> // rethrow the fail from within the try <add> throw e; <add> } catch (JSONFormattingException e) { <add> // Test that this is what we thought would happen. <add> assertEquals("This node is not fully initialised: it has no objectId", e.getMessage()); <add> } catch (Throwable e){ <add> // All other exceptions are failures <add> fail("Got unexpected error: " + e); <add> } <add> <add> } <add> <add> // Attributes on references should precede references on references <add> public void testSingleObjectWithACollection() throws Exception { <add> os.setResultsSize(2); <add> <add> ResultsRow row = new ResultsRow(); <add> row.add(david); <add> row.add(sales); <add> row.add(tim); <add> os.addRow(row); <add> ResultsRow row2 = new ResultsRow(); <add> row2.add(david); <add> row2.add(sales); <add> row2.add(gareth); <add> os.addRow(row2); <add> <add> String jsonString = <add> "{" + <add> " 'objectId' : 3," + <add> " 'class' : 'Manager'," + <add> " 'name' : 'David Brent'," + <add> " 'age' : 39," + <add> " 'department' : {" + <add> " 'objectId' : 11," + <add> " 'class' : 'Department'," + <add> " 'name' : 'Sales'," + <add> " 'employees' : [" + <add> " { " + <add> " 'objectId' : 5," + <add> " 'class' : 'Employee'," + <add> " 'name' : 'Tim Canterbury'," + <add> " 'age' : 30" + <add> " }, " + <add> " { " + <add> " 'objectId' : 6," + <add> " 'class' : 'Employee'," + <add> " 'name' : 'Gareth Keenan'," + <add> " 'age' : 32" + <add> " }" + <add> " ]" + <add> " }" + <add> "}"; <add> <add> PathQuery pq = new PathQuery(model); <add> pq.addViews("Manager.name", "Manager.age", "Manager.department.name", "Manager.department.employees.name", "Manager.department.employees.age"); <add> <add> <add> Map pathToQueryNode = new HashMap(); <add> Query q = MainHelper.makeQuery(pq, new HashMap(), pathToQueryNode, null, null); <add> List resultList = os.execute(q, 0, 2, true, true, new HashMap()); <add> Results results = new DummyResults(q, resultList); <add> <add> ExportResultsIterator iter = new ExportResultsIterator(pq, results, pathToQueryNode); <add> <add> JSONResultsIterator jsonIter = new JSONResultsIterator(iter); <add> <add> List<JSONObject> got = new ArrayList<JSONObject>(); <add> for (JSONObject gotRow : new IteratorIterable<JSONObject>(jsonIter)) { <add> got.add(gotRow); <add> } <add> <add> assertEquals(got.size(), 1); <add> <add> JSONObject expected = new JSONObject(jsonString); <add> assertEquals(null, getProblemsComparing(expected, got.get(0))); <add> <add> } <add> <add> // Attributes on references should precede references on references <add> // Not doing so causes an error <add> public void testBadCollectionTrail() throws Exception { <add> os.setResultsSize(2); <add> <add> ResultsRow row = new ResultsRow(); <add> row.add(david); <add> row.add(tim); <add> os.addRow(row); <add> ResultsRow row2 = new ResultsRow(); <add> row2.add(david); <add> row2.add(gareth); <add> os.addRow(row2); <add> <add> PathQuery pq = new PathQuery(model); <add> pq.addViews("Manager.name", "Manager.department.employees.name"); <add> <add> <add> Map pathToQueryNode = new HashMap(); <add> Query q = MainHelper.makeQuery(pq, new HashMap(), pathToQueryNode, null, null); <add> List resultList = os.execute(q, 0, 2, true, true, new HashMap()); <add> Results results = new DummyResults(q, resultList); <add> <add> ExportResultsIterator iter = new ExportResultsIterator(pq, results, pathToQueryNode); <add> <add> JSONResultsIterator jsonIter = new JSONResultsIterator(iter); <add> <add> try { <add> List<JSONObject> got = new ArrayList<JSONObject>(); <add> for (JSONObject gotRow : new IteratorIterable<JSONObject>(jsonIter)) { <add> got.add(gotRow); <add> } <add> fail("No exception was thrown dealing with bad query - got this list: " + got); <add> } catch (AssertionFailedError e) { <add> // rethrow the fail from within the try <add> throw e; <add> } catch (JSONFormattingException e) { <add> // Test that this is what we thought would happen. <add> assertEquals("This node is not properly initialised (it doesn't have an objectId) - is the view in the right order?", e.getMessage()); <add> } catch (Throwable e){ <add> // All other exceptions are failures <add> fail("Got unexpected error: " + e); <add> } <add> <add> } <add> <add> public void testHeadlessQuery() throws Exception { <add> os.setResultsSize(2); <add> <add> ResultsRow row = new ResultsRow(); <add> row.add(tim); <add> os.addRow(row); <add> ResultsRow row2 = new ResultsRow(); <add> row2.add(gareth); <add> os.addRow(row2); <add> <add> PathQuery pq = new PathQuery(model); <add> pq.addViews("Manager.department.employees.name", "Manager.department.employees.age"); <add> <add> Map pathToQueryNode = new HashMap(); <add> Query q = MainHelper.makeQuery(pq, new HashMap(), pathToQueryNode, null, null); <add> List resultList = os.execute(q, 0, 2, true, true, new HashMap()); <add> Results results = new DummyResults(q, resultList); <add> <add> ExportResultsIterator iter = new ExportResultsIterator(pq, results, pathToQueryNode); <add> <add> JSONResultsIterator jsonIter = new JSONResultsIterator(iter); <add> <add> try { <add> List<JSONObject> got = new ArrayList<JSONObject>(); <add> for (JSONObject gotRow : new IteratorIterable<JSONObject>(jsonIter)) { <add> got.add(gotRow); <add> } <add> fail("No exception was thrown dealing with bad query - got this list: " + got); <add> } catch (AssertionFailedError e) { <add> // rethrow the fail from within the try <add> throw e; <add> } catch (JSONFormattingException e) { <add> // Test that this is what we thought would happen. <add> assertEquals("Head of the object is missing", e.getMessage()); <add> } catch (Throwable e){ <add> // All other exceptions are failures <add> fail("Got unexpected error: " + e); <add> } <add> <add> } <add> <add> public void testParallelCollection() throws Exception { <add> os.setResultsSize(1); <add> <add> String jsonString = <add> "{" + <add> " 'class' : 'Company'," + <add> " 'objectId' : 1," + <add> " 'name' : 'Wernham-Hogg'," + <add> " 'vatNumber' : 101," + <add> " departments : [" + <add> " {" + <add> " 'class' : 'Department'," + <add> " 'objectId' : 11," + <add> " 'name' : 'Sales'" + <add> " }," + <add> " {" + <add> " 'class' : 'Department'," + <add> " 'objectId' : 12," + <add> " 'name' : 'Accounts'" + <add> " }" + <add> " ]," + <add> " contractors : [" + <add> " {" + <add> " 'class' : 'Contractor'," + <add> " 'objectId' : 16," + <add> " 'name' : 'Rowan'" + <add> " }," + <add> " {" + <add> " 'class' : 'Contractor'," + <add> " 'objectId' : 17," + <add> " 'name' : 'Ray'" + <add> " }," + <add> " {" + <add> " 'class' : 'Contractor'," + <add> " 'objectId' : 18," + <add> " 'name' : 'Jude'" + <add> " }" + <add> " ]" + <add> "}"; <add> <add> ResultsRow row = new ResultsRow(); <add> row.add(wernhamHogg); <add> List sub1 = new ArrayList(); <add> ResultsRow subRow1 = new ResultsRow(); <add> subRow1.add(sales); <add> sub1.add(subRow1); <add> subRow1 = new ResultsRow(); <add> subRow1.add(accounts); <add> sub1.add(subRow1); <add> row.add(sub1); <add> sub1 = new ArrayList(); <add> subRow1 = new ResultsRow(); <add> subRow1.add(rowan); <add> sub1.add(subRow1); <add> subRow1 = new ResultsRow(); <add> subRow1.add(ray); <add> sub1.add(subRow1); <add> subRow1 = new ResultsRow(); <add> subRow1.add(jude); <add> sub1.add(subRow1); <add> row.add(sub1); <add> os.addRow(row); <add> <add> PathQuery pq = new PathQuery(model); <add> pq.addViews("Company.name", "Company.vatNumber", <add> "Company.departments.name", <add> "Company.contractors.name"); <add> pq.setOuterJoinStatus("Company.departments", OuterJoinStatus.OUTER); <add> pq.setOuterJoinStatus("Company.contractors", OuterJoinStatus.OUTER); <add> <add> Map pathToQueryNode = new HashMap(); <add> Query q = MainHelper.makeQuery(pq, new HashMap(), pathToQueryNode, null, null); <add> List resultList = os.execute(q, 0, 1, true, true, new HashMap()); <add> Results results = new DummyResults(q, resultList); <add> <add> ExportResultsIterator iter = new ExportResultsIterator(pq, results, pathToQueryNode); <add> <add> JSONResultsIterator jsonIter = new JSONResultsIterator(iter); <add> <add> <add> List<JSONObject> got = new ArrayList<JSONObject>(); <add> for (JSONObject gotRow : new IteratorIterable<JSONObject>(jsonIter)) { <add> got.add(gotRow); <add> } <add> <add> JSONObject expected = new JSONObject(jsonString); <add> <add> assertEquals(got.size(), 1); <add> <add> assertEquals(null, getProblemsComparing(expected, got.get(0))); <add> <add> } <add> <add> public void testHeadInWrongPlace() throws Exception { <add> os.setResultsSize(2); <add> <add> ResultsRow row1 = new ResultsRow(); <add> row1.add(tim); <add> row1.add(sales); <add> os.addRow(row1); <add> ResultsRow row2 = new ResultsRow(); <add> row2.add(gareth); <add> row2.add(sales); <add> os.addRow(row2); <add> <add> PathQuery pq = new PathQuery(model); <add> pq.addViews("Department.employees.name", "Department.name"); <add> <add> Map pathToQueryNode = new HashMap(); <add> Query q = MainHelper.makeQuery(pq, new HashMap(), pathToQueryNode, null, null); <add> List resultList = os.execute(q, 0, 2, true, true, new HashMap()); <add> Results results = new DummyResults(q, resultList); <add> <add> ExportResultsIterator iter = new ExportResultsIterator(pq, results, pathToQueryNode); <add> <add> JSONResultsIterator jsonIter = new JSONResultsIterator(iter); <add> <add> try { <add> List<JSONObject> got = new ArrayList<JSONObject>(); <add> for (JSONObject gotRow : new IteratorIterable<JSONObject>(jsonIter)) { <add> got.add(gotRow); <add> } <add> fail("No exception was thrown dealing with bad query - got this list: " + got); <add> } catch (AssertionFailedError e) { <add> // rethrow the fail from within the try <add> throw e; <add> } catch (JSONFormattingException e) { <add> // Test that this is what we thought would happen. <add> assertEquals("Head of the object is missing", e.getMessage()); <add> } catch (Throwable e){ <add> // All other exceptions are failures <add> fail("Got unexpected error: " + e); <add> } <add> <add> } <add> public void testRefBeforeItsParentCollectionOrder() throws Exception { <add> os.setResultsSize(2); <add> <add> ResultsRow row1 = new ResultsRow(); <add> row1.add(wernhamHogg); <add> row1.add(tim); <add> row1.add(sales); <add> os.addRow(row1); <add> ResultsRow row2 = new ResultsRow(); <add> row2.add(wernhamHogg); <add> row2.add(gareth); <add> row2.add(sales); <add> os.addRow(row2); <add> <add> PathQuery pq = new PathQuery(model); <add> pq.addViews("Company.name", "Company.departments.employees.name", "Company.departments.name"); <add> <add> Map pathToQueryNode = new HashMap(); <add> Query q = MainHelper.makeQuery(pq, new HashMap(), pathToQueryNode, null, null); <add> List resultList = os.execute(q, 0, 2, true, true, new HashMap()); <add> Results results = new DummyResults(q, resultList); <add> <add> ExportResultsIterator iter = new ExportResultsIterator(pq, results, pathToQueryNode); <add> <add> JSONResultsIterator jsonIter = new JSONResultsIterator(iter); <add> <add> try { <add> List<JSONObject> got = new ArrayList<JSONObject>(); <add> for (JSONObject gotRow : new IteratorIterable<JSONObject>(jsonIter)) { <add> got.add(gotRow); <add> } <add> fail("No exception was thrown dealing with bad query - got this list: " + got); <add> } catch (AssertionFailedError e) { <add> // rethrow the fail from within the try <add> throw e; <add> } catch (JSONFormattingException e) { <add> // Test that this is what we thought would happen. <add> assertEquals("This array is empty - is the view in the wrong order?", e.getMessage()); <add> } catch (Throwable e){ <add> // All other exceptions are failures <add> fail("Got unexpected error: " + e); <add> } <add> <add> } <add> public void testColBeforeItsParentRefOrder() throws Exception { <add> os.setResultsSize(2); <add> <add> ResultsRow row1 = new ResultsRow(); <add> row1.add(david); <add> row1.add(tim); <add> row1.add(sales); <add> os.addRow(row1); <add> ResultsRow row2 = new ResultsRow(); <add> row2.add(david); <add> row2.add(gareth); <add> row2.add(sales); <add> os.addRow(row2); <add> <add> PathQuery pq = new PathQuery(model); <add> pq.addViews("Manager.name", "Manager.department.employees.name", "Manager.department.name"); <add> <add> Map pathToQueryNode = new HashMap(); <add> Query q = MainHelper.makeQuery(pq, new HashMap(), pathToQueryNode, null, null); <add> List resultList = os.execute(q, 0, 2, true, true, new HashMap()); <add> Results results = new DummyResults(q, resultList); <add> <add> ExportResultsIterator iter = new ExportResultsIterator(pq, results, pathToQueryNode); <add> <add> JSONResultsIterator jsonIter = new JSONResultsIterator(iter); <add> <add> try { <add> List<JSONObject> got = new ArrayList<JSONObject>(); <add> for (JSONObject gotRow : new IteratorIterable<JSONObject>(jsonIter)) { <add> got.add(gotRow); <add> } <add> fail("No exception was thrown dealing with bad query - got this list: " + got); <add> } catch (AssertionFailedError e) { <add> // rethrow the fail from within the try <add> throw e; <add> } catch (JSONFormattingException e) { <add> // Test that this is what we thought would happen. <add> assertEquals("This node is not properly initialised (it doesn't have an objectId) - is the view in the right order?", e.getMessage()); <add> } catch (Throwable e){ <add> // All other exceptions are failures <add> fail("Got unexpected error: " + e); <add> } <add> <add> } <add> <add> public void testMultipleObjectsWithColls() throws Exception { <add> os.setResultsSize(6); <add> <add> List<String> jsonStrings = new ArrayList<String>(); <add> <add> jsonStrings.add( <add> " {" + <add> " 'objectId' : 11," + <add> " 'class' : 'Department'," + <add> " 'name' : 'Sales'," + <add> " 'employees' : [" + <add> " { " + <add> " 'objectId' : 5," + <add> " 'class' : 'Employee'," + <add> " 'name' : 'Tim Canterbury'," + <add> " 'age' : 30" + <add> " }, " + <add> " { " + <add> " 'objectId' : 6," + <add> " 'class' : 'Employee'," + <add> " 'name' : 'Gareth Keenan'," + <add> " 'age' : 32" + <add> " }" + <add> " ]" + <add> " }"); <add> jsonStrings.add( <add> " {" + <add> " 'objectId' : 12," + <add> " 'class' : 'Department'," + <add> " 'name' : 'Accounts'," + <add> " 'employees' : [" + <add> " { " + <add> " 'objectId' : 8," + <add> " 'class' : 'Employee'," + <add> " 'name' : 'Keith Bishop'," + <add> " 'age' : 41" + <add> " } " + <add> " ]" + <add> " }"); <add> <add> jsonStrings.add( <add> " {" + <add> " 'objectId' : 13," + <add> " 'class' : 'Department'," + <add> " 'name' : 'Warehouse', " + <add> " 'employees' : [" + <add> " {" + <add> " 'objectId' : 9," + <add> " 'class' : 'Employee'," + <add> " 'name' : 'Lee'," + <add> " 'age' : 28" + <add> " }," + <add> " {" + <add> " 'objectId' : 10," + <add> " 'class' : 'Employee'," + <add> " 'name' : 'Alex'," + <add> " 'age' : 24" + <add> " }" + <add> " ]" + <add> " }"); <add> jsonStrings.add( <add> " {" + <add> " 'objectId' : 14," + <add> " 'class' : 'Department'," + <add> " 'name' : 'Reception'," + <add> " 'employees' : [" + <add> " { " + <add> " 'objectId' : 7," + <add> " 'class' : 'Employee'," + <add> " 'name' : 'Dawn Tinsley'," + <add> " 'age' : 26" + <add> " } " + <add> " ]" + <add> " }"); <add> <add> ResultsRow row1 = new ResultsRow(); <add> row1.add(sales); <add> row1.add(tim); <add> ResultsRow row2 = new ResultsRow(); <add> row2.add(sales); <add> row2.add(gareth); <add> ResultsRow row3 = new ResultsRow(); <add> row3.add(accounts); <add> row3.add(keith); <add> ResultsRow row4 = new ResultsRow(); <add> row4.add(distribution); <add> row4.add(lee); <add> ResultsRow row5 = new ResultsRow(); <add> row5.add(distribution); <add> row5.add(alex); <add> ResultsRow row6 = new ResultsRow(); <add> row6.add(reception); <add> row6.add(dawn); <add> <add> os.addRow(row1); <add> os.addRow(row2); <add> os.addRow(row3); <add> os.addRow(row4); <add> os.addRow(row5); <add> os.addRow(row6); <add> <add> PathQuery pq = new PathQuery(model); <add> pq.addViews("Department.name", "Department.employees.name", "Department.employees.age"); <add> <add> Map pathToQueryNode = new HashMap(); <add> Query q = MainHelper.makeQuery(pq, new HashMap(), pathToQueryNode, null, null); <add> List resultList = os.execute(q, 0, 6, true, true, new HashMap()); <add> Results results = new DummyResults(q, resultList); <add> <add> ExportResultsIterator iter = new ExportResultsIterator(pq, results, pathToQueryNode); <add> <add> JSONResultsIterator jsonIter = new JSONResultsIterator(iter); <add> <add> List<JSONObject> got = new ArrayList<JSONObject>(); <add> for (JSONObject gotRow : new IteratorIterable<JSONObject>(jsonIter)) { <add> got.add(gotRow); <add> } <add> <add> assertEquals(4, got.size()); <add> for (int i = 0; i < jsonStrings.size(); i++) { <add> JSONObject jo = new JSONObject(jsonStrings.get(i)); <add> assertEquals(null, getProblemsComparing(jo, got.get(i))); <add> } <add> } <add> <add> public void testMultipleObjectsWithRefs() throws Exception { <add> os.setResultsSize(6); <add> <add> List<String> jsonStrings = new ArrayList<String>(); <add> <add> jsonStrings.add( <add> " {" + <add> " objectId : 11," + <add> " class : 'Department'," + <add> " name : 'Sales'," + <add> " manager : { class: 'Manager', objectId: 3, age: 39, name: 'David Brent' }," + <add> " company : { class: 'Company', objectId: 1, vatNumber: 101, name: 'Wernham-Hogg' }" + <add> " }"); <add> jsonStrings.add( <add> " {" + <add> " objectId : 12," + <add> " class : 'Department'," + <add> " name : 'Accounts'," + <add> " manager : { class: 'Manager', objectId: 3, age: 39, name: 'David Brent' }," + <add> " company : { class: 'Company', objectId: 1, vatNumber: 101, name: 'Wernham-Hogg' }" + <add> " }"); <add> <add> jsonStrings.add( <add> " {" + <add> " objectId : 13," + <add> " class : 'Department'," + <add> " name : 'Warehouse', " + <add> " manager : { class: 'Manager', objectId: 4, age: 38, name: 'Glynn' }," + <add> " company : { class: 'Company', objectId: 1, vatNumber: 101, name: 'Wernham-Hogg' }" + <add> " }"); <add> jsonStrings.add( <add> " {" + <add> " objectId : 19," + <add> " class : 'Department'," + <add> " name : 'Swindon', " + <add> " manager : { class: 'Manager', objectId: 20, age: 35, name: 'Neil Godwin' }," + <add> " company : { class: 'Company', objectId: 1, vatNumber: 101, name: 'Wernham-Hogg' }" + <add> " }"); <add> <add> ResultsRow row1 = new ResultsRow(); <add> row1.add(sales); <add> row1.add(david); <add> row1.add(wernhamHogg); <add> ResultsRow row2 = new ResultsRow(); <add> row2.add(accounts); <add> row2.add(david); <add> row2.add(wernhamHogg); <add> ResultsRow row3 = new ResultsRow(); <add> row3.add(distribution); <add> row3.add(taffy); <add> row3.add(wernhamHogg); <add> ResultsRow row4 = new ResultsRow(); <add> row4.add(swindon); <add> row4.add(neil); <add> row4.add(wernhamHogg); <add> <add> os.addRow(row1); <add> os.addRow(row2); <add> os.addRow(row3); <add> os.addRow(row4); <add> <add> PathQuery pq = new PathQuery(model); <add> pq.addViews("Department.name", "Department.manager.name", "Department.manager.age", "Department.company.name", "Department.company.vatNumber"); <add> <add> Map pathToQueryNode = new HashMap(); <add> Query q = MainHelper.makeQuery(pq, new HashMap(), pathToQueryNode, null, null); <add> List resultList = os.execute(q, 0, 4, true, true, new HashMap()); <add> Results results = new DummyResults(q, resultList); <add> <add> ExportResultsIterator iter = new ExportResultsIterator(pq, results, pathToQueryNode); <add> <add> JSONResultsIterator jsonIter = new JSONResultsIterator(iter); <add> <add> List<JSONObject> got = new ArrayList<JSONObject>(); <add> for (JSONObject gotRow : new IteratorIterable<JSONObject>(jsonIter)) { <add> got.add(gotRow); <add> } <add> <add> assertEquals(4, got.size()); <add> for (int i = 0; i < jsonStrings.size(); i++) { <add> JSONObject jo = new JSONObject(jsonStrings.get(i)); <add> assertEquals(null, getProblemsComparing(jo, got.get(i))); <add> } <add> } <add> <add> public void testMultipleObjectsWithRefsAndCols() throws Exception { <add> os.setResultsSize(7); <add> <add> List<String> jsonStrings = new ArrayList<String>(); <add> <add> jsonStrings.add( <add> " {" + <add> " objectId : 11," + <add> " class : 'Department'," + <add> " name : 'Sales'," + <add> " manager : { class: 'Manager', objectId: 3, age: 39, name: 'David Brent' }," + <add> " company : { class: 'Company', objectId: 1, vatNumber: 101, name: 'Wernham-Hogg' }," + <add> " 'employees' : [" + <add> " { " + <add> " objectId : 5," + <add> " class : 'Employee'," + <add> " name : 'Tim Canterbury'," + <add> " age : 30" + <add> " }, " + <add> " { " + <add> " objectId : 6," + <add> " class : 'Employee'," + <add> " name : 'Gareth Keenan'," + <add> " age : 32" + <add> " }" + <add> " ]" + <add> " }"); <add> jsonStrings.add( <add> " {" + <add> " objectId : 12," + <add> " class : 'Department'," + <add> " name : 'Accounts'," + <add> " manager : { class: 'Manager', objectId: 3, age: 39, name: 'David Brent' }," + <add> " company : { class: 'Company', objectId: 1, vatNumber: 101, name: 'Wernham-Hogg' }," + <add> " employees : [" + <add> " { " + <add> " objectId : 8," + <add> " class : 'Employee'," + <add> " name : 'Keith Bishop'," + <add> " age : 41" + <add> " } " + <add> " ]" + <add> " }"); <add> <add> jsonStrings.add( <add> " {" + <add> " objectId : 13," + <add> " class : 'Department'," + <add> " name : 'Warehouse', " + <add> " manager : { class: 'Manager', objectId: 4, age: 38, name: 'Glynn' }," + <add> " company : { class: 'Company', objectId: 1, vatNumber: 101, name: 'Wernham-Hogg' }," + <add> " employees : [" + <add> " {" + <add> " objectId : 9," + <add> " class : 'Employee'," + <add> " name : 'Lee'," + <add> " age : 28" + <add> " }," + <add> " {" + <add> " objectId : 10," + <add> " class : 'Employee'," + <add> " name : 'Alex'," + <add> " age : 24" + <add> " }" + <add> " ]" + <add> " }"); <add> jsonStrings.add( <add> " {" + <add> " objectId : 19," + <add> " class : 'Department'," + <add> " name : 'Swindon', " + <add> " manager : { class: 'Manager', objectId: 20, age: 35, name: 'Neil Godwin' }," + <add> " company : { class: 'Company', objectId: 1, vatNumber: 101, name: 'Wernham-Hogg' }," + <add> " employees : [" + <add> " {" + <add> " objectId : 21," + <add> " class : 'Employee'," + <add> " name : 'Rachel'," + <add> " age : 34" + <add> " }," + <add> " {" + <add> " objectId : 22," + <add> " class : 'Employee'," + <add> " name : 'Trudy'," + <add> " age : 25" + <add> " }" + <add> " ]" + <add> " }"); <add> <add> ResultsRow row1a = new ResultsRow(); <add> row1a.add(sales); <add> row1a.add(david); <add> row1a.add(wernhamHogg); <add> row1a.add(tim); <add> ResultsRow row1b = new ResultsRow(); <add> row1b.add(sales); <add> row1b.add(david); <add> row1b.add(wernhamHogg); <add> row1b.add(gareth); <add> ResultsRow row2 = new ResultsRow(); <add> row2.add(accounts); <add> row2.add(david); <add> row2.add(wernhamHogg); <add> row2.add(keith); <add> ResultsRow row3a = new ResultsRow(); <add> row3a.add(distribution); <add> row3a.add(taffy); <add> row3a.add(wernhamHogg); <add> row3a.add(lee); <add> ResultsRow row3b = new ResultsRow(); <add> row3b.add(distribution); <add> row3b.add(taffy); <add> row3b.add(wernhamHogg); <add> row3b.add(alex); <add> ResultsRow row4a = new ResultsRow(); <add> row4a.add(swindon); <add> row4a.add(neil); <add> row4a.add(wernhamHogg); <add> row4a.add(rachel); <add> ResultsRow row4b = new ResultsRow(); <add> row4b.add(swindon); <add> row4b.add(neil); <add> row4b.add(wernhamHogg); <add> row4b.add(trudy); <add> <add> <add> os.addRow(row1a); <add> os.addRow(row1b); <add> os.addRow(row2); <add> os.addRow(row3a); <add> os.addRow(row3b); <add> os.addRow(row4a); <add> os.addRow(row4b); <add> <add> PathQuery pq = new PathQuery(model); <add> pq.addViews("Department.name", "Department.manager.name", "Department.manager.age", <add> "Department.company.name", "Department.company.vatNumber", <add> "Department.employees.name", "Department.employees.age"); <add> <add> Map pathToQueryNode = new HashMap(); <add> Query q = MainHelper.makeQuery(pq, new HashMap(), pathToQueryNode, null, null); <add> List resultList = os.execute(q, 0, 7, true, true, new HashMap()); <add> Results results = new DummyResults(q, resultList); <add> <add> ExportResultsIterator iter = new ExportResultsIterator(pq, results, pathToQueryNode); <add> <add> JSONResultsIterator jsonIter = new JSONResultsIterator(iter); <add> <add> List<JSONObject> got = new ArrayList<JSONObject>(); <add> for (JSONObject gotRow : new IteratorIterable<JSONObject>(jsonIter)) { <add> got.add(gotRow); <add> } <add> <add> assertEquals(4, got.size()); <add> for (int i = 0; i < jsonStrings.size(); i++) { <add> JSONObject jo = new JSONObject(jsonStrings.get(i)); <add> assertEquals(null, getProblemsComparing(jo, got.get(i))); <add> } <add> } <add> <add> public void testUnsupportedOperations() throws Exception { <add> os.setResultsSize(1); <add> <add> ResultsRow row = new ResultsRow(); <add> row.add(wernhamHogg); <add> <add> os.addRow(row); <add> PathQuery pq = new PathQuery(model); <add> pq.addViews("Company.name"); <add> <add> Map pathToQueryNode = new HashMap(); <add> Query q = MainHelper.makeQuery(pq, new HashMap(), pathToQueryNode, null, null); <add> List resultList = os.execute(q, 0, 1, true, true, new HashMap()); <add> Results results = new DummyResults(q, resultList); <add> <add> ExportResultsIterator iter = new ExportResultsIterator(pq, results, pathToQueryNode); <add> <add> JSONResultsIterator jsonIter = new JSONResultsIterator(iter); <add> <add> <add> try { <add> jsonIter.remove(); <add> fail("No exception was thrown when calling the unsupported method remove"); <add> } catch (AssertionFailedError e) { <add> // rethrow the fail from within the try <add> throw e; <add> } catch (UnsupportedOperationException e) { <add> // Test that this is what we thought would happen. <add> assertEquals("Remove is not implemented in this class", e.getMessage()); <add> } catch (Throwable e){ <add> // All other exceptions are failures <add> fail("Got unexpected error: " + e); <add> } <add> } <add> <add> public void testCurrentArrayIsEmpty() throws Exception { <add> os.setResultsSize(1); <add> <add> ResultsRow row = new ResultsRow(); <add> row.add(wernhamHogg); <add> row.add(david); <add> <add> os.addRow(row); <add> PathQuery pq = new PathQuery(model); <add> pq.addViews("Company.name", "Company.contractors.oldComs.departments.manager.name"); <add> <add> Map pathToQueryNode = new HashMap(); <add> Query q = MainHelper.makeQuery(pq, new HashMap(), pathToQueryNode, null, null); <add> List resultList = os.execute(q, 0, 1, true, true, new HashMap()); <add> Results results = new DummyResults(q, resultList); <add> <add> ExportResultsIterator iter = new ExportResultsIterator(pq, results, pathToQueryNode); <add> <add> JSONResultsIterator jsonIter = new JSONResultsIterator(iter); <add> <add> <add> try { <add> <add> List<JSONObject> got = new ArrayList<JSONObject>(); <add> for (JSONObject gotRow : new IteratorIterable<JSONObject>(jsonIter)) { <add> got.add(gotRow); <add> } <add> fail("No exception was thrown when calling the unsupported method remove"); <add> } catch (AssertionFailedError e) { <add> // rethrow the fail from within the try <add> throw e; <add> } catch (JSONFormattingException e) { <add> // Test that this is what we thought would happen. <add> assertEquals("This array is empty - is the view in the wrong order?", e.getMessage()); <add> } catch (Throwable e){ <add> // All other exceptions are failures <add> fail("Got unexpected error: " + e); <add> } <add> } <add> <add> public void testCurrentMapIsNull() throws Exception { <add> os.setResultsSize(1); <add> <add> ResultsRow row = new ResultsRow(); <add> row.add(sales); <add> row.add(address); <add> <add> os.addRow(row); <add> PathQuery pq = new PathQuery(model); <add> pq.addViews("Department.name", "Department.company.contractors.personalAddress.address"); <add> <add> Map pathToQueryNode = new HashMap(); <add> Query q = MainHelper.makeQuery(pq, new HashMap(), pathToQueryNode, null, null); <add> List resultList = os.execute(q, 0, 1, true, true, new HashMap()); <add> Results results = new DummyResults(q, resultList); <add> <add> ExportResultsIterator iter = new ExportResultsIterator(pq, results, pathToQueryNode); <add> <add> JSONResultsIterator jsonIter = new JSONResultsIterator(iter); <add> <add> <add> try { <add> <add> List<JSONObject> got = new ArrayList<JSONObject>(); <add> for (JSONObject gotRow : new IteratorIterable<JSONObject>(jsonIter)) { <add> got.add(gotRow); <add> } <add> fail("No exception was thrown when calling the unsupported method remove"); <add> } catch (AssertionFailedError e) { <add> // rethrow the fail from within the try <add> throw e; <add> } catch (JSONFormattingException e) { <add> // Test that this is what we thought would happen. <add> assertEquals("This node is not properly initialised (it doesn't have an objectId) - is the view in the right order?", e.getMessage()); <add> } catch (Throwable e){ <add> // All other exceptions are failures <add> fail("Got unexpected error: " + e); <add> } <add> } <add> <add> public void testDateConversion() throws Exception { <add> os.setResultsSize(1); <add> <add> Types typeContainer = new Types(); <add> typeContainer.setId(new Integer(100)); <add> Calendar cal = Calendar.getInstance(); <add> cal.set(108 + 1900, 6, 6); <add> typeContainer.setDateObjType(cal.getTime()); <add> <add> ResultsRow row = new ResultsRow(); <add> row.add(typeContainer); <add> <add> os.addRow(row); <add> PathQuery pq = new PathQuery(model); <add> pq.addViews("Types.dateObjType"); <add> <add> String jsonString = "{ class: 'Types', objectId: 100, dateObjType: '2008-07-06' }"; <add> <add> Map pathToQueryNode = new HashMap(); <add> Query q = MainHelper.makeQuery(pq, new HashMap(), pathToQueryNode, null, null); <add> List resultList = os.execute(q, 0, 1, true, true, new HashMap()); <add> Results results = new DummyResults(q, resultList); <add> <add> ExportResultsIterator iter = new ExportResultsIterator(pq, results, pathToQueryNode); <add> <add> JSONResultsIterator jsonIter = new JSONResultsIterator(iter); <add> <add> List<JSONObject> got = new ArrayList<JSONObject>(); <add> for (JSONObject gotRow : new IteratorIterable<JSONObject>(jsonIter)) { <add> got.add(gotRow); <add> } <add> <add> assertEquals(1, got.size()); <add> JSONObject expected = new JSONObject(jsonString); <add> assertEquals(null, getProblemsComparing(expected, got.get(0))); <add> <add> } <add> <add> public void testThosePlacesOtherTestsCannotReach() throws Exception { <add> // In normal circumstances these exceptions will never be thrown. <add> // These tests are just to check that they will be <add> // should abnormal circumstances ever occur. <add> Path p = null; <add> Path depP = null; <add> Path empsP = null; <add> Path badP = null; <add> try { <add> p = new Path(model, "Manager.name"); <add> depP = new Path(model, "Manager.department"); <add> empsP = new Path(model, "Manager.department.employees"); <add> badP = new BadPath(model, "Manager.name"); <add> } catch (PathException e) { <add> e.printStackTrace(); <add> } <add> ResultElement re = new ResultElement(david, p, false); <add> Map<String, Object> jsonMap = new TreeMap<String, Object>(); <add> <add> <add> ResultsRow row = new ResultsRow(); <add> row.add(david); <add> os.addRow(row); <add> <add> PathQuery pq = new PathQuery(model); <add> pq.addViews("Manager.name"); <add> Map pathToQueryNode = new HashMap(); <add> <add> Query q = MainHelper.makeQuery(pq, new HashMap(), pathToQueryNode, null, null); <add> List resultList = os.execute(q, 0, 1, true, true, new HashMap()); <add> Results results = new DummyResults(q, resultList); <add> <add> ExportResultsIterator iter = new ExportResultsIterator(pq, results, pathToQueryNode); <add> <add> JSONResultsIterator jsonIter = new JSONResultsIterator(iter); <add> <add> <add> jsonMap.put("objectId", 1000); <add> try { <add> jsonIter.setOrCheckClassAndId(re, jsonMap); <add> fail("No exception was thrown, although I tried very hard indeed to cause one"); <add> } catch (AssertionFailedError e) { <add> // rethrow the fail from within the try <add> throw e; <add> } catch (JSONFormattingException e) { <add> // Test that this is what we thought would happen. <add> assertEquals( <add> "This result element ( David Brent 3 Manager) " + <add> "does not belong on this map ({class=Manager, objectId=1000}) - " + <add> "objectIds don't match (1000 != 3)", <add> e.getMessage()); <add> } catch (Throwable e){ <add> // All other exceptions are failures <add> fail("Got unexpected error: " + e); <add> } <add> <add> jsonMap.put("class", "Fool"); <add> try { <add> jsonIter.setOrCheckClassAndId(re, jsonMap); <add> fail("No exception was thrown, although I tried very hard indeed to cause one"); <add> } catch (AssertionFailedError e) { <add> // rethrow the fail from within the try <add> throw e; <add> } catch (JSONFormattingException e) { <add> // Test that this is what we thought would happen. <add> assertEquals( <add> "This result element ( David Brent 3 Manager) " + <add> "does not belong on this map ({class=Fool, objectId=1000}) - " + <add> "classes don't match (Fool != Manager)", <add> e.getMessage()); <add> } catch (Throwable e){ <add> // All other exceptions are failures <add> fail("Got unexpected error: " + e); <add> } <add> jsonMap.clear(); <add> jsonMap.put("name", "Neil"); <add> try { <add> jsonIter.addFieldToMap(re, p, jsonMap); <add> fail("No exception was thrown, although I tried very hard indeed to cause one"); <add> } catch (AssertionFailedError e) { <add> // rethrow the fail from within the try <add> throw e; <add> } catch (JSONFormattingException e) { <add> // Test that this is what we thought would happen. <add> assertEquals( <add> "Trying to set key name as David Brent in {class=Manager, name=Neil, objectId=3} " + <add> "but it already has the value Neil", <add> e.getMessage()); <add> } catch (Throwable e){ <add> // All other exceptions are failures <add> fail("Got unexpected error: " + e); <add> } <add> <add> jsonIter.currentArray = null; <add> try { <add> jsonIter.setCurrentMapFromCurrentArray(re); <add> fail("No exception was thrown, although I tried very hard indeed to cause one"); <add> } catch (AssertionFailedError e) { <add> // rethrow the fail from within the try <add> throw e; <add> } catch (JSONFormattingException e) { <add> // Test that this is what we thought would happen. <add> assertEquals( <add> "Nowhere to put this field", <add> e.getMessage()); <add> } catch (Throwable e){ <add> // All other exceptions are failures <add> fail("Got unexpected error: " + e); <add> } <add> <add> jsonIter.currentArray = null; <add> try { <add> jsonIter.setCurrentMapFromCurrentArray(); <add> fail("No exception was thrown, although I tried very hard indeed to cause one"); <add> } catch (AssertionFailedError e) { <add> // rethrow the fail from within the try <add> throw e; <add> } catch (JSONFormattingException e) { <add> // Test that this is what we thought would happen. <add> assertEquals( <add> "Nowhere to put this reference", <add> e.getMessage()); <add> } catch (Throwable e){ <add> // All other exceptions are failures <add> fail("Got unexpected error: " + e); <add> } <add> <add> jsonMap.put("department", "Clowning About"); <add> jsonIter.currentMap = jsonMap; <add> try { <add> jsonIter.addReferenceToCurrentNode(depP); <add> fail("No exception was thrown, although I tried very hard indeed to cause one"); <add> } catch (AssertionFailedError e) { <add> // rethrow the fail from within the try <add> throw e; <add> } catch (JSONFormattingException e) { <add> // Test that this is what we thought would happen. <add> assertEquals( <add> "Trying to set a reference on department, " + <add> "but this node " + <add> "{class=Manager, department=Clowning About, name=Neil, objectId=3} " + <add> "already has this key set, " + <add> "and to something other than a map " + <add> "(java.lang.String: Clowning About)", <add> e.getMessage()); <add> } catch (Throwable e){ <add> // All other exceptions are failures <add> fail("Got unexpected error: " + e); <add> } <add> <add> jsonIter.currentMap = null; <add> try { <add> jsonIter.addReferenceToCurrentNode(depP); <add> fail("No exception was thrown, although I tried very hard indeed to cause one"); <add> } catch (AssertionFailedError e) { <add> // rethrow the fail from within the try <add> throw e; <add> } catch (JSONFormattingException e) { <add> // Test that this is what we thought would happen. <add> assertEquals( <add> "The current map should have been set " + <add> "by a preceding attribute - " + <add> "is the view in the right order?", <add> e.getMessage()); <add> } catch (Throwable e){ <add> // All other exceptions are failures <add> fail("Got unexpected error: " + e); <add> } <add> <add> jsonMap.put("employees", "Poor Fools"); <add> jsonIter.currentMap = jsonMap; <add> try { <add> jsonIter.addCollectionToCurrentNode(empsP); <add> fail("No exception was thrown, although I tried very hard indeed to cause one"); <add> } catch (AssertionFailedError e) { <add> // rethrow the fail from within the try <add> throw e; <add> } catch (JSONFormattingException e) { <add> // Test that this is what we thought would happen. <add> assertEquals( <add> "Trying to set a collection on employees, " + <add> "but this node " + <add> "{class=Manager, department=Clowning About, employees=Poor Fools, name=Neil, objectId=3} " + <add> "already has this key set to something other than a list " + <add> "(java.lang.String: Poor Fools)", <add> e.getMessage()); <add> } catch (Throwable e){ <add> // All other exceptions are failures <add> fail("Got unexpected error: " + e); <add> } <add> <add> try { <add> jsonIter.addReferencedCellToJsonMap(re, badP, jsonMap); <add> fail("No exception was thrown, although I tried very hard indeed to cause one"); <add> } catch (AssertionFailedError e) { <add> // rethrow the fail from within the try <add> throw e; <add> } catch (JSONFormattingException e) { <add> // Test that this is what we thought would happen. <add> assertEquals( <add> "Bad path type: Manager.name", <add> e.getMessage()); <add> } catch (Throwable e){ <add> // All other exceptions are failures <add> fail("Got unexpected error: " + e); <add> } <add> <add> <add> } <add> <add> private class BadPath extends Path { <add> <add> public BadPath(Model m, String s) throws PathException { <add> super(m, s); <add> } <add> <add> @Override <add> public List<Path> decomposePath() { <add> return Arrays.asList((Path) this); <add> } <add> @Override <add> public boolean endIsAttribute() { <add> return false; <add> } <add> @Override <add> public boolean endIsReference() { <add> return false; <add> } <add> @Override <add> public boolean endIsCollection() { <add> return false; <add> } <add> @Override <add> public boolean isRootPath() { <add> return false; <add> } <add> <add> } <add> <add> <ide> }
Java
mit
75ad6c200d9f44e7614b92da9f205ec2d6102000
0
jheusser/XChange,npomfret/XChange,mmithril/XChange,cinjoff/XChange-1,anwfr/XChange,timmolter/XChange,evdubs/XChange,yarKH/XChange,codeck/XChange,kzbikowski/XChange,TSavo/XChange,Panchen/XChange,coingecko/XChange,Achterhoeker/XChange,habibmasuro/XChange,nopy/XChange,dozd/XChange,joansmith/XChange,okazia/XChange,stevenuray/XChange,Muffon/XChange,LeonidShamis/XChange,chrisrico/XChange,stachon/XChange,sutra/XChange,andre77/XChange,gaborkolozsy/XChange,ww3456/XChange,nivertech/XChange,douggie/XChange,jennieolsson/XChange
/** * Copyright (C) 2012 - 2014 Xeiam LLC http://xeiam.com * * 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.xeiam.xchange.dto.marketdata; import java.math.BigDecimal; import java.util.Date; import org.joda.money.BigMoney; import com.xeiam.xchange.dto.Order.OrderType; /** * Data object representing a Trade */ public final class Trade { /** * Did this trade result from the execution of a bid or a ask? */ private final OrderType type; /** * Amount that was traded */ private final BigDecimal tradableAmount; /** * An identifier that uniquely identifies the tradable */ private final String tradableIdentifier; /** * The currency used to settle the market order transaction */ private final String transactionCurrency; /** * The price */ private final BigMoney price; /** * The timestamp of the trade */ private final Date timestamp; /** * The trade id */ private final String id; /** * The id of the order responsible for execution of this trade */ private final String orderId; /** * @param type * The trade type (BID side or ASK side) * @param tradableAmount * The depth of this trade * @param tradableIdentifier * The exchange identifier (e.g. "BTC/USD") * @param transactionCurrency * The transaction currency (e.g. USD in BTC/USD) * @param price * The price (either the bid or the ask) * @param timestamp * The timestamp when the order was placed. Exchange matching is * usually price first then timestamp asc to clear older orders * @param id * The id of the trade * @param orderId * The id of the corresponding order responsible for execution of this trade */ public Trade(OrderType type, BigDecimal tradableAmount, String tradableIdentifier, String transactionCurrency, BigMoney price, Date timestamp, String id, String orderId) { this.type = type; this.tradableAmount = tradableAmount; this.tradableIdentifier = tradableIdentifier; this.transactionCurrency = transactionCurrency; this.price = price; this.timestamp = timestamp; this.id = id; this.orderId = orderId; } /** * @param type * The trade type (BID side or ASK side) * @param tradableAmount * The depth of this trade * @param tradableIdentifier * The exchange identifier (e.g. "BTC/USD") * @param transactionCurrency * The transaction currency (e.g. USD in BTC/USD) * @param price * The price (either the bid or the ask) * @param timestamp * The timestamp when the order was placed. Exchange matching is * usually price first then timestamp asc to clear older orders * @param id * The id of the trade */ public Trade(OrderType type, BigDecimal tradableAmount, String tradableIdentifier, String transactionCurrency, BigMoney price, Date timestamp, String id) { this(type, tradableAmount, tradableIdentifier, transactionCurrency, price, timestamp, id, null); } public OrderType getType() { return type; } public BigDecimal getTradableAmount() { return tradableAmount; } public String getTradableIdentifier() { return tradableIdentifier; } public String getTransactionCurrency() { return transactionCurrency; } public BigMoney getPrice() { return price; } public Date getTimestamp() { return timestamp; } public String getId() { return id; } public String getOrderId() { return orderId; } @Override public String toString() { return "Trade [type=" + type + ", tradableAmount=" + tradableAmount + ", tradableIdentifier=" + tradableIdentifier + ", transactionCurrency=" + transactionCurrency + ", price=" + price + ", timestamp=" + timestamp + ", id=" + id + ", orderId=" + orderId + "]"; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } return this.id.equals(((Trade) o).getId()); } @Override public int hashCode() { return id.hashCode(); } }
xchange-core/src/main/java/com/xeiam/xchange/dto/marketdata/Trade.java
/** * Copyright (C) 2012 - 2014 Xeiam LLC http://xeiam.com * * 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.xeiam.xchange.dto.marketdata; import java.math.BigDecimal; import java.util.Date; import org.joda.money.BigMoney; import com.xeiam.xchange.dto.Order.OrderType; /** * Data object representing a Trade */ public final class Trade { /** * Did this trade result from the execution of a bid or a ask? */ private final OrderType type; /** * Amount that was traded */ private final BigDecimal tradableAmount; /** * An identifier that uniquely identifies the tradable */ private final String tradableIdentifier; /** * The currency used to settle the market order transaction */ private final String transactionCurrency; /** * The price */ private final BigMoney price; /** * The timestamp of the trade */ private final Date timestamp; /** * The trade id */ private final String id; /** * The id of the order responsible for execution of this trade */ private final String orderId; /** * @param type * The trade type (BID side or ASK side) * @param tradableAmount * The depth of this trade * @param tradableIdentifier * The exchange identifier (e.g. "BTC/USD") * @param transactionCurrency * The transaction currency (e.g. USD in BTC/USD) * @param price * The price (either the bid or the ask) * @param timestamp * The timestamp when the order was placed. Exchange matching is * usually price first then timestamp asc to clear older orders * @param id * The id of the trade * @param orderId * The id of the corresponding order responsible for execution of this trade */ public Trade(OrderType type, BigDecimal tradableAmount, String tradableIdentifier, String transactionCurrency, BigMoney price, Date timestamp, String id, String orderId) { this.type = type; this.tradableAmount = tradableAmount; this.tradableIdentifier = tradableIdentifier; this.transactionCurrency = transactionCurrency; this.price = price; this.timestamp = timestamp; this.id = id; this.orderId = orderId; } /** * @param type * The trade type (BID side or ASK side) * @param tradableAmount * The depth of this trade * @param tradableIdentifier * The exchange identifier (e.g. "BTC/USD") * @param transactionCurrency * The transaction currency (e.g. USD in BTC/USD) * @param price * The price (either the bid or the ask) * @param timestamp * The timestamp when the order was placed. Exchange matching is * usually price first then timestamp asc to clear older orders * @param id * The id of the trade */ public Trade(OrderType type, BigDecimal tradableAmount, String tradableIdentifier, String transactionCurrency, BigMoney price, Date timestamp, String id) { this(type, tradableAmount, tradableIdentifier, transactionCurrency, price, timestamp, id, null); } public OrderType getType() { return type; } public BigDecimal getTradableAmount() { return tradableAmount; } public String getTradableIdentifier() { return tradableIdentifier; } public String getTransactionCurrency() { return transactionCurrency; } public BigMoney getPrice() { return price; } public Date getTimestamp() { return timestamp; } public String getId() { return id; } @Override public String toString() { return "Trade [type=" + type + ", tradableAmount=" + tradableAmount + ", tradableIdentifier=" + tradableIdentifier + ", transactionCurrency=" + transactionCurrency + ", price=" + price + ", timestamp=" + timestamp + ", id=" + id + ", orderId=" + orderId + "]"; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } return this.id.equals(((Trade) o).getId()); } @Override public int hashCode() { return id.hashCode(); } }
added the getter for orderId
xchange-core/src/main/java/com/xeiam/xchange/dto/marketdata/Trade.java
added the getter for orderId
<ide><path>change-core/src/main/java/com/xeiam/xchange/dto/marketdata/Trade.java <ide> <ide> return id; <ide> } <add> <add> public String getOrderId() { <add> <add> return orderId; <add> } <ide> <ide> @Override <ide> public String toString() {
Java
apache-2.0
b82746f0ead13314d26085b27335681f287ecd30
0
freiheit-com/fuava_simplebatch
/** * Copyright 2015 freiheit.com technologies gmbh * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package com.freiheit.fuava.simplebatch.processor; import java.util.List; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.freiheit.fuava.simplebatch.result.Result; import com.google.common.base.Function; import com.google.common.collect.FluentIterable; import com.google.common.collect.ImmutableList; import com.google.common.collect.Iterables; /** * A processor implementation which delegates processing of lists of * (successful) values to a function. * * If persisting of a batch failed, it will be divided into singleton batches * and retried. * * You have to ensure that aborting and retying the function will not lead to * illegal states. * * If your function persists to databases for example, you may need to ensure * that your function opens and closes the toplevel transaction and rolls back * for <b>all</b> exceptions. * * * @param <Input> * @param <Output> */ class RetryingProcessor<Input, Output, ProcessorResult> implements Processor<Input, Output, ProcessorResult> { private final Function<List<Output>, List<ProcessorResult>> _func; private static final Logger LOG = LoggerFactory.getLogger( RetryingProcessor.class ); /** * Creates a new processor that delegates to the given function. * * Note that you need to ensure, that the input and output lists correspond * to each other and that the function supports retrying. For details, see * the class documentation. * * You have to ensure that your input and output lists have the same amount * of rows. The processor will assume that each position of input and output * corresponds to each other and will associate results accordingly. * * Note that this function only gets the successfully processed Output * values. If you need to persist all, you need to implement the Persistence * interface yourself. * * @param func */ public RetryingProcessor( final Function<List<Output>, List<ProcessorResult>> func ) { _func = func; } @Override public Iterable<Result<Input, ProcessorResult>> process( final Iterable<Result<Input, Output>> inputs ) { final List<Result<Input, Output>> inputList = ImmutableList.copyOf( inputs ); if ( inputList.isEmpty() ) { return ImmutableList.of(); } try { return doPersist( inputList ); } catch ( final Throwable t ) { if ( inputList.size() == 1 ) { final Result<Input, Output> result = inputList.get( 0 ); return ImmutableList.of( Result.<Input, ProcessorResult> builder( result ).failed( t ) ); } LOG.info( "Caught Exception during processing of batch with " + inputList.size() + " items, will RETRY in single item batches", t ); final ImmutableList.Builder<Result<Input, ProcessorResult>> retriedResults = ImmutableList.builder(); for ( final Result<Input, Output> input : inputList ) { final Iterable<Result<Input, ProcessorResult>> outputs = process( ImmutableList.of( input ) ); if ( Iterables.isEmpty( outputs ) ) { throw new IllegalStateException( "processing of singletons must never lead to empty lists here" ); } retriedResults.addAll( outputs ); } return retriedResults.build(); } } private Iterable<Result<Input, ProcessorResult>> doPersist( final Iterable<Result<Input, Output>> iterable ) { final ImmutableList<Result<Input, Output>> successes = FluentIterable.from( iterable ).filter( Result::isSuccess ).toList(); final ImmutableList<Result<Input, Output>> fails = FluentIterable.from( iterable ).filter( Result::isFailed ).toList(); final ImmutableList<Output> outputs = FluentIterable.from( successes ).transform( Result::getOutput ).toList(); final List<ProcessorResult> persistenceResults = outputs.isEmpty() ? ImmutableList.of() : this._func.apply( outputs ); if ( persistenceResults.size() != outputs.size() || persistenceResults.size() != successes.size() ) { throw new IllegalStateException( "persistence results of unexpected size produced by " + this._func ); } final ImmutableList.Builder<Result<Input, ProcessorResult>> b = ImmutableList.builder(); for ( int i = 0; i < outputs.size(); i++ ) { final Result<Input, Output> processingResult = successes.get( i ); final ProcessorResult persistenceResult = persistenceResults.get( i ); b.add( Result.<Input, ProcessorResult> builder( processingResult ).withOutput( persistenceResult ).success() ); } for ( final Result<Input, Output> failed : fails ) { b.add( Result.<Input, ProcessorResult> builder( failed ).failed() ); } return b.build(); } }
core/src/main/java/com/freiheit/fuava/simplebatch/processor/RetryingProcessor.java
/** * Copyright 2015 freiheit.com technologies gmbh * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package com.freiheit.fuava.simplebatch.processor; import java.util.List; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.freiheit.fuava.simplebatch.result.Result; import com.google.common.base.Function; import com.google.common.collect.FluentIterable; import com.google.common.collect.ImmutableList; import com.google.common.collect.Iterables; /** * A processor implementation which delegates processing of lists of * (successful) values to a function. * * If persisting of a batch failed, it will be divided into singleton batches * and retried. * * You have to ensure that aborting and retying the function will not lead to * illegal states. * * If your function persists to databases for example, you may need to ensure * that your function opens and closes the toplevel transaction and rolls back * for <b>all</b> exceptions. * * * @param <Input> * @param <Output> */ class RetryingProcessor<Input, Output, ProcessorResult> implements Processor<Input, Output, ProcessorResult> { private final Function<List<Output>, List<ProcessorResult>> _func; private static final Logger LOG = LoggerFactory.getLogger( RetryingProcessor.class ); /** * Creates a new processor that delegates to the given function. * * Note that you need to ensure, that the input and output lists correspond * to each other and that the function supports retrying. For details, see * the class documentation. * * You have to ensure that your input and output lists have the same amount * of rows. The processor will assume that each position of input and output * corresponds to each other and will associate results accordingly. * * Note that this function only gets the successfully processed Output * values. If you need to persist all, you need to implement the Persistence * interface yourself. * * @param func */ public RetryingProcessor( final Function<List<Output>, List<ProcessorResult>> func ) { _func = func; } @Override public Iterable<Result<Input, ProcessorResult>> process( final Iterable<Result<Input, Output>> inputs ) { final List<Result<Input, Output>> inputList = ImmutableList.copyOf( inputs ); if ( inputList.isEmpty() ) { return ImmutableList.of(); } try { return doPersist( inputList ); } catch ( final Throwable t ) { if ( inputList.size() == 1 ) { final Result<Input, Output> result = inputList.get( 0 ); return ImmutableList.of( Result.<Input, ProcessorResult> builder( result ).failed( t ) ); } LOG.info( "Caught Exception during processing of batch with " + inputList.size() + " items, will RETRY in single item batches", t ); final ImmutableList.Builder<Result<Input, ProcessorResult>> retriedResults = ImmutableList.builder(); for ( final Result<Input, Output> input : inputList ) { final Iterable<Result<Input, ProcessorResult>> outputs = process( ImmutableList.of( input ) ); if ( Iterables.isEmpty( outputs ) ) { throw new IllegalStateException( "processing of singletons must never lead to empty lists here" ); } retriedResults.addAll( outputs ); } return retriedResults.build(); } } private Iterable<Result<Input, ProcessorResult>> doPersist( final Iterable<Result<Input, Output>> iterable ) { final ImmutableList<Result<Input, Output>> successes = FluentIterable.from( iterable ).filter( Result::isSuccess ).toList(); final ImmutableList<Result<Input, Output>> fails = FluentIterable.from( iterable ).filter( Result::isFailed ).toList(); final ImmutableList<Output> outputs = FluentIterable.from( successes ).transform( Result::getOutput ).toList(); final List<ProcessorResult> persistenceResults = outputs.isEmpty() ? ImmutableList.of() : this._func.apply( outputs ); if ( persistenceResults.size() != outputs.size() || persistenceResults.size() != successes.size() ) { throw new IllegalStateException( "persistence results of unexpected size" ); } final ImmutableList.Builder<Result<Input, ProcessorResult>> b = ImmutableList.builder(); for ( int i = 0; i < outputs.size(); i++ ) { final Result<Input, Output> processingResult = successes.get( i ); final ProcessorResult persistenceResult = persistenceResults.get( i ); b.add( Result.<Input, ProcessorResult> builder( processingResult ).withOutput( persistenceResult ).success() ); } for ( final Result<Input, Output> failed : fails ) { b.add( Result.<Input, ProcessorResult> builder( failed ).failed() ); } return b.build(); } }
better logging
core/src/main/java/com/freiheit/fuava/simplebatch/processor/RetryingProcessor.java
better logging
<ide><path>ore/src/main/java/com/freiheit/fuava/simplebatch/processor/RetryingProcessor.java <ide> : this._func.apply( outputs ); <ide> <ide> if ( persistenceResults.size() != outputs.size() || persistenceResults.size() != successes.size() ) { <del> throw new IllegalStateException( "persistence results of unexpected size" ); <add> throw new IllegalStateException( "persistence results of unexpected size produced by " + this._func ); <ide> } <ide> final ImmutableList.Builder<Result<Input, ProcessorResult>> b = ImmutableList.builder(); <ide>
Java
apache-2.0
90ead92bd20f4ea31f8212f46b6632a2ad45fb52
0
sotorrent/so-posthistory-extractor
package de.unitrier.st.soposthistory; import de.unitrier.st.soposthistory.history.PostHistoryIterator; import org.apache.commons.cli.*; import java.nio.file.Path; import java.nio.file.Paths; class MainIterator { // TODO : Also store n-grams of code blocks in database? -> would result in a very large database // TODO: Evolution of question title (PostHistoryTypeId 1)? // TODO: Use CreationDate instead of PostHistoryId to sort versions (see broken_entries in analysis_postversion_edit_timespan.R)? public static void main (String[] args) { System.out.println("SOPostHistory (Iterator Mode)"); Options options = new Options(); Option dataDirOption = new Option("d", "data-dir", true, "path to data directory (used to store post id lists"); dataDirOption.setRequired(true); options.addOption(dataDirOption); Option hibernateConfigFileOption = new Option("h", "hibernate-config", true, "path to hibernate config file"); hibernateConfigFileOption.setRequired(true); options.addOption(hibernateConfigFileOption); Option partitionCountOption = new Option("p", "partition-count", true, "number of partitions created from post id lists (one worker thread per partition, default value: 4)"); partitionCountOption.setRequired(false); options.addOption(partitionCountOption); Option tagsOption = new Option("t", "tags", true, "tags for filtering questions and answers (separated by a space)"); tagsOption.setRequired(false); options.addOption(tagsOption); CommandLineParser commandLineParser = new DefaultParser(); HelpFormatter commandLineFormatter = new HelpFormatter(); CommandLine commandLine; try { commandLine = commandLineParser.parse(options, args); } catch (ParseException e) { System.out.println(e.getMessage()); commandLineFormatter.printHelp("SOPostHistory (Iterator Mode)", options); System.exit(1); return; } Path dataDirPath = Paths.get(commandLine.getOptionValue("data-dir")); Path hibernateConfigFilePath = Paths.get(commandLine.getOptionValue("hibernate-config")); String[] tags = {}; // no tags provided -> all posts int partitionCount = 4; if (commandLine.hasOption("tags")) { tags = commandLine.getOptionValue("tags").split(" "); } if (commandLine.hasOption("partition-count")) { partitionCount = Integer.parseInt(commandLine.getOptionValue("partition-count")); } PostHistoryIterator.createSessionFactory(hibernateConfigFilePath); PostHistoryIterator postHistoryIterator = new PostHistoryIterator( dataDirPath, "all", partitionCount, tags ); postHistoryIterator.extractSaveAndSplitPostIds(); // including split postHistoryIterator.extractDataFromPostHistory("questions"); postHistoryIterator.extractDataFromPostHistory("answers"); PostHistoryIterator.sessionFactory.close(); } }
src/de/unitrier/st/soposthistory/MainIterator.java
package de.unitrier.st.soposthistory; import de.unitrier.st.soposthistory.history.PostHistoryIterator; import org.apache.commons.cli.*; import java.nio.file.Path; import java.nio.file.Paths; class MainIterator { // TODO : Also store n-grams of code blocks in database? -> would result in a very large database // TODO: Evolution of question title (PostHistoryTypeId 1)? // TODO: Use CreationDate instead of PostHistoryId to sort versions? public static void main (String[] args) { System.out.println("SOPostHistory (Iterator Mode)"); Options options = new Options(); Option dataDirOption = new Option("d", "data-dir", true, "path to data directory (used to store post id lists"); dataDirOption.setRequired(true); options.addOption(dataDirOption); Option hibernateConfigFileOption = new Option("h", "hibernate-config", true, "path to hibernate config file"); hibernateConfigFileOption.setRequired(true); options.addOption(hibernateConfigFileOption); Option partitionCountOption = new Option("p", "partition-count", true, "number of partitions created from post id lists (one worker thread per partition, default value: 4)"); partitionCountOption.setRequired(false); options.addOption(partitionCountOption); Option tagsOption = new Option("t", "tags", true, "tags for filtering questions and answers (separated by a space)"); tagsOption.setRequired(false); options.addOption(tagsOption); CommandLineParser commandLineParser = new DefaultParser(); HelpFormatter commandLineFormatter = new HelpFormatter(); CommandLine commandLine; try { commandLine = commandLineParser.parse(options, args); } catch (ParseException e) { System.out.println(e.getMessage()); commandLineFormatter.printHelp("SOPostHistory (Iterator Mode)", options); System.exit(1); return; } Path dataDirPath = Paths.get(commandLine.getOptionValue("data-dir")); Path hibernateConfigFilePath = Paths.get(commandLine.getOptionValue("hibernate-config")); String[] tags = {}; // no tags provided -> all posts int partitionCount = 4; if (commandLine.hasOption("tags")) { tags = commandLine.getOptionValue("tags").split(" "); } if (commandLine.hasOption("partition-count")) { partitionCount = Integer.parseInt(commandLine.getOptionValue("partition-count")); } PostHistoryIterator.createSessionFactory(hibernateConfigFilePath); PostHistoryIterator postHistoryIterator = new PostHistoryIterator( dataDirPath, "all", partitionCount, tags ); postHistoryIterator.extractSaveAndSplitPostIds(); // including split postHistoryIterator.extractDataFromPostHistory("questions"); postHistoryIterator.extractDataFromPostHistory("answers"); PostHistoryIterator.sessionFactory.close(); } }
Update TODO
src/de/unitrier/st/soposthistory/MainIterator.java
Update TODO
<ide><path>rc/de/unitrier/st/soposthistory/MainIterator.java <ide> class MainIterator { <ide> // TODO : Also store n-grams of code blocks in database? -> would result in a very large database <ide> // TODO: Evolution of question title (PostHistoryTypeId 1)? <del> // TODO: Use CreationDate instead of PostHistoryId to sort versions? <add> // TODO: Use CreationDate instead of PostHistoryId to sort versions (see broken_entries in analysis_postversion_edit_timespan.R)? <ide> <ide> public static void main (String[] args) { <ide> System.out.println("SOPostHistory (Iterator Mode)");
Java
apache-2.0
da8dfbd82dc749d94f1a653d4b76e2a2c76e210b
0
robertwb/incubator-beam,lukecwik/incubator-beam,lukecwik/incubator-beam,robertwb/incubator-beam,apache/beam,robertwb/incubator-beam,lukecwik/incubator-beam,RyanSkraba/beam,lukecwik/incubator-beam,RyanSkraba/beam,RyanSkraba/beam,apache/beam,chamikaramj/beam,robertwb/incubator-beam,robertwb/incubator-beam,robertwb/incubator-beam,apache/beam,lukecwik/incubator-beam,RyanSkraba/beam,apache/beam,RyanSkraba/beam,chamikaramj/beam,chamikaramj/beam,apache/beam,apache/beam,lukecwik/incubator-beam,lukecwik/incubator-beam,lukecwik/incubator-beam,chamikaramj/beam,apache/beam,iemejia/incubator-beam,apache/beam,robertwb/incubator-beam,chamikaramj/beam,robertwb/incubator-beam,iemejia/incubator-beam,chamikaramj/beam,robertwb/incubator-beam,apache/beam,chamikaramj/beam,apache/beam,lukecwik/incubator-beam,lukecwik/incubator-beam,chamikaramj/beam,RyanSkraba/beam,apache/beam,chamikaramj/beam,RyanSkraba/beam,chamikaramj/beam,robertwb/incubator-beam
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.beam.runners.spark.structuredstreaming.translation.helpers; import static org.apache.spark.sql.types.DataTypes.BinaryType; import java.io.ByteArrayInputStream; import java.io.Serializable; import java.util.ArrayList; import java.util.List; import java.util.Objects; import org.apache.beam.runners.spark.structuredstreaming.translation.SchemaHelpers; import org.apache.beam.sdk.coders.Coder; import org.apache.beam.sdk.util.WindowedValue; import org.apache.beam.sdk.values.KV; import org.apache.spark.sql.Encoder; import org.apache.spark.sql.Encoders; import org.apache.spark.sql.catalyst.analysis.GetColumnByOrdinal; import org.apache.spark.sql.catalyst.encoders.ExpressionEncoder; import org.apache.spark.sql.catalyst.expressions.BoundReference; import org.apache.spark.sql.catalyst.expressions.Cast; import org.apache.spark.sql.catalyst.expressions.Expression; import org.apache.spark.sql.catalyst.expressions.NonSQLExpression; import org.apache.spark.sql.catalyst.expressions.UnaryExpression; import org.apache.spark.sql.catalyst.expressions.codegen.Block; import org.apache.spark.sql.catalyst.expressions.codegen.CodeGenerator; import org.apache.spark.sql.catalyst.expressions.codegen.CodegenContext; import org.apache.spark.sql.catalyst.expressions.codegen.ExprCode; import org.apache.spark.sql.types.DataType; import org.apache.spark.sql.types.ObjectType; import scala.StringContext; import scala.collection.JavaConversions; import scala.reflect.ClassTag; import scala.reflect.ClassTag$; /** {@link Encoders} utility class. */ public class EncoderHelpers { /* --------- Bridges from Beam Coders to Spark Encoders */ /** * Wrap a Beam coder into a Spark Encoder using Catalyst Expression Encoders (which uses java code * generation). */ public static <T> Encoder<T> fromBeamCoder(Coder<T> beamCoder) { List<Expression> serialiserList = new ArrayList<>(); Class<? super T> claz = beamCoder.getEncodedTypeDescriptor().getRawType(); serialiserList.add( new EncodeUsingBeamCoder<>(new BoundReference(0, new ObjectType(claz), true), beamCoder)); ClassTag<T> classTag = ClassTag$.MODULE$.apply(claz); return new ExpressionEncoder<>( SchemaHelpers.binarySchema(), false, JavaConversions.collectionAsScalaIterable(serialiserList).toSeq(), new DecodeUsingBeamCoder<>( new Cast(new GetColumnByOrdinal(0, BinaryType), BinaryType), classTag, beamCoder), classTag); } /** * Catalyst Expression that serializes elements using Beam {@link Coder}. * * @param <T>: Type of elements ot be serialized. */ public static class EncodeUsingBeamCoder<T> extends UnaryExpression implements NonSQLExpression, Serializable { private Expression child; private Coder<T> beamCoder; public EncodeUsingBeamCoder(Expression child, Coder<T> beamCoder) { this.child = child; this.beamCoder = beamCoder; } @Override public Expression child() { return child; } @Override public ExprCode doGenCode(CodegenContext ctx, ExprCode ev) { // Code to serialize. String accessCode = ctx.addReferenceObj("beamCoder", beamCoder, beamCoder.getClass().getName()); ExprCode input = child.genCode(ctx); /* CODE GENERATED byte[] ${ev.value}; try { java.io.ByteArrayOutputStream baos = new java.io.ByteArrayOutputStream(); if ({input.isNull}) ${ev.value} = null; else{ $beamCoder.encode(${input.value}, baos); ${ev.value} = baos.toByteArray(); } } catch (Exception e) { throw org.apache.beam.sdk.util.UserCodeException.wrap(e); } */ List<String> parts = new ArrayList<>(); parts.add("byte[] "); parts.add( ";try { java.io.ByteArrayOutputStream baos = new java.io.ByteArrayOutputStream(); if ("); parts.add(") "); parts.add(" = null; else{"); parts.add(".encode("); parts.add(", baos); "); parts.add( " = baos.toByteArray();}} catch (Exception e) {throw org.apache.beam.sdk.util.UserCodeException.wrap(e);}"); StringContext sc = new StringContext(JavaConversions.collectionAsScalaIterable(parts).toSeq()); List<Object> args = new ArrayList<>(); args.add(ev.value()); args.add(input.isNull()); args.add(ev.value()); args.add(accessCode); args.add(input.value()); args.add(ev.value()); Block code = (new Block.BlockHelper(sc)).code(JavaConversions.collectionAsScalaIterable(args).toSeq()); return ev.copy(input.code().$plus(code), input.isNull(), ev.value()); } @Override public DataType dataType() { return BinaryType; } @Override public Object productElement(int n) { switch (n) { case 0: return child; case 1: return beamCoder; default: throw new ArrayIndexOutOfBoundsException("productElement out of bounds"); } } @Override public int productArity() { return 2; } @Override public boolean canEqual(Object that) { return (that instanceof EncodeUsingBeamCoder); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } EncodeUsingBeamCoder<?> that = (EncodeUsingBeamCoder<?>) o; return beamCoder.equals(that.beamCoder) && child.equals(that.child); } @Override public int hashCode() { return Objects.hash(super.hashCode(), child, beamCoder); } } /** * Catalyst Expression that deserializes elements using Beam {@link Coder}. * * @param <T>: Type of elements ot be serialized. */ public static class DecodeUsingBeamCoder<T> extends UnaryExpression implements NonSQLExpression, Serializable { private Expression child; private ClassTag<T> classTag; private Coder<T> beamCoder; public DecodeUsingBeamCoder(Expression child, ClassTag<T> classTag, Coder<T> beamCoder) { this.child = child; this.classTag = classTag; this.beamCoder = beamCoder; } @Override public Expression child() { return child; } @Override public ExprCode doGenCode(CodegenContext ctx, ExprCode ev) { // Code to deserialize. String accessCode = ctx.addReferenceObj("beamCoder", beamCoder, beamCoder.getClass().getName()); ExprCode input = child.genCode(ctx); String javaType = CodeGenerator.javaType(dataType()); /* CODE GENERATED: final $javaType ${ev.value} try { ${ev.value} = ${input.isNull} ? ${CodeGenerator.defaultValue(dataType)} : ($javaType) $beamCoder.decode(new java.io.ByteArrayInputStream(${input.value})); } catch (Exception e) { throw org.apache.beam.sdk.util.UserCodeException.wrap(e); } */ List<String> parts = new ArrayList<>(); parts.add("final "); parts.add(" "); parts.add(";try { "); parts.add(" = "); parts.add("? "); parts.add(": ("); parts.add(") "); parts.add(".decode(new java.io.ByteArrayInputStream("); parts.add( ")); } catch (Exception e) {throw org.apache.beam.sdk.util.UserCodeException.wrap(e);}"); StringContext sc = new StringContext(JavaConversions.collectionAsScalaIterable(parts).toSeq()); List<Object> args = new ArrayList<>(); args.add(javaType); args.add(ev.value()); args.add(ev.value()); args.add(input.isNull()); args.add(CodeGenerator.defaultValue(dataType(), false)); args.add(javaType); args.add(accessCode); args.add(input.value()); Block code = (new Block.BlockHelper(sc)).code(JavaConversions.collectionAsScalaIterable(args).toSeq()); return ev.copy(input.code().$plus(code), input.isNull(), ev.value()); } @Override public Object nullSafeEval(Object input) { try { return beamCoder.decode(new ByteArrayInputStream((byte[]) input)); } catch (Exception e) { throw new IllegalStateException("Error decoding bytes for coder: " + beamCoder, e); } } @Override public DataType dataType() { return new ObjectType(classTag.runtimeClass()); } @Override public Object productElement(int n) { switch (n) { case 0: return child; case 1: return classTag; case 2: return beamCoder; default: throw new ArrayIndexOutOfBoundsException("productElement out of bounds"); } } @Override public int productArity() { return 3; } @Override public boolean canEqual(Object that) { return (that instanceof DecodeUsingBeamCoder); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } DecodeUsingBeamCoder<?> that = (DecodeUsingBeamCoder<?>) o; return child.equals(that.child) && classTag.equals(that.classTag) && beamCoder.equals(that.beamCoder); } @Override public int hashCode() { return Objects.hash(super.hashCode(), child, classTag, beamCoder); } } }
runners/spark/src/main/java/org/apache/beam/runners/spark/structuredstreaming/translation/helpers/EncoderHelpers.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.beam.runners.spark.structuredstreaming.translation.helpers; import static org.apache.spark.sql.types.DataTypes.BinaryType; import java.io.ByteArrayInputStream; import java.io.Serializable; import java.util.ArrayList; import java.util.List; import java.util.Objects; import org.apache.beam.runners.spark.structuredstreaming.translation.SchemaHelpers; import org.apache.beam.sdk.coders.Coder; import org.apache.beam.sdk.util.WindowedValue; import org.apache.beam.sdk.values.KV; import org.apache.spark.sql.Encoder; import org.apache.spark.sql.Encoders; import org.apache.spark.sql.catalyst.analysis.GetColumnByOrdinal; import org.apache.spark.sql.catalyst.encoders.ExpressionEncoder; import org.apache.spark.sql.catalyst.expressions.BoundReference; import org.apache.spark.sql.catalyst.expressions.Cast; import org.apache.spark.sql.catalyst.expressions.Expression; import org.apache.spark.sql.catalyst.expressions.NonSQLExpression; import org.apache.spark.sql.catalyst.expressions.UnaryExpression; import org.apache.spark.sql.catalyst.expressions.codegen.Block; import org.apache.spark.sql.catalyst.expressions.codegen.CodeGenerator; import org.apache.spark.sql.catalyst.expressions.codegen.CodegenContext; import org.apache.spark.sql.catalyst.expressions.codegen.ExprCode; import org.apache.spark.sql.types.DataType; import org.apache.spark.sql.types.ObjectType; import scala.StringContext; import scala.collection.JavaConversions; import scala.reflect.ClassTag; import scala.reflect.ClassTag$; /** {@link Encoders} utility class. */ public class EncoderHelpers { // 1. use actual class and not object to avoid Spark fallback to GenericRowWithSchema. // 2. use raw class because only raw classes can be used with kryo. Cast to Class<T> to allow // the type inference mechanism to infer for ex Encoder<WindowedValue<T>> to get back the type // checking /* --------- Encoders for internal spark runner objects */ /** * Get a bytes {@link Encoder} for {@link WindowedValue}. Bytes serialisation is issued by Kryo */ @SuppressWarnings("unchecked") public static <T> Encoder<T> windowedValueEncoder() { return Encoders.kryo((Class<T>) WindowedValue.class); } /** Get a bytes {@link Encoder} for {@link KV}. Bytes serialisation is issued by Kryo */ @SuppressWarnings("unchecked") public static <T> Encoder<T> kvEncoder() { return Encoders.kryo((Class<T>) KV.class); } /** Get a bytes {@link Encoder} for {@code T}. Bytes serialisation is issued by Kryo */ @SuppressWarnings("unchecked") public static <T> Encoder<T> genericEncoder() { return Encoders.kryo((Class<T>) Object.class); } /* */ /** Get a bytes {@link Encoder} for {@link Tuple2}. Bytes serialisation is issued by Kryo */ /* public static <T1, T2> Encoder<Tuple2<T1, T2>> tuple2Encoder() { return Encoders.tuple(EncoderHelpers.genericEncoder(), EncoderHelpers.genericEncoder()); } */ /* --------- Bridges from Beam Coders to Spark Encoders */ /** * Wrap a Beam coder into a Spark Encoder using Catalyst Expression Encoders (which uses java code * generation). */ public static <T> Encoder<T> fromBeamCoder(Coder<T> beamCoder) { List<Expression> serialiserList = new ArrayList<>(); Class<? super T> claz = beamCoder.getEncodedTypeDescriptor().getRawType(); serialiserList.add( new EncodeUsingBeamCoder<>(new BoundReference(0, new ObjectType(claz), true), beamCoder)); ClassTag<T> classTag = ClassTag$.MODULE$.apply(claz); return new ExpressionEncoder<>( SchemaHelpers.binarySchema(), false, JavaConversions.collectionAsScalaIterable(serialiserList).toSeq(), new DecodeUsingBeamCoder<>( new Cast(new GetColumnByOrdinal(0, BinaryType), BinaryType), classTag, beamCoder), classTag); } /** * Catalyst Expression that serializes elements using Beam {@link Coder}. * * @param <T>: Type of elements ot be serialized. */ public static class EncodeUsingBeamCoder<T> extends UnaryExpression implements NonSQLExpression, Serializable { private Expression child; private Coder<T> beamCoder; public EncodeUsingBeamCoder(Expression child, Coder<T> beamCoder) { this.child = child; this.beamCoder = beamCoder; } @Override public Expression child() { return child; } @Override public ExprCode doGenCode(CodegenContext ctx, ExprCode ev) { // Code to serialize. String accessCode = ctx.addReferenceObj("beamCoder", beamCoder, beamCoder.getClass().getName()); ExprCode input = child.genCode(ctx); /* CODE GENERATED byte[] ${ev.value}; try { java.io.ByteArrayOutputStream baos = new java.io.ByteArrayOutputStream(); if ({input.isNull}) ${ev.value} = null; else{ $beamCoder.encode(${input.value}, baos); ${ev.value} = baos.toByteArray(); } } catch (Exception e) { throw org.apache.beam.sdk.util.UserCodeException.wrap(e); } */ List<String> parts = new ArrayList<>(); parts.add("byte[] "); parts.add( ";try { java.io.ByteArrayOutputStream baos = new java.io.ByteArrayOutputStream(); if ("); parts.add(") "); parts.add(" = null; else{"); parts.add(".encode("); parts.add(", baos); "); parts.add( " = baos.toByteArray();}} catch (Exception e) {throw org.apache.beam.sdk.util.UserCodeException.wrap(e);}"); StringContext sc = new StringContext(JavaConversions.collectionAsScalaIterable(parts).toSeq()); List<Object> args = new ArrayList<>(); args.add(ev.value()); args.add(input.isNull()); args.add(ev.value()); args.add(accessCode); args.add(input.value()); args.add(ev.value()); Block code = (new Block.BlockHelper(sc)).code(JavaConversions.collectionAsScalaIterable(args).toSeq()); return ev.copy(input.code().$plus(code), input.isNull(), ev.value()); } @Override public DataType dataType() { return BinaryType; } @Override public Object productElement(int n) { switch (n) { case 0: return child; case 1: return beamCoder; default: throw new ArrayIndexOutOfBoundsException("productElement out of bounds"); } } @Override public int productArity() { return 2; } @Override public boolean canEqual(Object that) { return (that instanceof EncodeUsingBeamCoder); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } EncodeUsingBeamCoder<?> that = (EncodeUsingBeamCoder<?>) o; return beamCoder.equals(that.beamCoder) && child.equals(that.child); } @Override public int hashCode() { return Objects.hash(super.hashCode(), child, beamCoder); } } /** * Catalyst Expression that deserializes elements using Beam {@link Coder}. * * @param <T>: Type of elements ot be serialized. */ public static class DecodeUsingBeamCoder<T> extends UnaryExpression implements NonSQLExpression, Serializable { private Expression child; private ClassTag<T> classTag; private Coder<T> beamCoder; public DecodeUsingBeamCoder(Expression child, ClassTag<T> classTag, Coder<T> beamCoder) { this.child = child; this.classTag = classTag; this.beamCoder = beamCoder; } @Override public Expression child() { return child; } @Override public ExprCode doGenCode(CodegenContext ctx, ExprCode ev) { // Code to deserialize. String accessCode = ctx.addReferenceObj("beamCoder", beamCoder, beamCoder.getClass().getName()); ExprCode input = child.genCode(ctx); String javaType = CodeGenerator.javaType(dataType()); /* CODE GENERATED: final $javaType ${ev.value} try { ${ev.value} = ${input.isNull} ? ${CodeGenerator.defaultValue(dataType)} : ($javaType) $beamCoder.decode(new java.io.ByteArrayInputStream(${input.value})); } catch (Exception e) { throw org.apache.beam.sdk.util.UserCodeException.wrap(e); } */ List<String> parts = new ArrayList<>(); parts.add("final "); parts.add(" "); parts.add(";try { "); parts.add(" = "); parts.add("? "); parts.add(": ("); parts.add(") "); parts.add(".decode(new java.io.ByteArrayInputStream("); parts.add( ")); } catch (Exception e) {throw org.apache.beam.sdk.util.UserCodeException.wrap(e);}"); StringContext sc = new StringContext(JavaConversions.collectionAsScalaIterable(parts).toSeq()); List<Object> args = new ArrayList<>(); args.add(javaType); args.add(ev.value()); args.add(ev.value()); args.add(input.isNull()); args.add(CodeGenerator.defaultValue(dataType(), false)); args.add(javaType); args.add(accessCode); args.add(input.value()); Block code = (new Block.BlockHelper(sc)).code(JavaConversions.collectionAsScalaIterable(args).toSeq()); return ev.copy(input.code().$plus(code), input.isNull(), ev.value()); } @Override public Object nullSafeEval(Object input) { try { return beamCoder.decode(new ByteArrayInputStream((byte[]) input)); } catch (Exception e) { throw new IllegalStateException("Error decoding bytes for coder: " + beamCoder, e); } } @Override public DataType dataType() { return new ObjectType(classTag.runtimeClass()); } @Override public Object productElement(int n) { switch (n) { case 0: return child; case 1: return classTag; case 2: return beamCoder; default: throw new ArrayIndexOutOfBoundsException("productElement out of bounds"); } } @Override public int productArity() { return 3; } @Override public boolean canEqual(Object that) { return (that instanceof DecodeUsingBeamCoder); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } DecodeUsingBeamCoder<?> that = (DecodeUsingBeamCoder<?>) o; return child.equals(that.child) && classTag.equals(that.classTag) && beamCoder.equals(that.beamCoder); } @Override public int hashCode() { return Objects.hash(super.hashCode(), child, classTag, beamCoder); } } }
[BEAM-8470] Remove Encoders based on kryo now that we call Beam coders in the runner
runners/spark/src/main/java/org/apache/beam/runners/spark/structuredstreaming/translation/helpers/EncoderHelpers.java
[BEAM-8470] Remove Encoders based on kryo now that we call Beam coders in the runner
<ide><path>unners/spark/src/main/java/org/apache/beam/runners/spark/structuredstreaming/translation/helpers/EncoderHelpers.java <ide> /** {@link Encoders} utility class. */ <ide> public class EncoderHelpers { <ide> <del> // 1. use actual class and not object to avoid Spark fallback to GenericRowWithSchema. <del> // 2. use raw class because only raw classes can be used with kryo. Cast to Class<T> to allow <del> // the type inference mechanism to infer for ex Encoder<WindowedValue<T>> to get back the type <del> // checking <del> <del> /* <del> --------- Encoders for internal spark runner objects <del> */ <del> <del> /** <del> * Get a bytes {@link Encoder} for {@link WindowedValue}. Bytes serialisation is issued by Kryo <del> */ <del> @SuppressWarnings("unchecked") <del> public static <T> Encoder<T> windowedValueEncoder() { <del> return Encoders.kryo((Class<T>) WindowedValue.class); <del> } <del> <del> /** Get a bytes {@link Encoder} for {@link KV}. Bytes serialisation is issued by Kryo */ <del> @SuppressWarnings("unchecked") <del> public static <T> Encoder<T> kvEncoder() { <del> return Encoders.kryo((Class<T>) KV.class); <del> } <del> <del> /** Get a bytes {@link Encoder} for {@code T}. Bytes serialisation is issued by Kryo */ <del> @SuppressWarnings("unchecked") <del> public static <T> Encoder<T> genericEncoder() { <del> return Encoders.kryo((Class<T>) Object.class); <del> } <del> <del> /* <del> */ <del> /** Get a bytes {@link Encoder} for {@link Tuple2}. Bytes serialisation is issued by Kryo */ <del> /* <del> <del> public static <T1, T2> Encoder<Tuple2<T1, T2>> tuple2Encoder() { <del> return Encoders.tuple(EncoderHelpers.genericEncoder(), EncoderHelpers.genericEncoder()); <del> } <del> */ <del> <del> /* <add> /* <ide> --------- Bridges from Beam Coders to Spark Encoders <ide> */ <ide>
JavaScript
mit
f945db2db4c593659629c25b73ff18d8aec55d59
0
l-urence/react-native-autocomplete-input,l-urence/react-native-autocomplete-input,l-urence/react-native-autocomplete-input
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import { ListView, Platform, StyleSheet, Text, TextInput, View, ViewPropTypes as RNViewPropTypes } from 'react-native'; const ViewPropTypes = RNViewPropTypes || View.propTypes; class Autocomplete extends Component { static propTypes = { ...TextInput.propTypes, /** * These styles will be applied to the container which * surrounds the autocomplete component. */ containerStyle: ViewPropTypes.style, /** * Assign an array of data objects which should be * rendered in respect to the entered text. */ data: PropTypes.array, /** * Set to `true` to hide the suggestion list. */ hideResults: PropTypes.bool, /* * These styles will be applied to the container which surrounds * the textInput component. */ inputContainerStyle: ViewPropTypes.style, /* * Set `keyboardShouldPersistTaps` to true if RN version is <= 0.39. */ keyboardShouldPersistTaps: PropTypes.oneOfType([ PropTypes.string, PropTypes.bool ]), /* * These styles will be applied to the container which surrounds * the result list. */ listContainerStyle: ViewPropTypes.style, /** * These style will be applied to the result list. */ listStyle: ViewPropTypes.style, /** * `onShowResults` will be called when list is going to * show/hide results. */ onShowResults: PropTypes.func, /** * method for intercepting swipe on ListView. Used for ScrollView support on Android */ onStartShouldSetResponderCapture: PropTypes.func, /** * `renderItem` will be called to render the data objects * which will be displayed in the result view below the * text input. */ renderItem: PropTypes.func, /** * `renderSeparator` will be called to render the list separators * which will be displayed between the list elements in the result view * below the text input. */ renderSeparator: PropTypes.func, /** * renders custom TextInput. All props passed to this function. */ renderTextInput: PropTypes.func, /** * `rowHasChanged` will be used for data objects comparison for dataSource */ rowHasChanged: PropTypes.func }; static defaultProps = { data: [], defaultValue: '', keyboardShouldPersistTaps: 'always', onStartShouldSetResponderCapture: () => false, renderItem: rowData => <Text>{rowData}</Text>, renderSeparator: null, renderTextInput: props => <TextInput {...props} />, rowHasChanged: (r1, r2) => r1 !== r2 }; constructor(props) { super(props); const ds = new ListView.DataSource({ rowHasChanged: props.rowHasChanged }); this.state = { dataSource: ds.cloneWithRows(props.data) }; this.resultList = null; } componentWillReceiveProps({ data }) { const dataSource = this.state.dataSource.cloneWithRows(data); this.setState({ dataSource }); } /** * Proxy `blur()` to autocomplete's text input. */ blur() { const { textInput } = this; textInput && textInput.blur(); } /** * Proxy `focus()` to autocomplete's text input. */ focus() { const { textInput } = this; textInput && textInput.focus(); } /** * Proxy `isFocused()` to autocomplete's text input. */ isFocused() { const { textInput } = this; return textInput && textInput.isFocused(); } renderResultList() { const { dataSource } = this.state; const { listStyle, renderItem, renderSeparator, keyboardShouldPersistTaps, onEndReached, onEndReachedThreshold } = this.props; return ( <ListView ref={(resultList) => { this.resultList = resultList; }} dataSource={dataSource} keyboardShouldPersistTaps={keyboardShouldPersistTaps} renderRow={renderItem} renderSeparator={renderSeparator} onEndReached={onEndReached} onEndReachedThreshold={onEndReachedThreshold} style={[styles.list, listStyle]} /> ); } renderTextInput() { const { onEndEditing, renderTextInput, style } = this.props; const props = { style: [styles.input, style], ref: ref => (this.textInput = ref), onEndEditing: e => onEndEditing && onEndEditing(e), ...this.props }; return renderTextInput(props); } render() { const { dataSource } = this.state; const { containerStyle, hideResults, inputContainerStyle, listContainerStyle, onShowResults, onStartShouldSetResponderCapture } = this.props; const showResults = dataSource.getRowCount() > 0; // Notify listener if the suggestion will be shown. onShowResults && onShowResults(showResults); return ( <View style={[styles.container, containerStyle]}> <View style={[styles.inputContainer, inputContainerStyle]}> {this.renderTextInput()} </View> {!hideResults && ( <View style={listContainerStyle} onStartShouldSetResponderCapture={onStartShouldSetResponderCapture} > {showResults && this.renderResultList()} </View> )} </View> ); } } const border = { borderColor: '#b9b9b9', borderRadius: 1, borderWidth: 1 }; const androidStyles = { container: { flex: 1 }, inputContainer: { ...border, marginBottom: 0 }, list: { ...border, backgroundColor: 'white', borderTopWidth: 0, margin: 10, marginTop: 0 } }; const iosStyles = { container: { zIndex: 1 }, inputContainer: { ...border }, input: { backgroundColor: 'white', height: 40, paddingLeft: 3 }, list: { ...border, backgroundColor: 'white', borderTopWidth: 0, left: 0, position: 'absolute', right: 0 } }; const styles = StyleSheet.create({ input: { backgroundColor: 'white', height: 40, paddingLeft: 3 }, ...Platform.select({ android: { ...androidStyles }, ios: { ...iosStyles } }) }); export default Autocomplete;
index.js
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import { ListView, Platform, StyleSheet, Text, TextInput, View, ViewPropTypes as RNViewPropTypes } from 'react-native'; const ViewPropTypes = RNViewPropTypes || View.propTypes; class Autocomplete extends Component { static propTypes = { ...TextInput.propTypes, /** * These styles will be applied to the container which * surrounds the autocomplete component. */ containerStyle: ViewPropTypes.style, /** * Assign an array of data objects which should be * rendered in respect to the entered text. */ data: PropTypes.array, /** * Set to `true` to hide the suggestion list. */ hideResults: PropTypes.bool, /* * These styles will be applied to the container which surrounds * the textInput component. */ inputContainerStyle: ViewPropTypes.style, /* * Set `keyboardShouldPersistTaps` to true if RN version is <= 0.39. */ keyboardShouldPersistTaps: PropTypes.oneOfType([ PropTypes.string, PropTypes.bool ]), /* * These styles will be applied to the container which surrounds * the result list. */ listContainerStyle: ViewPropTypes.style, /** * These style will be applied to the result list. */ listStyle: ViewPropTypes.style, /** * `onShowResults` will be called when list is going to * show/hide results. */ onShowResults: PropTypes.func, /** * method for intercepting swipe on ListView. Used for ScrollView support on Android */ onStartShouldSetResponderCapture: PropTypes.func, /** * `renderItem` will be called to render the data objects * which will be displayed in the result view below the * text input. */ renderItem: PropTypes.func, /** * `renderSeparator` will be called to render the list separators * which will be displayed between the list elements in the result view * below the text input. */ renderSeparator: PropTypes.func, /** * renders custom TextInput. All props passed to this function. */ renderTextInput: PropTypes.func, /** * `rowHasChanged` will be used for data objects comparison for dataSource */ rowHasChanged: PropTypes.func }; static defaultProps = { data: [], defaultValue: '', keyboardShouldPersistTaps: 'always', onStartShouldSetResponderCapture: () => false, renderItem: rowData => <Text>{rowData}</Text>, renderSeparator: null, renderTextInput: props => <TextInput {...props} />, rowHasChanged: (r1, r2) => r1 !== r2 }; constructor(props) { super(props); const ds = new ListView.DataSource({ rowHasChanged: props.rowHasChanged }); this.state = { dataSource: ds.cloneWithRows(props.data) }; this.resultList = null; } componentWillReceiveProps({ data }) { const dataSource = this.state.dataSource.cloneWithRows(data); this.setState({ dataSource }); } /** * Proxy `blur()` to autocomplete's text input. */ blur() { const { textInput } = this; textInput && textInput.blur(); } /** * Proxy `focus()` to autocomplete's text input. */ focus() { const { textInput } = this; textInput && textInput.focus(); } renderResultList() { const { dataSource } = this.state; const { listStyle, renderItem, renderSeparator, keyboardShouldPersistTaps, onEndReached, onEndReachedThreshold } = this.props; return ( <ListView ref={(resultList) => { this.resultList = resultList; }} dataSource={dataSource} keyboardShouldPersistTaps={keyboardShouldPersistTaps} renderRow={renderItem} renderSeparator={renderSeparator} onEndReached={onEndReached} onEndReachedThreshold={onEndReachedThreshold} style={[styles.list, listStyle]} /> ); } renderTextInput() { const { onEndEditing, renderTextInput, style } = this.props; const props = { style: [styles.input, style], ref: ref => (this.textInput = ref), onEndEditing: e => onEndEditing && onEndEditing(e), ...this.props }; return renderTextInput(props); } render() { const { dataSource } = this.state; const { containerStyle, hideResults, inputContainerStyle, listContainerStyle, onShowResults, onStartShouldSetResponderCapture } = this.props; const showResults = dataSource.getRowCount() > 0; // Notify listener if the suggestion will be shown. onShowResults && onShowResults(showResults); return ( <View style={[styles.container, containerStyle]}> <View style={[styles.inputContainer, inputContainerStyle]}> {this.renderTextInput()} </View> {!hideResults && ( <View style={listContainerStyle} onStartShouldSetResponderCapture={onStartShouldSetResponderCapture} > {showResults && this.renderResultList()} </View> )} </View> ); } } const border = { borderColor: '#b9b9b9', borderRadius: 1, borderWidth: 1 }; const androidStyles = { container: { flex: 1 }, inputContainer: { ...border, marginBottom: 0 }, list: { ...border, backgroundColor: 'white', borderTopWidth: 0, margin: 10, marginTop: 0 } }; const iosStyles = { container: { zIndex: 1 }, inputContainer: { ...border }, input: { backgroundColor: 'white', height: 40, paddingLeft: 3 }, list: { ...border, backgroundColor: 'white', borderTopWidth: 0, left: 0, position: 'absolute', right: 0 } }; const styles = StyleSheet.create({ input: { backgroundColor: 'white', height: 40, paddingLeft: 3 }, ...Platform.select({ android: { ...androidStyles }, ios: { ...iosStyles } }) }); export default Autocomplete;
Add isFocused() proxy to the internal TextInput
index.js
Add isFocused() proxy to the internal TextInput
<ide><path>ndex.js <ide> focus() { <ide> const { textInput } = this; <ide> textInput && textInput.focus(); <add> } <add> <add> /** <add> * Proxy `isFocused()` to autocomplete's text input. <add> */ <add> isFocused() { <add> const { textInput } = this; <add> return textInput && textInput.isFocused(); <ide> } <ide> <ide> renderResultList() {
JavaScript
mit
183efaf3910003f944e00b2690c32effe0869928
0
JHallberg5100/BattleShip,JHallberg5100/BattleShip,JHallberg5100/BattleShip,JHallberg5100/BattleShip
$(document).ready(function() { var boardFunctionality = function(){ var direction = "horizontal" $("#toggle-button").on("click", function(){ if (direction === "horizontal"){ direction = "vertical"; } else{ direction = "horizontal"; } }) $('a').on("click", function(){ event.preventDefault(); $currentShip = $(this) shipName = $(this).html(); console.log(shipName) size = $(this).attr('href'); }); $('.cell').on("mouseenter", function() { $("#warning").html(""); $mousePosition = $(this); $currentPosition = $mousePosition $('.ship-shadow').removeClass("ship-shadow"); if (direction === "horizontal") { for (var i = 0 ; i <= size-1; i++){ if($currentPosition.hasClass("ship-placed")){ $(".ship-shadow").removeClass("ship-shadow"); $("#warning").html("Invalid Position"); } else { if($currentPosition.is("td")){ $currentPosition.addClass("ship-shadow"); $currentPosition = $currentPosition.prev(); } else { $(".ship-shadow").removeClass("ship-shadow"); $("#warning").html("Invalid Position"); } } } } else if (direction === "vertical") { sibIndex= $currentPosition.parent().children(); indexNum = sibIndex.index($currentPosition); for (var i = 0 ; i <= size-1; i++) { if($currentPosition.hasClass("ship-placed")){ $(".ship-shadow").removeClass("ship-shadow"); $("#warning").html("Invalid Position"); } else { if($currentPosition.is("td")){ $currentPosition.addClass("ship-shadow"); $currentPosition = $currentPosition.parent().prev(); // console.log($currentPosition); $currentPosition = $($currentPosition.children().get(indexNum)); } else{ $(".ship-shadow").removeClass("ship-shadow"); $("#warning").html("Invalid Position"); } } } } }); $(".cell").on("click", function(){ $allShips= $(".ship-shadow"); $allShips.addClass("ship-placed"); $allShips.removeClass("ship-shadow") $currentShip.hide(); createShip(shipName, size, $mousePosition.html(), direction) size = null; }); }; boardFunctionality(); }); var createShip = function(name, size, position, direction){ $.ajax({ url: "/ships", type: "POST", data: {name: name, size: size, position: position, direction: direction }, }) .done(function(response) { console.log(response); }) }
Battleship/app/assets/javascripts/game_setup.js
$(document).ready(function() { var boardFunctionality = function(){ var direction = "horizontal" $("#toggle-button").on("click", function(){ if( direction === "horizontal"){ direction = "vertical"; } else{ direction = "horizontal"; } }) $('a').on("click", function(){ event.preventDefault(); $currentShip = $(this) shipName = $(this).html(); console.log(shipName) size = $(this).attr('href'); }); $('.cell').on("mouseenter", function() { $("#warning").html(""); $mousePosition = $(this); $currentPosition = $mousePosition $('.ship-shadow').removeClass("ship-shadow"); if (direction === "horizontal"){ for (var i = 0 ; i <= size-1; i++){ if($currentPosition.hasClass("ship-placed")){ $(".ship-shadow").removeClass("ship-shadow"); $("#warning").html("Invalid Position"); } else{ if($currentPosition.is("td")){ $currentPosition.addClass("ship-shadow"); $currentPosition = $currentPosition.prev(); } else{ $(".ship-shadow").removeClass("ship-shadow"); $("#warning").html("Invalid Position"); }}}} else { sibIndex= $currentPosition.parent().children(); indexNum = sibIndex.index($currentPosition); for (var i = 0 ; i <= size-1; i++){ if($currentPosition.hasClass("ship-placed")){ $(".ship-shadow").removeClass("ship-shadow"); $("#warning").html("Invalid Position"); } else{ if($currentPosition.is("td")){ $currentPosition.addClass("ship-shadow"); $currentPosition = $currentPosition.parent().prev(); // console.log($currentPosition); $currentPosition = $($currentPosition.children().get(indexNum)); } else{ $(".ship-shadow").removeClass("ship-shadow"); $("#warning").html("Invalid Position"); }}} } }); $(".cell").on("click", function(){ $allShips= $(".ship-shadow"); $allShips.addClass("ship-placed"); $allShips.removeClass("ship-shadow") $currentShip.hide(); createShip(shipName, size, $mousePosition.html(), direction) size = null; }); }; boardFunctionality(); }); var createShip = function(name, size, position, direction){ $.ajax({ url: "/ships", type: "POST", data: {name: name, size: size, position: position, direction: direction }, }) .done(function(response) { console.log(response); }) }
Clean up JS
Battleship/app/assets/javascripts/game_setup.js
Clean up JS
<ide><path>attleship/app/assets/javascripts/game_setup.js <ide> var boardFunctionality = function(){ <ide> var direction = "horizontal" <ide> $("#toggle-button").on("click", function(){ <del> if( direction === "horizontal"){ <add> if (direction === "horizontal"){ <ide> direction = "vertical"; <ide> } <ide> else{ <ide> $currentPosition = $mousePosition <ide> <ide> $('.ship-shadow').removeClass("ship-shadow"); <del> if (direction === "horizontal"){ <add> <add> if (direction === "horizontal") { <ide> for (var i = 0 ; i <= size-1; i++){ <ide> if($currentPosition.hasClass("ship-placed")){ <ide> $(".ship-shadow").removeClass("ship-shadow"); <ide> $("#warning").html("Invalid Position"); <ide> } <del> else{ <add> else { <ide> if($currentPosition.is("td")){ <ide> $currentPosition.addClass("ship-shadow"); <ide> $currentPosition = $currentPosition.prev(); <ide> } <add> else { <add> $(".ship-shadow").removeClass("ship-shadow"); <add> $("#warning").html("Invalid Position"); <add> } <add> } <add> } <add> } <add> <add> else if (direction === "vertical") { <add> sibIndex= $currentPosition.parent().children(); <add> indexNum = sibIndex.index($currentPosition); <add> for (var i = 0 ; i <= size-1; i++) { <add> if($currentPosition.hasClass("ship-placed")){ <add> $(".ship-shadow").removeClass("ship-shadow"); <add> $("#warning").html("Invalid Position"); <add> } <add> else { <add> if($currentPosition.is("td")){ <add> $currentPosition.addClass("ship-shadow"); <add> $currentPosition = $currentPosition.parent().prev(); <add> // console.log($currentPosition); <add> $currentPosition = $($currentPosition.children().get(indexNum)); <add> } <ide> else{ <ide> $(".ship-shadow").removeClass("ship-shadow"); <ide> $("#warning").html("Invalid Position"); <del> }}}} <del> else { <del> sibIndex= $currentPosition.parent().children(); <del> indexNum = sibIndex.index($currentPosition); <del> for (var i = 0 ; i <= size-1; i++){ <del> if($currentPosition.hasClass("ship-placed")){ <del> $(".ship-shadow").removeClass("ship-shadow"); <del> $("#warning").html("Invalid Position"); <del> } <del> else{ <del> if($currentPosition.is("td")){ <del> $currentPosition.addClass("ship-shadow"); <del> $currentPosition = $currentPosition.parent().prev(); <del> // console.log($currentPosition); <del> $currentPosition = $($currentPosition.children().get(indexNum)); <del> } <del> else{ <del> $(".ship-shadow").removeClass("ship-shadow"); <del> $("#warning").html("Invalid Position"); <add> } <add> } <add> } <add> } <add> }); <ide> <del> }}} <del> } <del> }); <del>$(".cell").on("click", function(){ <del> $allShips= $(".ship-shadow"); <del> $allShips.addClass("ship-placed"); <del> $allShips.removeClass("ship-shadow") <del> $currentShip.hide(); <del> createShip(shipName, size, $mousePosition.html(), direction) <del> size = null; <add> $(".cell").on("click", function(){ <add> $allShips= $(".ship-shadow"); <add> $allShips.addClass("ship-placed"); <add> $allShips.removeClass("ship-shadow") <add> $currentShip.hide(); <add> createShip(shipName, size, $mousePosition.html(), direction) <add> size = null; <add> }); <add> }; <ide> <del>}); <del>}; <del>boardFunctionality(); <add> boardFunctionality(); <ide> }); <ide> <ide> var createShip = function(name, size, position, direction){
Java
apache-2.0
error: pathspec 'core/src/main/java/nl/nn/adapterframework/webcontrol/DummySSLSocketFactory.java' did not match any file(s) known to git
1e7b688e445510d9c2fee4401881ed7320d7a962
1
ibissource/iaf,ibissource/iaf,ibissource/iaf,ibissource/iaf,ibissource/iaf
/* Copyright 2013 Nationale-Nederlanden 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 nl.nn.adapterframework.webcontrol; import java.io.IOException; import java.net.InetAddress; import java.net.Socket; import java.security.cert.X509Certificate; import javax.net.SocketFactory; import javax.net.ssl.SSLContext; import javax.net.ssl.SSLSocketFactory; import javax.net.ssl.TrustManager; import javax.net.ssl.X509TrustManager; /** * Dummy SSLSocketFactory for LoginFilter. * * (to avoid java.security.InvalidAlgorithmParameterException: the trustAnchors parameter must be non-empty). * * @author Peter Leeuwenburgh * @version $Id$ */ public class DummySSLSocketFactory extends SSLSocketFactory { private SSLSocketFactory factory; public DummySSLSocketFactory() { try { SSLContext sslcontext = null; if (sslcontext == null) { sslcontext = SSLContext.getInstance("TLS"); sslcontext.init( null, // No KeyManager required new TrustManager[] { new DummyTrustManager() }, new java.security.SecureRandom()); } factory = (SSLSocketFactory) sslcontext.getSocketFactory(); } catch (Exception ex) { ex.printStackTrace(); } } public static SocketFactory getDefault() { return new DummySSLSocketFactory(); } public Socket createSocket(Socket socket, String s, int i, boolean flag) throws IOException { return factory.createSocket(socket, s, i, flag); } public Socket createSocket(InetAddress inaddr, int i, InetAddress inaddr1, int j) throws IOException { return factory.createSocket(inaddr, i, inaddr1, j); } public Socket createSocket(InetAddress inaddr, int i) throws IOException { return factory.createSocket(inaddr, i); } public Socket createSocket(String s, int i, InetAddress inaddr, int j) throws IOException { return factory.createSocket(s, i, inaddr, j); } public Socket createSocket(String s, int i) throws IOException { return factory.createSocket(s, i); } public String[] getDefaultCipherSuites() { return factory.getSupportedCipherSuites(); } public String[] getSupportedCipherSuites() { return factory.getSupportedCipherSuites(); } public class DummyTrustManager implements X509TrustManager { public void checkClientTrusted(X509Certificate[] cert, String authType) { return; } public void checkServerTrusted(X509Certificate[] cert, String authType) { return; } public X509Certificate[] getAcceptedIssuers() { return new X509Certificate[0]; } } }
core/src/main/java/nl/nn/adapterframework/webcontrol/DummySSLSocketFactory.java
initial version
core/src/main/java/nl/nn/adapterframework/webcontrol/DummySSLSocketFactory.java
initial version
<ide><path>ore/src/main/java/nl/nn/adapterframework/webcontrol/DummySSLSocketFactory.java <add>/* <add> Copyright 2013 Nationale-Nederlanden <add> <add> Licensed under the Apache License, Version 2.0 (the "License"); <add> you may not use this file except in compliance with the License. <add> You may obtain a copy of the License at <add> <add> http://www.apache.org/licenses/LICENSE-2.0 <add> <add> Unless required by applicable law or agreed to in writing, software <add> distributed under the License is distributed on an "AS IS" BASIS, <add> WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. <add> See the License for the specific language governing permissions and <add> limitations under the License. <add> */ <add>package nl.nn.adapterframework.webcontrol; <add> <add>import java.io.IOException; <add>import java.net.InetAddress; <add>import java.net.Socket; <add>import java.security.cert.X509Certificate; <add> <add>import javax.net.SocketFactory; <add>import javax.net.ssl.SSLContext; <add>import javax.net.ssl.SSLSocketFactory; <add>import javax.net.ssl.TrustManager; <add>import javax.net.ssl.X509TrustManager; <add> <add>/** <add> * Dummy SSLSocketFactory for LoginFilter. <add> * <add> * (to avoid java.security.InvalidAlgorithmParameterException: the trustAnchors parameter must be non-empty). <add> * <add> * @author Peter Leeuwenburgh <add> * @version $Id$ <add> */ <add> <add>public class DummySSLSocketFactory extends SSLSocketFactory { <add> private SSLSocketFactory factory; <add> <add> public DummySSLSocketFactory() { <add> try { <add> <add> SSLContext sslcontext = null; <add> if (sslcontext == null) { <add> sslcontext = SSLContext.getInstance("TLS"); <add> sslcontext.init( <add> null, // No KeyManager required <add> new TrustManager[] { new DummyTrustManager() }, <add> new java.security.SecureRandom()); <add> } <add> <add> factory = (SSLSocketFactory) sslcontext.getSocketFactory(); <add> <add> } catch (Exception ex) { <add> ex.printStackTrace(); <add> } <add> } <add> <add> public static SocketFactory getDefault() { <add> return new DummySSLSocketFactory(); <add> } <add> <add> public Socket createSocket(Socket socket, String s, int i, boolean flag) <add> throws IOException { <add> return factory.createSocket(socket, s, i, flag); <add> } <add> <add> public Socket createSocket(InetAddress inaddr, int i, InetAddress inaddr1, <add> int j) throws IOException { <add> return factory.createSocket(inaddr, i, inaddr1, j); <add> } <add> <add> public Socket createSocket(InetAddress inaddr, int i) throws IOException { <add> return factory.createSocket(inaddr, i); <add> } <add> <add> public Socket createSocket(String s, int i, InetAddress inaddr, int j) <add> throws IOException { <add> return factory.createSocket(s, i, inaddr, j); <add> } <add> <add> public Socket createSocket(String s, int i) throws IOException { <add> return factory.createSocket(s, i); <add> } <add> <add> public String[] getDefaultCipherSuites() { <add> return factory.getSupportedCipherSuites(); <add> } <add> <add> public String[] getSupportedCipherSuites() { <add> return factory.getSupportedCipherSuites(); <add> } <add> <add> public class DummyTrustManager implements X509TrustManager { <add> public void checkClientTrusted(X509Certificate[] cert, String authType) { <add> return; <add> } <add> <add> public void checkServerTrusted(X509Certificate[] cert, String authType) { <add> return; <add> } <add> <add> public X509Certificate[] getAcceptedIssuers() { <add> return new X509Certificate[0]; <add> } <add> } <add>}
Java
mit
084a78a78ffeba8239a9135a350c56dad69b5f70
0
venkatramanm/swf-all,venkatramanm/swf-all,venkatramanm/swf-all
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package com.venky.swf.db.model; import java.sql.Timestamp; import java.util.List; import java.util.Map; import com.venky.cache.Cache; import com.venky.swf.db.annotations.column.COLUMN_DEF; import com.venky.swf.db.annotations.column.COLUMN_NAME; import com.venky.swf.db.annotations.column.COLUMN_SIZE; import com.venky.swf.db.annotations.column.HOUSEKEEPING; import com.venky.swf.db.annotations.column.IS_NULLABLE; import com.venky.swf.db.annotations.column.IS_VIRTUAL; import com.venky.swf.db.annotations.column.PASSWORD; import com.venky.swf.db.annotations.column.UNIQUE_KEY; import com.venky.swf.db.annotations.column.defaulting.StandardDefault; import com.venky.swf.db.annotations.column.indexing.Index; import com.venky.swf.db.annotations.column.pm.PARTICIPANT; import com.venky.swf.db.annotations.column.relationship.CONNECTED_VIA; import com.venky.swf.db.annotations.column.ui.HIDDEN; import com.venky.swf.db.annotations.column.ui.PROTECTION; import com.venky.swf.db.annotations.model.CONFIGURATION; import com.venky.swf.db.annotations.model.EXPORTABLE; import com.venky.swf.db.annotations.model.HAS_DESCRIPTION_FIELD; import com.venky.swf.db.annotations.model.MENU; import com.venky.swf.db.model.reflection.ModelReflector; import com.venky.swf.sql.Expression; /** * * @author venky */ @HAS_DESCRIPTION_FIELD("LONG_NAME") @MENU("Admin") public interface User extends Model{ @IS_NULLABLE(false) @UNIQUE_KEY("K1,K2,K3") @Index public String getName(); public void setName(String name); @Index @UNIQUE_KEY("K2") public String getLongName(); public void setLongName(String name); @IS_NULLABLE @UNIQUE_KEY("API") @HIDDEN @PROTECTION @COLUMN_DEF(StandardDefault.NULL) @EXPORTABLE(false) public String getApiKey(); public void setApiKey(String key); @IS_NULLABLE @HIDDEN @EXPORTABLE(false) @COLUMN_DEF(StandardDefault.NULL) public Timestamp getApiKeyGeneratedTs(); public void setApiKeyGeneratedTs(Timestamp ts); @IS_VIRTUAL @COLUMN_SIZE(60) @PASSWORD public String getChangePassword(); @IS_VIRTUAL public void setChangePassword(String password); @PASSWORD @HIDDEN @PROTECTION public String getPassword(); public void setPassword(String password); public boolean authenticate(String password); public static final String USER_AUTHENTICATE = "user.authenticate" ; public <M extends Model> Cache<String,Map<String,List<Long>>> getParticipationOptions(Class<M> modelClass); public Cache<String,Map<String,List<Long>>> getParticipationOptions(Class<? extends Model> modelClass,Model model); public static final String GET_PARTICIPATION_OPTION = "get.participation.option";//++ModelClass.SimpleName public <M extends Model> Expression getDataSecurityWhereClause(Class<M> modelClass); public Expression getDataSecurityWhereClause(Class<? extends Model> modelClass,Model model); public Expression getDataSecurityWhereClause(ModelReflector<? extends Model> ref, Cache<String,Map<String,List<Long>>> participatingRoleGroupOptions); @IS_VIRTUAL public boolean isAdmin(); @CONNECTED_VIA("USER_ID") public List<UserEmail> getUserEmails(); public void generateApiKey(); public void generateApiKey(boolean save); @IS_VIRTUAL public String getEncryptedPassword(String unencryptedPassword); @IS_VIRTUAL public int getNumMinutesToKeyExpiration(); @COLUMN_DEF(StandardDefault.BOOLEAN_FALSE) public boolean isPasswordEncrypted(); public void setPasswordEncrypted(boolean encrypted); }
swf-db/src/main/java/com/venky/swf/db/model/User.java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package com.venky.swf.db.model; import java.sql.Timestamp; import java.util.List; import java.util.Map; import com.venky.cache.Cache; import com.venky.swf.db.annotations.column.COLUMN_DEF; import com.venky.swf.db.annotations.column.COLUMN_NAME; import com.venky.swf.db.annotations.column.COLUMN_SIZE; import com.venky.swf.db.annotations.column.HOUSEKEEPING; import com.venky.swf.db.annotations.column.IS_NULLABLE; import com.venky.swf.db.annotations.column.IS_VIRTUAL; import com.venky.swf.db.annotations.column.PASSWORD; import com.venky.swf.db.annotations.column.UNIQUE_KEY; import com.venky.swf.db.annotations.column.defaulting.StandardDefault; import com.venky.swf.db.annotations.column.indexing.Index; import com.venky.swf.db.annotations.column.pm.PARTICIPANT; import com.venky.swf.db.annotations.column.relationship.CONNECTED_VIA; import com.venky.swf.db.annotations.column.ui.HIDDEN; import com.venky.swf.db.annotations.column.ui.PROTECTION; import com.venky.swf.db.annotations.model.CONFIGURATION; import com.venky.swf.db.annotations.model.EXPORTABLE; import com.venky.swf.db.annotations.model.HAS_DESCRIPTION_FIELD; import com.venky.swf.db.annotations.model.MENU; import com.venky.swf.db.model.reflection.ModelReflector; import com.venky.swf.sql.Expression; /** * * @author venky */ @HAS_DESCRIPTION_FIELD("LONG_NAME") @MENU("Admin") public interface User extends Model{ @IS_NULLABLE(false) @UNIQUE_KEY("K1,K2") @Index public String getName(); public void setName(String name); @Index @UNIQUE_KEY("K2") public String getLongName(); public void setLongName(String name); @IS_NULLABLE @UNIQUE_KEY("API") @HIDDEN @PROTECTION @COLUMN_DEF(StandardDefault.NULL) @EXPORTABLE(false) public String getApiKey(); public void setApiKey(String key); @IS_NULLABLE @HIDDEN @EXPORTABLE(false) @COLUMN_DEF(StandardDefault.NULL) public Timestamp getApiKeyGeneratedTs(); public void setApiKeyGeneratedTs(Timestamp ts); @IS_VIRTUAL @COLUMN_SIZE(60) @PASSWORD public String getChangePassword(); @IS_VIRTUAL public void setChangePassword(String password); @PASSWORD @HIDDEN @PROTECTION public String getPassword(); public void setPassword(String password); public boolean authenticate(String password); public static final String USER_AUTHENTICATE = "user.authenticate" ; public <M extends Model> Cache<String,Map<String,List<Long>>> getParticipationOptions(Class<M> modelClass); public Cache<String,Map<String,List<Long>>> getParticipationOptions(Class<? extends Model> modelClass,Model model); public static final String GET_PARTICIPATION_OPTION = "get.participation.option";//++ModelClass.SimpleName public <M extends Model> Expression getDataSecurityWhereClause(Class<M> modelClass); public Expression getDataSecurityWhereClause(Class<? extends Model> modelClass,Model model); public Expression getDataSecurityWhereClause(ModelReflector<? extends Model> ref, Cache<String,Map<String,List<Long>>> participatingRoleGroupOptions); @IS_VIRTUAL public boolean isAdmin(); @CONNECTED_VIA("USER_ID") public List<UserEmail> getUserEmails(); public void generateApiKey(); public void generateApiKey(boolean save); @IS_VIRTUAL public String getEncryptedPassword(String unencryptedPassword); @IS_VIRTUAL public int getNumMinutesToKeyExpiration(); @COLUMN_DEF(StandardDefault.BOOLEAN_FALSE) public boolean isPasswordEncrypted(); public void setPasswordEncrypted(boolean encrypted); }
User UK Fix
swf-db/src/main/java/com/venky/swf/db/model/User.java
User UK Fix
<ide><path>wf-db/src/main/java/com/venky/swf/db/model/User.java <ide> public interface User extends Model{ <ide> <ide> @IS_NULLABLE(false) <del> @UNIQUE_KEY("K1,K2") <add> @UNIQUE_KEY("K1,K2,K3") <ide> @Index <ide> public String getName(); <ide> public void setName(String name);
JavaScript
mit
4fe7f3b4ebc6a477b30bd3cb55055bb9cdbffc47
0
TeamIllegalSkillsException/CashFlow,TeamIllegalSkillsException/CashFlow,TeamIllegalSkillsException/CashFlow
'use strict'; module.exports = function(environment) { const config = { development: { cookieName: 'test cookie', sessionSecret: 'secret ala bala', webTokenSecret: 'secret mecret', connectionString: 'mongodb://localhost:27017/cash-flow-db', port: 3003, email: '[email protected]', password: 'ninjas123456' }, production: { cookieName: process.env.COOKIE_NAME, sessionSecret: process.env.SESSION_SECRET, webTokenSecret: process.env.WEB_TOKEN_SECRET, connectionString: process.env.CONNECTION_STRING, port: process.env.PORT, email: process.env.EMAIL, password: process.env.PASSWORD } }; return config[environment]; };
server/config/config.js
'use strict'; module.exports = function(environment) { const config = { development: { cookieName: 'test cookie', sessionSecret: 'secret ala bala', webTokenSecret: 'secret mecret', connectionString: 'mongodb://Azonic89:[email protected]:51018/cash-flow-db', port: 3003, email: '[email protected]', password: 'ninjas123456' }, production: { cookieName: process.env.COOKIE_NAME, sessionSecret: process.env.SESSION_SECRET, webTokenSecret: process.env.WEB_TOKEN_SECRET, connectionString: process.env.CONNECTION_STRING, port: process.env.PORT, email: process.env.EMAIL, password: process.env.PASSWORD } }; return config[environment]; };
dev connect string
server/config/config.js
dev connect string
<ide><path>erver/config/config.js <ide> cookieName: 'test cookie', <ide> sessionSecret: 'secret ala bala', <ide> webTokenSecret: 'secret mecret', <del> connectionString: 'mongodb://Azonic89:[email protected]:51018/cash-flow-db', <add> connectionString: 'mongodb://localhost:27017/cash-flow-db', <ide> port: 3003, <ide> email: '[email protected]', <ide> password: 'ninjas123456'
Java
apache-2.0
49202e2cf849dce7df3856ec9f40b1b5596a7ae9
0
sunjincheng121/flink,twalthr/flink,gyfora/flink,godfreyhe/flink,darionyaphet/flink,zentol/flink,xccui/flink,tzulitai/flink,xccui/flink,tillrohrmann/flink,tillrohrmann/flink,xccui/flink,gyfora/flink,wwjiang007/flink,zjureel/flink,StephanEwen/incubator-flink,fhueske/flink,aljoscha/flink,hequn8128/flink,godfreyhe/flink,xccui/flink,gyfora/flink,jinglining/flink,hequn8128/flink,fhueske/flink,tony810430/flink,zentol/flink,zjureel/flink,zjureel/flink,zentol/flink,zjureel/flink,greghogan/flink,kl0u/flink,greghogan/flink,tzulitai/flink,bowenli86/flink,kl0u/flink,tzulitai/flink,apache/flink,GJL/flink,kl0u/flink,StephanEwen/incubator-flink,greghogan/flink,tony810430/flink,tzulitai/flink,kl0u/flink,mbode/flink,fhueske/flink,zjureel/flink,greghogan/flink,clarkyzl/flink,godfreyhe/flink,apache/flink,tony810430/flink,GJL/flink,wwjiang007/flink,clarkyzl/flink,apache/flink,aljoscha/flink,fhueske/flink,zentol/flink,zentol/flink,tillrohrmann/flink,apache/flink,godfreyhe/flink,bowenli86/flink,kl0u/flink,mbode/flink,gyfora/flink,aljoscha/flink,wwjiang007/flink,godfreyhe/flink,rmetzger/flink,gyfora/flink,StephanEwen/incubator-flink,bowenli86/flink,wwjiang007/flink,tzulitai/flink,xccui/flink,sunjincheng121/flink,jinglining/flink,lincoln-lil/flink,aljoscha/flink,kaibozhou/flink,hequn8128/flink,kl0u/flink,sunjincheng121/flink,StephanEwen/incubator-flink,xccui/flink,rmetzger/flink,twalthr/flink,jinglining/flink,tzulitai/flink,zentol/flink,jinglining/flink,fhueske/flink,lincoln-lil/flink,rmetzger/flink,bowenli86/flink,greghogan/flink,zjureel/flink,apache/flink,gyfora/flink,tony810430/flink,wwjiang007/flink,gyfora/flink,tillrohrmann/flink,clarkyzl/flink,lincoln-lil/flink,aljoscha/flink,darionyaphet/flink,bowenli86/flink,greghogan/flink,lincoln-lil/flink,twalthr/flink,twalthr/flink,godfreyhe/flink,darionyaphet/flink,tillrohrmann/flink,mbode/flink,lincoln-lil/flink,kaibozhou/flink,kaibozhou/flink,GJL/flink,jinglining/flink,GJL/flink,godfreyhe/flink,darionyaphet/flink,twalthr/flink,zjureel/flink,xccui/flink,clarkyzl/flink,wwjiang007/flink,tony810430/flink,apache/flink,lincoln-lil/flink,twalthr/flink,hequn8128/flink,tillrohrmann/flink,kaibozhou/flink,apache/flink,zentol/flink,GJL/flink,tony810430/flink,GJL/flink,rmetzger/flink,StephanEwen/incubator-flink,tillrohrmann/flink,kaibozhou/flink,sunjincheng121/flink,rmetzger/flink,rmetzger/flink,tony810430/flink,jinglining/flink,mbode/flink,fhueske/flink,hequn8128/flink,darionyaphet/flink,bowenli86/flink,StephanEwen/incubator-flink,sunjincheng121/flink,mbode/flink,kaibozhou/flink,clarkyzl/flink,lincoln-lil/flink,twalthr/flink,sunjincheng121/flink,wwjiang007/flink,rmetzger/flink,aljoscha/flink,hequn8128/flink
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.flink.table.catalog; import org.apache.flink.annotation.Internal; import org.apache.flink.annotation.VisibleForTesting; import org.apache.flink.table.api.TableSchema; import org.apache.flink.table.sinks.TableSink; import org.apache.flink.table.sources.DefinedProctimeAttribute; import org.apache.flink.table.sources.DefinedRowtimeAttributes; import org.apache.flink.table.sources.RowtimeAttributeDescriptor; import org.apache.flink.table.sources.TableSource; import org.apache.flink.table.types.AtomicDataType; import org.apache.flink.table.types.DataType; import org.apache.flink.table.types.logical.TimestampKind; import org.apache.flink.table.types.logical.TimestampType; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.stream.Collectors; /** * A {@link CatalogTable} that wraps a {@link TableSource} and/or {@link TableSink}. * This allows registering those in a {@link Catalog}. It can not be persisted as the * source and/or sink might be inline implementations and not be representable in a * property based form. * * @param <T1> type of the produced elements by the {@link TableSource} * @param <T2> type of the expected elements by the {@link TableSink} */ @Internal public class ConnectorCatalogTable<T1, T2> extends AbstractCatalogTable { private final TableSource<T1> tableSource; private final TableSink<T2> tableSink; // Flag that tells if the tableSource/tableSink is BatchTableSource/BatchTableSink. // NOTES: this should be false in BLINK planner, because BLINK planner always uses StreamTableSource. private final boolean isBatch; public static <T1> ConnectorCatalogTable source(TableSource<T1> source, boolean isBatch) { final TableSchema tableSchema = calculateSourceSchema(source, isBatch); return new ConnectorCatalogTable<>(source, null, tableSchema, isBatch); } public static <T2> ConnectorCatalogTable sink(TableSink<T2> sink, boolean isBatch) { return new ConnectorCatalogTable<>(null, sink, sink.getTableSchema(), isBatch); } public static <T1, T2> ConnectorCatalogTable sourceAndSink( TableSource<T1> source, TableSink<T2> sink, boolean isBatch) { TableSchema tableSchema = calculateSourceSchema(source, isBatch); return new ConnectorCatalogTable<>(source, sink, tableSchema, isBatch); } @VisibleForTesting protected ConnectorCatalogTable( TableSource<T1> tableSource, TableSink<T2> tableSink, TableSchema tableSchema, boolean isBatch) { super(tableSchema, Collections.emptyMap(), ""); this.tableSource = tableSource; this.tableSink = tableSink; this.isBatch = isBatch; } public Optional<TableSource<T1>> getTableSource() { return Optional.ofNullable(tableSource); } public Optional<TableSink<T2>> getTableSink() { return Optional.ofNullable(tableSink); } public boolean isBatch() { return isBatch; } @Override public Map<String, String> toProperties() { // This effectively makes sure the table cannot be persisted in a catalog. throw new UnsupportedOperationException("ConnectorCatalogTable cannot be converted to properties"); } @Override public CatalogBaseTable copy() { return this; } @Override public Optional<String> getDescription() { return Optional.empty(); } @Override public Optional<String> getDetailedDescription() { return Optional.empty(); } private static <T1> TableSchema calculateSourceSchema(TableSource<T1> source, boolean isBatch) { TableSchema tableSchema = source.getTableSchema(); if (isBatch) { return tableSchema; } DataType[] types = Arrays.copyOf(tableSchema.getFieldDataTypes(), tableSchema.getFieldCount()); String[] fieldNames = tableSchema.getFieldNames(); if (source instanceof DefinedRowtimeAttributes) { updateRowtimeIndicators((DefinedRowtimeAttributes) source, fieldNames, types); } if (source instanceof DefinedProctimeAttribute) { updateProctimeIndicator((DefinedProctimeAttribute) source, fieldNames, types); } return TableSchema.builder().fields(fieldNames, types).build(); } private static void updateRowtimeIndicators( DefinedRowtimeAttributes source, String[] fieldNames, DataType[] types) { List<String> rowtimeAttributes = source.getRowtimeAttributeDescriptors() .stream() .map(RowtimeAttributeDescriptor::getAttributeName) .collect(Collectors.toList()); for (int i = 0; i < fieldNames.length; i++) { if (rowtimeAttributes.contains(fieldNames[i])) { // bridged to timestamp for compatible flink-planner types[i] = new AtomicDataType(new TimestampType(true, TimestampKind.ROWTIME, 3)) .bridgedTo(java.sql.Timestamp.class); } } } private static void updateProctimeIndicator( DefinedProctimeAttribute source, String[] fieldNames, DataType[] types) { String proctimeAttribute = source.getProctimeAttribute(); for (int i = 0; i < fieldNames.length; i++) { if (fieldNames[i].equals(proctimeAttribute)) { // bridged to timestamp for compatible flink-planner types[i] = new AtomicDataType(new TimestampType(true, TimestampKind.PROCTIME, 3)) .bridgedTo(java.sql.Timestamp.class); break; } } } }
flink-table/flink-table-api-java/src/main/java/org/apache/flink/table/catalog/ConnectorCatalogTable.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.flink.table.catalog; import org.apache.flink.annotation.Internal; import org.apache.flink.annotation.VisibleForTesting; import org.apache.flink.api.common.typeinfo.TypeInformation; import org.apache.flink.table.api.TableSchema; import org.apache.flink.table.sinks.TableSink; import org.apache.flink.table.sources.DefinedProctimeAttribute; import org.apache.flink.table.sources.DefinedRowtimeAttributes; import org.apache.flink.table.sources.RowtimeAttributeDescriptor; import org.apache.flink.table.sources.TableSource; import org.apache.flink.table.typeutils.TimeIndicatorTypeInfo; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.stream.Collectors; /** * A {@link CatalogTable} that wraps a {@link TableSource} and/or {@link TableSink}. * This allows registering those in a {@link Catalog}. It can not be persisted as the * source and/or sink might be inline implementations and not be representable in a * property based form. * * @param <T1> type of the produced elements by the {@link TableSource} * @param <T2> type of the expected elements by the {@link TableSink} */ @Internal public class ConnectorCatalogTable<T1, T2> extends AbstractCatalogTable { private final TableSource<T1> tableSource; private final TableSink<T2> tableSink; // Flag that tells if the tableSource/tableSink is BatchTableSource/BatchTableSink. // NOTES: this should be false in BLINK planner, because BLINK planner always uses StreamTableSource. private final boolean isBatch; public static <T1> ConnectorCatalogTable source(TableSource<T1> source, boolean isBatch) { final TableSchema tableSchema = calculateSourceSchema(source, isBatch); return new ConnectorCatalogTable<>(source, null, tableSchema, isBatch); } public static <T2> ConnectorCatalogTable sink(TableSink<T2> sink, boolean isBatch) { return new ConnectorCatalogTable<>(null, sink, sink.getTableSchema(), isBatch); } public static <T1, T2> ConnectorCatalogTable sourceAndSink( TableSource<T1> source, TableSink<T2> sink, boolean isBatch) { TableSchema tableSchema = calculateSourceSchema(source, isBatch); return new ConnectorCatalogTable<>(source, sink, tableSchema, isBatch); } @VisibleForTesting protected ConnectorCatalogTable( TableSource<T1> tableSource, TableSink<T2> tableSink, TableSchema tableSchema, boolean isBatch) { super(tableSchema, Collections.emptyMap(), ""); this.tableSource = tableSource; this.tableSink = tableSink; this.isBatch = isBatch; } public Optional<TableSource<T1>> getTableSource() { return Optional.ofNullable(tableSource); } public Optional<TableSink<T2>> getTableSink() { return Optional.ofNullable(tableSink); } public boolean isBatch() { return isBatch; } @Override public Map<String, String> toProperties() { // This effectively makes sure the table cannot be persisted in a catalog. throw new UnsupportedOperationException("ConnectorCatalogTable cannot be converted to properties"); } @Override public CatalogBaseTable copy() { return this; } @Override public Optional<String> getDescription() { return Optional.empty(); } @Override public Optional<String> getDetailedDescription() { return Optional.empty(); } private static <T1> TableSchema calculateSourceSchema(TableSource<T1> source, boolean isBatch) { TableSchema tableSchema = source.getTableSchema(); if (isBatch) { return tableSchema; } TypeInformation[] types = Arrays.copyOf(tableSchema.getFieldTypes(), tableSchema.getFieldCount()); String[] fieldNames = tableSchema.getFieldNames(); if (source instanceof DefinedRowtimeAttributes) { updateRowtimeIndicators((DefinedRowtimeAttributes) source, fieldNames, types); } if (source instanceof DefinedProctimeAttribute) { updateProctimeIndicator((DefinedProctimeAttribute) source, fieldNames, types); } return new TableSchema(fieldNames, types); } private static void updateRowtimeIndicators( DefinedRowtimeAttributes source, String[] fieldNames, TypeInformation[] types) { List<String> rowtimeAttributes = source.getRowtimeAttributeDescriptors() .stream() .map(RowtimeAttributeDescriptor::getAttributeName) .collect(Collectors.toList()); for (int i = 0; i < fieldNames.length; i++) { if (rowtimeAttributes.contains(fieldNames[i])) { types[i] = TimeIndicatorTypeInfo.ROWTIME_INDICATOR; } } } private static void updateProctimeIndicator( DefinedProctimeAttribute source, String[] fieldNames, TypeInformation[] types) { String proctimeAttribute = source.getProctimeAttribute(); for (int i = 0; i < fieldNames.length; i++) { if (fieldNames[i].equals(proctimeAttribute)) { types[i] = TimeIndicatorTypeInfo.PROCTIME_INDICATOR; break; } } } }
[FLINK-13495][table-api] Use DataType in ConnectorCatalogTable instead of TypeInformation
flink-table/flink-table-api-java/src/main/java/org/apache/flink/table/catalog/ConnectorCatalogTable.java
[FLINK-13495][table-api] Use DataType in ConnectorCatalogTable instead of TypeInformation
<ide><path>link-table/flink-table-api-java/src/main/java/org/apache/flink/table/catalog/ConnectorCatalogTable.java <ide> <ide> import org.apache.flink.annotation.Internal; <ide> import org.apache.flink.annotation.VisibleForTesting; <del>import org.apache.flink.api.common.typeinfo.TypeInformation; <ide> import org.apache.flink.table.api.TableSchema; <ide> import org.apache.flink.table.sinks.TableSink; <ide> import org.apache.flink.table.sources.DefinedProctimeAttribute; <ide> import org.apache.flink.table.sources.DefinedRowtimeAttributes; <ide> import org.apache.flink.table.sources.RowtimeAttributeDescriptor; <ide> import org.apache.flink.table.sources.TableSource; <del>import org.apache.flink.table.typeutils.TimeIndicatorTypeInfo; <add>import org.apache.flink.table.types.AtomicDataType; <add>import org.apache.flink.table.types.DataType; <add>import org.apache.flink.table.types.logical.TimestampKind; <add>import org.apache.flink.table.types.logical.TimestampType; <ide> <ide> import java.util.Arrays; <ide> import java.util.Collections; <ide> return tableSchema; <ide> } <ide> <del> TypeInformation[] types = Arrays.copyOf(tableSchema.getFieldTypes(), tableSchema.getFieldCount()); <add> DataType[] types = Arrays.copyOf(tableSchema.getFieldDataTypes(), tableSchema.getFieldCount()); <ide> String[] fieldNames = tableSchema.getFieldNames(); <ide> if (source instanceof DefinedRowtimeAttributes) { <ide> updateRowtimeIndicators((DefinedRowtimeAttributes) source, fieldNames, types); <ide> if (source instanceof DefinedProctimeAttribute) { <ide> updateProctimeIndicator((DefinedProctimeAttribute) source, fieldNames, types); <ide> } <del> return new TableSchema(fieldNames, types); <add> return TableSchema.builder().fields(fieldNames, types).build(); <ide> } <ide> <ide> private static void updateRowtimeIndicators( <ide> DefinedRowtimeAttributes source, <ide> String[] fieldNames, <del> TypeInformation[] types) { <add> DataType[] types) { <ide> List<String> rowtimeAttributes = source.getRowtimeAttributeDescriptors() <ide> .stream() <ide> .map(RowtimeAttributeDescriptor::getAttributeName) <ide> <ide> for (int i = 0; i < fieldNames.length; i++) { <ide> if (rowtimeAttributes.contains(fieldNames[i])) { <del> types[i] = TimeIndicatorTypeInfo.ROWTIME_INDICATOR; <add> // bridged to timestamp for compatible flink-planner <add> types[i] = new AtomicDataType(new TimestampType(true, TimestampKind.ROWTIME, 3)) <add> .bridgedTo(java.sql.Timestamp.class); <ide> } <ide> } <ide> } <ide> private static void updateProctimeIndicator( <ide> DefinedProctimeAttribute source, <ide> String[] fieldNames, <del> TypeInformation[] types) { <add> DataType[] types) { <ide> String proctimeAttribute = source.getProctimeAttribute(); <ide> <ide> for (int i = 0; i < fieldNames.length; i++) { <ide> if (fieldNames[i].equals(proctimeAttribute)) { <del> types[i] = TimeIndicatorTypeInfo.PROCTIME_INDICATOR; <add> // bridged to timestamp for compatible flink-planner <add> types[i] = new AtomicDataType(new TimestampType(true, TimestampKind.PROCTIME, 3)) <add> .bridgedTo(java.sql.Timestamp.class); <ide> break; <ide> } <ide> }
Java
agpl-3.0
31573637f659d77b1bc61717d2b568f3f033eac4
0
alcarraz/jPOS,jpos/jPOS,jpos/jPOS,barspi/jPOS,alcarraz/jPOS,jpos/jPOS,barspi/jPOS,alcarraz/jPOS,barspi/jPOS
/* * jPOS Project [http://jpos.org] * Copyright (C) 2000-2017 jPOS Software SRL * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.jpos.q2.iso; import org.HdrHistogram.AtomicHistogram; import org.HdrHistogram.Histogram; import org.jdom2.Element; import org.jpos.core.ConfigurationException; import org.jpos.iso.*; import org.jpos.q2.QBeanSupport; import org.jpos.q2.QFactory; import org.jpos.space.*; import org.jpos.util.Chronometer; import org.jpos.util.Loggeable; import org.jpos.util.Metrics; import org.jpos.util.NameRegistrar; import java.io.IOException; import java.io.PrintStream; import java.util.*; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.TimeUnit; /** * @author Alejandro Revilla */ @SuppressWarnings("unchecked") public class QMUX extends QBeanSupport implements SpaceListener, MUX, QMUXMBean, Loggeable { static final String nomap = "0123456789"; static final String DEFAULT_KEY = "41, 11"; protected LocalSpace sp; protected String in, out, unhandled; protected String[] ready; protected String[] key; protected String ignorerc; protected String[] mtiMapping; private boolean headerIsKey; private boolean returnRejects; private LocalSpace isp; // internal space private Map<String,String[]> mtiKey = new HashMap<>(); private Metrics metrics = new Metrics(new AtomicHistogram(60000, 2)); List<ISORequestListener> listeners; int rx, tx, rxExpired, txExpired, rxPending, rxUnhandled, rxForwarded; long lastTxn = 0L; boolean listenerRegistered; public QMUX () { super (); listeners = new ArrayList<ISORequestListener>(); } public void initService () throws ConfigurationException { Element e = getPersist (); sp = grabSpace (e.getChild ("space")); isp = cfg.getBoolean("reuse-space", false) ? sp : new TSpace(); in = e.getChildTextTrim ("in"); out = e.getChildTextTrim ("out"); ignorerc = e.getChildTextTrim ("ignore-rc"); key = toStringArray(DEFAULT_KEY, ", ", null); returnRejects = cfg.getBoolean("return-rejects", false); for (Element keyElement : e.getChildren("key")) { String mtiOverride = keyElement.getAttributeValue("mti"); if (mtiOverride != null && mtiOverride.length() >= 2) { mtiKey.put (mtiOverride.substring(0,2), toStringArray(keyElement.getTextTrim(), ", ", null)); } else { key = toStringArray(e.getChildTextTrim("key"), ", ", DEFAULT_KEY); } } ready = toStringArray(e.getChildTextTrim ("ready")); mtiMapping = toStringArray(e.getChildTextTrim ("mtimapping")); if (mtiMapping == null || mtiMapping.length != 3) mtiMapping = new String[] { nomap, nomap, "0022446789" }; addListeners (); unhandled = e.getChildTextTrim ("unhandled"); NameRegistrar.register ("mux."+getName (), this); } public void startService () { if (!listenerRegistered) { listenerRegistered = true; // Handle messages that could be in the in queue at start time synchronized (sp) { Object[] pending = SpaceUtil.inpAll(sp, in); sp.addListener (in, this); for (Object o : pending) sp.out(in, o); } } } public void stopService () { listenerRegistered = false; sp.removeListener (in, this); } public void destroyService () { NameRegistrar.unregister ("mux."+getName ()); } /** * @return MUX with name using NameRegistrar * @throws NameRegistrar.NotFoundException * @see NameRegistrar */ public static MUX getMUX (String name) throws NameRegistrar.NotFoundException { return (MUX) NameRegistrar.get ("mux."+name); } /** * @param m message to send * @param timeout amount of time in millis to wait for a response * @return response or null */ public ISOMsg request (ISOMsg m, long timeout) throws ISOException { String key = getKey (m); String req = key + ".req"; if (isp.rdp (req) != null) throw new ISOException ("Duplicate key '" + req + "' detected"); isp.out (req, m); m.setDirection(0); Chronometer c = new Chronometer(); if (timeout > 0) sp.out (out, m, timeout); else sp.out (out, m); ISOMsg resp; try { synchronized (this) { tx++; rxPending++; } for (;;) { resp = (ISOMsg) isp.in (key, timeout); if (!shouldIgnore (resp)) break; } if (resp == null && isp.inp (req) == null) { // possible race condition, retry for a few extra seconds resp = (ISOMsg) isp.in (key, 10000); } synchronized (this) { if (resp != null) { rx++; lastTxn = System.currentTimeMillis(); }else { rxExpired++; if (m.getDirection() != ISOMsg.OUTGOING) txExpired++; } } } finally { synchronized (this) { rxPending--; } } long elapsed = c.elapsed(); metrics.record("all", elapsed); if (resp != null) metrics.record("ok", elapsed); return resp; } public void request (ISOMsg m, long timeout, ISOResponseListener rl, Object handBack) throws ISOException { String key = getKey (m); String req = key + ".req"; if (isp.rdp (req) != null) throw new ISOException ("Duplicate key '" + req + "' detected."); m.setDirection(0); AsyncRequest ar = new AsyncRequest (rl, handBack); synchronized (ar) { if (timeout > 0) ar.setFuture(getScheduledThreadPoolExecutor().schedule(ar, timeout, TimeUnit.MILLISECONDS)); } isp.out (req, ar, timeout); if (timeout > 0) sp.out (out, m, timeout); else sp.out (out, m); synchronized (this) { tx++; rxPending++; } } public void notify (Object k, Object value) { Object obj = sp.inp (k); if (obj instanceof ISOMsg) { ISOMsg m = (ISOMsg) obj; try { if (returnRejects || m.isResponse()) { String key = getKey (m); String req = key + ".req"; Object r = isp.inp (req); if (r != null) { if (r instanceof AsyncRequest) { ((AsyncRequest) r).responseReceived (m); } else { isp.out (key, m); } return; } } } catch (ISOException e) { getLog().warn ("notify", e); } processUnhandled (m); } } public String getKey (ISOMsg m) throws ISOException { StringBuilder sb = new StringBuilder (out); sb.append ('.'); sb.append (mapMTI(m.getMTI())); if (headerIsKey && m.getHeader()!=null) { sb.append ('.'); sb.append(ISOUtil.hexString(m.getHeader())); sb.append ('.'); } boolean hasFields = false; String[] k = mtiKey.getOrDefault(m.getMTI().substring(0,2), key); for (String f : k) { String v = m.getString(f); if (v != null) { if ("11".equals(f)) { String vt = v.trim(); int l = m.getMTI().charAt(0) == '2' ? 12 : 6; if (vt.length() < l) v = ISOUtil.zeropad(vt, l); } if ("41".equals(f)) { v = ISOUtil.zeropad(v.trim(), 16); // BIC ANSI to ISO hack } hasFields = true; sb.append(v); } } if (!hasFields) throw new ISOException ("Key fields not found - not sending " + sb.toString()); return sb.toString(); } public Map<String, Histogram> getMetrics() { return metrics.metrics(); } private String mapMTI (String mti) throws ISOException { StringBuilder sb = new StringBuilder(); if (mti != null) { if (mti.length() < 4) mti = ISOUtil.zeropad(mti, 4); // #jPOS-55 if (mti.length() == 4) { for (int i=0; i<mtiMapping.length; i++) { int c = mti.charAt (i) - '0'; if (c >= 0 && c < 10) sb.append (mtiMapping[i].charAt(c)); } } } return sb.toString(); } public synchronized void setInQueue (String in) { this.in = in; getPersist().getChild("in").setText (in); setModified (true); } public String getInQueue () { return in; } public synchronized void setOutQueue (String out) { this.out = out; getPersist().getChild("out").setText (out); setModified (true); } public String getOutQueue () { return out; } public Space getSpace() { return sp; } public synchronized void setUnhandledQueue (String unhandled) { this.unhandled = unhandled; getPersist().getChild("unhandled").setText (unhandled); setModified (true); } public String getUnhandledQueue () { return unhandled; } @SuppressWarnings("unused") public String[] getReadyIndicatorNames() { return ready; } private void addListeners () throws ConfigurationException { QFactory factory = getFactory (); Iterator iter = getPersist().getChildren ( "request-listener" ).iterator(); while (iter.hasNext()) { Element l = (Element) iter.next(); ISORequestListener listener = (ISORequestListener) factory.newInstance (l.getAttributeValue ("class")); factory.setLogger (listener, l); factory.setConfiguration (listener, l); addISORequestListener (listener); } } public void addISORequestListener(ISORequestListener l) { listeners.add (l); } public boolean removeISORequestListener(ISORequestListener l) { return listeners.remove(l); } public synchronized void resetCounters() { rx = tx = rxExpired = txExpired = rxPending = rxUnhandled = rxForwarded = 0; lastTxn = 0l; } public String getCountersAsString () { StringBuffer sb = new StringBuffer(); append (sb, "tx=", tx); append (sb, ", rx=", rx); append (sb, ", tx_expired=", txExpired); append (sb, ", tx_pending=", sp.size(out)); append (sb, ", rx_expired=", rxExpired); append (sb, ", rx_pending=", rxPending); append (sb, ", rx_unhandled=", rxUnhandled); append (sb, ", rx_forwarded=", rxForwarded); sb.append (", connected="); sb.append (Boolean.toString(isConnected())); sb.append (", last="); sb.append (lastTxn); if (lastTxn > 0) { sb.append (", idle="); sb.append(System.currentTimeMillis() - lastTxn); sb.append ("ms"); } return sb.toString(); } public int getTXCounter() { return tx; } public int getRXCounter() { return rx; } public long getLastTxnTimestampInMillis() { return lastTxn; } public long getIdleTimeInMillis() { return lastTxn > 0L ? System.currentTimeMillis() - lastTxn : -1L; } protected void processUnhandled (ISOMsg m) { ISOSource source = m.getSource () != null ? m.getSource() : this; Iterator iter = listeners.iterator(); if (iter.hasNext()) synchronized (this) { rxForwarded++; } while (iter.hasNext()) if (((ISORequestListener)iter.next()).process (source, m)) return; if (unhandled != null) { synchronized (this) { rxUnhandled++; } sp.out (unhandled, m, 120000); } } private LocalSpace grabSpace (Element e) throws ConfigurationException { String uri = e != null ? e.getText() : ""; Space sp = SpaceFactory.getSpace (uri); if (sp instanceof LocalSpace) { return (LocalSpace) sp; } throw new ConfigurationException ("Invalid space " + uri); } /** * sends (or hands back) an ISOMsg * * @param m the Message to be sent * @throws java.io.IOException * @throws org.jpos.iso.ISOException * @throws org.jpos.iso.ISOFilter.VetoException; */ public void send(ISOMsg m) throws IOException, ISOException { if (!isConnected()) throw new ISOException ("MUX is not connected"); sp.out (out, m); } public boolean isConnected() { if (running() && ready != null && ready.length > 0) { for (String aReady : ready) if (sp.rdp(aReady) != null) return true; return false; } return running(); } public void dump (PrintStream p, String indent) { p.println (indent + getCountersAsString()); metrics.dump (p, indent); } private String[] toStringArray(String s, String delimiter, String def) { if (s == null) s = def; String[] arr = null; if (s != null && s.length() > 0) { StringTokenizer st; if (delimiter != null) st = new StringTokenizer(s, delimiter); else st = new StringTokenizer(s); List<String> l = new ArrayList<String>(); while (st.hasMoreTokens()) { String t = st.nextToken(); if ("header".equalsIgnoreCase(t)) { headerIsKey = true; } else { l.add (t); } } arr = l.toArray(new String[l.size()]); } return arr; } private String[] toStringArray(String s) { return toStringArray(s, null,null); } private boolean shouldIgnore (ISOMsg m) { if (m != null && ignorerc != null && ignorerc.length() > 0 && m.hasField(39)) { return ignorerc.contains(m.getString(39)); } return false; } private void append (StringBuffer sb, String name, int value) { sb.append (name); sb.append (value); } public class AsyncRequest implements Runnable { ISOResponseListener rl; Object handBack; ScheduledFuture future; Chronometer chrono; public AsyncRequest (ISOResponseListener rl, Object handBack) { super(); this.rl = rl; this.handBack = handBack; this.chrono = new Chronometer(); } public void setFuture(ScheduledFuture future) { this.future = future; } public void responseReceived (ISOMsg response) { if (future == null || future.cancel(false)) { synchronized (QMUX.this) { rx++; rxPending--; lastTxn = System.currentTimeMillis(); } long elapsed = chrono.elapsed(); metrics.record("all", elapsed); metrics.record("ok", elapsed); rl.responseReceived(response, handBack); } } public void run() { synchronized(QMUX.this) { rxPending--; } metrics.record("all", chrono.elapsed()); rl.expired(handBack); } } }
jpos/src/main/java/org/jpos/q2/iso/QMUX.java
/* * jPOS Project [http://jpos.org] * Copyright (C) 2000-2017 jPOS Software SRL * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.jpos.q2.iso; import org.jdom2.Element; import org.jpos.core.ConfigurationException; import org.jpos.iso.*; import org.jpos.q2.QBeanSupport; import org.jpos.q2.QFactory; import org.jpos.space.*; import org.jpos.util.Loggeable; import org.jpos.util.NameRegistrar; import java.io.IOException; import java.io.PrintStream; import java.util.*; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.TimeUnit; /** * @author Alejandro Revilla */ @SuppressWarnings("unchecked") public class QMUX extends QBeanSupport implements SpaceListener, MUX, QMUXMBean, Loggeable { static final String nomap = "0123456789"; static final String DEFAULT_KEY = "41, 11"; protected LocalSpace sp; protected String in, out, unhandled; protected String[] ready; protected String[] key; protected String ignorerc; protected String[] mtiMapping; private boolean headerIsKey; private boolean returnRejects; private LocalSpace isp; // internal space private Map<String,String[]> mtiKey = new HashMap<>(); List<ISORequestListener> listeners; int rx, tx, rxExpired, txExpired, rxPending, rxUnhandled, rxForwarded; long lastTxn = 0L; boolean listenerRegistered; public QMUX () { super (); listeners = new ArrayList<ISORequestListener>(); } public void initService () throws ConfigurationException { Element e = getPersist (); sp = grabSpace (e.getChild ("space")); isp = cfg.getBoolean("reuse-space", false) ? sp : new TSpace(); in = e.getChildTextTrim ("in"); out = e.getChildTextTrim ("out"); ignorerc = e.getChildTextTrim ("ignore-rc"); key = toStringArray(DEFAULT_KEY, ", ", null); returnRejects = cfg.getBoolean("return-rejects", false); for (Element keyElement : e.getChildren("key")) { String mtiOverride = keyElement.getAttributeValue("mti"); if (mtiOverride != null && mtiOverride.length() >= 2) { mtiKey.put (mtiOverride.substring(0,2), toStringArray(keyElement.getTextTrim(), ", ", null)); } else { key = toStringArray(e.getChildTextTrim("key"), ", ", DEFAULT_KEY); } } ready = toStringArray(e.getChildTextTrim ("ready")); mtiMapping = toStringArray(e.getChildTextTrim ("mtimapping")); if (mtiMapping == null || mtiMapping.length != 3) mtiMapping = new String[] { nomap, nomap, "0022446789" }; addListeners (); unhandled = e.getChildTextTrim ("unhandled"); NameRegistrar.register ("mux."+getName (), this); } public void startService () { if (!listenerRegistered) { listenerRegistered = true; // Handle messages that could be in the in queue at start time synchronized (sp) { Object[] pending = SpaceUtil.inpAll(sp, in); sp.addListener (in, this); for (Object o : pending) sp.out(in, o); } } } public void stopService () { listenerRegistered = false; sp.removeListener (in, this); } public void destroyService () { NameRegistrar.unregister ("mux."+getName ()); } /** * @return MUX with name using NameRegistrar * @throws NameRegistrar.NotFoundException * @see NameRegistrar */ public static MUX getMUX (String name) throws NameRegistrar.NotFoundException { return (MUX) NameRegistrar.get ("mux."+name); } /** * @param m message to send * @param timeout amount of time in millis to wait for a response * @return response or null */ public ISOMsg request (ISOMsg m, long timeout) throws ISOException { String key = getKey (m); String req = key + ".req"; if (isp.rdp (req) != null) throw new ISOException ("Duplicate key '" + req + "' detected"); isp.out (req, m); m.setDirection(0); if (timeout > 0) sp.out (out, m, timeout); else sp.out (out, m); ISOMsg resp; try { synchronized (this) { tx++; rxPending++; } for (;;) { resp = (ISOMsg) isp.in (key, timeout); if (!shouldIgnore (resp)) break; } if (resp == null && isp.inp (req) == null) { // possible race condition, retry for a few extra seconds resp = (ISOMsg) isp.in (key, 10000); } synchronized (this) { if (resp != null) { rx++; lastTxn = System.currentTimeMillis(); }else { rxExpired++; if (m.getDirection() != ISOMsg.OUTGOING) txExpired++; } } } finally { synchronized (this) { rxPending--; } } return resp; } public void request (ISOMsg m, long timeout, ISOResponseListener rl, Object handBack) throws ISOException { String key = getKey (m); String req = key + ".req"; if (isp.rdp (req) != null) throw new ISOException ("Duplicate key '" + req + "' detected."); m.setDirection(0); AsyncRequest ar = new AsyncRequest (rl, handBack); synchronized (ar) { if (timeout > 0) ar.setFuture(getScheduledThreadPoolExecutor().schedule(ar, timeout, TimeUnit.MILLISECONDS)); } isp.out (req, ar, timeout); if (timeout > 0) sp.out (out, m, timeout); else sp.out (out, m); synchronized (this) { tx++; rxPending++; } } public void notify (Object k, Object value) { Object obj = sp.inp (k); if (obj instanceof ISOMsg) { ISOMsg m = (ISOMsg) obj; try { if (returnRejects || m.isResponse()) { String key = getKey (m); String req = key + ".req"; Object r = isp.inp (req); if (r != null) { if (r instanceof AsyncRequest) { ((AsyncRequest) r).responseReceived (m); } else { isp.out (key, m); } return; } } } catch (ISOException e) { getLog().warn ("notify", e); } processUnhandled (m); } } public String getKey (ISOMsg m) throws ISOException { StringBuilder sb = new StringBuilder (out); sb.append ('.'); sb.append (mapMTI(m.getMTI())); if (headerIsKey && m.getHeader()!=null) { sb.append ('.'); sb.append(ISOUtil.hexString(m.getHeader())); sb.append ('.'); } boolean hasFields = false; String[] k = mtiKey.getOrDefault(m.getMTI().substring(0,2), key); for (String f : k) { String v = m.getString(f); if (v != null) { if ("11".equals(f)) { String vt = v.trim(); int l = m.getMTI().charAt(0) == '2' ? 12 : 6; if (vt.length() < l) v = ISOUtil.zeropad(vt, l); } if ("41".equals(f)) { v = ISOUtil.zeropad(v.trim(), 16); // BIC ANSI to ISO hack } hasFields = true; sb.append(v); } } if (!hasFields) throw new ISOException ("Key fields not found - not sending " + sb.toString()); return sb.toString(); } private String mapMTI (String mti) throws ISOException { StringBuilder sb = new StringBuilder(); if (mti != null) { if (mti.length() < 4) mti = ISOUtil.zeropad(mti, 4); // #jPOS-55 if (mti.length() == 4) { for (int i=0; i<mtiMapping.length; i++) { int c = mti.charAt (i) - '0'; if (c >= 0 && c < 10) sb.append (mtiMapping[i].charAt(c)); } } } return sb.toString(); } public synchronized void setInQueue (String in) { this.in = in; getPersist().getChild("in").setText (in); setModified (true); } public String getInQueue () { return in; } public synchronized void setOutQueue (String out) { this.out = out; getPersist().getChild("out").setText (out); setModified (true); } public String getOutQueue () { return out; } public Space getSpace() { return sp; } public synchronized void setUnhandledQueue (String unhandled) { this.unhandled = unhandled; getPersist().getChild("unhandled").setText (unhandled); setModified (true); } public String getUnhandledQueue () { return unhandled; } @SuppressWarnings("unused") public String[] getReadyIndicatorNames() { return ready; } private void addListeners () throws ConfigurationException { QFactory factory = getFactory (); Iterator iter = getPersist().getChildren ( "request-listener" ).iterator(); while (iter.hasNext()) { Element l = (Element) iter.next(); ISORequestListener listener = (ISORequestListener) factory.newInstance (l.getAttributeValue ("class")); factory.setLogger (listener, l); factory.setConfiguration (listener, l); addISORequestListener (listener); } } public void addISORequestListener(ISORequestListener l) { listeners.add (l); } public boolean removeISORequestListener(ISORequestListener l) { return listeners.remove(l); } public synchronized void resetCounters() { rx = tx = rxExpired = txExpired = rxPending = rxUnhandled = rxForwarded = 0; lastTxn = 0l; } public String getCountersAsString () { StringBuffer sb = new StringBuffer(); append (sb, "tx=", tx); append (sb, ", rx=", rx); append (sb, ", tx_expired=", txExpired); append (sb, ", tx_pending=", sp.size(out)); append (sb, ", rx_expired=", rxExpired); append (sb, ", rx_pending=", rxPending); append (sb, ", rx_unhandled=", rxUnhandled); append (sb, ", rx_forwarded=", rxForwarded); sb.append (", connected="); sb.append (Boolean.toString(isConnected())); sb.append (", last="); sb.append (lastTxn); if (lastTxn > 0) { sb.append (", idle="); sb.append(System.currentTimeMillis() - lastTxn); sb.append ("ms"); } return sb.toString(); } public int getTXCounter() { return tx; } public int getRXCounter() { return rx; } public long getLastTxnTimestampInMillis() { return lastTxn; } public long getIdleTimeInMillis() { return lastTxn > 0L ? System.currentTimeMillis() - lastTxn : -1L; } protected void processUnhandled (ISOMsg m) { ISOSource source = m.getSource () != null ? m.getSource() : this; Iterator iter = listeners.iterator(); if (iter.hasNext()) synchronized (this) { rxForwarded++; } while (iter.hasNext()) if (((ISORequestListener)iter.next()).process (source, m)) return; if (unhandled != null) { synchronized (this) { rxUnhandled++; } sp.out (unhandled, m, 120000); } } private LocalSpace grabSpace (Element e) throws ConfigurationException { String uri = e != null ? e.getText() : ""; Space sp = SpaceFactory.getSpace (uri); if (sp instanceof LocalSpace) { return (LocalSpace) sp; } throw new ConfigurationException ("Invalid space " + uri); } /** * sends (or hands back) an ISOMsg * * @param m the Message to be sent * @throws java.io.IOException * @throws org.jpos.iso.ISOException * @throws org.jpos.iso.ISOFilter.VetoException; */ public void send(ISOMsg m) throws IOException, ISOException { if (!isConnected()) throw new ISOException ("MUX is not connected"); sp.out (out, m); } public boolean isConnected() { if (running() && ready != null && ready.length > 0) { for (String aReady : ready) if (sp.rdp(aReady) != null) return true; return false; } return running(); } public void dump (PrintStream p, String indent) { p.println (indent + getCountersAsString()); } private String[] toStringArray(String s, String delimiter, String def) { if (s == null) s = def; String[] arr = null; if (s != null && s.length() > 0) { StringTokenizer st; if (delimiter != null) st = new StringTokenizer(s, delimiter); else st = new StringTokenizer(s); List<String> l = new ArrayList<String>(); while (st.hasMoreTokens()) { String t = st.nextToken(); if ("header".equalsIgnoreCase(t)) { headerIsKey = true; } else { l.add (t); } } arr = l.toArray(new String[l.size()]); } return arr; } private String[] toStringArray(String s) { return toStringArray(s, null,null); } private boolean shouldIgnore (ISOMsg m) { if (m != null && ignorerc != null && ignorerc.length() > 0 && m.hasField(39)) { return ignorerc.contains(m.getString(39)); } return false; } private void append (StringBuffer sb, String name, int value) { sb.append (name); sb.append (value); } public class AsyncRequest implements Runnable { ISOResponseListener rl; Object handBack; ScheduledFuture future; public AsyncRequest (ISOResponseListener rl, Object handBack) { super(); this.rl = rl; this.handBack = handBack; } public void setFuture(ScheduledFuture future) { this.future = future; } public void responseReceived (ISOMsg response) { if (future == null || future.cancel(false)) { synchronized (QMUX.this) { rx++; rxPending--; lastTxn = System.currentTimeMillis(); } rl.responseReceived(response, handBack); } } public void run() { synchronized(QMUX.this) { rxPending--; } rl.expired(handBack); } } }
added metrics
jpos/src/main/java/org/jpos/q2/iso/QMUX.java
added metrics
<ide><path>pos/src/main/java/org/jpos/q2/iso/QMUX.java <ide> <ide> package org.jpos.q2.iso; <ide> <add>import org.HdrHistogram.AtomicHistogram; <add>import org.HdrHistogram.Histogram; <ide> import org.jdom2.Element; <ide> import org.jpos.core.ConfigurationException; <ide> import org.jpos.iso.*; <ide> import org.jpos.q2.QBeanSupport; <ide> import org.jpos.q2.QFactory; <ide> import org.jpos.space.*; <add>import org.jpos.util.Chronometer; <ide> import org.jpos.util.Loggeable; <add>import org.jpos.util.Metrics; <ide> import org.jpos.util.NameRegistrar; <ide> <ide> import java.io.IOException; <ide> private boolean returnRejects; <ide> private LocalSpace isp; // internal space <ide> private Map<String,String[]> mtiKey = new HashMap<>(); <add> private Metrics metrics = new Metrics(new AtomicHistogram(60000, 2)); <ide> <ide> List<ISORequestListener> listeners; <ide> int rx, tx, rxExpired, txExpired, rxPending, rxUnhandled, rxForwarded; <ide> throw new ISOException ("Duplicate key '" + req + "' detected"); <ide> isp.out (req, m); <ide> m.setDirection(0); <add> Chronometer c = new Chronometer(); <ide> if (timeout > 0) <ide> sp.out (out, m, timeout); <ide> else <ide> } finally { <ide> synchronized (this) { rxPending--; } <ide> } <add> long elapsed = c.elapsed(); <add> metrics.record("all", elapsed); <add> if (resp != null) <add> metrics.record("ok", elapsed); <ide> return resp; <ide> } <ide> public void request (ISOMsg m, long timeout, ISOResponseListener rl, Object handBack) <ide> throw new ISOException ("Key fields not found - not sending " + sb.toString()); <ide> return sb.toString(); <ide> } <add> <add> public Map<String, Histogram> getMetrics() { <add> return metrics.metrics(); <add> } <add> <ide> private String mapMTI (String mti) throws ISOException { <ide> StringBuilder sb = new StringBuilder(); <ide> if (mti != null) { <ide> } <ide> public void dump (PrintStream p, String indent) { <ide> p.println (indent + getCountersAsString()); <add> metrics.dump (p, indent); <ide> } <ide> private String[] toStringArray(String s, String delimiter, String def) { <ide> if (s == null) <ide> ISOResponseListener rl; <ide> Object handBack; <ide> ScheduledFuture future; <add> Chronometer chrono; <ide> public AsyncRequest (ISOResponseListener rl, Object handBack) { <ide> super(); <ide> this.rl = rl; <ide> this.handBack = handBack; <add> this.chrono = new Chronometer(); <ide> } <ide> public void setFuture(ScheduledFuture future) { <ide> this.future = future; <ide> rxPending--; <ide> lastTxn = System.currentTimeMillis(); <ide> } <add> long elapsed = chrono.elapsed(); <add> metrics.record("all", elapsed); <add> metrics.record("ok", elapsed); <ide> rl.responseReceived(response, handBack); <ide> } <ide> } <ide> synchronized(QMUX.this) { <ide> rxPending--; <ide> } <add> metrics.record("all", chrono.elapsed()); <ide> rl.expired(handBack); <ide> } <ide> }
Java
apache-2.0
f460e5d0831e8c497179c7edbf1e66f992f09cf0
0
fubuki/elasticsearch,fubuki/elasticsearch,fubuki/elasticsearch,fubuki/elasticsearch,fubuki/elasticsearch,fubuki/elasticsearch
/* * Licensed to Elasticsearch under one or more contributor * license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright * ownership. Elasticsearch 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.elasticsearch.transport; import com.google.common.collect.ImmutableMap; import org.elasticsearch.Version; import org.elasticsearch.action.admin.cluster.repositories.verify.VerifyRepositoryAction; import org.elasticsearch.action.admin.indices.get.GetIndexAction; import org.elasticsearch.action.exists.ExistsAction; import org.elasticsearch.action.fieldstats.FieldStatsAction; import org.elasticsearch.action.indexedscripts.delete.DeleteIndexedScriptAction; import org.elasticsearch.action.indexedscripts.get.GetIndexedScriptAction; import org.elasticsearch.action.indexedscripts.put.PutIndexedScriptAction; import org.elasticsearch.cluster.node.DiscoveryNode; import org.elasticsearch.cluster.node.DiscoveryNodes; import org.elasticsearch.discovery.zen.ping.unicast.UnicastZenPing; import org.elasticsearch.indices.store.IndicesStore; import org.elasticsearch.repositories.VerifyNodeRepositoryAction; import org.elasticsearch.search.action.SearchServiceTransportAction; import org.elasticsearch.test.ElasticsearchBackwardsCompatIntegrationTest; import org.elasticsearch.test.InternalTestCluster; import org.elasticsearch.threadpool.ThreadPool; import org.junit.Test; import java.util.HashMap; import java.util.Map; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicReference; import static org.hamcrest.CoreMatchers.*; /** * This test verifies the backwards compatibility mechanism that allowed us to rename the action names in a bwc manner, * by converting the new name to the old one when needed. * * Actions that get added after 1.4.0 don't need any renaming/mapping, thus this test needs to be instructed to * ignore those actions by adding them to the actionsVersions map, as it is fine to not have a mapping for those.DOCS */ public class ActionNamesBackwardsCompatibilityTest extends ElasticsearchBackwardsCompatIntegrationTest { private static final Map<String, Version> actionsVersions = new HashMap<>(); static { actionsVersions.put(GetIndexAction.NAME, Version.V_1_4_0_Beta1); actionsVersions.put(ExistsAction.NAME, Version.V_1_4_0_Beta1); actionsVersions.put(ExistsAction.NAME + "[s]", Version.V_1_4_0_Beta1); actionsVersions.put(FieldStatsAction.NAME, Version.V_1_6_0); actionsVersions.put(FieldStatsAction.NAME + "[s]", Version.V_1_6_0); actionsVersions.put(IndicesStore.ACTION_SHARD_EXISTS, Version.V_1_3_0); actionsVersions.put(GetIndexedScriptAction.NAME, Version.V_1_3_0); actionsVersions.put(DeleteIndexedScriptAction.NAME, Version.V_1_3_0); actionsVersions.put(PutIndexedScriptAction.NAME, Version.V_1_3_0); actionsVersions.put(UnicastZenPing.ACTION_NAME_GTE_1_4, Version.V_1_4_0_Beta1); actionsVersions.put(SearchServiceTransportAction.FREE_CONTEXT_SCROLL_ACTION_NAME, Version.V_1_4_0_Beta1); actionsVersions.put(SearchServiceTransportAction.FETCH_ID_SCROLL_ACTION_NAME, Version.V_1_4_0_Beta1); actionsVersions.put(VerifyRepositoryAction.NAME, Version.V_1_4_0); actionsVersions.put(VerifyNodeRepositoryAction.ACTION_NAME, Version.V_1_4_0); } @Test @SuppressWarnings("unchecked") public void testTransportHandlers() throws NoSuchFieldException, IllegalAccessException, InterruptedException { InternalTestCluster internalCluster = backwardsCluster().internalCluster(); TransportService transportService = internalCluster.getInstance(TransportService.class); ImmutableMap<String, TransportRequestHandler> requestHandlers = transportService.serverHandlers; DiscoveryNodes nodes = client().admin().cluster().prepareState().get().getState().nodes(); DiscoveryNode selectedNode = null; for (DiscoveryNode node : nodes) { if (node.getVersion().before(Version.CURRENT)) { selectedNode = node; break; } } assertThat(selectedNode, notNullValue()); final TransportRequest transportRequest = new TransportRequest() {}; for (String action : requestHandlers.keySet()) { final CountDownLatch latch = new CountDownLatch(1); final AtomicReference<TransportException> failure = new AtomicReference<>(); transportService.sendRequest(selectedNode, action, transportRequest, new TransportResponseHandler<TransportResponse>() { @Override public TransportResponse newInstance() { return new TransportResponse() {}; } @Override public void handleResponse(TransportResponse response) { latch.countDown(); } @Override public void handleException(TransportException exp) { failure.set(exp); latch.countDown(); } @Override public String executor() { return ThreadPool.Names.SAME; } }); assertThat(latch.await(5, TimeUnit.SECONDS), equalTo(true)); if (failure.get() != null) { Throwable cause = failure.get().unwrapCause(); if (isActionNotFoundExpected(selectedNode.version(), action)) { assertThat(cause, instanceOf(ActionNotFoundTransportException.class)); } else { assertThat(cause, not(instanceOf(ActionNotFoundTransportException.class))); if (! (cause instanceof IndexOutOfBoundsException)) { cause.printStackTrace(); } } } } } private static boolean isActionNotFoundExpected(Version version, String action) { Version actionVersion = actionsVersions.get(action); return actionVersion != null && version.before(actionVersion); } }
src/test/java/org/elasticsearch/transport/ActionNamesBackwardsCompatibilityTest.java
/* * Licensed to Elasticsearch under one or more contributor * license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright * ownership. Elasticsearch 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.elasticsearch.transport; import com.google.common.collect.ImmutableMap; import org.elasticsearch.Version; import org.elasticsearch.action.admin.cluster.repositories.verify.VerifyRepositoryAction; import org.elasticsearch.action.admin.indices.get.GetIndexAction; import org.elasticsearch.action.exists.ExistsAction; import org.elasticsearch.action.fieldstats.FieldStatsAction; import org.elasticsearch.action.indexedscripts.delete.DeleteIndexedScriptAction; import org.elasticsearch.action.indexedscripts.get.GetIndexedScriptAction; import org.elasticsearch.action.indexedscripts.put.PutIndexedScriptAction; import org.elasticsearch.cluster.node.DiscoveryNode; import org.elasticsearch.cluster.node.DiscoveryNodes; import org.elasticsearch.discovery.zen.ping.unicast.UnicastZenPing; import org.elasticsearch.indices.store.IndicesStore; import org.elasticsearch.search.action.SearchServiceTransportAction; import org.elasticsearch.repositories.VerifyNodeRepositoryAction; import org.elasticsearch.test.ElasticsearchBackwardsCompatIntegrationTest; import org.elasticsearch.test.InternalTestCluster; import org.elasticsearch.threadpool.ThreadPool; import org.junit.Test; import java.util.HashMap; import java.util.Map; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicReference; import static org.hamcrest.CoreMatchers.*; /** * This test verifies the backwards compatibility mechanism that allowed us to rename the action names in a bwc manner, * by converting the new name to the old one when needed. * * Actions that get added after 1.4.0 don't need any renaming/mapping, thus this test needs to be instructed to * ignore those actions by adding them to the actionsVersions map, as it is fine to not have a mapping for those.DOCS */ public class ActionNamesBackwardsCompatibilityTest extends ElasticsearchBackwardsCompatIntegrationTest { private static final Map<String, Version> actionsVersions = new HashMap<>(); static { actionsVersions.put(GetIndexAction.NAME, Version.V_1_4_0_Beta1); actionsVersions.put(ExistsAction.NAME, Version.V_1_4_0_Beta1); actionsVersions.put(ExistsAction.NAME + "[s]", Version.V_1_4_0_Beta1); actionsVersions.put(FieldStatsAction.NAME, Version.V_1_4_0_Beta1); actionsVersions.put(FieldStatsAction.NAME + "[s]", Version.V_1_4_0_Beta1); actionsVersions.put(IndicesStore.ACTION_SHARD_EXISTS, Version.V_1_3_0); actionsVersions.put(GetIndexedScriptAction.NAME, Version.V_1_3_0); actionsVersions.put(DeleteIndexedScriptAction.NAME, Version.V_1_3_0); actionsVersions.put(PutIndexedScriptAction.NAME, Version.V_1_3_0); actionsVersions.put(UnicastZenPing.ACTION_NAME_GTE_1_4, Version.V_1_4_0_Beta1); actionsVersions.put(SearchServiceTransportAction.FREE_CONTEXT_SCROLL_ACTION_NAME, Version.V_1_4_0_Beta1); actionsVersions.put(SearchServiceTransportAction.FETCH_ID_SCROLL_ACTION_NAME, Version.V_1_4_0_Beta1); actionsVersions.put(VerifyRepositoryAction.NAME, Version.V_1_4_0); actionsVersions.put(VerifyNodeRepositoryAction.ACTION_NAME, Version.V_1_4_0); } @Test @SuppressWarnings("unchecked") public void testTransportHandlers() throws NoSuchFieldException, IllegalAccessException, InterruptedException { InternalTestCluster internalCluster = backwardsCluster().internalCluster(); TransportService transportService = internalCluster.getInstance(TransportService.class); ImmutableMap<String, TransportRequestHandler> requestHandlers = transportService.serverHandlers; DiscoveryNodes nodes = client().admin().cluster().prepareState().get().getState().nodes(); DiscoveryNode selectedNode = null; for (DiscoveryNode node : nodes) { if (node.getVersion().before(Version.CURRENT)) { selectedNode = node; break; } } assertThat(selectedNode, notNullValue()); final TransportRequest transportRequest = new TransportRequest() {}; for (String action : requestHandlers.keySet()) { final CountDownLatch latch = new CountDownLatch(1); final AtomicReference<TransportException> failure = new AtomicReference<>(); transportService.sendRequest(selectedNode, action, transportRequest, new TransportResponseHandler<TransportResponse>() { @Override public TransportResponse newInstance() { return new TransportResponse() {}; } @Override public void handleResponse(TransportResponse response) { latch.countDown(); } @Override public void handleException(TransportException exp) { failure.set(exp); latch.countDown(); } @Override public String executor() { return ThreadPool.Names.SAME; } }); assertThat(latch.await(5, TimeUnit.SECONDS), equalTo(true)); if (failure.get() != null) { Throwable cause = failure.get().unwrapCause(); if (isActionNotFoundExpected(selectedNode.version(), action)) { assertThat(cause, instanceOf(ActionNotFoundTransportException.class)); } else { assertThat(cause, not(instanceOf(ActionNotFoundTransportException.class))); if (! (cause instanceof IndexOutOfBoundsException)) { cause.printStackTrace(); } } } } } private static boolean isActionNotFoundExpected(Version version, String action) { Version actionVersion = actionsVersions.get(action); return actionVersion != null && version.before(actionVersion); } }
test: add exception for field stats api
src/test/java/org/elasticsearch/transport/ActionNamesBackwardsCompatibilityTest.java
test: add exception for field stats api
<ide><path>rc/test/java/org/elasticsearch/transport/ActionNamesBackwardsCompatibilityTest.java <ide> import org.elasticsearch.cluster.node.DiscoveryNodes; <ide> import org.elasticsearch.discovery.zen.ping.unicast.UnicastZenPing; <ide> import org.elasticsearch.indices.store.IndicesStore; <add>import org.elasticsearch.repositories.VerifyNodeRepositoryAction; <ide> import org.elasticsearch.search.action.SearchServiceTransportAction; <del>import org.elasticsearch.repositories.VerifyNodeRepositoryAction; <ide> import org.elasticsearch.test.ElasticsearchBackwardsCompatIntegrationTest; <ide> import org.elasticsearch.test.InternalTestCluster; <ide> import org.elasticsearch.threadpool.ThreadPool; <ide> actionsVersions.put(ExistsAction.NAME, Version.V_1_4_0_Beta1); <ide> actionsVersions.put(ExistsAction.NAME + "[s]", Version.V_1_4_0_Beta1); <ide> <del> actionsVersions.put(FieldStatsAction.NAME, Version.V_1_4_0_Beta1); <del> actionsVersions.put(FieldStatsAction.NAME + "[s]", Version.V_1_4_0_Beta1); <add> actionsVersions.put(FieldStatsAction.NAME, Version.V_1_6_0); <add> actionsVersions.put(FieldStatsAction.NAME + "[s]", Version.V_1_6_0); <ide> <ide> actionsVersions.put(IndicesStore.ACTION_SHARD_EXISTS, Version.V_1_3_0); <ide>
Java
apache-2.0
cca887b51ee07da85793ccbb9adc1cd856eb647c
0
google/error-prone,google/error-prone
/* * Copyright 2021 The Error Prone 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.errorprone.bugpatterns; import com.google.errorprone.CompilationTestHelper; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /** Unit tests for {@link AlreadyChecked}. */ @RunWith(JUnit4.class) public final class AlreadyCheckedTest { private final CompilationTestHelper helper = CompilationTestHelper.newInstance(AlreadyChecked.class, getClass()); @Test public void elseChecksSameVariable() { helper .addSourceLines( "Test.java", "class Test {", " public void test(boolean a) {", " if (a) {", " // BUG: Diagnostic contains: false", " } else if (a) {}", " }", "}") .doTest(); } @Test public void thisAndThat() { helper .addSourceLines( "Test.java", "class Test {", " public void test(boolean a, boolean b) {", " if (a && b) {", " } else if (a) {", " } else if (b) {}", " }", "}") .doTest(); } @Test public void guardBlock() { helper .addSourceLines( "Test.java", "class Test {", " public void test(boolean a) {", " if (a) {", " return;", " }", " // BUG: Diagnostic contains: false", " if (a) {}", " }", "}") .doTest(); } @Test public void guardBlock_returnFromElse() { helper .addSourceLines( "Test.java", "class Test {", " public void test(boolean a) {", " if (!a) {", " } else {", " return;", " }", " // BUG: Diagnostic contains: false", " if (a) {}", " }", "}") .doTest(); } @Test public void withinLambda() { helper .addSourceLines( "Test.java", "import java.util.stream.Stream;", "class Test {", " public Stream<String> test(Stream<String> xs, String x) {", " if (x.isEmpty()) {", " return Stream.empty();", " }", " return xs.filter(", " // BUG: Diagnostic contains: x.isEmpty()", " y -> x.isEmpty() || y.equals(x));", " }", "}") .doTest(); } @Test public void checkedInDifferentMethods() { helper .addSourceLines( "Test.java", "import com.google.common.collect.ImmutableList;", "class Test {", " private final ImmutableList<Integer> foos = null;", " public boolean a() {", " if (foos.isEmpty()) {", " return true;", " }", " return false;", " }", " public boolean b() {", " return foos.isEmpty();", " }", "}") .doTest(); } @Test public void checkedInLambdaAndAfter() { helper .addSourceLines( "Test.java", "import com.google.common.collect.ImmutableList;", "class Test {", " private final ImmutableList<Integer> foos = null;", " public boolean a() {", " ImmutableList.of().stream().anyMatch(x -> true);", " if (foos.isEmpty()) {", " return true;", " }", " // BUG: Diagnostic contains:", " return foos.isEmpty();", " }", "}") .doTest(); } @Test public void sameVariableCheckedTwice() { helper .addSourceLines( "Test.java", "class Test {", " public void test(boolean a) {", " if (a) {", " // BUG: Diagnostic contains: true", " if (a) {}", " }", " }", "}") .doTest(); } @Test public void sameVariableCheckedThrice() { helper .addSourceLines( "Test.java", "class Test {", " public void test(boolean a) {", " if (a) {", " // BUG: Diagnostic contains: true", " if (a) {}", " // BUG: Diagnostic contains: true", " if (a) {}", " }", " }", "}") .doTest(); } @Test public void sameVariableCheckedTwice_negated() { helper .addSourceLines( "Test.java", "class Test {", " public void test(boolean a) {", " if (a) {", " // BUG: Diagnostic contains: true", " if (!a) {}", " }", " }", "}") .doTest(); } @Test public void sameVariableCheckedTwice_atTopLevel() { helper .addSourceLines( "Test.java", "class Test {", " public void test(boolean a) {", " if (a) {}", " if (a) {}", " }", "}") .doTest(); } @Test public void sameVariableCheckedTwice_asPartOfAnd() { helper .addSourceLines( "Test.java", "class Test {", " public void test(boolean a, boolean b, boolean c) {", " if (a && b) {", " // BUG: Diagnostic contains: true", " if (a && c) {}", " }", " }", "}") .doTest(); } @Test public void sameVariableCheckedTwice_butOuterIfNotSimple() { helper .addSourceLines( "Test.java", "class Test {", " public void test(boolean a, boolean b, boolean c) {", " if ((a && b) || b) {", " if (a && c) {}", " }", " }", "}") .doTest(); } @Test public void complexExpression() { helper .addSourceLines( "Test.java", "class Test {", " public void test(boolean a, boolean b, boolean c) {", " if (!a || (b && c)) {", " } else if (b) {}", " }", "}") .doTest(); } @Test public void notFinal_noFinding() { helper .addSourceLines( "Test.java", "class Test {", " public void test(boolean a) {", " a = true;", " if (a) {", " } else if (a) {}", " }", "}") .doTest(); } @Test public void ternaryWithinIf() { helper .addSourceLines( "Test.java", "class Test {", " public int test(boolean a) {", " if (a) {", " // BUG: Diagnostic contains: true", " return a ? 1 : 2;", " }", " return 0;", " }", "}") .doTest(); } @Test public void equalsCheckedTwice() { helper .addSourceLines( "Test.java", "class Test {", " public int test(String a) {", " if (a.equals(\"a\")) {", " // BUG: Diagnostic contains: true", " return a.equals(\"a\") ? 1 : 2;", " }", " return 0;", " }", "}") .doTest(); } @Test public void equalsCheckedTwice_comparedToDifferentConstant() { helper .addSourceLines( "Test.java", "class Test {", " public int test(String a) {", " if (a.equals(\"b\")) {", " return a.equals(\"a\") ? 1 : 2;", " }", " return 0;", " }", "}") .doTest(); } @Test public void comparedUsingBinaryEquals() { helper .addSourceLines( "Test.java", "class Test {", " public int test(int a, int b) {", " if (a == 1) {", " if (a == b) {", " return 3;", " }", " // BUG: Diagnostic contains:", " return a != 1 ? 1 : 2;", " }", " return 0;", " }", "}") .doTest(); } @Test public void checkedTwiceWithinTernary() { helper .addSourceLines( "Test.java", "class Test {", " public int test(int a) {", " // BUG: Diagnostic contains:", " return a == 1 ? (a == 1 ? 1 : 2) : 2;", " }", "}") .doTest(); } @Test public void durationsComparedUsingFactoryMethods() { helper .addSourceLines( "Test.java", "import java.time.Duration;", "class Test {", " public void test(Duration a, Duration b) {", " if (a.equals(Duration.ofSeconds(1))) {", " if (a.equals(Duration.ofSeconds(2))) {}", " // BUG: Diagnostic contains:", " if (a.equals(Duration.ofSeconds(1))) {}", " }", " }", "}") .doTest(); } @Test public void autoValues() { helper .addSourceLines( "Test.java", "import com.google.auto.value.AutoValue;", "class Test {", " public void test(Foo a, Foo b) {", " if (a.bar().equals(\"foo\") && a.bar().equals(b.bar())) {", " // BUG: Diagnostic contains:", " if (a.bar().equals(\"foo\")) {}", " // BUG: Diagnostic contains:", " if (a.bar().equals(b.bar())) {}", " }", " }", " @AutoValue abstract static class Foo {", " abstract String bar();", " }", "}") .doTest(); } @Test public void autoValue_withEnum() { helper .addSourceLines( "Test.java", "import com.google.auto.value.AutoValue;", "import com.google.errorprone.annotations.Immutable;", "class Test {", " public void test(Foo a, Foo b) {", " if (a.bar().equals(E.A)) {", " // BUG: Diagnostic contains:", " if (a.bar().equals(E.A)) {}", " }", " }", " @AutoValue abstract static class Foo {", " abstract E bar();", " }", " @Immutable", " private enum E {", " A", " }", "}") .doTest(); } @Test public void fieldCheckedTwice() { helper .addSourceLines( "Test.java", "import com.google.auto.value.AutoValue;", "class Test {", " private final String a = \"foo\";", " public void test(String a) {", " if (this.a.equals(a)) {", " // BUG: Diagnostic contains:", " if (this.a.equals(a)) {}", " }", " }", "}") .doTest(); } @Test public void knownQuantityPassedToMethod() { helper .addSourceLines( "Test.java", "import com.google.auto.value.AutoValue;", "class Test {", " void test(boolean a) {", " if (a) {", " set(a);", " }", " }", " void set(boolean a) {}", "}") .doTest(); } @Test public void equalsCalledTwiceOnMutableType_noFinding() { helper .addSourceLines( "Test.java", "import java.util.List;", "class Test {", " private final List<String> xs = null;", " public boolean e(List<String> ys) {", " if (xs.equals(ys)) {", " return true;", " }", " return xs.equals(ys);", " }", "}") .doTest(); } }
core/src/test/java/com/google/errorprone/bugpatterns/AlreadyCheckedTest.java
/* * Copyright 2021 The Error Prone 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.errorprone.bugpatterns; import com.google.errorprone.CompilationTestHelper; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /** Unit tests for {@link AlreadyChecked}. */ @RunWith(JUnit4.class) public final class AlreadyCheckedTest { private final CompilationTestHelper helper = CompilationTestHelper.newInstance(AlreadyChecked.class, getClass()); @Test public void elseChecksSameVariable() { helper .addSourceLines( "Test.java", "class Test {", " public void test(boolean a) {", " if (a) {", " // BUG: Diagnostic contains: false", " } else if (a) {}", " }", "}") .doTest(); } @Test public void guardBlock() { helper .addSourceLines( "Test.java", "class Test {", " public void test(boolean a) {", " if (a) {", " return;", " }", " // BUG: Diagnostic contains: false", " if (a) {}", " }", "}") .doTest(); } @Test public void guardBlock_returnFromElse() { helper .addSourceLines( "Test.java", "class Test {", " public void test(boolean a) {", " if (!a) {", " } else {", " return;", " }", " // BUG: Diagnostic contains: false", " if (a) {}", " }", "}") .doTest(); } @Test public void withinLambda() { helper .addSourceLines( "Test.java", "import java.util.stream.Stream;", "class Test {", " public Stream<String> test(Stream<String> xs, String x) {", " if (x.isEmpty()) {", " return Stream.empty();", " }", " return xs.filter(", " // BUG: Diagnostic contains: x.isEmpty()", " y -> x.isEmpty() || y.equals(x));", " }", "}") .doTest(); } @Test public void checkedInDifferentMethods() { helper .addSourceLines( "Test.java", "import com.google.common.collect.ImmutableList;", "class Test {", " private final ImmutableList<Integer> foos = null;", " public boolean a() {", " if (foos.isEmpty()) {", " return true;", " }", " return false;", " }", " public boolean b() {", " return foos.isEmpty();", " }", "}") .doTest(); } @Test public void checkedInLambdaAndAfter() { helper .addSourceLines( "Test.java", "import com.google.common.collect.ImmutableList;", "class Test {", " private final ImmutableList<Integer> foos = null;", " public boolean a() {", " ImmutableList.of().stream().anyMatch(x -> true);", " if (foos.isEmpty()) {", " return true;", " }", " // BUG: Diagnostic contains:", " return foos.isEmpty();", " }", "}") .doTest(); } @Test public void sameVariableCheckedTwice() { helper .addSourceLines( "Test.java", "class Test {", " public void test(boolean a) {", " if (a) {", " // BUG: Diagnostic contains: true", " if (a) {}", " }", " }", "}") .doTest(); } @Test public void sameVariableCheckedThrice() { helper .addSourceLines( "Test.java", "class Test {", " public void test(boolean a) {", " if (a) {", " // BUG: Diagnostic contains: true", " if (a) {}", " // BUG: Diagnostic contains: true", " if (a) {}", " }", " }", "}") .doTest(); } @Test public void sameVariableCheckedTwice_negated() { helper .addSourceLines( "Test.java", "class Test {", " public void test(boolean a) {", " if (a) {", " // BUG: Diagnostic contains: true", " if (!a) {}", " }", " }", "}") .doTest(); } @Test public void sameVariableCheckedTwice_atTopLevel() { helper .addSourceLines( "Test.java", "class Test {", " public void test(boolean a) {", " if (a) {}", " if (a) {}", " }", "}") .doTest(); } @Test public void sameVariableCheckedTwice_asPartOfAnd() { helper .addSourceLines( "Test.java", "class Test {", " public void test(boolean a, boolean b, boolean c) {", " if (a && b) {", " // BUG: Diagnostic contains: true", " if (a && c) {}", " }", " }", "}") .doTest(); } @Test public void sameVariableCheckedTwice_butOuterIfNotSimple() { helper .addSourceLines( "Test.java", "class Test {", " public void test(boolean a, boolean b, boolean c) {", " if ((a && b) || b) {", " if (a && c) {}", " }", " }", "}") .doTest(); } @Test public void complexExpression() { helper .addSourceLines( "Test.java", "class Test {", " public void test(boolean a, boolean b, boolean c) {", " if (!a || (b && c)) {", " } else if (b) {}", " }", "}") .doTest(); } @Test public void notFinal_noFinding() { helper .addSourceLines( "Test.java", "class Test {", " public void test(boolean a) {", " a = true;", " if (a) {", " } else if (a) {}", " }", "}") .doTest(); } @Test public void ternaryWithinIf() { helper .addSourceLines( "Test.java", "class Test {", " public int test(boolean a) {", " if (a) {", " // BUG: Diagnostic contains: true", " return a ? 1 : 2;", " }", " return 0;", " }", "}") .doTest(); } @Test public void equalsCheckedTwice() { helper .addSourceLines( "Test.java", "class Test {", " public int test(String a) {", " if (a.equals(\"a\")) {", " // BUG: Diagnostic contains: true", " return a.equals(\"a\") ? 1 : 2;", " }", " return 0;", " }", "}") .doTest(); } @Test public void equalsCheckedTwice_comparedToDifferentConstant() { helper .addSourceLines( "Test.java", "class Test {", " public int test(String a) {", " if (a.equals(\"b\")) {", " return a.equals(\"a\") ? 1 : 2;", " }", " return 0;", " }", "}") .doTest(); } @Test public void comparedUsingBinaryEquals() { helper .addSourceLines( "Test.java", "class Test {", " public int test(int a, int b) {", " if (a == 1) {", " if (a == b) {", " return 3;", " }", " // BUG: Diagnostic contains:", " return a != 1 ? 1 : 2;", " }", " return 0;", " }", "}") .doTest(); } @Test public void checkedTwiceWithinTernary() { helper .addSourceLines( "Test.java", "class Test {", " public int test(int a) {", " // BUG: Diagnostic contains:", " return a == 1 ? (a == 1 ? 1 : 2) : 2;", " }", "}") .doTest(); } @Test public void durationsComparedUsingFactoryMethods() { helper .addSourceLines( "Test.java", "import java.time.Duration;", "class Test {", " public void test(Duration a, Duration b) {", " if (a.equals(Duration.ofSeconds(1))) {", " if (a.equals(Duration.ofSeconds(2))) {}", " // BUG: Diagnostic contains:", " if (a.equals(Duration.ofSeconds(1))) {}", " }", " }", "}") .doTest(); } @Test public void autoValues() { helper .addSourceLines( "Test.java", "import com.google.auto.value.AutoValue;", "class Test {", " public void test(Foo a, Foo b) {", " if (a.bar().equals(\"foo\") && a.bar().equals(b.bar())) {", " // BUG: Diagnostic contains:", " if (a.bar().equals(\"foo\")) {}", " // BUG: Diagnostic contains:", " if (a.bar().equals(b.bar())) {}", " }", " }", " @AutoValue abstract static class Foo {", " abstract String bar();", " }", "}") .doTest(); } @Test public void autoValue_withEnum() { helper .addSourceLines( "Test.java", "import com.google.auto.value.AutoValue;", "import com.google.errorprone.annotations.Immutable;", "class Test {", " public void test(Foo a, Foo b) {", " if (a.bar().equals(E.A)) {", " // BUG: Diagnostic contains:", " if (a.bar().equals(E.A)) {}", " }", " }", " @AutoValue abstract static class Foo {", " abstract E bar();", " }", " @Immutable", " private enum E {", " A", " }", "}") .doTest(); } @Test public void fieldCheckedTwice() { helper .addSourceLines( "Test.java", "import com.google.auto.value.AutoValue;", "class Test {", " private final String a = \"foo\";", " public void test(String a) {", " if (this.a.equals(a)) {", " // BUG: Diagnostic contains:", " if (this.a.equals(a)) {}", " }", " }", "}") .doTest(); } @Test public void knownQuantityPassedToMethod() { helper .addSourceLines( "Test.java", "import com.google.auto.value.AutoValue;", "class Test {", " void test(boolean a) {", " if (a) {", " set(a);", " }", " }", " void set(boolean a) {}", "}") .doTest(); } @Test public void equalsCalledTwiceOnMutableType_noFinding() { helper .addSourceLines( "Test.java", "import java.util.List;", "class Test {", " private final List<String> xs = null;", " public boolean e(List<String> ys) {", " if (xs.equals(ys)) {", " return true;", " }", " return xs.equals(ys);", " }", "}") .doTest(); } }
Add a regression test for https://github.com/google/error-prone/issues/2928 Must've already been fixed. PiperOrigin-RevId: 427168692
core/src/test/java/com/google/errorprone/bugpatterns/AlreadyCheckedTest.java
Add a regression test for https://github.com/google/error-prone/issues/2928
<ide><path>ore/src/test/java/com/google/errorprone/bugpatterns/AlreadyCheckedTest.java <ide> } <ide> <ide> @Test <add> public void thisAndThat() { <add> helper <add> .addSourceLines( <add> "Test.java", <add> "class Test {", <add> " public void test(boolean a, boolean b) {", <add> " if (a && b) {", <add> " } else if (a) {", <add> " } else if (b) {}", <add> " }", <add> "}") <add> .doTest(); <add> } <add> <add> @Test <ide> public void guardBlock() { <ide> helper <ide> .addSourceLines(
Java
mit
33017b957c4f503db52f2f09f3e89146f232b9f9
0
aterai/java-swing-tips,aterai/java-swing-tips,aterai/java-swing-tips,aterai/java-swing-tips
package example; //-*- mode:java; encoding:utf-8 -*- // vim:set fileencoding=utf-8: //@homepage@ import java.awt.*; import java.awt.event.*; import java.awt.geom.*; import java.util.Objects; import java.util.regex.*; import javax.swing.*; import javax.swing.plaf.metal.MetalScrollBarUI; import javax.swing.text.*; import com.sun.java.swing.plaf.windows.WindowsScrollBarUI; public class MainPanel extends JPanel { protected static final String PATTERN = "Swing"; protected static final String INITTXT = "Trail: Creating a GUI with JFC/Swing\n" + "Lesson: Learning Swing by Example\n" + "This lesson explains the concepts you need to\n" + " use Swing components in building a user interface.\n" + " First we examine the simplest Swing application you can write.\n" + " Then we present several progressively complicated examples of creating\n" + " user interfaces using components in the javax.swing package.\n" + " We cover several Swing components, such as buttons, labels, and text areas.\n" + " The handling of events is also discussed,\n" + " as are layout management and accessibility.\n" + " This lesson ends with a set of questions and exercises\n" + " so you can test yourself on what you've learned.\n" + "https://docs.oracle.com/javase/tutorial/uiswing/learn/index.html\n"; protected final transient Highlighter.HighlightPainter highlightPainter = new DefaultHighlighter.DefaultHighlightPainter(Color.YELLOW); protected final JTextArea textArea = new JTextArea(); protected final JScrollPane scroll = new JScrollPane(textArea); protected final JScrollBar scrollbar = new JScrollBar(Adjustable.VERTICAL); // protected final JScrollBar scrollbar = new JScrollBar(Adjustable.VERTICAL) { // @Override public Dimension getPreferredSize() { // Dimension d = super.getPreferredSize(); // d.width += 4; //getInsets().left; // return d; // } // }; public MainPanel() { super(new BorderLayout()); textArea.setEditable(false); textArea.setText(INITTXT + INITTXT + INITTXT); if (scrollbar.getUI() instanceof WindowsScrollBarUI) { scrollbar.setUI(new WindowsHighlightScrollBarUI(textArea)); } else { scrollbar.setUI(new MetalHighlightScrollBarUI(textArea)); } scrollbar.setUnitIncrement(10); scroll.setVerticalScrollBar(scrollbar); JLabel label = new JLabel(new HighlightIcon(textArea, scrollbar)); //label.setBorder(BorderFactory.createLineBorder(Color.RED)); scroll.setRowHeaderView(label); /* // Bug ID: JDK-6826074 JScrollPane does not revalidate the component hierarchy after scrolling // http://bugs.java.com/view_bug.do?bug_id=6826074 // Affected Versions: 6u12, 6u16, 7 // Fixed Versions: 7 (b134) JViewport vp = new JViewport() { @Override public void setViewPosition(Point p) { super.setViewPosition(p); revalidate(); } }; vp.setView(new JLabel(new HighlightIcon(textArea, scrollbar))); scroll.setRowHeader(vp); */ JCheckBox check = new JCheckBox("LineWrap"); check.addActionListener(e -> textArea.setLineWrap(((JCheckBox) e.getSource()).isSelected())); JButton highlight = new JButton("highlight"); highlight.addActionListener(e -> setHighlight(textArea, PATTERN)); JButton clear = new JButton("clear"); clear.addActionListener(e -> { textArea.getHighlighter().removeAllHighlights(); scroll.repaint(); }); Box box = Box.createHorizontalBox(); box.add(check); box.add(Box.createHorizontalGlue()); box.add(highlight); box.add(Box.createHorizontalStrut(2)); box.add(clear); add(box, BorderLayout.SOUTH); add(scroll); setPreferredSize(new Dimension(320, 240)); } public void setHighlight(JTextComponent jtc, String pattern) { Highlighter highlighter = jtc.getHighlighter(); highlighter.removeAllHighlights(); Document doc = jtc.getDocument(); try { String text = doc.getText(0, doc.getLength()); Matcher matcher = Pattern.compile(pattern).matcher(text); int pos = 0; while (matcher.find(pos)) { int start = matcher.start(); int end = matcher.end(); highlighter.addHighlight(start, end, highlightPainter); pos = end; } } catch (BadLocationException | PatternSyntaxException ex) { ex.printStackTrace(); } repaint(); } public static void main(String... args) { EventQueue.invokeLater(new Runnable() { @Override public void run() { createAndShowGUI(); } }); } public static void createAndShowGUI() { try { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) { ex.printStackTrace(); } JFrame frame = new JFrame("@title@"); frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); frame.getContentPane().add(new MainPanel()); frame.pack(); frame.setLocationRelativeTo(null); frame.setVisible(true); } } class HighlightIcon implements Icon { private static final Color THUMB_COLOR = new Color(0, 0, 255, 50); private final Rectangle thumbRect = new Rectangle(); private final JTextComponent textArea; private final JScrollBar scrollbar; protected HighlightIcon(JTextComponent textArea, JScrollBar scrollbar) { this.textArea = textArea; this.scrollbar = scrollbar; } @Override public void paintIcon(Component c, Graphics g, int x, int y) { //Rectangle rect = textArea.getBounds(); //Dimension sbSize = scrollbar.getSize(); //Insets sbInsets = scrollbar.getInsets(); //double sy = (sbSize.height - sbInsets.top - sbInsets.bottom) / rect.getHeight(); int itop = scrollbar.getInsets().top; BoundedRangeModel range = scrollbar.getModel(); double sy = range.getExtent() / (double) (range.getMaximum() - range.getMinimum()); AffineTransform at = AffineTransform.getScaleInstance(1d, sy); Highlighter highlighter = textArea.getHighlighter(); //paint Highlight Graphics2D g2 = (Graphics2D) g.create(); g2.translate(x, y); g2.setPaint(Color.RED); try { for (Highlighter.Highlight hh: highlighter.getHighlights()) { Rectangle r = textArea.modelToView(hh.getStartOffset()); Rectangle s = at.createTransformedShape(r).getBounds(); int h = 2; //Math.max(2, s.height - 2); g2.fillRect(0, itop + s.y, getIconWidth(), h); } } catch (BadLocationException ex) { ex.printStackTrace(); } //paint Thumb if (scrollbar.isVisible()) { //JViewport vport = Objects.requireNonNull((JViewport) SwingUtilities.getAncestorOfClass(JViewport.class, textArea)); //Rectangle thumbRect = vport.getBounds(); thumbRect.height = range.getExtent(); thumbRect.y = range.getValue(); //vport.getViewPosition().y; g2.setColor(THUMB_COLOR); Rectangle s = at.createTransformedShape(thumbRect).getBounds(); g2.fillRect(0, itop + s.y, getIconWidth(), s.height); } g2.dispose(); } @Override public int getIconWidth() { return 4; } @Override public int getIconHeight() { //return scrollbar.getHeight(); JViewport vport = Objects.requireNonNull((JViewport) SwingUtilities.getAncestorOfClass(JViewport.class, textArea)); return vport.getHeight(); } } class WindowsHighlightScrollBarUI extends WindowsScrollBarUI { private final JTextComponent textArea; protected WindowsHighlightScrollBarUI(JTextComponent textArea) { super(); this.textArea = textArea; } @Override protected void paintTrack(Graphics g, JComponent c, Rectangle trackBounds) { super.paintTrack(g, c, trackBounds); Rectangle rect = textArea.getBounds(); double sy = trackBounds.getHeight() / rect.getHeight(); AffineTransform at = AffineTransform.getScaleInstance(1d, sy); Highlighter highlighter = textArea.getHighlighter(); g.setColor(Color.YELLOW); try { for (Highlighter.Highlight hh: highlighter.getHighlights()) { Rectangle r = textArea.modelToView(hh.getStartOffset()); Rectangle s = at.createTransformedShape(r).getBounds(); int h = 2; //Math.max(2, s.height - 2); g.fillRect(trackBounds.x, trackBounds.y + s.y, trackBounds.width, h); } } catch (BadLocationException ex) { ex.printStackTrace(); } } } class MetalHighlightScrollBarUI extends MetalScrollBarUI { private final JTextComponent textArea; protected MetalHighlightScrollBarUI(JTextComponent textArea) { super(); this.textArea = textArea; } @Override protected void paintTrack(Graphics g, JComponent c, Rectangle trackBounds) { super.paintTrack(g, c, trackBounds); Rectangle rect = textArea.getBounds(); double sy = trackBounds.getHeight() / rect.getHeight(); AffineTransform at = AffineTransform.getScaleInstance(1d, sy); Highlighter highlighter = textArea.getHighlighter(); g.setColor(Color.YELLOW); try { for (Highlighter.Highlight hh: highlighter.getHighlights()) { Rectangle r = textArea.modelToView(hh.getStartOffset()); Rectangle s = at.createTransformedShape(r).getBounds(); int h = 2; //Math.max(2, s.height - 2); g.fillRect(trackBounds.x, trackBounds.y + s.y, trackBounds.width, h); } } catch (BadLocationException ex) { ex.printStackTrace(); } } }
ScrollBarSearchHighlighter/src/java/example/MainPanel.java
package example; //-*- mode:java; encoding:utf-8 -*- // vim:set fileencoding=utf-8: //@homepage@ import java.awt.*; import java.awt.event.*; import java.awt.geom.*; import java.util.Objects; import java.util.regex.*; import javax.swing.*; import javax.swing.plaf.metal.MetalScrollBarUI; import javax.swing.text.*; import com.sun.java.swing.plaf.windows.WindowsScrollBarUI; public class MainPanel extends JPanel { protected static final String PATTERN = "Swing"; protected static final String INITTXT = "Trail: Creating a GUI with JFC/Swing\n" + "Lesson: Learning Swing by Example\n" + "This lesson explains the concepts you need to\n" + " use Swing components in building a user interface.\n" + " First we examine the simplest Swing application you can write.\n" + " Then we present several progressively complicated examples of creating\n" + " user interfaces using components in the javax.swing package.\n" + " We cover several Swing components, such as buttons, labels, and text areas.\n" + " The handling of events is also discussed,\n" + " as are layout management and accessibility.\n" + " This lesson ends with a set of questions and exercises\n" + " so you can test yourself on what you've learned.\n" + "https://docs.oracle.com/javase/tutorial/uiswing/learn/index.html\n"; protected final transient Highlighter.HighlightPainter highlightPainter = new DefaultHighlighter.DefaultHighlightPainter(Color.YELLOW); protected final JTextArea textArea = new JTextArea(); protected final JScrollPane scroll = new JScrollPane(textArea); protected final JScrollBar scrollbar = new JScrollBar(Adjustable.VERTICAL); // protected final JScrollBar scrollbar = new JScrollBar(Adjustable.VERTICAL) { // @Override public Dimension getPreferredSize() { // Dimension d = super.getPreferredSize(); // d.width += 4; //getInsets().left; // return d; // } // }; protected final JCheckBox check = new JCheckBox(new AbstractAction("LineWrap") { @Override public void actionPerformed(ActionEvent e) { JCheckBox c = (JCheckBox) e.getSource(); textArea.setLineWrap(c.isSelected()); } }); public MainPanel() { super(new BorderLayout()); textArea.setEditable(false); textArea.setText(INITTXT + INITTXT + INITTXT); scrollbar.setUnitIncrement(10); if (scrollbar.getUI() instanceof WindowsScrollBarUI) { scrollbar.setUI(new WindowsHighlightScrollBarUI(textArea)); } else { scrollbar.setUI(new MetalHighlightScrollBarUI(textArea)); } scroll.setVerticalScrollBar(scrollbar); JLabel label = new JLabel(new HighlightIcon(textArea, scrollbar)); //label.setBorder(BorderFactory.createLineBorder(Color.RED)); scroll.setRowHeaderView(label); /* // Bug ID: JDK-6826074 JScrollPane does not revalidate the component hierarchy after scrolling // http://bugs.java.com/view_bug.do?bug_id=6826074 // Affected Versions: 6u12, 6u16, 7 // Fixed Versions: 7 (b134) JViewport vp = new JViewport() { @Override public void setViewPosition(Point p) { super.setViewPosition(p); revalidate(); } }; vp.setView(new JLabel(new HighlightIcon(textArea, scrollbar))); scroll.setRowHeader(vp); */ add(scroll); Box box = Box.createHorizontalBox(); box.add(check); box.add(Box.createHorizontalGlue()); box.add(new JButton(new AbstractAction("highlight") { @Override public void actionPerformed(ActionEvent e) { setHighlight(textArea, PATTERN); } })); box.add(Box.createHorizontalStrut(2)); box.add(new JButton(new AbstractAction("clear") { @Override public void actionPerformed(ActionEvent e) { textArea.getHighlighter().removeAllHighlights(); scroll.repaint(); } })); add(box, BorderLayout.SOUTH); setPreferredSize(new Dimension(320, 240)); } public void setHighlight(JTextComponent jtc, String pattern) { Highlighter highlighter = jtc.getHighlighter(); highlighter.removeAllHighlights(); Document doc = jtc.getDocument(); try { String text = doc.getText(0, doc.getLength()); Matcher matcher = Pattern.compile(pattern).matcher(text); int pos = 0; while (matcher.find(pos)) { int start = matcher.start(); int end = matcher.end(); highlighter.addHighlight(start, end, highlightPainter); pos = end; } } catch (BadLocationException | PatternSyntaxException ex) { ex.printStackTrace(); } repaint(); } public static void main(String... args) { EventQueue.invokeLater(new Runnable() { @Override public void run() { createAndShowGUI(); } }); } public static void createAndShowGUI() { try { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) { ex.printStackTrace(); } JFrame frame = new JFrame("@title@"); frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); frame.getContentPane().add(new MainPanel()); frame.pack(); frame.setLocationRelativeTo(null); frame.setVisible(true); } } class HighlightIcon implements Icon { private static final Color THUMB_COLOR = new Color(0, 0, 255, 50); private final Rectangle thumbRect = new Rectangle(); private final JTextComponent textArea; private final JScrollBar scrollbar; protected HighlightIcon(JTextComponent textArea, JScrollBar scrollbar) { this.textArea = textArea; this.scrollbar = scrollbar; } @Override public void paintIcon(Component c, Graphics g, int x, int y) { //Rectangle rect = textArea.getBounds(); //Dimension sbSize = scrollbar.getSize(); //Insets sbInsets = scrollbar.getInsets(); //double sy = (sbSize.height - sbInsets.top - sbInsets.bottom) / rect.getHeight(); int itop = scrollbar.getInsets().top; BoundedRangeModel range = scrollbar.getModel(); double sy = range.getExtent() / (double) (range.getMaximum() - range.getMinimum()); AffineTransform at = AffineTransform.getScaleInstance(1d, sy); Highlighter highlighter = textArea.getHighlighter(); //paint Highlight Graphics2D g2 = (Graphics2D) g.create(); g2.translate(x, y); g2.setPaint(Color.RED); try { for (Highlighter.Highlight hh: highlighter.getHighlights()) { Rectangle r = textArea.modelToView(hh.getStartOffset()); Rectangle s = at.createTransformedShape(r).getBounds(); int h = 2; //Math.max(2, s.height - 2); g2.fillRect(0, itop + s.y, getIconWidth(), h); } } catch (BadLocationException ex) { ex.printStackTrace(); } //paint Thumb if (scrollbar.isVisible()) { //JViewport vport = Objects.requireNonNull((JViewport) SwingUtilities.getAncestorOfClass(JViewport.class, textArea)); //Rectangle thumbRect = vport.getBounds(); thumbRect.height = range.getExtent(); thumbRect.y = range.getValue(); //vport.getViewPosition().y; g2.setColor(THUMB_COLOR); Rectangle s = at.createTransformedShape(thumbRect).getBounds(); g2.fillRect(0, itop + s.y, getIconWidth(), s.height); } g2.dispose(); } @Override public int getIconWidth() { return 4; } @Override public int getIconHeight() { //return scrollbar.getHeight(); JViewport vport = Objects.requireNonNull((JViewport) SwingUtilities.getAncestorOfClass(JViewport.class, textArea)); return vport.getHeight(); } } class WindowsHighlightScrollBarUI extends WindowsScrollBarUI { private final JTextComponent textArea; protected WindowsHighlightScrollBarUI(JTextComponent textArea) { super(); this.textArea = textArea; } @Override protected void paintTrack(Graphics g, JComponent c, Rectangle trackBounds) { super.paintTrack(g, c, trackBounds); Rectangle rect = textArea.getBounds(); double sy = trackBounds.getHeight() / rect.getHeight(); AffineTransform at = AffineTransform.getScaleInstance(1d, sy); Highlighter highlighter = textArea.getHighlighter(); g.setColor(Color.YELLOW); try { for (Highlighter.Highlight hh: highlighter.getHighlights()) { Rectangle r = textArea.modelToView(hh.getStartOffset()); Rectangle s = at.createTransformedShape(r).getBounds(); int h = 2; //Math.max(2, s.height - 2); g.fillRect(trackBounds.x, trackBounds.y + s.y, trackBounds.width, h); } } catch (BadLocationException ex) { ex.printStackTrace(); } } } class MetalHighlightScrollBarUI extends MetalScrollBarUI { private final JTextComponent textArea; protected MetalHighlightScrollBarUI(JTextComponent textArea) { super(); this.textArea = textArea; } @Override protected void paintTrack(Graphics g, JComponent c, Rectangle trackBounds) { super.paintTrack(g, c, trackBounds); Rectangle rect = textArea.getBounds(); double sy = trackBounds.getHeight() / rect.getHeight(); AffineTransform at = AffineTransform.getScaleInstance(1d, sy); Highlighter highlighter = textArea.getHighlighter(); g.setColor(Color.YELLOW); try { for (Highlighter.Highlight hh: highlighter.getHighlights()) { Rectangle r = textArea.modelToView(hh.getStartOffset()); Rectangle s = at.createTransformedShape(r).getBounds(); int h = 2; //Math.max(2, s.height - 2); g.fillRect(trackBounds.x, trackBounds.y + s.y, trackBounds.width, h); } } catch (BadLocationException ex) { ex.printStackTrace(); } } }
refactor: use a lambda expression instead of an anonymous class(ActionListener)
ScrollBarSearchHighlighter/src/java/example/MainPanel.java
refactor: use a lambda expression instead of an anonymous class(ActionListener)
<ide><path>crollBarSearchHighlighter/src/java/example/MainPanel.java <ide> // return d; <ide> // } <ide> // }; <del> protected final JCheckBox check = new JCheckBox(new AbstractAction("LineWrap") { <del> @Override public void actionPerformed(ActionEvent e) { <del> JCheckBox c = (JCheckBox) e.getSource(); <del> textArea.setLineWrap(c.isSelected()); <del> } <del> }); <ide> <ide> public MainPanel() { <ide> super(new BorderLayout()); <ide> textArea.setEditable(false); <ide> textArea.setText(INITTXT + INITTXT + INITTXT); <ide> <del> scrollbar.setUnitIncrement(10); <del> <ide> if (scrollbar.getUI() instanceof WindowsScrollBarUI) { <ide> scrollbar.setUI(new WindowsHighlightScrollBarUI(textArea)); <ide> } else { <ide> scrollbar.setUI(new MetalHighlightScrollBarUI(textArea)); <ide> } <ide> <add> scrollbar.setUnitIncrement(10); <ide> scroll.setVerticalScrollBar(scrollbar); <ide> JLabel label = new JLabel(new HighlightIcon(textArea, scrollbar)); <ide> //label.setBorder(BorderFactory.createLineBorder(Color.RED)); <ide> vp.setView(new JLabel(new HighlightIcon(textArea, scrollbar))); <ide> scroll.setRowHeader(vp); <ide> */ <del> add(scroll); <add> <add> JCheckBox check = new JCheckBox("LineWrap"); <add> check.addActionListener(e -> textArea.setLineWrap(((JCheckBox) e.getSource()).isSelected())); <add> <add> JButton highlight = new JButton("highlight"); <add> highlight.addActionListener(e -> setHighlight(textArea, PATTERN)); <add> <add> JButton clear = new JButton("clear"); <add> clear.addActionListener(e -> { <add> textArea.getHighlighter().removeAllHighlights(); <add> scroll.repaint(); <add> }); <ide> <ide> Box box = Box.createHorizontalBox(); <ide> box.add(check); <ide> box.add(Box.createHorizontalGlue()); <del> box.add(new JButton(new AbstractAction("highlight") { <del> @Override public void actionPerformed(ActionEvent e) { <del> setHighlight(textArea, PATTERN); <del> } <del> })); <add> box.add(highlight); <ide> box.add(Box.createHorizontalStrut(2)); <del> box.add(new JButton(new AbstractAction("clear") { <del> @Override public void actionPerformed(ActionEvent e) { <del> textArea.getHighlighter().removeAllHighlights(); <del> scroll.repaint(); <del> } <del> })); <add> box.add(clear); <add> <ide> add(box, BorderLayout.SOUTH); <add> add(scroll); <ide> setPreferredSize(new Dimension(320, 240)); <ide> } <ide> public void setHighlight(JTextComponent jtc, String pattern) {
Java
apache-2.0
91496c0617fcb598cce66cb4cd06ae1f39c4e21d
0
andyadc/idea-framework
package com.idea4j.framework.bean; import com.idea4j.framework.FrameworkException; import com.idea4j.framework.bean.annotation.Bean; import com.idea4j.framework.core.ClassHelper; import com.idea4j.framework.core.fault.InitializationError; import com.idea4j.framework.mvc.annotation.Action; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.HashMap; import java.util.List; import java.util.Map; /** * 初始化相关 Bean 类 * * @author andaicheng */ public class BeanHelper { private static final Logger LOGGER = LoggerFactory.getLogger(BeanHelper.class); /** * Bean Map(Bean 类 => Bean 实例) */ private static final Map<Class<?>, Object> beanMap = new HashMap<>(); static { try { List<Class<?>> classList = ClassHelper.getClassList(); for (Class<?> cls : classList) { // 处理带有 Bean/Service/Action/Aspect 注解的类 if (cls.isAnnotationPresent(Bean.class) || cls.isAnnotationPresent(Action.class)) { // 创建 Bean 实例 Object beanInstance = cls.newInstance(); // 将 Bean 实例放入 Bean Map 中(键为 Bean 类,值为 Bean 实例) beanMap.put(cls, beanInstance); } } } catch (Exception e) { LOGGER.error("Initial BeanHelper error!", e); throw new InitializationError("Initial BeanHelper error!", e); } } private BeanHelper() { } /** * 获取 Bean Map */ public static Map<Class<?>, Object> getBeanMap() { return beanMap; } /** * 获取 Bean 实例 */ @SuppressWarnings("unchecked") public static <T> T getBean(Class<T> cls) { if (!beanMap.containsKey(cls)) { LOGGER.error("Can't get instance by class name! {}", cls); throw new FrameworkException("Can't get instance by class name!" + cls); } return (T) beanMap.get(cls); } /** * 设置 Bean 实例 */ public static void setBean(Class<?> cls, Object obj) { beanMap.put(cls, obj); } }
idea4j/src/main/java/com/idea4j/framework/bean/BeanHelper.java
package com.idea4j.framework.bean; import com.idea4j.framework.FrameworkException; import com.idea4j.framework.bean.annotation.Bean; import com.idea4j.framework.core.ClassHelper; import com.idea4j.framework.core.fault.InitializationError; import com.idea4j.framework.mvc.annotation.Action; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.HashMap; import java.util.List; import java.util.Map; /** * 初始化相关 Bean 类 * * @author andaicheng */ public class BeanHelper { private static final Logger LOGGER = LoggerFactory.getLogger(BeanHelper.class); /** * Bean Map(Bean 类 => Bean 实例) */ private static final Map<Class<?>, Object> beanMap = new HashMap<>(); static { try { List<Class<?>> classList = ClassHelper.getClassList(); for (Class<?> cls : classList) { // 处理带有 Bean/Service/Action/Aspect 注解的类 if (cls.isAnnotationPresent(Bean.class) || cls.isAnnotationPresent(Action.class)) { // 创建 Bean 实例 Object beanInstance = cls.newInstance(); // 将 Bean 实例放入 Bean Map 中(键为 Bean 类,值为 Bean 实例) beanMap.put(cls, beanInstance); } } } catch (Exception e) { LOGGER.error("初始化 BeanHelper 出错!", e); throw new InitializationError("初始化 BeanHelper 出错!", e); } } private BeanHelper() { } /** * 获取 Bean Map */ public static Map<Class<?>, Object> getBeanMap() { return beanMap; } /** * 获取 Bean 实例 */ @SuppressWarnings("unchecked") public static <T> T getBean(Class<T> cls) { if (!beanMap.containsKey(cls)) { LOGGER.error("无法根据类名获取实例!{}", cls); throw new FrameworkException("无法根据类名获取实例!" + cls); } return (T) beanMap.get(cls); } /** * 设置 Bean 实例 */ public static void setBean(Class<?> cls, Object obj) { beanMap.put(cls, obj); } }
english logs
idea4j/src/main/java/com/idea4j/framework/bean/BeanHelper.java
english logs
<ide><path>dea4j/src/main/java/com/idea4j/framework/bean/BeanHelper.java <ide> } <ide> } <ide> } catch (Exception e) { <del> LOGGER.error("初始化 BeanHelper 出错!", e); <del> throw new InitializationError("初始化 BeanHelper 出错!", e); <add> LOGGER.error("Initial BeanHelper error!", e); <add> throw new InitializationError("Initial BeanHelper error!", e); <ide> } <ide> } <ide> <ide> @SuppressWarnings("unchecked") <ide> public static <T> T getBean(Class<T> cls) { <ide> if (!beanMap.containsKey(cls)) { <del> LOGGER.error("无法根据类名获取实例!{}", cls); <del> throw new FrameworkException("无法根据类名获取实例!" + cls); <add> LOGGER.error("Can't get instance by class name! {}", cls); <add> throw new FrameworkException("Can't get instance by class name!" + cls); <ide> } <ide> return (T) beanMap.get(cls); <ide> }
Java
lgpl-2.1
92c4bd538df7302b0580542eafb2500b77669270
0
tklauser/sopc2dts
/* sopc2dts - Devicetree generation for Altera systems Copyright (C) 2011 Walter Goossens <[email protected]> This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ package sopc2dts.generators; import sopc2dts.lib.AvalonSystem; import sopc2dts.lib.Bin2IHex; import sopc2dts.lib.Bin2IHex.HexTypes; import sopc2dts.lib.BoardInfo; public class DTBHex8Generator extends AbstractSopcGenerator { private DTBGenerator dtbGen; public DTBHex8Generator(AvalonSystem s) { super(s, true); dtbGen = new DTBGenerator(s); } @Override public String getExtension() { return "hex"; } @Override public String getTextOutput(BoardInfo bi) { return Bin2IHex.toHex(dtbGen.getBinaryOutput(bi), HexTypes.I8Hex); } }
sopc2dts/sopc2dts/generators/DTBHex8Generator.java
package sopc2dts.generators; import sopc2dts.lib.AvalonSystem; import sopc2dts.lib.Bin2IHex; import sopc2dts.lib.Bin2IHex.HexTypes; import sopc2dts.lib.BoardInfo; public class DTBHex8Generator extends AbstractSopcGenerator { private DTBGenerator dtbGen; public DTBHex8Generator(AvalonSystem s) { super(s, true); dtbGen = new DTBGenerator(s); } @Override public String getExtension() { return "hex"; } @Override public String getTextOutput(BoardInfo bi) { return Bin2IHex.toHex(dtbGen.getBinaryOutput(bi), HexTypes.I8Hex); } }
dtbhex8: Add missing copyright header Signed-off-by: Walter Goossens <[email protected]>
sopc2dts/sopc2dts/generators/DTBHex8Generator.java
dtbhex8: Add missing copyright header
<ide><path>opc2dts/sopc2dts/generators/DTBHex8Generator.java <add>/* <add>sopc2dts - Devicetree generation for Altera systems <add> <add>Copyright (C) 2011 Walter Goossens <[email protected]> <add> <add>This library is free software; you can redistribute it and/or <add>modify it under the terms of the GNU Lesser General Public <add>License as published by the Free Software Foundation; either <add>version 2.1 of the License, or (at your option) any later version. <add> <add>This library is distributed in the hope that it will be useful, <add>but WITHOUT ANY WARRANTY; without even the implied warranty of <add>MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU <add>Lesser General Public License for more details. <add> <add>You should have received a copy of the GNU Lesser General Public <add>License along with this library; if not, write to the Free Software <add>Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA <add>*/ <ide> package sopc2dts.generators; <ide> <ide> import sopc2dts.lib.AvalonSystem;
Java
mit
c20a76c38484206736f7dfa6a0ca87d060305a34
0
auth0/auth0-api-java,auth0/auth0-java
package com.auth0.net; import com.auth0.client.MockServer; import com.auth0.exception.APIException; import com.auth0.exception.Auth0Exception; import com.auth0.json.auth.TokenHolder; import com.fasterxml.jackson.core.JsonParseException; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; import okhttp3.Call; import okhttp3.OkHttpClient; import okhttp3.mockwebserver.RecordedRequest; import org.hamcrest.Matchers; import org.junit.*; import org.junit.rules.ExpectedException; import java.io.IOException; import java.util.List; import java.util.Map; import static com.auth0.client.MockServer.*; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.*; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; public class CustomRequestTest { private MockServer server; private OkHttpClient client; @Rule public ExpectedException exception = ExpectedException.none(); private TypeReference<TokenHolder> tokenHolderType; private TypeReference<List> listType; private TypeReference<Void> voidType; @Before public void setUp() throws Exception { server = new MockServer(); client = new OkHttpClient(); tokenHolderType = new TypeReference<TokenHolder>() { }; listType = new TypeReference<List>() { }; voidType = new TypeReference<Void>() { }; } @After public void tearDown() throws Exception { server.stop(); } @Test public void shouldCreateGETRequest() throws Exception { CustomRequest<TokenHolder> request = new CustomRequest<>(client, server.getBaseUrl(), "GET", tokenHolderType); assertThat(request, is(notNullValue())); server.jsonResponse(AUTH_TOKENS, 200); TokenHolder execute = request.execute(); RecordedRequest recordedRequest = server.takeRequest(); Assert.assertThat(recordedRequest.getMethod(), is("GET")); Assert.assertThat(execute, is(notNullValue())); } @Test public void shouldCreatePOSTRequest() throws Exception { CustomRequest<TokenHolder> request = new CustomRequest<>(client, server.getBaseUrl(), "POST", tokenHolderType); assertThat(request, is(notNullValue())); request.addParameter("non_empty", "body"); server.jsonResponse(AUTH_TOKENS, 200); TokenHolder execute = request.execute(); RecordedRequest recordedRequest = server.takeRequest(); Assert.assertThat(recordedRequest.getMethod(), is("POST")); Assert.assertThat(execute, is(notNullValue())); } @Test public void shouldAddParameters() throws Exception { CustomRequest<TokenHolder> request = new CustomRequest<>(client, server.getBaseUrl(), "POST", tokenHolderType); Map mapValue = mock(Map.class); request.addParameter("key", "value"); request.addParameter("map", mapValue); server.jsonResponse(AUTH_TOKENS, 200); request.execute(); RecordedRequest recordedRequest = server.takeRequest(); Map<String, Object> values = bodyFromRequest(recordedRequest); assertThat(values, hasEntry("key", (Object) "value")); assertThat(values, hasEntry("map", (Object) mapValue)); } @Test public void shouldAddHeaders() throws Exception { CustomRequest<TokenHolder> request = new CustomRequest<>(client, server.getBaseUrl(), "POST", tokenHolderType); request.addParameter("non_empty", "body"); request.addHeader("Content-Type", "application/json"); request.addHeader("Authorization", "Bearer my_access_token"); server.jsonResponse(AUTH_TOKENS, 200); request.execute(); RecordedRequest recordedRequest = server.takeRequest(); assertThat(recordedRequest.getHeader("Content-Type"), is("application/json")); assertThat(recordedRequest.getHeader("Authorization"), is("Bearer my_access_token")); } @Test public void shouldThrowOnExecuteFailure() throws Exception { exception.expect(Auth0Exception.class); exception.expectCause(Matchers.<Throwable>instanceOf(IOException.class)); exception.expectMessage("Failed to execute request"); OkHttpClient client = mock(OkHttpClient.class); Call call = mock(Call.class); when(client.newCall(any(okhttp3.Request.class))).thenReturn(call); when(call.execute()).thenThrow(IOException.class); CustomRequest<Void> request = new CustomRequest<>(client, server.getBaseUrl(), "GET", voidType); request.execute(); } @Test public void shouldThrowOnBodyCreationFailure() throws Exception { ObjectMapper mapper = mock(ObjectMapper.class); when(mapper.writeValueAsBytes(any(Object.class))).thenThrow(JsonProcessingException.class); CustomRequest request = new CustomRequest<>(client, server.getBaseUrl(), "POST", mapper, voidType); request.addParameter("name", "value"); exception.expect(Auth0Exception.class); exception.expectCause(Matchers.<Throwable>instanceOf(JsonProcessingException.class)); exception.expectMessage("Couldn't create the request body."); request.execute(); } @Test public void shouldParseSuccessfulResponse() throws Exception { CustomRequest<TokenHolder> request = new CustomRequest<>(client, server.getBaseUrl(), "GET", tokenHolderType); server.jsonResponse(AUTH_TOKENS, 200); TokenHolder response = request.execute(); server.takeRequest(); assertThat(response, is(notNullValue())); assertThat(response.getAccessToken(), not(isEmptyOrNullString())); assertThat(response.getIdToken(), not(isEmptyOrNullString())); assertThat(response.getRefreshToken(), not(isEmptyOrNullString())); assertThat(response.getTokenType(), not(isEmptyOrNullString())); assertThat(response.getExpiresIn(), is(notNullValue())); } @Test public void shouldThrowOnParseInvalidSuccessfulResponse() throws Exception { CustomRequest<List> request = new CustomRequest<>(client, server.getBaseUrl(), "GET", listType); server.jsonResponse(AUTH_TOKENS, 200); Exception exception = null; try { request.execute(); server.takeRequest(); } catch (Exception e) { exception = e; } assertThat(exception, is(notNullValue())); assertThat(exception, is(instanceOf(APIException.class))); assertThat(exception.getCause(), is(instanceOf(JsonMappingException.class))); assertThat(exception.getMessage(), is("Request failed with status code 200: Failed to parse json body")); APIException authException = (APIException) exception; assertThat(authException.getDescription(), is("Failed to parse json body")); assertThat(authException.getError(), is(nullValue())); assertThat(authException.getStatusCode(), is(200)); } @Test public void shouldParseJSONErrorResponseWithErrorDescription() throws Exception { CustomRequest<List> request = new CustomRequest<>(client, server.getBaseUrl(), "GET", listType); server.jsonResponse(AUTH_ERROR_WITH_ERROR_DESCRIPTION, 400); Exception exception = null; try { request.execute(); server.takeRequest(); } catch (Exception e) { exception = e; } assertThat(exception, is(notNullValue())); assertThat(exception, is(instanceOf(APIException.class))); assertThat(exception.getCause(), is(nullValue())); assertThat(exception.getMessage(), is("Request failed with status code 400: the connection was not found")); APIException authException = (APIException) exception; assertThat(authException.getDescription(), is("the connection was not found")); assertThat(authException.getError(), is("invalid_request")); assertThat(authException.getStatusCode(), is(400)); } @Test public void shouldParseJSONErrorResponseWithError() throws Exception { CustomRequest<List> request = new CustomRequest<>(client, server.getBaseUrl(), "GET", listType); server.jsonResponse(AUTH_ERROR_WITH_ERROR, 400); Exception exception = null; try { request.execute(); server.takeRequest(); } catch (Exception e) { exception = e; } assertThat(exception, is(notNullValue())); assertThat(exception, is(instanceOf(APIException.class))); assertThat(exception.getCause(), is(nullValue())); assertThat(exception.getMessage(), is("Request failed with status code 400: missing username for Username-Password-Authentication connection with requires_username enabled")); APIException authException = (APIException) exception; assertThat(authException.getDescription(), is("missing username for Username-Password-Authentication connection with requires_username enabled")); assertThat(authException.getError(), is("missing username for Username-Password-Authentication connection with requires_username enabled")); assertThat(authException.getStatusCode(), is(400)); } @Test public void shouldParseJSONErrorResponseWithDescriptionAndExtraProperties() throws Exception { CustomRequest<List> request = new CustomRequest<>(client, server.getBaseUrl(), "GET", listType); server.jsonResponse(AUTH_ERROR_WITH_DESCRIPTION_AND_EXTRA_PROPERTIES, 400); Exception exception = null; try { request.execute(); server.takeRequest(); } catch (Exception e) { exception = e; } assertThat(exception, is(notNullValue())); assertThat(exception, is(instanceOf(APIException.class))); assertThat(exception.getCause(), is(nullValue())); assertThat(exception.getMessage(), is("Request failed with status code 400: Multifactor authentication required")); APIException authException = (APIException) exception; assertThat(authException.getDescription(), is("Multifactor authentication required")); assertThat(authException.getError(), is("mfa_required")); assertThat(authException.getValue("mfa_token"), is("Fe26...Ha")); assertThat(authException.getValue("non_existing_key"), is(nullValue())); assertThat(authException.getStatusCode(), is(400)); } @Test public void shouldParseJSONErrorResponseWithDescription() throws Exception { CustomRequest<List> request = new CustomRequest<>(client, server.getBaseUrl(), "GET", listType); server.jsonResponse(AUTH_ERROR_WITH_DESCRIPTION, 400); Exception exception = null; try { request.execute(); server.takeRequest(); } catch (Exception e) { exception = e; } assertThat(exception, is(notNullValue())); assertThat(exception, is(instanceOf(APIException.class))); assertThat(exception.getCause(), is(nullValue())); assertThat(exception.getMessage(), is("Request failed with status code 400: The user already exists.")); APIException authException = (APIException) exception; assertThat(authException.getDescription(), is("The user already exists.")); assertThat(authException.getError(), is("user_exists")); assertThat(authException.getStatusCode(), is(400)); } @Test public void shouldParseJSONErrorResponseWithMessage() throws Exception { CustomRequest<List> request = new CustomRequest<>(client, server.getBaseUrl(), "GET", listType); server.jsonResponse(MGMT_ERROR_WITH_MESSAGE, 400); Exception exception = null; try { request.execute(); server.takeRequest(); } catch (Exception e) { exception = e; } assertThat(exception, is(notNullValue())); assertThat(exception, is(instanceOf(APIException.class))); assertThat(exception.getCause(), is(nullValue())); assertThat(exception.getMessage(), is("Request failed with status code 400: Query validation error: 'String 'invalid_field' does not match pattern. Must be a comma separated list of the following values: allowed_logout_urls,change_password.")); APIException authException = (APIException) exception; assertThat(authException.getDescription(), is("Query validation error: 'String 'invalid_field' does not match pattern. Must be a comma separated list of the following values: allowed_logout_urls,change_password.")); assertThat(authException.getError(), is("invalid_query_string")); assertThat(authException.getStatusCode(), is(400)); } @Test public void shouldParsePlainTextErrorResponse() throws Exception { CustomRequest<List> request = new CustomRequest<>(client, server.getBaseUrl(), "GET", listType); server.textResponse(AUTH_ERROR_PLAINTEXT, 400); Exception exception = null; try { request.execute(); server.takeRequest(); } catch (Exception e) { exception = e; } assertThat(exception, is(notNullValue())); assertThat(exception, is(instanceOf(APIException.class))); assertThat(exception.getCause(), is(instanceOf(JsonParseException.class))); assertThat(exception.getMessage(), is("Request failed with status code 400: A plain-text error response")); APIException authException = (APIException) exception; assertThat(authException.getDescription(), is("A plain-text error response")); assertThat(authException.getError(), is(nullValue())); assertThat(authException.getValue("non_existing_key"), is(nullValue())); assertThat(authException.getStatusCode(), is(400)); } }
src/test/java/com/auth0/net/CustomRequestTest.java
package com.auth0.net; import com.auth0.client.MockServer; import com.auth0.exception.APIException; import com.auth0.exception.Auth0Exception; import com.auth0.json.auth.TokenHolder; import com.fasterxml.jackson.core.JsonParseException; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; import okhttp3.Call; import okhttp3.OkHttpClient; import okhttp3.mockwebserver.RecordedRequest; import org.hamcrest.Matchers; import org.junit.*; import org.junit.rules.ExpectedException; import java.io.IOException; import java.util.List; import java.util.Map; import static com.auth0.client.MockServer.*; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.*; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; public class CustomRequestTest { private MockServer server; private OkHttpClient client; @Rule public ExpectedException exception = ExpectedException.none(); private TypeReference<TokenHolder> tokenHolderType; private TypeReference<List> listType; private TypeReference<Void> voidType; @Before public void setUp() throws Exception { server = new MockServer(); client = new OkHttpClient(); tokenHolderType = new TypeReference<TokenHolder>() { }; listType = new TypeReference<List>() { }; voidType = new TypeReference<Void>() { }; } @After public void tearDown() throws Exception { server.stop(); } @Test public void shouldCreateGETRequest() throws Exception { CustomRequest<TokenHolder> request = new CustomRequest<>(client, server.getBaseUrl(), "GET", tokenHolderType); assertThat(request, is(notNullValue())); server.jsonResponse(AUTH_TOKENS, 200); TokenHolder execute = request.execute(); RecordedRequest recordedRequest = server.takeRequest(); Assert.assertThat(recordedRequest.getMethod(), is("GET")); Assert.assertThat(execute, is(notNullValue())); } @Test public void shouldCreatePOSTRequest() throws Exception { CustomRequest<TokenHolder> request = new CustomRequest<>(client, server.getBaseUrl(), "POST", tokenHolderType); assertThat(request, is(notNullValue())); request.addParameter("non_empty", "body"); server.jsonResponse(AUTH_TOKENS, 200); TokenHolder execute = request.execute(); RecordedRequest recordedRequest = server.takeRequest(); Assert.assertThat(recordedRequest.getMethod(), is("POST")); Assert.assertThat(execute, is(notNullValue())); } @Test public void shouldAddParameters() throws Exception { CustomRequest<TokenHolder> request = new CustomRequest<>(client, server.getBaseUrl(), "POST", tokenHolderType); Map mapValue = mock(Map.class); request.addParameter("key", "value"); request.addParameter("map", mapValue); server.jsonResponse(AUTH_TOKENS, 200); request.execute(); RecordedRequest recordedRequest = server.takeRequest(); Map<String, Object> values = bodyFromRequest(recordedRequest); assertThat(values, hasEntry("key", (Object) "value")); assertThat(values, hasEntry("map", (Object) mapValue)); } @Test public void shouldAddHeaders() throws Exception { CustomRequest<TokenHolder> request = new CustomRequest<>(client, server.getBaseUrl(), "POST", tokenHolderType); request.addParameter("non_empty", "body"); request.addHeader("Content-Type", "application/json"); request.addHeader("Authorization", "Bearer my_access_token"); server.jsonResponse(AUTH_TOKENS, 200); request.execute(); RecordedRequest recordedRequest = server.takeRequest(); assertThat(recordedRequest.getHeader("Content-Type"), is("application/json")); assertThat(recordedRequest.getHeader("Authorization"), is("Bearer my_access_token")); } @Test public void shouldThrowOnExecuteFailure() throws Exception { exception.expect(Auth0Exception.class); exception.expectCause(Matchers.<Throwable>instanceOf(IOException.class)); exception.expectMessage("Failed to execute request"); OkHttpClient client = mock(OkHttpClient.class); Call call = mock(Call.class); when(client.newCall(any(okhttp3.Request.class))).thenReturn(call); when(call.execute()).thenThrow(IOException.class); CustomRequest<Void> request = new CustomRequest<>(client, server.getBaseUrl(), "GET", voidType); request.execute(); } @Test public void shouldThrowOnBodyCreationFailure() throws Exception { ObjectMapper mapper = mock(ObjectMapper.class); when(mapper.writeValueAsBytes(any(Object.class))).thenThrow(JsonProcessingException.class); CustomRequest request = new CustomRequest<>(client, server.getBaseUrl(), "POST", mapper, voidType); request.addParameter("name", "value"); exception.expect(Auth0Exception.class); exception.expectCause(Matchers.<Throwable>instanceOf(JsonProcessingException.class)); exception.expectMessage("Couldn't create the request body."); request.execute(); } @Test public void shouldParseSuccessfulResponse() throws Exception { CustomRequest<TokenHolder> request = new CustomRequest<>(client, server.getBaseUrl(), "GET", tokenHolderType); server.jsonResponse(AUTH_TOKENS, 200); TokenHolder response = request.execute(); server.takeRequest(); assertThat(response, is(notNullValue())); assertThat(response.getAccessToken(), not(isEmptyOrNullString())); assertThat(response.getIdToken(), not(isEmptyOrNullString())); assertThat(response.getRefreshToken(), not(isEmptyOrNullString())); assertThat(response.getTokenType(), not(isEmptyOrNullString())); assertThat(response.getExpiresIn(), is(notNullValue())); } @Test public void shouldThrowOnParseInvalidSuccessfulResponse() throws Exception { CustomRequest<List> request = new CustomRequest<>(client, server.getBaseUrl(), "GET", listType); server.jsonResponse(AUTH_TOKENS, 200); Exception exception = null; try { request.execute(); server.takeRequest(); } catch (Exception e) { exception = e; } assertThat(exception, is(notNullValue())); assertThat(exception, is(instanceOf(APIException.class))); assertThat(exception.getCause(), is(instanceOf(JsonMappingException.class))); assertThat(exception.getMessage(), is("Request failed with status code 200: Failed to parse json body")); APIException authException = (APIException) exception; assertThat(authException.getDescription(), is("Failed to parse json body")); assertThat(authException.getError(), is(nullValue())); assertThat(authException.getStatusCode(), is(200)); } @Test public void shouldParseJSONErrorResponseWithErrorDescription() throws Exception { CustomRequest<List> request = new CustomRequest<>(client, server.getBaseUrl(), "GET", listType); server.jsonResponse(AUTH_ERROR_WITH_ERROR_DESCRIPTION, 400); Exception exception = null; try { request.execute(); server.takeRequest(); } catch (Exception e) { exception = e; } assertThat(exception, is(notNullValue())); assertThat(exception, is(instanceOf(APIException.class))); assertThat(exception.getCause(), is(nullValue())); assertThat(exception.getMessage(), is("Request failed with status code 400: the connection was not found")); APIException authException = (APIException) exception; assertThat(authException.getDescription(), is("the connection was not found")); assertThat(authException.getError(), is("invalid_request")); assertThat(authException.getStatusCode(), is(400)); } @Test public void shouldParseJSONErrorResponseWithError() throws Exception { CustomRequest<List> request = new CustomRequest<>(client, server.getBaseUrl(), "GET", listType); server.jsonResponse(AUTH_ERROR_WITH_ERROR, 400); Exception exception = null; try { request.execute(); server.takeRequest(); } catch (Exception e) { exception = e; } assertThat(exception, is(notNullValue())); assertThat(exception, is(instanceOf(APIException.class))); assertThat(exception.getCause(), is(nullValue())); assertThat(exception.getMessage(), is("Request failed with status code 400: missing username for Username-Password-Authentication connection with requires_username enabled")); APIException authException = (APIException) exception; assertThat(authException.getDescription(), is("missing username for Username-Password-Authentication connection with requires_username enabled")); assertThat(authException.getError(), is("missing username for Username-Password-Authentication connection with requires_username enabled")); assertThat(authException.getStatusCode(), is(400)); } @Test public void shouldParseJSONErrorResponseWithDescriptionAndExtraProperties() throws Exception { CustomRequest<List> request = new CustomRequest<>(client, server.getBaseUrl(), "GET", listType); server.jsonResponse(AUTH_ERROR_WITH_DESCRIPTION_AND_EXTRA_PROPERTIES, 400); Exception exception = null; try { request.execute(); server.takeRequest(); } catch (Exception e) { exception = e; } assertThat(exception, is(notNullValue())); assertThat(exception, is(instanceOf(APIException.class))); assertThat(exception.getCause(), is(nullValue())); assertThat(exception.getMessage(), is("Request failed with status code 400: Multifactor authentication required")); APIException authException = (APIException) exception; assertThat(authException.getDescription(), is("Multifactor authentication required")); assertThat(authException.getError(), is("mfa_required")); assertThat(authException.getValue("mfa_token"), is("Fe26...Ha")); assertThat(authException.getValue("non_existing_key"), is(nullValue())); assertThat(authException.getStatusCode(), is(400)); } @Test public void shouldParseJSONErrorResponseWithDescription() throws Exception { CustomRequest<List> request = new CustomRequest<>(client, server.getBaseUrl(), "GET", listType); server.jsonResponse(AUTH_ERROR_WITH_DESCRIPTION, 400); Exception exception = null; try { request.execute(); server.takeRequest(); } catch (Exception e) { exception = e; } assertThat(exception, is(notNullValue())); assertThat(exception, is(instanceOf(APIException.class))); assertThat(exception.getCause(), is(nullValue())); assertThat(exception.getMessage(), is("Request failed with status code 400: The user already exists.")); APIException authException = (APIException) exception; assertThat(authException.getDescription(), is("The user already exists.")); assertThat(authException.getError(), is("user_exists")); assertThat(authException.getStatusCode(), is(400)); } @Test public void shouldParseJSONErrorResponseWithMessage() throws Exception { CustomRequest<List> request = new CustomRequest<>(client, server.getBaseUrl(), "GET", listType); server.jsonResponse(MGMT_ERROR_WITH_MESSAGE, 400); Exception exception = null; try { request.execute(); server.takeRequest(); } catch (Exception e) { exception = e; } assertThat(exception, is(notNullValue())); assertThat(exception, is(instanceOf(APIException.class))); assertThat(exception.getCause(), is(nullValue())); assertThat(exception.getMessage(), is("Request failed with status code 400: Query validation error: 'String 'invalid_field' does not match pattern. Must be a comma separated list of the following values: allowed_logout_urls,change_password.")); APIException authException = (APIException) exception; assertThat(authException.getDescription(), is("Query validation error: 'String 'invalid_field' does not match pattern. Must be a comma separated list of the following values: allowed_logout_urls,change_password.")); assertThat(authException.getError(), is("invalid_query_string")); assertThat(authException.getStatusCode(), is(400)); } @Test public void shouldParsePlainTextErrorResponse() throws Exception { CustomRequest<List> request = new CustomRequest<>(client, server.getBaseUrl(), "GET", listType); server.textResponse(AUTH_ERROR_PLAINTEXT, 400); Exception exception = null; try { request.execute(); server.takeRequest(); } catch (Exception e) { exception = e; } assertThat(exception, is(notNullValue())); assertThat(exception, is(instanceOf(APIException.class))); assertThat(exception.getCause(), is(instanceOf(JsonParseException.class))); assertThat(exception.getMessage(), is("Request failed with status code 400: A plain-text error response")); APIException authException = (APIException) exception; assertThat(authException.getDescription(), is("A plain-text error response")); assertThat(authException.getError(), is(nullValue())); assertThat(authException.getStatusCode(), is(400)); } }
add missing test case
src/test/java/com/auth0/net/CustomRequestTest.java
add missing test case
<ide><path>rc/test/java/com/auth0/net/CustomRequestTest.java <ide> APIException authException = (APIException) exception; <ide> assertThat(authException.getDescription(), is("A plain-text error response")); <ide> assertThat(authException.getError(), is(nullValue())); <add> assertThat(authException.getValue("non_existing_key"), is(nullValue())); <ide> assertThat(authException.getStatusCode(), is(400)); <ide> } <ide>
Java
bsd-3-clause
error: pathspec 'core/src/androidTest/java/org/hisp/dhis/android/core/event/internal/EventDataFilterStoreIntegrationShould.java' did not match any file(s) known to git
5bca30114c72208b45defc1cc0cb0ba362dc4de2
1
dhis2/dhis2-android-sdk,dhis2/dhis2-android-sdk,dhis2/dhis2-android-sdk
/* * Copyright (c) 2004-2019, 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.event.internal; import org.hisp.dhis.android.core.data.database.ObjectStoreAbstractIntegrationShould; import org.hisp.dhis.android.core.data.event.EventDataFilterSamples; import org.hisp.dhis.android.core.event.EventDataFilter; import org.hisp.dhis.android.core.event.EventDataFilterTableInfo; import org.hisp.dhis.android.core.utils.integration.mock.TestDatabaseAdapterFactory; import org.hisp.dhis.android.core.utils.runner.D2JunitRunner; import org.junit.runner.RunWith; @RunWith(D2JunitRunner.class) public class EventDataFilterStoreIntegrationShould extends ObjectStoreAbstractIntegrationShould<EventDataFilter> { public EventDataFilterStoreIntegrationShould() { super(EventDataFilterStore.create(TestDatabaseAdapterFactory.get()), EventDataFilterTableInfo.TABLE_INFO, TestDatabaseAdapterFactory.get()); } @Override protected EventDataFilter buildObject() { return EventDataFilterSamples.get(); } }
core/src/androidTest/java/org/hisp/dhis/android/core/event/internal/EventDataFilterStoreIntegrationShould.java
[androsdk-1269] Add EventDataFilterStoreIntegrationShould
core/src/androidTest/java/org/hisp/dhis/android/core/event/internal/EventDataFilterStoreIntegrationShould.java
[androsdk-1269] Add EventDataFilterStoreIntegrationShould
<ide><path>ore/src/androidTest/java/org/hisp/dhis/android/core/event/internal/EventDataFilterStoreIntegrationShould.java <add>/* <add> * Copyright (c) 2004-2019, University of Oslo <add> * All rights reserved. <add> * <add> * Redistribution and use in source and binary forms, with or without <add> * modification, are permitted provided that the following conditions are met: <add> * Redistributions of source code must retain the above copyright notice, this <add> * list of conditions and the following disclaimer. <add> * <add> * Redistributions in binary form must reproduce the above copyright notice, <add> * this list of conditions and the following disclaimer in the documentation <add> * and/or other materials provided with the distribution. <add> * Neither the name of the HISP project nor the names of its contributors may <add> * be used to endorse or promote products derived from this software without <add> * specific prior written permission. <add> * <add> * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND <add> * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED <add> * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE <add> * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR <add> * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES <add> * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; <add> * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON <add> * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT <add> * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS <add> * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. <add> */ <add> <add>package org.hisp.dhis.android.core.event.internal; <add> <add>import org.hisp.dhis.android.core.data.database.ObjectStoreAbstractIntegrationShould; <add>import org.hisp.dhis.android.core.data.event.EventDataFilterSamples; <add>import org.hisp.dhis.android.core.event.EventDataFilter; <add>import org.hisp.dhis.android.core.event.EventDataFilterTableInfo; <add>import org.hisp.dhis.android.core.utils.integration.mock.TestDatabaseAdapterFactory; <add>import org.hisp.dhis.android.core.utils.runner.D2JunitRunner; <add>import org.junit.runner.RunWith; <add> <add>@RunWith(D2JunitRunner.class) <add>public class EventDataFilterStoreIntegrationShould extends ObjectStoreAbstractIntegrationShould<EventDataFilter> { <add> <add> public EventDataFilterStoreIntegrationShould() { <add> super(EventDataFilterStore.create(TestDatabaseAdapterFactory.get()), <add> EventDataFilterTableInfo.TABLE_INFO, TestDatabaseAdapterFactory.get()); <add> } <add> <add> @Override <add> protected EventDataFilter buildObject() { <add> return EventDataFilterSamples.get(); <add> } <add>}
JavaScript
mit
4f28522bf6d9a1732a35c00b7d5c53414975eb8e
0
Simpreative/WebSockChat,Simpreative/WebSockChat
var ws = require("nodejs-websocket") function broadcast(server, msg) { server.connections.forEach(function (conn) { conn.sendText(msg) }) } var server = ws.createServer(function (conn) { console.log("New connection") conn.on("text", function (str) { console.log("Received " + str) broadcast(self, str) }) conn.on("close", function (code, reason) { console.log("Connection closed") }) }).listen(80)
ws_server.js
var ws = require("nodejs-websocket") var server = ws.createServer(function (conn) { console.log("New connection") conn.on("text", function (str) { console.log("Received "+str) conn.sendText(str) }) conn.on("close", function (code, reason) { console.log("Connection closed") }) }).listen(8000)
broadcast test
ws_server.js
broadcast test
<ide><path>s_server.js <ide> var ws = require("nodejs-websocket") <ide> <add>function broadcast(server, msg) { <add> server.connections.forEach(function (conn) { <add> conn.sendText(msg) <add> }) <add>} <add> <ide> var server = ws.createServer(function (conn) { <ide> console.log("New connection") <ide> conn.on("text", function (str) { <del> console.log("Received "+str) <del> conn.sendText(str) <add> console.log("Received " + str) <add> broadcast(self, str) <ide> }) <ide> conn.on("close", function (code, reason) { <ide> console.log("Connection closed") <ide> }) <del>}).listen(8000) <add>}).listen(80)
Java
apache-2.0
b7e949dc8ddf9c5bf5c4601ec30105c103cc6dca
0
vladmm/intellij-community,kdwink/intellij-community,ftomassetti/intellij-community,fitermay/intellij-community,signed/intellij-community,amith01994/intellij-community,robovm/robovm-studio,mglukhikh/intellij-community,akosyakov/intellij-community,caot/intellij-community,hurricup/intellij-community,vvv1559/intellij-community,lucafavatella/intellij-community,hurricup/intellij-community,dslomov/intellij-community,ol-loginov/intellij-community,izonder/intellij-community,MichaelNedzelsky/intellij-community,retomerz/intellij-community,nicolargo/intellij-community,muntasirsyed/intellij-community,fnouama/intellij-community,da1z/intellij-community,slisson/intellij-community,samthor/intellij-community,ol-loginov/intellij-community,supersven/intellij-community,idea4bsd/idea4bsd,retomerz/intellij-community,tmpgit/intellij-community,TangHao1987/intellij-community,suncycheng/intellij-community,FHannes/intellij-community,salguarnieri/intellij-community,FHannes/intellij-community,mglukhikh/intellij-community,izonder/intellij-community,mglukhikh/intellij-community,michaelgallacher/intellij-community,kool79/intellij-community,semonte/intellij-community,hurricup/intellij-community,signed/intellij-community,MichaelNedzelsky/intellij-community,SerCeMan/intellij-community,samthor/intellij-community,robovm/robovm-studio,TangHao1987/intellij-community,samthor/intellij-community,akosyakov/intellij-community,tmpgit/intellij-community,ThiagoGarciaAlves/intellij-community,ahb0327/intellij-community,fnouama/intellij-community,muntasirsyed/intellij-community,mglukhikh/intellij-community,youdonghai/intellij-community,amith01994/intellij-community,suncycheng/intellij-community,Distrotech/intellij-community,ol-loginov/intellij-community,fnouama/intellij-community,ol-loginov/intellij-community,signed/intellij-community,adedayo/intellij-community,Lekanich/intellij-community,jexp/idea2,caot/intellij-community,diorcety/intellij-community,xfournet/intellij-community,consulo/consulo,jexp/idea2,kool79/intellij-community,clumsy/intellij-community,apixandru/intellij-community,FHannes/intellij-community,izonder/intellij-community,vvv1559/intellij-community,ftomassetti/intellij-community,suncycheng/intellij-community,supersven/intellij-community,fitermay/intellij-community,fnouama/intellij-community,lucafavatella/intellij-community,ol-loginov/intellij-community,asedunov/intellij-community,vvv1559/intellij-community,Distrotech/intellij-community,muntasirsyed/intellij-community,xfournet/intellij-community,nicolargo/intellij-community,ahb0327/intellij-community,ernestp/consulo,allotria/intellij-community,fnouama/intellij-community,robovm/robovm-studio,ibinti/intellij-community,kool79/intellij-community,fengbaicanhe/intellij-community,allotria/intellij-community,wreckJ/intellij-community,orekyuu/intellij-community,fitermay/intellij-community,retomerz/intellij-community,MichaelNedzelsky/intellij-community,ibinti/intellij-community,youdonghai/intellij-community,clumsy/intellij-community,ol-loginov/intellij-community,robovm/robovm-studio,dslomov/intellij-community,tmpgit/intellij-community,SerCeMan/intellij-community,FHannes/intellij-community,slisson/intellij-community,da1z/intellij-community,adedayo/intellij-community,pwoodworth/intellij-community,orekyuu/intellij-community,gnuhub/intellij-community,ol-loginov/intellij-community,salguarnieri/intellij-community,semonte/intellij-community,fengbaicanhe/intellij-community,fitermay/intellij-community,alphafoobar/intellij-community,petteyg/intellij-community,xfournet/intellij-community,adedayo/intellij-community,holmes/intellij-community,alphafoobar/intellij-community,ivan-fedorov/intellij-community,gnuhub/intellij-community,MichaelNedzelsky/intellij-community,apixandru/intellij-community,ernestp/consulo,jagguli/intellij-community,caot/intellij-community,vvv1559/intellij-community,idea4bsd/idea4bsd,fitermay/intellij-community,joewalnes/idea-community,kdwink/intellij-community,slisson/intellij-community,alphafoobar/intellij-community,samthor/intellij-community,adedayo/intellij-community,jagguli/intellij-community,semonte/intellij-community,lucafavatella/intellij-community,caot/intellij-community,joewalnes/idea-community,holmes/intellij-community,MER-GROUP/intellij-community,lucafavatella/intellij-community,akosyakov/intellij-community,michaelgallacher/intellij-community,holmes/intellij-community,MER-GROUP/intellij-community,ftomassetti/intellij-community,tmpgit/intellij-community,retomerz/intellij-community,xfournet/intellij-community,ryano144/intellij-community,pwoodworth/intellij-community,MichaelNedzelsky/intellij-community,ivan-fedorov/intellij-community,Lekanich/intellij-community,dslomov/intellij-community,supersven/intellij-community,Lekanich/intellij-community,fengbaicanhe/intellij-community,supersven/intellij-community,izonder/intellij-community,pwoodworth/intellij-community,kool79/intellij-community,fengbaicanhe/intellij-community,akosyakov/intellij-community,ibinti/intellij-community,jexp/idea2,Lekanich/intellij-community,caot/intellij-community,da1z/intellij-community,hurricup/intellij-community,salguarnieri/intellij-community,TangHao1987/intellij-community,ol-loginov/intellij-community,kool79/intellij-community,blademainer/intellij-community,MichaelNedzelsky/intellij-community,wreckJ/intellij-community,idea4bsd/idea4bsd,ryano144/intellij-community,ryano144/intellij-community,izonder/intellij-community,salguarnieri/intellij-community,caot/intellij-community,fitermay/intellij-community,signed/intellij-community,fengbaicanhe/intellij-community,ftomassetti/intellij-community,da1z/intellij-community,michaelgallacher/intellij-community,michaelgallacher/intellij-community,muntasirsyed/intellij-community,pwoodworth/intellij-community,kool79/intellij-community,diorcety/intellij-community,jagguli/intellij-community,blademainer/intellij-community,clumsy/intellij-community,michaelgallacher/intellij-community,ryano144/intellij-community,ibinti/intellij-community,nicolargo/intellij-community,lucafavatella/intellij-community,adedayo/intellij-community,asedunov/intellij-community,alphafoobar/intellij-community,wreckJ/intellij-community,semonte/intellij-community,orekyuu/intellij-community,ivan-fedorov/intellij-community,ryano144/intellij-community,lucafavatella/intellij-community,gnuhub/intellij-community,Lekanich/intellij-community,izonder/intellij-community,idea4bsd/idea4bsd,Distrotech/intellij-community,MER-GROUP/intellij-community,xfournet/intellij-community,gnuhub/intellij-community,fnouama/intellij-community,vladmm/intellij-community,MER-GROUP/intellij-community,da1z/intellij-community,amith01994/intellij-community,idea4bsd/idea4bsd,apixandru/intellij-community,semonte/intellij-community,wreckJ/intellij-community,idea4bsd/idea4bsd,TangHao1987/intellij-community,muntasirsyed/intellij-community,suncycheng/intellij-community,ivan-fedorov/intellij-community,youdonghai/intellij-community,ivan-fedorov/intellij-community,adedayo/intellij-community,signed/intellij-community,idea4bsd/idea4bsd,allotria/intellij-community,TangHao1987/intellij-community,SerCeMan/intellij-community,ol-loginov/intellij-community,ibinti/intellij-community,blademainer/intellij-community,holmes/intellij-community,fitermay/intellij-community,idea4bsd/idea4bsd,apixandru/intellij-community,TangHao1987/intellij-community,vladmm/intellij-community,Distrotech/intellij-community,ThiagoGarciaAlves/intellij-community,nicolargo/intellij-community,Distrotech/intellij-community,ryano144/intellij-community,clumsy/intellij-community,ahb0327/intellij-community,jagguli/intellij-community,petteyg/intellij-community,amith01994/intellij-community,ibinti/intellij-community,michaelgallacher/intellij-community,MER-GROUP/intellij-community,salguarnieri/intellij-community,blademainer/intellij-community,fnouama/intellij-community,izonder/intellij-community,muntasirsyed/intellij-community,dslomov/intellij-community,ThiagoGarciaAlves/intellij-community,blademainer/intellij-community,mglukhikh/intellij-community,ibinti/intellij-community,akosyakov/intellij-community,tmpgit/intellij-community,joewalnes/idea-community,nicolargo/intellij-community,joewalnes/idea-community,ftomassetti/intellij-community,fitermay/intellij-community,jagguli/intellij-community,lucafavatella/intellij-community,supersven/intellij-community,mglukhikh/intellij-community,ahb0327/intellij-community,samthor/intellij-community,signed/intellij-community,fengbaicanhe/intellij-community,TangHao1987/intellij-community,retomerz/intellij-community,youdonghai/intellij-community,blademainer/intellij-community,semonte/intellij-community,allotria/intellij-community,ivan-fedorov/intellij-community,idea4bsd/idea4bsd,kdwink/intellij-community,da1z/intellij-community,ThiagoGarciaAlves/intellij-community,amith01994/intellij-community,retomerz/intellij-community,MER-GROUP/intellij-community,nicolargo/intellij-community,mglukhikh/intellij-community,dslomov/intellij-community,FHannes/intellij-community,petteyg/intellij-community,vladmm/intellij-community,xfournet/intellij-community,vvv1559/intellij-community,SerCeMan/intellij-community,asedunov/intellij-community,samthor/intellij-community,suncycheng/intellij-community,FHannes/intellij-community,kool79/intellij-community,apixandru/intellij-community,supersven/intellij-community,kdwink/intellij-community,clumsy/intellij-community,ernestp/consulo,FHannes/intellij-community,xfournet/intellij-community,hurricup/intellij-community,Lekanich/intellij-community,fengbaicanhe/intellij-community,youdonghai/intellij-community,alphafoobar/intellij-community,ftomassetti/intellij-community,diorcety/intellij-community,ryano144/intellij-community,clumsy/intellij-community,MichaelNedzelsky/intellij-community,pwoodworth/intellij-community,supersven/intellij-community,fengbaicanhe/intellij-community,orekyuu/intellij-community,ryano144/intellij-community,ivan-fedorov/intellij-community,michaelgallacher/intellij-community,caot/intellij-community,dslomov/intellij-community,slisson/intellij-community,da1z/intellij-community,salguarnieri/intellij-community,ftomassetti/intellij-community,fitermay/intellij-community,wreckJ/intellij-community,youdonghai/intellij-community,salguarnieri/intellij-community,slisson/intellij-community,diorcety/intellij-community,Lekanich/intellij-community,consulo/consulo,blademainer/intellij-community,apixandru/intellij-community,consulo/consulo,mglukhikh/intellij-community,slisson/intellij-community,orekyuu/intellij-community,izonder/intellij-community,nicolargo/intellij-community,SerCeMan/intellij-community,gnuhub/intellij-community,ernestp/consulo,vvv1559/intellij-community,holmes/intellij-community,blademainer/intellij-community,nicolargo/intellij-community,jexp/idea2,apixandru/intellij-community,FHannes/intellij-community,vvv1559/intellij-community,diorcety/intellij-community,fitermay/intellij-community,FHannes/intellij-community,apixandru/intellij-community,vladmm/intellij-community,kdwink/intellij-community,suncycheng/intellij-community,asedunov/intellij-community,SerCeMan/intellij-community,vvv1559/intellij-community,kdwink/intellij-community,holmes/intellij-community,jagguli/intellij-community,diorcety/intellij-community,kool79/intellij-community,vladmm/intellij-community,jexp/idea2,akosyakov/intellij-community,caot/intellij-community,suncycheng/intellij-community,TangHao1987/intellij-community,alphafoobar/intellij-community,ibinti/intellij-community,ThiagoGarciaAlves/intellij-community,fengbaicanhe/intellij-community,youdonghai/intellij-community,Distrotech/intellij-community,caot/intellij-community,MER-GROUP/intellij-community,da1z/intellij-community,gnuhub/intellij-community,TangHao1987/intellij-community,retomerz/intellij-community,akosyakov/intellij-community,ryano144/intellij-community,ahb0327/intellij-community,ibinti/intellij-community,adedayo/intellij-community,ahb0327/intellij-community,petteyg/intellij-community,orekyuu/intellij-community,mglukhikh/intellij-community,samthor/intellij-community,retomerz/intellij-community,tmpgit/intellij-community,Distrotech/intellij-community,michaelgallacher/intellij-community,allotria/intellij-community,FHannes/intellij-community,blademainer/intellij-community,ol-loginov/intellij-community,mglukhikh/intellij-community,holmes/intellij-community,pwoodworth/intellij-community,fitermay/intellij-community,izonder/intellij-community,pwoodworth/intellij-community,tmpgit/intellij-community,amith01994/intellij-community,allotria/intellij-community,retomerz/intellij-community,vladmm/intellij-community,semonte/intellij-community,ahb0327/intellij-community,jagguli/intellij-community,jexp/idea2,youdonghai/intellij-community,fnouama/intellij-community,MER-GROUP/intellij-community,fengbaicanhe/intellij-community,nicolargo/intellij-community,consulo/consulo,ernestp/consulo,ahb0327/intellij-community,alphafoobar/intellij-community,diorcety/intellij-community,robovm/robovm-studio,signed/intellij-community,clumsy/intellij-community,ahb0327/intellij-community,ThiagoGarciaAlves/intellij-community,amith01994/intellij-community,allotria/intellij-community,signed/intellij-community,hurricup/intellij-community,orekyuu/intellij-community,MER-GROUP/intellij-community,alphafoobar/intellij-community,holmes/intellij-community,akosyakov/intellij-community,michaelgallacher/intellij-community,alphafoobar/intellij-community,SerCeMan/intellij-community,Distrotech/intellij-community,xfournet/intellij-community,MER-GROUP/intellij-community,salguarnieri/intellij-community,Distrotech/intellij-community,pwoodworth/intellij-community,samthor/intellij-community,fnouama/intellij-community,muntasirsyed/intellij-community,ahb0327/intellij-community,SerCeMan/intellij-community,clumsy/intellij-community,ernestp/consulo,izonder/intellij-community,SerCeMan/intellij-community,adedayo/intellij-community,ivan-fedorov/intellij-community,clumsy/intellij-community,pwoodworth/intellij-community,fengbaicanhe/intellij-community,nicolargo/intellij-community,asedunov/intellij-community,diorcety/intellij-community,pwoodworth/intellij-community,retomerz/intellij-community,slisson/intellij-community,asedunov/intellij-community,slisson/intellij-community,gnuhub/intellij-community,adedayo/intellij-community,kool79/intellij-community,supersven/intellij-community,ibinti/intellij-community,vladmm/intellij-community,allotria/intellij-community,vvv1559/intellij-community,fnouama/intellij-community,TangHao1987/intellij-community,TangHao1987/intellij-community,caot/intellij-community,clumsy/intellij-community,akosyakov/intellij-community,supersven/intellij-community,suncycheng/intellij-community,salguarnieri/intellij-community,consulo/consulo,vladmm/intellij-community,orekyuu/intellij-community,ftomassetti/intellij-community,wreckJ/intellij-community,lucafavatella/intellij-community,MER-GROUP/intellij-community,ftomassetti/intellij-community,alphafoobar/intellij-community,signed/intellij-community,dslomov/intellij-community,semonte/intellij-community,jagguli/intellij-community,ibinti/intellij-community,adedayo/intellij-community,tmpgit/intellij-community,youdonghai/intellij-community,amith01994/intellij-community,alphafoobar/intellij-community,fnouama/intellij-community,Distrotech/intellij-community,semonte/intellij-community,fengbaicanhe/intellij-community,retomerz/intellij-community,amith01994/intellij-community,dslomov/intellij-community,xfournet/intellij-community,suncycheng/intellij-community,semonte/intellij-community,petteyg/intellij-community,xfournet/intellij-community,michaelgallacher/intellij-community,kool79/intellij-community,robovm/robovm-studio,idea4bsd/idea4bsd,petteyg/intellij-community,xfournet/intellij-community,ThiagoGarciaAlves/intellij-community,asedunov/intellij-community,ibinti/intellij-community,ThiagoGarciaAlves/intellij-community,apixandru/intellij-community,diorcety/intellij-community,caot/intellij-community,robovm/robovm-studio,wreckJ/intellij-community,joewalnes/idea-community,ivan-fedorov/intellij-community,allotria/intellij-community,allotria/intellij-community,Lekanich/intellij-community,samthor/intellij-community,lucafavatella/intellij-community,ol-loginov/intellij-community,petteyg/intellij-community,hurricup/intellij-community,allotria/intellij-community,akosyakov/intellij-community,semonte/intellij-community,mglukhikh/intellij-community,apixandru/intellij-community,dslomov/intellij-community,petteyg/intellij-community,lucafavatella/intellij-community,MichaelNedzelsky/intellij-community,michaelgallacher/intellij-community,jexp/idea2,suncycheng/intellij-community,xfournet/intellij-community,asedunov/intellij-community,youdonghai/intellij-community,MichaelNedzelsky/intellij-community,gnuhub/intellij-community,kool79/intellij-community,suncycheng/intellij-community,joewalnes/idea-community,ibinti/intellij-community,kdwink/intellij-community,joewalnes/idea-community,Distrotech/intellij-community,TangHao1987/intellij-community,kdwink/intellij-community,hurricup/intellij-community,hurricup/intellij-community,michaelgallacher/intellij-community,jagguli/intellij-community,youdonghai/intellij-community,robovm/robovm-studio,joewalnes/idea-community,ThiagoGarciaAlves/intellij-community,gnuhub/intellij-community,da1z/intellij-community,kdwink/intellij-community,MichaelNedzelsky/intellij-community,lucafavatella/intellij-community,blademainer/intellij-community,muntasirsyed/intellij-community,tmpgit/intellij-community,Lekanich/intellij-community,diorcety/intellij-community,ftomassetti/intellij-community,ol-loginov/intellij-community,ivan-fedorov/intellij-community,kdwink/intellij-community,holmes/intellij-community,idea4bsd/idea4bsd,semonte/intellij-community,dslomov/intellij-community,mglukhikh/intellij-community,jagguli/intellij-community,ryano144/intellij-community,robovm/robovm-studio,robovm/robovm-studio,tmpgit/intellij-community,orekyuu/intellij-community,jagguli/intellij-community,signed/intellij-community,wreckJ/intellij-community,FHannes/intellij-community,izonder/intellij-community,signed/intellij-community,akosyakov/intellij-community,gnuhub/intellij-community,petteyg/intellij-community,retomerz/intellij-community,ftomassetti/intellij-community,xfournet/intellij-community,vvv1559/intellij-community,semonte/intellij-community,lucafavatella/intellij-community,asedunov/intellij-community,slisson/intellij-community,tmpgit/intellij-community,allotria/intellij-community,dslomov/intellij-community,salguarnieri/intellij-community,hurricup/intellij-community,tmpgit/intellij-community,signed/intellij-community,youdonghai/intellij-community,ivan-fedorov/intellij-community,MER-GROUP/intellij-community,signed/intellij-community,vvv1559/intellij-community,diorcety/intellij-community,vladmm/intellij-community,apixandru/intellij-community,amith01994/intellij-community,pwoodworth/intellij-community,apixandru/intellij-community,mglukhikh/intellij-community,FHannes/intellij-community,holmes/intellij-community,wreckJ/intellij-community,alphafoobar/intellij-community,kdwink/intellij-community,SerCeMan/intellij-community,holmes/intellij-community,holmes/intellij-community,fnouama/intellij-community,da1z/intellij-community,SerCeMan/intellij-community,SerCeMan/intellij-community,Lekanich/intellij-community,vladmm/intellij-community,diorcety/intellij-community,ahb0327/intellij-community,vladmm/intellij-community,Lekanich/intellij-community,adedayo/intellij-community,akosyakov/intellij-community,ThiagoGarciaAlves/intellij-community,muntasirsyed/intellij-community,blademainer/intellij-community,supersven/intellij-community,lucafavatella/intellij-community,gnuhub/intellij-community,adedayo/intellij-community,ryano144/intellij-community,suncycheng/intellij-community,ahb0327/intellij-community,samthor/intellij-community,youdonghai/intellij-community,vvv1559/intellij-community,ivan-fedorov/intellij-community,hurricup/intellij-community,blademainer/intellij-community,idea4bsd/idea4bsd,gnuhub/intellij-community,wreckJ/intellij-community,slisson/intellij-community,joewalnes/idea-community,robovm/robovm-studio,da1z/intellij-community,muntasirsyed/intellij-community,da1z/intellij-community,wreckJ/intellij-community,allotria/intellij-community,muntasirsyed/intellij-community,fitermay/intellij-community,kdwink/intellij-community,salguarnieri/intellij-community,consulo/consulo,ryano144/intellij-community,samthor/intellij-community,FHannes/intellij-community,pwoodworth/intellij-community,muntasirsyed/intellij-community,apixandru/intellij-community,MichaelNedzelsky/intellij-community,idea4bsd/idea4bsd,supersven/intellij-community,jexp/idea2,samthor/intellij-community,hurricup/intellij-community,retomerz/intellij-community,slisson/intellij-community,dslomov/intellij-community,petteyg/intellij-community,apixandru/intellij-community,salguarnieri/intellij-community,hurricup/intellij-community,wreckJ/intellij-community,supersven/intellij-community,vvv1559/intellij-community,jagguli/intellij-community,nicolargo/intellij-community,orekyuu/intellij-community,da1z/intellij-community,asedunov/intellij-community,izonder/intellij-community,amith01994/intellij-community,Lekanich/intellij-community,petteyg/intellij-community,clumsy/intellij-community,asedunov/intellij-community,kool79/intellij-community,asedunov/intellij-community,fitermay/intellij-community,orekyuu/intellij-community,nicolargo/intellij-community,ThiagoGarciaAlves/intellij-community,asedunov/intellij-community,ftomassetti/intellij-community,clumsy/intellij-community,amith01994/intellij-community,ThiagoGarciaAlves/intellij-community,orekyuu/intellij-community,caot/intellij-community,MichaelNedzelsky/intellij-community,slisson/intellij-community,robovm/robovm-studio,Distrotech/intellij-community,petteyg/intellij-community
/* * Created by IntelliJ IDEA. * User: cdr * Date: Jul 15, 2007 * Time: 4:04:39 PM */ package com.intellij.openapi.vfs.encoding; import com.intellij.openapi.actionSystem.*; import com.intellij.openapi.actionSystem.impl.SimpleDataContext; import com.intellij.openapi.project.Project; import com.intellij.openapi.roots.ProjectFileIndex; import com.intellij.openapi.roots.ProjectRootManager; import com.intellij.openapi.ui.Messages; import com.intellij.openapi.vfs.VfsUtil; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.openapi.util.Pair; import com.intellij.openapi.fileEditor.impl.LoadTextUtil; import com.intellij.ui.TableUtil; import com.intellij.util.IconUtil; import com.intellij.util.Icons; import com.intellij.util.containers.HashMap; import com.intellij.util.ui.UIUtil; import com.intellij.util.ui.tree.TreeUtil; import com.intellij.util.ui.treetable.TreeTable; import com.intellij.util.ui.treetable.TreeTableCellRenderer; import com.intellij.util.ui.treetable.TreeTableModel; import gnu.trove.THashMap; import org.jetbrains.annotations.NotNull; import javax.swing.*; import javax.swing.table.DefaultTableCellRenderer; import javax.swing.table.TableColumn; import javax.swing.tree.DefaultMutableTreeNode; import javax.swing.tree.DefaultTreeCellRenderer; import javax.swing.tree.DefaultTreeModel; import javax.swing.tree.TreeNode; import java.awt.*; import java.nio.charset.Charset; import java.util.*; import java.util.List; public class FileTreeTable extends TreeTable { private final MyModel myModel; private final Project myProject; public FileTreeTable(final Project project) { super(new MyModel(project)); myProject = project; myModel = (MyModel)getTableModel(); final TableColumn valueColumn = getColumnModel().getColumn(1); valueColumn.setCellRenderer(new DefaultTableCellRenderer(){ public Component getTableCellRendererComponent(final JTable table, final Object value, final boolean isSelected, final boolean hasFocus, final int row, final int column) { super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column); Charset t = (Charset)value; Object userObject = table.getModel().getValueAt(row, 0); VirtualFile file = userObject instanceof VirtualFile ? (VirtualFile)userObject : null; Pair<String,Boolean> pair = ChangeEncodingUpdateGroup.update(myProject, file); boolean enabled = file == null || pair.getSecond(); if (t != null) { setText(t.displayName()); } else { if (file != null) { Charset charset = ChooseFileEncodingAction.encodingFromContent(myProject, file); if (charset != null) { setText(charset.displayName()); } else if (LoadTextUtil.utfCharsetWasDetectedFromBytes(file)) { setText(file.getCharset().displayName()); } else if (!ChooseFileEncodingAction.isEnabled(myProject, file)) { setText("N/A"); } } } setEnabled(enabled); return this; } }); valueColumn.setCellEditor(new DefaultCellEditor(new JComboBox()){ private VirtualFile myVirtualFile; { delegate = new EditorDelegate() { public void setValue(Object value) { myModel.setValueAt(value, new DefaultMutableTreeNode(myVirtualFile), -1); } public Object getCellEditorValue() { return myModel.getValueAt(new DefaultMutableTreeNode(myVirtualFile), 1); } }; } public Component getTableCellEditorComponent(JTable table, final Object value, boolean isSelected, int row, int column) { Object o = table.getModel().getValueAt(row, 0); myVirtualFile = o instanceof Project ? null : (VirtualFile)o; final ChooseFileEncodingAction changeAction = new ChooseFileEncodingAction(myVirtualFile, myProject){ protected void chosen(VirtualFile virtualFile, Charset charset) { valueColumn.getCellEditor().stopCellEditing(); int ret = askWhetherClearSubdirectories(virtualFile); if (ret != 2) { myModel.setValueAt(charset, new DefaultMutableTreeNode(virtualFile), 1); } } }; Presentation templatePresentation = changeAction.getTemplatePresentation(); final JComponent comboComponent = changeAction.createCustomComponent(templatePresentation); DataContext dataContext = SimpleDataContext.getSimpleContext(DataConstants.VIRTUAL_FILE, myVirtualFile, SimpleDataContext.getProjectContext(myProject)); AnActionEvent event = new AnActionEvent(null, dataContext, ActionPlaces.UNKNOWN, templatePresentation, ActionManager.getInstance(), 0); changeAction.update(event); editorComponent = comboComponent; Charset charset = (Charset)myModel.getValueAt(new DefaultMutableTreeNode(myVirtualFile), 1); templatePresentation.setText(charset == null ? "" : charset.displayName()); comboComponent.revalidate(); return editorComponent; } }); getTree().setShowsRootHandles(true); getTree().setLineStyleAngled(); getTree().setRootVisible(true); getTree().setCellRenderer(new DefaultTreeCellRenderer(){ public Component getTreeCellRendererComponent(final JTree tree, final Object value, final boolean sel, final boolean expanded, final boolean leaf, final int row, final boolean hasFocus) { super.getTreeCellRendererComponent(tree, value, sel, expanded, leaf, row, hasFocus); if (value instanceof ProjectRootNode) { setText("Project"); return this; } FileNode fileNode = (FileNode)value; VirtualFile file = fileNode.getObject(); if (fileNode.getParent() instanceof FileNode) { setText(file.getName()); } else { setText(file.getPresentableUrl()); } Icon icon; if (file.isDirectory()) { icon = expanded ? Icons.DIRECTORY_OPEN_ICON : Icons.DIRECTORY_CLOSED_ICON; } else { icon = IconUtil.getIcon(file, 0, null); } setIcon(icon); return this; } }); getTableHeader().setReorderingAllowed(false); setSelectionMode(ListSelectionModel.SINGLE_SELECTION); setPreferredScrollableViewportSize(new Dimension(300, getRowHeight() * 10)); getColumnModel().getColumn(0).setPreferredWidth(280); valueColumn.setPreferredWidth(60); } private int askWhetherClearSubdirectories(final VirtualFile parent) { Map<VirtualFile, Charset> mappings = myModel.myCurrentMapping; Map<VirtualFile, Charset> subdirectoryMappings = new THashMap<VirtualFile, Charset>(); for (VirtualFile file : mappings.keySet()) { if (file != null && (parent == null || VfsUtil.isAncestor(parent, file, true))) { subdirectoryMappings.put(file, mappings.get(file)); } } if (subdirectoryMappings.isEmpty()) { return 0; } else { int ret = Messages.showDialog(myProject, "There are encodings specified for the subdirectories. Override them?", "Override Subdirectory Encoding", new String[]{"Override","Do Not Override","Cancel"}, 0, Messages.getWarningIcon()); if (ret == 0) { for (VirtualFile file : subdirectoryMappings.keySet()) { myModel.setValueAt(null, new DefaultMutableTreeNode(file), 1); } } return ret; } } public Map<VirtualFile, Charset> getValues() { return myModel.getValues(); } public TreeTableCellRenderer createTableRenderer(TreeTableModel treeTableModel) { TreeTableCellRenderer tableRenderer = super.createTableRenderer(treeTableModel); UIUtil.setLineStyleAngled(tableRenderer); tableRenderer.setRootVisible(false); tableRenderer.setShowsRootHandles(true); return tableRenderer; } public void reset(final Map<VirtualFile, Charset> mappings) { myModel.reset(mappings); final TreeNode root = (TreeNode)myModel.getRoot(); myModel.nodeChanged(root); getTree().setModel(null); getTree().setModel(myModel); } public void select(final VirtualFile toSelect) { if (toSelect != null) { select(toSelect, (TreeNode)myModel.getRoot()); } } private void select(@NotNull VirtualFile toSelect, final TreeNode root) { for (int i = 0; i < root.getChildCount(); i++) { TreeNode child = root.getChildAt(i); VirtualFile file = ((FileNode)child).getObject(); if (VfsUtil.isAncestor(file, toSelect, false)) { if (file == toSelect) { TreeUtil.selectNode(getTree(), child); getSelectionModel().clearSelection(); addSelectedPath(TreeUtil.getPathFromRoot(child)); TableUtil.scrollSelectionToVisible(this); } else { select(toSelect, child); } return; } } } private static class MyModel extends DefaultTreeModel implements TreeTableModel { private final Map<VirtualFile, Charset> myCurrentMapping = new HashMap<VirtualFile, Charset>(); private final Project myProject; private MyModel(Project project) { super(new ProjectRootNode(project)); myProject = project; myCurrentMapping.putAll(EncodingProjectManager.getInstance(project).getAllMappings()); } private Map<VirtualFile, Charset> getValues() { return new HashMap<VirtualFile, Charset>(myCurrentMapping); } public int getColumnCount() { return 2; } public String getColumnName(final int column) { switch(column) { case 0: return "File/Directory"; case 1: return "Default Encoding"; default: throw new RuntimeException("invalid column " + column); } } public Class getColumnClass(final int column) { switch(column) { case 0: return TreeTableModel.class; case 1: return Charset.class; default: throw new RuntimeException("invalid column " + column); } } public Object getValueAt(final Object node, final int column) { Object userObject = ((DefaultMutableTreeNode)node).getUserObject(); if (userObject instanceof Project) { switch(column) { case 0: return userObject; case 1: return myCurrentMapping.get(null); } } VirtualFile file = (VirtualFile)userObject; switch(column) { case 0: return file; case 1: return myCurrentMapping.get(file); default: throw new RuntimeException("invalid column " + column); } } public boolean isCellEditable(final Object node, final int column) { switch(column) { case 0: return false; case 1: Object userObject = ((DefaultMutableTreeNode)node).getUserObject(); if (userObject instanceof VirtualFile) { VirtualFile file = (VirtualFile)userObject; Pair<String,Boolean> pair = ChangeEncodingUpdateGroup.update(myProject, file); return pair.getSecond(); } return true; default: throw new RuntimeException("invalid column " + column); } } public void setValueAt(final Object aValue, final Object node, final int column) { DefaultMutableTreeNode treeNode = (DefaultMutableTreeNode)node; Object userObject = treeNode.getUserObject(); if (userObject instanceof Project) return; VirtualFile file = (VirtualFile)userObject; Charset charset = (Charset)aValue; if (charset == ChooseFileEncodingAction.NO_ENCODING || charset == null) { myCurrentMapping.remove(file); } else { myCurrentMapping.put(file, charset); } fireTreeNodesChanged(this, new Object[]{getRoot()}, null, null); } public void reset(final Map<VirtualFile, Charset> mappings) { myCurrentMapping.clear(); myCurrentMapping.putAll(mappings); ((ProjectRootNode)getRoot()).clearCachedChildren(); } } private static class ProjectRootNode extends ConvenientNode<Project> { public ProjectRootNode(Project project) { super(project); } protected void appendChildrenTo(final Collection<ConvenientNode> children) { Project project = getObject(); VirtualFile[] roots = ProjectRootManager.getInstance(project).getContentRoots(); NextRoot: for (VirtualFile root : roots) { for (VirtualFile candidate : roots) { if (VfsUtil.isAncestor(candidate, root, true)) continue NextRoot; } children.add(new FileNode(root, project)); } } } private abstract static class ConvenientNode<T> extends DefaultMutableTreeNode { private final T myObject; private ConvenientNode(T object) { myObject = object; } public T getObject() { return myObject; } protected abstract void appendChildrenTo(final Collection<ConvenientNode> children); public int getChildCount() { init(); return super.getChildCount(); } public TreeNode getChildAt(final int childIndex) { init(); return super.getChildAt(childIndex); } public Enumeration children() { init(); return super.children(); } private void init() { if (getUserObject() == null) { setUserObject(myObject); List<ConvenientNode> children = new ArrayList<ConvenientNode>(); appendChildrenTo(children); Collections.sort(children, new Comparator<ConvenientNode>() { public int compare(final ConvenientNode node1, final ConvenientNode node2) { Object o1 = node1.getObject(); Object o2 = node2.getObject(); if (o1 == o2) return 0; if (o1 instanceof Project) return -1; if (o2 instanceof Project) return 1; VirtualFile file1 = (VirtualFile)o1; VirtualFile file2 = (VirtualFile)o2; if (file1.isDirectory() != file2.isDirectory()) { return file1.isDirectory() ? -1 : 1; } return file1.getName().compareTo(file2.getName()); } }); int i=0; for (ConvenientNode child : children) { insert(child, i++); } } } public void clearCachedChildren() { if (children != null) { for (Object child : children) { ConvenientNode<T> node = (ConvenientNode<T>)child; node.clearCachedChildren(); } } removeAllChildren(); setUserObject(null); } } private static class FileNode extends ConvenientNode<VirtualFile> { private final Project myProject; private FileNode(@NotNull VirtualFile file, final Project project) { super(file); myProject = project; } protected void appendChildrenTo(final Collection<ConvenientNode> children) { VirtualFile[] childrenf = getObject().getChildren(); ProjectFileIndex fileIndex = ProjectRootManager.getInstance(myProject).getFileIndex(); for (VirtualFile child : childrenf) { if (fileIndex.isInContent(child)) { children.add(new FileNode(child, myProject)); } } } } }
source/com/intellij/openapi/vfs/encoding/FileTreeTable.java
/* * Created by IntelliJ IDEA. * User: cdr * Date: Jul 15, 2007 * Time: 4:04:39 PM */ package com.intellij.openapi.vfs.encoding; import com.intellij.openapi.actionSystem.*; import com.intellij.openapi.actionSystem.impl.SimpleDataContext; import com.intellij.openapi.project.Project; import com.intellij.openapi.roots.ProjectFileIndex; import com.intellij.openapi.roots.ProjectRootManager; import com.intellij.openapi.ui.Messages; import com.intellij.openapi.vfs.VfsUtil; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.ui.TableUtil; import com.intellij.util.IconUtil; import com.intellij.util.Icons; import com.intellij.util.containers.HashMap; import com.intellij.util.ui.UIUtil; import com.intellij.util.ui.tree.TreeUtil; import com.intellij.util.ui.treetable.TreeTable; import com.intellij.util.ui.treetable.TreeTableCellRenderer; import com.intellij.util.ui.treetable.TreeTableModel; import gnu.trove.THashMap; import org.jetbrains.annotations.NotNull; import javax.swing.*; import javax.swing.table.DefaultTableCellRenderer; import javax.swing.table.TableColumn; import javax.swing.tree.DefaultMutableTreeNode; import javax.swing.tree.DefaultTreeCellRenderer; import javax.swing.tree.DefaultTreeModel; import javax.swing.tree.TreeNode; import java.awt.*; import java.nio.charset.Charset; import java.util.*; import java.util.List; public class FileTreeTable extends TreeTable { private final MyModel myModel; private final Project myProject; public FileTreeTable(final Project project) { super(new MyModel(project)); myProject = project; myModel = (MyModel)getTableModel(); final TableColumn valueColumn = getColumnModel().getColumn(1); valueColumn.setCellRenderer(new DefaultTableCellRenderer(){ public Component getTableCellRendererComponent(final JTable table, final Object value, final boolean isSelected, final boolean hasFocus, final int row, final int column) { super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column); Charset t = (Charset)value; if (t != null) { setText(t.displayName()); } else { Object userObject = table.getModel().getValueAt(row, 0); if (userObject instanceof VirtualFile) { VirtualFile file = (VirtualFile)userObject; Charset charset = ChooseFileEncodingAction.encodingFromContent(myProject, file); boolean enabled = ChooseFileEncodingAction.isEnabled(myProject, file); if (charset != null) { setText(charset.displayName()); } else if (!enabled) { setText("N/A"); } setEnabled(enabled); return this; } } setEnabled(true); return this; } }); valueColumn.setCellEditor(new DefaultCellEditor(new JComboBox()){ private VirtualFile myVirtualFile; { delegate = new EditorDelegate() { public void setValue(Object value) { myModel.setValueAt(value, new DefaultMutableTreeNode(myVirtualFile), -1); } public Object getCellEditorValue() { return myModel.getValueAt(new DefaultMutableTreeNode(myVirtualFile), 1); } }; } public Component getTableCellEditorComponent(JTable table, final Object value, boolean isSelected, int row, int column) { Object o = table.getModel().getValueAt(row, 0); myVirtualFile = o instanceof Project ? null : (VirtualFile)o; final ChooseFileEncodingAction changeAction = new ChooseFileEncodingAction(myVirtualFile, myProject){ protected void chosen(VirtualFile virtualFile, Charset charset) { valueColumn.getCellEditor().stopCellEditing(); int ret = askWhetherClearSubdirectories(virtualFile); if (ret != 2) { myModel.setValueAt(charset, new DefaultMutableTreeNode(virtualFile), 1); } } }; Presentation templatePresentation = changeAction.getTemplatePresentation(); final JComponent comboComponent = changeAction.createCustomComponent(templatePresentation); DataContext dataContext = SimpleDataContext.getSimpleContext(DataConstants.VIRTUAL_FILE, myVirtualFile, SimpleDataContext.getProjectContext(myProject)); AnActionEvent event = new AnActionEvent(null, dataContext, ActionPlaces.UNKNOWN, templatePresentation, ActionManager.getInstance(), 0); changeAction.update(event); editorComponent = comboComponent; Charset charset = (Charset)myModel.getValueAt(new DefaultMutableTreeNode(myVirtualFile), 1); templatePresentation.setText(charset == null ? "" : charset.displayName()); comboComponent.revalidate(); return editorComponent; } }); getTree().setShowsRootHandles(true); getTree().setLineStyleAngled(); getTree().setRootVisible(true); getTree().setCellRenderer(new DefaultTreeCellRenderer(){ public Component getTreeCellRendererComponent(final JTree tree, final Object value, final boolean sel, final boolean expanded, final boolean leaf, final int row, final boolean hasFocus) { super.getTreeCellRendererComponent(tree, value, sel, expanded, leaf, row, hasFocus); if (value instanceof ProjectRootNode) { setText("Project"); return this; } FileNode fileNode = (FileNode)value; VirtualFile file = fileNode.getObject(); if (fileNode.getParent() instanceof FileNode) { setText(file.getName()); } else { setText(file.getPresentableUrl()); } Icon icon; if (file.isDirectory()) { icon = expanded ? Icons.DIRECTORY_OPEN_ICON : Icons.DIRECTORY_CLOSED_ICON; } else { icon = IconUtil.getIcon(file, 0, null); } setIcon(icon); return this; } }); getTableHeader().setReorderingAllowed(false); setSelectionMode(ListSelectionModel.SINGLE_SELECTION); setPreferredScrollableViewportSize(new Dimension(300, getRowHeight() * 10)); getColumnModel().getColumn(0).setPreferredWidth(280); valueColumn.setPreferredWidth(60); } private int askWhetherClearSubdirectories(final VirtualFile parent) { Map<VirtualFile, Charset> mappings = myModel.myCurrentMapping; Map<VirtualFile, Charset> subdirectoryMappings = new THashMap<VirtualFile, Charset>(); for (VirtualFile file : mappings.keySet()) { if (file != null && (parent == null || VfsUtil.isAncestor(parent, file, true))) { subdirectoryMappings.put(file, mappings.get(file)); } } if (subdirectoryMappings.isEmpty()) { return 0; } else { int ret = Messages.showDialog(myProject, "There are encodings specified for the subdirectories. Override them?", "Override Subdirectory Encoding", new String[]{"Override","Do Not Override","Cancel"}, 0, Messages.getWarningIcon()); if (ret == 0) { for (VirtualFile file : subdirectoryMappings.keySet()) { myModel.setValueAt(null, new DefaultMutableTreeNode(file), 1); } } return ret; } } public Map<VirtualFile, Charset> getValues() { return myModel.getValues(); } public TreeTableCellRenderer createTableRenderer(TreeTableModel treeTableModel) { TreeTableCellRenderer tableRenderer = super.createTableRenderer(treeTableModel); UIUtil.setLineStyleAngled(tableRenderer); tableRenderer.setRootVisible(false); tableRenderer.setShowsRootHandles(true); return tableRenderer; } public void reset(final Map<VirtualFile, Charset> mappings) { myModel.reset(mappings); final TreeNode root = (TreeNode)myModel.getRoot(); myModel.nodeChanged(root); getTree().setModel(null); getTree().setModel(myModel); } public void select(final VirtualFile toSelect) { if (toSelect != null) { select(toSelect, (TreeNode)myModel.getRoot()); } } private void select(@NotNull VirtualFile toSelect, final TreeNode root) { for (int i = 0; i < root.getChildCount(); i++) { TreeNode child = root.getChildAt(i); VirtualFile file = ((FileNode)child).getObject(); if (VfsUtil.isAncestor(file, toSelect, false)) { if (file == toSelect) { TreeUtil.selectNode(getTree(), child); getSelectionModel().clearSelection(); addSelectedPath(TreeUtil.getPathFromRoot(child)); TableUtil.scrollSelectionToVisible(this); } else { select(toSelect, child); } return; } } } private static class MyModel extends DefaultTreeModel implements TreeTableModel { private final Map<VirtualFile, Charset> myCurrentMapping = new HashMap<VirtualFile, Charset>(); private final Project myProject; private MyModel(Project project) { super(new ProjectRootNode(project)); myProject = project; myCurrentMapping.putAll(EncodingProjectManager.getInstance(project).getAllMappings()); } private Map<VirtualFile, Charset> getValues() { return new HashMap<VirtualFile, Charset>(myCurrentMapping); } public int getColumnCount() { return 2; } public String getColumnName(final int column) { switch(column) { case 0: return "File/Directory"; case 1: return "Default Encoding"; default: throw new RuntimeException("invalid column " + column); } } public Class getColumnClass(final int column) { switch(column) { case 0: return TreeTableModel.class; case 1: return Charset.class; default: throw new RuntimeException("invalid column " + column); } } public Object getValueAt(final Object node, final int column) { Object userObject = ((DefaultMutableTreeNode)node).getUserObject(); if (userObject instanceof Project) { switch(column) { case 0: return userObject; case 1: return myCurrentMapping.get(null); } } VirtualFile file = (VirtualFile)userObject; switch(column) { case 0: return file; case 1: return myCurrentMapping.get(file); default: throw new RuntimeException("invalid column " + column); } } public boolean isCellEditable(final Object node, final int column) { switch(column) { case 0: return false; case 1: Object userObject = ((DefaultMutableTreeNode)node).getUserObject(); if (userObject instanceof VirtualFile) { VirtualFile file = (VirtualFile)userObject; return ChooseFileEncodingAction.isEnabled(myProject, file); } return true; default: throw new RuntimeException("invalid column " + column); } } public void setValueAt(final Object aValue, final Object node, final int column) { DefaultMutableTreeNode treeNode = (DefaultMutableTreeNode)node; Object userObject = treeNode.getUserObject(); if (userObject instanceof Project) return; VirtualFile file = (VirtualFile)userObject; Charset charset = (Charset)aValue; if (charset == ChooseFileEncodingAction.NO_ENCODING || charset == null) { myCurrentMapping.remove(file); } else { myCurrentMapping.put(file, charset); } fireTreeNodesChanged(this, new Object[]{getRoot()}, null, null); } public void reset(final Map<VirtualFile, Charset> mappings) { myCurrentMapping.clear(); myCurrentMapping.putAll(mappings); ((ProjectRootNode)getRoot()).clearCachedChildren(); } } private static class ProjectRootNode extends ConvenientNode<Project> { public ProjectRootNode(Project project) { super(project); } protected void appendChildrenTo(final Collection<ConvenientNode> children) { Project project = getObject(); VirtualFile[] roots = ProjectRootManager.getInstance(project).getContentRoots(); NextRoot: for (VirtualFile root : roots) { for (VirtualFile candidate : roots) { if (VfsUtil.isAncestor(candidate, root, true)) continue NextRoot; } children.add(new FileNode(root, project)); } } } private abstract static class ConvenientNode<T> extends DefaultMutableTreeNode { private final T myObject; private ConvenientNode(T object) { myObject = object; } public T getObject() { return myObject; } protected abstract void appendChildrenTo(final Collection<ConvenientNode> children); public int getChildCount() { init(); return super.getChildCount(); } public TreeNode getChildAt(final int childIndex) { init(); return super.getChildAt(childIndex); } public Enumeration children() { init(); return super.children(); } private void init() { if (getUserObject() == null) { setUserObject(myObject); List<ConvenientNode> children = new ArrayList<ConvenientNode>(); appendChildrenTo(children); Collections.sort(children, new Comparator<ConvenientNode>() { public int compare(final ConvenientNode node1, final ConvenientNode node2) { Object o1 = node1.getObject(); Object o2 = node2.getObject(); if (o1 == o2) return 0; if (o1 instanceof Project) return -1; if (o2 instanceof Project) return 1; VirtualFile file1 = (VirtualFile)o1; VirtualFile file2 = (VirtualFile)o2; if (file1.isDirectory() != file2.isDirectory()) { return file1.isDirectory() ? -1 : 1; } return file1.getName().compareTo(file2.getName()); } }); int i=0; for (ConvenientNode child : children) { insert(child, i++); } } } public void clearCachedChildren() { if (children != null) { for (Object child : children) { ConvenientNode<T> node = (ConvenientNode<T>)child; node.clearCachedChildren(); } } removeAllChildren(); setUserObject(null); } } private static class FileNode extends ConvenientNode<VirtualFile> { private final Project myProject; private FileNode(@NotNull VirtualFile file, final Project project) { super(file); myProject = project; } protected void appendChildrenTo(final Collection<ConvenientNode> children) { VirtualFile[] childrenf = getObject().getChildren(); ProjectFileIndex fileIndex = ProjectRootManager.getInstance(myProject).getFileIndex(); for (VirtualFile child : childrenf) { if (fileIndex.isInContent(child)) { children.add(new FileNode(child, myProject)); } } } } }
IDEADEV-24088
source/com/intellij/openapi/vfs/encoding/FileTreeTable.java
IDEADEV-24088
<ide><path>ource/com/intellij/openapi/vfs/encoding/FileTreeTable.java <ide> import com.intellij.openapi.ui.Messages; <ide> import com.intellij.openapi.vfs.VfsUtil; <ide> import com.intellij.openapi.vfs.VirtualFile; <add>import com.intellij.openapi.util.Pair; <add>import com.intellij.openapi.fileEditor.impl.LoadTextUtil; <ide> import com.intellij.ui.TableUtil; <ide> import com.intellij.util.IconUtil; <ide> import com.intellij.util.Icons; <ide> final boolean isSelected, final boolean hasFocus, final int row, final int column) { <ide> super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column); <ide> Charset t = (Charset)value; <add> Object userObject = table.getModel().getValueAt(row, 0); <add> VirtualFile file = userObject instanceof VirtualFile ? (VirtualFile)userObject : null; <add> Pair<String,Boolean> pair = ChangeEncodingUpdateGroup.update(myProject, file); <add> boolean enabled = file == null || pair.getSecond(); <ide> if (t != null) { <ide> setText(t.displayName()); <ide> } <ide> else { <del> Object userObject = table.getModel().getValueAt(row, 0); <del> if (userObject instanceof VirtualFile) { <del> VirtualFile file = (VirtualFile)userObject; <add> if (file != null) { <ide> Charset charset = ChooseFileEncodingAction.encodingFromContent(myProject, file); <del> boolean enabled = ChooseFileEncodingAction.isEnabled(myProject, file); <ide> if (charset != null) { <ide> setText(charset.displayName()); <ide> } <del> else if (!enabled) { <add> else if (LoadTextUtil.utfCharsetWasDetectedFromBytes(file)) { <add> setText(file.getCharset().displayName()); <add> } <add> else if (!ChooseFileEncodingAction.isEnabled(myProject, file)) { <ide> setText("N/A"); <ide> } <del> setEnabled(enabled); <del> return this; <ide> } <ide> } <del> setEnabled(true); <add> setEnabled(enabled); <ide> return this; <ide> } <ide> }); <ide> Object userObject = ((DefaultMutableTreeNode)node).getUserObject(); <ide> if (userObject instanceof VirtualFile) { <ide> VirtualFile file = (VirtualFile)userObject; <del> return ChooseFileEncodingAction.isEnabled(myProject, file); <add> Pair<String,Boolean> pair = ChangeEncodingUpdateGroup.update(myProject, file); <add> return pair.getSecond(); <ide> } <ide> return true; <ide> default: throw new RuntimeException("invalid column " + column);
Java
apache-2.0
23e26edcca61e42e7ed938fda0306887e74c4ece
0
skittlesdev/kubrick
package com.github.skittlesdev.kubrick; import android.app.FragmentTransaction; import android.os.Bundle; import android.support.v4.widget.DrawerLayout; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.Toolbar; import android.text.TextUtils; import android.util.Log; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.widget.Button; import android.widget.ImageView; import android.widget.TextView; import com.bumptech.glide.Glide; import com.github.skittlesdev.kubrick.events.LoginEvent; import com.github.skittlesdev.kubrick.events.LogoutEvent; import com.github.skittlesdev.kubrick.ui.fragments.FavoritesOverviewFragment; import com.github.skittlesdev.kubrick.ui.menus.DrawerMenu; import com.github.skittlesdev.kubrick.ui.menus.ToolbarMenu; import com.github.skittlesdev.kubrick.utils.ProfileElement; import com.parse.*; import com.parse.ParseUser; import jp.wasabeef.glide.transformations.CropCircleTransformation; public class ProfileActivity extends AppCompatActivity implements View.OnClickListener { private ParseUser user; private boolean followed = false; public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_profile); this.setSupportActionBar((Toolbar) this.findViewById(R.id.toolBar)); getSupportActionBar().setDisplayHomeAsUpEnabled(true); new DrawerMenu(this, (DrawerLayout) findViewById(R.id.homeDrawerLayout), (RecyclerView) findViewById(R.id.homeRecyclerView)).draw(); KubrickApplication.getEventBus().register(this); final Button toggle = (Button) findViewById(R.id.followToggle); toggle.setOnClickListener(this); } @Override public void onStart() { super.onStart(); ParseUser.getQuery().getInBackground(getIntent().getStringExtra("user_id"), new GetCallback<ParseUser>() { @Override public void done(ParseUser user, ParseException e) { buildProfile(user); setUser(user); getFollowStatus(); FavoritesOverviewFragment movieFavorites = new FavoritesOverviewFragment(); Bundle movieFavoritesArgs = new Bundle(); movieFavoritesArgs.putString("user_id", user.getObjectId()); movieFavoritesArgs.putString("MEDIA_TYPE", "movie"); movieFavorites.setArguments(movieFavoritesArgs); FavoritesOverviewFragment seriesFavorites = new FavoritesOverviewFragment(); Bundle seriesFavoritesArgs = new Bundle(); seriesFavoritesArgs.putString("user_id", user.getObjectId()); seriesFavoritesArgs.putString("MEDIA_TYPE", "tv"); seriesFavorites.setArguments(seriesFavoritesArgs); FragmentTransaction transaction = getFragmentManager().beginTransaction(); transaction.add(R.id.fragment_movies, movieFavorites, "movies"); transaction.add(R.id.fragment_series, seriesFavorites, "series"); transaction.commit(); } }); } private void buildProfile(ParseUser user) { ProfileElement profile = new ProfileElement(user); TextView name = (TextView) findViewById(R.id.name); ImageView image = (ImageView) findViewById(R.id.circleView); name.setText(profile.getName()); if (!TextUtils.isEmpty(profile.getAvatarUrl())) { Glide.with(KubrickApplication.getContext()) .load(profile.getAvatarUrl()) .placeholder(R.drawable.poster_default_placeholder) .error(R.drawable.poster_default_error) .bitmapTransform(new CropCircleTransformation(KubrickApplication.getContext())) .into(image); } } @Override public boolean onCreateOptionsMenu(Menu menu) { MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.menu_home, menu); new ToolbarMenu(this).filterItems(menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { new ToolbarMenu(this).itemSelected(item); return super.onOptionsItemSelected(item); } public void getFollowStatus() { if (ParseUser.getCurrentUser() == null) { return; } ParseQuery<ParseObject> query = ParseQuery.getQuery("Follow"); query.whereEqualTo("user", ParseUser.getCurrentUser()); query.whereEqualTo("other_user", this.user); query.getFirstInBackground(new GetCallback<ParseObject>() { @Override public void done(ParseObject object, ParseException e) { if (object != null) { setFollowed(true); } else { setFollowed(false); } } }); } public void setUser(ParseUser user) { this.user = user; } public void setFollowed(boolean followed) { this.followed = followed; final Button toggle = (Button) findViewById(R.id.followToggle); if (!this.followed) { toggle.setText("FOLLOW"); } else { toggle.setText("UNFOLLOW"); } toggle.setVisibility(View.VISIBLE); } @Override public void onClick(View v) { if (!this.followed) { ParseObject follow = new ParseObject("Follow"); follow.put("user", ParseUser.getCurrentUser()); follow.put("other_user", this.user); follow.saveInBackground(new SaveCallback() { @Override public void done(ParseException e) { if (e == null) { setFollowed(true); } } }); } else { ParseQuery<ParseObject> query = ParseQuery.getQuery("Follow"); query.whereEqualTo("user", ParseUser.getCurrentUser()); query.whereEqualTo("other_user", this.user); query.getFirstInBackground(new GetCallback<ParseObject>() { @Override public void done(ParseObject object, ParseException e) { if (e == null) { object.deleteInBackground(new DeleteCallback() { @Override public void done(ParseException e) { if (e == null) { setFollowed(false); } } }); } } }); } } public void onEvent(LoginEvent e) { getFollowStatus(); } public void onEvent(LogoutEvent e) { final Button toggle = (Button) findViewById(R.id.followToggle); toggle.setVisibility(View.INVISIBLE); } }
app/src/main/java/com/github/skittlesdev/kubrick/ProfileActivity.java
package com.github.skittlesdev.kubrick; import android.app.FragmentTransaction; import android.os.Bundle; import android.support.v4.widget.DrawerLayout; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.Toolbar; import android.text.TextUtils; import android.util.Log; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.widget.Button; import android.widget.ImageView; import android.widget.TextView; import com.bumptech.glide.Glide; import com.github.skittlesdev.kubrick.ui.fragments.FavoritesOverviewFragment; import com.github.skittlesdev.kubrick.ui.menus.DrawerMenu; import com.github.skittlesdev.kubrick.ui.menus.ToolbarMenu; import com.github.skittlesdev.kubrick.utils.ProfileElement; import com.parse.*; import com.parse.ParseUser; import jp.wasabeef.glide.transformations.CropCircleTransformation; public class ProfileActivity extends AppCompatActivity implements View.OnClickListener { private ParseUser user; private boolean followed = false; public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_profile); this.setSupportActionBar((Toolbar) this.findViewById(R.id.toolBar)); getSupportActionBar().setDisplayHomeAsUpEnabled(true); new DrawerMenu(this, (DrawerLayout) findViewById(R.id.homeDrawerLayout), (RecyclerView) findViewById(R.id.homeRecyclerView)).draw(); final Button toggle = (Button) findViewById(R.id.followToggle); toggle.setOnClickListener(this); } @Override public void onStart() { super.onStart(); ParseUser.getQuery().getInBackground(getIntent().getStringExtra("user_id"), new GetCallback<ParseUser>() { @Override public void done(ParseUser user, ParseException e) { buildProfile(user); setUser(user); getFollowStatus(); FavoritesOverviewFragment movieFavorites = new FavoritesOverviewFragment(); Bundle movieFavoritesArgs = new Bundle(); movieFavoritesArgs.putString("user_id", user.getObjectId()); movieFavoritesArgs.putString("MEDIA_TYPE", "movie"); movieFavorites.setArguments(movieFavoritesArgs); FavoritesOverviewFragment seriesFavorites = new FavoritesOverviewFragment(); Bundle seriesFavoritesArgs = new Bundle(); seriesFavoritesArgs.putString("user_id", user.getObjectId()); seriesFavoritesArgs.putString("MEDIA_TYPE", "tv"); seriesFavorites.setArguments(seriesFavoritesArgs); FragmentTransaction transaction = getFragmentManager().beginTransaction(); transaction.add(R.id.fragment_movies, movieFavorites, "movies"); transaction.add(R.id.fragment_series, seriesFavorites, "series"); transaction.commit(); } }); } private void buildProfile(ParseUser user) { ProfileElement profile = new ProfileElement(user); TextView name = (TextView) findViewById(R.id.name); ImageView image = (ImageView) findViewById(R.id.circleView); name.setText(profile.getName()); if (!TextUtils.isEmpty(profile.getAvatarUrl())) { Glide.with(KubrickApplication.getContext()) .load(profile.getAvatarUrl()) .placeholder(R.drawable.poster_default_placeholder) .error(R.drawable.poster_default_error) .bitmapTransform(new CropCircleTransformation(KubrickApplication.getContext())) .into(image); } } @Override public boolean onCreateOptionsMenu(Menu menu) { MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.menu_home, menu); new ToolbarMenu(this).filterItems(menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { new ToolbarMenu(this).itemSelected(item); return super.onOptionsItemSelected(item); } public void getFollowStatus() { ParseQuery<ParseObject> query = ParseQuery.getQuery("Follow"); query.whereEqualTo("user", ParseUser.getCurrentUser()); query.whereEqualTo("other_user", this.user); query.getFirstInBackground(new GetCallback<ParseObject>() { @Override public void done(ParseObject object, ParseException e) { if (object != null) { setFollowed(true); } else { setFollowed(false); } } }); } public void setUser(ParseUser user) { this.user = user; } public void setFollowed(boolean followed) { this.followed = followed; final Button toggle = (Button) findViewById(R.id.followToggle); if (!this.followed) { toggle.setText("FOLLOW"); } else { toggle.setText("UNFOLLOW"); } toggle.setVisibility(View.VISIBLE); } @Override public void onClick(View v) { if (!this.followed) { ParseObject follow = new ParseObject("Follow"); follow.put("user", ParseUser.getCurrentUser()); follow.put("other_user", this.user); follow.saveInBackground(new SaveCallback() { @Override public void done(ParseException e) { if (e == null) { setFollowed(true); } } }); } else { ParseQuery<ParseObject> query = ParseQuery.getQuery("Follow"); query.whereEqualTo("user", ParseUser.getCurrentUser()); query.whereEqualTo("other_user", this.user); query.getFirstInBackground(new GetCallback<ParseObject>() { @Override public void done(ParseObject object, ParseException e) { if (e == null) { object.deleteInBackground(new DeleteCallback() { @Override public void done(ParseException e) { if (e == null) { setFollowed(false); } } }); } } }); } } }
Login / logout events handling in ProfileActivity
app/src/main/java/com/github/skittlesdev/kubrick/ProfileActivity.java
Login / logout events handling in ProfileActivity
<ide><path>pp/src/main/java/com/github/skittlesdev/kubrick/ProfileActivity.java <ide> import android.widget.ImageView; <ide> import android.widget.TextView; <ide> import com.bumptech.glide.Glide; <add>import com.github.skittlesdev.kubrick.events.LoginEvent; <add>import com.github.skittlesdev.kubrick.events.LogoutEvent; <ide> import com.github.skittlesdev.kubrick.ui.fragments.FavoritesOverviewFragment; <ide> import com.github.skittlesdev.kubrick.ui.menus.DrawerMenu; <ide> import com.github.skittlesdev.kubrick.ui.menus.ToolbarMenu; <ide> this.setSupportActionBar((Toolbar) this.findViewById(R.id.toolBar)); <ide> getSupportActionBar().setDisplayHomeAsUpEnabled(true); <ide> new DrawerMenu(this, (DrawerLayout) findViewById(R.id.homeDrawerLayout), (RecyclerView) findViewById(R.id.homeRecyclerView)).draw(); <add> <add> KubrickApplication.getEventBus().register(this); <ide> <ide> final Button toggle = (Button) findViewById(R.id.followToggle); <ide> toggle.setOnClickListener(this); <ide> } <ide> <ide> public void getFollowStatus() { <add> if (ParseUser.getCurrentUser() == null) { <add> return; <add> } <add> <ide> ParseQuery<ParseObject> query = ParseQuery.getQuery("Follow"); <ide> query.whereEqualTo("user", ParseUser.getCurrentUser()); <ide> query.whereEqualTo("other_user", this.user); <ide> }); <ide> } <ide> } <add> <add> public void onEvent(LoginEvent e) { <add> getFollowStatus(); <add> } <add> <add> public void onEvent(LogoutEvent e) { <add> final Button toggle = (Button) findViewById(R.id.followToggle); <add> toggle.setVisibility(View.INVISIBLE); <add> } <ide> }
Java
mit
776881fb9eede46c6db92f10941308499f7363d3
0
kits-ab/gakusei,kits-ab/gakusei,kits-ab/gakusei
package se.kits.gakusei.content.model; import com.fasterxml.jackson.annotation.JsonManagedReference; import org.hibernate.annotations.Fetch; import org.hibernate.annotations.FetchMode; import org.hibernate.annotations.NotFound; import org.hibernate.annotations.NotFoundAction; import javax.persistence.*; import java.io.Serializable; import java.util.List; @Entity @Table(name = "courses", schema = "contentschema") public class Course implements Serializable { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; @Column(nullable = false, unique = true) private String name; private String description; @ManyToOne private Course parent; @OneToMany(mappedBy = "parent", cascade = CascadeType.ALL, orphanRemoval = true) private List<Course> partCourses; @ManyToMany @JoinTable( name = "prerequisites", joinColumns = @JoinColumn(name = "course_id", referencedColumnName = "id"), inverseJoinColumns = @JoinColumn(name = "prerequisite_id", referencedColumnName = "id")) private List<Course> prerequisites; private int order; @Column(nullable = false, unique = true) private String courseCode; @OneToMany(mappedBy="course", fetch = FetchType.LAZY) @JsonManagedReference @Fetch(value = FetchMode.SUBSELECT) private List<Lesson> lessons; public Course(){ } public Long getId() { return id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public Course getParent() { return parent; } public void setParent(Course parent) { this.parent = parent; } public List<Course> getPartCourses() { return partCourses; } public void setPartCourses(List<Course> partCourses) { this.partCourses = partCourses; } public List<Course> getPrerequisites() { return prerequisites; } public void setPrerequisites(List<Course> prerequisites) { this.prerequisites = prerequisites; } public int getOrder() { return order; } public void setOrder(int order) { this.order = order; } public String getCourseCode() { return courseCode; } public void setCourseCode(String courseCode) { this.courseCode = courseCode; } public List<Lesson> getLessons() { return lessons; } public void setLessons(List<Lesson> lessons) { this.lessons = lessons; } }
src/main/java/se/kits/gakusei/content/model/Course.java
package se.kits.gakusei.content.model; import javax.persistence.*; import java.io.Serializable; import java.util.List; @Entity @Table(name = "courses", schema = "contentschema") public class Course implements Serializable { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; @Column(nullable = false, unique = true) private String name; @ManyToOne private Course parent; @ManyToMany @JoinTable( name = "prerequisites", joinColumns = @JoinColumn(name = "course_id", referencedColumnName = "id"), inverseJoinColumns = @JoinColumn(name = "prerequisite_id", referencedColumnName = "id")) private List<Course> prerequisites; private String description; private int order; @Column(nullable = false, unique = true) private String courseCode; @OneToMany private List<Lesson> lessons; public Course(){ } public Long getId() { return id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public Course getParent() { return parent; } public void setParent(Course parent) { this.parent = parent; } public int getOrder() { return order; } public void setOrder(int order) { this.order = order; } public String getCourseCode() { return courseCode; } public void setCourseCode(String courseCode) { this.courseCode = courseCode; } public List<Course> getPrerequisites() { return prerequisites; } public void setPrerequisites(List<Course> prerequisites) { this.prerequisites = prerequisites; } public List<Lesson> getLessons() { return lessons; } public void setLessons(List<Lesson> lessons) { this.lessons = lessons; } }
changed course-part course relationship
src/main/java/se/kits/gakusei/content/model/Course.java
changed course-part course relationship
<ide><path>rc/main/java/se/kits/gakusei/content/model/Course.java <ide> package se.kits.gakusei.content.model; <add> <add>import com.fasterxml.jackson.annotation.JsonManagedReference; <add>import org.hibernate.annotations.Fetch; <add>import org.hibernate.annotations.FetchMode; <add>import org.hibernate.annotations.NotFound; <add>import org.hibernate.annotations.NotFoundAction; <ide> <ide> import javax.persistence.*; <ide> import java.io.Serializable; <ide> @Column(nullable = false, unique = true) <ide> private String name; <ide> <add> private String description; <add> <ide> @ManyToOne <ide> private Course parent; <add> <add> @OneToMany(mappedBy = "parent", cascade = CascadeType.ALL, orphanRemoval = true) <add> private List<Course> partCourses; <ide> <ide> @ManyToMany <ide> @JoinTable( <ide> inverseJoinColumns = @JoinColumn(name = "prerequisite_id", referencedColumnName = "id")) <ide> private List<Course> prerequisites; <ide> <del> private String description; <del> <ide> private int order; <ide> <ide> @Column(nullable = false, unique = true) <ide> private String courseCode; <ide> <del> @OneToMany <add> @OneToMany(mappedBy="course", fetch = FetchType.LAZY) <add> @JsonManagedReference <add> @Fetch(value = FetchMode.SUBSELECT) <ide> private List<Lesson> lessons; <ide> <ide> public Course(){ <ide> this.parent = parent; <ide> } <ide> <add> public List<Course> getPartCourses() { <add> return partCourses; <add> } <add> <add> public void setPartCourses(List<Course> partCourses) { <add> this.partCourses = partCourses; <add> } <add> <add> public List<Course> getPrerequisites() { <add> return prerequisites; <add> } <add> <add> public void setPrerequisites(List<Course> prerequisites) { <add> this.prerequisites = prerequisites; <add> } <add> <ide> public int getOrder() { <ide> return order; <ide> } <ide> this.courseCode = courseCode; <ide> } <ide> <del> public List<Course> getPrerequisites() { <del> return prerequisites; <del> } <del> <del> public void setPrerequisites(List<Course> prerequisites) { <del> this.prerequisites = prerequisites; <del> } <del> <ide> public List<Lesson> getLessons() { <ide> return lessons; <ide> }
JavaScript
mit
cf5753375303302be51e0be2303ed226daa9dacc
0
jordandh/sprout,jordandh/sprout
define(["module", "sprout/pubsub", "sprout/util", "sprout/dom", "sprout/env"], function (module, pubsub, _, $, env) { "use strict"; (function () { 'use strict'; var DEFAULT_MAX_DEPTH = 6; var DEFAULT_ARRAY_MAX_LENGTH = 50; var seen; // Same variable used for all stringifications var iterator; // either forEachEnumerableOwnProperty, forEachEnumerableProperty or forEachProperty // iterates on enumerable own properties (default behavior) var forEachEnumerableOwnProperty = function(obj, callback) { for (var k in obj) { if (Object.prototype.hasOwnProperty.call(obj, k)) callback(k); } }; // iterates on enumerable properties var forEachEnumerableProperty = function(obj, callback) { for (var k in obj) callback(k); }; // iterates on properties, even non enumerable and inherited ones // This is dangerous var forEachProperty = function(obj, callback, excluded) { if (obj==null) return; excluded = excluded || {}; Object.getOwnPropertyNames(obj).forEach(function(k){ if (!excluded[k]) { callback(k); excluded[k] = true; } }); forEachProperty(Object.getPrototypeOf(obj), callback, excluded); }; Date.prototype.toPrunedJSON = Date.prototype.toJSON; String.prototype.toPrunedJSON = String.prototype.toJSON; var cx = /[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g, escapable = /[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g, meta = { // table of character substitutions '\b': '\\b', '\t': '\\t', '\n': '\\n', '\f': '\\f', '\r': '\\r', '"' : '\\"', '\\': '\\\\' }; function quote(string) { escapable.lastIndex = 0; return escapable.test(string) ? '"' + string.replace(escapable, function (a) { var c = meta[a]; return typeof c === 'string' ? c : '\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4); }) + '"' : '"' + string + '"'; } function str(key, holder, depthDecr, arrayMaxLength) { var i, k, v, length, partial, value = holder[key]; if (value && typeof value === 'object' && typeof value.toPrunedJSON === 'function') { value = value.toPrunedJSON(key); } switch (typeof value) { case 'string': return quote(value); case 'number': return isFinite(value) ? String(value) : 'null'; case 'boolean': case 'null': return String(value); case 'object': if (!value) { return 'null'; } if (depthDecr<=0 || seen.indexOf(value)!==-1) { return '"-pruned-"'; } seen.push(value); partial = []; if (Object.prototype.toString.apply(value) === '[object Array]') { length = Math.min(value.length, arrayMaxLength); for (i = 0; i < length; i += 1) { partial[i] = str(i, value, depthDecr-1, arrayMaxLength) || 'null'; } return '[' + partial.join(',') + ']'; } iterator(value, function(k) { try { v = str(k, value, depthDecr-1, arrayMaxLength); if (v) partial.push(quote(k) + ':' + v); } catch (e) { // this try/catch due to forbidden accessors on some objects } }); return '{' + partial.join(',') + '}'; } } JSON.prune = function (value, depthDecr, arrayMaxLength) { if (typeof depthDecr == "object") { var options = depthDecr; depthDecr = options.depthDecr; arrayMaxLength = options.arrayMaxLength; iterator = options.iterator || forEachEnumerableOwnProperty; if (options.allProperties) iterator = forEachProperty; else if (options.inheritedProperties) iterator = forEachEnumerableProperty } else { iterator = forEachEnumerableOwnProperty; } seen = []; depthDecr = depthDecr || DEFAULT_MAX_DEPTH; arrayMaxLength = arrayMaxLength || DEFAULT_ARRAY_MAX_LENGTH; return str('', {'': value}, depthDecr, arrayMaxLength); }; JSON.prune.log = function() { console.log.apply(console, Array.prototype.slice.call(arguments).map(function(v){return JSON.parse(JSON.prune(v))})); } JSON.prune.forEachProperty = forEachProperty; // you might want to also assign it to Object.forEachProperty }()); /* * localStorage error store * Keeps an error from being reported more than once a day. */ var localStorageErrorStore = { /* * Private helper functions */ LocalStorageKey: 'sprout-errors', LocalStorageErrorSetVersionKey: '-version', getErrorKey: function (error) { var key, ex; if (_.isArray(error.exceptions) && error.exceptions.length > 0) { ex = error.exceptions[0]; key = ex.toString(); } return key || undefined; }, getErrorStore: function () { // Grab the error data store from local storage var errorStore = localStorage[localStorageErrorStore.LocalStorageKey]; // If there is a data store then parse it if (errorStore) { return JSON.parse(errorStore); } return {}; }, getErrorSetVersionKey: function () { return localStorageErrorStore.LocalStorageKey + localStorageErrorStore.LocalStorageErrorSetVersionKey; }, getErrorSetVersion: function () { var errorSetVersion = localStorage[localStorageErrorStore.getErrorSetVersionKey()]; return _.isUndefined(errorSetVersion) ? null : errorSetVersion; }, setErrorStore: function (errorStore) { localStorage[localStorageErrorStore.LocalStorageKey] = JSON.stringify(errorStore); }, pruneErrorStore: function () { var errorStore = localStorageErrorStore.getErrorStore(), errors; if (_.size(errorStore) > localStorageErrorStore.MaxErrorsInStore) { // Sort the errors by lastReportedAt and grab the set to keep (MaxErrorsInStore size set) errors = _.chain(errorStore).sortBy(function (errorInfo) { return errorInfo.lastReportedAt; }).last(localStorageErrorStore.MaxErrorsInStore).value(); // Start with a fresh error store errorStore = {}; // Put the remaining errors back into the store _.each(errors, function (errorInfo) { errorStore[errorInfo.key] = errorInfo; }); localStorageErrorStore.setErrorStore(errorStore); } }, /* * Public interface */ MaxErrorsInStore: 20, shouldReportError: function (error) { var errorKey = localStorageErrorStore.getErrorKey(error), errorStore, errorInfo, aDayAgo, lastReportedAt; // If this error does not have a key or local storage is not supported if (!errorKey || !env.localStorageEnabled()) { return false; } // Grab the error data store errorStore = localStorageErrorStore.getErrorStore(); // Grab the info for this error errorInfo = errorStore[errorKey]; // If this error was in the data store if (errorInfo) { lastReportedAt = new Date(errorInfo.lastReportedAt); aDayAgo = new Date(); aDayAgo.setDate(aDayAgo.getDate() - 1); // If this error was already reported today if (lastReportedAt > aDayAgo) { return false; } } return true; }, markErrorAsReported: function (error) { var errorKey = localStorageErrorStore.getErrorKey(error), errorStore = localStorageErrorStore.getErrorStore(); errorStore[errorKey] = { key: errorKey, lastReportedAt: new Date().getTime() }; localStorageErrorStore.setErrorStore(errorStore); localStorageErrorStore.pruneErrorStore(); }, clearErrors: function () { localStorageErrorStore.setErrorStore({}); }, setErrorSetVersion: function (newErrorSetVersion) { // Grab the current version of the error set in the store var errorSetVersion = localStorageErrorStore.getErrorSetVersion(); // Update the error set version localStorage[localStorageErrorStore.getErrorSetVersionKey()] = newErrorSetVersion; // If the error set in the store has a different version then clear out the errors if (errorSetVersion != newErrorSetVersion) { // != on purpose localStorageErrorStore.clearErrors(); } } }; var errorModule = { options: _.extend({ reportGlobalErrors: true, reportPubsubErrors: true, reportRequireErrors: true }, module.config().options), requestOptions: _.extend({ url: "/errors", type: "POST", dataType: "json", contentType: "application/json" }, module.config().requestOptions), stringify: function (error) { //return JSON.stringify(decycle(packageError(error)), jsonReplacer); //return cereal.stringify(packageError(error)); //return JSON.stringify(packageError(error), getSerialize(jsonReplacer)); return JSON.prune(packageError(error), { //inheritedProperties: true }); }, errorStore: localStorageErrorStore }; function packageError (error) { var err = { type: error.type, info: {}, navigator: {}, window: {}, exceptions: [] }, $window = $(window), ex, exInfo; // Grab the exception information if (error.exceptions) { for (var i = 0, length = error.exceptions.length; i < length; i += 1) { ex = error.exceptions[i]; if (ex) { exInfo = { name: ex.name, message: ex.message }; if (ex.fileName) { exInfo.fileName = ex.fileName; } if (ex.lineNumber) { exInfo.lineNumber = ex.lineNumber; } if (ex.type) { exInfo.type = ex.type; } if (ex.description) { exInfo.description = ex.description; } if (ex.number) { exInfo.number = ex.number; } if (ex.arguments) { exInfo.arguments = ex.arguments; } if (ex.stack) { exInfo.stack = ex.stack; } if (ex.info) { exInfo.info = ex.info; } err.exceptions.push(exInfo); } } } // Grab the information related to the error if (error.info) { for (var name in error.info) { if (error.info.hasOwnProperty(name)) { err.info[name] = error.info[name]; } } } // Grab info about the client's environment err.navigator.userAgent = navigator.userAgent; err.navigator.language = navigator.language; err.window.location = window.location.toString(); err.window.viewport = $window.width() + 'x' + $window.height(); return err; } function submitError (error) { try { if (error && errorModule.errorStore.shouldReportError(error)) { $.ajax($.extend({}, errorModule.requestOptions, { data: errorModule.stringify(error) })); errorModule.errorStore.markErrorAsReported(error); } } catch (ex) { /* empty */ } } function createGlobalError (message, fileName, lineNumber) { return { message: message, fileName: fileName, lineNumber: lineNumber, toString: function () { return this.message; } }; } window.onerror = function (message, fileName, lineNumber) { if (errorModule.options.reportGlobalErrors) { submitError({ type: "global", exceptions: [ createGlobalError(message, fileName, lineNumber) ] }); } }; pubsub.subscribe("error", function (e) { if (errorModule.options.reportPubsubErrors) { submitError({ type: "pubsub", exceptions: e.info.exception ? [e.info.exception] : [], info: e.info.info }); } }); requirejs.onError = function (error) { if (errorModule.options.reportRequireErrors) { submitError({ type: "requirejs", exceptions: [error, error.originalError], info: { moduleName: error.moduleName, moduleTree: error.moduleTree, requireType: error.requireType, requireModules: error.requireModules } }); } }; return errorModule; });
src/error.js
define(["module", "sprout/pubsub", "sprout/util", "sprout/dom", "sprout/env"], function (module, pubsub, _, $, env) { "use strict"; (function () { 'use strict'; var DEFAULT_MAX_DEPTH = 6; var DEFAULT_ARRAY_MAX_LENGTH = 50; var seen; // Same variable used for all stringifications var iterator; // either forEachEnumerableOwnProperty, forEachEnumerableProperty or forEachProperty // iterates on enumerable own properties (default behavior) var forEachEnumerableOwnProperty = function(obj, callback) { for (var k in obj) { if (Object.prototype.hasOwnProperty.call(obj, k)) callback(k); } }; // iterates on enumerable properties var forEachEnumerableProperty = function(obj, callback) { for (var k in obj) callback(k); }; // iterates on properties, even non enumerable and inherited ones // This is dangerous var forEachProperty = function(obj, callback, excluded) { if (obj==null) return; excluded = excluded || {}; Object.getOwnPropertyNames(obj).forEach(function(k){ if (!excluded[k]) { callback(k); excluded[k] = true; } }); forEachProperty(Object.getPrototypeOf(obj), callback, excluded); }; Date.prototype.toPrunedJSON = Date.prototype.toJSON; String.prototype.toPrunedJSON = String.prototype.toJSON; var cx = /[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g, escapable = /[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g, meta = { // table of character substitutions '\b': '\\b', '\t': '\\t', '\n': '\\n', '\f': '\\f', '\r': '\\r', '"' : '\\"', '\\': '\\\\' }; function quote(string) { escapable.lastIndex = 0; return escapable.test(string) ? '"' + string.replace(escapable, function (a) { var c = meta[a]; return typeof c === 'string' ? c : '\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4); }) + '"' : '"' + string + '"'; } function str(key, holder, depthDecr, arrayMaxLength) { var i, k, v, length, partial, value = holder[key]; if (value && typeof value === 'object' && typeof value.toPrunedJSON === 'function') { value = value.toPrunedJSON(key); } switch (typeof value) { case 'string': return quote(value); case 'number': return isFinite(value) ? String(value) : 'null'; case 'boolean': case 'null': return String(value); case 'object': if (!value) { return 'null'; } if (depthDecr<=0 || seen.indexOf(value)!==-1) { return '"-pruned-"'; } seen.push(value); partial = []; if (Object.prototype.toString.apply(value) === '[object Array]') { length = Math.min(value.length, arrayMaxLength); for (i = 0; i < length; i += 1) { partial[i] = str(i, value, depthDecr-1, arrayMaxLength) || 'null'; } return '[' + partial.join(',') + ']'; } iterator(value, function(k) { try { v = str(k, value, depthDecr-1, arrayMaxLength); if (v) partial.push(quote(k) + ':' + v); } catch (e) { // this try/catch due to forbidden accessors on some objects } }); return '{' + partial.join(',') + '}'; } } JSON.prune = function (value, depthDecr, arrayMaxLength) { if (typeof depthDecr == "object") { var options = depthDecr; depthDecr = options.depthDecr; arrayMaxLength = options.arrayMaxLength; iterator = options.iterator || forEachEnumerableOwnProperty; if (options.allProperties) iterator = forEachProperty; else if (options.inheritedProperties) iterator = forEachEnumerableProperty } else { iterator = forEachEnumerableOwnProperty; } seen = []; depthDecr = depthDecr || DEFAULT_MAX_DEPTH; arrayMaxLength = arrayMaxLength || DEFAULT_ARRAY_MAX_LENGTH; return str('', {'': value}, depthDecr, arrayMaxLength); }; JSON.prune.log = function() { console.log.apply(console, Array.prototype.slice.call(arguments).map(function(v){return JSON.parse(JSON.prune(v))})); } JSON.prune.forEachProperty = forEachProperty; // you might want to also assign it to Object.forEachProperty }()); /* * localStorage error store * Keeps an error from being reported more than once a day. */ var localStorageErrorStore = { /* * Private helper functions */ LocalStorageKey: 'sprout-errors', getErrorKey: function (error) { var key, ex; if (_.isArray(error.exceptions) && error.exceptions.length > 0) { ex = error.exceptions[0]; key = ex.toString(); } return key || undefined; }, getErrorStore: function () { // Grab the error data store from local storage var errorStore = localStorage[localStorageErrorStore.LocalStorageKey]; // If there is a data store then parse it if (errorStore) { return JSON.parse(errorStore); } return {}; }, setErrorStore: function (errorStore) { localStorage[localStorageErrorStore.LocalStorageKey] = JSON.stringify(errorStore); }, pruneErrorStore: function () { var errorStore = localStorageErrorStore.getErrorStore(), errors; if (_.size(errorStore) > localStorageErrorStore.MaxErrorsInStore) { // Sort the errors by lastReportedAt and grab the set to keep (MaxErrorsInStore size set) errors = _.chain(errorStore).sortBy(function (errorInfo) { return errorInfo.lastReportedAt; }).last(localStorageErrorStore.MaxErrorsInStore).value(); // Start with a fresh error store errorStore = {}; // Put the remaining errors back into the store _.each(errors, function (errorInfo) { errorStore[errorInfo.key] = errorInfo; }); localStorageErrorStore.setErrorStore(errorStore); } }, /* * Public interface */ MaxErrorsInStore: 20, shouldReportError: function (error) { var errorKey = localStorageErrorStore.getErrorKey(error), errorStore, errorInfo, aDayAgo, lastReportedAt; // If this error does not have a key or local storage is not supported if (!errorKey || !env.localStorageEnabled()) { return false; } // Grab the error data store errorStore = localStorageErrorStore.getErrorStore(); // Grab the info for this error errorInfo = errorStore[errorKey]; // If this error was in the data store if (errorInfo) { lastReportedAt = new Date(errorInfo.lastReportedAt); aDayAgo = new Date(); aDayAgo.setDate(aDayAgo.getDate() - 1); // If this error was already reported today if (lastReportedAt > aDayAgo) { return false; } } return true; }, markErrorAsReported: function (error) { var errorKey = localStorageErrorStore.getErrorKey(error), errorStore = localStorageErrorStore.getErrorStore(); errorStore[errorKey] = { key: errorKey, lastReportedAt: new Date().getTime() }; localStorageErrorStore.setErrorStore(errorStore); localStorageErrorStore.pruneErrorStore(); } }; var errorModule = { options: _.extend({ reportGlobalErrors: true, reportPubsubErrors: true, reportRequireErrors: true }, module.config().options), requestOptions: _.extend({ url: "/errors", type: "POST", dataType: "json", contentType: "application/json" }, module.config().requestOptions), stringify: function (error) { //return JSON.stringify(decycle(packageError(error)), jsonReplacer); //return cereal.stringify(packageError(error)); //return JSON.stringify(packageError(error), getSerialize(jsonReplacer)); return JSON.prune(packageError(error), { //inheritedProperties: true }); }, errorStore: localStorageErrorStore }; function packageError (error) { var err = { type: error.type, info: {}, navigator: {}, window: {}, exceptions: [] }, $window = $(window), ex, exInfo; // Grab the exception information if (error.exceptions) { for (var i = 0, length = error.exceptions.length; i < length; i += 1) { ex = error.exceptions[i]; if (ex) { exInfo = { name: ex.name, message: ex.message }; if (ex.fileName) { exInfo.fileName = ex.fileName; } if (ex.lineNumber) { exInfo.lineNumber = ex.lineNumber; } if (ex.type) { exInfo.type = ex.type; } if (ex.description) { exInfo.description = ex.description; } if (ex.number) { exInfo.number = ex.number; } if (ex.arguments) { exInfo.arguments = ex.arguments; } if (ex.stack) { exInfo.stack = ex.stack; } if (ex.info) { exInfo.info = ex.info; } err.exceptions.push(exInfo); } } } // Grab the information related to the error if (error.info) { for (var name in error.info) { if (error.info.hasOwnProperty(name)) { err.info[name] = error.info[name]; } } } // Grab info about the client's environment err.navigator.userAgent = navigator.userAgent; err.navigator.language = navigator.language; err.window.location = window.location.toString(); err.window.viewport = $window.width() + 'x' + $window.height(); return err; } function submitError (error) { try { if (error && errorModule.errorStore.shouldReportError(error)) { $.ajax($.extend({}, errorModule.requestOptions, { data: errorModule.stringify(error) })); errorModule.errorStore.markErrorAsReported(error); } } catch (ex) { /* empty */ } } function createGlobalError (message, fileName, lineNumber) { return { message: message, fileName: fileName, lineNumber: lineNumber, toString: function () { return this.message; } }; } window.onerror = function (message, fileName, lineNumber) { if (errorModule.options.reportGlobalErrors) { submitError({ type: "global", exceptions: [ createGlobalError(message, fileName, lineNumber) ] }); } }; pubsub.subscribe("error", function (e) { if (errorModule.options.reportPubsubErrors) { submitError({ type: "pubsub", exceptions: e.info.exception ? [e.info.exception] : [], info: e.info.info }); } }); requirejs.onError = function (error) { if (errorModule.options.reportRequireErrors) { submitError({ type: "requirejs", exceptions: [error, error.originalError], info: { moduleName: error.moduleName, moduleTree: error.moduleTree, requireType: error.requireType, requireModules: error.requireModules } }); } }; return errorModule; });
Added versioning to the error module. A set of stored errors can have a version associated with it. If the error set version changes then the error store is cleared.
src/error.js
Added versioning to the error module. A set of stored errors can have a version associated with it. If the error set version changes then the error store is cleared.
<ide><path>rc/error.js <ide> * Private helper functions <ide> */ <ide> LocalStorageKey: 'sprout-errors', <add> LocalStorageErrorSetVersionKey: '-version', <ide> <ide> getErrorKey: function (error) <ide> { <ide> } <ide> <ide> return {}; <add> }, <add> <add> getErrorSetVersionKey: function () <add> { <add> return localStorageErrorStore.LocalStorageKey + localStorageErrorStore.LocalStorageErrorSetVersionKey; <add> }, <add> <add> getErrorSetVersion: function () <add> { <add> var errorSetVersion = localStorage[localStorageErrorStore.getErrorSetVersionKey()]; <add> <add> return _.isUndefined(errorSetVersion) ? null : errorSetVersion; <ide> }, <ide> <ide> setErrorStore: function (errorStore) <ide> <ide> localStorageErrorStore.setErrorStore(errorStore); <ide> localStorageErrorStore.pruneErrorStore(); <add> }, <add> <add> clearErrors: function () <add> { <add> localStorageErrorStore.setErrorStore({}); <add> }, <add> <add> setErrorSetVersion: function (newErrorSetVersion) <add> { <add> // Grab the current version of the error set in the store <add> var errorSetVersion = localStorageErrorStore.getErrorSetVersion(); <add> <add> // Update the error set version <add> localStorage[localStorageErrorStore.getErrorSetVersionKey()] = newErrorSetVersion; <add> <add> // If the error set in the store has a different version then clear out the errors <add> if (errorSetVersion != newErrorSetVersion) { // != on purpose <add> localStorageErrorStore.clearErrors(); <add> } <ide> } <ide> }; <ide>
Java
apache-2.0
4ab77acf4af2150b1aa6e079264726f6a620da15
0
petteyg/intellij-community,idea4bsd/idea4bsd,ernestp/consulo,da1z/intellij-community,alphafoobar/intellij-community,ibinti/intellij-community,TangHao1987/intellij-community,idea4bsd/idea4bsd,kdwink/intellij-community,xfournet/intellij-community,joewalnes/idea-community,kool79/intellij-community,ahb0327/intellij-community,jagguli/intellij-community,Distrotech/intellij-community,jagguli/intellij-community,blademainer/intellij-community,fitermay/intellij-community,semonte/intellij-community,ahb0327/intellij-community,salguarnieri/intellij-community,da1z/intellij-community,retomerz/intellij-community,da1z/intellij-community,MER-GROUP/intellij-community,clumsy/intellij-community,nicolargo/intellij-community,alphafoobar/intellij-community,blademainer/intellij-community,izonder/intellij-community,suncycheng/intellij-community,jagguli/intellij-community,ivan-fedorov/intellij-community,TangHao1987/intellij-community,SerCeMan/intellij-community,orekyuu/intellij-community,joewalnes/idea-community,tmpgit/intellij-community,akosyakov/intellij-community,michaelgallacher/intellij-community,Lekanich/intellij-community,clumsy/intellij-community,lucafavatella/intellij-community,ernestp/consulo,MER-GROUP/intellij-community,pwoodworth/intellij-community,michaelgallacher/intellij-community,semonte/intellij-community,apixandru/intellij-community,ibinti/intellij-community,adedayo/intellij-community,alphafoobar/intellij-community,amith01994/intellij-community,dslomov/intellij-community,dslomov/intellij-community,youdonghai/intellij-community,clumsy/intellij-community,tmpgit/intellij-community,diorcety/intellij-community,fitermay/intellij-community,tmpgit/intellij-community,izonder/intellij-community,asedunov/intellij-community,MER-GROUP/intellij-community,da1z/intellij-community,ibinti/intellij-community,lucafavatella/intellij-community,blademainer/intellij-community,amith01994/intellij-community,caot/intellij-community,fengbaicanhe/intellij-community,TangHao1987/intellij-community,Lekanich/intellij-community,dslomov/intellij-community,idea4bsd/idea4bsd,michaelgallacher/intellij-community,salguarnieri/intellij-community,hurricup/intellij-community,MER-GROUP/intellij-community,fengbaicanhe/intellij-community,adedayo/intellij-community,orekyuu/intellij-community,fengbaicanhe/intellij-community,signed/intellij-community,caot/intellij-community,mglukhikh/intellij-community,semonte/intellij-community,joewalnes/idea-community,clumsy/intellij-community,gnuhub/intellij-community,pwoodworth/intellij-community,nicolargo/intellij-community,alphafoobar/intellij-community,SerCeMan/intellij-community,kool79/intellij-community,retomerz/intellij-community,lucafavatella/intellij-community,suncycheng/intellij-community,fengbaicanhe/intellij-community,holmes/intellij-community,orekyuu/intellij-community,adedayo/intellij-community,izonder/intellij-community,muntasirsyed/intellij-community,TangHao1987/intellij-community,asedunov/intellij-community,hurricup/intellij-community,Lekanich/intellij-community,dslomov/intellij-community,ThiagoGarciaAlves/intellij-community,consulo/consulo,kdwink/intellij-community,akosyakov/intellij-community,MER-GROUP/intellij-community,robovm/robovm-studio,Distrotech/intellij-community,asedunov/intellij-community,robovm/robovm-studio,nicolargo/intellij-community,holmes/intellij-community,nicolargo/intellij-community,ibinti/intellij-community,ibinti/intellij-community,tmpgit/intellij-community,joewalnes/idea-community,ol-loginov/intellij-community,robovm/robovm-studio,slisson/intellij-community,MichaelNedzelsky/intellij-community,amith01994/intellij-community,youdonghai/intellij-community,da1z/intellij-community,ftomassetti/intellij-community,kool79/intellij-community,tmpgit/intellij-community,vvv1559/intellij-community,ivan-fedorov/intellij-community,robovm/robovm-studio,Lekanich/intellij-community,gnuhub/intellij-community,signed/intellij-community,suncycheng/intellij-community,apixandru/intellij-community,petteyg/intellij-community,ivan-fedorov/intellij-community,ol-loginov/intellij-community,suncycheng/intellij-community,blademainer/intellij-community,kool79/intellij-community,xfournet/intellij-community,ThiagoGarciaAlves/intellij-community,gnuhub/intellij-community,ibinti/intellij-community,caot/intellij-community,suncycheng/intellij-community,adedayo/intellij-community,FHannes/intellij-community,ol-loginov/intellij-community,gnuhub/intellij-community,kdwink/intellij-community,hurricup/intellij-community,gnuhub/intellij-community,ibinti/intellij-community,asedunov/intellij-community,ryano144/intellij-community,robovm/robovm-studio,slisson/intellij-community,salguarnieri/intellij-community,signed/intellij-community,Lekanich/intellij-community,samthor/intellij-community,muntasirsyed/intellij-community,retomerz/intellij-community,dslomov/intellij-community,xfournet/intellij-community,fitermay/intellij-community,ol-loginov/intellij-community,ftomassetti/intellij-community,muntasirsyed/intellij-community,caot/intellij-community,da1z/intellij-community,MichaelNedzelsky/intellij-community,robovm/robovm-studio,youdonghai/intellij-community,ftomassetti/intellij-community,retomerz/intellij-community,muntasirsyed/intellij-community,youdonghai/intellij-community,FHannes/intellij-community,orekyuu/intellij-community,samthor/intellij-community,kdwink/intellij-community,semonte/intellij-community,apixandru/intellij-community,kool79/intellij-community,youdonghai/intellij-community,supersven/intellij-community,kdwink/intellij-community,youdonghai/intellij-community,signed/intellij-community,consulo/consulo,diorcety/intellij-community,wreckJ/intellij-community,ryano144/intellij-community,gnuhub/intellij-community,youdonghai/intellij-community,apixandru/intellij-community,mglukhikh/intellij-community,semonte/intellij-community,joewalnes/idea-community,jagguli/intellij-community,kdwink/intellij-community,muntasirsyed/intellij-community,Distrotech/intellij-community,samthor/intellij-community,nicolargo/intellij-community,akosyakov/intellij-community,clumsy/intellij-community,gnuhub/intellij-community,vvv1559/intellij-community,tmpgit/intellij-community,ThiagoGarciaAlves/intellij-community,ftomassetti/intellij-community,allotria/intellij-community,SerCeMan/intellij-community,kool79/intellij-community,pwoodworth/intellij-community,idea4bsd/idea4bsd,asedunov/intellij-community,supersven/intellij-community,caot/intellij-community,wreckJ/intellij-community,signed/intellij-community,diorcety/intellij-community,ol-loginov/intellij-community,supersven/intellij-community,robovm/robovm-studio,kool79/intellij-community,vvv1559/intellij-community,mglukhikh/intellij-community,pwoodworth/intellij-community,retomerz/intellij-community,samthor/intellij-community,ol-loginov/intellij-community,Lekanich/intellij-community,vladmm/intellij-community,ivan-fedorov/intellij-community,gnuhub/intellij-community,kool79/intellij-community,ThiagoGarciaAlves/intellij-community,ryano144/intellij-community,consulo/consulo,retomerz/intellij-community,da1z/intellij-community,samthor/intellij-community,caot/intellij-community,michaelgallacher/intellij-community,holmes/intellij-community,ftomassetti/intellij-community,diorcety/intellij-community,gnuhub/intellij-community,alphafoobar/intellij-community,michaelgallacher/intellij-community,gnuhub/intellij-community,kdwink/intellij-community,ryano144/intellij-community,samthor/intellij-community,apixandru/intellij-community,ftomassetti/intellij-community,da1z/intellij-community,petteyg/intellij-community,diorcety/intellij-community,apixandru/intellij-community,nicolargo/intellij-community,fnouama/intellij-community,Distrotech/intellij-community,salguarnieri/intellij-community,supersven/intellij-community,diorcety/intellij-community,fitermay/intellij-community,akosyakov/intellij-community,ThiagoGarciaAlves/intellij-community,vladmm/intellij-community,vvv1559/intellij-community,MichaelNedzelsky/intellij-community,ryano144/intellij-community,wreckJ/intellij-community,supersven/intellij-community,Distrotech/intellij-community,jagguli/intellij-community,slisson/intellij-community,lucafavatella/intellij-community,akosyakov/intellij-community,signed/intellij-community,ryano144/intellij-community,ibinti/intellij-community,Distrotech/intellij-community,fnouama/intellij-community,tmpgit/intellij-community,ThiagoGarciaAlves/intellij-community,FHannes/intellij-community,SerCeMan/intellij-community,ThiagoGarciaAlves/intellij-community,TangHao1987/intellij-community,akosyakov/intellij-community,FHannes/intellij-community,allotria/intellij-community,clumsy/intellij-community,semonte/intellij-community,amith01994/intellij-community,orekyuu/intellij-community,MER-GROUP/intellij-community,dslomov/intellij-community,ahb0327/intellij-community,signed/intellij-community,ahb0327/intellij-community,ol-loginov/intellij-community,michaelgallacher/intellij-community,izonder/intellij-community,retomerz/intellij-community,semonte/intellij-community,MichaelNedzelsky/intellij-community,akosyakov/intellij-community,petteyg/intellij-community,ryano144/intellij-community,signed/intellij-community,ThiagoGarciaAlves/intellij-community,fnouama/intellij-community,akosyakov/intellij-community,vladmm/intellij-community,izonder/intellij-community,petteyg/intellij-community,apixandru/intellij-community,suncycheng/intellij-community,michaelgallacher/intellij-community,idea4bsd/idea4bsd,Lekanich/intellij-community,lucafavatella/intellij-community,vvv1559/intellij-community,tmpgit/intellij-community,pwoodworth/intellij-community,kdwink/intellij-community,signed/intellij-community,wreckJ/intellij-community,allotria/intellij-community,vvv1559/intellij-community,orekyuu/intellij-community,TangHao1987/intellij-community,fitermay/intellij-community,ftomassetti/intellij-community,salguarnieri/intellij-community,kool79/intellij-community,ftomassetti/intellij-community,ahb0327/intellij-community,kdwink/intellij-community,retomerz/intellij-community,FHannes/intellij-community,joewalnes/idea-community,robovm/robovm-studio,joewalnes/idea-community,youdonghai/intellij-community,fnouama/intellij-community,allotria/intellij-community,caot/intellij-community,TangHao1987/intellij-community,kool79/intellij-community,allotria/intellij-community,wreckJ/intellij-community,joewalnes/idea-community,nicolargo/intellij-community,lucafavatella/intellij-community,salguarnieri/intellij-community,retomerz/intellij-community,youdonghai/intellij-community,ahb0327/intellij-community,adedayo/intellij-community,signed/intellij-community,retomerz/intellij-community,nicolargo/intellij-community,apixandru/intellij-community,vladmm/intellij-community,adedayo/intellij-community,dslomov/intellij-community,holmes/intellij-community,kdwink/intellij-community,muntasirsyed/intellij-community,da1z/intellij-community,kool79/intellij-community,ryano144/intellij-community,ahb0327/intellij-community,blademainer/intellij-community,izonder/intellij-community,supersven/intellij-community,TangHao1987/intellij-community,idea4bsd/idea4bsd,xfournet/intellij-community,pwoodworth/intellij-community,fengbaicanhe/intellij-community,alphafoobar/intellij-community,salguarnieri/intellij-community,SerCeMan/intellij-community,MER-GROUP/intellij-community,fitermay/intellij-community,vvv1559/intellij-community,lucafavatella/intellij-community,pwoodworth/intellij-community,youdonghai/intellij-community,ThiagoGarciaAlves/intellij-community,semonte/intellij-community,vvv1559/intellij-community,mglukhikh/intellij-community,TangHao1987/intellij-community,holmes/intellij-community,TangHao1987/intellij-community,ibinti/intellij-community,hurricup/intellij-community,xfournet/intellij-community,clumsy/intellij-community,dslomov/intellij-community,MichaelNedzelsky/intellij-community,suncycheng/intellij-community,dslomov/intellij-community,ol-loginov/intellij-community,muntasirsyed/intellij-community,xfournet/intellij-community,MichaelNedzelsky/intellij-community,alphafoobar/intellij-community,youdonghai/intellij-community,ivan-fedorov/intellij-community,michaelgallacher/intellij-community,ivan-fedorov/intellij-community,blademainer/intellij-community,supersven/intellij-community,Lekanich/intellij-community,salguarnieri/intellij-community,apixandru/intellij-community,xfournet/intellij-community,semonte/intellij-community,muntasirsyed/intellij-community,idea4bsd/idea4bsd,suncycheng/intellij-community,adedayo/intellij-community,allotria/intellij-community,mglukhikh/intellij-community,petteyg/intellij-community,wreckJ/intellij-community,signed/intellij-community,Distrotech/intellij-community,ThiagoGarciaAlves/intellij-community,MichaelNedzelsky/intellij-community,slisson/intellij-community,ahb0327/intellij-community,samthor/intellij-community,xfournet/intellij-community,holmes/intellij-community,semonte/intellij-community,mglukhikh/intellij-community,SerCeMan/intellij-community,jagguli/intellij-community,ahb0327/intellij-community,blademainer/intellij-community,ryano144/intellij-community,dslomov/intellij-community,MichaelNedzelsky/intellij-community,Distrotech/intellij-community,robovm/robovm-studio,samthor/intellij-community,alphafoobar/intellij-community,fnouama/intellij-community,asedunov/intellij-community,MichaelNedzelsky/intellij-community,clumsy/intellij-community,lucafavatella/intellij-community,michaelgallacher/intellij-community,amith01994/intellij-community,orekyuu/intellij-community,Distrotech/intellij-community,hurricup/intellij-community,diorcety/intellij-community,ivan-fedorov/intellij-community,ftomassetti/intellij-community,nicolargo/intellij-community,hurricup/intellij-community,slisson/intellij-community,salguarnieri/intellij-community,samthor/intellij-community,wreckJ/intellij-community,akosyakov/intellij-community,kool79/intellij-community,suncycheng/intellij-community,mglukhikh/intellij-community,alphafoobar/intellij-community,vladmm/intellij-community,youdonghai/intellij-community,SerCeMan/intellij-community,xfournet/intellij-community,pwoodworth/intellij-community,petteyg/intellij-community,clumsy/intellij-community,kdwink/intellij-community,akosyakov/intellij-community,ahb0327/intellij-community,adedayo/intellij-community,Lekanich/intellij-community,jagguli/intellij-community,vladmm/intellij-community,MichaelNedzelsky/intellij-community,da1z/intellij-community,xfournet/intellij-community,samthor/intellij-community,amith01994/intellij-community,ahb0327/intellij-community,ol-loginov/intellij-community,allotria/intellij-community,FHannes/intellij-community,mglukhikh/intellij-community,retomerz/intellij-community,SerCeMan/intellij-community,wreckJ/intellij-community,xfournet/intellij-community,caot/intellij-community,FHannes/intellij-community,xfournet/intellij-community,ernestp/consulo,fnouama/intellij-community,izonder/intellij-community,MichaelNedzelsky/intellij-community,holmes/intellij-community,caot/intellij-community,jagguli/intellij-community,ivan-fedorov/intellij-community,mglukhikh/intellij-community,ivan-fedorov/intellij-community,mglukhikh/intellij-community,asedunov/intellij-community,samthor/intellij-community,Distrotech/intellij-community,samthor/intellij-community,pwoodworth/intellij-community,diorcety/intellij-community,fnouama/intellij-community,robovm/robovm-studio,holmes/intellij-community,semonte/intellij-community,caot/intellij-community,ol-loginov/intellij-community,suncycheng/intellij-community,youdonghai/intellij-community,asedunov/intellij-community,lucafavatella/intellij-community,vladmm/intellij-community,fitermay/intellij-community,ibinti/intellij-community,pwoodworth/intellij-community,wreckJ/intellij-community,petteyg/intellij-community,consulo/consulo,lucafavatella/intellij-community,adedayo/intellij-community,vladmm/intellij-community,nicolargo/intellij-community,vvv1559/intellij-community,hurricup/intellij-community,orekyuu/intellij-community,fengbaicanhe/intellij-community,izonder/intellij-community,ryano144/intellij-community,supersven/intellij-community,wreckJ/intellij-community,Lekanich/intellij-community,vvv1559/intellij-community,salguarnieri/intellij-community,MER-GROUP/intellij-community,fengbaicanhe/intellij-community,SerCeMan/intellij-community,jagguli/intellij-community,hurricup/intellij-community,amith01994/intellij-community,amith01994/intellij-community,akosyakov/intellij-community,FHannes/intellij-community,blademainer/intellij-community,SerCeMan/intellij-community,clumsy/intellij-community,hurricup/intellij-community,slisson/intellij-community,michaelgallacher/intellij-community,lucafavatella/intellij-community,hurricup/intellij-community,diorcety/intellij-community,michaelgallacher/intellij-community,allotria/intellij-community,wreckJ/intellij-community,supersven/intellij-community,semonte/intellij-community,fnouama/intellij-community,slisson/intellij-community,Distrotech/intellij-community,fengbaicanhe/intellij-community,adedayo/intellij-community,fitermay/intellij-community,consulo/consulo,amith01994/intellij-community,kdwink/intellij-community,ernestp/consulo,idea4bsd/idea4bsd,MER-GROUP/intellij-community,robovm/robovm-studio,Lekanich/intellij-community,diorcety/intellij-community,slisson/intellij-community,vladmm/intellij-community,orekyuu/intellij-community,petteyg/intellij-community,SerCeMan/intellij-community,da1z/intellij-community,fitermay/intellij-community,adedayo/intellij-community,amith01994/intellij-community,ryano144/intellij-community,fitermay/intellij-community,robovm/robovm-studio,salguarnieri/intellij-community,idea4bsd/idea4bsd,fengbaicanhe/intellij-community,wreckJ/intellij-community,petteyg/intellij-community,alphafoobar/intellij-community,blademainer/intellij-community,TangHao1987/intellij-community,ol-loginov/intellij-community,izonder/intellij-community,idea4bsd/idea4bsd,supersven/intellij-community,caot/intellij-community,allotria/intellij-community,signed/intellij-community,hurricup/intellij-community,holmes/intellij-community,tmpgit/intellij-community,tmpgit/intellij-community,nicolargo/intellij-community,vvv1559/intellij-community,ThiagoGarciaAlves/intellij-community,apixandru/intellij-community,gnuhub/intellij-community,idea4bsd/idea4bsd,vvv1559/intellij-community,caot/intellij-community,jagguli/intellij-community,petteyg/intellij-community,apixandru/intellij-community,ibinti/intellij-community,ibinti/intellij-community,dslomov/intellij-community,orekyuu/intellij-community,vladmm/intellij-community,fengbaicanhe/intellij-community,lucafavatella/intellij-community,izonder/intellij-community,ftomassetti/intellij-community,alphafoobar/intellij-community,allotria/intellij-community,vvv1559/intellij-community,asedunov/intellij-community,ftomassetti/intellij-community,ernestp/consulo,semonte/intellij-community,lucafavatella/intellij-community,allotria/intellij-community,slisson/intellij-community,ryano144/intellij-community,signed/intellij-community,apixandru/intellij-community,michaelgallacher/intellij-community,adedayo/intellij-community,ivan-fedorov/intellij-community,fitermay/intellij-community,holmes/intellij-community,asedunov/intellij-community,MER-GROUP/intellij-community,orekyuu/intellij-community,Distrotech/intellij-community,supersven/intellij-community,vladmm/intellij-community,MER-GROUP/intellij-community,FHannes/intellij-community,FHannes/intellij-community,jagguli/intellij-community,nicolargo/intellij-community,fengbaicanhe/intellij-community,muntasirsyed/intellij-community,fengbaicanhe/intellij-community,slisson/intellij-community,fnouama/intellij-community,ibinti/intellij-community,pwoodworth/intellij-community,blademainer/intellij-community,fnouama/intellij-community,ivan-fedorov/intellij-community,hurricup/intellij-community,pwoodworth/intellij-community,mglukhikh/intellij-community,diorcety/intellij-community,holmes/intellij-community,da1z/intellij-community,fitermay/intellij-community,MER-GROUP/intellij-community,asedunov/intellij-community,tmpgit/intellij-community,consulo/consulo,SerCeMan/intellij-community,idea4bsd/idea4bsd,tmpgit/intellij-community,MichaelNedzelsky/intellij-community,xfournet/intellij-community,blademainer/intellij-community,ftomassetti/intellij-community,retomerz/intellij-community,slisson/intellij-community,da1z/intellij-community,retomerz/intellij-community,apixandru/intellij-community,muntasirsyed/intellij-community,petteyg/intellij-community,hurricup/intellij-community,supersven/intellij-community,Lekanich/intellij-community,allotria/intellij-community,ThiagoGarciaAlves/intellij-community,dslomov/intellij-community,idea4bsd/idea4bsd,asedunov/intellij-community,amith01994/intellij-community,amith01994/intellij-community,FHannes/intellij-community,joewalnes/idea-community,salguarnieri/intellij-community,akosyakov/intellij-community,mglukhikh/intellij-community,diorcety/intellij-community,clumsy/intellij-community,slisson/intellij-community,vladmm/intellij-community,ahb0327/intellij-community,ol-loginov/intellij-community,ivan-fedorov/intellij-community,ernestp/consulo,fitermay/intellij-community,fnouama/intellij-community,muntasirsyed/intellij-community,blademainer/intellij-community,jagguli/intellij-community,mglukhikh/intellij-community,holmes/intellij-community,alphafoobar/intellij-community,orekyuu/intellij-community,suncycheng/intellij-community,fnouama/intellij-community,FHannes/intellij-community,FHannes/intellij-community,muntasirsyed/intellij-community,suncycheng/intellij-community,izonder/intellij-community,asedunov/intellij-community,izonder/intellij-community,allotria/intellij-community,TangHao1987/intellij-community,apixandru/intellij-community,gnuhub/intellij-community,clumsy/intellij-community
/* * Copyright 2000-2009 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.refactoring; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.progress.ProgressIndicator; import com.intellij.openapi.progress.ProgressManager; import com.intellij.openapi.project.Project; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.psi.*; import com.intellij.psi.codeStyle.JavaCodeStyleManager; import com.intellij.usageView.UsageInfo; import com.intellij.util.IncorrectOperationException; import com.intellij.util.containers.HashSet; import java.util.Collection; import java.util.Set; public class OptimizeImportsRefactoringHelper implements RefactoringHelper<Set<PsiJavaFile>> { private static final Logger LOG = Logger.getInstance("#com.intellij.refactoring.OptimizeImportsRefactoringHelper"); public Set<PsiJavaFile> prepareOperation(final UsageInfo[] usages) { Set<PsiJavaFile> javaFiles = new HashSet<PsiJavaFile>(); for (UsageInfo usage : usages) { final PsiElement element = usage.getElement(); if (element != null) { final PsiFile file = element.getContainingFile(); if (file instanceof PsiJavaFile) { javaFiles.add((PsiJavaFile)file); } } } return javaFiles; } public void performOperation(final Project project, final Set<PsiJavaFile> javaFiles) { PsiManager.getInstance(project).performActionWithFormatterDisabled(new Runnable() { public void run() { ApplicationManager.getApplication().runWriteAction(new Runnable() { public void run() { PsiDocumentManager.getInstance(project).commitAllDocuments(); } }); } }); final Set<SmartPsiElementPointer<PsiImportStatementBase>> redundants = new HashSet<SmartPsiElementPointer<PsiImportStatementBase>>(); final Runnable findRedundantImports = new Runnable() { public void run() { final JavaCodeStyleManager styleManager = JavaCodeStyleManager.getInstance(project); final ProgressIndicator progressIndicator = ProgressManager.getInstance().getProgressIndicator(); final SmartPointerManager pointerManager = SmartPointerManager.getInstance(project); for (PsiJavaFile file : javaFiles) { if (file.isValid()) { final VirtualFile virtualFile = file.getVirtualFile(); if (virtualFile != null) { if (progressIndicator != null) { progressIndicator.setText2(virtualFile.getPresentableUrl()); } final Collection<PsiImportStatementBase> perFile = styleManager.findRedundantImports(file); if (perFile != null) { for (PsiImportStatementBase redundant : perFile) { redundants.add(pointerManager.createSmartPsiElementPointer(redundant)); } } } } } } }; if (!ProgressManager.getInstance().runProcessWithProgressSynchronously(findRedundantImports, "Removing redundant imports", false, project)) return; ApplicationManager.getApplication().runWriteAction(new Runnable() { public void run() { try { for (final SmartPsiElementPointer<PsiImportStatementBase> pointer : redundants) { final PsiImportStatementBase importStatement = pointer.getElement(); if (importStatement != null && importStatement.isValid()) { final PsiJavaCodeReferenceElement ref = importStatement.getImportReference(); //Do not remove non-resolving refs if (ref == null || ref.resolve() == null) { continue; } importStatement.delete(); } } } catch (IncorrectOperationException e) { LOG.error(e); } } }); } }
java/java-impl/src/com/intellij/refactoring/OptimizeImportsRefactoringHelper.java
/* * Copyright 2000-2009 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.refactoring; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.progress.ProgressIndicator; import com.intellij.openapi.progress.ProgressManager; import com.intellij.openapi.project.Project; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.psi.*; import com.intellij.psi.codeStyle.JavaCodeStyleManager; import com.intellij.usageView.UsageInfo; import com.intellij.util.IncorrectOperationException; import com.intellij.util.containers.HashSet; import java.util.Collection; import java.util.Set; public class OptimizeImportsRefactoringHelper implements RefactoringHelper<Set<PsiJavaFile>> { private static final Logger LOG = Logger.getInstance("#com.intellij.refactoring.OptimizeImportsRefactoringHelper"); public Set<PsiJavaFile> prepareOperation(final UsageInfo[] usages) { Set<PsiJavaFile> javaFiles = new HashSet<PsiJavaFile>(); for (UsageInfo usage : usages) { final PsiElement element = usage.getElement(); if (element != null) { final PsiFile file = element.getContainingFile(); if (file instanceof PsiJavaFile) { javaFiles.add((PsiJavaFile)file); } } } return javaFiles; } public void performOperation(final Project project, final Set<PsiJavaFile> javaFiles) { ApplicationManager.getApplication().runWriteAction(new Runnable() { public void run() { PsiDocumentManager.getInstance(project).commitAllDocuments(); } }); final Set<SmartPsiElementPointer<PsiImportStatementBase>> redundants = new HashSet<SmartPsiElementPointer<PsiImportStatementBase>>(); final Runnable findRedundantImports = new Runnable() { public void run() { final JavaCodeStyleManager styleManager = JavaCodeStyleManager.getInstance(project); final ProgressIndicator progressIndicator = ProgressManager.getInstance().getProgressIndicator(); final SmartPointerManager pointerManager = SmartPointerManager.getInstance(project); for (PsiJavaFile file : javaFiles) { if (file.isValid()) { final VirtualFile virtualFile = file.getVirtualFile(); if (virtualFile != null) { if (progressIndicator != null) { progressIndicator.setText2(virtualFile.getPresentableUrl()); } final Collection<PsiImportStatementBase> perFile = styleManager.findRedundantImports(file); if (perFile != null) { for (PsiImportStatementBase redundant : perFile) { redundants.add(pointerManager.createSmartPsiElementPointer(redundant)); } } } } } } }; if (!ProgressManager.getInstance().runProcessWithProgressSynchronously(findRedundantImports, "Removing redundant imports", false, project)) return; ApplicationManager.getApplication().runWriteAction(new Runnable() { public void run() { try { for (final SmartPsiElementPointer<PsiImportStatementBase> pointer : redundants) { final PsiImportStatementBase importStatement = pointer.getElement(); if (importStatement != null && importStatement.isValid()) { final PsiJavaCodeReferenceElement ref = importStatement.getImportReference(); //Do not remove non-resolving refs if (ref == null || ref.resolve() == null) { continue; } importStatement.delete(); } } } catch (IncorrectOperationException e) { LOG.error(e); } } }); } }
Hold formatting until import optimization finished
java/java-impl/src/com/intellij/refactoring/OptimizeImportsRefactoringHelper.java
Hold formatting until import optimization finished
<ide><path>ava/java-impl/src/com/intellij/refactoring/OptimizeImportsRefactoringHelper.java <ide> } <ide> <ide> public void performOperation(final Project project, final Set<PsiJavaFile> javaFiles) { <del> ApplicationManager.getApplication().runWriteAction(new Runnable() { <add> PsiManager.getInstance(project).performActionWithFormatterDisabled(new Runnable() { <ide> public void run() { <del> PsiDocumentManager.getInstance(project).commitAllDocuments(); <add> ApplicationManager.getApplication().runWriteAction(new Runnable() { <add> public void run() { <add> PsiDocumentManager.getInstance(project).commitAllDocuments(); <add> } <add> }); <ide> } <ide> }); <add> <ide> final Set<SmartPsiElementPointer<PsiImportStatementBase>> redundants = new HashSet<SmartPsiElementPointer<PsiImportStatementBase>>(); <ide> final Runnable findRedundantImports = new Runnable() { <ide> public void run() {
Java
mit
0bcc8e7ab19f3fc300a5f5c888fa505c22a4c6fe
0
Winglu/SecondWork
package alg; import java.util.ArrayList; import java.util.Hashtable; import java.util.Iterator; import java.util.Map; import java.util.Queue; import java.util.Set; import java.util.concurrent.LinkedBlockingQueue; import jgraphtResearch.Vertex; import org.jgrapht.UndirectedGraph; import org.jgrapht.alg.NeighborIndex; import org.jgrapht.graph.DefaultEdge; import ds.EdgeSupport; import ds.EdgeTrussness; /** * After calling trussDecomposition, the graph must be reloaded * Moved to git hub * @author luchen * */ public class TrussDecomposition { public UndirectedGraph<Vertex, DefaultEdge> g; public EdgeTrussness et; public TrussDecomposition(UndirectedGraph<Vertex, DefaultEdge> g){ this.g = g; et = new EdgeTrussness(); } /** * * no bug left, only may have performance issues * */ public void trussDecomposition(){ Hashtable<DefaultEdge, EdgeSupport> edgeSupport = new Hashtable<>(); NeighborIndex<Vertex, DefaultEdge> ni = new NeighborIndex<>(g); //supportComputation(edgeSupport,ni); Iterator<Map.Entry<DefaultEdge, EdgeSupport> > isz = edgeSupport.entrySet().iterator(); while(isz.hasNext()){ Map.Entry<DefaultEdge, EdgeSupport> m = isz.next(); System.out.println(m.getKey()+"support: "+m.getValue().support); } int k = 2; int j = k-2; while(g.edgeSet().size()!=0){ removeUnsupportedEdges(edgeSupport,ni,j); k++; j=k-2; } Iterator<Map.Entry<DefaultEdge, Integer> > i = et.et.entrySet().iterator(); while(i.hasNext()){ Map.Entry<DefaultEdge, Integer> m = i.next(); System.out.println(m.getKey()+"'s trussness is:"+m.getValue()); } System.out.println(et.et.size()); System.out.println(g); /* * debug: pass */ } //!!!!!!!!!!! neighbor index must be recalculated during the graph update private void removeUnsupportedEdges(Hashtable<DefaultEdge, EdgeSupport> esl,NeighborIndex<Vertex, DefaultEdge> ni,int j){ //support of each edge has been calculated //ni = new NeighborIndex<>(g); Queue<EdgeSupport> q = new LinkedBlockingQueue<>(); //for all edges less than j are removed and put them in to a queue /* Iterator<Map.Entry<DefaultEdge, EdgeSupport> > isz = es.entrySet().iterator(); while(isz.hasNext()){ Map.Entry<DefaultEdge, EdgeSupport> m = isz.next(); if(m.getValue().support<j){ //added it into q q.add(m.getValue()); //remove it from g g.removeEdge(m.getValue().e); //ni = new NeighborIndex<>(g); } } */ Set<DefaultEdge> edges = g.edgeSet(); ArrayList<DefaultEdge> edgeList = new ArrayList<>(edges); Vertex sv; Vertex tv; ArrayList<Vertex> svn = new ArrayList<>(); ArrayList<Vertex> tvn = new ArrayList<>(); Iterator<DefaultEdge> ide = edgeList.iterator(); while(ide.hasNext()){ //for(DefaultEdge e:edges){ ni = new NeighborIndex<>(g); DefaultEdge e = ide.next(); sv = g.getEdgeSource(e); tv = g.getEdgeTarget(e); svn.addAll(ni.neighborsOf(sv)); tvn.addAll(ni.neighborsOf(tv)); svn.retainAll(tvn); int support = svn.size(); //System.out.println(support); if(support<j){ g.removeEdge(e); ni = new NeighborIndex<>(g); }else{ EdgeSupport es = new EdgeSupport(); es.support = support; es.e = e; esl.put(e, es); } svn.clear(); tvn.clear(); } ni = new NeighborIndex<>(g); while(q.isEmpty()!=true){ ni = new NeighborIndex<>(g); EdgeSupport ces = q.poll(); //get edge source and target sv = g.getEdgeSource(ces.e); tv = g.getEdgeTarget(ces.e); svn.addAll(ni.neighborsOf(sv)); tvn.addAll(ni.neighborsOf(tv)); svn.retainAll(tvn); for(Vertex v:svn){ DefaultEdge aes = g.getEdge(sv,v); if(aes!=null){ EdgeSupport aess = esl.get(aes); aess.support = aess.support - 1; if(aess.support<j){ q.add(aess); g.removeEdge(aess.e); //ni = new NeighborIndex<>(g); } } DefaultEdge aet = g.getEdge(tv,v); if(aet!=null){ EdgeSupport aets = esl.get(aet); aets.support = aets.support - 1; if(aets.support<j){ q.add(aets); g.removeEdge(aets.e); //ni = new NeighborIndex<>(g); } } } svn.clear(); tvn.clear(); } //for all edges that currently in the graph, they should all have trussness of j edges = g.edgeSet(); for(DefaultEdge e:edges){ et.et.put(e, j+2); } } private void supportComputation(Hashtable<DefaultEdge, EdgeSupport> esl,NeighborIndex<Vertex, DefaultEdge> ni){ Set<DefaultEdge> edges = g.edgeSet(); Vertex sv; Vertex tv; ArrayList<Vertex> svn = new ArrayList<>(); ArrayList<Vertex> tvn = new ArrayList<>(); for(DefaultEdge e:edges){ sv = g.getEdgeSource(e); tv = g.getEdgeTarget(e); svn.addAll(ni.neighborsOf(sv)); tvn.addAll(ni.neighborsOf(tv)); svn.retainAll(tvn); int support = svn.size(); EdgeSupport es = new EdgeSupport(); es.support = support; es.e = e; esl.put(e, es); svn.clear(); tvn.clear(); } } public void trussDecomposition_workable(){ int k = 3; Set<DefaultEdge> edges = g.edgeSet(); NeighborIndex<Vertex, DefaultEdge> ni = new NeighborIndex<>(g); Hashtable<DefaultEdge, EdgeSupport> edgeSupport = new Hashtable<>(); Queue<EdgeSupport> q = new LinkedBlockingQueue<>(); Vertex sv; Vertex tv; ArrayList<Vertex> svn = new ArrayList<>(); ArrayList<Vertex> tvn = new ArrayList<>(); //initial edge support for(DefaultEdge e:edges){ //computes support sv = g.getEdgeSource(e); tv = g.getEdgeTarget(e); svn.addAll(ni.neighborsOf(sv)); tvn.addAll(ni.neighborsOf(tv)); svn.retainAll(tvn); int support = svn.size(); EdgeSupport es = new EdgeSupport(); es.support = support; es.e = e; edgeSupport.put(e, es); svn.clear(); tvn.clear(); } //now edge support are calculated //clean up edges with support of 0 Iterator<Map.Entry<DefaultEdge, EdgeSupport> > is = edgeSupport.entrySet().iterator(); while(is.hasNext()){ Map.Entry<DefaultEdge, EdgeSupport> m = is.next(); if(m.getValue().support==0){ g.removeEdge(m.getValue().e); } } for(DefaultEdge e:g.edgeSet()){ EdgeSupport es = edgeSupport.get(e); if(es.support <=(k-2)){ q.add(es); } } Iterator<Map.Entry<DefaultEdge, EdgeSupport> > isz = edgeSupport.entrySet().iterator(); while(isz.hasNext()){ Map.Entry<DefaultEdge, EdgeSupport> m = isz.next(); System.out.println(m.getKey()+"support: "+m.getValue().support); } //compute trussness while(g.edgeSet().size()!=0){ while(q.isEmpty()!=true){ EdgeSupport es = q.poll(); //get edge source and target sv = g.getEdgeSource(es.e); tv = g.getEdgeTarget(es.e); svn.addAll(ni.neighborsOf(sv)); tvn.addAll(ni.neighborsOf(tv)); svn.retainAll(tvn); //get edges for(Vertex v:svn){ DefaultEdge aes = g.getEdge(sv,v); if(aes!=null){ EdgeSupport aess = edgeSupport.get(aes); aess.support = aess.support - 1; //do not know why, but it works //according to k-truss definition if(aess.support < (k-2)){ if(q.contains(aess)!=true){ q.add(aess); } } } DefaultEdge aet = g.getEdge(tv, v); if(aet!=null){ EdgeSupport aets = edgeSupport.get(aet); aets.support = aets.support - 1; //do not know why, but it works //according to k-truss definition if(aets.support < (k-2)){ if(q.contains(aets)!=true){ q.add(aets); } } } } et.et.put(es.e, k); g.removeEdge(es.e); svn.clear(); tvn.clear(); } if(g.edgeSet().size()!=0){ k++; //System.out.println("trussness: "+k); for(DefaultEdge e:g.edgeSet()){ EdgeSupport es = edgeSupport.get(e); if(es.support <= (k-2)){ if(q.contains(es)!=true){ q.add(es); } } } } } System.out.println(et.et.size()); Iterator<Map.Entry<DefaultEdge, Integer> > i = et.et.entrySet().iterator(); while(i.hasNext()){ Map.Entry<DefaultEdge, Integer> m = i.next(); System.out.println(m.getKey()+"'s trussness is:"+m.getValue()); } } public void trussDecompositionAdv(){ int k = 2; Set<DefaultEdge> edges = g.edgeSet(); NeighborIndex<Vertex, DefaultEdge> ni = new NeighborIndex<>(g); Hashtable<DefaultEdge, EdgeSupport> edgeSupport = new Hashtable<>(); //setup a queue to store edges that have number of support less than k Queue<EdgeSupport> q = new LinkedBlockingQueue<>(); //reducing creations of variable Vertex sv; Vertex tv; ArrayList<Vertex> svn = new ArrayList<>(); ArrayList<Vertex> tvn = new ArrayList<>(); //number of edge int noe = g.edgeSet().size(); //number of maximal support int noms = noe-2; int [] supportSpace = new int [noe-2]; for(DefaultEdge e:edges){ //computes support sv = g.getEdgeSource(e); tv = g.getEdgeTarget(e); svn.addAll(ni.neighborsOf(sv)); tvn.addAll(ni.neighborsOf(tv)); //= ni.neighborsOf(sv); //= ni.neighborsOf(tv); /* Testing * System.out.println(svn.size()); System.out.println(tvn.size()); System.out.println(ni.neighborsOf(sv)); System.out.println(ni.neighborsOf(tv));*/ svn.retainAll(tvn); int support = svn.size(); EdgeSupport es = new EdgeSupport(); es.support = support; es.e = e; //great increase the space for the current support number to +1 supportSpace[support]++; edgeSupport.put(e, es); /* Testing * System.out.println(e+" support is :"+support); System.out.println(svn.size()); System.out.println(tvn.size()); System.out.println(ni.neighborsOf(sv)); System.out.println(ni.neighborsOf(tv));*/ /* * Clear up */ svn.clear(); tvn.clear(); } //good sort!!!! //compute start location for each support number int l = 0; //initial location //key: number of support, value location in the sorted array int [] initialLoction = new int [noe-1]; initialLoction[0] =0; for(int i=1; i<supportSpace.length;i++){ initialLoction[i]=initialLoction[i-1]+supportSpace[i-1]; } /* for(int i=0; i<supportSpace.length;i++){ System.out.println(i+":"+initialLoction[i]); } */ DefaultEdge [] sortedEdge = new DefaultEdge [noe]; //hash table for sotre location Hashtable<DefaultEdge, Integer> edgeSortedLocation = new Hashtable<>(); //iterate the edge Iterator<Map.Entry<DefaultEdge, EdgeSupport> > isz = edgeSupport.entrySet().iterator(); while(isz.hasNext()){ Map.Entry<DefaultEdge, EdgeSupport> m = isz.next(); //put edge into a array sortedEdge[initialLoction[m.getValue().support]] = m.getValue().e; edgeSortedLocation.put(m.getValue().e, initialLoction[m.getValue().support]); //recorder location information using a hash table initialLoction[m.getValue().support]++; } /* *tested for(int i=0;i<noe;i++){ System.out.println(sortedEdge[i]+" support is: "+ edgeSupport.get(sortedEdge[i]).support); } */ //now the end position of support k should be initialLoction[m.getValue().support]-- for(int i=1; i<supportSpace.length;i++){ initialLoction[i]--; } //System.out.println(initialLoction[2]+","+supportSpace[2]); //now the initialLocation store the end location /* System.out.println("*****"); for(int i=1; i<supportSpace.length;i++){ System.out.println(i+":"+initialLoction[i]); } */ //System.out.println(q.size()); /* * end of compute support of each edge */ /* * debug edge support */ /* Iterator<Map.Entry<DefaultEdge, EdgeSupport> > isz = edgeSupport.entrySet().iterator(); while(isz.hasNext()){ Map.Entry<DefaultEdge, EdgeSupport> m = isz.next(); System.out.println(m.getKey()+"support: "+m.getValue().support); } */ Iterator<Map.Entry<DefaultEdge, EdgeSupport> > is = edgeSupport.entrySet().iterator(); while(is.hasNext()){ Map.Entry<DefaultEdge, EdgeSupport> m = is.next(); if(m.getValue().support==0){ g.removeEdge(m.getValue().e); } } //now the all edges has been sorted according to their support number in sortedEdge //the end location of edge with support number of k is in initialLoction[k] //the number of edges with support number of k is in supportSpace[k] // while(g.edgeSet().size()!=0){ for(int i=0;i<noe;i++){ DefaultEdge lowestSupportE = sortedEdge[i]; if(lowestSupportE!=null){ EdgeSupport es = edgeSupport.get(lowestSupportE); if(es.support<=k-2){ sv = g.getEdgeSource(es.e); tv = g.getEdgeTarget(es.e); svn.addAll(ni.neighborsOf(sv)); tvn.addAll(ni.neighborsOf(tv)); svn.retainAll(tvn); System.out.println(es.e); if(svn.size()<=tvn.size()){ for(Vertex v:svn){ DefaultEdge aes = g.getEdge(sv,v); if(aes!=null){ EdgeSupport aess = edgeSupport.get(aes); aess.support = aess.support - 1; //if(aess.support<=(k-2)){ // q.add(aess); //} //reorder int s = aess.support; System.out.println(s); int ps = s+1; int startOf = initialLoction[ps-1]+1; int currentEdgeLocation = edgeSortedLocation.get(aess.e); DefaultEdge te = sortedEdge[startOf]; sortedEdge[startOf] = aess.e; sortedEdge[currentEdgeLocation] = te; i=-1; } DefaultEdge aet = g.getEdge(tv, v); if(aet!=null){ EdgeSupport aets = edgeSupport.get(aet); aets.support = aets.support - 1; //if(aets.support<=(k-2)){ // q.add(aets); //} //reorder int s = aets.support; int ps = s+1; int startOf = initialLoction[ps-1]+1; int currentEdgeLocation = edgeSortedLocation.get(aets.e); DefaultEdge te = sortedEdge[startOf]; sortedEdge[startOf] = aets.e; sortedEdge[currentEdgeLocation] = te; i=-1; /* for(int j=0;j<noe;j++){ System.out.println(j+":"+sortedEdge[j]); }*/ } } }else{ for(Vertex v:svn){ DefaultEdge aet = g.getEdge(tv, v); if(aet!=null){ EdgeSupport aets = edgeSupport.get(aet); aets.support = aets.support - 1; //if(aets.support<=(k-2)){ // q.add(aets); //} //reorder int s = aets.support; int ps = s+1; int startOf = initialLoction[ps-1]+1; int currentEdgeLocation = edgeSortedLocation.get(aets.e); DefaultEdge te = sortedEdge[startOf]; sortedEdge[startOf] = aets.e; sortedEdge[currentEdgeLocation] = te; i=-1; } DefaultEdge aes = g.getEdge(sv,v); if(aes!=null){ EdgeSupport aess = edgeSupport.get(aes); aess.support = aess.support - 1; //if(aess.support<=(k-2)){ // q.add(aess); //} //reorder int s = aess.support; int ps = s+1; int startOf = initialLoction[ps-1]+1; int currentEdgeLocation = edgeSortedLocation.get(aess.e); DefaultEdge te = sortedEdge[startOf]; sortedEdge[startOf] = aess.e; sortedEdge[currentEdgeLocation] = te; i=-1; } } } et.et.put(es.e, k); g.removeEdge(es.e); System.out.println("edge size"+g.edgeSet().size()); svn.clear(); tvn.clear(); } } } if(g.edgeSet().size()!=0){ k++; //System.out.println("trussness: "+k); } } /* //ArrayList<DefaultEdge> el = new ArrayList<>(); // now q contains some edge with support less than 3 while(g.edgeSet().size()!=0){ // while(q.isEmpty()!=true){ EdgeSupport es = q.poll(); //get edge source and target sv = g.getEdgeSource(es.e); tv = g.getEdgeTarget(es.e); svn.addAll(ni.neighborsOf(sv)); tvn.addAll(ni.neighborsOf(tv)); svn.retainAll(tvn); //get edges for(Vertex v:svn){ DefaultEdge aes = g.getEdge(sv,v); if(aes!=null){ EdgeSupport aess = edgeSupport.get(aes); aess.support = aess.support - 1; //if(aess.support<=(k-2)){ // q.add(aess); //} } DefaultEdge aet = g.getEdge(tv, v); if(aet!=null){ EdgeSupport aets = edgeSupport.get(aet); aets.support = aets.support - 1; //if(aets.support<=(k-2)){ // q.add(aets); //} } } et.et.put(es.e, k); g.removeEdge(es.e); //now the edge trusness can be stored. svn.clear(); tvn.clear(); //break; } //update the queue put all edges, that have support less than k, into the queue //current implementation is not efficient, it iterates all remaining edge in the graph if(g.edgeSet().size()!=0){ k++; } for(DefaultEdge e:g.edgeSet()){ EdgeSupport es = edgeSupport.get(e); if(es.support <=(k-2)){ q.add(es); } } } /* System.out.println(et.et.size()); Iterator<Map.Entry<DefaultEdge, Integer> > i = et.et.entrySet().iterator(); while(i.hasNext()){ Map.Entry<DefaultEdge, Integer> m = i.next(); System.out.println(m.getKey()+"'s truness is:"+m.getValue()); } */ } }
src/main/java/alg/TrussDecomposition.java
package alg; import java.util.ArrayList; import java.util.Hashtable; import java.util.Iterator; import java.util.Map; import java.util.Queue; import java.util.Set; import java.util.concurrent.LinkedBlockingQueue; import jgraphtResearch.Vertex; import org.jgrapht.UndirectedGraph; import org.jgrapht.alg.NeighborIndex; import org.jgrapht.graph.DefaultEdge; import ds.EdgeSupport; import ds.EdgeTrussness; /** * After calling trussDecomposition, the graph must be reloaded * @author luchen * */ public class TrussDecomposition { public UndirectedGraph<Vertex, DefaultEdge> g; public EdgeTrussness et; public TrussDecomposition(UndirectedGraph<Vertex, DefaultEdge> g){ this.g = g; et = new EdgeTrussness(); } /** * * no bug left, only may have performance issues * */ public void trussDecomposition(){ Hashtable<DefaultEdge, EdgeSupport> edgeSupport = new Hashtable<>(); NeighborIndex<Vertex, DefaultEdge> ni = new NeighborIndex<>(g); //supportComputation(edgeSupport,ni); Iterator<Map.Entry<DefaultEdge, EdgeSupport> > isz = edgeSupport.entrySet().iterator(); while(isz.hasNext()){ Map.Entry<DefaultEdge, EdgeSupport> m = isz.next(); System.out.println(m.getKey()+"support: "+m.getValue().support); } int k = 0; int j = k-2; while(g.edgeSet().size()!=0){ removeUnsupportedEdges(edgeSupport,ni,j); k++; j=k-2; } Iterator<Map.Entry<DefaultEdge, Integer> > i = et.et.entrySet().iterator(); while(i.hasNext()){ Map.Entry<DefaultEdge, Integer> m = i.next(); System.out.println(m.getKey()+"'s trussness is:"+m.getValue()); } System.out.println(et.et.size()); System.out.println(g); /* * debug: pass */ } //!!!!!!!!!!! neighbor index must be recalculated during the graph update private void removeUnsupportedEdges(Hashtable<DefaultEdge, EdgeSupport> esl,NeighborIndex<Vertex, DefaultEdge> ni,int j){ //support of each edge has been calculated //ni = new NeighborIndex<>(g); Queue<EdgeSupport> q = new LinkedBlockingQueue<>(); //for all edges less than j are removed and put them in to a queue /* Iterator<Map.Entry<DefaultEdge, EdgeSupport> > isz = es.entrySet().iterator(); while(isz.hasNext()){ Map.Entry<DefaultEdge, EdgeSupport> m = isz.next(); if(m.getValue().support<j){ //added it into q q.add(m.getValue()); //remove it from g g.removeEdge(m.getValue().e); //ni = new NeighborIndex<>(g); } } */ Set<DefaultEdge> edges = g.edgeSet(); ArrayList<DefaultEdge> edgeList = new ArrayList<>(edges); Vertex sv; Vertex tv; ArrayList<Vertex> svn = new ArrayList<>(); ArrayList<Vertex> tvn = new ArrayList<>(); Iterator<DefaultEdge> ide = edgeList.iterator(); while(ide.hasNext()){ //for(DefaultEdge e:edges){ ni = new NeighborIndex<>(g); DefaultEdge e = ide.next(); sv = g.getEdgeSource(e); tv = g.getEdgeTarget(e); svn.addAll(ni.neighborsOf(sv)); tvn.addAll(ni.neighborsOf(tv)); svn.retainAll(tvn); int support = svn.size(); //System.out.println(support); if(support<j){ g.removeEdge(e); ni = new NeighborIndex<>(g); }else{ EdgeSupport es = new EdgeSupport(); es.support = support; es.e = e; esl.put(e, es); } svn.clear(); tvn.clear(); } ni = new NeighborIndex<>(g); while(q.isEmpty()!=true){ ni = new NeighborIndex<>(g); EdgeSupport ces = q.poll(); //get edge source and target sv = g.getEdgeSource(ces.e); tv = g.getEdgeTarget(ces.e); svn.addAll(ni.neighborsOf(sv)); tvn.addAll(ni.neighborsOf(tv)); svn.retainAll(tvn); for(Vertex v:svn){ DefaultEdge aes = g.getEdge(sv,v); if(aes!=null){ EdgeSupport aess = esl.get(aes); aess.support = aess.support - 1; if(aess.support<j){ q.add(aess); g.removeEdge(aess.e); //ni = new NeighborIndex<>(g); } } DefaultEdge aet = g.getEdge(tv,v); if(aet!=null){ EdgeSupport aets = esl.get(aet); aets.support = aets.support - 1; if(aets.support<j){ q.add(aets); g.removeEdge(aets.e); //ni = new NeighborIndex<>(g); } } } svn.clear(); tvn.clear(); } //for all edges that currently in the graph, they should all have trussness of j edges = g.edgeSet(); for(DefaultEdge e:edges){ et.et.put(e, j+2); } } private void supportComputation(Hashtable<DefaultEdge, EdgeSupport> esl,NeighborIndex<Vertex, DefaultEdge> ni){ Set<DefaultEdge> edges = g.edgeSet(); Vertex sv; Vertex tv; ArrayList<Vertex> svn = new ArrayList<>(); ArrayList<Vertex> tvn = new ArrayList<>(); for(DefaultEdge e:edges){ sv = g.getEdgeSource(e); tv = g.getEdgeTarget(e); svn.addAll(ni.neighborsOf(sv)); tvn.addAll(ni.neighborsOf(tv)); svn.retainAll(tvn); int support = svn.size(); EdgeSupport es = new EdgeSupport(); es.support = support; es.e = e; esl.put(e, es); svn.clear(); tvn.clear(); } } public void trussDecomposition_workable(){ int k = 3; Set<DefaultEdge> edges = g.edgeSet(); NeighborIndex<Vertex, DefaultEdge> ni = new NeighborIndex<>(g); Hashtable<DefaultEdge, EdgeSupport> edgeSupport = new Hashtable<>(); Queue<EdgeSupport> q = new LinkedBlockingQueue<>(); Vertex sv; Vertex tv; ArrayList<Vertex> svn = new ArrayList<>(); ArrayList<Vertex> tvn = new ArrayList<>(); //initial edge support for(DefaultEdge e:edges){ //computes support sv = g.getEdgeSource(e); tv = g.getEdgeTarget(e); svn.addAll(ni.neighborsOf(sv)); tvn.addAll(ni.neighborsOf(tv)); svn.retainAll(tvn); int support = svn.size(); EdgeSupport es = new EdgeSupport(); es.support = support; es.e = e; edgeSupport.put(e, es); svn.clear(); tvn.clear(); } //now edge support are calculated //clean up edges with support of 0 Iterator<Map.Entry<DefaultEdge, EdgeSupport> > is = edgeSupport.entrySet().iterator(); while(is.hasNext()){ Map.Entry<DefaultEdge, EdgeSupport> m = is.next(); if(m.getValue().support==0){ g.removeEdge(m.getValue().e); } } for(DefaultEdge e:g.edgeSet()){ EdgeSupport es = edgeSupport.get(e); if(es.support <=(k-2)){ q.add(es); } } Iterator<Map.Entry<DefaultEdge, EdgeSupport> > isz = edgeSupport.entrySet().iterator(); while(isz.hasNext()){ Map.Entry<DefaultEdge, EdgeSupport> m = isz.next(); System.out.println(m.getKey()+"support: "+m.getValue().support); } //compute trussness while(g.edgeSet().size()!=0){ while(q.isEmpty()!=true){ EdgeSupport es = q.poll(); //get edge source and target sv = g.getEdgeSource(es.e); tv = g.getEdgeTarget(es.e); svn.addAll(ni.neighborsOf(sv)); tvn.addAll(ni.neighborsOf(tv)); svn.retainAll(tvn); //get edges for(Vertex v:svn){ DefaultEdge aes = g.getEdge(sv,v); if(aes!=null){ EdgeSupport aess = edgeSupport.get(aes); aess.support = aess.support - 1; //do not know why, but it works //according to k-truss definition if(aess.support < (k-2)){ if(q.contains(aess)!=true){ q.add(aess); } } } DefaultEdge aet = g.getEdge(tv, v); if(aet!=null){ EdgeSupport aets = edgeSupport.get(aet); aets.support = aets.support - 1; //do not know why, but it works //according to k-truss definition if(aets.support < (k-2)){ if(q.contains(aets)!=true){ q.add(aets); } } } } et.et.put(es.e, k); g.removeEdge(es.e); svn.clear(); tvn.clear(); } if(g.edgeSet().size()!=0){ k++; //System.out.println("trussness: "+k); for(DefaultEdge e:g.edgeSet()){ EdgeSupport es = edgeSupport.get(e); if(es.support <= (k-2)){ if(q.contains(es)!=true){ q.add(es); } } } } } System.out.println(et.et.size()); Iterator<Map.Entry<DefaultEdge, Integer> > i = et.et.entrySet().iterator(); while(i.hasNext()){ Map.Entry<DefaultEdge, Integer> m = i.next(); System.out.println(m.getKey()+"'s trussness is:"+m.getValue()); } } public void trussDecompositionAdv(){ int k = 2; Set<DefaultEdge> edges = g.edgeSet(); NeighborIndex<Vertex, DefaultEdge> ni = new NeighborIndex<>(g); Hashtable<DefaultEdge, EdgeSupport> edgeSupport = new Hashtable<>(); //setup a queue to store edges that have number of support less than k Queue<EdgeSupport> q = new LinkedBlockingQueue<>(); //reducing creations of variable Vertex sv; Vertex tv; ArrayList<Vertex> svn = new ArrayList<>(); ArrayList<Vertex> tvn = new ArrayList<>(); //number of edge int noe = g.edgeSet().size(); //number of maximal support int noms = noe-2; int [] supportSpace = new int [noe-2]; for(DefaultEdge e:edges){ //computes support sv = g.getEdgeSource(e); tv = g.getEdgeTarget(e); svn.addAll(ni.neighborsOf(sv)); tvn.addAll(ni.neighborsOf(tv)); //= ni.neighborsOf(sv); //= ni.neighborsOf(tv); /* Testing * System.out.println(svn.size()); System.out.println(tvn.size()); System.out.println(ni.neighborsOf(sv)); System.out.println(ni.neighborsOf(tv));*/ svn.retainAll(tvn); int support = svn.size(); EdgeSupport es = new EdgeSupport(); es.support = support; es.e = e; //great increase the space for the current support number to +1 supportSpace[support]++; edgeSupport.put(e, es); /* Testing * System.out.println(e+" support is :"+support); System.out.println(svn.size()); System.out.println(tvn.size()); System.out.println(ni.neighborsOf(sv)); System.out.println(ni.neighborsOf(tv));*/ /* * Clear up */ svn.clear(); tvn.clear(); } //good sort!!!! //compute start location for each support number int l = 0; //initial location //key: number of support, value location in the sorted array int [] initialLoction = new int [noe-1]; initialLoction[0] =0; for(int i=1; i<supportSpace.length;i++){ initialLoction[i]=initialLoction[i-1]+supportSpace[i-1]; } /* for(int i=0; i<supportSpace.length;i++){ System.out.println(i+":"+initialLoction[i]); } */ DefaultEdge [] sortedEdge = new DefaultEdge [noe]; //hash table for sotre location Hashtable<DefaultEdge, Integer> edgeSortedLocation = new Hashtable<>(); //iterate the edge Iterator<Map.Entry<DefaultEdge, EdgeSupport> > isz = edgeSupport.entrySet().iterator(); while(isz.hasNext()){ Map.Entry<DefaultEdge, EdgeSupport> m = isz.next(); //put edge into a array sortedEdge[initialLoction[m.getValue().support]] = m.getValue().e; edgeSortedLocation.put(m.getValue().e, initialLoction[m.getValue().support]); //recorder location information using a hash table initialLoction[m.getValue().support]++; } /* *tested for(int i=0;i<noe;i++){ System.out.println(sortedEdge[i]+" support is: "+ edgeSupport.get(sortedEdge[i]).support); } */ //now the end position of support k should be initialLoction[m.getValue().support]-- for(int i=1; i<supportSpace.length;i++){ initialLoction[i]--; } //System.out.println(initialLoction[2]+","+supportSpace[2]); //now the initialLocation store the end location /* System.out.println("*****"); for(int i=1; i<supportSpace.length;i++){ System.out.println(i+":"+initialLoction[i]); } */ //System.out.println(q.size()); /* * end of compute support of each edge */ /* * debug edge support */ /* Iterator<Map.Entry<DefaultEdge, EdgeSupport> > isz = edgeSupport.entrySet().iterator(); while(isz.hasNext()){ Map.Entry<DefaultEdge, EdgeSupport> m = isz.next(); System.out.println(m.getKey()+"support: "+m.getValue().support); } */ Iterator<Map.Entry<DefaultEdge, EdgeSupport> > is = edgeSupport.entrySet().iterator(); while(is.hasNext()){ Map.Entry<DefaultEdge, EdgeSupport> m = is.next(); if(m.getValue().support==0){ g.removeEdge(m.getValue().e); } } //now the all edges has been sorted according to their support number in sortedEdge //the end location of edge with support number of k is in initialLoction[k] //the number of edges with support number of k is in supportSpace[k] // while(g.edgeSet().size()!=0){ for(int i=0;i<noe;i++){ DefaultEdge lowestSupportE = sortedEdge[i]; if(lowestSupportE!=null){ EdgeSupport es = edgeSupport.get(lowestSupportE); if(es.support<=k-2){ sv = g.getEdgeSource(es.e); tv = g.getEdgeTarget(es.e); svn.addAll(ni.neighborsOf(sv)); tvn.addAll(ni.neighborsOf(tv)); svn.retainAll(tvn); System.out.println(es.e); if(svn.size()<=tvn.size()){ for(Vertex v:svn){ DefaultEdge aes = g.getEdge(sv,v); if(aes!=null){ EdgeSupport aess = edgeSupport.get(aes); aess.support = aess.support - 1; //if(aess.support<=(k-2)){ // q.add(aess); //} //reorder int s = aess.support; System.out.println(s); int ps = s+1; int startOf = initialLoction[ps-1]+1; int currentEdgeLocation = edgeSortedLocation.get(aess.e); DefaultEdge te = sortedEdge[startOf]; sortedEdge[startOf] = aess.e; sortedEdge[currentEdgeLocation] = te; i=-1; } DefaultEdge aet = g.getEdge(tv, v); if(aet!=null){ EdgeSupport aets = edgeSupport.get(aet); aets.support = aets.support - 1; //if(aets.support<=(k-2)){ // q.add(aets); //} //reorder int s = aets.support; int ps = s+1; int startOf = initialLoction[ps-1]+1; int currentEdgeLocation = edgeSortedLocation.get(aets.e); DefaultEdge te = sortedEdge[startOf]; sortedEdge[startOf] = aets.e; sortedEdge[currentEdgeLocation] = te; i=-1; /* for(int j=0;j<noe;j++){ System.out.println(j+":"+sortedEdge[j]); }*/ } } }else{ for(Vertex v:svn){ DefaultEdge aet = g.getEdge(tv, v); if(aet!=null){ EdgeSupport aets = edgeSupport.get(aet); aets.support = aets.support - 1; //if(aets.support<=(k-2)){ // q.add(aets); //} //reorder int s = aets.support; int ps = s+1; int startOf = initialLoction[ps-1]+1; int currentEdgeLocation = edgeSortedLocation.get(aets.e); DefaultEdge te = sortedEdge[startOf]; sortedEdge[startOf] = aets.e; sortedEdge[currentEdgeLocation] = te; i=-1; } DefaultEdge aes = g.getEdge(sv,v); if(aes!=null){ EdgeSupport aess = edgeSupport.get(aes); aess.support = aess.support - 1; //if(aess.support<=(k-2)){ // q.add(aess); //} //reorder int s = aess.support; int ps = s+1; int startOf = initialLoction[ps-1]+1; int currentEdgeLocation = edgeSortedLocation.get(aess.e); DefaultEdge te = sortedEdge[startOf]; sortedEdge[startOf] = aess.e; sortedEdge[currentEdgeLocation] = te; i=-1; } } } et.et.put(es.e, k); g.removeEdge(es.e); System.out.println("edge size"+g.edgeSet().size()); svn.clear(); tvn.clear(); } } } if(g.edgeSet().size()!=0){ k++; //System.out.println("trussness: "+k); } } /* //ArrayList<DefaultEdge> el = new ArrayList<>(); // now q contains some edge with support less than 3 while(g.edgeSet().size()!=0){ // while(q.isEmpty()!=true){ EdgeSupport es = q.poll(); //get edge source and target sv = g.getEdgeSource(es.e); tv = g.getEdgeTarget(es.e); svn.addAll(ni.neighborsOf(sv)); tvn.addAll(ni.neighborsOf(tv)); svn.retainAll(tvn); //get edges for(Vertex v:svn){ DefaultEdge aes = g.getEdge(sv,v); if(aes!=null){ EdgeSupport aess = edgeSupport.get(aes); aess.support = aess.support - 1; //if(aess.support<=(k-2)){ // q.add(aess); //} } DefaultEdge aet = g.getEdge(tv, v); if(aet!=null){ EdgeSupport aets = edgeSupport.get(aet); aets.support = aets.support - 1; //if(aets.support<=(k-2)){ // q.add(aets); //} } } et.et.put(es.e, k); g.removeEdge(es.e); //now the edge trusness can be stored. svn.clear(); tvn.clear(); //break; } //update the queue put all edges, that have support less than k, into the queue //current implementation is not efficient, it iterates all remaining edge in the graph if(g.edgeSet().size()!=0){ k++; } for(DefaultEdge e:g.edgeSet()){ EdgeSupport es = edgeSupport.get(e); if(es.support <=(k-2)){ q.add(es); } } } /* System.out.println(et.et.size()); Iterator<Map.Entry<DefaultEdge, Integer> > i = et.et.entrySet().iterator(); while(i.hasNext()){ Map.Entry<DefaultEdge, Integer> m = i.next(); System.out.println(m.getKey()+"'s truness is:"+m.getValue()); } */ } }
test commit2
src/main/java/alg/TrussDecomposition.java
test commit2
<ide><path>rc/main/java/alg/TrussDecomposition.java <ide> <ide> /** <ide> * After calling trussDecomposition, the graph must be reloaded <add> * Moved to git hub <ide> * @author luchen <ide> * <ide> */ <ide> } <ide> <ide> <del> int k = 0; <add> int k = 2; <ide> int j = k-2; <ide> <ide> while(g.edgeSet().size()!=0){
Java
apache-2.0
24ec59b4739f17b1b0568e20e1da8dc57a84e7f5
0
fengshao0907/HikariJSON,brettwooldridge/HikariJSON
package com.zaxxer.hikari.json.serializer; import static com.zaxxer.hikari.json.util.Utf8Utils.fastTrackAsciiDecode; import static com.zaxxer.hikari.json.util.Utf8Utils.findEndQuote; import static com.zaxxer.hikari.json.util.Utf8Utils.findEndQuoteUTF8; import static com.zaxxer.hikari.json.util.Utf8Utils.seekBackUtf8Boundary; import java.io.IOException; import java.io.InputStream; import java.util.Arrays; import java.util.Collection; import java.util.HashSet; import sun.misc.Unsafe; import com.zaxxer.hikari.json.JsonFactory.Option; import com.zaxxer.hikari.json.ObjectMapper; import com.zaxxer.hikari.json.util.MutableBoolean; import com.zaxxer.hikari.json.util.Phield; import com.zaxxer.hikari.json.util.Types; import com.zaxxer.hikari.json.util.UnsafeHelper; @SuppressWarnings("restriction") public final class BaseJsonParser implements ObjectMapper { protected static final char CR = '\r'; protected static final char TAB = '\t'; protected static final char SPACE = ' '; protected static final char QUOTE = '"'; protected static final char COLON = ':'; protected static final char COMMA = ','; protected static final char NEWLINE = '\n'; protected static final char OPEN_CURLY = '{'; protected static final char CLOSE_CURLY = '}'; protected static final char OPEN_BRACKET = '['; protected static final char CLOSE_BRACKET = ']'; private static final Unsafe UNSAFE = UnsafeHelper.getUnsafe(); private final boolean isAsciiMembers; private final boolean isAsciiValues; private final int BUFFER_SIZE = 16384; protected InputStream source; protected byte[] byteBuffer; protected int bufferLimit; public BaseJsonParser(Option... options) { byteBuffer = new byte[BUFFER_SIZE]; HashSet<Option> set = new HashSet<>(Arrays.asList(options)); isAsciiMembers = set.contains(Option.MEMBERS_ASCII); isAsciiValues = set.contains(Option.VALUES_ASCII); } @Override @SuppressWarnings("unchecked") final public <T> T readValue(final InputStream src, final Class<T> valueType) { source = src; Context context = new Context(valueType); context.createInstance(); parseObject(0, context); return (T) context.target; } private int parseObject(int bufferIndex, final Context context) { do { if (bufferIndex == bufferLimit && (bufferIndex = fillBuffer()) == -1) { throw new RuntimeException("Insufficent data."); } switch (byteBuffer[bufferIndex]) { case OPEN_CURLY: bufferIndex = parseMembers(bufferIndex + 1, context); continue; case CLOSE_CURLY: return bufferIndex + 1; default: bufferIndex++; } } while (true); } private int parseMembers(int bufferIndex, final Context context) { int limit = bufferLimit; do { for (final byte[] buffer = byteBuffer; bufferIndex < limit && buffer[bufferIndex] <= SPACE; bufferIndex++) ; // skip whitespace if (bufferIndex == limit) { if ((bufferIndex = fillBuffer()) == -1) { throw new RuntimeException("Insufficent data."); } limit = bufferLimit; } switch (byteBuffer[bufferIndex]) { case QUOTE: bufferIndex = parseMember(bufferIndex, context); break; case CLOSE_CURLY: return bufferIndex; default: bufferIndex++; } } while (true); } private int parseMember(int bufferIndex, final Context context) { // Parse the member name bufferIndex = (isAsciiMembers ? parseAsciiString(bufferIndex + 1, context) : parseString(bufferIndex + 1, context)); // Next character better be a colon do { if (bufferIndex == bufferLimit && (bufferIndex = fillBuffer()) == -1) { throw new RuntimeException("Insufficent data. Expecting colon after member."); } if (byteBuffer[bufferIndex++] == COLON) { break; } } while (true); // Now the value final Phield phield = context.clazz.getPhield(context.stringHolder); context.holderType = phield.type; if (phield.type == Types.OBJECT) { final Context nextContext = new Context(phield); nextContext.createInstance(); context.objectHolder = nextContext.target; bufferIndex = parseValue(bufferIndex, context, nextContext); } else { bufferIndex = parseValue(bufferIndex, context, null); } setMember(phield, context); return bufferIndex; } private int parseValue(int bufferIndex, final Context context, final Context nextContext) { int limit = bufferLimit; do { for (final byte[] buffer = byteBuffer; bufferIndex < limit; bufferIndex++) { final int b = buffer[bufferIndex]; if (b <= SPACE) { continue; } switch (b) { case QUOTE: return (isAsciiValues ? parseAsciiString(bufferIndex + 1, context) : parseString(bufferIndex + 1, context)); case 't': context.booleanHolder = true; return bufferIndex + 1; case 'f': context.booleanHolder = false; return bufferIndex + 1; case 'n': context.objectHolder = null; return bufferIndex + 1; case '-': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': return ((context.holderType & Types.INTEGRAL_TYPE) > 0) ? parseInteger(bufferIndex, context) : parseDecimal(bufferIndex, context); case OPEN_CURLY: return parseObject(bufferIndex, nextContext); case OPEN_BRACKET: return parseArray(bufferIndex + 1, nextContext); default: break; } limit = bufferLimit; } if (bufferIndex == limit && ((bufferIndex = fillBuffer()) == -1)) { throw new RuntimeException("Insufficent data."); } } while (true); } private int parseArray(int bufferIndex, final Context context) { int limit = bufferLimit; do { for (final byte[] buffer = byteBuffer; bufferIndex < limit && buffer[bufferIndex] <= SPACE; bufferIndex++) ; // skip whitespace if (bufferIndex == limit) { if ((bufferIndex = fillBuffer()) == -1) { throw new RuntimeException("Insufficent data."); } limit = bufferLimit; } switch (byteBuffer[bufferIndex]) { case CLOSE_BRACKET: return bufferIndex + 1; default: Context nextContext = context; final Phield phield = context.phield; if (phield != null) { if (phield.isCollection || phield.isArray) { nextContext = new Context(phield.getCollectionParameterClazz1()); nextContext.createInstance(); } } bufferIndex = parseValue(bufferIndex, context, nextContext); @SuppressWarnings("unchecked") Collection<Object> collection = ((Collection<Object>) context.target); collection.add(nextContext.target); } } while (true); } private int parseString(int bufferIndex, final Context context) { try { final int startIndex = bufferIndex; do { final MutableBoolean utf8Detected = new MutableBoolean(); final int newIndex = findEndQuoteUTF8(byteBuffer, bufferIndex, utf8Detected); if (newIndex > 0) { if (utf8Detected.bool) { context.stringHolder = new String(byteBuffer, startIndex, (newIndex - startIndex), "UTF-8"); } else { context.stringHolder = fastTrackAsciiDecode(byteBuffer, startIndex, (newIndex - startIndex)); } return newIndex + 1; } final byte[] newArray = new byte[bufferLimit * 2]; System.arraycopy(byteBuffer, 0, newArray, 0, byteBuffer.length); byteBuffer = newArray; int read = source.read(byteBuffer, bufferIndex, byteBuffer.length - bufferIndex); if (read < 0) { throw new RuntimeException("Insufficent data."); } bufferIndex = seekBackUtf8Boundary(byteBuffer, bufferIndex); } while (true); } catch (Exception e) { throw new RuntimeException(); } } private int parseAsciiString(int bufferIndex, final Context context) { try { final int startIndex = bufferIndex; do { final int newIndex = findEndQuote(byteBuffer, bufferIndex); if (newIndex > 0) { context.stringHolder = fastTrackAsciiDecode(byteBuffer, startIndex, (newIndex - startIndex)); return newIndex + 1; } final byte[] newArray = new byte[bufferLimit * 2]; System.arraycopy(byteBuffer, 0, newArray, 0, byteBuffer.length); byteBuffer = newArray; int read = source.read(byteBuffer, bufferIndex, byteBuffer.length - bufferIndex); if (read < 0) { throw new RuntimeException("Insufficent data."); } bufferIndex = seekBackUtf8Boundary(byteBuffer, bufferIndex); } while (true); } catch (Exception e) { throw new RuntimeException(); } } private int parseInteger(int bufferIndex, Context context) { boolean neg = (byteBuffer[bufferIndex] == '-'); if (neg) { ++bufferIndex; } int limit = bufferLimit; // integer part long part = 0; outer1: while (true) { try { for (final byte[] buffer = byteBuffer; bufferIndex < limit; bufferIndex++) { final int b = buffer[bufferIndex]; if (b >= '0' && b <= '9') { part = part * 10 + (b - '0'); } else { break outer1; } } limit = bufferLimit; } finally { if (bufferIndex == limit && ((bufferIndex = fillBuffer()) == -1)) { throw new RuntimeException("Insufficent data during number parsing."); } } } if (neg) { part *= -1; } context.longHolder = part; return bufferIndex; } private int parseDecimal(int bufferIndex, Context context) { double d = 0.0; // value long part = 0; // the current part (int, float and sci parts of the number) boolean neg = (byteBuffer[bufferIndex] == '-'); if (neg) { ++bufferIndex; } // integer part long shift = 0; outer1: while (true) { final int limit = bufferLimit; try { for (final byte[] buffer = byteBuffer; bufferIndex < limit; bufferIndex++) { final int b = buffer[bufferIndex]; if (b >= '0' && b <= '9') { shift *= 10; part = part * 10 + (b - '0'); } else if (b == '.') { shift = 1; } else { break outer1; } } } finally { if (bufferIndex == limit && ((bufferIndex = fillBuffer()) == -1)) { throw new RuntimeException("Insufficent data during number parsing."); } } } if (neg) { part *= -1; } d = shift != 0 ? (double)part / (double)shift : part; // scientific part if (byteBuffer[bufferIndex] == 'e' || byteBuffer[bufferIndex] == 'E') { ++bufferIndex; part = 0; neg = byteBuffer[bufferIndex] == '-'; bufferIndex = neg ? ++bufferIndex : bufferIndex; outer1: while (true) { final int limit = bufferLimit; for (final byte[] buffer = byteBuffer; bufferIndex < limit; bufferIndex++) { final int b = buffer[bufferIndex]; if (b >= '0' && b <= '9') { part = part * 10 + (b - '0'); continue; } break outer1; } if (bufferIndex == limit && ((bufferIndex = fillBuffer()) == -1)) { throw new RuntimeException("Insufficent data during number parsing."); } } d = (neg) ? d / (double)Math.pow(10, part) : d * (double)Math.pow(10, part); } context.doubleHolder = d; return bufferIndex; } private void setMember(final Phield phield, final Context context) { try { switch (phield.type) { case Types.INT: UNSAFE.putInt(context.target, phield.fieldOffset, (int) context.longHolder); break; case Types.FLOAT: UNSAFE.putFloat(context.target, phield.fieldOffset, (float) context.doubleHolder); break; case Types.DOUBLE: UNSAFE.putDouble(context.target, phield.fieldOffset, context.doubleHolder); break; case Types.STRING: UNSAFE.putObject(context.target, phield.fieldOffset, context.stringHolder); break; case Types.OBJECT: UNSAFE.putObject(context.target, phield.fieldOffset, (context.objectHolder == Void.TYPE ? null : context.objectHolder)); break; } } catch (SecurityException | IllegalArgumentException e) { throw new RuntimeException(e); } } final protected int fillBuffer() { try { int read = source.read(byteBuffer); if (read > 0) { bufferLimit = read; return 0; } return -1; } catch (IOException io) { throw new RuntimeException(io); } } }
src/main/java/com/zaxxer/hikari/json/serializer/BaseJsonParser.java
package com.zaxxer.hikari.json.serializer; import static com.zaxxer.hikari.json.util.Utf8Utils.fastTrackAsciiDecode; import static com.zaxxer.hikari.json.util.Utf8Utils.findEndQuote; import static com.zaxxer.hikari.json.util.Utf8Utils.findEndQuoteUTF8; import static com.zaxxer.hikari.json.util.Utf8Utils.seekBackUtf8Boundary; import java.io.IOException; import java.io.InputStream; import java.util.Arrays; import java.util.Collection; import java.util.HashSet; import sun.misc.Unsafe; import com.zaxxer.hikari.json.JsonFactory.Option; import com.zaxxer.hikari.json.ObjectMapper; import com.zaxxer.hikari.json.util.MutableBoolean; import com.zaxxer.hikari.json.util.Phield; import com.zaxxer.hikari.json.util.Types; import com.zaxxer.hikari.json.util.UnsafeHelper; @SuppressWarnings("restriction") public final class BaseJsonParser implements ObjectMapper { protected static final char CR = '\r'; protected static final char TAB = '\t'; protected static final char SPACE = ' '; protected static final char QUOTE = '"'; protected static final char COLON = ':'; protected static final char COMMA = ','; protected static final char NEWLINE = '\n'; protected static final char OPEN_CURLY = '{'; protected static final char CLOSE_CURLY = '}'; protected static final char OPEN_BRACKET = '['; protected static final char CLOSE_BRACKET = ']'; private static final Unsafe UNSAFE = UnsafeHelper.getUnsafe(); private final boolean isAsciiMembers; private final boolean isAsciiValues; private final int BUFFER_SIZE = 16384; protected InputStream source; protected byte[] byteBuffer; protected int bufferLimit; public BaseJsonParser(Option... options) { byteBuffer = new byte[BUFFER_SIZE]; HashSet<Option> set = new HashSet<>(Arrays.asList(options)); isAsciiMembers = set.contains(Option.MEMBERS_ASCII); isAsciiValues = set.contains(Option.VALUES_ASCII); } @Override @SuppressWarnings("unchecked") final public <T> T readValue(final InputStream src, final Class<T> valueType) { source = src; Context context = new Context(valueType); context.createInstance(); parseObject(0, context); return (T) context.target; } private int parseObject(int bufferIndex, final Context context) { do { if (bufferIndex == bufferLimit && (bufferIndex = fillBuffer()) == -1) { throw new RuntimeException("Insufficent data."); } switch (byteBuffer[bufferIndex]) { case OPEN_CURLY: bufferIndex = parseMembers(bufferIndex + 1, context); continue; case CLOSE_CURLY: return bufferIndex + 1; default: bufferIndex++; } } while (true); } private int parseMembers(int bufferIndex, final Context context) { do { final int limit = bufferLimit; for (final byte[] buffer = byteBuffer; bufferIndex < limit && buffer[bufferIndex] <= SPACE; bufferIndex++) ; // skip whitespace if (bufferIndex == limit) { if ((bufferIndex = fillBuffer()) == -1) { throw new RuntimeException("Insufficent data."); } } switch (byteBuffer[bufferIndex]) { case QUOTE: bufferIndex = parseMember(bufferIndex, context); break; case CLOSE_CURLY: return bufferIndex; default: bufferIndex++; } } while (true); } private int parseMember(int bufferIndex, final Context context) { // Parse the member name bufferIndex = (isAsciiMembers ? parseAsciiString(bufferIndex + 1, context) : parseString(bufferIndex + 1, context)); // Next character better be a colon do { if (bufferIndex == bufferLimit && (bufferIndex = fillBuffer()) == -1) { throw new RuntimeException("Insufficent data. Expecting colon after member."); } if (byteBuffer[bufferIndex++] == COLON) { break; } } while (true); // Now the value final Phield phield = context.clazz.getPhield(context.stringHolder); context.holderType = phield.type; if (phield.type == Types.OBJECT) { final Context nextContext = new Context(phield); nextContext.createInstance(); context.objectHolder = nextContext.target; bufferIndex = parseValue(bufferIndex, context, nextContext); } else { bufferIndex = parseValue(bufferIndex, context, null); } setMember(phield, context); return bufferIndex; } private int parseValue(int bufferIndex, final Context context, final Context nextContext) { do { final int limit = bufferLimit; for (final byte[] buffer = byteBuffer; bufferIndex < limit; bufferIndex++) { final int b = buffer[bufferIndex]; if (b <= SPACE) { continue; } switch (b) { case QUOTE: return (isAsciiValues ? parseAsciiString(bufferIndex + 1, context) : parseString(bufferIndex + 1, context)); case 't': context.booleanHolder = true; return bufferIndex + 1; case 'f': context.booleanHolder = false; return bufferIndex + 1; case 'n': context.objectHolder = null; return bufferIndex + 1; case '-': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': return ((context.holderType & Types.INTEGRAL_TYPE) > 0) ? parseInteger(bufferIndex, context) : parseDecimal(bufferIndex, context); case OPEN_CURLY: return parseObject(bufferIndex, nextContext); case OPEN_BRACKET: return parseArray(bufferIndex + 1, nextContext); default: break; } } if (bufferIndex == limit && ((bufferIndex = fillBuffer()) == -1)) { throw new RuntimeException("Insufficent data."); } } while (true); } private int parseArray(int bufferIndex, final Context context) { do { final int limit = bufferLimit; for (final byte[] buffer = byteBuffer; bufferIndex < limit && buffer[bufferIndex] <= SPACE; bufferIndex++) ; // skip whitespace if (bufferIndex == limit) { if ((bufferIndex = fillBuffer()) == -1) { throw new RuntimeException("Insufficent data."); } } switch (byteBuffer[bufferIndex]) { case CLOSE_BRACKET: return bufferIndex + 1; default: Context nextContext = context; final Phield phield = context.phield; if (phield != null) { if (phield.isCollection || phield.isArray) { nextContext = new Context(phield.getCollectionParameterClazz1()); nextContext.createInstance(); } } bufferIndex = parseValue(bufferIndex, context, nextContext); @SuppressWarnings("unchecked") Collection<Object> collection = ((Collection<Object>) context.target); collection.add(nextContext.target); } } while (true); } private int parseString(int bufferIndex, final Context context) { try { final int startIndex = bufferIndex; do { final MutableBoolean utf8Detected = new MutableBoolean(); final int newIndex = findEndQuoteUTF8(byteBuffer, bufferIndex, utf8Detected); if (newIndex > 0) { if (utf8Detected.bool) { context.stringHolder = new String(byteBuffer, startIndex, (newIndex - startIndex), "UTF-8"); } else { context.stringHolder = fastTrackAsciiDecode(byteBuffer, startIndex, (newIndex - startIndex)); } return newIndex + 1; } final byte[] newArray = new byte[bufferLimit * 2]; System.arraycopy(byteBuffer, 0, newArray, 0, byteBuffer.length); byteBuffer = newArray; int read = source.read(byteBuffer, bufferIndex, byteBuffer.length - bufferIndex); if (read < 0) { throw new RuntimeException("Insufficent data."); } bufferIndex = seekBackUtf8Boundary(byteBuffer, bufferIndex); } while (true); } catch (Exception e) { throw new RuntimeException(); } } private int parseAsciiString(int bufferIndex, final Context context) { try { final int startIndex = bufferIndex; do { final int newIndex = findEndQuote(byteBuffer, bufferIndex); if (newIndex > 0) { context.stringHolder = fastTrackAsciiDecode(byteBuffer, startIndex, (newIndex - startIndex)); return newIndex + 1; } final byte[] newArray = new byte[bufferLimit * 2]; System.arraycopy(byteBuffer, 0, newArray, 0, byteBuffer.length); byteBuffer = newArray; int read = source.read(byteBuffer, bufferIndex, byteBuffer.length - bufferIndex); if (read < 0) { throw new RuntimeException("Insufficent data."); } bufferIndex = seekBackUtf8Boundary(byteBuffer, bufferIndex); } while (true); } catch (Exception e) { throw new RuntimeException(); } } private int parseInteger(int bufferIndex, Context context) { boolean neg = (byteBuffer[bufferIndex] == '-'); if (neg) { ++bufferIndex; } // integer part long part = 0; outer1: while (true) { final int limit = bufferLimit; try { for (final byte[] buffer = byteBuffer; bufferIndex < limit; bufferIndex++) { final int b = buffer[bufferIndex]; if (b >= '0' && b <= '9') { part = part * 10 + (b - '0'); } else { break outer1; } } } finally { if (bufferIndex == limit && ((bufferIndex = fillBuffer()) == -1)) { throw new RuntimeException("Insufficent data during number parsing."); } } } if (neg) { part *= -1; } context.longHolder = part; return bufferIndex; } private int parseDecimal(int bufferIndex, Context context) { double d = 0.0; // value long part = 0; // the current part (int, float and sci parts of the number) boolean neg = (byteBuffer[bufferIndex] == '-'); if (neg) { ++bufferIndex; } // integer part long shift = 0; outer1: while (true) { final int limit = bufferLimit; try { for (final byte[] buffer = byteBuffer; bufferIndex < limit; bufferIndex++) { final int b = buffer[bufferIndex]; if (b >= '0' && b <= '9') { shift *= 10; part = part * 10 + (b - '0'); } else if (b == '.') { shift = 1; } else { break outer1; } } } finally { if (bufferIndex == limit && ((bufferIndex = fillBuffer()) == -1)) { throw new RuntimeException("Insufficent data during number parsing."); } } } if (neg) { part *= -1; } d = shift != 0 ? (double)part / (double)shift : part; // scientific part if (byteBuffer[bufferIndex] == 'e' || byteBuffer[bufferIndex] == 'E') { ++bufferIndex; part = 0; neg = byteBuffer[bufferIndex] == '-'; bufferIndex = neg ? ++bufferIndex : bufferIndex; outer1: while (true) { final int limit = bufferLimit; for (final byte[] buffer = byteBuffer; bufferIndex < limit; bufferIndex++) { final int b = buffer[bufferIndex]; if (b >= '0' && b <= '9') { part = part * 10 + (b - '0'); continue; } break outer1; } if (bufferIndex == limit && ((bufferIndex = fillBuffer()) == -1)) { throw new RuntimeException("Insufficent data during number parsing."); } } d = (neg) ? d / (double)Math.pow(10, part) : d * (double)Math.pow(10, part); } context.doubleHolder = d; return bufferIndex; } private void setMember(final Phield phield, final Context context) { try { switch (phield.type) { case Types.INT: UNSAFE.putInt(context.target, phield.fieldOffset, (int) context.longHolder); break; case Types.FLOAT: UNSAFE.putFloat(context.target, phield.fieldOffset, (float) context.doubleHolder); break; case Types.DOUBLE: UNSAFE.putDouble(context.target, phield.fieldOffset, context.doubleHolder); break; case Types.STRING: UNSAFE.putObject(context.target, phield.fieldOffset, context.stringHolder); break; case Types.OBJECT: UNSAFE.putObject(context.target, phield.fieldOffset, (context.objectHolder == Void.TYPE ? null : context.objectHolder)); break; } } catch (SecurityException | IllegalArgumentException e) { throw new RuntimeException(e); } } final protected int fillBuffer() { try { int read = source.read(byteBuffer); if (read > 0) { bufferLimit = read; return 0; } return -1; } catch (IOException io) { throw new RuntimeException(io); } } }
Rollback some tweaks that paradoxically slowed things down. Likely the JIT could not spot the intended optimization and actually chose a less efficient path.
src/main/java/com/zaxxer/hikari/json/serializer/BaseJsonParser.java
Rollback some tweaks that paradoxically slowed things down. Likely the JIT could not spot the intended optimization and actually chose a less efficient path.
<ide><path>rc/main/java/com/zaxxer/hikari/json/serializer/BaseJsonParser.java <ide> <ide> private int parseMembers(int bufferIndex, final Context context) <ide> { <add> int limit = bufferLimit; <ide> do { <del> final int limit = bufferLimit; <ide> for (final byte[] buffer = byteBuffer; bufferIndex < limit && buffer[bufferIndex] <= SPACE; bufferIndex++) <ide> ; // skip whitespace <ide> <ide> if ((bufferIndex = fillBuffer()) == -1) { <ide> throw new RuntimeException("Insufficent data."); <ide> } <add> limit = bufferLimit; <ide> } <ide> <ide> switch (byteBuffer[bufferIndex]) { <ide> <ide> private int parseValue(int bufferIndex, final Context context, final Context nextContext) <ide> { <del> <add> int limit = bufferLimit; <ide> do { <del> final int limit = bufferLimit; <ide> for (final byte[] buffer = byteBuffer; bufferIndex < limit; bufferIndex++) { <ide> <ide> final int b = buffer[bufferIndex]; <ide> default: <ide> break; <ide> } <add> limit = bufferLimit; <ide> } <ide> <ide> if (bufferIndex == limit && ((bufferIndex = fillBuffer()) == -1)) { <ide> <ide> private int parseArray(int bufferIndex, final Context context) <ide> { <add> int limit = bufferLimit; <ide> do { <del> final int limit = bufferLimit; <ide> for (final byte[] buffer = byteBuffer; bufferIndex < limit && buffer[bufferIndex] <= SPACE; bufferIndex++) <ide> ; // skip whitespace <ide> <ide> if ((bufferIndex = fillBuffer()) == -1) { <ide> throw new RuntimeException("Insufficent data."); <ide> } <add> limit = bufferLimit; <ide> } <ide> <ide> switch (byteBuffer[bufferIndex]) { <ide> ++bufferIndex; <ide> } <ide> <add> int limit = bufferLimit; <add> <ide> // integer part <ide> long part = 0; <ide> outer1: while (true) { <del> final int limit = bufferLimit; <ide> try { <ide> for (final byte[] buffer = byteBuffer; bufferIndex < limit; bufferIndex++) { <ide> final int b = buffer[bufferIndex]; <ide> break outer1; <ide> } <ide> } <add> limit = bufferLimit; <ide> } <ide> finally { <ide> if (bufferIndex == limit && ((bufferIndex = fillBuffer()) == -1)) {
Java
apache-2.0
9203845d134473205c384a1b2b10f6c23bc5aa1d
0
ThiagoGarciaAlves/intellij-community,ibinti/intellij-community,idea4bsd/idea4bsd,vvv1559/intellij-community,michaelgallacher/intellij-community,da1z/intellij-community,idea4bsd/idea4bsd,youdonghai/intellij-community,FHannes/intellij-community,idea4bsd/idea4bsd,youdonghai/intellij-community,idea4bsd/idea4bsd,FHannes/intellij-community,vvv1559/intellij-community,mglukhikh/intellij-community,hurricup/intellij-community,xfournet/intellij-community,ThiagoGarciaAlves/intellij-community,asedunov/intellij-community,ThiagoGarciaAlves/intellij-community,asedunov/intellij-community,signed/intellij-community,idea4bsd/idea4bsd,ibinti/intellij-community,ThiagoGarciaAlves/intellij-community,ibinti/intellij-community,fitermay/intellij-community,semonte/intellij-community,fitermay/intellij-community,da1z/intellij-community,asedunov/intellij-community,signed/intellij-community,mglukhikh/intellij-community,ibinti/intellij-community,ThiagoGarciaAlves/intellij-community,da1z/intellij-community,apixandru/intellij-community,ThiagoGarciaAlves/intellij-community,da1z/intellij-community,FHannes/intellij-community,xfournet/intellij-community,hurricup/intellij-community,FHannes/intellij-community,signed/intellij-community,asedunov/intellij-community,fitermay/intellij-community,hurricup/intellij-community,ThiagoGarciaAlves/intellij-community,fitermay/intellij-community,vvv1559/intellij-community,mglukhikh/intellij-community,ibinti/intellij-community,allotria/intellij-community,hurricup/intellij-community,FHannes/intellij-community,allotria/intellij-community,fitermay/intellij-community,mglukhikh/intellij-community,hurricup/intellij-community,asedunov/intellij-community,da1z/intellij-community,xfournet/intellij-community,ibinti/intellij-community,youdonghai/intellij-community,xfournet/intellij-community,apixandru/intellij-community,da1z/intellij-community,signed/intellij-community,mglukhikh/intellij-community,mglukhikh/intellij-community,signed/intellij-community,signed/intellij-community,hurricup/intellij-community,apixandru/intellij-community,xfournet/intellij-community,suncycheng/intellij-community,xfournet/intellij-community,ThiagoGarciaAlves/intellij-community,xfournet/intellij-community,hurricup/intellij-community,michaelgallacher/intellij-community,da1z/intellij-community,apixandru/intellij-community,michaelgallacher/intellij-community,youdonghai/intellij-community,youdonghai/intellij-community,semonte/intellij-community,semonte/intellij-community,suncycheng/intellij-community,mglukhikh/intellij-community,allotria/intellij-community,apixandru/intellij-community,xfournet/intellij-community,apixandru/intellij-community,suncycheng/intellij-community,signed/intellij-community,fitermay/intellij-community,ibinti/intellij-community,michaelgallacher/intellij-community,allotria/intellij-community,da1z/intellij-community,xfournet/intellij-community,semonte/intellij-community,vvv1559/intellij-community,hurricup/intellij-community,asedunov/intellij-community,apixandru/intellij-community,michaelgallacher/intellij-community,asedunov/intellij-community,fitermay/intellij-community,hurricup/intellij-community,apixandru/intellij-community,vvv1559/intellij-community,da1z/intellij-community,allotria/intellij-community,michaelgallacher/intellij-community,ibinti/intellij-community,youdonghai/intellij-community,signed/intellij-community,signed/intellij-community,xfournet/intellij-community,ibinti/intellij-community,FHannes/intellij-community,youdonghai/intellij-community,youdonghai/intellij-community,FHannes/intellij-community,FHannes/intellij-community,asedunov/intellij-community,semonte/intellij-community,idea4bsd/idea4bsd,allotria/intellij-community,idea4bsd/idea4bsd,hurricup/intellij-community,apixandru/intellij-community,suncycheng/intellij-community,ibinti/intellij-community,hurricup/intellij-community,allotria/intellij-community,da1z/intellij-community,michaelgallacher/intellij-community,idea4bsd/idea4bsd,allotria/intellij-community,hurricup/intellij-community,semonte/intellij-community,vvv1559/intellij-community,FHannes/intellij-community,semonte/intellij-community,mglukhikh/intellij-community,vvv1559/intellij-community,youdonghai/intellij-community,ThiagoGarciaAlves/intellij-community,signed/intellij-community,vvv1559/intellij-community,vvv1559/intellij-community,ThiagoGarciaAlves/intellij-community,ibinti/intellij-community,ThiagoGarciaAlves/intellij-community,semonte/intellij-community,da1z/intellij-community,semonte/intellij-community,suncycheng/intellij-community,idea4bsd/idea4bsd,ibinti/intellij-community,vvv1559/intellij-community,allotria/intellij-community,allotria/intellij-community,youdonghai/intellij-community,mglukhikh/intellij-community,suncycheng/intellij-community,hurricup/intellij-community,youdonghai/intellij-community,youdonghai/intellij-community,da1z/intellij-community,fitermay/intellij-community,fitermay/intellij-community,FHannes/intellij-community,da1z/intellij-community,suncycheng/intellij-community,ibinti/intellij-community,asedunov/intellij-community,michaelgallacher/intellij-community,idea4bsd/idea4bsd,suncycheng/intellij-community,xfournet/intellij-community,apixandru/intellij-community,vvv1559/intellij-community,youdonghai/intellij-community,idea4bsd/idea4bsd,allotria/intellij-community,vvv1559/intellij-community,apixandru/intellij-community,fitermay/intellij-community,apixandru/intellij-community,michaelgallacher/intellij-community,apixandru/intellij-community,asedunov/intellij-community,mglukhikh/intellij-community,michaelgallacher/intellij-community,mglukhikh/intellij-community,suncycheng/intellij-community,apixandru/intellij-community,signed/intellij-community,michaelgallacher/intellij-community,suncycheng/intellij-community,semonte/intellij-community,xfournet/intellij-community,signed/intellij-community,idea4bsd/idea4bsd,suncycheng/intellij-community,vvv1559/intellij-community,signed/intellij-community,FHannes/intellij-community,asedunov/intellij-community,semonte/intellij-community,ThiagoGarciaAlves/intellij-community,allotria/intellij-community,asedunov/intellij-community,fitermay/intellij-community,michaelgallacher/intellij-community,idea4bsd/idea4bsd,fitermay/intellij-community,xfournet/intellij-community,FHannes/intellij-community,fitermay/intellij-community,mglukhikh/intellij-community,asedunov/intellij-community,semonte/intellij-community,mglukhikh/intellij-community,allotria/intellij-community,FHannes/intellij-community,semonte/intellij-community,suncycheng/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.ui.components; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.util.Key; import com.intellij.openapi.util.SystemInfo; import com.intellij.openapi.util.registry.Registry; import com.intellij.openapi.wm.IdeGlassPane; import com.intellij.ui.Gray; import com.intellij.ui.IdeBorderFactory; import com.intellij.util.ArrayUtil; import com.intellij.util.ReflectionUtil; import com.intellij.util.ui.ButtonlessScrollBarUI; import com.intellij.util.ui.JBInsets; import com.intellij.util.ui.RegionPainter; import com.intellij.util.ui.UIUtil; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.swing.*; import javax.swing.border.Border; import javax.swing.border.LineBorder; import javax.swing.plaf.ScrollBarUI; import javax.swing.plaf.ScrollPaneUI; import javax.swing.plaf.UIResource; import javax.swing.plaf.basic.BasicScrollBarUI; import javax.swing.plaf.basic.BasicScrollPaneUI; import java.awt.*; import java.awt.event.InputEvent; import java.awt.event.MouseEvent; import java.awt.event.MouseWheelEvent; import java.awt.event.MouseWheelListener; import java.awt.geom.RoundRectangle2D; import java.awt.image.*; import java.lang.reflect.Field; public class JBScrollPane extends JScrollPane { /** * This key is used to specify which colors should use the scroll bars on the pane. * If a client property is set to {@code true} the bar's brightness * will be modified according to the view's background. * * @see UIUtil#putClientProperty * @see UIUtil#isUnderDarcula */ public static final Key<Boolean> BRIGHTNESS_FROM_VIEW = Key.create("JB_SCROLL_PANE_BRIGHTNESS_FROM_VIEW"); @Deprecated public static final RegionPainter<Float> TRACK_PAINTER = new AlphaPainter(.0f, .1f, Gray.x80); @Deprecated public static final RegionPainter<Float> TRACK_DARK_PAINTER = new AlphaPainter(.0f, .1f, Gray.x80); @Deprecated public static final RegionPainter<Float> THUMB_PAINTER = new ProtectedPainter( new DefaultThumbPainter(new SubtractThumbPainter(.25f, .15f, Gray.x80, Gray.x8C), new CachedValue("ide.scroll.thumb.windows.default.alpha", "0.25", .25f), new CachedValue("ide.scroll.thumb.windows.default.delta", "0.15", .15f), new CachedColor("ide.scroll.thumb.windows.default.color", "#808080", Gray.x80), new CachedColor("ide.scroll.thumb.windows.default.border", "#8C8C8C", Gray.x8C)), new DefaultThumbPainter(new ThumbPainter(.7f, .2f, Gray.x99, Gray.x8C), new CachedValue("ide.scroll.thumb.linux.default.alpha", "0.70", .70f), new CachedValue("ide.scroll.thumb.linux.default.delta", "0.20", .20f), new CachedColor("ide.scroll.thumb.linux.default.color", "#999999", Gray.x99), new CachedColor("ide.scroll.thumb.linux.default.border", "#8c8c8c", Gray.x8C))); @Deprecated public static final RegionPainter<Float> THUMB_DARK_PAINTER = new DefaultThumbPainter( new ThumbPainter(.37f, .13f, Gray.xA6, Gray.x1A), new CachedValue("ide.scroll.thumb.windows.darcula.alpha", "0.37", .37f), new CachedValue("ide.scroll.thumb.windows.darcula.delta", "0.13", .13f), new CachedColor("ide.scroll.thumb.windows.darcula.color", "#A6A6A6", Gray.xA6), new CachedColor("ide.scroll.thumb.windows.darcula.border", "#1A1A1A", Gray.x1A)); @Deprecated public static final RegionPainter<Float> MAC_THUMB_PAINTER = new DefaultThumbPainter( new RoundThumbPainter(2, .2f, .3f, Gray.x00, Gray.x00), new CachedValue("ide.scroll.thumb.mac.classic.default.alpha", "0.20", .20f), new CachedValue("ide.scroll.thumb.mac.classic.default.delta", "0.30", .30f), new CachedColor("ide.scroll.thumb.mac.classic.default.color", "#000000", Gray.x00), new CachedColor("ide.scroll.thumb.mac.classic.default.border", "", null)); static final RegionPainter<Float> MAC_OVERLAY_THUMB_PAINTER = new DefaultThumbPainter( new RoundThumbPainter(2, 0f, .5f, Gray.x00, Gray.x00), new CachedValue("ide.scroll.thumb.mac.overlay.default.alpha", "0.00", .00f), new CachedValue("ide.scroll.thumb.mac.overlay.default.delta", "0.50", .50f), new CachedColor("ide.scroll.thumb.mac.overlay.default.color", "#000000", Gray.x00), new CachedColor("ide.scroll.thumb.mac.overlay.default.border", "", null)); @Deprecated public static final RegionPainter<Float> MAC_THUMB_DARK_PAINTER = new DefaultThumbPainter( new RoundThumbPainter(1, .35f, .20f, Gray.xA6, Gray.x1A), new CachedValue("ide.scroll.thumb.mac.classic.darcula.alpha", "0.35", .35f), new CachedValue("ide.scroll.thumb.mac.classic.darcula.delta", "0.20", .20f), new CachedColor("ide.scroll.thumb.mac.classic.darcula.color", "#A6A6A6", Gray.xA6), new CachedColor("ide.scroll.thumb.mac.classic.darcula.border", "#1A1A1A", Gray.x1A)); static final RegionPainter<Float> MAC_OVERLAY_THUMB_DARK_PAINTER = new DefaultThumbPainter( new RoundThumbPainter(1, 0f, .55f, Gray.xA6, Gray.x1A), new CachedValue("ide.scroll.thumb.mac.overlay.darcula.alpha", "0.00", .00f), new CachedValue("ide.scroll.thumb.mac.overlay.darcula.delta", "0.55", .55f), new CachedColor("ide.scroll.thumb.mac.overlay.darcula.color", "#A6A6A6", Gray.xA6), new CachedColor("ide.scroll.thumb.mac.overlay.darcula.border", "#1A1A1A", Gray.x1A)); private static final Logger LOG = Logger.getInstance(JBScrollPane.class); private int myViewportBorderWidth = -1; private boolean myHasOverlayScrollbars; private volatile boolean myBackgroundRequested; // avoid cyclic references public JBScrollPane(int viewportWidth) { init(false); myViewportBorderWidth = viewportWidth; updateViewportBorder(); } public JBScrollPane() { init(); } public JBScrollPane(Component view) { super(view); init(); } public JBScrollPane(int vsbPolicy, int hsbPolicy) { super(vsbPolicy, hsbPolicy); init(); } public JBScrollPane(Component view, int vsbPolicy, int hsbPolicy) { super(view, vsbPolicy, hsbPolicy); init(); } @Override public Color getBackground() { Color color = super.getBackground(); if (!myBackgroundRequested && EventQueue.isDispatchThread() && Registry.is("ide.scroll.background.auto")) { if (!isBackgroundSet() || color instanceof UIResource) { Component child = getViewport(); if (child != null) { try { myBackgroundRequested = true; return child.getBackground(); } finally { myBackgroundRequested = false; } } } } return color; } static Color getViewBackground(JScrollPane pane) { if (pane == null) return null; JViewport viewport = pane.getViewport(); if (viewport == null) return null; Component view = viewport.getView(); if (view == null) return null; return view.getBackground(); } public static JScrollPane findScrollPane(Component c) { if (c == null) return null; if (!(c instanceof JViewport)) { Container vp = c.getParent(); if (vp instanceof JViewport) c = vp; } c = c.getParent(); if (!(c instanceof JScrollPane)) return null; return (JScrollPane)c; } private void init() { init(true); } private void init(boolean setupCorners) { setLayout(Registry.is("ide.scroll.new.layout") ? new Layout() : new ScrollPaneLayout()); if (setupCorners) { setupCorners(); } } protected void setupCorners() { setBorder(IdeBorderFactory.createBorder()); setCorner(UPPER_RIGHT_CORNER, new Corner(UPPER_RIGHT_CORNER)); setCorner(UPPER_LEFT_CORNER, new Corner(UPPER_LEFT_CORNER)); setCorner(LOWER_RIGHT_CORNER, new Corner(LOWER_RIGHT_CORNER)); setCorner(LOWER_LEFT_CORNER, new Corner(LOWER_LEFT_CORNER)); } @Override public void setUI(ScrollPaneUI ui) { super.setUI(ui); updateViewportBorder(); if (ui instanceof BasicScrollPaneUI) { try { Field field = BasicScrollPaneUI.class.getDeclaredField("mouseScrollListener"); field.setAccessible(true); Object value = field.get(ui); if (value instanceof MouseWheelListener) { MouseWheelListener oldListener = (MouseWheelListener)value; MouseWheelListener newListener = event -> { if (isScrollEvent(event)) { Object source = event.getSource(); if (source instanceof JScrollPane) { JScrollPane pane = (JScrollPane)source; if (pane.isWheelScrollingEnabled()) { JScrollBar bar = event.isShiftDown() ? pane.getHorizontalScrollBar() : pane.getVerticalScrollBar(); if (bar != null && bar.isVisible()) oldListener.mouseWheelMoved(event); } } } }; field.set(ui, newListener); // replace listener if field updated successfully removeMouseWheelListener(oldListener); addMouseWheelListener(newListener); } } catch (Exception exception) { LOG.warn(exception); } } } @Override public boolean isOptimizedDrawingEnabled() { if (getLayout() instanceof Layout) { return isOptimizedDrawingEnabledFor(getVerticalScrollBar()) && isOptimizedDrawingEnabledFor(getHorizontalScrollBar()); } return !myHasOverlayScrollbars; } /** * Returns {@code false} for visible translucent scroll bars, or {@code true} otherwise. * It is needed to repaint translucent scroll bars on viewport repainting. */ private static boolean isOptimizedDrawingEnabledFor(JScrollBar bar) { return bar == null || bar.isOpaque() || !bar.isVisible(); } private void updateViewportBorder() { if (getViewportBorder() instanceof ViewportBorder) { setViewportBorder(new ViewportBorder(myViewportBorderWidth >= 0 ? myViewportBorderWidth : 1)); } } public static ViewportBorder createIndentBorder() { return new ViewportBorder(2); } @Override public JScrollBar createVerticalScrollBar() { return new MyScrollBar(Adjustable.VERTICAL); } @NotNull @Override public JScrollBar createHorizontalScrollBar() { return new MyScrollBar(Adjustable.HORIZONTAL); } @Override protected JViewport createViewport() { return new JBViewport(); } @SuppressWarnings("deprecation") @Override public void layout() { LayoutManager layout = getLayout(); ScrollPaneLayout scrollLayout = layout instanceof ScrollPaneLayout ? (ScrollPaneLayout)layout : null; // Now we let JScrollPane layout everything as necessary super.layout(); if (layout instanceof Layout) return; if (scrollLayout != null) { // Now it's time to jump in and expand the viewport so it fits the whole area // (taking into consideration corners, headers and other stuff). myHasOverlayScrollbars = relayoutScrollbars( this, scrollLayout, myHasOverlayScrollbars // If last time we did relayouting, we should restore it back. ); } else { myHasOverlayScrollbars = false; } } private boolean relayoutScrollbars(@NotNull JComponent container, @NotNull ScrollPaneLayout layout, boolean forceRelayout) { JViewport viewport = layout.getViewport(); if (viewport == null) return false; JScrollBar vsb = layout.getVerticalScrollBar(); JScrollBar hsb = layout.getHorizontalScrollBar(); JViewport colHead = layout.getColumnHeader(); JViewport rowHead = layout.getRowHeader(); Rectangle viewportBounds = viewport.getBounds(); boolean extendViewportUnderVScrollbar = vsb != null && shouldExtendViewportUnderScrollbar(vsb); boolean extendViewportUnderHScrollbar = hsb != null && shouldExtendViewportUnderScrollbar(hsb); boolean hasOverlayScrollbars = extendViewportUnderVScrollbar || extendViewportUnderHScrollbar; if (!hasOverlayScrollbars && !forceRelayout) return false; container.setComponentZOrder(viewport, container.getComponentCount() - 1); if (vsb != null) container.setComponentZOrder(vsb, 0); if (hsb != null) container.setComponentZOrder(hsb, 0); if (extendViewportUnderVScrollbar) { int x2 = Math.max(vsb.getX() + vsb.getWidth(), viewportBounds.x + viewportBounds.width); viewportBounds.x = Math.min(viewportBounds.x, vsb.getX()); viewportBounds.width = x2 - viewportBounds.x; } if (extendViewportUnderHScrollbar) { int y2 = Math.max(hsb.getY() + hsb.getHeight(), viewportBounds.y + viewportBounds.height); viewportBounds.y = Math.min(viewportBounds.y, hsb.getY()); viewportBounds.height = y2 - viewportBounds.y; } if (extendViewportUnderVScrollbar) { if (hsb != null) { Rectangle scrollbarBounds = hsb.getBounds(); scrollbarBounds.width = viewportBounds.x + viewportBounds.width - scrollbarBounds.x; hsb.setBounds(scrollbarBounds); } if (colHead != null) { Rectangle headerBounds = colHead.getBounds(); headerBounds.width = viewportBounds.width; colHead.setBounds(headerBounds); } hideFromView(layout.getCorner(UPPER_RIGHT_CORNER)); hideFromView(layout.getCorner(LOWER_RIGHT_CORNER)); } if (extendViewportUnderHScrollbar) { if (vsb != null) { Rectangle scrollbarBounds = vsb.getBounds(); scrollbarBounds.height = viewportBounds.y + viewportBounds.height - scrollbarBounds.y; vsb.setBounds(scrollbarBounds); } if (rowHead != null) { Rectangle headerBounds = rowHead.getBounds(); headerBounds.height = viewportBounds.height; rowHead.setBounds(headerBounds); } hideFromView(layout.getCorner(LOWER_LEFT_CORNER)); hideFromView(layout.getCorner(LOWER_RIGHT_CORNER)); } viewport.setBounds(viewportBounds); return hasOverlayScrollbars; } private boolean shouldExtendViewportUnderScrollbar(@Nullable JScrollBar scrollbar) { if (scrollbar == null || !scrollbar.isVisible()) return false; return isOverlaidScrollbar(scrollbar); } protected boolean isOverlaidScrollbar(@Nullable JScrollBar scrollbar) { if (!ButtonlessScrollBarUI.isMacOverlayScrollbarSupported()) return false; ScrollBarUI vsbUI = scrollbar == null ? null : scrollbar.getUI(); return vsbUI instanceof ButtonlessScrollBarUI && !((ButtonlessScrollBarUI)vsbUI).alwaysShowTrack(); } private static void hideFromView(Component component) { if (component == null) return; component.setBounds(-10, -10, 1, 1); } private class MyScrollBar extends ScrollBar implements IdeGlassPane.TopComponent { public MyScrollBar(int orientation) { super(orientation); } @Override public void updateUI() { ScrollBarUI ui = getUI(); if (ui instanceof DefaultScrollBarUI) return; setUI(JBScrollBar.createUI(this)); } @Override public boolean canBePreprocessed(MouseEvent e) { return JBScrollPane.canBePreprocessed(e, this); } } public static boolean canBePreprocessed(MouseEvent e, JScrollBar bar) { if (e.getID() == MouseEvent.MOUSE_MOVED || e.getID() == MouseEvent.MOUSE_PRESSED) { ScrollBarUI ui = bar.getUI(); if (ui instanceof BasicScrollBarUI) { BasicScrollBarUI bui = (BasicScrollBarUI)ui; try { Rectangle rect = (Rectangle)ReflectionUtil.getDeclaredMethod(BasicScrollBarUI.class, "getThumbBounds", ArrayUtil.EMPTY_CLASS_ARRAY).invoke(bui); Point point = SwingUtilities.convertPoint(e.getComponent(), e.getX(), e.getY(), bar); return !rect.contains(point); } catch (Exception e1) { return true; } } else if (ui instanceof DefaultScrollBarUI) { DefaultScrollBarUI dui = (DefaultScrollBarUI)ui; Point point = e.getLocationOnScreen(); SwingUtilities.convertPointFromScreen(point, bar); return !dui.isThumbContains(point.x, point.y); } } return true; } private static class Corner extends JPanel { private final String myPos; public Corner(String pos) { myPos = pos; ScrollColorProducer.setBackground(this); ScrollColorProducer.setForeground(this); } @Override protected void paintComponent(Graphics g) { g.setColor(getBackground()); g.fillRect(0, 0, getWidth(), getHeight()); if (SystemInfo.isMac || !Registry.is("ide.scroll.track.border.paint")) return; g.setColor(getForeground()); int x2 = getWidth() - 1; int y2 = getHeight() - 1; if (myPos == UPPER_LEFT_CORNER || myPos == UPPER_RIGHT_CORNER) { g.drawLine(0, y2, x2, y2); } if (myPos == LOWER_LEFT_CORNER || myPos == LOWER_RIGHT_CORNER) { g.drawLine(0, 0, x2, 0); } if (myPos == UPPER_LEFT_CORNER || myPos == LOWER_LEFT_CORNER) { g.drawLine(x2, 0, x2, y2); } if (myPos == UPPER_RIGHT_CORNER || myPos == LOWER_RIGHT_CORNER) { g.drawLine(0, 0, 0, y2); } } } private static class ViewportBorder extends LineBorder { public ViewportBorder(int thickness) { super(null, thickness); } @Override public void paintBorder(Component c, Graphics g, int x, int y, int width, int height) { updateColor(c); super.paintBorder(c, g, x, y, width, height); } private void updateColor(Component c) { if (!(c instanceof JScrollPane)) return; lineColor = getViewBackground((JScrollPane)c); } } /** * These client properties modify a scroll pane layout. * Use the class object as a property key. * * @see #putClientProperty(Object, Object) */ public enum Flip { NONE, VERTICAL, HORIZONTAL, BOTH } /** * These client properties show a component position on a scroll pane. * It is set by internal layout manager of the scroll pane. */ public enum Alignment { TOP, LEFT, RIGHT, BOTTOM; public static Alignment get(JComponent component) { if (component != null) { Object property = component.getClientProperty(Alignment.class); if (property instanceof Alignment) return (Alignment)property; Container parent = component.getParent(); if (parent instanceof JScrollPane) { JScrollPane pane = (JScrollPane)parent; if (component == pane.getColumnHeader()) { return TOP; } if (component == pane.getHorizontalScrollBar()) { return BOTTOM; } boolean ltr = pane.getComponentOrientation().isLeftToRight(); if (component == pane.getVerticalScrollBar()) { return ltr ? RIGHT : LEFT; } if (component == pane.getRowHeader()) { return ltr ? LEFT : RIGHT; } } // assume alignment for a scroll bar, // which is not contained in a scroll pane if (component instanceof JScrollBar) { JScrollBar bar = (JScrollBar)component; switch (bar.getOrientation()) { case Adjustable.HORIZONTAL: return BOTTOM; case Adjustable.VERTICAL: return bar.getComponentOrientation().isLeftToRight() ? RIGHT : LEFT; } } } return null; } } /** * ScrollPaneLayout implementation that supports * ScrollBar flipping and non-opaque ScrollBars. */ private static class Layout extends ScrollPaneLayout { private static final Insets EMPTY_INSETS = new Insets(0, 0, 0, 0); @Override public void layoutContainer(Container parent) { JScrollPane pane = (JScrollPane)parent; // Calculate inner bounds of the scroll pane Rectangle bounds = new Rectangle(pane.getWidth(), pane.getHeight()); JBInsets.removeFrom(bounds, pane.getInsets()); // Determine positions of scroll bars on the scroll pane Object property = pane.getClientProperty(Flip.class); Flip flip = property instanceof Flip ? (Flip)property : Flip.NONE; boolean hsbOnTop = flip == Flip.BOTH || flip == Flip.VERTICAL; boolean vsbOnLeft = pane.getComponentOrientation().isLeftToRight() ? flip == Flip.BOTH || flip == Flip.HORIZONTAL : flip == Flip.NONE || flip == Flip.VERTICAL; // If there's a visible row header remove the space it needs. // The row header is treated as if it were fixed width, arbitrary height. Rectangle rowHeadBounds = new Rectangle(bounds.x, 0, 0, 0); if (rowHead != null && rowHead.isVisible()) { rowHeadBounds.width = min(bounds.width, rowHead.getPreferredSize().width); bounds.width -= rowHeadBounds.width; if (vsbOnLeft) { rowHeadBounds.x += bounds.width; } else { bounds.x += rowHeadBounds.width; } } // If there's a visible column header remove the space it needs. // The column header is treated as if it were fixed height, arbitrary width. Rectangle colHeadBounds = new Rectangle(0, bounds.y, 0, 0); if (colHead != null && colHead.isVisible()) { colHeadBounds.height = min(bounds.height, colHead.getPreferredSize().height); bounds.height -= colHeadBounds.height; if (hsbOnTop) { colHeadBounds.y += bounds.height; } else { bounds.y += colHeadBounds.height; } } // If there's a JScrollPane.viewportBorder, remove the space it occupies Border border = pane.getViewportBorder(); Insets insets = border == null ? null : border.getBorderInsets(parent); JBInsets.removeFrom(bounds, insets); if (insets == null) insets = EMPTY_INSETS; // At this point: // colHeadBounds is correct except for its width and x // rowHeadBounds is correct except for its height and y // bounds - the space available for the viewport and scroll bars // Once we're through computing the dimensions of these three parts // we can go back and set the bounds for the corners and the dimensions of // colHeadBounds.x, colHeadBounds.width, rowHeadBounds.y, rowHeadBounds.height. boolean isEmpty = bounds.width < 0 || bounds.height < 0; Component view = viewport == null ? null : viewport.getView(); Dimension viewPreferredSize = view == null ? new Dimension() : view.getPreferredSize(); if (view instanceof JComponent) JBViewport.fixPreferredSize(viewPreferredSize, (JComponent)view, vsb, hsb); Dimension viewportExtentSize = viewport == null ? new Dimension() : viewport.toViewCoordinates(bounds.getSize()); // If the view is tracking the viewports width we don't bother with a horizontal scrollbar. // If the view is tracking the viewports height we don't bother with a vertical scrollbar. Scrollable scrollable = null; boolean viewTracksViewportWidth = false; boolean viewTracksViewportHeight = false; // Don't bother checking the Scrollable methods if there is no room for the viewport, // we aren't going to show any scroll bars in this case anyway. if (!isEmpty && view instanceof Scrollable) { scrollable = (Scrollable)view; viewTracksViewportWidth = scrollable.getScrollableTracksViewportWidth(); viewTracksViewportHeight = scrollable.getScrollableTracksViewportHeight(); } // If there's a vertical scroll bar and we need one, allocate space for it. // A vertical scroll bar is considered to be fixed width, arbitrary height. boolean vsbOpaque = false; boolean vsbNeeded = false; int vsbPolicy = pane.getVerticalScrollBarPolicy(); if (!isEmpty && vsbPolicy != VERTICAL_SCROLLBAR_NEVER) { vsbNeeded = vsbPolicy == VERTICAL_SCROLLBAR_ALWAYS || !viewTracksViewportHeight && viewPreferredSize.height > viewportExtentSize.height; } Rectangle vsbBounds = new Rectangle(0, bounds.y - insets.top, 0, 0); if (vsb != null) { if (!SystemInfo.isMac && view instanceof JTable) vsb.setOpaque(true); vsbOpaque = vsb.isOpaque(); if (vsbNeeded) { adjustForVSB(bounds, insets, vsbBounds, vsbOpaque, vsbOnLeft); if (vsbOpaque && viewport != null) { viewportExtentSize = viewport.toViewCoordinates(bounds.getSize()); } } } // If there's a horizontal scroll bar and we need one, allocate space for it. // A horizontal scroll bar is considered to be fixed height, arbitrary width. boolean hsbOpaque = false; boolean hsbNeeded = false; int hsbPolicy = pane.getHorizontalScrollBarPolicy(); if (!isEmpty && hsbPolicy != HORIZONTAL_SCROLLBAR_NEVER) { hsbNeeded = hsbPolicy == HORIZONTAL_SCROLLBAR_ALWAYS || !viewTracksViewportWidth && viewPreferredSize.width > viewportExtentSize.width; } Rectangle hsbBounds = new Rectangle(bounds.x - insets.left, 0, 0, 0); if (hsb != null) { if (!SystemInfo.isMac && view instanceof JTable) hsb.setOpaque(true); hsbOpaque = hsb.isOpaque(); if (hsbNeeded) { adjustForHSB(bounds, insets, hsbBounds, hsbOpaque, hsbOnTop); if (hsbOpaque && viewport != null) { // If we added the horizontal scrollbar and reduced the vertical space // we may have to add the vertical scrollbar, if that hasn't been done so already. if (vsb != null && !vsbNeeded && vsbPolicy != VERTICAL_SCROLLBAR_NEVER) { viewportExtentSize = viewport.toViewCoordinates(bounds.getSize()); vsbNeeded = viewPreferredSize.height > viewportExtentSize.height; if (vsbNeeded) adjustForVSB(bounds, insets, vsbBounds, vsbOpaque, vsbOnLeft); } } } } // Set the size of the viewport first, and then recheck the Scrollable methods. // Some components base their return values for the Scrollable methods on the size of the viewport, // so that if we don't ask after resetting the bounds we may have gotten the wrong answer. if (viewport != null) { viewport.setBounds(bounds); if (scrollable != null && hsbOpaque && vsbOpaque) { viewTracksViewportWidth = scrollable.getScrollableTracksViewportWidth(); viewTracksViewportHeight = scrollable.getScrollableTracksViewportHeight(); viewportExtentSize = viewport.toViewCoordinates(bounds.getSize()); boolean vsbNeededOld = vsbNeeded; if (vsb != null && vsbPolicy == VERTICAL_SCROLLBAR_AS_NEEDED) { boolean vsbNeededNew = !viewTracksViewportHeight && viewPreferredSize.height > viewportExtentSize.height; if (vsbNeeded != vsbNeededNew) { vsbNeeded = vsbNeededNew; if (vsbNeeded) { adjustForVSB(bounds, insets, vsbBounds, vsbOpaque, vsbOnLeft); } else if (vsbOpaque) { bounds.width += vsbBounds.width; } if (vsbOpaque) viewportExtentSize = viewport.toViewCoordinates(bounds.getSize()); } } boolean hsbNeededOld = hsbNeeded; if (hsb != null && hsbPolicy == HORIZONTAL_SCROLLBAR_AS_NEEDED) { boolean hsbNeededNew = !viewTracksViewportWidth && viewPreferredSize.width > viewportExtentSize.width; if (hsbNeeded != hsbNeededNew) { hsbNeeded = hsbNeededNew; if (hsbNeeded) { adjustForHSB(bounds, insets, hsbBounds, hsbOpaque, hsbOnTop); } else if (hsbOpaque) { bounds.height += hsbBounds.height; } if (hsbOpaque && vsb != null && !vsbNeeded && vsbPolicy != VERTICAL_SCROLLBAR_NEVER) { viewportExtentSize = viewport.toViewCoordinates(bounds.getSize()); vsbNeeded = viewPreferredSize.height > viewportExtentSize.height; if (vsbNeeded) adjustForVSB(bounds, insets, vsbBounds, vsbOpaque, vsbOnLeft); } } } if (hsbNeededOld != hsbNeeded || vsbNeededOld != vsbNeeded) { viewport.setBounds(bounds); // You could argue that we should recheck the Scrollable methods again until they stop changing, // but they might never stop changing, so we stop here and don't do any additional checks. } } } // Set the bounds of the row header. rowHeadBounds.y = bounds.y - insets.top; rowHeadBounds.height = bounds.height + insets.top + insets.bottom; if (rowHead != null) { rowHead.setBounds(rowHeadBounds); rowHead.putClientProperty(Alignment.class, vsbOnLeft ? Alignment.RIGHT : Alignment.LEFT); } // Set the bounds of the column header. colHeadBounds.x = bounds.x - insets.left; colHeadBounds.width = bounds.width + insets.left + insets.right; if (colHead != null) { colHead.setBounds(colHeadBounds); colHead.putClientProperty(Alignment.class, hsbOnTop ? Alignment.BOTTOM : Alignment.TOP); } // Calculate overlaps for translucent scroll bars int overlapWidth = 0; int overlapHeight = 0; if (vsbNeeded && !vsbOpaque && hsbNeeded && !hsbOpaque) { overlapWidth = vsbBounds.width; // shrink horizontally //overlapHeight = hsbBounds.height; // shrink vertically } // Set the bounds of the vertical scroll bar. vsbBounds.y = bounds.y - insets.top; vsbBounds.height = bounds.height + insets.top + insets.bottom; if (vsb != null) { vsb.setVisible(vsbNeeded); if (vsbNeeded) { if (vsbOpaque && colHead != null && UIManager.getBoolean("ScrollPane.fillUpperCorner")) { if ((vsbOnLeft ? upperLeft : upperRight) == null) { // This is used primarily for GTK L&F, which needs to extend // the vertical scrollbar to fill the upper corner near the column header. // Note that we skip this step (and use the default behavior) // if the user has set a custom corner component. if (!hsbOnTop) vsbBounds.y -= colHeadBounds.height; vsbBounds.height += colHeadBounds.height; } } int overlapY = !hsbOnTop ? 0 : overlapHeight; vsb.setBounds(vsbBounds.x, vsbBounds.y + overlapY, vsbBounds.width, vsbBounds.height - overlapHeight); vsb.putClientProperty(Alignment.class, vsbOnLeft ? Alignment.LEFT : Alignment.RIGHT); } // Modify the bounds of the translucent scroll bar. if (!vsbOpaque) { if (!vsbOnLeft) vsbBounds.x += vsbBounds.width; vsbBounds.width = 0; } } // Set the bounds of the horizontal scroll bar. hsbBounds.x = bounds.x - insets.left; hsbBounds.width = bounds.width + insets.left + insets.right; if (hsb != null) { hsb.setVisible(hsbNeeded); if (hsbNeeded) { if (hsbOpaque && rowHead != null && UIManager.getBoolean("ScrollPane.fillLowerCorner")) { if ((vsbOnLeft ? lowerRight : lowerLeft) == null) { // This is used primarily for GTK L&F, which needs to extend // the horizontal scrollbar to fill the lower corner near the row header. // Note that we skip this step (and use the default behavior) // if the user has set a custom corner component. if (!vsbOnLeft) hsbBounds.x -= rowHeadBounds.width; hsbBounds.width += rowHeadBounds.width; } } int overlapX = !vsbOnLeft ? 0 : overlapWidth; hsb.setBounds(hsbBounds.x + overlapX, hsbBounds.y, hsbBounds.width - overlapWidth, hsbBounds.height); hsb.putClientProperty(Alignment.class, hsbOnTop ? Alignment.TOP : Alignment.BOTTOM); } // Modify the bounds of the translucent scroll bar. if (!hsbOpaque) { if (!hsbOnTop) hsbBounds.y += hsbBounds.height; hsbBounds.height = 0; } } // Set the bounds of the corners. if (lowerLeft != null) { lowerLeft.setBounds(vsbOnLeft ? vsbBounds.x : rowHeadBounds.x, hsbOnTop ? colHeadBounds.y : hsbBounds.y, vsbOnLeft ? vsbBounds.width : rowHeadBounds.width, hsbOnTop ? colHeadBounds.height : hsbBounds.height); } if (lowerRight != null) { lowerRight.setBounds(vsbOnLeft ? rowHeadBounds.x : vsbBounds.x, hsbOnTop ? colHeadBounds.y : hsbBounds.y, vsbOnLeft ? rowHeadBounds.width : vsbBounds.width, hsbOnTop ? colHeadBounds.height : hsbBounds.height); } if (upperLeft != null) { upperLeft.setBounds(vsbOnLeft ? vsbBounds.x : rowHeadBounds.x, hsbOnTop ? hsbBounds.y : colHeadBounds.y, vsbOnLeft ? vsbBounds.width : rowHeadBounds.width, hsbOnTop ? hsbBounds.height : colHeadBounds.height); } if (upperRight != null) { upperRight.setBounds(vsbOnLeft ? rowHeadBounds.x : vsbBounds.x, hsbOnTop ? hsbBounds.y : colHeadBounds.y, vsbOnLeft ? rowHeadBounds.width : vsbBounds.width, hsbOnTop ? hsbBounds.height : colHeadBounds.height); } if (!vsbOpaque && vsbNeeded || !hsbOpaque && hsbNeeded) { fixComponentZOrder(vsb, 0); fixComponentZOrder(viewport, -1); } } private static void fixComponentZOrder(Component component, int index) { if (component != null) { Container parent = component.getParent(); synchronized (parent.getTreeLock()) { if (index < 0) index += parent.getComponentCount(); parent.setComponentZOrder(component, index); } } } private void adjustForVSB(Rectangle bounds, Insets insets, Rectangle vsbBounds, boolean vsbOpaque, boolean vsbOnLeft) { vsbBounds.width = !vsb.isEnabled() ? 0 : min(bounds.width, vsb.getPreferredSize().width); if (vsbOnLeft) { vsbBounds.x = bounds.x - insets.left/* + vsbBounds.width*/; if (vsbOpaque) bounds.x += vsbBounds.width; } else { vsbBounds.x = bounds.x + bounds.width + insets.right - vsbBounds.width; } if (vsbOpaque) bounds.width -= vsbBounds.width; } private void adjustForHSB(Rectangle bounds, Insets insets, Rectangle hsbBounds, boolean hsbOpaque, boolean hsbOnTop) { hsbBounds.height = !hsb.isEnabled() ? 0 : min(bounds.height, hsb.getPreferredSize().height); if (hsbOnTop) { hsbBounds.y = bounds.y - insets.top/* + hsbBounds.height*/; if (hsbOpaque) bounds.y += hsbBounds.height; } else { hsbBounds.y = bounds.y + bounds.height + insets.bottom - hsbBounds.height; } if (hsbOpaque) bounds.height -= hsbBounds.height; } private static int min(int one, int two) { return Math.max(0, Math.min(one, two)); } } private static class ProtectedPainter implements RegionPainter<Float> { private RegionPainter<Float> myPainter; private RegionPainter<Float> myFallback; public ProtectedPainter(RegionPainter<Float> painter, RegionPainter<Float> fallback) { myPainter = painter; myFallback = fallback; } @Override public void paint(Graphics2D g, int x, int y, int width, int height, Float value) { RegionPainter<Float> painter = myFallback; if (myPainter != null) { try { myPainter.paint(g, x, y, width, height, value); return; } catch (Throwable exception) { // do not try to use myPainter again on other systems if (!SystemInfo.isWindows) myPainter = null; } } if (painter != null) { painter.paint(g, x, y, width, height, value); } } } private static class AlphaPainter extends RegionPainter.Alpha { float myBase; float myDelta; Color myFillColor; private AlphaPainter(float base, float delta, Color fill) { myBase = base; myDelta = delta; myFillColor = fill; } @Override protected void paint(Graphics2D g, int x, int y, int width, int height) { if (myFillColor != null) { g.setColor(myFillColor); g.fillRect(x, y, width, height); } } @Override protected float getAlpha(Float value) { return value != null ? myBase + myDelta * value : 0; } } private static class RoundThumbPainter extends ThumbPainter { private final int myBorder; private RoundThumbPainter(int border, float base, float delta, Color fill, Color draw) { super(base, delta, fill, draw); myBorder = border; } @Override protected void paint(Graphics2D g, int x, int y, int width, int height) { Object old = g.getRenderingHint(RenderingHints.KEY_ANTIALIASING); g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); x += myBorder; y += myBorder; width -= myBorder + myBorder; height -= myBorder + myBorder; int arc = Math.min(width, height); if (myFillColor != null) { g.setColor(myFillColor); g.fillRoundRect(x, y, width, height, arc, arc); } if (myDrawColor != null) { g.setColor(myDrawColor); if (UIUtil.isRetina(g)) { g.drawRoundRect(x, y, width, height, arc, arc); } else { g.drawRoundRect(x, y, width - 1, height - 1, arc, arc); } } g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, old); } } private static class ThumbPainter extends AlphaPainter { Color myDrawColor; private ThumbPainter(float base, float delta, Color fill, Color draw) { super(base, delta, fill); myDrawColor = draw; } @Override protected void paint(Graphics2D g, int x, int y, int width, int height) { super.paint(g, x + 1, y + 1, width - 2, height - 2); if (myDrawColor != null) { g.setColor(myDrawColor); if (Registry.is("ide.scroll.thumb.border.rounded")) { g.drawLine(x + 1, y, x + width - 2, y); g.drawLine(x + 1, y + height - 1, x + width - 2, y + height - 1); g.drawLine(x, y + 1, x, y + height - 2); g.drawLine(x + width - 1, y + 1, x + width - 1, y + height - 2); } else { g.drawRect(x, y, width - 1, height - 1); } } } } private static class SubtractThumbPainter extends ThumbPainter { public SubtractThumbPainter(float base, float delta, Color fill, Color draw) { super(base, delta, fill, draw); } @Override protected Composite getComposite(float alpha) { return alpha < 1 ? new SubtractComposite(alpha) : AlphaComposite.SrcOver; } } private static class SubtractComposite implements Composite, CompositeContext { private final float myAlpha; private SubtractComposite(float alpha) { myAlpha = alpha; } private int subtract(int newValue, int oldValue) { float value = (oldValue & 0xFF) - (newValue & 0xFF) * myAlpha; return value <= 0 ? 0 : (int)value; } @Override public CompositeContext createContext(ColorModel src, ColorModel dst, RenderingHints hints) { return isValid(src) && isValid(dst) ? this : AlphaComposite.SrcOver.derive(myAlpha).createContext(src, dst, hints); } private static boolean isValid(ColorModel model) { if (model instanceof DirectColorModel && DataBuffer.TYPE_INT == model.getTransferType()) { DirectColorModel dcm = (DirectColorModel)model; if (0x00FF0000 == dcm.getRedMask() && 0x0000FF00 == dcm.getGreenMask() && 0x000000FF == dcm.getBlueMask()) { return 4 != dcm.getNumComponents() || 0xFF000000 == dcm.getAlphaMask(); } } return false; } @Override public void compose(Raster srcIn, Raster dstIn, WritableRaster dstOut) { int width = Math.min(srcIn.getWidth(), dstIn.getWidth()); int height = Math.min(srcIn.getHeight(), dstIn.getHeight()); int[] srcPixels = new int[width]; int[] dstPixels = new int[width]; for (int y = 0; y < height; y++) { srcIn.getDataElements(0, y, width, 1, srcPixels); dstIn.getDataElements(0, y, width, 1, dstPixels); for (int x = 0; x < width; x++) { int src = srcPixels[x]; int dst = dstPixels[x]; int a = subtract(src >> 24, dst >> 24) << 24; int r = subtract(src >> 16, dst >> 16) << 16; int g = subtract(src >> 8, dst >> 8) << 8; int b = subtract(src, dst); dstPixels[x] = a | r | g | b; } dstOut.setDataElements(0, y, width, 1, dstPixels); } } @Override public void dispose() { } } /** * Indicates whether the specified event is not consumed and does not have unexpected modifiers. * * @param event a mouse wheel event to check for validity * @return {@code true} if the specified event is valid, {@code false} otherwise */ public static boolean isScrollEvent(@NotNull MouseWheelEvent event) { if (event.isConsumed()) return false; // event should not be consumed already if (event.getWheelRotation() == 0) return false; // any rotation expected (forward or backward) return 0 == (SCROLL_MODIFIERS & event.getModifiers()); } private static final int SCROLL_MODIFIERS = // event modifiers allowed during scrolling ~InputEvent.SHIFT_MASK & ~InputEvent.SHIFT_DOWN_MASK & // for horizontal scrolling ~InputEvent.BUTTON1_MASK & ~InputEvent.BUTTON1_DOWN_MASK; // for selection private static class CachedColor { private final String myKey; private String myString; private Color myColor; private CachedColor(String key, String string, Color color) { myKey = key; myString = string; myColor = color; } private Color get() { String string = Registry.stringValue(myKey); if (!string.equals(myString)) { try { myColor = Color.decode(string); } catch (Exception ignore) { myColor = null; } finally { myString = string; } } return myColor; } } private static class CachedValue { private final String myKey; private String myString; private float myValue; private CachedValue(String key, String string, float value) { myKey = key; myString = string; myValue = value; } private float get() { String string = Registry.stringValue(myKey); if (!string.equals(myString)) { try { myValue = Float.parseFloat(string); } catch (Exception ignore) { } finally { myString = string; } } return myValue; } } private static class ThumbPainterDelegate<P extends AlphaPainter> implements RegionPainter<Float> { final P myPainter; private final CachedValue myBase; private final CachedValue myDelta; private final CachedColor myFillColor; private ThumbPainterDelegate(P painter, CachedValue base, CachedValue delta, CachedColor fill) { myPainter = painter; myBase = base; myDelta = delta; myFillColor = fill; } @Override public void paint(Graphics2D g, int x, int y, int width, int height, Float object) { myPainter.myBase = myBase.get(); myPainter.myDelta = myDelta.get(); myPainter.myFillColor = myFillColor.get(); myPainter.paint(g, x, y, width, height, object); } } private static class DefaultThumbPainter extends ThumbPainterDelegate<ThumbPainter> { private final CachedColor myDrawColor; private DefaultThumbPainter(ThumbPainter painter, CachedValue base, CachedValue delta, CachedColor fill, CachedColor draw) { super(painter, base, delta, fill); myDrawColor = draw; } @Override public final void paint(Graphics2D g, int x, int y, int width, int height, Float object) { myPainter.myDrawColor = myDrawColor.get(); super.paint(g, x, y, width, height, object); } } }
platform/platform-api/src/com/intellij/ui/components/JBScrollPane.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.ui.components; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.util.Key; import com.intellij.openapi.util.SystemInfo; import com.intellij.openapi.util.registry.Registry; import com.intellij.openapi.wm.IdeGlassPane; import com.intellij.ui.Gray; import com.intellij.ui.IdeBorderFactory; import com.intellij.util.ArrayUtil; import com.intellij.util.ReflectionUtil; import com.intellij.util.ui.ButtonlessScrollBarUI; import com.intellij.util.ui.JBInsets; import com.intellij.util.ui.RegionPainter; import com.intellij.util.ui.UIUtil; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.swing.*; import javax.swing.border.Border; import javax.swing.border.LineBorder; import javax.swing.plaf.ScrollBarUI; import javax.swing.plaf.ScrollPaneUI; import javax.swing.plaf.UIResource; import javax.swing.plaf.basic.BasicScrollBarUI; import javax.swing.plaf.basic.BasicScrollPaneUI; import java.awt.*; import java.awt.event.InputEvent; import java.awt.event.MouseEvent; import java.awt.event.MouseWheelEvent; import java.awt.event.MouseWheelListener; import java.awt.geom.RoundRectangle2D; import java.awt.image.*; import java.lang.reflect.Field; public class JBScrollPane extends JScrollPane { /** * This key is used to specify which colors should use the scroll bars on the pane. * If a client property is set to {@code true} the bar's brightness * will be modified according to the view's background. * * @see UIUtil#putClientProperty * @see UIUtil#isUnderDarcula */ public static final Key<Boolean> BRIGHTNESS_FROM_VIEW = Key.create("JB_SCROLL_PANE_BRIGHTNESS_FROM_VIEW"); @Deprecated public static final RegionPainter<Float> TRACK_PAINTER = new AlphaPainter(.0f, .1f, Gray.x80); @Deprecated public static final RegionPainter<Float> TRACK_DARK_PAINTER = new AlphaPainter(.0f, .1f, Gray.x80); @Deprecated public static final RegionPainter<Float> THUMB_PAINTER = new ProtectedPainter( new DefaultThumbPainter(new SubtractThumbPainter(.25f, .15f, Gray.x80, Gray.x8C), new CachedValue("ide.scroll.thumb.windows.default.alpha", "0.25", .25f), new CachedValue("ide.scroll.thumb.windows.default.delta", "0.15", .15f), new CachedColor("ide.scroll.thumb.windows.default.color", "#808080", Gray.x80), new CachedColor("ide.scroll.thumb.windows.default.border", "#8C8C8C", Gray.x8C)), new DefaultThumbPainter(new ThumbPainter(.7f, .2f, Gray.x99, Gray.x8C), new CachedValue("ide.scroll.thumb.linux.default.alpha", "0.70", .70f), new CachedValue("ide.scroll.thumb.linux.default.delta", "0.20", .20f), new CachedColor("ide.scroll.thumb.linux.default.color", "#999999", Gray.x99), new CachedColor("ide.scroll.thumb.linux.default.border", "#8c8c8c", Gray.x8C))); @Deprecated public static final RegionPainter<Float> THUMB_DARK_PAINTER = new DefaultThumbPainter( new ThumbPainter(.37f, .13f, Gray.xA6, Gray.x1A), new CachedValue("ide.scroll.thumb.windows.darcula.alpha", "0.37", .37f), new CachedValue("ide.scroll.thumb.windows.darcula.delta", "0.13", .13f), new CachedColor("ide.scroll.thumb.windows.darcula.color", "#A6A6A6", Gray.xA6), new CachedColor("ide.scroll.thumb.windows.darcula.border", "#1A1A1A", Gray.x1A)); @Deprecated public static final RegionPainter<Float> MAC_THUMB_PAINTER = new DefaultThumbPainter( new RoundThumbPainter(2, .2f, .3f, Gray.x00, Gray.x00), new CachedValue("ide.scroll.thumb.mac.classic.default.alpha", "0.20", .20f), new CachedValue("ide.scroll.thumb.mac.classic.default.delta", "0.30", .30f), new CachedColor("ide.scroll.thumb.mac.classic.default.color", "#000000", Gray.x00), new CachedColor("ide.scroll.thumb.mac.classic.default.border", "", null)); static final RegionPainter<Float> MAC_OVERLAY_THUMB_PAINTER = new DefaultThumbPainter( new RoundThumbPainter(2, 0f, .5f, Gray.x00, Gray.x00), new CachedValue("ide.scroll.thumb.mac.overlay.default.alpha", "0.00", .00f), new CachedValue("ide.scroll.thumb.mac.overlay.default.delta", "0.50", .50f), new CachedColor("ide.scroll.thumb.mac.overlay.default.color", "#000000", Gray.x00), new CachedColor("ide.scroll.thumb.mac.overlay.default.border", "", null)); @Deprecated public static final RegionPainter<Float> MAC_THUMB_DARK_PAINTER = new DefaultThumbPainter( new RoundThumbPainter(1, .35f, .20f, Gray.xA6, Gray.x1A), new CachedValue("ide.scroll.thumb.mac.classic.darcula.alpha", "0.35", .35f), new CachedValue("ide.scroll.thumb.mac.classic.darcula.delta", "0.20", .20f), new CachedColor("ide.scroll.thumb.mac.classic.darcula.color", "#A6A6A6", Gray.xA6), new CachedColor("ide.scroll.thumb.mac.classic.darcula.border", "#1A1A1A", Gray.x1A)); static final RegionPainter<Float> MAC_OVERLAY_THUMB_DARK_PAINTER = new DefaultThumbPainter( new RoundThumbPainter(1, 0f, .55f, Gray.xA6, Gray.x1A), new CachedValue("ide.scroll.thumb.mac.overlay.darcula.alpha", "0.00", .00f), new CachedValue("ide.scroll.thumb.mac.overlay.darcula.delta", "0.55", .55f), new CachedColor("ide.scroll.thumb.mac.overlay.darcula.color", "#A6A6A6", Gray.xA6), new CachedColor("ide.scroll.thumb.mac.overlay.darcula.border", "#1A1A1A", Gray.x1A)); private static final Logger LOG = Logger.getInstance(JBScrollPane.class); private int myViewportBorderWidth = -1; private boolean myHasOverlayScrollbars; private volatile boolean myBackgroundRequested; // avoid cyclic references public JBScrollPane(int viewportWidth) { init(false); myViewportBorderWidth = viewportWidth; updateViewportBorder(); } public JBScrollPane() { init(); } public JBScrollPane(Component view) { super(view); init(); } public JBScrollPane(int vsbPolicy, int hsbPolicy) { super(vsbPolicy, hsbPolicy); init(); } public JBScrollPane(Component view, int vsbPolicy, int hsbPolicy) { super(view, vsbPolicy, hsbPolicy); init(); } @Override public Color getBackground() { Color color = super.getBackground(); if (!myBackgroundRequested && EventQueue.isDispatchThread() && Registry.is("ide.scroll.background.auto")) { if (!isBackgroundSet() || color instanceof UIResource) { Component child = getViewport(); if (child != null) { try { myBackgroundRequested = true; return child.getBackground(); } finally { myBackgroundRequested = false; } } } } return color; } static Color getViewBackground(JScrollPane pane) { if (pane == null) return null; JViewport viewport = pane.getViewport(); if (viewport == null) return null; Component view = viewport.getView(); if (view == null) return null; return view.getBackground(); } public static JScrollPane findScrollPane(Component c) { if (c == null) return null; if (!(c instanceof JViewport)) { Container vp = c.getParent(); if (vp instanceof JViewport) c = vp; } c = c.getParent(); if (!(c instanceof JScrollPane)) return null; return (JScrollPane)c; } private void init() { init(true); } private void init(boolean setupCorners) { setLayout(Registry.is("ide.scroll.new.layout") ? new Layout() : new ScrollPaneLayout()); if (setupCorners) { setupCorners(); } } protected void setupCorners() { setBorder(IdeBorderFactory.createBorder()); setCorner(UPPER_RIGHT_CORNER, new Corner(UPPER_RIGHT_CORNER)); setCorner(UPPER_LEFT_CORNER, new Corner(UPPER_LEFT_CORNER)); setCorner(LOWER_RIGHT_CORNER, new Corner(LOWER_RIGHT_CORNER)); setCorner(LOWER_LEFT_CORNER, new Corner(LOWER_LEFT_CORNER)); } @Override public void setUI(ScrollPaneUI ui) { super.setUI(ui); updateViewportBorder(); if (ui instanceof BasicScrollPaneUI) { try { Field field = BasicScrollPaneUI.class.getDeclaredField("mouseScrollListener"); field.setAccessible(true); Object value = field.get(ui); if (value instanceof MouseWheelListener) { MouseWheelListener oldListener = (MouseWheelListener)value; MouseWheelListener newListener = event -> { if (isScrollEvent(event)) { Object source = event.getSource(); if (source instanceof JScrollPane) { JScrollPane pane = (JScrollPane)source; if (pane.isWheelScrollingEnabled()) { JScrollBar bar = event.isShiftDown() ? pane.getHorizontalScrollBar() : pane.getVerticalScrollBar(); if (bar != null && bar.isVisible()) oldListener.mouseWheelMoved(event); } } } }; field.set(ui, newListener); // replace listener if field updated successfully removeMouseWheelListener(oldListener); addMouseWheelListener(newListener); } } catch (Exception exception) { LOG.warn(exception); } } } @Override public boolean isOptimizedDrawingEnabled() { if (getLayout() instanceof Layout) { return isOptimizedDrawingEnabledFor(getVerticalScrollBar()) && isOptimizedDrawingEnabledFor(getHorizontalScrollBar()); } return !myHasOverlayScrollbars; } /** * Returns {@code false} for visible translucent scroll bars, or {@code true} otherwise. * It is needed to repaint translucent scroll bars on viewport repainting. */ private static boolean isOptimizedDrawingEnabledFor(JScrollBar bar) { return bar == null || bar.isOpaque() || !bar.isVisible(); } private void updateViewportBorder() { if (getViewportBorder() instanceof ViewportBorder) { setViewportBorder(new ViewportBorder(myViewportBorderWidth >= 0 ? myViewportBorderWidth : 1)); } } public static ViewportBorder createIndentBorder() { return new ViewportBorder(2); } @Override public JScrollBar createVerticalScrollBar() { return new MyScrollBar(Adjustable.VERTICAL); } @NotNull @Override public JScrollBar createHorizontalScrollBar() { return new MyScrollBar(Adjustable.HORIZONTAL); } @Override protected JViewport createViewport() { return new JBViewport(); } @SuppressWarnings("deprecation") @Override public void layout() { LayoutManager layout = getLayout(); ScrollPaneLayout scrollLayout = layout instanceof ScrollPaneLayout ? (ScrollPaneLayout)layout : null; // Now we let JScrollPane layout everything as necessary super.layout(); if (layout instanceof Layout) return; if (scrollLayout != null) { // Now it's time to jump in and expand the viewport so it fits the whole area // (taking into consideration corners, headers and other stuff). myHasOverlayScrollbars = relayoutScrollbars( this, scrollLayout, myHasOverlayScrollbars // If last time we did relayouting, we should restore it back. ); } else { myHasOverlayScrollbars = false; } } private boolean relayoutScrollbars(@NotNull JComponent container, @NotNull ScrollPaneLayout layout, boolean forceRelayout) { JViewport viewport = layout.getViewport(); if (viewport == null) return false; JScrollBar vsb = layout.getVerticalScrollBar(); JScrollBar hsb = layout.getHorizontalScrollBar(); JViewport colHead = layout.getColumnHeader(); JViewport rowHead = layout.getRowHeader(); Rectangle viewportBounds = viewport.getBounds(); boolean extendViewportUnderVScrollbar = vsb != null && shouldExtendViewportUnderScrollbar(vsb); boolean extendViewportUnderHScrollbar = hsb != null && shouldExtendViewportUnderScrollbar(hsb); boolean hasOverlayScrollbars = extendViewportUnderVScrollbar || extendViewportUnderHScrollbar; if (!hasOverlayScrollbars && !forceRelayout) return false; container.setComponentZOrder(viewport, container.getComponentCount() - 1); if (vsb != null) container.setComponentZOrder(vsb, 0); if (hsb != null) container.setComponentZOrder(hsb, 0); if (extendViewportUnderVScrollbar) { int x2 = Math.max(vsb.getX() + vsb.getWidth(), viewportBounds.x + viewportBounds.width); viewportBounds.x = Math.min(viewportBounds.x, vsb.getX()); viewportBounds.width = x2 - viewportBounds.x; } if (extendViewportUnderHScrollbar) { int y2 = Math.max(hsb.getY() + hsb.getHeight(), viewportBounds.y + viewportBounds.height); viewportBounds.y = Math.min(viewportBounds.y, hsb.getY()); viewportBounds.height = y2 - viewportBounds.y; } if (extendViewportUnderVScrollbar) { if (hsb != null) { Rectangle scrollbarBounds = hsb.getBounds(); scrollbarBounds.width = viewportBounds.x + viewportBounds.width - scrollbarBounds.x; hsb.setBounds(scrollbarBounds); } if (colHead != null) { Rectangle headerBounds = colHead.getBounds(); headerBounds.width = viewportBounds.width; colHead.setBounds(headerBounds); } hideFromView(layout.getCorner(UPPER_RIGHT_CORNER)); hideFromView(layout.getCorner(LOWER_RIGHT_CORNER)); } if (extendViewportUnderHScrollbar) { if (vsb != null) { Rectangle scrollbarBounds = vsb.getBounds(); scrollbarBounds.height = viewportBounds.y + viewportBounds.height - scrollbarBounds.y; vsb.setBounds(scrollbarBounds); } if (rowHead != null) { Rectangle headerBounds = rowHead.getBounds(); headerBounds.height = viewportBounds.height; rowHead.setBounds(headerBounds); } hideFromView(layout.getCorner(LOWER_LEFT_CORNER)); hideFromView(layout.getCorner(LOWER_RIGHT_CORNER)); } viewport.setBounds(viewportBounds); return hasOverlayScrollbars; } private boolean shouldExtendViewportUnderScrollbar(@Nullable JScrollBar scrollbar) { if (scrollbar == null || !scrollbar.isVisible()) return false; return isOverlaidScrollbar(scrollbar); } protected boolean isOverlaidScrollbar(@Nullable JScrollBar scrollbar) { if (!ButtonlessScrollBarUI.isMacOverlayScrollbarSupported()) return false; ScrollBarUI vsbUI = scrollbar == null ? null : scrollbar.getUI(); return vsbUI instanceof ButtonlessScrollBarUI && !((ButtonlessScrollBarUI)vsbUI).alwaysShowTrack(); } private static void hideFromView(Component component) { if (component == null) return; component.setBounds(-10, -10, 1, 1); } private class MyScrollBar extends ScrollBar implements IdeGlassPane.TopComponent { public MyScrollBar(int orientation) { super(orientation); } @Override public void updateUI() { ScrollBarUI ui = getUI(); if (ui instanceof DefaultScrollBarUI) return; setUI(JBScrollBar.createUI(this)); } @Override public boolean canBePreprocessed(MouseEvent e) { return JBScrollPane.canBePreprocessed(e, this); } } public static boolean canBePreprocessed(MouseEvent e, JScrollBar bar) { if (e.getID() == MouseEvent.MOUSE_MOVED || e.getID() == MouseEvent.MOUSE_PRESSED) { ScrollBarUI ui = bar.getUI(); if (ui instanceof BasicScrollBarUI) { BasicScrollBarUI bui = (BasicScrollBarUI)ui; try { Rectangle rect = (Rectangle)ReflectionUtil.getDeclaredMethod(BasicScrollBarUI.class, "getThumbBounds", ArrayUtil.EMPTY_CLASS_ARRAY).invoke(bui); Point point = SwingUtilities.convertPoint(e.getComponent(), e.getX(), e.getY(), bar); return !rect.contains(point); } catch (Exception e1) { return true; } } else if (ui instanceof DefaultScrollBarUI) { DefaultScrollBarUI dui = (DefaultScrollBarUI)ui; Point point = e.getLocationOnScreen(); SwingUtilities.convertPointFromScreen(point, bar); return !dui.isThumbContains(point.x, point.y); } } return true; } private static class Corner extends JPanel { private final String myPos; public Corner(String pos) { myPos = pos; ScrollColorProducer.setBackground(this); ScrollColorProducer.setForeground(this); } @Override protected void paintComponent(Graphics g) { g.setColor(getBackground()); g.fillRect(0, 0, getWidth(), getHeight()); if (SystemInfo.isMac || !Registry.is("ide.scroll.track.border.paint")) return; g.setColor(getForeground()); int x2 = getWidth() - 1; int y2 = getHeight() - 1; if (myPos == UPPER_LEFT_CORNER || myPos == UPPER_RIGHT_CORNER) { g.drawLine(0, y2, x2, y2); } if (myPos == LOWER_LEFT_CORNER || myPos == LOWER_RIGHT_CORNER) { g.drawLine(0, 0, x2, 0); } if (myPos == UPPER_LEFT_CORNER || myPos == LOWER_LEFT_CORNER) { g.drawLine(x2, 0, x2, y2); } if (myPos == UPPER_RIGHT_CORNER || myPos == LOWER_RIGHT_CORNER) { g.drawLine(0, 0, 0, y2); } } } private static class ViewportBorder extends LineBorder { public ViewportBorder(int thickness) { super(null, thickness); } @Override public void paintBorder(Component c, Graphics g, int x, int y, int width, int height) { updateColor(c); super.paintBorder(c, g, x, y, width, height); } private void updateColor(Component c) { if (!(c instanceof JScrollPane)) return; lineColor = getViewBackground((JScrollPane)c); } } /** * These client properties modify a scroll pane layout. * Use the class object as a property key. * * @see #putClientProperty(Object, Object) */ public enum Flip { NONE, VERTICAL, HORIZONTAL, BOTH } /** * These client properties show a component position on a scroll pane. * It is set by internal layout manager of the scroll pane. */ public enum Alignment { TOP, LEFT, RIGHT, BOTTOM; public static Alignment get(JComponent component) { if (component != null) { Object property = component.getClientProperty(Alignment.class); if (property instanceof Alignment) return (Alignment)property; Container parent = component.getParent(); if (parent instanceof JScrollPane) { JScrollPane pane = (JScrollPane)parent; if (component == pane.getColumnHeader()) { return TOP; } if (component == pane.getHorizontalScrollBar()) { return BOTTOM; } boolean ltr = pane.getComponentOrientation().isLeftToRight(); if (component == pane.getVerticalScrollBar()) { return ltr ? RIGHT : LEFT; } if (component == pane.getRowHeader()) { return ltr ? LEFT : RIGHT; } } // assume alignment for a scroll bar, // which is not contained in a scroll pane if (component instanceof JScrollBar) { JScrollBar bar = (JScrollBar)component; switch (bar.getOrientation()) { case Adjustable.HORIZONTAL: return BOTTOM; case Adjustable.VERTICAL: return bar.getComponentOrientation().isLeftToRight() ? RIGHT : LEFT; } } } return null; } } /** * ScrollPaneLayout implementation that supports * ScrollBar flipping and non-opaque ScrollBars. */ private static class Layout extends ScrollPaneLayout { private static final Insets EMPTY_INSETS = new Insets(0, 0, 0, 0); @Override public void layoutContainer(Container parent) { JScrollPane pane = (JScrollPane)parent; // Calculate inner bounds of the scroll pane Rectangle bounds = new Rectangle(pane.getWidth(), pane.getHeight()); JBInsets.removeFrom(bounds, pane.getInsets()); // Determine positions of scroll bars on the scroll pane Object property = pane.getClientProperty(Flip.class); Flip flip = property instanceof Flip ? (Flip)property : Flip.NONE; boolean hsbOnTop = flip == Flip.BOTH || flip == Flip.VERTICAL; boolean vsbOnLeft = pane.getComponentOrientation().isLeftToRight() ? flip == Flip.BOTH || flip == Flip.HORIZONTAL : flip == Flip.NONE || flip == Flip.VERTICAL; // If there's a visible row header remove the space it needs. // The row header is treated as if it were fixed width, arbitrary height. Rectangle rowHeadBounds = new Rectangle(bounds.x, 0, 0, 0); if (rowHead != null && rowHead.isVisible()) { rowHeadBounds.width = min(bounds.width, rowHead.getPreferredSize().width); bounds.width -= rowHeadBounds.width; if (vsbOnLeft) { rowHeadBounds.x += bounds.width; } else { bounds.x += rowHeadBounds.width; } } // If there's a visible column header remove the space it needs. // The column header is treated as if it were fixed height, arbitrary width. Rectangle colHeadBounds = new Rectangle(0, bounds.y, 0, 0); if (colHead != null && colHead.isVisible()) { colHeadBounds.height = min(bounds.height, colHead.getPreferredSize().height); bounds.height -= colHeadBounds.height; if (hsbOnTop) { colHeadBounds.y += bounds.height; } else { bounds.y += colHeadBounds.height; } } // If there's a JScrollPane.viewportBorder, remove the space it occupies Border border = pane.getViewportBorder(); Insets insets = border == null ? null : border.getBorderInsets(parent); JBInsets.removeFrom(bounds, insets); if (insets == null) insets = EMPTY_INSETS; // At this point: // colHeadBounds is correct except for its width and x // rowHeadBounds is correct except for its height and y // bounds - the space available for the viewport and scroll bars // Once we're through computing the dimensions of these three parts // we can go back and set the bounds for the corners and the dimensions of // colHeadBounds.x, colHeadBounds.width, rowHeadBounds.y, rowHeadBounds.height. boolean isEmpty = bounds.width < 0 || bounds.height < 0; Component view = viewport == null ? null : viewport.getView(); Dimension viewPreferredSize = view == null ? new Dimension() : view.getPreferredSize(); if (view instanceof JComponent) JBViewport.fixPreferredSize(viewPreferredSize, (JComponent)view, vsb, hsb); Dimension viewportExtentSize = viewport == null ? new Dimension() : viewport.toViewCoordinates(bounds.getSize()); // If the view is tracking the viewports width we don't bother with a horizontal scrollbar. // If the view is tracking the viewports height we don't bother with a vertical scrollbar. Scrollable scrollable = null; boolean viewTracksViewportWidth = false; boolean viewTracksViewportHeight = false; // Don't bother checking the Scrollable methods if there is no room for the viewport, // we aren't going to show any scroll bars in this case anyway. if (!isEmpty && view instanceof Scrollable) { scrollable = (Scrollable)view; viewTracksViewportWidth = scrollable.getScrollableTracksViewportWidth(); viewTracksViewportHeight = scrollable.getScrollableTracksViewportHeight(); } // If there's a vertical scroll bar and we need one, allocate space for it. // A vertical scroll bar is considered to be fixed width, arbitrary height. boolean vsbOpaque = false; boolean vsbNeeded = false; int vsbPolicy = pane.getVerticalScrollBarPolicy(); if (!isEmpty && vsbPolicy != VERTICAL_SCROLLBAR_NEVER) { vsbNeeded = vsbPolicy == VERTICAL_SCROLLBAR_ALWAYS || !viewTracksViewportHeight && viewPreferredSize.height > viewportExtentSize.height; } Rectangle vsbBounds = new Rectangle(0, bounds.y - insets.top, 0, 0); if (vsb != null) { if (!SystemInfo.isMac && view instanceof JTable) vsb.setOpaque(true); vsbOpaque = vsb.isOpaque(); if (vsbNeeded) { adjustForVSB(bounds, insets, vsbBounds, vsbOpaque, vsbOnLeft); if (vsbOpaque && viewport != null) { viewportExtentSize = viewport.toViewCoordinates(bounds.getSize()); } } } // If there's a horizontal scroll bar and we need one, allocate space for it. // A horizontal scroll bar is considered to be fixed height, arbitrary width. boolean hsbOpaque = false; boolean hsbNeeded = false; int hsbPolicy = pane.getHorizontalScrollBarPolicy(); if (!isEmpty && hsbPolicy != HORIZONTAL_SCROLLBAR_NEVER) { hsbNeeded = hsbPolicy == HORIZONTAL_SCROLLBAR_ALWAYS || !viewTracksViewportWidth && viewPreferredSize.width > viewportExtentSize.width; } Rectangle hsbBounds = new Rectangle(bounds.x - insets.left, 0, 0, 0); if (hsb != null) { if (!SystemInfo.isMac && view instanceof JTable) hsb.setOpaque(true); hsbOpaque = hsb.isOpaque(); if (hsbNeeded) { adjustForHSB(bounds, insets, hsbBounds, hsbOpaque, hsbOnTop); if (hsbOpaque && viewport != null) { // If we added the horizontal scrollbar and reduced the vertical space // we may have to add the vertical scrollbar, if that hasn't been done so already. if (vsb != null && !vsbNeeded && vsbPolicy != VERTICAL_SCROLLBAR_NEVER) { viewportExtentSize = viewport.toViewCoordinates(bounds.getSize()); vsbNeeded = viewPreferredSize.height > viewportExtentSize.height; if (vsbNeeded) adjustForVSB(bounds, insets, vsbBounds, vsbOpaque, vsbOnLeft); } } } } // Set the size of the viewport first, and then recheck the Scrollable methods. // Some components base their return values for the Scrollable methods on the size of the viewport, // so that if we don't ask after resetting the bounds we may have gotten the wrong answer. if (viewport != null) { viewport.setBounds(bounds); if (scrollable != null && hsbOpaque && vsbOpaque) { viewTracksViewportWidth = scrollable.getScrollableTracksViewportWidth(); viewTracksViewportHeight = scrollable.getScrollableTracksViewportHeight(); viewportExtentSize = viewport.toViewCoordinates(bounds.getSize()); boolean vsbNeededOld = vsbNeeded; if (vsb != null && vsbPolicy == VERTICAL_SCROLLBAR_AS_NEEDED) { boolean vsbNeededNew = !viewTracksViewportHeight && viewPreferredSize.height > viewportExtentSize.height; if (vsbNeeded != vsbNeededNew) { vsbNeeded = vsbNeededNew; if (vsbNeeded) { adjustForVSB(bounds, insets, vsbBounds, vsbOpaque, vsbOnLeft); } else if (vsbOpaque) { bounds.width += vsbBounds.width; } if (vsbOpaque) viewportExtentSize = viewport.toViewCoordinates(bounds.getSize()); } } boolean hsbNeededOld = hsbNeeded; if (hsb != null && hsbPolicy == HORIZONTAL_SCROLLBAR_AS_NEEDED) { boolean hsbNeededNew = !viewTracksViewportWidth && viewPreferredSize.width > viewportExtentSize.width; if (hsbNeeded != hsbNeededNew) { hsbNeeded = hsbNeededNew; if (hsbNeeded) { adjustForHSB(bounds, insets, hsbBounds, hsbOpaque, hsbOnTop); } else if (hsbOpaque) { bounds.height += hsbBounds.height; } if (hsbOpaque && vsb != null && !vsbNeeded && vsbPolicy != VERTICAL_SCROLLBAR_NEVER) { viewportExtentSize = viewport.toViewCoordinates(bounds.getSize()); vsbNeeded = viewPreferredSize.height > viewportExtentSize.height; if (vsbNeeded) adjustForVSB(bounds, insets, vsbBounds, vsbOpaque, vsbOnLeft); } } } if (hsbNeededOld != hsbNeeded || vsbNeededOld != vsbNeeded) { viewport.setBounds(bounds); // You could argue that we should recheck the Scrollable methods again until they stop changing, // but they might never stop changing, so we stop here and don't do any additional checks. } } } // Set the bounds of the row header. rowHeadBounds.y = bounds.y - insets.top; rowHeadBounds.height = bounds.height + insets.top + insets.bottom; if (rowHead != null) { rowHead.setBounds(rowHeadBounds); rowHead.putClientProperty(Alignment.class, vsbOnLeft ? Alignment.RIGHT : Alignment.LEFT); } // Set the bounds of the column header. colHeadBounds.x = bounds.x - insets.left; colHeadBounds.width = bounds.width + insets.left + insets.right; if (colHead != null) { colHead.setBounds(colHeadBounds); colHead.putClientProperty(Alignment.class, hsbOnTop ? Alignment.BOTTOM : Alignment.TOP); } // Calculate overlaps for translucent scroll bars int overlapWidth = 0; int overlapHeight = 0; if (vsbNeeded && !vsbOpaque && hsbNeeded && !hsbOpaque) { overlapWidth = vsbBounds.width; // shrink horizontally //overlapHeight = hsbBounds.height; // shrink vertically } // Set the bounds of the vertical scroll bar. vsbBounds.y = bounds.y - insets.top; vsbBounds.height = bounds.height + insets.top + insets.bottom; if (vsb != null) { vsb.setVisible(vsbNeeded); if (vsbNeeded) { if (vsbOpaque && colHead != null && UIManager.getBoolean("ScrollPane.fillUpperCorner")) { if ((vsbOnLeft ? upperLeft : upperRight) == null) { // This is used primarily for GTK L&F, which needs to extend // the vertical scrollbar to fill the upper corner near the column header. // Note that we skip this step (and use the default behavior) // if the user has set a custom corner component. if (!hsbOnTop) vsbBounds.y -= colHeadBounds.height; vsbBounds.height += colHeadBounds.height; } } int overlapY = !hsbOnTop ? 0 : overlapHeight; vsb.setBounds(vsbBounds.x, vsbBounds.y + overlapY, vsbBounds.width, vsbBounds.height - overlapHeight); vsb.putClientProperty(Alignment.class, vsbOnLeft ? Alignment.LEFT : Alignment.RIGHT); } // Modify the bounds of the translucent scroll bar. if (!vsbOpaque) { if (!vsbOnLeft) vsbBounds.x += vsbBounds.width; vsbBounds.width = 0; } } // Set the bounds of the horizontal scroll bar. hsbBounds.x = bounds.x - insets.left; hsbBounds.width = bounds.width + insets.left + insets.right; if (hsb != null) { hsb.setVisible(hsbNeeded); if (hsbNeeded) { if (hsbOpaque && rowHead != null && UIManager.getBoolean("ScrollPane.fillLowerCorner")) { if ((vsbOnLeft ? lowerRight : lowerLeft) == null) { // This is used primarily for GTK L&F, which needs to extend // the horizontal scrollbar to fill the lower corner near the row header. // Note that we skip this step (and use the default behavior) // if the user has set a custom corner component. if (!vsbOnLeft) hsbBounds.x -= rowHeadBounds.width; hsbBounds.width += rowHeadBounds.width; } } int overlapX = !vsbOnLeft ? 0 : overlapWidth; hsb.setBounds(hsbBounds.x + overlapX, hsbBounds.y, hsbBounds.width - overlapWidth, hsbBounds.height); hsb.putClientProperty(Alignment.class, hsbOnTop ? Alignment.TOP : Alignment.BOTTOM); } // Modify the bounds of the translucent scroll bar. if (!hsbOpaque) { if (!hsbOnTop) hsbBounds.y += hsbBounds.height; hsbBounds.height = 0; } } // Set the bounds of the corners. if (lowerLeft != null) { lowerLeft.setBounds(vsbOnLeft ? vsbBounds.x : rowHeadBounds.x, hsbOnTop ? colHeadBounds.y : hsbBounds.y, vsbOnLeft ? vsbBounds.width : rowHeadBounds.width, hsbOnTop ? colHeadBounds.height : hsbBounds.height); } if (lowerRight != null) { lowerRight.setBounds(vsbOnLeft ? rowHeadBounds.x : vsbBounds.x, hsbOnTop ? colHeadBounds.y : hsbBounds.y, vsbOnLeft ? rowHeadBounds.width : vsbBounds.width, hsbOnTop ? colHeadBounds.height : hsbBounds.height); } if (upperLeft != null) { upperLeft.setBounds(vsbOnLeft ? vsbBounds.x : rowHeadBounds.x, hsbOnTop ? hsbBounds.y : colHeadBounds.y, vsbOnLeft ? vsbBounds.width : rowHeadBounds.width, hsbOnTop ? hsbBounds.height : colHeadBounds.height); } if (upperRight != null) { upperRight.setBounds(vsbOnLeft ? rowHeadBounds.x : vsbBounds.x, hsbOnTop ? hsbBounds.y : colHeadBounds.y, vsbOnLeft ? rowHeadBounds.width : vsbBounds.width, hsbOnTop ? hsbBounds.height : colHeadBounds.height); } if (!vsbOpaque && vsbNeeded || !hsbOpaque && hsbNeeded) { fixComponentZOrder(vsb, 0); fixComponentZOrder(viewport, -1); } } private static void fixComponentZOrder(Component component, int index) { if (component != null) { Container parent = component.getParent(); synchronized (parent.getTreeLock()) { if (index < 0) index += parent.getComponentCount(); parent.setComponentZOrder(component, index); } } } private void adjustForVSB(Rectangle bounds, Insets insets, Rectangle vsbBounds, boolean vsbOpaque, boolean vsbOnLeft) { vsbBounds.width = !vsb.isEnabled() ? 0 : min(bounds.width, vsb.getPreferredSize().width); if (vsbOnLeft) { vsbBounds.x = bounds.x - insets.left/* + vsbBounds.width*/; if (vsbOpaque) bounds.x += vsbBounds.width; } else { vsbBounds.x = bounds.x + bounds.width + insets.right - vsbBounds.width; } if (vsbOpaque) bounds.width -= vsbBounds.width; } private void adjustForHSB(Rectangle bounds, Insets insets, Rectangle hsbBounds, boolean hsbOpaque, boolean hsbOnTop) { hsbBounds.height = !hsb.isEnabled() ? 0 : min(bounds.height, hsb.getPreferredSize().height); if (hsbOnTop) { hsbBounds.y = bounds.y - insets.top/* + hsbBounds.height*/; if (hsbOpaque) bounds.y += hsbBounds.height; } else { hsbBounds.y = bounds.y + bounds.height + insets.bottom - hsbBounds.height; } if (hsbOpaque) bounds.height -= hsbBounds.height; } private static int min(int one, int two) { return Math.max(0, Math.min(one, two)); } } private static class ProtectedPainter implements RegionPainter<Float> { private RegionPainter<Float> myPainter; private RegionPainter<Float> myFallback; public ProtectedPainter(RegionPainter<Float> painter, RegionPainter<Float> fallback) { myPainter = painter; myFallback = fallback; } @Override public void paint(Graphics2D g, int x, int y, int width, int height, Float value) { RegionPainter<Float> painter = myFallback; if (myPainter != null) { try { myPainter.paint(g, x, y, width, height, value); return; } catch (Throwable exception) { // do not try to use myPainter again on other systems if (!SystemInfo.isWindows) myPainter = null; } } if (painter != null) { painter.paint(g, x, y, width, height, value); } } } private static class AlphaPainter extends RegionPainter.Alpha { float myBase; float myDelta; Color myFillColor; private AlphaPainter(float base, float delta, Color fill) { myBase = base; myDelta = delta; myFillColor = fill; } @Override protected void paint(Graphics2D g, int x, int y, int width, int height) { if (myFillColor != null) { g.setColor(myFillColor); g.fillRect(x, y, width, height); } } @Override protected float getAlpha(Float value) { return value != null ? myBase + myDelta * value : 0; } } private static class RoundThumbPainter extends ThumbPainter { private final int myBorder; private RoundThumbPainter(int border, float base, float delta, Color fill, Color draw) { super(base, delta, fill, draw); myBorder = border; } @Override protected void paint(Graphics2D g, int x, int y, int width, int height) { Object old = g.getRenderingHint(RenderingHints.KEY_ANTIALIASING); g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); x += myBorder; y += myBorder; width -= myBorder + myBorder; height -= myBorder + myBorder; int arc = Math.min(width, height); if (myFillColor != null) { g.setColor(myFillColor); g.fillRoundRect(x, y, width, height, arc, arc); } if (myDrawColor != null) { g.setColor(myDrawColor); if (UIUtil.isRetina(g)) { g.draw(new RoundRectangle2D.Double(.5 + x, .5 + y, width - 1, height - 1, arc, arc)); } else { g.drawRoundRect(x, y, width - 1, height - 1, arc, arc); } } g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, old); } } private static class ThumbPainter extends AlphaPainter { Color myDrawColor; private ThumbPainter(float base, float delta, Color fill, Color draw) { super(base, delta, fill); myDrawColor = draw; } @Override protected void paint(Graphics2D g, int x, int y, int width, int height) { super.paint(g, x + 1, y + 1, width - 2, height - 2); if (myDrawColor != null) { g.setColor(myDrawColor); if (Registry.is("ide.scroll.thumb.border.rounded")) { g.drawLine(x + 1, y, x + width - 2, y); g.drawLine(x + 1, y + height - 1, x + width - 2, y + height - 1); g.drawLine(x, y + 1, x, y + height - 2); g.drawLine(x + width - 1, y + 1, x + width - 1, y + height - 2); } else { g.drawRect(x, y, width - 1, height - 1); } } } } private static class SubtractThumbPainter extends ThumbPainter { public SubtractThumbPainter(float base, float delta, Color fill, Color draw) { super(base, delta, fill, draw); } @Override protected Composite getComposite(float alpha) { return alpha < 1 ? new SubtractComposite(alpha) : AlphaComposite.SrcOver; } } private static class SubtractComposite implements Composite, CompositeContext { private final float myAlpha; private SubtractComposite(float alpha) { myAlpha = alpha; } private int subtract(int newValue, int oldValue) { float value = (oldValue & 0xFF) - (newValue & 0xFF) * myAlpha; return value <= 0 ? 0 : (int)value; } @Override public CompositeContext createContext(ColorModel src, ColorModel dst, RenderingHints hints) { return isValid(src) && isValid(dst) ? this : AlphaComposite.SrcOver.derive(myAlpha).createContext(src, dst, hints); } private static boolean isValid(ColorModel model) { if (model instanceof DirectColorModel && DataBuffer.TYPE_INT == model.getTransferType()) { DirectColorModel dcm = (DirectColorModel)model; if (0x00FF0000 == dcm.getRedMask() && 0x0000FF00 == dcm.getGreenMask() && 0x000000FF == dcm.getBlueMask()) { return 4 != dcm.getNumComponents() || 0xFF000000 == dcm.getAlphaMask(); } } return false; } @Override public void compose(Raster srcIn, Raster dstIn, WritableRaster dstOut) { int width = Math.min(srcIn.getWidth(), dstIn.getWidth()); int height = Math.min(srcIn.getHeight(), dstIn.getHeight()); int[] srcPixels = new int[width]; int[] dstPixels = new int[width]; for (int y = 0; y < height; y++) { srcIn.getDataElements(0, y, width, 1, srcPixels); dstIn.getDataElements(0, y, width, 1, dstPixels); for (int x = 0; x < width; x++) { int src = srcPixels[x]; int dst = dstPixels[x]; int a = subtract(src >> 24, dst >> 24) << 24; int r = subtract(src >> 16, dst >> 16) << 16; int g = subtract(src >> 8, dst >> 8) << 8; int b = subtract(src, dst); dstPixels[x] = a | r | g | b; } dstOut.setDataElements(0, y, width, 1, dstPixels); } } @Override public void dispose() { } } /** * Indicates whether the specified event is not consumed and does not have unexpected modifiers. * * @param event a mouse wheel event to check for validity * @return {@code true} if the specified event is valid, {@code false} otherwise */ public static boolean isScrollEvent(@NotNull MouseWheelEvent event) { if (event.isConsumed()) return false; // event should not be consumed already if (event.getWheelRotation() == 0) return false; // any rotation expected (forward or backward) return 0 == (SCROLL_MODIFIERS & event.getModifiers()); } private static final int SCROLL_MODIFIERS = // event modifiers allowed during scrolling ~InputEvent.SHIFT_MASK & ~InputEvent.SHIFT_DOWN_MASK & // for horizontal scrolling ~InputEvent.BUTTON1_MASK & ~InputEvent.BUTTON1_DOWN_MASK; // for selection private static class CachedColor { private final String myKey; private String myString; private Color myColor; private CachedColor(String key, String string, Color color) { myKey = key; myString = string; myColor = color; } private Color get() { String string = Registry.stringValue(myKey); if (!string.equals(myString)) { try { myColor = Color.decode(string); } catch (Exception ignore) { myColor = null; } finally { myString = string; } } return myColor; } } private static class CachedValue { private final String myKey; private String myString; private float myValue; private CachedValue(String key, String string, float value) { myKey = key; myString = string; myValue = value; } private float get() { String string = Registry.stringValue(myKey); if (!string.equals(myString)) { try { myValue = Float.parseFloat(string); } catch (Exception ignore) { } finally { myString = string; } } return myValue; } } private static class ThumbPainterDelegate<P extends AlphaPainter> implements RegionPainter<Float> { final P myPainter; private final CachedValue myBase; private final CachedValue myDelta; private final CachedColor myFillColor; private ThumbPainterDelegate(P painter, CachedValue base, CachedValue delta, CachedColor fill) { myPainter = painter; myBase = base; myDelta = delta; myFillColor = fill; } @Override public void paint(Graphics2D g, int x, int y, int width, int height, Float object) { myPainter.myBase = myBase.get(); myPainter.myDelta = myDelta.get(); myPainter.myFillColor = myFillColor.get(); myPainter.paint(g, x, y, width, height, object); } } private static class DefaultThumbPainter extends ThumbPainterDelegate<ThumbPainter> { private final CachedColor myDrawColor; private DefaultThumbPainter(ThumbPainter painter, CachedValue base, CachedValue delta, CachedColor fill, CachedColor draw) { super(painter, base, delta, fill); myDrawColor = draw; } @Override public final void paint(Graphics2D g, int x, int y, int width, int height, Float object) { myPainter.myDrawColor = myDrawColor.get(); super.paint(g, x, y, width, height, object); } } }
IDEA-157667 Editor's scrollbar thumb: alpha and colors tune border alignment for Retina on Mac
platform/platform-api/src/com/intellij/ui/components/JBScrollPane.java
IDEA-157667 Editor's scrollbar thumb: alpha and colors tune border alignment for Retina on Mac
<ide><path>latform/platform-api/src/com/intellij/ui/components/JBScrollPane.java <ide> if (myDrawColor != null) { <ide> g.setColor(myDrawColor); <ide> if (UIUtil.isRetina(g)) { <del> g.draw(new RoundRectangle2D.Double(.5 + x, .5 + y, width - 1, height - 1, arc, arc)); <add> g.drawRoundRect(x, y, width, height, arc, arc); <ide> } <ide> else { <ide> g.drawRoundRect(x, y, width - 1, height - 1, arc, arc);
Java
lgpl-2.1
db0d93db78e32d1ba6c6ce01bdaca89deffd276a
0
wesley1001/orbeon-forms,ajw625/orbeon-forms,orbeon/orbeon-forms,ajw625/orbeon-forms,evlist/orbeon-forms,orbeon/orbeon-forms,joansmith/orbeon-forms,ajw625/orbeon-forms,martinluther/orbeon-forms,wesley1001/orbeon-forms,evlist/orbeon-forms,tanbo800/orbeon-forms,wesley1001/orbeon-forms,tanbo800/orbeon-forms,joansmith/orbeon-forms,brunobuzzi/orbeon-forms,wesley1001/orbeon-forms,ajw625/orbeon-forms,brunobuzzi/orbeon-forms,tanbo800/orbeon-forms,orbeon/orbeon-forms,tanbo800/orbeon-forms,evlist/orbeon-forms,orbeon/orbeon-forms,martinluther/orbeon-forms,joansmith/orbeon-forms,brunobuzzi/orbeon-forms,evlist/orbeon-forms,martinluther/orbeon-forms,evlist/orbeon-forms,joansmith/orbeon-forms,brunobuzzi/orbeon-forms,martinluther/orbeon-forms
/** * Copyright (C) 2010 Orbeon, Inc. * * This program is free software; you can redistribute it and/or modify it under the terms of the * GNU Lesser General Public License as published by the Free Software Foundation; either version * 2.1 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU Lesser General Public License for more details. * * The full text of the license is available at http://www.gnu.org/copyleft/lesser.html */ package org.orbeon.oxf.xforms.processor; import org.apache.commons.pool.ObjectPool; import org.apache.log4j.Logger; import org.dom4j.Document; import org.orbeon.oxf.common.OXFException; import org.orbeon.oxf.pipeline.api.ExternalContext; import org.orbeon.oxf.pipeline.api.PipelineContext; import org.orbeon.oxf.processor.*; import org.orbeon.oxf.processor.generator.URLGenerator; import org.orbeon.oxf.util.IndentedLogger; import org.orbeon.oxf.util.LoggerFactory; import org.orbeon.oxf.util.UUIDUtils; import org.orbeon.oxf.xforms.*; import org.orbeon.oxf.xforms.analysis.XFormsAnnotatorContentHandler; import org.orbeon.oxf.xforms.analysis.XFormsExtractorContentHandler; import org.orbeon.oxf.xforms.processor.handlers.*; import org.orbeon.oxf.xforms.state.XFormsDocumentCache; import org.orbeon.oxf.xforms.state.XFormsState; import org.orbeon.oxf.xforms.state.XFormsStateManager; import org.orbeon.oxf.xforms.submission.AsynchronousSubmissionManager; import org.orbeon.oxf.xml.*; import org.orbeon.oxf.xml.dom4j.LocationDocumentResult; import org.xml.sax.ContentHandler; import org.xml.sax.SAXException; import javax.xml.transform.sax.TransformerHandler; import java.io.IOException; import java.util.List; /** * This processor handles XForms initialization and produces an XHTML document which is a * translation from the source XForms + XHTML. */ public class XFormsToXHTML extends ProcessorImpl { public static final String LOGGING_CATEGORY = "html"; private static final Logger logger = LoggerFactory.createLogger(XFormsToXHTML.class); private static final String INPUT_ANNOTATED_DOCUMENT = "annotated-document"; private static final String OUTPUT_DOCUMENT = "document"; private static final String OUTPUT_CACHE_KEY = "dynamicState"; public XFormsToXHTML() { addInputInfo(new ProcessorInputOutputInfo(INPUT_ANNOTATED_DOCUMENT)); addInputInfo(new ProcessorInputOutputInfo("namespace")); // This input ensures that we depend on a portlet namespace addOutputInfo(new ProcessorInputOutputInfo(OUTPUT_DOCUMENT)); } /** * Case where an XML response must be generated. */ @Override public ProcessorOutput createOutput(final String outputName) { final ProcessorOutput output = new URIProcessorOutputImpl(XFormsToXHTML.this, outputName, INPUT_ANNOTATED_DOCUMENT) { public void readImpl(final PipelineContext pipelineContext, ContentHandler contentHandler) { doIt(pipelineContext, contentHandler, this, outputName); } @Override protected boolean supportsLocalKeyValidity() { return true; } @Override public KeyValidity getLocalKeyValidity(PipelineContext pipelineContext, URIReferences uriReferences) { // NOTE: As of 2010-03, caching of the output should never happen // o more work is needed to make this work properly // o not many use cases benefit return null; } }; addOutput(outputName, output); return output; } @Override public ProcessorInput createInput(final String inputName) { if (inputName.equals(INPUT_ANNOTATED_DOCUMENT)) { // Insert processor on the fly to handle dependencies. This is a bit tricky: we used to have an // XSLT/XInclude before XFormsToXHTML. This step handled XBL dependencies. Now that it is removed, we // need a mechanism to detect dependencies. So we insert a step here. // Return an input which handles dependencies // The system actually has two processors: // o stage1 is the processor automatically inserted below for the purpose of handling dependencies // o stage2 is the actual oxf:xforms-to-xhtml which actually does XForms processing final ProcessorInput originalInput = super.createInput(inputName); return new DependenciesProcessorInput(inputName, originalInput) { @Override protected URIProcessorOutputImpl.URIReferences getURIReferences(PipelineContext pipelineContext) { // Return dependencies object, set by stage2 before reading its input return ((Stage2TransientState) XFormsToXHTML.this.getState(pipelineContext)).stage1CacheableState; } }; } else { return super.createInput(inputName); } } @Override public void reset(PipelineContext context) { setState(context, new Stage2TransientState()); } // State passed by the second stage to the first stage. // NOTE: This extends URIReferencesState because we use URIProcessorOutputImpl. // It is not clear that we absolutely need URIProcessorOutputImpl in the second stage, but right now we keep it, // because XFormsURIResolver requires URIProcessorOutputImpl. private class Stage2TransientState extends URIProcessorOutputImpl.URIReferencesState { public Stage1CacheableState stage1CacheableState; } private void doIt(final PipelineContext pipelineContext, ContentHandler contentHandler, final URIProcessorOutputImpl processorOutput, String outputName) { final ExternalContext externalContext = XFormsUtils.getExternalContext(pipelineContext); final IndentedLogger indentedLogger = XFormsContainingDocument.getIndentedLogger(XFormsToXHTML.logger, XFormsServer.getLogger(), LOGGING_CATEGORY); // ContainingDocument and XFormsState created below final XFormsContainingDocument[] containingDocument = new XFormsContainingDocument[1]; final XFormsState[] xformsState = new XFormsState[1]; final boolean[] cachedInput = new boolean[] { false } ; // Read and try to cache the complete XForms+XHTML document with annotations final Stage2CacheableState stage2CacheableState = (Stage2CacheableState) readCacheInputAsObject(pipelineContext, getInputByName(INPUT_ANNOTATED_DOCUMENT), new CacheableInputReader() { public Object read(PipelineContext pipelineContext, ProcessorInput processorInput) { // Create URIResolver final XFormsURIResolver uriResolver = new XFormsURIResolver(XFormsToXHTML.this, processorOutput, pipelineContext, INPUT_ANNOTATED_DOCUMENT, URLGenerator.DEFAULT_HANDLE_XINCLUDE); // Compute annotated XForms document + static state document final Stage1CacheableState stage1CacheableState = new Stage1CacheableState(); final Stage2CacheableState stage2CacheableState; { final TransformerHandler identity = TransformerUtils.getIdentityTransformerHandler(); // TODO: Use TinyTree instead of dom4j Document final LocationDocumentResult documentResult = new LocationDocumentResult(); identity.setResult(documentResult); final XFormsAnnotatorContentHandler.Metadata metadata = new XFormsAnnotatorContentHandler.Metadata(); final SAXStore annotatedSAXStore = new SAXStore(new XFormsExtractorContentHandler(externalContext, identity, metadata)); // Store dependencies container in state before reading ((Stage2TransientState) XFormsToXHTML.this.getState(pipelineContext)).stage1CacheableState = stage1CacheableState; // Read the input through the annotator and gather namespace mappings readInputAsSAX(pipelineContext, processorInput, new XFormsAnnotatorContentHandler(annotatedSAXStore, externalContext, metadata)); // Get static state document and create static state object final Document staticStateDocument = documentResult.getDocument(); final XFormsStaticState xformsStaticState = new XFormsStaticState(pipelineContext, staticStateDocument, metadata, annotatedSAXStore); // Update input dependencies object stage2CacheableState = new Stage2CacheableState(annotatedSAXStore, xformsStaticState); } // Create document here so we can do appropriate analysis of caching dependencies createCacheContainingDocument(pipelineContext, uriResolver, stage2CacheableState.getXFormsEngineStaticState(), containingDocument, xformsState); // Gather set caching dependencies gatherInputDependencies(containingDocument[0], indentedLogger, stage1CacheableState); return stage2CacheableState; } @Override public void foundInCache() { cachedInput[0] = true; } @Override public void storedInCache() { cachedInput[0] = true; } }); try { // Create containing document if not done yet final String staticStateUUID; if (containingDocument[0] == null) { // In this case, we found the static state and more in the cache, but we must now create a new XFormsContainingDocument from this information indentedLogger.logDebug("", "annotated document and static state obtained from cache; creating containing document."); // Create URIResolver and XFormsContainingDocument final XFormsURIResolver uriResolver = new XFormsURIResolver(XFormsToXHTML.this, processorOutput, pipelineContext, INPUT_ANNOTATED_DOCUMENT, URLGenerator.DEFAULT_HANDLE_XINCLUDE); createCacheContainingDocument(pipelineContext, uriResolver, stage2CacheableState.getXFormsEngineStaticState(), containingDocument, xformsState); } else { indentedLogger.logDebug("", "annotated document and static state not obtained from cache."); } // Get static state UUID if (cachedInput[0]) { staticStateUUID = stage2CacheableState.getXFormsEngineStaticState().getUUID(); indentedLogger.logDebug("", "found cached static state UUID."); } else { staticStateUUID = null; indentedLogger.logDebug("", "did not find cached static state UUID."); } // Try to cache dynamic state UUID associated with the output // NOTE: As of 2010-03, caching of the output should never happen because we disable it final String dynamicStateUUID = (String) getCacheOutputObject(pipelineContext, processorOutput, OUTPUT_CACHE_KEY, new OutputObjectCreator() { public Object create(PipelineContext pipelineContext, ProcessorOutput processorOutput) { indentedLogger.logDebug("", "caching dynamic state UUID for resulting document."); return UUIDUtils.createPseudoUUID(); } @Override public void foundInCache() { indentedLogger.logDebug("", "found cached dynamic state UUID for resulting document."); } @Override public void unableToCache() { indentedLogger.logDebug("", "cannot cache dynamic state UUID for resulting document."); } }); // Output resulting document if (outputName.equals("document")) { // Normal case where we output XHTML // Get encoded state for the client final XFormsState encodedClientState = XFormsStateManager.getInitialEncodedClientState(containingDocument[0], externalContext, xformsState[0], staticStateUUID, dynamicStateUUID); outputResponseDocument(pipelineContext, externalContext, indentedLogger, stage2CacheableState.getAnnotatedSAXStore(), containingDocument[0], contentHandler, encodedClientState); } else { // Output in test mode testOutputResponseState(pipelineContext, containingDocument[0], indentedLogger, contentHandler, new XFormsStateManager.XFormsDecodedClientState(xformsState[0], staticStateUUID, dynamicStateUUID)); } } catch (Throwable e) { if (containingDocument[0] != null) { // If an exception is caught, we need to discard the object as its state may be inconsistent final ObjectPool sourceObjectPool = containingDocument[0].getSourceObjectPool(); if (sourceObjectPool != null) { indentedLogger.logDebug("", "containing document cache: throwable caught, discarding document from pool."); try { sourceObjectPool.invalidateObject(containingDocument); containingDocument[0].setSourceObjectPool(null); } catch (Exception e1) { throw new OXFException(e1); } } } throw new OXFException(e); } } // What can be cached by the first stage: URI dependencies private static class Stage1CacheableState extends URIProcessorOutputImpl.URIReferences {} // What can be cached by the second stage: SAXStore and static state private static class Stage2CacheableState extends URIProcessorOutputImpl.URIReferences { private final SAXStore annotatedSAXStore; private final XFormsStaticState xformsStaticState; public Stage2CacheableState(SAXStore annotatedSAXStore, XFormsStaticState xformsStaticState) { this.annotatedSAXStore = annotatedSAXStore; this.xformsStaticState = xformsStaticState; } public SAXStore getAnnotatedSAXStore() { return annotatedSAXStore; } public XFormsStaticState getXFormsEngineStaticState() { return xformsStaticState; } } private void gatherInputDependencies(XFormsContainingDocument containingDocument, IndentedLogger indentedLogger, Stage1CacheableState stage1CacheableState) { // Set caching dependencies if the input was actually read // WIP: check all models/instances: for (Iterator i = containingDocument.getAllModels().iterator(); i.hasNext();) { for (final XFormsModel currentModel: containingDocument.getModels()) { // Add schema dependencies final String[] schemaURIs = currentModel.getSchemaURIs(); // TODO: We should also use dependencies computed in XFormsModelSchemaValidator.SchemaInfo if (schemaURIs != null) { for (final String currentSchemaURI: schemaURIs) { if (indentedLogger.isDebugEnabled()) indentedLogger.logDebug("", "adding document cache dependency for schema", "schema URI", currentSchemaURI); stage1CacheableState.addReference(null, currentSchemaURI, null, null, XFormsProperties.getForwardSubmissionHeaders(containingDocument));// TODO: support username / password on schema refs } } // Add instance source dependencies if (currentModel.getInstances() != null) { for (final XFormsInstance currentInstance: currentModel.getInstances()) { final String instanceSourceURI = currentInstance.getSourceURI(); if (instanceSourceURI != null) { if (!currentInstance.isCache()) { // Add dependency only for instances that are not globally shared if (indentedLogger.isDebugEnabled()) indentedLogger.logDebug("", "adding document cache dependency for non-cacheable instance", "instance URI", instanceSourceURI); stage1CacheableState.addReference(null, instanceSourceURI, currentInstance.getUsername(), currentInstance.getPassword(), XFormsProperties.getForwardSubmissionHeaders(containingDocument)); } else { // Don't add the dependency as we don't want the instance URI to be hit // For all practical purposes, globally shared instances must remain constant! if (indentedLogger.isDebugEnabled()) indentedLogger.logDebug("", "not adding document cache dependency for cacheable instance", "instance URI", instanceSourceURI); } } } } // TODO: Add @src attributes from controls? Not used often. } // Set caching dependencies for XBL inclusions { final XFormsAnnotatorContentHandler.Metadata metadata = containingDocument.getStaticState().getMetadata(); final List<String> includes = metadata.getBindingsIncludes(); if (includes != null) { for (final String include: includes) { stage1CacheableState.addReference(null, "oxf:" + include, null, null, null); } } } } private void createCacheContainingDocument(final PipelineContext pipelineContext, XFormsURIResolver uriResolver, XFormsStaticState xformsStaticState, XFormsContainingDocument[] containingDocument, XFormsState[] xformsState) { { // Create containing document and initialize XForms engine containingDocument[0] = new XFormsContainingDocument(pipelineContext, xformsStaticState, uriResolver); // This is the state after XForms initialization xformsState[0] = containingDocument[0].getXFormsState(pipelineContext); } // Cache ContainingDocument if requested and possible { if (XFormsProperties.isCacheDocument()) { XFormsDocumentCache.instance().add(pipelineContext, xformsState[0], containingDocument[0]); } } } public static void outputResponseDocument(final PipelineContext pipelineContext, final ExternalContext externalContext, final IndentedLogger indentedLogger, final SAXStore annotatedDocument, final XFormsContainingDocument containingDocument, final ContentHandler contentHandler, final XFormsState encodedClientState) throws SAXException, IOException { final List<XFormsContainingDocument.Load> loads = containingDocument.getLoadsToRun(); if (containingDocument.isGotSubmissionReplaceAll()) { // 1. Got a submission with replace="all" // NOP: Response already sent out by a submission // TODO: modify XFormsModelSubmission accordingly indentedLogger.logDebug("", "handling response for submission with replace=\"all\""); } else if (loads != null && loads.size() > 0) { // 2. Got at least one xforms:load // Send redirect out // Get first load only final XFormsContainingDocument.Load load = loads.get(0); // Send redirect final String redirectResource = load.getResource(); indentedLogger.logDebug("", "handling redirect response for xforms:load", "url", redirectResource); // Set isNoRewrite to true, because the resource is either a relative path or already contains the servlet context externalContext.getResponse().sendRedirect(redirectResource, null, false, false, true); // Still send out a null document to signal that no further processing must take place XMLUtils.streamNullDocument(contentHandler); } else { // 3. Regular case: produce an XHTML document out final ElementHandlerController controller = new ElementHandlerController(); // Register handlers on controller (the other handlers are registered by the body handler) { controller.registerHandler(XHTMLHeadHandler.class.getName(), XMLConstants.XHTML_NAMESPACE_URI, "head"); controller.registerHandler(XHTMLBodyHandler.class.getName(), XMLConstants.XHTML_NAMESPACE_URI, "body"); // Register a handler for AVTs on HTML elements final boolean hostLanguageAVTs = XFormsProperties.isHostLanguageAVTs(); // TODO: this should be obtained per document, but we only know about this in the extractor if (hostLanguageAVTs) { controller.registerHandler(XXFormsAttributeHandler.class.getName(), XFormsConstants.XXFORMS_NAMESPACE_URI, "attribute"); controller.registerHandler(XHTMLElementHandler.class.getName(), XMLConstants.XHTML_NAMESPACE_URI); } // Swallow XForms elements that are unknown controller.registerHandler(NullHandler.class.getName(), XFormsConstants.XFORMS_NAMESPACE_URI); controller.registerHandler(NullHandler.class.getName(), XFormsConstants.XXFORMS_NAMESPACE_URI); controller.registerHandler(NullHandler.class.getName(), XFormsConstants.XBL_NAMESPACE_URI); } // Set final output controller.setOutput(new DeferredContentHandlerImpl(contentHandler)); // Set handler context controller.setElementHandlerContext(new HandlerContext(controller, pipelineContext, containingDocument, encodedClientState, externalContext, null)); // Process the entire input annotatedDocument.replay(new ExceptionWrapperContentHandler(controller, "converting XHTML+XForms document to XHTML")); // Process foreground asynchronous submissions // NOTE: Given the complexity of the epilogue, this could cause the page to stop loading until all submissions // are processed, even though that is not meant to happen. final AsynchronousSubmissionManager asynchronousSubmissionManager = containingDocument.getAsynchronousSubmissionManager(false); if (asynchronousSubmissionManager != null) asynchronousSubmissionManager.processForegroundAsynchronousSubmissions(); } } private void testOutputResponseState(final PipelineContext pipelineContext, final XFormsContainingDocument containingDocument, final IndentedLogger indentedLogger, final ContentHandler contentHandler, final XFormsStateManager.XFormsDecodedClientState xformsDecodedClientState) throws SAXException { // Output XML response XFormsServer.outputAjaxResponse(containingDocument, indentedLogger, null, pipelineContext, contentHandler, xformsDecodedClientState, null, false, false, false, true); } }
src/java/org/orbeon/oxf/xforms/processor/XFormsToXHTML.java
/** * Copyright (C) 2010 Orbeon, Inc. * * This program is free software; you can redistribute it and/or modify it under the terms of the * GNU Lesser General Public License as published by the Free Software Foundation; either version * 2.1 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU Lesser General Public License for more details. * * The full text of the license is available at http://www.gnu.org/copyleft/lesser.html */ package org.orbeon.oxf.xforms.processor; import org.apache.commons.pool.ObjectPool; import org.apache.log4j.Logger; import org.dom4j.Document; import org.orbeon.oxf.common.OXFException; import org.orbeon.oxf.pipeline.api.ExternalContext; import org.orbeon.oxf.pipeline.api.PipelineContext; import org.orbeon.oxf.processor.*; import org.orbeon.oxf.processor.generator.URLGenerator; import org.orbeon.oxf.util.IndentedLogger; import org.orbeon.oxf.util.LoggerFactory; import org.orbeon.oxf.util.UUIDUtils; import org.orbeon.oxf.xforms.*; import org.orbeon.oxf.xforms.analysis.XFormsAnnotatorContentHandler; import org.orbeon.oxf.xforms.analysis.XFormsExtractorContentHandler; import org.orbeon.oxf.xforms.processor.handlers.*; import org.orbeon.oxf.xforms.state.XFormsDocumentCache; import org.orbeon.oxf.xforms.state.XFormsState; import org.orbeon.oxf.xforms.state.XFormsStateManager; import org.orbeon.oxf.xforms.submission.AsynchronousSubmissionManager; import org.orbeon.oxf.xml.*; import org.orbeon.oxf.xml.dom4j.LocationDocumentResult; import org.xml.sax.ContentHandler; import org.xml.sax.SAXException; import javax.xml.transform.sax.TransformerHandler; import java.io.IOException; import java.util.List; /** * This processor handles XForms initialization and produces an XHTML document which is a * translation from the source XForms + XHTML. */ public class XFormsToXHTML extends ProcessorImpl { public static final String LOGGING_CATEGORY = "html"; private static final Logger logger = LoggerFactory.createLogger(XFormsToXHTML.class); private static final String INPUT_ANNOTATED_DOCUMENT = "annotated-document"; private static final String OUTPUT_DOCUMENT = "document"; private static final String OUTPUT_CACHE_KEY = "dynamicState"; public XFormsToXHTML() { addInputInfo(new ProcessorInputOutputInfo(INPUT_ANNOTATED_DOCUMENT)); addInputInfo(new ProcessorInputOutputInfo("namespace")); // This input ensures that we depend on a portlet namespace addOutputInfo(new ProcessorInputOutputInfo(OUTPUT_DOCUMENT)); } /** * Case where an XML response must be generated. */ @Override public ProcessorOutput createOutput(final String outputName) { final ProcessorOutput output = new URIProcessorOutputImpl(XFormsToXHTML.this, outputName, INPUT_ANNOTATED_DOCUMENT) { public void readImpl(final PipelineContext pipelineContext, ContentHandler contentHandler) { doIt(pipelineContext, contentHandler, this, outputName); } @Override protected boolean supportsLocalKeyValidity() { return true; } @Override public KeyValidity getLocalKeyValidity(PipelineContext pipelineContext, URIReferences uriReferences) { // NOTE: As of 2010-03, caching of the output should never happen // o more work is needed to make this work properly // o not many use cases benefit return null; } }; addOutput(outputName, output); return output; } @Override public ProcessorInput createInput(final String inputName) { if (inputName.equals(INPUT_ANNOTATED_DOCUMENT)) { // Insert processor on the fly to handle dependencies. This is a bit tricky: we used to have an // XSLT/XInclude before XFormsToXHTML. This step handled XBL dependencies. Now that it is removed, we // need a mechanism to detect dependencies. So we insert a step here. // Return an input which handles dependencies // The system actually has two processors: // o stage1 is the processor automatically inserted below for the purpose of handling dependencies // o stage2 is the actual oxf:xforms-to-xhtml which actually does XForms processing final ProcessorInput originalInput = super.createInput(inputName); return new DependenciesProcessorInput(inputName, originalInput) { @Override protected URIProcessorOutputImpl.URIReferences getURIReferences(PipelineContext pipelineContext) { // Return dependencies object, set by stage2 before reading its input return ((Stage2TransientState) XFormsToXHTML.this.getState(pipelineContext)).stage1CacheableState; } }; } else { return super.createInput(inputName); } } @Override public void reset(PipelineContext context) { setState(context, new Stage2TransientState()); } // State passed by the second stage to the first stage. // NOTE: This extends URIReferencesState because we use URIProcessorOutputImpl. // It is not clear that we absolutely need URIProcessorOutputImpl in the second stage, but right now we keep it, // because XFormsURIResolver requires URIProcessorOutputImpl. private class Stage2TransientState extends URIProcessorOutputImpl.URIReferencesState { public Stage1CacheableState stage1CacheableState; } private void doIt(final PipelineContext pipelineContext, ContentHandler contentHandler, final URIProcessorOutputImpl processorOutput, String outputName) { final ExternalContext externalContext = XFormsUtils.getExternalContext(pipelineContext); final IndentedLogger indentedLogger = XFormsContainingDocument.getIndentedLogger(XFormsToXHTML.logger, XFormsServer.getLogger(), LOGGING_CATEGORY); // ContainingDocument and XFormsState created below final XFormsContainingDocument[] containingDocument = new XFormsContainingDocument[1]; final XFormsState[] xformsState = new XFormsState[1]; final boolean[] cachedInput = new boolean[] { false } ; // Read and try to cache the complete XForms+XHTML document with annotations final Stage2CacheableState stage2CacheableState = (Stage2CacheableState) readCacheInputAsObject(pipelineContext, getInputByName(INPUT_ANNOTATED_DOCUMENT), new CacheableInputReader() { public Object read(PipelineContext pipelineContext, ProcessorInput processorInput) { // Create URIResolver final XFormsURIResolver uriResolver = new XFormsURIResolver(XFormsToXHTML.this, processorOutput, pipelineContext, INPUT_ANNOTATED_DOCUMENT, URLGenerator.DEFAULT_HANDLE_XINCLUDE); // Compute annotated XForms document + static state document final Stage1CacheableState stage1CacheableState = new Stage1CacheableState(); final Stage2CacheableState stage2CacheableState; { final TransformerHandler identity = TransformerUtils.getIdentityTransformerHandler(); // TODO: Use TinyTree instead of dom4j Document final LocationDocumentResult documentResult = new LocationDocumentResult(); identity.setResult(documentResult); final XFormsAnnotatorContentHandler.Metadata metadata = new XFormsAnnotatorContentHandler.Metadata(); final SAXStore annotatedSAXStore = new SAXStore(new XFormsExtractorContentHandler(externalContext, identity, metadata)); // Store dependencies container in state before reading ((Stage2TransientState) XFormsToXHTML.this.getState(pipelineContext)).stage1CacheableState = stage1CacheableState; // Read the input through the annotator and gather namespace mappings readInputAsSAX(pipelineContext, processorInput, new XFormsAnnotatorContentHandler(annotatedSAXStore, externalContext, metadata)); // Get static state document and create static state object final Document staticStateDocument = documentResult.getDocument(); final XFormsStaticState xformsStaticState = new XFormsStaticState(pipelineContext, staticStateDocument, metadata, annotatedSAXStore); // Update input dependencies object stage2CacheableState = new Stage2CacheableState(annotatedSAXStore, xformsStaticState); } // Create document here so we can do appropriate analysis of caching dependencies createCacheContainingDocument(pipelineContext, uriResolver, stage2CacheableState.getXFormsEngineStaticState(), containingDocument, xformsState); // Gather set caching dependencies gatherInputDependencies(containingDocument[0], indentedLogger, stage1CacheableState); return stage2CacheableState; } @Override public void foundInCache() { cachedInput[0] = true; } @Override public void storedInCache() { cachedInput[0] = true; } }); try { // Create containing document if not done yet final String staticStateUUID; if (containingDocument[0] == null) { // In this case, we found the static state and more in the cache, but we must now create a new XFormsContainingDocument from this information indentedLogger.logDebug("", "annotated document and static state obtained from cache; creating containing document."); // Create URIResolver and XFormsContainingDocument final XFormsURIResolver uriResolver = new XFormsURIResolver(XFormsToXHTML.this, processorOutput, pipelineContext, INPUT_ANNOTATED_DOCUMENT, URLGenerator.DEFAULT_HANDLE_XINCLUDE); createCacheContainingDocument(pipelineContext, uriResolver, stage2CacheableState.getXFormsEngineStaticState(), containingDocument, xformsState); } else { indentedLogger.logDebug("", "annotated document and static state not obtained from cache."); } // Get static state UUID if (cachedInput[0]) { staticStateUUID = stage2CacheableState.getXFormsEngineStaticState().getUUID(); indentedLogger.logDebug("", "found cached static state UUID."); } else { staticStateUUID = null; indentedLogger.logDebug("", "did not find cached static state UUID."); } // Try to cache dynamic state UUID associated with the output // NOTE: As of 2010-03, caching of the output should never happen because we disable it final String dynamicStateUUID = (String) getCacheOutputObject(pipelineContext, processorOutput, OUTPUT_CACHE_KEY, new OutputObjectCreator() { public Object create(PipelineContext pipelineContext, ProcessorOutput processorOutput) { indentedLogger.logDebug("", "caching dynamic state UUID for resulting document."); return UUIDUtils.createPseudoUUID(); } @Override public void foundInCache() { indentedLogger.logDebug("", "found cached dynamic state UUID for resulting document."); } @Override public void unableToCache() { indentedLogger.logDebug("", "cannot cache dynamic state UUID for resulting document."); } }); // Output resulting document if (outputName.equals("document")) { // Normal case where we output XHTML // Get encoded state for the client final XFormsState encodedClientState = XFormsStateManager.getInitialEncodedClientState(containingDocument[0], externalContext, xformsState[0], staticStateUUID, dynamicStateUUID); outputResponseDocument(pipelineContext, externalContext, indentedLogger, stage2CacheableState.getAnnotatedSAXStore(), containingDocument[0], contentHandler, encodedClientState); } else { // Output in test mode testOutputResponseState(pipelineContext, containingDocument[0], indentedLogger, contentHandler, new XFormsStateManager.XFormsDecodedClientState(xformsState[0], staticStateUUID, dynamicStateUUID)); } } catch (Throwable e) { if (containingDocument[0] != null) { // If an exception is caught, we need to discard the object as its state may be inconsistent final ObjectPool sourceObjectPool = containingDocument[0].getSourceObjectPool(); if (sourceObjectPool != null) { indentedLogger.logDebug("", "containing document cache: throwable caught, discarding document from pool."); try { sourceObjectPool.invalidateObject(containingDocument); containingDocument[0].setSourceObjectPool(null); } catch (Exception e1) { throw new OXFException(e1); } } } throw new OXFException(e); } } // What can be cached by the first stage: URI dependencies private static class Stage1CacheableState extends URIProcessorOutputImpl.URIReferences {} // What can be cached by the second stage: SAXStore and static state private static class Stage2CacheableState extends URIProcessorOutputImpl.URIReferences { private final SAXStore annotatedSAXStore; private final XFormsStaticState xformsStaticState; public Stage2CacheableState(SAXStore annotatedSAXStore, XFormsStaticState xformsStaticState) { this.annotatedSAXStore = annotatedSAXStore; this.xformsStaticState = xformsStaticState; } public SAXStore getAnnotatedSAXStore() { return annotatedSAXStore; } public XFormsStaticState getXFormsEngineStaticState() { return xformsStaticState; } } private void gatherInputDependencies(XFormsContainingDocument containingDocument, IndentedLogger indentedLogger, Stage1CacheableState stage1CacheableState) { // Set caching dependencies if the input was actually read // WIP: check all models/instances: for (Iterator i = containingDocument.getAllModels().iterator(); i.hasNext();) { for (final XFormsModel currentModel: containingDocument.getModels()) { // Add schema dependencies final String[] schemaURIs = currentModel.getSchemaURIs(); // TODO: We should also use dependencies computed in XFormsModelSchemaValidator.SchemaInfo if (schemaURIs != null) { for (final String currentSchemaURI: schemaURIs) { if (indentedLogger.isDebugEnabled()) indentedLogger.logDebug("", "adding document cache dependency for schema", "schema URI", currentSchemaURI); stage1CacheableState.addReference(null, currentSchemaURI, null, null, XFormsProperties.getForwardSubmissionHeaders(containingDocument));// TODO: support username / password on schema refs } } // Add instance source dependencies if (currentModel.getInstances() != null) { for (final XFormsInstance currentInstance: currentModel.getInstances()) { final String instanceSourceURI = currentInstance.getSourceURI(); if (instanceSourceURI != null) { if (!currentInstance.isCache()) { // Add dependency only for instances that are not globally shared if (indentedLogger.isDebugEnabled()) indentedLogger.logDebug("", "adding document cache dependency for non-cacheable instance", "instance URI", instanceSourceURI); stage1CacheableState.addReference(null, instanceSourceURI, currentInstance.getUsername(), currentInstance.getPassword(), XFormsProperties.getForwardSubmissionHeaders(containingDocument)); } else { // Don't add the dependency as we don't want the instance URI to be hit // For all practical purposes, globally shared instances must remain constant! if (indentedLogger.isDebugEnabled()) indentedLogger.logDebug("", "not adding document cache dependency for cacheable instance", "instance URI", instanceSourceURI); } } } } // TODO: Add @src attributes from controls? Not used often. } // Set caching dependencies for XBL inclusions { final XFormsAnnotatorContentHandler.Metadata metadata = containingDocument.getStaticState().getMetadata(); final List<String> includes = metadata.getBindingsIncludes(); if (includes != null) { for (final String include: includes) { stage1CacheableState.addReference(null, "oxf:" + include, null, null, null); } } } } private void createCacheContainingDocument(final PipelineContext pipelineContext, XFormsURIResolver uriResolver, XFormsStaticState xformsStaticState, XFormsContainingDocument[] containingDocument, XFormsState[] xformsState) { { // Create containing document and initialize XForms engine containingDocument[0] = new XFormsContainingDocument(pipelineContext, xformsStaticState, uriResolver); // This is the state after XForms initialization xformsState[0] = containingDocument[0].getXFormsState(pipelineContext); } // Cache ContainingDocument if requested and possible { if (XFormsProperties.isCacheDocument()) { XFormsDocumentCache.instance().add(pipelineContext, xformsState[0], containingDocument[0]); } } } public static void outputResponseDocument(final PipelineContext pipelineContext, final ExternalContext externalContext, final IndentedLogger indentedLogger, final SAXStore annotatedDocument, final XFormsContainingDocument containingDocument, final ContentHandler contentHandler, final XFormsState encodedClientState) throws SAXException, IOException { final List<XFormsContainingDocument.Load> loads = containingDocument.getLoadsToRun(); if (containingDocument.isGotSubmissionReplaceAll()) { // 1. Got a submission with replace="all" // NOP: Response already sent out by a submission // TODO: modify XFormsModelSubmission accordingly indentedLogger.logDebug("", "handling response for submission with replace=\"all\""); } else if (loads != null && loads.size() > 0) { // 2. Got at least one xforms:load // Send redirect out // Get first load only final XFormsContainingDocument.Load load = loads.get(0); // Send redirect final String redirectResource = load.getResource(); indentedLogger.logDebug("", "handling redirect response for xforms:load", "url", redirectResource); // Set isNoRewrite to true, because the resource is either a relative path or already contains the servlet context externalContext.getResponse().sendRedirect(redirectResource, null, false, false, true); // Still send out a null document to signal that no further processing must take place XMLUtils.streamNullDocument(contentHandler); } else { // 3. Regular case: produce an XHTML document out final ElementHandlerController controller = new ElementHandlerController(); // Register handlers on controller (the other handlers are registered by the body handler) { controller.registerHandler(XHTMLHeadHandler.class.getName(), XMLConstants.XHTML_NAMESPACE_URI, "head"); controller.registerHandler(XHTMLBodyHandler.class.getName(), XMLConstants.XHTML_NAMESPACE_URI, "body"); // Register a handler for AVTs on HTML elements final boolean hostLanguageAVTs = XFormsProperties.isHostLanguageAVTs(); // TODO: this should be obtained per document, but we only know about this in the extractor if (hostLanguageAVTs) { controller.registerHandler(XXFormsAttributeHandler.class.getName(), XFormsConstants.XXFORMS_NAMESPACE_URI, "attribute"); controller.registerHandler(XHTMLElementHandler.class.getName(), XMLConstants.XHTML_NAMESPACE_URI); } // Swallow XForms elements that are unknown controller.registerHandler(NullHandler.class.getName(), XFormsConstants.XFORMS_NAMESPACE_URI); controller.registerHandler(NullHandler.class.getName(), XFormsConstants.XXFORMS_NAMESPACE_URI); controller.registerHandler(NullHandler.class.getName(), XFormsConstants.XBL_NAMESPACE_URI); } // Set final output controller.setOutput(new DeferredContentHandlerImpl(contentHandler)); // Set handler context controller.setElementHandlerContext(new HandlerContext(controller, pipelineContext, containingDocument, encodedClientState, externalContext, null)); // Process the entire input annotatedDocument.replay(new ExceptionWrapperContentHandler(controller, "converting XHTML+XForms document to XHTML")); // Process foreground asynchronous submissions // NOTE: Given the complexity of the epilogue, this could cause the page to stop loading until all submissions // are processed, even though that is not meant to happen. final AsynchronousSubmissionManager asynchronousSubmissionManager = containingDocument.getAsynchronousSubmissionManager(false); if (asynchronousSubmissionManager != null) asynchronousSubmissionManager.processForegroundAsynchronousSubmissions(); } } private void testOutputResponseState(final PipelineContext pipelineContext, final XFormsContainingDocument containingDocument, final IndentedLogger indentedLogger, final ContentHandler contentHandler, final XFormsStateManager.XFormsDecodedClientState xformsDecodedClientState) throws SAXException { // Output XML response XFormsServer.outputAjaxResponse(containingDocument, indentedLogger, null, pipelineContext, contentHandler, xformsDecodedClientState, null, false, false, false, true); } }
Space.
src/java/org/orbeon/oxf/xforms/processor/XFormsToXHTML.java
Space.
<ide><path>rc/java/org/orbeon/oxf/xforms/processor/XFormsToXHTML.java <ide> for (final String currentSchemaURI: schemaURIs) { <ide> if (indentedLogger.isDebugEnabled()) <ide> indentedLogger.logDebug("", "adding document cache dependency for schema", "schema URI", currentSchemaURI); <add> <ide> stage1CacheableState.addReference(null, currentSchemaURI, null, null, <ide> XFormsProperties.getForwardSubmissionHeaders(containingDocument));// TODO: support username / password on schema refs <ide> } <ide> // Add dependency only for instances that are not globally shared <ide> if (indentedLogger.isDebugEnabled()) <ide> indentedLogger.logDebug("", "adding document cache dependency for non-cacheable instance", "instance URI", instanceSourceURI); <add> <ide> stage1CacheableState.addReference(null, instanceSourceURI, currentInstance.getUsername(), currentInstance.getPassword(), <ide> XFormsProperties.getForwardSubmissionHeaders(containingDocument)); <ide> } else {
Java
apache-2.0
1eda8fb101f2843046520e9cd4e73f2955a2a94c
0
MrGussio/EarthInvadersGDX,MrGussio/EarthInvadersGDX,MrGussio/EarthInvadersGDX
package ga.gussio.ld38.earthinvaders.screen; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.graphics.Color; import com.badlogic.gdx.graphics.OrthographicCamera; import com.badlogic.gdx.graphics.Texture; import com.badlogic.gdx.graphics.g2d.BitmapFont; import com.badlogic.gdx.graphics.g2d.Sprite; import com.badlogic.gdx.graphics.g2d.SpriteBatch; import com.badlogic.gdx.graphics.glutils.ShapeRenderer; import com.badlogic.gdx.math.Vector2; import com.badlogic.gdx.math.Vector3; import com.badlogic.gdx.utils.viewport.FitViewport; import java.util.Random; import ga.gussio.ld38.earthinvaders.Game; import ga.gussio.ld38.earthinvaders.InputListener; import ga.gussio.ld38.earthinvaders.buttons.Button; import ga.gussio.ld38.earthinvaders.buttons.CenteredButton; import ga.gussio.ld38.earthinvaders.entities.particles.Particle; public class MenuScreen extends Screen implements InputListener { private Particle[] background; private Sprite logo; private Button play; public MenuScreen(){ camera = new OrthographicCamera(); viewport = new FitViewport(Game.WIDTH, Game.HEIGHT, camera); viewport.apply(); camera.position.set(Game.WIDTH/2, Game.HEIGHT/2, 0); camera.update(); logo = new Sprite(new Texture("logo.png")); Random r = new Random(); background = new Particle[r.nextInt(55-45)+45]; for(int i = 0; i < background.length; i++){ int size = r.nextInt(4)+1; int x = r.nextInt(Game.WIDTH); int y = r.nextInt(Game.HEIGHT); background[i] = new Particle(x, y, 0, 0, -1, new Color(207/255f, 187/255f, 20/255f, 1f), size); } play = new CenteredButton(500, "buttons/play.png"); } @Override public void render(SpriteBatch sb, ShapeRenderer sr) { sb.setProjectionMatrix(camera.combined); sr.setAutoShapeType(true); sr.setProjectionMatrix(camera.combined); //SHAPERENDERER sr.begin(); sr.set(ShapeRenderer.ShapeType.Filled); sr.setColor(new Color(23/255f, 23/255f, 23/255f, 1f)); sr.rect(0, 0, Game.WIDTH, Game.HEIGHT); for(int i = 0; i < background.length; i++){ background[i].renderSR(sr); } play.renderSR(sr); sr.end(); //SPRITEBATCH sb.begin(); sb.draw(logo, Game.WIDTH/2-(logo.getTexture().getWidth()*10)/2, Game.HEIGHT-50-logo.getHeight()*10, logo.getWidth()*10, logo.getHeight()*10); play.renderSB(sb); sb.end(); } @Override public void tick() { if(play.clicked){ GameScreen gs = new GameScreen(); Game.setCurrentScreen(gs); play.clicked = false; } play.tick(); } @Override public void dispose() { play.dispose(); logo.getTexture().dispose(); } @Override public void touchDown(int screenX, int screenY, int pointer, int button) { Vector3 coords = camera.unproject(new Vector3(screenX, screenY, 0)); play.click(new Vector2(coords.x, coords.y)); } @Override public void touchUp(int screenX, int screenY, int pointer, int button) { Vector3 coords = camera.unproject(new Vector3(screenX, screenY, 0)); play.release(new Vector2(coords.x, coords.y)); } @Override public void touchDragged(int screenX, int screenY, int pointer) { Vector3 coords = camera.unproject(new Vector3(screenX, screenY, 0)); play.drag(new Vector2(coords.x, coords.y)); } }
core/src/ga/gussio/ld38/earthinvaders/screen/MenuScreen.java
package ga.gussio.ld38.earthinvaders.screen; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.graphics.Color; import com.badlogic.gdx.graphics.OrthographicCamera; import com.badlogic.gdx.graphics.Texture; import com.badlogic.gdx.graphics.g2d.BitmapFont; import com.badlogic.gdx.graphics.g2d.Sprite; import com.badlogic.gdx.graphics.g2d.SpriteBatch; import com.badlogic.gdx.graphics.glutils.ShapeRenderer; import com.badlogic.gdx.math.Vector2; import com.badlogic.gdx.math.Vector3; import com.badlogic.gdx.utils.viewport.FitViewport; import java.util.Random; import ga.gussio.ld38.earthinvaders.Game; import ga.gussio.ld38.earthinvaders.InputListener; import ga.gussio.ld38.earthinvaders.buttons.Button; import ga.gussio.ld38.earthinvaders.buttons.CenteredButton; import ga.gussio.ld38.earthinvaders.entities.particles.Particle; public class MenuScreen extends Screen implements InputListener { private Particle[] background; private Sprite logo; private Button play; public MenuScreen(){ camera = new OrthographicCamera(); viewport = new FitViewport(Game.WIDTH, Game.HEIGHT, camera); viewport.apply(); camera.position.set(Game.WIDTH/2, Game.HEIGHT/2, 0); camera.update(); logo = new Sprite(new Texture("logo.png")); Random r = new Random(); background = new Particle[r.nextInt(55-45)+45]; for(int i = 0; i < background.length; i++){ int size = r.nextInt(4)+1; int x = r.nextInt(Game.WIDTH); int y = r.nextInt(Game.HEIGHT); background[i] = new Particle(x, y, 0, 0, -1, new Color(207/255f, 187/255f, 20/255f, 1f), size); } play = new CenteredButton(500, "buttons/play.png"); } @Override public void render(SpriteBatch sb, ShapeRenderer sr) { sb.setProjectionMatrix(camera.combined); sr.setAutoShapeType(true); sr.setProjectionMatrix(camera.combined); //SHAPERENDERER sr.begin(); sr.set(ShapeRenderer.ShapeType.Filled); sr.setColor(new Color(23/255f, 23/255f, 23/255f, 1f)); sr.rect(0, 0, Game.WIDTH, Game.HEIGHT); for(int i = 0; i < background.length; i++){ background[i].renderSR(sr); } play.renderSR(sr); sr.end(); //SPRITEBATCH sb.begin(); sb.draw(logo, Game.WIDTH/2-(logo.getTexture().getWidth()*10)/2, Game.HEIGHT-50-logo.getHeight()*10, logo.getWidth()*10, logo.getHeight()*10); play.renderSB(sb); sb.end(); } @Override public void tick() { if(play.clicked){ GameScreen gs = new GameScreen(); Game.setCurrentScreen(gs); play.clicked = false; } play.tick(); } @Override public void dispose() { } @Override public void touchDown(int screenX, int screenY, int pointer, int button) { Vector3 coords = camera.unproject(new Vector3(screenX, screenY, 0)); play.click(new Vector2(coords.x, coords.y)); } @Override public void touchUp(int screenX, int screenY, int pointer, int button) { Vector3 coords = camera.unproject(new Vector3(screenX, screenY, 0)); play.release(new Vector2(coords.x, coords.y)); } @Override public void touchDragged(int screenX, int screenY, int pointer) { Vector3 coords = camera.unproject(new Vector3(screenX, screenY, 0)); play.drag(new Vector2(coords.x, coords.y)); } }
Fixed disposals in the menu screen.
core/src/ga/gussio/ld38/earthinvaders/screen/MenuScreen.java
Fixed disposals in the menu screen.
<ide><path>ore/src/ga/gussio/ld38/earthinvaders/screen/MenuScreen.java <ide> sb.draw(logo, Game.WIDTH/2-(logo.getTexture().getWidth()*10)/2, Game.HEIGHT-50-logo.getHeight()*10, logo.getWidth()*10, logo.getHeight()*10); <ide> play.renderSB(sb); <ide> sb.end(); <del> <ide> } <ide> <ide> @Override <ide> <ide> @Override <ide> public void dispose() { <del> <add> play.dispose(); <add> logo.getTexture().dispose(); <ide> } <ide> <ide> @Override
JavaScript
bsd-3-clause
16f8083ecae4fe541d827431473324fa22493887
0
WhiskeyMedia/ella,whalerock/ella,MichalMaM/ella,whalerock/ella,petrlosa/ella,MichalMaM/ella,WhiskeyMedia/ella,ella/ella,petrlosa/ella,whalerock/ella
/** * Text Area powered by callbacks. * requires: jQuery 1.4.2+, * gettext() function, * log_ntarea object (initialized in fuckitup.js), * ContentElementViewportDetector object (utils.js). * */ var NEWMAN_TEXTAREA_PREVIEW_SIZE_ADDITION = 10; //px var newman_textarea_focused; var newman_textarea_edit_content; function install_box_editor() { // FIXME refactorize! function getTypeFromPath(id) { var path = AVAILABLE_CONTENT_TYPES[id].path; return path.substring(1,path.length - 1).replace('/','.'); } if( $('#rich-box').length ) { return; } $('<div id="rich-box" title="Box"></div>').hide().appendTo('body'); $('#rich-box').load(BASE_URL+'nm/editor-box/', function(){ $('#id_box_obj_ct').bind('change', function(){ if(getTypeFromPath($('#id_box_obj_ct').val()) == 'photos.photo'){ $('#rich-box-attrs').hide(); $('#rich-photo-format').show(); } else { $('#rich-photo-format').hide(); $('#rich-box-attrs').show(); } }); $('#lookup_id_box_obj_id').bind('click', function(e){ e.preventDefault(); open_overlay(getTypeFromPath($('#id_box_obj_ct').val()), function(id){ $('#id_box_obj_id').val(id); }); }); $('#rich-object').bind('submit', function(e) { e.preventDefault(); if($('#id_box_obj_ct').val()) { var type = getTypeFromPath($('#id_box_obj_ct').val()); if(!!type){ var id = $('#id_box_obj_id').val() || '0'; var params = $('#id_box_obj_params').val().replace(/\n+/g, ' '); // Add format and size info for photo var addon = ''; var box_type = ''; if(getTypeFromPath($('#id_box_obj_ct').val()) == 'photos.photo'){ addon = '_'+$('#id_box_photo_size').val()+'_'+$('#id_box_photo_format').val(); box_type = 'inline'; // Add extra parameters $('.photo-meta input[type=checkbox]:checked','#rich-photo-format').each(function(){ params += ((params) ? '\n' : '') + $(this).attr('name').replace('box_photo_meta_','') + ':1'; }); } else { box_type = $('#id_box_type').val(); } // Insert code var selection_handler = TextAreaSelectionHandler(); newman_textarea_focused.focus(); selection_handler.init(newman_textarea_focused[0]); //newman_textarea_focused is jQuery object. var box_text = '\n{% box '+box_type+addon+' for '+type+' with pk '+$('#id_box_obj_id').val()+' %}'+((params) ? '\n'+params+'\n' : '')+'{% endbox %}\n'; selection_handler.insert_after_selection(box_text); // Reset and close dialog $('#rich-object').trigger('reset'); $('#rich-box').dialog('close'); $('#id_box_obj_ct').trigger('change'); newman_textarea_focused.focus(); // after all set focus to text area var toolbar = newman_textarea_focused.data('newman_text_area_toolbar_object'); NewmanLib.debug_area = newman_textarea_focused; NewmanLib.debug_type = typeof(toolbar); NewmanLib.debug_bar = toolbar; if (typeof(toolbar) == 'object' && typeof(toolbar.trigger_preview) != 'undefined') { toolbar.trigger_preview(); } } } }); $('#rich-object').bind('cancel_close', function(e) { $('#rich-box').dialog('close'); newman_textarea_focused.focus(); // after all set focus to text area }); }); $('#rich-box').dialog({ modal: false, autoOpen: false, width: 420, height: 360 }); } function preview_iframe_height($iFrame, $txArea) { if ($iFrame) { $iFrame.css("height", Math.max(50, $txArea.height() + NEWMAN_TEXTAREA_PREVIEW_SIZE_ADDITION)+"px"); } } // resize appropriately after enter key is pressed inside markItUp <textarea> element. function enter_pressed_callback(evt) { var $txArea = $(evt.currentTarget); var $container = $txArea.parents('.markItUpContainer'); var $iFrame = $container.find('iframe'); preview_iframe_height($iFrame, $txArea); } function discard_auto_preview(evt) { var $editor = markitdown_get_editor(evt); var existing_tm = $editor.data('auto_preview_timer'); if (existing_tm) { clearTimeout(existing_tm); $editor.data('auto_preview_timer', null); } //log_ntarea.log('Discarding auto preview for: ' , $editor.selector); } function markitdown_get_editor(evt) { var $container = $(evt.currentTarget).parents('.markItUpContainer'); var $editor = $container.find('.markItUpEditor'); return $editor; } function markitdown_auto_preview(evt, optional_force_preview) { var AGE = 90; var MIN_KEY_PRESS_DELAY = 1000; var $editor = markitdown_get_editor(evt); var $text_area = $editor.data('newman_text_area'); var existing_tm = $editor.data('auto_preview_timer'); var now = new Date().getTime(); function set_preview_timer() { function call_markitdown_auto_preview() { markitdown_auto_preview(evt, true); } var tm = setTimeout(call_markitdown_auto_preview, AGE); $editor.data('auto_preview_timer', tm); existing_tm = tm; } if (optional_force_preview) { var last_key = Number($editor.data('last_time_key_pressed')); var trigger_ok = false; if (existing_tm) { clearTimeout(existing_tm); //log_ntarea.log('Clearing timeout ' , existing_tm); existing_tm = null; $editor.data('auto_preview_timer', existing_tm); trigger_ok = true; } var difference = now - last_key; if ( difference < MIN_KEY_PRESS_DELAY ) { // if key was pressed in shorter time MIN_KEY_PRESS_DELAY, re-schedule preview refresh set_preview_timer(); //log_ntarea.log('Update timer Re-scheduled. diff=' , difference); return; } if (trigger_ok) { //log_ntarea.log('Auto preview triggering preview. diff=' , difference); //markitdown_trigger_preview(evt); $text_area.trigger('item_clicked.newman_text_area_toolbar', 'preview'); } return; } $editor.data('last_time_key_pressed', now); if (!existing_tm) { // schedule preview refresh set_preview_timer(); //log_ntarea.log('Update timer scheduled.'); } } /** * Standard toolbar with Bold, Italic, ..., Preview buttons. */ var NewmanTextAreaStandardToolbar = function () { var PREVIEW_URL = BASE_URL + 'nm/editor-preview/'; var PREVIEW_VARIABLE = 'text'; var PREVIEW_LOADING_GIF = MEDIA_URL + 'ico/15/loading.gif'; var AUTO_PREVIEW_TOOLBAR_BUTTON_CLICKED_DELAY = 250; //msec var me = NewmanTextAreaToolbar(); // selection_handler holds text selection of textarea element. var selection_handler = TextAreaSelectionHandler(); me.selection_handler = selection_handler; // Note: me.$text_area holds associated textarea element var button_handlers = { bold: handle_bold, italic: handle_italic, url: handle_url, h1: handle_h1, h2: handle_h2, h3: handle_h3, photo: handle_photo, gallery: handle_gallery, box: handle_box, preview: handle_preview }; button_handlers['list-bullet'] = handle_unordered_list; button_handlers['list-numeric'] = handle_ordered_list; var preview_window = null; me.preview_window = preview_window; function render_preview(success_callback) { var res = ''; function success_handler(data) { res = data; try { success_callback(data); } catch (e) { log_ntarea.log('Problem calling preview success callback.' , e); } } function error_handler(xhr, error_status, error_thrown) { res = [ gettext('Preview error.'), '\nException: ', error_thrown ].join(''); } var csrf_token = $('input[name=csrfmiddlewaretoken]').val(); //alert(csrf_token); var csrf_data = [ 'csrfmiddlewaretoken', '=', encodeURIComponent(csrf_token) ].join(''); var preview_data = [ PREVIEW_VARIABLE, '=', encodeURIComponent(me.$text_area.val()) ].join(''); var final_data = [ preview_data, '&', csrf_data ].join('') $.ajax( { type: 'POST', async: true, cache: false, url: PREVIEW_URL, //data: [ PREVIEW_VARIABLE, '=', encodeURIComponent(me.$text_area.val()) ].join(''), data: final_data, success: success_handler, error: error_handler } ); return res; } function render_preview_wait() { var wait_data = [ '<html><body>', '<div style="position: fixed; left: 20%; top: 20%;">', '<img src="', PREVIEW_LOADING_GIF, '" alt="" />&nbsp;&nbsp;&nbsp;', gettext('Sending'), '</div>', '</body></html>' ]; /* wait_data = [ '<html><body>', 'Wait...', '</body></html>' ]; */ me.preview_window.document.open(); me.preview_window.document.write(wait_data.join('')); me.preview_window.document.close(); } function preview_show_callback(data) { if (me.preview_window.document) { me.$preview_iframe.hide(); var sp; try { sp = me.preview_window.document.documentElement.scrollTop } catch(e) { sp = 0; } me.preview_window.document.open(); me.preview_window.document.write(data); me.preview_window.document.close(); me.preview_window.document.documentElement.scrollTop = sp; me.$text_area.trigger('preview_done', [me.$text_area, me.$preview_iframe, me.preview_window]); // trigger event on textarea when preview is finished me.$preview_iframe.show(); } //preview_window.focus(); } function handle_preview(evt) { var $iframe = me.$text_area.closest('.markItUpContainer').find('iframe.markItUpPreviewFrame'); if ($iframe.length == 0) { $iframe = $('<iframe class="markItUpPreviewFrame"></iframe>'); } $iframe.insertAfter(me.$text_area); me.preview_window = $iframe[$iframe.length-1].contentWindow || frame[$iframe.length-1]; me.$preview_iframe = $iframe; render_preview_wait(me.preview_window); render_preview(preview_show_callback); me.$text_area.focus(); } function trigger_preview() { handle_preview(); } me.trigger_preview = trigger_preview; function getIdFromPath(path){ // function used by box var id; $.each(AVAILABLE_CONTENT_TYPES, function(i){ if(this.path == '/'+path.replace('.','/')+'/'){ id = i; return; } }); return id; } function handle_box(evt) { if (!me.$text_area) { log_ntarea.log('NO TEXT AREA'); return; } $('#rich-box').dialog('open'); var focused = me.$text_area; var range = focused.getSelection(); var content = focused.val(); if (content.match(/\{% box(.|\n)+\{% endbox %\}/g) && range.start != -1) { var start = content.substring(0,range.start).lastIndexOf('{% box'); var end = content.indexOf('{% endbox %}',range.end); if (start != -1 && end != -1 && content.substring(start,range.start).indexOf('{% endbox %}') == -1) { var box = content.substring(start,end+12); newman_textarea_edit_content = box; var id = box.replace(/^.+pk (\d+) (.|\n)+$/,'$1'); var mode = box.replace(/^.+box (\w+) for(.|\n)+$/,'$1'); var type = box.replace(/^.+for (\w+\.\w+) (.|\n)+$/,'$1'); var params = box.replace(/^.+%\}\n?((.|\n)*)\{% endbox %\}$/,'$1'); $('#id_box_obj_ct').val(getIdFromPath(type)).trigger('change'); $('#id_box_obj_id').val(id); if (type == 'photos.photo') { if(box.indexOf('show_title:1') != -1){ $('#id_box_photo_meta_show_title').attr('checked','checked'); } else $('#id_box_photo_meta_show_title').removeAttr('checked'); if(box.indexOf('show_authors:1') != -1){ $('#id_box_photo_meta_show_author').attr('checked','checked'); } else $('#id_box_photo_meta_show_author').removeAttr('checked'); if(box.indexOf('show_description:1') != -1){ $('#id_box_photo_meta_show_description').attr('checked','checked'); } else $('#id_box_photo_meta_show_description').removeAttr('checked'); if(box.indexOf('show_detail:1') != -1){ $('#id_box_photo_meta_show_detail').attr('checked','checked'); } else $('#id_box_photo_meta_show_detail').removeAttr('checked'); params = params.replace(/show_title:\d/,'').replace(/show_authors:\d/,'').replace(/show_description:\d/,'').replace(/show_detail:\d/,'').replace(/\n{2,}/g,'\n').replace(/\s{2,}/g,' '); if(mode.indexOf('inline_velka') != -1){ $('#id_box_photo_size').val('velka') } else if(mode.indexOf('inline_standard') != -1){ $('#id_box_photo_size').val('standard') } else if(mode.indexOf('inline_mala') != -1){ $('#id_box_photo_size').val('mala') } if(mode.indexOf('ctverec') != -1){ $('#id_box_photo_format').val('ctverec') } else if(mode.indexOf('obdelnik_sirka') != -1){ $('#id_box_photo_format').val('obdelnik_sirka') } else if(mode.indexOf('obdelnik_vyska') != -1){ $('#id_box_photo_format').val('obdelnik_vyska') } else if(mode.indexOf('nudle_sirka') != -1){ $('#id_box_photo_format').val('nudle_sirka') } else if(mode.indexOf('nudle_vyska') != -1){ $('#id_box_photo_format').val('nudle_vyska') } } $('#id_box_obj_params').val(params); } } else { log_ntarea.log('NO CONTENT MATCHED'); } } function handle_gallery(evt) { $('#rich-box').dialog('open'); $('#id_box_obj_ct').val(getIdFromPath('galleries.gallery')).trigger('change');// 37 is value for galleries.gallery } function handle_photo(evt) { $('#rich-box').dialog('open'); $('#id_box_obj_ct').val(getIdFromPath('photos.photo')).trigger('change');// 20 is value for photos.photo in the select box $('#lookup_id_box_obj_id').trigger('click'); } function handle_unordered_list(evt) { var TEXT = '* text\n'; var sel = selection_handler.get_selection(); if (!sel) { var str = [ '\n', TEXT, TEXT, TEXT, ].join(''); selection_handler.replace_selection(str); return; } var lines = sel.split(/\r\n|\n|\r/); var bullet_lines = []; var i = 0; /* find first and last non-empty line */ for (i=0; i<lines.length && lines[i].replace(/^\s*/, "") == ""; i++); var first_line = i; for (i=lines.length-1; i!=0 && lines[i].replace(/^\s*/, "") == ""; i--); var last_line = i+1; if (last_line < first_line) { return; } for (i=0; i<first_line; i++) { bullet_lines[i] = lines[i]; } for (i = first_line; i < last_line; i++) { if ( /^\*\s+/.test( lines[i] ) ) { bullet_lines[i] = lines[i]; continue; } bullet_lines[i] = [ '* ', lines[i] ].join(''); } for (i=last_line; i<lines.length; i++) { bullet_lines[i] = lines[i]; } var str = bullet_lines.join('\n'); selection_handler.replace_selection(str); setTimeout(handle_preview, AUTO_PREVIEW_TOOLBAR_BUTTON_CLICKED_DELAY); } function handle_ordered_list(evt) { var TEXT = ' text'; var sel = selection_handler.get_selection(); if (!sel) { var str = [ '\n' // end line befor list begins ]; for (var i = 1; i < 4; i++) { str.push( [ i.toString(), '.', TEXT ].join('') ); } selection_handler.replace_selection(str.join('\n')); return; } var lines = sel.split(/\r\n|\n|\r/); var numbered_lines = []; var line_regex = /^(\d+)(\.\s+.*)/; var i = 0; /* find first and last non-empty line */ for (i=0; i<lines.length && lines[i].replace(/^\s*/, "") == ""; i++); var first_line = i; for (i=lines.length-1; i!=0 && lines[i].replace(/^\s*/, "") == ""; i--); var last_line = i+1; if (last_line < first_line) { return; } var counter = 1; for (i=0; i<first_line; i++) { numbered_lines[i] = lines[i]; } for (i = first_line; i < last_line; i++) { var match = lines[i].match(line_regex); if ( match ) { numbered_lines[i] = lines[i].replace(line_regex, counter + '$2'); } else { numbered_lines[i] = [ counter.toString(), '. ', lines[i] ].join(''); } counter++; } for (i=last_line; i<lines.length; i++) { numbered_lines[i] = lines[i]; } var str = numbered_lines.join('\n'); selection_handler.replace_selection(str); setTimeout(handle_preview, AUTO_PREVIEW_TOOLBAR_BUTTON_CLICKED_DELAY); } function heading_markup(heading_char, default_text) { var selection = selection_handler.get_selection(); if (selection == '') { selection = default_text; } var str = [ '\n\n', selection, '\n', new Array( selection.length ).join(heading_char), '\n' ].join(''); selection_handler.replace_selection(str); } function handle_h1(evt) { heading_markup('=', gettext('Heading H1')); setTimeout(handle_preview, AUTO_PREVIEW_TOOLBAR_BUTTON_CLICKED_DELAY); } function handle_h2(evt) { heading_markup('-', gettext('Heading H2')); setTimeout(handle_preview, AUTO_PREVIEW_TOOLBAR_BUTTON_CLICKED_DELAY); } function handle_h3(evt) { var sel = selection_handler.get_selection(); if (!sel) { sel = gettext('Heading H3'); } var str = [ '\n\n### ', sel, '\n' ].join(''); selection_handler.replace_selection(str); setTimeout(handle_preview, AUTO_PREVIEW_TOOLBAR_BUTTON_CLICKED_DELAY); } function handle_bold(evt) { selection_handler.wrap_selection('**', '**'); setTimeout(handle_preview, AUTO_PREVIEW_TOOLBAR_BUTTON_CLICKED_DELAY); } function handle_italic(evt) { selection_handler.wrap_selection('*', '*'); setTimeout(handle_preview, AUTO_PREVIEW_TOOLBAR_BUTTON_CLICKED_DELAY); } function handle_url(evt) { //'[', closeWith:']([![Url:!:http://]!] "[![Title]!]")', placeHolder: 'Text odkazu' var result = null; var replacement = ''; var text = selection_handler.get_selection(); if (!text) { text = prompt('Text:', ''); if (text == null) return; } result = prompt('URL:', 'http://'); if (result == null) return; // if protocol is not inserted, force HTTP if ( ! /:\/\//.test(result) ) { result = 'http://' + result; } replacement = [ '[', text, ']', '(', result, ' "', text, '")' ].join(''); // produces [Anchor text](http://dummy.centrum.cz "Anchor text") selection_handler.replace_selection(replacement); setTimeout(handle_preview, AUTO_PREVIEW_TOOLBAR_BUTTON_CLICKED_DELAY); } function toolbar_buttons() { // creates NewmanTextAreaToolbar items. me.add_item(gettext('Italic'), 'italic', 'I'); me.add_item(gettext('Bold'), 'bold', 'B'); me.add_separator(); me.add_item(gettext('Link'), 'url', 'L'); me.add_separator(); me.add_item(gettext('Head 1'), 'h1', '1'); me.add_item(gettext('Head 2'), 'h2', '2'); me.add_item(gettext('Head 3'), 'h3', '3'); me.add_separator(); me.add_item(gettext('List unordered'), 'list-bullet'); me.add_item(gettext('List ordered'), 'list-numeric'); me.add_separator(); //me.add_item(gettext('Quote'), 'quote'); //me.add_separator(); me.add_item(gettext('Photo'), 'photo'); me.add_item(gettext('Gallery'), 'gallery'); me.add_item(gettext('Box'), 'box'); me.add_separator(); me.add_item(gettext('Quick preview'), 'preview'); //me.add_item(gettext('Preview on site'), 'preview_on_site'); } me.toolbar_buttons = toolbar_buttons; function item_clicked(evt, button_name) { var cback = button_handlers[button_name]; //log_ntarea.log('item_clicked ' , button_name , ', element name:' , me.$text_area.attr('name')); if (typeof(cback) == 'undefined') return; try { selection_handler.init(me.$text_area[0]); // init selection_handler (assigns textarea selection) cback(evt); } catch (e) { log_ntarea.log('item_clicked error: ' , e); } } me.toolbar_item_clicked = item_clicked; return me; }; var TextAreaFocusListener = function() { /** * TextAreaFocusListener manages showing and hiding of toolbar. * Listens to all focus and focusout events triggered in textareas. */ var me = new Object(); var TOOLBAR_HIDE_TIMEOUT = 500; //msec var hide_toolbar_timeout = null; var $last_shown_header = null; var detector = null; var main_toolbar_offset = $('#header').position().top + $('#header').height(); var main_toolbar_offset_px = main_toolbar_offset + 'px'; function clean_toolbar_div() { var $bar = $('.js-textarea-toolbar'); $bar.children().detach(); $bar.hide(); $last_shown_header = null; $('div#container').unbind('scroll.text_area_focus_listener', scroll_handler); detector = null; //log_ntarea.log('Toolbar cleaned'); } function toolbar_stick_to_top($bar, $text_area) { //log_ntarea.log('sticked to top'); //$bar.css('position', 'relative'); var pos = [ main_toolbar_offset + $text_area.position().top - $bar.height() - 5, 'px' ].join(''); $bar.css('top', pos); $bar.show(); } function toolbar_stick_to_bottom($bar, $text_area) { //log_ntarea.log('sticked to bottom'); //$bar.css('position', 'relative'); var pos = [ main_toolbar_offset + $text_area.height() + $text_area.position().top, 'px' ].join(''); $bar.css('top', pos); $bar.show(); } function toolbar_float($bar) { //log_ntarea.log('floats on top'); $bar.css('top', main_toolbar_offset_px); $bar.show(); } function scroll_handler(evt) { var $bar = evt.data.$bar; if ( !detector.in_viewport() ) { // hide toolbar //log_ntarea.log('hidden'); $bar.hide(); } else if (detector.top_in_viewport() && !detector.bottom_in_viewport()) { // show toolbar sticked to textarea's top toolbar_stick_to_top($bar, evt.data.$text_area); } else if (detector.top_in_viewport() && detector.bottom_in_viewport()) { toolbar_stick_to_top($bar, evt.data.$text_area); } else { // only middle-part of textarea is in viewport, toolbar floats on top toolbar_float($bar); } } function show_toolbar($bar, $header) { clean_toolbar_div(); /*var p_element = [ '<p class="description">', gettext('Edit toolbar'), '</p>' ].join(''); NewmanLib.debug_textarea = $text_area; $(p_element).appendTo($bar);*/ $header.appendTo($bar); $bar.show(); $last_shown_header = $header; //log_ntarea.log('toolbar shown'); } function focus_in($text_area, $header) { if (hide_toolbar_timeout) { //log_ntarea.log('Clearing timeout'); clearTimeout(hide_toolbar_timeout); } newman_textarea_focused = $text_area; var $bar = $('.js-textarea-toolbar'); if ($bar.find('.markItUpHeader').length && ($header == $last_shown_header)) { //log_ntarea.log('toolbar instances are equiv. Aborting.'); return; } show_toolbar($bar, $header); // register handler for scroll event detector = new ContentElementViewportDetector($text_area); var $container = $('div#container'); $container.bind('scroll.text_area_focus_listener', {$bar: $bar, $text_area: $text_area}, scroll_handler); $container.trigger('scroll.text_area_focus_listener'); } me.focus_in = focus_in; function focus_out($text_area, $header) { hide_toolbar_timeout = setTimeout(clean_toolbar_div, TOOLBAR_HIDE_TIMEOUT); } me.focus_out = focus_out; return me; }; textarea_focus_listener = TextAreaFocusListener(); // shared object among CustomToolbar instances. var FloatingOneToolbar = function () { /** * Toolbar floats in fix-positioned <div>. textarea_focus_listener * object handles showing and hiding of appropriate toolbar. * If textarea has focus (blinking caret) it's toolbar is shown, while * other textarea related toolbars are hidden. */ var me = NewmanTextAreaStandardToolbar(); var super_get_toolbar = me.get_toolbar; function textarea_focus_in(evt) { textarea_focus_listener.focus_in(me.$text_area, me.$header); } function textarea_focus_out(evt) { textarea_focus_listener.focus_out(me.$text_area, me.$header); } function get_toolbar($text_area) { var $fake_out = $('<div></div>'); if (!me.toolbar_generated) { $text_area.bind('focus', textarea_focus_in); $text_area.bind('focusout', textarea_focus_out); // super! super_get_toolbar($text_area); } return $fake_out; } me.get_toolbar = get_toolbar; return me; }; $(function() { // keycode table http://www.scottklarr.com/topic/126/how-to-create-ctrl-key-shortcuts-in-javascript/ var RESIZE_DELAY_MSEC = 1250; var ENTER = 13; var KEY_A = 65; var KEY_Z = 90; var KEY_0 = 48; var KEY_9 = 57; var KEY_NUM_0 = 96; var KEY_NUM_DIVIDE = 111; var KEY_BACKSPACE = 8; var KEY_DELETE = 46; var newman_text_area_settings = { toolbar: FloatingOneToolbar }; function register_textarea_events() { var key_code; var $tx_area = $(this); function textarea_keyup_handler(evt) { key_code = evt.keyCode || evt.which; key_code = parseInt(key_code); // auto refresh preview if ( (key_code >= KEY_0 && key_code <= KEY_9) || (key_code >= KEY_NUM_0 && key_code <= KEY_NUM_DIVIDE) || (key_code >= KEY_A && key_code <= KEY_Z) || key_code == KEY_BACKSPACE || key_code == KEY_DELETE || key_code == 0 // national coded keys ) { markitdown_auto_preview(evt); } // if not return pressed, textarea resize won't be done. if (key_code != ENTER) return; setTimeout(function() {enter_pressed_callback(evt); }, RESIZE_DELAY_MSEC); } $tx_area.bind('keyup', textarea_keyup_handler); $tx_area.bind( 'preview_done', function (evt, $text_area, $iframe, preview_window) { preview_iframe_height($iframe, $text_area); } ); } // end of register_textarea_events function media_loaded_handler() { // install only if there is change-form displayed if ($('.change-form').length == 0) { return; } if ( $('.change-form').data('textarea_handlers_installed') === true ) { log_ntarea.log('ALREADY INSTALLED TEXTAREA HANDLERS'); return; } log_ntarea.log('INSTALLING TEXTAREA HANDLERS...'); // enable NewmanTextArea (replacement for markItUp!) install_box_editor(); $('.rich_text_area').newmanTextArea(newman_text_area_settings); $('.markItUpEditor').each(register_textarea_events); $('.rich_text_area.markItUpEditor').bind('focusout', discard_auto_preview); $('textarea.rich_text_area').autogrow(); $('.change-form').data('textarea_handlers_installed', true); } $(document).bind('media_loaded', media_loaded_handler); });
ella/newman/media/js/fuckitup_install.js
/** * Text Area powered by callbacks. * requires: jQuery 1.4.2+, * gettext() function, * log_ntarea object (initialized in fuckitup.js), * ContentElementViewportDetector object (utils.js). * */ var NEWMAN_TEXTAREA_PREVIEW_SIZE_ADDITION = 10; //px var newman_textarea_focused; var newman_textarea_edit_content; function install_box_editor() { // FIXME refactorize! function getTypeFromPath(id) { var path = AVAILABLE_CONTENT_TYPES[id].path; return path.substring(1,path.length - 1).replace('/','.'); } if( $('#rich-box').length ) { return; } $('<div id="rich-box" title="Box"></div>').hide().appendTo('body'); $('#rich-box').load(BASE_URL+'nm/editor-box/', function(){ $('#id_box_obj_ct').bind('change', function(){ if(getTypeFromPath($('#id_box_obj_ct').val()) == 'photos.photo'){ $('#rich-box-attrs').hide(); $('#rich-photo-format').show(); } else { $('#rich-photo-format').hide(); $('#rich-box-attrs').show(); } }); $('#lookup_id_box_obj_id').bind('click', function(e){ e.preventDefault(); open_overlay(getTypeFromPath($('#id_box_obj_ct').val()), function(id){ $('#id_box_obj_id').val(id); }); }); $('#rich-object').bind('submit', function(e) { e.preventDefault(); if($('#id_box_obj_ct').val()) { var type = getTypeFromPath($('#id_box_obj_ct').val()); if(!!type){ var id = $('#id_box_obj_id').val() || '0'; var params = $('#id_box_obj_params').val().replace(/\n+/g, ' '); // Add format and size info for photo var addon = ''; var box_type = ''; if(getTypeFromPath($('#id_box_obj_ct').val()) == 'photos.photo'){ addon = '_'+$('#id_box_photo_size').val()+'_'+$('#id_box_photo_format').val(); box_type = 'inline'; // Add extra parameters $('.photo-meta input[type=checkbox]:checked','#rich-photo-format').each(function(){ params += ((params) ? '\n' : '') + $(this).attr('name').replace('box_photo_meta_','') + ':1'; }); } else { box_type = $('#id_box_type').val(); } // Insert code var selection_handler = TextAreaSelectionHandler(); newman_textarea_focused.focus(); selection_handler.init(newman_textarea_focused[0]); //newman_textarea_focused is jQuery object. var box_text = '\n{% box '+box_type+addon+' for '+type+' with pk '+$('#id_box_obj_id').val()+' %}'+((params) ? '\n'+params+'\n' : '')+'{% endbox %}\n'; selection_handler.insert_after_selection(box_text); // Reset and close dialog $('#rich-object').trigger('reset'); $('#rich-box').dialog('close'); $('#id_box_obj_ct').trigger('change'); newman_textarea_focused.focus(); // after all set focus to text area var toolbar = newman_textarea_focused.data('newman_text_area_toolbar_object'); NewmanLib.debug_area = newman_textarea_focused; NewmanLib.debug_type = typeof(toolbar); NewmanLib.debug_bar = toolbar; if (typeof(toolbar) == 'object' && typeof(toolbar.trigger_preview) != 'undefined') { toolbar.trigger_preview(); } } } }); $('#rich-object').bind('cancel_close', function(e) { $('#rich-box').dialog('close'); newman_textarea_focused.focus(); // after all set focus to text area }); }); $('#rich-box').dialog({ modal: false, autoOpen: false, width: 420, height: 360 }); } function preview_iframe_height($iFrame, $txArea) { if ($iFrame) { $iFrame.css("height", Math.max(50, $txArea.height() + NEWMAN_TEXTAREA_PREVIEW_SIZE_ADDITION)+"px"); } } // resize appropriately after enter key is pressed inside markItUp <textarea> element. function enter_pressed_callback(evt) { var $txArea = $(evt.currentTarget); var $container = $txArea.parents('.markItUpContainer'); var $iFrame = $container.find('iframe'); preview_iframe_height($iFrame, $txArea); } function discard_auto_preview(evt) { var $editor = markitdown_get_editor(evt); var existing_tm = $editor.data('auto_preview_timer'); if (existing_tm) { clearTimeout(existing_tm); $editor.data('auto_preview_timer', null); } //log_ntarea.log('Discarding auto preview for: ' , $editor.selector); } function markitdown_get_editor(evt) { var $container = $(evt.currentTarget).parents('.markItUpContainer'); var $editor = $container.find('.markItUpEditor'); return $editor; } function markitdown_auto_preview(evt, optional_force_preview) { var AGE = 90; var MIN_KEY_PRESS_DELAY = 1000; var $editor = markitdown_get_editor(evt); var $text_area = $editor.data('newman_text_area'); var existing_tm = $editor.data('auto_preview_timer'); var now = new Date().getTime(); function set_preview_timer() { function call_markitdown_auto_preview() { markitdown_auto_preview(evt, true); } var tm = setTimeout(call_markitdown_auto_preview, AGE); $editor.data('auto_preview_timer', tm); existing_tm = tm; } if (optional_force_preview) { var last_key = Number($editor.data('last_time_key_pressed')); var trigger_ok = false; if (existing_tm) { clearTimeout(existing_tm); //log_ntarea.log('Clearing timeout ' , existing_tm); existing_tm = null; $editor.data('auto_preview_timer', existing_tm); trigger_ok = true; } var difference = now - last_key; if ( difference < MIN_KEY_PRESS_DELAY ) { // if key was pressed in shorter time MIN_KEY_PRESS_DELAY, re-schedule preview refresh set_preview_timer(); //log_ntarea.log('Update timer Re-scheduled. diff=' , difference); return; } if (trigger_ok) { //log_ntarea.log('Auto preview triggering preview. diff=' , difference); //markitdown_trigger_preview(evt); $text_area.trigger('item_clicked.newman_text_area_toolbar', 'preview'); } return; } $editor.data('last_time_key_pressed', now); if (!existing_tm) { // schedule preview refresh set_preview_timer(); //log_ntarea.log('Update timer scheduled.'); } } /** * Standard toolbar with Bold, Italic, ..., Preview buttons. */ var NewmanTextAreaStandardToolbar = function () { var PREVIEW_URL = BASE_URL + 'nm/editor-preview/'; var PREVIEW_VARIABLE = 'text'; var PREVIEW_LOADING_GIF = MEDIA_URL + 'ico/15/loading.gif'; var AUTO_PREVIEW_TOOLBAR_BUTTON_CLICKED_DELAY = 250; //msec var me = NewmanTextAreaToolbar(); // selection_handler holds text selection of textarea element. var selection_handler = TextAreaSelectionHandler(); me.selection_handler = selection_handler; // Note: me.$text_area holds associated textarea element var button_handlers = { bold: handle_bold, italic: handle_italic, url: handle_url, h1: handle_h1, h2: handle_h2, h3: handle_h3, photo: handle_photo, gallery: handle_gallery, box: handle_box, preview: handle_preview }; button_handlers['list-bullet'] = handle_unordered_list; button_handlers['list-numeric'] = handle_ordered_list; var preview_window = null; me.preview_window = preview_window; function render_preview(success_callback) { var res = ''; function success_handler(data) { res = data; try { success_callback(data); } catch (e) { log_ntarea.log('Problem calling preview success callback.' , e); } } function error_handler(xhr, error_status, error_thrown) { res = [ gettext('Preview error.'), '\nException: ', error_thrown ].join(''); } var csrf_token = $('input[name=csrfmiddlewaretoken]').val(); //alert(csrf_token); var csrf_data = [ 'csrfmiddlewaretoken', '=', encodeURIComponent(csrf_token) ].join(''); var preview_data = [ PREVIEW_VARIABLE, '=', encodeURIComponent(me.$text_area.val()) ].join(''); var final_data = [ preview_data, '&', csrf_data ].join('') $.ajax( { type: 'POST', async: true, cache: false, url: PREVIEW_URL, //data: [ PREVIEW_VARIABLE, '=', encodeURIComponent(me.$text_area.val()) ].join(''), data: final_data, success: success_handler, error: error_handler } ); return res; } function render_preview_wait() { var wait_data = [ '<html><body>', '<div style="position: fixed; left: 20%; top: 20%;">', '<img src="', PREVIEW_LOADING_GIF, '" alt="" />&nbsp;&nbsp;&nbsp;', gettext('Sending'), '</div>', '</body></html>' ]; /* wait_data = [ '<html><body>', 'Wait...', '</body></html>' ]; */ me.preview_window.document.open(); me.preview_window.document.write(wait_data.join('')); me.preview_window.document.close(); } function preview_show_callback(data) { if (me.preview_window.document) { me.$preview_iframe.hide(); var sp; try { sp = me.preview_window.document.documentElement.scrollTop } catch(e) { sp = 0; } me.preview_window.document.open(); me.preview_window.document.write(data); me.preview_window.document.close(); me.preview_window.document.documentElement.scrollTop = sp; me.$text_area.trigger('preview_done', [me.$text_area, me.$preview_iframe, me.preview_window]); // trigger event on textarea when preview is finished me.$preview_iframe.show(); } //preview_window.focus(); } function handle_preview(evt) { var $iframe = me.$text_area.closest('.markItUpContainer').find('iframe.markItUpPreviewFrame'); if ($iframe.length == 0) { $iframe = $('<iframe class="markItUpPreviewFrame"></iframe>'); } $iframe.insertAfter(me.$text_area); me.preview_window = $iframe[$iframe.length-1].contentWindow || frame[$iframe.length-1]; me.$preview_iframe = $iframe; render_preview_wait(me.preview_window); render_preview(preview_show_callback); me.$text_area.focus(); } function trigger_preview() { handle_preview(); } me.trigger_preview = trigger_preview; function getIdFromPath(path){ // function used by box var id; $.each(AVAILABLE_CONTENT_TYPES, function(i){ if(this.path == '/'+path.replace('.','/')+'/'){ id = i; return; } }); return id; } function handle_box(evt) { if (!me.$text_area) { log_ntarea.log('NO TEXT AREA'); return; } $('#rich-box').dialog('open'); var focused = me.$text_area; var range = focused.getSelection(); var content = focused.val(); if (content.match(/\{% box(.|\n)+\{% endbox %\}/g) && range.start != -1) { var start = content.substring(0,range.start).lastIndexOf('{% box'); var end = content.indexOf('{% endbox %}',range.end); if (start != -1 && end != -1 && content.substring(start,range.start).indexOf('{% endbox %}') == -1) { var box = content.substring(start,end+12); newman_textarea_edit_content = box; var id = box.replace(/^.+pk (\d+) (.|\n)+$/,'$1'); var mode = box.replace(/^.+box (\w+) for(.|\n)+$/,'$1'); var type = box.replace(/^.+for (\w+\.\w+) (.|\n)+$/,'$1'); var params = box.replace(/^.+%\}\n?((.|\n)*)\{% endbox %\}$/,'$1'); $('#id_box_obj_ct').val(getIdFromPath(type)).trigger('change'); $('#id_box_obj_id').val(id); if (type == 'photos.photo') { if(box.indexOf('show_title:1') != -1){ $('#id_box_photo_meta_show_title').attr('checked','checked'); } else $('#id_box_photo_meta_show_title').removeAttr('checked'); if(box.indexOf('show_authors:1') != -1){ $('#id_box_photo_meta_show_author').attr('checked','checked'); } else $('#id_box_photo_meta_show_author').removeAttr('checked'); if(box.indexOf('show_description:1') != -1){ $('#id_box_photo_meta_show_description').attr('checked','checked'); } else $('#id_box_photo_meta_show_description').removeAttr('checked'); if(box.indexOf('show_detail:1') != -1){ $('#id_box_photo_meta_show_detail').attr('checked','checked'); } else $('#id_box_photo_meta_show_detail').removeAttr('checked'); params = params.replace(/show_title:\d/,'').replace(/show_authors:\d/,'').replace(/show_description:\d/,'').replace(/show_detail:\d/,'').replace(/\n{2,}/g,'\n').replace(/\s{2,}/g,' '); if(mode.indexOf('inline_velka') != -1){ $('#id_box_photo_size').val('velka') } else if(mode.indexOf('inline_standard') != -1){ $('#id_box_photo_size').val('standard') } else if(mode.indexOf('inline_mala') != -1){ $('#id_box_photo_size').val('mala') } if(mode.indexOf('ctverec') != -1){ $('#id_box_photo_format').val('ctverec') } else if(mode.indexOf('obdelnik_sirka') != -1){ $('#id_box_photo_format').val('obdelnik_sirka') } else if(mode.indexOf('obdelnik_vyska') != -1){ $('#id_box_photo_format').val('obdelnik_vyska') } else if(mode.indexOf('nudle_sirka') != -1){ $('#id_box_photo_format').val('nudle_sirka') } else if(mode.indexOf('nudle_vyska') != -1){ $('#id_box_photo_format').val('nudle_vyska') } } $('#id_box_obj_params').val(params); } } else { log_ntarea.log('NO CONTENT MATCHED'); } } function handle_gallery(evt) { $('#rich-box').dialog('open'); $('#id_box_obj_ct').val(getIdFromPath('galleries.gallery')).trigger('change');// 37 is value for galleries.gallery } function handle_photo(evt) { $('#rich-box').dialog('open'); $('#id_box_obj_ct').val(getIdFromPath('photos.photo')).trigger('change');// 20 is value for photos.photo in the select box $('#lookup_id_box_obj_id').trigger('click'); } function handle_unordered_list(evt) { var TEXT = '* text\n'; var sel = selection_handler.get_selection(); if (!sel) { var str = [ '\n', TEXT, TEXT, TEXT, ].join(''); selection_handler.replace_selection(str); return; } var lines = sel.split(/\r\n|\n|\r/); var bullet_lines = []; for (var i = 0; i < lines.length; i++) { if ( /^\*\s+/.test( lines[i] ) ) { bullet_lines[i] = lines[i]; continue; } bullet_lines[i] = [ '* ', lines[i] ].join(''); } var str = bullet_lines.join('\n'); selection_handler.replace_selection(str); setTimeout(handle_preview, AUTO_PREVIEW_TOOLBAR_BUTTON_CLICKED_DELAY); } function handle_ordered_list(evt) { var TEXT = ' text'; var sel = selection_handler.get_selection(); if (!sel) { var str = [ '\n' // end line befor list begins ]; for (var i = 1; i < 4; i++) { str.push( [ i.toString(), '.', TEXT ].join('') ); } selection_handler.replace_selection(str.join('\n')); return; } var lines = sel.split(/\r\n|\n|\r/); var numbered_lines = []; var line_regex = /^(\d+)(\.\s+.*)/; for (var i = 0; i < lines.length; i++) { var match = lines[i].match(line_regex); var counter = i + 1; if ( match ) { numbered_lines[i] = lines[i].replace(line_regex, counter + '$2'); continue; } numbered_lines[i] = [ counter.toString(), '. ', lines[i] ].join(''); } var str = numbered_lines.join('\n'); selection_handler.replace_selection(str); setTimeout(handle_preview, AUTO_PREVIEW_TOOLBAR_BUTTON_CLICKED_DELAY); } function heading_markup(heading_char, default_text) { var selection = selection_handler.get_selection(); if (selection == '') { selection = default_text; } var str = [ '\n\n', selection, '\n', new Array( selection.length ).join(heading_char), '\n' ].join(''); selection_handler.replace_selection(str); } function handle_h1(evt) { heading_markup('=', gettext('Heading H1')); setTimeout(handle_preview, AUTO_PREVIEW_TOOLBAR_BUTTON_CLICKED_DELAY); } function handle_h2(evt) { heading_markup('-', gettext('Heading H2')); setTimeout(handle_preview, AUTO_PREVIEW_TOOLBAR_BUTTON_CLICKED_DELAY); } function handle_h3(evt) { var sel = selection_handler.get_selection(); if (!sel) { sel = gettext('Heading H3'); } var str = [ '\n\n### ', sel, '\n' ].join(''); selection_handler.replace_selection(str); setTimeout(handle_preview, AUTO_PREVIEW_TOOLBAR_BUTTON_CLICKED_DELAY); } function handle_bold(evt) { selection_handler.wrap_selection('**', '**'); setTimeout(handle_preview, AUTO_PREVIEW_TOOLBAR_BUTTON_CLICKED_DELAY); } function handle_italic(evt) { selection_handler.wrap_selection('*', '*'); setTimeout(handle_preview, AUTO_PREVIEW_TOOLBAR_BUTTON_CLICKED_DELAY); } function handle_url(evt) { //'[', closeWith:']([![Url:!:http://]!] "[![Title]!]")', placeHolder: 'Text odkazu' var result = null; var replacement = ''; var text = selection_handler.get_selection(); if (!text) { text = prompt('Text:', ''); if (text == null) return; } result = prompt('URL:', 'http://'); if (result == null) return; // if protocol is not inserted, force HTTP if ( ! /:\/\//.test(result) ) { result = 'http://' + result; } replacement = [ '[', text, ']', '(', result, ' "', text, '")' ].join(''); // produces [Anchor text](http://dummy.centrum.cz "Anchor text") selection_handler.replace_selection(replacement); setTimeout(handle_preview, AUTO_PREVIEW_TOOLBAR_BUTTON_CLICKED_DELAY); } function toolbar_buttons() { // creates NewmanTextAreaToolbar items. me.add_item(gettext('Italic'), 'italic', 'I'); me.add_item(gettext('Bold'), 'bold', 'B'); me.add_separator(); me.add_item(gettext('Link'), 'url', 'L'); me.add_separator(); me.add_item(gettext('Head 1'), 'h1', '1'); me.add_item(gettext('Head 2'), 'h2', '2'); me.add_item(gettext('Head 3'), 'h3', '3'); me.add_separator(); me.add_item(gettext('List unordered'), 'list-bullet'); me.add_item(gettext('List ordered'), 'list-numeric'); me.add_separator(); //me.add_item(gettext('Quote'), 'quote'); //me.add_separator(); me.add_item(gettext('Photo'), 'photo'); me.add_item(gettext('Gallery'), 'gallery'); me.add_item(gettext('Box'), 'box'); me.add_separator(); me.add_item(gettext('Quick preview'), 'preview'); //me.add_item(gettext('Preview on site'), 'preview_on_site'); } me.toolbar_buttons = toolbar_buttons; function item_clicked(evt, button_name) { var cback = button_handlers[button_name]; //log_ntarea.log('item_clicked ' , button_name , ', element name:' , me.$text_area.attr('name')); if (typeof(cback) == 'undefined') return; try { selection_handler.init(me.$text_area[0]); // init selection_handler (assigns textarea selection) cback(evt); } catch (e) { log_ntarea.log('item_clicked error: ' , e); } } me.toolbar_item_clicked = item_clicked; return me; }; var TextAreaFocusListener = function() { /** * TextAreaFocusListener manages showing and hiding of toolbar. * Listens to all focus and focusout events triggered in textareas. */ var me = new Object(); var TOOLBAR_HIDE_TIMEOUT = 500; //msec var hide_toolbar_timeout = null; var $last_shown_header = null; var detector = null; var main_toolbar_offset = $('#header').position().top + $('#header').height(); var main_toolbar_offset_px = main_toolbar_offset + 'px'; function clean_toolbar_div() { var $bar = $('.js-textarea-toolbar'); $bar.children().detach(); $bar.hide(); $last_shown_header = null; $('div#container').unbind('scroll.text_area_focus_listener', scroll_handler); detector = null; //log_ntarea.log('Toolbar cleaned'); } function toolbar_stick_to_top($bar, $text_area) { //log_ntarea.log('sticked to top'); //$bar.css('position', 'relative'); var pos = [ main_toolbar_offset + $text_area.position().top - $bar.height() - 5, 'px' ].join(''); $bar.css('top', pos); $bar.show(); } function toolbar_stick_to_bottom($bar, $text_area) { //log_ntarea.log('sticked to bottom'); //$bar.css('position', 'relative'); var pos = [ main_toolbar_offset + $text_area.height() + $text_area.position().top, 'px' ].join(''); $bar.css('top', pos); $bar.show(); } function toolbar_float($bar) { //log_ntarea.log('floats on top'); $bar.css('top', main_toolbar_offset_px); $bar.show(); } function scroll_handler(evt) { var $bar = evt.data.$bar; if ( !detector.in_viewport() ) { // hide toolbar //log_ntarea.log('hidden'); $bar.hide(); } else if (detector.top_in_viewport() && !detector.bottom_in_viewport()) { // show toolbar sticked to textarea's top toolbar_stick_to_top($bar, evt.data.$text_area); } else if (detector.top_in_viewport() && detector.bottom_in_viewport()) { toolbar_stick_to_top($bar, evt.data.$text_area); } else { // only middle-part of textarea is in viewport, toolbar floats on top toolbar_float($bar); } } function show_toolbar($bar, $header) { clean_toolbar_div(); /*var p_element = [ '<p class="description">', gettext('Edit toolbar'), '</p>' ].join(''); NewmanLib.debug_textarea = $text_area; $(p_element).appendTo($bar);*/ $header.appendTo($bar); $bar.show(); $last_shown_header = $header; //log_ntarea.log('toolbar shown'); } function focus_in($text_area, $header) { if (hide_toolbar_timeout) { //log_ntarea.log('Clearing timeout'); clearTimeout(hide_toolbar_timeout); } newman_textarea_focused = $text_area; var $bar = $('.js-textarea-toolbar'); if ($bar.find('.markItUpHeader').length && ($header == $last_shown_header)) { //log_ntarea.log('toolbar instances are equiv. Aborting.'); return; } show_toolbar($bar, $header); // register handler for scroll event detector = new ContentElementViewportDetector($text_area); var $container = $('div#container'); $container.bind('scroll.text_area_focus_listener', {$bar: $bar, $text_area: $text_area}, scroll_handler); $container.trigger('scroll.text_area_focus_listener'); } me.focus_in = focus_in; function focus_out($text_area, $header) { hide_toolbar_timeout = setTimeout(clean_toolbar_div, TOOLBAR_HIDE_TIMEOUT); } me.focus_out = focus_out; return me; }; textarea_focus_listener = TextAreaFocusListener(); // shared object among CustomToolbar instances. var FloatingOneToolbar = function () { /** * Toolbar floats in fix-positioned <div>. textarea_focus_listener * object handles showing and hiding of appropriate toolbar. * If textarea has focus (blinking caret) it's toolbar is shown, while * other textarea related toolbars are hidden. */ var me = NewmanTextAreaStandardToolbar(); var super_get_toolbar = me.get_toolbar; function textarea_focus_in(evt) { textarea_focus_listener.focus_in(me.$text_area, me.$header); } function textarea_focus_out(evt) { textarea_focus_listener.focus_out(me.$text_area, me.$header); } function get_toolbar($text_area) { var $fake_out = $('<div></div>'); if (!me.toolbar_generated) { $text_area.bind('focus', textarea_focus_in); $text_area.bind('focusout', textarea_focus_out); // super! super_get_toolbar($text_area); } return $fake_out; } me.get_toolbar = get_toolbar; return me; }; $(function() { // keycode table http://www.scottklarr.com/topic/126/how-to-create-ctrl-key-shortcuts-in-javascript/ var RESIZE_DELAY_MSEC = 1250; var ENTER = 13; var KEY_A = 65; var KEY_Z = 90; var KEY_0 = 48; var KEY_9 = 57; var KEY_NUM_0 = 96; var KEY_NUM_DIVIDE = 111; var KEY_BACKSPACE = 8; var KEY_DELETE = 46; var newman_text_area_settings = { toolbar: FloatingOneToolbar }; function register_textarea_events() { var key_code; var $tx_area = $(this); function textarea_keyup_handler(evt) { key_code = evt.keyCode || evt.which; key_code = parseInt(key_code); // auto refresh preview if ( (key_code >= KEY_0 && key_code <= KEY_9) || (key_code >= KEY_NUM_0 && key_code <= KEY_NUM_DIVIDE) || (key_code >= KEY_A && key_code <= KEY_Z) || key_code == KEY_BACKSPACE || key_code == KEY_DELETE || key_code == 0 // national coded keys ) { markitdown_auto_preview(evt); } // if not return pressed, textarea resize won't be done. if (key_code != ENTER) return; setTimeout(function() {enter_pressed_callback(evt); }, RESIZE_DELAY_MSEC); } $tx_area.bind('keyup', textarea_keyup_handler); $tx_area.bind( 'preview_done', function (evt, $text_area, $iframe, preview_window) { preview_iframe_height($iframe, $text_area); } ); } // end of register_textarea_events function media_loaded_handler() { // install only if there is change-form displayed if ($('.change-form').length == 0) { return; } if ( $('.change-form').data('textarea_handlers_installed') === true ) { log_ntarea.log('ALREADY INSTALLED TEXTAREA HANDLERS'); return; } log_ntarea.log('INSTALLING TEXTAREA HANDLERS...'); // enable NewmanTextArea (replacement for markItUp!) install_box_editor(); $('.rich_text_area').newmanTextArea(newman_text_area_settings); $('.markItUpEditor').each(register_textarea_events); $('.rich_text_area.markItUpEditor').bind('focusout', discard_auto_preview); $('textarea.rich_text_area').autogrow(); $('.change-form').data('textarea_handlers_installed', true); } $(document).bind('media_loaded', media_loaded_handler); });
markdown area buttons for creating ordered and unordered list now ignores blank lines on beginning and end of selection (usability improvement)
ella/newman/media/js/fuckitup_install.js
markdown area buttons for creating ordered and unordered list now ignores blank lines on beginning and end of selection (usability improvement)
<ide><path>lla/newman/media/js/fuckitup_install.js <ide> } <ide> var lines = sel.split(/\r\n|\n|\r/); <ide> var bullet_lines = []; <del> for (var i = 0; i < lines.length; i++) { <add> <add> var i = 0; <add> /* find first and last non-empty line */ <add> for (i=0; i<lines.length && lines[i].replace(/^\s*/, "") == ""; i++); <add> var first_line = i; <add> for (i=lines.length-1; i!=0 && lines[i].replace(/^\s*/, "") == ""; i--); <add> var last_line = i+1; <add> if (last_line < first_line) { <add> return; <add> } <add> for (i=0; i<first_line; i++) { <add> bullet_lines[i] = lines[i]; <add> } <add> for (i = first_line; i < last_line; i++) { <ide> if ( /^\*\s+/.test( lines[i] ) ) { <ide> bullet_lines[i] = lines[i]; <ide> continue; <ide> } <ide> bullet_lines[i] = [ '* ', lines[i] ].join(''); <add> } <add> for (i=last_line; i<lines.length; i++) { <add> bullet_lines[i] = lines[i]; <ide> } <ide> var str = bullet_lines.join('\n'); <ide> selection_handler.replace_selection(str); <ide> var lines = sel.split(/\r\n|\n|\r/); <ide> var numbered_lines = []; <ide> var line_regex = /^(\d+)(\.\s+.*)/; <del> for (var i = 0; i < lines.length; i++) { <add> <add> var i = 0; <add> /* find first and last non-empty line */ <add> for (i=0; i<lines.length && lines[i].replace(/^\s*/, "") == ""; i++); <add> var first_line = i; <add> for (i=lines.length-1; i!=0 && lines[i].replace(/^\s*/, "") == ""; i--); <add> var last_line = i+1; <add> if (last_line < first_line) { <add> return; <add> } <add> var counter = 1; <add> for (i=0; i<first_line; i++) { <add> numbered_lines[i] = lines[i]; <add> } <add> for (i = first_line; i < last_line; i++) { <ide> var match = lines[i].match(line_regex); <del> var counter = i + 1; <ide> if ( match ) { <ide> numbered_lines[i] = lines[i].replace(line_regex, counter + '$2'); <del> continue; <del> } <del> numbered_lines[i] = [ counter.toString(), '. ', lines[i] ].join(''); <add> } else { <add> numbered_lines[i] = [ counter.toString(), '. ', lines[i] ].join(''); <add> } <add> counter++; <add> } <add> for (i=last_line; i<lines.length; i++) { <add> numbered_lines[i] = lines[i]; <ide> } <ide> var str = numbered_lines.join('\n'); <ide> selection_handler.replace_selection(str);
JavaScript
mit
f5fff2124d6ff3bb96e7359f928e61614577a072
0
esdoc/esdoc,h13i32maru/esdoc,h13i32maru/esdoc
/** * this is TestGuessReturn. */ export default class TestGuessReturn { method1(){ return 123; } method2(){ return [123, 456]; } method3(){ return {x1: 123, x2: 'text'}; } method4(){ return `text`; } method5(){ const obj = {} return {...obj} } }
test/fixture/package/src/Guess/Return.js
/** * this is TestGuessReturn. */ export default class TestGuessReturn { method1(){ return 123; } method2(){ return [123, 456]; } method3(){ return {x1: 123, x2: 'text'}; } method4(){ return `text`; } }
Add test to show parser crash.
test/fixture/package/src/Guess/Return.js
Add test to show parser crash.
<ide><path>est/fixture/package/src/Guess/Return.js <ide> method4(){ <ide> return `text`; <ide> } <add> <add> method5(){ <add> const obj = {} <add> return {...obj} <add> } <ide> }
Java
mit
6cde154084aef7c9f991bfbef523dd764cd0f9f0
0
amarseillan/pedestriansimulation,amarseillan/pedestriansimulation,amarseillan/pedestriansimulation
package ar.edu.itba.pedestriansim.front; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.util.Scanner; import org.newdawn.slick.AppGameContainer; import org.newdawn.slick.BasicGame; import org.newdawn.slick.GameContainer; import org.newdawn.slick.Graphics; import org.newdawn.slick.Input; import org.newdawn.slick.SlickException; import ar.edu.itba.pedestriansim.back.PedestrianSimApp; import ar.edu.itba.pedestriansim.back.config.CrossingConfig; import ar.edu.itba.pedestriansim.back.entity.PedestrianAppConfig; import ar.edu.itba.pedestriansim.back.entity.PedestrianArea; import ar.edu.itba.pedestriansim.back.entity.PedestrianAreaFileSerializer; import ar.edu.itba.pedestriansim.back.entity.PedestrianSim; import ar.edu.itba.pedestriansim.back.logic.PedestrianAreaStep; import com.google.common.base.Predicate; import com.google.common.io.Closer; public class GUIPedestrianSim extends BasicGame { public static void main(String[] args) throws SlickException { AppGameContainer appContainer = new AppGameContainer(new GUIPedestrianSim()); appContainer.setUpdateOnlyWhenVisible(false); appContainer.setDisplayMode(1200, 700, false); appContainer.start(); } private PedestrianAppConfig _config; private Camera _camera; private PedestrianSim _simulation; private PedestrianAreaRenderer _renderer; private boolean _simulationIsFinished = false; public GUIPedestrianSim() { super("Pedestrian simulation"); _config = new CrossingConfig().get(); // XXX: Run back-end first! new PedestrianSimApp(_config).run(); } @Override public void init(GameContainer gc) throws SlickException { final Closer closer = Closer.create(); Scanner staticReader = closer.register(newScanner(_config.staticfile())); Scanner dynamicReader = closer.register(newScanner(_config.dynamicfile())); PedestrianAreaFileSerializer serializer = new PedestrianAreaFileSerializer(); _simulation = new PedestrianSim(_config.pedestrianArea()) .cutCondition(new Predicate<PedestrianArea>() { @Override public boolean apply(PedestrianArea input) { return _simulationIsFinished; } }) .onStep(new UpdatePositionsFromFile(serializer.staticFileInfo(staticReader), serializer.steps(dynamicReader))) .onEnd(new PedestrianAreaStep() { @Override public void update(PedestrianArea input) { try { closer.close(); } catch (IOException e) { throw new IllegalStateException(e); } } }) ; _camera = new Camera(); _camera.setZoom(20f); // _camera.scrollX(1200); _renderer = new PedestrianAreaRenderer(_camera); gc.setAlwaysRender(true); gc.setTargetFrameRate(60); gc.getInput().addKeyListener(new KeyHandler(_camera, _renderer, gc)); } private Scanner newScanner(File file) { try { return new Scanner(file); } catch (FileNotFoundException e) { throw new IllegalStateException(e); } } public void render(GameContainer gc, Graphics g) throws SlickException { _renderer.render(gc, g, _simulation.pedestrianArea()); } @Override public void update(GameContainer gc, int delta) throws SlickException { _camera.update(gc); if (gc.getInput().isKeyDown(Input.KEY_X) || gc.getInput().isKeyDown(Input.KEY_ESCAPE) || _simulation.isFinished()) { System.out.println("Simulation finished... Exiting application!"); gc.exit(); return; } if (delta > 0) { // 0 = means paused! _simulation.step(); } if (gc.getInput().isKeyDown(Input.KEY_R)) { gc.reinit(); } } }
src/main/java/ar/edu/itba/pedestriansim/front/GUIPedestrianSim.java
package ar.edu.itba.pedestriansim.front; import java.io.File; import java.io.IOException; import java.util.Scanner; import org.newdawn.slick.AppGameContainer; import org.newdawn.slick.BasicGame; import org.newdawn.slick.GameContainer; import org.newdawn.slick.Graphics; import org.newdawn.slick.Input; import org.newdawn.slick.SlickException; import ar.edu.itba.pedestriansim.back.PedestrianSimApp; import ar.edu.itba.pedestriansim.back.config.CrossingConfig; import ar.edu.itba.pedestriansim.back.entity.PedestrianAppConfig; import ar.edu.itba.pedestriansim.back.entity.PedestrianArea; import ar.edu.itba.pedestriansim.back.entity.PedestrianAreaFileSerializer; import ar.edu.itba.pedestriansim.back.entity.PedestrianSim; import ar.edu.itba.pedestriansim.back.logic.PedestrianAreaStep; import com.google.common.base.Predicate; import com.google.common.io.Closer; public class GUIPedestrianSim extends BasicGame { public static void main(String[] args) throws SlickException { AppGameContainer appContainer = new AppGameContainer(new GUIPedestrianSim()); appContainer.setUpdateOnlyWhenVisible(false); appContainer.setDisplayMode(1200, 700, false); appContainer.start(); } private PedestrianAppConfig _config; private Camera _camera; private PedestrianSim _simulation; private PedestrianAreaRenderer _renderer; private boolean _simulationIsFinished = false; public GUIPedestrianSim() { super("Pedestrian simulation"); _config = new CrossingConfig().get(); // XXX: Run back-end first! new PedestrianSimApp(_config).run(); } @Override public void init(GameContainer gc) throws SlickException { final Closer closer = Closer.create(); Scanner staticReader = closer.register(newScanner(_config.staticfile())); Scanner dynamicReader = closer.register(newScanner(_config.dynamicfile())); PedestrianAreaFileSerializer serializer = new PedestrianAreaFileSerializer(); _simulation = new PedestrianSim(_config.pedestrianArea()) .cutCondition(new Predicate<PedestrianArea>() { @Override public boolean apply(PedestrianArea input) { return _simulationIsFinished; } }) .onStep(new UpdatePositionsFromFile(serializer.staticFileInfo(staticReader), serializer.steps(dynamicReader))) .onEnd(new PedestrianAreaStep() { @Override public void update(PedestrianArea input) { try { closer.close(); } catch (IOException e) { throw new IllegalStateException(e); } } }) ; _camera = new Camera(); _camera.setZoom(20f); // _camera.scrollX(1200); _renderer = new PedestrianAreaRenderer(_camera); gc.setAlwaysRender(true); gc.setTargetFrameRate(60); gc.getInput().addKeyListener(new KeyHandler(_camera, _renderer, gc)); } private Scanner newScanner(File file) { try { return new Scanner(file); } catch (FileNotFoundException e) { throw new IllegalStateException(e); } } public void render(GameContainer gc, Graphics g) throws SlickException { _renderer.render(gc, g, _simulation.pedestrianArea()); } @Override public void update(GameContainer gc, int delta) throws SlickException { _camera.update(gc); if (gc.getInput().isKeyDown(Input.KEY_X) || gc.getInput().isKeyDown(Input.KEY_ESCAPE) || _simulation.isFinished()) { System.out.println("Simulation finished... Exiting application!"); gc.exit(); return; } if (delta > 0) { // 0 = means paused! _simulation.step(); } if (gc.getInput().isKeyDown(Input.KEY_R)) { gc.reinit(); } } }
import faltante que producia error de compilacion.
src/main/java/ar/edu/itba/pedestriansim/front/GUIPedestrianSim.java
import faltante que producia error de compilacion.
<ide><path>rc/main/java/ar/edu/itba/pedestriansim/front/GUIPedestrianSim.java <ide> package ar.edu.itba.pedestriansim.front; <ide> <ide> import java.io.File; <add>import java.io.FileNotFoundException; <ide> import java.io.IOException; <ide> import java.util.Scanner; <ide>
Java
apache-2.0
6c0c508ef8afe602a12dbeb2b68ea708fdffedd2
0
5of9/traccar,tananaev/traccar,joseant/traccar-1,jssenyange/traccar,stalien/traccar_test,renaudallard/traccar,duke2906/traccar,jon-stumpf/traccar,AnshulJain1985/Roadcast-Tracker,tananaev/traccar,vipien/traccar,tsmgeek/traccar,tananaev/traccar,renaudallard/traccar,jon-stumpf/traccar,5of9/traccar,al3x1s/traccar,al3x1s/traccar,jssenyange/traccar,tsmgeek/traccar,ninioe/traccar,orcoliver/traccar,orcoliver/traccar,tsmgeek/traccar,vipien/traccar,joseant/traccar-1,duke2906/traccar,stalien/traccar_test,jssenyange/traccar,jon-stumpf/traccar,ninioe/traccar,orcoliver/traccar,AnshulJain1985/Roadcast-Tracker,ninioe/traccar
/* * Copyright 2016 Anton Tananaev ([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.traccar.api.resource; import java.sql.SQLException; import java.util.Collection; import javax.ws.rs.Consumes; import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.QueryParam; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import org.traccar.Context; import org.traccar.api.BaseResource; import org.traccar.model.Notification; @Path("users/notifications") @Produces(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON) public class NotificationResource extends BaseResource { @GET public Collection<Notification> get(@QueryParam("all") boolean all, @QueryParam("userId") long userId) throws SQLException { if (all) { return Context.getNotificationManager().getAllNotifications(); } if (userId == 0) { userId = getUserId(); } Context.getPermissionsManager().checkUser(getUserId(), userId); return Context.getNotificationManager().getUserNotifications(userId); } @POST public Response update(Notification entity) throws SQLException { Context.getPermissionsManager().checkReadonly(getUserId()); Context.getPermissionsManager().checkUser(getUserId(), entity.getUserId()); Context.getNotificationManager().updateNotification(entity); return Response.ok(entity).build(); } }
src/org/traccar/api/resource/NotificationResource.java
package org.traccar.api.resource; import java.sql.SQLException; import java.util.Collection; import javax.ws.rs.Consumes; import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.QueryParam; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import org.traccar.Context; import org.traccar.api.BaseResource; import org.traccar.model.Notification; @Path("users/notifications") @Produces(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON) public class NotificationResource extends BaseResource { @GET public Collection<Notification> get(@QueryParam("all") boolean all, @QueryParam("userId") long userId) throws SQLException { if (all) { return Context.getNotificationManager().getAllNotifications(); } if (userId == 0) { userId = getUserId(); } Context.getPermissionsManager().checkUser(getUserId(), userId); return Context.getNotificationManager().getUserNotifications(userId); } @POST public Response update(Notification entity) throws SQLException { Context.getPermissionsManager().checkReadonly(getUserId()); Context.getPermissionsManager().checkUser(getUserId(), entity.getUserId()); Context.getNotificationManager().updateNotification(entity); return Response.ok(entity).build(); } }
Fixed missed license and wrong EOL
src/org/traccar/api/resource/NotificationResource.java
Fixed missed license and wrong EOL
<ide><path>rc/org/traccar/api/resource/NotificationResource.java <add>/* <add> * Copyright 2016 Anton Tananaev ([email protected]) <add> * <add> * Licensed under the Apache License, Version 2.0 (the "License"); <add> * you may not use this file except in compliance with the License. <add> * You may obtain a copy of the License at <add> * <add> * http://www.apache.org/licenses/LICENSE-2.0 <add> * <add> * Unless required by applicable law or agreed to in writing, software <add> * distributed under the License is distributed on an "AS IS" BASIS, <add> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. <add> * See the License for the specific language governing permissions and <add> * limitations under the License. <add> */ <ide> package org.traccar.api.resource; <ide> <ide> import java.sql.SQLException;
JavaScript
mit
0f799d8808410ac1975178721a6720228d794d40
0
rafaeljesus/easy-schedule
import User from '../../api/users/collection' import Event from '../../api/events/collection' describe('Events:RoutesSpec', () => { let fixture = require('./fixture')() , evt1 = fixture.event1 , evt2 = fixture.event2 , name = 'user-name' , password = 'user-password' beforeEach(function* () { try { let user = yield User.create(name, password) evt1.user = user evt2.user = user let res = yield [ Event.create(evt1), Event.create(evt2), ] evt1 = res[0] evt2 = res[1] } catch(err) { expect(err).to.not.exist } }) afterEach(function* () { try { yield [ User.cleardb(), Event.cleardb() ] } catch(err) { expect(err).to.not.exist } }) it('should respond 401', done => { request. get('/events'). set('Accept', 'application/json'). set('Accept-Encoding', 'gzip'). expect('Content-Type', /json/). expect(401, done) }) describe('GET /v1/events', () => { it('should find all events', done => { request. get('/v1/events'). auth(name, password). set('Accept', 'application/json'). set('Accept-Encoding', 'gzip'). expect('Content-Type', /json/). expect(200, done) }) }) describe('GET /v1/events/:id', () => { it('should find a event by id', done => { request. get('/v1/events/' + evt1._id). auth(name, password). set('Accept', 'application/json'). set('Accept-Encoding', 'gzip'). expect('Content-Type', /json/). expect(200, done) }) }) describe('POST /v1/events', () => { it('should create a event', done => { delete evt1._id const newEvent = evt1 request. post('/v1/events'). auth(name, password). set('Accept', 'application/json'). set('Accept-Encoding', 'gzip'). send(newEvent). expect('Content-Type', /json/). expect(200, done) }) }) describe('PUT /v1/events/:id', () => { it('should update a event', done => { let _id = evt1._id delete evt1._id evt1.url = 'https://github.com/rafaeljesus' request. put('/v1/events/' + _id). auth(name, password). send(evt1). set('Accept', 'application/json'). set('Accept-Encoding', 'gzip'). expect('Content-Type', /json/). expect(200, done) }) }) describe('DELETE /v1/events/:id', () => { it('should delete a event', done => { request. delete('/v1/events/' + evt1._id). auth(name, password). set('Accept', 'application/json'). set('Accept-Encoding', 'gzip'). expect('Content-Type', /json/). expect(200, done) }) }) })
test/events/routes.spec.js
import User from '../../api/users/collection' import Event from '../../api/events/collection' describe('Events:RoutesSpec', () => { let fixture = require('./fixture')() , evt1 = fixture.event1 , evt2 = fixture.event2 , name = 'user-name' , password = 'user-password' beforeEach(function* () { try { let user = yield User.create(name, password) evt1.user = user evt2.user = user let res = yield [ Event.create(evt1), Event.create(evt2), ] evt1 = res[0] evt2 = res[1] } catch(err) { expect(err).to.not.exist } }) afterEach(function* () { try { yield [ User.cleardb(), Event.cleardb() ] } catch(err) { expect(err).to.not.exist } }) it('should respond 401', done => { request. get('/events'). set('Accept', 'application/json'). set('Accept-Encoding', 'gzip'). expect('Content-Type', /json/). expect(401, (err, res) => { if (err) return done(err) expect(res.body.error).to.equal('unauthorized') done() }) }) describe('GET /v1/events', () => { it('should find all events', done => { request. get('/v1/events'). auth(name, password). set('Accept', 'application/json'). set('Accept-Encoding', 'gzip'). expect('Content-Type', /json/). expect(200, (err, res) => { if (err) return done(err) expect(res.body.length).to.be.equal(2) done() }) }) }) describe('GET /v1/events/:id', () => { it('should find a event by id', done => { request. get('/v1/events/' + evt1._id). auth(name, password). set('Accept', 'application/json'). set('Accept-Encoding', 'gzip'). expect('Content-Type', /json/). expect(200, (err, res) => { if (err) return done(err) expect(res.body._id).to.be.equal(evt1._id + '') done() }) }) }) describe('POST /v1/events', () => { it('should create a event', done => { delete evt1._id const newEvent = evt1 request. post('/v1/events'). auth(name, password). set('Accept', 'application/json'). set('Accept-Encoding', 'gzip'). send(newEvent). expect('Content-Type', /json/). expect(200, (err, res) => { if (err) return done(err) expect(res.body._id).to.exist done() }) }) }) describe('PUT /v1/events/:id', () => { it('should update a event', done => { let _id = evt1._id delete evt1._id evt1.url = 'https://github.com/rafaeljesus' request. put('/v1/events/' + _id). auth(name, password). send(evt1). set('Accept', 'application/json'). set('Accept-Encoding', 'gzip'). expect('Content-Type', /json/). expect(200, (err, res) => { if (err) return done(err) expect(res.body.url).to.be.equal(evt1.url) done() }) }) }) describe('DELETE /v1/events/:id', () => { it('should delete a event', done => { request. delete('/v1/events/' + evt1._id). auth(name, password). set('Accept', 'application/json'). set('Accept-Encoding', 'gzip'). expect('Content-Type', /json/). expect(200, (err, res) => { if (err) return done(err) expect(res.status).to.be.equal(200) done() }) }) }) })
Remove unnecessary done callback from spec
test/events/routes.spec.js
Remove unnecessary done callback from spec
<ide><path>est/events/routes.spec.js <ide> set('Accept', 'application/json'). <ide> set('Accept-Encoding', 'gzip'). <ide> expect('Content-Type', /json/). <del> expect(401, (err, res) => { <del> if (err) return done(err) <del> expect(res.body.error).to.equal('unauthorized') <del> done() <del> }) <add> expect(401, done) <ide> }) <ide> <ide> describe('GET /v1/events', () => { <ide> set('Accept', 'application/json'). <ide> set('Accept-Encoding', 'gzip'). <ide> expect('Content-Type', /json/). <del> expect(200, (err, res) => { <del> if (err) return done(err) <del> expect(res.body.length).to.be.equal(2) <del> done() <del> }) <add> expect(200, done) <ide> }) <ide> }) <ide> <ide> set('Accept', 'application/json'). <ide> set('Accept-Encoding', 'gzip'). <ide> expect('Content-Type', /json/). <del> expect(200, (err, res) => { <del> if (err) return done(err) <del> expect(res.body._id).to.be.equal(evt1._id + '') <del> done() <del> }) <add> expect(200, done) <ide> }) <ide> }) <ide> <ide> set('Accept-Encoding', 'gzip'). <ide> send(newEvent). <ide> expect('Content-Type', /json/). <del> expect(200, (err, res) => { <del> if (err) return done(err) <del> expect(res.body._id).to.exist <del> done() <del> }) <add> expect(200, done) <ide> }) <ide> }) <ide> <ide> set('Accept', 'application/json'). <ide> set('Accept-Encoding', 'gzip'). <ide> expect('Content-Type', /json/). <del> expect(200, (err, res) => { <del> if (err) return done(err) <del> expect(res.body.url).to.be.equal(evt1.url) <del> done() <del> }) <add> expect(200, done) <ide> }) <ide> }) <ide> <ide> set('Accept', 'application/json'). <ide> set('Accept-Encoding', 'gzip'). <ide> expect('Content-Type', /json/). <del> expect(200, (err, res) => { <del> if (err) return done(err) <del> expect(res.status).to.be.equal(200) <del> done() <del> }) <add> expect(200, done) <ide> }) <ide> }) <ide> })
Java
apache-2.0
2e99b50fffda1c6798a0ef5c1dba6feb5cb70ef4
0
kuali/kc-rice,UniversityOfHawaiiORS/rice,shahess/rice,cniesen/rice,smith750/rice,ewestfal/rice,bsmith83/rice-1,shahess/rice,gathreya/rice-kc,bhutchinson/rice,jwillia/kc-rice1,rojlarge/rice-kc,kuali/kc-rice,bsmith83/rice-1,bsmith83/rice-1,ewestfal/rice-svn2git-test,jwillia/kc-rice1,cniesen/rice,gathreya/rice-kc,sonamuthu/rice-1,geothomasp/kualico-rice-kc,rojlarge/rice-kc,UniversityOfHawaiiORS/rice,rojlarge/rice-kc,ewestfal/rice,sonamuthu/rice-1,sonamuthu/rice-1,ewestfal/rice,cniesen/rice,kuali/kc-rice,ewestfal/rice-svn2git-test,ewestfal/rice-svn2git-test,smith750/rice,jwillia/kc-rice1,geothomasp/kualico-rice-kc,sonamuthu/rice-1,UniversityOfHawaiiORS/rice,cniesen/rice,shahess/rice,kuali/kc-rice,geothomasp/kualico-rice-kc,UniversityOfHawaiiORS/rice,ewestfal/rice,geothomasp/kualico-rice-kc,bhutchinson/rice,shahess/rice,rojlarge/rice-kc,rojlarge/rice-kc,bhutchinson/rice,kuali/kc-rice,smith750/rice,bhutchinson/rice,ewestfal/rice-svn2git-test,smith750/rice,jwillia/kc-rice1,geothomasp/kualico-rice-kc,bsmith83/rice-1,UniversityOfHawaiiORS/rice,bhutchinson/rice,gathreya/rice-kc,shahess/rice,jwillia/kc-rice1,cniesen/rice,gathreya/rice-kc,ewestfal/rice,smith750/rice,gathreya/rice-kc
/** * Copyright 2005-2013 The Kuali Foundation * * Licensed under the Educational Community License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.opensource.org/licenses/ecl2.php * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package edu.sampleu.travel.dataobject; import edu.sampleu.travel.options.PostalCountryCode; import edu.sampleu.travel.options.PostalCountryCodeKeyValuesFinder; import edu.sampleu.travel.options.PostalStateCode; import edu.sampleu.travel.options.PostalStateCodeKeyValuesFinder; import org.kuali.rice.core.api.mo.common.active.MutableInactivatable; import org.kuali.rice.krad.bo.DataObjectBase; import org.kuali.rice.krad.data.jpa.converters.BooleanYNConverter; import org.kuali.rice.krad.data.jpa.eclipselink.PortableSequenceGenerator; import org.kuali.rice.krad.data.provider.annotation.Description; import org.kuali.rice.krad.data.provider.annotation.KeyValuesFinderClass; import org.kuali.rice.krad.data.provider.annotation.Label; import org.kuali.rice.krad.data.provider.annotation.UifAutoCreateViewType; import org.kuali.rice.krad.data.provider.annotation.UifAutoCreateViews; import org.kuali.rice.krad.data.provider.annotation.UifDisplayHint; import org.kuali.rice.krad.data.provider.annotation.UifDisplayHintType; import org.kuali.rice.krad.data.provider.annotation.UifDisplayHints; import org.kuali.rice.krad.data.provider.annotation.UifValidCharactersConstraintBeanName; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.Table; import javax.persistence.Transient; import java.io.Serializable; /** * This class provides travel destination record for TEM sample * * @author Kuali Rice Team ([email protected]) */ @Entity @Table(name = "TRVL_DEST_T") @UifAutoCreateViews({UifAutoCreateViewType.INQUIRY, UifAutoCreateViewType.LOOKUP}) public class TravelDestination extends DataObjectBase implements MutableInactivatable, Serializable { private static final long serialVersionUID = 8448891916448081149L; @Id @Column(name = "TRVL_DEST_ID", length = 40) @GeneratedValue(generator = "TRVL_DEST_ID_S") @PortableSequenceGenerator(name = "TRVL_DEST_ID_S") @Label("id") @Description("Unique identifier for destination item") @UifValidCharactersConstraintBeanName("AlphaNumericPatternConstraint") private String travelDestinationId; @Column(name = "DEST_NM", length = 40) @Label("Destination name") @Description("Name of location") private String travelDestinationName; @Column(name = "POSTAL_CNTRY_CD") @UifDisplayHints({@UifDisplayHint(UifDisplayHintType.NO_LOOKUP_RESULT), @UifDisplayHint(UifDisplayHintType.NO_INQUIRY)}) @KeyValuesFinderClass(PostalCountryCodeKeyValuesFinder.class) private String countryCd; @Transient @UifDisplayHints(@UifDisplayHint(UifDisplayHintType.NO_LOOKUP_CRITERIA)) @Label("Country") private String countryName; @Column(name = "POSTAL_STATE_CD") @UifDisplayHints({@UifDisplayHint(UifDisplayHintType.NO_LOOKUP_RESULT), @UifDisplayHint(UifDisplayHintType.NO_INQUIRY)}) @KeyValuesFinderClass(PostalStateCodeKeyValuesFinder.class) private String stateCd; @Transient @UifDisplayHints(@UifDisplayHint(UifDisplayHintType.NO_LOOKUP_CRITERIA)) @Label("State") private String stateName; @Column(name = "ACTV_IND", nullable = false, length = 1) @javax.persistence.Convert(converter = BooleanYNConverter.class) @Label("Active") @Description("Whether active or inactive") private boolean active = Boolean.TRUE; public String getTravelDestinationId() { return travelDestinationId; } public void setTravelDestinationId(String travelDestinationId) { this.travelDestinationId = travelDestinationId; } public String getTravelDestinationName() { return travelDestinationName; } public void setTravelDestinationName(String travelDestinationName) { this.travelDestinationName = travelDestinationName; } public String getCountryCd() { return countryCd; } public void setCountryCd(String countryCd) { this.countryCd = countryCd; } public String getCountryName() { return PostalCountryCode.valueOf(countryCd).getLabel(); } public String getStateCd() { return stateCd; } public void setStateCd(String stateCd) { this.stateCd = stateCd; } public String getStateName() { return PostalStateCode.valueOf(stateCd).getLabel(); } public boolean isActive() { return active; } public void setActive(boolean active) { this.active = active; } }
rice-framework/krad-sampleapp/impl/src/main/java/edu/sampleu/travel/dataobject/TravelDestination.java
/** * Copyright 2005-2013 The Kuali Foundation * * Licensed under the Educational Community License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.opensource.org/licenses/ecl2.php * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package edu.sampleu.travel.dataobject; import edu.sampleu.travel.options.PostalCountryCodeKeyValuesFinder; import edu.sampleu.travel.options.PostalStateCodeKeyValuesFinder; import org.kuali.rice.core.api.mo.common.active.MutableInactivatable; import org.kuali.rice.krad.bo.DataObjectBase; import org.kuali.rice.krad.data.jpa.converters.BooleanYNConverter; import org.kuali.rice.krad.data.jpa.eclipselink.PortableSequenceGenerator; import org.kuali.rice.krad.data.provider.annotation.Description; import org.kuali.rice.krad.data.provider.annotation.KeyValuesFinderClass; import org.kuali.rice.krad.data.provider.annotation.Label; import org.kuali.rice.krad.data.provider.annotation.UifAutoCreateViewType; import org.kuali.rice.krad.data.provider.annotation.UifAutoCreateViews; import org.kuali.rice.krad.data.provider.annotation.UifValidCharactersConstraintBeanName; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.Table; import java.io.Serializable; /** * This class provides travel destination record for TEM sample * * @author Kuali Rice Team ([email protected]) */ @Entity @Table(name = "TRVL_DEST_T") @UifAutoCreateViews({UifAutoCreateViewType.INQUIRY, UifAutoCreateViewType.LOOKUP}) public class TravelDestination extends DataObjectBase implements MutableInactivatable, Serializable { private static final long serialVersionUID = 8448891916448081149L; @Id @Column(name = "TRVL_DEST_ID", length = 40) @GeneratedValue(generator = "TRVL_DEST_ID_S") @PortableSequenceGenerator(name = "TRVL_DEST_ID_S") @Label("id") @Description("Unique identifier for destination item") @UifValidCharactersConstraintBeanName("AlphaNumericPatternConstraint") private String travelDestinationId; @Column(name = "DEST_NM", length = 40) @Label("Destination name") @Description("Name of location") private String travelDestinationName; @Column(name = "POSTAL_CNTRY_CD") @KeyValuesFinderClass(PostalCountryCodeKeyValuesFinder.class) private String countryCd; @Column(name = "POSTAL_STATE_CD") @KeyValuesFinderClass(PostalStateCodeKeyValuesFinder.class) private String stateCd; @Column(name = "ACTV_IND", nullable = false, length = 1) @javax.persistence.Convert(converter = BooleanYNConverter.class) @Label("Active") @Description("Whether active or inactive") private boolean active = Boolean.TRUE; public String getTravelDestinationId() { return travelDestinationId; } public void setTravelDestinationId(String travelDestinationId) { this.travelDestinationId = travelDestinationId; } public String getTravelDestinationName() { return travelDestinationName; } public void setTravelDestinationName(String travelDestinationName) { this.travelDestinationName = travelDestinationName; } public String getCountryCd() { return countryCd; } public void setCountryCd(String countryCd) { this.countryCd = countryCd; } public String getStateCd() { return stateCd; } public void setStateCd(String stateCd) { this.stateCd = stateCd; } public boolean isActive() { return active; } public void setActive(boolean active) { this.active = active; } }
KULRICE-11003 Advanced Lookup Demo - Configure basic DD, Maintenance, Lookup & Inquiry for Primary Destination
rice-framework/krad-sampleapp/impl/src/main/java/edu/sampleu/travel/dataobject/TravelDestination.java
KULRICE-11003 Advanced Lookup Demo - Configure basic DD, Maintenance, Lookup & Inquiry for Primary Destination
<ide><path>ice-framework/krad-sampleapp/impl/src/main/java/edu/sampleu/travel/dataobject/TravelDestination.java <ide> */ <ide> package edu.sampleu.travel.dataobject; <ide> <add>import edu.sampleu.travel.options.PostalCountryCode; <ide> import edu.sampleu.travel.options.PostalCountryCodeKeyValuesFinder; <add>import edu.sampleu.travel.options.PostalStateCode; <ide> import edu.sampleu.travel.options.PostalStateCodeKeyValuesFinder; <ide> import org.kuali.rice.core.api.mo.common.active.MutableInactivatable; <ide> import org.kuali.rice.krad.bo.DataObjectBase; <ide> import org.kuali.rice.krad.data.provider.annotation.Label; <ide> import org.kuali.rice.krad.data.provider.annotation.UifAutoCreateViewType; <ide> import org.kuali.rice.krad.data.provider.annotation.UifAutoCreateViews; <add>import org.kuali.rice.krad.data.provider.annotation.UifDisplayHint; <add>import org.kuali.rice.krad.data.provider.annotation.UifDisplayHintType; <add>import org.kuali.rice.krad.data.provider.annotation.UifDisplayHints; <ide> import org.kuali.rice.krad.data.provider.annotation.UifValidCharactersConstraintBeanName; <ide> <ide> import javax.persistence.Column; <ide> import javax.persistence.GeneratedValue; <ide> import javax.persistence.Id; <ide> import javax.persistence.Table; <add>import javax.persistence.Transient; <ide> import java.io.Serializable; <ide> <ide> /** <ide> private String travelDestinationName; <ide> <ide> @Column(name = "POSTAL_CNTRY_CD") <add> @UifDisplayHints({@UifDisplayHint(UifDisplayHintType.NO_LOOKUP_RESULT), <add> @UifDisplayHint(UifDisplayHintType.NO_INQUIRY)}) <ide> @KeyValuesFinderClass(PostalCountryCodeKeyValuesFinder.class) <ide> private String countryCd; <ide> <add> @Transient <add> @UifDisplayHints(@UifDisplayHint(UifDisplayHintType.NO_LOOKUP_CRITERIA)) <add> @Label("Country") <add> private String countryName; <add> <ide> @Column(name = "POSTAL_STATE_CD") <add> @UifDisplayHints({@UifDisplayHint(UifDisplayHintType.NO_LOOKUP_RESULT), <add> @UifDisplayHint(UifDisplayHintType.NO_INQUIRY)}) <ide> @KeyValuesFinderClass(PostalStateCodeKeyValuesFinder.class) <ide> private String stateCd; <add> <add> @Transient <add> @UifDisplayHints(@UifDisplayHint(UifDisplayHintType.NO_LOOKUP_CRITERIA)) <add> @Label("State") <add> private String stateName; <add> <ide> <ide> @Column(name = "ACTV_IND", nullable = false, length = 1) <ide> @javax.persistence.Convert(converter = BooleanYNConverter.class) <ide> this.countryCd = countryCd; <ide> } <ide> <add> public String getCountryName() { <add> return PostalCountryCode.valueOf(countryCd).getLabel(); <add> } <add> <ide> public String getStateCd() { <ide> return stateCd; <ide> } <ide> <ide> public void setStateCd(String stateCd) { <ide> this.stateCd = stateCd; <add> } <add> <add> public String getStateName() { <add> return PostalStateCode.valueOf(stateCd).getLabel(); <ide> } <ide> <ide> public boolean isActive() {
Java
apache-2.0
c6788ccb91ac88f7ae3d15b8c7d6b9251c4dd7c1
0
psoreide/bnd,psoreide/bnd,psoreide/bnd
package aQute.libg.reporter; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.lang.reflect.Proxy; import java.util.Arrays; import java.util.IllegalFormatException; import aQute.service.reporter.Messages.ERROR; import aQute.service.reporter.Messages.WARNING; import aQute.service.reporter.Report.Location; import aQute.service.reporter.Reporter; import aQute.service.reporter.Reporter.SetLocation; public class ReporterMessages { static class WARNINGImpl implements WARNING { Reporter.SetLocation loc; @Override public SetLocation file(String file) { return loc.file(file); } @Override public SetLocation header(String header) { return loc.header(header); } @Override public SetLocation context(String context) { return loc.context(context); } @Override public SetLocation method(String methodName) { return loc.method(methodName); } @Override public SetLocation line(int n) { return loc.line(n); } @Override public SetLocation reference(String reference) { return loc.reference(reference); } public WARNINGImpl(Reporter.SetLocation loc) { this.loc = loc; } @Override public SetLocation details(Object details) { return loc.details(details); } @Override public Location location() { return loc.location(); } @Override public SetLocation length(int length) { loc.length(length); return this; } } static class ERRORImpl extends WARNINGImpl implements ERROR { public ERRORImpl(SetLocation e) { super(e); } } @SuppressWarnings("unchecked") public static <T> T base(final Reporter reporter, Class<T> messages) { return (T) Proxy.newProxyInstance(messages.getClassLoader(), new Class[] { messages }, new InvocationHandler() { @Override @SuppressWarnings("deprecation") public Object invoke(Object target, Method method, Object[] args) throws Throwable { String format; Message d = method.getAnnotation(Message.class); if (d == null) { String name = method.getName(); StringBuilder sb = new StringBuilder(); sb.append(name.charAt(0)); int n = 0; for (int i = 1; i < name.length(); i++) { char c = name.charAt(i); switch (c) { case '_' : sb.append(" %s"); if (i + 1 < name.length()) { sb.append(", "); } n++; break; case '$' : sb.append(" "); break; default : if (Character.isUpperCase(c)) { sb.append(" "); c = Character.toLowerCase(c); } sb.append(c); } } while (n < method.getParameterTypes().length) { sb.append(": %s"); n++; } format = sb.toString(); } else { format = d.value(); } try { if (method.getReturnType() == ERROR.class) { for (int i = args.length - 1; i >= 0; i--) { if (args[i] instanceof Throwable) { return new ERRORImpl(reporter.exception((Throwable) args[i], format, args)); } } return new ERRORImpl(reporter.error(format, args)); } else if (method.getReturnType() == WARNING.class) { return new WARNINGImpl(reporter.warning(format, args)); } else { reporter.trace(format, args); } } catch (IllegalFormatException e) { reporter.error("Formatter failed: %s %s %s", method.getName(), format, Arrays.toString(args)); } return null; } }); } }
aQute.libg/src/aQute/libg/reporter/ReporterMessages.java
package aQute.libg.reporter; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.lang.reflect.Proxy; import java.util.Arrays; import java.util.IllegalFormatException; import aQute.service.reporter.Messages.ERROR; import aQute.service.reporter.Messages.WARNING; import aQute.service.reporter.Report.Location; import aQute.service.reporter.Reporter; import aQute.service.reporter.Reporter.SetLocation; public class ReporterMessages { static class WARNINGImpl implements WARNING { Reporter.SetLocation loc; @Override public SetLocation file(String file) { return loc.file(file); } @Override public SetLocation header(String header) { return loc.header(header); } @Override public SetLocation context(String context) { return loc.context(context); } @Override public SetLocation method(String methodName) { return loc.method(methodName); } @Override public SetLocation line(int n) { return loc.line(n); } @Override public SetLocation reference(String reference) { return loc.reference(reference); } public WARNINGImpl(Reporter.SetLocation loc) { this.loc = loc; } @Override public SetLocation details(Object details) { return loc.details(details); } @Override public Location location() { return loc.location(); } @Override public SetLocation length(int length) { loc.length(length); return this; } } static class ERRORImpl extends WARNINGImpl implements ERROR { public ERRORImpl(SetLocation e) { super(e); } } @SuppressWarnings("unchecked") public static <T> T base(final Reporter reporter, Class<T> messages) { return (T) Proxy.newProxyInstance(messages.getClassLoader(), new Class[] { messages }, new InvocationHandler() { @Override @SuppressWarnings("deprecation") public Object invoke(Object target, Method method, Object[] args) throws Throwable { String format; Message d = method.getAnnotation(Message.class); if (d == null) { String name = method.getName(); StringBuilder sb = new StringBuilder(); sb.append(name.charAt(0)); int n = 0; for (int i = 1; i < name.length(); i++) { char c = name.charAt(i); switch (c) { case '_' : sb.append(" %s, "); n++; break; case '$' : sb.append(" "); break; default : if (Character.isUpperCase(c)) { sb.append(" "); c = Character.toLowerCase(c); } sb.append(c); } } while (n < method.getParameterTypes().length) { sb.append(": %s"); n++; } format = sb.toString(); } else format = d.value(); try { if (method.getReturnType() == ERROR.class) { return new ERRORImpl(reporter.error(format, args)); } else if (method.getReturnType() == WARNING.class) { return new WARNINGImpl(reporter.warning(format, args)); } else reporter.trace(format, args); } catch (IllegalFormatException e) { reporter.error("Formatter failed: %s %s %s", method.getName(), format, Arrays.toString(args)); } return null; } }); } }
reporter: Better report exceptions for ERROR class proxy This will unroll InvocationTargetExceptions to show the real issue. Signed-off-by: BJ Hargrave <[email protected]>
aQute.libg/src/aQute/libg/reporter/ReporterMessages.java
reporter: Better report exceptions for ERROR class proxy
<ide><path>Qute.libg/src/aQute/libg/reporter/ReporterMessages.java <ide> char c = name.charAt(i); <ide> switch (c) { <ide> case '_' : <del> sb.append(" %s, "); <add> sb.append(" %s"); <add> if (i + 1 < name.length()) { <add> sb.append(", "); <add> } <ide> n++; <ide> break; <ide> <ide> n++; <ide> } <ide> format = sb.toString(); <del> } else <add> } else { <ide> format = d.value(); <add> } <ide> <ide> try { <ide> if (method.getReturnType() == ERROR.class) { <add> for (int i = args.length - 1; i >= 0; i--) { <add> if (args[i] instanceof Throwable) { <add> return new ERRORImpl(reporter.exception((Throwable) args[i], format, args)); <add> } <add> } <ide> return new ERRORImpl(reporter.error(format, args)); <del> <ide> } else if (method.getReturnType() == WARNING.class) { <ide> return new WARNINGImpl(reporter.warning(format, args)); <del> } else <add> } else { <ide> reporter.trace(format, args); <add> } <ide> } catch (IllegalFormatException e) { <ide> reporter.error("Formatter failed: %s %s %s", method.getName(), format, Arrays.toString(args)); <ide> }
Java
apache-2.0
ffabf9ba9b70baa679cca6cf804ef4ec275fdccc
0
amyvmiwei/hbase,Eshcar/hbase,narendragoyal/hbase,ChinmaySKulkarni/hbase,Guavus/hbase,JingchengDu/hbase,StackVista/hbase,ibmsoe/hbase,mahak/hbase,apurtell/hbase,bijugs/hbase,Apache9/hbase,Guavus/hbase,drewpope/hbase,drewpope/hbase,StackVista/hbase,Apache9/hbase,drewpope/hbase,justintung/hbase,apurtell/hbase,HubSpot/hbase,HubSpot/hbase,StackVista/hbase,narendragoyal/hbase,StackVista/hbase,joshelser/hbase,juwi/hbase,JingchengDu/hbase,justintung/hbase,justintung/hbase,StackVista/hbase,juwi/hbase,francisliu/hbase,amyvmiwei/hbase,drewpope/hbase,ndimiduk/hbase,ultratendency/hbase,vincentpoon/hbase,Guavus/hbase,apurtell/hbase,apurtell/hbase,vincentpoon/hbase,Guavus/hbase,StackVista/hbase,amyvmiwei/hbase,bijugs/hbase,Eshcar/hbase,justintung/hbase,narendragoyal/hbase,gustavoanatoly/hbase,ibmsoe/hbase,ndimiduk/hbase,bijugs/hbase,lshmouse/hbase,gustavoanatoly/hbase,ndimiduk/hbase,joshelser/hbase,ChinmaySKulkarni/hbase,vincentpoon/hbase,mahak/hbase,vincentpoon/hbase,gustavoanatoly/hbase,JingchengDu/hbase,ndimiduk/hbase,SeekerResource/hbase,vincentpoon/hbase,JingchengDu/hbase,HubSpot/hbase,StackVista/hbase,justintung/hbase,StackVista/hbase,HubSpot/hbase,toshimasa-nasu/hbase,ChinmaySKulkarni/hbase,andrewmains12/hbase,ChinmaySKulkarni/hbase,ultratendency/hbase,lshmouse/hbase,ChinmaySKulkarni/hbase,ultratendency/hbase,narendragoyal/hbase,juwi/hbase,vincentpoon/hbase,francisliu/hbase,narendragoyal/hbase,amyvmiwei/hbase,ChinmaySKulkarni/hbase,gustavoanatoly/hbase,gustavoanatoly/hbase,andrewmains12/hbase,justintung/hbase,bijugs/hbase,SeekerResource/hbase,juwi/hbase,HubSpot/hbase,ibmsoe/hbase,joshelser/hbase,SeekerResource/hbase,SeekerResource/hbase,narendragoyal/hbase,apurtell/hbase,francisliu/hbase,lshmouse/hbase,mahak/hbase,ChinmaySKulkarni/hbase,vincentpoon/hbase,Guavus/hbase,joshelser/hbase,joshelser/hbase,juwi/hbase,mahak/hbase,justintung/hbase,ultratendency/hbase,andrewmains12/hbase,JingchengDu/hbase,joshelser/hbase,francisliu/hbase,lshmouse/hbase,ChinmaySKulkarni/hbase,ibmsoe/hbase,HubSpot/hbase,ibmsoe/hbase,narendragoyal/hbase,Guavus/hbase,ChinmaySKulkarni/hbase,SeekerResource/hbase,mahak/hbase,francisliu/hbase,narendragoyal/hbase,StackVista/hbase,amyvmiwei/hbase,Apache9/hbase,andrewmains12/hbase,HubSpot/hbase,juwi/hbase,mahak/hbase,ndimiduk/hbase,toshimasa-nasu/hbase,vincentpoon/hbase,toshimasa-nasu/hbase,apurtell/hbase,Apache9/hbase,SeekerResource/hbase,joshelser/hbase,ibmsoe/hbase,drewpope/hbase,toshimasa-nasu/hbase,amyvmiwei/hbase,vincentpoon/hbase,ndimiduk/hbase,apurtell/hbase,francisliu/hbase,amyvmiwei/hbase,vincentpoon/hbase,apurtell/hbase,toshimasa-nasu/hbase,ndimiduk/hbase,bijugs/hbase,Eshcar/hbase,Eshcar/hbase,toshimasa-nasu/hbase,JingchengDu/hbase,ibmsoe/hbase,lshmouse/hbase,drewpope/hbase,JingchengDu/hbase,ultratendency/hbase,bijugs/hbase,gustavoanatoly/hbase,JingchengDu/hbase,lshmouse/hbase,narendragoyal/hbase,ultratendency/hbase,SeekerResource/hbase,toshimasa-nasu/hbase,Eshcar/hbase,Eshcar/hbase,amyvmiwei/hbase,drewpope/hbase,Guavus/hbase,toshimasa-nasu/hbase,ibmsoe/hbase,Eshcar/hbase,bijugs/hbase,juwi/hbase,HubSpot/hbase,ndimiduk/hbase,lshmouse/hbase,francisliu/hbase,andrewmains12/hbase,amyvmiwei/hbase,toshimasa-nasu/hbase,ndimiduk/hbase,ChinmaySKulkarni/hbase,gustavoanatoly/hbase,Apache9/hbase,andrewmains12/hbase,justintung/hbase,SeekerResource/hbase,mahak/hbase,narendragoyal/hbase,gustavoanatoly/hbase,joshelser/hbase,justintung/hbase,apurtell/hbase,Apache9/hbase,andrewmains12/hbase,juwi/hbase,joshelser/hbase,HubSpot/hbase,mahak/hbase,lshmouse/hbase,andrewmains12/hbase,JingchengDu/hbase,mahak/hbase,francisliu/hbase,bijugs/hbase,ultratendency/hbase,JingchengDu/hbase,drewpope/hbase,lshmouse/hbase,ibmsoe/hbase,amyvmiwei/hbase,HubSpot/hbase,Apache9/hbase,Guavus/hbase,justintung/hbase,francisliu/hbase,Apache9/hbase,juwi/hbase,StackVista/hbase,SeekerResource/hbase,lshmouse/hbase,bijugs/hbase,andrewmains12/hbase,joshelser/hbase,Guavus/hbase,ultratendency/hbase,Apache9/hbase,Eshcar/hbase,Eshcar/hbase,Guavus/hbase,drewpope/hbase,ndimiduk/hbase,ultratendency/hbase,Apache9/hbase,ultratendency/hbase,apurtell/hbase,andrewmains12/hbase,bijugs/hbase,Eshcar/hbase,francisliu/hbase,SeekerResource/hbase,mahak/hbase,ibmsoe/hbase,gustavoanatoly/hbase,gustavoanatoly/hbase
/* * 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.hbase.util; import java.io.IOException; import java.util.Arrays; import java.util.HashSet; import java.util.Set; import java.util.concurrent.atomic.AtomicLong; import org.apache.commons.lang.math.RandomUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.hbase.HRegionLocation; import org.apache.hadoop.hbase.TableName; import org.apache.hadoop.hbase.client.Get; import org.apache.hadoop.hbase.client.HTable; import org.apache.hadoop.hbase.client.Result; import org.apache.hadoop.hbase.util.test.LoadTestDataGenerator; /** Creates multiple threads that read and verify previously written data */ public class MultiThreadedReader extends MultiThreadedAction { private static final Log LOG = LogFactory.getLog(MultiThreadedReader.class); protected Set<HBaseReaderThread> readers = new HashSet<HBaseReaderThread>(); private final double verifyPercent; protected volatile boolean aborted; protected MultiThreadedWriterBase writer = null; /** * The number of keys verified in a sequence. This will never be larger than * the total number of keys in the range. The reader might also verify * random keys when it catches up with the writer. */ private final AtomicLong numUniqueKeysVerified = new AtomicLong(); /** * Default maximum number of read errors to tolerate before shutting down all * readers. */ public static final int DEFAULT_MAX_ERRORS = 10; /** * Default "window" size between the last key written by the writer and the * key that we attempt to read. The lower this number, the stricter our * testing is. If this is zero, we always attempt to read the highest key * in the contiguous sequence of keys written by the writers. */ public static final int DEFAULT_KEY_WINDOW = 0; /** * Default batch size for multigets */ public static final int DEFAULT_BATCH_SIZE = 1; //translates to simple GET (no multi GET) protected AtomicLong numKeysVerified = new AtomicLong(0); protected AtomicLong numReadErrors = new AtomicLong(0); protected AtomicLong numReadFailures = new AtomicLong(0); protected AtomicLong nullResult = new AtomicLong(0); private int maxErrors = DEFAULT_MAX_ERRORS; private int keyWindow = DEFAULT_KEY_WINDOW; private int batchSize = DEFAULT_BATCH_SIZE; public MultiThreadedReader(LoadTestDataGenerator dataGen, Configuration conf, TableName tableName, double verifyPercent) { super(dataGen, conf, tableName, "R"); this.verifyPercent = verifyPercent; } public void linkToWriter(MultiThreadedWriterBase writer) { this.writer = writer; writer.setTrackWroteKeys(true); } public void setMaxErrors(int maxErrors) { this.maxErrors = maxErrors; } public void setKeyWindow(int keyWindow) { this.keyWindow = keyWindow; } public void setMultiGetBatchSize(int batchSize) { this.batchSize = batchSize; } @Override public void start(long startKey, long endKey, int numThreads) throws IOException { super.start(startKey, endKey, numThreads); if (verbose) { LOG.debug("Reading keys [" + startKey + ", " + endKey + ")"); } addReaderThreads(numThreads); startThreads(readers); } protected void addReaderThreads(int numThreads) throws IOException { for (int i = 0; i < numThreads; ++i) { HBaseReaderThread reader = createReaderThread(i); readers.add(reader); } } protected HBaseReaderThread createReaderThread(int readerId) throws IOException { return new HBaseReaderThread(readerId); } public class HBaseReaderThread extends Thread { protected final int readerId; protected final HTable table; /** The "current" key being read. Increases from startKey to endKey. */ private long curKey; /** Time when the thread started */ protected long startTimeMs; /** If we are ahead of the writer and reading a random key. */ private boolean readingRandomKey; private boolean printExceptionTrace = true; /** * @param readerId only the keys with this remainder from division by * {@link #numThreads} will be read by this thread */ public HBaseReaderThread(int readerId) throws IOException { this.readerId = readerId; table = createTable(); setName(getClass().getSimpleName() + "_" + readerId); } protected HTable createTable() throws IOException { return new HTable(conf, tableName); } @Override public void run() { try { runReader(); } finally { closeTable(); numThreadsWorking.decrementAndGet(); } } protected void closeTable() { try { if (table != null) { table.close(); } } catch (IOException e) { LOG.error("Error closing table", e); } } private void runReader() { if (verbose) { LOG.info("Started thread #" + readerId + " for reads..."); } startTimeMs = System.currentTimeMillis(); curKey = startKey; long [] keysForThisReader = new long[batchSize]; int readingRandomKeyStartIndex = -1; while (curKey < endKey && !aborted) { int numKeys = 0; // if multiGet, loop until we have the number of keys equal to the batch size do { long k = getNextKeyToRead(); if (k < startKey || k >= endKey) { numReadErrors.incrementAndGet(); throw new AssertionError("Load tester logic error: proposed key " + "to read " + k + " is out of range (startKey=" + startKey + ", endKey=" + endKey + ")"); } if (k % numThreads != readerId || writer != null && writer.failedToWriteKey(k)) { // Skip keys that this thread should not read, as well as the keys // that we know the writer failed to write. continue; } keysForThisReader[numKeys] = k; if (readingRandomKey && readingRandomKeyStartIndex == -1) { //store the first index of a random read readingRandomKeyStartIndex = numKeys; } numKeys++; } while (numKeys < batchSize); if (numKeys > 0) { //meaning there is some key to read readKey(keysForThisReader); // We have verified some unique key(s). numUniqueKeysVerified.getAndAdd(readingRandomKeyStartIndex == -1 ? numKeys : readingRandomKeyStartIndex); } } } /** * Should only be used for the concurrent writer/reader workload. The * maximum key we are allowed to read, subject to the "key window" * constraint. */ private long maxKeyWeCanRead() { long insertedUpToKey = writer.wroteUpToKey(); if (insertedUpToKey >= endKey - 1) { // The writer has finished writing our range, so we can read any // key in the range. return endKey - 1; } return Math.min(endKey - 1, writer.wroteUpToKey() - keyWindow); } protected long getNextKeyToRead() { readingRandomKey = false; if (writer == null || curKey <= maxKeyWeCanRead()) { return curKey++; } // We caught up with the writer. See if we can read any keys at all. long maxKeyToRead; while ((maxKeyToRead = maxKeyWeCanRead()) < startKey) { // The writer has not written sufficient keys for us to be able to read // anything at all. Sleep a bit. This should only happen in the // beginning of a load test run. Threads.sleepWithoutInterrupt(50); } if (curKey <= maxKeyToRead) { // The writer wrote some keys, and we are now allowed to read our // current key. return curKey++; } // startKey <= maxKeyToRead <= curKey - 1. Read one of the previous keys. // Don't increment the current key -- we still have to try reading it // later. Set a flag to make sure that we don't count this key towards // the set of unique keys we have verified. readingRandomKey = true; return startKey + Math.abs(RandomUtils.nextLong()) % (maxKeyToRead - startKey + 1); } private Get[] readKey(long[] keysToRead) { Get [] gets = new Get[keysToRead.length]; int i = 0; for (long keyToRead : keysToRead) { try { gets[i] = createGet(keyToRead); if (keysToRead.length == 1) { queryKey(gets[i], RandomUtils.nextInt(100) < verifyPercent, keyToRead); } i++; } catch (IOException e) { numReadFailures.addAndGet(1); LOG.debug("[" + readerId + "] FAILED read, key = " + (keyToRead + "") + ", time from start: " + (System.currentTimeMillis() - startTimeMs) + " ms"); if (printExceptionTrace) { LOG.warn(e); printExceptionTrace = false; } } } if (keysToRead.length > 1) { try { queryKey(gets, RandomUtils.nextInt(100) < verifyPercent, keysToRead); } catch (IOException e) { numReadFailures.addAndGet(gets.length); for (long keyToRead : keysToRead) { LOG.debug("[" + readerId + "] FAILED read, key = " + (keyToRead + "") + ", time from start: " + (System.currentTimeMillis() - startTimeMs) + " ms"); } if (printExceptionTrace) { LOG.warn(e); printExceptionTrace = false; } } } return gets; } protected Get createGet(long keyToRead) throws IOException { Get get = new Get(dataGenerator.getDeterministicUniqueKey(keyToRead)); String cfsString = ""; byte[][] columnFamilies = dataGenerator.getColumnFamilies(); for (byte[] cf : columnFamilies) { get.addFamily(cf); if (verbose) { if (cfsString.length() > 0) { cfsString += ", "; } cfsString += "[" + Bytes.toStringBinary(cf) + "]"; } } get = dataGenerator.beforeGet(keyToRead, get); if (verbose) { LOG.info("[" + readerId + "] " + "Querying key " + keyToRead + ", cfs " + cfsString); } return get; } public void queryKey(Get[] gets, boolean verify, long[] keysToRead) throws IOException { // read the data long start = System.nanoTime(); // Uses multi/batch gets Result[] results = table.get(Arrays.asList(gets)); long end = System.nanoTime(); verifyResultsAndUpdateMetrics(verify, gets, end - start, results, table, false); } public void queryKey(Get get, boolean verify, long keyToRead) throws IOException { // read the data long start = System.nanoTime(); // Uses simple get Result result = table.get(get); long end = System.nanoTime(); verifyResultsAndUpdateMetrics(verify, get, end - start, result, table, false); } protected void verifyResultsAndUpdateMetrics(boolean verify, Get[] gets, long elapsedNano, Result[] results, HTable table, boolean isNullExpected) throws IOException { totalOpTimeMs.addAndGet(elapsedNano / 1000000); numKeys.addAndGet(gets.length); int i = 0; for (Result result : results) { verifyResultsAndUpdateMetricsOnAPerGetBasis(verify, gets[i++], result, table, isNullExpected); } } protected void verifyResultsAndUpdateMetrics(boolean verify, Get get, long elapsedNano, Result result, HTable table, boolean isNullExpected) throws IOException { verifyResultsAndUpdateMetrics(verify, new Get[]{get}, elapsedNano, new Result[]{result}, table, isNullExpected); } private void verifyResultsAndUpdateMetricsOnAPerGetBasis(boolean verify, Get get, Result result, HTable table, boolean isNullExpected) throws IOException { if (!result.isEmpty()) { if (verify) { numKeysVerified.incrementAndGet(); } } else { HRegionLocation hloc = table.getRegionLocation(get.getRow()); String rowKey = Bytes.toString(get.getRow()); LOG.info("Key = " + rowKey + ", RegionServer: " + hloc.getHostname()); if(isNullExpected) { nullResult.incrementAndGet(); LOG.debug("Null result obtained for the key ="+rowKey); return; } } boolean isOk = verifyResultAgainstDataGenerator(result, verify, false); long numErrorsAfterThis = 0; if (isOk) { long cols = 0; // Count the columns for reporting purposes. for (byte[] cf : result.getMap().keySet()) { cols += result.getFamilyMap(cf).size(); } numCols.addAndGet(cols); } else { if (writer != null) { LOG.error("At the time of failure, writer wrote " + writer.numKeys.get() + " keys"); } numErrorsAfterThis = numReadErrors.incrementAndGet(); } if (numErrorsAfterThis > maxErrors) { LOG.error("Aborting readers -- found more than " + maxErrors + " errors"); aborted = true; } } } public long getNumReadFailures() { return numReadFailures.get(); } public long getNumReadErrors() { return numReadErrors.get(); } public long getNumKeysVerified() { return numKeysVerified.get(); } public long getNumUniqueKeysVerified() { return numUniqueKeysVerified.get(); } public long getNullResultsCount() { return nullResult.get(); } @Override protected String progressInfo() { StringBuilder sb = new StringBuilder(); appendToStatus(sb, "verified", numKeysVerified.get()); appendToStatus(sb, "READ FAILURES", numReadFailures.get()); appendToStatus(sb, "READ ERRORS", numReadErrors.get()); appendToStatus(sb, "NULL RESULT", nullResult.get()); return sb.toString(); } }
hbase-server/src/test/java/org/apache/hadoop/hbase/util/MultiThreadedReader.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.hbase.util; import java.io.IOException; import java.util.Arrays; import java.util.HashSet; import java.util.Set; import java.util.concurrent.atomic.AtomicLong; import org.apache.commons.lang.math.RandomUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.hbase.HRegionLocation; import org.apache.hadoop.hbase.TableName; import org.apache.hadoop.hbase.client.Get; import org.apache.hadoop.hbase.client.HTable; import org.apache.hadoop.hbase.client.Result; import org.apache.hadoop.hbase.util.test.LoadTestDataGenerator; /** Creates multiple threads that read and verify previously written data */ public class MultiThreadedReader extends MultiThreadedAction { private static final Log LOG = LogFactory.getLog(MultiThreadedReader.class); protected Set<HBaseReaderThread> readers = new HashSet<HBaseReaderThread>(); private final double verifyPercent; protected volatile boolean aborted; protected MultiThreadedWriterBase writer = null; /** * The number of keys verified in a sequence. This will never be larger than * the total number of keys in the range. The reader might also verify * random keys when it catches up with the writer. */ private final AtomicLong numUniqueKeysVerified = new AtomicLong(); /** * Default maximum number of read errors to tolerate before shutting down all * readers. */ public static final int DEFAULT_MAX_ERRORS = 10; /** * Default "window" size between the last key written by the writer and the * key that we attempt to read. The lower this number, the stricter our * testing is. If this is zero, we always attempt to read the highest key * in the contiguous sequence of keys written by the writers. */ public static final int DEFAULT_KEY_WINDOW = 0; /** * Default batch size for multigets */ public static final int DEFAULT_BATCH_SIZE = 1; //translates to simple GET (no multi GET) protected AtomicLong numKeysVerified = new AtomicLong(0); protected AtomicLong numReadErrors = new AtomicLong(0); protected AtomicLong numReadFailures = new AtomicLong(0); protected AtomicLong nullResult = new AtomicLong(0); private int maxErrors = DEFAULT_MAX_ERRORS; private int keyWindow = DEFAULT_KEY_WINDOW; private int batchSize = DEFAULT_BATCH_SIZE; public MultiThreadedReader(LoadTestDataGenerator dataGen, Configuration conf, TableName tableName, double verifyPercent) { super(dataGen, conf, tableName, "R"); this.verifyPercent = verifyPercent; } public void linkToWriter(MultiThreadedWriterBase writer) { this.writer = writer; writer.setTrackWroteKeys(true); } public void setMaxErrors(int maxErrors) { this.maxErrors = maxErrors; } public void setKeyWindow(int keyWindow) { this.keyWindow = keyWindow; } public void setMultiGetBatchSize(int batchSize) { this.batchSize = batchSize; } @Override public void start(long startKey, long endKey, int numThreads) throws IOException { super.start(startKey, endKey, numThreads); if (verbose) { LOG.debug("Reading keys [" + startKey + ", " + endKey + ")"); } addReaderThreads(numThreads); startThreads(readers); } protected void addReaderThreads(int numThreads) throws IOException { for (int i = 0; i < numThreads; ++i) { HBaseReaderThread reader = createReaderThread(i); readers.add(reader); } } protected HBaseReaderThread createReaderThread(int readerId) throws IOException { return new HBaseReaderThread(readerId); } public class HBaseReaderThread extends Thread { protected final int readerId; protected final HTable table; /** The "current" key being read. Increases from startKey to endKey. */ private long curKey; /** Time when the thread started */ protected long startTimeMs; /** If we are ahead of the writer and reading a random key. */ private boolean readingRandomKey; private boolean printExceptionTrace = true; /** * @param readerId only the keys with this remainder from division by * {@link #numThreads} will be read by this thread */ public HBaseReaderThread(int readerId) throws IOException { this.readerId = readerId; table = createTable(); setName(getClass().getSimpleName() + "_" + readerId); } protected HTable createTable() throws IOException { return new HTable(conf, tableName); } @Override public void run() { try { runReader(); } finally { closeTable(); numThreadsWorking.decrementAndGet(); } } protected void closeTable() { try { if (table != null) { table.close(); } } catch (IOException e) { LOG.error("Error closing table", e); } } private void runReader() { if (verbose) { LOG.info("Started thread #" + readerId + " for reads..."); } startTimeMs = System.currentTimeMillis(); curKey = startKey; long [] keysForThisReader = new long[batchSize]; int readingRandomKeyStartIndex = -1; while (curKey < endKey && !aborted) { int numKeys = 0; // if multiGet, loop until we have the number of keys equal to the batch size do { long k = getNextKeyToRead(); if (k < startKey || k >= endKey) { numReadErrors.incrementAndGet(); throw new AssertionError("Load tester logic error: proposed key " + "to read " + k + " is out of range (startKey=" + startKey + ", endKey=" + endKey + ")"); } if (k % numThreads != readerId || writer != null && writer.failedToWriteKey(k)) { // Skip keys that this thread should not read, as well as the keys // that we know the writer failed to write. continue; } keysForThisReader[numKeys] = k; if (readingRandomKey && readingRandomKeyStartIndex == -1) { //store the first index of a random read readingRandomKeyStartIndex = numKeys; } numKeys++; } while (numKeys < batchSize); if (numKeys > 1) { //meaning there is some key to read readKey(keysForThisReader); // We have verified some unique key(s). numUniqueKeysVerified.getAndAdd(readingRandomKeyStartIndex == -1 ? numKeys : readingRandomKeyStartIndex); } } } /** * Should only be used for the concurrent writer/reader workload. The * maximum key we are allowed to read, subject to the "key window" * constraint. */ private long maxKeyWeCanRead() { long insertedUpToKey = writer.wroteUpToKey(); if (insertedUpToKey >= endKey - 1) { // The writer has finished writing our range, so we can read any // key in the range. return endKey - 1; } return Math.min(endKey - 1, writer.wroteUpToKey() - keyWindow); } protected long getNextKeyToRead() { readingRandomKey = false; if (writer == null || curKey <= maxKeyWeCanRead()) { return curKey++; } // We caught up with the writer. See if we can read any keys at all. long maxKeyToRead; while ((maxKeyToRead = maxKeyWeCanRead()) < startKey) { // The writer has not written sufficient keys for us to be able to read // anything at all. Sleep a bit. This should only happen in the // beginning of a load test run. Threads.sleepWithoutInterrupt(50); } if (curKey <= maxKeyToRead) { // The writer wrote some keys, and we are now allowed to read our // current key. return curKey++; } // startKey <= maxKeyToRead <= curKey - 1. Read one of the previous keys. // Don't increment the current key -- we still have to try reading it // later. Set a flag to make sure that we don't count this key towards // the set of unique keys we have verified. readingRandomKey = true; return startKey + Math.abs(RandomUtils.nextLong()) % (maxKeyToRead - startKey + 1); } private Get[] readKey(long[] keysToRead) { Get [] gets = new Get[keysToRead.length]; int i = 0; for (long keyToRead : keysToRead) { try { gets[i] = createGet(keyToRead); if (keysToRead.length == 1) { queryKey(gets[i], RandomUtils.nextInt(100) < verifyPercent, keyToRead); } i++; } catch (IOException e) { numReadFailures.addAndGet(1); LOG.debug("[" + readerId + "] FAILED read, key = " + (keyToRead + "") + ", time from start: " + (System.currentTimeMillis() - startTimeMs) + " ms"); if (printExceptionTrace) { LOG.warn(e); printExceptionTrace = false; } } } if (keysToRead.length > 1) { try { queryKey(gets, RandomUtils.nextInt(100) < verifyPercent, keysToRead); } catch (IOException e) { numReadFailures.addAndGet(gets.length); for (long keyToRead : keysToRead) { LOG.debug("[" + readerId + "] FAILED read, key = " + (keyToRead + "") + ", time from start: " + (System.currentTimeMillis() - startTimeMs) + " ms"); } if (printExceptionTrace) { LOG.warn(e); printExceptionTrace = false; } } } return gets; } protected Get createGet(long keyToRead) throws IOException { Get get = new Get(dataGenerator.getDeterministicUniqueKey(keyToRead)); String cfsString = ""; byte[][] columnFamilies = dataGenerator.getColumnFamilies(); for (byte[] cf : columnFamilies) { get.addFamily(cf); if (verbose) { if (cfsString.length() > 0) { cfsString += ", "; } cfsString += "[" + Bytes.toStringBinary(cf) + "]"; } } get = dataGenerator.beforeGet(keyToRead, get); if (verbose) { LOG.info("[" + readerId + "] " + "Querying key " + keyToRead + ", cfs " + cfsString); } return get; } public void queryKey(Get[] gets, boolean verify, long[] keysToRead) throws IOException { // read the data long start = System.nanoTime(); // Uses multi/batch gets Result[] results = table.get(Arrays.asList(gets)); long end = System.nanoTime(); verifyResultsAndUpdateMetrics(verify, gets, end - start, results, table, false); } public void queryKey(Get get, boolean verify, long keyToRead) throws IOException { // read the data long start = System.nanoTime(); // Uses simple get Result result = table.get(get); long end = System.nanoTime(); verifyResultsAndUpdateMetrics(verify, get, end - start, result, table, false); } protected void verifyResultsAndUpdateMetrics(boolean verify, Get[] gets, long elapsedNano, Result[] results, HTable table, boolean isNullExpected) throws IOException { totalOpTimeMs.addAndGet(elapsedNano / 1000000); numKeys.addAndGet(gets.length); int i = 0; for (Result result : results) { verifyResultsAndUpdateMetricsOnAPerGetBasis(verify, gets[i++], result, table, isNullExpected); } } protected void verifyResultsAndUpdateMetrics(boolean verify, Get get, long elapsedNano, Result result, HTable table, boolean isNullExpected) throws IOException { verifyResultsAndUpdateMetrics(verify, new Get[]{get}, elapsedNano, new Result[]{result}, table, isNullExpected); } private void verifyResultsAndUpdateMetricsOnAPerGetBasis(boolean verify, Get get, Result result, HTable table, boolean isNullExpected) throws IOException { if (!result.isEmpty()) { if (verify) { numKeysVerified.incrementAndGet(); } } else { HRegionLocation hloc = table.getRegionLocation(get.getRow()); String rowKey = Bytes.toString(get.getRow()); LOG.info("Key = " + rowKey + ", RegionServer: " + hloc.getHostname()); if(isNullExpected) { nullResult.incrementAndGet(); LOG.debug("Null result obtained for the key ="+rowKey); return; } } boolean isOk = verifyResultAgainstDataGenerator(result, verify, false); long numErrorsAfterThis = 0; if (isOk) { long cols = 0; // Count the columns for reporting purposes. for (byte[] cf : result.getMap().keySet()) { cols += result.getFamilyMap(cf).size(); } numCols.addAndGet(cols); } else { if (writer != null) { LOG.error("At the time of failure, writer wrote " + writer.numKeys.get() + " keys"); } numErrorsAfterThis = numReadErrors.incrementAndGet(); } if (numErrorsAfterThis > maxErrors) { LOG.error("Aborting readers -- found more than " + maxErrors + " errors"); aborted = true; } } } public long getNumReadFailures() { return numReadFailures.get(); } public long getNumReadErrors() { return numReadErrors.get(); } public long getNumKeysVerified() { return numKeysVerified.get(); } public long getNumUniqueKeysVerified() { return numUniqueKeysVerified.get(); } public long getNullResultsCount() { return nullResult.get(); } @Override protected String progressInfo() { StringBuilder sb = new StringBuilder(); appendToStatus(sb, "verified", numKeysVerified.get()); appendToStatus(sb, "READ FAILURES", numReadFailures.get()); appendToStatus(sb, "READ ERRORS", numReadErrors.get()); appendToStatus(sb, "NULL RESULT", nullResult.get()); return sb.toString(); } }
HBASE-10616. Addendum that fixes the case of multiget_batchsize == 1 git-svn-id: 5353167ba0f92ab62ee9bfcb6d1de88aeef09424@1577438 13f79535-47bb-0310-9956-ffa450edef68
hbase-server/src/test/java/org/apache/hadoop/hbase/util/MultiThreadedReader.java
HBASE-10616. Addendum that fixes the case of multiget_batchsize == 1
<ide><path>base-server/src/test/java/org/apache/hadoop/hbase/util/MultiThreadedReader.java <ide> numKeys++; <ide> } while (numKeys < batchSize); <ide> <del> if (numKeys > 1) { //meaning there is some key to read <add> if (numKeys > 0) { //meaning there is some key to read <ide> readKey(keysForThisReader); <ide> // We have verified some unique key(s). <ide> numUniqueKeysVerified.getAndAdd(readingRandomKeyStartIndex == -1 ?
JavaScript
apache-2.0
eacd15082555e44fde87543b41827f8fe16401dd
0
mcanthony/ares-project,mcanthony/ares-project,mcanthony/ares-project,enyojs/ares-project,enyojs/ares-project,mcanthony/ares-project,enyojs/ares-project,mcanthony/ares-project,enyojs/ares-project,enyojs/ares-project,mcanthony/ares-project
/*global Ares, ares, async, ProjectConfig, ServiceRegistry */ enyo.kind({ name: "ProjectWizardCreate", kind: "onyx.Popup", modal: true, centered: true, floating: true, autoDismiss: false, classes: "enyo-unselectable", events: { onAddProjectInList: "", onShowWaitPopup: "", onHideWaitPopup: "" }, handlers: { onFileChosen: "prepareShowProjectPropPopup", onModifiedConfig: "createProject" , // can be canceled by either of the included components onDone: "hideMe" }, components: [ {kind: "ProjectProperties", name: "propertiesWidget", onApplyAddSource: "notifyChangeSource"}, {kind: "Ares.FileChooser", canGenerate: false, name: "selectDirectoryPopup", classes:"ares-masked-content-popup", folderChooser: true, allowCreateFolder: true}, {kind: "Ares.ErrorPopup", name: "errorPopup", msg: $L("unknown error")} ], debug: false, projectName: "", create: function() { ares.setupTraceLogger(this); // Setup this.trace() function according to this.debug value this.inherited(arguments); }, /** * start project creation by showing direction selection widget */ start: function() { var dirPopup = this.$.selectDirectoryPopup ; this.trace("starting") ; this.show(); this.config = new ProjectConfig() ; // is a ProjectConfig object. dirPopup.$.header.setContent("Select a directory containing the new project") ; dirPopup.show(); }, // Step 2: once the directory is selected by user, show the project properties popup // Bail out if a project.json file already exists prepareShowProjectPropPopup: function(inSender, inEvent) { this.trace("sender:", inSender, ", event:", inEvent); if (!inEvent.file) { this.hideMe(); return; } var propW = this.$.propertiesWidget; this.selectedDir = inEvent.file; propW.setupCreate(); propW.setTemplateList([]); // Reset template list // Pre-fill project properties widget propW.preFill(ProjectConfig.PREFILLED_CONFIG_FOR_UI), propW.$.projectDirectory.setContent(this.selectedDir.path); propW.$.projectName.setValue(this.selectedDir.name); propW.activateFileChoosers(false); async.series([ this.checkProjectJson.bind(this, inSender, inEvent), this.checkGetAppinfo.bind(this, inSender, inEvent), this.getTemplates.bind(this, inSender, inEvent), this.createProjectJson.bind(this, inSender, inEvent), this.showProjectPropPopup.bind(this, inSender, inEvent) ], this.waitOk.bind(this)); }, checkProjectJson: function(inSender, inEvent, next) { // scan content for a project.json var matchFileName = function(node){ return (node.content === 'project.json' ) ; }; var hft = this.$.selectDirectoryPopup.$.hermesFileTree ; var topNode = hft.$.serverNode ; var matchingNodes = topNode.getNodeFiles(hft.selectedNode).filter(matchFileName) ; if (matchingNodes.length !== 0) { this.hide(); var msg = $L("Cannot create project: a project.json file already exists"); this.$.errorPopup.raise(msg); next({handled: true, msg: msg}); } else { next(); } }, checkGetAppinfo: function(inSender, inEvent, next) { var propW = this.$.propertiesWidget; // scan content for an appinfo.json var matchFileName = function(node){ return (node.content === 'appinfo.json' ) ; }; var hft = this.$.selectDirectoryPopup.$.hermesFileTree ; var topNode = hft.$.serverNode ; var matchingNodes = topNode.getNodeFiles(hft.selectedNode).filter( matchFileName ) ; if (matchingNodes.length === 1) { this.warn("There is an appinfo.json", matchingNodes); var appinfoReq = this.selectedDir.service.getFile(matchingNodes[0].file.id); appinfoReq.response(this, function(inSender, fileStuff) { var info; try { info = JSON.parse(fileStuff.content); } catch(err) { this.hide(); this.warn( "Unable to parse appinfo.json >>", fileStuff.content, "<<"); var msg = this.$LS("Unable to parse appinfo.json: {error}", {error: err.toString()}); this.$.errorPopup.raise(msg); next({handled: true, msg: msg}); return; } var conf = {}; conf.id = info.id; conf.version = info.version; conf.title = info.title; propW.update(conf); next(); }); appinfoReq.error(this, function(inSender, fileStuff) { // Strange: network error, ... ? this.hide(); var msg = $L("Unable to retrieve appinfo.json"); this.$.errorPopup.raise(msg); next({handled: true, msg: msg}); }); } else { // No appinfo.json found. Or more that one which should be a bug next(); // Just continue } }, /** * @public */ getTemplates: function(inSender, inEvent, next) { return this.getSources('template', next); }, /** * @public */ getSources: function(type, next) { var propW = this.$.propertiesWidget; // Getting template list var service = ServiceRegistry.instance.getServicesByType('generate')[0]; if (service) { var templateReq = service.getSources('template'); templateReq.response(this, function(inSender, inTemplates) { propW.setTemplateList(inTemplates); next(); // Should we return immediately without waiting the answer ? }); templateReq.error(this, function(inSender, inError) { this.warn("Unable to get template list (", inError, ")"); this.$.errorPopup.raise($L("Unable to get template list")); propW.setTemplateList([]); next(); }); } else { this.warn("Unable to get template list (No service defined)"); this.$.errorPopup.raise($L("Unable to get template list (No service defined)")); propW.setTemplateList([]); next(); } }, createProjectJson: function(inSender, inEvent, next) { this.config.init({ folderId: this.selectedDir.id, service: this.selectedDir.service }, function(err) { if (err) { this.$.errorPopup.raise(err.toString()); var testCallBack = inEvent.testCallBack; if (testCallBack) { testCallBack(); } next({handled: true, msg: err.toString()}); } else { next(); } }.bind(this)); }, showProjectPropPopup: function(inSender, inEvent, next) { var testCallBack = inEvent.testCallBack; // once project.json is created, setup and show project properties widget this.$.selectDirectoryPopup.hide(); this.$.propertiesWidget.show() ; if (testCallBack) { testCallBack(); } next(); }, waitOk:function(err, results) { if (err) { var showError = true; if (err.handled && (err.handled === true)) { showError = false; } if (showError) { this.$.selectDirectoryPopup.hide(); this.hideMe(); this.warn("An error occured: ", err); this.$.errorPopup.raise(err.msg); } } // Else: nothing to do }, // step 3: actually create project in ares data structure createProject: function (inSender, inEvent, next) { this.projectName = inEvent.data.name; var folderId = this.selectedDir.id ; var template = inEvent.template; this.warn("Creating new project ", name, " in folderId=", folderId, " (template: ", template, ")"); this.config.setData(inEvent.data) ; this.config.save() ; if (template) { this.instanciateTemplate(inEvent); } else { var service = this.selectedDir.service; service.createFile(folderId, "package.js", "enyo.depends(\n);\n") .response(this, function(inRequest, inFsNode) { this.trace("package.js inFsNode[0]:", inFsNode[0]); this.projectReady(null, inEvent); }) .error(this, function(inRequest, inError) { this.warn("inRequest:", inRequest, "inError:", inError); }); } return true ; // stop bubble }, $LS: function(msg, params) { var tmp = new enyo.g11n.Template($L(msg)); return tmp.evaluate(params); }, // step 4: populate the project with the selected template instanciateTemplate: function (inEvent) { var sources = []; var template = inEvent.template; var addSources = inEvent.addSources || []; this.doShowWaitPopup({msg: this.$LS("Creating project from #{template}", {template: template})}); var substitutions = [{ fileRegexp: "appinfo.json", json: { id: inEvent.data.id, version: inEvent.data.version, title: inEvent.data.title } }]; var genService = ServiceRegistry.instance.getServicesByType('generate')[0]; sources.push(template); addSources.forEach(function(source) { sources.push(source); }); var req = genService.generate({ sourceIds: sources, substitutions: substitutions }); req.response(this, this.populateProject); req.error(this, function(inSender, inError) { this.warn("Unable to get the template files (", inError, ")"); this.$.errorPopup.raise($L("Unable to instanciate projet content from the template")); this.doHideWaitPopup(); }); }, // step 5: populate the project with the retrieved template files populateProject: function(inSender, inData) { var folderId = this.selectedDir.id; var service = this.selectedDir.service; // Copy the template files into the new project var req = service.createFiles(folderId, {content: inData.content, ctype: inData.ctype}); req.response(this, this.projectReady); req.error(this, function(inEvent, inError) { this.$.errorPopup.raise($L("Unable to create projet content from the template")); this.doHideWaitPopup(); }); }, // step 6: we're done projectReady: function(inSender, inData) { this.doAddProjectInList({ name: this.projectName, folderId: this.selectedDir.id, service: this.selectedDir.service }); }, /** * Hide the whole widget. Typically called when ok or cancel is clicked */ hideMe: function() { this.config = null ; // forget ProjectConfig object this.hide() ; return true; }, notifyChangeSource: function(inSender, inEvent) { this.waterfallDown("onAdditionalSource", inEvent, inSender); return true; } }); /** * This kind handles the project modifications treatment (extracted from ProjectView) */ enyo.kind({ name: "ProjectWizardModify", kind: "onyx.Popup", modal: true, centered: true, floating: true, autoDismiss: false, events: { onProjectSelected: "" }, handlers: { onDone: "hide", onModifiedConfig: "saveProjectConfig", onModifiedSource: "populateProject", onSelectFile: "selectFile", onCheckPath: "checkPath", onPathChecked: "pathChecked" }, classes:"ares-masked-content-popup", components: [ {kind: "ProjectProperties", name: "propertiesWidget", onApplyAddSource: "notifyChangeSource", onFileChoosersChecked: "fileChoosersChecked"}, {name: "selectFilePopup", kind: "Ares.FileChooser", classes:"ares-masked-content-popup", showing: false, folderChooser: false, onFileChosen: "selectFileChosen"} ], debug: false, targetProject: null, chooser: null, checker: null, create: function() { ares.setupTraceLogger(this); // Setup this.trace() function according to this.debug value this.inherited(arguments); }, /** * Step 1: start the modification by showing project properties widget */ start: function(target) { if (target) { var config = target.getConfig(); this.targetProject = target ; this.$.propertiesWidget.setupModif() ; this.$.propertiesWidget.preFill(config.data); this.$.propertiesWidget.activateFileChoosers(true); var show = (function () { this.show(); }).bind(this); this.$.propertiesWidget.checkFileChoosers(show); } }, // step 2: saveProjectConfig: function(inSender, inEvent) { this.trace("saving project config"); if (! this.targetProject) { this.warn("internal error: saveProjectConfig was called without a target project.") ; return true ; // stop bubble } // Save the data to project.json var config = this.targetProject.getConfig(); config.setData(inEvent.data); config.save(); // selected project name was modified if (inEvent.data.name !== this.targetProject.getName()) { // project name has changed, update project model list var oldName = this.targetProject.getName(); Ares.Workspace.projects.renameProject(oldName, inEvent.data.name); } return true ; // stop bubble }, /** @private */ selectFile: function(inSender, inData) { this.trace(inSender, "=>", inData); this.chooser = inData.input; this.$.selectFilePopup.reset(); this.$.selectFilePopup.connectProject(this.targetProject, (function() { this.$.selectFilePopup.setHeaderText(inData.header); this.$.selectFilePopup.pointSelectedName(inData.value, inData.status); this.$.selectFilePopup.show(); }).bind(this)); return true; }, /** @private */ selectFileChosen: function(inSender, inEvent) { this.trace(inSender, "=>", inEvent); var chooser = this.chooser; this.chooser = null; if (!inEvent.file) { // no file or folder chosen return true; } this.$.propertiesWidget.updateFileInput(chooser, inEvent.name); return true; }, notifyChangeSource: function(inSender, inEvent) { this.waterfallDown("onAdditionalSource", inEvent, inSender); return true; }, populateProject: function(inSender, inData) { var selectedDir = this.targetProject.getConfig(); var folderId = selectedDir.folderId; var service = selectedDir.service; // Copy the template files into the new project var req = service.createFiles(folderId, {content: inData.content, ctype: inData.ctype}); req.response(this, this.projectRefresh); req.error(this, function(inEvent, inError) { this.$.errorPopup.raise($L("Unable to create projet content from the template")); this.doHideWaitPopup(); }); return true; }, projectRefresh: function(inSender, inData) { this.doProjectSelected({ project: this.targetProject }); this.hideMe(); }, /** * Hide the whole widget. Typically called when ok or cancel is clicked */ hideMe: function() { this.config = null ; // forget ProjectConfig object this.hide() ; return true; }, /** @private */ checkPath: function (inSender, inData) { this.trace(inSender, "=>", inData); this.checker = inData.input; // FIXME ENYO-2761: this is a workaround that shows the developer that the path is not // valid because it doesn't begin with an "/". if (inData.value.indexOf("/") !== 0) { this.pathChecked(inSender, {status: false}); return true; } this.$.selectFilePopup.connectProject(this.targetProject, (function() { this.$.selectFilePopup.checkSelectedName(inData.value); }).bind(this)); }, /** @private */ pathChecked: function (inSender, inData) { this.trace(inSender, "=>", inData); this.$.selectFilePopup.reset(); this.$.propertiesWidget.updatePathCheck(this.checker, inData.status); this.checker = null; }, /** @private */ fileChoosersChecked: function (inSender, inEvent) { this.trace(inSender, "=>", inEvent); this.show(); return true; } }); /** * This kind will scan a directory. It will create a new project for each project.json found. */ enyo.kind({ name: "ProjectWizardScan", kind: "Ares.FileChooser", modal: true, centered: true, floating: true, autoDismiss: false, classes: "enyo-unselectable", events: { onAddProjectInList: "" }, handlers: { onFileChosen: "searchProjects" }, debug: false, create: function() { ares.setupTraceLogger(this); // Setup this.trace() function according to this.debug value this.inherited(arguments); }, importProject: function(service, parentDir, child) { this.trace('opening project.json from ', parentDir.name ) ; service.getFile( child.id ). response(this, function(inSender, fileStuff) { var projectData={}; this.trace( "file contents: '", fileStuff.content, "'" ) ; try { projectData = JSON.parse(fileStuff.content) ; } catch(e) { this.warn("Error parsing project data: ", e.toString()); } this.trace('Imported project ', projectData.name, " from ", parentDir.id) ; this.doAddProjectInList({ name: projectData.name || parentDir.name, folderId: parentDir.id, service: this.selectedFile.service }); }); }, searchProjects: function (inSender, inEvent) { if (!inEvent.file) { this.hide(); return; } var service = inEvent.file.service; var hft = this.$.hermesFileTree ; // we cannot use directly listFiles as this method sends a list of unrelated files // we need to use the file tree to be able to relate a project.json with is parent dir. var topDir = hft.selectedNode.file ; // construct an (kind of) iterator that will scan all directory of the // HFT and look for project.json var toScan = [ [ null , topDir ] ] ; // list of parent_dir , child // var this = this ; var iter, inIter ; inIter = function() { var item = toScan.shift() ; var child = item[1]; this.trace('search iteration on ', child.name, ' isDir ', child.isDir ) ; service.listFiles(child.id) .response(this, function(inSender, inFiles) { var toPush = [] ; var foundProject = false ; enyo.forEach(inFiles, function(v) { if ( v.name === 'project.json' ) { foundProject = true ; this.importProject(service, child, v) ; } else if ( v.isDir === true ) { this.trace('pushing ', v.name, " from ", child.id) ; toPush.push([child,v]); } // else skip plain file }, this) ; if (! foundProject ) { // black magic required to push the entire array toScan.push.apply(toScan, toPush); } iter.apply(this) ; } ) ; } ; iter = function() { while (toScan.length > 0) { inIter.apply(this) ; } } ; iter.apply(this) ; // do not forget to launch the whole stuff this.hide(); } }); enyo.kind({ name: "ProjectWizardCopy", kind: "onyx.Popup", modal: true, centered: true, floating: true, autoDismiss: false, handlers: { onDone: "hide", onModifiedConfig: "copyProject" }, events: { onError: "", onShowWaitPopup: "", onHideWaitPopup: "" }, components: [ {kind: "ProjectProperties", name: "propertiesWidget"} ], debug: false, targetProject: null, create: function() { ares.setupTraceLogger(this); // Setup this.trace() function according to this.debug value this.inherited(arguments); }, /** * Step 1: start the modification by showing project properties widget */ start: function(target) { if (target) { var data = enyo.clone(target.getConfig().data); // TODO: Verify that the project name and dir does not exist data.name = data.name + "-Copy"; this.targetProject = target; this.$.propertiesWidget.setupModif() ; this.$.propertiesWidget.preFill(data); this.$.propertiesWidget.activateFileChoosers(false); this.show(); } }, // step 2: copyProject: function(inSender, inEvent) { this.trace("Copying project", this.targetProject.getConfig().data.name); this.doShowWaitPopup({msg: "Duplicating project"}); var service = this.targetProject.getService(); var folderId = this.targetProject.getFolderId(); this.newConfigData = inEvent.data; var destination = inEvent.data.name; var known = Ares.Workspace.projects.get(destination); if (known) { this.doError({msg: this.$LS("Unable to duplicate the project, the project '{destination}' already exists", {destination: destination})}); return true ; // stop bubble } var req = service.copy(folderId, destination); req.response(this, this.saveProjectJson); req.error(this, function(inSender, status) { var msg = $L("Unable to duplicate the project"); if (status === 412 /*Precondition-Failed*/) { this.warn("Unable to duplicate the project, directory '", destination, "' already exists", status); msg = this.$LS("Unable to duplicate the project, directory '{destination}' already exists", {destination: destination}); } else { this.warn("Unable to duplicate the project", status); } this.doError({msg: msg}); }); return true ; // stop bubble }, saveProjectJson: function(inSender, inData) { this.trace(inData); var folderId = inData.id; this.newFolderId = folderId; var service = this.targetProject.getService(); var fileId; enyo.forEach(inData.children, function(entry) { if (entry.name === "project.json") { fileId = entry.id; } }); if (! fileId) { this.warn("Unable to duplicate the project, no 'project.json' found", inData); this.doError({msg: $L("Unable to duplicate the project, no 'project.json' found")}); return; } var req = service.putFile(fileId, JSON.stringify(this.newConfigData, null, 2)); req.response(this, this.createProjectEntry); req.error(this, function(inSender, inError) { this.warn("Unable to duplicate the project, unable to update 'project.json'", inError); this.doError({msg: $L("Unable to duplicate the project, unable to update 'project.json'")}); }); }, createProjectEntry: function(inSender, inData) { this.trace(inData); var serviceId = this.targetProject.getServiceId(); // Create the project entry in the project list Ares.Workspace.projects.createProject(this.newConfigData.name, this.newFolderId, serviceId); this.doHideWaitPopup(); }, $LS: function(msg, params) { var tmp = new enyo.g11n.Template($L(msg)); return tmp.evaluate(params); } });
project-view/source/ProjectWizard.js
/*global Ares, ares, async, ProjectConfig, ServiceRegistry */ enyo.kind({ name: "ProjectWizardCreate", kind: "onyx.Popup", modal: true, centered: true, floating: true, autoDismiss: false, classes: "enyo-unselectable", events: { onAddProjectInList: "", onShowWaitPopup: "", onHideWaitPopup: "" }, handlers: { onFileChosen: "prepareShowProjectPropPopup", onModifiedConfig: "createProject" , // can be canceled by either of the included components onDone: "hideMe" }, components: [ {kind: "ProjectProperties", name: "propertiesWidget", onApplyAddSource: "notifyChangeSource"}, {kind: "Ares.FileChooser", canGenerate: false, name: "selectDirectoryPopup", classes:"ares-masked-content-popup", folderChooser: true}, {kind: "Ares.ErrorPopup", name: "errorPopup", msg: $L("unknown error")} ], debug: false, projectName: "", create: function() { ares.setupTraceLogger(this); // Setup this.trace() function according to this.debug value this.inherited(arguments); }, /** * start project creation by showing direction selection widget */ start: function() { var dirPopup = this.$.selectDirectoryPopup ; this.trace("starting") ; this.show(); this.config = new ProjectConfig() ; // is a ProjectConfig object. dirPopup.$.header.setContent("Select a directory containing the new project") ; dirPopup.$.hermesFileTree.showNewFolderButton(); dirPopup.show(); }, // Step 2: once the directory is selected by user, show the project properties popup // Bail out if a project.json file already exists prepareShowProjectPropPopup: function(inSender, inEvent) { this.trace("sender:", inSender, ", event:", inEvent); if (!inEvent.file) { this.hideMe(); return; } var propW = this.$.propertiesWidget; this.selectedDir = inEvent.file; propW.setupCreate(); propW.setTemplateList([]); // Reset template list // Pre-fill project properties widget propW.preFill(ProjectConfig.PREFILLED_CONFIG_FOR_UI), propW.$.projectDirectory.setContent(this.selectedDir.path); propW.$.projectName.setValue(this.selectedDir.name); propW.activateFileChoosers(false); async.series([ this.checkProjectJson.bind(this, inSender, inEvent), this.checkGetAppinfo.bind(this, inSender, inEvent), this.getTemplates.bind(this, inSender, inEvent), this.createProjectJson.bind(this, inSender, inEvent), this.showProjectPropPopup.bind(this, inSender, inEvent) ], this.waitOk.bind(this)); }, checkProjectJson: function(inSender, inEvent, next) { // scan content for a project.json var matchFileName = function(node){ return (node.content === 'project.json' ) ; }; var hft = this.$.selectDirectoryPopup.$.hermesFileTree ; var topNode = hft.$.serverNode ; var matchingNodes = topNode.getNodeFiles(hft.selectedNode).filter(matchFileName) ; if (matchingNodes.length !== 0) { this.hide(); var msg = $L("Cannot create project: a project.json file already exists"); this.$.errorPopup.raise(msg); next({handled: true, msg: msg}); } else { next(); } }, checkGetAppinfo: function(inSender, inEvent, next) { var propW = this.$.propertiesWidget; // scan content for an appinfo.json var matchFileName = function(node){ return (node.content === 'appinfo.json' ) ; }; var hft = this.$.selectDirectoryPopup.$.hermesFileTree ; var topNode = hft.$.serverNode ; var matchingNodes = topNode.getNodeFiles(hft.selectedNode).filter( matchFileName ) ; if (matchingNodes.length === 1) { this.warn("There is an appinfo.json", matchingNodes); var appinfoReq = this.selectedDir.service.getFile(matchingNodes[0].file.id); appinfoReq.response(this, function(inSender, fileStuff) { var info; try { info = JSON.parse(fileStuff.content); } catch(err) { this.hide(); this.warn( "Unable to parse appinfo.json >>", fileStuff.content, "<<"); var msg = this.$LS("Unable to parse appinfo.json: {error}", {error: err.toString()}); this.$.errorPopup.raise(msg); next({handled: true, msg: msg}); return; } var conf = {}; conf.id = info.id; conf.version = info.version; conf.title = info.title; propW.update(conf); next(); }); appinfoReq.error(this, function(inSender, fileStuff) { // Strange: network error, ... ? this.hide(); var msg = $L("Unable to retrieve appinfo.json"); this.$.errorPopup.raise(msg); next({handled: true, msg: msg}); }); } else { // No appinfo.json found. Or more that one which should be a bug next(); // Just continue } }, /** * @public */ getTemplates: function(inSender, inEvent, next) { return this.getSources('template', next); }, /** * @public */ getSources: function(type, next) { var propW = this.$.propertiesWidget; // Getting template list var service = ServiceRegistry.instance.getServicesByType('generate')[0]; if (service) { var templateReq = service.getSources('template'); templateReq.response(this, function(inSender, inTemplates) { propW.setTemplateList(inTemplates); next(); // Should we return immediately without waiting the answer ? }); templateReq.error(this, function(inSender, inError) { this.warn("Unable to get template list (", inError, ")"); this.$.errorPopup.raise($L("Unable to get template list")); propW.setTemplateList([]); next(); }); } else { this.warn("Unable to get template list (No service defined)"); this.$.errorPopup.raise($L("Unable to get template list (No service defined)")); propW.setTemplateList([]); next(); } }, createProjectJson: function(inSender, inEvent, next) { this.config.init({ folderId: this.selectedDir.id, service: this.selectedDir.service }, function(err) { if (err) { this.$.errorPopup.raise(err.toString()); var testCallBack = inEvent.testCallBack; if (testCallBack) { testCallBack(); } next({handled: true, msg: err.toString()}); } else { next(); } }.bind(this)); }, showProjectPropPopup: function(inSender, inEvent, next) { var testCallBack = inEvent.testCallBack; // once project.json is created, setup and show project properties widget this.$.selectDirectoryPopup.hide(); this.$.propertiesWidget.show() ; if (testCallBack) { testCallBack(); } next(); }, waitOk:function(err, results) { if (err) { var showError = true; if (err.handled && (err.handled === true)) { showError = false; } if (showError) { this.$.selectDirectoryPopup.hide(); this.hideMe(); this.warn("An error occured: ", err); this.$.errorPopup.raise(err.msg); } } // Else: nothing to do }, // step 3: actually create project in ares data structure createProject: function (inSender, inEvent, next) { this.projectName = inEvent.data.name; var folderId = this.selectedDir.id ; var template = inEvent.template; this.warn("Creating new project ", name, " in folderId=", folderId, " (template: ", template, ")"); this.config.setData(inEvent.data) ; this.config.save() ; if (template) { this.instanciateTemplate(inEvent); } else { var service = this.selectedDir.service; service.createFile(folderId, "package.js", "enyo.depends(\n);\n") .response(this, function(inRequest, inFsNode) { this.trace("package.js inFsNode[0]:", inFsNode[0]); this.projectReady(null, inEvent); }) .error(this, function(inRequest, inError) { this.warn("inRequest:", inRequest, "inError:", inError); }); } return true ; // stop bubble }, $LS: function(msg, params) { var tmp = new enyo.g11n.Template($L(msg)); return tmp.evaluate(params); }, // step 4: populate the project with the selected template instanciateTemplate: function (inEvent) { var sources = []; var template = inEvent.template; var addSources = inEvent.addSources || []; this.doShowWaitPopup({msg: this.$LS("Creating project from #{template}", {template: template})}); var substitutions = [{ fileRegexp: "appinfo.json", json: { id: inEvent.data.id, version: inEvent.data.version, title: inEvent.data.title } }]; var genService = ServiceRegistry.instance.getServicesByType('generate')[0]; sources.push(template); addSources.forEach(function(source) { sources.push(source); }); var req = genService.generate({ sourceIds: sources, substitutions: substitutions }); req.response(this, this.populateProject); req.error(this, function(inSender, inError) { this.warn("Unable to get the template files (", inError, ")"); this.$.errorPopup.raise($L("Unable to instanciate projet content from the template")); this.doHideWaitPopup(); }); }, // step 5: populate the project with the retrieved template files populateProject: function(inSender, inData) { var folderId = this.selectedDir.id; var service = this.selectedDir.service; // Copy the template files into the new project var req = service.createFiles(folderId, {content: inData.content, ctype: inData.ctype}); req.response(this, this.projectReady); req.error(this, function(inEvent, inError) { this.$.errorPopup.raise($L("Unable to create projet content from the template")); this.doHideWaitPopup(); }); }, // step 6: we're done projectReady: function(inSender, inData) { this.doAddProjectInList({ name: this.projectName, folderId: this.selectedDir.id, service: this.selectedDir.service }); }, /** * Hide the whole widget. Typically called when ok or cancel is clicked */ hideMe: function() { this.config = null ; // forget ProjectConfig object this.hide() ; return true; }, notifyChangeSource: function(inSender, inEvent) { this.waterfallDown("onAdditionalSource", inEvent, inSender); return true; } }); /** * This kind handles the project modifications treatment (extracted from ProjectView) */ enyo.kind({ name: "ProjectWizardModify", kind: "onyx.Popup", modal: true, centered: true, floating: true, autoDismiss: false, events: { onProjectSelected: "" }, handlers: { onDone: "hide", onModifiedConfig: "saveProjectConfig", onModifiedSource: "populateProject", onSelectFile: "selectFile", onCheckPath: "checkPath", onPathChecked: "pathChecked" }, classes:"ares-masked-content-popup", components: [ {kind: "ProjectProperties", name: "propertiesWidget", onApplyAddSource: "notifyChangeSource", onFileChoosersChecked: "fileChoosersChecked"}, {name: "selectFilePopup", kind: "Ares.FileChooser", classes:"ares-masked-content-popup", showing: false, folderChooser: false, onFileChosen: "selectFileChosen"} ], debug: false, targetProject: null, chooser: null, checker: null, create: function() { ares.setupTraceLogger(this); // Setup this.trace() function according to this.debug value this.inherited(arguments); }, /** * Step 1: start the modification by showing project properties widget */ start: function(target) { if (target) { var config = target.getConfig(); this.targetProject = target ; this.$.propertiesWidget.setupModif() ; this.$.propertiesWidget.preFill(config.data); this.$.propertiesWidget.activateFileChoosers(true); var show = (function () { this.show(); }).bind(this); this.$.propertiesWidget.checkFileChoosers(show); } }, // step 2: saveProjectConfig: function(inSender, inEvent) { this.trace("saving project config"); if (! this.targetProject) { this.warn("internal error: saveProjectConfig was called without a target project.") ; return true ; // stop bubble } // Save the data to project.json var config = this.targetProject.getConfig(); config.setData(inEvent.data); config.save(); // selected project name was modified if (inEvent.data.name !== this.targetProject.getName()) { // project name has changed, update project model list var oldName = this.targetProject.getName(); Ares.Workspace.projects.renameProject(oldName, inEvent.data.name); } return true ; // stop bubble }, /** @private */ selectFile: function(inSender, inData) { this.trace(inSender, "=>", inData); this.chooser = inData.input; this.$.selectFilePopup.reset(); this.$.selectFilePopup.connectProject(this.targetProject, (function() { this.$.selectFilePopup.setHeaderText(inData.header); this.$.selectFilePopup.pointSelectedName(inData.value, inData.status); this.$.selectFilePopup.show(); }).bind(this)); return true; }, /** @private */ selectFileChosen: function(inSender, inEvent) { this.trace(inSender, "=>", inEvent); var chooser = this.chooser; this.chooser = null; if (!inEvent.file) { // no file or folder chosen return true; } this.$.propertiesWidget.updateFileInput(chooser, inEvent.name); return true; }, notifyChangeSource: function(inSender, inEvent) { this.waterfallDown("onAdditionalSource", inEvent, inSender); return true; }, populateProject: function(inSender, inData) { var selectedDir = this.targetProject.getConfig(); var folderId = selectedDir.folderId; var service = selectedDir.service; // Copy the template files into the new project var req = service.createFiles(folderId, {content: inData.content, ctype: inData.ctype}); req.response(this, this.projectRefresh); req.error(this, function(inEvent, inError) { this.$.errorPopup.raise($L("Unable to create projet content from the template")); this.doHideWaitPopup(); }); return true; }, projectRefresh: function(inSender, inData) { this.doProjectSelected({ project: this.targetProject }); this.hideMe(); }, /** * Hide the whole widget. Typically called when ok or cancel is clicked */ hideMe: function() { this.config = null ; // forget ProjectConfig object this.hide() ; return true; }, /** @private */ checkPath: function (inSender, inData) { this.trace(inSender, "=>", inData); this.checker = inData.input; // FIXME ENYO-2761: this is a workaround that shows the developer that the path is not // valid because it doesn't begin with an "/". if (inData.value.indexOf("/") !== 0) { this.pathChecked(inSender, {status: false}); return true; } this.$.selectFilePopup.connectProject(this.targetProject, (function() { this.$.selectFilePopup.checkSelectedName(inData.value); }).bind(this)); }, /** @private */ pathChecked: function (inSender, inData) { this.trace(inSender, "=>", inData); this.$.selectFilePopup.reset(); this.$.propertiesWidget.updatePathCheck(this.checker, inData.status); this.checker = null; }, /** @private */ fileChoosersChecked: function (inSender, inEvent) { this.trace(inSender, "=>", inEvent); this.show(); return true; } }); /** * This kind will scan a directory. It will create a new project for each project.json found. */ enyo.kind({ name: "ProjectWizardScan", kind: "Ares.FileChooser", modal: true, centered: true, floating: true, autoDismiss: false, classes: "enyo-unselectable", events: { onAddProjectInList: "" }, handlers: { onFileChosen: "searchProjects" }, debug: false, create: function() { ares.setupTraceLogger(this); // Setup this.trace() function according to this.debug value this.inherited(arguments); }, importProject: function(service, parentDir, child) { this.trace('opening project.json from ', parentDir.name ) ; service.getFile( child.id ). response(this, function(inSender, fileStuff) { var projectData={}; this.trace( "file contents: '", fileStuff.content, "'" ) ; try { projectData = JSON.parse(fileStuff.content) ; } catch(e) { this.warn("Error parsing project data: ", e.toString()); } this.trace('Imported project ', projectData.name, " from ", parentDir.id) ; this.doAddProjectInList({ name: projectData.name || parentDir.name, folderId: parentDir.id, service: this.selectedFile.service }); }); }, searchProjects: function (inSender, inEvent) { if (!inEvent.file) { this.hide(); return; } var service = inEvent.file.service; var hft = this.$.hermesFileTree ; // we cannot use directly listFiles as this method sends a list of unrelated files // we need to use the file tree to be able to relate a project.json with is parent dir. var topDir = hft.selectedNode.file ; // construct an (kind of) iterator that will scan all directory of the // HFT and look for project.json var toScan = [ [ null , topDir ] ] ; // list of parent_dir , child // var this = this ; var iter, inIter ; inIter = function() { var item = toScan.shift() ; var child = item[1]; this.trace('search iteration on ', child.name, ' isDir ', child.isDir ) ; service.listFiles(child.id) .response(this, function(inSender, inFiles) { var toPush = [] ; var foundProject = false ; enyo.forEach(inFiles, function(v) { if ( v.name === 'project.json' ) { foundProject = true ; this.importProject(service, child, v) ; } else if ( v.isDir === true ) { this.trace('pushing ', v.name, " from ", child.id) ; toPush.push([child,v]); } // else skip plain file }, this) ; if (! foundProject ) { // black magic required to push the entire array toScan.push.apply(toScan, toPush); } iter.apply(this) ; } ) ; } ; iter = function() { while (toScan.length > 0) { inIter.apply(this) ; } } ; iter.apply(this) ; // do not forget to launch the whole stuff this.hide(); } }); enyo.kind({ name: "ProjectWizardCopy", kind: "onyx.Popup", modal: true, centered: true, floating: true, autoDismiss: false, handlers: { onDone: "hide", onModifiedConfig: "copyProject" }, events: { onError: "", onShowWaitPopup: "", onHideWaitPopup: "" }, components: [ {kind: "ProjectProperties", name: "propertiesWidget"} ], debug: false, targetProject: null, create: function() { ares.setupTraceLogger(this); // Setup this.trace() function according to this.debug value this.inherited(arguments); }, /** * Step 1: start the modification by showing project properties widget */ start: function(target) { if (target) { var data = enyo.clone(target.getConfig().data); // TODO: Verify that the project name and dir does not exist data.name = data.name + "-Copy"; this.targetProject = target; this.$.propertiesWidget.setupModif() ; this.$.propertiesWidget.preFill(data); this.$.propertiesWidget.activateFileChoosers(false); this.show(); } }, // step 2: copyProject: function(inSender, inEvent) { this.trace("Copying project", this.targetProject.getConfig().data.name); this.doShowWaitPopup({msg: "Duplicating project"}); var service = this.targetProject.getService(); var folderId = this.targetProject.getFolderId(); this.newConfigData = inEvent.data; var destination = inEvent.data.name; var known = Ares.Workspace.projects.get(destination); if (known) { this.doError({msg: this.$LS("Unable to duplicate the project, the project '{destination}' already exists", {destination: destination})}); return true ; // stop bubble } var req = service.copy(folderId, destination); req.response(this, this.saveProjectJson); req.error(this, function(inSender, status) { var msg = $L("Unable to duplicate the project"); if (status === 412 /*Precondition-Failed*/) { this.warn("Unable to duplicate the project, directory '", destination, "' already exists", status); msg = this.$LS("Unable to duplicate the project, directory '{destination}' already exists", {destination: destination}); } else { this.warn("Unable to duplicate the project", status); } this.doError({msg: msg}); }); return true ; // stop bubble }, saveProjectJson: function(inSender, inData) { this.trace(inData); var folderId = inData.id; this.newFolderId = folderId; var service = this.targetProject.getService(); var fileId; enyo.forEach(inData.children, function(entry) { if (entry.name === "project.json") { fileId = entry.id; } }); if (! fileId) { this.warn("Unable to duplicate the project, no 'project.json' found", inData); this.doError({msg: $L("Unable to duplicate the project, no 'project.json' found")}); return; } var req = service.putFile(fileId, JSON.stringify(this.newConfigData, null, 2)); req.response(this, this.createProjectEntry); req.error(this, function(inSender, inError) { this.warn("Unable to duplicate the project, unable to update 'project.json'", inError); this.doError({msg: $L("Unable to duplicate the project, unable to update 'project.json'")}); }); }, createProjectEntry: function(inSender, inData) { this.trace(inData); var serviceId = this.targetProject.getServiceId(); // Create the project entry in the project list Ares.Workspace.projects.createProject(this.newConfigData.name, this.newFolderId, serviceId); this.doHideWaitPopup(); }, $LS: function(msg, params) { var tmp = new enyo.g11n.Template($L(msg)); return tmp.evaluate(params); } });
ENYO-2388: Modify "Project Properties" wizard for a project creation to fit new fileChooser improvements
project-view/source/ProjectWizard.js
ENYO-2388: Modify "Project Properties" wizard for a project creation to fit new fileChooser improvements
<ide><path>roject-view/source/ProjectWizard.js <ide> <ide> components: [ <ide> {kind: "ProjectProperties", name: "propertiesWidget", onApplyAddSource: "notifyChangeSource"}, <del> {kind: "Ares.FileChooser", canGenerate: false, name: "selectDirectoryPopup", classes:"ares-masked-content-popup", folderChooser: true}, <add> {kind: "Ares.FileChooser", canGenerate: false, name: "selectDirectoryPopup", classes:"ares-masked-content-popup", folderChooser: true, allowCreateFolder: true}, <ide> {kind: "Ares.ErrorPopup", name: "errorPopup", msg: $L("unknown error")} <ide> ], <ide> debug: false, <ide> this.config = new ProjectConfig() ; // is a ProjectConfig object. <ide> <ide> dirPopup.$.header.setContent("Select a directory containing the new project") ; <del> dirPopup.$.hermesFileTree.showNewFolderButton(); <ide> dirPopup.show(); <ide> }, <ide>
Java
mit
054fda2f0bf4754a58af48db543b312ac90e04f9
0
cristid9/FunWeb,cristid9/FunWeb,cristid9/FunWeb
package controllers; import com.mashape.unirest.http.exceptions.UnirestException; import factories.BidirectionalLoginDataCustomFactory; import factories.BidirectionalPendingPasswordResetFactory; import factories.BidirectionalQuestionFactory; import factories.BidirectionalUserFactory; import funWebMailer.FunWebMailer; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.*; import org.springframework.web.servlet.ModelAndView; import pojos.LoginDataCustom; import pojos.PendingPasswordReset; import pojos.Question; import pojos.User; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.util.ArrayList; import java.util.List; import java.util.UUID; @Controller @SessionAttributes(value = "username") public class MainController { User loggedInUser = null; @RequestMapping(value ="statistics", method = RequestMethod.GET) public String getStatistics(HttpServletRequest request) { String username = (String) request.getSession().getAttribute("username"); if (username == null) { return "error"; } return "statistics"; } @RequestMapping(value = "/register", method = RequestMethod.GET) public String getRegisterPage(HttpServletRequest request) { return "register"; } @RequestMapping(value = "/change_password", method = RequestMethod.GET) public String getChangePassword(HttpServletRequest request) { return "change_password"; } @RequestMapping(value = "/change_password", method = RequestMethod.POST) public String postChangePassword(HttpServletRequest request) { return "success_recover"; } @RequestMapping(value = "/recover_password", method = RequestMethod.GET) public String getRecoverPasswordPage() { return "recover_password"; } @RequestMapping( value = "/recoverPassword", method = RequestMethod.POST ) public ModelAndView postRecoverPassword( @RequestParam(name = "username") String username) { User user = null; try { user = BidirectionalUserFactory.newInstance(username); } catch (UnirestException e) { e.printStackTrace(); } String recoverUrlToken = UUID.randomUUID().toString(); // send mail with reset link for the password String recoverUrl = String.format("localhost:8089/reset_password/%s", recoverUrlToken); PendingPasswordReset pendingPasswordReset = new PendingPasswordReset(); pendingPasswordReset.setId(0l); // Dummy pendingPasswordReset.setToken(recoverUrlToken); pendingPasswordReset.setUsername(user.getName()); try { BidirectionalPendingPasswordResetFactory.persist(pendingPasswordReset); } catch (UnirestException e) { e.printStackTrace(); } FunWebMailer.setResetPasswordLink(user.getName(), user.getEmail(), recoverUrl); return new ModelAndView("success_recover"); } @RequestMapping(value = "reset_password/{token}", method = RequestMethod.GET) public ModelAndView getResetPassword(@PathVariable String token) { PendingPasswordReset pendingPasswordReset = null; try { pendingPasswordReset = BidirectionalPendingPasswordResetFactory.newInstance(token); } catch (UnirestException e) { e.printStackTrace(); } if (pendingPasswordReset == null) { return null; // some error page } return new ModelAndView("reset_password"); } @RequestMapping(value = "reset_password/{token}", method = RequestMethod.POST) public ModelAndView postResetPassword( @PathVariable String token, @RequestParam(name = "new_password1") String newPassword1, @RequestParam(name = "new_password2") String newPassword2) { if (!newPassword1.equals(newPassword2)) { return null; } PendingPasswordReset pendingPasswordReset = null; try { pendingPasswordReset = BidirectionalPendingPasswordResetFactory.newInstance(token); } catch (UnirestException e) { e.printStackTrace(); } User user = null; try { user = BidirectionalUserFactory.newInstance(pendingPasswordReset.getUsername()); } catch (UnirestException e) { e.printStackTrace(); } try { BidirectionalLoginDataCustomFactory.update(user.getId(), String.valueOf(newPassword1.hashCode())); } catch (UnirestException e) { e.printStackTrace(); } return new ModelAndView("reset_password_success"); } @RequestMapping(value = "/login", method = RequestMethod.POST) public ModelAndView doLogin( HttpServletRequest request, HttpServletResponse response, @RequestParam(name = "username") String username, @RequestParam(name = "password") String password) { User user = null; try { user = BidirectionalUserFactory.newInstance(username); } catch (UnirestException e) { e.printStackTrace(); } String actualPassword = null; // That's not the way it supposed to be try { actualPassword = BidirectionalLoginDataCustomFactory.getPassword(user.getId()); } catch (UnirestException e) { e.printStackTrace(); } if (String.valueOf(password.hashCode()).equals(actualPassword)) { request.getSession().setAttribute("loggedIn", Boolean.TRUE); request.getSession().setAttribute("username", user.getName()); } return new ModelAndView("redirect:/main_menu"); } @RequestMapping(value="/pvp", method = RequestMethod.GET) public ModelAndView getPvpPage(HttpServletRequest request) { String username = (String) request.getSession().getAttribute("username"); if (username == null) { return new ModelAndView("error"); } ModelAndView modelAndView = new ModelAndView(); modelAndView.addObject("username", request.getSession().getAttribute("username")); return modelAndView; } @RequestMapping(value="/main_menu", method = RequestMethod.GET) public String getMainMenuPage(HttpServletRequest request){ String username = (String) request.getSession().getAttribute("username"); if (username == null) { return "error"; } return "main_menu"; } @RequestMapping(value="/chat_room", method = RequestMethod.GET) public String getChatRoomPage(HttpServletRequest request){ String username = (String) request.getSession().getAttribute("username"); if (request.getSession().getAttribute("username").equals("")) { return "error"; } return "chat_room"; } @RequestMapping(value="/add_question", method = RequestMethod.GET) public String getAddQuestionPage(HttpServletRequest request) { if (request.getSession().getAttribute("username").equals("")) { return "error"; } return "add_question"; } @ResponseBody @RequestMapping(value = "/checkUsernameAvailable", method = RequestMethod.POST) public String checkValidUsername(@RequestParam String username) { // JSONObject json = new JSONObject(); // JSONArray jsonArray = new JSONArray(); // // String suggestion = dao.checkIfValidUsername(username); // if (suggestion != null) { // try { // json.put("status", "taken"); // json.put("suggestion", suggestion); // } catch (JSONException e) { // e.printStackTrace(); // } // // return json.toString(); // } else { // try { // json.put("status", "ok"); // } catch (JSONException e) { // e.printStackTrace(); // } // // return json.toString(); // } return null; } @ResponseBody @RequestMapping(value = "/checkPasswordStrength", method = RequestMethod.POST) public String checkPasswordStrength(@RequestParam String password) { // JSONObject json = new JSONObject(); // // int strength = dao.checkPasswordStrengthness(password); // // try { // json.put("strength", strength); // } catch (JSONException e) { // e.printStackTrace(); // } // // return json.toString(); return null; } @RequestMapping(value = "/validateRegistration", method = RequestMethod.POST) public ModelAndView validateRegistration( @RequestParam(name = "email") String email, @RequestParam(name = "username") String username, @RequestParam(name = "password") String password) { if (email.equals("") || username.equals("") || password.equals("")) { ModelAndView modelAndView = new ModelAndView("redirect:/register"); modelAndView.addObject("error", "Invalid credentials"); return modelAndView; } FunWebMailer.sendTextRegisterNotification(username, email); try { if (BidirectionalUserFactory.newInstance(username) == null) { ModelAndView modelAndView = new ModelAndView("redirect:/register"); modelAndView.addObject("error", "Username already taken"); return modelAndView; } } catch (UnirestException e) { e.printStackTrace(); } User user = new User(); user.setName(username); user.setUserRole("user"); user.setEmail(email); user.setLoginType("custom"); user.setLevel(0); user.setHintsLeft(0); user.setGoldLeft(0); user.setAvatarPath("/home"); user.setId(0l); try { BidirectionalUserFactory.persist(user); } catch (UnirestException e) { e.printStackTrace(); ModelAndView modelAndView = new ModelAndView("redirect:/register"); modelAndView.addObject("error", "Error storing the new user"); } try { user = BidirectionalUserFactory.newInstance(username); } catch (UnirestException e) { ModelAndView modelAndView = new ModelAndView("redirect:/register"); modelAndView.addObject("error", "Error accessing the db service"); e.printStackTrace(); } LoginDataCustom loginDataCustom = new LoginDataCustom(); loginDataCustom.setPassword(String.valueOf(password.hashCode())); loginDataCustom.setId(0l); loginDataCustom.setUserId(user.getId()); try { BidirectionalLoginDataCustomFactory.persist(loginDataCustom); } catch (UnirestException e) { ModelAndView modelAndView = new ModelAndView("redirect:/register"); modelAndView.addObject("error", "Error accesing the db service"); e.printStackTrace(); } return new ModelAndView("redirect:/"); } @ResponseBody @RequestMapping(value = "/weakestChapter", method = RequestMethod.POST) public String getWeakestChapter() { // JSONObject json = new JSONObject(); // // try { // json.put("weakestChapter", dao.weakestChapter((int) loggedInUser.getId())); // } catch (JSONException e) { // e.printStackTrace(); // } // // return json.toString(); return null; } @ResponseBody @RequestMapping(value = "/isRelevant", method = RequestMethod.POST) public String getRelevance(@RequestParam(name ="id") Long id){ // JSONObject json = new JSONObject(); // // try{ // json.put("relevance", qDao.isRelevant(id)); // // if (qDao.getError() != null) { // json.put("error", "yes"); // json.put("errorMessage", qDao.getError()); // } else { // json.put("error", "no"); // } // // } catch (JSONException e){ // e.printStackTrace(); // } // // return json.toString(); return null; } @RequestMapping(value = "/adminPanel", method = RequestMethod.GET) public ModelAndView getAdminPannel(HttpServletRequest request) { String username = (String) request.getSession().getAttribute("username"); if (username == null) { return new ModelAndView("error"); } return new ModelAndView("admin"); } @RequestMapping(value = "/logout", method = RequestMethod.GET) public ModelAndView logout(HttpServletRequest request) { request.getSession().removeAttribute("username"); return new ModelAndView("register"); } @ResponseBody @RequestMapping(value="/getUsersList" , method = RequestMethod.POST) public String getUsersList(){ JSONArray jsonArray = new JSONArray(); List<String> users = new ArrayList<String>(); try { users = BidirectionalUserFactory.getAll(); } catch (UnirestException e) { e.printStackTrace(); } for (String user : users) { JSONObject jsonUser = new JSONObject(); try { jsonUser.put("username", user); jsonArray.put(jsonUser); } catch (JSONException e) { e.printStackTrace(); } } return jsonArray.toString(); } @ResponseBody @RequestMapping(value="/banUser" , method = RequestMethod.POST) public String banUser(@RequestParam(name = "username") String username) { User toBan = new User(); toBan.setName(username); System.out.println(toBan.getName()); try { BidirectionalUserFactory.remove(toBan); } catch (UnirestException e) { e.printStackTrace(); } return null; } @ResponseBody @RequestMapping(value = "/updatePassword", method = RequestMethod.POST) public String updatePassword(@RequestParam(name = "newPassword") String newPassword) { // JSONObject json = new JSONObject(); // // dao.updateUserPassword(loggedInUser, newPassword); // // try { // json.put("status", "success"); // } catch (JSONException e) { // e.printStackTrace(); // } // // return json.toString(); return null; } @ResponseBody @RequestMapping(value = "/checkAlreadyReceived", method = RequestMethod.POST) public String checkAlreadyReceived(@RequestParam(name = "id") String id) { JSONObject json = new JSONObject(); try { json.put("receivedStatus", null); } catch (JSONException e) { e.printStackTrace(); } return null; } @RequestMapping(value = "/arena", method = RequestMethod.GET) public ModelAndView getArena(HttpServletRequest request) { String username = (String) request.getSession().getAttribute("username"); if (username == null) { return new ModelAndView("error"); } return new ModelAndView("arena"); } @RequestMapping(value = "/quick_chat", method = RequestMethod.GET) public ModelAndView quickChatPage(HttpServletRequest request, HttpServletResponse response) { String username = (String) request.getSession().getAttribute("username"); if (username == null) { return new ModelAndView("error"); } ModelAndView modelAndView = new ModelAndView("quick_chat"); modelAndView.addObject("username", username); return modelAndView; } }
funweb-code/src/main/java/controllers/MainController.java
package controllers; import com.mashape.unirest.http.exceptions.UnirestException; import factories.BidirectionalLoginDataCustomFactory; import factories.BidirectionalPendingPasswordResetFactory; import factories.BidirectionalQuestionFactory; import factories.BidirectionalUserFactory; import funWebMailer.FunWebMailer; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.*; import org.springframework.web.servlet.ModelAndView; import pojos.LoginDataCustom; import pojos.PendingPasswordReset; import pojos.Question; import pojos.User; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.util.ArrayList; import java.util.List; import java.util.UUID; @Controller @SessionAttributes(value = "username") public class MainController { User loggedInUser = null; @RequestMapping(value ="statistics", method = RequestMethod.GET) public String getStatistics(HttpServletRequest request) { String username = (String) request.getSession().getAttribute("username"); if (username == null) { return "error"; } return "statistics"; } @RequestMapping(value = "/register", method = RequestMethod.GET) public String getRegisterPage(HttpServletRequest request) { return "register"; } @RequestMapping(value = "/change_password", method = RequestMethod.GET) public String getChangePassword(HttpServletRequest request) { return "change_password"; } @RequestMapping(value = "/recover_password", method = RequestMethod.GET) public String getRecoverPasswordPage() { return "recover_password"; } @RequestMapping( value = "/recoverPassword", method = RequestMethod.POST ) public ModelAndView postRecoverPassword( @RequestParam(name = "username") String username) { User user = null; try { user = BidirectionalUserFactory.newInstance(username); } catch (UnirestException e) { e.printStackTrace(); } String recoverUrlToken = UUID.randomUUID().toString(); // send mail with reset link for the password String recoverUrl = String.format("localhost:8089/reset_password/%s", recoverUrlToken); PendingPasswordReset pendingPasswordReset = new PendingPasswordReset(); pendingPasswordReset.setId(0l); // Dummy pendingPasswordReset.setToken(recoverUrlToken); pendingPasswordReset.setUsername(user.getName()); try { BidirectionalPendingPasswordResetFactory.persist(pendingPasswordReset); } catch (UnirestException e) { e.printStackTrace(); } FunWebMailer.setResetPasswordLink(user.getName(), user.getEmail(), recoverUrl); return new ModelAndView("success_recover"); } @RequestMapping(value = "reset_password/{token}", method = RequestMethod.GET) public ModelAndView getResetPassword(@PathVariable String token) { PendingPasswordReset pendingPasswordReset = null; try { pendingPasswordReset = BidirectionalPendingPasswordResetFactory.newInstance(token); } catch (UnirestException e) { e.printStackTrace(); } if (pendingPasswordReset == null) { return null; // some error page } return new ModelAndView("reset_password"); } @RequestMapping(value = "reset_password/{token}", method = RequestMethod.POST) public ModelAndView postResetPassword( @PathVariable String token, @RequestParam(name = "new_password1") String newPassword1, @RequestParam(name = "new_password2") String newPassword2) { if (!newPassword1.equals(newPassword2)) { return null; } PendingPasswordReset pendingPasswordReset = null; try { pendingPasswordReset = BidirectionalPendingPasswordResetFactory.newInstance(token); } catch (UnirestException e) { e.printStackTrace(); } User user = null; try { user = BidirectionalUserFactory.newInstance(pendingPasswordReset.getUsername()); } catch (UnirestException e) { e.printStackTrace(); } try { BidirectionalLoginDataCustomFactory.update(user.getId(), String.valueOf(newPassword1.hashCode())); } catch (UnirestException e) { e.printStackTrace(); } return new ModelAndView("reset_password_success"); } @RequestMapping(value = "/login", method = RequestMethod.POST) public ModelAndView doLogin( HttpServletRequest request, HttpServletResponse response, @RequestParam(name = "username") String username, @RequestParam(name = "password") String password) { User user = null; try { user = BidirectionalUserFactory.newInstance(username); } catch (UnirestException e) { e.printStackTrace(); } String actualPassword = null; // That's not the way it supposed to be try { actualPassword = BidirectionalLoginDataCustomFactory.getPassword(user.getId()); } catch (UnirestException e) { e.printStackTrace(); } if (String.valueOf(password.hashCode()).equals(actualPassword)) { request.getSession().setAttribute("loggedIn", Boolean.TRUE); request.getSession().setAttribute("username", user.getName()); } return new ModelAndView("redirect:/main_menu"); } @RequestMapping(value="/pvp", method = RequestMethod.GET) public ModelAndView getPvpPage(HttpServletRequest request) { String username = (String) request.getSession().getAttribute("username"); if (username == null) { return new ModelAndView("error"); } ModelAndView modelAndView = new ModelAndView(); modelAndView.addObject("username", request.getSession().getAttribute("username")); return modelAndView; } @RequestMapping(value="/main_menu", method = RequestMethod.GET) public String getMainMenuPage(HttpServletRequest request){ String username = (String) request.getSession().getAttribute("username"); if (username == null) { return "error"; } return "main_menu"; } @RequestMapping(value="/chat_room", method = RequestMethod.GET) public String getChatRoomPage(HttpServletRequest request){ String username = (String) request.getSession().getAttribute("username"); if (request.getSession().getAttribute("username").equals("")) { return "error"; } return "chat_room"; } @RequestMapping(value="/add_question", method = RequestMethod.GET) public String getAddQuestionPage(HttpServletRequest request) { if (request.getSession().getAttribute("username").equals("")) { return "error"; } return "add_question"; } @ResponseBody @RequestMapping(value = "/checkUsernameAvailable", method = RequestMethod.POST) public String checkValidUsername(@RequestParam String username) { // JSONObject json = new JSONObject(); // JSONArray jsonArray = new JSONArray(); // // String suggestion = dao.checkIfValidUsername(username); // if (suggestion != null) { // try { // json.put("status", "taken"); // json.put("suggestion", suggestion); // } catch (JSONException e) { // e.printStackTrace(); // } // // return json.toString(); // } else { // try { // json.put("status", "ok"); // } catch (JSONException e) { // e.printStackTrace(); // } // // return json.toString(); // } return null; } @ResponseBody @RequestMapping(value = "/checkPasswordStrength", method = RequestMethod.POST) public String checkPasswordStrength(@RequestParam String password) { // JSONObject json = new JSONObject(); // // int strength = dao.checkPasswordStrengthness(password); // // try { // json.put("strength", strength); // } catch (JSONException e) { // e.printStackTrace(); // } // // return json.toString(); return null; } @RequestMapping(value = "/validateRegistration", method = RequestMethod.POST) public ModelAndView validateRegistration( @RequestParam(name = "email") String email, @RequestParam(name = "username") String username, @RequestParam(name = "password") String password) { if (email.equals("") || username.equals("") || password.equals("")) { ModelAndView modelAndView = new ModelAndView("redirect:/register"); modelAndView.addObject("error", "Invalid credentials"); return modelAndView; } FunWebMailer.sendTextRegisterNotification(username, email); try { if (BidirectionalUserFactory.newInstance(username) == null) { ModelAndView modelAndView = new ModelAndView("redirect:/register"); modelAndView.addObject("error", "Username already taken"); return modelAndView; } } catch (UnirestException e) { e.printStackTrace(); } User user = new User(); user.setName(username); user.setUserRole("user"); user.setEmail(email); user.setLoginType("custom"); user.setLevel(0); user.setHintsLeft(0); user.setGoldLeft(0); user.setAvatarPath("/home"); user.setId(0l); try { BidirectionalUserFactory.persist(user); } catch (UnirestException e) { e.printStackTrace(); ModelAndView modelAndView = new ModelAndView("redirect:/register"); modelAndView.addObject("error", "Error storing the new user"); } try { user = BidirectionalUserFactory.newInstance(username); } catch (UnirestException e) { ModelAndView modelAndView = new ModelAndView("redirect:/register"); modelAndView.addObject("error", "Error accessing the db service"); e.printStackTrace(); } LoginDataCustom loginDataCustom = new LoginDataCustom(); loginDataCustom.setPassword(String.valueOf(password.hashCode())); loginDataCustom.setId(0l); loginDataCustom.setUserId(user.getId()); try { BidirectionalLoginDataCustomFactory.persist(loginDataCustom); } catch (UnirestException e) { ModelAndView modelAndView = new ModelAndView("redirect:/register"); modelAndView.addObject("error", "Error accesing the db service"); e.printStackTrace(); } return new ModelAndView("redirect:/"); } @ResponseBody @RequestMapping(value = "/weakestChapter", method = RequestMethod.POST) public String getWeakestChapter() { // JSONObject json = new JSONObject(); // // try { // json.put("weakestChapter", dao.weakestChapter((int) loggedInUser.getId())); // } catch (JSONException e) { // e.printStackTrace(); // } // // return json.toString(); return null; } @ResponseBody @RequestMapping(value = "/isRelevant", method = RequestMethod.POST) public String getRelevance(@RequestParam(name ="id") Long id){ // JSONObject json = new JSONObject(); // // try{ // json.put("relevance", qDao.isRelevant(id)); // // if (qDao.getError() != null) { // json.put("error", "yes"); // json.put("errorMessage", qDao.getError()); // } else { // json.put("error", "no"); // } // // } catch (JSONException e){ // e.printStackTrace(); // } // // return json.toString(); return null; } @RequestMapping(value = "/adminPanel", method = RequestMethod.GET) public ModelAndView getAdminPannel(HttpServletRequest request) { String username = (String) request.getSession().getAttribute("username"); if (username == null) { return new ModelAndView("error"); } return new ModelAndView("admin"); } @RequestMapping(value = "/logout", method = RequestMethod.GET) public ModelAndView logout(HttpServletRequest request) { request.getSession().removeAttribute("username"); return new ModelAndView("register"); } @ResponseBody @RequestMapping(value="/getUsersList" , method = RequestMethod.POST) public String getUsersList(){ JSONArray jsonArray = new JSONArray(); List<String> users = new ArrayList<String>(); try { users = BidirectionalUserFactory.getAll(); } catch (UnirestException e) { e.printStackTrace(); } for (String user : users) { JSONObject jsonUser = new JSONObject(); try { jsonUser.put("username", user); jsonArray.put(jsonUser); } catch (JSONException e) { e.printStackTrace(); } } return jsonArray.toString(); } @ResponseBody @RequestMapping(value="/banUser" , method = RequestMethod.POST) public String banUser(@RequestParam(name = "username") String username) { User toBan = new User(); toBan.setName(username); System.out.println(toBan.getName()); try { BidirectionalUserFactory.remove(toBan); } catch (UnirestException e) { e.printStackTrace(); } return null; } @ResponseBody @RequestMapping(value = "/updatePassword", method = RequestMethod.POST) public String updatePassword(@RequestParam(name = "newPassword") String newPassword) { // JSONObject json = new JSONObject(); // // dao.updateUserPassword(loggedInUser, newPassword); // // try { // json.put("status", "success"); // } catch (JSONException e) { // e.printStackTrace(); // } // // return json.toString(); return null; } @ResponseBody @RequestMapping(value = "/checkAlreadyReceived", method = RequestMethod.POST) public String checkAlreadyReceived(@RequestParam(name = "id") String id) { JSONObject json = new JSONObject(); try { json.put("receivedStatus", null); } catch (JSONException e) { e.printStackTrace(); } return null; } @RequestMapping(value = "/arena", method = RequestMethod.GET) public ModelAndView getArena(HttpServletRequest request) { String username = (String) request.getSession().getAttribute("username"); if (username == null) { return new ModelAndView("error"); } return new ModelAndView("arena"); } @RequestMapping(value = "/quick_chat", method = RequestMethod.GET) public ModelAndView quickChatPage(HttpServletRequest request, HttpServletResponse response) { String username = (String) request.getSession().getAttribute("username"); if (username == null) { return new ModelAndView("error"); } ModelAndView modelAndView = new ModelAndView("quick_chat"); modelAndView.addObject("username", username); return modelAndView; } }
Adeed post end point for change password
funweb-code/src/main/java/controllers/MainController.java
Adeed post end point for change password
<ide><path>unweb-code/src/main/java/controllers/MainController.java <ide> return "change_password"; <ide> } <ide> <add> <add> @RequestMapping(value = "/change_password", method = RequestMethod.POST) <add> public String postChangePassword(HttpServletRequest request) { <add> <add> return "success_recover"; <add> } <add> <ide> @RequestMapping(value = "/recover_password", method = RequestMethod.GET) <ide> public String getRecoverPasswordPage() { <ide> return "recover_password";
Java
apache-2.0
fedeba9b94574fe207f767731442a3633df7b826
0
kool79/intellij-community,muntasirsyed/intellij-community,alphafoobar/intellij-community,apixandru/intellij-community,retomerz/intellij-community,samthor/intellij-community,ryano144/intellij-community,jexp/idea2,semonte/intellij-community,holmes/intellij-community,holmes/intellij-community,clumsy/intellij-community,tmpgit/intellij-community,asedunov/intellij-community,ryano144/intellij-community,Lekanich/intellij-community,ahb0327/intellij-community,akosyakov/intellij-community,ol-loginov/intellij-community,asedunov/intellij-community,suncycheng/intellij-community,petteyg/intellij-community,adedayo/intellij-community,suncycheng/intellij-community,orekyuu/intellij-community,alphafoobar/intellij-community,robovm/robovm-studio,gnuhub/intellij-community,apixandru/intellij-community,michaelgallacher/intellij-community,wreckJ/intellij-community,ryano144/intellij-community,dslomov/intellij-community,pwoodworth/intellij-community,clumsy/intellij-community,supersven/intellij-community,adedayo/intellij-community,MichaelNedzelsky/intellij-community,fengbaicanhe/intellij-community,MER-GROUP/intellij-community,allotria/intellij-community,ThiagoGarciaAlves/intellij-community,gnuhub/intellij-community,muntasirsyed/intellij-community,izonder/intellij-community,slisson/intellij-community,youdonghai/intellij-community,jagguli/intellij-community,akosyakov/intellij-community,FHannes/intellij-community,asedunov/intellij-community,wreckJ/intellij-community,idea4bsd/idea4bsd,muntasirsyed/intellij-community,akosyakov/intellij-community,joewalnes/idea-community,supersven/intellij-community,lucafavatella/intellij-community,samthor/intellij-community,jexp/idea2,blademainer/intellij-community,youdonghai/intellij-community,lucafavatella/intellij-community,vladmm/intellij-community,ol-loginov/intellij-community,tmpgit/intellij-community,suncycheng/intellij-community,mglukhikh/intellij-community,gnuhub/intellij-community,SerCeMan/intellij-community,ibinti/intellij-community,ol-loginov/intellij-community,samthor/intellij-community,Lekanich/intellij-community,ernestp/consulo,ol-loginov/intellij-community,clumsy/intellij-community,ThiagoGarciaAlves/intellij-community,diorcety/intellij-community,suncycheng/intellij-community,ol-loginov/intellij-community,caot/intellij-community,pwoodworth/intellij-community,ftomassetti/intellij-community,youdonghai/intellij-community,ahb0327/intellij-community,ftomassetti/intellij-community,retomerz/intellij-community,alphafoobar/intellij-community,hurricup/intellij-community,izonder/intellij-community,MichaelNedzelsky/intellij-community,fengbaicanhe/intellij-community,TangHao1987/intellij-community,vladmm/intellij-community,ftomassetti/intellij-community,ibinti/intellij-community,youdonghai/intellij-community,asedunov/intellij-community,lucafavatella/intellij-community,holmes/intellij-community,samthor/intellij-community,ibinti/intellij-community,kdwink/intellij-community,allotria/intellij-community,jagguli/intellij-community,amith01994/intellij-community,ThiagoGarciaAlves/intellij-community,semonte/intellij-community,allotria/intellij-community,holmes/intellij-community,petteyg/intellij-community,lucafavatella/intellij-community,izonder/intellij-community,nicolargo/intellij-community,allotria/intellij-community,ahb0327/intellij-community,MER-GROUP/intellij-community,clumsy/intellij-community,salguarnieri/intellij-community,ol-loginov/intellij-community,vladmm/intellij-community,idea4bsd/idea4bsd,michaelgallacher/intellij-community,vladmm/intellij-community,alphafoobar/intellij-community,holmes/intellij-community,fengbaicanhe/intellij-community,kdwink/intellij-community,Lekanich/intellij-community,robovm/robovm-studio,apixandru/intellij-community,idea4bsd/idea4bsd,ernestp/consulo,TangHao1987/intellij-community,michaelgallacher/intellij-community,petteyg/intellij-community,adedayo/intellij-community,ftomassetti/intellij-community,lucafavatella/intellij-community,Lekanich/intellij-community,fengbaicanhe/intellij-community,michaelgallacher/intellij-community,Distrotech/intellij-community,salguarnieri/intellij-community,MER-GROUP/intellij-community,nicolargo/intellij-community,akosyakov/intellij-community,gnuhub/intellij-community,vvv1559/intellij-community,xfournet/intellij-community,SerCeMan/intellij-community,petteyg/intellij-community,hurricup/intellij-community,fitermay/intellij-community,diorcety/intellij-community,signed/intellij-community,asedunov/intellij-community,FHannes/intellij-community,ol-loginov/intellij-community,da1z/intellij-community,xfournet/intellij-community,kdwink/intellij-community,MichaelNedzelsky/intellij-community,supersven/intellij-community,muntasirsyed/intellij-community,SerCeMan/intellij-community,adedayo/intellij-community,amith01994/intellij-community,allotria/intellij-community,vvv1559/intellij-community,MER-GROUP/intellij-community,izonder/intellij-community,tmpgit/intellij-community,jexp/idea2,Distrotech/intellij-community,mglukhikh/intellij-community,robovm/robovm-studio,xfournet/intellij-community,fitermay/intellij-community,signed/intellij-community,kdwink/intellij-community,fitermay/intellij-community,ryano144/intellij-community,ibinti/intellij-community,wreckJ/intellij-community,holmes/intellij-community,apixandru/intellij-community,salguarnieri/intellij-community,idea4bsd/idea4bsd,vvv1559/intellij-community,vvv1559/intellij-community,kdwink/intellij-community,da1z/intellij-community,michaelgallacher/intellij-community,SerCeMan/intellij-community,alphafoobar/intellij-community,robovm/robovm-studio,hurricup/intellij-community,holmes/intellij-community,dslomov/intellij-community,kool79/intellij-community,ol-loginov/intellij-community,fnouama/intellij-community,fengbaicanhe/intellij-community,ftomassetti/intellij-community,petteyg/intellij-community,caot/intellij-community,mglukhikh/intellij-community,allotria/intellij-community,Lekanich/intellij-community,da1z/intellij-community,apixandru/intellij-community,supersven/intellij-community,Distrotech/intellij-community,SerCeMan/intellij-community,pwoodworth/intellij-community,izonder/intellij-community,blademainer/intellij-community,kdwink/intellij-community,ThiagoGarciaAlves/intellij-community,kdwink/intellij-community,SerCeMan/intellij-community,kool79/intellij-community,blademainer/intellij-community,da1z/intellij-community,blademainer/intellij-community,gnuhub/intellij-community,dslomov/intellij-community,TangHao1987/intellij-community,allotria/intellij-community,FHannes/intellij-community,blademainer/intellij-community,hurricup/intellij-community,fengbaicanhe/intellij-community,SerCeMan/intellij-community,orekyuu/intellij-community,gnuhub/intellij-community,adedayo/intellij-community,semonte/intellij-community,apixandru/intellij-community,orekyuu/intellij-community,Distrotech/intellij-community,tmpgit/intellij-community,salguarnieri/intellij-community,muntasirsyed/intellij-community,TangHao1987/intellij-community,MER-GROUP/intellij-community,youdonghai/intellij-community,retomerz/intellij-community,michaelgallacher/intellij-community,Distrotech/intellij-community,muntasirsyed/intellij-community,akosyakov/intellij-community,vvv1559/intellij-community,ahb0327/intellij-community,ahb0327/intellij-community,mglukhikh/intellij-community,pwoodworth/intellij-community,nicolargo/intellij-community,ftomassetti/intellij-community,consulo/consulo,akosyakov/intellij-community,joewalnes/idea-community,wreckJ/intellij-community,jagguli/intellij-community,diorcety/intellij-community,amith01994/intellij-community,da1z/intellij-community,youdonghai/intellij-community,amith01994/intellij-community,vladmm/intellij-community,kool79/intellij-community,vladmm/intellij-community,ThiagoGarciaAlves/intellij-community,petteyg/intellij-community,mglukhikh/intellij-community,ivan-fedorov/intellij-community,ibinti/intellij-community,ol-loginov/intellij-community,ibinti/intellij-community,lucafavatella/intellij-community,salguarnieri/intellij-community,slisson/intellij-community,orekyuu/intellij-community,vladmm/intellij-community,muntasirsyed/intellij-community,slisson/intellij-community,samthor/intellij-community,hurricup/intellij-community,MER-GROUP/intellij-community,fitermay/intellij-community,vladmm/intellij-community,fnouama/intellij-community,retomerz/intellij-community,diorcety/intellij-community,izonder/intellij-community,semonte/intellij-community,xfournet/intellij-community,amith01994/intellij-community,adedayo/intellij-community,youdonghai/intellij-community,amith01994/intellij-community,supersven/intellij-community,caot/intellij-community,holmes/intellij-community,blademainer/intellij-community,izonder/intellij-community,wreckJ/intellij-community,petteyg/intellij-community,nicolargo/intellij-community,petteyg/intellij-community,hurricup/intellij-community,diorcety/intellij-community,signed/intellij-community,orekyuu/intellij-community,vvv1559/intellij-community,da1z/intellij-community,TangHao1987/intellij-community,akosyakov/intellij-community,fnouama/intellij-community,fnouama/intellij-community,joewalnes/idea-community,kdwink/intellij-community,salguarnieri/intellij-community,adedayo/intellij-community,dslomov/intellij-community,hurricup/intellij-community,apixandru/intellij-community,robovm/robovm-studio,nicolargo/intellij-community,muntasirsyed/intellij-community,muntasirsyed/intellij-community,nicolargo/intellij-community,MichaelNedzelsky/intellij-community,allotria/intellij-community,FHannes/intellij-community,jagguli/intellij-community,orekyuu/intellij-community,dslomov/intellij-community,jagguli/intellij-community,ahb0327/intellij-community,amith01994/intellij-community,da1z/intellij-community,wreckJ/intellij-community,Lekanich/intellij-community,youdonghai/intellij-community,ibinti/intellij-community,pwoodworth/intellij-community,clumsy/intellij-community,idea4bsd/idea4bsd,da1z/intellij-community,wreckJ/intellij-community,slisson/intellij-community,supersven/intellij-community,allotria/intellij-community,ftomassetti/intellij-community,kdwink/intellij-community,ivan-fedorov/intellij-community,izonder/intellij-community,clumsy/intellij-community,vladmm/intellij-community,fnouama/intellij-community,ernestp/consulo,blademainer/intellij-community,ThiagoGarciaAlves/intellij-community,blademainer/intellij-community,petteyg/intellij-community,pwoodworth/intellij-community,slisson/intellij-community,ernestp/consulo,orekyuu/intellij-community,kdwink/intellij-community,mglukhikh/intellij-community,robovm/robovm-studio,dslomov/intellij-community,Distrotech/intellij-community,salguarnieri/intellij-community,lucafavatella/intellij-community,tmpgit/intellij-community,nicolargo/intellij-community,kool79/intellij-community,Lekanich/intellij-community,MER-GROUP/intellij-community,signed/intellij-community,ivan-fedorov/intellij-community,jagguli/intellij-community,hurricup/intellij-community,fnouama/intellij-community,kool79/intellij-community,fnouama/intellij-community,vvv1559/intellij-community,Distrotech/intellij-community,fengbaicanhe/intellij-community,muntasirsyed/intellij-community,FHannes/intellij-community,tmpgit/intellij-community,diorcety/intellij-community,asedunov/intellij-community,ryano144/intellij-community,supersven/intellij-community,retomerz/intellij-community,slisson/intellij-community,alphafoobar/intellij-community,TangHao1987/intellij-community,apixandru/intellij-community,amith01994/intellij-community,Lekanich/intellij-community,joewalnes/idea-community,xfournet/intellij-community,ftomassetti/intellij-community,mglukhikh/intellij-community,samthor/intellij-community,holmes/intellij-community,samthor/intellij-community,vladmm/intellij-community,alphafoobar/intellij-community,FHannes/intellij-community,consulo/consulo,FHannes/intellij-community,xfournet/intellij-community,ThiagoGarciaAlves/intellij-community,mglukhikh/intellij-community,izonder/intellij-community,semonte/intellij-community,lucafavatella/intellij-community,pwoodworth/intellij-community,idea4bsd/idea4bsd,idea4bsd/idea4bsd,fnouama/intellij-community,fitermay/intellij-community,alphafoobar/intellij-community,wreckJ/intellij-community,semonte/intellij-community,michaelgallacher/intellij-community,jagguli/intellij-community,asedunov/intellij-community,MichaelNedzelsky/intellij-community,fengbaicanhe/intellij-community,fnouama/intellij-community,MichaelNedzelsky/intellij-community,idea4bsd/idea4bsd,vladmm/intellij-community,amith01994/intellij-community,joewalnes/idea-community,MichaelNedzelsky/intellij-community,ryano144/intellij-community,jexp/idea2,ivan-fedorov/intellij-community,apixandru/intellij-community,vvv1559/intellij-community,adedayo/intellij-community,dslomov/intellij-community,ivan-fedorov/intellij-community,Lekanich/intellij-community,salguarnieri/intellij-community,samthor/intellij-community,clumsy/intellij-community,joewalnes/idea-community,ryano144/intellij-community,ryano144/intellij-community,clumsy/intellij-community,ftomassetti/intellij-community,ernestp/consulo,fengbaicanhe/intellij-community,semonte/intellij-community,fitermay/intellij-community,ThiagoGarciaAlves/intellij-community,ibinti/intellij-community,slisson/intellij-community,kool79/intellij-community,caot/intellij-community,kool79/intellij-community,fitermay/intellij-community,retomerz/intellij-community,tmpgit/intellij-community,slisson/intellij-community,FHannes/intellij-community,kool79/intellij-community,akosyakov/intellij-community,hurricup/intellij-community,ryano144/intellij-community,Distrotech/intellij-community,pwoodworth/intellij-community,apixandru/intellij-community,xfournet/intellij-community,youdonghai/intellij-community,jagguli/intellij-community,MichaelNedzelsky/intellij-community,tmpgit/intellij-community,suncycheng/intellij-community,semonte/intellij-community,Distrotech/intellij-community,suncycheng/intellij-community,hurricup/intellij-community,SerCeMan/intellij-community,clumsy/intellij-community,wreckJ/intellij-community,pwoodworth/intellij-community,semonte/intellij-community,fitermay/intellij-community,retomerz/intellij-community,Lekanich/intellij-community,MER-GROUP/intellij-community,idea4bsd/idea4bsd,consulo/consulo,clumsy/intellij-community,ernestp/consulo,wreckJ/intellij-community,slisson/intellij-community,jexp/idea2,wreckJ/intellij-community,allotria/intellij-community,jagguli/intellij-community,robovm/robovm-studio,robovm/robovm-studio,amith01994/intellij-community,youdonghai/intellij-community,caot/intellij-community,tmpgit/intellij-community,nicolargo/intellij-community,semonte/intellij-community,michaelgallacher/intellij-community,michaelgallacher/intellij-community,slisson/intellij-community,lucafavatella/intellij-community,samthor/intellij-community,joewalnes/idea-community,samthor/intellij-community,Lekanich/intellij-community,xfournet/intellij-community,Distrotech/intellij-community,apixandru/intellij-community,ahb0327/intellij-community,suncycheng/intellij-community,allotria/intellij-community,gnuhub/intellij-community,gnuhub/intellij-community,signed/intellij-community,apixandru/intellij-community,fengbaicanhe/intellij-community,consulo/consulo,MER-GROUP/intellij-community,blademainer/intellij-community,jexp/idea2,clumsy/intellij-community,retomerz/intellij-community,dslomov/intellij-community,joewalnes/idea-community,lucafavatella/intellij-community,nicolargo/intellij-community,ol-loginov/intellij-community,ahb0327/intellij-community,TangHao1987/intellij-community,alphafoobar/intellij-community,Distrotech/intellij-community,fengbaicanhe/intellij-community,fitermay/intellij-community,TangHao1987/intellij-community,MichaelNedzelsky/intellij-community,nicolargo/intellij-community,TangHao1987/intellij-community,supersven/intellij-community,FHannes/intellij-community,ivan-fedorov/intellij-community,hurricup/intellij-community,SerCeMan/intellij-community,michaelgallacher/intellij-community,jagguli/intellij-community,caot/intellij-community,orekyuu/intellij-community,supersven/intellij-community,ol-loginov/intellij-community,youdonghai/intellij-community,ThiagoGarciaAlves/intellij-community,asedunov/intellij-community,adedayo/intellij-community,diorcety/intellij-community,amith01994/intellij-community,suncycheng/intellij-community,muntasirsyed/intellij-community,jexp/idea2,orekyuu/intellij-community,semonte/intellij-community,akosyakov/intellij-community,idea4bsd/idea4bsd,diorcety/intellij-community,orekyuu/intellij-community,pwoodworth/intellij-community,allotria/intellij-community,xfournet/intellij-community,fitermay/intellij-community,ryano144/intellij-community,caot/intellij-community,diorcety/intellij-community,slisson/intellij-community,xfournet/intellij-community,akosyakov/intellij-community,FHannes/intellij-community,vvv1559/intellij-community,dslomov/intellij-community,ivan-fedorov/intellij-community,supersven/intellij-community,signed/intellij-community,caot/intellij-community,allotria/intellij-community,supersven/intellij-community,ibinti/intellij-community,gnuhub/intellij-community,hurricup/intellij-community,suncycheng/intellij-community,nicolargo/intellij-community,SerCeMan/intellij-community,signed/intellij-community,vvv1559/intellij-community,alphafoobar/intellij-community,robovm/robovm-studio,FHannes/intellij-community,FHannes/intellij-community,caot/intellij-community,ivan-fedorov/intellij-community,da1z/intellij-community,wreckJ/intellij-community,da1z/intellij-community,MER-GROUP/intellij-community,izonder/intellij-community,adedayo/intellij-community,apixandru/intellij-community,suncycheng/intellij-community,alphafoobar/intellij-community,ryano144/intellij-community,mglukhikh/intellij-community,mglukhikh/intellij-community,blademainer/intellij-community,retomerz/intellij-community,kool79/intellij-community,SerCeMan/intellij-community,retomerz/intellij-community,vladmm/intellij-community,slisson/intellij-community,TangHao1987/intellij-community,robovm/robovm-studio,asedunov/intellij-community,vvv1559/intellij-community,SerCeMan/intellij-community,gnuhub/intellij-community,supersven/intellij-community,blademainer/intellij-community,alphafoobar/intellij-community,suncycheng/intellij-community,petteyg/intellij-community,signed/intellij-community,ivan-fedorov/intellij-community,ahb0327/intellij-community,ibinti/intellij-community,ivan-fedorov/intellij-community,ThiagoGarciaAlves/intellij-community,adedayo/intellij-community,nicolargo/intellij-community,diorcety/intellij-community,hurricup/intellij-community,amith01994/intellij-community,joewalnes/idea-community,xfournet/intellij-community,pwoodworth/intellij-community,semonte/intellij-community,gnuhub/intellij-community,tmpgit/intellij-community,dslomov/intellij-community,asedunov/intellij-community,blademainer/intellij-community,tmpgit/intellij-community,gnuhub/intellij-community,caot/intellij-community,Distrotech/intellij-community,TangHao1987/intellij-community,ahb0327/intellij-community,consulo/consulo,holmes/intellij-community,salguarnieri/intellij-community,fitermay/intellij-community,fitermay/intellij-community,muntasirsyed/intellij-community,caot/intellij-community,robovm/robovm-studio,ivan-fedorov/intellij-community,michaelgallacher/intellij-community,xfournet/intellij-community,samthor/intellij-community,FHannes/intellij-community,signed/intellij-community,semonte/intellij-community,caot/intellij-community,akosyakov/intellij-community,MichaelNedzelsky/intellij-community,ftomassetti/intellij-community,ahb0327/intellij-community,ahb0327/intellij-community,mglukhikh/intellij-community,xfournet/intellij-community,kool79/intellij-community,izonder/intellij-community,apixandru/intellij-community,akosyakov/intellij-community,TangHao1987/intellij-community,samthor/intellij-community,jagguli/intellij-community,youdonghai/intellij-community,retomerz/intellij-community,ibinti/intellij-community,dslomov/intellij-community,petteyg/intellij-community,asedunov/intellij-community,orekyuu/intellij-community,ThiagoGarciaAlves/intellij-community,orekyuu/intellij-community,ibinti/intellij-community,robovm/robovm-studio,clumsy/intellij-community,retomerz/intellij-community,jagguli/intellij-community,ThiagoGarciaAlves/intellij-community,holmes/intellij-community,ftomassetti/intellij-community,ibinti/intellij-community,dslomov/intellij-community,vvv1559/intellij-community,kdwink/intellij-community,signed/intellij-community,kdwink/intellij-community,fnouama/intellij-community,kool79/intellij-community,idea4bsd/idea4bsd,da1z/intellij-community,ftomassetti/intellij-community,mglukhikh/intellij-community,retomerz/intellij-community,vvv1559/intellij-community,ivan-fedorov/intellij-community,consulo/consulo,asedunov/intellij-community,diorcety/intellij-community,fitermay/intellij-community,suncycheng/intellij-community,ryano144/intellij-community,fengbaicanhe/intellij-community,da1z/intellij-community,salguarnieri/intellij-community,da1z/intellij-community,signed/intellij-community,mglukhikh/intellij-community,fnouama/intellij-community,fnouama/intellij-community,salguarnieri/intellij-community,izonder/intellij-community,michaelgallacher/intellij-community,holmes/intellij-community,MichaelNedzelsky/intellij-community,idea4bsd/idea4bsd,lucafavatella/intellij-community,petteyg/intellij-community,adedayo/intellij-community,jexp/idea2,salguarnieri/intellij-community,tmpgit/intellij-community,ol-loginov/intellij-community,lucafavatella/intellij-community,Lekanich/intellij-community,lucafavatella/intellij-community,youdonghai/intellij-community,MER-GROUP/intellij-community,pwoodworth/intellij-community,signed/intellij-community,idea4bsd/idea4bsd,signed/intellij-community,diorcety/intellij-community,MichaelNedzelsky/intellij-community,asedunov/intellij-community,MER-GROUP/intellij-community
package com.intellij.codeInsight.lookup.impl; import com.intellij.codeInsight.CodeInsightSettings; import com.intellij.codeInsight.completion.CompletionPreferencePolicy; import com.intellij.codeInsight.completion.PrefixMatcher; import com.intellij.codeInsight.completion.impl.CamelHumpMatcher; import com.intellij.codeInsight.hint.HintManagerImpl; import com.intellij.codeInsight.hint.HintUtil; import com.intellij.codeInsight.lookup.*; import com.intellij.featureStatistics.FeatureUsageTracker; import com.intellij.lang.LangBundle; import com.intellij.openapi.Disposable; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.application.Result; import com.intellij.openapi.command.CommandProcessor; import com.intellij.openapi.command.WriteCommandAction; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.editor.*; import com.intellij.openapi.editor.event.*; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.Disposer; import com.intellij.openapi.util.Key; import com.intellij.psi.PsiDocumentManager; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiFile; import com.intellij.psi.util.proximity.PsiProximityComparator; import com.intellij.ui.LightweightHint; import com.intellij.ui.ListScrollingUtil; import com.intellij.ui.plaf.beg.BegPopupMenuBorder; import com.intellij.util.SmartList; import com.intellij.util.containers.SortedList; import com.intellij.util.ui.AsyncProcessIcon; import gnu.trove.THashSet; import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.TestOnly; import javax.swing.*; import javax.swing.event.ListSelectionEvent; import javax.swing.event.ListSelectionListener; import java.awt.*; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.util.*; import java.util.List; public class LookupImpl extends LightweightHint implements Lookup, Disposable { private static final Logger LOG = Logger.getInstance("#com.intellij.codeInsight.lookup.impl.LookupImpl"); private static final int MAX_PREFERRED_COUNT = 5; private static final LookupItem EMPTY_LOOKUP_ITEM = new LookupItem("preselect", "preselect"); private static final Key<Boolean> USED_LOOKUP_ELEMENT = Key.create("USED_LOOKUP_ELEMENT"); private final Project myProject; private final Editor myEditor; private final SortedList<LookupElement> myItems; private final SortedMap<LookupItemWeightComparable, SortedList<LookupElement>> myItemsMap; private int myMinPrefixLength; private int myPreferredItemsCount; private int myInitialOffset; private long myShownStamp = -1; private String myInitialPrefix; @Nullable private final LookupItemPreferencePolicy myItemPreferencePolicy; private RangeMarker myLookupStartMarker; private final JList myList; private final LookupCellRenderer myCellRenderer; private Boolean myPositionedAbove = null; private CaretListener myEditorCaretListener; private SelectionListener myEditorSelectionListener; private EditorMouseListener myEditorMouseListener; private final ArrayList<LookupListener> myListeners = new ArrayList<LookupListener>(); private boolean myDisposed = false; private boolean myHidden = false; private LookupElement myPreselectedItem = EMPTY_LOOKUP_ITEM; private boolean myDirty; private String myAdditionalPrefix = ""; private PsiElement myElement; private final AsyncProcessIcon myProcessIcon; private final Comparator<LookupElement> myComparator; private volatile boolean myCalculating; private final JLabel myAdComponent; private volatile String myAdText; private volatile int myLookupWidth = 50; public LookupImpl(Project project, Editor editor, LookupElement[] items, @Nullable LookupItemPreferencePolicy itemPreferencePolicy){ super(new JPanel(new BorderLayout())); myProject = project; myEditor = editor; myItemPreferencePolicy = itemPreferencePolicy; myInitialOffset = myEditor.getSelectionModel().hasSelection() ? myEditor.getSelectionModel().getSelectionStart() : myEditor.getCaretModel().getOffset(); final Document document = myEditor.getDocument(); final PsiFile psiFile = PsiDocumentManager.getInstance(myProject).getPsiFile(document); myElement = psiFile == null ? null : psiFile.findElementAt(myEditor.getCaretModel().getOffset()); final PsiProximityComparator proximityComparator = new PsiProximityComparator(myElement == null ? psiFile : myElement); myComparator = new Comparator<LookupElement>() { public int compare(LookupElement o1, LookupElement o2) { if (o1 instanceof LookupItem && o2 instanceof LookupItem) { double priority1 = ((LookupItem)o1).getPriority(); double priority2 = ((LookupItem)o2).getPriority(); if (priority1 > priority2) return -1; if (priority2 > priority1) return 1; int grouping1 = ((LookupItem)o1).getGrouping(); int grouping2 = ((LookupItem)o2).getGrouping(); if (grouping1 > grouping2) return -1; if (grouping2 > grouping1) return 1; } int stringCompare = o1.getLookupString().compareToIgnoreCase(o2.getLookupString()); if (stringCompare != 0) return stringCompare; return proximityComparator.compare(o1.getObject(), o2.getObject()); } }; myItems = new SortedList<LookupElement>(myComparator); myItemsMap = new TreeMap<LookupItemWeightComparable, SortedList<LookupElement>>(); myProcessIcon = new AsyncProcessIcon("Completion progress"); myProcessIcon.setVisible(false); myList = new JList(new DefaultListModel()); myCellRenderer = new LookupCellRenderer(this); myList.setCellRenderer(myCellRenderer); for (final LookupElement item : items) { addItem(item); } myList.setFocusable(false); myList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); myList.setBackground(LookupCellRenderer.BACKGROUND_COLOR); JScrollPane scrollPane = new JScrollPane(myList); scrollPane.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER); getComponent().add(scrollPane, BorderLayout.NORTH); scrollPane.setBorder(null); JPanel bottomPanel = new JPanel(new BorderLayout()); bottomPanel.add(myProcessIcon, BorderLayout.EAST); myAdComponent = HintUtil.createAdComponent(null); bottomPanel.add(myAdComponent, BorderLayout.CENTER); getComponent().add(bottomPanel, BorderLayout.SOUTH); getComponent().setBorder(new BegPopupMenuBorder()); updateList(); selectMostPreferableItem(); } public AsyncProcessIcon getProcessIcon() { return myProcessIcon; } public boolean isCalculating() { return myCalculating; } public void setCalculating(final boolean calculating) { myCalculating = calculating; } public int getPreferredItemsCount() { return myPreferredItemsCount; } public void markDirty() { myDirty = true; myPreselectedItem = null; } @TestOnly public void resort() { final ArrayList<LookupElement> items = new ArrayList<LookupElement>(myItems); myDirty = false; myPreselectedItem = EMPTY_LOOKUP_ITEM; myItemsMap.clear(); myItems.clear(); for (final LookupElement item : items) { item.putUserData(USED_LOOKUP_ELEMENT, null); addItem(item); } updateList(); } public void addItem(LookupElement item) { if (item.getUserData(USED_LOOKUP_ELEMENT) != null) { LOG.assertTrue(false, "An attempt to reuse lookup item detected. Giving the same lookup element instance to more than one lookup or completion process is prohibited: item=" + item); } item.putUserData(USED_LOOKUP_ELEMENT, Boolean.TRUE); synchronized (myItems) { myItems.add(item); addItemWeight(item); } int maxWidth = myCellRenderer.updateMaximumWidth(item); myLookupWidth = Math.max(maxWidth, myLookupWidth); } private void addItemWeight(final LookupElement item) { final Comparable[] weight = getWeight(myItemPreferencePolicy, myElement, item); final LookupItemWeightComparable key = new LookupItemWeightComparable(item instanceof LookupItem ? ((LookupItem)item).getPriority() : 0, weight); SortedList<LookupElement> list = myItemsMap.get(key); if (list == null) myItemsMap.put(key, list = new SortedList<LookupElement>(myComparator)); list.add(item); } @Nullable public LookupItemPreferencePolicy getItemPreferencePolicy() { return myItemPreferencePolicy; } private static Comparable[] getWeight(final LookupItemPreferencePolicy itemPreferencePolicy, final PsiElement context, final LookupElement item) { if (itemPreferencePolicy instanceof CompletionPreferencePolicy) { return ((CompletionPreferencePolicy)itemPreferencePolicy).getWeight(item); } Comparable i = null; if (item.getObject() instanceof PsiElement) { i = PsiProximityComparator.getProximity((PsiElement)item.getObject(), context); } return new Comparable[]{i}; } public int getMinPrefixLength() { return myMinPrefixLength; } public JList getList() { return myList; } public LookupElement[] getItems(){ synchronized (myItems) { return myItems.toArray(new LookupElement[myItems.size()]); } } public void setAdvertisementText(@Nullable String text) { myAdText = text; } public String getAdvertisementText() { return myAdText; } public String getAdditionalPrefix() { return myAdditionalPrefix; } public void setAdditionalPrefix(final String additionalPrefix) { myAdditionalPrefix = additionalPrefix; myInitialPrefix = null; markDirty(); updateList(); } public final void updateList() { synchronized (myItems) { int minPrefixLength = myItems.isEmpty() ? 0 : Integer.MAX_VALUE; for (final LookupElement item : myItems) { minPrefixLength = Math.min(item.getPrefixMatcher().getPrefix().length(), minPrefixLength); } if (myMinPrefixLength != minPrefixLength) { myLookupStartMarker = null; } myMinPrefixLength = minPrefixLength; Object oldSelected = !myDirty ? null : myList.getSelectedValue(); DefaultListModel model = (DefaultListModel)myList.getModel(); model.clear(); Set<LookupElement> firstItems = new THashSet<LookupElement>(); addExactPrefixItems(model, firstItems); boolean hasExactPrefixes = !firstItems.isEmpty(); addMostRelevantItems(model, firstItems); final boolean hasPreselectedItem = addPreselectedItem(model, firstItems); myPreferredItemsCount = firstItems.size(); addRemainingItemsLexicographically(model, firstItems); boolean isEmpty = model.getSize() == 0; if (isEmpty) { addEmptyItem(model); } else { myList.setFixedCellWidth(myLookupWidth); } myList.setFixedCellHeight(myCellRenderer.getListCellRendererComponent(myList, myList.getModel().getElementAt(0), 0, false, false).getPreferredSize().height); myList.setVisibleRowCount(Math.min(myList.getModel().getSize(), CodeInsightSettings.getInstance().LOOKUP_HEIGHT)); myAdComponent.setText(myAdText); if (!isEmpty) { if (oldSelected != null) { if (hasExactPrefixes || !ListScrollingUtil.selectItem(myList, oldSelected)) { selectMostPreferableItem(); } } else { if (myPreselectedItem == EMPTY_LOOKUP_ITEM) { selectMostPreferableItem(); myPreselectedItem = getCurrentItem(); } else if (hasPreselectedItem && !hasExactPrefixes) { ListScrollingUtil.selectItem(myList, myPreselectedItem); } else { selectMostPreferableItem(); } } } } } private void addEmptyItem(DefaultListModel model) { LookupItem<String> item = new EmptyLookupItem(myCalculating ? " " : LangBundle.message("completion.no.suggestions")); item.setPrefixMatcher(new CamelHumpMatcher("")); if (!myCalculating) { final int maxWidth = myCellRenderer.updateMaximumWidth(item); myList.setFixedCellWidth(Math.max(maxWidth, myLookupWidth)); } model.addElement(item); } private void addRemainingItemsLexicographically(DefaultListModel model, Set<LookupElement> firstItems) { for (LookupElement item : myItems) { if (!firstItems.contains(item) && prefixMatches(item)) { model.addElement(item); } } } private boolean addPreselectedItem(DefaultListModel model, Set<LookupElement> firstItems) { final boolean hasPreselectedItem = !myDirty && myPreselectedItem != EMPTY_LOOKUP_ITEM; if (hasPreselectedItem && !firstItems.contains(myPreselectedItem)) { firstItems.add(myPreselectedItem); model.addElement(myPreselectedItem); } return hasPreselectedItem; } private void addMostRelevantItems(DefaultListModel model, Set<LookupElement> firstItems) { for (final LookupItemWeightComparable comparable : myItemsMap.keySet()) { final List<LookupElement> suitable = new SmartList<LookupElement>(); for (final LookupElement item : myItemsMap.get(comparable)) { if (!firstItems.contains(item) && prefixMatches(item)) { suitable.add(item); } } if (firstItems.size() + suitable.size() > MAX_PREFERRED_COUNT) break; for (final LookupElement item : suitable) { firstItems.add(item); model.addElement(item); } } } private void addExactPrefixItems(DefaultListModel model, Set<LookupElement> firstItems) { for (final LookupItemWeightComparable comparable : myItemsMap.keySet()) { for (final LookupElement item : myItemsMap.get(comparable)) { if (isExactPrefixItem(item)) { model.addElement(item); firstItems.add(item); } } } } private boolean prefixMatches(final LookupElement item) { if (myAdditionalPrefix.length() == 0) return item.isPrefixMatched(); return item.getPrefixMatcher().cloneWithPrefix(item.getPrefixMatcher().getPrefix() + myAdditionalPrefix).prefixMatches(item); } /** * @return point in layered pane coordinate system. */ public Point calculatePosition(){ Dimension dim = getComponent().getPreferredSize(); int lookupStart = getLookupStart(); LogicalPosition pos = myEditor.offsetToLogicalPosition(lookupStart); Point location = myEditor.logicalPositionToXY(pos); location.y += myEditor.getLineHeight(); JComponent editorComponent = myEditor.getComponent(); JComponent internalComponent = myEditor.getContentComponent(); final JRootPane rootPane = editorComponent.getRootPane(); if (rootPane == null) { synchronized (myItems) { LOG.assertTrue(false, myItems); } } JLayeredPane layeredPane = rootPane.getLayeredPane(); Point layeredPanePoint=SwingUtilities.convertPoint(internalComponent,location, layeredPane); layeredPanePoint.x -= myCellRenderer.getIconIndent(); if (dim.width > layeredPane.getWidth()){ dim.width = layeredPane.getWidth(); } int wshift = layeredPane.getWidth() - (layeredPanePoint.x + dim.width); if (wshift < 0){ layeredPanePoint.x += wshift; } int shiftLow = layeredPane.getHeight() - (layeredPanePoint.y + dim.height); int shiftHigh = layeredPanePoint.y - dim.height; myPositionedAbove = shiftLow < 0 && shiftLow < shiftHigh ? Boolean.TRUE : Boolean.FALSE; if (myPositionedAbove.booleanValue()){ layeredPanePoint.y -= dim.height + myEditor.getLineHeight(); } return layeredPanePoint; } public void finishLookup(final char completionChar) { if (myShownStamp > 0 && System.currentTimeMillis() - myShownStamp < 239 && !ApplicationManager.getApplication().isUnitTestMode()) { return; } final LookupElement item = (LookupElement)myList.getSelectedValue(); doHide(false); if (item == null || item instanceof EmptyLookupItem || item.getObject() instanceof DeferredUserLookupValue && item instanceof LookupItem && !((DeferredUserLookupValue)item.getObject()).handleUserSelection((LookupItem)item, myProject)) { fireItemSelected(null, completionChar); return; } ApplicationManager.getApplication().runWriteAction(new Runnable() { public void run() { EditorModificationUtil.deleteSelectedText(myEditor); final int caretOffset = myEditor.getCaretModel().getOffset(); final String prefix = item.getPrefixMatcher().getPrefix(); int lookupStart = caretOffset - prefix.length() - myAdditionalPrefix.length(); final String lookupString = item.getLookupString(); if (!lookupString.startsWith(prefix + myAdditionalPrefix)) { FeatureUsageTracker.getInstance().triggerFeatureUsed("editing.completion.camelHumps"); } myEditor.getDocument().replaceString(lookupStart, caretOffset, lookupString); int offset = lookupStart + lookupString.length(); myEditor.getCaretModel().moveToOffset(offset); myEditor.getScrollingModel().scrollToCaret(ScrollType.RELATIVE); myEditor.getSelectionModel().removeSelection(); } }); fireItemSelected(item, completionChar); } public int getLookupStart() { return myLookupStartMarker != null ? myLookupStartMarker.getStartOffset() : calcLookupStart(); } public void show(){ assert !myDisposed; int lookupStart = calcLookupStart(); myLookupStartMarker = myEditor.getDocument().createRangeMarker(lookupStart, lookupStart); myLookupStartMarker.setGreedyToLeft(true); myEditor.getDocument().addDocumentListener(new DocumentAdapter() { public void documentChanged(DocumentEvent e) { if (myLookupStartMarker != null && !myLookupStartMarker.isValid()){ hide(); } } }, this); myEditorCaretListener = new CaretListener() { public void caretPositionChanged(CaretEvent e){ int curOffset = myEditor.getCaretModel().getOffset(); if (curOffset != myInitialOffset + myAdditionalPrefix.length()) { hide(); } } }; myEditorSelectionListener = new SelectionListener() { public void selectionChanged(final SelectionEvent e) { if (!e.getNewRange().isEmpty()) { hide(); } } }; myEditor.getCaretModel().addCaretListener(myEditorCaretListener); myEditor.getSelectionModel().addSelectionListener(myEditorSelectionListener); myEditorMouseListener = new EditorMouseAdapter() { public void mouseClicked(EditorMouseEvent e){ e.consume(); hide(); } }; myEditor.addEditorMouseListener(myEditorMouseListener); myList.addListSelectionListener(new ListSelectionListener() { private LookupElement oldItem = null; public void valueChanged(ListSelectionEvent e){ LookupElement item = getCurrentItem(); if (oldItem != item) { fireCurrentItemChanged(item); } oldItem = item; } }); myList.addMouseListener(new MouseAdapter() { public void mouseClicked(MouseEvent e){ if (e.getClickCount() == 2){ CommandProcessor.getInstance().executeCommand(myProject, new Runnable() { public void run() { finishLookup(NORMAL_SELECT_CHAR); } }, "", null); } } }); if (ApplicationManager.getApplication().isUnitTestMode()) return; Point p = calculatePosition(); HintManagerImpl hintManager = HintManagerImpl.getInstanceImpl(); hintManager.showEditorHint(this, myEditor, p, HintManagerImpl.HIDE_BY_ESCAPE | HintManagerImpl.UPDATE_BY_SCROLLING, 0, false); myShownStamp = System.currentTimeMillis(); } private int calcLookupStart() { int offset = myEditor.getSelectionModel().hasSelection() ? myEditor.getSelectionModel().getSelectionStart() : myEditor.getCaretModel().getOffset(); return offset - myMinPrefixLength; } private void selectMostPreferableItem(){ final int index = doSelectMostPreferableItem(((DefaultListModel)myList.getModel()).toArray()); myList.setSelectedIndex(index); if (index >= 0 && index < myList.getModel().getSize()){ ListScrollingUtil.selectItem(myList, index); } else if (!myItems.isEmpty()) { ListScrollingUtil.selectItem(myList, 0); } } @Nullable public LookupElement getCurrentItem(){ LookupElement item = (LookupElement)myList.getSelectedValue(); return item instanceof EmptyLookupItem ? null : item; } public void setCurrentItem(LookupElement item){ ListScrollingUtil.selectItem(myList, item); } public void addLookupListener(LookupListener listener){ myListeners.add(listener); } public void removeLookupListener(LookupListener listener){ myListeners.remove(listener); } public Rectangle getCurrentItemBounds(){ int index = myList.getSelectedIndex(); Rectangle itmBounds = myList.getCellBounds(index, index); if (itmBounds == null){ return null; } Rectangle listBounds=myList.getBounds(); final JRootPane pane = myList.getRootPane(); if (pane == null) { synchronized (myItems) { LOG.assertTrue(false, myItems); } } JLayeredPane layeredPane= pane.getLayeredPane(); Point layeredPanePoint=SwingUtilities.convertPoint(myList,listBounds.x,listBounds.y,layeredPane); itmBounds.x = layeredPanePoint.x; itmBounds.y = layeredPanePoint.y; return itmBounds; } public void fireItemSelected(final LookupElement item, char completionChar){ PsiDocumentManager.getInstance(myProject).commitAllDocuments(); if (item != null && myItemPreferencePolicy != null){ myItemPreferencePolicy.itemSelected(item, this); } if (!myListeners.isEmpty()){ LookupEvent event = new LookupEvent(this, item, completionChar); LookupListener[] listeners = myListeners.toArray(new LookupListener[myListeners.size()]); for (LookupListener listener : listeners) { try { listener.itemSelected(event); } catch (Throwable e) { LOG.error(e); } } } } private void fireLookupCanceled(){ if (!myListeners.isEmpty()){ LookupEvent event = new LookupEvent(this, null); LookupListener[] listeners = myListeners.toArray(new LookupListener[myListeners.size()]); for (LookupListener listener : listeners) { try { listener.lookupCanceled(event); } catch (Throwable e) { LOG.error(e); } } } } private void fireCurrentItemChanged(LookupElement item){ if (!myListeners.isEmpty()){ LookupEvent event = new LookupEvent(this, item); LookupListener[] listeners = myListeners.toArray(new LookupListener[myListeners.size()]); for (LookupListener listener : listeners) { listener.currentItemChanged(event); } } } private static int divideString(String lookupString, PrefixMatcher matcher) { for (int i = matcher.getPrefix().length(); i <= lookupString.length(); i++) { if (matcher.prefixMatches(lookupString.substring(0, i))) { return i; } } return -1; } public boolean fillInCommonPrefix(boolean explicitlyInvoked) { if (explicitlyInvoked && myCalculating) return false; if (!explicitlyInvoked && myDirty) return false; ListModel listModel = myList.getModel(); if (listModel.getSize() <= 1) return false; if (listModel.getSize() == 0) return false; final LookupElement firstItem = (LookupElement)listModel.getElementAt(0); if (listModel.getSize() == 1 && firstItem instanceof EmptyLookupItem) return false; final PrefixMatcher firstItemMatcher = firstItem.getPrefixMatcher(); final String oldPrefix = firstItemMatcher.getPrefix(); String presentPrefix = oldPrefix + myAdditionalPrefix; final PrefixMatcher matcher = firstItemMatcher.cloneWithPrefix(presentPrefix); String lookupString = firstItem.getLookupString(); int div = divideString(lookupString, matcher); if (div < 0) return false; String beforeCaret = lookupString.substring(0, div); String afterCaret = lookupString.substring(div); for (int i = 1; i < listModel.getSize(); i++) { LookupElement item = (LookupElement)listModel.getElementAt(i); if (!oldPrefix.equals(item.getPrefixMatcher().getPrefix())) return false; lookupString = item.getLookupString(); div = divideString(lookupString, item.getPrefixMatcher()); if (div < 0) return false; String _afterCaret = lookupString.substring(div); if (beforeCaret != null) { if (div != beforeCaret.length() || !lookupString.startsWith(beforeCaret)) { beforeCaret = null; } } while (afterCaret.length() > 0) { if (_afterCaret.startsWith(afterCaret)) { break; } afterCaret = afterCaret.substring(0, afterCaret.length() - 1); } if (afterCaret.length() == 0) return false; } if (myAdditionalPrefix.length() == 0 && myInitialPrefix == null && !explicitlyInvoked) { myInitialPrefix = presentPrefix; } else { myInitialPrefix = null; } EditorModificationUtil.deleteSelectedText(myEditor); int offset = myEditor.getCaretModel().getOffset(); if (beforeCaret != null) { // correct case, expand camel-humps final int start = offset - presentPrefix.length(); myInitialOffset = start + beforeCaret.length(); myEditor.getDocument().replaceString(start, offset, beforeCaret); presentPrefix = beforeCaret; } offset = myEditor.getCaretModel().getOffset(); myEditor.getDocument().insertString(offset, afterCaret); final String newPrefix = presentPrefix + afterCaret; synchronized (myItems) { for (Iterator<LookupElement> it = myItems.iterator(); it.hasNext();) { LookupElement item = it.next(); if (!item.setPrefixMatcher(item.getPrefixMatcher().cloneWithPrefix(newPrefix))) { it.remove(); } } myAdditionalPrefix = ""; updateList(); } offset += afterCaret.length(); myInitialOffset = offset; myEditor.getCaretModel().moveToOffset(offset); return true; } public PsiFile getPsiFile() { return PsiDocumentManager.getInstance(myEditor.getProject()).getPsiFile(myEditor.getDocument()); } public boolean isCompletion() { return myItemPreferencePolicy instanceof CompletionPreferencePolicy; } public PsiElement getPsiElement() { PsiFile file = getPsiFile(); if (file == null) return null; int offset = getLookupStart(); if (offset > 0) return file.findElementAt(offset - 1); return file.findElementAt(0); } public Editor getEditor() { return myEditor; } public boolean isPositionedAboveCaret(){ return myPositionedAbove != null && myPositionedAbove.booleanValue(); } public void hide(){ ApplicationManager.getApplication().assertIsDispatchThread(); //if (IdeEventQueue.getInstance().getPopupManager().closeAllPopups()) return; if (myDisposed) return; doHide(true); } private void doHide(final boolean fireCanceled) { assert !myDisposed; myHidden = true; super.hide(); Disposer.dispose(this); if (fireCanceled) { fireLookupCanceled(); } } public void restorePrefix() { if (myInitialPrefix != null) { new WriteCommandAction(myProject) { protected void run(Result result) throws Throwable { myEditor.getDocument() .replaceString(getLookupStart(), myEditor.getCaretModel().getOffset(), myInitialPrefix); } }.execute(); } } public void dispose() { assert myHidden; assert !myDisposed; myDisposed = true; myProcessIcon.dispose(); if (myEditorCaretListener != null) { myEditor.getCaretModel().removeCaretListener(myEditorCaretListener); myEditor.getSelectionModel().removeSelectionListener(myEditorSelectionListener); } if (myEditorMouseListener != null) { myEditor.removeEditorMouseListener(myEditorMouseListener); } } private int doSelectMostPreferableItem(Object[] items) { if (myItemPreferencePolicy == null){ return -1; } int prefItemIndex = -1; for(int i = 0; i < items.length; i++){ LookupElement item = (LookupElement)items[i]; final Object obj = item.getObject(); if (obj instanceof PsiElement && !((PsiElement)obj).isValid()) continue; if (prefItemIndex == -1) { prefItemIndex = i; } else { int d = myItemPreferencePolicy.compare(item, (LookupElement)items[prefItemIndex]); if (d < 0) { prefItemIndex = i; } } if (isExactPrefixItem(item)) { break; } } return prefItemIndex; } private boolean isExactPrefixItem(LookupElement item) { return item.getAllLookupStrings().contains(item.getPrefixMatcher().getPrefix() + myAdditionalPrefix); } public void adaptSize() { if (isVisible()) { HintManagerImpl.getInstanceImpl().adjustEditorHintPosition(this, myEditor, getComponent().getLocation()); } } public LookupElement[] getSortedItems() { synchronized (myItems) { final LookupElement[] result = new LookupElement[myList.getModel().getSize()]; ((DefaultListModel)myList.getModel()).copyInto(result); return result; } } }
lang-impl/src/com/intellij/codeInsight/lookup/impl/LookupImpl.java
package com.intellij.codeInsight.lookup.impl; import com.intellij.codeInsight.CodeInsightSettings; import com.intellij.codeInsight.completion.CompletionPreferencePolicy; import com.intellij.codeInsight.completion.PrefixMatcher; import com.intellij.codeInsight.completion.impl.CamelHumpMatcher; import com.intellij.codeInsight.hint.HintManagerImpl; import com.intellij.codeInsight.hint.HintUtil; import com.intellij.codeInsight.lookup.*; import com.intellij.featureStatistics.FeatureUsageTracker; import com.intellij.lang.LangBundle; import com.intellij.openapi.Disposable; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.application.Result; import com.intellij.openapi.command.CommandProcessor; import com.intellij.openapi.command.WriteCommandAction; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.editor.*; import com.intellij.openapi.editor.event.*; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.Disposer; import com.intellij.openapi.util.Key; import com.intellij.psi.PsiDocumentManager; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiFile; import com.intellij.psi.util.proximity.PsiProximityComparator; import com.intellij.ui.LightweightHint; import com.intellij.ui.ListScrollingUtil; import com.intellij.ui.plaf.beg.BegPopupMenuBorder; import com.intellij.util.SmartList; import com.intellij.util.containers.SortedList; import com.intellij.util.ui.AsyncProcessIcon; import gnu.trove.THashSet; import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.TestOnly; import javax.swing.*; import javax.swing.event.ListSelectionEvent; import javax.swing.event.ListSelectionListener; import java.awt.*; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.util.*; import java.util.List; public class LookupImpl extends LightweightHint implements Lookup, Disposable { private static final Logger LOG = Logger.getInstance("#com.intellij.codeInsight.lookup.impl.LookupImpl"); private static final int MAX_PREFERRED_COUNT = 5; private static final LookupItem EMPTY_LOOKUP_ITEM = new LookupItem("preselect", "preselect"); private static final Key<Boolean> USED_LOOKUP_ELEMENT = Key.create("USED_LOOKUP_ELEMENT"); private final Project myProject; private final Editor myEditor; private final SortedList<LookupElement> myItems; private final SortedMap<LookupItemWeightComparable, SortedList<LookupElement>> myItemsMap; private int myMinPrefixLength; private int myPreferredItemsCount; private int myInitialOffset; private long myShownStamp = -1; private String myInitialPrefix; @Nullable private final LookupItemPreferencePolicy myItemPreferencePolicy; private RangeMarker myLookupStartMarker; private final JList myList; private final LookupCellRenderer myCellRenderer; private Boolean myPositionedAbove = null; private CaretListener myEditorCaretListener; private SelectionListener myEditorSelectionListener; private EditorMouseListener myEditorMouseListener; private final ArrayList<LookupListener> myListeners = new ArrayList<LookupListener>(); private boolean myDisposed = false; private boolean myHidden = false; private LookupElement myPreselectedItem = EMPTY_LOOKUP_ITEM; private boolean myDirty; private String myAdditionalPrefix = ""; private PsiElement myElement; private final AsyncProcessIcon myProcessIcon; private final Comparator<LookupElement> myComparator; private volatile boolean myCalculating; private final JLabel myAdComponent; private volatile String myAdText; private volatile int myLookupWidth = 50; public LookupImpl(Project project, Editor editor, LookupElement[] items, @Nullable LookupItemPreferencePolicy itemPreferencePolicy){ super(new JPanel(new BorderLayout())); myProject = project; myEditor = editor; myItemPreferencePolicy = itemPreferencePolicy; myInitialOffset = myEditor.getSelectionModel().hasSelection() ? myEditor.getSelectionModel().getSelectionStart() : myEditor.getCaretModel().getOffset(); final Document document = myEditor.getDocument(); final PsiFile psiFile = PsiDocumentManager.getInstance(myProject).getPsiFile(document); myElement = psiFile == null ? null : psiFile.findElementAt(myEditor.getCaretModel().getOffset()); final PsiProximityComparator proximityComparator = new PsiProximityComparator(myElement == null ? psiFile : myElement); myComparator = new Comparator<LookupElement>() { public int compare(LookupElement o1, LookupElement o2) { if (o1 instanceof LookupItem && o2 instanceof LookupItem) { double priority1 = ((LookupItem)o1).getPriority(); double priority2 = ((LookupItem)o2).getPriority(); if (priority1 > priority2) return -1; if (priority2 > priority1) return 1; int grouping1 = ((LookupItem)o1).getGrouping(); int grouping2 = ((LookupItem)o2).getGrouping(); if (grouping1 > grouping2) return -1; if (grouping2 > grouping1) return 1; } int stringCompare = o1.getLookupString().compareToIgnoreCase(o2.getLookupString()); if (stringCompare != 0) return stringCompare; return proximityComparator.compare(o1.getObject(), o2.getObject()); } }; myItems = new SortedList<LookupElement>(myComparator); myItemsMap = new TreeMap<LookupItemWeightComparable, SortedList<LookupElement>>(); myProcessIcon = new AsyncProcessIcon("Completion progress"); myProcessIcon.setVisible(false); myList = new JList(new DefaultListModel()); myCellRenderer = new LookupCellRenderer(this); myList.setCellRenderer(myCellRenderer); for (final LookupElement item : items) { addItem(item); } myList.setFocusable(false); myList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); myList.setBackground(LookupCellRenderer.BACKGROUND_COLOR); JScrollPane scrollPane = new JScrollPane(myList); scrollPane.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER); getComponent().add(scrollPane, BorderLayout.NORTH); scrollPane.setBorder(null); JPanel bottomPanel = new JPanel(new BorderLayout()); bottomPanel.add(myProcessIcon, BorderLayout.EAST); myAdComponent = HintUtil.createAdComponent(null); bottomPanel.add(myAdComponent, BorderLayout.CENTER); getComponent().add(bottomPanel, BorderLayout.SOUTH); getComponent().setBorder(new BegPopupMenuBorder()); updateList(); selectMostPreferableItem(); } public AsyncProcessIcon getProcessIcon() { return myProcessIcon; } public boolean isCalculating() { return myCalculating; } public void setCalculating(final boolean calculating) { myCalculating = calculating; } public int getPreferredItemsCount() { return myPreferredItemsCount; } public void markDirty() { myDirty = true; myPreselectedItem = null; } @TestOnly public void resort() { final ArrayList<LookupElement> items = new ArrayList<LookupElement>(myItems); myDirty = false; myPreselectedItem = EMPTY_LOOKUP_ITEM; myItemsMap.clear(); myItems.clear(); for (final LookupElement item : items) { item.putUserData(USED_LOOKUP_ELEMENT, null); addItem(item); } updateList(); } public void addItem(LookupElement item) { if (item.getUserData(USED_LOOKUP_ELEMENT) != null) { LOG.assertTrue(false, "An attempt to reuse lookup item detected. Giving the same lookup element instance to more than one lookup or completion process is prohibited: item=" + item); } item.putUserData(USED_LOOKUP_ELEMENT, Boolean.TRUE); synchronized (myItems) { myItems.add(item); addItemWeight(item); } int maxWidth = myCellRenderer.updateMaximumWidth(item); myLookupWidth = Math.max(maxWidth, myLookupWidth); } private void addItemWeight(final LookupElement item) { final Comparable[] weight = getWeight(myItemPreferencePolicy, myElement, item); final LookupItemWeightComparable key = new LookupItemWeightComparable(item instanceof LookupItem ? ((LookupItem)item).getPriority() : 0, weight); SortedList<LookupElement> list = myItemsMap.get(key); if (list == null) myItemsMap.put(key, list = new SortedList<LookupElement>(myComparator)); list.add(item); } @Nullable public LookupItemPreferencePolicy getItemPreferencePolicy() { return myItemPreferencePolicy; } private static Comparable[] getWeight(final LookupItemPreferencePolicy itemPreferencePolicy, final PsiElement context, final LookupElement item) { if (itemPreferencePolicy instanceof CompletionPreferencePolicy) { return ((CompletionPreferencePolicy)itemPreferencePolicy).getWeight(item); } Comparable i = null; if (item.getObject() instanceof PsiElement) { i = PsiProximityComparator.getProximity((PsiElement)item.getObject(), context); } return new Comparable[]{i}; } public int getMinPrefixLength() { return myMinPrefixLength; } public JList getList() { return myList; } public LookupElement[] getItems(){ synchronized (myItems) { return myItems.toArray(new LookupElement[myItems.size()]); } } public void setAdvertisementText(@Nullable String text) { myAdText = text; } public String getAdvertisementText() { return myAdText; } public String getAdditionalPrefix() { return myAdditionalPrefix; } public void setAdditionalPrefix(final String additionalPrefix) { myAdditionalPrefix = additionalPrefix; myInitialPrefix = null; markDirty(); updateList(); } public final void updateList() { synchronized (myItems) { int minPrefixLength = myItems.isEmpty() ? 0 : Integer.MAX_VALUE; for (final LookupElement item : myItems) { minPrefixLength = Math.min(item.getPrefixMatcher().getPrefix().length(), minPrefixLength); } if (myMinPrefixLength != minPrefixLength) { myLookupStartMarker = null; } myMinPrefixLength = minPrefixLength; Object oldSelected = !myDirty ? null : myList.getSelectedValue(); DefaultListModel model = (DefaultListModel)myList.getModel(); model.clear(); Set<LookupElement> firstItems = new THashSet<LookupElement>(); addExactPrefixItems(model, firstItems); boolean hasExactPrefixes = !firstItems.isEmpty(); addMostRelevantItems(model, firstItems); final boolean hasPreselectedItem = addPreselectedItem(model, firstItems); myPreferredItemsCount = firstItems.size(); addRemainingItemsLexicographically(model, firstItems); boolean isEmpty = model.getSize() == 0; if (isEmpty) { addEmptyItem(model); } else { myList.setFixedCellWidth(myLookupWidth); } myList.setFixedCellHeight(myCellRenderer.getListCellRendererComponent(myList, myList.getModel().getElementAt(0), 0, false, false).getPreferredSize().height); myList.setVisibleRowCount(Math.min(myList.getModel().getSize(), CodeInsightSettings.getInstance().LOOKUP_HEIGHT)); myAdComponent.setText(myAdText); if (!isEmpty) { if (oldSelected != null) { if (!ListScrollingUtil.selectItem(myList, oldSelected)) { selectMostPreferableItem(); } } else { if (myPreselectedItem == EMPTY_LOOKUP_ITEM) { selectMostPreferableItem(); myPreselectedItem = getCurrentItem(); } else if (hasPreselectedItem && !hasExactPrefixes) { ListScrollingUtil.selectItem(myList, myPreselectedItem); } else { selectMostPreferableItem(); } } } } } private void addEmptyItem(DefaultListModel model) { LookupItem<String> item = new EmptyLookupItem(myCalculating ? " " : LangBundle.message("completion.no.suggestions")); item.setPrefixMatcher(new CamelHumpMatcher("")); if (!myCalculating) { final int maxWidth = myCellRenderer.updateMaximumWidth(item); myList.setFixedCellWidth(Math.max(maxWidth, myLookupWidth)); } model.addElement(item); } private void addRemainingItemsLexicographically(DefaultListModel model, Set<LookupElement> firstItems) { for (LookupElement item : myItems) { if (!firstItems.contains(item) && prefixMatches(item)) { model.addElement(item); } } } private boolean addPreselectedItem(DefaultListModel model, Set<LookupElement> firstItems) { final boolean hasPreselectedItem = !myDirty && myPreselectedItem != EMPTY_LOOKUP_ITEM; if (hasPreselectedItem && !firstItems.contains(myPreselectedItem)) { firstItems.add(myPreselectedItem); model.addElement(myPreselectedItem); } return hasPreselectedItem; } private void addMostRelevantItems(DefaultListModel model, Set<LookupElement> firstItems) { for (final LookupItemWeightComparable comparable : myItemsMap.keySet()) { final List<LookupElement> suitable = new SmartList<LookupElement>(); for (final LookupElement item : myItemsMap.get(comparable)) { if (!firstItems.contains(item) && prefixMatches(item)) { suitable.add(item); } } if (firstItems.size() + suitable.size() > MAX_PREFERRED_COUNT) break; for (final LookupElement item : suitable) { firstItems.add(item); model.addElement(item); } } } private void addExactPrefixItems(DefaultListModel model, Set<LookupElement> firstItems) { for (final LookupItemWeightComparable comparable : myItemsMap.keySet()) { for (final LookupElement item : myItemsMap.get(comparable)) { if (isExactPrefixItem(item)) { model.addElement(item); firstItems.add(item); } } } } private boolean prefixMatches(final LookupElement item) { if (myAdditionalPrefix.length() == 0) return item.isPrefixMatched(); return item.getPrefixMatcher().cloneWithPrefix(item.getPrefixMatcher().getPrefix() + myAdditionalPrefix).prefixMatches(item); } /** * @return point in layered pane coordinate system. */ public Point calculatePosition(){ Dimension dim = getComponent().getPreferredSize(); int lookupStart = getLookupStart(); LogicalPosition pos = myEditor.offsetToLogicalPosition(lookupStart); Point location = myEditor.logicalPositionToXY(pos); location.y += myEditor.getLineHeight(); JComponent editorComponent = myEditor.getComponent(); JComponent internalComponent = myEditor.getContentComponent(); final JRootPane rootPane = editorComponent.getRootPane(); if (rootPane == null) { synchronized (myItems) { LOG.assertTrue(false, myItems); } } JLayeredPane layeredPane = rootPane.getLayeredPane(); Point layeredPanePoint=SwingUtilities.convertPoint(internalComponent,location, layeredPane); layeredPanePoint.x -= myCellRenderer.getIconIndent(); if (dim.width > layeredPane.getWidth()){ dim.width = layeredPane.getWidth(); } int wshift = layeredPane.getWidth() - (layeredPanePoint.x + dim.width); if (wshift < 0){ layeredPanePoint.x += wshift; } int shiftLow = layeredPane.getHeight() - (layeredPanePoint.y + dim.height); int shiftHigh = layeredPanePoint.y - dim.height; myPositionedAbove = shiftLow < 0 && shiftLow < shiftHigh ? Boolean.TRUE : Boolean.FALSE; if (myPositionedAbove.booleanValue()){ layeredPanePoint.y -= dim.height + myEditor.getLineHeight(); } return layeredPanePoint; } public void finishLookup(final char completionChar) { if (myShownStamp > 0 && System.currentTimeMillis() - myShownStamp < 239 && !ApplicationManager.getApplication().isUnitTestMode()) { return; } final LookupElement item = (LookupElement)myList.getSelectedValue(); doHide(false); if (item == null || item instanceof EmptyLookupItem || item.getObject() instanceof DeferredUserLookupValue && item instanceof LookupItem && !((DeferredUserLookupValue)item.getObject()).handleUserSelection((LookupItem)item, myProject)) { fireItemSelected(null, completionChar); return; } ApplicationManager.getApplication().runWriteAction(new Runnable() { public void run() { EditorModificationUtil.deleteSelectedText(myEditor); final int caretOffset = myEditor.getCaretModel().getOffset(); final String prefix = item.getPrefixMatcher().getPrefix(); int lookupStart = caretOffset - prefix.length() - myAdditionalPrefix.length(); final String lookupString = item.getLookupString(); if (!lookupString.startsWith(prefix + myAdditionalPrefix)) { FeatureUsageTracker.getInstance().triggerFeatureUsed("editing.completion.camelHumps"); } myEditor.getDocument().replaceString(lookupStart, caretOffset, lookupString); int offset = lookupStart + lookupString.length(); myEditor.getCaretModel().moveToOffset(offset); myEditor.getScrollingModel().scrollToCaret(ScrollType.RELATIVE); myEditor.getSelectionModel().removeSelection(); } }); fireItemSelected(item, completionChar); } public int getLookupStart() { return myLookupStartMarker != null ? myLookupStartMarker.getStartOffset() : calcLookupStart(); } public void show(){ assert !myDisposed; int lookupStart = calcLookupStart(); myLookupStartMarker = myEditor.getDocument().createRangeMarker(lookupStart, lookupStart); myLookupStartMarker.setGreedyToLeft(true); myEditor.getDocument().addDocumentListener(new DocumentAdapter() { public void documentChanged(DocumentEvent e) { if (myLookupStartMarker != null && !myLookupStartMarker.isValid()){ hide(); } } }, this); myEditorCaretListener = new CaretListener() { public void caretPositionChanged(CaretEvent e){ int curOffset = myEditor.getCaretModel().getOffset(); if (curOffset != myInitialOffset + myAdditionalPrefix.length()) { hide(); } } }; myEditorSelectionListener = new SelectionListener() { public void selectionChanged(final SelectionEvent e) { if (!e.getNewRange().isEmpty()) { hide(); } } }; myEditor.getCaretModel().addCaretListener(myEditorCaretListener); myEditor.getSelectionModel().addSelectionListener(myEditorSelectionListener); myEditorMouseListener = new EditorMouseAdapter() { public void mouseClicked(EditorMouseEvent e){ e.consume(); hide(); } }; myEditor.addEditorMouseListener(myEditorMouseListener); myList.addListSelectionListener(new ListSelectionListener() { private LookupElement oldItem = null; public void valueChanged(ListSelectionEvent e){ LookupElement item = getCurrentItem(); if (oldItem != item) { fireCurrentItemChanged(item); } oldItem = item; } }); myList.addMouseListener(new MouseAdapter() { public void mouseClicked(MouseEvent e){ if (e.getClickCount() == 2){ CommandProcessor.getInstance().executeCommand(myProject, new Runnable() { public void run() { finishLookup(NORMAL_SELECT_CHAR); } }, "", null); } } }); if (ApplicationManager.getApplication().isUnitTestMode()) return; Point p = calculatePosition(); HintManagerImpl hintManager = HintManagerImpl.getInstanceImpl(); hintManager.showEditorHint(this, myEditor, p, HintManagerImpl.HIDE_BY_ESCAPE | HintManagerImpl.UPDATE_BY_SCROLLING, 0, false); myShownStamp = System.currentTimeMillis(); } private int calcLookupStart() { int offset = myEditor.getSelectionModel().hasSelection() ? myEditor.getSelectionModel().getSelectionStart() : myEditor.getCaretModel().getOffset(); return offset - myMinPrefixLength; } private void selectMostPreferableItem(){ final int index = doSelectMostPreferableItem(((DefaultListModel)myList.getModel()).toArray()); myList.setSelectedIndex(index); if (index >= 0 && index < myList.getModel().getSize()){ ListScrollingUtil.selectItem(myList, index); } else if (!myItems.isEmpty()) { ListScrollingUtil.selectItem(myList, 0); } } @Nullable public LookupElement getCurrentItem(){ LookupElement item = (LookupElement)myList.getSelectedValue(); return item instanceof EmptyLookupItem ? null : item; } public void setCurrentItem(LookupElement item){ ListScrollingUtil.selectItem(myList, item); } public void addLookupListener(LookupListener listener){ myListeners.add(listener); } public void removeLookupListener(LookupListener listener){ myListeners.remove(listener); } public Rectangle getCurrentItemBounds(){ int index = myList.getSelectedIndex(); Rectangle itmBounds = myList.getCellBounds(index, index); if (itmBounds == null){ return null; } Rectangle listBounds=myList.getBounds(); final JRootPane pane = myList.getRootPane(); if (pane == null) { synchronized (myItems) { LOG.assertTrue(false, myItems); } } JLayeredPane layeredPane= pane.getLayeredPane(); Point layeredPanePoint=SwingUtilities.convertPoint(myList,listBounds.x,listBounds.y,layeredPane); itmBounds.x = layeredPanePoint.x; itmBounds.y = layeredPanePoint.y; return itmBounds; } public void fireItemSelected(final LookupElement item, char completionChar){ PsiDocumentManager.getInstance(myProject).commitAllDocuments(); if (item != null && myItemPreferencePolicy != null){ myItemPreferencePolicy.itemSelected(item, this); } if (!myListeners.isEmpty()){ LookupEvent event = new LookupEvent(this, item, completionChar); LookupListener[] listeners = myListeners.toArray(new LookupListener[myListeners.size()]); for (LookupListener listener : listeners) { try { listener.itemSelected(event); } catch (Throwable e) { LOG.error(e); } } } } private void fireLookupCanceled(){ if (!myListeners.isEmpty()){ LookupEvent event = new LookupEvent(this, null); LookupListener[] listeners = myListeners.toArray(new LookupListener[myListeners.size()]); for (LookupListener listener : listeners) { try { listener.lookupCanceled(event); } catch (Throwable e) { LOG.error(e); } } } } private void fireCurrentItemChanged(LookupElement item){ if (!myListeners.isEmpty()){ LookupEvent event = new LookupEvent(this, item); LookupListener[] listeners = myListeners.toArray(new LookupListener[myListeners.size()]); for (LookupListener listener : listeners) { listener.currentItemChanged(event); } } } private static int divideString(String lookupString, PrefixMatcher matcher) { for (int i = matcher.getPrefix().length(); i <= lookupString.length(); i++) { if (matcher.prefixMatches(lookupString.substring(0, i))) { return i; } } return -1; } public boolean fillInCommonPrefix(boolean explicitlyInvoked) { if (explicitlyInvoked && myCalculating) return false; if (!explicitlyInvoked && myDirty) return false; ListModel listModel = myList.getModel(); if (listModel.getSize() <= 1) return false; if (listModel.getSize() == 0) return false; final LookupElement firstItem = (LookupElement)listModel.getElementAt(0); if (listModel.getSize() == 1 && firstItem instanceof EmptyLookupItem) return false; final PrefixMatcher firstItemMatcher = firstItem.getPrefixMatcher(); final String oldPrefix = firstItemMatcher.getPrefix(); String presentPrefix = oldPrefix + myAdditionalPrefix; final PrefixMatcher matcher = firstItemMatcher.cloneWithPrefix(presentPrefix); String lookupString = firstItem.getLookupString(); int div = divideString(lookupString, matcher); if (div < 0) return false; String beforeCaret = lookupString.substring(0, div); String afterCaret = lookupString.substring(div); for (int i = 1; i < listModel.getSize(); i++) { LookupElement item = (LookupElement)listModel.getElementAt(i); if (!oldPrefix.equals(item.getPrefixMatcher().getPrefix())) return false; lookupString = item.getLookupString(); div = divideString(lookupString, item.getPrefixMatcher()); if (div < 0) return false; String _afterCaret = lookupString.substring(div); if (beforeCaret != null) { if (div != beforeCaret.length() || !lookupString.startsWith(beforeCaret)) { beforeCaret = null; } } while (afterCaret.length() > 0) { if (_afterCaret.startsWith(afterCaret)) { break; } afterCaret = afterCaret.substring(0, afterCaret.length() - 1); } if (afterCaret.length() == 0) return false; } if (myAdditionalPrefix.length() == 0 && myInitialPrefix == null && !explicitlyInvoked) { myInitialPrefix = presentPrefix; } else { myInitialPrefix = null; } EditorModificationUtil.deleteSelectedText(myEditor); int offset = myEditor.getCaretModel().getOffset(); if (beforeCaret != null) { // correct case, expand camel-humps final int start = offset - presentPrefix.length(); myInitialOffset = start + beforeCaret.length(); myEditor.getDocument().replaceString(start, offset, beforeCaret); presentPrefix = beforeCaret; } offset = myEditor.getCaretModel().getOffset(); myEditor.getDocument().insertString(offset, afterCaret); final String newPrefix = presentPrefix + afterCaret; synchronized (myItems) { for (Iterator<LookupElement> it = myItems.iterator(); it.hasNext();) { LookupElement item = it.next(); if (!item.setPrefixMatcher(item.getPrefixMatcher().cloneWithPrefix(newPrefix))) { it.remove(); } } myAdditionalPrefix = ""; updateList(); } offset += afterCaret.length(); myInitialOffset = offset; myEditor.getCaretModel().moveToOffset(offset); return true; } public PsiFile getPsiFile() { return PsiDocumentManager.getInstance(myEditor.getProject()).getPsiFile(myEditor.getDocument()); } public boolean isCompletion() { return myItemPreferencePolicy instanceof CompletionPreferencePolicy; } public PsiElement getPsiElement() { PsiFile file = getPsiFile(); if (file == null) return null; int offset = getLookupStart(); if (offset > 0) return file.findElementAt(offset - 1); return file.findElementAt(0); } public Editor getEditor() { return myEditor; } public boolean isPositionedAboveCaret(){ return myPositionedAbove != null && myPositionedAbove.booleanValue(); } public void hide(){ ApplicationManager.getApplication().assertIsDispatchThread(); //if (IdeEventQueue.getInstance().getPopupManager().closeAllPopups()) return; if (myDisposed) return; doHide(true); } private void doHide(final boolean fireCanceled) { assert !myDisposed; myHidden = true; super.hide(); Disposer.dispose(this); if (fireCanceled) { fireLookupCanceled(); } } public void restorePrefix() { if (myInitialPrefix != null) { new WriteCommandAction(myProject) { protected void run(Result result) throws Throwable { myEditor.getDocument() .replaceString(getLookupStart(), myEditor.getCaretModel().getOffset(), myInitialPrefix); } }.execute(); } } public void dispose() { assert myHidden; assert !myDisposed; myDisposed = true; myProcessIcon.dispose(); if (myEditorCaretListener != null) { myEditor.getCaretModel().removeCaretListener(myEditorCaretListener); myEditor.getSelectionModel().removeSelectionListener(myEditorSelectionListener); } if (myEditorMouseListener != null) { myEditor.removeEditorMouseListener(myEditorMouseListener); } } private int doSelectMostPreferableItem(Object[] items) { if (myItemPreferencePolicy == null){ return -1; } int prefItemIndex = -1; for(int i = 0; i < items.length; i++){ LookupElement item = (LookupElement)items[i]; final Object obj = item.getObject(); if (obj instanceof PsiElement && !((PsiElement)obj).isValid()) continue; if (prefItemIndex == -1) { prefItemIndex = i; } else { int d = myItemPreferencePolicy.compare(item, (LookupElement)items[prefItemIndex]); if (d < 0) { prefItemIndex = i; } } if (isExactPrefixItem(item)) { break; } } return prefItemIndex; } private boolean isExactPrefixItem(LookupElement item) { return item.getAllLookupStrings().contains(item.getPrefixMatcher().getPrefix() + myAdditionalPrefix); } public void adaptSize() { if (isVisible()) { HintManagerImpl.getInstanceImpl().adjustEditorHintPosition(this, myEditor, getComponent().getLocation()); } } public LookupElement[] getSortedItems() { synchronized (myItems) { final LookupElement[] result = new LookupElement[myList.getModel().getSize()]; ((DefaultListModel)myList.getModel()).copyInto(result); return result; } } }
fix nik
lang-impl/src/com/intellij/codeInsight/lookup/impl/LookupImpl.java
fix nik
<ide><path>ang-impl/src/com/intellij/codeInsight/lookup/impl/LookupImpl.java <ide> <ide> if (!isEmpty) { <ide> if (oldSelected != null) { <del> if (!ListScrollingUtil.selectItem(myList, oldSelected)) { <add> if (hasExactPrefixes || !ListScrollingUtil.selectItem(myList, oldSelected)) { <ide> selectMostPreferableItem(); <ide> } <del> } else { <add> } <add> else { <ide> if (myPreselectedItem == EMPTY_LOOKUP_ITEM) { <ide> selectMostPreferableItem(); <ide> myPreselectedItem = getCurrentItem(); <del> } else if (hasPreselectedItem && !hasExactPrefixes) { <add> } <add> else if (hasPreselectedItem && !hasExactPrefixes) { <ide> ListScrollingUtil.selectItem(myList, myPreselectedItem); <del> } else { <add> } <add> else { <ide> selectMostPreferableItem(); <ide> } <ide> }
Java
apache-2.0
8ef0abda48c40aa40481ae0f018b8380d2a4b61d
0
orientechnologies/orientdb,orientechnologies/orientdb,orientechnologies/orientdb,orientechnologies/orientdb
/* * * * Copyright 2010-2016 OrientDB LTD (http://orientdb.com) * * * * 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. * * * * For more information: http://orientdb.com * */ package com.orientechnologies.orient.core.storage.impl.local.paginated; import com.orientechnologies.common.io.OIOUtils; import com.orientechnologies.common.log.OLogManager; import com.orientechnologies.orient.core.config.OGlobalConfiguration; import com.orientechnologies.orient.core.exception.OStorageException; import net.jpountz.xxhash.XXHash64; import net.jpountz.xxhash.XXHashFactory; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.channels.FileChannel; import java.nio.channels.FileLock; import java.nio.channels.OverlappingFileLockException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.StandardOpenOption; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; import java.util.zip.ZipEntry; import java.util.zip.ZipOutputStream; /** * @author Andrey Lomakin (a.lomakin-at-orientdb.com) * @since 5/6/14 */ public class StorageStartupMetadata { private static final long XX_HASH_SEED = 0xADF678FE45L; private static final XXHash64 XX_HASH_64; private static final int XX_HASH_OFFSET = 0; private static final int VERSION_OFFSET = XX_HASH_OFFSET + 8; private static final int DIRTY_FLAG_OFFSET = VERSION_OFFSET + 4; private static final int TRANSACTION_ID_OFFSET = DIRTY_FLAG_OFFSET + 1; private static final int METADATA_LEN_OFFSET = TRANSACTION_ID_OFFSET + 8; static { final XXHashFactory xxHashFactory = XXHashFactory.fastestInstance(); XX_HASH_64 = xxHashFactory.hash64(); } private static final int VERSION = 3; private final Path filePath; private FileChannel channel; private FileLock fileLock; private volatile boolean dirtyFlag; private volatile long lastTxId; private volatile byte[] txMetadata; private final Lock lock = new ReentrantLock(); public void addFileToArchive(ZipOutputStream zos, String name) throws IOException { final ZipEntry ze = new ZipEntry(name); zos.putNextEntry(ze); try { final ByteBuffer byteBuffer = serialize(); byteBuffer.put(DIRTY_FLAG_OFFSET, (byte) 0); zos.write(byteBuffer.array()); } finally { zos.closeEntry(); } } public StorageStartupMetadata(Path filePath) { this.filePath = filePath; } public void create() throws IOException { lock.lock(); try { if (Files.exists(filePath)) { Files.delete(filePath); } channel = FileChannel .open(filePath, StandardOpenOption.READ, StandardOpenOption.CREATE, StandardOpenOption.WRITE, StandardOpenOption.SYNC); if (OGlobalConfiguration.FILE_LOCK.getValueAsBoolean()) { lockFile(); } final ByteBuffer buffer = ByteBuffer.allocate(1 + 8 + 8 + 4 + 4);//version + dirty flag + transaction id + tx metadata len buffer.position(8); buffer.putInt(VERSION); //dirty flag buffer.put((byte) 1); //transaction id buffer.putLong(-1); //tx metadata len buffer.putInt(-1); final long xxHash = XX_HASH_64.hash(buffer, 8, buffer.capacity() - 8, XX_HASH_SEED); buffer.putLong(0, xxHash); buffer.rewind(); OIOUtils.writeByteBuffer(buffer, channel, 0); dirtyFlag = true; lastTxId = -1; } finally { lock.unlock(); } } private void lockFile() throws IOException { try { fileLock = channel.tryLock(); } catch (OverlappingFileLockException e) { OLogManager.instance().warn(this, "File is already locked by other thread", e); } if (fileLock == null) throw new OStorageException("Database is locked by another process, please shutdown process and try again"); } public boolean exists() { lock.lock(); try { return Files.exists(filePath); } finally { lock.unlock(); } } public void open() throws IOException { lock.lock(); try { if (!Files.exists(filePath)) { OLogManager.instance().infoNoDb(this, "File with startup metadata does not exist, creating new one"); create(); return; } else { channel = FileChannel .open(filePath, StandardOpenOption.SYNC, StandardOpenOption.WRITE, StandardOpenOption.READ, StandardOpenOption.CREATE); final long size = channel.size(); if (size < 9) { ByteBuffer buffer = ByteBuffer.allocate(1); OIOUtils.readByteBuffer(buffer, channel, 0, true); buffer.position(0); dirtyFlag = buffer.get() > 0; } else if (size == 9) { ByteBuffer buffer = ByteBuffer.allocate(8 + 1); OIOUtils.readByteBuffer(buffer, channel, 0, true); buffer.position(0); dirtyFlag = buffer.get() > 0; lastTxId = buffer.getLong(); } else { final ByteBuffer buffer = ByteBuffer.allocate((int) size); OIOUtils.readByteBuffer(buffer, channel); buffer.rewind(); final long xxHash = XX_HASH_64.hash(buffer, 8, buffer.capacity() - 8, XX_HASH_SEED); if (xxHash != buffer.getLong(0)) { OLogManager.instance().error(this, "File with startup metadata is broken and can not be used, creation new one", null); channel.close(); create(); return; } buffer.position(8); final int version = buffer.getInt(); if (version != VERSION) { throw new IllegalStateException( "Invalid version of the binary format of startup metadata file found " + version + " but expected " + VERSION); } dirtyFlag = buffer.get() > 0; lastTxId = buffer.getLong(); final int metadataLen = buffer.getInt(); if (metadataLen > 0) { final byte[] txMeta = new byte[metadataLen]; buffer.get(txMeta); txMetadata = txMeta; } } } if (OGlobalConfiguration.FILE_LOCK.getValueAsBoolean()) { lockFile(); } } finally { lock.unlock(); } } public void close() throws IOException { lock.lock(); try { if (channel == null) return; if (Files.exists(filePath)) { if (fileLock != null) { fileLock.release(); fileLock = null; } channel.close(); channel = null; } } finally { lock.unlock(); } } public void delete() throws IOException { lock.lock(); try { if (channel == null) return; if (Files.exists(filePath)) { if (fileLock != null) { fileLock.release(); fileLock = null; } channel.close(); channel = null; Files.delete(filePath); } } finally { lock.unlock(); } } public void makeDirty() throws IOException { if (dirtyFlag) return; lock.lock(); try { if (dirtyFlag) return; dirtyFlag = true; OIOUtils.writeByteBuffer(serialize(), channel, 0); } finally { lock.unlock(); } } public void clearDirty() throws IOException { if (!dirtyFlag) return; lock.lock(); try { if (!dirtyFlag) return; dirtyFlag = false; OIOUtils.writeByteBuffer(serialize(), channel, 0); } finally { lock.unlock(); } } public void setLastTxId(long lastTxId) throws IOException { lock.lock(); try { this.lastTxId = lastTxId; OIOUtils.writeByteBuffer(serialize(), channel, 0); } finally { lock.unlock(); } } public void setTxMetadata(final byte[] txMetadata) throws IOException { lock.lock(); try { this.txMetadata = txMetadata; OIOUtils.writeByteBuffer(serialize(), channel, 0); } finally { lock.unlock(); } } public boolean isDirty() { return dirtyFlag; } public long getLastTxId() { return lastTxId; } public byte[] getTxMetadata() { return txMetadata; } private ByteBuffer serialize() { final ByteBuffer buffer; if (txMetadata == null) { buffer = ByteBuffer.allocate(8 + 4 + 1 + 8 + 4); } else { buffer = ByteBuffer.allocate(8 + 4 + 1 + 8 + 4 + txMetadata.length); } buffer.position(8); buffer.putInt(VERSION); //dirty flag buffer.put(dirtyFlag ? (byte) 1 : (byte) 0); //transaction id buffer.putLong(lastTxId); //tx metadata if (txMetadata == null) { buffer.putInt(-1); } else { buffer.putInt(txMetadata.length); buffer.put(txMetadata); } final long xxHash = XX_HASH_64.hash(buffer, 8, buffer.capacity() - 8, XX_HASH_SEED); buffer.putLong(0, xxHash); buffer.rewind(); return buffer; } }
core/src/main/java/com/orientechnologies/orient/core/storage/impl/local/paginated/StorageStartupMetadata.java
/* * * * Copyright 2010-2016 OrientDB LTD (http://orientdb.com) * * * * 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. * * * * For more information: http://orientdb.com * */ package com.orientechnologies.orient.core.storage.impl.local.paginated; import com.orientechnologies.common.io.OIOUtils; import com.orientechnologies.common.log.OLogManager; import com.orientechnologies.orient.core.config.OGlobalConfiguration; import com.orientechnologies.orient.core.exception.OStorageException; import net.jpountz.xxhash.XXHash64; import net.jpountz.xxhash.XXHashFactory; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.channels.FileChannel; import java.nio.channels.FileLock; import java.nio.channels.OverlappingFileLockException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.StandardOpenOption; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; import java.util.zip.ZipEntry; import java.util.zip.ZipOutputStream; /** * @author Andrey Lomakin (a.lomakin-at-orientdb.com) * @since 5/6/14 */ public class StorageStartupMetadata { private static final long XX_HASH_SEED = 0xADF678FE45L; private static final XXHash64 XX_HASH_64; private static final int XX_HASH_OFFSET = 0; private static final int VERSION_OFFSET = XX_HASH_OFFSET + 8; private static final int DIRTY_FLAG_OFFSET = VERSION_OFFSET + 4; private static final int TRANSACTION_ID_OFFSET = DIRTY_FLAG_OFFSET + 1; private static final int METADATA_LEN_OFFSET = TRANSACTION_ID_OFFSET + 8; static { final XXHashFactory xxHashFactory = XXHashFactory.fastestInstance(); XX_HASH_64 = xxHashFactory.hash64(); } private static final int VERSION = 3; private final Path filePath; private FileChannel channel; private FileLock fileLock; private volatile boolean dirtyFlag; private volatile long lastTxId; private volatile byte[] txMetadata; private final Lock lock = new ReentrantLock(); public void addFileToArchive(ZipOutputStream zos, String name) throws IOException { final ZipEntry ze = new ZipEntry(name); zos.putNextEntry(ze); try { final ByteBuffer byteBuffer = serialize(); byteBuffer.put(DIRTY_FLAG_OFFSET, (byte) 0); zos.write(byteBuffer.array()); } finally { zos.closeEntry(); } } public StorageStartupMetadata(Path filePath) { this.filePath = filePath; } public void create() throws IOException { lock.lock(); try { if (Files.exists(filePath)) { Files.delete(filePath); } channel = FileChannel .open(filePath, StandardOpenOption.READ, StandardOpenOption.CREATE, StandardOpenOption.WRITE, StandardOpenOption.SYNC); if (OGlobalConfiguration.FILE_LOCK.getValueAsBoolean()) { lockFile(); } final ByteBuffer buffer = ByteBuffer.allocate(1 + 8 + 8 + 4 + 4);//version + dirty flag + transaction id + tx metadata len buffer.position(8); buffer.putInt(VERSION); //dirty flag buffer.put((byte) 1); //transaction id buffer.putLong(-1); //tx metadata len buffer.putInt(-1); final long xxHash = XX_HASH_64.hash(buffer, 8, buffer.capacity() - 8, XX_HASH_SEED); buffer.putLong(0, xxHash); buffer.rewind(); OIOUtils.writeByteBuffer(buffer, channel, 0); dirtyFlag = true; lastTxId = -1; } finally { lock.unlock(); } } private void lockFile() throws IOException { try { fileLock = channel.tryLock(); } catch (OverlappingFileLockException e) { OLogManager.instance().warn(this, "File is already locked by other thread", e); } if (fileLock == null) throw new OStorageException("Database is locked by another process, please shutdown process and try again"); } public boolean exists() { lock.lock(); try { return Files.exists(filePath); } finally { lock.unlock(); } } public void open() throws IOException { lock.lock(); try { if (!Files.exists(filePath)) { OLogManager.instance().infoNoDb(this, "File with startup metadata does not exist, creating new one"); create(); return; } else { channel = FileChannel .open(filePath, StandardOpenOption.SYNC, StandardOpenOption.WRITE, StandardOpenOption.READ, StandardOpenOption.CREATE); final long size = channel.size(); if (size == 1) { ByteBuffer buffer = ByteBuffer.allocate(1); OIOUtils.readByteBuffer(buffer, channel, 0, true); buffer.position(0); dirtyFlag = buffer.get() > 0; } else if (size == 9) { ByteBuffer buffer = ByteBuffer.allocate(8 + 1); OIOUtils.readByteBuffer(buffer, channel, 0, true); buffer.position(0); dirtyFlag = buffer.get() > 0; lastTxId = buffer.getLong(); } else { final ByteBuffer buffer = ByteBuffer.allocate((int) size); OIOUtils.readByteBuffer(buffer, channel); buffer.rewind(); final long xxHash = XX_HASH_64.hash(buffer, 8, buffer.capacity() - 8, XX_HASH_SEED); if (xxHash != buffer.getLong(0)) { OLogManager.instance().error(this, "File with startup metadata is broken and can not be used, creation new one", null); channel.close(); create(); return; } buffer.position(8); final int version = buffer.getInt(); if (version != VERSION) { throw new IllegalStateException( "Invalid version of the binary format of startup metadata file found " + version + " but expected " + VERSION); } dirtyFlag = buffer.get() > 0; lastTxId = buffer.getLong(); final int metadataLen = buffer.getInt(); if (metadataLen > 0) { final byte[] txMeta = new byte[metadataLen]; buffer.get(txMeta); txMetadata = txMeta; } } } if (OGlobalConfiguration.FILE_LOCK.getValueAsBoolean()) { lockFile(); } } finally { lock.unlock(); } } public void close() throws IOException { lock.lock(); try { if (channel == null) return; if (Files.exists(filePath)) { if (fileLock != null) { fileLock.release(); fileLock = null; } channel.close(); channel = null; } } finally { lock.unlock(); } } public void delete() throws IOException { lock.lock(); try { if (channel == null) return; if (Files.exists(filePath)) { if (fileLock != null) { fileLock.release(); fileLock = null; } channel.close(); channel = null; Files.delete(filePath); } } finally { lock.unlock(); } } public void makeDirty() throws IOException { if (dirtyFlag) return; lock.lock(); try { if (dirtyFlag) return; dirtyFlag = true; OIOUtils.writeByteBuffer(serialize(), channel, 0); } finally { lock.unlock(); } } public void clearDirty() throws IOException { if (!dirtyFlag) return; lock.lock(); try { if (!dirtyFlag) return; dirtyFlag = false; OIOUtils.writeByteBuffer(serialize(), channel, 0); } finally { lock.unlock(); } } public void setLastTxId(long lastTxId) throws IOException { lock.lock(); try { this.lastTxId = lastTxId; OIOUtils.writeByteBuffer(serialize(), channel, 0); } finally { lock.unlock(); } } public void setTxMetadata(final byte[] txMetadata) throws IOException { lock.lock(); try { this.txMetadata = txMetadata; OIOUtils.writeByteBuffer(serialize(), channel, 0); } finally { lock.unlock(); } } public boolean isDirty() { return dirtyFlag; } public long getLastTxId() { return lastTxId; } public byte[] getTxMetadata() { return txMetadata; } private ByteBuffer serialize() { final ByteBuffer buffer; if (txMetadata == null) { buffer = ByteBuffer.allocate(8 + 4 + 1 + 8 + 4); } else { buffer = ByteBuffer.allocate(8 + 4 + 1 + 8 + 4 + txMetadata.length); } buffer.position(8); buffer.putInt(VERSION); //dirty flag buffer.put(dirtyFlag ? (byte) 1 : (byte) 0); //transaction id buffer.putLong(lastTxId); //tx metadata if (txMetadata == null) { buffer.putInt(-1); } else { buffer.putInt(txMetadata.length); buffer.put(txMetadata); } final long xxHash = XX_HASH_64.hash(buffer, 8, buffer.capacity() - 8, XX_HASH_SEED); buffer.putLong(0, xxHash); buffer.rewind(); return buffer; } }
Bug of binary compatibility with previous versions of startup metadata was fixed.
core/src/main/java/com/orientechnologies/orient/core/storage/impl/local/paginated/StorageStartupMetadata.java
Bug of binary compatibility with previous versions of startup metadata was fixed.
<ide><path>ore/src/main/java/com/orientechnologies/orient/core/storage/impl/local/paginated/StorageStartupMetadata.java <ide> <ide> final long size = channel.size(); <ide> <del> if (size == 1) { <add> if (size < 9) { <ide> ByteBuffer buffer = ByteBuffer.allocate(1); <ide> OIOUtils.readByteBuffer(buffer, channel, 0, true); <ide>
JavaScript
mit
76161e1cabb97d5701e259d5228df2e32989226a
0
zarocknz/javascript-winwheel
/* Winwheel.js, by Douglas McKechie @ www.dougtesting.net See website for tutorials and other documentation. The MIT License (MIT) Copyright (c) 2016 Douglas McKechie 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. */ // ==================================================================================================================== // The constructor for the WinWheel object, a JOSN-like array of options can be passed in. // By default the wheel is drawn if canvas object exists on the page, but can pass false as second parameter if don't want this to happen. // ==================================================================================================================== function Winwheel(options, drawWheel) { defaultOptions = { 'canvasId' : 'canvas', // Id of the canvas which the wheel is to draw on to. 'centerX' : null, // X position of the center of the wheel. The default of these are null which means will be placed in center of the canvas. 'centerY' : null, // Y position of the wheel center. If left null at time of construct the center of the canvas is used. 'outerRadius' : null, // The radius of the outside of the wheel. If left null it will be set to the radius from the center of the canvas to its shortest side. 'innerRadius' : 0, // Normally 0. Allows the creation of rings / doughnuts if set to value > 0. Should not exceed outer radius. 'numSegments' : 1, // The number of segments. Need at least one to draw. 'drawMode' : 'code', // The draw mode. Possible values are 'code' and 'image'. Default is code which means segments are drawn using canvas arc() function. 'rotationAngle' : 0, // The angle of rotation of the wheel - 0 is 12 o'clock position. 'textFontFamily' : 'Arial', // Segment text font, you should use web safe fonts. 'textFontSize' : 20, // Size of the segment text. 'textFontWeight' : 'bold', // Font weight. 'textOrientation' : 'horizontal', // Either horizontal, vertical, or curved. 'textAlignment' : 'center', // Either center, inner, or outer. 'textDirection' : 'normal', // Either normal or reversed. In normal mode for horizontal text in segment at 3 o'clock is correct way up, in reversed text at 9 o'clock segment is correct way up. 'textMargin' : null, // Margin between the inner or outer of the wheel (depends on textAlignment). 'textFillStyle' : 'black', // This is basically the text colour. 'textStrokeStyle' : null, // Basically the line colour for segment text, only looks good for large text so off by default. 'textLineWidth' : 1, // Width of the lines around the text. Even though this defaults to 1, a line is only drawn if textStrokeStyle specified. 'fillStyle' : 'silver', // The segment background colour. 'strokeStyle' : 'black', // Segment line colour. Again segment lines only drawn if this is specified. 'lineWidth' : 1, // Width of lines around segments. 'clearTheCanvas' : true, // When set to true the canvas will be cleared before the wheel is drawn. 'imageOverlay' : false, // If set to true in image drawing mode the outline of the segments will be displayed over the image. Does nothing in code drawMode. 'drawText' : true, // By default the text of the segments is rendered in code drawMode and not in image drawMode. 'pointerAngle' : 0, // Location of the pointer that indicates the prize when wheel has stopped. Default is 0 so the (corrected) 12 o'clock position. 'wheelImage' : null // Must be set to image data in order to use image to draw the wheel - drawMode must also be 'image'. }; // ----------------------------------------- // Loop through the default options and create properties of this class set to the value for the option passed in // or if not value for the option was passed in then to the default. for (var key in defaultOptions) { if ((options != null) && (typeof(options[key]) !== 'undefined')) { this[key] = options[key]; } else { this[key] = defaultOptions[key]; } } // Also loop though the passed in options and add anything specified not part of the class in to it as a property. if (options != null) { for (var key in options) { if (typeof(this[key]) === 'undefined') { this[key] = options[key]; } } } // ------------------------------------------ // If the id of the canvas is set, try to get the canvas as we need it for drawing. if (this.canvasId) { this.canvas = document.getElementById(this.canvasId); if (this.canvas) { // If the centerX and centerY have not been specified in the options then default to center of the canvas // and make the outerRadius half of the canvas width - this means the wheel will fill the canvas. if (this.centerX == null) { this.centerX = this.canvas.width / 2; } if (this.centerY == null) { this.centerY = this.canvas.height / 2; } if (this.outerRadius == null) { // Need to set to half the width of the shortest dimension of the canvas as the canvas may not be square. // Minus the line segment line width otherwise the lines around the segments on the top,left,bottom,right // side are chopped by the edge of the canvas. if (this.canvas.width < this.canvas.height) { this.outerRadius = (this.canvas.width / 2) - this.lineWidth; } else { this.outerRadius = (this.canvas.height / 2) - this.lineWidth; } } // Also get a 2D context to the canvas as we need this to draw with. this.ctx = this.canvas.getContext('2d'); } else { this.canvas = null; this.ctx = null; } } else { this.cavnas = null; this.ctx = null; } // ------------------------------------------ // Add array of segments to the wheel, then populate with segments if number of segments is specified for this object. this.segments = new Array(null); for (x = 1; x <= this.numSegments; x++) { // If options for the segments have been specified then create a segment sending these options so // the specified values are used instead of the defaults. if ((options != null) && (options['segments']) && (typeof(options['segments'][x-1]) !== 'undefined')) { this.segments[x] = new Segment(options['segments'][x-1]); } else { this.segments[x] = new Segment(); } } // ------------------------------------------ // Call function to update the segment sizes setting the starting and ending angles. this.updateSegmentSizes(); // If the text margin is null then set to same as font size as we want some by default. if (this.textMargin === null) { this.textMargin = (this.textFontSize / 1.7); } // ------------------------------------------ // If the animation options have been passed in then create animation object as a property of this class // and pass the options to it so the animation is set. Otherwise create default animation object. if ((options != null) && (options['animation']) && (typeof(options['animation']) !== 'undefined')) { this.animation = new Animation(options['animation']); } else { this.animation = new Animation(); } // ------------------------------------------ // On that note, if the drawMode is image change some defaults provided a value has not been specified. if (this.drawMode == 'image') { // Remove grey fillStyle. if (typeof(options['fillStyle']) === 'undefined') { this.fillStyle = null; } // Set strokeStyle to red. if (typeof(options['strokeStyle']) === 'undefined') { this.strokeStyle = 'red'; } // Set drawText to false as we will assume any text is part of the image. if (typeof(options['drawText']) === 'undefined') { this.drawText = false; } // Also set the lineWidth to 1 so that segment overlay will look correct. if (typeof(options['lineWidth']) === 'undefined') { this.lineWidth = 1; } // Set drawWheel to false as normally the image needs to be loaded first. if (typeof(drawWheel) === 'undefined') { drawWheel = false; } } else { // When in code drawMode the default is the wheel will draw. if (typeof(drawWheel) === 'undefined') { drawWheel = true; } } // Create pointer guide. if ((options != null) && (options['pointerGuide']) && (typeof(options['pointerGuide']) !== 'undefined')) { this.pointerGuide = new PointerGuide(options['pointerGuide']); } else { this.pointerGuide = new PointerGuide(); } // Finally if drawWheel is true then call function to render the wheel, segment text, overlay etc. if (drawWheel == true) { this.draw(this.clearTheCanvas); } } // ==================================================================================================================== // This function sorts out the segment sizes. Some segments may have set sizes, for the others what is left out of // 360 degrees is shared evenly. What this function actually does is set the start and end angle of the arcs. // ==================================================================================================================== Winwheel.prototype.updateSegmentSizes = function() { // If this object actually contains some segments if (this.segments) { // First add up the arc used for the segments where the size has been set. var arcUsed = 0; var numSet = 0; // Remember, to make it easy to access segments, the position of the segments in the array starts from 1 (not 0). for (x = 1; x <= this.numSegments; x ++) { if (this.segments[x].size !== null) { arcUsed += this.segments[x].size; numSet ++; } } var arcLeft = (360 - arcUsed); // Create variable to hold how much each segment with non-set size will get in terms of degrees. var degreesEach = 0; if (arcLeft > 0) { degreesEach = (arcLeft / (this.numSegments - numSet)); } // ------------------------------------------ // Now loop though and set the start and end angle of each segment. var currentDegree = 0; for (x = 1; x <= this.numSegments; x ++) { // Set start angle. this.segments[x].startAngle = currentDegree; // If the size is set then add this to the current degree to get the end, else add the degreesEach to it. if (this.segments[x].size) { currentDegree += this.segments[x].size; } else { currentDegree += degreesEach; } // Set end angle. this.segments[x].endAngle = currentDegree; } } } // ==================================================================================================================== // This function clears the canvas. Will wipe anything else which happens to be drawn on it. // ==================================================================================================================== Winwheel.prototype.clearCanvas = function() { if (this.ctx) { this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height); } } // ==================================================================================================================== // This function draws / re-draws the wheel on the canvas therefore rendering any changes. // ==================================================================================================================== Winwheel.prototype.draw = function(clearTheCanvas) { // If have the canvas context. if (this.ctx) { // Clear the canvas, unless told not to. if (typeof(clearTheCanvas) !== 'undefined') { if (clearTheCanvas == true) { this.clearCanvas(); } } else { this.clearCanvas(); } // Call functions to draw the segments and then segment text. if (this.drawMode == 'image') { // Draw the wheel by loading and drawing an image such as a png on the canvas. this.drawWheelImage(); // If we are to draw the text, do so before the overlay is drawn // as this allows the overlay to be used to create some interesting effects. if (this.drawText == true) { this.drawSegmentText(); } // If image overlay is true then call function to draw the segments over the top of the image. // This is useful during development to check alignment between where the code thinks the segments are and where they appear on the image. if (this.imageOverlay == true) { this.drawSegments(); } } else { // The default operation is to draw the segments using code via the canvas arc() method. this.drawSegments(); // The text is drawn on top. if (this.drawText == true) { this.drawSegmentText(); } } // If pointer guide is display property is set to true then call function to draw the pointer guide. if (this.pointerGuide.display == true) { this.drawPointerGuide(); } } } // ==================================================================================================================== // Draws a line from the center of the wheel to the outside at the angle where the code thinks the pointer is. // ==================================================================================================================== Winwheel.prototype.drawPointerGuide = function() { // If have canvas context. if (this.ctx) { this.ctx.save(); this.ctx.translate(this.canvas.width / 2, this.canvas.height / 2); this.ctx.rotate(this.degToRad(this.pointerAngle)); this.ctx.translate(-this.canvas.width / 2, -this.canvas.height / 2); this.ctx.strokeStyle = this.pointerGuide.strokeStyle; this.ctx.lineWidth = this.pointerGuide.lineWidth; // Draw from the center of the wheel out at the pointer angle to the edge of the canvas. this.ctx.beginPath(); this.ctx.moveTo(this.canvas.width / 2, this.canvas.height / 2); this.ctx.lineTo(this.centerX, -(this.outerRadius / 5)); this.ctx.stroke(); this.ctx.restore(); } } // ==================================================================================================================== // This function takes an image such as PNG and draws it on the canvas making its center at the centerX and center for the wheel. // ==================================================================================================================== Winwheel.prototype.drawWheelImage = function() { // Double check the wheelImage property of this class is not null. This does not actually detect that an image // source was set and actually loaded so might get error if this is not the case. This is why the initial call // to draw() should be done from a wheelImage.onload callback as detailed in example documentation. if (this.wheelImage != null) { // Work out the correct X and Y to draw the image at. We need to get the center point of the image // aligned over the center point of the wheel, we can't just place it at 0, 0. var imageLeft = (this.centerX - (this.wheelImage.height / 2)); var imageTop = (this.centerY - (this.wheelImage.width / 2)); // Rotate and then draw the wheel. We must rotate by the rotationAngle before drawing to ensure that // image wheels will spin. this.ctx.save(); this.ctx.translate(this.canvas.width / 2, this.canvas.height / 2); this.ctx.rotate(this.degToRad(this.rotationAngle)); this.ctx.translate(-this.canvas.width / 2, -this.canvas.height / 2); this.ctx.drawImage(this.wheelImage, imageLeft, imageTop); this.ctx.restore(); } } // ==================================================================================================================== // This function draws the wheel on the page by rendering the segments on the canvas. // ==================================================================================================================== Winwheel.prototype.drawSegments = function() { // Again check have context in case this function was called directly and not via draw function. if (this.ctx) { // Draw the segments if there is at least one in the segments array. if (this.segments) { // Loop though and output all segments - position 0 of the array is not used, so start loop from index 1 // this is to avoid confusion when talking about the first segment. for (x = 1; x <= this.numSegments; x ++) { // Get the segment object as we need it to read options from. seg = this.segments[x]; var fillStyle; var lineWidth; var strokeStyle; // Set the variables that defined in the segment, or use the default options. if (seg.fillStyle !== null) fillStyle = seg.fillStyle; else fillStyle = this.fillStyle; this.ctx.fillStyle = fillStyle; if (seg.lineWidth !== null) lineWidth = seg.lineWidth; else lineWidth = this.lineWidth; this.ctx.lineWidth = lineWidth; if (seg.strokeStyle !== null) strokeStyle = seg.strokeStyle; else strokeStyle = this.strokeStyle; this.ctx.strokeStyle = strokeStyle; // Check there is a strokeStyle or fillStyle, if either the the segment is invisible so should not // try to draw it otherwise a path is began but not ended. if ((strokeStyle) || (fillStyle)) { // ---------------------------------- // Begin a path as the segment consists of an arc and 2 lines. this.ctx.beginPath(); // If don't have an inner radius then move to the center of the wheel as we want a line out from the center // to the start of the arc for the outside of the wheel when we arc. Canvas will draw the connecting line for us. if (!this.innerRadius) { this.ctx.moveTo(this.centerX, this.centerY); } else { //++ do need to draw the starting line in the correct x + y based on the start angle //++ otherwise as seen when the wheel does not use up 360 the starting segment is missing the stroked side, } // Draw the outer arc of the segment clockwise in direction --> this.ctx.arc(this.centerX, this.centerY, this.outerRadius, this.degToRad(seg.startAngle + this.rotationAngle - 90), this.degToRad(seg.endAngle + this.rotationAngle - 90), false); if (this.innerRadius) { // Draw another arc, this time anticlockwise <-- at the innerRadius between the end angle and the start angle. // Canvas will draw a connecting line from the end of the outer arc to the beginning of the inner arc completing the shape. //++ Think the reason the lines are thinner for 2 of the segments is because the thing auto chops part of it //++ when doing the next one. Again think that actually drawing the lines will help. this.ctx.arc(this.centerX, this.centerY, this.innerRadius, this.degToRad(seg.endAngle + this.rotationAngle - 90), this.degToRad(seg.startAngle + this.rotationAngle - 90), true); } else { // If no inner radius then we draw a line back to the center of the wheel. this.ctx.lineTo(this.centerX, this.centerY); } // Fill and stroke the segment. Only do either if a style was specified, if the style is null then // we assume the developer did not want that particular thing. // For example no stroke style so no lines to be drawn. if (fillStyle) this.ctx.fill(); if (strokeStyle) this.ctx.stroke(); } } } } } // ==================================================================================================================== // This draws the text on the segments using the specified text options. // ==================================================================================================================== Winwheel.prototype.drawSegmentText = function() { // Again only draw the text if have a canvas context. if (this.ctx) { // Declare variables to hold the values. These are populated either with the value for the specific segment, // or if not specified then the global default value. var fontFamily; var fontSize; var fontWeight; var orientation; var alignment; var direction; var margin; var fillStyle; var strokeStyle; var lineWidth; var fontSetting; // Loop though all the segments. for (x = 1; x <= this.numSegments; x ++) { // Save the context so it is certain that each segment text option will not affect the other. this.ctx.save(); // Get the segment object as we need it to read options from. seg = this.segments[x]; // Check is text as no point trying to draw if there is no text to render. if (seg.text) { // Set values to those for the specific segment or use global default if null. if (seg.textFontFamily !== null) fontFamily = seg.textFontFamily; else fontFamily = this.textFontFamily; if (seg.textFontSize !== null) fontSize = seg.textFontSize; else fontSize = this.textFontSize; if (seg.textFontWeight !== null) fontWeight = seg.textFontWeight; else fontWeight = this.textFontWeight; if (seg.textOrientation !== null) orientation = seg.textOrientation; else orientation = this.textOrientation; if (seg.textAlignment !== null) alignment = seg.textAlignment; else alignment = this.textAlignment; if (seg.textDirection !== null) direction = seg.textDirection; else direction = this.textDirection; if (seg.textMargin !== null) margin = seg.textMargin; else margin = this.textMargin; if (seg.textFillStyle !== null) fillStyle = seg.textFillStyle; else fillStyle = this.textFillStyle; if (seg.textStrokeStyle !== null) strokeStyle = seg.textStrokeStyle; else strokeStyle = this.textStrokeStyle; if (seg.textLineWidth !== null) lineWidth = seg.textLineWidth; else lineWidth = this.textLineWidth; // ------------------------------ // We need to put the font bits together in to one string. fontSetting = ''; if (fontWeight != null) fontSetting += fontWeight + ' '; if (fontSize != null) fontSetting += fontSize + 'px '; // Fonts on canvas are always a px value. if (fontFamily != null) fontSetting += fontFamily; // Now set the canvas context to the decided values. this.ctx.font = fontSetting; this.ctx.fillStyle = fillStyle; this.ctx.strokeStyle = strokeStyle; this.ctx.lineWidth = lineWidth; // --------------------------------- // If direction is reversed then do things differently than if normal (which is the default - see further down) if (direction == 'reversed') { // When drawing reversed or 'upside down' we need to do some trickery on our part. // The canvas text rendering function still draws the text left to right and the correct way up, // so we need to overcome this with rotating the opposite side of the wheel the correct way up then pulling the text // through the center point to the correct segment it is supposed to be on. if (orientation == 'horizontal') { if (alignment == 'inner') this.ctx.textAlign = 'right'; else if (alignment == 'outer') this.ctx.textAlign = 'left'; else this.ctx.textAlign = 'center'; this.ctx.textBaseline = 'middle'; // Work out the angle to rotate the wheel, this is in the center of the segment but on the opposite side of the wheel which is why do -180. var textAngle = this.degToRad((seg.endAngle - ((seg.endAngle - seg.startAngle) / 2) + this.rotationAngle - 90) - 180); this.ctx.save(); this.ctx.translate(this.canvas.width / 2, this.canvas.height / 2); this.ctx.rotate(textAngle); this.ctx.translate(-this.canvas.width / 2, -this.canvas.height / 2); if (alignment == 'inner') { // In reversed state the margin is subtracted from the innerX. // When inner the inner radius also comes in to play. if (fillStyle) this.ctx.fillText(seg.text, this.centerX - this.innerRadius - margin, this.centerY); if (strokeStyle) this.ctx.strokeText(seg.text, this.centerX - this.innerRadius - margin, this.centerY); } else if (alignment == 'outer') { // In reversed state the position is the center minus the radius + the margin for outer aligned text. if (fillStyle) this.ctx.fillText(seg.text, this.centerX - this.outerRadius + margin, this.centerY); if (strokeStyle) this.ctx.strokeText(seg.text, this.centerX - this.outerRadius + margin, this.centerY); } else { // In reversed state the everything in minused. if (fillStyle) this.ctx.fillText(seg.text, this.centerX - this.innerRadius - ((this.outerRadius - this.innerRadius) / 2) - margin, this.centerY); if (strokeStyle) this.ctx.strokeText(seg.text, this.centerX - this.innerRadius - ((this.outerRadius - this.innerRadius) / 2) - margin, this.centerY); } this.ctx.restore(); } else if (orientation == 'vertical') { // See normal code further down for comments on how it works, this is similar by plus/minus is reversed. this.ctx.textAlign = 'center'; // In reversed mode this are reversed. if (alignment == 'inner') this.ctx.textBaseline = 'top'; else if (alignment == 'outer') this.ctx.textBaseline = 'bottom'; else this.ctx.textBaseline = 'middle'; var textAngle = (seg.endAngle - ((seg.endAngle - seg.startAngle) / 2) - 180); textAngle += this.rotationAngle; this.ctx.save(); this.ctx.translate(this.centerX, this.centerY); this.ctx.rotate(this.degToRad(textAngle)); this.ctx.translate(-this.centerX, -this.centerY); if (alignment == 'outer') var yPos = (this.centerY + this.outerRadius - margin); else if (alignment == 'inner') var yPos = (this.centerY + this.innerRadius + margin); // I have found that the text looks best when a fraction of the font size is shaved off. var yInc = (fontSize - (fontSize / 9)); // Loop though and output the characters. if (alignment == 'outer') { // In reversed mode outer means text in 6 o'clock segment sits at bottom of the wheel and we draw up. for (var c = (seg.text.length -1); c >= 0; c--) { character = seg.text.charAt(c); if (fillStyle) this.ctx.fillText(character, this.centerX, yPos); if (strokeStyle) this.ctx.strokeText(character, this.centerX, yPos); yPos -= yInc; } } else if (alignment == 'inner') { // In reversed mode inner text is drawn from top of segment at 6 o'clock position to bottom of the wheel. for (var c = 0; c < seg.text.length; c++) { character = seg.text.charAt(c); if (fillStyle) this.ctx.fillText(character, this.centerX, yPos); if (strokeStyle) this.ctx.strokeText(character, this.centerX, yPos); yPos += yInc; } } else if (alignment == 'center') { // Again for reversed this is the opposite of before. // If there is more than one character in the text then an adjustment to the position needs to be done. // What we are aiming for is to position the center of the text at the center point between the inner and outer radius. var centerAdjustment = 0; if (seg.text.length > 1) { centerAdjustment = (yInc * (seg.text.length -1) / 2); } var yPos = (this.centerY + this.innerRadius + ((this.outerRadius - this.innerRadius) / 2)) + centerAdjustment + margin; for (var c = (seg.text.length -1); c >= 0; c--) { character = seg.text.charAt(c); if (fillStyle) this.ctx.fillText(character, this.centerX, yPos); if (strokeStyle) this.ctx.strokeText(character, this.centerX, yPos); yPos -= yInc; } } this.ctx.restore(); } else if (orientation == 'curved') { // There is no built in canvas function to draw text around an arc, // so we need to do this ourselves. var radius = 0; // Set the alignment of the text - inner, outer, or center by calculating // how far out from the center point of the wheel the text is drawn. if (alignment == 'inner') { // When alignment is inner the radius is the innerRadius plus any margin. radius = this.innerRadius + margin; this.ctx.textBaseline = 'top'; } else if (alignment == 'outer') { // Outer it is the outerRadius minus any margin. radius = this.outerRadius - margin; this.ctx.textBaseline = 'bottom'; } else if (alignment == 'center') { // When center we want the text halfway between the inner and outer radius. radius = this.innerRadius + margin + ((this.outerRadius - this.innerRadius) / 2); this.ctx.textBaseline = 'middle'; } // Set the angle to increment by when looping though and outputting the characters in the text // as we do this by rotating the wheel small amounts adding each character. var anglePerChar = 0; var drawAngle = 0; // If more than one character in the text then... if (seg.text.length > 1) { // Text is drawn from the left. this.ctx.textAlign = 'left'; // Work out how much angle the text rendering loop below needs to rotate by for each character to render them next to each other. // I have discovered that 4 * the font size / 10 at 100px radius is the correct spacing for between the characters // using a monospace font, non monospace may look a little odd as in there will appear to be extra spaces between chars. anglePerChar = (4 * (fontSize / 10)); // Work out what percentage the radius the text will be drawn at is of 100px. radiusPercent = (100 / radius); // Then use this to scale up or down the anglePerChar value. // When the radius is less than 100px we need more angle between the letters, when radius is greater (so the text is further // away from the center of the wheel) the angle needs to be less otherwise the characters will appear further apart. anglePerChar = (anglePerChar * radiusPercent); // Next we want the text to be drawn in the middle of the segment, without this it would start at the beginning of the segment. // To do this we need to work out how much arc the text will take up in total then subtract half of this from the center // of the segment so that it sits centred. totalArc = (anglePerChar * seg.text.length); // Now set initial draw angle to half way between the start and end of the segment. drawAngle = seg.startAngle + (((seg.endAngle - seg.startAngle) / 2) - (totalArc / 2)); } else { // The initial draw angle is the center of the segment when only one character. drawAngle = (seg.startAngle + ((seg.endAngle - seg.startAngle) / 2)); // To ensure is dead-center the text alignment also needs to be centered. this.ctx.textAlign = 'center'; } // ---------------------- // Adjust the initial draw angle as needed to take in to account the rotationAngle of the wheel. drawAngle += this.rotationAngle; // And as with other 'reverse' text direction functions we need to subtract 180 degrees from the angle // because when it comes to draw the characters in the loop below we add the radius instead of subtract it. drawAngle -= 180; // ---------------------- // Now the drawing itself. // In reversed direction mode we loop through the characters in the text backwards in order for them to appear on screen correctly for (c = seg.text.length; c >= 0; c--) { this.ctx.save(); character = seg.text.charAt(c); // Rotate the wheel to the draw angle as we need to add the character at this location. this.ctx.translate(this.centerX, this.centerY); this.ctx.rotate(this.degToRad(drawAngle)); this.ctx.translate(-this.centerX, -this.centerY); // Now draw the character directly below the center point of the wheel at the appropriate radius. // Note in the reversed mode we add the radius to the this.centerY instead of subtract. if (strokeStyle) this.ctx.strokeText(character, this.centerX, this.centerY + radius); if (fillStyle) this.ctx.fillText(character, this.centerX, this.centerY + radius); // Increment the drawAngle by the angle per character so next loop we rotate // to the next angle required to draw the character at. drawAngle += anglePerChar; this.ctx.restore(); } } } else { // Normal direction so do things normally. // Check text orientation, of horizontal then reasonably straight forward, if vertical then a bit more work to do. if (orientation == 'horizontal') { // Based on the text alignment, set the correct value in the context. if (alignment == 'inner') this.ctx.textAlign = 'left'; else if (alignment == 'outer') this.ctx.textAlign = 'right'; else this.ctx.textAlign = 'center'; // Set this too. this.ctx.textBaseline = 'middle'; // Work out the angle around the wheel to draw the text at, which is simply in the middle of the segment the text is for. // The rotation angle is added in to correct the annoyance with the canvas arc drawing functions which put the 0 degrees at the 3 oclock var textAngle = this.degToRad(seg.endAngle - ((seg.endAngle - seg.startAngle) / 2) + this.rotationAngle - 90); // We need to rotate in order to draw the text because it is output horizontally, so to // place correctly around the wheel for all but a segment at 3 o'clock we need to rotate. this.ctx.save(); this.ctx.translate(this.centerX, this.centerY); this.ctx.rotate(textAngle); this.ctx.translate(-this.centerX, -this.centerY); // -------------------------- // Draw the text based on its alignment adding margin if inner or outer. if (alignment == 'inner') { // Inner means that the text is aligned with the inner of the wheel. If looking at a segment in in the 3 o'clock position // it would look like the text is left aligned within the segment. // Because the segments are smaller towards the inner of the wheel, in order for the text to fit is is a good idea that // a margin is added which pushes the text towards the outer a bit. // The inner radius also needs to be taken in to account as when inner aligned. // If fillstyle is set the draw the text filled in. if (fillStyle) this.ctx.fillText(seg.text, this.centerX + this.innerRadius + margin, this.centerY); // If stroke style is set draw the text outline. if (strokeStyle) this.ctx.strokeText(seg.text, this.centerX + this.innerRadius + margin, this.centerY); } else if (alignment == 'outer') { // Outer means the text is aligned with the outside of the wheel, so if looking at a segment in the 3 o'clock position // it would appear the text is right aligned. To position we add the radius of the wheel in to the equation // and subtract the margin this time, rather than add it. // I don't understand why, but in order of the text to render correctly with stroke and fill, the stroke needs to // come first when drawing outer, rather than second when doing inner. if (fillStyle) this.ctx.fillText(seg.text, this.centerX + this.outerRadius - margin, this.centerY); // If fillstyle the fill the text. if (strokeStyle) this.ctx.strokeText(seg.text, this.centerX + this.outerRadius - margin, this.centerY); } else { // In this case the text is to drawn centred in the segment. // Typically no margin is required, however even though centred the text can look closer to the inner of the wheel // due to the way the segments narrow in (is optical effect), so if a margin is specified it is placed on the inner // side so the text is pushed towards the outer. // If stoke style the stroke the text. if (fillStyle) this.ctx.fillText(seg.text, this.centerX + this.innerRadius + ((this.outerRadius - this.innerRadius) / 2) + margin, this.centerY); // If fillstyle the fill the text. if (strokeStyle) this.ctx.strokeText(seg.text, this.centerX + this.innerRadius + ((this.outerRadius - this.innerRadius) / 2) + margin, this.centerY); } // Restore the context so that wheel is returned to original position. this.ctx.restore(); } else if (orientation == 'vertical') { // If vertical then we need to do this ourselves because as far as I am aware there is no option built in to html canvas // which causes the text to draw downwards or upwards one character after another. // In this case the textAlign is always center, but the baseline is either top or bottom // depending on if inner or outer alignment has been specified. this.ctx.textAlign = 'center'; if (alignment == 'inner') this.ctx.textBaseline = 'bottom'; else if (alignment == 'outer') this.ctx.textBaseline = 'top'; else this.ctx.textBaseline = 'middle'; // The angle to draw the text at is halfway between the end and the starting angle of the segment. var textAngle = seg.endAngle - ((seg.endAngle - seg.startAngle) / 2); // Ensure the rotation angle of the wheel is added in, otherwise the test placement won't match // the segments they are supposed to be for. textAngle += this.rotationAngle; // Rotate so can begin to place the text. this.ctx.save(); this.ctx.translate(this.centerX, this.centerY); this.ctx.rotate(this.degToRad(textAngle)); this.ctx.translate(-this.centerX, -this.centerY); // Work out the position to start drawing in based on the alignment. // If outer then when considering a segment at the 12 o'clock position want to start drawing down from the top of the wheel. if (alignment == 'outer') var yPos = (this.centerY - this.outerRadius + margin); else if (alignment == 'inner') var yPos = (this.centerY - this.innerRadius - margin); // We need to know how much to move the y axis each time. // This is not quite simply the font size as that puts a larger gap in between the letters // than expected, especially with monospace fonts. I found that shaving a little off makes it look "right". var yInc = (fontSize - (fontSize / 9)); // Loop though and output the characters. if (alignment == 'outer') { // For this alignment we draw down from the top of a segment at the 12 o'clock position to simply // loop though the characters in order. for (var c = 0; c < seg.text.length; c++) { character = seg.text.charAt(c); if (fillStyle) this.ctx.fillText(character, this.centerX, yPos); if (strokeStyle) this.ctx.strokeText(character, this.centerX, yPos); yPos += yInc; } } else if (alignment == 'inner') { // Here we draw from the inner of the wheel up, but in order for the letters in the text text to // remain in the correct order when reading, we actually need to loop though the text characters backwards. for (var c = (seg.text.length -1); c >= 0; c--) { character = seg.text.charAt(c); if (fillStyle) this.ctx.fillText(character, this.centerX, yPos); if (strokeStyle) this.ctx.strokeText(character, this.centerX, yPos); yPos -= yInc; } } else if (alignment == 'center') { // This is the most complex of the three as we need to draw the text top down centred between the inner and outer of the wheel. // So logically we have to put the middle character of the text in the center then put the others each side of it. // In reality that is a really bad way to do it, we can achieve the same if not better positioning using a // variation on the method used for the rendering of outer aligned text once we have figured out the height of the text. // If there is more than one character in the text then an adjustment to the position needs to be done. // What we are aiming for is to position the center of the text at the center point between the inner and outer radius. var centerAdjustment = 0; if (seg.text.length > 1) { centerAdjustment = (yInc * (seg.text.length -1) / 2); } // Now work out where to start rendering the string. This is half way between the inner and outer of the wheel, with the // centerAdjustment included to correctly position texts with more than one character over the center. // If there is a margin it is used to push the text away from the center of the wheel. var yPos = (this.centerY - this.innerRadius - ((this.outerRadius - this.innerRadius) / 2)) - centerAdjustment - margin; // Now loop and draw just like outer text rendering. for (var c = 0; c < seg.text.length; c++) { character = seg.text.charAt(c); if (fillStyle) this.ctx.fillText(character, this.centerX, yPos); if (strokeStyle) this.ctx.strokeText(character, this.centerX, yPos); yPos += yInc; } } this.ctx.restore(); } else if (orientation == 'curved') { // There is no built in canvas function to draw text around an arc, so // we need to do this ourselves. var radius = 0; // Set the alignment of the text - inner, outer, or center by calculating // how far out from the center point of the wheel the text is drawn. if (alignment == 'inner') { // When alignment is inner the radius is the innerRadius plus any margin. radius = this.innerRadius + margin; this.ctx.textBaseline = 'bottom'; } else if (alignment == 'outer') { // Outer it is the outerRadius minus any margin. radius = this.outerRadius - margin; this.ctx.textBaseline = 'top'; } else if (alignment == 'center') { // When center we want the text halfway between the inner and outer radius. radius = this.innerRadius + margin + ((this.outerRadius - this.innerRadius) / 2); this.ctx.textBaseline = 'middle'; } // Set the angle to increment by when looping though and outputting the characters in the text // as we do this by rotating the wheel small amounts adding each character. var anglePerChar = 0; var drawAngle = 0; // If more than one character in the text then... if (seg.text.length > 1) { // Text is drawn from the left. this.ctx.textAlign = 'left'; // Work out how much angle the text rendering loop below needs to rotate by for each character to render them next to each other. // I have discovered that 4 * the font size / 10 at 100px radius is the correct spacing for between the characters // using a monospace font, non monospace may look a little odd as in there will appear to be extra spaces between chars. anglePerChar = (4 * (fontSize / 10)); // Work out what percentage the radius the text will be drawn at is of 100px. radiusPercent = (100 / radius); // Then use this to scale up or down the anglePerChar value. // When the radius is less than 100px we need more angle between the letters, when radius is greater (so the text is further // away from the center of the wheel) the angle needs to be less otherwise the characters will appear further apart. anglePerChar = (anglePerChar * radiusPercent); // Next we want the text to be drawn in the middle of the segment, without this it would start at the beginning of the segment. // To do this we need to work out how much arc the text will take up in total then subtract half of this from the center // of the segment so that it sits centred. totalArc = (anglePerChar * seg.text.length); // Now set initial draw angle to half way between the start and end of the segment. drawAngle = seg.startAngle + (((seg.endAngle - seg.startAngle) / 2) - (totalArc / 2)); } else { // The initial draw angle is the center of the segment when only one character. drawAngle = (seg.startAngle + ((seg.endAngle - seg.startAngle) / 2)); // To ensure is dead-center the text alignment also needs to be centred. this.ctx.textAlign = 'center'; } // ---------------------- // Adjust the initial draw angle as needed to take in to account the rotationAngle of the wheel. drawAngle += this.rotationAngle; // ---------------------- // Now the drawing itself. // Loop for each character in the text. for (c = 0; c < (seg.text.length); c++) { this.ctx.save(); character = seg.text.charAt(c); // Rotate the wheel to the draw angle as we need to add the character at this location. this.ctx.translate(this.centerX, this.centerY); this.ctx.rotate(this.degToRad(drawAngle)); this.ctx.translate(-this.centerX, -this.centerY); // Now draw the character directly above the center point of the wheel at the appropriate radius. if (strokeStyle) this.ctx.strokeText(character, this.centerX, this.centerY - radius); if (fillStyle) this.ctx.fillText(character, this.centerX, this.centerY - radius); // Increment the drawAngle by the angle per character so next loop we rotate // to the next angle required to draw the character at. drawAngle += anglePerChar; this.ctx.restore(); } } } } // Restore so all text options are reset ready for the next text. this.ctx.restore(); } } } // ==================================================================================================================== // Converts degrees to radians which is what is used when specifying the angles on HTML5 canvas arcs. // ==================================================================================================================== Winwheel.prototype.degToRad = function(d) { return d * 0.0174532925199432957; } // ==================================================================================================================== // This function sets the center location of the wheel, saves a function call to set x then y. // ==================================================================================================================== Winwheel.prototype.setCenter = function(x, y) { this.centerX = x; this.centerY = y; } // ==================================================================================================================== // This function allows a segment to be added to the wheel. The position of the segment is optional, // if not specified the new segment will be added to the end of the wheel. // ==================================================================================================================== Winwheel.prototype.addSegment = function(options, position) { // Create a new segment object passing the options in. newSegment = new Segment(options); // Increment the numSegments property of the class since new segment being added. this.numSegments ++; var segmentPos; // Work out where to place the segment, the default is simply as a new segment at the end of the wheel. if (typeof position !== 'undefined') { // Because we need to insert the segment at this position, not overwrite it, we need to move all segments after this // location along one in the segments array, before finally adding this new segment at the specified location. for (var x = this.numSegments; x > position; x --) { this.segments[x] = this.segments[x -1]; } this.segments[position] = newSegment; segmentPos = position; } else { this.segments[this.numSegments] = newSegment; segmentPos = this.numSegments; } // Since a segment has been added the segment sizes need to be re-computed so call function to do this. this.updateSegmentSizes(); // Return the segment object just created in the wheel (JavaScript will return it by reference), so that // further things can be done with it by the calling code if desired. return this.segments[segmentPos]; } // ==================================================================================================================== // This function must be used if the canvasId is changed as we also need to get the context of the new canvas. // ==================================================================================================================== Winwheel.prototype.setCanvasId = function(canvasId) { if (canvasId) { this.canvasId = canvasId; this.canvas = document.getElementById(this.canvasId); if (this.canvas) { this.ctx = this.canvas.getContext('2d'); } } else { this.canvasId = null this.ctx = null; this.canvas = null; } } // ==================================================================================================================== // This function deletes the specified segment from the wheel by removing it from the segments array. // It then sorts out the other bits such as update of the numSegments. // ==================================================================================================================== Winwheel.prototype.deleteSegment = function(position) { // There needs to be at least one segment in order for the wheel to draw, so only allow delete if there // is more than one segment currently left in the wheel. //++ check that specifying a position that does not exist - say 10 in a 6 segment wheel does not cause issues. if (this.numSegments > 1) { // If the position of the segment to remove has been specified. if (typeof position !== 'undefined') { // The array is to be shortened so we need to move all segments after the one // to be removed down one so there is no gap. for (var x = position; x < this.numSegments; x ++) { this.segments[x] = this.segments[x + 1]; } } // Unset the last item in the segments array since there is now one less. this.segments[this.numSegments] = undefined; // Decrement the number of segments, // then call function to update the segment sizes. this.numSegments --; this.updateSegmentSizes(); } } // ==================================================================================================================== // This function takes the x an the y of a mouse event, such as click or move, and converts the x and the y in to // co-ordinates on the canvas as the raw values are the x and the y from the top and left of the user's browser. // ==================================================================================================================== Winwheel.prototype.windowToCanvas = function(x, y) { var bbox = this.canvas.getBoundingClientRect(); return { x: Math.floor(x - bbox.left * (this.canvas.width / bbox.width)), y: Math.floor(y - bbox.top * (this.canvas.height / bbox.height)) }; } // ==================================================================================================================== // This function returns the segment object located at the specified x and y coordinates on the canvas. // It is used to allow things to be done with a segment clicked by the user, such as highlight, display or change some values, etc. // ==================================================================================================================== Winwheel.prototype.getSegmentAt = function(x, y) { var foundSegment = null; // Call function to return segment number. var segmentNumber = this.getSegmentNumberAt(x, y); // If found one then set found segment to pointer to the segment object. if (segmentNumber !== null) { foundSegment = this.segments[segmentNumber]; } return foundSegment; } // ==================================================================================================================== // Returns the number of the segment clicked instead of the segment object. // ==================================================================================================================== Winwheel.prototype.getSegmentNumberAt = function(x, y) { // KNOWN ISSUE: this does not work correct if the canvas is scaled using css, or has padding, border. // @TODO see if can find a solution at some point, check windowToCanvas working as needed, then below. // Call function above to convert the raw x and y from the user's browser to canvas coordinates // i.e. top and left is top and left of canvas, not top and left of the user's browser. var loc = this.windowToCanvas(x, y); // ------------------------------------------ // Now start the process of working out the segment clicked. // First we need to figure out the angle of an imaginary line between the centerX and centerY of the wheel and // the X and Y of the location (for example a mouse click). var topBottom; var leftRight; var adjacentSideLength; var oppositeSideLength; var hypotenuseSideLength; // We will use right triangle maths with the TAN function. // The start of the triangle is the wheel center, the adjacent side is along the x axis, and the opposite side is along the y axis. // We only ever use positive numbers to work out the triangle and the center of the wheel needs to be considered as 0 for the numbers // in the maths which is why there is the subtractions below. We also remember what quadrant of the wheel the location is in as we // need this information later to add 90, 180, 270 degrees to the angle worked out from the triangle to get the position around a 360 degree wheel. if (loc.x > this.centerX) { adjacentSideLength = (loc.x - this.centerX); leftRight = 'R'; // Location is in the right half of the wheel. } else { adjacentSideLength = (this.centerX - loc.x); leftRight = 'L'; // Location is in the left half of the wheel. } if (loc.y > this.centerY) { oppositeSideLength = (loc.y - this.centerY); topBottom = 'B'; // Bottom half of wheel. } else { oppositeSideLength = (this.centerY - loc.y); topBottom = 'T'; // Top Half of wheel. } // Now divide opposite by adjacent to get tan value. var tanVal = oppositeSideLength / adjacentSideLength; // Use the tan function and convert results to degrees since that is what we work with. var result = (Math.atan(tanVal) * 180/Math.PI); var locationAngle = 0; // We also need the length of the hypotenuse as later on we need to compare this to the outerRadius of the segment / circle. hypotenuseSideLength = Math.sqrt((oppositeSideLength * oppositeSideLength) + (adjacentSideLength * adjacentSideLength)); // ------------------------------------------ // Now to make sense around the wheel we need to alter the values based on if the location was in top or bottom half // and also right or left half of the wheel, by adding 90, 180, 270 etc. Also for some the initial locationAngle needs to be inverted. if ((topBottom == 'T') && (leftRight == 'R')) { locationAngle = Math.round(90 - result); } else if ((topBottom == 'B') && (leftRight == 'R')) { locationAngle = Math.round(result + 90); } else if ((topBottom == 'B') && (leftRight == 'L')) { locationAngle = Math.round((90 - result) + 180); } else if ((topBottom == 'T') && (leftRight == 'L')) { locationAngle = Math.round(result + 270); } // ------------------------------------------ // And now we have to adjust to make sense when the wheel is rotated from the 0 degrees either // positive or negative and it can be many times past 360 degrees. if (this.rotationAngle != 0) { var rotatedPosition = this.getRotationPosition(); // So we have this, now we need to alter the locationAngle as a result of this. locationAngle = (locationAngle - rotatedPosition); // If negative then take the location away from 360. if (locationAngle < 0) { locationAngle = (360 - Math.abs(locationAngle)); } } // ------------------------------------------ // OK, so after all of that we have the angle of a line between the centerX and centerY of the wheel and // the X and Y of the location on the canvas where the mouse was clicked. Now time to work out the segment // this corresponds to. We can use the segment start and end angles for this. var foundSegmentNumber = null; for (var x = 1; x <= this.numSegments; x ++) { // Due to segments sharing start and end angles, if line is clicked will pick earlier segment. if ((locationAngle >= this.segments[x].startAngle) && (locationAngle <= this.segments[x].endAngle)) { // To ensure that a click anywhere on the canvas in the segment direction will not cause a // segment to be matched, as well as the angles, we need to ensure the click was within the radius // of the segment (or circle if no segment radius). // If the hypotenuseSideLength (length of location from the center of the wheel) is with the radius // then we can assign the segment to the found segment and break out the loop. // Have to take in to account hollow wheels (doughnuts) so check is greater than innerRadius as // well as less than or equal to the outerRadius of the wheel. if ((hypotenuseSideLength >= this.innerRadius) && (hypotenuseSideLength <= this.outerRadius)) { foundSegmentNumber = x; break; } } } // Finally return the number. return foundSegmentNumber; } // ==================================================================================================================== // Returns a reference to the segment that is at the location of the pointer on the wheel. // ==================================================================================================================== Winwheel.prototype.getIndicatedSegment = function() { // Call function below to work this out and return the prizeNumber. var prizeNumber = this.getIndicatedSegmentNumber(); // Then simply return the segment in the segments array at that position. return this.segments[prizeNumber]; } // ==================================================================================================================== // Works out the segment currently pointed to by the pointer of the wheel. Normally called when the spinning has stopped // to work out the prize the user has won. Returns the number of the segment in the segments array. // ==================================================================================================================== Winwheel.prototype.getIndicatedSegmentNumber = function() { var indicatedPrize = 0; var rawAngle = this.getRotationPosition(); // Now we have the angle of the wheel, but we need to take in to account where the pointer is because // will not always be at the 12 o'clock 0 degrees location. var relativeAngle = Math.floor(this.pointerAngle - rawAngle); if (relativeAngle < 0) { relativeAngle = 360 - Math.abs(relativeAngle); } // Now we can work out the prize won by seeing what prize segment startAngle and endAngle the relativeAngle is between. for (x = 1; x < (this.segments.length); x ++) { if ((relativeAngle >= this.segments[x]['startAngle']) && (relativeAngle <= this.segments[x]['endAngle'])) { indicatedPrize = x; break; } } return indicatedPrize; } // ================================================================================================================================================== // Returns the rotation angle of the wheel corrected to 0-360 (i.e. removes all the multiples of 360). // ================================================================================================================================================== Winwheel.prototype.getRotationPosition = function() { var rawAngle = this.rotationAngle; // Get current rotation angle of wheel. // If positive work out how many times past 360 this is and then take the floor of this off the rawAngle. if (rawAngle >= 0) { if (rawAngle > 360) { // Get floor of the number of times past 360 degrees. var timesPast360 = Math.floor(rawAngle / 360); // Take all this extra off to get just the angle 0-360 degrees. rawAngle = (rawAngle - (360 * timesPast360)); } } else { // Is negative, need to take off the extra then convert in to 0-360 degree value // so if, for example, was -90 then final value will be (360 - 90) = 270 degrees. if (rawAngle < -360) { var timesPast360 = Math.ceil(rawAngle / 360); // Ceil when negative. rawAngle = (rawAngle - (360 * timesPast360)); // Is minus because dealing with negative. } rawAngle = (360 + rawAngle); // Make in the range 0-360. Is plus because raw is still negative. } return rawAngle; } // ================================================================================================================================================== // This function starts the wheel's animation by using the properties of the animation object of of the wheel to begin the a greensock tween. // ================================================================================================================================================== Winwheel.prototype.startAnimation = function() { if (this.animation) { // Call function to compute the animation properties. this.computeAnimation(); //++ when have multiple wheels and an animation for one or the other is played or stopped it affects the others //++ on the screen. Is there a way to give each wheel its own instance of tweenmax not affected by the other??? // Set this global variable to this object as an external function is required to call the draw() function on the wheel // each loop of the animation as Greensock cannot call the draw function directly on this class. winwheelToDrawDuringAnimation = this; // Instruct tween to call the winwheel animation loop each tick of the animation // this is required in order to re-draw the wheel and actually show the animation. TweenMax.ticker.addEventListener("tick", winwheelAnimationLoop); //++ How do we replay the animation without resetting the wheel, or must we reset and what is an easy way to do this. //++ perahps the wheel state before the animation is saved? var properties = new Array(null); properties[this.animation.propertyName] = this.animation.propertyValue; // Here we set the property to be animated and its value. properties['yoyo'] = this.animation.yoyo; // Set others. properties['repeat'] = this.animation.repeat; properties['ease'] = this.animation.easing; properties['onComplete'] = winwheelStopAnimation; // This is always set to function outside of this class. // Do the tween animation passing the properties from the animation object as an array of key => value pairs. // Keep reference to the tween object in the wheel as that allows pausing, resuming, and stopping while the animation is still running. this.tween = TweenMax.to(this, this.animation.duration, properties); } } // ================================================================================================================================================== // Use same function function which needs to be outside the class for the callback when it stops because is finished. // ================================================================================================================================================== Winwheel.prototype.stopAnimation = function(canCallback) { //++ @TODO re-check if kill is the correct thing here, and if there is more than one wheel object being animated (once sort how to do that) //++ what is the effect on it? // We can kill the animation using our tween object. winwheelToDrawDuringAnimation.tween.kill(); // We should still call the external function to stop the wheel being redrawn even click and also callback any function that is supposed to be. winwheelToDrawDuringAnimation = this; winwheelStopAnimation(canCallback); } // ================================================================================================================================================== // Pause animation by telling tween to pause. // ================================================================================================================================================== Winwheel.prototype.pauseAnimation = function() { if (this.tween) { this.tween.pause(); } } // ================================================================================================================================================== // Resume the animation by telling tween to continue playing it. // ================================================================================================================================================== Winwheel.prototype.resumeAnimation = function() { if (this.tween) { this.tween.play(); } } // ==================================================================================================================== // Called at the beginning of the startAnimation function and computes the values needed to do the animation // before it starts. This allows the developer to change the animation properties after the wheel has been created // and have the animation use the new values of the animation properties. // ==================================================================================================================== Winwheel.prototype.computeAnimation = function() { if (this.animation) { // Set the animation parameters for the specified animation type including some sensible defaults if values have not been specified. if (this.animation.type == 'spinOngoing') { // When spinning the rotationAngle is the wheel property which is animated. this.animation.propertyName = 'rotationAngle'; if (this.animation.spins == null) { this.animation.spins = 5; } if (this.animation.repeat == null) { this.animation.repeat = -1; // -1 means it will repeat forever. } if (this.animation.easing == null) { this.animation.easing = 'Linear.easeNone'; } if (this.animation.yoyo == null) { this.animation.yoyo = false; } // We need to calculate the propertyValue and this is the spins * 360 degrees. this.animation.propertyValue = (this.animation.spins * 360); // If the direction is anti-clockwise then make the property value negative. if (this.animation.direction == 'anti-clockwise') { this.animation.propertyValue = (0 - this.animation.propertyValue); } } else if (this.animation.type == 'spinToStop') { // Spin to stop the rotation angle is affected. this.animation.propertyName = 'rotationAngle'; if (this.animation.spins == null) { this.animation.spins = 5; } if (this.animation.repeat == null) { this.animation.repeat = 0; // As this is spin to stop we don't normally want it repeated. } if (this.animation.easing == null) { this.animation.easing = 'Power4.easeOut'; // This easing is fast start and slows over time. } if (this.animation.stopAngle == null) { // If the stop angle has not been specified then pick random between 0 and 359. this.animation._stopAngle = Math.floor((Math.random() * 359)); } else { // We need to set the internal to 360 minus what the user entered // because the wheel spins past 0 without this it would indicate the // prize on the opposite side of the wheel. this.animation._stopAngle = (360 - this.animation.stopAngle); } if (this.animation.yoyo == null) { this.animation.yoyo = false; } // The property value is the spins * 360 then plus or minus the stopAngle depending on if the rotation is clockwise or anti-clockwise. this.animation.propertyValue = (this.animation.spins * 360); if (this.animation.direction == 'anti-clockwise') { this.animation.propertyValue = (0 - this.animation.propertyValue); // Also if the value is anti-clockwise we need subtract the stopAngle (but to get the wheel to stop in the correct // place this is 360 minus the stop angle as the wheel is rotating backwards). this.animation.propertyValue -= (360 - this.animation._stopAngle); } else { // Add the stopAngle to the propertyValue as the wheel must rotate around to this place and stop there. this.animation.propertyValue += this.animation._stopAngle; } } else if (this.animation.type == 'spinAndBack') { // This is basically is a spin for a number of times then the animation reverses and goes back to start. // If a repeat is specified then this can be used to make the wheel "rock" left and right. // Again this is a spin so the rotationAngle the property which is animated. this.animation.propertyName = 'rotationAngle'; if (this.animation.spins == null) { this.animation.spins = 5; } if (this.animation.repeat == null) { this.animation.repeat = 1; // This needs to be set to at least 1 in order for the animation to reverse. } if (this.animation.easing == null) { this.animation.easing = 'Power2.easeInOut'; // This is slow at the start and end and fast in the middle. } if (this.animation.yoyo == null) { this.animation.yoyo = true; // This needs to be set to true to have the animation reverse back like a yo-yo. } if (this.animation.stopAngle == null) { this.animation._stopAngle = 0; } else { // We need to set the internal to 360 minus what the user entered // because the wheel spins past 0 without this it would indicate the // prize on the opposite side of the wheel. this.animation._stopAngle = (360 - this.animation.stopAngle); } // The property value is the spins * 360 then plus or minus the stopAngle depending on if the rotation is clockwise or anti-clockwise. this.animation.propertyValue = (this.animation.spins * 360); if (this.animation.direction == 'anti-clockwise') { this.animation.propertyValue = (0 - this.animation.propertyValue); // Also if the value is anti-clockwise we need subtract the stopAngle (but to get the wheel to stop in the correct // place this is 360 minus the stop angle as the wheel is rotating backwards). this.animation.propertyValue -= (360 - this.animation._stopAngle); } else { // Add the stopAngle to the propertyValue as the wheel must rotate around to this place and stop there. this.animation.propertyValue += this.animation._stopAngle; } } else if (this.animation.type == 'custom') { // Do nothing as all values must be set by the developer in the parameters // especially the propertyName and propertyValue. } } } // ==================================================================================================================== // Calculates and returns a random stop angle inside the specified segment number. Value will always be 1 degree inside // the start and end of the segment to avoid issue with the segment overlap. // ==================================================================================================================== Winwheel.prototype.getRandomForSegment = function(segmentNumber) { var stopAngle = 0; if (segmentNumber) { if (typeof this.segments[segmentNumber] !== 'undefined') { var startAngle = this.segments[segmentNumber].startAngle; var endAngle = this.segments[segmentNumber].endAngle; var range = (endAngle - startAngle) - 2; if (range > 0) { stopAngle = (startAngle + 1 + Math.floor((Math.random() * range))); } //++ At 2 degrees or less the segment is too small. //++ throw some sort of error? } //++ Error? } //++ Throw error? return stopAngle; } // ==================================================================================================================== // Class for the wheel spinning animation which like a segment becomes a property of the wheel. // ==================================================================================================================== function Animation(options) { defaultOptions = { 'type' : 'spinOngoing', // For now there are only supported types are spinOngoing (continuous), spinToStop, spinAndBack, custom. 'direction' : 'clockwise', // clockwise or anti-clockwise. 'propertyName' : null, // The name of the winning wheel property to be affected by the animation. 'propertyValue' : null, // The value the property is to be set to at the end of the animation. 'duration' : 10, // Duration of the animation. 'yoyo' : false, // If the animation is to reverse back again i.e. yo-yo. 'repeat' : 0, // The number of times the animation is to repeat, -1 will cause it to repeat forever. 'easing' : 'power3.easeOut', // The easing to use for the animation, default is the best for spin to stop. Use Linear.easeNone for no easing. 'stopAngle' : null, // Used for spinning, the angle at which the wheel is to stop. 'spins' : null, // Used for spinning, the number of complete 360 degree rotations the wheel is to do. 'clearTheCanvas' : null, // If set to true the canvas will be cleared before the wheel is re-drawn, false it will not, null the animation will abide by the value of this property for the parent wheel object. 'callbackFinished' : null, // Function to callback when the animation has finished. 'callbackBefore' : null, // Function to callback before the wheel is drawn each animation loop. 'callbackAfter' : null // Function to callback after the wheel is drawn each animation loop. }; // Now loop through the default options and create properties of this class set to the value for // the option passed in if a value was, or if not then set the value of the default. for (var key in defaultOptions) { if ((options != null) && (typeof(options[key]) !== 'undefined')) this[key] = options[key]; else this[key] = defaultOptions[key]; } // Also loop though the passed in options and add anything specified not part of the class in to it as a property. if (options != null) { for (var key in options) { if (typeof(this[key]) === 'undefined') { this[key] = options[key]; } } } } // ==================================================================================================================== // Class for segments. When creating a json of options can be passed in. // ==================================================================================================================== function Segment(options) { // Define default options for segments, most are null so that the global defaults for the wheel // are used if the values for a particular segment are not specifically set. defaultOptions = { 'size' : null, // Leave null for automatic. Valid values are degrees 0-360. Use percentToDegrees function if needed to convert. 'text' : '', // Default is blank. 'fillStyle' : null, // If null for the rest the global default will be used. 'strokeStyle' : null, 'lineWidth' : null, 'textFontFamily' : null, 'textFontSize' : null, 'textFontWeight' : null, 'textOrientation' : null, 'textAlignment' : null, 'textDirection' : null, 'textMargin' : null, 'textFillStyle' : null, 'textStrokeStyle' : null, 'textLineWidth' : null }; // Now loop through the default options and create properties of this class set to the value for // the option passed in if a value was, or if not then set the value of the default. for (var key in defaultOptions) { if ((options != null) && (typeof(options[key]) !== 'undefined')) this[key] = options[key]; else this[key] = defaultOptions[key]; } // Also loop though the passed in options and add anything specified not part of the class in to it as a property. // This allows the developer to easily add properties to segments at construction time. if (options != null) { for (var key in options) { if (typeof(this[key]) === 'undefined') { this[key] = options[key]; } } } // There are 2 additional properties which are set by the code, so need to define them here. // They are not in the default options because they are not something that should be set by the user, // the values are updated every time the updateSegmentSizes() function is called. this.startAngle = 0; this.endAngle = 0; } // ==================================================================================================================== // Class that is created as property of the wheel. Draws line from center of the wheel out to edge of canvas to // indicate where the code thinks the pointer location is. Helpful to get alignment correct esp when using images. // ==================================================================================================================== function PointerGuide(options) { defaultOptions = { 'display' : false, 'strokeStyle' : 'red', 'lineWidth' : 3 }; // Now loop through the default options and create properties of this class set to the value for // the option passed in if a value was, or if not then set the value of the default. for (var key in defaultOptions) { if ((options != null) && (typeof(options[key]) !== 'undefined')) { this[key] = options[key]; } else { this[key] = defaultOptions[key]; } } } // ==================================================================================================================== // This function takes the percent 0-100 and returns the number of degrees 0-360 this equates to. // ==================================================================================================================== function winwheelPercentToDegrees(percentValue) { var degrees = 0; if ((percentValue > 0) && (percentValue <= 100)) { var divider = (percentValue / 100); degrees = (360 * divider); } return degrees; } // ==================================================================================================================== // In order for the wheel to be re-drawn during the spin animation the function greesock calls needs to be outside // of the class as for some reason it errors if try to call winwheel.draw() directly. // ==================================================================================================================== var winwheelToDrawDuringAnimation = null; // This global is set by the winwheel class to the wheel object to be re-drawn. function winwheelAnimationLoop() { if (winwheelToDrawDuringAnimation) { // Check if the clearTheCanvas is specified for this animation, if not or it is not false then clear the canvas. if (winwheelToDrawDuringAnimation.animation.clearTheCanvas != false) { winwheelToDrawDuringAnimation.ctx.clearRect(0, 0, winwheelToDrawDuringAnimation.canvas.width, winwheelToDrawDuringAnimation.canvas.height); } // If there is a callback function which is supposed to be called before the wheel is drawn then do that. if (winwheelToDrawDuringAnimation.animation.callbackBefore != null) { eval(winwheelToDrawDuringAnimation.animation.callbackBefore); } // Call code to draw the wheel, pass in false as we never want it to clear the canvas as that would wipe anything drawn in the callbackBefore. winwheelToDrawDuringAnimation.draw(false); // If there is a callback function which is supposed to be called after the wheel has been drawn then do that. if (winwheelToDrawDuringAnimation.animation.callbackAfter != null) { eval(winwheelToDrawDuringAnimation.animation.callbackAfter); } } } // ==================================================================================================================== // This function is called-back when the greensock animation has finished. We remove the event listener to the function // above to stop the wheel being re-drawn all the time even though it is not animating as the greensock ticker keeps going. // ==================================================================================================================== function winwheelStopAnimation(canCallback) { // Remove the redraw from the ticker. TweenMax.ticker.removeEventListener("tick", winwheelAnimationLoop); // When the animation is stopped if canCallback is not false then try to call the callback. // false can be passed in to stop the after happening if the animation has been stopped before it ended normally. if (canCallback != false) { if (winwheelToDrawDuringAnimation.animation.callbackFinished != null) { eval(winwheelToDrawDuringAnimation.animation.callbackFinished); } } }
Winwheel.js
/* Winwheel.js, by Douglas McKechie @ www.dougtesting.net See website for tutorials and other documentation. The MIT License (MIT) Copyright (c) 2016 Douglas McKechie 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. */ // ==================================================================================================================== // The constructor for the WinWheel object, a JOSN-like array of options can be passed in. // By default the wheel is drawn if canvas object exists on the page, but can pass false as second parameter if don't want this to happen. // ==================================================================================================================== function Winwheel(options, drawWheel) { defaultOptions = { 'canvasId' : 'canvas', // Id of the canvas which the wheel is to draw on to. 'centerX' : null, // X position of the center of the wheel. The default of these are null which means will be placed in center of the canvas. 'centerY' : null, // Y position of the wheel center. If left null at time of construct the center of the canvas is used. 'outerRadius' : null, // The radius of the outside of the wheel. If left null it will be set to the radius from the center of the canvas to its shortest side. 'innerRadius' : 0, // Normally 0. Allows the creation of rings / doughnuts if set to value > 0. Should not exceed outer radius. 'numSegments' : 1, // The number of segments. Need at least one to draw. 'drawMode' : 'code', // The draw mode. Possible values are 'code' and 'image'. Default is code which means segments are drawn using canvas arc() function. 'rotationAngle' : 0, // The angle of rotation of the wheel - 0 is 12 o'clock position. 'textFontFamily' : 'Arial', // Segment text font, you should use web safe fonts. 'textFontSize' : 20, // Size of the segment text. 'textFontWeight' : 'bold', // Font weight. 'textOrientation' : 'horizontal', // Either horizontal, vertical, or curved. 'textAlignment' : 'center', // Either center, inner, or outer. 'textDirection' : 'normal', // Either normal or reversed. In normal mode for horizontal text in segment at 3 o'clock is correct way up, in reversed text at 9 o'clock segment is correct way up. 'textMargin' : null, // Margin between the inner or outer of the wheel (depends on textAlignment). 'textFillStyle' : 'black', // This is basically the text colour. 'textStrokeStyle' : null, // Basically the line colour for segment text, only looks good for large text so off by default. 'textLineWidth' : 1, // Width of the lines around the text. Even though this defaults to 1, a line is only drawn if textStrokeStyle specified. 'fillStyle' : 'silver', // The segment background colour. 'strokeStyle' : 'black', // Segment line colour. Again segment lines only drawn if this is specified. 'lineWidth' : 1, // Width of lines around segments. 'clearTheCanvas' : true, // When set to true the canvas will be cleared before the wheel is drawn. 'imageOverlay' : false, // If set to true in image drawing mode the outline of the segments will be displayed over the image. Does nothing in code drawMode. 'drawText' : true, // By default the text of the segments is rendered in code drawMode and not in image drawMode. 'pointerAngle' : 0, // Location of the pointer that indicates the prize when wheel has stopped. Default is 0 so the (corrected) 12 o'clock position. 'wheelImage' : null // Must be set to image data in order to use image to draw the wheel - drawMode must also be 'image'. }; // ----------------------------------------- // Loop through the default options and create properties of this class set to the value for the option passed in // or if not value for the option was passed in then to the default. for (var key in defaultOptions) { if ((options != null) && (typeof(options[key]) !== 'undefined')) { this[key] = options[key]; } else { this[key] = defaultOptions[key]; } } // Also loop though the passed in options and add anything specified not part of the class in to it as a property. if (options != null) { for (var key in options) { if (typeof(this[key]) === 'undefined') { this[key] = options[key]; } } } // ------------------------------------------ // If the id of the canvas is set, try to get the canvas as we need it for drawing. if (this.canvasId) { this.canvas = document.getElementById(this.canvasId); if (this.canvas) { // If the centerX and centerY have not been specified in the options then default to center of the canvas // and make the outerRadius half of the canvas width - this means the wheel will fill the canvas. if (this.centerX == null) { this.centerX = this.canvas.width / 2; } if (this.centerY == null) { this.centerY = this.canvas.height / 2; } if (this.outerRadius == null) { // Need to set to half the width of the shortest dimension of the canvas as the canvas may not be square. // Minus the line segment line width otherwise the lines around the segments on the top,left,bottom,right // side are chopped by the edge of the canvas. if (this.canvas.width < this.canvas.height) { this.outerRadius = (this.canvas.width / 2) - this.lineWidth; } else { this.outerRadius = (this.canvas.height / 2) - this.lineWidth; } } // Also get a 2D context to the canvas as we need this to draw with. this.ctx = this.canvas.getContext('2d'); } else { this.canvas = null; this.ctx = null; } } else { this.cavnas = null; this.ctx = null; } // ------------------------------------------ // Add array of segments to the wheel, then populate with segments if number of segments is specified for this object. this.segments = new Array(null); for (x = 1; x <= this.numSegments; x++) { // If options for the segments have been specified then create a segment sending these options so // the specified values are used instead of the defaults. if ((options != null) && (options['segments']) && (typeof(options['segments'][x-1]) !== 'undefined')) { this.segments[x] = new Segment(options['segments'][x-1]); } else { this.segments[x] = new Segment(); } } // ------------------------------------------ // Call function to update the segment sizes setting the starting and ending angles. this.updateSegmentSizes(); // If the text margin is null then set to same as font size as we want some by default. if (this.textMargin === null) { this.textMargin = (this.textFontSize / 1.7); } // ------------------------------------------ // If the animation options have been passed in then create animation object as a property of this class // and pass the options to it so the animation is set. Otherwise create default animation object. if ((options != null) && (options['animation']) && (typeof(options['animation']) !== 'undefined')) { this.animation = new Animation(options['animation']); } else { this.animation = new Animation(); } // ------------------------------------------ // On that note, if the drawMode is image change some defaults provided a value has not been specified. if (this.drawMode == 'image') { // Remove grey fillStyle. if (typeof(options['fillStyle']) === 'undefined') { this.fillStyle = null; } // Set strokeStyle to red. if (typeof(options['strokeStyle']) === 'undefined') { this.strokeStyle = 'red'; } // Set drawText to false as we will assume any text is part of the image. if (typeof(options['drawText']) === 'undefined') { this.drawText = false; } // Also set the lineWidth to 1 so that segment overlay will look correct. if (typeof(options['lineWidth']) === 'undefined') { this.lineWidth = 1; } // Set drawWheel to false as normally the image needs to be loaded first. if (typeof(drawWheel) === 'undefined') { drawWheel = false; } } else { // When in code drawMode the default is the wheel will draw. if (typeof(drawWheel) === 'undefined') { drawWheel = true; } } // Create pointer guide. if ((options != null) && (options['pointerGuide']) && (typeof(options['pointerGuide']) !== 'undefined')) { this.pointerGuide = new PointerGuide(options['pointerGuide']); } else { this.pointerGuide = new PointerGuide(); } // Finally if drawWheel is true then call function to render the wheel, segment text, overlay etc. if (drawWheel == true) { this.draw(this.clearTheCanvas); } } // ==================================================================================================================== // This function sorts out the segment sizes. Some segments may have set sizes, for the others what is left out of // 360 degrees is shared evenly. What this function actually does is set the start and end angle of the arcs. // ==================================================================================================================== Winwheel.prototype.updateSegmentSizes = function() { // If this object actually contains some segments if (this.segments) { // First add up the arc used for the segments where the size has been set. var arcUsed = 0; var numSet = 0; // Remember, to make it easy to access segments, the position of the segments in the array starts from 1 (not 0). for (x = 1; x <= this.numSegments; x ++) { if (this.segments[x].size !== null) { arcUsed += this.segments[x].size; numSet ++; } } var arcLeft = (360 - arcUsed); // Create variable to hold how much each segment with non-set size will get in terms of degrees. var degreesEach = 0; if (arcLeft > 0) { degreesEach = (arcLeft / (this.numSegments - numSet)); } // ------------------------------------------ // Now loop though and set the start and end angle of each segment. var currentDegree = 0; for (x = 1; x <= this.numSegments; x ++) { // Set start angle. this.segments[x].startAngle = currentDegree; // If the size is set then add this to the current degree to get the end, else add the degreesEach to it. if (this.segments[x].size) { currentDegree += this.segments[x].size; } else { currentDegree += degreesEach; } // Set end angle. this.segments[x].endAngle = currentDegree; } } } // ==================================================================================================================== // This function clears the canvas. Will wipe anything else which happens to be drawn on it. // ==================================================================================================================== Winwheel.prototype.clearCanvas = function() { if (this.ctx) { this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height); } } // ==================================================================================================================== // This function draws / re-draws the wheel on the canvas therefore rendering any changes. // ==================================================================================================================== Winwheel.prototype.draw = function(clearTheCanvas) { // If have the canvas context. if (this.ctx) { // Clear the canvas, unless told not to. if (typeof(clearTheCanvas) !== 'undefined') { if (clearTheCanvas == true) { this.clearCanvas(); } } else { this.clearCanvas(); } // Call functions to draw the segments and then segment text. if (this.drawMode == 'image') { // Draw the wheel by loading and drawing an image such as a png on the canvas. this.drawWheelImage(); // If we are to draw the text, do so before the overlay is drawn // as this allows the overlay to be used to create some interesting effects. if (this.drawText == true) { this.drawSegmentText(); } // If image overlay is true then call function to draw the segments over the top of the image. // This is useful during development to check alignment between where the code thinks the segments are and where they appear on the image. if (this.imageOverlay == true) { this.drawSegments(); } } else { // The default operation is to draw the segments using code via the canvas arc() method. this.drawSegments(); // The text is drawn on top. if (this.drawText == true) { this.drawSegmentText(); } } // If pointer guide is display property is set to true then call function to draw the pointer guide. if (this.pointerGuide.display == true) { this.drawPointerGuide(); } } } // ==================================================================================================================== // Draws a line from the center of the wheel to the outside at the angle where the code thinks the pointer is. // ==================================================================================================================== Winwheel.prototype.drawPointerGuide = function() { // If have canvas context. if (this.ctx) { this.ctx.save(); this.ctx.translate(this.canvas.width / 2, this.canvas.height / 2); this.ctx.rotate(this.degToRad(this.pointerAngle)); this.ctx.translate(-this.canvas.width / 2, -this.canvas.height / 2); this.ctx.strokeStyle = this.pointerGuide.strokeStyle; this.ctx.lineWidth = this.pointerGuide.lineWidth; // Draw from the center of the wheel out at the pointer angle to the edge of the canvas. this.ctx.beginPath(); this.ctx.moveTo(this.canvas.width / 2, this.canvas.height / 2); this.ctx.lineTo(this.centerX, -(this.outerRadius / 5)); this.ctx.stroke(); this.ctx.restore(); } } // ==================================================================================================================== // This function takes an image such as PNG and draws it on the canvas making its center at the centerX and center for the wheel. // ==================================================================================================================== Winwheel.prototype.drawWheelImage = function() { // Double check the wheelImage property of this class is not null. This does not actually detect that an image // source was set and actually loaded so might get error if this is not the case. This is why the initial call // to draw() should be done from a wheelImage.onload callback as detailed in example documentation. if (this.wheelImage != null) { // Work out the correct X and Y to draw the image at. We need to get the center point of the image // aligned over the center point of the wheel, we can't just place it at 0, 0. var imageLeft = (this.centerX - (this.wheelImage.height / 2)); var imageTop = (this.centerY - (this.wheelImage.width / 2)); // Rotate and then draw the wheel. We must rotate by the rotationAngle before drawing to ensure that // image wheels will spin. this.ctx.save(); this.ctx.translate(this.canvas.width / 2, this.canvas.height / 2); this.ctx.rotate(this.degToRad(this.rotationAngle)); this.ctx.translate(-this.canvas.width / 2, -this.canvas.height / 2); this.ctx.drawImage(this.wheelImage, imageLeft, imageTop); this.ctx.restore(); } } // ==================================================================================================================== // This function draws the wheel on the page by rendering the segments on the canvas. // ==================================================================================================================== Winwheel.prototype.drawSegments = function() { // Again check have context in case this function was called directly and not via draw function. if (this.ctx) { // Draw the segments if there is at least one in the segments array. if (this.segments) { // Loop though and output all segments - position 0 of the array is not used, so start loop from index 1 // this is to avoid confusion when talking about the first segment. for (x = 1; x <= this.numSegments; x ++) { // Get the segment object as we need it to read options from. seg = this.segments[x]; var fillStyle; var lineWidth; var strokeStyle; // Set the variables that defined in the segment, or use the default options. if (seg.fillStyle !== null) fillStyle = seg.fillStyle; else fillStyle = this.fillStyle; this.ctx.fillStyle = fillStyle; if (seg.lineWidth !== null) lineWidth = seg.lineWidth; else lineWidth = this.lineWidth; this.ctx.lineWidth = lineWidth; if (seg.strokeStyle !== null) strokeStyle = seg.strokeStyle; else strokeStyle = this.strokeStyle; this.ctx.strokeStyle = strokeStyle; // Check there is a strokeStyle or fillStyle, if either the the segment is invisible so should not // try to draw it otherwise a path is began but not ended. if ((strokeStyle) || (fillStyle)) { // ---------------------------------- // Begin a path as the segment consists of an arc and 2 lines. this.ctx.beginPath(); // If don't have an inner radius then move to the center of the wheel as we want a line out from the center // to the start of the arc for the outside of the wheel when we arc. Canvas will draw the connecting line for us. if (!this.innerRadius) { this.ctx.moveTo(this.centerX, this.centerY); } else { //++ do need to draw the starting line in the correct x + y based on the start angle //++ otherwise as seen when the wheel does not use up 360 the starting segment is missing the stroked side, } // Draw the outer arc of the segment clockwise in direction --> this.ctx.arc(this.centerX, this.centerY, this.outerRadius, this.degToRad(seg.startAngle + this.rotationAngle - 90), this.degToRad(seg.endAngle + this.rotationAngle - 90), false); if (this.innerRadius) { // Draw another arc, this time anticlockwise <-- at the innerRadius between the end angle and the start angle. // Canvas will draw a connecting line from the end of the outer arc to the beginning of the inner arc completing the shape. //++ Think the reason the lines are thinner for 2 of the segments is because the thing auto chops part of it //++ when doing the next one. Again think that actually drawing the lines will help. this.ctx.arc(this.centerX, this.centerY, this.innerRadius, this.degToRad(seg.endAngle + this.rotationAngle - 90), this.degToRad(seg.startAngle + this.rotationAngle - 90), true); } else { // If no inner radius then we draw a line back to the center of the wheel. this.ctx.lineTo(this.centerX, this.centerY); } // Fill and stroke the segment. Only do either if a style was specified, if the style is null then // we assume the developer did not want that particular thing. // For example no stroke style so no lines to be drawn. if (fillStyle) this.ctx.fill(); if (strokeStyle) this.ctx.stroke(); } } } } } // ==================================================================================================================== // This draws the text on the segments using the specified text options. // ==================================================================================================================== Winwheel.prototype.drawSegmentText = function() { // Again only draw the text if have a canvas context. if (this.ctx) { // Declare variables to hold the values. These are populated either with the value for the specific segment, // or if not specified then the global default value. var fontFamily; var fontSize; var fontWeight; var orientation; var alignment; var direction; var margin; var fillStyle; var strokeStyle; var lineWidth; var fontSetting; // Loop though all the segments. for (x = 1; x <= this.numSegments; x ++) { // Save the context so it is certain that each segment text option will not affect the other. this.ctx.save(); // Get the segment object as we need it to read options from. seg = this.segments[x]; // Check is text as no point trying to draw if there is no text to render. if (seg.text) { // Set values to those for the specific segment or use global default if null. if (seg.textFontFamily !== null) fontFamily = seg.textFontFamily; else fontFamily = this.textFontFamily; if (seg.textFontSize !== null) fontSize = seg.textFontSize; else fontSize = this.textFontSize; if (seg.textFontWeight !== null) fontWeight = seg.textFontWeight; else fontWeight = this.textFontWeight; if (seg.textOrientation !== null) orientation = seg.textOrientation; else orientation = this.textOrientation; if (seg.textAlignment !== null) alignment = seg.textAlignment; else alignment = this.textAlignment; if (seg.textDirection !== null) direction = seg.textDirection; else direction = this.textDirection; if (seg.textMargin !== null) margin = seg.textMargin; else margin = this.textMargin; if (seg.textFillStyle !== null) fillStyle = seg.textFillStyle; else fillStyle = this.textFillStyle; if (seg.textStrokeStyle !== null) strokeStyle = seg.textStrokeStyle; else strokeStyle = this.textStrokeStyle; if (seg.textLineWidth !== null) lineWidth = seg.textLineWidth; else lineWidth = this.textLineWidth; // ------------------------------ // We need to put the font bits together in to one string. fontSetting = ''; if (fontWeight != null) fontSetting += fontWeight + ' '; if (fontSize != null) fontSetting += fontSize + 'px '; // Fonts on canvas are always a px value. if (fontFamily != null) fontSetting += fontFamily; // Now set the canvas context to the decided values. this.ctx.font = fontSetting; this.ctx.fillStyle = fillStyle; this.ctx.strokeStyle = strokeStyle; this.ctx.lineWidth = lineWidth; // --------------------------------- // If direction is reversed then do things differently than if normal (which is the default - see further down) if (direction == 'reversed') { // When drawing reversed or 'upside down' we need to do some trickery on our part. // The canvas text rendering function still draws the text left to right and the correct way up, // so we need to overcome this with rotating the opposite side of the wheel the correct way up then pulling the text // through the center point to the correct segment it is supposed to be on. if (orientation == 'horizontal') { if (alignment == 'inner') this.ctx.textAlign = 'right'; else if (alignment == 'outer') this.ctx.textAlign = 'left'; else this.ctx.textAlign = 'center'; this.ctx.textBaseline = 'middle'; // Work out the angle to rotate the wheel, this is in the center of the segment but on the opposite side of the wheel which is why do -180. var textAngle = this.degToRad((seg.endAngle - ((seg.endAngle - seg.startAngle) / 2) + this.rotationAngle - 90) - 180); this.ctx.save(); this.ctx.translate(this.canvas.width / 2, this.canvas.height / 2); this.ctx.rotate(textAngle); this.ctx.translate(-this.canvas.width / 2, -this.canvas.height / 2); if (alignment == 'inner') { // In reversed state the margin is subtracted from the innerX. // When inner the inner radius also comes in to play. if (fillStyle) this.ctx.fillText(seg.text, this.centerX - this.innerRadius - margin, this.centerY); if (strokeStyle) this.ctx.strokeText(seg.text, this.centerX - this.innerRadius - margin, this.centerY); } else if (alignment == 'outer') { // In reversed state the position is the center minus the radius + the margin for outer aligned text. if (fillStyle) this.ctx.fillText(seg.text, this.centerX - this.outerRadius + margin, this.centerY); if (strokeStyle) this.ctx.strokeText(seg.text, this.centerX - this.outerRadius + margin, this.centerY); } else { // In reversed state the everything in minused. if (fillStyle) this.ctx.fillText(seg.text, this.centerX - this.innerRadius - ((this.outerRadius - this.innerRadius) / 2) - margin, this.centerY); if (strokeStyle) this.ctx.strokeText(seg.text, this.centerX - this.innerRadius - ((this.outerRadius - this.innerRadius) / 2) - margin, this.centerY); } this.ctx.restore(); } else if (orientation == 'vertical') { // See normal code further down for comments on how it works, this is similar by plus/minus is reversed. this.ctx.textAlign = 'center'; // In reversed mode this are reversed. if (alignment == 'inner') this.ctx.textBaseline = 'top'; else if (alignment == 'outer') this.ctx.textBaseline = 'bottom'; else this.ctx.textBaseline = 'middle'; var textAngle = (seg.endAngle - ((seg.endAngle - seg.startAngle) / 2) - 180); textAngle += this.rotationAngle; this.ctx.save(); this.ctx.translate(this.centerX, this.centerY); this.ctx.rotate(this.degToRad(textAngle)); this.ctx.translate(-this.centerX, -this.centerY); if (alignment == 'outer') var yPos = (this.centerY + this.outerRadius - margin); else if (alignment == 'inner') var yPos = (this.centerY + this.innerRadius + margin); // I have found that the text looks best when a fraction of the font size is shaved off. var yInc = (fontSize - (fontSize / 9)); // Loop though and output the characters. if (alignment == 'outer') { // In reversed mode outer means text in 6 o'clock segment sits at bottom of the wheel and we draw up. for (var c = (seg.text.length -1); c >= 0; c--) { character = seg.text.charAt(c); if (fillStyle) this.ctx.fillText(character, this.centerX, yPos); if (strokeStyle) this.ctx.strokeText(character, this.centerX, yPos); yPos -= yInc; } } else if (alignment == 'inner') { // In reversed mode inner text is drawn from top of segment at 6 o'clock position to bottom of the wheel. for (var c = 0; c < seg.text.length; c++) { character = seg.text.charAt(c); if (fillStyle) this.ctx.fillText(character, this.centerX, yPos); if (strokeStyle) this.ctx.strokeText(character, this.centerX, yPos); yPos += yInc; } } else if (alignment == 'center') { // Again for reversed this is the opposite of before. // If there is more than one character in the text then an adjustment to the position needs to be done. // What we are aiming for is to position the center of the text at the center point between the inner and outer radius. var centerAdjustment = 0; if (seg.text.length > 1) { centerAdjustment = (yInc * (seg.text.length -1) / 2); } var yPos = (this.centerY + this.innerRadius + ((this.outerRadius - this.innerRadius) / 2)) + centerAdjustment + margin; for (var c = (seg.text.length -1); c >= 0; c--) { character = seg.text.charAt(c); if (fillStyle) this.ctx.fillText(character, this.centerX, yPos); if (strokeStyle) this.ctx.strokeText(character, this.centerX, yPos); yPos -= yInc; } } this.ctx.restore(); } else if (orientation == 'curved') { // There is no built in canvas function to draw text around an arc, // so we need to do this ourselves. var radius = 0; // Set the alignment of the text - inner, outer, or center by calculating // how far out from the center point of the wheel the text is drawn. if (alignment == 'inner') { // When alignment is inner the radius is the innerRadius plus any margin. radius = this.innerRadius + margin; this.ctx.textBaseline = 'top'; } else if (alignment == 'outer') { // Outer it is the outerRadius minus any margin. radius = this.outerRadius - margin; this.ctx.textBaseline = 'bottom'; } else if (alignment == 'center') { // When center we want the text halfway between the inner and outer radius. radius = this.innerRadius + margin + ((this.outerRadius - this.innerRadius) / 2); this.ctx.textBaseline = 'middle'; } // Set the angle to increment by when looping though and outputting the characters in the text // as we do this by rotating the wheel small amounts adding each character. var anglePerChar = 0; var drawAngle = 0; // If more than one character in the text then... if (seg.text.length > 1) { // Text is drawn from the left. this.ctx.textAlign = 'left'; // Work out how much angle the text rendering loop below needs to rotate by for each character to render them next to each other. // I have discovered that 4 * the font size / 10 at 100px radius is the correct spacing for between the characters // using a monospace font, non monospace may look a little odd as in there will appear to be extra spaces between chars. anglePerChar = (4 * (fontSize / 10)); // Work out what percentage the radius the text will be drawn at is of 100px. radiusPercent = (100 / radius); // Then use this to scale up or down the anglePerChar value. // When the radius is less than 100px we need more angle between the letters, when radius is greater (so the text is further // away from the center of the wheel) the angle needs to be less otherwise the characters will appear further apart. anglePerChar = (anglePerChar * radiusPercent); // Next we want the text to be drawn in the middle of the segment, without this it would start at the beginning of the segment. // To do this we need to work out how much arc the text will take up in total then subtract half of this from the center // of the segment so that it sits centred. totalArc = (anglePerChar * seg.text.length); // Now set initial draw angle to half way between the start and end of the segment. drawAngle = seg.startAngle + (((seg.endAngle - seg.startAngle) / 2) - (totalArc / 2)); } else { // The initial draw angle is the center of the segment when only one character. drawAngle = (seg.startAngle + ((seg.endAngle - seg.startAngle) / 2)); // To ensure is dead-center the text alignment also needs to be centered. this.ctx.textAlign = 'center'; } // ---------------------- // Adjust the initial draw angle as needed to take in to account the rotationAngle of the wheel. drawAngle += this.rotationAngle; // And as with other 'reverse' text direction functions we need to subtract 180 degrees from the angle // because when it comes to draw the characters in the loop below we add the radius instead of subtract it. drawAngle -= 180; // ---------------------- // Now the drawing itself. // In reversed direction mode we loop through the characters in the text backwards in order for them to appear on screen correctly for (c = seg.text.length; c >= 0; c--) { this.ctx.save(); character = seg.text.charAt(c); // Rotate the wheel to the draw angle as we need to add the character at this location. this.ctx.translate(this.centerX, this.centerY); this.ctx.rotate(this.degToRad(drawAngle)); this.ctx.translate(-this.centerX, -this.centerY); // Now draw the character directly below the center point of the wheel at the appropriate radius. // Note in the reversed mode we add the radius to the this.centerY instead of subtract. if (strokeStyle) this.ctx.strokeText(character, this.centerX, this.centerY + radius); if (fillStyle) this.ctx.fillText(character, this.centerX, this.centerY + radius); // Increment the drawAngle by the angle per character so next loop we rotate // to the next angle required to draw the character at. drawAngle += anglePerChar; this.ctx.restore(); } } } else { // Normal direction so do things normally. // Check text orientation, of horizontal then reasonably straight forward, if vertical then a bit more work to do. if (orientation == 'horizontal') { // Based on the text alignment, set the correct value in the context. if (alignment == 'inner') this.ctx.textAlign = 'left'; else if (alignment == 'outer') this.ctx.textAlign = 'right'; else this.ctx.textAlign = 'center'; // Set this too. this.ctx.textBaseline = 'middle'; // Work out the angle around the wheel to draw the text at, which is simply in the middle of the segment the text is for. // The rotation angle is added in to correct the annoyance with the canvas arc drawing functions which put the 0 degrees at the 3 oclock var textAngle = this.degToRad(seg.endAngle - ((seg.endAngle - seg.startAngle) / 2) + this.rotationAngle - 90); // We need to rotate in order to draw the text because it is output horizontally, so to // place correctly around the wheel for all but a segment at 3 o'clock we need to rotate. this.ctx.save(); this.ctx.translate(this.centerX, this.centerY); this.ctx.rotate(textAngle); this.ctx.translate(-this.centerX, -this.centerY); // -------------------------- // Draw the text based on its alignment adding margin if inner or outer. if (alignment == 'inner') { // Inner means that the text is aligned with the inner of the wheel. If looking at a segment in in the 3 o'clock position // it would look like the text is left aligned within the segment. // Because the segments are smaller towards the inner of the wheel, in order for the text to fit is is a good idea that // a margin is added which pushes the text towards the outer a bit. // The inner radius also needs to be taken in to account as when inner aligned. // If fillstyle is set the draw the text filled in. if (fillStyle) this.ctx.fillText(seg.text, this.centerX + this.innerRadius + margin, this.centerY); // If stroke style is set draw the text outline. if (strokeStyle) this.ctx.strokeText(seg.text, this.centerX + this.innerRadius + margin, this.centerY); } else if (alignment == 'outer') { // Outer means the text is aligned with the outside of the wheel, so if looking at a segment in the 3 o'clock position // it would appear the text is right aligned. To position we add the radius of the wheel in to the equation // and subtract the margin this time, rather than add it. // I don't understand why, but in order of the text to render correctly with stroke and fill, the stroke needs to // come first when drawing outer, rather than second when doing inner. if (fillStyle) this.ctx.fillText(seg.text, this.centerX + this.outerRadius - margin, this.centerY); // If fillstyle the fill the text. if (strokeStyle) this.ctx.strokeText(seg.text, this.centerX + this.outerRadius - margin, this.centerY); } else { // In this case the text is to drawn centred in the segment. // Typically no margin is required, however even though centred the text can look closer to the inner of the wheel // due to the way the segments narrow in (is optical effect), so if a margin is specified it is placed on the inner // side so the text is pushed towards the outer. // If stoke style the stroke the text. if (fillStyle) this.ctx.fillText(seg.text, this.centerX + this.innerRadius + ((this.outerRadius - this.innerRadius) / 2) + margin, this.centerY); // If fillstyle the fill the text. if (strokeStyle) this.ctx.strokeText(seg.text, this.centerX + this.innerRadius + ((this.outerRadius - this.innerRadius) / 2) + margin, this.centerY); } // Restore the context so that wheel is returned to original position. this.ctx.restore(); } else if (orientation == 'vertical') { // If vertical then we need to do this ourselves because as far as I am aware there is no option built in to html canvas // which causes the text to draw downwards or upwards one character after another. // In this case the textAlign is always center, but the baseline is either top or bottom // depending on if inner or outer alignment has been specified. this.ctx.textAlign = 'center'; if (alignment == 'inner') this.ctx.textBaseline = 'bottom'; else if (alignment == 'outer') this.ctx.textBaseline = 'top'; else this.ctx.textBaseline = 'middle'; // The angle to draw the text at is halfway between the end and the starting angle of the segment. var textAngle = seg.endAngle - ((seg.endAngle - seg.startAngle) / 2); // Ensure the rotation angle of the wheel is added in, otherwise the test placement won't match // the segments they are supposed to be for. textAngle += this.rotationAngle; // Rotate so can begin to place the text. this.ctx.save(); this.ctx.translate(this.centerX, this.centerY); this.ctx.rotate(this.degToRad(textAngle)); this.ctx.translate(-this.centerX, -this.centerY); // Work out the position to start drawing in based on the alignment. // If outer then when considering a segment at the 12 o'clock position want to start drawing down from the top of the wheel. if (alignment == 'outer') var yPos = (this.centerY - this.outerRadius + margin); else if (alignment == 'inner') var yPos = (this.centerY - this.innerRadius - margin); // We need to know how much to move the y axis each time. // This is not quite simply the font size as that puts a larger gap in between the letters // than expected, especially with monospace fonts. I found that shaving a little off makes it look "right". var yInc = (fontSize - (fontSize / 9)); // Loop though and output the characters. if (alignment == 'outer') { // For this alignment we draw down from the top of a segment at the 12 o'clock position to simply // loop though the characters in order. for (var c = 0; c < seg.text.length; c++) { character = seg.text.charAt(c); if (fillStyle) this.ctx.fillText(character, this.centerX, yPos); if (strokeStyle) this.ctx.strokeText(character, this.centerX, yPos); yPos += yInc; } } else if (alignment == 'inner') { // Here we draw from the inner of the wheel up, but in order for the letters in the text text to // remain in the correct order when reading, we actually need to loop though the text characters backwards. for (var c = (seg.text.length -1); c >= 0; c--) { character = seg.text.charAt(c); if (fillStyle) this.ctx.fillText(character, this.centerX, yPos); if (strokeStyle) this.ctx.strokeText(character, this.centerX, yPos); yPos -= yInc; } } else if (alignment == 'center') { // This is the most complex of the three as we need to draw the text top down centred between the inner and outer of the wheel. // So logically we have to put the middle character of the text in the center then put the others each side of it. // In reality that is a really bad way to do it, we can achieve the same if not better positioning using a // variation on the method used for the rendering of outer aligned text once we have figured out the height of the text. // If there is more than one character in the text then an adjustment to the position needs to be done. // What we are aiming for is to position the center of the text at the center point between the inner and outer radius. var centerAdjustment = 0; if (seg.text.length > 1) { centerAdjustment = (yInc * (seg.text.length -1) / 2); } // Now work out where to start rendering the string. This is half way between the inner and outer of the wheel, with the // centerAdjustment included to correctly position texts with more than one character over the center. // If there is a margin it is used to push the text away from the center of the wheel. var yPos = (this.centerY - this.innerRadius - ((this.outerRadius - this.innerRadius) / 2)) - centerAdjustment - margin; // Now loop and draw just like outer text rendering. for (var c = 0; c < seg.text.length; c++) { character = seg.text.charAt(c); if (fillStyle) this.ctx.fillText(character, this.centerX, yPos); if (strokeStyle) this.ctx.strokeText(character, this.centerX, yPos); yPos += yInc; } } this.ctx.restore(); } else if (orientation == 'curved') { // There is no built in canvas function to draw text around an arc, so // we need to do this ourselves. var radius = 0; // Set the alignment of the text - inner, outer, or center by calculating // how far out from the center point of the wheel the text is drawn. if (alignment == 'inner') { // When alignment is inner the radius is the innerRadius plus any margin. radius = this.innerRadius + margin; this.ctx.textBaseline = 'bottom'; } else if (alignment == 'outer') { // Outer it is the outerRadius minus any margin. radius = this.outerRadius - margin; this.ctx.textBaseline = 'top'; } else if (alignment == 'center') { // When center we want the text halfway between the inner and outer radius. radius = this.innerRadius + margin + ((this.outerRadius - this.innerRadius) / 2); this.ctx.textBaseline = 'middle'; } // Set the angle to increment by when looping though and outputting the characters in the text // as we do this by rotating the wheel small amounts adding each character. var anglePerChar = 0; var drawAngle = 0; // If more than one character in the text then... if (seg.text.length > 1) { // Text is drawn from the left. this.ctx.textAlign = 'left'; // Work out how much angle the text rendering loop below needs to rotate by for each character to render them next to each other. // I have discovered that 4 * the font size / 10 at 100px radius is the correct spacing for between the characters // using a monospace font, non monospace may look a little odd as in there will appear to be extra spaces between chars. anglePerChar = (4 * (fontSize / 10)); // Work out what percentage the radius the text will be drawn at is of 100px. radiusPercent = (100 / radius); // Then use this to scale up or down the anglePerChar value. // When the radius is less than 100px we need more angle between the letters, when radius is greater (so the text is further // away from the center of the wheel) the angle needs to be less otherwise the characters will appear further apart. anglePerChar = (anglePerChar * radiusPercent); // Next we want the text to be drawn in the middle of the segment, without this it would start at the beginning of the segment. // To do this we need to work out how much arc the text will take up in total then subtract half of this from the center // of the segment so that it sits centred. totalArc = (anglePerChar * seg.text.length); // Now set initial draw angle to half way between the start and end of the segment. drawAngle = seg.startAngle + (((seg.endAngle - seg.startAngle) / 2) - (totalArc / 2)); } else { // The initial draw angle is the center of the segment when only one character. drawAngle = (seg.startAngle + ((seg.endAngle - seg.startAngle) / 2)); // To ensure is dead-center the text alignment also needs to be centred. this.ctx.textAlign = 'center'; } // ---------------------- // Adjust the initial draw angle as needed to take in to account the rotationAngle of the wheel. drawAngle += this.rotationAngle; // ---------------------- // Now the drawing itself. // Loop for each character in the text. for (c = 0; c < (seg.text.length); c++) { this.ctx.save(); character = seg.text.charAt(c); // Rotate the wheel to the draw angle as we need to add the character at this location. this.ctx.translate(this.centerX, this.centerY); this.ctx.rotate(this.degToRad(drawAngle)); this.ctx.translate(-this.centerX, -this.centerY); // Now draw the character directly above the center point of the wheel at the appropriate radius. if (strokeStyle) this.ctx.strokeText(character, this.centerX, this.centerY - radius); if (fillStyle) this.ctx.fillText(character, this.centerX, this.centerY - radius); // Increment the drawAngle by the angle per character so next loop we rotate // to the next angle required to draw the character at. drawAngle += anglePerChar; this.ctx.restore(); } } } } // Restore so all text options are reset ready for the next text. this.ctx.restore(); } } } // ==================================================================================================================== // Converts degrees to radians which is what is used when specifying the angles on HTML5 canvas arcs. // ==================================================================================================================== Winwheel.prototype.degToRad = function(d) { return d * 0.0174532925199432957; } // ==================================================================================================================== // This function sets the center location of the wheel, saves a function call to set x then y. // ==================================================================================================================== Winwheel.prototype.setCenter = function(x, y) { this.centerX = x; this.centerY = y; } // ==================================================================================================================== // This function allows a segment to be added to the wheel. The position of the segment is optional, // if not specified the new segment will be added to the end of the wheel. // ==================================================================================================================== Winwheel.prototype.addSegment = function(options, position) { // Create a new segment object passing the options in. newSegment = new Segment(options); // Increment the numSegments property of the class since new segment being added. this.numSegments ++; var segmentPos; // Work out where to place the segment, the default is simply as a new segment at the end of the wheel. if (typeof position !== 'undefined') { // Because we need to insert the segment at this position, not overwrite it, we need to move all segments after this // location along one in the segments array, before finally adding this new segment at the specified location. for (var x = this.numSegments; x > position; x --) { this.segments[x] = this.segments[x -1]; } this.segments[position] = newSegment; segmentPos = position; } else { this.segments[this.numSegments] = newSegment; segmentPos = this.numSegments; } // Since a segment has been added the segment sizes need to be re-computed so call function to do this. this.updateSegmentSizes(); // Return the segment object just created in the wheel (JavaScript will return it by reference), so that // further things can be done with it by the calling code if desired. return this.segments[segmentPos]; } // ==================================================================================================================== // This function must be used if the canvasId is changed as we also need to get the context of the new canvas. // ==================================================================================================================== Winwheel.prototype.setCanvasId = function(canvasId) { if (canvasId) { this.canvasId = canvasId; this.canvas = document.getElementById(this.canvasId); if (this.canvas) { this.ctx = this.canvas.getContext('2d'); } } else { this.canvasId = null this.ctx = null; this.canvas = null; } } // ==================================================================================================================== // This function deletes the specified segment from the wheel by removing it from the segments array. // It then sorts out the other bits such as update of the numSegments. // ==================================================================================================================== Winwheel.prototype.deleteSegment = function(position) { // There needs to be at least one segment in order for the wheel to draw, so only allow delete if there // is more than one segment currently left in the wheel. //++ check that specifying a position that does not exist - say 10 in a 6 segment wheel does not cause issues. if (this.numSegments > 1) { // If the position of the segment to remove has been specified. if (typeof position !== 'undefined') { // The array is to be shortened so we need to move all segments after the one // to be removed down one so there is no gap. for (var x = position; x < this.numSegments; x ++) { this.segments[x] = this.segments[x + 1]; } } // Unset the last item in the segments array since there is now one less. this.segments[this.numSegments] = undefined; // Decrement the number of segments, // then call function to update the segment sizes. this.numSegments --; this.updateSegmentSizes(); } } // ==================================================================================================================== // This function takes the x an the y of a mouse event, such as click or move, and converts the x and the y in to // co-ordinates on the canvas as the raw values are the x and the y from the top and left of the user's browser. // ==================================================================================================================== Winwheel.prototype.windowToCanvas = function(x, y) { var bbox = this.canvas.getBoundingClientRect(); return { x: Math.floor(x - bbox.left * (this.canvas.width / bbox.width)), y: Math.floor(y - bbox.top * (this.canvas.height / bbox.height)) }; } // ==================================================================================================================== // This function returns the segment object located at the specified x and y coordinates on the canvas. // It is used to allow things to be done with a segment clicked by the user, such as highlight, display or change some values, etc. // ==================================================================================================================== Winwheel.prototype.getSegmentAt = function(x, y) { var foundSegment = null; // Call function to return segment number. var segmentNumber = this.getSegmentNumberAt(x, y); // If found one then set found segment to pointer to the segment object. if (segmentNumber !== null) { foundSegment = this.segments[segmentNumber]; } return foundSegment; } // ==================================================================================================================== // Returns the number of the segment clicked instead of the segment object. // ==================================================================================================================== Winwheel.prototype.getSegmentNumberAt = function(x, y) { // KNOWN ISSUE: this does not work correct if the canvas is scaled using css, or has padding, border. // @TODO see if can find a solution at some point, check windowToCanvas working as needed, then below. // Call function above to convert the raw x and y from the user's browser to canvas coordinates // i.e. top and left is top and left of canvas, not top and left of the user's browser. var loc = this.windowToCanvas(x, y); // ------------------------------------------ // Now start the process of working out the segment clicked. // First we need to figure out the angle of an imaginary line between the centerX and centerY of the wheel and // the X and Y of the location (for example a mouse click). var topBottom; var leftRight; var adjacentSideLength; var oppositeSideLength; var hypotenuseSideLength; // We will use right triangle maths with the TAN function. // The start of the triangle is the wheel center, the adjacent side is along the x axis, and the opposite side is along the y axis. // We only ever use positive numbers to work out the triangle and the center of the wheel needs to be considered as 0 for the numbers // in the maths which is why there is the subtractions below. We also remember what quadrant of the wheel the location is in as we // need this information later to add 90, 180, 270 degrees to the angle worked out from the triangle to get the position around a 360 degree wheel. if (loc.x > this.centerX) { adjacentSideLength = (loc.x - this.centerX); leftRight = 'R'; // Location is in the right half of the wheel. } else { adjacentSideLength = (this.centerX - loc.x); leftRight = 'L'; // Location is in the left half of the wheel. } if (loc.y > this.centerY) { oppositeSideLength = (loc.y - this.centerY); topBottom = 'B'; // Bottom half of wheel. } else { oppositeSideLength = (this.centerY - loc.y); topBottom = 'T'; // Top Half of wheel. } // Now divide opposite by adjacent to get tan value. var tanVal = oppositeSideLength / adjacentSideLength; // Use the tan function and convert results to degrees since that is what we work with. var result = (Math.atan(tanVal) * 180/Math.PI); var locationAngle = 0; // We also need the length of the hypotenuse as later on we need to compare this to the outerRadius of the segment / circle. hypotenuseSideLength = Math.sqrt((oppositeSideLength * oppositeSideLength) + (adjacentSideLength * adjacentSideLength)); // ------------------------------------------ // Now to make sense around the wheel we need to alter the values based on if the location was in top or bottom half // and also right or left half of the wheel, by adding 90, 180, 270 etc. Also for some the initial locationAngle needs to be inverted. if ((topBottom == 'T') && (leftRight == 'R')) { locationAngle = Math.round(90 - result); } else if ((topBottom == 'B') && (leftRight == 'R')) { locationAngle = Math.round(result + 90); } else if ((topBottom == 'B') && (leftRight == 'L')) { locationAngle = Math.round((90 - result) + 180); } else if ((topBottom == 'T') && (leftRight == 'L')) { locationAngle = Math.round(result + 270); } // ------------------------------------------ // And now we have to adjust to make sense when the wheel is rotated from the 0 degrees either // positive or negative and it can be many times past 360 degrees. if (this.rotationAngle != 0) { var rotatedPosition = this.getRotationPosition(); // So we have this, now we need to alter the locationAngle as a result of this. locationAngle = (locationAngle - rotatedPosition); // If negative then take the location away from 360. if (locationAngle < 0) { locationAngle = (360 - Math.abs(locationAngle)); } } // ------------------------------------------ // OK, so after all of that we have the angle of a line between the centerX and centerY of the wheel and // the X and Y of the location on the canvas where the mouse was clicked. Now time to work out the segment // this corresponds to. We can use the segment start and end angles for this. var foundSegmentNumber = null; for (var x = 1; x <= this.numSegments; x ++) { // Due to segments sharing start and end angles, if line is clicked will pick earlier segment. if ((locationAngle >= this.segments[x].startAngle) && (locationAngle <= this.segments[x].endAngle)) { // To ensure that a click anywhere on the canvas in the segment direction will not cause a // segment to be matched, as well as the angles, we need to ensure the click was within the radius // of the segment (or circle if no segment radius). // If the hypotenuseSideLength (length of location from the center of the wheel) is with the radius // then we can assign the segment to the found segment and break out the loop. // Have to take in to account hollow wheels (doughnuts) so check is greater than innerRadius as // well as less than or equal to the outerRadius of the wheel. if ((hypotenuseSideLength >= this.innerRadius) && (hypotenuseSideLength <= this.outerRadius)) { foundSegmentNumber = x; break; } } } // Finally return the number. return foundSegmentNumber; } // ==================================================================================================================== // Returns a reference to the segment that is at the location of the pointer on the wheel. // ==================================================================================================================== Winwheel.prototype.getIndicatedSegment = function() { // Call function below to work this out and return the prizeNumber. var prizeNumber = this.getIndicatedSegmentNumber(); // Then simply return the segment in the segments array at that position. return this.segments[prizeNumber]; } // ==================================================================================================================== // Works out the segment currently pointed to by the pointer of the wheel. Normally called when the spinning has stopped // to work out the prize the user has won. Returns the number of the segment in the segments array. // ==================================================================================================================== Winwheel.prototype.getIndicatedSegmentNumber = function() { var indicatedPrize = 0; var rawAngle = this.getRotationPosition(); // Now we have the angle of the wheel, but we need to take in to account where the pointer is because // will not always be at the 12 o'clock 0 degrees location. var relativeAngle = Math.floor(this.pointerAngle - rawAngle); if (relativeAngle < 0) { relativeAngle = 360 - Math.abs(relativeAngle); } // Now we can work out the prize won by seeing what prize segment startAngle and endAngle the relativeAngle is between. for (x = 1; x < (this.segments.length); x ++) { if ((relativeAngle >= this.segments[x]['startAngle']) && (relativeAngle <= this.segments[x]['endAngle'])) { indicatedPrize = x; break; } } return indicatedPrize; } // ================================================================================================================================================== // Returns the rotation angle of the wheel corrected to 0-360 (i.e. removes all the multiples of 360). // ================================================================================================================================================== Winwheel.prototype.getRotationPosition = function() { var rawAngle = this.rotationAngle; // Get current rotation angle of wheel. // If positive work out how many times past 360 this is and then take the floor of this off the rawAngle. if (rawAngle >= 0) { if (rawAngle > 360) { // Get floor of the number of times past 360 degrees. var timesPast360 = Math.floor(rawAngle / 360); // Take all this extra off to get just the angle 0-360 degrees. rawAngle = (rawAngle - (360 * timesPast360)); } } else { // Is negative, need to take off the extra then convert in to 0-360 degree value // so if, for example, was -90 then final value will be (360 - 90) = 270 degrees. if (rawAngle < -360) { var timesPast360 = Math.ceil(rawAngle / 360); // Ceil when negative. rawAngle = (rawAngle - (360 * timesPast360)); // Is minus because dealing with negative. } rawAngle = (360 + rawAngle); // Make in the range 0-360. Is plus because raw is still negative. } return rawAngle; } // ================================================================================================================================================== // This function starts the wheel's animation by using the properties of the animation object of of the wheel to begin the a greensock tween. // ================================================================================================================================================== Winwheel.prototype.startAnimation = function() { if (this.animation) { // Call function to compute the animation properties. this.computeAnimation(); //++ when have multiple wheels and an animation for one or the other is played or stopped it affects the others //++ on the screen. Is there a way to give each wheel its own instance of tweenmax not affected by the other??? // Set this global variable to this object as an external function is required to call the draw() function on the wheel // each loop of the animation as Greensock cannot call the draw function directly on this class. winwheelToDrawDuringAnimation = this; // Instruct tween to call the winwheel animation loop each tick of the animation // this is required in order to re-draw the wheel and actually show the animation. TweenMax.ticker.addEventListener("tick", winwheelAnimationLoop); //++ How do we replay the animation without resetting the wheel, or must we reset and what is an easy way to do this. //++ perahps the wheel state before the animation is saved? var properties = new Array(null); properties[this.animation.propertyName] = this.animation.propertyValue; // Here we set the property to be animated and its value. properties['yoyo'] = this.animation.yoyo; // Set others. properties['repeat'] = this.animation.repeat; properties['ease'] = this.animation.easing; properties['onComplete'] = winwheelStopAnimation; // This is always set to function outside of this class. // Do the tween animation passing the properties from the animation object as an array of key => value pairs. // Keep reference to the tween object in the wheel as that allows pausing, resuming, and stopping while the animation is still running. this.tween = TweenMax.to(this, this.animation.duration, properties); } } // ================================================================================================================================================== // Use same function function which needs to be outside the class for the callback when it stops because is finished. // ================================================================================================================================================== Winwheel.prototype.stopAnimation = function(canCallback) { //++ @TODO re-check if kill is the correct thing here, and if there is more than one wheel object being animated (once sort how to do that) //++ what is the effect on it? // We can kill the animation using our tween object. winwheelToDrawDuringAnimation.tween.kill(); // We should still call the external function to stop the wheel being redrawn even click and also callback any function that is supposed to be. winwheelToDrawDuringAnimation = this; winwheelStopAnimation(canCallback); } // ================================================================================================================================================== // Pause animation by telling tween to pause. // ================================================================================================================================================== Winwheel.prototype.pauseAnimation = function() { if (this.tween) { this.tween.pause(); } } // ================================================================================================================================================== // Resume the animation by telling tween to continue playing it. // ================================================================================================================================================== Winwheel.prototype.resumeAnimation = function() { if (this.tween) { this.tween.play(); } } // ==================================================================================================================== // Called at the beginning of the startAnimation function and computes the values needed to do the animation // before it starts. This allows the developer to change the animation properties after the wheel has been created // and have the animation use the new values of the animation properties. // ==================================================================================================================== Winwheel.prototype.computeAnimation = function() { if (this.animation) { // Set the animation parameters for the specified animation type including some sensible defaults if values have not been specified. if (this.animation.type == 'spinOngoing') { // When spinning the rotationAngle is the wheel property which is animated. this.animation.propertyName = 'rotationAngle'; if (this.animation.spins == null) { this.animation.spins = 5; } if (this.animation.repeat == null) { this.animation.repeat = -1; // -1 means it will repeat forever. } if (this.animation.easing == null) { this.animation.easing = 'Linear.easeNone'; } if (this.animation.yoyo == null) { this.animation.yoyo = false; } // We need to calculate the propertyValue and this is the spins * 360 degrees. this.animation.propertyValue = (this.animation.spins * 360); // If the direction is anti-clockwise then make the property value negative. if (this.animation.direction == 'anti-clockwise') { this.animation.propertyValue = (0 - this.animation.propertyValue); } } else if (this.animation.type == 'spinToStop') { // Spin to stop the rotation angle is affected. this.animation.propertyName = 'rotationAngle'; if (this.animation.spins == null) { this.animation.spins = 5; } if (this.animation.repeat == null) { this.animation.repeat = 0; // As this is spin to stop we don't normally want it repeated. } if (this.animation.easing == null) { this.animation.easing = 'Power4.easeOut'; // This easing is fast start and slows over time. } if (this.animation.stopAngle == null) { // If the stop angle has not been specified then pick random between 0 and 359. this.animation._stopAngle = Math.floor((Math.random() * 359)); } else { // We need to set the internal to 360 minus what the user entered // because the wheel spins past 0 without this it would indicate the // prize on the opposite side of the wheel. this.animation._stopAngle = (360 - this.animation.stopAngle); } if (this.animation.yoyo == null) { this.animation.yoyo = false; } // The property value is the spins * 360 then plus or minus the stopAngle depending on if the rotation is clockwise or anti-clockwise. this.animation.propertyValue = (this.animation.spins * 360); if (this.animation.direction == 'anti-clockwise') { this.animation.propertyValue = (0 - this.animation.propertyValue); // Also if the value is anti-clockwise we need subtract the stopAngle (but to get the wheel to stop in the correct // place this is 360 minus the stop angle as the wheel is rotating backwards). this.animation.propertyValue -= (360 - this.animation._stopAngle); } else { // Add the stopAngle to the propertyValue as the wheel must rotate around to this place and stop there. this.animation.propertyValue += this.animation._stopAngle; } } else if (this.animation.type == 'spinAndBack') { // This is basically is a spin for a number of times then the animation reverses and goes back to start. // If a repeat is specified then this can be used to make the wheel "rock" left and right. // Again this is a spin so the rotationAngle the property which is animated. this.animation.propertyName = 'rotationAngle'; if (this.animation.spins == null) { this.animation.spins = 5; } if (this.animation.repeat == null) { this.animation.repeat = 1; // This needs to be set to at least 1 in order for the animation to reverse. } if (this.animation.easing == null) { this.animation.easing = 'Power2.easeInOut'; // This is slow at the start and end and fast in the middle. } if (this.animation.yoyo == null) { this.animation.yoyo = true; // This needs to be set to true to have the animation reverse back like a yo-yo. } if (this.animation.stopAngle == null) { this.animation._stopAngle = 0; } else { // We need to set the internal to 360 minus what the user entered // because the wheel spins past 0 without this it would indicate the // prize on the opposite side of the wheel. this.animation._stopAngle = (360 - this.animation.stopAngle); } // The property value is the spins * 360 then plus or minus the stopAngle depending on if the rotation is clockwise or anti-clockwise. this.animation.propertyValue = (this.animation.spins * 360); if (this.animation.direction == 'anti-clockwise') { this.animation.propertyValue = (0 - this.animation.propertyValue); // Also if the value is anti-clockwise we need subtract the stopAngle (but to get the wheel to stop in the correct // place this is 360 minus the stop angle as the wheel is rotating backwards). this.animation.propertyValue -= (360 - this.animation._stopAngle); } else { // Add the stopAngle to the propertyValue as the wheel must rotate around to this place and stop there. this.animation.propertyValue += this.animation._stopAngle; } } else if (this.animation.type == 'custom') { // Do nothing as all values must be set by the developer in the parameters // especially the propertyName and propertyValue. } } } // ==================================================================================================================== // Calculates and returns a random stop angle inside the specified segment number. Value will always be 1 degree inside // the start and end of the segment to avoid issue with the segment overlap. // ==================================================================================================================== Winwheel.prototype.getRandomForSegment = function(segmentNumber) { var stopAngle = 0; if (segmentNumber) { if (typeof this.segments[segmentNumber] !== 'undefined') { var startAngle = this.segments[segmentNumber].startAngle; var endAngle = this.segments[segmentNumber].endAngle; var range = (endAngle - startAngle) - 2; if (range > 0) { stopAngle = (startAngle + 1 + Math.floor((Math.random() * range))); } //++ At 2 degrees or less the segment is too small. //++ throw some sort of error? } //++ Error? } //++ Throw error? return stopAngle; } // ==================================================================================================================== // Class for the wheel spinning animation which like a segment becomes a property of the wheel. // ==================================================================================================================== function Animation(options) { defaultOptions = { 'type' : 'spinOngoing', // For now there are only supported types are spinOngoing (continuous), spinToStop, spinAndBack, custom. 'direction' : 'clockwise', // clockwise or anti-clockwise. 'propertyName' : null, // The name of the winning wheel property to be affected by the animation. 'propertyValue' : null, // The value the property is to be set to at the end of the animation. 'duration' : 10, // Duration of the animation. 'yoyo' : false, // If the animation is to reverse back again i.e. yo-yo. 'repeat' : 0, // The number of times the animation is to repeat, -1 will cause it to repeat forever. 'easing' : 'power3.easeOut', // The easing to use for the animation, default is the best for spin to stop. Use Linear.easeNone for no easing. 'stopAngle' : null, // Used for spinning, the angle at which the wheel is to stop. 'spins' : null, // Used for spinning, the number of complete 360 degree rotations the wheel is to do. 'clearTheCanvas' : null, // If set to true the canvas will be cleared before the wheel is re-drawn, false it will not, null the animation will abide by the value of this property for the parent wheel object. 'callbackFinished' : null, // Function to callback when the animation has finished. 'callbackBefore' : null, // Function to callback before the wheel is drawn each animation loop. 'callbackAfter' : null // Function to callback after the wheel is drawn each animation loop. }; // Now loop through the default options and create properties of this class set to the value for // the option passed in if a value was, or if not then set the value of the default. for (var key in defaultOptions) { if ((options != null) && (typeof(options[key]) !== 'undefined')) this[key] = options[key]; else this[key] = defaultOptions[key]; } // Also loop though the passed in options and add anything specified not part of the class in to it as a property. if (options != null) { for (var key in options) { if (typeof(this[key]) === 'undefined') { this[key] = options[key]; } } } } // ==================================================================================================================== // Class for segments. When creating a json of options can be passed in. // ==================================================================================================================== function Segment(options) { // Define default options for segments, most are null so that the global defaults for the wheel // are used if the values for a particular segment are not specifically set. defaultOptions = { 'size' : null, // Leave null for automatic. Valid values are degrees 0-360. Use percentToDegrees function if needed to convert. 'text' : '', // Default is blank. 'fillStyle' : null, // If null for the rest the global default will be used. 'strokeStyle' : null, 'lineWidth' : null, 'textFontFamily' : null, 'textFontSize' : null, 'textFontWeight' : null, 'textOrientation' : null, 'textAlignment' : null, 'textDirection' : null, 'textMargin' : null, 'textFillStyle' : null, 'textStrokeStyle' : null, 'textLineWidth' : null }; // Now loop through the default options and create properties of this class set to the value for // the option passed in if a value was, or if not then set the value of the default. for (var key in defaultOptions) { if ((options != null) && (typeof(options[key]) !== 'undefined')) this[key] = options[key]; else this[key] = defaultOptions[key]; } // Also loop though the passed in options and add anything specified not part of the class in to it as a property. // This allows the developer to easily add properties to segments at construction time. if (options != null) { for (var key in options) { if (typeof(this[key]) === 'undefined') { this[key] = options[key]; } } } // There are 2 additional properties which are set by the code, so need to define them here. // They are not in the default options because they are not something that should be set by the user, // the values are updated every time the updateSegmentSizes() function is called. this.startAngle = 0; this.endAngle = 0; } // ==================================================================================================================== // Class that is created as property of the wheel. Draws line from center of the wheel out to edge of canvas to // indicate where the code thinks the pointer location is. Helpful to get alignment correct esp when using images. // ==================================================================================================================== function PointerGuide(options) { defaultOptions = { 'display' : false, 'strokeStyle' : 'red', 'lineWidth' : 3 }; // Now loop through the default options and create properties of this class set to the value for // the option passed in if a value was, or if not then set the value of the default. for (var key in defaultOptions) { if ((options != null) && (typeof(options[key]) !== 'undefined')) { this[key] = options[key]; } else { this[key] = defaultOptions[key]; } } } // ==================================================================================================================== // This function takes the percent 0-100 and returns the number of degrees 0-360 this equates to. // ==================================================================================================================== function winwheelPercentToDegrees(percentValue) { var degrees = 0; if ((percentValue > 0) && (percentValue <= 100)) { var divider = (percentValue / 100); degrees = (360 * divider); } return degrees; } // ==================================================================================================================== // In order for the wheel to be re-drawn during the spin animation the function greesock calls needs to be outside // of the class as for some reason it errors if try to call winwheel.draw() directly. // ==================================================================================================================== var winwheelToDrawDuringAnimation = null; // This global is set by the winwheel class to the wheel object to be re-drawn. function winwheelAnimationLoop() { if (winwheelToDrawDuringAnimation) { // Check if the clearTheCanvas is specified for this animation, if not or it is not false then clear the canvas. if (winwheelToDrawDuringAnimation.animation.clearTheCanvas != false) { winwheelToDrawDuringAnimation.ctx.clearRect(0, 0, winwheelToDrawDuringAnimation.canvas.width, winwheelToDrawDuringAnimation.canvas.height); } // If there is a callback function which is supposed to be called before the wheel is drawn then do that. if (winwheelToDrawDuringAnimation.animation.callbackBefore != null) { eval(winwheelToDrawDuringAnimation.animation.callbackBefore); } // Call code to draw the wheel, pass in false as we never want it to clear the canvas as that would wipe anything drawn in the callbackBefore. winwheelToDrawDuringAnimation.draw(false); // If there is a callback function which is supposed to be called after the wheel has been drawn then do that. if (winwheelToDrawDuringAnimation.animation.callbackAfter != null) { eval(winwheelToDrawDuringAnimation.animation.callbackAfter); } } } // ==================================================================================================================== // This function is called-back when the greensock animation has finished. We remove the event listener to the function // above to stop the wheel being re-drawn all the time even though it is not animating as the greensock ticker keeps going. // ==================================================================================================================== function winwheelStopAnimation(canCallback) { // Remove the redraw from the ticker. TweenMax.ticker.removeEventListener("tick", winwheelAnimationLoop); // When the animation is stopped if canCallback is not false then try to call the callback. // false can be passed in to stop the after happening if the animation has been stopped before it ended normally. if (canCallback != false) { if (winwheelToDrawDuringAnimation.animation.callbackFinished != null) { eval(winwheelToDrawDuringAnimation.animation.callbackFinished); } } }
Convert tabs to spaces
Winwheel.js
Convert tabs to spaces
<ide><path>inwheel.js <ide> /* <del> Winwheel.js, by Douglas McKechie @ www.dougtesting.net <del> See website for tutorials and other documentation. <del> <del> The MIT License (MIT) <del> <del> Copyright (c) 2016 Douglas McKechie <del> <del> Permission is hereby granted, free of charge, to any person obtaining a copy <del> of this software and associated documentation files (the "Software"), to deal <del> in the Software without restriction, including without limitation the rights <del> to use, copy, modify, merge, publish, distribute, sublicense, and/or sell <del> copies of the Software, and to permit persons to whom the Software is <del> furnished to do so, subject to the following conditions: <del> <del> The above copyright notice and this permission notice shall be included in all <del> copies or substantial portions of the Software. <del> <del> THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR <del> IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, <del> FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE <del> AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER <del> LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, <del> OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE <del> SOFTWARE. <add> Winwheel.js, by Douglas McKechie @ www.dougtesting.net <add> See website for tutorials and other documentation. <add> <add> The MIT License (MIT) <add> <add> Copyright (c) 2016 Douglas McKechie <add> <add> Permission is hereby granted, free of charge, to any person obtaining a copy <add> of this software and associated documentation files (the "Software"), to deal <add> in the Software without restriction, including without limitation the rights <add> to use, copy, modify, merge, publish, distribute, sublicense, and/or sell <add> copies of the Software, and to permit persons to whom the Software is <add> furnished to do so, subject to the following conditions: <add> <add> The above copyright notice and this permission notice shall be included in all <add> copies or substantial portions of the Software. <add> <add> THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR <add> IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, <add> FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE <add> AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER <add> LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, <add> OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE <add> SOFTWARE. <ide> */ <ide> <ide> // ==================================================================================================================== <ide> // ==================================================================================================================== <ide> function Winwheel(options, drawWheel) <ide> { <del> defaultOptions = { <del> 'canvasId' : 'canvas', // Id of the canvas which the wheel is to draw on to. <del> 'centerX' : null, // X position of the center of the wheel. The default of these are null which means will be placed in center of the canvas. <del> 'centerY' : null, // Y position of the wheel center. If left null at time of construct the center of the canvas is used. <del> 'outerRadius' : null, // The radius of the outside of the wheel. If left null it will be set to the radius from the center of the canvas to its shortest side. <del> 'innerRadius' : 0, // Normally 0. Allows the creation of rings / doughnuts if set to value > 0. Should not exceed outer radius. <del> 'numSegments' : 1, // The number of segments. Need at least one to draw. <del> 'drawMode' : 'code', // The draw mode. Possible values are 'code' and 'image'. Default is code which means segments are drawn using canvas arc() function. <del> 'rotationAngle' : 0, // The angle of rotation of the wheel - 0 is 12 o'clock position. <del> 'textFontFamily' : 'Arial', // Segment text font, you should use web safe fonts. <del> 'textFontSize' : 20, // Size of the segment text. <del> 'textFontWeight' : 'bold', // Font weight. <del> 'textOrientation' : 'horizontal', // Either horizontal, vertical, or curved. <del> 'textAlignment' : 'center', // Either center, inner, or outer. <del> 'textDirection' : 'normal', // Either normal or reversed. In normal mode for horizontal text in segment at 3 o'clock is correct way up, in reversed text at 9 o'clock segment is correct way up. <del> 'textMargin' : null, // Margin between the inner or outer of the wheel (depends on textAlignment). <del> 'textFillStyle' : 'black', // This is basically the text colour. <del> 'textStrokeStyle' : null, // Basically the line colour for segment text, only looks good for large text so off by default. <del> 'textLineWidth' : 1, // Width of the lines around the text. Even though this defaults to 1, a line is only drawn if textStrokeStyle specified. <del> 'fillStyle' : 'silver', // The segment background colour. <del> 'strokeStyle' : 'black', // Segment line colour. Again segment lines only drawn if this is specified. <del> 'lineWidth' : 1, // Width of lines around segments. <del> 'clearTheCanvas' : true, // When set to true the canvas will be cleared before the wheel is drawn. <del> 'imageOverlay' : false, // If set to true in image drawing mode the outline of the segments will be displayed over the image. Does nothing in code drawMode. <del> 'drawText' : true, // By default the text of the segments is rendered in code drawMode and not in image drawMode. <del> 'pointerAngle' : 0, // Location of the pointer that indicates the prize when wheel has stopped. Default is 0 so the (corrected) 12 o'clock position. <del> 'wheelImage' : null // Must be set to image data in order to use image to draw the wheel - drawMode must also be 'image'. <del> }; <del> <add> defaultOptions = { <add> 'canvasId' : 'canvas', // Id of the canvas which the wheel is to draw on to. <add> 'centerX' : null, // X position of the center of the wheel. The default of these are null which means will be placed in center of the canvas. <add> 'centerY' : null, // Y position of the wheel center. If left null at time of construct the center of the canvas is used. <add> 'outerRadius' : null, // The radius of the outside of the wheel. If left null it will be set to the radius from the center of the canvas to its shortest side. <add> 'innerRadius' : 0, // Normally 0. Allows the creation of rings / doughnuts if set to value > 0. Should not exceed outer radius. <add> 'numSegments' : 1, // The number of segments. Need at least one to draw. <add> 'drawMode' : 'code', // The draw mode. Possible values are 'code' and 'image'. Default is code which means segments are drawn using canvas arc() function. <add> 'rotationAngle' : 0, // The angle of rotation of the wheel - 0 is 12 o'clock position. <add> 'textFontFamily' : 'Arial', // Segment text font, you should use web safe fonts. <add> 'textFontSize' : 20, // Size of the segment text. <add> 'textFontWeight' : 'bold', // Font weight. <add> 'textOrientation' : 'horizontal', // Either horizontal, vertical, or curved. <add> 'textAlignment' : 'center', // Either center, inner, or outer. <add> 'textDirection' : 'normal', // Either normal or reversed. In normal mode for horizontal text in segment at 3 o'clock is correct way up, in reversed text at 9 o'clock segment is correct way up. <add> 'textMargin' : null, // Margin between the inner or outer of the wheel (depends on textAlignment). <add> 'textFillStyle' : 'black', // This is basically the text colour. <add> 'textStrokeStyle' : null, // Basically the line colour for segment text, only looks good for large text so off by default. <add> 'textLineWidth' : 1, // Width of the lines around the text. Even though this defaults to 1, a line is only drawn if textStrokeStyle specified. <add> 'fillStyle' : 'silver', // The segment background colour. <add> 'strokeStyle' : 'black', // Segment line colour. Again segment lines only drawn if this is specified. <add> 'lineWidth' : 1, // Width of lines around segments. <add> 'clearTheCanvas' : true, // When set to true the canvas will be cleared before the wheel is drawn. <add> 'imageOverlay' : false, // If set to true in image drawing mode the outline of the segments will be displayed over the image. Does nothing in code drawMode. <add> 'drawText' : true, // By default the text of the segments is rendered in code drawMode and not in image drawMode. <add> 'pointerAngle' : 0, // Location of the pointer that indicates the prize when wheel has stopped. Default is 0 so the (corrected) 12 o'clock position. <add> 'wheelImage' : null // Must be set to image data in order to use image to draw the wheel - drawMode must also be 'image'. <add> }; <add> <ide> // ----------------------------------------- <ide> // Loop through the default options and create properties of this class set to the value for the option passed in <del> // or if not value for the option was passed in then to the default. <del> for (var key in defaultOptions) <del> { <del> if ((options != null) && (typeof(options[key]) !== 'undefined')) <del> { <del> this[key] = options[key]; <del> } <del> else <del> { <del> this[key] = defaultOptions[key]; <del> } <del> } <add> // or if not value for the option was passed in then to the default. <add> for (var key in defaultOptions) <add> { <add> if ((options != null) && (typeof(options[key]) !== 'undefined')) <add> { <add> this[key] = options[key]; <add> } <add> else <add> { <add> this[key] = defaultOptions[key]; <add> } <add> } <ide> <ide> // Also loop though the passed in options and add anything specified not part of the class in to it as a property. <ide> if (options != null) <ide> } <ide> } <ide> } <del> <del> <add> <add> <ide> // ------------------------------------------ <del> // If the id of the canvas is set, try to get the canvas as we need it for drawing. <del> if (this.canvasId) <del> { <add> // If the id of the canvas is set, try to get the canvas as we need it for drawing. <add> if (this.canvasId) <add> { <ide> this.canvas = document.getElementById(this.canvasId); <ide> <del> if (this.canvas) <del> { <del> // If the centerX and centerY have not been specified in the options then default to center of the canvas <add> if (this.canvas) <add> { <add> // If the centerX and centerY have not been specified in the options then default to center of the canvas <ide> // and make the outerRadius half of the canvas width - this means the wheel will fill the canvas. <del> if (this.centerX == null) <del> { <del> this.centerX = this.canvas.width / 2; <del> } <del> <del> if (this.centerY == null) <del> { <del> this.centerY = this.canvas.height / 2; <del> } <del> <del> if (this.outerRadius == null) <del> { <del> // Need to set to half the width of the shortest dimension of the canvas as the canvas may not be square. <del> // Minus the line segment line width otherwise the lines around the segments on the top,left,bottom,right <add> if (this.centerX == null) <add> { <add> this.centerX = this.canvas.width / 2; <add> } <add> <add> if (this.centerY == null) <add> { <add> this.centerY = this.canvas.height / 2; <add> } <add> <add> if (this.outerRadius == null) <add> { <add> // Need to set to half the width of the shortest dimension of the canvas as the canvas may not be square. <add> // Minus the line segment line width otherwise the lines around the segments on the top,left,bottom,right <ide> // side are chopped by the edge of the canvas. <del> if (this.canvas.width < this.canvas.height) <add> if (this.canvas.width < this.canvas.height) <ide> { <del> this.outerRadius = (this.canvas.width / 2) - this.lineWidth; <add> this.outerRadius = (this.canvas.width / 2) - this.lineWidth; <ide> } <del> else <add> else <ide> { <del> this.outerRadius = (this.canvas.height / 2) - this.lineWidth; <add> this.outerRadius = (this.canvas.height / 2) - this.lineWidth; <ide> } <del> } <add> } <ide> <ide> // Also get a 2D context to the canvas as we need this to draw with. <ide> this.ctx = this.canvas.getContext('2d'); <del> } <del> else <del> { <del> this.canvas = null; <add> } <add> else <add> { <add> this.canvas = null; <ide> this.ctx = null; <del> } <del> } <del> else <del> { <add> } <add> } <add> else <add> { <ide> this.cavnas = null; <ide> this.ctx = null; <del> } <del> <del> <add> } <add> <add> <ide> // ------------------------------------------ <del> // Add array of segments to the wheel, then populate with segments if number of segments is specified for this object. <del> this.segments = new Array(null); <del> <del> for (x = 1; x <= this.numSegments; x++) <del> { <del> // If options for the segments have been specified then create a segment sending these options so <del> // the specified values are used instead of the defaults. <del> if ((options != null) && (options['segments']) && (typeof(options['segments'][x-1]) !== 'undefined')) <del> { <del> this.segments[x] = new Segment(options['segments'][x-1]); <del> } <del> else <del> { <del> this.segments[x] = new Segment(); <del> } <del> } <del> <del> // ------------------------------------------ <del> // Call function to update the segment sizes setting the starting and ending angles. <del> this.updateSegmentSizes(); <add> // Add array of segments to the wheel, then populate with segments if number of segments is specified for this object. <add> this.segments = new Array(null); <add> <add> for (x = 1; x <= this.numSegments; x++) <add> { <add> // If options for the segments have been specified then create a segment sending these options so <add> // the specified values are used instead of the defaults. <add> if ((options != null) && (options['segments']) && (typeof(options['segments'][x-1]) !== 'undefined')) <add> { <add> this.segments[x] = new Segment(options['segments'][x-1]); <add> } <add> else <add> { <add> this.segments[x] = new Segment(); <add> } <add> } <add> <add> // ------------------------------------------ <add> // Call function to update the segment sizes setting the starting and ending angles. <add> this.updateSegmentSizes(); <ide> <ide> <ide> // If the text margin is null then set to same as font size as we want some by default. <ide> { <ide> this.pointerGuide = new PointerGuide(); <ide> } <del> <del> // Finally if drawWheel is true then call function to render the wheel, segment text, overlay etc. <add> <add> // Finally if drawWheel is true then call function to render the wheel, segment text, overlay etc. <ide> if (drawWheel == true) <ide> { <del> this.draw(this.clearTheCanvas); <add> this.draw(this.clearTheCanvas); <ide> } <ide> } <ide> <ide> // ==================================================================================================================== <ide> Winwheel.prototype.updateSegmentSizes = function() <ide> { <del> // If this object actually contains some segments <del> if (this.segments) <del> { <del> // First add up the arc used for the segments where the size has been set. <del> var arcUsed = 0; <del> var numSet = 0; <del> <del> // Remember, to make it easy to access segments, the position of the segments in the array starts from 1 (not 0). <del> for (x = 1; x <= this.numSegments; x ++) <del> { <del> if (this.segments[x].size !== null) <del> { <del> arcUsed += this.segments[x].size; <del> numSet ++; <del> } <del> } <del> <del> var arcLeft = (360 - arcUsed); <del> <del> // Create variable to hold how much each segment with non-set size will get in terms of degrees. <del> var degreesEach = 0; <del> <del> if (arcLeft > 0) <del> { <del> degreesEach = (arcLeft / (this.numSegments - numSet)); <del> } <del> <del> // ------------------------------------------ <del> // Now loop though and set the start and end angle of each segment. <del> var currentDegree = 0; <del> <del> for (x = 1; x <= this.numSegments; x ++) <del> { <del> // Set start angle. <del> this.segments[x].startAngle = currentDegree; <del> <del> // If the size is set then add this to the current degree to get the end, else add the degreesEach to it. <del> if (this.segments[x].size) <del> { <del> currentDegree += this.segments[x].size; <del> } <del> else <del> { <del> currentDegree += degreesEach; <del> } <del> <del> // Set end angle. <del> this.segments[x].endAngle = currentDegree; <del> } <del> } <add> // If this object actually contains some segments <add> if (this.segments) <add> { <add> // First add up the arc used for the segments where the size has been set. <add> var arcUsed = 0; <add> var numSet = 0; <add> <add> // Remember, to make it easy to access segments, the position of the segments in the array starts from 1 (not 0). <add> for (x = 1; x <= this.numSegments; x ++) <add> { <add> if (this.segments[x].size !== null) <add> { <add> arcUsed += this.segments[x].size; <add> numSet ++; <add> } <add> } <add> <add> var arcLeft = (360 - arcUsed); <add> <add> // Create variable to hold how much each segment with non-set size will get in terms of degrees. <add> var degreesEach = 0; <add> <add> if (arcLeft > 0) <add> { <add> degreesEach = (arcLeft / (this.numSegments - numSet)); <add> } <add> <add> // ------------------------------------------ <add> // Now loop though and set the start and end angle of each segment. <add> var currentDegree = 0; <add> <add> for (x = 1; x <= this.numSegments; x ++) <add> { <add> // Set start angle. <add> this.segments[x].startAngle = currentDegree; <add> <add> // If the size is set then add this to the current degree to get the end, else add the degreesEach to it. <add> if (this.segments[x].size) <add> { <add> currentDegree += this.segments[x].size; <add> } <add> else <add> { <add> currentDegree += degreesEach; <add> } <add> <add> // Set end angle. <add> this.segments[x].endAngle = currentDegree; <add> } <add> } <ide> } <ide> <ide> // ==================================================================================================================== <ide> Winwheel.prototype.clearCanvas = function() <ide> { <ide> if (this.ctx) <del> { <add> { <ide> this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height); <ide> } <ide> } <ide> // ==================================================================================================================== <ide> Winwheel.prototype.draw = function(clearTheCanvas) <ide> { <del> // If have the canvas context. <del> if (this.ctx) <del> { <del> // Clear the canvas, unless told not to. <add> // If have the canvas context. <add> if (this.ctx) <add> { <add> // Clear the canvas, unless told not to. <ide> if (typeof(clearTheCanvas) !== 'undefined') <ide> { <ide> if (clearTheCanvas == true) <ide> { <ide> this.clearCanvas(); <ide> } <del> <del> // Call functions to draw the segments and then segment text. <add> <add> // Call functions to draw the segments and then segment text. <ide> if (this.drawMode == 'image') <del> { <add> { <ide> // Draw the wheel by loading and drawing an image such as a png on the canvas. <ide> this.drawWheelImage(); <ide> <ide> { <ide> this.drawSegments(); <ide> } <del> } <del> else <del> { <del> // The default operation is to draw the segments using code via the canvas arc() method. <del> this.drawSegments(); <add> } <add> else <add> { <add> // The default operation is to draw the segments using code via the canvas arc() method. <add> this.drawSegments(); <ide> <ide> // The text is drawn on top. <ide> if (this.drawText == true) <ide> { <ide> this.drawSegmentText(); <ide> } <del> } <del> <add> } <add> <ide> // If pointer guide is display property is set to true then call function to draw the pointer guide. <ide> if (this.pointerGuide.display == true) <ide> { <ide> { <ide> this.ctx.save(); <ide> this.ctx.translate(this.canvas.width / 2, this.canvas.height / 2); <del> this.ctx.rotate(this.degToRad(this.pointerAngle)); <del> this.ctx.translate(-this.canvas.width / 2, -this.canvas.height / 2); <add> this.ctx.rotate(this.degToRad(this.pointerAngle)); <add> this.ctx.translate(-this.canvas.width / 2, -this.canvas.height / 2); <ide> <ide> this.ctx.strokeStyle = this.pointerGuide.strokeStyle; <ide> this.ctx.lineWidth = this.pointerGuide.lineWidth; <ide> // image wheels will spin. <ide> this.ctx.save(); <ide> this.ctx.translate(this.canvas.width / 2, this.canvas.height / 2); <del> this.ctx.rotate(this.degToRad(this.rotationAngle)); <del> this.ctx.translate(-this.canvas.width / 2, -this.canvas.height / 2); <add> this.ctx.rotate(this.degToRad(this.rotationAngle)); <add> this.ctx.translate(-this.canvas.width / 2, -this.canvas.height / 2); <ide> <ide> this.ctx.drawImage(this.wheelImage, imageLeft, imageTop); <ide> <ide> // ==================================================================================================================== <ide> Winwheel.prototype.drawSegments = function() <ide> { <del> // Again check have context in case this function was called directly and not via draw function. <del> if (this.ctx) <del> { <add> // Again check have context in case this function was called directly and not via draw function. <add> if (this.ctx) <add> { <ide> // Draw the segments if there is at least one in the segments array. <del> if (this.segments) <del> { <del> // Loop though and output all segments - position 0 of the array is not used, so start loop from index 1 <del> // this is to avoid confusion when talking about the first segment. <del> for (x = 1; x <= this.numSegments; x ++) <del> { <add> if (this.segments) <add> { <add> // Loop though and output all segments - position 0 of the array is not used, so start loop from index 1 <add> // this is to avoid confusion when talking about the first segment. <add> for (x = 1; x <= this.numSegments; x ++) <add> { <ide> // Get the segment object as we need it to read options from. <del> seg = this.segments[x]; <del> <del> var fillStyle; <del> var lineWidth; <del> var strokeStyle; <del> <del> // Set the variables that defined in the segment, or use the default options. <del> if (seg.fillStyle !== null) <del> fillStyle = seg.fillStyle; <del> else <del> fillStyle = this.fillStyle; <del> <del> this.ctx.fillStyle = fillStyle; <del> <del> if (seg.lineWidth !== null) <del> lineWidth = seg.lineWidth; <del> else <del> lineWidth = this.lineWidth; <del> <del> this.ctx.lineWidth = lineWidth; <del> <del> if (seg.strokeStyle !== null) <del> strokeStyle = seg.strokeStyle; <del> else <del> strokeStyle = this.strokeStyle; <del> <del> this.ctx.strokeStyle = strokeStyle; <del> <del> <add> seg = this.segments[x]; <add> <add> var fillStyle; <add> var lineWidth; <add> var strokeStyle; <add> <add> // Set the variables that defined in the segment, or use the default options. <add> if (seg.fillStyle !== null) <add> fillStyle = seg.fillStyle; <add> else <add> fillStyle = this.fillStyle; <add> <add> this.ctx.fillStyle = fillStyle; <add> <add> if (seg.lineWidth !== null) <add> lineWidth = seg.lineWidth; <add> else <add> lineWidth = this.lineWidth; <add> <add> this.ctx.lineWidth = lineWidth; <add> <add> if (seg.strokeStyle !== null) <add> strokeStyle = seg.strokeStyle; <add> else <add> strokeStyle = this.strokeStyle; <add> <add> this.ctx.strokeStyle = strokeStyle; <add> <add> <ide> // Check there is a strokeStyle or fillStyle, if either the the segment is invisible so should not <ide> // try to draw it otherwise a path is began but not ended. <ide> if ((strokeStyle) || (fillStyle)) <ide> if (strokeStyle) <ide> this.ctx.stroke(); <ide> } <del> } <del> } <del> } <add> } <add> } <add> } <ide> } <ide> <ide> // ==================================================================================================================== <ide> // This draws the text on the segments using the specified text options. <ide> // ==================================================================================================================== <ide> Winwheel.prototype.drawSegmentText = function() <del>{ <del> // Again only draw the text if have a canvas context. <del> if (this.ctx) <del> { <del> // Declare variables to hold the values. These are populated either with the value for the specific segment, <del> // or if not specified then the global default value. <del> var fontFamily; <del> var fontSize; <del> var fontWeight; <del> var orientation; <del> var alignment; <del> var direction; <del> var margin; <del> var fillStyle; <del> var strokeStyle; <del> var lineWidth; <del> var fontSetting; <del> <del> // Loop though all the segments. <del> for (x = 1; x <= this.numSegments; x ++) <del> { <del> // Save the context so it is certain that each segment text option will not affect the other. <del> this.ctx.save(); <del> <del> // Get the segment object as we need it to read options from. <del> seg = this.segments[x]; <del> <del> // Check is text as no point trying to draw if there is no text to render. <del> if (seg.text) <del> { <del> // Set values to those for the specific segment or use global default if null. <del> if (seg.textFontFamily !== null) fontFamily = seg.textFontFamily; else fontFamily = this.textFontFamily; <del> if (seg.textFontSize !== null) fontSize = seg.textFontSize; else fontSize = this.textFontSize; <del> if (seg.textFontWeight !== null) fontWeight = seg.textFontWeight; else fontWeight = this.textFontWeight; <del> if (seg.textOrientation !== null) orientation = seg.textOrientation; else orientation = this.textOrientation; <del> if (seg.textAlignment !== null) alignment = seg.textAlignment; else alignment = this.textAlignment; <del> if (seg.textDirection !== null) direction = seg.textDirection; else direction = this.textDirection; <del> if (seg.textMargin !== null) margin = seg.textMargin; else margin = this.textMargin; <del> if (seg.textFillStyle !== null) fillStyle = seg.textFillStyle; else fillStyle = this.textFillStyle; <del> if (seg.textStrokeStyle !== null) strokeStyle = seg.textStrokeStyle; else strokeStyle = this.textStrokeStyle; <del> if (seg.textLineWidth !== null) lineWidth = seg.textLineWidth; else lineWidth = this.textLineWidth; <del> <del> // ------------------------------ <del> // We need to put the font bits together in to one string. <del> fontSetting = ''; <del> <del> if (fontWeight != null) <del> fontSetting += fontWeight + ' '; <del> <del> if (fontSize != null) <del> fontSetting += fontSize + 'px '; // Fonts on canvas are always a px value. <del> <del> if (fontFamily != null) <del> fontSetting += fontFamily; <del> <del> // Now set the canvas context to the decided values. <del> this.ctx.font = fontSetting; <del> this.ctx.fillStyle = fillStyle; <del> this.ctx.strokeStyle = strokeStyle; <del> this.ctx.lineWidth = lineWidth; <del> <del> // --------------------------------- <del> // If direction is reversed then do things differently than if normal (which is the default - see further down) <del> if (direction == 'reversed') <del> { <del> // When drawing reversed or 'upside down' we need to do some trickery on our part. <del> // The canvas text rendering function still draws the text left to right and the correct way up, <del> // so we need to overcome this with rotating the opposite side of the wheel the correct way up then pulling the text <del> // through the center point to the correct segment it is supposed to be on. <del> if (orientation == 'horizontal') <del> { <del> if (alignment == 'inner') <del> this.ctx.textAlign = 'right'; <del> else if (alignment == 'outer') <del> this.ctx.textAlign = 'left'; <del> else <del> this.ctx.textAlign = 'center'; <del> <del> this.ctx.textBaseline = 'middle'; <del> <del> // Work out the angle to rotate the wheel, this is in the center of the segment but on the opposite side of the wheel which is why do -180. <del> var textAngle = this.degToRad((seg.endAngle - ((seg.endAngle - seg.startAngle) / 2) + this.rotationAngle - 90) - 180); <del> <del> this.ctx.save(); <del> this.ctx.translate(this.canvas.width / 2, this.canvas.height / 2); <del> this.ctx.rotate(textAngle); <del> this.ctx.translate(-this.canvas.width / 2, -this.canvas.height / 2); <del> <del> if (alignment == 'inner') <del> { <del> // In reversed state the margin is subtracted from the innerX. <del> // When inner the inner radius also comes in to play. <del> if (fillStyle) <del> this.ctx.fillText(seg.text, this.centerX - this.innerRadius - margin, this.centerY); <del> <del> if (strokeStyle) <del> this.ctx.strokeText(seg.text, this.centerX - this.innerRadius - margin, this.centerY); <del> } <del> else if (alignment == 'outer') <del> { <del> // In reversed state the position is the center minus the radius + the margin for outer aligned text. <del> if (fillStyle) <del> this.ctx.fillText(seg.text, this.centerX - this.outerRadius + margin, this.centerY); <del> <del> if (strokeStyle) <del> this.ctx.strokeText(seg.text, this.centerX - this.outerRadius + margin, this.centerY); <del> } <del> else <del> { <del> // In reversed state the everything in minused. <del> if (fillStyle) <del> this.ctx.fillText(seg.text, this.centerX - this.innerRadius - ((this.outerRadius - this.innerRadius) / 2) - margin, this.centerY); <del> <del> if (strokeStyle) <del> this.ctx.strokeText(seg.text, this.centerX - this.innerRadius - ((this.outerRadius - this.innerRadius) / 2) - margin, this.centerY); <del> } <del> <del> this.ctx.restore(); <del> } <del> else if (orientation == 'vertical') <del> { <del> // See normal code further down for comments on how it works, this is similar by plus/minus is reversed. <del> this.ctx.textAlign = 'center'; <del> <del> // In reversed mode this are reversed. <del> if (alignment == 'inner') <del> this.ctx.textBaseline = 'top'; <del> else if (alignment == 'outer') <del> this.ctx.textBaseline = 'bottom'; <del> else <del> this.ctx.textBaseline = 'middle'; <del> <del> var textAngle = (seg.endAngle - ((seg.endAngle - seg.startAngle) / 2) - 180); <add>{ <add> // Again only draw the text if have a canvas context. <add> if (this.ctx) <add> { <add> // Declare variables to hold the values. These are populated either with the value for the specific segment, <add> // or if not specified then the global default value. <add> var fontFamily; <add> var fontSize; <add> var fontWeight; <add> var orientation; <add> var alignment; <add> var direction; <add> var margin; <add> var fillStyle; <add> var strokeStyle; <add> var lineWidth; <add> var fontSetting; <add> <add> // Loop though all the segments. <add> for (x = 1; x <= this.numSegments; x ++) <add> { <add> // Save the context so it is certain that each segment text option will not affect the other. <add> this.ctx.save(); <add> <add> // Get the segment object as we need it to read options from. <add> seg = this.segments[x]; <add> <add> // Check is text as no point trying to draw if there is no text to render. <add> if (seg.text) <add> { <add> // Set values to those for the specific segment or use global default if null. <add> if (seg.textFontFamily !== null) fontFamily = seg.textFontFamily; else fontFamily = this.textFontFamily; <add> if (seg.textFontSize !== null) fontSize = seg.textFontSize; else fontSize = this.textFontSize; <add> if (seg.textFontWeight !== null) fontWeight = seg.textFontWeight; else fontWeight = this.textFontWeight; <add> if (seg.textOrientation !== null) orientation = seg.textOrientation; else orientation = this.textOrientation; <add> if (seg.textAlignment !== null) alignment = seg.textAlignment; else alignment = this.textAlignment; <add> if (seg.textDirection !== null) direction = seg.textDirection; else direction = this.textDirection; <add> if (seg.textMargin !== null) margin = seg.textMargin; else margin = this.textMargin; <add> if (seg.textFillStyle !== null) fillStyle = seg.textFillStyle; else fillStyle = this.textFillStyle; <add> if (seg.textStrokeStyle !== null) strokeStyle = seg.textStrokeStyle; else strokeStyle = this.textStrokeStyle; <add> if (seg.textLineWidth !== null) lineWidth = seg.textLineWidth; else lineWidth = this.textLineWidth; <add> <add> // ------------------------------ <add> // We need to put the font bits together in to one string. <add> fontSetting = ''; <add> <add> if (fontWeight != null) <add> fontSetting += fontWeight + ' '; <add> <add> if (fontSize != null) <add> fontSetting += fontSize + 'px '; // Fonts on canvas are always a px value. <add> <add> if (fontFamily != null) <add> fontSetting += fontFamily; <add> <add> // Now set the canvas context to the decided values. <add> this.ctx.font = fontSetting; <add> this.ctx.fillStyle = fillStyle; <add> this.ctx.strokeStyle = strokeStyle; <add> this.ctx.lineWidth = lineWidth; <add> <add> // --------------------------------- <add> // If direction is reversed then do things differently than if normal (which is the default - see further down) <add> if (direction == 'reversed') <add> { <add> // When drawing reversed or 'upside down' we need to do some trickery on our part. <add> // The canvas text rendering function still draws the text left to right and the correct way up, <add> // so we need to overcome this with rotating the opposite side of the wheel the correct way up then pulling the text <add> // through the center point to the correct segment it is supposed to be on. <add> if (orientation == 'horizontal') <add> { <add> if (alignment == 'inner') <add> this.ctx.textAlign = 'right'; <add> else if (alignment == 'outer') <add> this.ctx.textAlign = 'left'; <add> else <add> this.ctx.textAlign = 'center'; <add> <add> this.ctx.textBaseline = 'middle'; <add> <add> // Work out the angle to rotate the wheel, this is in the center of the segment but on the opposite side of the wheel which is why do -180. <add> var textAngle = this.degToRad((seg.endAngle - ((seg.endAngle - seg.startAngle) / 2) + this.rotationAngle - 90) - 180); <add> <add> this.ctx.save(); <add> this.ctx.translate(this.canvas.width / 2, this.canvas.height / 2); <add> this.ctx.rotate(textAngle); <add> this.ctx.translate(-this.canvas.width / 2, -this.canvas.height / 2); <add> <add> if (alignment == 'inner') <add> { <add> // In reversed state the margin is subtracted from the innerX. <add> // When inner the inner radius also comes in to play. <add> if (fillStyle) <add> this.ctx.fillText(seg.text, this.centerX - this.innerRadius - margin, this.centerY); <add> <add> if (strokeStyle) <add> this.ctx.strokeText(seg.text, this.centerX - this.innerRadius - margin, this.centerY); <add> } <add> else if (alignment == 'outer') <add> { <add> // In reversed state the position is the center minus the radius + the margin for outer aligned text. <add> if (fillStyle) <add> this.ctx.fillText(seg.text, this.centerX - this.outerRadius + margin, this.centerY); <add> <add> if (strokeStyle) <add> this.ctx.strokeText(seg.text, this.centerX - this.outerRadius + margin, this.centerY); <add> } <add> else <add> { <add> // In reversed state the everything in minused. <add> if (fillStyle) <add> this.ctx.fillText(seg.text, this.centerX - this.innerRadius - ((this.outerRadius - this.innerRadius) / 2) - margin, this.centerY); <add> <add> if (strokeStyle) <add> this.ctx.strokeText(seg.text, this.centerX - this.innerRadius - ((this.outerRadius - this.innerRadius) / 2) - margin, this.centerY); <add> } <add> <add> this.ctx.restore(); <add> } <add> else if (orientation == 'vertical') <add> { <add> // See normal code further down for comments on how it works, this is similar by plus/minus is reversed. <add> this.ctx.textAlign = 'center'; <add> <add> // In reversed mode this are reversed. <add> if (alignment == 'inner') <add> this.ctx.textBaseline = 'top'; <add> else if (alignment == 'outer') <add> this.ctx.textBaseline = 'bottom'; <add> else <add> this.ctx.textBaseline = 'middle'; <add> <add> var textAngle = (seg.endAngle - ((seg.endAngle - seg.startAngle) / 2) - 180); <ide> textAngle += this.rotationAngle; <ide> <del> this.ctx.save(); <del> this.ctx.translate(this.centerX, this.centerY); <del> this.ctx.rotate(this.degToRad(textAngle)); <del> this.ctx.translate(-this.centerX, -this.centerY); <del> <del> if (alignment == 'outer') <del> var yPos = (this.centerY + this.outerRadius - margin); <del> else if (alignment == 'inner') <del> var yPos = (this.centerY + this.innerRadius + margin); <del> <del> // I have found that the text looks best when a fraction of the font size is shaved off. <add> this.ctx.save(); <add> this.ctx.translate(this.centerX, this.centerY); <add> this.ctx.rotate(this.degToRad(textAngle)); <add> this.ctx.translate(-this.centerX, -this.centerY); <add> <add> if (alignment == 'outer') <add> var yPos = (this.centerY + this.outerRadius - margin); <add> else if (alignment == 'inner') <add> var yPos = (this.centerY + this.innerRadius + margin); <add> <add> // I have found that the text looks best when a fraction of the font size is shaved off. <ide> var yInc = (fontSize - (fontSize / 9)); <del> <del> // Loop though and output the characters. <del> if (alignment == 'outer') <del> { <del> // In reversed mode outer means text in 6 o'clock segment sits at bottom of the wheel and we draw up. <del> for (var c = (seg.text.length -1); c >= 0; c--) <del> { <del> character = seg.text.charAt(c); <del> <del> if (fillStyle) <del> this.ctx.fillText(character, this.centerX, yPos); <del> <del> if (strokeStyle) <del> this.ctx.strokeText(character, this.centerX, yPos); <del> <del> yPos -= yInc; <del> } <del> } <del> else if (alignment == 'inner') <del> { <del> // In reversed mode inner text is drawn from top of segment at 6 o'clock position to bottom of the wheel. <del> for (var c = 0; c < seg.text.length; c++) <del> { <del> character = seg.text.charAt(c); <del> <del> if (fillStyle) <del> this.ctx.fillText(character, this.centerX, yPos); <del> <del> if (strokeStyle) <del> this.ctx.strokeText(character, this.centerX, yPos); <del> <del> yPos += yInc; <del> } <del> } <del> else if (alignment == 'center') <del> { <del> // Again for reversed this is the opposite of before. <del> // If there is more than one character in the text then an adjustment to the position needs to be done. <del> // What we are aiming for is to position the center of the text at the center point between the inner and outer radius. <del> var centerAdjustment = 0; <del> <del> if (seg.text.length > 1) <del> { <del> centerAdjustment = (yInc * (seg.text.length -1) / 2); <del> } <del> <del> var yPos = (this.centerY + this.innerRadius + ((this.outerRadius - this.innerRadius) / 2)) + centerAdjustment + margin; <del> <del> for (var c = (seg.text.length -1); c >= 0; c--) <del> { <del> character = seg.text.charAt(c); <del> <del> if (fillStyle) <del> this.ctx.fillText(character, this.centerX, yPos); <del> <del> if (strokeStyle) <del> this.ctx.strokeText(character, this.centerX, yPos); <del> <del> yPos -= yInc; <del> } <del> } <del> <del> this.ctx.restore(); <del> } <del> else if (orientation == 'curved') <del> { <del> // There is no built in canvas function to draw text around an arc, <add> <add> // Loop though and output the characters. <add> if (alignment == 'outer') <add> { <add> // In reversed mode outer means text in 6 o'clock segment sits at bottom of the wheel and we draw up. <add> for (var c = (seg.text.length -1); c >= 0; c--) <add> { <add> character = seg.text.charAt(c); <add> <add> if (fillStyle) <add> this.ctx.fillText(character, this.centerX, yPos); <add> <add> if (strokeStyle) <add> this.ctx.strokeText(character, this.centerX, yPos); <add> <add> yPos -= yInc; <add> } <add> } <add> else if (alignment == 'inner') <add> { <add> // In reversed mode inner text is drawn from top of segment at 6 o'clock position to bottom of the wheel. <add> for (var c = 0; c < seg.text.length; c++) <add> { <add> character = seg.text.charAt(c); <add> <add> if (fillStyle) <add> this.ctx.fillText(character, this.centerX, yPos); <add> <add> if (strokeStyle) <add> this.ctx.strokeText(character, this.centerX, yPos); <add> <add> yPos += yInc; <add> } <add> } <add> else if (alignment == 'center') <add> { <add> // Again for reversed this is the opposite of before. <add> // If there is more than one character in the text then an adjustment to the position needs to be done. <add> // What we are aiming for is to position the center of the text at the center point between the inner and outer radius. <add> var centerAdjustment = 0; <add> <add> if (seg.text.length > 1) <add> { <add> centerAdjustment = (yInc * (seg.text.length -1) / 2); <add> } <add> <add> var yPos = (this.centerY + this.innerRadius + ((this.outerRadius - this.innerRadius) / 2)) + centerAdjustment + margin; <add> <add> for (var c = (seg.text.length -1); c >= 0; c--) <add> { <add> character = seg.text.charAt(c); <add> <add> if (fillStyle) <add> this.ctx.fillText(character, this.centerX, yPos); <add> <add> if (strokeStyle) <add> this.ctx.strokeText(character, this.centerX, yPos); <add> <add> yPos -= yInc; <add> } <add> } <add> <add> this.ctx.restore(); <add> } <add> else if (orientation == 'curved') <add> { <add> // There is no built in canvas function to draw text around an arc, <ide> // so we need to do this ourselves. <del> var radius = 0; <del> <del> // Set the alignment of the text - inner, outer, or center by calculating <add> var radius = 0; <add> <add> // Set the alignment of the text - inner, outer, or center by calculating <ide> // how far out from the center point of the wheel the text is drawn. <del> if (alignment == 'inner') <del> { <del> // When alignment is inner the radius is the innerRadius plus any margin. <del> radius = this.innerRadius + margin; <add> if (alignment == 'inner') <add> { <add> // When alignment is inner the radius is the innerRadius plus any margin. <add> radius = this.innerRadius + margin; <ide> this.ctx.textBaseline = 'top'; <del> } <del> else if (alignment == 'outer') <del> { <del> // Outer it is the outerRadius minus any margin. <del> radius = this.outerRadius - margin; <add> } <add> else if (alignment == 'outer') <add> { <add> // Outer it is the outerRadius minus any margin. <add> radius = this.outerRadius - margin; <ide> this.ctx.textBaseline = 'bottom'; <del> } <del> else if (alignment == 'center') <del> { <del> // When center we want the text halfway between the inner and outer radius. <del> radius = this.innerRadius + margin + ((this.outerRadius - this.innerRadius) / 2); <del> this.ctx.textBaseline = 'middle'; <del> } <del> <del> // Set the angle to increment by when looping though and outputting the characters in the text <add> } <add> else if (alignment == 'center') <add> { <add> // When center we want the text halfway between the inner and outer radius. <add> radius = this.innerRadius + margin + ((this.outerRadius - this.innerRadius) / 2); <add> this.ctx.textBaseline = 'middle'; <add> } <add> <add> // Set the angle to increment by when looping though and outputting the characters in the text <ide> // as we do this by rotating the wheel small amounts adding each character. <del> var anglePerChar = 0; <del> var drawAngle = 0; <del> <del> // If more than one character in the text then... <add> var anglePerChar = 0; <add> var drawAngle = 0; <add> <add> // If more than one character in the text then... <ide> if (seg.text.length > 1) <del> { <del> // Text is drawn from the left. <del> this.ctx.textAlign = 'left'; <del> <del> // Work out how much angle the text rendering loop below needs to rotate by for each character to render them next to each other. <add> { <add> // Text is drawn from the left. <add> this.ctx.textAlign = 'left'; <add> <add> // Work out how much angle the text rendering loop below needs to rotate by for each character to render them next to each other. <ide> // I have discovered that 4 * the font size / 10 at 100px radius is the correct spacing for between the characters <ide> // using a monospace font, non monospace may look a little odd as in there will appear to be extra spaces between chars. <ide> anglePerChar = (4 * (fontSize / 10)); <ide> totalArc = (anglePerChar * seg.text.length); <ide> <ide> // Now set initial draw angle to half way between the start and end of the segment. <del> drawAngle = seg.startAngle + (((seg.endAngle - seg.startAngle) / 2) - (totalArc / 2)); <del> } <del> else <del> { <del> // The initial draw angle is the center of the segment when only one character. <del> drawAngle = (seg.startAngle + ((seg.endAngle - seg.startAngle) / 2)); <del> <del> // To ensure is dead-center the text alignment also needs to be centered. <del> this.ctx.textAlign = 'center'; <del> } <add> drawAngle = seg.startAngle + (((seg.endAngle - seg.startAngle) / 2) - (totalArc / 2)); <add> } <add> else <add> { <add> // The initial draw angle is the center of the segment when only one character. <add> drawAngle = (seg.startAngle + ((seg.endAngle - seg.startAngle) / 2)); <add> <add> // To ensure is dead-center the text alignment also needs to be centered. <add> this.ctx.textAlign = 'center'; <add> } <ide> <ide> // ---------------------- <ide> // Adjust the initial draw angle as needed to take in to account the rotationAngle of the wheel. <ide> // And as with other 'reverse' text direction functions we need to subtract 180 degrees from the angle <ide> // because when it comes to draw the characters in the loop below we add the radius instead of subtract it. <ide> drawAngle -= 180; <del> <del> // ---------------------- <del> // Now the drawing itself. <add> <add> // ---------------------- <add> // Now the drawing itself. <ide> // In reversed direction mode we loop through the characters in the text backwards in order for them to appear on screen correctly <del> for (c = seg.text.length; c >= 0; c--) <del> { <del> this.ctx.save(); <add> for (c = seg.text.length; c >= 0; c--) <add> { <add> this.ctx.save(); <ide> <ide> character = seg.text.charAt(c); <del> <del> // Rotate the wheel to the draw angle as we need to add the character at this location. <add> <add> // Rotate the wheel to the draw angle as we need to add the character at this location. <ide> this.ctx.translate(this.centerX, this.centerY); <del> this.ctx.rotate(this.degToRad(drawAngle)); <del> this.ctx.translate(-this.centerX, -this.centerY); <del> <del> // Now draw the character directly below the center point of the wheel at the appropriate radius. <add> this.ctx.rotate(this.degToRad(drawAngle)); <add> this.ctx.translate(-this.centerX, -this.centerY); <add> <add> // Now draw the character directly below the center point of the wheel at the appropriate radius. <ide> // Note in the reversed mode we add the radius to the this.centerY instead of subtract. <del> if (strokeStyle) <del> this.ctx.strokeText(character, this.centerX, this.centerY + radius); <del> <del> if (fillStyle) <del> this.ctx.fillText(character, this.centerX, this.centerY + radius); <del> <del> // Increment the drawAngle by the angle per character so next loop we rotate <add> if (strokeStyle) <add> this.ctx.strokeText(character, this.centerX, this.centerY + radius); <add> <add> if (fillStyle) <add> this.ctx.fillText(character, this.centerX, this.centerY + radius); <add> <add> // Increment the drawAngle by the angle per character so next loop we rotate <ide> // to the next angle required to draw the character at. <del> drawAngle += anglePerChar; <add> drawAngle += anglePerChar; <ide> <ide> this.ctx.restore(); <del> } <del> } <del> } <del> else <del> { <del> // Normal direction so do things normally. <del> // Check text orientation, of horizontal then reasonably straight forward, if vertical then a bit more work to do. <del> if (orientation == 'horizontal') <del> { <del> // Based on the text alignment, set the correct value in the context. <del> if (alignment == 'inner') <del> this.ctx.textAlign = 'left'; <del> else if (alignment == 'outer') <del> this.ctx.textAlign = 'right'; <del> else <del> this.ctx.textAlign = 'center'; <del> <del> // Set this too. <del> this.ctx.textBaseline = 'middle'; <del> <del> // Work out the angle around the wheel to draw the text at, which is simply in the middle of the segment the text is for. <del> // The rotation angle is added in to correct the annoyance with the canvas arc drawing functions which put the 0 degrees at the 3 oclock <del> var textAngle = this.degToRad(seg.endAngle - ((seg.endAngle - seg.startAngle) / 2) + this.rotationAngle - 90); <del> <del> // We need to rotate in order to draw the text because it is output horizontally, so to <del> // place correctly around the wheel for all but a segment at 3 o'clock we need to rotate. <del> this.ctx.save(); <del> this.ctx.translate(this.centerX, this.centerY); <del> this.ctx.rotate(textAngle); <del> this.ctx.translate(-this.centerX, -this.centerY); <del> <del> // -------------------------- <del> // Draw the text based on its alignment adding margin if inner or outer. <del> if (alignment == 'inner') <del> { <del> // Inner means that the text is aligned with the inner of the wheel. If looking at a segment in in the 3 o'clock position <del> // it would look like the text is left aligned within the segment. <del> <del> // Because the segments are smaller towards the inner of the wheel, in order for the text to fit is is a good idea that <del> // a margin is added which pushes the text towards the outer a bit. <del> <del> // The inner radius also needs to be taken in to account as when inner aligned. <del> <del> // If fillstyle is set the draw the text filled in. <del> if (fillStyle) <del> this.ctx.fillText(seg.text, this.centerX + this.innerRadius + margin, this.centerY); <del> <del> // If stroke style is set draw the text outline. <del> if (strokeStyle) <del> this.ctx.strokeText(seg.text, this.centerX + this.innerRadius + margin, this.centerY); <del> } <del> else if (alignment == 'outer') <del> { <del> // Outer means the text is aligned with the outside of the wheel, so if looking at a segment in the 3 o'clock position <del> // it would appear the text is right aligned. To position we add the radius of the wheel in to the equation <del> // and subtract the margin this time, rather than add it. <del> <del> // I don't understand why, but in order of the text to render correctly with stroke and fill, the stroke needs to <del> // come first when drawing outer, rather than second when doing inner. <del> if (fillStyle) <del> this.ctx.fillText(seg.text, this.centerX + this.outerRadius - margin, this.centerY); <del> <del> // If fillstyle the fill the text. <del> if (strokeStyle) <del> this.ctx.strokeText(seg.text, this.centerX + this.outerRadius - margin, this.centerY); <del> } <del> else <del> { <del> // In this case the text is to drawn centred in the segment. <del> // Typically no margin is required, however even though centred the text can look closer to the inner of the wheel <del> // due to the way the segments narrow in (is optical effect), so if a margin is specified it is placed on the inner <del> // side so the text is pushed towards the outer. <del> <del> // If stoke style the stroke the text. <del> if (fillStyle) <del> this.ctx.fillText(seg.text, this.centerX + this.innerRadius + ((this.outerRadius - this.innerRadius) / 2) + margin, this.centerY); <del> <del> // If fillstyle the fill the text. <del> if (strokeStyle) <del> this.ctx.strokeText(seg.text, this.centerX + this.innerRadius + ((this.outerRadius - this.innerRadius) / 2) + margin, this.centerY); <del> } <del> <del> // Restore the context so that wheel is returned to original position. <del> this.ctx.restore(); <del> } <del> else if (orientation == 'vertical') <del> { <del> // If vertical then we need to do this ourselves because as far as I am aware there is no option built in to html canvas <del> // which causes the text to draw downwards or upwards one character after another. <del> <del> // In this case the textAlign is always center, but the baseline is either top or bottom <del> // depending on if inner or outer alignment has been specified. <del> this.ctx.textAlign = 'center'; <del> <del> if (alignment == 'inner') <del> this.ctx.textBaseline = 'bottom'; <del> else if (alignment == 'outer') <del> this.ctx.textBaseline = 'top'; <del> else <del> this.ctx.textBaseline = 'middle'; <del> <del> // The angle to draw the text at is halfway between the end and the starting angle of the segment. <del> var textAngle = seg.endAngle - ((seg.endAngle - seg.startAngle) / 2); <add> } <add> } <add> } <add> else <add> { <add> // Normal direction so do things normally. <add> // Check text orientation, of horizontal then reasonably straight forward, if vertical then a bit more work to do. <add> if (orientation == 'horizontal') <add> { <add> // Based on the text alignment, set the correct value in the context. <add> if (alignment == 'inner') <add> this.ctx.textAlign = 'left'; <add> else if (alignment == 'outer') <add> this.ctx.textAlign = 'right'; <add> else <add> this.ctx.textAlign = 'center'; <add> <add> // Set this too. <add> this.ctx.textBaseline = 'middle'; <add> <add> // Work out the angle around the wheel to draw the text at, which is simply in the middle of the segment the text is for. <add> // The rotation angle is added in to correct the annoyance with the canvas arc drawing functions which put the 0 degrees at the 3 oclock <add> var textAngle = this.degToRad(seg.endAngle - ((seg.endAngle - seg.startAngle) / 2) + this.rotationAngle - 90); <add> <add> // We need to rotate in order to draw the text because it is output horizontally, so to <add> // place correctly around the wheel for all but a segment at 3 o'clock we need to rotate. <add> this.ctx.save(); <add> this.ctx.translate(this.centerX, this.centerY); <add> this.ctx.rotate(textAngle); <add> this.ctx.translate(-this.centerX, -this.centerY); <add> <add> // -------------------------- <add> // Draw the text based on its alignment adding margin if inner or outer. <add> if (alignment == 'inner') <add> { <add> // Inner means that the text is aligned with the inner of the wheel. If looking at a segment in in the 3 o'clock position <add> // it would look like the text is left aligned within the segment. <add> <add> // Because the segments are smaller towards the inner of the wheel, in order for the text to fit is is a good idea that <add> // a margin is added which pushes the text towards the outer a bit. <add> <add> // The inner radius also needs to be taken in to account as when inner aligned. <add> <add> // If fillstyle is set the draw the text filled in. <add> if (fillStyle) <add> this.ctx.fillText(seg.text, this.centerX + this.innerRadius + margin, this.centerY); <add> <add> // If stroke style is set draw the text outline. <add> if (strokeStyle) <add> this.ctx.strokeText(seg.text, this.centerX + this.innerRadius + margin, this.centerY); <add> } <add> else if (alignment == 'outer') <add> { <add> // Outer means the text is aligned with the outside of the wheel, so if looking at a segment in the 3 o'clock position <add> // it would appear the text is right aligned. To position we add the radius of the wheel in to the equation <add> // and subtract the margin this time, rather than add it. <add> <add> // I don't understand why, but in order of the text to render correctly with stroke and fill, the stroke needs to <add> // come first when drawing outer, rather than second when doing inner. <add> if (fillStyle) <add> this.ctx.fillText(seg.text, this.centerX + this.outerRadius - margin, this.centerY); <add> <add> // If fillstyle the fill the text. <add> if (strokeStyle) <add> this.ctx.strokeText(seg.text, this.centerX + this.outerRadius - margin, this.centerY); <add> } <add> else <add> { <add> // In this case the text is to drawn centred in the segment. <add> // Typically no margin is required, however even though centred the text can look closer to the inner of the wheel <add> // due to the way the segments narrow in (is optical effect), so if a margin is specified it is placed on the inner <add> // side so the text is pushed towards the outer. <add> <add> // If stoke style the stroke the text. <add> if (fillStyle) <add> this.ctx.fillText(seg.text, this.centerX + this.innerRadius + ((this.outerRadius - this.innerRadius) / 2) + margin, this.centerY); <add> <add> // If fillstyle the fill the text. <add> if (strokeStyle) <add> this.ctx.strokeText(seg.text, this.centerX + this.innerRadius + ((this.outerRadius - this.innerRadius) / 2) + margin, this.centerY); <add> } <add> <add> // Restore the context so that wheel is returned to original position. <add> this.ctx.restore(); <add> } <add> else if (orientation == 'vertical') <add> { <add> // If vertical then we need to do this ourselves because as far as I am aware there is no option built in to html canvas <add> // which causes the text to draw downwards or upwards one character after another. <add> <add> // In this case the textAlign is always center, but the baseline is either top or bottom <add> // depending on if inner or outer alignment has been specified. <add> this.ctx.textAlign = 'center'; <add> <add> if (alignment == 'inner') <add> this.ctx.textBaseline = 'bottom'; <add> else if (alignment == 'outer') <add> this.ctx.textBaseline = 'top'; <add> else <add> this.ctx.textBaseline = 'middle'; <add> <add> // The angle to draw the text at is halfway between the end and the starting angle of the segment. <add> var textAngle = seg.endAngle - ((seg.endAngle - seg.startAngle) / 2); <ide> <ide> // Ensure the rotation angle of the wheel is added in, otherwise the test placement won't match <ide> // the segments they are supposed to be for. <ide> textAngle += this.rotationAngle; <del> <del> // Rotate so can begin to place the text. <del> this.ctx.save(); <del> this.ctx.translate(this.centerX, this.centerY); <del> this.ctx.rotate(this.degToRad(textAngle)); <del> this.ctx.translate(-this.centerX, -this.centerY); <del> <del> // Work out the position to start drawing in based on the alignment. <del> // If outer then when considering a segment at the 12 o'clock position want to start drawing down from the top of the wheel. <del> if (alignment == 'outer') <del> var yPos = (this.centerY - this.outerRadius + margin); <del> else if (alignment == 'inner') <del> var yPos = (this.centerY - this.innerRadius - margin); <del> <del> // We need to know how much to move the y axis each time. <add> <add> // Rotate so can begin to place the text. <add> this.ctx.save(); <add> this.ctx.translate(this.centerX, this.centerY); <add> this.ctx.rotate(this.degToRad(textAngle)); <add> this.ctx.translate(-this.centerX, -this.centerY); <add> <add> // Work out the position to start drawing in based on the alignment. <add> // If outer then when considering a segment at the 12 o'clock position want to start drawing down from the top of the wheel. <add> if (alignment == 'outer') <add> var yPos = (this.centerY - this.outerRadius + margin); <add> else if (alignment == 'inner') <add> var yPos = (this.centerY - this.innerRadius - margin); <add> <add> // We need to know how much to move the y axis each time. <ide> // This is not quite simply the font size as that puts a larger gap in between the letters <ide> // than expected, especially with monospace fonts. I found that shaving a little off makes it look "right". <del> var yInc = (fontSize - (fontSize / 9)); <del> <del> // Loop though and output the characters. <del> if (alignment == 'outer') <del> { <del> // For this alignment we draw down from the top of a segment at the 12 o'clock position to simply <del> // loop though the characters in order. <del> for (var c = 0; c < seg.text.length; c++) <del> { <del> character = seg.text.charAt(c); <del> <del> if (fillStyle) <del> this.ctx.fillText(character, this.centerX, yPos); <del> <del> if (strokeStyle) <del> this.ctx.strokeText(character, this.centerX, yPos); <del> <del> yPos += yInc; <del> } <del> } <del> else if (alignment == 'inner') <del> { <del> // Here we draw from the inner of the wheel up, but in order for the letters in the text text to <del> // remain in the correct order when reading, we actually need to loop though the text characters backwards. <del> for (var c = (seg.text.length -1); c >= 0; c--) <del> { <del> character = seg.text.charAt(c); <del> <del> if (fillStyle) <del> this.ctx.fillText(character, this.centerX, yPos); <del> <del> if (strokeStyle) <del> this.ctx.strokeText(character, this.centerX, yPos); <del> <del> yPos -= yInc; <del> } <del> } <del> else if (alignment == 'center') <del> { <del> // This is the most complex of the three as we need to draw the text top down centred between the inner and outer of the wheel. <del> // So logically we have to put the middle character of the text in the center then put the others each side of it. <del> // In reality that is a really bad way to do it, we can achieve the same if not better positioning using a <del> // variation on the method used for the rendering of outer aligned text once we have figured out the height of the text. <del> <del> // If there is more than one character in the text then an adjustment to the position needs to be done. <del> // What we are aiming for is to position the center of the text at the center point between the inner and outer radius. <del> var centerAdjustment = 0; <del> <del> if (seg.text.length > 1) <del> { <del> centerAdjustment = (yInc * (seg.text.length -1) / 2); <del> } <del> <del> // Now work out where to start rendering the string. This is half way between the inner and outer of the wheel, with the <del> // centerAdjustment included to correctly position texts with more than one character over the center. <del> // If there is a margin it is used to push the text away from the center of the wheel. <del> var yPos = (this.centerY - this.innerRadius - ((this.outerRadius - this.innerRadius) / 2)) - centerAdjustment - margin; <del> <del> // Now loop and draw just like outer text rendering. <del> for (var c = 0; c < seg.text.length; c++) <del> { <del> character = seg.text.charAt(c); <del> <del> if (fillStyle) <del> this.ctx.fillText(character, this.centerX, yPos); <del> <del> if (strokeStyle) <del> this.ctx.strokeText(character, this.centerX, yPos); <del> <del> yPos += yInc; <del> } <del> } <del> <del> this.ctx.restore(); <del> } <del> else if (orientation == 'curved') <del> { <del> // There is no built in canvas function to draw text around an arc, so <add> var yInc = (fontSize - (fontSize / 9)); <add> <add> // Loop though and output the characters. <add> if (alignment == 'outer') <add> { <add> // For this alignment we draw down from the top of a segment at the 12 o'clock position to simply <add> // loop though the characters in order. <add> for (var c = 0; c < seg.text.length; c++) <add> { <add> character = seg.text.charAt(c); <add> <add> if (fillStyle) <add> this.ctx.fillText(character, this.centerX, yPos); <add> <add> if (strokeStyle) <add> this.ctx.strokeText(character, this.centerX, yPos); <add> <add> yPos += yInc; <add> } <add> } <add> else if (alignment == 'inner') <add> { <add> // Here we draw from the inner of the wheel up, but in order for the letters in the text text to <add> // remain in the correct order when reading, we actually need to loop though the text characters backwards. <add> for (var c = (seg.text.length -1); c >= 0; c--) <add> { <add> character = seg.text.charAt(c); <add> <add> if (fillStyle) <add> this.ctx.fillText(character, this.centerX, yPos); <add> <add> if (strokeStyle) <add> this.ctx.strokeText(character, this.centerX, yPos); <add> <add> yPos -= yInc; <add> } <add> } <add> else if (alignment == 'center') <add> { <add> // This is the most complex of the three as we need to draw the text top down centred between the inner and outer of the wheel. <add> // So logically we have to put the middle character of the text in the center then put the others each side of it. <add> // In reality that is a really bad way to do it, we can achieve the same if not better positioning using a <add> // variation on the method used for the rendering of outer aligned text once we have figured out the height of the text. <add> <add> // If there is more than one character in the text then an adjustment to the position needs to be done. <add> // What we are aiming for is to position the center of the text at the center point between the inner and outer radius. <add> var centerAdjustment = 0; <add> <add> if (seg.text.length > 1) <add> { <add> centerAdjustment = (yInc * (seg.text.length -1) / 2); <add> } <add> <add> // Now work out where to start rendering the string. This is half way between the inner and outer of the wheel, with the <add> // centerAdjustment included to correctly position texts with more than one character over the center. <add> // If there is a margin it is used to push the text away from the center of the wheel. <add> var yPos = (this.centerY - this.innerRadius - ((this.outerRadius - this.innerRadius) / 2)) - centerAdjustment - margin; <add> <add> // Now loop and draw just like outer text rendering. <add> for (var c = 0; c < seg.text.length; c++) <add> { <add> character = seg.text.charAt(c); <add> <add> if (fillStyle) <add> this.ctx.fillText(character, this.centerX, yPos); <add> <add> if (strokeStyle) <add> this.ctx.strokeText(character, this.centerX, yPos); <add> <add> yPos += yInc; <add> } <add> } <add> <add> this.ctx.restore(); <add> } <add> else if (orientation == 'curved') <add> { <add> // There is no built in canvas function to draw text around an arc, so <ide> // we need to do this ourselves. <del> var radius = 0; <del> <del> // Set the alignment of the text - inner, outer, or center by calculating <add> var radius = 0; <add> <add> // Set the alignment of the text - inner, outer, or center by calculating <ide> // how far out from the center point of the wheel the text is drawn. <del> if (alignment == 'inner') <del> { <del> // When alignment is inner the radius is the innerRadius plus any margin. <del> radius = this.innerRadius + margin; <add> if (alignment == 'inner') <add> { <add> // When alignment is inner the radius is the innerRadius plus any margin. <add> radius = this.innerRadius + margin; <ide> this.ctx.textBaseline = 'bottom'; <del> } <del> else if (alignment == 'outer') <del> { <del> // Outer it is the outerRadius minus any margin. <del> radius = this.outerRadius - margin; <add> } <add> else if (alignment == 'outer') <add> { <add> // Outer it is the outerRadius minus any margin. <add> radius = this.outerRadius - margin; <ide> this.ctx.textBaseline = 'top'; <del> } <del> else if (alignment == 'center') <del> { <del> // When center we want the text halfway between the inner and outer radius. <del> radius = this.innerRadius + margin + ((this.outerRadius - this.innerRadius) / 2); <del> this.ctx.textBaseline = 'middle'; <del> } <del> <del> // Set the angle to increment by when looping though and outputting the characters in the text <add> } <add> else if (alignment == 'center') <add> { <add> // When center we want the text halfway between the inner and outer radius. <add> radius = this.innerRadius + margin + ((this.outerRadius - this.innerRadius) / 2); <add> this.ctx.textBaseline = 'middle'; <add> } <add> <add> // Set the angle to increment by when looping though and outputting the characters in the text <ide> // as we do this by rotating the wheel small amounts adding each character. <del> var anglePerChar = 0; <del> var drawAngle = 0; <del> <del> // If more than one character in the text then... <add> var anglePerChar = 0; <add> var drawAngle = 0; <add> <add> // If more than one character in the text then... <ide> if (seg.text.length > 1) <del> { <del> // Text is drawn from the left. <del> this.ctx.textAlign = 'left'; <del> <del> // Work out how much angle the text rendering loop below needs to rotate by for each character to render them next to each other. <add> { <add> // Text is drawn from the left. <add> this.ctx.textAlign = 'left'; <add> <add> // Work out how much angle the text rendering loop below needs to rotate by for each character to render them next to each other. <ide> // I have discovered that 4 * the font size / 10 at 100px radius is the correct spacing for between the characters <ide> // using a monospace font, non monospace may look a little odd as in there will appear to be extra spaces between chars. <ide> anglePerChar = (4 * (fontSize / 10)); <ide> totalArc = (anglePerChar * seg.text.length); <ide> <ide> // Now set initial draw angle to half way between the start and end of the segment. <del> drawAngle = seg.startAngle + (((seg.endAngle - seg.startAngle) / 2) - (totalArc / 2)); <del> } <del> else <del> { <del> // The initial draw angle is the center of the segment when only one character. <del> drawAngle = (seg.startAngle + ((seg.endAngle - seg.startAngle) / 2)); <del> <del> // To ensure is dead-center the text alignment also needs to be centred. <del> this.ctx.textAlign = 'center'; <del> } <add> drawAngle = seg.startAngle + (((seg.endAngle - seg.startAngle) / 2) - (totalArc / 2)); <add> } <add> else <add> { <add> // The initial draw angle is the center of the segment when only one character. <add> drawAngle = (seg.startAngle + ((seg.endAngle - seg.startAngle) / 2)); <add> <add> // To ensure is dead-center the text alignment also needs to be centred. <add> this.ctx.textAlign = 'center'; <add> } <ide> <ide> // ---------------------- <ide> // Adjust the initial draw angle as needed to take in to account the rotationAngle of the wheel. <ide> drawAngle += this.rotationAngle; <del> <del> // ---------------------- <del> // Now the drawing itself. <del> // Loop for each character in the text. <del> for (c = 0; c < (seg.text.length); c++) <del> { <del> this.ctx.save(); <add> <add> // ---------------------- <add> // Now the drawing itself. <add> // Loop for each character in the text. <add> for (c = 0; c < (seg.text.length); c++) <add> { <add> this.ctx.save(); <ide> <ide> character = seg.text.charAt(c); <del> <del> // Rotate the wheel to the draw angle as we need to add the character at this location. <add> <add> // Rotate the wheel to the draw angle as we need to add the character at this location. <ide> this.ctx.translate(this.centerX, this.centerY); <del> this.ctx.rotate(this.degToRad(drawAngle)); <del> this.ctx.translate(-this.centerX, -this.centerY); <del> <del> // Now draw the character directly above the center point of the wheel at the appropriate radius. <del> if (strokeStyle) <del> this.ctx.strokeText(character, this.centerX, this.centerY - radius); <del> <del> if (fillStyle) <del> this.ctx.fillText(character, this.centerX, this.centerY - radius); <del> <del> // Increment the drawAngle by the angle per character so next loop we rotate <add> this.ctx.rotate(this.degToRad(drawAngle)); <add> this.ctx.translate(-this.centerX, -this.centerY); <add> <add> // Now draw the character directly above the center point of the wheel at the appropriate radius. <add> if (strokeStyle) <add> this.ctx.strokeText(character, this.centerX, this.centerY - radius); <add> <add> if (fillStyle) <add> this.ctx.fillText(character, this.centerX, this.centerY - radius); <add> <add> // Increment the drawAngle by the angle per character so next loop we rotate <ide> // to the next angle required to draw the character at. <del> drawAngle += anglePerChar; <add> drawAngle += anglePerChar; <ide> <ide> this.ctx.restore(); <del> } <del> } <del> } <del> } <del> <del> // Restore so all text options are reset ready for the next text. <del> this.ctx.restore(); <del> } <del> } <add> } <add> } <add> } <add> } <add> <add> // Restore so all text options are reset ready for the next text. <add> this.ctx.restore(); <add> } <add> } <ide> } <ide> <ide> // ==================================================================================================================== <ide> // ==================================================================================================================== <ide> Winwheel.prototype.degToRad = function(d) <ide> { <del> return d * 0.0174532925199432957; <add> return d * 0.0174532925199432957; <ide> } <ide> <ide> // ==================================================================================================================== <ide> // ==================================================================================================================== <ide> Winwheel.prototype.setCenter = function(x, y) <ide> { <del> this.centerX = x; <del> this.centerY = y; <add> this.centerX = x; <add> this.centerY = y; <ide> } <ide> <ide> // ==================================================================================================================== <ide> // ==================================================================================================================== <ide> Winwheel.prototype.addSegment = function(options, position) <ide> { <del> // Create a new segment object passing the options in. <del> newSegment = new Segment(options); <del> <del> // Increment the numSegments property of the class since new segment being added. <del> this.numSegments ++; <del> var segmentPos; <del> <del> // Work out where to place the segment, the default is simply as a new segment at the end of the wheel. <del> if (typeof position !== 'undefined') <del> { <del> // Because we need to insert the segment at this position, not overwrite it, we need to move all segments after this <del> // location along one in the segments array, before finally adding this new segment at the specified location. <del> for (var x = this.numSegments; x > position; x --) <del> { <del> this.segments[x] = this.segments[x -1]; <del> } <del> <del> this.segments[position] = newSegment; <del> segmentPos = position; <del> } <del> else <del> { <del> this.segments[this.numSegments] = newSegment; <del> segmentPos = this.numSegments; <del> } <del> <del> // Since a segment has been added the segment sizes need to be re-computed so call function to do this. <del> this.updateSegmentSizes(); <del> <del> // Return the segment object just created in the wheel (JavaScript will return it by reference), so that <del> // further things can be done with it by the calling code if desired. <del> return this.segments[segmentPos]; <add> // Create a new segment object passing the options in. <add> newSegment = new Segment(options); <add> <add> // Increment the numSegments property of the class since new segment being added. <add> this.numSegments ++; <add> var segmentPos; <add> <add> // Work out where to place the segment, the default is simply as a new segment at the end of the wheel. <add> if (typeof position !== 'undefined') <add> { <add> // Because we need to insert the segment at this position, not overwrite it, we need to move all segments after this <add> // location along one in the segments array, before finally adding this new segment at the specified location. <add> for (var x = this.numSegments; x > position; x --) <add> { <add> this.segments[x] = this.segments[x -1]; <add> } <add> <add> this.segments[position] = newSegment; <add> segmentPos = position; <add> } <add> else <add> { <add> this.segments[this.numSegments] = newSegment; <add> segmentPos = this.numSegments; <add> } <add> <add> // Since a segment has been added the segment sizes need to be re-computed so call function to do this. <add> this.updateSegmentSizes(); <add> <add> // Return the segment object just created in the wheel (JavaScript will return it by reference), so that <add> // further things can be done with it by the calling code if desired. <add> return this.segments[segmentPos]; <ide> } <ide> <ide> // ==================================================================================================================== <ide> // ==================================================================================================================== <ide> Winwheel.prototype.deleteSegment = function(position) <ide> { <del> // There needs to be at least one segment in order for the wheel to draw, so only allow delete if there <del> // is more than one segment currently left in the wheel. <add> // There needs to be at least one segment in order for the wheel to draw, so only allow delete if there <add> // is more than one segment currently left in the wheel. <ide> <ide> //++ check that specifying a position that does not exist - say 10 in a 6 segment wheel does not cause issues. <del> if (this.numSegments > 1) <del> { <del> // If the position of the segment to remove has been specified. <del> if (typeof position !== 'undefined') <del> { <del> // The array is to be shortened so we need to move all segments after the one <del> // to be removed down one so there is no gap. <del> for (var x = position; x < this.numSegments; x ++) <del> { <del> this.segments[x] = this.segments[x + 1]; <del> } <del> } <del> <del> // Unset the last item in the segments array since there is now one less. <del> this.segments[this.numSegments] = undefined; <del> <del> // Decrement the number of segments, <del> // then call function to update the segment sizes. <del> this.numSegments --; <del> this.updateSegmentSizes(); <del> } <add> if (this.numSegments > 1) <add> { <add> // If the position of the segment to remove has been specified. <add> if (typeof position !== 'undefined') <add> { <add> // The array is to be shortened so we need to move all segments after the one <add> // to be removed down one so there is no gap. <add> for (var x = position; x < this.numSegments; x ++) <add> { <add> this.segments[x] = this.segments[x + 1]; <add> } <add> } <add> <add> // Unset the last item in the segments array since there is now one less. <add> this.segments[this.numSegments] = undefined; <add> <add> // Decrement the number of segments, <add> // then call function to update the segment sizes. <add> this.numSegments --; <add> this.updateSegmentSizes(); <add> } <ide> } <ide> <ide> // ==================================================================================================================== <ide> // ==================================================================================================================== <ide> Winwheel.prototype.windowToCanvas = function(x, y) <ide> { <del> var bbox = this.canvas.getBoundingClientRect(); <del> <del> return { <del> x: Math.floor(x - bbox.left * (this.canvas.width / bbox.width)), <del> y: Math.floor(y - bbox.top * (this.canvas.height / bbox.height)) <del> }; <add> var bbox = this.canvas.getBoundingClientRect(); <add> <add> return { <add> x: Math.floor(x - bbox.left * (this.canvas.width / bbox.width)), <add> y: Math.floor(y - bbox.top * (this.canvas.height / bbox.height)) <add> }; <ide> } <ide> <ide> // ==================================================================================================================== <ide> // ==================================================================================================================== <ide> Winwheel.prototype.getSegmentAt = function(x, y) <ide> { <del> var foundSegment = null; <add> var foundSegment = null; <ide> <ide> // Call function to return segment number. <ide> var segmentNumber = this.getSegmentNumberAt(x, y); <ide> foundSegment = this.segments[segmentNumber]; <ide> } <ide> <del> return foundSegment; <add> return foundSegment; <ide> } <ide> <ide> // ==================================================================================================================== <ide> Winwheel.prototype.getSegmentNumberAt = function(x, y) <ide> { <ide> // KNOWN ISSUE: this does not work correct if the canvas is scaled using css, or has padding, border. <del> // @TODO see if can find a solution at some point, check windowToCanvas working as needed, then below. <del> <del> // Call function above to convert the raw x and y from the user's browser to canvas coordinates <del> // i.e. top and left is top and left of canvas, not top and left of the user's browser. <del> var loc = this.windowToCanvas(x, y); <del> <del> // ------------------------------------------ <del> // Now start the process of working out the segment clicked. <del> // First we need to figure out the angle of an imaginary line between the centerX and centerY of the wheel and <del> // the X and Y of the location (for example a mouse click). <del> var topBottom; <del> var leftRight; <del> var adjacentSideLength; <del> var oppositeSideLength; <del> var hypotenuseSideLength; <del> <del> // We will use right triangle maths with the TAN function. <del> // The start of the triangle is the wheel center, the adjacent side is along the x axis, and the opposite side is along the y axis. <del> <del> // We only ever use positive numbers to work out the triangle and the center of the wheel needs to be considered as 0 for the numbers <del> // in the maths which is why there is the subtractions below. We also remember what quadrant of the wheel the location is in as we <del> // need this information later to add 90, 180, 270 degrees to the angle worked out from the triangle to get the position around a 360 degree wheel. <del> if (loc.x > this.centerX) <del> { <del> adjacentSideLength = (loc.x - this.centerX); <del> leftRight = 'R'; // Location is in the right half of the wheel. <del> } <del> else <del> { <del> adjacentSideLength = (this.centerX - loc.x); <del> leftRight = 'L'; // Location is in the left half of the wheel. <del> } <del> <del> if (loc.y > this.centerY) <del> { <del> oppositeSideLength = (loc.y - this.centerY); <del> topBottom = 'B'; // Bottom half of wheel. <del> } <del> else <del> { <del> oppositeSideLength = (this.centerY - loc.y); <del> topBottom = 'T'; // Top Half of wheel. <del> } <del> <del> // Now divide opposite by adjacent to get tan value. <del> var tanVal = oppositeSideLength / adjacentSideLength; <del> <del> // Use the tan function and convert results to degrees since that is what we work with. <del> var result = (Math.atan(tanVal) * 180/Math.PI); <del> var locationAngle = 0; <del> <del> // We also need the length of the hypotenuse as later on we need to compare this to the outerRadius of the segment / circle. <del> hypotenuseSideLength = Math.sqrt((oppositeSideLength * oppositeSideLength) + (adjacentSideLength * adjacentSideLength)); <del> <del> // ------------------------------------------ <del> // Now to make sense around the wheel we need to alter the values based on if the location was in top or bottom half <del> // and also right or left half of the wheel, by adding 90, 180, 270 etc. Also for some the initial locationAngle needs to be inverted. <del> if ((topBottom == 'T') && (leftRight == 'R')) <del> { <del> locationAngle = Math.round(90 - result); <del> } <del> else if ((topBottom == 'B') && (leftRight == 'R')) <del> { <del> locationAngle = Math.round(result + 90); <del> } <del> else if ((topBottom == 'B') && (leftRight == 'L')) <del> { <del> locationAngle = Math.round((90 - result) + 180); <del> } <del> else if ((topBottom == 'T') && (leftRight == 'L')) <del> { <del> locationAngle = Math.round(result + 270); <del> } <add> // @TODO see if can find a solution at some point, check windowToCanvas working as needed, then below. <add> <add> // Call function above to convert the raw x and y from the user's browser to canvas coordinates <add> // i.e. top and left is top and left of canvas, not top and left of the user's browser. <add> var loc = this.windowToCanvas(x, y); <add> <add> // ------------------------------------------ <add> // Now start the process of working out the segment clicked. <add> // First we need to figure out the angle of an imaginary line between the centerX and centerY of the wheel and <add> // the X and Y of the location (for example a mouse click). <add> var topBottom; <add> var leftRight; <add> var adjacentSideLength; <add> var oppositeSideLength; <add> var hypotenuseSideLength; <add> <add> // We will use right triangle maths with the TAN function. <add> // The start of the triangle is the wheel center, the adjacent side is along the x axis, and the opposite side is along the y axis. <add> <add> // We only ever use positive numbers to work out the triangle and the center of the wheel needs to be considered as 0 for the numbers <add> // in the maths which is why there is the subtractions below. We also remember what quadrant of the wheel the location is in as we <add> // need this information later to add 90, 180, 270 degrees to the angle worked out from the triangle to get the position around a 360 degree wheel. <add> if (loc.x > this.centerX) <add> { <add> adjacentSideLength = (loc.x - this.centerX); <add> leftRight = 'R'; // Location is in the right half of the wheel. <add> } <add> else <add> { <add> adjacentSideLength = (this.centerX - loc.x); <add> leftRight = 'L'; // Location is in the left half of the wheel. <add> } <add> <add> if (loc.y > this.centerY) <add> { <add> oppositeSideLength = (loc.y - this.centerY); <add> topBottom = 'B'; // Bottom half of wheel. <add> } <add> else <add> { <add> oppositeSideLength = (this.centerY - loc.y); <add> topBottom = 'T'; // Top Half of wheel. <add> } <add> <add> // Now divide opposite by adjacent to get tan value. <add> var tanVal = oppositeSideLength / adjacentSideLength; <add> <add> // Use the tan function and convert results to degrees since that is what we work with. <add> var result = (Math.atan(tanVal) * 180/Math.PI); <add> var locationAngle = 0; <add> <add> // We also need the length of the hypotenuse as later on we need to compare this to the outerRadius of the segment / circle. <add> hypotenuseSideLength = Math.sqrt((oppositeSideLength * oppositeSideLength) + (adjacentSideLength * adjacentSideLength)); <add> <add> // ------------------------------------------ <add> // Now to make sense around the wheel we need to alter the values based on if the location was in top or bottom half <add> // and also right or left half of the wheel, by adding 90, 180, 270 etc. Also for some the initial locationAngle needs to be inverted. <add> if ((topBottom == 'T') && (leftRight == 'R')) <add> { <add> locationAngle = Math.round(90 - result); <add> } <add> else if ((topBottom == 'B') && (leftRight == 'R')) <add> { <add> locationAngle = Math.round(result + 90); <add> } <add> else if ((topBottom == 'B') && (leftRight == 'L')) <add> { <add> locationAngle = Math.round((90 - result) + 180); <add> } <add> else if ((topBottom == 'T') && (leftRight == 'L')) <add> { <add> locationAngle = Math.round(result + 270); <add> } <ide> <ide> // ------------------------------------------ <ide> // And now we have to adjust to make sense when the wheel is rotated from the 0 degrees either <ide> locationAngle = (360 - Math.abs(locationAngle)); <ide> } <ide> } <del> <del> // ------------------------------------------ <del> // OK, so after all of that we have the angle of a line between the centerX and centerY of the wheel and <del> // the X and Y of the location on the canvas where the mouse was clicked. Now time to work out the segment <del> // this corresponds to. We can use the segment start and end angles for this. <del> var foundSegmentNumber = null; <del> <del> for (var x = 1; x <= this.numSegments; x ++) <del> { <del> // Due to segments sharing start and end angles, if line is clicked will pick earlier segment. <del> if ((locationAngle >= this.segments[x].startAngle) && (locationAngle <= this.segments[x].endAngle)) <del> { <add> <add> // ------------------------------------------ <add> // OK, so after all of that we have the angle of a line between the centerX and centerY of the wheel and <add> // the X and Y of the location on the canvas where the mouse was clicked. Now time to work out the segment <add> // this corresponds to. We can use the segment start and end angles for this. <add> var foundSegmentNumber = null; <add> <add> for (var x = 1; x <= this.numSegments; x ++) <add> { <add> // Due to segments sharing start and end angles, if line is clicked will pick earlier segment. <add> if ((locationAngle >= this.segments[x].startAngle) && (locationAngle <= this.segments[x].endAngle)) <add> { <ide> // To ensure that a click anywhere on the canvas in the segment direction will not cause a <del> // segment to be matched, as well as the angles, we need to ensure the click was within the radius <del> // of the segment (or circle if no segment radius). <del> <del> // If the hypotenuseSideLength (length of location from the center of the wheel) is with the radius <del> // then we can assign the segment to the found segment and break out the loop. <del> <del> // Have to take in to account hollow wheels (doughnuts) so check is greater than innerRadius as <add> // segment to be matched, as well as the angles, we need to ensure the click was within the radius <add> // of the segment (or circle if no segment radius). <add> <add> // If the hypotenuseSideLength (length of location from the center of the wheel) is with the radius <add> // then we can assign the segment to the found segment and break out the loop. <add> <add> // Have to take in to account hollow wheels (doughnuts) so check is greater than innerRadius as <ide> // well as less than or equal to the outerRadius of the wheel. <del> if ((hypotenuseSideLength >= this.innerRadius) && (hypotenuseSideLength <= this.outerRadius)) <add> if ((hypotenuseSideLength >= this.innerRadius) && (hypotenuseSideLength <= this.outerRadius)) <ide> { <ide> foundSegmentNumber = x; <ide> break; <ide> } <del> } <del> } <del> <del> // Finally return the number. <del> return foundSegmentNumber; <add> } <add> } <add> <add> // Finally return the number. <add> return foundSegmentNumber; <ide> } <ide> <ide> // ==================================================================================================================== <ide> // Call function to compute the animation properties. <ide> this.computeAnimation(); <ide> <del> //++ when have multiple wheels and an animation for one or the other is played or stopped it affects the others <del> //++ on the screen. Is there a way to give each wheel its own instance of tweenmax not affected by the other??? <del> <del> // Set this global variable to this object as an external function is required to call the draw() function on the wheel <add> //++ when have multiple wheels and an animation for one or the other is played or stopped it affects the others <add> //++ on the screen. Is there a way to give each wheel its own instance of tweenmax not affected by the other??? <add> <add> // Set this global variable to this object as an external function is required to call the draw() function on the wheel <ide> // each loop of the animation as Greensock cannot call the draw function directly on this class. <ide> winwheelToDrawDuringAnimation = this; <ide> <ide> // ================================================================================================================================================== <ide> Winwheel.prototype.stopAnimation = function(canCallback) <ide> { <del> //++ @TODO re-check if kill is the correct thing here, and if there is more than one wheel object being animated (once sort how to do that) <del> //++ what is the effect on it? <del> <del> // We can kill the animation using our tween object. <add> //++ @TODO re-check if kill is the correct thing here, and if there is more than one wheel object being animated (once sort how to do that) <add> //++ what is the effect on it? <add> <add> // We can kill the animation using our tween object. <ide> winwheelToDrawDuringAnimation.tween.kill(); <ide> <ide> // We should still call the external function to stop the wheel being redrawn even click and also callback any function that is supposed to be. <ide> }; <ide> <ide> // Now loop through the default options and create properties of this class set to the value for <del> // the option passed in if a value was, or if not then set the value of the default. <del> for (var key in defaultOptions) <del> { <del> if ((options != null) && (typeof(options[key]) !== 'undefined')) <del> this[key] = options[key]; <del> else <del> this[key] = defaultOptions[key]; <del> } <add> // the option passed in if a value was, or if not then set the value of the default. <add> for (var key in defaultOptions) <add> { <add> if ((options != null) && (typeof(options[key]) !== 'undefined')) <add> this[key] = options[key]; <add> else <add> this[key] = defaultOptions[key]; <add> } <ide> <ide> // Also loop though the passed in options and add anything specified not part of the class in to it as a property. <ide> if (options != null) <ide> // ==================================================================================================================== <ide> function Segment(options) <ide> { <del> // Define default options for segments, most are null so that the global defaults for the wheel <del> // are used if the values for a particular segment are not specifically set. <del> defaultOptions = { <del> 'size' : null, // Leave null for automatic. Valid values are degrees 0-360. Use percentToDegrees function if needed to convert. <del> 'text' : '', // Default is blank. <del> 'fillStyle' : null, // If null for the rest the global default will be used. <del> 'strokeStyle' : null, <del> 'lineWidth' : null, <del> 'textFontFamily' : null, <del> 'textFontSize' : null, <del> 'textFontWeight' : null, <del> 'textOrientation' : null, <del> 'textAlignment' : null, <del> 'textDirection' : null, <del> 'textMargin' : null, <del> 'textFillStyle' : null, <del> 'textStrokeStyle' : null, <del> 'textLineWidth' : null <del> }; <del> <del> // Now loop through the default options and create properties of this class set to the value for <del> // the option passed in if a value was, or if not then set the value of the default. <del> for (var key in defaultOptions) <del> { <del> if ((options != null) && (typeof(options[key]) !== 'undefined')) <del> this[key] = options[key]; <del> else <del> this[key] = defaultOptions[key]; <del> } <add> // Define default options for segments, most are null so that the global defaults for the wheel <add> // are used if the values for a particular segment are not specifically set. <add> defaultOptions = { <add> 'size' : null, // Leave null for automatic. Valid values are degrees 0-360. Use percentToDegrees function if needed to convert. <add> 'text' : '', // Default is blank. <add> 'fillStyle' : null, // If null for the rest the global default will be used. <add> 'strokeStyle' : null, <add> 'lineWidth' : null, <add> 'textFontFamily' : null, <add> 'textFontSize' : null, <add> 'textFontWeight' : null, <add> 'textOrientation' : null, <add> 'textAlignment' : null, <add> 'textDirection' : null, <add> 'textMargin' : null, <add> 'textFillStyle' : null, <add> 'textStrokeStyle' : null, <add> 'textLineWidth' : null <add> }; <add> <add> // Now loop through the default options and create properties of this class set to the value for <add> // the option passed in if a value was, or if not then set the value of the default. <add> for (var key in defaultOptions) <add> { <add> if ((options != null) && (typeof(options[key]) !== 'undefined')) <add> this[key] = options[key]; <add> else <add> this[key] = defaultOptions[key]; <add> } <ide> <ide> // Also loop though the passed in options and add anything specified not part of the class in to it as a property. <ide> // This allows the developer to easily add properties to segments at construction time. <ide> } <ide> } <ide> } <del> <del> // There are 2 additional properties which are set by the code, so need to define them here. <del> // They are not in the default options because they are not something that should be set by the user, <del> // the values are updated every time the updateSegmentSizes() function is called. <del> this.startAngle = 0; <del> this.endAngle = 0; <add> <add> // There are 2 additional properties which are set by the code, so need to define them here. <add> // They are not in the default options because they are not something that should be set by the user, <add> // the values are updated every time the updateSegmentSizes() function is called. <add> this.startAngle = 0; <add> this.endAngle = 0; <ide> } <ide> <ide> // ==================================================================================================================== <ide> }; <ide> <ide> // Now loop through the default options and create properties of this class set to the value for <del> // the option passed in if a value was, or if not then set the value of the default. <del> for (var key in defaultOptions) <del> { <del> if ((options != null) && (typeof(options[key]) !== 'undefined')) <del> { <del> this[key] = options[key]; <del> } <del> else <del> { <del> this[key] = defaultOptions[key]; <del> } <del> } <add> // the option passed in if a value was, or if not then set the value of the default. <add> for (var key in defaultOptions) <add> { <add> if ((options != null) && (typeof(options[key]) !== 'undefined')) <add> { <add> this[key] = options[key]; <add> } <add> else <add> { <add> this[key] = defaultOptions[key]; <add> } <add> } <ide> } <ide> <ide> // ==================================================================================================================== <ide> if (winwheelToDrawDuringAnimation) <ide> { <ide> // Check if the clearTheCanvas is specified for this animation, if not or it is not false then clear the canvas. <del> if (winwheelToDrawDuringAnimation.animation.clearTheCanvas != false) <del> { <del> winwheelToDrawDuringAnimation.ctx.clearRect(0, 0, winwheelToDrawDuringAnimation.canvas.width, winwheelToDrawDuringAnimation.canvas.height); <del> } <del> <del> // If there is a callback function which is supposed to be called before the wheel is drawn then do that. <add> if (winwheelToDrawDuringAnimation.animation.clearTheCanvas != false) <add> { <add> winwheelToDrawDuringAnimation.ctx.clearRect(0, 0, winwheelToDrawDuringAnimation.canvas.width, winwheelToDrawDuringAnimation.canvas.height); <add> } <add> <add> // If there is a callback function which is supposed to be called before the wheel is drawn then do that. <ide> if (winwheelToDrawDuringAnimation.animation.callbackBefore != null) <ide> { <ide> eval(winwheelToDrawDuringAnimation.animation.callbackBefore); <ide> } <ide> <ide> // Call code to draw the wheel, pass in false as we never want it to clear the canvas as that would wipe anything drawn in the callbackBefore. <del> winwheelToDrawDuringAnimation.draw(false); <add> winwheelToDrawDuringAnimation.draw(false); <ide> <ide> // If there is a callback function which is supposed to be called after the wheel has been drawn then do that. <ide> if (winwheelToDrawDuringAnimation.animation.callbackAfter != null) <ide> TweenMax.ticker.removeEventListener("tick", winwheelAnimationLoop); <ide> <ide> // When the animation is stopped if canCallback is not false then try to call the callback. <del> // false can be passed in to stop the after happening if the animation has been stopped before it ended normally. <add> // false can be passed in to stop the after happening if the animation has been stopped before it ended normally. <ide> if (canCallback != false) <ide> { <ide> if (winwheelToDrawDuringAnimation.animation.callbackFinished != null)
Java
mit
6ad3c974774df2f03e800ae3caf5e7aa9552110a
0
DDoS/SpongeVanilla,DDoS/SpongeVanilla,CodeKingdomsTeam/SpongeVanilla,CodeKingdomsTeam/SpongeVanilla,kenzierocks/SpongeVanilla,kenzierocks/SpongeVanilla
badsrc/MythicEssentials.java
public class MythicEssentials { /* * This class handles command events to provide Essentials-like functionality. * It also demonstrates a plugin setup. */ public static String dbPrefix = "mythic_ess"; public static void onInstall(){ Mythic.getDatabase().install(dbPrefix, true, true, true, true, true, true, true, true); //register essentials event handler MythicEventHandlerRegistry.register(MythicEssentials.class); } public static void onUninstall(){ } @MythicEventHandler public void handle(MythicEventCommand event) { if(routeCommand(event)){ event.cancelled = true; } } public boolean routeCommand(MythicEventCommand event){ if(event.parameters.length == 0) return false; if(event.parameters[0].equalsIgnoreCase("spawn")){ onCommandSpawn(event); return true; } else if(event.parameters[0].equalsIgnoreCase("home")){ onCommandHome(event); return true; } else if(event.parameters[0].equalsIgnoreCase("sethome")){ onCommandSetHome(event); return true; } else if(event.parameters[0].equalsIgnoreCase("warp")){ onCommandWarp(event); return true; } else if(event.parameters[0].equalsIgnoreCase("setwarp")){ onCommandSetWarp(event); return true; } else if(event.parameters[0].equalsIgnoreCase("delwarp")){ onCommandDelWarp(event); return true; } else if(event.parameters[0].equalsIgnoreCase("tpa")){ onCommandTpa(event); return true; } else if(event.parameters[0].equalsIgnoreCase("tpahere")){ onCommandTpaHere(event); return true; } else if(event.parameters[0].equalsIgnoreCase("tpaccept")){ onCommandTpAccept(event); return true; } else if(event.parameters[0].equalsIgnoreCase("tpdeny")){ onCommandTpDeny(event); return true; } else if(event.parameters[0].equalsIgnoreCase("rules")){ onCommandRules(event); return true; } else if(event.parameters[0].equalsIgnoreCase("plugins")){ onCommandPlugins(event); return true; } else if(event.parameters[0].equalsIgnoreCase("heal")){ onCommandHeal(event); return true; } else if(event.parameters[0].equalsIgnoreCase("feed")){ onCommandFeed(event); return true; } else if(event.parameters[0].equalsIgnoreCase("ping")){ onCommandPing(event); return true; } else if(event.parameters[0].equalsIgnoreCase("world")){ onCommandWorld(event); return true; } else if(event.parameters[0].equalsIgnoreCase("back")){ onCommandBack(event); return true; } return false; } private void onCommandBack(MythicEventCommand event) { if(event.player == null){ MythicLogger.info("Only a player can use this command."); } else { event.player.sendChatMessage(MythicChatFormatCodes.preFormatError() + "This command is not available yet."); } } private void onCommandWorld(MythicEventCommand event) { if(event.player == null){ MythicLogger.info("Only a player can use this command."); } else { event.player.sendChatMessage(MythicChatFormatCodes.preFormatError() + "This command is not available yet."); } } private void onCommandPing(MythicEventCommand event) { if(event.player == null){ MythicLogger.info("Pong!"); } else { event.player.sendChatMessage(MythicChatFormatCodes.preFormatInfo() + "Pong!"); } } private void onCommandFeed(MythicEventCommand event) { if(event.player == null){ MythicLogger.info("Only a player can use this command."); } else { event.player.sendChatMessage(MythicChatFormatCodes.preFormatError() + "This command is not available yet."); } } private void onCommandHeal(MythicEventCommand event) { if(event.player == null){ MythicLogger.info("Only a player can use this command."); } else { event.player.sendChatMessage(MythicChatFormatCodes.preFormatError() + "This command is not available yet."); } } private void onCommandPlugins(MythicEventCommand event) { if(event.player == null){ MythicLogger.info("Only a player can use this command."); } else { event.player.sendChatMessage(MythicChatFormatCodes.preFormatInfo() + "Running MythicAPI (Version: 1.0) - Plugins (1):"); event.player.sendChatMessage(MythicChatFormatCodes.preFormatInfo() + "Mythic-Essentials"); } } private void onCommandRules(MythicEventCommand event) { if(event.player == null){ MythicLogger.info("Only a player can use this command."); } else { event.player.sendChatMessage(MythicChatFormatCodes.preFormatInfo() + "No hacking, mods, or exploits."); event.player.sendChatMessage(MythicChatFormatCodes.preFormatInfo() + "Be respectful of other players. Watch your language."); event.player.sendChatMessage(MythicChatFormatCodes.preFormatInfo() + "No griefing, raiding, or PvP."); event.player.sendChatMessage(MythicChatFormatCodes.preFormatInfo() + "Do not ask for items or favors from staff."); event.player.sendChatMessage(MythicChatFormatCodes.preFormatInfo() + "Act responsible and mature. Do not spam or advertise."); event.player.sendChatMessage(MythicChatFormatCodes.preFormatInfo() + "Do not scam, aggrevate, or harass other players."); } } private void onCommandTpDeny(MythicEventCommand event) { if(event.player == null){ MythicLogger.info("Only a player can use this command."); } else { String requestFrom = getPlayerString(event.player, "teleport.request.from.username", null); if(requestFrom != null && !requestFrom.equalsIgnoreCase("X")){ MythicPlayer requestor = MythicServer.getPlayerByName(requestFrom); if(requestor != null){ requestor.sendChatMessage(MythicChatFormatCodes.preFormatError() + "Your teleport request was denied."); } } event.player.sendChatMessage(MythicChatFormatCodes.preFormatInfo() + "Teleport request denied."); clearTeleportRequest(event.player); } } private void onCommandTpAccept(MythicEventCommand event) { if(event.player == null){ MythicLogger.info("Only a player can use this command."); } else { if(event.parameters.length != 1){ event.player.sendChatMessage(MythicChatFormatCodes.preFormatError() + "Wrong number of parameters."); } else { String requestFrom = getPlayerString(event.player, "teleport.request.from.username", null); if(requestFrom == null || requestFrom.equalsIgnoreCase("X")){ event.player.sendChatMessage(MythicChatFormatCodes.preFormatError() + "You do not have a pending teleport request."); } else { MythicPlayer requestor = MythicServer.getPlayerByName(requestFrom); if(requestor == null){ clearTeleportRequest(event.player); event.player.sendChatMessage(MythicChatFormatCodes.preFormatError() + "Could not locate player " + requestFrom + "."); } else { String direction = getPlayerString(event.player, "teleport.request.direction", null); if(direction.equalsIgnoreCase("you.to.them")){ clearTeleportRequest(event.player); event.player.teleportToPlayer(requestor); event.player.sendChatMessage(MythicChatFormatCodes.preFormatInfo() + "Teleported to " + requestFrom + "."); requestor.sendChatMessage(MythicChatFormatCodes.preFormatInfo() + event.player.getName() + " has teleported to you."); } else if(direction.equalsIgnoreCase("them.to.you")){ clearTeleportRequest(event.player); requestor.teleportToPlayer(event.player); event.player.sendChatMessage(MythicChatFormatCodes.preFormatInfo() + requestor.getName() + " has teleported to you."); requestor.sendChatMessage(MythicChatFormatCodes.preFormatInfo() + "Teleported to " + event.player.getName() + "."); } else { clearTeleportRequest(event.player); event.player.sendChatMessage(MythicChatFormatCodes.preFormatError() + "Could not complete teleport request safely."); } } } } } } private void clearTeleportRequest(MythicPlayer recipient){ setPlayerString(recipient, "teleport.request.from.username", "X"); } private void onCommandTpaHere(MythicEventCommand event) { if(event.player == null){ MythicLogger.info("Only a player can use this command."); } else { if(event.parameters.length != 2){ event.player.sendChatMessage(MythicChatFormatCodes.preFormatError() + "Wrong number of parameters."); } else { String targetUsername = event.parameters[1]; targetUsername = MythicServer.getMatchingPlayerName(targetUsername); if(targetUsername == null || targetUsername.equalsIgnoreCase("X")){ event.player.sendChatMessage(MythicChatFormatCodes.preFormatError() + "Could not find a player matching " + event.parameters[1] + "."); } else { MythicPlayer target = MythicServer.getPlayerByName(targetUsername); target.sendChatMessage(MythicChatFormatCodes.preFormatInfo() + event.player.getName() + " would like to teleport you to them."); target.sendChatMessage(MythicChatFormatCodes.preFormatInfo() + "Type " + MythicChatFormatCodes.lightgreen + "/tpaccept " + MythicChatFormatCodes.gold + "to go to them, or " + MythicChatFormatCodes.lightred + "/tpdeny " + MythicChatFormatCodes.gold + "to refuse."); event.player.sendChatMessage(MythicChatFormatCodes.preFormatInfo() + "Sent teleport request to " + targetUsername + "."); setPlayerString(target, "teleport.request.from.username", event.player.getName()); setPlayerString(target, "teleport.request.direction", "you.to.them"); } } } } private void onCommandTpa(MythicEventCommand event) { if(event.player == null){ MythicLogger.info("Only a player can use this command."); } else { if(event.parameters.length != 2){ event.player.sendChatMessage(MythicChatFormatCodes.preFormatError() + "Wrong number of parameters."); } else { String targetUsername = event.parameters[1]; targetUsername = MythicServer.getMatchingPlayerName(targetUsername); if(targetUsername == null || targetUsername.equalsIgnoreCase("X")){ event.player.sendChatMessage(MythicChatFormatCodes.preFormatError() + "Could not find a player matching " + event.parameters[1] + "."); } else { MythicPlayer target = MythicServer.getPlayerByName(targetUsername); target.sendChatMessage(MythicChatFormatCodes.preFormatInfo() + event.player.getName() + " would like to teleport to you."); target.sendChatMessage(MythicChatFormatCodes.preFormatInfo() + "Type " + MythicChatFormatCodes.lightgreen + "/tpaccept " + MythicChatFormatCodes.gold + "to bring them here, or " + MythicChatFormatCodes.lightred + "/tpdeny " + MythicChatFormatCodes.gold + "to refuse."); event.player.sendChatMessage(MythicChatFormatCodes.preFormatInfo() + "Sent teleport request to " + targetUsername + "."); setPlayerString(target, "teleport.request.from.username", event.player.getName()); setPlayerString(target, "teleport.request.direction", "them.to.you"); } } } } private void onCommandDelWarp(MythicEventCommand event) { if(event.player == null){ MythicLogger.info("Only a player can use this command."); } else { event.player.sendChatMessage(MythicChatFormatCodes.preFormatError() + "This command is not available yet."); } } private void onCommandSetWarp(MythicEventCommand event) { if(event.player == null){ MythicLogger.info("Only a player can use this command."); } else { event.player.sendChatMessage(MythicChatFormatCodes.preFormatError() + "This command is not available yet."); } } private void onCommandWarp(MythicEventCommand event) { if(event.player == null){ MythicLogger.info("Only a player can use this command."); } else { event.player.sendChatMessage(MythicChatFormatCodes.preFormatError() + "This command is not available yet."); } } private void onCommandSetHome(MythicEventCommand event) { if(event.player == null){ MythicLogger.info("Only a player can use this command."); } else { if(event.parameters.length > 1){ event.player.sendChatMessage(MythicChatFormatCodes.preFormatError() + "Too many parameters."); } else { setPlayerInt(event.player, "home.dimension", event.player.getDimension()); setPlayerFloat(event.player, "home.x", (float) event.player.getX()); setPlayerFloat(event.player, "home.y", (float) event.player.getY()); setPlayerFloat(event.player, "home.z", (float) event.player.getZ()); event.player.sendChatMessage(MythicChatFormatCodes.preFormatInfo() + "Home set."); } } } private void onCommandHome(MythicEventCommand event) { if(event.player == null){ MythicLogger.info("Only a player can use this command."); } else { if(event.parameters.length > 1){ event.player.sendChatMessage(MythicChatFormatCodes.preFormatError() + "Too many parameters."); } else { int dimId = getPlayerInt(event.player, "home.dimension", 999); if(dimId == 999){ event.player.sendChatMessage(MythicChatFormatCodes.preFormatError() + "You do not have a home set."); } else { if(event.player.getDimension() != dimId) event.player.travelToDimension(dimId); double x = getPlayerFloat(event.player, "home.x", (float) event.player.getX()); double y = getPlayerFloat(event.player, "home.y", (float) event.player.getY()); double z = getPlayerFloat(event.player, "home.z", (float) event.player.getZ()); event.player.setPosition(x, y, z); event.player.sendChatMessage(MythicChatFormatCodes.preFormatInfo() + "Teleported home."); } } } } private void onCommandSpawn(MythicEventCommand event) { if(event.parameters.length > 1){ if(event.parameters.length == 2){ } else { if(event.player == null){ MythicLogger.info("Too many parameters."); return; } else { event.player.sendChatMessage(MythicChatFormatCodes.preFormatError() + "Too many parameters."); } } } else { if(event.player == null){ MythicLogger.info("Only a player is can execute the self-targeted variant of this command."); return; } else { if(event.player.getDimension() != 0) event.player.travelToDimension(0); event.player.setPosition(164.5D, 73.5D, 41.5D); event.player.sendChatMessage(MythicChatFormatCodes.preFormatInfo() + "Teleported to spawn."); } } } private void setPlayerString(MythicPlayer player, String dataName, String value){ Mythic.getDatabase().setPlayerString(dbPrefix, dataName, player.getUUIDString(), value); } private void setPlayerFloat(MythicPlayer player, String dataName, float value){ Mythic.getDatabase().setPlayerFloat(dbPrefix, dataName, player.getUUIDString(), value); } private void setPlayerInt(MythicPlayer player, String dataName, int value){ Mythic.getDatabase().setPlayerInt(dbPrefix, dataName, player.getUUIDString(), value); } private String getPlayerString(MythicPlayer player, String dataName, String defaultVal){ return Mythic.getDatabase().getPlayerString(dbPrefix, dataName, player.getUUIDString(), defaultVal); } private float getPlayerFloat(MythicPlayer player, String dataName, float defaultVal){ return Mythic.getDatabase().getPlayerFloat(dbPrefix, dataName, player.getUUIDString(), defaultVal); } private int getPlayerInt(MythicPlayer player, String dataName, int defaultVal){ return Mythic.getDatabase().getPlayerInt(dbPrefix, dataName, player.getUUIDString(), defaultVal); } }
Remove old badsrc code.
badsrc/MythicEssentials.java
Remove old badsrc code.
<ide><path>adsrc/MythicEssentials.java <del> <del>public class MythicEssentials { <del> <del> /* <del> * This class handles command events to provide Essentials-like functionality. <del> * It also demonstrates a plugin setup. <del> */ <del> <del> public static String dbPrefix = "mythic_ess"; <del> <del> public static void onInstall(){ <del> Mythic.getDatabase().install(dbPrefix, true, true, true, true, true, true, true, true); <del> //register essentials event handler <del> MythicEventHandlerRegistry.register(MythicEssentials.class); <del> } <del> <del> public static void onUninstall(){ <del> <del> } <del> <del> @MythicEventHandler <del> public void handle(MythicEventCommand event) { <del> if(routeCommand(event)){ <del> event.cancelled = true; <del> } <del> } <del> <del> public boolean routeCommand(MythicEventCommand event){ <del> if(event.parameters.length == 0) return false; <del> if(event.parameters[0].equalsIgnoreCase("spawn")){ <del> onCommandSpawn(event); <del> return true; <del> } else if(event.parameters[0].equalsIgnoreCase("home")){ <del> onCommandHome(event); <del> return true; <del> } else if(event.parameters[0].equalsIgnoreCase("sethome")){ <del> onCommandSetHome(event); <del> return true; <del> } else if(event.parameters[0].equalsIgnoreCase("warp")){ <del> onCommandWarp(event); <del> return true; <del> } else if(event.parameters[0].equalsIgnoreCase("setwarp")){ <del> onCommandSetWarp(event); <del> return true; <del> } else if(event.parameters[0].equalsIgnoreCase("delwarp")){ <del> onCommandDelWarp(event); <del> return true; <del> } else if(event.parameters[0].equalsIgnoreCase("tpa")){ <del> onCommandTpa(event); <del> return true; <del> } else if(event.parameters[0].equalsIgnoreCase("tpahere")){ <del> onCommandTpaHere(event); <del> return true; <del> } else if(event.parameters[0].equalsIgnoreCase("tpaccept")){ <del> onCommandTpAccept(event); <del> return true; <del> } else if(event.parameters[0].equalsIgnoreCase("tpdeny")){ <del> onCommandTpDeny(event); <del> return true; <del> } else if(event.parameters[0].equalsIgnoreCase("rules")){ <del> onCommandRules(event); <del> return true; <del> } else if(event.parameters[0].equalsIgnoreCase("plugins")){ <del> onCommandPlugins(event); <del> return true; <del> } else if(event.parameters[0].equalsIgnoreCase("heal")){ <del> onCommandHeal(event); <del> return true; <del> } else if(event.parameters[0].equalsIgnoreCase("feed")){ <del> onCommandFeed(event); <del> return true; <del> } else if(event.parameters[0].equalsIgnoreCase("ping")){ <del> onCommandPing(event); <del> return true; <del> } else if(event.parameters[0].equalsIgnoreCase("world")){ <del> onCommandWorld(event); <del> return true; <del> } else if(event.parameters[0].equalsIgnoreCase("back")){ <del> onCommandBack(event); <del> return true; <del> } <del> return false; <del> } <del> <del> private void onCommandBack(MythicEventCommand event) { <del> if(event.player == null){ <del> MythicLogger.info("Only a player can use this command."); <del> } else { <del> event.player.sendChatMessage(MythicChatFormatCodes.preFormatError() + "This command is not available yet."); <del> } <del> } <del> <del> private void onCommandWorld(MythicEventCommand event) { <del> if(event.player == null){ <del> MythicLogger.info("Only a player can use this command."); <del> } else { <del> event.player.sendChatMessage(MythicChatFormatCodes.preFormatError() + "This command is not available yet."); <del> } <del> } <del> <del> private void onCommandPing(MythicEventCommand event) { <del> if(event.player == null){ <del> MythicLogger.info("Pong!"); <del> } else { <del> event.player.sendChatMessage(MythicChatFormatCodes.preFormatInfo() + "Pong!"); <del> } <del> } <del> <del> private void onCommandFeed(MythicEventCommand event) { <del> if(event.player == null){ <del> MythicLogger.info("Only a player can use this command."); <del> } else { <del> event.player.sendChatMessage(MythicChatFormatCodes.preFormatError() + "This command is not available yet."); <del> } <del> } <del> <del> private void onCommandHeal(MythicEventCommand event) { <del> if(event.player == null){ <del> MythicLogger.info("Only a player can use this command."); <del> } else { <del> event.player.sendChatMessage(MythicChatFormatCodes.preFormatError() + "This command is not available yet."); <del> } <del> } <del> <del> private void onCommandPlugins(MythicEventCommand event) { <del> if(event.player == null){ <del> MythicLogger.info("Only a player can use this command."); <del> } else { <del> event.player.sendChatMessage(MythicChatFormatCodes.preFormatInfo() + "Running MythicAPI (Version: 1.0) - Plugins (1):"); <del> event.player.sendChatMessage(MythicChatFormatCodes.preFormatInfo() + "Mythic-Essentials"); <del> } <del> } <del> <del> private void onCommandRules(MythicEventCommand event) { <del> if(event.player == null){ <del> MythicLogger.info("Only a player can use this command."); <del> } else { <del> event.player.sendChatMessage(MythicChatFormatCodes.preFormatInfo() + "No hacking, mods, or exploits."); <del> event.player.sendChatMessage(MythicChatFormatCodes.preFormatInfo() + "Be respectful of other players. Watch your language."); <del> event.player.sendChatMessage(MythicChatFormatCodes.preFormatInfo() + "No griefing, raiding, or PvP."); <del> event.player.sendChatMessage(MythicChatFormatCodes.preFormatInfo() + "Do not ask for items or favors from staff."); <del> event.player.sendChatMessage(MythicChatFormatCodes.preFormatInfo() + "Act responsible and mature. Do not spam or advertise."); <del> event.player.sendChatMessage(MythicChatFormatCodes.preFormatInfo() + "Do not scam, aggrevate, or harass other players."); <del> } <del> } <del> <del> private void onCommandTpDeny(MythicEventCommand event) { <del> if(event.player == null){ <del> MythicLogger.info("Only a player can use this command."); <del> } else { <del> String requestFrom = getPlayerString(event.player, "teleport.request.from.username", null); <del> if(requestFrom != null && !requestFrom.equalsIgnoreCase("X")){ <del> MythicPlayer requestor = MythicServer.getPlayerByName(requestFrom); <del> if(requestor != null){ <del> requestor.sendChatMessage(MythicChatFormatCodes.preFormatError() + "Your teleport request was denied."); <del> } <del> } <del> event.player.sendChatMessage(MythicChatFormatCodes.preFormatInfo() + "Teleport request denied."); <del> clearTeleportRequest(event.player); <del> } <del> } <del> <del> private void onCommandTpAccept(MythicEventCommand event) { <del> if(event.player == null){ <del> MythicLogger.info("Only a player can use this command."); <del> } else { <del> if(event.parameters.length != 1){ <del> event.player.sendChatMessage(MythicChatFormatCodes.preFormatError() + "Wrong number of parameters."); <del> } else { <del> String requestFrom = getPlayerString(event.player, "teleport.request.from.username", null); <del> if(requestFrom == null || requestFrom.equalsIgnoreCase("X")){ <del> event.player.sendChatMessage(MythicChatFormatCodes.preFormatError() + "You do not have a pending teleport request."); <del> } else { <del> MythicPlayer requestor = MythicServer.getPlayerByName(requestFrom); <del> if(requestor == null){ <del> clearTeleportRequest(event.player); <del> event.player.sendChatMessage(MythicChatFormatCodes.preFormatError() + "Could not locate player " + requestFrom + "."); <del> } else { <del> String direction = getPlayerString(event.player, "teleport.request.direction", null); <del> if(direction.equalsIgnoreCase("you.to.them")){ <del> clearTeleportRequest(event.player); <del> event.player.teleportToPlayer(requestor); <del> event.player.sendChatMessage(MythicChatFormatCodes.preFormatInfo() + "Teleported to " + requestFrom + "."); <del> requestor.sendChatMessage(MythicChatFormatCodes.preFormatInfo() + event.player.getName() + " has teleported to you."); <del> } else if(direction.equalsIgnoreCase("them.to.you")){ <del> clearTeleportRequest(event.player); <del> requestor.teleportToPlayer(event.player); <del> event.player.sendChatMessage(MythicChatFormatCodes.preFormatInfo() + requestor.getName() + " has teleported to you."); <del> requestor.sendChatMessage(MythicChatFormatCodes.preFormatInfo() + "Teleported to " + event.player.getName() + "."); <del> } else { <del> clearTeleportRequest(event.player); <del> event.player.sendChatMessage(MythicChatFormatCodes.preFormatError() + "Could not complete teleport request safely."); <del> } <del> } <del> } <del> } <del> } <del> } <del> <del> private void clearTeleportRequest(MythicPlayer recipient){ <del> setPlayerString(recipient, "teleport.request.from.username", "X"); <del> } <del> <del> private void onCommandTpaHere(MythicEventCommand event) { <del> if(event.player == null){ <del> MythicLogger.info("Only a player can use this command."); <del> } else { <del> if(event.parameters.length != 2){ <del> event.player.sendChatMessage(MythicChatFormatCodes.preFormatError() + "Wrong number of parameters."); <del> } else { <del> String targetUsername = event.parameters[1]; <del> targetUsername = MythicServer.getMatchingPlayerName(targetUsername); <del> if(targetUsername == null || targetUsername.equalsIgnoreCase("X")){ <del> event.player.sendChatMessage(MythicChatFormatCodes.preFormatError() + "Could not find a player matching " + event.parameters[1] + "."); <del> } else { <del> MythicPlayer target = MythicServer.getPlayerByName(targetUsername); <del> target.sendChatMessage(MythicChatFormatCodes.preFormatInfo() + event.player.getName() + " would like to teleport you to them."); <del> target.sendChatMessage(MythicChatFormatCodes.preFormatInfo() + "Type " + MythicChatFormatCodes.lightgreen + "/tpaccept " + MythicChatFormatCodes.gold + "to go to them, or " + MythicChatFormatCodes.lightred + "/tpdeny " + MythicChatFormatCodes.gold + "to refuse."); <del> event.player.sendChatMessage(MythicChatFormatCodes.preFormatInfo() + "Sent teleport request to " + targetUsername + "."); <del> setPlayerString(target, "teleport.request.from.username", event.player.getName()); <del> setPlayerString(target, "teleport.request.direction", "you.to.them"); <del> } <del> } <del> } <del> } <del> <del> private void onCommandTpa(MythicEventCommand event) { <del> if(event.player == null){ <del> MythicLogger.info("Only a player can use this command."); <del> } else { <del> if(event.parameters.length != 2){ <del> event.player.sendChatMessage(MythicChatFormatCodes.preFormatError() + "Wrong number of parameters."); <del> } else { <del> String targetUsername = event.parameters[1]; <del> targetUsername = MythicServer.getMatchingPlayerName(targetUsername); <del> if(targetUsername == null || targetUsername.equalsIgnoreCase("X")){ <del> event.player.sendChatMessage(MythicChatFormatCodes.preFormatError() + "Could not find a player matching " + event.parameters[1] + "."); <del> } else { <del> MythicPlayer target = MythicServer.getPlayerByName(targetUsername); <del> target.sendChatMessage(MythicChatFormatCodes.preFormatInfo() + event.player.getName() + " would like to teleport to you."); <del> target.sendChatMessage(MythicChatFormatCodes.preFormatInfo() + "Type " + MythicChatFormatCodes.lightgreen + "/tpaccept " + MythicChatFormatCodes.gold + "to bring them here, or " + MythicChatFormatCodes.lightred + "/tpdeny " + MythicChatFormatCodes.gold + "to refuse."); <del> event.player.sendChatMessage(MythicChatFormatCodes.preFormatInfo() + "Sent teleport request to " + targetUsername + "."); <del> setPlayerString(target, "teleport.request.from.username", event.player.getName()); <del> setPlayerString(target, "teleport.request.direction", "them.to.you"); <del> } <del> } <del> } <del> } <del> <del> private void onCommandDelWarp(MythicEventCommand event) { <del> if(event.player == null){ <del> MythicLogger.info("Only a player can use this command."); <del> } else { <del> event.player.sendChatMessage(MythicChatFormatCodes.preFormatError() + "This command is not available yet."); <del> } <del> } <del> <del> private void onCommandSetWarp(MythicEventCommand event) { <del> if(event.player == null){ <del> MythicLogger.info("Only a player can use this command."); <del> } else { <del> event.player.sendChatMessage(MythicChatFormatCodes.preFormatError() + "This command is not available yet."); <del> } <del> } <del> <del> private void onCommandWarp(MythicEventCommand event) { <del> if(event.player == null){ <del> MythicLogger.info("Only a player can use this command."); <del> } else { <del> event.player.sendChatMessage(MythicChatFormatCodes.preFormatError() + "This command is not available yet."); <del> } <del> } <del> <del> private void onCommandSetHome(MythicEventCommand event) { <del> if(event.player == null){ <del> MythicLogger.info("Only a player can use this command."); <del> } else { <del> if(event.parameters.length > 1){ <del> event.player.sendChatMessage(MythicChatFormatCodes.preFormatError() + "Too many parameters."); <del> } else { <del> setPlayerInt(event.player, "home.dimension", event.player.getDimension()); <del> setPlayerFloat(event.player, "home.x", (float) event.player.getX()); <del> setPlayerFloat(event.player, "home.y", (float) event.player.getY()); <del> setPlayerFloat(event.player, "home.z", (float) event.player.getZ()); <del> event.player.sendChatMessage(MythicChatFormatCodes.preFormatInfo() + "Home set."); <del> } <del> } <del> } <del> <del> private void onCommandHome(MythicEventCommand event) { <del> if(event.player == null){ <del> MythicLogger.info("Only a player can use this command."); <del> } else { <del> if(event.parameters.length > 1){ <del> event.player.sendChatMessage(MythicChatFormatCodes.preFormatError() + "Too many parameters."); <del> } else { <del> int dimId = getPlayerInt(event.player, "home.dimension", 999); <del> if(dimId == 999){ <del> event.player.sendChatMessage(MythicChatFormatCodes.preFormatError() + "You do not have a home set."); <del> } else { <del> if(event.player.getDimension() != dimId) event.player.travelToDimension(dimId); <del> double x = getPlayerFloat(event.player, "home.x", (float) event.player.getX()); <del> double y = getPlayerFloat(event.player, "home.y", (float) event.player.getY()); <del> double z = getPlayerFloat(event.player, "home.z", (float) event.player.getZ()); <del> event.player.setPosition(x, y, z); <del> event.player.sendChatMessage(MythicChatFormatCodes.preFormatInfo() + "Teleported home."); <del> } <del> } <del> } <del> } <del> <del> private void onCommandSpawn(MythicEventCommand event) { <del> if(event.parameters.length > 1){ <del> if(event.parameters.length == 2){ <del> <del> } else { <del> if(event.player == null){ <del> MythicLogger.info("Too many parameters."); <del> return; <del> } else { <del> event.player.sendChatMessage(MythicChatFormatCodes.preFormatError() + "Too many parameters."); <del> } <del> } <del> } else { <del> if(event.player == null){ <del> MythicLogger.info("Only a player is can execute the self-targeted variant of this command."); <del> return; <del> } else { <del> if(event.player.getDimension() != 0) event.player.travelToDimension(0); <del> event.player.setPosition(164.5D, 73.5D, 41.5D); <del> event.player.sendChatMessage(MythicChatFormatCodes.preFormatInfo() + "Teleported to spawn."); <del> } <del> } <del> } <del> private void setPlayerString(MythicPlayer player, String dataName, String value){ <del> Mythic.getDatabase().setPlayerString(dbPrefix, dataName, player.getUUIDString(), value); <del> } <del> private void setPlayerFloat(MythicPlayer player, String dataName, float value){ <del> Mythic.getDatabase().setPlayerFloat(dbPrefix, dataName, player.getUUIDString(), value); <del> } <del> private void setPlayerInt(MythicPlayer player, String dataName, int value){ <del> Mythic.getDatabase().setPlayerInt(dbPrefix, dataName, player.getUUIDString(), value); <del> } <del> private String getPlayerString(MythicPlayer player, String dataName, String defaultVal){ <del> return Mythic.getDatabase().getPlayerString(dbPrefix, dataName, player.getUUIDString(), defaultVal); <del> } <del> private float getPlayerFloat(MythicPlayer player, String dataName, float defaultVal){ <del> return Mythic.getDatabase().getPlayerFloat(dbPrefix, dataName, player.getUUIDString(), defaultVal); <del> } <del> private int getPlayerInt(MythicPlayer player, String dataName, int defaultVal){ <del> return Mythic.getDatabase().getPlayerInt(dbPrefix, dataName, player.getUUIDString(), defaultVal); <del> } <del>}
Java
apache-2.0
59cfa777de9aa92037b4d80a147a89f4ea5e99f2
0
tonellotto/nibiru,edwardcapriolo/nibiru
package io.teknek.nibiru; import java.util.List; import io.teknek.nibiru.personality.ColumnFamilyPersonality; import io.teknek.nibiru.personality.KeyValuePersonality; import io.teknek.nibiru.transport.Message; import io.teknek.nibiru.transport.Response; public class Coordinator { private static final String SYSTEM_KEYSPACE = "system"; private final Server server; private Destination destinationLocal; public Coordinator(Server server){ this.server = server; } public void init(){ destinationLocal = new Destination(); destinationLocal.setDestinationId(server.getServerId().getU().toString()); } public Response handle(Message message) { if (SYSTEM_KEYSPACE.equals(message.getKeyspace())) { return null; } Keyspace keyspace = server.getKeyspaces().get(message.getKeyspace()); if (keyspace == null){ throw new RuntimeException(message.getKeyspace() + " is not found"); } ColumnFamily columnFamily = keyspace.getColumnFamilies().get(message.getColumnFamily()); if (columnFamily == null){ throw new RuntimeException(message.getColumnFamily() + " is not found"); } List<Destination> destinations = keyspace.getKeyspaceMetadata().getRouter() .routesTo(message, server.getServerId(), keyspace); long timeoutInMs = determineTimeout(columnFamily, message); if (destinations.contains(destinationLocal)) { if (ColumnFamilyPersonality.COLUMN_FAMILY_PERSONALITY.equals(message.getRequestPersonality())) { return handleColumnFamilyPersonality(message, keyspace, columnFamily); } else if (KeyValuePersonality.KEY_VALUE_PERSONALITY.equals(message.getRequestPersonality())) { return handleKeyValuePersonality(message, keyspace, columnFamily); } else { throw new UnsupportedOperationException(message.getRequestPersonality()); } } else { throw new UnsupportedOperationException("We can not route messages. Yet!"); } } private static long determineTimeout(ColumnFamily columnFamily, Message message){ if (message.getPayload().containsKey("timeout")){ return ((Number) message.getPayload().get("timeout")).longValue(); } else { return columnFamily.getColumnFamilyMetadata().getOperationTimeoutInMs(); } } private Response handleKeyValuePersonality(Message message, Keyspace ks, ColumnFamily cf){ if (cf instanceof KeyValuePersonality){ KeyValuePersonality personality = (KeyValuePersonality) cf; if (message.getPayload().get("type").equals("get")){ String s = personality.get((String) message.getPayload().get("key")); Response r = new Response(); r.put("payload", s); return r; } else if (message.getPayload().get("type").equals("put")){ personality.put((String) message.getPayload().get("key"), (String) message.getPayload().get("value")); return new Response(); } else { throw new RuntimeException("Does not support this type of message"); } } return null; } private Response handleColumnFamilyPersonality(Message message, Keyspace ks, ColumnFamily cf){ if (cf instanceof ColumnFamilyPersonality){ ColumnFamilyPersonality personality = (ColumnFamilyPersonality) cf; if (message.getPayload().get("type").equals("get")){ Val v = personality.get( (String)message.getPayload().get("rowkey"), (String) message.getPayload().get("column")); Response r = new Response(); r.put("payload", v); return r; } else if (message.getPayload().get("type").equals("put")) { Long l = ((Long) message.getPayload().get("ttl")); if (l == null){ personality.put( (String) message.getPayload().get("rowkey"), (String) message.getPayload().get("column"), (String) message.getPayload().get("value"), ((Number) message.getPayload().get("time")).longValue()); return new Response(); } else { personality.put( (String) message.getPayload().get("rowkey"), (String) message.getPayload().get("column"), (String) message.getPayload().get("value"), ((Number) message.getPayload().get("time")).longValue(), l); return new Response(); } } else if (message.getPayload().get("type").equals("delete")) { personality.delete( (String) message.getPayload().get("rowkey"), (String) message.getPayload().get("column"), ((Number) message.getPayload().get("time")).longValue()); return new Response(); } else { throw new RuntimeException("Does not support this type of message"); } } else { throw new RuntimeException("Does not support this personality"); } } }
src/main/java/io/teknek/nibiru/Coordinator.java
package io.teknek.nibiru; import java.util.List; import io.teknek.nibiru.personality.ColumnFamilyPersonality; import io.teknek.nibiru.personality.KeyValuePersonality; import io.teknek.nibiru.transport.Message; import io.teknek.nibiru.transport.Response; public class Coordinator { private static final String SYSTEM_KEYSPACE = "system"; private final Server server; private Destination destinationLocal; public Coordinator(Server server){ this.server = server; } public void init(){ destinationLocal = new Destination(); destinationLocal.setDestinationId(server.getServerId().getU().toString()); } public Response handle(Message message) { if (SYSTEM_KEYSPACE.equals(message.getKeyspace())) { return null; } Keyspace keyspace = server.getKeyspaces().get(message.getKeyspace()); ColumnFamily columnFamily = keyspace.getColumnFamilies().get(message.getColumnFamily()); List<Destination> destinations = keyspace.getKeyspaceMetadata().getRouter() .routesTo(message, server.getServerId(), keyspace); long timeoutInMs = determineTimeout(columnFamily, message); Keyspace ks = server.getKeyspaces().get(message.getKeyspace()); if (ks == null){ throw new RuntimeException(message.getKeyspace() + " is not found"); } ColumnFamily cf = ks.getColumnFamilies().get(message.getColumnFamily()); if (cf == null){ throw new RuntimeException(message.getColumnFamily() + " is not found"); } if (destinations.contains(destinationLocal)) { if (ColumnFamilyPersonality.COLUMN_FAMILY_PERSONALITY.equals(message.getRequestPersonality())) { return handleColumnFamilyPersonality(message, keyspace, columnFamily); } else if (KeyValuePersonality.KEY_VALUE_PERSONALITY.equals(message.getRequestPersonality())) { return handleKeyValuePersonality(message, keyspace, columnFamily); } else { throw new UnsupportedOperationException(message.getRequestPersonality()); } } else { throw new UnsupportedOperationException("We can not route messages. Yet!"); } } private static long determineTimeout(ColumnFamily columnFamily, Message message){ if (message.getPayload().containsKey("timeout")){ return ((Number) message.getPayload().get("timeout")).longValue(); } else { return columnFamily.getColumnFamilyMetadata().getOperationTimeoutInMs(); } } private Response handleKeyValuePersonality(Message message, Keyspace ks, ColumnFamily cf){ if (cf instanceof KeyValuePersonality){ KeyValuePersonality personality = (KeyValuePersonality) cf; if (message.getPayload().get("type").equals("get")){ String s = personality.get((String) message.getPayload().get("key")); Response r = new Response(); r.put("payload", s); return r; } else if (message.getPayload().get("type").equals("put")){ personality.put((String) message.getPayload().get("key"), (String) message.getPayload().get("value")); return new Response(); } else { throw new RuntimeException("Does not support this type of message"); } } return null; } private Response handleColumnFamilyPersonality(Message message, Keyspace ks, ColumnFamily cf){ if (cf instanceof ColumnFamilyPersonality){ ColumnFamilyPersonality personality = (ColumnFamilyPersonality) cf; if (message.getPayload().get("type").equals("get")){ Val v = personality.get( (String)message.getPayload().get("rowkey"), (String) message.getPayload().get("column")); Response r = new Response(); r.put("payload", v); return r; } else if (message.getPayload().get("type").equals("put")) { Long l = ((Long) message.getPayload().get("ttl")); if (l == null){ personality.put( (String) message.getPayload().get("rowkey"), (String) message.getPayload().get("column"), (String) message.getPayload().get("value"), ((Number) message.getPayload().get("time")).longValue()); return new Response(); } else { personality.put( (String) message.getPayload().get("rowkey"), (String) message.getPayload().get("column"), (String) message.getPayload().get("value"), ((Number) message.getPayload().get("time")).longValue(), l); return new Response(); } } else if (message.getPayload().get("type").equals("delete")) { personality.delete( (String) message.getPayload().get("rowkey"), (String) message.getPayload().get("column"), ((Number) message.getPayload().get("time")).longValue()); return new Response(); } else { throw new RuntimeException("Does not support this type of message"); } } else { throw new RuntimeException("Does not support this personality"); } } }
Remove redundant code
src/main/java/io/teknek/nibiru/Coordinator.java
Remove redundant code
<ide><path>rc/main/java/io/teknek/nibiru/Coordinator.java <ide> if (SYSTEM_KEYSPACE.equals(message.getKeyspace())) { <ide> return null; <ide> } <add> <ide> Keyspace keyspace = server.getKeyspaces().get(message.getKeyspace()); <add> if (keyspace == null){ <add> throw new RuntimeException(message.getKeyspace() + " is not found"); <add> } <ide> ColumnFamily columnFamily = keyspace.getColumnFamilies().get(message.getColumnFamily()); <add> if (columnFamily == null){ <add> throw new RuntimeException(message.getColumnFamily() + " is not found"); <add> } <ide> List<Destination> destinations = keyspace.getKeyspaceMetadata().getRouter() <ide> .routesTo(message, server.getServerId(), keyspace); <ide> long timeoutInMs = determineTimeout(columnFamily, message); <del> Keyspace ks = server.getKeyspaces().get(message.getKeyspace()); <del> if (ks == null){ <del> throw new RuntimeException(message.getKeyspace() + " is not found"); <del> } <del> ColumnFamily cf = ks.getColumnFamilies().get(message.getColumnFamily()); <del> if (cf == null){ <del> throw new RuntimeException(message.getColumnFamily() + " is not found"); <del> } <ide> if (destinations.contains(destinationLocal)) { <ide> if (ColumnFamilyPersonality.COLUMN_FAMILY_PERSONALITY.equals(message.getRequestPersonality())) { <ide> return handleColumnFamilyPersonality(message, keyspace, columnFamily);
Java
mit
f4c37b69a15a01bb3b0ead8b00b01536234dd7dd
0
petrs/ECTester,petrs/ECTester,petrs/ECTester
/* * ECTester, tool for testing Elliptic curve cryptography implementations. * Copyright (c) 2016-2018 Petr Svenda <[email protected]> * * 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 cz.crcs.ectester.standalone; import cz.crcs.ectester.common.cli.*; import cz.crcs.ectester.common.ec.EC_Curve; import cz.crcs.ectester.common.output.TestWriter; import cz.crcs.ectester.common.test.TestException; import cz.crcs.ectester.common.util.ByteUtil; import cz.crcs.ectester.common.util.ECUtil; import cz.crcs.ectester.common.util.FileUtil; import cz.crcs.ectester.data.EC_Store; import cz.crcs.ectester.standalone.consts.KeyAgreementIdent; import cz.crcs.ectester.standalone.consts.KeyPairGeneratorIdent; import cz.crcs.ectester.standalone.consts.SignatureIdent; import cz.crcs.ectester.standalone.libs.*; import cz.crcs.ectester.standalone.output.TextTestWriter; import cz.crcs.ectester.standalone.output.XMLTestWriter; import cz.crcs.ectester.standalone.output.YAMLTestWriter; import cz.crcs.ectester.standalone.test.suites.StandaloneDefaultSuite; import cz.crcs.ectester.standalone.test.suites.StandaloneTestSuite; import org.apache.commons.cli.DefaultParser; import org.apache.commons.cli.Option; import org.apache.commons.cli.Options; import org.apache.commons.cli.ParseException; import javax.crypto.KeyAgreement; import javax.crypto.SecretKey; import javax.xml.parsers.ParserConfigurationException; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.io.PrintStream; import java.nio.file.Files; import java.security.*; import java.security.interfaces.ECPrivateKey; import java.security.interfaces.ECPublicKey; import java.security.spec.AlgorithmParameterSpec; import java.security.spec.ECGenParameterSpec; import java.security.spec.ECParameterSpec; import java.util.*; import java.util.stream.Collectors; /** * Standalone part of ECTester, a tool for testing Elliptic curve implementations in software libraries. * * @author Jan Jancar [email protected] * @version v0.3.0 */ public class ECTesterStandalone { private ProviderECLibrary[] libs = new ProviderECLibrary[]{ new SunECLib(), new BouncyCastleLib(), new TomcryptLib(), new BotanLib(), new CryptoppLib(), new OpensslLib(), new BoringsslLib(), new GcryptLib(), new MscngLib(), new WolfCryptLib()}; private Config cfg; private Options opts = new Options(); private TreeParser optParser; private TreeCommandLine cli; public static final String VERSION = "v0.3.0"; private static final String DESCRIPTION = "ECTesterStandalone " + VERSION + ", an Elliptic Curve Cryptography support tester/utility."; private static final String LICENSE = "MIT Licensed\nCopyright (c) 2016-2018 Petr Svenda <[email protected]>"; private static final String CLI_HEADER = "\n" + DESCRIPTION + "\n\n"; private static final String CLI_FOOTER = "\n" + LICENSE; private void run(String[] args) { try { cli = parseArgs(args); if (cli.hasOption("version")) { CLITools.version(DESCRIPTION, LICENSE); return; } else if (cli.hasOption("help") || cli.getNext() == null) { String command = cli.getOptionValue("help"); if (command == null) { CLITools.help("ECTesterStandalone.jar", CLI_HEADER, opts, optParser, CLI_FOOTER, true); } else { CLITools.help(CLI_HEADER, optParser, CLI_FOOTER, command); } return; } for (ECLibrary lib : libs) { lib.initialize(); } cfg = new Config(libs); if (!cfg.readOptions(cli)) { return; } if (cli.isNext("list-libs")) { listLibraries(); } else if (cli.isNext("list-data")) { CLITools.listNamed(EC_Store.getInstance(), cli.getNext().getArg(0)); } else if (cli.isNext("list-suites")) { listSuites(); } else if (cli.isNext("ecdh")) { ecdh(); } else if (cli.isNext("ecdsa")) { ecdsa(); } else if (cli.isNext("generate")) { generate(); } else if (cli.isNext("test")) { test(); } else if (cli.isNext("export")) { export(); } } catch (ParseException | ParserConfigurationException | IOException ex) { System.err.println(ex.getMessage()); } catch (InvalidAlgorithmParameterException | InvalidParameterException e) { System.err.println("Invalid algorithm parameter: " + e.getMessage()); } catch (NoSuchAlgorithmException nsaex) { System.err.println("Algorithm not supported by the selected library: " + nsaex.getMessage()); nsaex.printStackTrace(); } catch (InvalidKeyException | SignatureException e) { e.printStackTrace(); } } private TreeCommandLine parseArgs(String[] args) throws ParseException { Map<String, ParserOptions> actions = new TreeMap<>(); Option namedCurve = Option.builder("nc").longOpt("named-curve").desc("Use a named curve, from CurveDB: <cat/id>").hasArg().argName("cat/id").optionalArg(false).build(); Option curveName = Option.builder("cn").longOpt("curve-name").desc("Use a named curve, search from curves supported by the library: <name>").hasArg().argName("name").optionalArg(false).build(); Option bits = Option.builder("b").longOpt("bits").hasArg().argName("n").optionalArg(false).desc("What size of curve to use.").build(); Option output = Option.builder("o").longOpt("output").desc("Output into file <output_file>.").hasArgs().argName("output_file").optionalArg(false).build(); Options testOpts = new Options(); testOpts.addOption(bits); testOpts.addOption(namedCurve); testOpts.addOption(curveName); testOpts.addOption(Option.builder("gt").longOpt("kpg-type").desc("Set the KeyPairGenerator object [type].").hasArg().argName("type").optionalArg(false).build()); testOpts.addOption(Option.builder("kt").longOpt("ka-type").desc("Set the KeyAgreement object [type].").hasArg().argName("type").optionalArg(false).build()); testOpts.addOption(Option.builder("st").longOpt("sig-type").desc("Set the Signature object [type].").hasArg().argName("type").optionalArg(false).build()); testOpts.addOption(Option.builder("f").longOpt("format").desc("Set the output format, one of text,yaml,xml.").hasArg().argName("format").optionalArg(false).build()); testOpts.addOption(Option.builder().longOpt("key-type").desc("Set the key [algorithm] for which the key should be derived in KeyAgreements with KDF. Default is \"AES\".").hasArg().argName("algorithm").optionalArg(false).build()); List<Argument> testArgs = new LinkedList<>(); testArgs.add(new Argument("test-suite", "The test suite to run.", true)); ParserOptions test = new ParserOptions(new TreeParser(Collections.emptyMap(), true, testArgs), testOpts, "Test a library."); actions.put("test", test); Options ecdhOpts = new Options(); ecdhOpts.addOption(bits); ecdhOpts.addOption(namedCurve); ecdhOpts.addOption(curveName); ecdhOpts.addOption(output); ecdhOpts.addOption(Option.builder("t").longOpt("type").desc("Set KeyAgreement object [type].").hasArg().argName("type").optionalArg(false).build()); ecdhOpts.addOption(Option.builder().longOpt("key-type").desc("Set the key [algorithm] for which the key should be derived in KeyAgreements with KDF. Default is \"AES\".").hasArg().argName("algorithm").optionalArg(false).build()); ecdhOpts.addOption(Option.builder("n").longOpt("amount").hasArg().argName("amount").optionalArg(false).desc("Do ECDH [amount] times.").build()); ecdhOpts.addOption(Option.builder().longOpt("fixed-private").desc("Perform ECDH with fixed private key.").build()); ecdhOpts.addOption(Option.builder().longOpt("fixed-public").desc("Perform ECDH with fixed public key.").build()); ParserOptions ecdh = new ParserOptions(new DefaultParser(), ecdhOpts, "Perform EC based KeyAgreement."); actions.put("ecdh", ecdh); Options ecdsaOpts = new Options(); ecdsaOpts.addOption(bits); ecdsaOpts.addOption(namedCurve); ecdsaOpts.addOption(curveName); ecdhOpts.addOption(output); ecdsaOpts.addOption(Option.builder("t").longOpt("type").desc("Set Signature object [type].").hasArg().argName("type").optionalArg(false).build()); ecdsaOpts.addOption(Option.builder("n").longOpt("amount").hasArg().argName("amount").optionalArg(false).desc("Do ECDSA [amount] times.").build()); ecdsaOpts.addOption(Option.builder("f").longOpt("file").hasArg().argName("file").optionalArg(false).desc("Input [file] to sign.").build()); ParserOptions ecdsa = new ParserOptions(new DefaultParser(), ecdsaOpts, "Perform EC based Signature."); actions.put("ecdsa", ecdsa); Options generateOpts = new Options(); generateOpts.addOption(bits); generateOpts.addOption(namedCurve); generateOpts.addOption(curveName); ecdhOpts.addOption(output); generateOpts.addOption(Option.builder("n").longOpt("amount").hasArg().argName("amount").optionalArg(false).desc("Generate [amount] of EC keys.").build()); generateOpts.addOption(Option.builder("t").longOpt("type").hasArg().argName("type").optionalArg(false).desc("Set KeyPairGenerator object [type].").build()); ParserOptions generate = new ParserOptions(new DefaultParser(), generateOpts, "Generate EC keypairs."); actions.put("generate", generate); Options exportOpts = new Options(); exportOpts.addOption(bits); ecdhOpts.addOption(output); exportOpts.addOption(Option.builder("t").longOpt("type").hasArg().argName("type").optionalArg(false).desc("Set KeyPair object [type].").build()); ParserOptions export = new ParserOptions(new DefaultParser(), exportOpts, "Export default curve parameters."); actions.put("export", export); Options listDataOpts = new Options(); List<Argument> listDataArgs = new LinkedList<>(); listDataArgs.add(new Argument("what", "what to list.", false)); ParserOptions listData = new ParserOptions(new TreeParser(Collections.emptyMap(), false, listDataArgs), listDataOpts, "List/show contained EC domain parameters/keys."); actions.put("list-data", listData); Options listLibsOpts = new Options(); ParserOptions listLibs = new ParserOptions(new DefaultParser(), listLibsOpts, "List supported libraries."); actions.put("list-libs", listLibs); Options listSuitesOpts = new Options(); ParserOptions listSuites = new ParserOptions(new DefaultParser(), listSuitesOpts, "List supported test suites."); actions.put("list-suites", listSuites); List<Argument> baseArgs = new LinkedList<>(); baseArgs.add(new Argument("lib", "What library to use.", false)); optParser = new TreeParser(actions, false, baseArgs); opts.addOption(Option.builder("V").longOpt("version").desc("Print version info.").build()); opts.addOption(Option.builder("h").longOpt("help").desc("Print help(about <command>).").hasArg().argName("command").optionalArg(true).build()); opts.addOption(Option.builder("C").longOpt("color").desc("Print stuff with color, requires ANSI terminal.").build()); return optParser.parse(opts, args); } /** * */ private void listLibraries() { for (ProviderECLibrary lib : libs) { if (lib.isInitialized() && (cfg.selected == null || lib == cfg.selected)) { System.out.println("\t- " + Colors.bold(lib.name())); System.out.println(Colors.bold("\t\t- Supports native timing: ") + lib.supportsNativeTiming()); Set<KeyPairGeneratorIdent> kpgs = lib.getKPGs(); if (!kpgs.isEmpty()) { System.out.println(Colors.bold("\t\t- KeyPairGenerators: ") + String.join(", ", kpgs.stream().map(KeyPairGeneratorIdent::getName).collect(Collectors.toList()))); } Set<KeyAgreementIdent> eckas = lib.getKAs(); if (!eckas.isEmpty()) { System.out.println(Colors.bold("\t\t- KeyAgreements: ") + String.join(", ", eckas.stream().map(KeyAgreementIdent::getName).collect(Collectors.toList()))); } Set<SignatureIdent> sigs = lib.getSigs(); if (!sigs.isEmpty()) { System.out.println(Colors.bold("\t\t- Signatures: ") + String.join(", ", sigs.stream().map(SignatureIdent::getName).collect(Collectors.toList()))); } Set<String> curves = lib.getCurves(); if (!curves.isEmpty()) { System.out.println(Colors.bold("\t\t- Curves: ") + String.join(", ", curves)); } System.out.println(); } } } /** * */ private void listSuites() { StandaloneTestSuite[] suites = new StandaloneTestSuite[]{new StandaloneDefaultSuite(null, null, null)}; for (StandaloneTestSuite suite : suites) { System.out.println(" - " + suite.getName()); for (String line : suite.getDescription()) { System.out.println("\t" + line); } } } /** * */ private void ecdh() throws NoSuchAlgorithmException, InvalidAlgorithmParameterException, InvalidKeyException, FileNotFoundException { ProviderECLibrary lib = cfg.selected; String algo = cli.getOptionValue("ecdh.type", "ECDH"); String keyAlgo = cli.getOptionValue("ecdh.key-type", "AES"); KeyAgreementIdent kaIdent = lib.getKAs().stream() .filter((ident) -> ident.contains(algo)) .findFirst() .orElse(null); String baseAlgo; if (algo.contains("with")) { baseAlgo = algo.split("with")[0]; } else { baseAlgo = algo; } KeyPairGeneratorIdent kpIdent = lib.getKPGs().stream() .filter((ident) -> ident.contains(algo)) .findFirst() .orElse(lib.getKPGs().stream() .filter((ident) -> ident.contains(baseAlgo)) .findFirst() .orElse(lib.getKPGs().stream() .filter((ident) -> ident.contains("ECDH")) .findFirst() .orElse(lib.getKPGs().stream() .filter((ident) -> ident.contains("EC")) .findFirst() .orElse(null)))); if (kaIdent == null || kpIdent == null) { throw new NoSuchAlgorithmException(algo); } KeyAgreement ka = kaIdent.getInstance(lib.getProvider()); KeyPairGenerator kpg = kpIdent.getInstance(lib.getProvider()); AlgorithmParameterSpec spec = null; if (cli.hasOption("ecdh.bits")) { int bits = Integer.parseInt(cli.getOptionValue("ecdh.bits")); kpg.initialize(bits); } else if (cli.hasOption("ecdh.named-curve")) { String curveName = cli.getOptionValue("ecdh.named-curve"); EC_Curve curve = EC_Store.getInstance().getObject(EC_Curve.class, curveName); if (curve == null) { System.err.println("Curve not found: " + curveName); return; } spec = curve.toSpec(); kpg.initialize(spec); } else if (cli.hasOption("ecdh.curve-name")) { String curveName = cli.getOptionValue("ecdh.curve-name"); spec = new ECGenParameterSpec(curveName); kpg.initialize(spec); } PrintStream out; if (cli.hasOption("ecdh.output")) { out = new PrintStream(FileUtil.openStream(cli.getOptionValues("ecdh.output"))); } else { out = System.out; } out.println("index;time[nano];pubW;privS;secret"); KeyPair one = null; if (cli.hasOption("ecdh.fixed-private")) { one = kpg.genKeyPair(); } KeyPair other = null; if (cli.hasOption("ecdh.fixed-public")) { other = kpg.genKeyPair(); } int amount = Integer.parseInt(cli.getOptionValue("ecdh.amount", "1")); for (int i = 0; i < amount; ++i) { if (!cli.hasOption("ecdh.fixed-private")) { one = kpg.genKeyPair(); } if (!cli.hasOption("ecdh.fixed-public")) { other = kpg.genKeyPair(); } ECPrivateKey privkey = (ECPrivateKey) one.getPrivate(); ECPublicKey pubkey = (ECPublicKey) other.getPublic(); long elapsed = -System.nanoTime(); if (spec instanceof ECParameterSpec) { ka.init(privkey, spec); } else { ka.init(privkey); } ka.doPhase(pubkey, true); elapsed += System.nanoTime(); SecretKey derived; byte[] result; elapsed -= System.nanoTime(); if (kaIdent.requiresKeyAlgo()) { derived = ka.generateSecret(keyAlgo); result = derived.getEncoded(); } else { result = ka.generateSecret(); } elapsed += System.nanoTime(); if (lib.supportsNativeTiming()) { elapsed = lib.getLastNativeTiming(); } ka = kaIdent.getInstance(lib.getProvider()); String pub = ByteUtil.bytesToHex(ECUtil.toX962Uncompressed(pubkey.getW(), pubkey.getParams()), false); String priv = ByteUtil.bytesToHex(privkey.getS().toByteArray(), false); String dh = ByteUtil.bytesToHex(result, false); out.println(String.format("%d;%d;%s;%s;%s", i, elapsed, pub, priv, dh)); } if (cli.hasOption("ecdh.output")) { out.close(); } } /** * */ private void ecdsa() throws NoSuchAlgorithmException, InvalidAlgorithmParameterException, InvalidKeyException, IOException, SignatureException { byte[] data; String dataString; if (cli.hasOption("ecdsa.file")) { String fileName = cli.getOptionValue("ecdsa.file"); File in = new File(fileName); long len = in.length(); if (len == 0) { throw new FileNotFoundException(fileName); } data = Files.readAllBytes(in.toPath()); dataString = ""; } else { SecureRandom random = new SecureRandom(); data = new byte[32]; random.nextBytes(data); dataString = ByteUtil.bytesToHex(data, false); } ProviderECLibrary lib = cfg.selected; String algo = cli.getOptionValue("ecdsa.type", "ECDSA"); SignatureIdent sigIdent = lib.getSigs().stream() .filter((ident) -> ident.contains(algo)) .findFirst() .orElse(null); String baseAlgo; if (algo.contains("with")) { baseAlgo = algo.split("with")[1]; } else { baseAlgo = algo; } KeyPairGeneratorIdent kpIdent = lib.getKPGs().stream() .filter((ident) -> ident.contains(algo)) .findFirst() .orElse(lib.getKPGs().stream() .filter((ident) -> ident.contains(baseAlgo)) .findFirst() .orElse(lib.getKPGs().stream() .filter((ident) -> ident.contains("ECDSA")) .findFirst() .orElse(lib.getKPGs().stream() .filter((ident) -> ident.contains("EC")) .findFirst() .orElse(null)))); if (sigIdent == null || kpIdent == null) { throw new NoSuchAlgorithmException(algo); } Signature sig = sigIdent.getInstance(lib.getProvider()); KeyPairGenerator kpg = kpIdent.getInstance(lib.getProvider()); if (cli.hasOption("ecdsa.bits")) { int bits = Integer.parseInt(cli.getOptionValue("ecdsa.bits")); kpg.initialize(bits); } else if (cli.hasOption("ecdsa.named-curve")) { String curveName = cli.getOptionValue("ecdsa.named-curve"); EC_Curve curve = EC_Store.getInstance().getObject(EC_Curve.class, curveName); if (curve == null) { System.err.println("Curve not found: " + curveName); return; } kpg.initialize(curve.toSpec()); } else if (cli.hasOption("ecdsa.curve-name")) { String curveName = cli.getOptionValue("ecdsa.curve-name"); kpg.initialize(new ECGenParameterSpec(curveName)); } PrintStream out; if (cli.hasOption("ecdsa.output")) { out = new PrintStream(FileUtil.openStream(cli.getOptionValues("ecdh.output"))); } else { out = System.out; } out.println("index;data;signTime[nano];verifyTime[nano];pubW;privS;signature;verified"); int amount = Integer.parseInt(cli.getOptionValue("ecdsa.amount", "1")); for (int i = 0; i < amount; ++i) { KeyPair one = kpg.genKeyPair(); ECPrivateKey privkey = (ECPrivateKey) one.getPrivate(); ECPublicKey pubkey = (ECPublicKey) one.getPublic(); sig.initSign(privkey); sig.update(data); long signTime = -System.nanoTime(); byte[] signature = sig.sign(); signTime += System.nanoTime(); if (lib.supportsNativeTiming()) { signTime = lib.getLastNativeTiming(); } sig.initVerify(pubkey); sig.update(data); long verifyTime = -System.nanoTime(); boolean verified = sig.verify(signature); verifyTime += System.nanoTime(); if (lib.supportsNativeTiming()) { verifyTime = lib.getLastNativeTiming(); } String pub = ByteUtil.bytesToHex(ECUtil.toX962Uncompressed(pubkey.getW(), pubkey.getParams()), false); String priv = ByteUtil.bytesToHex(privkey.getS().toByteArray(), false); String sign = ByteUtil.bytesToHex(signature, false); out.println(String.format("%d;%s;%d;%d;%s;%s;%s;%d", i, dataString, signTime, verifyTime, pub, priv, sign, verified ? 1 : 0)); } if (cli.hasOption("ecdsa.output")) { out.close(); } } /** * */ private void generate() throws NoSuchAlgorithmException, InvalidAlgorithmParameterException, FileNotFoundException { ProviderECLibrary lib = cfg.selected; KeyPairGeneratorIdent ident = null; String algo = cli.getOptionValue("generate.type", "EC"); for (KeyPairGeneratorIdent kpIdent : lib.getKPGs()) { if (kpIdent.contains(algo)) { ident = kpIdent; break; } } if (ident == null) { throw new NoSuchAlgorithmException(algo); } KeyPairGenerator kpg = ident.getInstance(lib.getProvider()); if (cli.hasOption("generate.bits")) { int bits = Integer.parseInt(cli.getOptionValue("generate.bits")); kpg.initialize(bits); } else if (cli.hasOption("generate.named-curve")) { String curveName = cli.getOptionValue("generate.named-curve"); EC_Curve curve = EC_Store.getInstance().getObject(EC_Curve.class, curveName); if (curve == null) { System.err.println("Curve not found: " + curveName); return; } kpg.initialize(curve.toSpec()); } else if (cli.hasOption("generate.curve-name")) { String curveName = cli.getOptionValue("generate.curve-name"); kpg.initialize(new ECGenParameterSpec(curveName)); } PrintStream out; if (cli.hasOption("generate.output")) { out = new PrintStream(FileUtil.openStream(cli.getOptionValues("ecdh.output"))); } else { out = System.out; } out.println("index;time[nano];pubW;privS"); int amount = Integer.parseInt(cli.getOptionValue("generate.amount", "1")); for (int i = 0; i < amount || amount == 0; ++i) { long elapsed = -System.nanoTime(); KeyPair kp = kpg.genKeyPair(); elapsed += System.nanoTime(); if (lib.supportsNativeTiming()) { elapsed = lib.getLastNativeTiming(); } ECPublicKey publicKey = (ECPublicKey) kp.getPublic(); ECPrivateKey privateKey = (ECPrivateKey) kp.getPrivate(); String pub = ByteUtil.bytesToHex(ECUtil.toX962Uncompressed(publicKey.getW(), publicKey.getParams()), false); String priv = ByteUtil.bytesToHex(privateKey.getS().toByteArray(), false); out.println(String.format("%d;%d;%s;%s", i, elapsed, pub, priv)); } if (cli.hasOption("generate.output")) { out.close(); } } /** * */ private void test() throws TestException, ParserConfigurationException { TestWriter writer; switch (cli.getOptionValue("test.format", "text").toLowerCase()) { case "yaml": case "yml": writer = new YAMLTestWriter(System.out); break; case "xml": writer = new XMLTestWriter(System.out); break; case "text": default: writer = new TextTestWriter(System.out); break; } String suiteName = cli.getArg(0); StandaloneTestSuite suite = new StandaloneDefaultSuite(writer, cfg, cli); suite.run(); } /** * */ private void export() throws NoSuchAlgorithmException, IOException { ProviderECLibrary lib = cfg.selected; KeyPairGeneratorIdent ident = null; String algo = cli.getOptionValue("export.type", "EC"); for (KeyPairGeneratorIdent kpIdent : lib.getKPGs()) { if (kpIdent.contains(algo)) { ident = kpIdent; break; } } if (ident == null) { throw new NoSuchAlgorithmException(algo); } KeyPairGenerator kpg = ident.getInstance(lib.getProvider()); if (cli.hasOption("export.bits")) { int bits = Integer.parseInt(cli.getOptionValue("export.bits")); kpg.initialize(bits); } KeyPair kp = kpg.genKeyPair(); ECPrivateKey privateKey = (ECPrivateKey) kp.getPrivate(); ECParameterSpec params = privateKey.getParams(); System.out.println(params); EC_Curve curve = EC_Curve.fromSpec(params); curve.writeCSV(System.out); } public static void main(String[] args) { ECTesterStandalone app = new ECTesterStandalone(); app.run(args); } /** * */ public static class Config { private ProviderECLibrary[] libs; public ProviderECLibrary selected = null; public boolean color = false; public Config(ProviderECLibrary[] libs) { this.libs = libs; } boolean readOptions(TreeCommandLine cli) { color = cli.hasOption("color"); Colors.enabled = color; if (cli.isNext("generate") || cli.isNext("export") || cli.isNext("ecdh") || cli.isNext("ecdsa") || cli.isNext("test")) { if (!cli.hasArg(-1)) { System.err.println("Missing library name argument."); return false; } String next = cli.getNextName(); boolean hasBits = cli.hasOption(next + ".bits"); boolean hasNamedCurve = cli.hasOption(next + ".named-curve"); boolean hasCurveName = cli.hasOption(next + ".curve-name"); if (hasBits ^ hasNamedCurve ? hasCurveName : hasBits) { System.err.println("You can only specify bitsize or a named curve/curve name, nor both."); return false; } } if (!cli.isNext("list-data") && !cli.isNext("list-suites")) { String libraryName = cli.getArg(-1); if (libraryName != null) { List<ProviderECLibrary> matchedLibs = new LinkedList<>(); for (ProviderECLibrary lib : libs) { if (lib.isInitialized() && lib.name().toLowerCase().contains(libraryName.toLowerCase())) { matchedLibs.add(lib); } } if (matchedLibs.size() == 0) { System.err.println("No library " + libraryName + " found."); return false; } else if (matchedLibs.size() > 1) { System.err.println("Multiple matching libraries found: " + String.join(",", matchedLibs.stream().map(ECLibrary::name).collect(Collectors.toList()))); return false; } else { selected = matchedLibs.get(0); } } } if (cli.hasOption("test.format")) { String fmt = cli.getOptionValue("test.format"); String formats[] = new String[]{"text", "xml", "yaml", "yml"}; if (!Arrays.asList(formats).contains(fmt.toLowerCase())) { System.err.println("Invalid format specified."); return false; } } return true; } } }
src/cz/crcs/ectester/standalone/ECTesterStandalone.java
/* * ECTester, tool for testing Elliptic curve cryptography implementations. * Copyright (c) 2016-2018 Petr Svenda <[email protected]> * * 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 cz.crcs.ectester.standalone; import cz.crcs.ectester.common.cli.*; import cz.crcs.ectester.common.ec.EC_Curve; import cz.crcs.ectester.common.output.TestWriter; import cz.crcs.ectester.common.test.TestException; import cz.crcs.ectester.common.util.ByteUtil; import cz.crcs.ectester.common.util.ECUtil; import cz.crcs.ectester.common.util.FileUtil; import cz.crcs.ectester.data.EC_Store; import cz.crcs.ectester.standalone.consts.KeyAgreementIdent; import cz.crcs.ectester.standalone.consts.KeyPairGeneratorIdent; import cz.crcs.ectester.standalone.consts.SignatureIdent; import cz.crcs.ectester.standalone.libs.*; import cz.crcs.ectester.standalone.output.TextTestWriter; import cz.crcs.ectester.standalone.output.XMLTestWriter; import cz.crcs.ectester.standalone.output.YAMLTestWriter; import cz.crcs.ectester.standalone.test.suites.StandaloneDefaultSuite; import cz.crcs.ectester.standalone.test.suites.StandaloneTestSuite; import org.apache.commons.cli.DefaultParser; import org.apache.commons.cli.Option; import org.apache.commons.cli.Options; import org.apache.commons.cli.ParseException; import javax.crypto.KeyAgreement; import javax.crypto.SecretKey; import javax.xml.parsers.ParserConfigurationException; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.io.PrintStream; import java.nio.file.Files; import java.security.*; import java.security.interfaces.ECPrivateKey; import java.security.interfaces.ECPublicKey; import java.security.spec.AlgorithmParameterSpec; import java.security.spec.ECGenParameterSpec; import java.security.spec.ECParameterSpec; import java.util.*; import java.util.stream.Collectors; /** * Standalone part of ECTester, a tool for testing Elliptic curve implementations in software libraries. * * @author Jan Jancar [email protected] * @version v0.3.0 */ public class ECTesterStandalone { private ProviderECLibrary[] libs = new ProviderECLibrary[]{ new SunECLib(), new BouncyCastleLib(), new TomcryptLib(), new BotanLib(), new CryptoppLib(), new OpensslLib(), new BoringsslLib(), new GcryptLib(), new MscngLib(), new WolfCryptLib()}; private Config cfg; private Options opts = new Options(); private TreeParser optParser; private TreeCommandLine cli; public static final String VERSION = "v0.3.0"; private static final String DESCRIPTION = "ECTesterStandalone " + VERSION + ", an Elliptic Curve Cryptography support tester/utility."; private static final String LICENSE = "MIT Licensed\nCopyright (c) 2016-2018 Petr Svenda <[email protected]>"; private static final String CLI_HEADER = "\n" + DESCRIPTION + "\n\n"; private static final String CLI_FOOTER = "\n" + LICENSE; private void run(String[] args) { try { cli = parseArgs(args); if (cli.hasOption("version")) { CLITools.version(DESCRIPTION, LICENSE); return; } else if (cli.hasOption("help") || cli.getNext() == null) { String command = cli.getOptionValue("help"); if (command == null) { CLITools.help("ECTesterStandalone.jar", CLI_HEADER, opts, optParser, CLI_FOOTER, true); } else { CLITools.help(CLI_HEADER, optParser, CLI_FOOTER, command); } return; } for (ECLibrary lib : libs) { lib.initialize(); } cfg = new Config(libs); if (!cfg.readOptions(cli)) { return; } if (cli.isNext("list-libs")) { listLibraries(); } else if (cli.isNext("list-data")) { CLITools.listNamed(EC_Store.getInstance(), cli.getNext().getArg(0)); } else if (cli.isNext("list-suites")) { listSuites(); } else if (cli.isNext("ecdh")) { ecdh(); } else if (cli.isNext("ecdsa")) { ecdsa(); } else if (cli.isNext("generate")) { generate(); } else if (cli.isNext("test")) { test(); } else if (cli.isNext("export")) { export(); } } catch (ParseException | ParserConfigurationException | IOException ex) { System.err.println(ex.getMessage()); } catch (InvalidAlgorithmParameterException | InvalidParameterException e) { System.err.println("Invalid algorithm parameter: " + e.getMessage()); } catch (NoSuchAlgorithmException nsaex) { System.err.println("Algorithm not supported by the selected library: " + nsaex.getMessage()); nsaex.printStackTrace(); } catch (InvalidKeyException | SignatureException e) { e.printStackTrace(); } } private TreeCommandLine parseArgs(String[] args) throws ParseException { Map<String, ParserOptions> actions = new TreeMap<>(); Option namedCurve = Option.builder("nc").longOpt("named-curve").desc("Use a named curve, from CurveDB: <cat/id>").hasArg().argName("cat/id").optionalArg(false).build(); Option curveName = Option.builder("cn").longOpt("curve-name").desc("Use a named curve, search from curves supported by the library: <name>").hasArg().argName("name").optionalArg(false).build(); Option bits = Option.builder("b").longOpt("bits").hasArg().argName("n").optionalArg(false).desc("What size of curve to use.").build(); Option output = Option.builder("o").longOpt("output").desc("Output into file <output_file>.").hasArgs().argName("output_file").optionalArg(false).build(); Options testOpts = new Options(); testOpts.addOption(bits); testOpts.addOption(namedCurve); testOpts.addOption(curveName); testOpts.addOption(Option.builder("gt").longOpt("kpg-type").desc("Set the KeyPairGenerator object [type].").hasArg().argName("type").optionalArg(false).build()); testOpts.addOption(Option.builder("kt").longOpt("ka-type").desc("Set the KeyAgreement object [type].").hasArg().argName("type").optionalArg(false).build()); testOpts.addOption(Option.builder("st").longOpt("sig-type").desc("Set the Signature object [type].").hasArg().argName("type").optionalArg(false).build()); testOpts.addOption(Option.builder("f").longOpt("format").desc("Set the output format, one of text,yaml,xml.").hasArg().argName("format").optionalArg(false).build()); testOpts.addOption(Option.builder().longOpt("key-type").desc("Set the key [algorithm] for which the key should be derived in KeyAgreements with KDF. Default is \"AES\".").hasArg().argName("algorithm").optionalArg(false).build()); List<Argument> testArgs = new LinkedList<>(); testArgs.add(new Argument("test-suite", "The test suite to run.", true)); ParserOptions test = new ParserOptions(new TreeParser(Collections.emptyMap(), true, testArgs), testOpts, "Test a library."); actions.put("test", test); Options ecdhOpts = new Options(); ecdhOpts.addOption(bits); ecdhOpts.addOption(namedCurve); ecdhOpts.addOption(curveName); ecdhOpts.addOption(output); ecdhOpts.addOption(Option.builder("t").longOpt("type").desc("Set KeyAgreement object [type].").hasArg().argName("type").optionalArg(false).build()); ecdhOpts.addOption(Option.builder().longOpt("key-type").desc("Set the key [algorithm] for which the key should be derived in KeyAgreements with KDF. Default is \"AES\".").hasArg().argName("algorithm").optionalArg(false).build()); ecdhOpts.addOption(Option.builder("n").longOpt("amount").hasArg().argName("amount").optionalArg(false).desc("Do ECDH [amount] times.").build()); ecdhOpts.addOption(Option.builder().longOpt("fixed-private").desc("Perform ECDH with fixed private key.").build()); ecdhOpts.addOption(Option.builder().longOpt("fixed-public").desc("Perform ECDH with fixed public key.").build()); ParserOptions ecdh = new ParserOptions(new DefaultParser(), ecdhOpts, "Perform EC based KeyAgreement."); actions.put("ecdh", ecdh); Options ecdsaOpts = new Options(); ecdsaOpts.addOption(bits); ecdsaOpts.addOption(namedCurve); ecdsaOpts.addOption(curveName); ecdhOpts.addOption(output); ecdsaOpts.addOption(Option.builder("t").longOpt("type").desc("Set Signature object [type].").hasArg().argName("type").optionalArg(false).build()); ecdsaOpts.addOption(Option.builder("n").longOpt("amount").hasArg().argName("amount").optionalArg(false).desc("Do ECDSA [amount] times.").build()); ecdsaOpts.addOption(Option.builder("f").longOpt("file").hasArg().argName("file").optionalArg(false).desc("Input [file] to sign.").build()); ParserOptions ecdsa = new ParserOptions(new DefaultParser(), ecdsaOpts, "Perform EC based Signature."); actions.put("ecdsa", ecdsa); Options generateOpts = new Options(); generateOpts.addOption(bits); generateOpts.addOption(namedCurve); generateOpts.addOption(curveName); ecdhOpts.addOption(output); generateOpts.addOption(Option.builder("n").longOpt("amount").hasArg().argName("amount").optionalArg(false).desc("Generate [amount] of EC keys.").build()); generateOpts.addOption(Option.builder("t").longOpt("type").hasArg().argName("type").optionalArg(false).desc("Set KeyPairGenerator object [type].").build()); ParserOptions generate = new ParserOptions(new DefaultParser(), generateOpts, "Generate EC keypairs."); actions.put("generate", generate); Options exportOpts = new Options(); exportOpts.addOption(bits); ecdhOpts.addOption(output); exportOpts.addOption(Option.builder("t").longOpt("type").hasArg().argName("type").optionalArg(false).desc("Set KeyPair object [type].").build()); ParserOptions export = new ParserOptions(new DefaultParser(), exportOpts, "Export default curve parameters."); actions.put("export", export); Options listDataOpts = new Options(); List<Argument> listDataArgs = new LinkedList<>(); listDataArgs.add(new Argument("what", "what to list.", false)); ParserOptions listData = new ParserOptions(new TreeParser(Collections.emptyMap(), false, listDataArgs), listDataOpts, "List/show contained EC domain parameters/keys."); actions.put("list-data", listData); Options listLibsOpts = new Options(); ParserOptions listLibs = new ParserOptions(new DefaultParser(), listLibsOpts, "List supported libraries."); actions.put("list-libs", listLibs); Options listSuitesOpts = new Options(); ParserOptions listSuites = new ParserOptions(new DefaultParser(), listSuitesOpts, "List supported test suites."); actions.put("list-suites", listSuites); List<Argument> baseArgs = new LinkedList<>(); baseArgs.add(new Argument("lib", "What library to use.", false)); optParser = new TreeParser(actions, false, baseArgs); opts.addOption(Option.builder("V").longOpt("version").desc("Print version info.").build()); opts.addOption(Option.builder("h").longOpt("help").desc("Print help(about <command>).").hasArg().argName("command").optionalArg(true).build()); opts.addOption(Option.builder("C").longOpt("color").desc("Print stuff with color, requires ANSI terminal.").build()); return optParser.parse(opts, args); } /** * */ private void listLibraries() { for (ProviderECLibrary lib : libs) { if (lib.isInitialized() && (cfg.selected == null || lib == cfg.selected)) { System.out.println("\t- " + Colors.bold(lib.name())); System.out.println(Colors.bold("\t\t- Supports native timing: ") + lib.supportsNativeTiming()); Set<KeyPairGeneratorIdent> kpgs = lib.getKPGs(); if (!kpgs.isEmpty()) { System.out.println(Colors.bold("\t\t- KeyPairGenerators: ") + String.join(", ", kpgs.stream().map(KeyPairGeneratorIdent::getName).collect(Collectors.toList()))); } Set<KeyAgreementIdent> eckas = lib.getKAs(); if (!eckas.isEmpty()) { System.out.println(Colors.bold("\t\t- KeyAgreements: ") + String.join(", ", eckas.stream().map(KeyAgreementIdent::getName).collect(Collectors.toList()))); } Set<SignatureIdent> sigs = lib.getSigs(); if (!sigs.isEmpty()) { System.out.println(Colors.bold("\t\t- Signatures: ") + String.join(", ", sigs.stream().map(SignatureIdent::getName).collect(Collectors.toList()))); } Set<String> curves = lib.getCurves(); if (!curves.isEmpty()) { System.out.println(Colors.bold("\t\t- Curves: ") + String.join(", ", curves)); } System.out.println(); } } } /** * */ private void listSuites() { StandaloneTestSuite[] suites = new StandaloneTestSuite[]{new StandaloneDefaultSuite(null, null, null)}; for (StandaloneTestSuite suite : suites) { System.out.println(" - " + suite.getName()); for (String line : suite.getDescription()) { System.out.println("\t" + line); } } } /** * */ private void ecdh() throws NoSuchAlgorithmException, InvalidAlgorithmParameterException, InvalidKeyException, FileNotFoundException { ProviderECLibrary lib = cfg.selected; String algo = cli.getOptionValue("ecdh.type", "ECDH"); String keyAlgo = cli.getOptionValue("ecdh.key-type", "AES"); KeyAgreementIdent kaIdent = lib.getKAs().stream() .filter((ident) -> ident.contains(algo)) .findFirst() .orElse(null); String baseAlgo; if (algo.contains("with")) { baseAlgo = algo.split("with")[0]; } else { baseAlgo = algo; } KeyPairGeneratorIdent kpIdent = lib.getKPGs().stream() .filter((ident) -> ident.contains(algo)) .findFirst() .orElse(lib.getKPGs().stream() .filter((ident) -> ident.contains(baseAlgo)) .findFirst() .orElse(lib.getKPGs().stream() .filter((ident) -> ident.contains("ECDH")) .findFirst() .orElse(lib.getKPGs().stream() .filter((ident) -> ident.contains("EC")) .findFirst() .orElse(null)))); if (kaIdent == null || kpIdent == null) { throw new NoSuchAlgorithmException(algo); } KeyAgreement ka = kaIdent.getInstance(lib.getProvider()); KeyPairGenerator kpg = kpIdent.getInstance(lib.getProvider()); AlgorithmParameterSpec spec = null; if (cli.hasOption("ecdh.bits")) { int bits = Integer.parseInt(cli.getOptionValue("ecdh.bits")); kpg.initialize(bits); } else if (cli.hasOption("ecdh.named-curve")) { String curveName = cli.getOptionValue("ecdh.named-curve"); EC_Curve curve = EC_Store.getInstance().getObject(EC_Curve.class, curveName); if (curve == null) { System.err.println("Curve not found: " + curveName); return; } spec = curve.toSpec(); kpg.initialize(spec); } else if (cli.hasOption("ecdh.curve-name")) { String curveName = cli.getOptionValue("ecdh.curve-name"); spec = new ECGenParameterSpec(curveName); kpg.initialize(spec); } PrintStream out; if (cli.hasOption("ecdh.output")) { out = new PrintStream(FileUtil.openStream(cli.getOptionValues("ecdh.output"))); } else { out = System.out; } out.println("index;time[nano];pubW;privS;secret"); KeyPair one = null; if (cli.hasOption("ecdh.fixed-private")) { one = kpg.genKeyPair(); } KeyPair other = null; if (cli.hasOption("ecdh.fixed-public")) { other = kpg.genKeyPair(); } int amount = Integer.parseInt(cli.getOptionValue("ecdh.amount", "1")); for (int i = 0; i < amount; ++i) { if (!cli.hasOption("ecdh.fixed-private")) { one = kpg.genKeyPair(); } if (!cli.hasOption("ecdh.fixed-public")) { other = kpg.genKeyPair(); } ECPrivateKey privkey = (ECPrivateKey) one.getPrivate(); ECPublicKey pubkey = (ECPublicKey) other.getPublic(); long elapsed = -System.nanoTime(); if (spec instanceof ECParameterSpec) { ka.init(privkey, spec); } else { ka.init(privkey); } ka.doPhase(pubkey, true); elapsed += System.nanoTime(); SecretKey derived; byte[] result; elapsed -= System.nanoTime(); if (kaIdent.requiresKeyAlgo()) { derived = ka.generateSecret(keyAlgo); result = derived.getEncoded(); } else { result = ka.generateSecret(); } elapsed += System.nanoTime(); ka = kaIdent.getInstance(lib.getProvider()); String pub = ByteUtil.bytesToHex(ECUtil.toX962Uncompressed(pubkey.getW(), pubkey.getParams()), false); String priv = ByteUtil.bytesToHex(privkey.getS().toByteArray(), false); String dh = ByteUtil.bytesToHex(result, false); out.println(String.format("%d;%d;%s;%s;%s", i, elapsed, pub, priv, dh)); } if (cli.hasOption("ecdh.output")) { out.close(); } } /** * */ private void ecdsa() throws NoSuchAlgorithmException, InvalidAlgorithmParameterException, InvalidKeyException, IOException, SignatureException { byte[] data; String dataString; if (cli.hasOption("ecdsa.file")) { String fileName = cli.getOptionValue("ecdsa.file"); File in = new File(fileName); long len = in.length(); if (len == 0) { throw new FileNotFoundException(fileName); } data = Files.readAllBytes(in.toPath()); dataString = ""; } else { SecureRandom random = new SecureRandom(); data = new byte[32]; random.nextBytes(data); dataString = ByteUtil.bytesToHex(data, false); } ProviderECLibrary lib = cfg.selected; String algo = cli.getOptionValue("ecdsa.type", "ECDSA"); SignatureIdent sigIdent = lib.getSigs().stream() .filter((ident) -> ident.contains(algo)) .findFirst() .orElse(null); String baseAlgo; if (algo.contains("with")) { baseAlgo = algo.split("with")[1]; } else { baseAlgo = algo; } KeyPairGeneratorIdent kpIdent = lib.getKPGs().stream() .filter((ident) -> ident.contains(algo)) .findFirst() .orElse(lib.getKPGs().stream() .filter((ident) -> ident.contains(baseAlgo)) .findFirst() .orElse(lib.getKPGs().stream() .filter((ident) -> ident.contains("ECDSA")) .findFirst() .orElse(lib.getKPGs().stream() .filter((ident) -> ident.contains("EC")) .findFirst() .orElse(null)))); if (sigIdent == null || kpIdent == null) { throw new NoSuchAlgorithmException(algo); } Signature sig = sigIdent.getInstance(lib.getProvider()); KeyPairGenerator kpg = kpIdent.getInstance(lib.getProvider()); if (cli.hasOption("ecdsa.bits")) { int bits = Integer.parseInt(cli.getOptionValue("ecdsa.bits")); kpg.initialize(bits); } else if (cli.hasOption("ecdsa.named-curve")) { String curveName = cli.getOptionValue("ecdsa.named-curve"); EC_Curve curve = EC_Store.getInstance().getObject(EC_Curve.class, curveName); if (curve == null) { System.err.println("Curve not found: " + curveName); return; } kpg.initialize(curve.toSpec()); } else if (cli.hasOption("ecdsa.curve-name")) { String curveName = cli.getOptionValue("ecdsa.curve-name"); kpg.initialize(new ECGenParameterSpec(curveName)); } PrintStream out; if (cli.hasOption("ecdsa.output")) { out = new PrintStream(FileUtil.openStream(cli.getOptionValues("ecdh.output"))); } else { out = System.out; } out.println("index;data;signTime[nano];verifyTime[nano];pubW;privS;signature;verified"); int amount = Integer.parseInt(cli.getOptionValue("ecdsa.amount", "1")); for (int i = 0; i < amount; ++i) { KeyPair one = kpg.genKeyPair(); ECPrivateKey privkey = (ECPrivateKey) one.getPrivate(); ECPublicKey pubkey = (ECPublicKey) one.getPublic(); sig.initSign(privkey); sig.update(data); long signTime = -System.nanoTime(); byte[] signature = sig.sign(); signTime += System.nanoTime(); sig.initVerify(pubkey); sig.update(data); long verifyTime = -System.nanoTime(); boolean verified = sig.verify(signature); verifyTime += System.nanoTime(); String pub = ByteUtil.bytesToHex(ECUtil.toX962Uncompressed(pubkey.getW(), pubkey.getParams()), false); String priv = ByteUtil.bytesToHex(privkey.getS().toByteArray(), false); String sign = ByteUtil.bytesToHex(signature, false); out.println(String.format("%d;%s;%d;%d;%s;%s;%s;%d", i, dataString, signTime, verifyTime, pub, priv, sign, verified ? 1 : 0)); } if (cli.hasOption("ecdsa.output")) { out.close(); } } /** * */ private void generate() throws NoSuchAlgorithmException, InvalidAlgorithmParameterException, FileNotFoundException { ProviderECLibrary lib = cfg.selected; KeyPairGeneratorIdent ident = null; String algo = cli.getOptionValue("generate.type", "EC"); for (KeyPairGeneratorIdent kpIdent : lib.getKPGs()) { if (kpIdent.contains(algo)) { ident = kpIdent; break; } } if (ident == null) { throw new NoSuchAlgorithmException(algo); } KeyPairGenerator kpg = ident.getInstance(lib.getProvider()); if (cli.hasOption("generate.bits")) { int bits = Integer.parseInt(cli.getOptionValue("generate.bits")); kpg.initialize(bits); } else if (cli.hasOption("generate.named-curve")) { String curveName = cli.getOptionValue("generate.named-curve"); EC_Curve curve = EC_Store.getInstance().getObject(EC_Curve.class, curveName); if (curve == null) { System.err.println("Curve not found: " + curveName); return; } kpg.initialize(curve.toSpec()); } else if (cli.hasOption("generate.curve-name")) { String curveName = cli.getOptionValue("generate.curve-name"); kpg.initialize(new ECGenParameterSpec(curveName)); } PrintStream out; if (cli.hasOption("generate.output")) { out = new PrintStream(FileUtil.openStream(cli.getOptionValues("ecdh.output"))); } else { out = System.out; } out.println("index;time[nano];pubW;privS"); int amount = Integer.parseInt(cli.getOptionValue("generate.amount", "1")); for (int i = 0; i < amount || amount == 0; ++i) { long elapsed = -System.nanoTime(); KeyPair kp = kpg.genKeyPair(); elapsed += System.nanoTime(); if (lib.supportsNativeTiming()) { elapsed = lib.getLastNativeTiming(); } ECPublicKey publicKey = (ECPublicKey) kp.getPublic(); ECPrivateKey privateKey = (ECPrivateKey) kp.getPrivate(); String pub = ByteUtil.bytesToHex(ECUtil.toX962Uncompressed(publicKey.getW(), publicKey.getParams()), false); String priv = ByteUtil.bytesToHex(privateKey.getS().toByteArray(), false); out.println(String.format("%d;%d;%s;%s", i, elapsed, pub, priv)); } if (cli.hasOption("generate.output")) { out.close(); } } /** * */ private void test() throws TestException, ParserConfigurationException { TestWriter writer; switch (cli.getOptionValue("test.format", "text").toLowerCase()) { case "yaml": case "yml": writer = new YAMLTestWriter(System.out); break; case "xml": writer = new XMLTestWriter(System.out); break; case "text": default: writer = new TextTestWriter(System.out); break; } String suiteName = cli.getArg(0); StandaloneTestSuite suite = new StandaloneDefaultSuite(writer, cfg, cli); suite.run(); } /** * */ private void export() throws NoSuchAlgorithmException, IOException { ProviderECLibrary lib = cfg.selected; KeyPairGeneratorIdent ident = null; String algo = cli.getOptionValue("export.type", "EC"); for (KeyPairGeneratorIdent kpIdent : lib.getKPGs()) { if (kpIdent.contains(algo)) { ident = kpIdent; break; } } if (ident == null) { throw new NoSuchAlgorithmException(algo); } else { KeyPairGenerator kpg = ident.getInstance(lib.getProvider()); if (cli.hasOption("export.bits")) { int bits = Integer.parseInt(cli.getOptionValue("export.bits")); kpg.initialize(bits); } KeyPair kp = kpg.genKeyPair(); ECPrivateKey privateKey = (ECPrivateKey) kp.getPrivate(); ECParameterSpec params = privateKey.getParams(); System.out.println(params); EC_Curve curve = EC_Curve.fromSpec(params); curve.writeCSV(System.out); } } public static void main(String[] args) { ECTesterStandalone app = new ECTesterStandalone(); app.run(args); } /** * */ public static class Config { private ProviderECLibrary[] libs; public ProviderECLibrary selected = null; public boolean color = false; public Config(ProviderECLibrary[] libs) { this.libs = libs; } boolean readOptions(TreeCommandLine cli) { color = cli.hasOption("color"); Colors.enabled = color; if (cli.isNext("generate") || cli.isNext("export") || cli.isNext("ecdh") || cli.isNext("ecdsa") || cli.isNext("test")) { if (!cli.hasArg(-1)) { System.err.println("Missing library name argument."); return false; } String next = cli.getNextName(); boolean hasBits = cli.hasOption(next + ".bits"); boolean hasNamedCurve = cli.hasOption(next + ".named-curve"); boolean hasCurveName = cli.hasOption(next + ".curve-name"); if (hasBits ^ hasNamedCurve ? hasCurveName : hasBits) { System.err.println("You can only specify bitsize or a named curve/curve name, nor both."); return false; } } if (!cli.isNext("list-data") && !cli.isNext("list-suites")) { String libraryName = cli.getArg(-1); if (libraryName != null) { List<ProviderECLibrary> matchedLibs = new LinkedList<>(); for (ProviderECLibrary lib : libs) { if (lib.isInitialized() && lib.name().toLowerCase().contains(libraryName.toLowerCase())) { matchedLibs.add(lib); } } if (matchedLibs.size() == 0) { System.err.println("No library " + libraryName + " found."); return false; } else if (matchedLibs.size() > 1) { System.err.println("Multiple matching libraries found: " + String.join(",", matchedLibs.stream().map(ECLibrary::name).collect(Collectors.toList()))); return false; } else { selected = matchedLibs.get(0); } } } if (cli.hasOption("test.format")) { String fmt = cli.getOptionValue("test.format"); String formats[] = new String[]{"text", "xml", "yaml", "yml"}; if (!Arrays.asList(formats).contains(fmt.toLowerCase())) { System.err.println("Invalid format specified."); return false; } } return true; } } }
Use native timing when available.
src/cz/crcs/ectester/standalone/ECTesterStandalone.java
Use native timing when available.
<ide><path>rc/cz/crcs/ectester/standalone/ECTesterStandalone.java <ide> result = ka.generateSecret(); <ide> } <ide> elapsed += System.nanoTime(); <add> if (lib.supportsNativeTiming()) { <add> elapsed = lib.getLastNativeTiming(); <add> } <ide> ka = kaIdent.getInstance(lib.getProvider()); <ide> <ide> String pub = ByteUtil.bytesToHex(ECUtil.toX962Uncompressed(pubkey.getW(), pubkey.getParams()), false); <ide> long signTime = -System.nanoTime(); <ide> byte[] signature = sig.sign(); <ide> signTime += System.nanoTime(); <add> if (lib.supportsNativeTiming()) { <add> signTime = lib.getLastNativeTiming(); <add> } <ide> <ide> sig.initVerify(pubkey); <ide> sig.update(data); <ide> long verifyTime = -System.nanoTime(); <ide> boolean verified = sig.verify(signature); <ide> verifyTime += System.nanoTime(); <add> if (lib.supportsNativeTiming()) { <add> verifyTime = lib.getLastNativeTiming(); <add> } <ide> <ide> String pub = ByteUtil.bytesToHex(ECUtil.toX962Uncompressed(pubkey.getW(), pubkey.getParams()), false); <ide> String priv = ByteUtil.bytesToHex(privkey.getS().toByteArray(), false); <ide> } <ide> if (ident == null) { <ide> throw new NoSuchAlgorithmException(algo); <del> } else { <del> KeyPairGenerator kpg = ident.getInstance(lib.getProvider()); <del> if (cli.hasOption("export.bits")) { <del> int bits = Integer.parseInt(cli.getOptionValue("export.bits")); <del> kpg.initialize(bits); <del> } <del> KeyPair kp = kpg.genKeyPair(); <del> ECPrivateKey privateKey = (ECPrivateKey) kp.getPrivate(); <del> ECParameterSpec params = privateKey.getParams(); <del> System.out.println(params); <del> EC_Curve curve = EC_Curve.fromSpec(params); <del> curve.writeCSV(System.out); <del> } <add> } <add> KeyPairGenerator kpg = ident.getInstance(lib.getProvider()); <add> if (cli.hasOption("export.bits")) { <add> int bits = Integer.parseInt(cli.getOptionValue("export.bits")); <add> kpg.initialize(bits); <add> } <add> KeyPair kp = kpg.genKeyPair(); <add> ECPrivateKey privateKey = (ECPrivateKey) kp.getPrivate(); <add> ECParameterSpec params = privateKey.getParams(); <add> System.out.println(params); <add> EC_Curve curve = EC_Curve.fromSpec(params); <add> curve.writeCSV(System.out); <ide> } <ide> <ide> public static void main(String[] args) {
JavaScript
apache-2.0
c9b676053eb4ad6ecb025f59904a68c601b4447f
0
caskdata/cdap,caskdata/cdap,caskdata/cdap,caskdata/cdap,caskdata/cdap,caskdata/cdap
/* * Copyright © 2016 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. */ angular.module(PKG.name + '.feature.hydratorplusplus') .service('HydratorPlusPlusDetailRunsStore', function(HydratorPlusPlusDetailDispatcher, $state, myHelpers, GLOBALS, myPipelineCommonApi, HydratorService) { var dispatcher = HydratorPlusPlusDetailDispatcher.getDispatcher(); this.changeListeners = []; this.HydratorService = HydratorService; this.setDefaults = function(app) { this.state = { runs:{ list: [], latest: {}, count: 0, nextRunTime: null }, params: app.params || {}, scheduleParams: app.scheduleParams || {}, logsParams: app.logsParams || {}, api: app.api, type: app.type, metricProgramType: app.metricProgramType, statistics: '' }; }; this.setDefaults({}); this.getRuns = function() { return angular.copy(this.state.runs.list); }; this.getLatestRun = function() { return this.state.runs.list[0]; }; this.getLatestMetricRunId = function() { var metricRunId; if (!this.state.runs.count) { return false; } metricRunId = this.state.runs.list[0].runid; return metricRunId; }; this.getAppType = function() { return this.state.type; }; this.getStatus = function() { var status; if (this.state.runs.list.length === 0) { status = 'STOPPED'; } else { status = myHelpers.objectQuery(this.state, 'runs', 'latest', 'status') || ''; } return status; }; this.getRunsCount = function() { return this.state.runs.count; }; this.getNextRunTime = function() { return this.state.runs.nextRunTime; }; this.setNextRunTime = function(nextRunTime) { this.state.runs.nextRunTime = nextRunTime; this.emitChange(); }; this.getApi = function() { return this.state.api; }; this.getParams = function() { return this.state.params; }; this.getScheduleParams = function() { return this.state.scheduleParams; }; this.getLogsParams = function() { var logsParams = angular.extend({runId: this.state.runs.latest.runid}, this.state.logsParams); return logsParams; }; this.getStatistics = function() { return this.state.statistics; }; this.getMetricProgramType = function() { return this.state.metricProgramType; }; this.registerOnChangeListener = function(callback) { this.changeListeners.push(callback); }; this.emitChange = function() { this.changeListeners.forEach(function(callback) { callback(); }); }; this.setRunsState = function(runs) { if (!runs.length) { return; } this.state.runs = { list: runs, count: runs.length, latest: runs[0], runsCount: runs.length, nextRunTime: this.state.runs.nextRunTime || null }; this.state.logsParams.runId = this.state.runs.latest.runid; this.emitChange(); }; this.setStatistics = function(statistics) { this.state.statistics = statistics; this.emitChange(); }; this.init = function(app) { var appConfig = {}; var appLevelParams, logsLevelParams, metricProgramType, programType; angular.extend(appConfig, app); appLevelParams = { namespace: $state.params.namespace, app: app.name }; logsLevelParams = { namespace: $state.params.namespace, appId: app.name }; programType = GLOBALS.etlBatchPipelines.indexOf(app.artifact.name) !== -1 ? 'WORKFLOWS' : 'WORKER'; if (programType === 'WORKFLOWS') { angular.forEach(app.programs, function (program) { if (program.type === 'Workflow') { appLevelParams.programName = program.id; appLevelParams.programType = program.type.toLowerCase() + 's'; metricProgramType = program.type.toLowerCase(); logsLevelParams.programId = program.id; logsLevelParams.programType = appLevelParams.programType; } }); } else { angular.forEach(app.programs, function (program) { metricProgramType = program.type.toLowerCase(); appLevelParams.programName = program.id; appLevelParams.programType = program.type.toLowerCase() + 's'; logsLevelParams.programId = program.id; logsLevelParams.programType = program.type.toLowerCase() + 's'; }); } appConfig.type = app.artifact.name; appConfig.logsParams = logsLevelParams; appConfig.params = appLevelParams; appConfig.api = myPipelineCommonApi; appConfig.metricProgramType = metricProgramType; appConfig.scheduleParams = { app: appLevelParams.app, schedule: 'etlWorkflow', namespace: appLevelParams.namespace }; this.setDefaults(appConfig); }; this.reset = function() { this.setDefaults({}); this.changeListeners = []; }; dispatcher.register('onRunsChange', this.setRunsState.bind(this)); dispatcher.register('onStatisticsFetch', this.setStatistics.bind(this)); dispatcher.register('onReset', this.setDefaults.bind(this, {})); dispatcher.register('onNextRunTime', this.setNextRunTime.bind(this)); });
cdap-ui/app/features/hydratorplusplus/services/detail/stores/pipeline-detail-runs-store.js
/* * Copyright © 2016 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. */ angular.module(PKG.name + '.feature.hydratorplusplus') .service('HydratorPlusPlusDetailRunsStore', function(HydratorPlusPlusDetailDispatcher, $state, myHelpers, GLOBALS, myPipelineCommonApi, HydratorService) { var dispatcher = HydratorPlusPlusDetailDispatcher.getDispatcher(); this.changeListeners = []; this.HydratorService = HydratorService; this.setDefaults = function(app) { this.state = { runs:{ list: [], latest: {}, count: 0, nextRunTime: null }, params: app.params || {}, scheduleParams: app.scheduleParams || {}, logsParams: app.logsParams || {}, api: app.api, type: app.type, metricProgramType: app.metricProgramType, statistics: '' }; }; this.setDefaults({}); this.getRuns = function() { return angular.copy(this.state.runs.list); }; this.getLatestRun = function() { return this.state.runs.list[0]; }; this.getLatestMetricRunId = function() { var appType = this.getAppType(); var metricRunId; if (!this.state.runs.count) { return false; } if (GLOBALS.etlBatchPipelines.indexOf(appType) !== -1) { // TODO: Make it generic so that we can choose between spark and mapreduce. // We will get a flag from backend called 'engine'. This can be chosen based on that. let mrProgramId = this.getLogsParams().programId; metricRunId = this.state.runs.list[0].properties[mrProgramId]; } else if (appType === GLOBALS.etlRealtime) { metricRunId = this.state.runs.list[0].runid; } return metricRunId; }; this.getAppType = function() { return this.state.type; }; this.getStatus = function() { var status; if (this.state.runs.list.length === 0) { status = 'STOPPED'; } else { status = myHelpers.objectQuery(this.state, 'runs', 'latest', 'status') || ''; } return status; }; this.getRunsCount = function() { return this.state.runs.count; }; this.getNextRunTime = function() { return this.state.runs.nextRunTime; }; this.setNextRunTime = function(nextRunTime) { this.state.runs.nextRunTime = nextRunTime; this.emitChange(); }; this.getApi = function() { return this.state.api; }; this.getParams = function() { return this.state.params; }; this.getScheduleParams = function() { return this.state.scheduleParams; }; this.getLogsParams = function() { var logsParams = angular.extend({runId: this.state.runs.latest.runid}, this.state.logsParams); return logsParams; }; this.getStatistics = function() { return this.state.statistics; }; this.getMetricProgramType = function() { return this.state.metricProgramType; }; this.registerOnChangeListener = function(callback) { this.changeListeners.push(callback); }; this.emitChange = function() { this.changeListeners.forEach(function(callback) { callback(); }); }; this.setRunsState = function(runs) { if (!runs.length) { return; } this.state.runs = { list: runs, count: runs.length, latest: runs[0], runsCount: runs.length, nextRunTime: this.state.runs.nextRunTime || null }; if (GLOBALS.etlBatchPipelines.indexOf(this.state.type) !== -1) { let mrProgramId = this.getLogsParams().programId; this.state.logsParams.runId = this.state.runs.latest.properties[mrProgramId]; } else { this.state.logsParams.runId = this.state.runs.latest.runid; } this.emitChange(); }; this.setStatistics = function(statistics) { this.state.statistics = statistics; this.emitChange(); }; this.init = function(app) { var appConfig = {}; var appLevelParams, logsLevelParams, metricProgramType, programType; angular.extend(appConfig, app); appLevelParams = { namespace: $state.params.namespace, app: app.name }; logsLevelParams = { namespace: $state.params.namespace, appId: app.name }; programType = GLOBALS.etlBatchPipelines.indexOf(app.artifact.name) !== -1 ? 'WORKFLOWS' : 'WORKER'; if (programType === 'WORKFLOWS') { let engineType = JSON.parse(app.configuration).engine; angular.forEach(app.programs, function (program) { if (program.type === 'Workflow') { appLevelParams.programName = program.id; appLevelParams.programType = program.type.toLowerCase() + 's'; } else { metricProgramType = program.type.toLowerCase(); logsLevelParams.programId = program.id; logsLevelParams.programType = engineType || 'mapreduce'; } }); } else { angular.forEach(app.programs, function (program) { metricProgramType = program.type.toLowerCase(); appLevelParams.programName = program.id; appLevelParams.programType = program.type.toLowerCase() + 's'; logsLevelParams.programId = program.id; logsLevelParams.programType = program.type.toLowerCase() + 's'; }); } appConfig.type = app.artifact.name; appConfig.logsParams = logsLevelParams; appConfig.params = appLevelParams; appConfig.api = myPipelineCommonApi; appConfig.metricProgramType = metricProgramType; appConfig.scheduleParams = { app: appLevelParams.app, schedule: 'etlWorkflow', namespace: appLevelParams.namespace }; this.setDefaults(appConfig); }; this.reset = function() { this.setDefaults({}); this.changeListeners = []; }; dispatcher.register('onRunsChange', this.setRunsState.bind(this)); dispatcher.register('onStatisticsFetch', this.setStatistics.bind(this)); dispatcher.register('onReset', this.setDefaults.bind(this, {})); dispatcher.register('onNextRunTime', this.setNextRunTime.bind(this)); });
Fixes logs and metrics to be on workflows instead of mapreduce in batch & data pipelines
cdap-ui/app/features/hydratorplusplus/services/detail/stores/pipeline-detail-runs-store.js
Fixes logs and metrics to be on workflows instead of mapreduce in batch & data pipelines
<ide><path>dap-ui/app/features/hydratorplusplus/services/detail/stores/pipeline-detail-runs-store.js <ide> return this.state.runs.list[0]; <ide> }; <ide> this.getLatestMetricRunId = function() { <del> var appType = this.getAppType(); <ide> var metricRunId; <ide> if (!this.state.runs.count) { <ide> return false; <ide> } <del> <del> if (GLOBALS.etlBatchPipelines.indexOf(appType) !== -1) { <del> // TODO: Make it generic so that we can choose between spark and mapreduce. <del> // We will get a flag from backend called 'engine'. This can be chosen based on that. <del> let mrProgramId = this.getLogsParams().programId; <del> metricRunId = this.state.runs.list[0].properties[mrProgramId]; <del> } else if (appType === GLOBALS.etlRealtime) { <del> metricRunId = this.state.runs.list[0].runid; <del> } <add> metricRunId = this.state.runs.list[0].runid; <ide> return metricRunId; <ide> }; <ide> this.getAppType = function() { <ide> runsCount: runs.length, <ide> nextRunTime: this.state.runs.nextRunTime || null <ide> }; <del> if (GLOBALS.etlBatchPipelines.indexOf(this.state.type) !== -1) { <del> let mrProgramId = this.getLogsParams().programId; <del> this.state.logsParams.runId = this.state.runs.latest.properties[mrProgramId]; <del> } else { <del> this.state.logsParams.runId = this.state.runs.latest.runid; <del> } <add> this.state.logsParams.runId = this.state.runs.latest.runid; <ide> this.emitChange(); <ide> }; <ide> this.setStatistics = function(statistics) { <ide> programType = GLOBALS.etlBatchPipelines.indexOf(app.artifact.name) !== -1 ? 'WORKFLOWS' : 'WORKER'; <ide> <ide> if (programType === 'WORKFLOWS') { <del> let engineType = JSON.parse(app.configuration).engine; <ide> angular.forEach(app.programs, function (program) { <ide> if (program.type === 'Workflow') { <ide> appLevelParams.programName = program.id; <ide> appLevelParams.programType = program.type.toLowerCase() + 's'; <del> } else { <ide> metricProgramType = program.type.toLowerCase(); <del> <ide> logsLevelParams.programId = program.id; <del> logsLevelParams.programType = engineType || 'mapreduce'; <add> logsLevelParams.programType = appLevelParams.programType; <ide> } <ide> }); <ide> } else {
JavaScript
mit
94d698793f2e395888d6a0490f46b6f3904ed4a2
0
exponentjs/xdl,exponentjs/xdl,exponentjs/xdl
/** * @flow */ import 'instapromise'; import { vsprintf } from 'sprintf-js'; import bodyParser from 'body-parser'; import child_process from 'child_process'; import delayAsync from 'delay-async'; import express from 'express'; import FormData from 'form-data'; import freeportAsync from 'freeport-async'; import fs from 'fs'; import joi from 'joi'; import _ from 'lodash'; import ngrok from 'ngrok'; import path from 'path'; import request from 'request'; import semver from 'semver'; import spawnAsync from '@exponent/spawn-async'; import treekill from 'tree-kill'; import * as Analytics from './Analytics'; import * as Android from './Android'; import Api from './Api'; import Config from './Config'; import ErrorCode from './ErrorCode'; import * as Exp from './Exp'; import Logger from './Logger'; import * as ProjectSettings from './ProjectSettings'; import * as UrlUtils from './UrlUtils'; import * as User from './User'; import * as Versions from './Versions'; import XDLError from './XDLError'; const MINIMUM_BUNDLE_SIZE = 500; const MAX_MESSAGE_LENGTH = 200; let _projectRootToExponentServer = {}; let _projectRootToLogger = {}; type CachedSignedManifest = { manifestString: ?string, signedManifest: ?string, }; let _cachedSignedManifest: CachedSignedManifest = { manifestString: null, signedManifest: null, }; function _getLogger(projectRoot: string) { let logger = _projectRootToLogger[projectRoot]; if (!logger) { logger = Logger.child({type: 'project', project: path.resolve(projectRoot)}); _projectRootToLogger[projectRoot] = logger; } return logger; } function _logWithLevel(projectRoot: string, level: string, object: any, msg: string) { let logger = _getLogger(projectRoot); switch (level) { case 'debug': logger.debug(object, msg); return; case 'info': logger.info(object, msg); return; case 'warn': logger.warn(object, msg); return; case 'error': logger.error(object, msg); return; default: logger.debug(object, msg); return; } } export function logDebug(projectRoot: string, tag: string, message: string) { _getLogger(projectRoot).debug({tag}, message.toString()); } export function logInfo(projectRoot: string, tag: string, message: string) { _getLogger(projectRoot).info({tag}, message.toString()); } export function logError(projectRoot: string, tag: string, message: string) { _getLogger(projectRoot).error({tag}, message.toString()); let truncatedMessage = message.toString(); if (truncatedMessage.length > MAX_MESSAGE_LENGTH) { truncatedMessage = truncatedMessage.substring(0, MAX_MESSAGE_LENGTH); } Analytics.logEvent('Project Error', { projectRoot, tag, message: truncatedMessage, }); } export function attachLoggerStream(projectRoot: string, stream: any) { _getLogger(projectRoot).addStream(stream); } async function _assertLoggedInAsync() { let user = await User.getCurrentUserAsync(); if (!user) { throw new XDLError(ErrorCode.NOT_LOGGED_IN, 'Not logged in'); } } async function _assertValidProjectRoot(projectRoot) { if (!projectRoot) { throw new XDLError(ErrorCode.NO_PROJECT_ROOT, 'No project root specified'); } } async function _getFreePortAsync(rangeStart) { let port = await freeportAsync(rangeStart); if (!port) { throw new XDLError(ErrorCode.NO_PORT_FOUND, 'No available port found'); } return port; } async function _readConfigJsonAsync(projectRoot): Promise<any> { let exp; let pkg; try { pkg = await Exp.packageJsonForRoot(projectRoot).readAsync(); exp = await Exp.expJsonForRoot(projectRoot).readAsync(); } catch (e) { if (e.isJsonFileError) { // TODO: add error codes to json-file if (e.message.startsWith('Error parsing JSON file')) { logError(projectRoot, 'exponent', `Error parsing JSON file: ${e.cause.toString()}`); return { exp: null, pkg: null }; } } // exp or pkg missing } // Easiest bail-out: package.json is missing if (!pkg) { logError(projectRoot, 'exponent', `Error: Can't find package.json`); return { exp: null, pkg: null }; } // Grab our exp config from package.json (legacy) or exp.json if (!exp && pkg.exp) { exp = pkg.exp; logError(projectRoot, 'exponent', `Deprecation Warning: Move your "exp" config from package.json to exp.json.`); } else if (!exp && !pkg.exp) { logError(projectRoot, 'exponent', `Error: Missing exp.json. See https://docs.getexponent.com/`); return { exp: null, pkg: null }; } return { exp, pkg }; } async function _validateConfigJsonAsync(projectRoot: string) { let { exp, pkg } = await _readConfigJsonAsync(projectRoot); if (!exp || !pkg) { // _readConfigJsonAsync already logged an error return; } // sdkVersion is necessary if (!exp.sdkVersion) { logError(projectRoot, 'exponent', `Error: Can't find key exp.sdkVersion in exp.json or package.json. See https://docs.getexponent.com/`); return; } // Warn if sdkVersion is UNVERSIONED let sdkVersion = exp.sdkVersion; if (sdkVersion === 'UNVERSIONED') { logError(projectRoot, 'exponent', `Warning: Using unversioned Exponent SDK. Do not publish until you set sdkVersion in exp.json`); return; } // react-native is required if (!pkg.dependencies || !pkg.dependencies['react-native']) { logError(projectRoot, 'exponent', `Error: Can't find react-native in package.json dependencies`); return; } let sdkVersions = await Api.sdkVersionsAsync(); if (!sdkVersions) { logError(projectRoot, 'exponent', `Error: Couldn't connect to server`); return; } if (!sdkVersions[sdkVersion]) { logError(projectRoot, 'exponent', `Error: Invalid sdkVersion. Valid options are ${_.keys(sdkVersions).join(', ')}`); return; } if (Config.validation.reactNativeVersionWarnings) { let reactNative = pkg.dependencies['react-native']; // Exponent fork of react-native is required if (!reactNative.includes('exponentjs/react-native#')) { logError(projectRoot, 'exponent', `Error: Must use the Exponent fork of react-native. See https://getexponent.com/help`); return; } let reactNativeTag = reactNative.substring(reactNative.lastIndexOf('#') + 1); let sdkVersionObject = sdkVersions[sdkVersion]; // TODO: Want to be smarter about this. Maybe warn if there's a newer version. if (semver.major(Versions.parseSdkVersionFromTag(reactNativeTag)) !== semver.major(Versions.parseSdkVersionFromTag(sdkVersionObject['exponentReactNativeTag']))) { logError(projectRoot, 'exponent', `Error: Invalid version of react-native for sdkVersion ${sdkVersion}. Use github:exponentjs/react-native#${sdkVersionObject['exponentReactNativeTag']}`); return; } } // TODO: Check any native module versions here } async function _getForPlatformAsync(url, platform, { errorCode, minLength }) { let response = await request.promise.get({ url: `${url}&platform=${platform}`, headers: { 'Exponent-Platform': platform, }, }); if (response.statusCode !== 200) { throw new XDLError(errorCode, `Packager returned unexpected code ${response.statusCode}`); } if (!response.body || (minLength && response.body.length < minLength)) { throw new XDLError(errorCode, `Body is: ${response.body}`); } return response.body; } export async function publishAsync(projectRoot: string, options: { quiet: bool } = { quiet: false }) { await _assertLoggedInAsync(); _assertValidProjectRoot(projectRoot); Analytics.logEvent('Publish', { projectRoot, }); let schema = joi.object().keys({ quiet: joi.boolean(), }); try { await joi.promise.validate(options, schema); } catch (e) { throw new XDLError(ErrorCode.INVALID_OPTIONS, e.toString()); } let packagerInfo = await ProjectSettings.readPackagerInfoAsync(projectRoot); if (!packagerInfo.packagerPort) { throw new XDLError(ErrorCode.NO_PACKAGER_PORT, `No packager found for project at ${projectRoot}.`); } let entryPoint = await Exp.determineEntryPointAsync(projectRoot); let publishUrl = await UrlUtils.constructPublishUrlAsync(projectRoot, entryPoint); let assetsUrl = await UrlUtils.constructAssetsUrlAsync(projectRoot, entryPoint); let [ iosBundle, androidBundle, iosAssetsJson, androidAssetsJson, ] = await Promise.all([ _getForPlatformAsync(publishUrl, 'ios', { errorCode: ErrorCode.INVALID_BUNDLE, minLength: MINIMUM_BUNDLE_SIZE, }), _getForPlatformAsync(publishUrl, 'android', { errorCode: ErrorCode.INVALID_BUNDLE, minLength: MINIMUM_BUNDLE_SIZE, }), _getForPlatformAsync(assetsUrl, 'ios', { errorCode: ErrorCode.INVALID_ASSETS, }), _getForPlatformAsync(assetsUrl, 'android', { errorCode: ErrorCode.INVALID_ASSETS, }), ]); let { exp, pkg } = await _readConfigJsonAsync(projectRoot); if (!exp || !pkg) { throw new XDLError(ErrorCode.NO_PACKAGE_JSON, `Couldn't read exp.json file in project at ${projectRoot}`); } // Support version and name being specified in package.json for legacy // support pre: exp.json if (!exp.version && pkg.version) { exp.version = pkg.version; } if (!exp.slug && pkg.name) { exp.slug = pkg.name; } if (exp.android && exp.android.config) { delete exp.android.config; } if (exp.ios && exp.ios.config) { delete exp.ios.config; } // Upload asset files const iosAssets = JSON.parse(iosAssetsJson); const androidAssets = JSON.parse(androidAssetsJson); const assets = iosAssets.concat(androidAssets); if (assets.length > 0 && assets[0].fileHashes) { await uploadAssetsAsync(projectRoot, assets); } let form = new FormData(); form.append('expJson', JSON.stringify(exp)); form.append('iosBundle', iosBundle, { filename: 'iosBundle', }); form.append('androidBundle', androidBundle, { filename: 'androidBundle', }); let response = await Api.callMethodAsync('publish', [options], 'put', form); return response; } // TODO(jesse): Add analytics for upload async function uploadAssetsAsync(projectRoot, assets) { // Collect paths by key, also effectively handles duplicates in the array const paths = {}; assets.forEach(asset => { asset.files.forEach((path, index) => { paths[asset.fileHashes[index]] = path; }); }); // Collect list of assets missing on host const metas = (await Api.callMethodAsync('assetsMetadata', [], 'post', { keys: Object.keys(paths), })).metadata; const missing = Object.keys(paths).filter(key => !metas[key].exists); // Upload them! await Promise.all(_.chunk(missing, 5).map(async (keys) => { let form = new FormData(); keys.forEach(key => { logDebug(projectRoot, 'exponent', `uploading ${paths[key]}`); form.append(key, fs.createReadStream(paths[key]), { filename: paths[key], }); }); await Api.callMethodAsync('uploadAssets', [], 'put', form); })); } export async function buildAsync(projectRoot: string, options: { current?: bool, quiet?: bool, mode?: string, platform?: string, expIds?: Array<string>, } = {}) { await _assertLoggedInAsync(); _assertValidProjectRoot(projectRoot); Analytics.logEvent('Build Shell App', { projectRoot, }); let schema = joi.object().keys({ current: joi.boolean(), quiet: joi.boolean(), mode: joi.string(), platform: joi.any().valid('ios', 'android', 'all'), expIds: joi.array(), }); try { await joi.promise.validate(options, schema); } catch (e) { throw new XDLError(ErrorCode.INVALID_OPTIONS, e.toString()); } let { exp, pkg } = await _readConfigJsonAsync(projectRoot); if (!exp || !pkg) { throw new XDLError(ErrorCode.NO_PACKAGE_JSON, `Couldn't read exp.json file in project at ${projectRoot}`); } // Support version and name being specified in package.json for legacy // support pre: exp.json if (!exp.version && pkg.version) { exp.version = pkg.version; } if (!exp.slug && pkg.name) { exp.slug = pkg.name; } if (options.platform === 'ios' || options.platform === 'all') { if (!exp.ios || !exp.ios.bundleIdentifier) { throw new XDLError(ErrorCode.INVALID_MANIFEST, 'Must specify a bundle identifier in order to build this experience for iOS. Please specify one in exp.json at "ios.bundleIdentifier"'); } } if (options.platform === 'android' || options.platform === 'all') { if (!exp.android || !exp.android.package) { throw new XDLError(ErrorCode.INVALID_MANIFEST, 'Must specify a java package in order to build this experience for Android. Please specify one in exp.json at "android.package"'); } } let response = await Api.callMethodAsync( 'build', [], 'put', { manifest: exp, options, }, ); return response; } async function _waitForRunningAsync(url) { try { let response = await request.promise(url); // Looking for "Cached Bundles" string is hacky, but unfortunately // ngrok returns a 200 when it succeeds but the port it's proxying // isn't bound. if (response.statusCode >= 200 && response.statusCode < 300 && response.body && response.body.includes('Cached Bundles')) { return true; } } catch (e) { // Try again after delay } await delayAsync(100); return _waitForRunningAsync(url); } function _stripPackagerOutputBox(output: string) { let re = /Running packager on port (\d+)/; let found = output.match(re); if (found && found.length >= 2) { return `Running packager on port ${found[1]}\n`; } else { return null; } } function _processPackagerLine(line: string) { let re = /\s*\[\d+\:\d+\:\d+\ (AM)?(PM)?\]\s+/; return line.replace(re, ''); } async function _restartWatchmanAsync(projectRoot: string) { try { let result = await spawnAsync('watchman', ['watch-del-all']); if (result.stdout.includes('roots')) { logInfo(projectRoot, 'exponent', 'Restarted watchman.'); return; } } catch (e) {} logError(projectRoot, 'exponent', 'Attempted to restart watchman but failed. Please try running `watchman watch-del-all`.'); } function _logPackagerOutput(projectRoot: string, level: string, data: Object) { let output = data.toString(); if (output.includes('─────')) { output = _stripPackagerOutputBox(output); if (output) { logInfo(projectRoot, 'exponent', output); } return; } if (!output) { return; } // Fix watchman if it's being dumb if (output.includes('watchman watch-del')) { _restartWatchmanAsync(projectRoot); return; } let lines = output.split(/\r?\n/); for (let i = 0; i < lines.length; i++) { lines[i] = _processPackagerLine(lines[i]); } output = lines.join('\n'); if (level === 'info') { logInfo(projectRoot, 'packager', output); } else { logError(projectRoot, 'packager', output); } } function _handleDeviceLogs(projectRoot: string, deviceId: string, deviceName: string, logs: any) { for (let i = 0; i < logs.length; i++) { let log = logs[i]; let bodyArray = []; if (typeof log.body === 'string') { bodyArray.push(log.body); } else { // body is in this format: // { 0: 'stuff', 1: 'more stuff' } // so convert to an array first let j = 0; while (log.body[j]) { bodyArray.push(log.body[j]); j++; } } let string; if (bodyArray[0] && typeof bodyArray[0] === 'string' && bodyArray[0].includes('%')) { string = vsprintf(bodyArray[0], bodyArray.slice(1)); } else { string = bodyArray.map(obj => { if (!obj) { return 'null'; } if (typeof obj === 'string' || typeof obj === 'number' || typeof obj === 'boolean') { return obj; } try { return JSON.stringify(obj); } catch (e) { return obj.toString(); } }).join(' '); } let level = log.level; let groupDepth = log.groupDepth; let shouldHide = log.shouldHide; _logWithLevel(projectRoot, level, { tag: 'device', deviceId, deviceName, groupDepth, shouldHide, }, string); } } export async function startReactNativeServerAsync(projectRoot: string, options: Object = {}) { await _assertLoggedInAsync(); _assertValidProjectRoot(projectRoot); await stopReactNativeServerAsync(projectRoot); let packagerPort = await _getFreePortAsync(19001); let exp = await Exp.expConfigForRootAsync(projectRoot); // Create packager options let packagerOpts = { port: packagerPort, projectRoots: projectRoot, assetRoots: projectRoot, }; const userPackagerOpts = _.get(exp, 'packagerOpts'); if (userPackagerOpts) { packagerOpts = { ...packagerOpts, ...userPackagerOpts, }; } let cliOpts = _.reduce(packagerOpts, (opts, val, key) => { if (val && val !== '') { opts.push(`--${key}`, val); } return opts; }, ['start']); if (options.reset) { cliOpts.push('--reset-cache'); } // Get custom CLI path from project package.json, but fall back to node_module path let defaultCliPath = path.join(projectRoot, 'node_modules/react-native/local-cli/cli.js'); const cliPath = _.get(exp, 'rnCliPath', defaultCliPath); // Run the copy of Node that's embedded in Electron by setting the // ELECTRON_RUN_AS_NODE environment variable // Note: the CLI script sets up graceful-fs and sets ulimit to 4096 in the // child process let packagerProcess = child_process.fork(cliPath, cliOpts, { cwd: projectRoot, env: { ...process.env, NODE_PATH: null, ELECTRON_RUN_AS_NODE: 1, }, silent: true, }); await ProjectSettings.setPackagerInfoAsync(projectRoot, { packagerPort, packagerPid: packagerProcess.pid, }); // TODO: do we need this? don't know if it's ever called process.on('exit', () => { treekill(packagerProcess.pid); }); packagerProcess.stdout.setEncoding('utf8'); packagerProcess.stderr.setEncoding('utf8'); packagerProcess.stdout.on('data', (data) => { _logPackagerOutput(projectRoot, 'info', data); }); packagerProcess.stderr.on('data', (data) => { _logPackagerOutput(projectRoot, 'error', data); }); packagerProcess.on('exit', async (code) => { logDebug(projectRoot, 'exponent', `packager process exited with code ${code}`); }); let packagerUrl = await UrlUtils.constructBundleUrlAsync(projectRoot, { urlType: 'http', hostType: 'localhost', }); await _waitForRunningAsync(`${packagerUrl}/debug`); } export async function stopReactNativeServerAsync(projectRoot: string) { await _assertLoggedInAsync(); _assertValidProjectRoot(projectRoot); let packagerInfo = await ProjectSettings.readPackagerInfoAsync(projectRoot); if (!packagerInfo.packagerPort || !packagerInfo.packagerPid) { logDebug(projectRoot, 'exponent', `No packager found for project at ${projectRoot}.`); return; } logDebug(projectRoot, 'exponent', `Killing packager process tree: ${packagerInfo.packagerPid}`); try { await treekill.promise(packagerInfo.packagerPid, 'SIGKILL'); } catch (e) { logDebug(projectRoot, 'exponent', `Error stopping packager process: ${e.toString()}`); } await ProjectSettings.setPackagerInfoAsync(projectRoot, { packagerPort: null, packagerPid: null, }); } export async function startExponentServerAsync(projectRoot: string) { await _assertLoggedInAsync(); _assertValidProjectRoot(projectRoot); let { exp, pkg } = await _readConfigJsonAsync(projectRoot); if (!exp || !pkg) { // TODO: actually say the correct file name when _readConfigJsonAsync is simpler throw new Error('Error with package.json or exp.json'); } await stopExponentServerAsync(projectRoot); let app = express(); app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: true })); _validateConfigJsonAsync(projectRoot); // Serve the manifest. let manifestHandler = async (req, res) => { try { // We intentionally don't `await`. We want to continue trying even // if there is a potential error in the package.json and don't want to slow // down the request _validateConfigJsonAsync(projectRoot); let { exp: manifest } = await _readConfigJsonAsync(projectRoot); if (!manifest) { throw new Error('No exp.json file found'); } // Get packager opts and then copy into bundleUrlPackagerOpts let packagerOpts = await ProjectSettings.getPackagerOptsAsync(projectRoot); let bundleUrlPackagerOpts = JSON.parse(JSON.stringify(packagerOpts)); bundleUrlPackagerOpts.urlType = 'http'; if (bundleUrlPackagerOpts.hostType === 'redirect') { bundleUrlPackagerOpts.hostType = 'tunnel'; } manifest.xde = true; // deprecated manifest.developer = { tool: Config.developerTool, }; manifest.packagerOpts = packagerOpts; let entryPoint = await Exp.determineEntryPointAsync(projectRoot); let mainModuleName = UrlUtils.guessMainModulePath(entryPoint); let platform = req.headers['exponent-platform'] || 'ios'; let queryParams = UrlUtils.constructBundleQueryParams(packagerOpts); let path = `/${mainModuleName}.bundle?platform=${platform}&${queryParams}`; manifest.bundleUrl = await UrlUtils.constructBundleUrlAsync(projectRoot, bundleUrlPackagerOpts) + path; manifest.debuggerHost = await UrlUtils.constructDebuggerHostAsync(projectRoot); manifest.mainModuleName = mainModuleName; manifest.logUrl = `${await UrlUtils.constructManifestUrlAsync(projectRoot, { urlType: 'http', })}/logs`; let manifestString = JSON.stringify(manifest); let currentUser = await User.getCurrentUserAsync(); if (req.headers['exponent-accept-signature'] && currentUser) { if (_cachedSignedManifest.manifestString === manifestString) { manifestString = _cachedSignedManifest.signedManifest; } else { let publishInfo = await Exp.getPublishInfoAsync(projectRoot); let signedManifest = await Api.callMethodAsync('signManifest', [publishInfo.args], 'post', manifest); _cachedSignedManifest.manifestString = manifestString; _cachedSignedManifest.signedManifest = signedManifest.response; manifestString = signedManifest.response; } } res.send(manifestString); } catch (e) { logDebug(projectRoot, 'exponent', `Error in manifestHandler: ${e} ${e.stack}`); // 5xx = Server Error HTTP code res.status(520).send({"error": e.toString()}); } }; app.get('/', manifestHandler); app.get('/manifest', manifestHandler); app.get('/index.exp', manifestHandler); app.post('/logs', async (req, res) => { let deviceId = req.get('Device-Id'); let deviceName = req.get('Device-Name'); if (deviceId && deviceName && req.body) { _handleDeviceLogs(projectRoot, deviceId, deviceName, req.body); } res.send('Success'); }); let exponentServerPort = await _getFreePortAsync(19000); await ProjectSettings.setPackagerInfoAsync(projectRoot, { exponentServerPort, }); let server = app.listen(exponentServerPort, () => { let host = server.address().address; let port = server.address().port; logDebug(projectRoot, 'exponent', `Local server listening at http://${host}:${port}`); }); _projectRootToExponentServer[projectRoot] = server; await Exp.saveRecentExpRootAsync(projectRoot); } // This only works when called from the same process that called // startExponentServerAsync. export async function stopExponentServerAsync(projectRoot: string) { await _assertLoggedInAsync(); _assertValidProjectRoot(projectRoot); let server = _projectRootToExponentServer[projectRoot]; if (!server) { logDebug(projectRoot, 'exponent', `No Exponent server found for project at ${projectRoot}.`); return; } try { await server.promise.close(); } catch (e) { // don't care if this fails } _projectRootToExponentServer[projectRoot] = null; await ProjectSettings.setPackagerInfoAsync(projectRoot, { exponentServerPort: null, }); } async function _connectToNgrokAsync(projectRoot: string, args: mixed, ngrokPid: ?number, attempts: number = 0) { try { let url = await ngrok.promise.connect(args); return url; } catch (e) { // Attempt to connect 3 times if (attempts >= 2) { throw new Error(JSON.stringify(e)); } if (!attempts) { attempts = 0; } // Attempt to fix the issue if (e.error_code && e.error_code === 103) { // Failed to start tunnel. Might be because url already bound to another session. if (ngrokPid) { try { process.kill(ngrokPid, 'SIGKILL'); } catch (e) { logDebug(projectRoot, 'exponent', `Couldn't kill ngrok with PID ${ngrokPid}`); } } else { await ngrok.promise.kill(); } } // Wait 100ms and then try again await delayAsync(100); return _connectToNgrokAsync(projectRoot, args, null, attempts + 1); } } export async function startTunnelsAsync(projectRoot: string) { await _assertLoggedInAsync(); _assertValidProjectRoot(projectRoot); let packagerInfo = await ProjectSettings.readPackagerInfoAsync(projectRoot); if (!packagerInfo.packagerPort) { throw new XDLError(ErrorCode.NO_PACKAGER_PORT, `No packager found for project at ${projectRoot}.`); } if (!packagerInfo.exponentServerPort) { throw new XDLError(ErrorCode.NO_EXPONENT_SERVER_PORT, `No Exponent server found for project at ${projectRoot}.`); } await stopTunnelsAsync(projectRoot); if (await Android.startAdbReverseAsync(projectRoot)) { logInfo(projectRoot, 'exponent', 'Sucessfully ran `adb reverse`. Localhost urls should work on the connected Android device.'); } let username = await User.getUsernameAsync(); let packageShortName = path.parse(projectRoot).base; if (!username) { username = await Exp.getLoggedOutPlaceholderUsernameAsync(); } let randomness = await Exp.getProjectRandomnessAsync(projectRoot); let hostname = [randomness, UrlUtils.domainify(username), UrlUtils.domainify(packageShortName), Config.ngrok.domain].join('.'); let packagerHostname = `packager.${hostname}`; try { let exponentServerNgrokUrl = await _connectToNgrokAsync(projectRoot, { hostname, authtoken: Config.ngrok.authToken, port: packagerInfo.exponentServerPort, proto: 'http', }, packagerInfo.ngrokPid); let packagerNgrokUrl = await _connectToNgrokAsync(projectRoot, { hostname: packagerHostname, authtoken: Config.ngrok.authToken, port: packagerInfo.packagerPort, proto: 'http', }, packagerInfo.ngrokPid); await ProjectSettings.setPackagerInfoAsync(projectRoot, { exponentServerNgrokUrl, packagerNgrokUrl, ngrokPid: ngrok.process().pid, }); } catch (e) { logError(projectRoot, 'exponent', `Error starting tunnel: ${e.toString()}`); throw e; } } export async function stopTunnelsAsync(projectRoot: string) { await _assertLoggedInAsync(); _assertValidProjectRoot(projectRoot); // This will kill all ngrok tunnels in the process. // We'll need to change this if we ever support more than one project // open at a time in XDE. let packagerInfo = await ProjectSettings.readPackagerInfoAsync(projectRoot); let ngrokProcess = ngrok.process(); let ngrokProcessPid = ngrokProcess ? ngrokProcess.pid : null; if (packagerInfo.ngrokPid && packagerInfo.ngrokPid !== ngrokProcessPid) { // Ngrok is running in some other process. Kill at the os level. try { process.kill(packagerInfo.ngrokPid); } catch (e) { logDebug(projectRoot, 'exponent', `Couldn't kill ngrok with PID ${packagerInfo.ngrokPid}`); } } else { // Ngrok is running from the current process. Kill using ngrok api. await ngrok.promise.kill(); } await ProjectSettings.setPackagerInfoAsync(projectRoot, { exponentServerNgrokUrl: null, packagerNgrokUrl: null, ngrokPid: null, }); await Android.stopAdbReverseAsync(projectRoot); } export async function setOptionsAsync(projectRoot: string, options: { packagerPort?: number }) { await _assertLoggedInAsync(); _assertValidProjectRoot(projectRoot); // Check to make sure all options are valid let schema = joi.object().keys({ packagerPort: joi.number().integer(), }); try { await joi.promise.validate(options, schema); } catch (e) { throw new XDLError(ErrorCode.INVALID_OPTIONS, e.toString()); } await ProjectSettings.setPackagerInfoAsync(projectRoot, options); } export async function getUrlAsync(projectRoot: string, options: Object = {}) { await _assertLoggedInAsync(); _assertValidProjectRoot(projectRoot); return await UrlUtils.constructManifestUrlAsync(projectRoot, options); } export async function startAsync(projectRoot: string, options: Object = {}): Promise<any> { Analytics.logEvent('Start Project', { projectRoot, }); await startExponentServerAsync(projectRoot); await startReactNativeServerAsync(projectRoot, options); await startTunnelsAsync(projectRoot); let { exp } = await _readConfigJsonAsync(projectRoot); return exp; } export async function stopAsync(projectRoot: string): Promise<void> { await stopTunnelsAsync(projectRoot); await stopReactNativeServerAsync(projectRoot); await stopExponentServerAsync(projectRoot); }
src/Project.js
/** * @flow */ import 'instapromise'; import { vsprintf } from 'sprintf-js'; import bodyParser from 'body-parser'; import child_process from 'child_process'; import delayAsync from 'delay-async'; import express from 'express'; import FormData from 'form-data'; import freeportAsync from 'freeport-async'; import fs from 'fs'; import joi from 'joi'; import _ from 'lodash'; import ngrok from 'ngrok'; import path from 'path'; import request from 'request'; import semver from 'semver'; import spawnAsync from '@exponent/spawn-async'; import treekill from 'tree-kill'; import * as Analytics from './Analytics'; import * as Android from './Android'; import Api from './Api'; import Config from './Config'; import ErrorCode from './ErrorCode'; import * as Exp from './Exp'; import Logger from './Logger'; import * as ProjectSettings from './ProjectSettings'; import * as UrlUtils from './UrlUtils'; import * as User from './User'; import * as Versions from './Versions'; import XDLError from './XDLError'; const MINIMUM_BUNDLE_SIZE = 500; const MAX_MESSAGE_LENGTH = 200; let _projectRootToExponentServer = {}; let _projectRootToLogger = {}; type CachedSignedManifest = { manifestString: ?string, signedManifest: ?string, }; let _cachedSignedManifest: CachedSignedManifest = { manifestString: null, signedManifest: null, }; function _getLogger(projectRoot: string) { let logger = _projectRootToLogger[projectRoot]; if (!logger) { logger = Logger.child({type: 'project', project: path.resolve(projectRoot)}); _projectRootToLogger[projectRoot] = logger; } return logger; } function _logWithLevel(projectRoot: string, level: string, object: any, msg: string) { let logger = _getLogger(projectRoot); switch (level) { case 'debug': logger.debug(object, msg); return; case 'info': logger.info(object, msg); return; case 'warn': logger.warn(object, msg); return; case 'error': logger.error(object, msg); return; default: logger.debug(object, msg); return; } } export function logDebug(projectRoot: string, tag: string, message: string) { _getLogger(projectRoot).debug({tag}, message.toString()); } export function logInfo(projectRoot: string, tag: string, message: string) { _getLogger(projectRoot).info({tag}, message.toString()); } export function logError(projectRoot: string, tag: string, message: string) { _getLogger(projectRoot).error({tag}, message.toString()); let truncatedMessage = message.toString(); if (truncatedMessage.length > MAX_MESSAGE_LENGTH) { truncatedMessage = truncatedMessage.substring(0, MAX_MESSAGE_LENGTH); } Analytics.logEvent('Project Error', { projectRoot, tag, message: truncatedMessage, }); } export function attachLoggerStream(projectRoot: string, stream: any) { _getLogger(projectRoot).addStream(stream); } async function _assertLoggedInAsync() { let user = await User.getCurrentUserAsync(); if (!user) { throw new XDLError(ErrorCode.NOT_LOGGED_IN, 'Not logged in'); } } async function _assertValidProjectRoot(projectRoot) { if (!projectRoot) { throw new XDLError(ErrorCode.NO_PROJECT_ROOT, 'No project root specified'); } } async function _getFreePortAsync(rangeStart) { let port = await freeportAsync(rangeStart); if (!port) { throw new XDLError(ErrorCode.NO_PORT_FOUND, 'No available port found'); } return port; } async function _readConfigJsonAsync(projectRoot): Promise<any> { let exp; let pkg; try { pkg = await Exp.packageJsonForRoot(projectRoot).readAsync(); exp = await Exp.expJsonForRoot(projectRoot).readAsync(); } catch (e) { if (e.isJsonFileError) { // TODO: add error codes to json-file if (e.message.startsWith('Error parsing JSON file')) { logError(projectRoot, 'exponent', `Error parsing JSON file: ${e.cause.toString()}`); return { exp: null, pkg: null }; } } // exp or pkg missing } // Easiest bail-out: package.json is missing if (!pkg) { logError(projectRoot, 'exponent', `Error: Can't find package.json`); return { exp: null, pkg: null }; } // Grab our exp config from package.json (legacy) or exp.json if (!exp && pkg.exp) { exp = pkg.exp; logError(projectRoot, 'exponent', `Deprecation Warning: Move your "exp" config from package.json to exp.json.`); } else if (!exp && !pkg.exp) { logError(projectRoot, 'exponent', `Error: Missing exp.json. See https://docs.getexponent.com/`); return { exp: null, pkg: null }; } return { exp, pkg }; } async function _validateConfigJsonAsync(projectRoot: string) { let { exp, pkg } = await _readConfigJsonAsync(projectRoot); if (!exp || !pkg) { // _readConfigJsonAsync already logged an error return; } // sdkVersion is necessary if (!exp.sdkVersion) { logError(projectRoot, 'exponent', `Error: Can't find key exp.sdkVersion in exp.json or package.json. See https://docs.getexponent.com/`); return; } // Warn if sdkVersion is UNVERSIONED let sdkVersion = exp.sdkVersion; if (sdkVersion === 'UNVERSIONED') { logError(projectRoot, 'exponent', `Warning: Using unversioned Exponent SDK. Do not publish until you set sdkVersion in exp.json`); return; } // react-native is required if (!pkg.dependencies || !pkg.dependencies['react-native']) { logError(projectRoot, 'exponent', `Error: Can't find react-native in package.json dependencies`); return; } let sdkVersions = await Api.sdkVersionsAsync(); if (!sdkVersions) { logError(projectRoot, 'exponent', `Error: Couldn't connect to server`); return; } if (!sdkVersions[sdkVersion]) { logError(projectRoot, 'exponent', `Error: Invalid sdkVersion. Valid options are ${_.keys(sdkVersions).join(', ')}`); return; } if (Config.validation.reactNativeVersionWarnings) { let reactNative = pkg.dependencies['react-native']; // Exponent fork of react-native is required if (!reactNative.includes('exponentjs/react-native#')) { logError(projectRoot, 'exponent', `Error: Must use the Exponent fork of react-native. See https://getexponent.com/help`); return; } let reactNativeTag = reactNative.substring(reactNative.lastIndexOf('#') + 1); let sdkVersionObject = sdkVersions[sdkVersion]; // TODO: Want to be smarter about this. Maybe warn if there's a newer version. if (semver.major(Versions.parseSdkVersionFromTag(reactNativeTag)) !== semver.major(Versions.parseSdkVersionFromTag(sdkVersionObject['exponentReactNativeTag']))) { logError(projectRoot, 'exponent', `Error: Invalid version of react-native for sdkVersion ${sdkVersion}. Use github:exponentjs/react-native#${sdkVersionObject['exponentReactNativeTag']}`); return; } } // TODO: Check any native module versions here } async function _getForPlatformAsync(url, platform, { errorCode, minLength }) { let response = await request.promise.get({ url: `${url}&platform=${platform}`, headers: { 'Exponent-Platform': platform, }, }); if (response.statusCode !== 200) { throw new XDLError(errorCode, `Packager returned unexpected code ${response.statusCode}`); } if (!response.body || (minLength && response.body.length < minLength)) { throw new XDLError(errorCode, `Body is: ${response.body}`); } return response.body; } export async function publishAsync(projectRoot: string, options: { quiet: bool } = { quiet: false }) { await _assertLoggedInAsync(); _assertValidProjectRoot(projectRoot); Analytics.logEvent('Publish', { projectRoot, }); let schema = joi.object().keys({ quiet: joi.boolean(), }); try { await joi.promise.validate(options, schema); } catch (e) { throw new XDLError(ErrorCode.INVALID_OPTIONS, e.toString()); } let packagerInfo = await ProjectSettings.readPackagerInfoAsync(projectRoot); if (!packagerInfo.packagerPort) { throw new XDLError(ErrorCode.NO_PACKAGER_PORT, `No packager found for project at ${projectRoot}.`); } let entryPoint = await Exp.determineEntryPointAsync(projectRoot); let publishUrl = await UrlUtils.constructPublishUrlAsync(projectRoot, entryPoint); let assetsUrl = await UrlUtils.constructAssetsUrlAsync(projectRoot, entryPoint); let [ iosBundle, androidBundle, iosAssetsJson, androidAssetsJson, ] = await Promise.all([ _getForPlatformAsync(publishUrl, 'ios', { errorCode: ErrorCode.INVALID_BUNDLE, minLength: MINIMUM_BUNDLE_SIZE, }), _getForPlatformAsync(publishUrl, 'android', { errorCode: ErrorCode.INVALID_BUNDLE, minLength: MINIMUM_BUNDLE_SIZE, }), _getForPlatformAsync(assetsUrl, 'ios', { errorCode: ErrorCode.INVALID_ASSETS, }), _getForPlatformAsync(assetsUrl, 'android', { errorCode: ErrorCode.INVALID_ASSETS, }), ]); let { exp, pkg } = await _readConfigJsonAsync(projectRoot); if (!exp || !pkg) { throw new XDLError(ErrorCode.NO_PACKAGE_JSON, `Couldn't read exp.json file in project at ${projectRoot}`); } // Support version and name being specified in package.json for legacy // support pre: exp.json if (!exp.version && pkg.version) { exp.version = pkg.version; } if (!exp.slug && pkg.name) { exp.slug = pkg.name; } if (exp.android && exp.android.config) { delete exp.android.config; } if (exp.ios && exp.ios.config) { delete exp.ios.config; } // Upload asset files const iosAssets = JSON.parse(iosAssetsJson); const androidAssets = JSON.parse(androidAssetsJson); const assets = iosAssets.concat(androidAssets); if (assets.length > 0 && assets[0].fileHashes) { await uploadAssetsAsync(projectRoot, assets); } let form = new FormData(); form.append('expJson', JSON.stringify(exp)); form.append('iosBundle', iosBundle, { filename: 'iosBundle', }); form.append('androidBundle', androidBundle, { filename: 'androidBundle', }); let response = await Api.callMethodAsync('publish', [options], 'put', form); return response; } // TODO(jesse): Add analytics for upload async function uploadAssetsAsync(projectRoot, assets) { // Collect paths by key, also effectively handles duplicates in the array const paths = {}; assets.forEach(asset => { asset.files.forEach((path, index) => { paths[asset.fileHashes[index]] = path; }); }); // Collect list of assets missing on host const metas = (await Api.callMethodAsync('assetsMetadata', [], 'post', { keys: Object.keys(paths), })).metadata; const missing = Object.keys(paths).filter(key => !metas[key].exists); // Upload them! await Promise.all(_.chunk(missing, 5).map(async (keys) => { let form = new FormData(); keys.forEach(key => { logDebug(projectRoot, 'exponent', `uploading ${paths[key]}`); form.append(key, fs.createReadStream(paths[key]), { filename: paths[key], }); }); await Api.callMethodAsync('uploadAssets', [], 'put', form); })); } export async function buildAsync(projectRoot: string, options: { current?: bool, quiet?: bool, mode?: string, platform?: string, expIds?: Array<string>, } = {}) { await _assertLoggedInAsync(); _assertValidProjectRoot(projectRoot); Analytics.logEvent('Build Shell App', { projectRoot, }); let schema = joi.object().keys({ current: joi.boolean(), quiet: joi.boolean(), mode: joi.string(), platform: joi.any().valid('ios', 'android', 'all'), expIds: joi.array(), }); try { await joi.promise.validate(options, schema); } catch (e) { throw new XDLError(ErrorCode.INVALID_OPTIONS, e.toString()); } let { exp, pkg } = await _readConfigJsonAsync(projectRoot); if (!exp || !pkg) { throw new XDLError(ErrorCode.NO_PACKAGE_JSON, `Couldn't read exp.json file in project at ${projectRoot}`); } // Support version and name being specified in package.json for legacy // support pre: exp.json if (!exp.version && pkg.version) { exp.version = pkg.version; } if (!exp.slug && pkg.name) { exp.slug = pkg.name; } if (options.platform === 'ios' || options.platform === 'all') { if (!exp.ios || !exp.ios.bundleIdentifier) { throw new XDLError(ErrorCode.INVALID_MANIFEST, 'Must specify a bundle identifier in order to build this experience for iOS. Please specify one in exp.json at "ios.bundleIdentifier"'); } } if (options.platform === 'android' || options.platform === 'all') { if (!exp.android || !exp.android.package) { throw new XDLError(ErrorCode.INVALID_MANIFEST, 'Must specify a java package in order to build this experience for Android. Please specify one in exp.json at "android.package"'); } } let response = await Api.callMethodAsync( 'build', [], 'put', { manifest: exp, options, }, ); return response; } async function _waitForRunningAsync(url) { try { let response = await request.promise(url); // Looking for "Cached Bundles" string is hacky, but unfortunately // ngrok returns a 200 when it succeeds but the port it's proxying // isn't bound. if (response.statusCode >= 200 && response.statusCode < 300 && response.body && response.body.includes('Cached Bundles')) { return true; } } catch (e) { // Try again after delay } await delayAsync(100); return _waitForRunningAsync(url); } function _stripPackagerOutputBox(output: string) { let re = /Running packager on port (\d+)/; let found = output.match(re); if (found && found.length >= 2) { return `Running packager on port ${found[1]}\n`; } else { return null; } } function _processPackagerLine(line: string) { let re = /\s*\[\d+\:\d+\:\d+\ (AM)?(PM)?\]\s+/; return line.replace(re, ''); } async function _restartWatchmanAsync(projectRoot: string) { try { let result = await spawnAsync('watchman', ['watch-del-all']); if (result.stdout.includes('roots')) { logInfo(projectRoot, 'exponent', 'Restarted watchman.'); return; } } catch (e) {} logError(projectRoot, 'exponent', 'Attempted to restart watchman but failed. Please try running `watchman watch-del-all`.'); } function _logPackagerOutput(projectRoot: string, data: Object) { let output = data.toString(); if (output.includes('─────')) { output = _stripPackagerOutputBox(output); if (output) { logInfo(projectRoot, 'exponent', output); } return; } if (!output) { return; } // Fix watchman if it's being dumb if (output.includes('watchman watch-del')) { _restartWatchmanAsync(projectRoot); return; } let lines = output.split(/\r?\n/); for (let i = 0; i < lines.length; i++) { lines[i] = _processPackagerLine(lines[i]); } output = lines.join('\n'); logInfo(projectRoot, 'packager', output); } function _handleDeviceLogs(projectRoot: string, deviceId: string, deviceName: string, logs: any) { for (let i = 0; i < logs.length; i++) { let log = logs[i]; let bodyArray = []; if (typeof log.body === 'string') { bodyArray.push(log.body); } else { // body is in this format: // { 0: 'stuff', 1: 'more stuff' } // so convert to an array first let j = 0; while (log.body[j]) { bodyArray.push(log.body[j]); j++; } } let string; if (bodyArray[0] && typeof bodyArray[0] === 'string' && bodyArray[0].includes('%')) { string = vsprintf(bodyArray[0], bodyArray.slice(1)); } else { string = bodyArray.map(obj => { if (!obj) { return 'null'; } if (typeof obj === 'string' || typeof obj === 'number' || typeof obj === 'boolean') { return obj; } try { return JSON.stringify(obj); } catch (e) { return obj.toString(); } }).join(' '); } let level = log.level; let groupDepth = log.groupDepth; let shouldHide = log.shouldHide; _logWithLevel(projectRoot, level, { tag: 'device', deviceId, deviceName, groupDepth, shouldHide, }, string); } } export async function startReactNativeServerAsync(projectRoot: string, options: Object = {}) { await _assertLoggedInAsync(); _assertValidProjectRoot(projectRoot); await stopReactNativeServerAsync(projectRoot); let packagerPort = await _getFreePortAsync(19001); let exp = await Exp.expConfigForRootAsync(projectRoot); // Create packager options let packagerOpts = { port: packagerPort, projectRoots: projectRoot, assetRoots: projectRoot, }; const userPackagerOpts = _.get(exp, 'packagerOpts'); if (userPackagerOpts) { packagerOpts = { ...packagerOpts, ...userPackagerOpts, }; } let cliOpts = _.reduce(packagerOpts, (opts, val, key) => { if (val && val !== '') { opts.push(`--${key}`, val); } return opts; }, ['start']); if (options.reset) { cliOpts.push('--reset-cache'); } // Get custom CLI path from project package.json, but fall back to node_module path let defaultCliPath = path.join(projectRoot, 'node_modules/react-native/local-cli/cli.js'); const cliPath = _.get(exp, 'rnCliPath', defaultCliPath); // Run the copy of Node that's embedded in Electron by setting the // ELECTRON_RUN_AS_NODE environment variable // Note: the CLI script sets up graceful-fs and sets ulimit to 4096 in the // child process let packagerProcess = child_process.fork(cliPath, cliOpts, { cwd: projectRoot, env: { ...process.env, NODE_PATH: null, ELECTRON_RUN_AS_NODE: 1, }, silent: true, }); await ProjectSettings.setPackagerInfoAsync(projectRoot, { packagerPort, packagerPid: packagerProcess.pid, }); // TODO: do we need this? don't know if it's ever called process.on('exit', () => { treekill(packagerProcess.pid); }); packagerProcess.stdout.setEncoding('utf8'); packagerProcess.stderr.setEncoding('utf8'); packagerProcess.stdout.on('data', (data) => { _logPackagerOutput(projectRoot, data); }); packagerProcess.stderr.on('data', (data) => { logError(projectRoot, 'packager', data.toString()); }); packagerProcess.on('exit', async (code) => { logDebug(projectRoot, 'exponent', `packager process exited with code ${code}`); }); let packagerUrl = await UrlUtils.constructBundleUrlAsync(projectRoot, { urlType: 'http', hostType: 'localhost', }); await _waitForRunningAsync(`${packagerUrl}/debug`); } export async function stopReactNativeServerAsync(projectRoot: string) { await _assertLoggedInAsync(); _assertValidProjectRoot(projectRoot); let packagerInfo = await ProjectSettings.readPackagerInfoAsync(projectRoot); if (!packagerInfo.packagerPort || !packagerInfo.packagerPid) { logDebug(projectRoot, 'exponent', `No packager found for project at ${projectRoot}.`); return; } logDebug(projectRoot, 'exponent', `Killing packager process tree: ${packagerInfo.packagerPid}`); try { await treekill.promise(packagerInfo.packagerPid, 'SIGKILL'); } catch (e) { logDebug(projectRoot, 'exponent', `Error stopping packager process: ${e.toString()}`); } await ProjectSettings.setPackagerInfoAsync(projectRoot, { packagerPort: null, packagerPid: null, }); } export async function startExponentServerAsync(projectRoot: string) { await _assertLoggedInAsync(); _assertValidProjectRoot(projectRoot); let { exp, pkg } = await _readConfigJsonAsync(projectRoot); if (!exp || !pkg) { // TODO: actually say the correct file name when _readConfigJsonAsync is simpler throw new Error('Error with package.json or exp.json'); } await stopExponentServerAsync(projectRoot); let app = express(); app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: true })); _validateConfigJsonAsync(projectRoot); // Serve the manifest. let manifestHandler = async (req, res) => { try { // We intentionally don't `await`. We want to continue trying even // if there is a potential error in the package.json and don't want to slow // down the request _validateConfigJsonAsync(projectRoot); let { exp: manifest } = await _readConfigJsonAsync(projectRoot); if (!manifest) { throw new Error('No exp.json file found'); } // Get packager opts and then copy into bundleUrlPackagerOpts let packagerOpts = await ProjectSettings.getPackagerOptsAsync(projectRoot); let bundleUrlPackagerOpts = JSON.parse(JSON.stringify(packagerOpts)); bundleUrlPackagerOpts.urlType = 'http'; if (bundleUrlPackagerOpts.hostType === 'redirect') { bundleUrlPackagerOpts.hostType = 'tunnel'; } manifest.xde = true; // deprecated manifest.developer = { tool: Config.developerTool, }; manifest.packagerOpts = packagerOpts; let entryPoint = await Exp.determineEntryPointAsync(projectRoot); let mainModuleName = UrlUtils.guessMainModulePath(entryPoint); let platform = req.headers['exponent-platform'] || 'ios'; let queryParams = UrlUtils.constructBundleQueryParams(packagerOpts); let path = `/${mainModuleName}.bundle?platform=${platform}&${queryParams}`; manifest.bundleUrl = await UrlUtils.constructBundleUrlAsync(projectRoot, bundleUrlPackagerOpts) + path; manifest.debuggerHost = await UrlUtils.constructDebuggerHostAsync(projectRoot); manifest.mainModuleName = mainModuleName; manifest.logUrl = `${await UrlUtils.constructManifestUrlAsync(projectRoot, { urlType: 'http', })}/logs`; let manifestString = JSON.stringify(manifest); let currentUser = await User.getCurrentUserAsync(); if (req.headers['exponent-accept-signature'] && currentUser) { if (_cachedSignedManifest.manifestString === manifestString) { manifestString = _cachedSignedManifest.signedManifest; } else { let publishInfo = await Exp.getPublishInfoAsync(projectRoot); let signedManifest = await Api.callMethodAsync('signManifest', [publishInfo.args], 'post', manifest); _cachedSignedManifest.manifestString = manifestString; _cachedSignedManifest.signedManifest = signedManifest.response; manifestString = signedManifest.response; } } res.send(manifestString); } catch (e) { logDebug(projectRoot, 'exponent', `Error in manifestHandler: ${e} ${e.stack}`); // 5xx = Server Error HTTP code res.status(520).send({"error": e.toString()}); } }; app.get('/', manifestHandler); app.get('/manifest', manifestHandler); app.get('/index.exp', manifestHandler); app.post('/logs', async (req, res) => { let deviceId = req.get('Device-Id'); let deviceName = req.get('Device-Name'); if (deviceId && deviceName && req.body) { _handleDeviceLogs(projectRoot, deviceId, deviceName, req.body); } res.send('Success'); }); let exponentServerPort = await _getFreePortAsync(19000); await ProjectSettings.setPackagerInfoAsync(projectRoot, { exponentServerPort, }); let server = app.listen(exponentServerPort, () => { let host = server.address().address; let port = server.address().port; logDebug(projectRoot, 'exponent', `Local server listening at http://${host}:${port}`); }); _projectRootToExponentServer[projectRoot] = server; await Exp.saveRecentExpRootAsync(projectRoot); } // This only works when called from the same process that called // startExponentServerAsync. export async function stopExponentServerAsync(projectRoot: string) { await _assertLoggedInAsync(); _assertValidProjectRoot(projectRoot); let server = _projectRootToExponentServer[projectRoot]; if (!server) { logDebug(projectRoot, 'exponent', `No Exponent server found for project at ${projectRoot}.`); return; } try { await server.promise.close(); } catch (e) { // don't care if this fails } _projectRootToExponentServer[projectRoot] = null; await ProjectSettings.setPackagerInfoAsync(projectRoot, { exponentServerPort: null, }); } async function _connectToNgrokAsync(projectRoot: string, args: mixed, ngrokPid: ?number, attempts: number = 0) { try { let url = await ngrok.promise.connect(args); return url; } catch (e) { // Attempt to connect 3 times if (attempts >= 2) { throw new Error(JSON.stringify(e)); } if (!attempts) { attempts = 0; } // Attempt to fix the issue if (e.error_code && e.error_code === 103) { // Failed to start tunnel. Might be because url already bound to another session. if (ngrokPid) { try { process.kill(ngrokPid, 'SIGKILL'); } catch (e) { logDebug(projectRoot, 'exponent', `Couldn't kill ngrok with PID ${ngrokPid}`); } } else { await ngrok.promise.kill(); } } // Wait 100ms and then try again await delayAsync(100); return _connectToNgrokAsync(projectRoot, args, null, attempts + 1); } } export async function startTunnelsAsync(projectRoot: string) { await _assertLoggedInAsync(); _assertValidProjectRoot(projectRoot); let packagerInfo = await ProjectSettings.readPackagerInfoAsync(projectRoot); if (!packagerInfo.packagerPort) { throw new XDLError(ErrorCode.NO_PACKAGER_PORT, `No packager found for project at ${projectRoot}.`); } if (!packagerInfo.exponentServerPort) { throw new XDLError(ErrorCode.NO_EXPONENT_SERVER_PORT, `No Exponent server found for project at ${projectRoot}.`); } await stopTunnelsAsync(projectRoot); if (await Android.startAdbReverseAsync(projectRoot)) { logInfo(projectRoot, 'exponent', 'Sucessfully ran `adb reverse`. Localhost urls should work on the connected Android device.'); } let username = await User.getUsernameAsync(); let packageShortName = path.parse(projectRoot).base; if (!username) { username = await Exp.getLoggedOutPlaceholderUsernameAsync(); } let randomness = await Exp.getProjectRandomnessAsync(projectRoot); let hostname = [randomness, UrlUtils.domainify(username), UrlUtils.domainify(packageShortName), Config.ngrok.domain].join('.'); let packagerHostname = `packager.${hostname}`; try { let exponentServerNgrokUrl = await _connectToNgrokAsync(projectRoot, { hostname, authtoken: Config.ngrok.authToken, port: packagerInfo.exponentServerPort, proto: 'http', }, packagerInfo.ngrokPid); let packagerNgrokUrl = await _connectToNgrokAsync(projectRoot, { hostname: packagerHostname, authtoken: Config.ngrok.authToken, port: packagerInfo.packagerPort, proto: 'http', }, packagerInfo.ngrokPid); await ProjectSettings.setPackagerInfoAsync(projectRoot, { exponentServerNgrokUrl, packagerNgrokUrl, ngrokPid: ngrok.process().pid, }); } catch (e) { logError(projectRoot, 'exponent', `Error starting tunnel: ${e.toString()}`); throw e; } } export async function stopTunnelsAsync(projectRoot: string) { await _assertLoggedInAsync(); _assertValidProjectRoot(projectRoot); // This will kill all ngrok tunnels in the process. // We'll need to change this if we ever support more than one project // open at a time in XDE. let packagerInfo = await ProjectSettings.readPackagerInfoAsync(projectRoot); let ngrokProcess = ngrok.process(); let ngrokProcessPid = ngrokProcess ? ngrokProcess.pid : null; if (packagerInfo.ngrokPid && packagerInfo.ngrokPid !== ngrokProcessPid) { // Ngrok is running in some other process. Kill at the os level. try { process.kill(packagerInfo.ngrokPid); } catch (e) { logDebug(projectRoot, 'exponent', `Couldn't kill ngrok with PID ${packagerInfo.ngrokPid}`); } } else { // Ngrok is running from the current process. Kill using ngrok api. await ngrok.promise.kill(); } await ProjectSettings.setPackagerInfoAsync(projectRoot, { exponentServerNgrokUrl: null, packagerNgrokUrl: null, ngrokPid: null, }); await Android.stopAdbReverseAsync(projectRoot); } export async function setOptionsAsync(projectRoot: string, options: { packagerPort?: number }) { await _assertLoggedInAsync(); _assertValidProjectRoot(projectRoot); // Check to make sure all options are valid let schema = joi.object().keys({ packagerPort: joi.number().integer(), }); try { await joi.promise.validate(options, schema); } catch (e) { throw new XDLError(ErrorCode.INVALID_OPTIONS, e.toString()); } await ProjectSettings.setPackagerInfoAsync(projectRoot, options); } export async function getUrlAsync(projectRoot: string, options: Object = {}) { await _assertLoggedInAsync(); _assertValidProjectRoot(projectRoot); return await UrlUtils.constructManifestUrlAsync(projectRoot, options); } export async function startAsync(projectRoot: string, options: Object = {}): Promise<any> { Analytics.logEvent('Start Project', { projectRoot, }); await startExponentServerAsync(projectRoot); await startReactNativeServerAsync(projectRoot, options); await startTunnelsAsync(projectRoot); let { exp } = await _readConfigJsonAsync(projectRoot); return exp; } export async function stopAsync(projectRoot: string): Promise<void> { await stopTunnelsAsync(projectRoot); await stopReactNativeServerAsync(projectRoot); await stopExponentServerAsync(projectRoot); }
SDK 7. Remove SDK 2, 4. Fix XDL watchman restarting. fbshipit-source-id: e3f0b90
src/Project.js
SDK 7. Remove SDK 2, 4. Fix XDL watchman restarting.
<ide><path>rc/Project.js <ide> logError(projectRoot, 'exponent', 'Attempted to restart watchman but failed. Please try running `watchman watch-del-all`.'); <ide> } <ide> <del>function _logPackagerOutput(projectRoot: string, data: Object) { <add>function _logPackagerOutput(projectRoot: string, level: string, data: Object) { <ide> let output = data.toString(); <ide> if (output.includes('─────')) { <ide> output = _stripPackagerOutputBox(output); <ide> } <ide> output = lines.join('\n'); <ide> <del> logInfo(projectRoot, 'packager', output); <add> if (level === 'info') { <add> logInfo(projectRoot, 'packager', output); <add> } else { <add> logError(projectRoot, 'packager', output); <add> } <ide> } <ide> <ide> function _handleDeviceLogs(projectRoot: string, deviceId: string, deviceName: string, logs: any) { <ide> packagerProcess.stdout.setEncoding('utf8'); <ide> packagerProcess.stderr.setEncoding('utf8'); <ide> packagerProcess.stdout.on('data', (data) => { <del> _logPackagerOutput(projectRoot, data); <add> _logPackagerOutput(projectRoot, 'info', data); <ide> }); <ide> <ide> packagerProcess.stderr.on('data', (data) => { <del> logError(projectRoot, 'packager', data.toString()); <add> _logPackagerOutput(projectRoot, 'error', data); <ide> }); <ide> <ide> packagerProcess.on('exit', async (code) => {
Java
bsd-3-clause
8494702f2bd344de90859b7790d1d75290555016
0
lockss/lockss-daemon,lockss/lockss-daemon,edina/lockss-daemon,edina/lockss-daemon,edina/lockss-daemon,edina/lockss-daemon,lockss/lockss-daemon,lockss/lockss-daemon,lockss/lockss-daemon,edina/lockss-daemon,lockss/lockss-daemon,edina/lockss-daemon,edina/lockss-daemon,lockss/lockss-daemon
/* * $Id: TestSiamHtmlLinkExtractorFactory.java,v 1.2 2013-08-30 22:45:58 alexandraohlson Exp $ */ /* Copyright (c) 2000-2013 Board of Trustees of Leland Stanford Jr. University, all rights reserved. Permission is hereby granted, free of charge, to any person obtaining a copy of his software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL STANFORD UNIVERSITY BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. Except as contained in this notice, the name of Stanford University shall not be used in advertising or otherwise to promote the sale, use or other dealings in this Software without prior written authorization from Stanford University. */ package org.lockss.plugin.atypon.siam; import java.util.HashSet; import java.util.Set; import org.lockss.plugin.UrlNormalizer; import org.lockss.plugin.atypon.BaseAtyponUrlNormalizer; import org.lockss.extractor.LinkExtractor; import org.lockss.extractor.RegexpCssLinkExtractor; import org.lockss.test.LockssTestCase; import org.lockss.test.MockArchivalUnit; import org.lockss.test.MockCachedUrl; import org.lockss.util.Constants; import org.lockss.util.SetUtil; public class TestSiamHtmlLinkExtractorFactory extends LockssTestCase { UrlNormalizer normalizer = new BaseAtyponUrlNormalizer(); private SiamHtmlLinkExtractorFactory fact; private LinkExtractor m_extractor; private MyLinkExtractorCallback m_callback; static String ENC = Constants.DEFAULT_ENCODING; private MockArchivalUnit m_mau; private final String SIAM_BASE_URL = "http://epubs.siam.org/"; private static final String DOI_START = "11.1111"; private static final String DOI_END = "TEST"; private static final String citationForm= "<html><head><title>Test Title</title></head><body>" + "<div>" + " <br />" + " <!-- download options -->" + " <form action=\"/action/downloadCitation\" name=\"frmCitmgr\" method=\"post\" target=\"_self\"><input type=\"hidden\" name=\"doi\" value=\"" + DOI_START + "/" + DOI_END + "\" />" + " <input type=\"hidden\" name=\"downloadFileName\" value=\"siam_siread52_1\" />" + " <input type='hidden' name='include' value='cit' />" + " <table summary=\"\">" + " <tr class=\"formats\"><th>Format</th>" + " <td>" + " <input type=\"radio\" name=\"format\" value=\"ris\" id=\"ris\" onclick=\"toggleImport(this);\" checked>" + " <label for=\"ris\">RIS (ProCite, Reference Manager)</label><br />" + " <input type=\"radio\" name=\"format\" value=\"endnote\" id=\"endnote\" onclick=\"toggleImport(this);\">" + " <label for=\"endnote\">EndNote</label><br />" + " <input type=\"radio\" name=\"format\" value=\"bibtex\" id=\"bibtex\" onclick=\"toggleImport(this);\" />" + " <label for=\"bibtex\">BibTex</label><br />" + " <input type=\"radio\" name=\"format\" value=\"medlars\" id=\"medlars\" onclick=\"toggleImport(this);\"/>" + " <label for=\"medlars\">Medlars</label><br />" + " <input type=\"radio\" name=\"format\" value=\"refworks\" id=\"refworks\" onclick=\"toggleimport(this);\">" + " <label for=\"refworks\">RefWorks</label><br />" + " <input type=\"radio\" name=\"format\" value=\"refworks-cn\" id=\"refworks-cn\" onclick=\"toggleimport(this);\">" + " <label for=\"refworks-cn\">RefWorks (China)</label>" + " </td>" + " </tr>" + " <tr class=\"directImport\"><th><label for=\"direct\">Direct import</label></th>" + " <td><input type='checkbox' name='direct' id='direct' checked=\"checked\" /></td>" + " </tr>" + " <tr>" + " <td class=\"submit\" colspan='2'>" + " <input type='submit' name='submit' value='Download publication citation data' onclick=\"onCitMgrSubmit()\" class=\"formbutton\"/>" + " </td>" + " </tr>" + " </table>" + " </form>" + "</div>" + "</body>" + "</html>"; @Override public void setUp() throws Exception { super.setUp(); m_mau = new MockArchivalUnit(); m_callback = new MyLinkExtractorCallback(); fact = new SiamHtmlLinkExtractorFactory(); m_extractor = fact.createLinkExtractor("html"); } Set<String> expectedUrls; public void testCitationsForm() throws Exception { expectedUrls = SetUtil.set( SIAM_BASE_URL + "action/downloadCitation?doi=" + DOI_START + "%2F" + DOI_END + "&format=ris&include=cit", SIAM_BASE_URL + "action/downloadCitation?doi=" + DOI_START + "%2F" + DOI_END + "&format=bibtex&include=cit", SIAM_BASE_URL + "action/downloadCitation?doi=" + DOI_START + "%2F" + DOI_END + "&format=endnote&include=cit", SIAM_BASE_URL + "action/downloadCitation?doi=" + DOI_START + "%2F" + DOI_END + "&format=medlars&include=cit"); String norm_url; Set<String> result_strings = parseSingleSource(citationForm); Set<String> norm_urls = new HashSet<String>(); // if the additional SIAM restriction didn't work, you would end up with 12 URLS due to duplication // refworks and refworks-cn is restricted out by base atypon assertEquals(4, result_strings.size()); for (String url : result_strings) { norm_url = normalizer.normalizeUrl(url, m_mau); //log.info("normalized citation form URL: " + norm_url); norm_urls.add(norm_url); } assertEquals(expectedUrls,norm_urls); } private Set<String> parseSingleSource(String source) throws Exception { MockArchivalUnit m_mau = new MockArchivalUnit(); LinkExtractor ue = new RegexpCssLinkExtractor(); m_mau.setLinkExtractor("text/css", ue); MockCachedUrl mcu = new org.lockss.test.MockCachedUrl("http://epubs.siam.org/", m_mau); mcu.setContent(source); m_callback.reset(); m_extractor.extractUrls(m_mau, new org.lockss.test.StringInputStream(source), ENC, SIAM_BASE_URL, m_callback); return m_callback.getFoundUrls(); } private static class MyLinkExtractorCallback implements LinkExtractor.Callback { Set<String> foundUrls = new java.util.HashSet<String>(); public void foundLink(String url) { foundUrls.add(url); } public Set<String> getFoundUrls() { return foundUrls; } public void reset() { foundUrls = new java.util.HashSet<String>(); } } }
plugins/test/src/org/lockss/plugin/atypon/siam/TestSiamHtmlLinkExtractorFactory.java
/* * $Id: TestSiamHtmlLinkExtractorFactory.java,v 1.1 2013-07-31 21:43:57 alexandraohlson Exp $ */ /* Copyright (c) 2000-2013 Board of Trustees of Leland Stanford Jr. University, all rights reserved. Permission is hereby granted, free of charge, to any person obtaining a copy of his software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL STANFORD UNIVERSITY BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. Except as contained in this notice, the name of Stanford University shall not be used in advertising or otherwise to promote the sale, use or other dealings in this Software without prior written authorization from Stanford University. */ package org.lockss.plugin.atypon.siam; import java.util.HashSet; import java.util.Set; import org.lockss.plugin.UrlNormalizer; import org.lockss.plugin.atypon.BaseAtyponUrlNormalizer; import org.lockss.extractor.LinkExtractor; import org.lockss.extractor.RegexpCssLinkExtractor; import org.lockss.test.LockssTestCase; import org.lockss.test.MockArchivalUnit; import org.lockss.test.MockCachedUrl; import org.lockss.util.Constants; import org.lockss.util.SetUtil; public class TestSiamHtmlLinkExtractorFactory extends LockssTestCase { UrlNormalizer normalizer = new BaseAtyponUrlNormalizer(); private SiamHtmlLinkExtractorFactory fact; private LinkExtractor m_extractor; private MyLinkExtractorCallback m_callback; static String ENC = Constants.DEFAULT_ENCODING; private MockArchivalUnit m_mau; private final String SIAM_BASE_URL = "http://epubs.siam.org/"; private static final String DOI_START = "11.1111"; private static final String DOI_END = "TEST"; private static final String citationForm= "<html><head><title>Test Title</title></head><body>" + "<div>" + " <br />" + " <!-- download options -->" + " <form action=\"/action/downloadCitation\" name=\"frmCitmgr\" method=\"post\" target=\"_self\"><input type=\"hidden\" name=\"doi\" value=\"" + DOI_START + "/" + DOI_END + "\" />" + " <input type=\"hidden\" name=\"downloadFileName\" value=\"siam_siread52_1\" />" + " <input type='hidden' name='include' value='cit' />" + " <table summary=\"\">" + " <tr class=\"formats\"><th>Format</th>" + " <td>" + " <input type=\"radio\" name=\"format\" value=\"ris\" id=\"ris\" onclick=\"toggleImport(this);\" checked>" + " <label for=\"ris\">RIS (ProCite, Reference Manager)</label><br />" + " <input type=\"radio\" name=\"format\" value=\"endnote\" id=\"endnote\" onclick=\"toggleImport(this);\">" + " <label for=\"endnote\">EndNote</label><br />" + " <input type=\"radio\" name=\"format\" value=\"bibtex\" id=\"bibtex\" onclick=\"toggleImport(this);\" />" + " <label for=\"bibtex\">BibTex</label><br />" + " <input type=\"radio\" name=\"format\" value=\"medlars\" id=\"medlars\" onclick=\"toggleImport(this);\"/>" + " <label for=\"medlars\">Medlars</label><br />" + " <input type=\"radio\" name=\"format\" value=\"refworks\" id=\"refworks\" onclick=\"toggleimport(this);\">" + " <label for=\"refworks\">RefWorks</label><br />" + " <input type=\"radio\" name=\"format\" value=\"refworks-cn\" id=\"refworks-cn\" onclick=\"toggleimport(this);\">" + " <label for=\"refworks-cn\">RefWorks (China)</label>" + " </td>" + " </tr>" + " <tr class=\"directImport\"><th><label for=\"direct\">Direct import</label></th>" + " <td><input type='checkbox' name='direct' id='direct' checked=\"checked\" /></td>" + " </tr>" + " <tr>" + " <td class=\"submit\" colspan='2'>" + " <input type='submit' name='submit' value='Download publication citation data' onclick=\"onCitMgrSubmit()\" class=\"formbutton\"/>" + " </td>" + " </tr>" + " </table>" + " </form>" + "</div>" + "</body>" + "</html>"; @Override public void setUp() throws Exception { super.setUp(); m_mau = new MockArchivalUnit(); m_callback = new MyLinkExtractorCallback(); fact = new SiamHtmlLinkExtractorFactory(); m_extractor = fact.createLinkExtractor("html"); } Set<String> expectedUrls; public void testCitationsForm() throws Exception { expectedUrls = SetUtil.set( SIAM_BASE_URL + "action/downloadCitation?doi=" + DOI_START + "%2F" + DOI_END + "&format=ris&include=cit", SIAM_BASE_URL + "action/downloadCitation?doi=" + DOI_START + "%2F" + DOI_END + "&format=bibtex&include=cit", SIAM_BASE_URL + "action/downloadCitation?doi=" + DOI_START + "%2F" + DOI_END + "&format=refworks&include=cit", SIAM_BASE_URL + "action/downloadCitation?doi=" + DOI_START + "%2F" + DOI_END + "&format=refworks-cn&include=cit", SIAM_BASE_URL + "action/downloadCitation?doi=" + DOI_START + "%2F" + DOI_END + "&format=endnote&include=cit", SIAM_BASE_URL + "action/downloadCitation?doi=" + DOI_START + "%2F" + DOI_END + "&format=medlars&include=cit"); String norm_url; Set<String> result_strings = parseSingleSource(citationForm); Set<String> norm_urls = new HashSet<String>(); // if the additional SIAM restriction didn't work, you would end up with 12 URLS due to duplication assertEquals(6, result_strings.size()); for (String url : result_strings) { norm_url = normalizer.normalizeUrl(url, m_mau); //log.info("normalized citation form URL: " + norm_url); norm_urls.add(norm_url); } assertEquals(expectedUrls,norm_urls); } private Set<String> parseSingleSource(String source) throws Exception { MockArchivalUnit m_mau = new MockArchivalUnit(); LinkExtractor ue = new RegexpCssLinkExtractor(); m_mau.setLinkExtractor("text/css", ue); MockCachedUrl mcu = new org.lockss.test.MockCachedUrl("http://epubs.siam.org/", m_mau); mcu.setContent(source); m_callback.reset(); m_extractor.extractUrls(m_mau, new org.lockss.test.StringInputStream(source), ENC, SIAM_BASE_URL, m_callback); return m_callback.getFoundUrls(); } private static class MyLinkExtractorCallback implements LinkExtractor.Callback { Set<String> foundUrls = new java.util.HashSet<String>(); public void foundLink(String url) { foundUrls.add(url); } public Set<String> getFoundUrls() { return foundUrls; } public void reset() { foundUrls = new java.util.HashSet<String>(); } } }
and more test adjusted to take in to account the additional form restriction... git-svn-id: 293778eaa97c8c94097d610b1bd5133a8f478f36@29628 4f837ed2-42f5-46e7-a7a5-fa17313484d4
plugins/test/src/org/lockss/plugin/atypon/siam/TestSiamHtmlLinkExtractorFactory.java
and more test adjusted to take in to account the additional form restriction...
<ide><path>lugins/test/src/org/lockss/plugin/atypon/siam/TestSiamHtmlLinkExtractorFactory.java <ide> /* <del> * $Id: TestSiamHtmlLinkExtractorFactory.java,v 1.1 2013-07-31 21:43:57 alexandraohlson Exp $ <add> * $Id: TestSiamHtmlLinkExtractorFactory.java,v 1.2 2013-08-30 22:45:58 alexandraohlson Exp $ <ide> */ <ide> /* <ide> <ide> expectedUrls = SetUtil.set( <ide> SIAM_BASE_URL + "action/downloadCitation?doi=" + DOI_START + "%2F" + DOI_END + "&format=ris&include=cit", <ide> SIAM_BASE_URL + "action/downloadCitation?doi=" + DOI_START + "%2F" + DOI_END + "&format=bibtex&include=cit", <del> SIAM_BASE_URL + "action/downloadCitation?doi=" + DOI_START + "%2F" + DOI_END + "&format=refworks&include=cit", <del> SIAM_BASE_URL + "action/downloadCitation?doi=" + DOI_START + "%2F" + DOI_END + "&format=refworks-cn&include=cit", <ide> SIAM_BASE_URL + "action/downloadCitation?doi=" + DOI_START + "%2F" + DOI_END + "&format=endnote&include=cit", <ide> SIAM_BASE_URL + "action/downloadCitation?doi=" + DOI_START + "%2F" + DOI_END + "&format=medlars&include=cit"); <ide> String norm_url; <ide> Set<String> norm_urls = new HashSet<String>(); <ide> <ide> // if the additional SIAM restriction didn't work, you would end up with 12 URLS due to duplication <del> assertEquals(6, result_strings.size()); <add> // refworks and refworks-cn is restricted out by base atypon <add> assertEquals(4, result_strings.size()); <ide> <ide> for (String url : result_strings) { <ide> norm_url = normalizer.normalizeUrl(url, m_mau);
JavaScript
mpl-2.0
bcbc6f5766a218c82e3d3746f95b5c822c936f5c
0
mozilla/talkilla,mozilla/talkilla,mozilla/talkilla
/* jshint expr:true */ "use strict"; /* The intent is for this to only add unit tests to this file going forward. * * XXX Before long, we're going to want to create a home for backend functional * tests, and move many of the tests that current live in this file there. */ var EventEmitter = require( "events" ).EventEmitter; var chai = require("chai"); var expect = chai.expect; var sinon = require("sinon"); var https = require("https"); chai.Assertion.includeStack = true; require("../../server/server"); var presence = require("../../server/presence"); var User = require("../../server/users").User; var logger = require("../../server/logger"); var config = require('../../server/config').config; describe("presence", function() { var sandbox; var api = presence.api; var users = presence._users; beforeEach(function() { sandbox = sinon.sandbox.create(); }); afterEach(function() { users.forEach(function(user) { users.remove(user.nick); }); sandbox.restore(); }); describe("api", function() { // XXX: this method is private but critical. That's why we have // test coverage for it. In the future we might pull it out into a // separate object as a way to separate concerns. describe("#_verifyAssertion", function() { var oldEnv; before(function() { oldEnv = process.env.NODE_ENV; process.env.NODE_ENV = "development"; }); after(function() { process.env.NODE_ENV = oldEnv; }); it("should send a secure http request to the verifier service", function() { var request = {write: function() {}, end: function() {}}; var options = { host: "verifier.login.persona.org", path: "/verify", method: "POST" }; sandbox.stub(https, "request").returns(request); api._verifyAssertion("fake assertion data", function() {}); sinon.assert.calledOnce(https.request); sinon.assert.calledWith(https.request, sinon.match(options)); }); it("should trigger without error if the assertion is valid", function() { var assertionCallback = sinon.spy(); var response = new EventEmitter(); var request = {write: function() {}, end: function() {}}; var answer = { status: "okay", email: "[email protected]" }; response.setEncoding = function() {}; sandbox.stub(https, "request", function(options, callback) { callback(response); return request; }); api._verifyAssertion("fake assertion data", assertionCallback); response.emit("data", JSON.stringify(answer)); response.emit("end"); sinon.assert.calledOnce(assertionCallback); sinon.assert.calledWithExactly( assertionCallback, null, answer.email); }); it("should trigger with an error if the assertion is invalid", function() { var assertionCallback = sinon.spy(); var response = new EventEmitter(); var request = {write: function() {}, end: function() {}}; var answer = { status: "not okay", reason: "invalid assertion" }; response.setEncoding = function() {}; sandbox.stub(https, "request", function(options, callback) { callback(response); return request; }); api._verifyAssertion("fake assertion data", assertionCallback); response.emit("data", JSON.stringify(answer)); response.emit("end"); sinon.assert.calledOnce(assertionCallback); sinon.assert.calledWithExactly( assertionCallback, answer.reason); }); }); describe("#signin", function() { it("should return the nick", function(done) { var req = {body: {assertion: "fake assertion"}, session: {}}; var res = {send: sinon.spy()}; var answer = JSON.stringify({nick: "foo"}); sandbox.stub(presence.api, "_verifyAssertion", function(a, c) { c(null, "foo"); sinon.assert.calledOnce(res.send); sinon.assert.calledWithExactly(res.send, 200, answer); done(); }); api.signin(req, res); }); it("should return a 400 if the assertion was invalid", function(done) { var req = {body: {assertion: "fake assertion"}, session: {}}; var res = {send: sinon.spy()}; var answer = JSON.stringify({error: "invalid assertion"}); sandbox.stub(presence.api, "_verifyAssertion", function(a, c) { c("invalid assertion"); expect(users.get("foo")).to.equal(undefined); sinon.assert.calledOnce(res.send); sinon.assert.calledWithExactly(res.send, 400, answer); done(); }); api.signin(req, res); }); }); describe("#signout", function() { it("should send the user's long poll connection a disconnect event", function() { sandbox.stub(User.prototype, "send"); var req = {session: {email: "foo", reset: function() {}}}; var res = {send: function() {}}; users.add("foo"); api.signout(req, res); sinon.assert.calledOnce(User.prototype.send); sinon.assert.calledWithExactly(User.prototype.send, "disconnect", null); }); it("should disconnect the user", function() { sandbox.stub(User.prototype, "disconnect"); var req = {session: {email: "foo", reset: function() {}}}; var res = {send: sinon.spy()}; users.add("foo"); api.signout(req, res); sinon.assert.calledOnce(User.prototype.disconnect); sinon.assert.calledOnce(res.send); sinon.assert.calledWith(res.send, 200); }); it("should reset the user's client session", function() { var req = {session: {email: "foo", reset: sinon.spy()}}; var res = {send: function() {} }; users.add("foo"); api.signout(req, res); sinon.assert.calledOnce(req.session.reset); }); it("should return a 400 if the assertion was invalid", function() { sandbox.stub(User.prototype, "disconnect"); var req = {session: {email: null}}; var res = {send: sinon.spy()}; api.signout(req, res); sinon.assert.calledOnce(res.send); sinon.assert.calledWith(res.send, 400); }); }); describe("#stream", function() { var clock; beforeEach(function() { // Use fake timers here to keep the tests running fast and // avoid waiting for the second long timeouts to occur. clock = sinon.useFakeTimers(); }); afterEach(function() { clock.restore(); }); it("should send to all users that a new user connected", function() { var bar = users.add("bar").get("bar"); var xoo = users.add("xoo").get("xoo"); var req = {session: {email: "foo"}}; var res = {send: function() {}}; sandbox.stub(bar, "send").returns(true); sandbox.stub(xoo, "send").returns(true); api.stream(req, res); sinon.assert.calledOnce(bar.send); sinon.assert.calledWith(bar.send, "userJoined", "foo"); sinon.assert.calledOnce(xoo.send); sinon.assert.calledWith(xoo.send, "userJoined", "foo"); }); it("should send an empty list if firstRequest is specified in the body", function(done) { users.add("foo").get("foo"); var req = {session: {email: "foo"}, body: {firstRequest: true}}; var res = {send: function(code, data) { expect(code).to.equal(200); expect(data).to.equal(JSON.stringify([])); done(); }}; api.stream(req, res); }); it("should send clear and pending waits on the user if firstRequest is " + "specified in the body", function(done) { var user = users.add("foo").get("foo"); sandbox.stub(user, "clearPending").returns(user); var req = {session: {email: "foo"}, body: {firstRequest: true}}; var res = {send: function() { sinon.assert.calledOnce(user.clearPending); done(); }}; api.stream(req, res); }); it("should send an empty list of events", function(done) { users.add("foo").get("foo"); var req = {session: {email: "foo"}}; var res = {send: function(code, data) { expect(code).to.equal(200); expect(data).to.equal(JSON.stringify([])); done(); }}; api.stream(req, res); clock.tick(config.LONG_POLLING_TIMEOUT * 3); }); it("should send a list of events", function(done) { var user = users.add("foo").get("foo"); var event = {topic: "some", data: "data"}; var req = {session: {email: "foo"}}; var res = {send: function(code, data) { expect(code).to.equal(200); expect(data).to.equal(JSON.stringify([event])); done(); }}; api.stream(req, res); user.send("some", "data"); }); it("should fail if no nick is provided", function() { var req = {session: {}}; var res = {send: sinon.spy()}; api.stream(req, res); sinon.assert.calledOnce(res.send); sinon.assert.calledWithExactly(res.send, 400); }); describe("disconnect", function() { beforeEach(function() { var req = {session: {email: "foo"}}; var res = {send: function() {}}; api.stream(req, res); }); it("should remove the user from the list of users", function() { users.get("foo").disconnect(); expect(users.get("foo")).to.be.equal(undefined); }); it("should notify peers that the user left", function() { var bar = users.add("bar").get("bar"); var xoo = users.add("xoo").get("xoo"); sandbox.stub(bar, "send").returns(true); sandbox.stub(xoo, "send").returns(true); users.get("foo").disconnect(); sinon.assert.calledOnce(bar.send); sinon.assert.calledWith(bar.send, "userLeft", "foo"); sinon.assert.calledOnce(xoo.send); sinon.assert.calledWith(xoo.send, "userLeft", "foo"); }); }); }); describe("#callOffer", function() { var req, res; beforeEach(function() { req = {body: {data: {peer: "bar"}}, session: {email: "foo"}}; res = {send: sinon.spy()}; }); it("should forward the event to the peer after swapping the nick", function() { var forwardedEvent = {peer: "foo"}; var bar = users.add("foo").add("bar").get("bar"); sandbox.stub(bar, "send"); api.callOffer(req, res); sinon.assert.calledOnce(bar.send); sinon.assert.calledWith(bar.send, "offer", forwardedEvent); }); it("should warn on handling offers to unknown users", function() { sandbox.stub(logger, "warn"); api.callOffer(req, res); sinon.assert.calledOnce(logger.warn); }); it("should return success", function() { users.add("foo").add("bar").get("bar"); api.iceCandidate(req, res); sinon.assert.calledOnce(res.send); sinon.assert.calledWithExactly(res.send, 204); }); }); describe("#callAccepted", function() { var req, res; beforeEach(function() { req = {body: {data: {peer: "bar"}}, session: {email: "foo"}}; res = {send: sinon.spy()}; }); it("should forward the event to the peer after swapping the nick", function() { var forwardedEvent = {peer: "foo"}; var bar = users.add("foo").add("bar").get("bar"); sandbox.stub(bar, "send"); api.callAccepted(req, res); sinon.assert.calledOnce(bar.send); sinon.assert.calledWith(bar.send, "answer", forwardedEvent); }); it("should warn on handling answers to unknown users", function() { sandbox.stub(logger, "warn"); api.callAccepted(req, res); sinon.assert.calledOnce(logger.warn); }); it("should return success", function() { users.add("foo").add("bar").get("bar"); api.iceCandidate(req, res); sinon.assert.calledOnce(res.send); sinon.assert.calledWithExactly(res.send, 204); }); }); describe("#callHangup", function() { var req, res; beforeEach(function() { req = {body: {data: {peer: "bar"}}, session: {email: "foo"}}; res = {send: sinon.spy()}; }); it("should forward the event to the peer after swapping the nick", function() { var res = {send: function() {}}; var forwardedEvent = {peer: "foo"}; var bar = users.add("foo").add("bar").get("bar"); sandbox.stub(bar, "send"); api.callHangup(req, res); sinon.assert.calledOnce(bar.send); sinon.assert.calledWith(bar.send, "hangup", forwardedEvent); }); it("should warn on handling hangups to unknown users", function() { sandbox.stub(logger, "warn"); api.callHangup(req, res); sinon.assert.calledOnce(logger.warn); }); it("should return success", function() { users.add("foo").add("bar").get("bar"); api.iceCandidate(req, res); sinon.assert.calledOnce(res.send); sinon.assert.calledWithExactly(res.send, 204); }); }); describe("#iceCandidate", function() { var req, res; beforeEach(function() { req = { body: {data: {peer: "bar", candidate: "dummy"}}, session: {email: "foo"} }; res = {send: sinon.spy()}; }); it("should forward the event to the peer after swapping the nick", function() { var forwardedEvent = {peer: "foo", candidate: "dummy"}; var bar = users.add("foo").add("bar").get("bar"); sandbox.stub(bar, "send"); api.iceCandidate(req, res); sinon.assert.calledOnce(bar.send); sinon.assert.calledWith(bar.send, "ice:candidate", forwardedEvent); }); it("should warn on handling candidates to unknown users", function() { sandbox.stub(logger, "warn"); api.iceCandidate(req, res); sinon.assert.calledOnce(logger.warn); }); it("should return success", function() { users.add("foo").add("bar").get("bar"); api.iceCandidate(req, res); sinon.assert.calledOnce(res.send); sinon.assert.calledWithExactly(res.send, 204); }); }); describe("#presenceRequest", function() { var req, res, foo, bar; beforeEach(function() { req = {session: {email: "foo"}}; res = {send: sinon.spy()}; foo = users.add("foo").get("foo"); bar = users.add("bar").get("bar"); sandbox.stub(foo, "send"); }); it("should send the list of connected users to the given user", function() { api.presenceRequest(req, res); sinon.assert.calledOnce(foo.send); sinon.assert.calledWithExactly(foo.send, "users", [ foo.toJSON(), bar.toJSON() ]); }); it("should return success", function() { api.presenceRequest(req, res); sinon.assert.calledOnce(res.send); sinon.assert.calledWithExactly(res.send, 204); }); }); describe("#instantSharePingBack", function() { var req, res, foo, bar; beforeEach(function() { req = {session: {email: "foo"}, params: {email: "bar"}}; res = {send: sinon.spy()}; foo = users.add("foo").get("foo"); bar = users.add("bar").get("bar"); sandbox.stub(foo, "send"); }); it("should send the given peer to myself", function() { api.instantSharePingBack(req, res); sinon.assert.calledOnce(foo.send); sinon.assert.calledWithExactly(foo.send, "instantshare", { peer: "bar" }); }); it("should return a 200 OK response", function() { api.instantSharePingBack(req, res); sinon.assert.calledOnce(res.send); sinon.assert.calledWithExactly(res.send, 200); }); }); describe("#instantShare", function() { var req, res; beforeEach(function() { req = {session: {email: "foo"}, params: {email: "bar"}}; res = {sendfile: sinon.spy()}; }); it("should send the 'static/instant-share.html' page", function() { api.instantShare(req, res); sinon.assert.calledOnce(res.sendfile); sinon.assert.calledWithExactly(res.sendfile, 'static/instant-share.html'); }); }); }); });
test/server/presence_test.js
/* jshint expr:true */ "use strict"; /* The intent is for this to only add unit tests to this file going forward. * * XXX Before long, we're going to want to create a home for backend functional * tests, and move many of the tests that current live in this file there. */ var EventEmitter = require( "events" ).EventEmitter; var chai = require("chai"); var expect = chai.expect; var sinon = require("sinon"); var https = require("https"); chai.Assertion.includeStack = true; require("../../server/server"); var presence = require("../../server/presence"); var User = require("../../server/users").User; var logger = require("../../server/logger"); var config = require('../../server/config').config; describe("presence", function() { var sandbox; var api = presence.api; var users = presence._users; beforeEach(function() { sandbox = sinon.sandbox.create(); }); afterEach(function() { users.forEach(function(user) { users.remove(user.nick); }); sandbox.restore(); }); describe("api", function() { // XXX: this method is private but critical. That's why we have // test coverage for it. In the future we might pull it out into a // separate object as a way to separate concerns. describe("#_verifyAssertion", function() { var oldEnv; before(function() { oldEnv = process.env.NODE_ENV; process.env.NODE_ENV = "development"; }); after(function() { process.env.NODE_ENV = oldEnv; }); it("should send a secure http request to the verifier service", function() { var request = {write: function() {}, end: function() {}}; var options = { host: "verifier.login.persona.org", path: "/verify", method: "POST" }; sandbox.stub(https, "request").returns(request); api._verifyAssertion("fake assertion data", function() {}); sinon.assert.calledOnce(https.request); sinon.assert.calledWith(https.request, sinon.match(options)); }); it("should trigger without error if the assertion is valid", function() { var assertionCallback = sinon.spy(); var response = new EventEmitter(); var request = {write: function() {}, end: function() {}}; var answer = { status: "okay", email: "[email protected]" }; response.setEncoding = function() {}; sandbox.stub(https, "request", function(options, callback) { callback(response); return request; }); api._verifyAssertion("fake assertion data", assertionCallback); response.emit("data", JSON.stringify(answer)); response.emit("end"); sinon.assert.calledOnce(assertionCallback); sinon.assert.calledWithExactly( assertionCallback, null, answer.email); }); it("should trigger with an error if the assertion is invalid", function() { var assertionCallback = sinon.spy(); var response = new EventEmitter(); var request = {write: function() {}, end: function() {}}; var answer = { status: "not okay", reason: "invalid assertion" }; response.setEncoding = function() {}; sandbox.stub(https, "request", function(options, callback) { callback(response); return request; }); api._verifyAssertion("fake assertion data", assertionCallback); response.emit("data", JSON.stringify(answer)); response.emit("end"); sinon.assert.calledOnce(assertionCallback); sinon.assert.calledWithExactly( assertionCallback, answer.reason); }); }); describe("#signin", function() { it("should return the nick", function(done) { var req = {body: {assertion: "fake assertion"}, session: {}}; var res = {send: sinon.spy()}; var answer = JSON.stringify({nick: "foo"}); sandbox.stub(presence.api, "_verifyAssertion", function(a, c) { c(null, "foo"); sinon.assert.calledOnce(res.send); sinon.assert.calledWithExactly(res.send, 200, answer); done(); }); api.signin(req, res); }); it("should return a 400 if the assertion was invalid", function(done) { var req = {body: {assertion: "fake assertion"}, session: {}}; var res = {send: sinon.spy()}; var answer = JSON.stringify({error: "invalid assertion"}); sandbox.stub(presence.api, "_verifyAssertion", function(a, c) { c("invalid assertion"); expect(users.get("foo")).to.equal(undefined); sinon.assert.calledOnce(res.send); sinon.assert.calledWithExactly(res.send, 400, answer); done(); }); api.signin(req, res); }); }); describe("#signout", function() { it("should send the user's long poll connection a disconnect event", function() { sandbox.stub(User.prototype, "send"); var req = {session: {email: "foo", reset: function() {}}}; var res = {send: function() {}}; users.add("foo"); api.signout(req, res); sinon.assert.calledOnce(User.prototype.send); sinon.assert.calledWithExactly(User.prototype.send, "disconnect", null); }); it("should disconnect the user", function() { sandbox.stub(User.prototype, "disconnect"); var req = {session: {email: "foo", reset: function() {}}}; var res = {send: sinon.spy()}; users.add("foo"); api.signout(req, res); sinon.assert.calledOnce(User.prototype.disconnect); sinon.assert.calledOnce(res.send); sinon.assert.calledWith(res.send, 200); }); it("should reset the user's client session", function() { var req = {session: {email: "foo", reset: sinon.spy()}}; var res = {send: function() {} }; users.add("foo"); api.signout(req, res); sinon.assert.calledOnce(req.session.reset); }); it("should return a 400 if the assertion was invalid", function() { sandbox.stub(User.prototype, "disconnect"); var req = {session: {email: null}}; var res = {send: sinon.spy()}; api.signout(req, res); sinon.assert.calledOnce(res.send); sinon.assert.calledWith(res.send, 400); }); }); describe("#stream", function() { var clock; beforeEach(function() { // Use fake timers here to keep the tests running fast and // avoid waiting for the second long timeouts to occur. clock = sinon.useFakeTimers(); }); afterEach(function() { clock.restore(); }); it("should send to all users that a new user connected", function() { var bar = users.add("bar").get("bar"); var xoo = users.add("xoo").get("xoo"); var req = {session: {email: "foo"}}; var res = {send: function() {}}; sandbox.stub(bar, "send").returns(true); sandbox.stub(xoo, "send").returns(true); api.stream(req, res); sinon.assert.calledOnce(bar.send); sinon.assert.calledWith(bar.send, "userJoined", "foo"); sinon.assert.calledOnce(xoo.send); sinon.assert.calledWith(xoo.send, "userJoined", "foo"); }); it("should send an empty list if firstRequest is specified in the body", function(done) { users.add("foo").get("foo"); var req = {session: {email: "foo"}, body: {firstRequest: true}}; var res = {send: function(code, data) { expect(code).to.equal(200); expect(data).to.equal(JSON.stringify([])); done(); }}; api.stream(req, res); }); it("should send clear and pending waits on the user if firstRequest is " + "specified in the body", function(done) { var user = users.add("foo").get("foo"); sandbox.stub(user, "clearPending").returns(user); var req = {session: {email: "foo"}, body: {firstRequest: true}}; var res = {send: function() { sinon.assert.calledOnce(user.clearPending); done(); }}; api.stream(req, res); }); it("should send an empty list of events", function(done) { users.add("foo").get("foo"); var req = {session: {email: "foo"}}; var res = {send: function(code, data) { expect(code).to.equal(200); expect(data).to.equal(JSON.stringify([])); done(); }}; api.stream(req, res); clock.tick(config.LONG_POLLING_TIMEOUT * 3); }); it("should send a list of events", function(done) { var user = users.add("foo").get("foo"); var event = {topic: "some", data: "data"}; var req = {session: {email: "foo"}}; var res = {send: function(code, data) { expect(code).to.equal(200); expect(data).to.equal(JSON.stringify([event])); done(); }}; api.stream(req, res); user.send("some", "data"); }); it("should fail if no nick is provided", function() { var req = {session: {}}; var res = {send: sinon.spy()}; api.stream(req, res); sinon.assert.calledOnce(res.send); sinon.assert.calledWithExactly(res.send, 400); }); describe("disconnect", function() { beforeEach(function() { var req = {session: {email: "foo"}}; var res = {send: function() {}}; api.stream(req, res); }); it("should remove the user from the list of users", function() { users.get("foo").disconnect(); expect(users.get("foo")).to.be.equal(undefined); }); it("should notify peers that the user left", function() { var bar = users.add("bar").get("bar"); var xoo = users.add("xoo").get("xoo"); sandbox.stub(bar, "send").returns(true); sandbox.stub(xoo, "send").returns(true); users.get("foo").disconnect(); sinon.assert.calledOnce(bar.send); sinon.assert.calledWith(bar.send, "userLeft", "foo"); sinon.assert.calledOnce(xoo.send); sinon.assert.calledWith(xoo.send, "userLeft", "foo"); }); }); }); describe("#callOffer", function() { var req, res; beforeEach(function() { req = {body: {data: {peer: "bar"}}, session: {email: "foo"}}; res = {send: sinon.spy()}; }); it("should forward the event to the peer after swapping the nick", function() { var forwardedEvent = {peer: "foo"}; var bar = users.add("foo").add("bar").get("bar"); sandbox.stub(bar, "send"); api.callOffer(req, res); sinon.assert.calledOnce(bar.send); sinon.assert.calledWith(bar.send, "offer", forwardedEvent); }); it("should warn on handling offers to unknown users", function() { sandbox.stub(logger, "warn"); api.callOffer(req, res); sinon.assert.calledOnce(logger.warn); }); it("should return success", function() { users.add("foo").add("bar").get("bar"); api.iceCandidate(req, res); sinon.assert.calledOnce(res.send); sinon.assert.calledWithExactly(res.send, 204); }); }); describe("#callAccepted", function() { var req, res; beforeEach(function() { req = {body: {data: {peer: "bar"}}, session: {email: "foo"}}; res = {send: sinon.spy()}; }); it("should forward the event to the peer after swapping the nick", function() { var forwardedEvent = {peer: "foo"}; var bar = users.add("foo").add("bar").get("bar"); sandbox.stub(bar, "send"); api.callAccepted(req, res); sinon.assert.calledOnce(bar.send); sinon.assert.calledWith(bar.send, "answer", forwardedEvent); }); it("should warn on handling answers to unknown users", function() { sandbox.stub(logger, "warn"); api.callAccepted(req, res); sinon.assert.calledOnce(logger.warn); }); it("should return success", function() { users.add("foo").add("bar").get("bar"); api.iceCandidate(req, res); sinon.assert.calledOnce(res.send); sinon.assert.calledWithExactly(res.send, 204); }); }); describe("#callHangup", function() { var req, res; beforeEach(function() { req = {body: {data: {peer: "bar"}}, session: {email: "foo"}}; res = {send: sinon.spy()}; }); it("should forward the event to the peer after swapping the nick", function() { var res = {send: function() {}}; var forwardedEvent = {peer: "foo"}; var bar = users.add("foo").add("bar").get("bar"); sandbox.stub(bar, "send"); api.callHangup(req, res); sinon.assert.calledOnce(bar.send); sinon.assert.calledWith(bar.send, "hangup", forwardedEvent); }); it("should warn on handling hangups to unknown users", function() { sandbox.stub(logger, "warn"); api.callHangup(req, res); sinon.assert.calledOnce(logger.warn); }); it("should return success", function() { users.add("foo").add("bar").get("bar"); api.iceCandidate(req, res); sinon.assert.calledOnce(res.send); sinon.assert.calledWithExactly(res.send, 204); }); }); describe("#iceCandidate", function() { var req, res; beforeEach(function() { req = { body: {data: {peer: "bar", candidate: "dummy"}}, session: {email: "foo"} }; res = {send: sinon.spy()}; }); it("should forward the event to the peer after swapping the nick", function() { var forwardedEvent = {peer: "foo", candidate: "dummy"}; var bar = users.add("foo").add("bar").get("bar"); sandbox.stub(bar, "send"); api.iceCandidate(req, res); sinon.assert.calledOnce(bar.send); sinon.assert.calledWith(bar.send, "ice:candidate", forwardedEvent); }); it("should warn on handling candidates to unknown users", function() { sandbox.stub(logger, "warn"); api.iceCandidate(req, res); sinon.assert.calledOnce(logger.warn); }); it("should return success", function() { users.add("foo").add("bar").get("bar"); api.iceCandidate(req, res); sinon.assert.calledOnce(res.send); sinon.assert.calledWithExactly(res.send, 204); }); }); describe("#presenceRequest", function() { var req, res, foo, bar; beforeEach(function() { req = {session: {email: "foo"}}; res = {send: sinon.spy()}; foo = users.add("foo").get("foo"); bar = users.add("bar").get("bar"); sandbox.stub(foo, "send"); }); it("should send the list of connected users to the given user", function() { api.presenceRequest(req, res); sinon.assert.calledOnce(foo.send); sinon.assert.calledWithExactly(foo.send, "users", [ foo.toJSON(), bar.toJSON() ]); }); it("should return success", function() { api.presenceRequest(req, res); sinon.assert.calledOnce(res.send); sinon.assert.calledWithExactly(res.send, 204); }); }); describe("#instantSharePingBack", function() { var req, res, foo, bar; beforeEach(function() { req = {session: {email: "foo"}, params: {email: "bar"}}; res = {send: sinon.spy()}; foo = users.add("foo").get("foo"); bar = users.add("bar").get("bar"); sandbox.stub(foo, "send"); }); it("should send the given peer to myself", function() { api.instantSharePingBack(req, res); sinon.assert.calledOnce(foo.send); sinon.assert.calledWithExactly(foo.send, "instantshare", { peer: "bar" }); }); it("should return a 200 OK response", function() { api.instantSharePingBack(req, res); sinon.assert.calledOnce(res.send); sinon.assert.calledWithExactly(res.send, 200); }); }); }); });
Add unit test for instant-share method
test/server/presence_test.js
Add unit test for instant-share method
<ide><path>est/server/presence_test.js <ide> }); <ide> <ide> }); <add> <add> describe("#instantShare", function() { <add> <add> var req, res; <add> <add> beforeEach(function() { <add> req = {session: {email: "foo"}, params: {email: "bar"}}; <add> res = {sendfile: sinon.spy()}; <add> }); <add> <add> it("should send the 'static/instant-share.html' page", function() { <add> api.instantShare(req, res); <add> <add> sinon.assert.calledOnce(res.sendfile); <add> sinon.assert.calledWithExactly(res.sendfile, <add> 'static/instant-share.html'); <add> }); <add> <add> }); <ide> }); <ide> });
Java
apache-2.0
77c4e9e308234a23ff9b92a9edb08e38d50de8c1
0
NEERC/chat,NEERC/chat,NEERC/chat
/* Copyright 2009 NEERC team 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. */ // $Id$ /** * Date: 27.10.2004 */ package ru.ifmo.neerc.chat.client; import ru.ifmo.neerc.chat.user.UserEntry; import ru.ifmo.neerc.chat.user.UserRegistry; import ru.ifmo.neerc.chat.user.UserRegistryListener; import javax.swing.*; import java.awt.*; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.util.ArrayList; import java.util.Arrays; /** * @author Matvey Kazakov */ public class UsersPanel extends JPanel { public static final ImageIcon iconUserNormal = new ImageIcon( UsersPanel.class.getResource("res/user_normal.gif")); public static final ImageIcon iconUserPower = new ImageIcon( UsersPanel.class.getResource("res/user_power.gif")); public static final ImageIcon iconUserNormalOffline = new ImageIcon( UsersPanel.class.getResource("res/user_normal_offline.gif")); public static final ImageIcon iconUserPowerOffline = new ImageIcon( UsersPanel.class.getResource("res/user_power_offline.gif")); public static final ImageIcon iconChannel = new ImageIcon( UsersPanel.class.getResource("res/user_channel.gif")); private static final int USER_ITEM_HEIGHT = 26; private UserEntry user; private JSplitPane splitter; private ArrayList<UserPickListener> listeners = new ArrayList<UserPickListener>(); private NameColorizer colorizer; public UsersPanel(UserEntry user, NameColorizer colorizer) { this.user = user; this.colorizer = colorizer; setLayout(new BorderLayout()); ListData model = new ListData(); final JList<UserEntry> userList = new JList<UserEntry>(); userList.setModel(model); userList.setCellRenderer(new UserListCellRenderer()); userList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); UserRegistry.getInstance().addListener(model); userList.addMouseListener(new MouseAdapter() { public void mouseClicked(MouseEvent e) { UserEntry user = (UserEntry)userList.getSelectedValue(); if (user != null && e.getClickCount() % 2 == 0) { for (UserPickListener listener : listeners) { listener.userPicked(user); } } } }); add(new JScrollPane(userList), BorderLayout.CENTER); } public void setSplitter(JSplitPane splitter) { this.splitter = splitter; } private void resize(int users) { if (splitter == null) return; splitter.setDividerLocation(users * USER_ITEM_HEIGHT + 5); } public void addListener(UserPickListener listener) { listeners.add(listener); } private class ListData extends AbstractListModel<UserEntry> implements UserRegistryListener { private UserEntry[] userEntries; public ListData() { init(); } private synchronized void init() { userEntries = UserRegistry.getInstance().serialize(); Arrays.sort(userEntries); resize(userEntries.length); } public synchronized int getSize() { return userEntries.length; } public synchronized UserEntry getElementAt(int index) { return userEntries[index]; } public void userChanged(UserEntry userEntry) { update(); } public void userPresenceChanged(UserEntry userEntry) { update(); } private void update() { init(); SwingUtilities.invokeLater(new Runnable() { @Override public void run() { fireContentsChanged(this, 0, getSize()); } }); } } private class UserListCellRenderer extends DefaultListCellRenderer { @Override public Component getListCellRendererComponent(JList<?> list, Object value, int index, boolean isSelected, boolean cellHasFocus) { UserEntry entry = (UserEntry) value; setBackground(list.getBackground()); setIcon(entry.isPower() ? (entry.isOnline() ? iconUserPower : iconUserPowerOffline) : (entry.isOnline() ? iconUserNormal : iconUserNormalOffline) ); setEnabled(list.isEnabled()); Font font = list.getFont(); if (entry.getId() == user.getId()) { font = font.deriveFont(Font.BOLD); } else { font = font.deriveFont(Font.PLAIN); } setFont(font); setText(entry.getName()); if (entry.isOnline()) { setForeground(colorizer.generateColor(entry)); } else { setForeground(Color.lightGray); } setBorder((cellHasFocus) ? UIManager.getBorder("List.focusCellHighlightBorder") : noFocusBorder); return this; } } }
Chat/src/main/java/ru/ifmo/neerc/chat/client/UsersPanel.java
/* Copyright 2009 NEERC team 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. */ // $Id$ /** * Date: 27.10.2004 */ package ru.ifmo.neerc.chat.client; import ru.ifmo.neerc.chat.user.UserEntry; import ru.ifmo.neerc.chat.user.UserRegistry; import ru.ifmo.neerc.chat.user.UserRegistryListener; import javax.swing.*; import java.awt.*; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.util.ArrayList; import java.util.Arrays; /** * @author Matvey Kazakov */ public class UsersPanel extends JPanel { public static final ImageIcon iconUserNormal = new ImageIcon( UsersPanel.class.getResource("res/user_normal.gif")); public static final ImageIcon iconUserPower = new ImageIcon( UsersPanel.class.getResource("res/user_power.gif")); public static final ImageIcon iconUserNormalOffline = new ImageIcon( UsersPanel.class.getResource("res/user_normal_offline.gif")); public static final ImageIcon iconUserPowerOffline = new ImageIcon( UsersPanel.class.getResource("res/user_power_offline.gif")); public static final ImageIcon iconChannel = new ImageIcon( UsersPanel.class.getResource("res/user_channel.gif")); private static final int USER_ITEM_HEIGHT = 26; private UserEntry user; private JSplitPane splitter; private ArrayList<UserPickListener> listeners = new ArrayList<UserPickListener>(); private NameColorizer colorizer; public UsersPanel(UserEntry user, NameColorizer colorizer) { this.user = user; this.colorizer = colorizer; setLayout(new BorderLayout()); ListData model = new ListData(); final JList<UserEntry> userList = new JList<UserEntry>(); userList.setModel(model); userList.setCellRenderer(new UserListCellRenderer()); userList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); UserRegistry.getInstance().addListener(model); userList.addMouseListener(new MouseAdapter() { public void mouseClicked(MouseEvent e) { UserEntry user = (UserEntry)userList.getSelectedValue(); if (user != null && e.getClickCount() % 2 == 0) { for (UserPickListener listener : listeners) { listener.userPicked(user); } } } }); add(new JScrollPane(userList), BorderLayout.CENTER); } public void setSplitter(JSplitPane splitter) { this.splitter = splitter; } private void resize(int users) { if (splitter == null) return; splitter.setDividerLocation(users * USER_ITEM_HEIGHT + 5); } public void addListener(UserPickListener listener) { listeners.add(listener); } private class ListData extends AbstractListModel<UserEntry> implements UserRegistryListener { private UserEntry[] userEntries; public ListData() { init(); } private synchronized void init() { userEntries = UserRegistry.getInstance().serialize(); Arrays.sort(userEntries); resize(userEntries.length); } public synchronized int getSize() { return userEntries.length; } public synchronized UserEntry getElementAt(int index) { return userEntries[index]; } public void userChanged(UserEntry userEntry) { update(); } public void userPresenceChanged(UserEntry userEntry) { update(); } private void update() { init(); fireContentsChanged(this, 0, userEntries.length); } } private class UserListCellRenderer extends DefaultListCellRenderer { @Override public Component getListCellRendererComponent(JList<?> list, Object value, int index, boolean isSelected, boolean cellHasFocus) { UserEntry entry = (UserEntry) value; setBackground(list.getBackground()); setIcon(entry.isPower() ? (entry.isOnline() ? iconUserPower : iconUserPowerOffline) : (entry.isOnline() ? iconUserNormal : iconUserNormalOffline) ); setEnabled(list.isEnabled()); Font font = list.getFont(); if (entry.getId() == user.getId()) { font = font.deriveFont(Font.BOLD); } else { font = font.deriveFont(Font.PLAIN); } setFont(font); setText(entry.getName()); if (entry.isOnline()) { setForeground(colorizer.generateColor(entry)); } else { setForeground(Color.lightGray); } setBorder((cellHasFocus) ? UIManager.getBorder("List.focusCellHighlightBorder") : noFocusBorder); return this; } } }
Update users list from EDT thread
Chat/src/main/java/ru/ifmo/neerc/chat/client/UsersPanel.java
Update users list from EDT thread
<ide><path>hat/src/main/java/ru/ifmo/neerc/chat/client/UsersPanel.java <ide> <ide> private void update() { <ide> init(); <del> fireContentsChanged(this, 0, userEntries.length); <add> SwingUtilities.invokeLater(new Runnable() { <add> @Override <add> public void run() { <add> fireContentsChanged(this, 0, getSize()); <add> } <add> }); <ide> } <ide> } <ide>
Java
apache-2.0
bcfe050c0c8629ed36d46160df63ae9bb61ccc9a
0
Hack23/cia,Hack23/cia,Hack23/cia,Hack23/cia
/* * Copyright 2010 James Pether Sörling * * 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. * * $Id$ * $HeadURL$ */ package com.hack23.cia.service.impl.task; import java.io.Serializable; import org.quartz.JobExecutionContext; import org.quartz.Scheduler; import org.quartz.SchedulerContext; import org.quartz.SchedulerException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.context.ApplicationContext; import org.springframework.scheduling.quartz.QuartzJobBean; /** * The Class AbstractJob. */ public abstract class AbstractJob extends QuartzJobBean implements Serializable{ /** The Constant LOGGER. */ private static final Logger LOGGER = LoggerFactory.getLogger(AbstractJob.class); /** The Constant APPLICATION_CONTEXT. */ private static final String APPLICATION_CONTEXT = "applicationContext"; /** The Constant serialVersionUID. */ private static final long serialVersionUID = 1L; /** * Gets the job context holder. * * @param jobContext * the job context * @return the job context holder */ protected final JobContextHolder getJobContextHolder(final JobExecutionContext jobContext) { final Scheduler scheduler = jobContext.getScheduler(); JobContextHolder bean = null; try { SchedulerContext schedulerContext = scheduler.getContext(); final ApplicationContext appContext = (ApplicationContext) schedulerContext.get(APPLICATION_CONTEXT); bean = appContext.getBean(JobContextHolder.class); } catch (final SchedulerException e) { LOGGER.error("Failed to get JobContextHolder",e ); } return bean; } }
service.impl/src/main/java/com/hack23/cia/service/impl/task/AbstractJob.java
package com.hack23.cia.service.impl.task; import java.io.Serializable; import org.quartz.JobExecutionContext; import org.quartz.Scheduler; import org.quartz.SchedulerContext; import org.quartz.SchedulerException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.context.ApplicationContext; import org.springframework.scheduling.quartz.QuartzJobBean; public abstract class AbstractJob extends QuartzJobBean implements Serializable{ private static final Logger LOGGER = LoggerFactory.getLogger(AbstractJob.class); private static final String APPLICATION_CONTEXT = "applicationContext"; /** * */ private static final long serialVersionUID = 1L; protected final JobContextHolder getJobContextHolder(final JobExecutionContext jobContext) { final Scheduler scheduler = jobContext.getScheduler(); JobContextHolder bean = null; try { SchedulerContext schedulerContext = scheduler.getContext(); final ApplicationContext appContext = (ApplicationContext) schedulerContext.get(APPLICATION_CONTEXT); bean = appContext.getBean(JobContextHolder.class); } catch (final SchedulerException e) { LOGGER.error("Failed to get JobContextHolder",e ); } return bean; } }
cleanup
service.impl/src/main/java/com/hack23/cia/service/impl/task/AbstractJob.java
cleanup
<ide><path>ervice.impl/src/main/java/com/hack23/cia/service/impl/task/AbstractJob.java <add>/* <add> * Copyright 2010 James Pether Sörling <add> * <add> * Licensed under the Apache License, Version 2.0 (the "License"); <add> * you may not use this file except in compliance with the License. <add> * You may obtain a copy of the License at <add> * <add> * http://www.apache.org/licenses/LICENSE-2.0 <add> * <add> * Unless required by applicable law or agreed to in writing, software <add> * distributed under the License is distributed on an "AS IS" BASIS, <add> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. <add> * See the License for the specific language governing permissions and <add> * limitations under the License. <add> * <add> * $Id$ <add> * $HeadURL$ <add>*/ <ide> package com.hack23.cia.service.impl.task; <ide> <ide> import java.io.Serializable; <ide> import org.springframework.context.ApplicationContext; <ide> import org.springframework.scheduling.quartz.QuartzJobBean; <ide> <add>/** <add> * The Class AbstractJob. <add> */ <ide> public abstract class AbstractJob extends QuartzJobBean implements Serializable{ <ide> <add> /** The Constant LOGGER. */ <ide> private static final Logger LOGGER = LoggerFactory.getLogger(AbstractJob.class); <ide> <add> /** The Constant APPLICATION_CONTEXT. */ <ide> private static final String APPLICATION_CONTEXT = "applicationContext"; <del> /** <del> * <del> */ <add> <add> /** The Constant serialVersionUID. */ <ide> private static final long serialVersionUID = 1L; <ide> <add> /** <add> * Gets the job context holder. <add> * <add> * @param jobContext <add> * the job context <add> * @return the job context holder <add> */ <ide> protected final JobContextHolder getJobContextHolder(final JobExecutionContext jobContext) { <ide> final Scheduler scheduler = jobContext.getScheduler(); <ide> JobContextHolder bean = null;
Java
mit
39543b1f632b1bbe44303ed0e2ea7690add41ea8
0
team1306/Robot2016
package org.usfirst.frc.team1306.robot; import edu.wpi.first.wpilibj.Joystick; /** * An Xbox controller. This is a relatively minor extension of Joystick that * adds methods specific to the Xbox controller. * * @author Finn Voichick * */ public class XboxController extends Joystick { /** * Creates a new XboxController connected to the specified port. * * @param port * the port that the Xbox controller is connected to. This can be * seen on the driver station. */ public XboxController(int port) { super(port); } /** * Get the x displacement of either joystick on an xbox controller. * * @param hand * which joystick, LS or RS. * @return raw X displacement of joystick, on a scale from -1.0 to 1.0. */ public double getX(Hand hand) { if (hand.equals(Hand.kLeft)) { return getRawAxis(0); } else { return getRawAxis(4); } } /** * Get the y displacement of either joystick on an xbox controller. * * @param hand * which joystick, LS or RS. * @return raw y displacement of joystick, on a scale from -1.0 to 1.0. */ public double getY(Hand hand) { if (hand.equals(Hand.kLeft)) { return -getRawAxis(1); } else { return -getRawAxis(5); } } /** * Get whether either trigger is pressed down. * * @param hand * which trigger, LT or RT. * @return true if the trigger is pressed, otherwise false. */ public boolean getTrigger(Hand hand) { if (hand.equals(Hand.kLeft)) { return getLT() > 0.5; } else { return getRT() > 0.5; } } /** * Get how far the left trigger is pressed down. * * @return the left trigger axis value, on a scale from 0.0 to 1.0. */ public double getLT() { return getRawAxis(2); } /** * Get how far the right trigger is pressed down. * * @return the right trigger axis value, on a scale from 0.0 to 1.0. */ public double getRT() { return getRawAxis(3); } /** The A button index */ public final static int A = 1; /** The B button index */ public final static int B = 2; /** The X button index */ public final static int X = 3; /** The Y button index */ public final static int Y = 4; /** The LB button index */ public final static int LB = 5; /** The RB button index */ public final static int RB = 6; /** The BACK button index */ public final static int BACK = 7; /** The START button index */ public final static int START = 8; /** The LS button index */ public final static int LS = 9; /** The RS button index */ public final static int RS = 10; }
src/org/usfirst/frc/team1306/robot/XboxController.java
package org.usfirst.frc.team1306.robot; import edu.wpi.first.wpilibj.Joystick; public class XboxController extends Joystick { public XboxController(int port) { super(port); } /** * Get the x displacement of either joystick on an xbox controller. * * @param hand * Which joystick * @return Raw X displacement of joystick */ public double getX(Hand hand) { if (hand.equals(Hand.kLeft)) { return getRawAxis(0); } else { return getRawAxis(4); } } /** * Get the x displacement of either joystick on an xbox controller. * * @param hand * Which joystick * @return Raw X displacement of joystick */ public double getY(Hand hand) { if (hand.equals(Hand.kLeft)) { return -getRawAxis(1); } else { return -getRawAxis(5); } } public boolean getTrigger(Hand hand) { if (hand.equals(Hand.kLeft)) { return getLT() > 0.5; } else { return getRT() > 0.5; } } public double getLT() { return getRawAxis(2); } public double getRT() { return getRawAxis(3); } public final static int A = 1; public final static int B = 2; public final static int X = 3; public final static int Y = 4; public final static int LB = 5; public final static int RB = 6; public final static int BACK = 7; public final static int START = 8; public final static int LS = 9; public final static int RS = 10; public final static int TRIGGERS = 3; }
Commented XboxController
src/org/usfirst/frc/team1306/robot/XboxController.java
Commented XboxController
<ide><path>rc/org/usfirst/frc/team1306/robot/XboxController.java <ide> <ide> import edu.wpi.first.wpilibj.Joystick; <ide> <add>/** <add> * An Xbox controller. This is a relatively minor extension of Joystick that <add> * adds methods specific to the Xbox controller. <add> * <add> * @author Finn Voichick <add> * <add> */ <ide> public class XboxController extends Joystick { <ide> <add> /** <add> * Creates a new XboxController connected to the specified port. <add> * <add> * @param port <add> * the port that the Xbox controller is connected to. This can be <add> * seen on the driver station. <add> */ <ide> public XboxController(int port) { <ide> super(port); <ide> } <ide> * Get the x displacement of either joystick on an xbox controller. <ide> * <ide> * @param hand <del> * Which joystick <del> * @return Raw X displacement of joystick <add> * which joystick, LS or RS. <add> * @return raw X displacement of joystick, on a scale from -1.0 to 1.0. <ide> */ <ide> public double getX(Hand hand) { <ide> if (hand.equals(Hand.kLeft)) { <ide> } <ide> <ide> /** <del> * Get the x displacement of either joystick on an xbox controller. <add> * Get the y displacement of either joystick on an xbox controller. <ide> * <ide> * @param hand <del> * Which joystick <del> * @return Raw X displacement of joystick <add> * which joystick, LS or RS. <add> * @return raw y displacement of joystick, on a scale from -1.0 to 1.0. <ide> */ <ide> public double getY(Hand hand) { <ide> if (hand.equals(Hand.kLeft)) { <ide> } <ide> } <ide> <add> /** <add> * Get whether either trigger is pressed down. <add> * <add> * @param hand <add> * which trigger, LT or RT. <add> * @return true if the trigger is pressed, otherwise false. <add> */ <ide> public boolean getTrigger(Hand hand) { <ide> if (hand.equals(Hand.kLeft)) { <ide> return getLT() > 0.5; <ide> } <ide> } <ide> <add> /** <add> * Get how far the left trigger is pressed down. <add> * <add> * @return the left trigger axis value, on a scale from 0.0 to 1.0. <add> */ <ide> public double getLT() { <ide> return getRawAxis(2); <ide> } <ide> <add> /** <add> * Get how far the right trigger is pressed down. <add> * <add> * @return the right trigger axis value, on a scale from 0.0 to 1.0. <add> */ <ide> public double getRT() { <ide> return getRawAxis(3); <ide> } <ide> <add> /** The A button index */ <ide> public final static int A = 1; <add> /** The B button index */ <ide> public final static int B = 2; <add> /** The X button index */ <ide> public final static int X = 3; <add> /** The Y button index */ <ide> public final static int Y = 4; <add> /** The LB button index */ <ide> public final static int LB = 5; <add> /** The RB button index */ <ide> public final static int RB = 6; <add> /** The BACK button index */ <ide> public final static int BACK = 7; <add> /** The START button index */ <ide> public final static int START = 8; <add> /** The LS button index */ <ide> public final static int LS = 9; <add> /** The RS button index */ <ide> public final static int RS = 10; <del> public final static int TRIGGERS = 3; <ide> }
JavaScript
mit
1c31886d3772a8a4b8301e7d9221e51d9e73cfd9
0
brianc/node-sql,braddunbar/node-sql,BeeDi/node-sql,danrzeppa/node-sql,bgag/node-sql,strugee/node-sql,paytm/node-sql,niklabh/node-sql
var assert = require('assert'); var Postgres = require(__dirname + '/../lib/dialect/postgres'); var Table = require(__dirname + '/../lib/table'); var test = function(expected) { var query = expected.query; var pgQuery = new Postgres().getQuery(query); var expectedPgText = expected.pg; assert.equal(pgQuery.text, expected.pg, 'Postgres text not equal\n actual: "' + pgQuery.text + '"\n expected: "' + expected.pg + '"'); if(expected.params) { assert.equal(expected.params.length, pgQuery.values.length); for(var i = 0; i < expected.params.length; i++) { assert.equal(expected.params[i], pgQuery.values[i]); } } } var user = Table.define({ name: 'user', quote: true, columns: ['id','name'] }) test({ query : user.select(user.id).from(user), pg : 'SELECT "user".id FROM "user"' }); test({ query : user.select(user.id, user.name).from(user), pg : 'SELECT "user".id, "user".name FROM "user"' }); test({ query : user.select(user.star()).from(user), pg : 'SELECT "user".* FROM "user"' }); test({ query : user.select(user.id).from(user).where(user.name.equals('foo')), pg : 'SELECT "user".id FROM "user" WHERE ("user".name = $1)', params: ['foo'] }); test({ query : user.select(user.id).from(user).where(user.name.equals('foo').or(user.name.equals('bar'))), pg : 'SELECT "user".id FROM "user" WHERE (("user".name = $1) OR ("user".name = $2))', params: ['foo', 'bar'] }); test({ query : user.select(user.id).from(user).where(user.name.equals('foo').and(user.name.equals('bar'))), pg : 'SELECT "user".id FROM "user" WHERE (("user".name = $1) AND ("user".name = $2))', params: ['foo', 'bar'] }); test({ query : user.select(user.id).from(user).where(user.name.equals('foo')).or(user.name.equals('bar')), pg : 'SELECT "user".id FROM "user" WHERE (("user".name = $1) OR ("user".name = $2))' }); test({ query : user.select(user.id).from(user).where(user.name.equals('foo')).or(user.name.equals('baz')).and(user.name.equals('bar')), pg : 'SELECT "user".id FROM "user" WHERE ((("user".name = $1) OR ("user".name = $2)) AND ("user".name = $3))' }); test({ query : user.select(user.id).from(user) .where(user.name.equals('boom') .and(user.id.equals(1))).or(user.name.equals('bang').and(user.id.equals(2))), pg : 'SELECT "user".id FROM "user" WHERE ((("user".name = $1) AND ("user".id = $2)) OR (("user".name = $3) AND ("user".id = $4)))' }); var post = Table.define({ name: 'post', columns: ['id', 'userId', 'content'] }); test({ query : user.select(user.name, post.content).from(user.join(post).on(user.id.equals(post.userId))), pg : 'SELECT "user".name, post.content FROM "user" INNER JOIN post ON ("user".id = post."userId")' }); var u = user.as('u'); test({ query : u.select(u.name).from(u), pg :'SELECT u.name FROM "user" AS u' }); var p = post.as('p'); test({ query : u.select(u.name).from(u.join(p).on(u.id.equals(p.userId).and(p.id.equals(3)))), pg : 'SELECT u.name FROM "user" AS u INNER JOIN post AS p ON ((u.id = p."userId") AND (p.id = $1))' }); test({ query : u.select(p.content, u.name).from(u.join(p).on(u.id.equals(p.userId).and(p.content.isNotNull()))), pg : 'SELECT p.content, u.name FROM "user" AS u INNER JOIN post AS p ON ((u.id = p."userId") AND (p.content IS NOT NULL))' }); console.log('inserting plain SQL'); test({ query : user.select('name').from('user').where('name <> NULL'), pg : 'SELECT name FROM user WHERE name <> NULL' }); console.log('automatic FROM on "easy" queries'); test({ query : post.select(post.content), pg : 'SELECT post.content FROM post' }); test({ query : post.select(post.content).where(post.userId.equals(1)), pg : 'SELECT post.content FROM post WHERE (post."userId" = $1)' }); console.log('order by'); test({ query : post.select(post.content).order(post.content), pg : 'SELECT post.content FROM post ORDER BY post.content', }); test({ query : post.select(post.content).order(post.content, post.userId.descending), pg : 'SELECT post.content FROM post ORDER BY post.content, (post."userId" DESC)' }); test({ query : post.select(post.content).order(post.content.asc, post.userId.desc), pg : 'SELECT post.content FROM post ORDER BY post.content, (post."userId" DESC)' }); console.log('parent queries'); var ignore = function() { var parent = post.select(post.content); assert.textEqual(parent, 'SELECT post.content FROM post'); var child = parent.select(post.userId).where(post.userId.equals(1)); assert.textEqual(parent, 'SELECT post.content FROM post'); assert.textEqual(child, 'SELECT post.content, post."userId" FROM post WHERE (post."userId" = $1)'); } console.log('quoting column names'); var comment = Table.define({ name: 'comment', columns: [{ name: 'text', quote: true }, { name: 'userId', quote: false }] }); test({ query : comment.select(comment.text, comment.userId), pg : 'SELECT comment."text", comment.userId FROM comment', });
test/dialect-tests.js
var assert = require('assert'); var Postgres = require(__dirname + '/../lib/dialect/postgres'); var Table = require(__dirname + '/../lib/table'); var user = Table.define({ name: 'user', quote: true, columns: ['id','name'] }) assert.textEqual = function(query, expected) { var q = new Postgres().getQuery(query).text; assert.equal(q, expected, 'Query text not equal\n actual: "' + q + '"\n expected: "' + expected + '"'); } assert.paramsEqual = function(query, expected) { var q = new Postgres().getQuery(query); assert.equal(q.values.length, expected.length); for(var i = 0; i < q.values.length; i++) { assert.equal(q.values[i], expected[i]); } } var test = function(expected) { var query = expected.query; var pgQuery = new Postgres().getQuery(query); var expectedPgText = expected.pg; assert.equal(pgQuery.text, expected.pg, 'Postgres text not equal\n actual: "' + pgQuery.text + '"\n expected: "' + expected.pg + '"'); console.log(expectedPgText); if(expected.params) { assert.equal(expected.params.length, pgQuery.values.length); for(var i = 0; i < expected.params.length; i++) { assert.equal(expected.params[i], pgQuery.values[i]); } } } test({ query : user.select(user.id).from(user), pg : 'SELECT "user".id FROM "user"' }); test({ query : user.select(user.id, user.name).from(user), pg : 'SELECT "user".id, "user".name FROM "user"' }); test({ query : user.select(user.star()).from(user), pg : 'SELECT "user".* FROM "user"' }); test({ query : user.select(user.id).from(user).where(user.name.equals('foo')), pg : 'SELECT "user".id FROM "user" WHERE ("user".name = $1)', params: ['foo'] }); test({ query : user.select(user.id).from(user).where(user.name.equals('foo').or(user.name.equals('bar'))), pg : 'SELECT "user".id FROM "user" WHERE (("user".name = $1) OR ("user".name = $2))', params: ['foo', 'bar'] }); test({ query : user.select(user.id).from(user).where(user.name.equals('foo').and(user.name.equals('bar'))), pg : 'SELECT "user".id FROM "user" WHERE (("user".name = $1) AND ("user".name = $2))', params: ['foo', 'bar'] }); test({ query : user.select(user.id).from(user).where(user.name.equals('foo')).or(user.name.equals('bar')), pg : 'SELECT "user".id FROM "user" WHERE (("user".name = $1) OR ("user".name = $2))' }); test({ query : user.select(user.id).from(user).where(user.name.equals('foo')).or(user.name.equals('baz')).and(user.name.equals('bar')), pg : 'SELECT "user".id FROM "user" WHERE ((("user".name = $1) OR ("user".name = $2)) AND ("user".name = $3))' }); test({ query : user.select(user.id).from(user) .where(user.name.equals('boom') .and(user.id.equals(1))).or(user.name.equals('bang').and(user.id.equals(2))), pg : 'SELECT "user".id FROM "user" WHERE ((("user".name = $1) AND ("user".id = $2)) OR (("user".name = $3) AND ("user".id = $4)))' }); var post = Table.define({ name: 'post', columns: ['id', 'userId', 'content'] }); test({ query : user.select(user.name, post.content).from(user.join(post).on(user.id.equals(post.userId))), pg : 'SELECT "user".name, post.content FROM "user" INNER JOIN post ON ("user".id = post."userId")' }); var u = user.as('u'); test({ query : u.select(u.name).from(u), pg :'SELECT u.name FROM "user" AS u' }); var p = post.as('p'); test({ query : u.select(u.name).from(u.join(p).on(u.id.equals(p.userId).and(p.id.equals(3)))), pg : 'SELECT u.name FROM "user" AS u INNER JOIN post AS p ON ((u.id = p."userId") AND (p.id = $1))' }); test({ query : u.select(p.content, u.name).from(u.join(p).on(u.id.equals(p.userId).and(p.content.isNotNull()))), pg : 'SELECT p.content, u.name FROM "user" AS u INNER JOIN post AS p ON ((u.id = p."userId") AND (p.content IS NOT NULL))' }); console.log('inserting plain SQL'); test({ query : user.select('name').from('user').where('name <> NULL'), pg : 'SELECT name FROM user WHERE name <> NULL' }); console.log('automatic FROM on "easy" queries'); test({ query : post.select(post.content), pg : 'SELECT post.content FROM post' }); test({ query : post.select(post.content).where(post.userId.equals(1)), pg : 'SELECT post.content FROM post WHERE (post."userId" = $1)' }); console.log('order by'); test({ query : post.select(post.content).order(post.content), pg : 'SELECT post.content FROM post ORDER BY post.content', }); test({ query : post.select(post.content).order(post.content, post.userId.descending), pg : 'SELECT post.content FROM post ORDER BY post.content, (post."userId" DESC)' }); test({ query : post.select(post.content).order(post.content.asc, post.userId.desc), pg : 'SELECT post.content FROM post ORDER BY post.content, (post."userId" DESC)' }); console.log('parent queries'); var ignore = function() { var parent = post.select(post.content); assert.textEqual(parent, 'SELECT post.content FROM post'); var child = parent.select(post.userId).where(post.userId.equals(1)); assert.textEqual(parent, 'SELECT post.content FROM post'); assert.textEqual(child, 'SELECT post.content, post."userId" FROM post WHERE (post."userId" = $1)'); } console.log('quoting column names'); var comment = Table.define({ name: 'comment', columns: [{ name: 'text', quote: true }, { name: 'userId', quote: false }] }); test({ query : comment.select(comment.text, comment.userId), pg : 'SELECT comment."text", comment.userId FROM comment', });
remove unused code
test/dialect-tests.js
remove unused code
<ide><path>est/dialect-tests.js <ide> var assert = require('assert'); <ide> var Postgres = require(__dirname + '/../lib/dialect/postgres'); <ide> var Table = require(__dirname + '/../lib/table'); <del> <del>var user = Table.define({ <del> name: 'user', <del> quote: true, <del> columns: ['id','name'] <del>}) <del> <del>assert.textEqual = function(query, expected) { <del> var q = new Postgres().getQuery(query).text; <del> assert.equal(q, expected, 'Query text not equal\n actual: "' + q + '"\n expected: "' + expected + '"'); <del>} <del> <del>assert.paramsEqual = function(query, expected) { <del> var q = new Postgres().getQuery(query); <del> assert.equal(q.values.length, expected.length); <del> for(var i = 0; i < q.values.length; i++) { <del> assert.equal(q.values[i], expected[i]); <del> } <del>} <ide> <ide> var test = function(expected) { <ide> var query = expected.query; <ide> var pgQuery = new Postgres().getQuery(query); <ide> var expectedPgText = expected.pg; <ide> assert.equal(pgQuery.text, expected.pg, 'Postgres text not equal\n actual: "' + pgQuery.text + '"\n expected: "' + expected.pg + '"'); <del> console.log(expectedPgText); <ide> if(expected.params) { <ide> assert.equal(expected.params.length, pgQuery.values.length); <ide> for(var i = 0; i < expected.params.length; i++) { <ide> } <ide> } <ide> } <add> <add>var user = Table.define({ <add> name: 'user', <add> quote: true, <add> columns: ['id','name'] <add>}) <ide> <ide> test({ <ide> query : user.select(user.id).from(user),
Java
bsd-3-clause
47f8cad1355f8ed8b798e4bfdec3ed06d9b4a7a9
0
lockss/lockss-daemon,lockss/lockss-daemon,edina/lockss-daemon,edina/lockss-daemon,lockss/lockss-daemon,lockss/lockss-daemon,lockss/lockss-daemon,lockss/lockss-daemon,edina/lockss-daemon,edina/lockss-daemon,edina/lockss-daemon,edina/lockss-daemon,lockss/lockss-daemon,edina/lockss-daemon
/* * $Id: LeafNodeImpl.java,v 1.3 2002-11-02 01:01:00 aalto Exp $ */ /* Copyright (c) 2002 Board of Trustees of Leland Stanford Jr. University, all rights reserved. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL STANFORD UNIVERSITY BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. Except as contained in this notice, the name of Stanford University shall not be used in advertising or otherwise to promote the sale, use or other dealings in this Software without prior written authorization from Stanford University. */ package org.lockss.repository; import java.io.*; import java.util.*; /** * LeafNodeImpl is a leaf-specific subclass of RepositoryNodeImpl. */ public class LeafNodeImpl extends RepositoryNodeImpl implements LeafNode { /** * The name of the file created in leaf cache directories. */ public static final String LEAF_FILE_NAME = "isLeaf"; private static final String CURRENT_SUFFIX = ".current"; private static final String PROPS_SUFFIX = ".props"; private static final String TEMP_SUFFIX = ".temp"; private boolean newVersionOpen = false; private OutputStream newVersionOutput; private InputStream curInput; private Properties curProps; private String versionName; private int currentVersion = -1; private StringBuffer buffer; public LeafNodeImpl(String url, String cacheLocation, LockssRepositoryImpl repository) { super(url, cacheLocation, repository); } public int getCurrentVersion() { ensureCurrentVersionLoaded(); return currentVersion; } public boolean isLeaf() { return true; } public boolean exists() { ensureCurrentVersionLoaded(); return (currentVersion > 0); } public void makeNewVersion() { if (newVersionOpen) { throw new UnsupportedOperationException("New version already"+ " initialized."); } ensureCurrentVersionLoaded(); if (currentVersion == 0) { File cacheDir = getCacheLocation(); if (!cacheDir.exists()) { cacheDir.mkdirs(); } File leafFile = new File(cacheDir, LEAF_FILE_NAME); try { leafFile.createNewFile(); } catch (IOException ioe) { logger.error("Couldn't create leaf file for " + cacheDir.getAbsolutePath()+"."); } } newVersionOpen = true; } public void sealNewVersion() { if (!newVersionOpen) { throw new UnsupportedOperationException("New version not initialized."); } synchronized (this) { File curContent = getCurrentCacheFile(); File curProps = getCurrentPropertiesFile(); File newContent = getTempCacheFile(); File newProps = getTempPropertiesFile(); // rename current curContent.renameTo(getVersionedCacheFile(currentVersion)); curProps.renameTo(getVersionedPropertiesFile(currentVersion)); // rename new newContent.renameTo(getCurrentCacheFile()); newProps.renameTo(getCurrentCacheFile()); currentVersion++; newVersionOutput = null; curInput = null; curProps = null; newVersionOpen = false; } } public InputStream getInputStream() { ensureCurrentVersionLoaded(); ensureReadInfoLoaded(); return curInput; } public Properties getProperties() { ensureCurrentVersionLoaded(); ensureReadInfoLoaded(); return curProps; } public OutputStream getNewOutputStream() { if (!newVersionOpen) { throw new UnsupportedOperationException("New version not initialized."); } if (newVersionOutput!=null) { return newVersionOutput; } File file = getTempCacheFile(); try { newVersionOutput = new FileOutputStream(file); return newVersionOutput; } catch (FileNotFoundException fnfe) { logger.error("No new version file for "+file.getAbsolutePath()+"."); return null; } } public void setNewProperties(Properties newProps) { if (!newVersionOpen) { throw new UnsupportedOperationException("New version not initialized."); } if (newProps!=null) { File file = getTempPropertiesFile(); try { OutputStream os = new FileOutputStream(file); newProps.setProperty("version_number", ""+(currentVersion+1)); newProps.store(os, "HTTP headers for " + url); os.close(); } catch (IOException ioe) { logger.error("Couldn't write properties for " + file.getAbsolutePath()+"."); } } } private void ensureReadInfoLoaded() { if ((curInput==null) || (curProps==null)) { synchronized (this) { File file = null; if (curInput==null) { file = getCurrentCacheFile(); try { curInput = new FileInputStream(file); } catch (FileNotFoundException fnfe) { logger.error("No inputstream for "+file.getAbsolutePath()+"."); } } if (curProps==null) { file = getCurrentPropertiesFile(); try { InputStream is = new FileInputStream(file); curProps = new Properties(); curProps.load(is); is.close(); } catch (IOException e) { logger.error("No properties file for "+file.getAbsolutePath()+"."); curProps = new Properties(); } } } } } private void ensureCurrentVersionLoaded() { if (currentVersion!=-1) return; File cacheDir = getCacheLocation(); versionName = cacheDir.getName(); if (!cacheDir.exists()) { currentVersion = 0; return; } //XXX getting version from props probably a mistake if (curProps==null) { synchronized (this) { File curPropsFile = getCurrentPropertiesFile(); if (curPropsFile.exists()) { try { InputStream is = new FileInputStream(curPropsFile); curProps = new Properties(); curProps.load(is); is.close(); } catch (Exception e) { logger.error("Error loading version from "+ curPropsFile.getAbsolutePath()+"."); curProps = new Properties(); } } else { curProps = new Properties(); } } } currentVersion = Integer.parseInt( curProps.getProperty("version_number", "0")); } private File getCurrentCacheFile() { buffer = new StringBuffer(cacheLocation); buffer.append(File.separator); buffer.append(versionName); buffer.append(CURRENT_SUFFIX); return new File(buffer.toString()); } private File getCurrentPropertiesFile() { buffer = new StringBuffer(cacheLocation); buffer.append(File.separator); buffer.append(versionName); buffer.append(PROPS_SUFFIX); buffer.append(CURRENT_SUFFIX); return new File(buffer.toString()); } private File getTempCacheFile() { buffer = new StringBuffer(cacheLocation); buffer.append(File.separator); buffer.append(versionName); buffer.append(TEMP_SUFFIX); return new File(buffer.toString()); } private File getTempPropertiesFile() { buffer = new StringBuffer(cacheLocation); buffer.append(File.separator); buffer.append(versionName); buffer.append(PROPS_SUFFIX); buffer.append(TEMP_SUFFIX); return new File(buffer.toString()); } private File getVersionedCacheFile(int version) { buffer = new StringBuffer(cacheLocation); buffer.append(File.separator); buffer.append(versionName); buffer.append("."); buffer.append(version); return new File(buffer.toString()); } private File getVersionedPropertiesFile(int version) { buffer = new StringBuffer(cacheLocation); buffer.append(File.separator); buffer.append(versionName); buffer.append(PROPS_SUFFIX); buffer.append("."); buffer.append(version); return new File(buffer.toString()); } private File getCacheLocation() { return new File(cacheLocation); } }
src/org/lockss/repository/LeafNodeImpl.java
/* * $Id: LeafNodeImpl.java,v 1.2 2002-11-02 00:57:50 aalto Exp $ */ /* Copyright (c) 2002 Board of Trustees of Leland Stanford Jr. University, all rights reserved. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL STANFORD UNIVERSITY BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. Except as contained in this notice, the name of Stanford University shall not be used in advertising or otherwise to promote the sale, use or other dealings in this Software without prior written authorization from Stanford University. */ package org.lockss.repository; import java.io.*; import java.util.*; /** * LeafNodeImpl is a leaf-specific subclass of RepositoryNodeImpl. */ public class LeafNodeImpl extends RepositoryNodeImpl implements LeafNode { /** * The name of the file created in leaf cache directories. */ public static final String LEAF_FILE_NAME = "isLeaf"; private static final String CURRENT_SUFFIX = ".current"; private static final String PROPS_SUFFIX = ".props"; private static final String TEMP_SUFFIX = ".temp"; private boolean newVersionOpen = false; private OutputStream newVersionOutput; private InputStream curInput; private Properties curProps; private String versionName; private int currentVersion = -1; private StringBuffer buffer; public LeafNodeImpl(String url, String cacheLocation, LockssRepositoryImpl repository) { super(url, cacheLocation, repository); } public int getCurrentVersion() { ensureCurrentVersionLoaded(); return currentVersion; } public boolean isLeaf() { return true; } public boolean exists() { ensureCurrentVersionLoaded(); return (currentVersion > 0); } public void makeNewVersion() { if (newVersionOpen) { throw new UnsupportedOperationException("New version already"+ " initialized."); } if (currentVersion == 0) { File cacheDir = getCacheLocation(); if (!cacheDir.exists()) { cacheDir.mkdirs(); } File leafFile = new File(cacheDir, LEAF_FILE_NAME); try { leafFile.createNewFile(); } catch (IOException ioe) { logger.error("Couldn't create leaf file for " + cacheDir.getAbsolutePath()+"."); } } newVersionOpen = true; } public void sealNewVersion() { if (!newVersionOpen) { throw new UnsupportedOperationException("New version not initialized."); } synchronized (this) { File curContent = getCurrentCacheFile(); File curProps = getCurrentPropertiesFile(); File newContent = getTempCacheFile(); File newProps = getTempPropertiesFile(); // rename current curContent.renameTo(getVersionedCacheFile(currentVersion)); curProps.renameTo(getVersionedPropertiesFile(currentVersion)); // rename new newContent.renameTo(getCurrentCacheFile()); newProps.renameTo(getCurrentCacheFile()); currentVersion++; newVersionOutput = null; curInput = null; curProps = null; newVersionOpen = false; } } public InputStream getInputStream() { ensureCurrentVersionLoaded(); ensureReadInfoLoaded(); return curInput; } public Properties getProperties() { ensureCurrentVersionLoaded(); ensureReadInfoLoaded(); return curProps; } public OutputStream getNewOutputStream() { if (!newVersionOpen) { throw new UnsupportedOperationException("New version not initialized."); } if (newVersionOutput!=null) { return newVersionOutput; } File file = getTempCacheFile(); try { newVersionOutput = new FileOutputStream(file); return newVersionOutput; } catch (FileNotFoundException fnfe) { logger.error("No new version file for "+file.getAbsolutePath()+"."); return null; } } public void setNewProperties(Properties newProps) { if (!newVersionOpen) { throw new UnsupportedOperationException("New version not initialized."); } if (newProps!=null) { File file = getTempPropertiesFile(); try { OutputStream os = new FileOutputStream(file); newProps.setProperty("version_number", ""+(currentVersion+1)); newProps.store(os, "HTTP headers for " + url); os.close(); } catch (IOException ioe) { logger.error("Couldn't write properties for " + file.getAbsolutePath()+"."); } } } private void ensureReadInfoLoaded() { if ((curInput==null) || (curProps==null)) { synchronized (this) { File file = null; if (curInput==null) { file = getCurrentCacheFile(); try { curInput = new FileInputStream(file); } catch (FileNotFoundException fnfe) { logger.error("No inputstream for "+file.getAbsolutePath()+"."); } } if (curProps==null) { file = getCurrentPropertiesFile(); try { InputStream is = new FileInputStream(file); curProps = new Properties(); curProps.load(is); is.close(); } catch (IOException e) { logger.error("No properties file for "+file.getAbsolutePath()+"."); curProps = new Properties(); } } } } } private void ensureCurrentVersionLoaded() { if (currentVersion!=-1) return; File cacheDir = getCacheLocation(); versionName = cacheDir.getName(); if (!cacheDir.exists()) { currentVersion = 0; return; } //XXX getting version from props probably a mistake if (curProps==null) { synchronized (this) { File curPropsFile = getCurrentPropertiesFile(); if (curPropsFile.exists()) { try { InputStream is = new FileInputStream(curPropsFile); curProps = new Properties(); curProps.load(is); is.close(); } catch (Exception e) { logger.error("Error loading version from "+ curPropsFile.getAbsolutePath()+"."); curProps = new Properties(); } } else { curProps = new Properties(); } } } currentVersion = Integer.parseInt( curProps.getProperty("version_number", "0")); } private File getCurrentCacheFile() { buffer = new StringBuffer(cacheLocation); buffer.append(File.separator); buffer.append(versionName); buffer.append(CURRENT_SUFFIX); return new File(buffer.toString()); } private File getCurrentPropertiesFile() { buffer = new StringBuffer(cacheLocation); buffer.append(File.separator); buffer.append(versionName); buffer.append(PROPS_SUFFIX); buffer.append(CURRENT_SUFFIX); return new File(buffer.toString()); } private File getTempCacheFile() { buffer = new StringBuffer(cacheLocation); buffer.append(File.separator); buffer.append(versionName); buffer.append(TEMP_SUFFIX); return new File(buffer.toString()); } private File getTempPropertiesFile() { buffer = new StringBuffer(cacheLocation); buffer.append(File.separator); buffer.append(versionName); buffer.append(PROPS_SUFFIX); buffer.append(TEMP_SUFFIX); return new File(buffer.toString()); } private File getVersionedCacheFile(int version) { buffer = new StringBuffer(cacheLocation); buffer.append(File.separator); buffer.append(versionName); buffer.append("."); buffer.append(version); return new File(buffer.toString()); } private File getVersionedPropertiesFile(int version) { buffer = new StringBuffer(cacheLocation); buffer.append(File.separator); buffer.append(versionName); buffer.append(PROPS_SUFFIX); buffer.append("."); buffer.append(version); return new File(buffer.toString()); } private File getCacheLocation() { return new File(cacheLocation); } }
Left a line out. git-svn-id: 293778eaa97c8c94097d610b1bd5133a8f478f36@190 4f837ed2-42f5-46e7-a7a5-fa17313484d4
src/org/lockss/repository/LeafNodeImpl.java
<ide><path>rc/org/lockss/repository/LeafNodeImpl.java <ide> /* <del> * $Id: LeafNodeImpl.java,v 1.2 2002-11-02 00:57:50 aalto Exp $ <add> * $Id: LeafNodeImpl.java,v 1.3 2002-11-02 01:01:00 aalto Exp $ <ide> */ <ide> <ide> /* <ide> throw new UnsupportedOperationException("New version already"+ <ide> " initialized."); <ide> } <add> ensureCurrentVersionLoaded(); <ide> if (currentVersion == 0) { <ide> File cacheDir = getCacheLocation(); <ide> if (!cacheDir.exists()) {
Java
mit
cfb4d5993abe55d5a79aabfec5b555d89ea6b0cf
0
sddtc/couple,sddtc/couple
src/com/sddtc/utils/accounts/factory/EmailFactory.java
package com.sddtc.utils.accounts.factory; /** * @author sddtc * */ public class EmailFactory { public void send() { //...silent is gold.. } }
delete
src/com/sddtc/utils/accounts/factory/EmailFactory.java
delete
<ide><path>rc/com/sddtc/utils/accounts/factory/EmailFactory.java <del>package com.sddtc.utils.accounts.factory; <del> <del>/** <del> * @author sddtc <del> * <del> */ <del>public class EmailFactory { <del> public void send() { <del> //...silent is gold.. <del> } <del> <del>}
Java
bsd-3-clause
4f5b7dacfa4b4aac190bd012d93097631b10f561
0
hoijui/JavaOSC
/* * Copyright (C) 2004-2014, C. Ramakrishnan / Illposed Software. * All rights reserved. * * This code is licensed under the BSD 3-Clause license. * See file LICENSE (or LICENSE.html) for more information. */ package com.illposed.osc.transport.udp; import com.illposed.osc.OSCPacket; import com.illposed.osc.OSCSerializer; import com.illposed.osc.OSCSerializerFactory; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.InetAddress; import java.net.SocketException; import java.net.UnknownHostException; /** * Sends OSC packets to a specific TCP/IP address and port. * * To send an OSC message, call {@link #send(OSCPacket)}. * * An example:<br> * (loosely based on {com.illposed.osc.OSCPortTest#testMessageWithArgs()}) * <blockquote><pre>{@code * OSCPortOut sender = new OSCPortOut(); * List<Object> args = new ArrayList<Object>(2); * args.add(3); * args.add("hello"); * OSCMessage msg = new OSCMessage("/sayhello", args); * try { * sender.send(msg); * } catch (Exception ex) { * System.err.println("Couldn't send"); * } * }</pre></blockquote> */ public class OSCPortOut extends OSCPort { private final InetAddress address; private final ByteArrayOutputStream outputBuffer; private final OSCSerializer converter; /** * Create an OSCPort that sends to address:port using a specified socket * and a specified serializer. * @param serializerFactory the UDP address to send to * @param address the UDP address to send to * @param port the UDP port to send to * @param socket the DatagramSocket to send from */ public OSCPortOut( final OSCSerializerFactory serializerFactory, final InetAddress address, final int port, final DatagramSocket socket) { super(socket, port); this.address = address; this.outputBuffer = new ByteArrayOutputStream(); this.converter = serializerFactory.create(outputBuffer); } /** * Create an OSCPort that sends to address:port using a specified socket. * @param address the UDP address to send to * @param port the UDP port to send to * @param socket the DatagramSocket to send from */ public OSCPortOut(final InetAddress address, final int port, final DatagramSocket socket) { this(OSCSerializerFactory.createDefaultFactory(), address, port, socket); } /** * Create an OSCPort that sends to address:port. * @param address the UDP address to send to * @param port the UDP port to send to * @throws SocketException when failing to create a (UDP) out socket */ public OSCPortOut(final InetAddress address, final int port) throws SocketException { this(address, port, new DatagramSocket()); } /** * Create an OSCPort that sends to address, * using the standard SuperCollider port. * @param address the UDP address to send to * @throws SocketException when failing to create a (UDP) out socket */ public OSCPortOut(final InetAddress address) throws SocketException { this(address, DEFAULT_SC_OSC_PORT); } /** * Create an OSCPort that sends to "localhost", * on the standard SuperCollider port. * @throws UnknownHostException if the local host name could not be resolved into an address * @throws SocketException when failing to create a (UDP) out socket */ public OSCPortOut() throws UnknownHostException, SocketException { this(InetAddress.getLocalHost(), DEFAULT_SC_OSC_PORT); } /** * Send an OSC packet (message or bundle) to the receiver we are bound to. * @param aPacket the bundle or message to send * @throws IOException if a (UDP) socket I/O error occurs */ public void send(final OSCPacket aPacket) throws IOException { outputBuffer.reset(); converter.write(aPacket); final byte[] byteArray = outputBuffer.toByteArray(); final DatagramPacket packet = new DatagramPacket(byteArray, byteArray.length, address, getPort()); getSocket().send(packet); } @Override public String toString() { final StringBuilder rep = new StringBuilder(64); rep .append('[') .append(getClass().getSimpleName()) .append(": sending to \"") .append(address.getHostName()) .append(':') .append(getPort()) .append("\"]"); return rep.toString(); } }
modules/core/src/main/java/com/illposed/osc/transport/udp/OSCPortOut.java
/* * Copyright (C) 2004-2014, C. Ramakrishnan / Illposed Software. * All rights reserved. * * This code is licensed under the BSD 3-Clause license. * See file LICENSE (or LICENSE.html) for more information. */ package com.illposed.osc.transport.udp; import com.illposed.osc.OSCPacket; import com.illposed.osc.OSCSerializer; import com.illposed.osc.OSCSerializerFactory; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.InetAddress; import java.net.SocketException; import java.net.UnknownHostException; /** * Sends OSC packets to a specific TCP/IP address and port. * * To send an OSC message, call {@link #send(OSCPacket)}. * * An example:<br> * (loosely based on {com.illposed.osc.OSCPortTest#testMessageWithArgs()}) * <blockquote><pre>{@code * OSCPortOut sender = new OSCPortOut(); * List<Object> args = new ArrayList<Object>(2); * args.add(3); * args.add("hello"); * OSCMessage msg = new OSCMessage("/sayhello", args); * try { * sender.send(msg); * } catch (Exception ex) { * System.err.println("Couldn't send"); * } * }</pre></blockquote> */ public class OSCPortOut extends OSCPort { private final InetAddress address; private final ByteArrayOutputStream outputBuffer; private final OSCSerializer converter; /** * Create an OSCPort that sends to address:port using a specified socket * and a specified serializer. * @param serializerFactory the UDP address to send to * @param address the UDP address to send to * @param port the UDP port to send to * @param socket the DatagramSocket to send from */ public OSCPortOut( final OSCSerializerFactory serializerFactory, final InetAddress address, final int port, final DatagramSocket socket) { super(socket, port); this.address = address; this.outputBuffer = new ByteArrayOutputStream(); this.converter = serializerFactory.create(outputBuffer); } /** * Create an OSCPort that sends to address:port using a specified socket. * @param address the UDP address to send to * @param port the UDP port to send to * @param socket the DatagramSocket to send from */ public OSCPortOut(final InetAddress address, final int port, final DatagramSocket socket) { this(OSCSerializerFactory.createDefaultFactory(), address, port, socket); } /** * Create an OSCPort that sends to address:port. * @param address the UDP address to send to * @param port the UDP port to send to * @throws SocketException when failing to create a (UDP) out socket */ public OSCPortOut(final InetAddress address, final int port) throws SocketException { this(address, port, new DatagramSocket()); } /** * Create an OSCPort that sends to address, * using the standard SuperCollider port. * @param address the UDP address to send to * @throws SocketException when failing to create a (UDP) out socket */ public OSCPortOut(final InetAddress address) throws SocketException { this(address, DEFAULT_SC_OSC_PORT); } /** * Create an OSCPort that sends to "localhost", * on the standard SuperCollider port. * @throws UnknownHostException if the local host name could not be resolved into an address * @throws SocketException when failing to create a (UDP) out socket */ public OSCPortOut() throws UnknownHostException, SocketException { this(InetAddress.getLocalHost(), DEFAULT_SC_OSC_PORT); } /** * Send an OSC packet (message or bundle) to the receiver we are bound to. * @param aPacket the bundle or message to send * @throws IOException if a (UDP) socket I/O error occurs */ public void send(final OSCPacket aPacket) throws IOException { outputBuffer.reset(); converter.write(aPacket); final byte[] byteArray = outputBuffer.toByteArray(); final DatagramPacket packet = new DatagramPacket(byteArray, byteArray.length, address, getPort()); getSocket().send(packet); } }
introduce `OSCPortOut#toString()`
modules/core/src/main/java/com/illposed/osc/transport/udp/OSCPortOut.java
introduce `OSCPortOut#toString()`
<ide><path>odules/core/src/main/java/com/illposed/osc/transport/udp/OSCPortOut.java <ide> new DatagramPacket(byteArray, byteArray.length, address, getPort()); <ide> getSocket().send(packet); <ide> } <add> <add> @Override <add> public String toString() { <add> <add> final StringBuilder rep = new StringBuilder(64); <add> <add> rep <add> .append('[') <add> .append(getClass().getSimpleName()) <add> .append(": sending to \"") <add> .append(address.getHostName()) <add> .append(':') <add> .append(getPort()) <add> .append("\"]"); <add> <add> return rep.toString(); <add> } <ide> }
Java
apache-2.0
ec8ca3d073a4606e340499503c32689a0157e517
0
bonigarcia/selenium-jupiter,bonigarcia/selenium-jupiter
/* * (C) Copyright 2017 Boni Garcia (http://bonigarcia.github.io/) * * 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.bonigarcia.handler; import static com.spotify.docker.client.messages.PortBinding.randomPort; import static io.github.bonigarcia.BrowserType.ANDROID; import static io.github.bonigarcia.BrowserType.OPERA; import static io.github.bonigarcia.SeleniumJupiter.config; import static io.github.bonigarcia.SurefireReports.getOutputFolder; import static java.lang.Character.toLowerCase; import static java.lang.String.format; import static java.lang.System.currentTimeMillis; import static java.lang.Thread.currentThread; import static java.lang.Thread.sleep; import static java.lang.invoke.MethodHandles.lookup; import static java.nio.file.Files.move; import static java.nio.file.Files.write; import static java.nio.file.StandardCopyOption.REPLACE_EXISTING; import static java.util.Arrays.asList; import static java.util.concurrent.Executors.newFixedThreadPool; import static java.util.concurrent.TimeUnit.SECONDS; import static org.apache.commons.lang3.SystemUtils.IS_OS_LINUX; import static org.slf4j.LoggerFactory.getLogger; import java.io.File; import java.io.IOException; import java.lang.reflect.Constructor; import java.lang.reflect.Method; import java.lang.reflect.Parameter; import java.net.URL; import java.nio.file.Paths; import java.util.ArrayList; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutorService; import org.junit.jupiter.api.extension.ExtensionContext; import org.openqa.selenium.Capabilities; import org.openqa.selenium.MutableCapabilities; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.opera.OperaOptions; import org.openqa.selenium.remote.DesiredCapabilities; import org.openqa.selenium.remote.RemoteWebDriver; import org.openqa.selenium.remote.SessionId; import org.slf4j.Logger; import com.spotify.docker.client.exceptions.DockerCertificateException; import com.spotify.docker.client.exceptions.DockerException; import com.spotify.docker.client.messages.PortBinding; import io.appium.java_client.android.AndroidDriver; import io.github.bonigarcia.AnnotationsReader; import io.github.bonigarcia.BrowserType; import io.github.bonigarcia.DockerBrowser; import io.github.bonigarcia.DockerContainer; import io.github.bonigarcia.DockerContainer.DockerBuilder; import io.github.bonigarcia.DockerService; import io.github.bonigarcia.SeleniumJupiterException; import io.github.bonigarcia.SelenoidConfig; /** * Resolver for DockerDriver's. * * @author Boni Garcia ([email protected]) * @since 1.2.0 */ public class DockerDriverHandler { static final String ALL_IPV4_ADDRESSES = "0.0.0.0"; final Logger log = getLogger(lookup().lookupClass()); DockerService dockerService; SelenoidConfig selenoidConfig; Map<String, DockerContainer> containerMap; File recordingFile; String name; File hostVideoFolder; ExtensionContext context; Parameter parameter; Optional<Object> testInstance; AnnotationsReader annotationsReader; String index; boolean recording = config().isRecording(); String selenoidImage = config().getSelenoidImage(); String novncImage = config().getNovncImage(); String androidNoVncUrl; public DockerDriverHandler() throws DockerCertificateException { this.selenoidConfig = new SelenoidConfig(); this.dockerService = new DockerService(); this.containerMap = new LinkedHashMap<>(); } public DockerDriverHandler(ExtensionContext context, Parameter parameter, Optional<Object> testInstance, AnnotationsReader annotationsReader, Map<String, DockerContainer> containerMap, DockerService dockerService, SelenoidConfig selenoidConfig) { this.context = context; this.parameter = parameter; this.testInstance = testInstance; this.annotationsReader = annotationsReader; this.containerMap = containerMap; this.dockerService = dockerService; this.selenoidConfig = selenoidConfig; } public WebDriver resolve(DockerBrowser dockerBrowser) { BrowserType browser = dockerBrowser.type(); String version = dockerBrowser.version(); String browserName = dockerBrowser.browserName(); String deviceName = dockerBrowser.deviceName(); return resolve(browser, version, browserName, deviceName); } public WebDriver resolve(BrowserType browser, String version, String browserName, String deviceName) { try { if (recording) { hostVideoFolder = new File(getOutputFolder(context)); } WebDriver webdriver; if (browser == ANDROID) { webdriver = getDriverForAndroid(browser, version, browserName, deviceName); } else { if (selenoidConfig == null) { selenoidConfig = new SelenoidConfig(); } webdriver = getDriverForBrowser(browser, version); } return webdriver; } catch (Exception e) { log.error("Exception resolving {} ({} {})", parameter, browser, version, e); throw new SeleniumJupiterException(e); } } private WebDriver getDriverForBrowser(BrowserType browser, String version) throws IllegalAccessException, IOException, DockerException, InterruptedException { boolean enableVnc = config().isVnc(); DesiredCapabilities capabilities = getCapabilities(browser, enableVnc); String imageVersion; String versionFromLabel = version; if (version != null && !version.isEmpty() && !version.equalsIgnoreCase("latest")) { if (version.startsWith("latest-")) { versionFromLabel = selenoidConfig.getVersionFromLabel(browser, version); } imageVersion = selenoidConfig.getImageVersion(browser, versionFromLabel); capabilities.setCapability("version", imageVersion); } else { imageVersion = selenoidConfig.getDefaultBrowser(browser); } String seleniumServerUrl = config().getSeleniumServerUrl(); boolean seleniumServerUrlAvailable = seleniumServerUrl != null && !seleniumServerUrl.isEmpty(); String hubUrl = seleniumServerUrlAvailable ? seleniumServerUrl : startDockerBrowser(browser, versionFromLabel); log.trace("Using Selenium Server at {}", hubUrl); WebDriver webdriver = new RemoteWebDriver(new URL(hubUrl), capabilities); SessionId sessionId = ((RemoteWebDriver) webdriver).getSessionId(); updateName(browser, imageVersion, webdriver); if (enableVnc && !seleniumServerUrlAvailable) { URL selenoidHubUrl = new URL(hubUrl); String selenoidHost = selenoidHubUrl.getHost(); int selenoidPort = selenoidHubUrl.getPort(); String novncUrl = getNoVncUrl(selenoidHost, selenoidPort, sessionId.toString(), config().getSelenoidVncPassword()); logSessionId(sessionId); logNoVncUrl(novncUrl); String vncExport = config().getVncExport(); log.trace("Exporting VNC URL as Java property {}", vncExport); System.setProperty(vncExport, novncUrl); if (config().isVncRedirectHtmlPage()) { String outputFolder = getOutputFolder(context); String vncHtmlPage = format("<!DOCTYPE html>\n" + "<html>\n" + "<head>\n" + "<meta http-equiv=\"refresh\" content=\"0; url=%s\">\n" + "</head>\n" + "<body>\n" + "</body>\n" + "</html>", novncUrl); write(Paths.get(outputFolder, name + ".html"), vncHtmlPage.getBytes()); } } if (recording) { recordingFile = new File(hostVideoFolder, sessionId + ".mp4"); } return webdriver; } private void logSessionId(SessionId sessionId) { log.info("Session id {}", sessionId); } private void logNoVncUrl(String novncUrl) { log.info( "VNC URL (copy and paste in a browser navigation bar to interact with remote session)"); log.info("{}", novncUrl); } private WebDriver getDriverForAndroid(BrowserType browser, String version, String browserName, String deviceName) throws DockerException, InterruptedException, IOException { browser.init(); DesiredCapabilities capabilities = browser.getCapabilities(); String browserNameCapability = browserName != null && !browserName.isEmpty() ? browserName : config().getAndroidBrowserName(); String deviceNameCapability = deviceName != null && !deviceName.isEmpty() ? deviceName : config().getAndroidDeviceName(); capabilities.setCapability("browserName", browserNameCapability); capabilities.setCapability("deviceName", deviceNameCapability); String appiumUrl = startAndroidBrowser(version, deviceNameCapability); AndroidDriver<WebElement> androidDriver = null; log.info("Appium URL in Android device: {}", appiumUrl); log.info("Android device name: {} -- Browser in Android device: {}", deviceNameCapability, browserNameCapability); log.info( "Waiting for Android device ... this might take long, please wait (retries each 5 seconds)"); int androidDeviceTimeoutSec = config().getAndroidDeviceTimeoutSec(); long endTimeMillis = currentTimeMillis() + androidDeviceTimeoutSec * 1000; do { try { androidDriver = new AndroidDriver<>(new URL(appiumUrl), capabilities); } catch (Exception e) { if (currentTimeMillis() > endTimeMillis) { throw new SeleniumJupiterException("Timeout (" + androidDeviceTimeoutSec + " seconds) waiting for Android device in Docker"); } String errorMessage = e.getMessage(); int i = errorMessage.indexOf("\n"); if (i != -1) { errorMessage = errorMessage.substring(0, i); } log.debug("Android device not ready: {}", errorMessage); sleep(5000); } } while (androidDriver == null); log.info("Android device ready {}", androidDriver); if (config().isVnc()) { SessionId sessionId = ((RemoteWebDriver) androidDriver) .getSessionId(); logSessionId(sessionId); logNoVncUrl(androidNoVncUrl); } return androidDriver; } private void updateName(BrowserType browser, String imageVersion, WebDriver webdriver) { if (parameter != null) { String parameterName = parameter.getName(); name = parameterName + "_" + browser + "_" + imageVersion + "_" + ((RemoteWebDriver) webdriver).getSessionId(); Optional<Method> testMethod = context.getTestMethod(); if (testMethod.isPresent()) { name = testMethod.get().getName() + "_" + name; } if (index != null) { name += index; } } else { name = browser.name().toLowerCase(); } } private DesiredCapabilities getCapabilities(BrowserType browser, boolean enableVnc) throws IllegalAccessException, IOException { DesiredCapabilities capabilities = browser.getCapabilities(); if (enableVnc) { capabilities.setCapability("enableVNC", true); capabilities.setCapability("screenResolution", config().getVncScreenResolution()); } if (recording) { capabilities.setCapability("enableVideo", true); capabilities.setCapability("videoScreenSize", config().getRecordingVideoScreenSize()); capabilities.setCapability("videoFrameRate", config().getRecordingVideoFrameRate()); } Optional<Capabilities> optionalCapabilities = annotationsReader != null ? annotationsReader.getCapabilities(parameter, testInstance) : Optional.of(new DesiredCapabilities()); MutableCapabilities options = browser.getDriverHandler() .getOptions(parameter, testInstance); // Due to bug in operablink the binary path must be set if (browser == OPERA) { ((OperaOptions) options).setBinary("/usr/bin/opera"); } if (optionalCapabilities.isPresent()) { options.merge(optionalCapabilities.get()); } capabilities.setCapability(browser.getOptionsKey(), options); log.trace("Using {}", capabilities); return capabilities; } public String getName() { return name; } public void cleanup() { try { // Wait for recordings if (recording) { waitForRecording(); } // Clear VNC URL String vncExport = config().getVncExport(); if (config().isVnc() && System.getProperty(vncExport) != null) { log.trace("Clearing Java property {}", vncExport); System.clearProperty(vncExport); } } catch (Exception e) { log.warn("Exception waiting for recording {}", e.getMessage()); } finally { // Stop containers if (containerMap != null && !containerMap.isEmpty() && dockerService != null) { int numContainers = containerMap.size(); if (numContainers > 0) { ExecutorService executorService = newFixedThreadPool( numContainers); CountDownLatch latch = new CountDownLatch(numContainers); for (Map.Entry<String, DockerContainer> entry : containerMap .entrySet()) { executorService.submit(() -> { dockerService.stopAndRemoveContainer( entry.getValue().getContainerId(), entry.getKey()); latch.countDown(); }); } containerMap.clear(); try { latch.await(); } catch (InterruptedException e) { log.warn("Exception cleaning Docker containers {}", e.getMessage()); currentThread().interrupt(); } executorService.shutdown(); } } } } public void close() { dockerService.close(); } private String startAndroidBrowser(String version, String deviceName) throws DockerException, InterruptedException, IOException { if (version == null || version.isEmpty()) { version = config().getAndroidDefaultVersion(); } String androidImage; String apiLevel; switch (version) { case "5.0.1": androidImage = IS_OS_LINUX ? config().getAndroidImageApi21Linux() : config().getAndroidImageApi21OsxWin(); apiLevel = "21"; break; case "5.1.1": androidImage = IS_OS_LINUX ? config().getAndroidImageApi22Linux() : config().getAndroidImageApi22OsxWin(); apiLevel = "22"; break; case "6.0": androidImage = IS_OS_LINUX ? config().getAndroidImageApi23Linux() : config().getAndroidImageApi23OsxWin(); apiLevel = "23"; break; case "7.0": androidImage = IS_OS_LINUX ? config().getAndroidImageApi24Linux() : config().getAndroidImageApi24OsxWin(); apiLevel = "24"; break; case "7.1.1": androidImage = IS_OS_LINUX ? config().getAndroidImageApi25Linux() : config().getAndroidImageApi25OsxWin(); apiLevel = "25"; break; default: throw new SeleniumJupiterException( "Version " + version + " not valid for Android devices"); } log.info("Using Android version {} (API level {})", version, apiLevel); dockerService.pullImage(androidImage); DockerContainer androidContainer = startAndroidContainer(androidImage, deviceName); return androidContainer.getContainerUrl(); } private String startDockerBrowser(BrowserType browser, String version) throws DockerException, InterruptedException, IOException { String browserImage; if (version == null || version.isEmpty() || version.equalsIgnoreCase("latest")) { log.info("Using {} version {} (latest)", browser, selenoidConfig.getDefaultBrowser(browser)); browserImage = selenoidConfig.getLatestImage(browser); } else { log.info("Using {} version {}", browser, version); browserImage = selenoidConfig.getImageFromVersion(browser, version); } dockerService.pullImage(browserImage); DockerContainer selenoidContainer = startSelenoidContainer(); return selenoidContainer.getContainerUrl(); } public DockerContainer startSelenoidContainer() throws DockerException, InterruptedException, IOException { DockerContainer selenoidContainer; if (containerMap.containsKey(selenoidImage)) { log.trace("Selenoid container already available"); selenoidContainer = containerMap.get(selenoidImage); } else { // Pull images dockerService.pullImageIfNecessary(selenoidImage); String recordingImage = config().getRecordingImage(); if (recording) { dockerService.pullImageIfNecessary(recordingImage); } // portBindings Map<String, List<PortBinding>> portBindings = new HashMap<>(); String defaultSelenoidPort = config().getSelenoidPort(); String internalSelenoidPort = defaultSelenoidPort; portBindings.put(internalSelenoidPort, asList(randomPort(ALL_IPV4_ADDRESSES))); // binds String defaultSocket = dockerService.getDockerDefaultSocket(); List<String> binds = new ArrayList<>(); binds.add(defaultSocket + ":" + defaultSocket); if (recording) { binds.add(getDockerPath(hostVideoFolder) + ":/opt/selenoid/video"); } // entrypoint & cmd List<String> entryPoint = asList(""); String internalBrowserPort = config().getSelenoidPort(); String browsersJson = selenoidConfig.getBrowsersJsonAsString(); String browserTimeout = config().getBrowserSessionTimeoutDuration(); String network = config().getDockerNetwork(); List<String> cmd = asList("sh", "-c", "mkdir -p /etc/selenoid/; echo '" + browsersJson + "' > /etc/selenoid/browsers.json; /usr/bin/selenoid" + " -listen :" + internalBrowserPort + " -conf /etc/selenoid/browsers.json" + " -video-output-dir /opt/selenoid/video/" + " -timeout " + browserTimeout + " -container-network " + network + " -limit " + getDockerBrowserCount()); // envs List<String> envs = new ArrayList<>(); envs.add("DOCKER_API_VERSION=" + config().getDockerApiVersion()); envs.add("TZ=" + config().getDockerTimeZone()); if (recording) { envs.add("OVERRIDE_VIDEO_OUTPUT_DIR=" + getDockerPath(hostVideoFolder)); } // Build container DockerBuilder dockerBuilder = DockerContainer .dockerBuilder(selenoidImage).portBindings(portBindings) .binds(binds).cmd(cmd).entryPoint(entryPoint).envs(envs) .network(network); selenoidContainer = dockerBuilder.build(); String containerId = dockerService .startContainer(selenoidContainer); String selenoidHost = dockerService.getHost(containerId, network); String selenoidPort = dockerService.getBindPort(containerId, internalSelenoidPort + "/tcp"); String selenoidUrl = format("http://%s:%s/wd/hub", selenoidHost, selenoidPort); selenoidContainer.setContainerId(containerId); selenoidContainer.setContainerUrl(selenoidUrl); containerMap.put(selenoidImage, selenoidContainer); } return selenoidContainer; } public DockerContainer startAndroidContainer(String androidImage, String deviceName) throws DockerException, InterruptedException, IOException { DockerContainer androidContainer; if (containerMap.containsKey(androidImage)) { log.trace("Android container already available"); androidContainer = containerMap.get(androidImage); } else { // Pull image dockerService.pullImageIfNecessary(androidImage); // portBindings Map<String, List<PortBinding>> portBindings = new HashMap<>(); String internalAppiumPort = config().getAndroidAppiumPort(); portBindings.put(internalAppiumPort, asList(randomPort(ALL_IPV4_ADDRESSES))); String internalNoVncPort = config().getAndroidNoVncPort(); portBindings.put(internalNoVncPort, asList(randomPort(ALL_IPV4_ADDRESSES))); // binds List<String> binds = new ArrayList<>(); if (recording) { binds.add(getDockerPath(hostVideoFolder) + ":/tmp/video"); } // network String network = config().getDockerNetwork(); // envs List<String> envs = new ArrayList<>(); envs.add("DEVICE=" + deviceName); envs.add("APPIUM=True"); if (recording) { envs.add("AUTO_RECORD=True"); } // Build container DockerBuilder dockerBuilder = DockerContainer .dockerBuilder(androidImage).portBindings(portBindings) .binds(binds).envs(envs).network(network).privileged(); androidContainer = dockerBuilder.build(); String containerId = dockerService.startContainer(androidContainer); String androidHost = dockerService.getHost(containerId, network); String androidPort = dockerService.getBindPort(containerId, internalAppiumPort + "/tcp"); String appiumUrl = format("http://%s:%s/wd/hub", androidHost, androidPort); androidContainer.setContainerId(containerId); androidContainer.setContainerUrl(appiumUrl); String androidNoVncPort = dockerService.getBindPort(containerId, internalNoVncPort + "/tcp"); androidNoVncUrl = format("http://%s:%s/vnc.html?autoconnect=true", androidHost, androidNoVncPort); containerMap.put(androidImage, androidContainer); } return androidContainer; } private int getDockerBrowserCount() { int count = 0; if (context != null) { Optional<Class<?>> testClass = context.getTestClass(); if (testClass.isPresent()) { Constructor<?>[] declaredConstructors = testClass.get() .getDeclaredConstructors(); for (Constructor<?> constructor : declaredConstructors) { Parameter[] parameters = constructor.getParameters(); count += getDockerBrowsersInParams(parameters); } Method[] declaredMethods = testClass.get().getDeclaredMethods(); for (Method method : declaredMethods) { Parameter[] parameters = method.getParameters(); count += getDockerBrowsersInParams(parameters); } } } else { // Interactive mode count = 1; } log.trace("Number of required Docker browser(s): {}", count); return count; } private int getDockerBrowsersInParams(Parameter[] parameters) { int count = 0; for (Parameter param : parameters) { Class<?> type = param.getType(); if (WebDriver.class.isAssignableFrom(type)) { count++; } else if (type.isAssignableFrom(List.class)) { DockerBrowser dockerBrowser = param .getAnnotation(DockerBrowser.class); if (dockerBrowser != null) { count += dockerBrowser.size(); } } } return count; } private String getNoVncUrl(String selenoidHost, int selenoidPort, String sessionId, String novncPassword) throws DockerException, InterruptedException, IOException { DockerContainer novncContainer = startNoVncContainer(); String novncUrl = novncContainer.getContainerUrl(); return format(novncUrl + "vnc.html?host=%s&port=%d&path=vnc/%s&resize=scale&autoconnect=true&password=%s", selenoidHost, selenoidPort, sessionId, novncPassword); } public DockerContainer startNoVncContainer() throws DockerException, InterruptedException, IOException { DockerContainer novncContainer; if (containerMap.containsKey(novncImage)) { log.debug("noVNC container already available"); novncContainer = containerMap.get(novncImage); } else { dockerService.pullImageIfNecessary(novncImage); Map<String, List<PortBinding>> portBindings = new HashMap<>(); String defaultNovncPort = config().getNovncPort(); portBindings.put(defaultNovncPort, asList(randomPort(ALL_IPV4_ADDRESSES))); String network = config().getDockerNetwork(); novncContainer = DockerContainer.dockerBuilder(novncImage) .portBindings(portBindings).network(network).build(); String containerId = dockerService.startContainer(novncContainer); String novncHost = dockerService.getHost(containerId, network); String novncPort = dockerService.getBindPort(containerId, defaultNovncPort + "/tcp"); String novncUrl = format("http://%s:%s/", novncHost, novncPort); novncContainer.setContainerId(containerId); novncContainer.setContainerUrl(novncUrl); containerMap.put(novncImage, novncContainer); } return novncContainer; } private String getDockerPath(File file) { String fileString = file.getAbsolutePath(); if (fileString.contains(":")) { // Windows fileString = toLowerCase(fileString.charAt(0)) + fileString.substring(1); fileString = fileString.replaceAll("\\\\", "/"); fileString = fileString.replaceAll(":", ""); fileString = "/" + fileString; } log.trace("The path of file {} in Docker format is {}", file, fileString); return fileString; } private void waitForRecording() throws IOException { int dockerWaitTimeoutSec = dockerService.getDockerWaitTimeoutSec(); int dockerPollTimeMs = dockerService.getDockerPollTimeMs(); long timeoutMs = currentTimeMillis() + SECONDS.toMillis(dockerWaitTimeoutSec); log.debug("Waiting for recording {} to be available", recordingFile); while (!recordingFile.exists()) { if (currentTimeMillis() > timeoutMs) { log.warn("Timeout of {} seconds waiting for file {}", dockerWaitTimeoutSec, recordingFile); break; } log.trace("Recording {} not present ... waiting {} ms", recordingFile, dockerPollTimeMs); try { sleep(dockerPollTimeMs); } catch (InterruptedException e) { log.warn("Interrupted Exception while waiting for container", e); currentThread().interrupt(); } } log.trace("Renaming {} to {}.mp4", recordingFile, name); move(recordingFile.toPath(), recordingFile.toPath().resolveSibling(name + ".mp4"), REPLACE_EXISTING); } public Map<String, DockerContainer> getContainerMap() { return containerMap; } public void setIndex(String index) { this.index = index; } }
src/main/java/io/github/bonigarcia/handler/DockerDriverHandler.java
/* * (C) Copyright 2017 Boni Garcia (http://bonigarcia.github.io/) * * 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.bonigarcia.handler; import static com.spotify.docker.client.messages.PortBinding.randomPort; import static io.github.bonigarcia.BrowserType.ANDROID; import static io.github.bonigarcia.BrowserType.OPERA; import static io.github.bonigarcia.SeleniumJupiter.config; import static io.github.bonigarcia.SurefireReports.getOutputFolder; import static java.lang.Character.toLowerCase; import static java.lang.String.format; import static java.lang.System.currentTimeMillis; import static java.lang.Thread.currentThread; import static java.lang.Thread.sleep; import static java.lang.invoke.MethodHandles.lookup; import static java.nio.file.Files.move; import static java.nio.file.Files.write; import static java.nio.file.StandardCopyOption.REPLACE_EXISTING; import static java.util.Arrays.asList; import static java.util.concurrent.Executors.newFixedThreadPool; import static java.util.concurrent.TimeUnit.SECONDS; import static org.apache.commons.lang3.SystemUtils.IS_OS_LINUX; import static org.slf4j.LoggerFactory.getLogger; import java.io.File; import java.io.IOException; import java.lang.reflect.Constructor; import java.lang.reflect.Method; import java.lang.reflect.Parameter; import java.net.URL; import java.nio.file.Paths; import java.util.ArrayList; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutorService; import org.junit.jupiter.api.extension.ExtensionContext; import org.openqa.selenium.Capabilities; import org.openqa.selenium.MutableCapabilities; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.opera.OperaOptions; import org.openqa.selenium.remote.DesiredCapabilities; import org.openqa.selenium.remote.RemoteWebDriver; import org.openqa.selenium.remote.SessionId; import org.slf4j.Logger; import com.spotify.docker.client.exceptions.DockerCertificateException; import com.spotify.docker.client.exceptions.DockerException; import com.spotify.docker.client.messages.PortBinding; import io.appium.java_client.android.AndroidDriver; import io.github.bonigarcia.AnnotationsReader; import io.github.bonigarcia.BrowserType; import io.github.bonigarcia.DockerBrowser; import io.github.bonigarcia.DockerContainer; import io.github.bonigarcia.DockerContainer.DockerBuilder; import io.github.bonigarcia.DockerService; import io.github.bonigarcia.SeleniumJupiterException; import io.github.bonigarcia.SelenoidConfig; /** * Resolver for DockerDriver's. * * @author Boni Garcia ([email protected]) * @since 1.2.0 */ public class DockerDriverHandler { static final String ALL_IPV4_ADDRESSES = "0.0.0.0"; final Logger log = getLogger(lookup().lookupClass()); DockerService dockerService; SelenoidConfig selenoidConfig; Map<String, DockerContainer> containerMap; File recordingFile; String name; File hostVideoFolder; ExtensionContext context; Parameter parameter; Optional<Object> testInstance; AnnotationsReader annotationsReader; String index; boolean recording = config().isRecording(); String selenoidImage = config().getSelenoidImage(); String novncImage = config().getNovncImage(); public DockerDriverHandler() throws DockerCertificateException { this.selenoidConfig = new SelenoidConfig(); this.dockerService = new DockerService(); this.containerMap = new LinkedHashMap<>(); } public DockerDriverHandler(ExtensionContext context, Parameter parameter, Optional<Object> testInstance, AnnotationsReader annotationsReader, Map<String, DockerContainer> containerMap, DockerService dockerService, SelenoidConfig selenoidConfig) { this.context = context; this.parameter = parameter; this.testInstance = testInstance; this.annotationsReader = annotationsReader; this.containerMap = containerMap; this.dockerService = dockerService; this.selenoidConfig = selenoidConfig; } public WebDriver resolve(DockerBrowser dockerBrowser) { BrowserType browser = dockerBrowser.type(); String version = dockerBrowser.version(); String browserName = dockerBrowser.browserName(); String deviceName = dockerBrowser.deviceName(); return resolve(browser, version, browserName, deviceName); } public WebDriver resolve(BrowserType browser, String version, String browserName, String deviceName) { try { if (recording) { hostVideoFolder = new File(getOutputFolder(context)); } WebDriver webdriver; if (browser == ANDROID) { webdriver = getDriverForAndroid(browser, version, browserName, deviceName); } else { if (selenoidConfig == null) { selenoidConfig = new SelenoidConfig(); } webdriver = getDriverForBrowser(browser, version); } return webdriver; } catch (Exception e) { log.error("Exception resolving {} ({} {})", parameter, browser, version, e); throw new SeleniumJupiterException(e); } } private WebDriver getDriverForBrowser(BrowserType browser, String version) throws IllegalAccessException, IOException, DockerException, InterruptedException { boolean enableVnc = config().isVnc(); DesiredCapabilities capabilities = getCapabilities(browser, enableVnc); String imageVersion; String versionFromLabel = version; if (version != null && !version.isEmpty() && !version.equalsIgnoreCase("latest")) { if (version.startsWith("latest-")) { versionFromLabel = selenoidConfig.getVersionFromLabel(browser, version); } imageVersion = selenoidConfig.getImageVersion(browser, versionFromLabel); capabilities.setCapability("version", imageVersion); } else { imageVersion = selenoidConfig.getDefaultBrowser(browser); } String seleniumServerUrl = config().getSeleniumServerUrl(); boolean seleniumServerUrlAvailable = seleniumServerUrl != null && !seleniumServerUrl.isEmpty(); String hubUrl = seleniumServerUrlAvailable ? seleniumServerUrl : startDockerBrowser(browser, versionFromLabel); log.trace("Using Selenium Server at {}", hubUrl); WebDriver webdriver = new RemoteWebDriver(new URL(hubUrl), capabilities); SessionId sessionId = ((RemoteWebDriver) webdriver).getSessionId(); updateName(browser, imageVersion, webdriver); if (enableVnc && !seleniumServerUrlAvailable) { URL selenoidHubUrl = new URL(hubUrl); String selenoidHost = selenoidHubUrl.getHost(); int selenoidPort = selenoidHubUrl.getPort(); String novncUrl = getNoVncUrl(selenoidHost, selenoidPort, sessionId.toString(), config().getSelenoidVncPassword()); log.info("Session id {}", sessionId); log.info( "VNC URL (copy and paste in a browser navigation bar to interact with remote session)"); log.info("{}", novncUrl); String vncExport = config().getVncExport(); log.trace("Exporting VNC URL as Java property {}", vncExport); System.setProperty(vncExport, novncUrl); if (config().isVncRedirectHtmlPage()) { String outputFolder = getOutputFolder(context); String vncHtmlPage = format("<!DOCTYPE html>\n" + "<html>\n" + "<head>\n" + "<meta http-equiv=\"refresh\" content=\"0; url=%s\">\n" + "</head>\n" + "<body>\n" + "</body>\n" + "</html>", novncUrl); write(Paths.get(outputFolder, name + ".html"), vncHtmlPage.getBytes()); } } if (recording) { recordingFile = new File(hostVideoFolder, sessionId + ".mp4"); } return webdriver; } private WebDriver getDriverForAndroid(BrowserType browser, String version, String browserName, String deviceName) throws DockerException, InterruptedException, IOException { browser.init(); DesiredCapabilities capabilities = browser.getCapabilities(); String browserNameCapability = browserName != null && !browserName.isEmpty() ? browserName : config().getAndroidBrowserName(); String deviceNameCapability = deviceName != null && !deviceName.isEmpty() ? deviceName : config().getAndroidDeviceName(); capabilities.setCapability("browserName", browserNameCapability); capabilities.setCapability("deviceName", deviceNameCapability); String appiumUrl = startAndroidBrowser(version, deviceNameCapability); AndroidDriver<WebElement> androidDriver = null; log.info("Appium URL in Android device: {}", appiumUrl); log.info("Android device name: {} -- Browser in Android device: {}", deviceNameCapability, browserNameCapability); log.info( "Waiting for Android device ... this might take long, please wait (retries each 5 seconds)"); int androidDeviceTimeoutSec = config().getAndroidDeviceTimeoutSec(); long endTimeMillis = currentTimeMillis() + androidDeviceTimeoutSec * 1000; do { try { androidDriver = new AndroidDriver<>(new URL(appiumUrl), capabilities); } catch (Exception e) { if (currentTimeMillis() > endTimeMillis) { throw new SeleniumJupiterException("Timeout (" + androidDeviceTimeoutSec + " seconds) waiting for Android device in Docker"); } String errorMessage = e.getMessage(); int i = errorMessage.indexOf("\n"); if (i != -1) { errorMessage = errorMessage.substring(0, i); } log.debug("Android device not ready: {}", errorMessage); sleep(5000); } } while (androidDriver == null); log.info("Android device ready {}", androidDriver); return androidDriver; } private void updateName(BrowserType browser, String imageVersion, WebDriver webdriver) { if (parameter != null) { String parameterName = parameter.getName(); name = parameterName + "_" + browser + "_" + imageVersion + "_" + ((RemoteWebDriver) webdriver).getSessionId(); Optional<Method> testMethod = context.getTestMethod(); if (testMethod.isPresent()) { name = testMethod.get().getName() + "_" + name; } if (index != null) { name += index; } } else { name = browser.name().toLowerCase(); } } private DesiredCapabilities getCapabilities(BrowserType browser, boolean enableVnc) throws IllegalAccessException, IOException { DesiredCapabilities capabilities = browser.getCapabilities(); if (enableVnc) { capabilities.setCapability("enableVNC", true); capabilities.setCapability("screenResolution", config().getVncScreenResolution()); } if (recording) { capabilities.setCapability("enableVideo", true); capabilities.setCapability("videoScreenSize", config().getRecordingVideoScreenSize()); capabilities.setCapability("videoFrameRate", config().getRecordingVideoFrameRate()); } Optional<Capabilities> optionalCapabilities = annotationsReader != null ? annotationsReader.getCapabilities(parameter, testInstance) : Optional.of(new DesiredCapabilities()); MutableCapabilities options = browser.getDriverHandler() .getOptions(parameter, testInstance); // Due to bug in operablink the binary path must be set if (browser == OPERA) { ((OperaOptions) options).setBinary("/usr/bin/opera"); } if (optionalCapabilities.isPresent()) { options.merge(optionalCapabilities.get()); } capabilities.setCapability(browser.getOptionsKey(), options); log.trace("Using {}", capabilities); return capabilities; } public String getName() { return name; } public void cleanup() { try { // Wait for recordings if (recording) { waitForRecording(); } // Clear VNC URL String vncExport = config().getVncExport(); if (config().isVnc() && System.getProperty(vncExport) != null) { log.trace("Clearing Java property {}", vncExport); System.clearProperty(vncExport); } } catch (Exception e) { log.warn("Exception waiting for recording {}", e.getMessage()); } finally { // Stop containers if (containerMap != null && !containerMap.isEmpty() && dockerService != null) { int numContainers = containerMap.size(); if (numContainers > 0) { ExecutorService executorService = newFixedThreadPool( numContainers); CountDownLatch latch = new CountDownLatch(numContainers); for (Map.Entry<String, DockerContainer> entry : containerMap .entrySet()) { executorService.submit(() -> { dockerService.stopAndRemoveContainer( entry.getValue().getContainerId(), entry.getKey()); latch.countDown(); }); } containerMap.clear(); try { latch.await(); } catch (InterruptedException e) { log.warn("Exception cleaning Docker containers {}", e.getMessage()); currentThread().interrupt(); } executorService.shutdown(); } } } } public void close() { dockerService.close(); } private String startAndroidBrowser(String version, String deviceName) throws DockerException, InterruptedException, IOException { if (version == null || version.isEmpty()) { version = config().getAndroidDefaultVersion(); } String androidImage; String apiLevel; switch (version) { case "5.0.1": androidImage = IS_OS_LINUX ? config().getAndroidImageApi21Linux() : config().getAndroidImageApi21OsxWin(); apiLevel = "21"; break; case "5.1.1": androidImage = IS_OS_LINUX ? config().getAndroidImageApi22Linux() : config().getAndroidImageApi22OsxWin(); apiLevel = "22"; break; case "6.0": androidImage = IS_OS_LINUX ? config().getAndroidImageApi23Linux() : config().getAndroidImageApi23OsxWin(); apiLevel = "23"; break; case "7.0": androidImage = IS_OS_LINUX ? config().getAndroidImageApi24Linux() : config().getAndroidImageApi24OsxWin(); apiLevel = "24"; break; case "7.1.1": androidImage = IS_OS_LINUX ? config().getAndroidImageApi25Linux() : config().getAndroidImageApi25OsxWin(); apiLevel = "25"; break; default: throw new SeleniumJupiterException( "Version " + version + " not valid for Android devices"); } log.info("Using Android version {} (API level {})", version, apiLevel); dockerService.pullImage(androidImage); DockerContainer androidContainer = startAndroidContainer(androidImage, deviceName); return androidContainer.getContainerUrl(); } private String startDockerBrowser(BrowserType browser, String version) throws DockerException, InterruptedException, IOException { String browserImage; if (version == null || version.isEmpty() || version.equalsIgnoreCase("latest")) { log.info("Using {} version {} (latest)", browser, selenoidConfig.getDefaultBrowser(browser)); browserImage = selenoidConfig.getLatestImage(browser); } else { log.info("Using {} version {}", browser, version); browserImage = selenoidConfig.getImageFromVersion(browser, version); } dockerService.pullImage(browserImage); DockerContainer selenoidContainer = startSelenoidContainer(); return selenoidContainer.getContainerUrl(); } public DockerContainer startSelenoidContainer() throws DockerException, InterruptedException, IOException { DockerContainer selenoidContainer; if (containerMap.containsKey(selenoidImage)) { log.trace("Selenoid container already available"); selenoidContainer = containerMap.get(selenoidImage); } else { // Pull images dockerService.pullImageIfNecessary(selenoidImage); String recordingImage = config().getRecordingImage(); if (recording) { dockerService.pullImageIfNecessary(recordingImage); } // portBindings Map<String, List<PortBinding>> portBindings = new HashMap<>(); String defaultSelenoidPort = config().getSelenoidPort(); String internalSelenoidPort = defaultSelenoidPort; portBindings.put(internalSelenoidPort, asList(randomPort(ALL_IPV4_ADDRESSES))); // binds String defaultSocket = dockerService.getDockerDefaultSocket(); List<String> binds = new ArrayList<>(); binds.add(defaultSocket + ":" + defaultSocket); if (recording) { binds.add(getDockerPath(hostVideoFolder) + ":/opt/selenoid/video"); } // entrypoint & cmd List<String> entryPoint = asList(""); String internalBrowserPort = config().getSelenoidPort(); String browsersJson = selenoidConfig.getBrowsersJsonAsString(); String browserTimeout = config().getBrowserSessionTimeoutDuration(); String network = config().getDockerNetwork(); List<String> cmd = asList("sh", "-c", "mkdir -p /etc/selenoid/; echo '" + browsersJson + "' > /etc/selenoid/browsers.json; /usr/bin/selenoid" + " -listen :" + internalBrowserPort + " -conf /etc/selenoid/browsers.json" + " -video-output-dir /opt/selenoid/video/" + " -timeout " + browserTimeout + " -container-network " + network + " -limit " + getDockerBrowserCount()); // envs List<String> envs = new ArrayList<>(); envs.add("DOCKER_API_VERSION=" + config().getDockerApiVersion()); envs.add("TZ=" + config().getDockerTimeZone()); if (recording) { envs.add("OVERRIDE_VIDEO_OUTPUT_DIR=" + getDockerPath(hostVideoFolder)); } // Build container DockerBuilder dockerBuilder = DockerContainer .dockerBuilder(selenoidImage).portBindings(portBindings) .binds(binds).cmd(cmd).entryPoint(entryPoint).envs(envs) .network(network); selenoidContainer = dockerBuilder.build(); String containerId = dockerService .startContainer(selenoidContainer); String selenoidHost = dockerService.getHost(containerId, network); String selenoidPort = dockerService.getBindPort(containerId, internalSelenoidPort + "/tcp"); String selenoidUrl = format("http://%s:%s/wd/hub", selenoidHost, selenoidPort); selenoidContainer.setContainerId(containerId); selenoidContainer.setContainerUrl(selenoidUrl); containerMap.put(selenoidImage, selenoidContainer); } return selenoidContainer; } public DockerContainer startAndroidContainer(String androidImage, String deviceName) throws DockerException, InterruptedException, IOException { DockerContainer androidContainer; if (containerMap.containsKey(androidImage)) { log.trace("Android container already available"); androidContainer = containerMap.get(androidImage); } else { // Pull image dockerService.pullImageIfNecessary(androidImage); // portBindings Map<String, List<PortBinding>> portBindings = new HashMap<>(); String internalAppiumPort = config().getAndroidAppiumPort(); portBindings.put(internalAppiumPort, asList(randomPort(ALL_IPV4_ADDRESSES))); String internalNoVncPort = config().getAndroidNoVncPort(); portBindings.put(internalNoVncPort, asList(randomPort(ALL_IPV4_ADDRESSES))); // binds List<String> binds = new ArrayList<>(); if (recording) { binds.add(getDockerPath(hostVideoFolder) + ":/tmp/video"); } // network String network = config().getDockerNetwork(); // envs List<String> envs = new ArrayList<>(); envs.add("DEVICE=" + deviceName); envs.add("APPIUM=True"); if (recording) { envs.add("AUTO_RECORD=True"); } // Build container DockerBuilder dockerBuilder = DockerContainer .dockerBuilder(androidImage).portBindings(portBindings) .binds(binds).envs(envs).network(network).privileged(); androidContainer = dockerBuilder.build(); String containerId = dockerService.startContainer(androidContainer); String androidHost = dockerService.getHost(containerId, network); String androidPort = dockerService.getBindPort(containerId, internalAppiumPort + "/tcp"); String appiumUrl = format("http://%s:%s/wd/hub", androidHost, androidPort); androidContainer.setContainerId(containerId); androidContainer.setContainerUrl(appiumUrl); containerMap.put(androidImage, androidContainer); } return androidContainer; } private int getDockerBrowserCount() { int count = 0; if (context != null) { Optional<Class<?>> testClass = context.getTestClass(); if (testClass.isPresent()) { Constructor<?>[] declaredConstructors = testClass.get() .getDeclaredConstructors(); for (Constructor<?> constructor : declaredConstructors) { Parameter[] parameters = constructor.getParameters(); count += getDockerBrowsersInParams(parameters); } Method[] declaredMethods = testClass.get().getDeclaredMethods(); for (Method method : declaredMethods) { Parameter[] parameters = method.getParameters(); count += getDockerBrowsersInParams(parameters); } } } else { // Interactive mode count = 1; } log.trace("Number of required Docker browser(s): {}", count); return count; } private int getDockerBrowsersInParams(Parameter[] parameters) { int count = 0; for (Parameter param : parameters) { Class<?> type = param.getType(); if (WebDriver.class.isAssignableFrom(type)) { count++; } else if (type.isAssignableFrom(List.class)) { DockerBrowser dockerBrowser = param .getAnnotation(DockerBrowser.class); if (dockerBrowser != null) { count += dockerBrowser.size(); } } } return count; } private String getNoVncUrl(String selenoidHost, int selenoidPort, String sessionId, String novncPassword) throws DockerException, InterruptedException, IOException { DockerContainer novncContainer = startNoVncContainer(); String novncUrl = novncContainer.getContainerUrl(); return format(novncUrl + "vnc.html?host=%s&port=%d&path=vnc/%s&resize=scale&autoconnect=true&password=%s", selenoidHost, selenoidPort, sessionId, novncPassword); } public DockerContainer startNoVncContainer() throws DockerException, InterruptedException, IOException { DockerContainer novncContainer; if (containerMap.containsKey(novncImage)) { log.debug("noVNC container already available"); novncContainer = containerMap.get(novncImage); } else { dockerService.pullImageIfNecessary(novncImage); Map<String, List<PortBinding>> portBindings = new HashMap<>(); String defaultNovncPort = config().getNovncPort(); portBindings.put(defaultNovncPort, asList(randomPort(ALL_IPV4_ADDRESSES))); String network = config().getDockerNetwork(); novncContainer = DockerContainer.dockerBuilder(novncImage) .portBindings(portBindings).network(network).build(); String containerId = dockerService.startContainer(novncContainer); String novncHost = dockerService.getHost(containerId, network); String novncPort = dockerService.getBindPort(containerId, defaultNovncPort + "/tcp"); String novncUrl = format("http://%s:%s/", novncHost, novncPort); novncContainer.setContainerId(containerId); novncContainer.setContainerUrl(novncUrl); containerMap.put(novncImage, novncContainer); } return novncContainer; } private String getDockerPath(File file) { String fileString = file.getAbsolutePath(); if (fileString.contains(":")) { // Windows fileString = toLowerCase(fileString.charAt(0)) + fileString.substring(1); fileString = fileString.replaceAll("\\\\", "/"); fileString = fileString.replaceAll(":", ""); fileString = "/" + fileString; } log.trace("The path of file {} in Docker format is {}", file, fileString); return fileString; } private void waitForRecording() throws IOException { int dockerWaitTimeoutSec = dockerService.getDockerWaitTimeoutSec(); int dockerPollTimeMs = dockerService.getDockerPollTimeMs(); long timeoutMs = currentTimeMillis() + SECONDS.toMillis(dockerWaitTimeoutSec); log.debug("Waiting for recording {} to be available", recordingFile); while (!recordingFile.exists()) { if (currentTimeMillis() > timeoutMs) { log.warn("Timeout of {} seconds waiting for file {}", dockerWaitTimeoutSec, recordingFile); break; } log.trace("Recording {} not present ... waiting {} ms", recordingFile, dockerPollTimeMs); try { sleep(dockerPollTimeMs); } catch (InterruptedException e) { log.warn("Interrupted Exception while waiting for container", e); currentThread().interrupt(); } } log.trace("Renaming {} to {}.mp4", recordingFile, name); move(recordingFile.toPath(), recordingFile.toPath().resolveSibling(name + ".mp4"), REPLACE_EXISTING); } public Map<String, DockerContainer> getContainerMap() { return containerMap; } public void setIndex(String index) { this.index = index; } }
Log noVNC URL of Android device when required
src/main/java/io/github/bonigarcia/handler/DockerDriverHandler.java
Log noVNC URL of Android device when required
<ide><path>rc/main/java/io/github/bonigarcia/handler/DockerDriverHandler.java <ide> boolean recording = config().isRecording(); <ide> String selenoidImage = config().getSelenoidImage(); <ide> String novncImage = config().getNovncImage(); <add> String androidNoVncUrl; <ide> <ide> public DockerDriverHandler() throws DockerCertificateException { <ide> this.selenoidConfig = new SelenoidConfig(); <ide> <ide> String novncUrl = getNoVncUrl(selenoidHost, selenoidPort, <ide> sessionId.toString(), config().getSelenoidVncPassword()); <del> log.info("Session id {}", sessionId); <del> log.info( <del> "VNC URL (copy and paste in a browser navigation bar to interact with remote session)"); <del> log.info("{}", novncUrl); <add> logSessionId(sessionId); <add> logNoVncUrl(novncUrl); <add> <ide> String vncExport = config().getVncExport(); <ide> log.trace("Exporting VNC URL as Java property {}", vncExport); <ide> System.setProperty(vncExport, novncUrl); <ide> recordingFile = new File(hostVideoFolder, sessionId + ".mp4"); <ide> } <ide> return webdriver; <add> } <add> <add> private void logSessionId(SessionId sessionId) { <add> log.info("Session id {}", sessionId); <add> } <add> <add> private void logNoVncUrl(String novncUrl) { <add> log.info( <add> "VNC URL (copy and paste in a browser navigation bar to interact with remote session)"); <add> log.info("{}", novncUrl); <ide> } <ide> <ide> private WebDriver getDriverForAndroid(BrowserType browser, String version, <ide> } <ide> } while (androidDriver == null); <ide> log.info("Android device ready {}", androidDriver); <add> <add> if (config().isVnc()) { <add> SessionId sessionId = ((RemoteWebDriver) androidDriver) <add> .getSessionId(); <add> logSessionId(sessionId); <add> logNoVncUrl(androidNoVncUrl); <add> } <ide> return androidDriver; <ide> } <ide> <ide> androidContainer.setContainerId(containerId); <ide> androidContainer.setContainerUrl(appiumUrl); <ide> <add> String androidNoVncPort = dockerService.getBindPort(containerId, <add> internalNoVncPort + "/tcp"); <add> androidNoVncUrl = format("http://%s:%s/vnc.html?autoconnect=true", <add> androidHost, androidNoVncPort); <add> <ide> containerMap.put(androidImage, androidContainer); <ide> } <ide> return androidContainer;
Java
apache-2.0
100041ff5d37b8cad8928cb46eb3755a6873d3a5
0
alfasoftware/morf,alfasoftware/morf
/* Copyright 2017 Alfa Financial Software * * 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.alfasoftware.morf.sql; import static org.alfasoftware.morf.sql.SqlUtils.tableRef; import java.util.Arrays; import java.util.List; import java.util.function.Function; import org.alfasoftware.morf.sql.element.AliasedField; import org.alfasoftware.morf.sql.element.AliasedFieldBuilder; import org.alfasoftware.morf.sql.element.Criterion; import org.alfasoftware.morf.sql.element.Join; import org.alfasoftware.morf.sql.element.JoinType; import org.alfasoftware.morf.sql.element.Operator; import org.alfasoftware.morf.sql.element.TableReference; import org.alfasoftware.morf.util.Builder; import org.alfasoftware.morf.util.ObjectTreeTraverser; import org.alfasoftware.morf.util.ObjectTreeTraverser.Driver; import org.apache.commons.lang3.StringUtils; import com.google.common.collect.FluentIterable; import com.google.common.collect.ImmutableList; import com.google.common.collect.Iterables; import com.google.common.collect.Lists; /** * Common behaviour of {@link SelectStatement} and {@link SelectFirstStatement}. * * @author Copyright (c) Alfa Financial Software 2014 */ public abstract class AbstractSelectStatement<T extends AbstractSelectStatement<T>> implements Statement,Driver{ /** * The fields to select from the table */ private final List<AliasedField> fields; /** * TODO make final * * The primary table to select from */ private TableReference table; /** * Select from multiple inner selects. */ private final List<SelectStatement> fromSelects; /** * The additional tables to join to */ private final List<Join> joins; /** * TODO make final * * The selection criteria for selecting from the database */ private Criterion whereCriterion; /** * TODO make final * * The alias to associate with this select statement. Useful when combining * multiple select statements. */ private String alias; /** * The fields to sort the result set by */ private final List<AliasedField> orderBys; protected AbstractSelectStatement(Iterable<? extends AliasedFieldBuilder> aliasedFields) { if (AliasedField.immutableDslEnabled()) { this.fromSelects = ImmutableList.of(); this.joins = ImmutableList.of(); this.orderBys = ImmutableList.of(); this.fields = FluentIterable.from(aliasedFields).transform(AliasedFieldBuilder::build).toList(); } else { this.fromSelects = Lists.newArrayList(); this.joins = Lists.newArrayList(); this.orderBys = Lists.newArrayList(); this.fields = Lists.newArrayList(); this.fields.addAll(Builder.Helper.<AliasedField>buildAll(aliasedFields)); } } protected AbstractSelectStatement(AliasedFieldBuilder... aliasedFields) { this(Arrays.asList(aliasedFields)); } /** * Constructor for use when using the builder. * * @param builder The builder. */ AbstractSelectStatement(AbstractSelectStatementBuilder<T, ?> builder) { this.table = builder.getTable(); this.whereCriterion = builder.getWhereCriterion(); this.alias = builder.getAlias(); if (AliasedField.immutableDslEnabled()) { this.fromSelects = ImmutableList.copyOf(builder.getFromSelects()); this.joins = ImmutableList.copyOf(builder.getJoins()); this.orderBys = ImmutableList.copyOf(builder.getOrderBys()); this.fields = ImmutableList.copyOf(builder.getFields()); } else { this.fromSelects = Lists.newArrayList(builder.getFromSelects()); this.joins = Lists.newArrayList(builder.getJoins()); this.orderBys = Lists.newArrayList(builder.getOrderBys()); this.fields = Lists.newArrayList(builder.getFields()); } } /** * @param aliasedFields The fields to add * @deprecated Do not use {@link AbstractSelectStatement} mutably. Create a new statement. */ @Deprecated protected void addFields(AliasedFieldBuilder... aliasedFields) { addFields(Arrays.asList(aliasedFields)); } /** * @param aliasedFields The fields to add * @deprecated Do not use {@link AbstractSelectStatement} mutably. Create a new statement. */ @Deprecated protected void addFields(Iterable<? extends AliasedFieldBuilder> aliasedFields) { AliasedField.assetImmutableDslDisabled(); fields.addAll(FluentIterable.from(aliasedFields) .transform(Builder.Helper.<AliasedField>buildAll()).toList()); } /** * Gets the first table * * @return the table */ public TableReference getTable() { return table; } /** * Gets the list of fields * * @return the fields */ public List<AliasedField> getFields() { return fields; } /** * @return the fromSelects */ public List<SelectStatement> getFromSelects() { return fromSelects; } /** * Gets the list of joined tables in the order they are joined * * @return the joined tables */ public List<Join> getJoins() { return joins; } /** * Gets the where criteria. * * @return the where criteria */ public Criterion getWhereCriterion() { return whereCriterion; } /** * Gets the fields which the select is ordered by * * @return the order by fields */ public List<AliasedField> getOrderBys() { return orderBys; } /** * @return this select statement as a sub-select defining a field. */ public abstract AliasedField asField(); /** * @return a reference to the alias of the select statement. */ public TableReference asTable() { return new TableReference(getAlias()); } /** * Gets the alias of this select statement. * * @return the alias */ public String getAlias() { return alias; } /** * Sets the alias for this select statement. This is useful if you are * including multiple select statements in a single select (not to be confused * with a join) and wish to reference the select statement itself. * * @param alias the alias to set. * @return the new select statement with the change applied. */ public T alias(String alias) { return copyOnWriteOrMutate( b -> b.alias(alias), () -> this.alias = alias ); } /** * Selects fields from a specific table: * * <blockquote><pre> * SelectStatement statement = select().from(tableRef(&quot;Foo&quot;)); * </pre></blockquote> * * @param fromTable the table to select from * @return a new select statement with the change applied. */ public T from(TableReference fromTable) { return copyOnWriteOrMutate( b -> b.from(fromTable), () -> this.table = fromTable ); } /** * Either uses {@link #shallowCopy()} and mutates the result, returning it, * or mutates the statement directly, depending on * {@link AliasedField#immutableDslEnabled()}. * * TODO for removal along with mutable behaviour. * * @param transform A transform which modifies the shallow copy builder. * @param mutator Code which applies the local changes instead. * @param <U> The builder type. * @return The result (which may be {@code this}). */ @SuppressWarnings({ "unchecked" }) protected <U extends AbstractSelectStatementBuilder<T, ?>> T copyOnWriteOrMutate(Function<U, U> transform, Runnable mutator) { if (AliasedField.immutableDslEnabled()) { return transform.apply((U) shallowCopy()).build(); } else { mutator.run(); return castToChild(this); } } /** * Performs a shallow copy to a builder, allowing a duplicate * to be created and modified. * * @return A builder, initialised as a duplicate of this statement. */ public abstract AbstractSelectStatementBuilder<T, ?> shallowCopy(); /** * Selects fields from a specific table: * * <blockquote><pre> * SelectStatement statement = select().from(&quot;Foo&quot;); * </pre></blockquote> * * @param tableName the table to select from * @return a new select statement with the change applied. */ public T from(String tableName) { return from(tableRef(tableName)); } /** * Selects fields from one or more inner selects: * * <blockquote><pre> * SelectStatement statement = select().from(select().from(&quot;Foo&quot;)); * </pre></blockquote> * * @param fromSelect the select statements to select from * @return a new select statement with the change applied. */ public T from(SelectStatement... fromSelect) { return copyOnWriteOrMutate( b -> b.from(fromSelect), () -> this.fromSelects.addAll(Arrays.asList(fromSelect)) ); } /** * Specifies a table to join to. * * <blockquote><pre> * TableReference foo = tableRef("Foo"); * TableReference bar = tableRef("Bar"); * SelectStatement statement = select() * .from(foo) * .innerJoin(bar, foo.field(&quot;id&quot;).eq(bar.field(&quot;fooId&quot;)));</pre> * </blockquote> * * @param toTable the table to join to * @param criterion the criteria on which to join the tables * @return a new select statement with the change applied. */ public T innerJoin(TableReference toTable, Criterion criterion) { return copyOnWriteOrMutate( b -> b.innerJoin(toTable, criterion), () -> joins.add(new Join(JoinType.INNER_JOIN, toTable, criterion)) ); } /** * Specifies a table to cross join to (creating a cartesian product). * * <blockquote><pre> * TableReference foo = tableRef("Foo"); * TableReference bar = tableRef("Bar"); * SelectStatement statement = select() * .from(tableRef("Foo")) * .innerJoin(tableRef("Bar"));</pre> * </blockquote> * * @param toTable the table to join to * @return a new select statement with the change applied. */ public T crossJoin(TableReference toTable) { return copyOnWriteOrMutate( b -> b.crossJoin(toTable), () -> joins.add(new Join(JoinType.INNER_JOIN, toTable, null)) ); } /** * @param toTable * @return * * @deprecated Use {@link #crossJoin(TableReference)} to do a cross join; * or add join conditions for {@link #innerJoin(SelectStatement, Criterion)} * to make this an inner join. */ @Deprecated @SuppressWarnings("deprecation") public T innerJoin(TableReference toTable) { return copyOnWriteOrMutate( b -> b.innerJoin(toTable), () -> joins.add(new Join(JoinType.INNER_JOIN, toTable)) ); } /** * Specifies an inner join to a subselect: * * <blockquote><pre> * TableReference sale = tableRef("Sale"); * TableReference customer = tableRef("Customer"); * * // Define the subselect - a group by showing total sales by age * SelectStatement amountsByAge = select(field("age"), sum(field("amount"))) * .from(sale) * .innerJoin(customer, sale.field("customerId").eq(customer.field("id"))) * .groupBy(customer.field("age") * .alias("amountByAge"); * * // The outer select, showing each sale as a percentage of the sales to that age * SelectStatement outer = select( * sale.field("id"), * sale.field("amount") * .divideBy(amountByAge.asTable().field("amount")) * .multiplyBy(literal(100)) * ) * .from(sale) * .innerJoin(customer, sale.field("customerId").eq(customer.field("id"))) * .innerJoin(amountsByAge, amountsByAge.asTable().field("age").eq(customer.field("age"))); * </pre></blockquote> * * @param subSelect the sub select statement to join on to * @param onCondition the criteria on which to join the tables * @return a new select statement with the change applied. */ public T innerJoin(SelectStatement subSelect, Criterion onCondition) { return copyOnWriteOrMutate( b -> b.innerJoin(subSelect, onCondition), () -> joins.add(new Join(JoinType.INNER_JOIN, subSelect, onCondition)) ); } /** * Specifies a cross join (creating a cartesian product) to a subselect: * * <blockquote><pre> * // Each sale as a percentage of all sales * TableReference sale = tableRef("Sale"); * SelectStatement outer = select( * sale.field("id"), * sale.field("amount") * .divideBy(totalSales.asTable().field("amount")) * .multiplyBy(literal(100)) * ) * .from(sale) * .innerJoin( * select(sum(field("amount"))) * .from(sale) * .alias("totalSales") * ); * </pre></blockquote> * * @param subSelect the sub select statement to join on to * @return a new select statement with the change applied. */ public T crossJoin(SelectStatement subSelect) { return copyOnWriteOrMutate( b -> b.crossJoin(subSelect), () -> joins.add(new Join(JoinType.INNER_JOIN, subSelect, null)) ); } /** * @param subSelect * @return * * @deprecated Use {@link #crossJoin(SelectStatement)} to do a cross join; * or add join conditions for {@link #innerJoin(SelectStatement, Criterion)} * to make this an inner join. */ @Deprecated @SuppressWarnings("deprecation") public T innerJoin(SelectStatement subSelect) { return copyOnWriteOrMutate( b -> b.innerJoin(subSelect), () -> joins.add(new Join(JoinType.INNER_JOIN, subSelect)) ); } /** * Specifies a left outer join to a table: * * <blockquote><pre> * TableReference foo = tableRef("Foo"); * TableReference bar = tableRef("Bar"); * SelectStatement statement = select() * .from(foo) * .leftOuterJoin(bar, foo.field(&quot;id&quot;).eq(bar.field(&quot;fooId&quot;)));</pre> * </blockquote> * * @param toTable the table to join to * @param criterion the criteria on which to join the tables * @return a new select statement with the change applied. */ public T leftOuterJoin(TableReference toTable, Criterion criterion) { return copyOnWriteOrMutate( b -> b.leftOuterJoin(toTable, criterion), () -> joins.add(new Join(JoinType.LEFT_OUTER_JOIN, toTable, criterion)) ); } /** * Specifies an left outer join to a subselect: * * <blockquote><pre> * TableReference sale = tableRef("Sale"); * TableReference customer = tableRef("Customer"); * * // Define the subselect - a group by showing total sales by age in the * // previous month. * SelectStatement amountsByAgeLastMonth = select(field("age"), sum(field("amount"))) * .from(sale) * .innerJoin(customer, sale.field("customerId").eq(customer.field("id"))) * .where(sale.field("month").eq(5)) * .groupBy(customer.field("age") * .alias("amountByAge"); * * // The outer select, showing each sale this month as a percentage of the sales * // to that age the previous month * SelectStatement outer = select( * sale.field("id"), * sale.field("amount") * // May cause division by zero (!) * .divideBy(isNull(amountsByAgeLastMonth.asTable().field("amount"), 0)) * .multiplyBy(literal(100)) * ) * .from(sale) * .innerJoin(customer, sale.field("customerId").eq(customer.field("id"))) * .leftOuterJoin(amountsByAgeLastMonth, amountsByAgeLastMonth.asTable().field("age").eq(customer.field("age"))); * </pre></blockquote> * * @param subSelect the sub select statement to join on to * @param criterion the criteria on which to join the tables * @return a new select statement with the change applied. */ public T leftOuterJoin(SelectStatement subSelect, Criterion criterion) { return copyOnWriteOrMutate( b -> b.leftOuterJoin(subSelect, criterion), () -> joins.add(new Join(JoinType.LEFT_OUTER_JOIN, subSelect, criterion)) ); } /** * Specifies the where criteria: * * <blockquote><pre> * SelectStatement statement = select().from("Foo").where(field("name").eq("Dave")); * </pre></blockquote> * * @param criterion the criteria to filter the results by * @return a new select statement with the change applied. */ public T where(Criterion criterion) { return copyOnWriteOrMutate( b -> b.where(criterion), () -> { if (criterion == null) { throw new IllegalArgumentException("Criterion was null in where clause"); } whereCriterion = criterion; } ); } /** * Specifies the where criteria. For use in code where the criteria are being generated dynamically. * The iterable can be empty but not null. * * @param criteria the criteria to filter the results by. They will be <i>AND</i>ed together. * @return a new select statement with the change applied. */ public T where(Iterable<Criterion> criteria) { return copyOnWriteOrMutate( b -> b.where(criteria), () -> { if (criteria == null) { throw new IllegalArgumentException("No criterion was given in the where clause"); } if (!Iterables.isEmpty(criteria)) { whereCriterion = new Criterion(Operator.AND, criteria); } } ); } /** * Specifies the fields by which to order the result set: * * <blockquote><pre> * SelectStatement statement = select().from("Foo").orderBy(field("name").desc()); * </pre></blockquote> * * @param orderFields the fields to order by * @return a new select statement with the change applied. */ public T orderBy(AliasedField... orderFields) { if (orderFields == null) { throw new IllegalArgumentException("Fields were null in order by clause"); } return orderBy(Arrays.asList(orderFields)); } /** * Specifies the fields by which to order the result set. For use in builder code. * See {@link #orderBy(AliasedField...)} for the DSL version. * * @param orderFields the fields to order by * @return a new select statement with the change applied. */ public T orderBy(Iterable<AliasedField> orderFields) { return copyOnWriteOrMutate( b -> b.orderBy(orderFields), () -> { if (orderFields == null) { throw new IllegalArgumentException("Fields were null in order by clause"); } // Add the list Iterables.addAll(orderBys, orderFields); // Default fields to ascending if no direction has been specified SqlInternalUtils.defaultOrderByToAscending(orderBys); } ); } /** * @see org.alfasoftware.morf.sql.Statement#deepCopy() */ @Override public abstract T deepCopy(); /** * @param abstractSelectStatement * @return */ @SuppressWarnings("unchecked") private T castToChild(AbstractSelectStatement<T> abstractSelectStatement) { return (T) abstractSelectStatement; } /** * @see org.alfasoftware.morf.util.ObjectTreeTraverser.Driver#drive(org.alfasoftware.morf.util.ObjectTreeTraverser) */ @Override public void drive(ObjectTreeTraverser dispatcher) { dispatcher .dispatch(table) .dispatch(fields) .dispatch(joins) .dispatch(fromSelects) .dispatch(whereCriterion) .dispatch(orderBys); } /** * @see java.lang.Object#toString() */ @Override public String toString() { StringBuilder result = new StringBuilder(); if (fields.isEmpty()) { result.append("*"); } else { result.append(fields); } if (table != null) { result.append(" FROM [").append(table).append("]"); } if (!fromSelects.isEmpty()) { result.append(" FROM ").append(fromSelects); } if (!joins.isEmpty()) result.append(" "); result.append(StringUtils.join(joins, " ")); if (whereCriterion != null) result.append(" WHERE [").append(whereCriterion).append("]"); if (!orderBys.isEmpty()) result.append(" ORDER BY ").append(orderBys); return result.toString(); } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + (alias == null ? 0 : alias.hashCode()); result = prime * result + (fields == null ? 0 : fields.hashCode()); result = prime * result + (fromSelects == null ? 0 : fromSelects.hashCode()); result = prime * result + (joins == null ? 0 : joins.hashCode()); result = prime * result + (orderBys == null ? 0 : orderBys.hashCode()); result = prime * result + (table == null ? 0 : table.hashCode()); result = prime * result + (whereCriterion == null ? 0 : whereCriterion.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; @SuppressWarnings("unchecked") AbstractSelectStatement<T> other = (AbstractSelectStatement<T>) obj; if (alias == null) { if (other.alias != null) return false; } else if (!alias.equals(other.alias)) return false; if (fields == null) { if (other.fields != null) return false; } else if (!fields.equals(other.fields)) return false; if (fromSelects == null) { if (other.fromSelects != null) return false; } else if (!fromSelects.equals(other.fromSelects)) return false; if (joins == null) { if (other.joins != null) return false; } else if (!joins.equals(other.joins)) return false; if (orderBys == null) { if (other.orderBys != null) return false; } else if (!orderBys.equals(other.orderBys)) return false; if (table == null) { if (other.table != null) return false; } else if (!table.equals(other.table)) return false; if (whereCriterion == null) { if (other.whereCriterion != null) return false; } else if (!whereCriterion.equals(other.whereCriterion)) return false; return true; } }
morf-core/src/main/java/org/alfasoftware/morf/sql/AbstractSelectStatement.java
/* Copyright 2017 Alfa Financial Software * * 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.alfasoftware.morf.sql; import static org.alfasoftware.morf.sql.SqlUtils.tableRef; import java.util.Arrays; import java.util.List; import java.util.function.Function; import org.alfasoftware.morf.sql.element.AliasedField; import org.alfasoftware.morf.sql.element.AliasedFieldBuilder; import org.alfasoftware.morf.sql.element.Criterion; import org.alfasoftware.morf.sql.element.Join; import org.alfasoftware.morf.sql.element.JoinType; import org.alfasoftware.morf.sql.element.Operator; import org.alfasoftware.morf.sql.element.TableReference; import org.alfasoftware.morf.util.Builder; import org.alfasoftware.morf.util.ObjectTreeTraverser; import org.alfasoftware.morf.util.ObjectTreeTraverser.Driver; import org.apache.commons.lang3.StringUtils; import com.google.common.collect.FluentIterable; import com.google.common.collect.ImmutableList; import com.google.common.collect.Iterables; import com.google.common.collect.Lists; /** * Common behaviour of {@link SelectStatement} and {@link SelectFirstStatement}. * * @author Copyright (c) Alfa Financial Software 2014 */ public abstract class AbstractSelectStatement<T extends AbstractSelectStatement<T>> implements Statement,Driver{ /** * The fields to select from the table */ private final List<AliasedField> fields; /** * TODO make final * * The primary table to select from */ private TableReference table; /** * Select from multiple inner selects. */ private final List<SelectStatement> fromSelects; /** * The additional tables to join to */ private final List<Join> joins; /** * TODO make final * * The selection criteria for selecting from the database */ private Criterion whereCriterion; /** * TODO make final * * The alias to associate with this select statement. Useful when combining * multiple select statements. */ private String alias; /** * The fields to sort the result set by */ private final List<AliasedField> orderBys; protected AbstractSelectStatement() { if (AliasedField.immutableDslEnabled()) { this.fromSelects = ImmutableList.of(); this.joins = ImmutableList.of(); this.orderBys = ImmutableList.of(); this.fields = ImmutableList.of(); } else { this.fromSelects = Lists.newArrayList(); this.joins = Lists.newArrayList(); this.orderBys = Lists.newArrayList(); this.fields = Lists.newArrayList(); } } protected AbstractSelectStatement(Iterable<? extends AliasedFieldBuilder> aliasedFields) { if (AliasedField.immutableDslEnabled()) { this.fromSelects = ImmutableList.of(); this.joins = ImmutableList.of(); this.orderBys = ImmutableList.of(); this.fields = FluentIterable.from(aliasedFields).transform(AliasedFieldBuilder::build).toList(); } else { this.fromSelects = Lists.newArrayList(); this.joins = Lists.newArrayList(); this.orderBys = Lists.newArrayList(); this.fields = Lists.newArrayList(); this.fields.addAll(Builder.Helper.<AliasedField>buildAll(aliasedFields)); } } protected AbstractSelectStatement(AliasedFieldBuilder... aliasedFields) { this(Arrays.asList(aliasedFields)); } /** * Constructor for use when using the builder. * * @param builder The builder. */ AbstractSelectStatement(AbstractSelectStatementBuilder<T, ?> builder) { this.table = builder.getTable(); this.whereCriterion = builder.getWhereCriterion(); this.alias = builder.getAlias(); if (AliasedField.immutableDslEnabled()) { this.fromSelects = ImmutableList.copyOf(builder.getFromSelects()); this.joins = ImmutableList.copyOf(builder.getJoins()); this.orderBys = ImmutableList.copyOf(builder.getOrderBys()); this.fields = ImmutableList.copyOf(builder.getFields()); } else { this.fromSelects = Lists.newArrayList(builder.getFromSelects()); this.joins = Lists.newArrayList(builder.getJoins()); this.orderBys = Lists.newArrayList(builder.getOrderBys()); this.fields = Lists.newArrayList(builder.getFields()); } } /** * @param aliasedFields The fields to add * @deprecated Do not use {@link AbstractSelectStatement} mutably. Create a new statement. */ @Deprecated protected void addFields(AliasedFieldBuilder... aliasedFields) { addFields(Arrays.asList(aliasedFields)); } /** * @param aliasedFields The fields to add */ protected void addFields(Iterable<? extends AliasedFieldBuilder> aliasedFields) { AliasedField.assetImmutableDslDisabled(); fields.addAll(FluentIterable.from(aliasedFields) .transform(Builder.Helper.<AliasedField>buildAll()).toList()); } /** * Gets the first table * * @return the table */ public TableReference getTable() { return table; } /** * Gets the list of fields * * @return the fields */ public List<AliasedField> getFields() { return fields; } /** * @return the fromSelects */ public List<SelectStatement> getFromSelects() { return fromSelects; } /** * Gets the list of joined tables in the order they are joined * * @return the joined tables */ public List<Join> getJoins() { return joins; } /** * Gets the where criteria. * * @return the where criteria */ public Criterion getWhereCriterion() { return whereCriterion; } /** * Gets the fields which the select is ordered by * * @return the order by fields */ public List<AliasedField> getOrderBys() { return orderBys; } /** * @return this select statement as a sub-select defining a field. */ public abstract AliasedField asField(); /** * @return a reference to the alias of the select statement. */ public TableReference asTable() { return new TableReference(getAlias()); } /** * Gets the alias of this select statement. * * @return the alias */ public String getAlias() { return alias; } /** * Sets the alias for this select statement. This is useful if you are * including multiple select statements in a single select (not to be confused * with a join) and wish to reference the select statement itself. * * @param alias the alias to set. * @return the new select statement with the change applied. */ public T alias(String alias) { return copyOnWriteOrMutate( b -> b.alias(alias), () -> this.alias = alias ); } /** * Selects fields from a specific table: * * <blockquote><pre> * SelectStatement statement = select().from(tableRef(&quot;Foo&quot;)); * </pre></blockquote> * * @param fromTable the table to select from * @return a new select statement with the change applied. */ public T from(TableReference fromTable) { return copyOnWriteOrMutate( b -> b.from(fromTable), () -> this.table = fromTable ); } /** * Either uses {@link #shallowCopy()} and mutates the result, returning it, * or mutates the statement directly, depending on * {@link AliasedField#immutableDslEnabled()}. * * TODO for removal along with mutable behaviour. * * @param transform A transform which modifies the shallow copy builder. * @param mutator Code which applies the local changes instead. * @param <U> The builder type. * @return The result (which may be {@code this}). */ @SuppressWarnings({ "unchecked" }) protected <U extends AbstractSelectStatementBuilder<T, ?>> T copyOnWriteOrMutate(Function<U, U> transform, Runnable mutator) { if (AliasedField.immutableDslEnabled()) { return transform.apply((U) shallowCopy()).build(); } else { mutator.run(); return castToChild(this); } } /** * Performs a shallow copy to a builder, allowing a duplicate * to be created and modified. * * @return A builder, initialised as a duplicate of this statement. */ public abstract AbstractSelectStatementBuilder<T, ?> shallowCopy(); /** * Selects fields from a specific table: * * <blockquote><pre> * SelectStatement statement = select().from(&quot;Foo&quot;); * </pre></blockquote> * * @param tableName the table to select from * @return a new select statement with the change applied. */ public T from(String tableName) { return from(tableRef(tableName)); } /** * Selects fields from one or more inner selects: * * <blockquote><pre> * SelectStatement statement = select().from(select().from(&quot;Foo&quot;)); * </pre></blockquote> * * @param fromSelect the select statements to select from * @return a new select statement with the change applied. */ public T from(SelectStatement... fromSelect) { return copyOnWriteOrMutate( b -> b.from(fromSelect), () -> this.fromSelects.addAll(Arrays.asList(fromSelect)) ); } /** * Specifies a table to join to. * * <blockquote><pre> * TableReference foo = tableRef("Foo"); * TableReference bar = tableRef("Bar"); * SelectStatement statement = select() * .from(foo) * .innerJoin(bar, foo.field(&quot;id&quot;).eq(bar.field(&quot;fooId&quot;)));</pre> * </blockquote> * * @param toTable the table to join to * @param criterion the criteria on which to join the tables * @return a new select statement with the change applied. */ public T innerJoin(TableReference toTable, Criterion criterion) { return copyOnWriteOrMutate( b -> b.innerJoin(toTable, criterion), () -> joins.add(new Join(JoinType.INNER_JOIN, toTable, criterion)) ); } /** * Specifies a table to cross join to (creating a cartesian product). * * <blockquote><pre> * TableReference foo = tableRef("Foo"); * TableReference bar = tableRef("Bar"); * SelectStatement statement = select() * .from(tableRef("Foo")) * .innerJoin(tableRef("Bar"));</pre> * </blockquote> * * @param toTable the table to join to * @return a new select statement with the change applied. */ public T crossJoin(TableReference toTable) { return copyOnWriteOrMutate( b -> b.crossJoin(toTable), () -> joins.add(new Join(JoinType.INNER_JOIN, toTable, null)) ); } /** * @param toTable * @return * * @deprecated Use {@link #crossJoin(TableReference)} to do a cross join; * or add join conditions for {@link #innerJoin(SelectStatement, Criterion)} * to make this an inner join. */ @Deprecated @SuppressWarnings("deprecation") public T innerJoin(TableReference toTable) { return copyOnWriteOrMutate( b -> b.innerJoin(toTable), () -> joins.add(new Join(JoinType.INNER_JOIN, toTable)) ); } /** * Specifies an inner join to a subselect: * * <blockquote><pre> * TableReference sale = tableRef("Sale"); * TableReference customer = tableRef("Customer"); * * // Define the subselect - a group by showing total sales by age * SelectStatement amountsByAge = select(field("age"), sum(field("amount"))) * .from(sale) * .innerJoin(customer, sale.field("customerId").eq(customer.field("id"))) * .groupBy(customer.field("age") * .alias("amountByAge"); * * // The outer select, showing each sale as a percentage of the sales to that age * SelectStatement outer = select( * sale.field("id"), * sale.field("amount") * .divideBy(amountByAge.asTable().field("amount")) * .multiplyBy(literal(100)) * ) * .from(sale) * .innerJoin(customer, sale.field("customerId").eq(customer.field("id"))) * .innerJoin(amountsByAge, amountsByAge.asTable().field("age").eq(customer.field("age"))); * </pre></blockquote> * * @param subSelect the sub select statement to join on to * @param onCondition the criteria on which to join the tables * @return a new select statement with the change applied. */ public T innerJoin(SelectStatement subSelect, Criterion onCondition) { return copyOnWriteOrMutate( b -> b.innerJoin(subSelect, onCondition), () -> joins.add(new Join(JoinType.INNER_JOIN, subSelect, onCondition)) ); } /** * Specifies a cross join (creating a cartesian product) to a subselect: * * <blockquote><pre> * // Each sale as a percentage of all sales * TableReference sale = tableRef("Sale"); * SelectStatement outer = select( * sale.field("id"), * sale.field("amount") * .divideBy(totalSales.asTable().field("amount")) * .multiplyBy(literal(100)) * ) * .from(sale) * .innerJoin( * select(sum(field("amount"))) * .from(sale) * .alias("totalSales") * ); * </pre></blockquote> * * @param subSelect the sub select statement to join on to * @return a new select statement with the change applied. */ public T crossJoin(SelectStatement subSelect) { return copyOnWriteOrMutate( b -> b.crossJoin(subSelect), () -> joins.add(new Join(JoinType.INNER_JOIN, subSelect, null)) ); } /** * @param subSelect * @return * * @deprecated Use {@link #crossJoin(SelectStatement)} to do a cross join; * or add join conditions for {@link #innerJoin(SelectStatement, Criterion)} * to make this an inner join. */ @Deprecated @SuppressWarnings("deprecation") public T innerJoin(SelectStatement subSelect) { return copyOnWriteOrMutate( b -> b.innerJoin(subSelect), () -> joins.add(new Join(JoinType.INNER_JOIN, subSelect)) ); } /** * Specifies a left outer join to a table: * * <blockquote><pre> * TableReference foo = tableRef("Foo"); * TableReference bar = tableRef("Bar"); * SelectStatement statement = select() * .from(foo) * .leftOuterJoin(bar, foo.field(&quot;id&quot;).eq(bar.field(&quot;fooId&quot;)));</pre> * </blockquote> * * @param toTable the table to join to * @param criterion the criteria on which to join the tables * @return a new select statement with the change applied. */ public T leftOuterJoin(TableReference toTable, Criterion criterion) { return copyOnWriteOrMutate( b -> b.leftOuterJoin(toTable, criterion), () -> joins.add(new Join(JoinType.LEFT_OUTER_JOIN, toTable, criterion)) ); } /** * Specifies an left outer join to a subselect: * * <blockquote><pre> * TableReference sale = tableRef("Sale"); * TableReference customer = tableRef("Customer"); * * // Define the subselect - a group by showing total sales by age in the * // previous month. * SelectStatement amountsByAgeLastMonth = select(field("age"), sum(field("amount"))) * .from(sale) * .innerJoin(customer, sale.field("customerId").eq(customer.field("id"))) * .where(sale.field("month").eq(5)) * .groupBy(customer.field("age") * .alias("amountByAge"); * * // The outer select, showing each sale this month as a percentage of the sales * // to that age the previous month * SelectStatement outer = select( * sale.field("id"), * sale.field("amount") * // May cause division by zero (!) * .divideBy(isNull(amountsByAgeLastMonth.asTable().field("amount"), 0)) * .multiplyBy(literal(100)) * ) * .from(sale) * .innerJoin(customer, sale.field("customerId").eq(customer.field("id"))) * .leftOuterJoin(amountsByAgeLastMonth, amountsByAgeLastMonth.asTable().field("age").eq(customer.field("age"))); * </pre></blockquote> * * @param subSelect the sub select statement to join on to * @param criterion the criteria on which to join the tables * @return a new select statement with the change applied. */ public T leftOuterJoin(SelectStatement subSelect, Criterion criterion) { return copyOnWriteOrMutate( b -> b.leftOuterJoin(subSelect, criterion), () -> joins.add(new Join(JoinType.LEFT_OUTER_JOIN, subSelect, criterion)) ); } /** * Specifies the where criteria: * * <blockquote><pre> * SelectStatement statement = select().from("Foo").where(field("name").eq("Dave")); * </pre></blockquote> * * @param criterion the criteria to filter the results by * @return a new select statement with the change applied. */ public T where(Criterion criterion) { return copyOnWriteOrMutate( b -> b.where(criterion), () -> { if (criterion == null) { throw new IllegalArgumentException("Criterion was null in where clause"); } whereCriterion = criterion; } ); } /** * Specifies the where criteria. For use in code where the criteria are being generated dynamically. * The iterable can be empty but not null. * * @param criteria the criteria to filter the results by. They will be <i>AND</i>ed together. * @return a new select statement with the change applied. */ public T where(Iterable<Criterion> criteria) { return copyOnWriteOrMutate( b -> b.where(criteria), () -> { if (criteria == null) { throw new IllegalArgumentException("No criterion was given in the where clause"); } if (!Iterables.isEmpty(criteria)) { whereCriterion = new Criterion(Operator.AND, criteria); } } ); } /** * Specifies the fields by which to order the result set: * * <blockquote><pre> * SelectStatement statement = select().from("Foo").orderBy(field("name").desc()); * </pre></blockquote> * * @param orderFields the fields to order by * @return a new select statement with the change applied. */ public T orderBy(AliasedField... orderFields) { if (orderFields == null) { throw new IllegalArgumentException("Fields were null in order by clause"); } return orderBy(Arrays.asList(orderFields)); } /** * Specifies the fields by which to order the result set. For use in builder code. * See {@link #orderBy(AliasedField...)} for the DSL version. * * @param orderFields the fields to order by * @return a new select statement with the change applied. */ public T orderBy(Iterable<AliasedField> orderFields) { return copyOnWriteOrMutate( b -> b.orderBy(orderFields), () -> { if (orderFields == null) { throw new IllegalArgumentException("Fields were null in order by clause"); } // Add the list Iterables.addAll(orderBys, orderFields); // Default fields to ascending if no direction has been specified SqlInternalUtils.defaultOrderByToAscending(orderBys); } ); } /** * @see org.alfasoftware.morf.sql.Statement#deepCopy() */ @Override public abstract T deepCopy(); /** * @param abstractSelectStatement * @return */ @SuppressWarnings("unchecked") private T castToChild(AbstractSelectStatement<T> abstractSelectStatement) { return (T) abstractSelectStatement; } /** * @see org.alfasoftware.morf.util.ObjectTreeTraverser.Driver#drive(org.alfasoftware.morf.util.ObjectTreeTraverser) */ @Override public void drive(ObjectTreeTraverser dispatcher) { dispatcher .dispatch(table) .dispatch(fields) .dispatch(joins) .dispatch(fromSelects) .dispatch(whereCriterion) .dispatch(orderBys); } /** * @see java.lang.Object#toString() */ @Override public String toString() { StringBuilder result = new StringBuilder(); if (fields.isEmpty()) { result.append("*"); } else { result.append(fields); } if (table != null) { result.append(" FROM [").append(table).append("]"); } if (!fromSelects.isEmpty()) { result.append(" FROM ").append(fromSelects); } if (!joins.isEmpty()) result.append(" "); result.append(StringUtils.join(joins, " ")); if (whereCriterion != null) result.append(" WHERE [").append(whereCriterion).append("]"); if (!orderBys.isEmpty()) result.append(" ORDER BY ").append(orderBys); return result.toString(); } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + (alias == null ? 0 : alias.hashCode()); result = prime * result + (fields == null ? 0 : fields.hashCode()); result = prime * result + (fromSelects == null ? 0 : fromSelects.hashCode()); result = prime * result + (joins == null ? 0 : joins.hashCode()); result = prime * result + (orderBys == null ? 0 : orderBys.hashCode()); result = prime * result + (table == null ? 0 : table.hashCode()); result = prime * result + (whereCriterion == null ? 0 : whereCriterion.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; @SuppressWarnings("unchecked") AbstractSelectStatement<T> other = (AbstractSelectStatement<T>) obj; if (alias == null) { if (other.alias != null) return false; } else if (!alias.equals(other.alias)) return false; if (fields == null) { if (other.fields != null) return false; } else if (!fields.equals(other.fields)) return false; if (fromSelects == null) { if (other.fromSelects != null) return false; } else if (!fromSelects.equals(other.fromSelects)) return false; if (joins == null) { if (other.joins != null) return false; } else if (!joins.equals(other.joins)) return false; if (orderBys == null) { if (other.orderBys != null) return false; } else if (!orderBys.equals(other.orderBys)) return false; if (table == null) { if (other.table != null) return false; } else if (!table.equals(other.table)) return false; if (whereCriterion == null) { if (other.whereCriterion != null) return false; } else if (!whereCriterion.equals(other.whereCriterion)) return false; return true; } }
Removing unused code.
morf-core/src/main/java/org/alfasoftware/morf/sql/AbstractSelectStatement.java
Removing unused code.
<ide><path>orf-core/src/main/java/org/alfasoftware/morf/sql/AbstractSelectStatement.java <ide> * The fields to sort the result set by <ide> */ <ide> private final List<AliasedField> orderBys; <del> <del> <del> protected AbstractSelectStatement() { <del> if (AliasedField.immutableDslEnabled()) { <del> this.fromSelects = ImmutableList.of(); <del> this.joins = ImmutableList.of(); <del> this.orderBys = ImmutableList.of(); <del> this.fields = ImmutableList.of(); <del> } else { <del> this.fromSelects = Lists.newArrayList(); <del> this.joins = Lists.newArrayList(); <del> this.orderBys = Lists.newArrayList(); <del> this.fields = Lists.newArrayList(); <del> } <del> } <ide> <ide> <ide> protected AbstractSelectStatement(Iterable<? extends AliasedFieldBuilder> aliasedFields) { <ide> <ide> /** <ide> * @param aliasedFields The fields to add <del> */ <add> * @deprecated Do not use {@link AbstractSelectStatement} mutably. Create a new statement. <add> */ <add> @Deprecated <ide> protected void addFields(Iterable<? extends AliasedFieldBuilder> aliasedFields) { <ide> AliasedField.assetImmutableDslDisabled(); <ide> fields.addAll(FluentIterable.from(aliasedFields)
Java
apache-2.0
27cdd4350a8782218e812afbe3531f11cc5ce8b9
0
andrej-sajenko/georocket,georocket/georocket,andrej-sajenko/georocket,georocket/georocket
package io.georocket.storage; import io.vertx.core.AsyncResult; import io.vertx.core.Handler; import io.vertx.core.json.JsonObject; import io.vertx.rx.java.ObservableFuture; import io.vertx.rx.java.RxHelper; import rx.Observable; /** * Wraps around {@link Store} and adds methods to be used with RxJava * @author Michel Kraemer */ public class RxStore implements Store { private final Store delegate; /** * Create a new rx-ified store * @param delegate the actual store to delegate to */ public RxStore(Store delegate) { this.delegate = delegate; } /** * @return the actual non-rx-ified store */ public Store getDelegate() { return delegate; } @Override public void add(String chunk, ChunkMeta chunkMeta, String path, IndexMeta indexMeta, Handler<AsyncResult<Void>> handler) { delegate.add(chunk, chunkMeta, path, indexMeta, handler); } /** * Observable version of {@link #add(String, ChunkMeta, String, IndexMeta, Handler)} * @param chunk the chunk to add * @param chunkMeta the chunk's metadata * @param path the path where the chunk should be stored (may be null) * @param indexMeta metadata affecting the way the chunk will be indexed * @return an observable that emits exactly one item when the operation has completed */ public Observable<Void> addObservable(String chunk, ChunkMeta chunkMeta, String path, IndexMeta indexMeta) { ObservableFuture<Void> o = RxHelper.observableFuture(); add(chunk, chunkMeta, path, indexMeta, o.toHandler()); return o; } @Override public void getOne(String path, Handler<AsyncResult<ChunkReadStream>> handler) { delegate.getOne(path, handler); } /** * Observable version of {@link #getOne(String, Handler)} * @param path the absolute path to the chunk * @return an observable that will emit a read stream that can be used to * get the chunk's contents */ public Observable<ChunkReadStream> getOneObservable(String path) { ObservableFuture<ChunkReadStream> o = RxHelper.observableFuture(); getOne(path, o.toHandler()); return o; } @Override public void delete(String search, String path, Handler<AsyncResult<Void>> handler) { delegate.delete(search, path, handler); } /** * Observable version of {@link #delete(String, String, Handler)} * @param search the search query * @param path the path where to search for the chunks (may be null) * @return an observable that emits exactly one item when the operation has completed */ public Observable<Void> deleteObservable(String search, String path) { ObservableFuture<Void> o = RxHelper.observableFuture(); delete(search, path, o.toHandler()); return o; } @Override public void get(String search, String path, Handler<AsyncResult<StoreCursor>> handler) { delegate.get(search, path, handler); } /** * Observable version of {@link #get(String, String, Handler)} * @param search the search query * @param path the path where to search for the chunks (may be null) * @return an observable that emits a cursor that can be used to iterate * over all matched chunks */ public Observable<StoreCursor> getObservable(String search, String path) { ObservableFuture<StoreCursor> o = RxHelper.observableFuture(); get(search, path, o.toHandler()); return o; } @Override public void getSize(Handler<AsyncResult<Long>> handler) { delegate.getSize(handler); } /** * Observable version of {@link #getSize(Handler)} * @return an observable that will emit the store's current size in bytes */ public Observable<Long> getSizeObservable() { ObservableFuture<Long> o = RxHelper.observableFuture(); getSize(o.toHandler()); return o; } @Override public void getStoreSummery(Handler<AsyncResult<JsonObject>> handler) { delegate.getStoreSummery(handler); } /** * Observable version of {@link #getStoreSummery(Handler)} * @return on observable that emits the store summery. */ public Observable<JsonObject> getStoreSummeryObservable() { ObservableFuture<JsonObject> o = RxHelper.observableFuture(); getStoreSummery(o.toHandler()); return o; } }
georocket-server/src/main/java/io/georocket/storage/RxStore.java
package io.georocket.storage; import io.vertx.core.AsyncResult; import io.vertx.core.Handler; import io.vertx.core.json.JsonObject; import io.vertx.rx.java.ObservableFuture; import io.vertx.rx.java.RxHelper; import javafx.collections.ObservableMap; import rx.Observable; import java.util.Map; /** * Wraps around {@link Store} and adds methods to be used with RxJava * @author Michel Kraemer */ public class RxStore implements Store { private final Store delegate; /** * Create a new rx-ified store * @param delegate the actual store to delegate to */ public RxStore(Store delegate) { this.delegate = delegate; } /** * @return the actual non-rx-ified store */ public Store getDelegate() { return delegate; } @Override public void add(String chunk, ChunkMeta chunkMeta, String path, IndexMeta indexMeta, Handler<AsyncResult<Void>> handler) { delegate.add(chunk, chunkMeta, path, indexMeta, handler); } /** * Observable version of {@link #add(String, ChunkMeta, String, IndexMeta, Handler)} * @param chunk the chunk to add * @param chunkMeta the chunk's metadata * @param path the path where the chunk should be stored (may be null) * @param indexMeta metadata affecting the way the chunk will be indexed * @return an observable that emits exactly one item when the operation has completed */ public Observable<Void> addObservable(String chunk, ChunkMeta chunkMeta, String path, IndexMeta indexMeta) { ObservableFuture<Void> o = RxHelper.observableFuture(); add(chunk, chunkMeta, path, indexMeta, o.toHandler()); return o; } @Override public void getOne(String path, Handler<AsyncResult<ChunkReadStream>> handler) { delegate.getOne(path, handler); } /** * Observable version of {@link #getOne(String, Handler)} * @param path the absolute path to the chunk * @return an observable that will emit a read stream that can be used to * get the chunk's contents */ public Observable<ChunkReadStream> getOneObservable(String path) { ObservableFuture<ChunkReadStream> o = RxHelper.observableFuture(); getOne(path, o.toHandler()); return o; } @Override public void delete(String search, String path, Handler<AsyncResult<Void>> handler) { delegate.delete(search, path, handler); } /** * Observable version of {@link #delete(String, String, Handler)} * @param search the search query * @param path the path where to search for the chunks (may be null) * @return an observable that emits exactly one item when the operation has completed */ public Observable<Void> deleteObservable(String search, String path) { ObservableFuture<Void> o = RxHelper.observableFuture(); delete(search, path, o.toHandler()); return o; } @Override public void get(String search, String path, Handler<AsyncResult<StoreCursor>> handler) { delegate.get(search, path, handler); } /** * Observable version of {@link #get(String, String, Handler)} * @param search the search query * @param path the path where to search for the chunks (may be null) * @return an observable that emits a cursor that can be used to iterate * over all matched chunks */ public Observable<StoreCursor> getObservable(String search, String path) { ObservableFuture<StoreCursor> o = RxHelper.observableFuture(); get(search, path, o.toHandler()); return o; } @Override public void getSize(Handler<AsyncResult<Long>> handler) { delegate.getSize(handler); } /** * Observable version of {@link #getSize(Handler)} * @return an observable that will emit the store's current size in bytes */ public Observable<Long> getSizeObservable() { ObservableFuture<Long> o = RxHelper.observableFuture(); getSize(o.toHandler()); return o; } @Override public void getStoreSummery(Handler<AsyncResult<JsonObject>> handler) { delegate.getStoreSummery(handler); } /** * Observable version of {@link #getStoreSummery(Handler)} * @return on observable that emits the store summery. */ public Observable<JsonObject> getStoreSummeryObservable() { ObservableFuture<JsonObject> o = RxHelper.observableFuture(); getStoreSummery(o.toHandler()); return o; } }
remove unused map imports
georocket-server/src/main/java/io/georocket/storage/RxStore.java
remove unused map imports
<ide><path>eorocket-server/src/main/java/io/georocket/storage/RxStore.java <ide> import io.vertx.core.json.JsonObject; <ide> import io.vertx.rx.java.ObservableFuture; <ide> import io.vertx.rx.java.RxHelper; <del>import javafx.collections.ObservableMap; <ide> import rx.Observable; <ide> <del>import java.util.Map; <ide> <ide> /** <ide> * Wraps around {@link Store} and adds methods to be used with RxJava
Java
apache-2.0
27d1b8a5177099df6f33d5ae228b7658682709d1
0
srishtyagrawal/storm,mesosphere/storm,kamleshbhatt/storm,hilfialkaff/storm,jamesmarva/storm,d2r/storm-marz,allenjin/storm,taoguan/storm-1,erikdw/storm,Crim/storm,nathanmarz/storm,erikdw/storm,Frostman/storm,kamleshbhatt/storm,srishtyagrawal/storm,ferrero-zhang/storm,carl34/storm,elancom/storm,Aloomaio/incubator-storm,javelinjs/storm,srdo/storm,cluo512/storm,cluo512/storm,pczb/storm,srishtyagrawal/storm,srdo/storm,Crim/storm,elancom/storm,kamleshbhatt/storm,carl34/storm,pczb/storm,cluo512/storm,konfer/storm,sakanaou/storm,kevpeek/storm,d2r/storm-marz,metamx/incubator-storm,revans2/storm,kevinconaway/storm,hmcl/storm-apache,ujfjhz/storm,0x726d77/storm,praisondani/storm,hilfialkaff/storm,carl34/storm,konfer/storm,praisondani/storm,rahulkavale/storm,cherryleer/storm,allenjin/storm,Crim/storm,lcp0578/storm,Frostman/storm,cluo512/storm,ujfjhz/storm,F30/storm,revans2/incubator-storm,kevpeek/storm,kishorvpatil/incubator-storm,cherryleer/storm,adityasharad/storm,javelinjs/storm,hmcl/storm-apache,raviperi/storm,pczb/storm,revans2/storm,elancom/storm,F30/storm,kevinconaway/storm,srdo/storm,elancom/storm,jamesmarva/storm,Frostman/storm,kamleshbhatt/storm,allenjin/storm,lcp0578/storm,adityasharad/storm,kishorvpatil/incubator-storm,Frostman/storm,pczb/storm,cherryleer/storm,nathanmarz/storm,kamleshbhatt/storm,srdo/storm,Frostman/storm,kishorvpatil/incubator-storm,adityasharad/storm,carl34/storm,hmcl/storm-apache,3manuek/storm-1,Crim/storm,cluo512/storm,kishorvpatil/incubator-storm,javelinjs/storm,lcp0578/storm,nathanmarz/storm,pczb/storm,knusbaum/incubator-storm,sakanaou/storm,3manuek/storm-1,erikdw/storm,Crim/storm,praisondani/storm,hilfialkaff/storm,kishorvpatil/incubator-storm,revans2/storm,revans2/storm,ujfjhz/storm,0x726d77/storm,gongsm/storm,3manuek/storm-1,cluo512/storm,mesosphere/storm,Aloomaio/incubator-storm,metamx/incubator-storm,srishtyagrawal/storm,nathanmarz/storm,mesosphere/storm,allenjin/storm,ferrero-zhang/storm,knusbaum/incubator-storm,chrismoulton/storm,srishtyagrawal/storm,roshannaik/storm,kevinconaway/storm,0x726d77/storm,kevinconaway/storm,hmcl/storm-apache,revans2/storm,sakanaou/storm,revans2/incubator-storm,metamx/incubator-storm,rahulkavale/storm,hmcc/storm,Aloomaio/incubator-storm,revans2/incubator-storm,F30/storm,kevinconaway/storm,srishtyagrawal/storm,knusbaum/incubator-storm,hmcc/storm,jamesmarva/storm,d2r/storm-marz,sakanaou/storm,srishtyagrawal/storm,F30/storm,raviperi/storm,roshannaik/storm,taoguan/storm-1,kevpeek/storm,hmcc/storm,gongsm/storm,hilfialkaff/storm,ujfjhz/storm,carl34/storm,revans2/incubator-storm,roshannaik/storm,taoguan/storm-1,jamesmarva/storm,taoguan/storm-1,hilfialkaff/storm,chrismoulton/storm,hmcc/storm,javelinjs/storm,roshannaik/storm,jamesmarva/storm,d2r/storm-marz,kamleshbhatt/storm,Aloomaio/incubator-storm,erikdw/storm,hmcc/storm,0x726d77/storm,konfer/storm,Crim/storm,metamx/incubator-storm,knusbaum/incubator-storm,gongsm/storm,rahulkavale/storm,sakanaou/storm,ujfjhz/storm,adityasharad/storm,3manuek/storm-1,metamx/incubator-storm,srdo/storm,rahulkavale/storm,elancom/storm,cherryleer/storm,revans2/incubator-storm,sakanaou/storm,pczb/storm,hmcl/storm-apache,knusbaum/incubator-storm,F30/storm,ujfjhz/storm,praisondani/storm,konfer/storm,Crim/storm,allenjin/storm,0x726d77/storm,roshannaik/storm,praisondani/storm,lcp0578/storm,gongsm/storm,kevpeek/storm,chrismoulton/storm,raviperi/storm,3manuek/storm-1,mesosphere/storm,Aloomaio/incubator-storm,Aloomaio/incubator-storm,d2r/storm-marz,kamleshbhatt/storm,gongsm/storm,raviperi/storm,sakanaou/storm,kevpeek/storm,ferrero-zhang/storm,srdo/storm,raviperi/storm,F30/storm,rahulkavale/storm,carl34/storm,erikdw/storm,hmcc/storm,Aloomaio/incubator-storm,pczb/storm,chrismoulton/storm,hmcl/storm-apache,roshannaik/storm,erikdw/storm,adityasharad/storm,chrismoulton/storm,roshannaik/storm,kevpeek/storm,nathanmarz/storm,kevinconaway/storm,kevinconaway/storm,hmcl/storm-apache,adityasharad/storm,ujfjhz/storm,adityasharad/storm,knusbaum/incubator-storm,mesosphere/storm,srdo/storm,ferrero-zhang/storm,raviperi/storm,mesosphere/storm,carl34/storm,taoguan/storm-1,0x726d77/storm,raviperi/storm,ferrero-zhang/storm,lcp0578/storm,kishorvpatil/incubator-storm,hmcc/storm,0x726d77/storm,F30/storm,cherryleer/storm,erikdw/storm,cluo512/storm,kevpeek/storm,knusbaum/incubator-storm,kishorvpatil/incubator-storm,konfer/storm
package backtype.storm.transactional; import backtype.storm.coordination.FailedBatchException; import backtype.storm.Config; import backtype.storm.spout.SpoutOutputCollector; import backtype.storm.task.TopologyContext; import backtype.storm.topology.IRichSpout; import backtype.storm.topology.OutputFieldsDeclarer; import backtype.storm.transactional.state.RotatingTransactionalState; import backtype.storm.transactional.state.TransactionalState; import backtype.storm.tuple.Fields; import backtype.storm.tuple.Values; import backtype.storm.utils.Utils; import java.math.BigInteger; import java.util.HashMap; import java.util.Map; import org.apache.log4j.Logger; public class TransactionalSpoutCoordinator implements IRichSpout { public static final Logger LOG = Logger.getLogger(TransactionalSpoutCoordinator.class); public static final BigInteger INIT_TXID = new BigInteger("1"); public static final String TRANSACTION_BATCH_STREAM_ID = TransactionalSpoutCoordinator.class.getName() + "/batch"; public static final String TRANSACTION_COMMIT_STREAM_ID = TransactionalSpoutCoordinator.class.getName() + "/commit"; private static final String CURRENT_TX = "currtx"; private static final String META_DIR = "meta"; private ITransactionalSpout _spout; private ITransactionalSpout.Coordinator _coordinator; private TransactionalState _state; private RotatingTransactionalState _coordinatorState; Map<BigInteger, TransactionStatus> _activeTx = new HashMap<BigInteger, TransactionStatus>(); private SpoutOutputCollector _collector; BigInteger _currTransaction; int _maxTransactionActive; StateInitializer _initializer; public TransactionalSpoutCoordinator(ITransactionalSpout spout) { _spout = spout; } public ITransactionalSpout getSpout() { return _spout; } @Override public void open(Map conf, TopologyContext context, SpoutOutputCollector collector) { _state = TransactionalState.newCoordinatorState(conf, (String) conf.get(Config.TOPOLOGY_TRANSACTIONAL_ID), _spout.getComponentConfiguration()); _coordinatorState = new RotatingTransactionalState(_state, META_DIR, true); _collector = collector; _coordinator = _spout.getCoordinator(conf, context); _currTransaction = getStoredCurrTransaction(_state); if(!conf.containsKey(Config.TOPOLOGY_MAX_SPOUT_PENDING)) { _maxTransactionActive = 0; } else { _maxTransactionActive = Utils.getInt(conf.get(Config.TOPOLOGY_MAX_SPOUT_PENDING)); } _initializer = new StateInitializer(); } @Override public void close() { _state.close(); } @Override public void nextTuple() { sync(); } @Override public void ack(Object msgId) { TransactionAttempt tx = (TransactionAttempt) msgId; TransactionStatus status = _activeTx.get(tx.getTransactionId()); if(!tx.equals(status.attempt)) { throw new IllegalStateException("Coordinator got into a bad state: acked transaction " + tx.toString() + " does not match up with stored attempt: " + status); } if(status.status==AttemptStatus.PROCESSING) { status.status = AttemptStatus.PROCESSED; } else if(status.status==AttemptStatus.COMMITTING) { _activeTx.remove(tx.getTransactionId()); _coordinatorState.cleanupBefore(tx.getTransactionId()); _currTransaction = nextTransactionId(tx.getTransactionId()); _state.setData(CURRENT_TX, _currTransaction); } sync(); } @Override public void fail(Object msgId) { TransactionAttempt tx = (TransactionAttempt) msgId; TransactionStatus stored = _activeTx.remove(tx.getTransactionId()); if(!tx.equals(stored.attempt)) { throw new IllegalStateException("Coordinator got into a bad state: failed transaction " + tx.toString() + " does not match up with stored attempt: " + stored); } sync(); } @Override public void declareOutputFields(OutputFieldsDeclarer declarer) { // in partitioned example, in case an emitter task receives a later transaction than it's emitted so far, // when it sees the earlier txid it should know to emit nothing declarer.declareStream(TRANSACTION_BATCH_STREAM_ID, new Fields("tx", "tx-meta", "curr-txid")); declarer.declareStream(TRANSACTION_COMMIT_STREAM_ID, new Fields("tx")); } private void sync() { // TODO: this code might be redundant. can just find the next transaction that needs a batch or commit tuple // and emit that, instead of iterating through (MAX_SPOUT_PENDING should take care of things) TransactionStatus maybeCommit = _activeTx.get(_currTransaction); if(maybeCommit!=null && maybeCommit.status == AttemptStatus.PROCESSED) { maybeCommit.status = AttemptStatus.COMMITTING; _collector.emit(TRANSACTION_COMMIT_STREAM_ID, new Values(maybeCommit.attempt), maybeCommit.attempt); } try { if(_activeTx.size() < _maxTransactionActive) { BigInteger curr = _currTransaction; for(int i=0; i<_maxTransactionActive; i++) { if(!_activeTx.containsKey(curr)) { TransactionAttempt attempt = new TransactionAttempt(curr, Utils.randomLong()); Object state = _coordinatorState.getState(curr, _initializer); _activeTx.put(curr, new TransactionStatus(attempt)); _collector.emit(TRANSACTION_BATCH_STREAM_ID, new Values(attempt, state, _currTransaction), attempt); } curr = nextTransactionId(curr); } } } catch(FailedBatchException e) { LOG.warn("Failed to get metadata for a transaction", e); } } @Override public Map<String, Object> getComponentConfiguration() { Config ret = new Config(); ret.setMaxTaskParallelism(1); return ret; } private static enum AttemptStatus { PROCESSING, PROCESSED, COMMITTING } private static class TransactionStatus { TransactionAttempt attempt; AttemptStatus status; public TransactionStatus(TransactionAttempt attempt) { this.attempt = attempt; this.status = AttemptStatus.PROCESSING; } @Override public String toString() { return attempt.toString() + " <" + status.toString() + ">"; } } private static final BigInteger ONE = new BigInteger("1"); private BigInteger nextTransactionId(BigInteger id) { return id.add(ONE); } private BigInteger getStoredCurrTransaction(TransactionalState state) { BigInteger ret = (BigInteger) state.getData(CURRENT_TX); if(ret==null) return ONE; else return ret; } private class StateInitializer implements RotatingTransactionalState.StateInitializer { @Override public Object init(BigInteger txid, Object lastState) { return _coordinator.initializeTransaction(txid, lastState); } } }
src/jvm/backtype/storm/transactional/TransactionalSpoutCoordinator.java
package backtype.storm.transactional; import backtype.storm.coordination.FailedBatchException; import backtype.storm.Config; import backtype.storm.spout.SpoutOutputCollector; import backtype.storm.task.TopologyContext; import backtype.storm.topology.IRichSpout; import backtype.storm.topology.OutputFieldsDeclarer; import backtype.storm.transactional.state.RotatingTransactionalState; import backtype.storm.transactional.state.TransactionalState; import backtype.storm.tuple.Fields; import backtype.storm.tuple.Values; import backtype.storm.utils.Utils; import java.math.BigInteger; import java.util.HashMap; import java.util.Map; import org.apache.log4j.Logger; public class TransactionalSpoutCoordinator implements IRichSpout { public static final Logger LOG = Logger.getLogger(TransactionalSpoutCoordinator.class); public static final BigInteger INIT_TXID = new BigInteger("1"); public static final String TRANSACTION_BATCH_STREAM_ID = TransactionalSpoutCoordinator.class.getName() + "/batch"; public static final String TRANSACTION_COMMIT_STREAM_ID = TransactionalSpoutCoordinator.class.getName() + "/commit"; private static final String CURRENT_TX = "currtx"; private static final String META_DIR = "meta"; private ITransactionalSpout _spout; private ITransactionalSpout.Coordinator _coordinator; private TransactionalState _state; private RotatingTransactionalState _coordinatorState; Map<BigInteger, TransactionStatus> _activeTx = new HashMap<BigInteger, TransactionStatus>(); private SpoutOutputCollector _collector; BigInteger _currTransaction; int _maxTransactionActive; StateInitializer _initializer; public TransactionalSpoutCoordinator(ITransactionalSpout spout) { _spout = spout; } public ITransactionalSpout getSpout() { return _spout; } @Override public void open(Map conf, TopologyContext context, SpoutOutputCollector collector) { _state = TransactionalState.newCoordinatorState(conf, (String) conf.get(Config.TOPOLOGY_TRANSACTIONAL_ID), _spout.getComponentConfiguration()); _coordinatorState = new RotatingTransactionalState(_state, META_DIR, true); _collector = collector; _coordinator = _spout.getCoordinator(conf, context); _currTransaction = getStoredCurrTransaction(_state); if(!conf.containsKey(Config.TOPOLOGY_MAX_SPOUT_PENDING)) { _maxTransactionActive = 0; } else { _maxTransactionActive = Utils.getInt(conf.get(Config.TOPOLOGY_MAX_SPOUT_PENDING)); } _initializer = new StateInitializer(); } @Override public void close() { _state.close(); } @Override public void nextTuple() { sync(); } @Override public void ack(Object msgId) { TransactionAttempt tx = (TransactionAttempt) msgId; TransactionStatus status = _activeTx.get(tx.getTransactionId()); if(!tx.equals(status.attempt)) { throw new IllegalStateException("Coordinator got into a bad state: acked transaction " + tx.toString() + " does not match up with stored attempt: " + status); } if(status.status==AttemptStatus.PROCESSING) { status.status = AttemptStatus.PROCESSED; } else if(status.status==AttemptStatus.COMMITTING) { _activeTx.remove(tx.getTransactionId()); _coordinatorState.cleanupBefore(tx.getTransactionId()); _currTransaction = nextTransactionId(tx.getTransactionId()); _state.setData(CURRENT_TX, _currTransaction); } sync(); } @Override public void fail(Object msgId) { TransactionAttempt tx = (TransactionAttempt) msgId; TransactionStatus stored = _activeTx.remove(tx.getTransactionId()); if(!tx.equals(stored.attempt)) { throw new IllegalStateException("Coordinator got into a bad state: failed transaction " + tx.toString() + " does not match up with stored attempt: " + stored); } sync(); } @Override public void declareOutputFields(OutputFieldsDeclarer declarer) { // in partitioned example, in case an emitter task receives a later transaction than it's emitted so far, // when it sees the earlier txid it should know to emit nothing declarer.declareStream(TRANSACTION_BATCH_STREAM_ID, new Fields("tx", "tx-meta", "curr-txid")); declarer.declareStream(TRANSACTION_COMMIT_STREAM_ID, new Fields("tx")); } private void sync() { // TODO: this code might be redundant. can just find the next transaction that needs a batch or commit tuple // and emit that, instead of iterating through (MAX_SPOUT_PENDING should take care of things) TransactionStatus maybeCommit = _activeTx.get(_currTransaction); if(maybeCommit!=null && maybeCommit.status == AttemptStatus.PROCESSED) { maybeCommit.status = AttemptStatus.COMMITTING; _collector.emit(TRANSACTION_COMMIT_STREAM_ID, new Values(maybeCommit.attempt), maybeCommit.attempt); } try { if(_activeTx.size() < _maxTransactionActive) { BigInteger curr = _currTransaction; for(int i=0; i<_maxTransactionActive; i++) { if(!_activeTx.containsKey(curr)) { TransactionAttempt attempt = new TransactionAttempt(curr, Utils.randomLong()); Object state = _coordinatorState.getState(curr, _initializer); _activeTx.put(curr, new TransactionStatus(attempt)); _collector.emit(TRANSACTION_BATCH_STREAM_ID, new Values(attempt, state, _currTransaction), attempt); } curr = nextTransactionId(curr); } } } catch(FailedBatchException e) { LOG.warn("Failed to get metadata for a transaction", e); } } @Override public Map<String, Object> getComponentConfiguration() { Map<String, Object> ret = new HashMap<String, Object>(_spout.getComponentConfiguration()); ret.put(Config.TOPOLOGY_MAX_TASK_PARALLELISM, 1); return ret; } private static enum AttemptStatus { PROCESSING, PROCESSED, COMMITTING } private static class TransactionStatus { TransactionAttempt attempt; AttemptStatus status; public TransactionStatus(TransactionAttempt attempt) { this.attempt = attempt; this.status = AttemptStatus.PROCESSING; } @Override public String toString() { return attempt.toString() + " <" + status.toString() + ">"; } } private static final BigInteger ONE = new BigInteger("1"); private BigInteger nextTransactionId(BigInteger id) { return id.add(ONE); } private BigInteger getStoredCurrTransaction(TransactionalState state) { BigInteger ret = (BigInteger) state.getData(CURRENT_TX); if(ret==null) return ONE; else return ret; } private class StateInitializer implements RotatingTransactionalState.StateInitializer { @Override public Object init(BigInteger txid, Object lastState) { return _coordinator.initializeTransaction(txid, lastState); } } }
clean up coordinator component conf
src/jvm/backtype/storm/transactional/TransactionalSpoutCoordinator.java
clean up coordinator component conf
<ide><path>rc/jvm/backtype/storm/transactional/TransactionalSpoutCoordinator.java <ide> <ide> @Override <ide> public Map<String, Object> getComponentConfiguration() { <del> Map<String, Object> ret = new HashMap<String, Object>(_spout.getComponentConfiguration()); <del> ret.put(Config.TOPOLOGY_MAX_TASK_PARALLELISM, 1); <add> Config ret = new Config(); <add> ret.setMaxTaskParallelism(1); <ide> return ret; <ide> } <ide>
Java
bsd-3-clause
3108e1f35f5913b74ed28be94917eb365ceb196b
0
threerings/game-gardens
// // $Id$ // // ToyBox library - framework for matchmaking networked games // Copyright (C) 2005 Three Rings Design, Inc., All Rights Reserved // http://www.gamegardens.com/code/ // // This library is free software; you can redistribute it and/or modify it // under the terms of the GNU Lesser General Public License as published // by the Free Software Foundation; either version 2.1 of the License, or // (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA package com.threerings.toybox.client; import javax.swing.JCheckBox; import javax.swing.JComboBox; import javax.swing.JLabel; import javax.swing.JPanel; import com.samskivert.swing.HGroupLayout; import com.samskivert.swing.SimpleSlider; import com.threerings.util.MessageBundle; import com.threerings.parlor.client.GameConfigurator; import com.threerings.toybox.data.ChoiceParameter; import com.threerings.toybox.data.GameDefinition; import com.threerings.toybox.data.Parameter; import com.threerings.toybox.data.RangeParameter; import com.threerings.toybox.data.ToggleParameter; import com.threerings.toybox.data.ToyBoxGameConfig; import com.threerings.toybox.util.ToyBoxContext; import static com.threerings.toybox.Log.log; /** * Handles the configuration of a ToyBox game. This works in conjunction * with the {@link ToyBoxGameConfig} to provide a generic mechanism for * defining and obtaining game configuration settings. */ public class ToyBoxGameConfigurator extends GameConfigurator { // documentation inherited protected void createConfigInterface () { super.createConfigInterface(); } // documentation inherited protected void gotGameConfig () { super.gotGameConfig(); ToyBoxContext ctx = (ToyBoxContext)_ctx; ToyBoxGameConfig config = (ToyBoxGameConfig)_config; GameDefinition gamedef = config.getGameDefinition(); // create our parameter editors if (_editors == null) { // TODO: make sure this works when we're in the real // dynamically loaded toybox environment MessageBundle msgs = ctx.getMessageManager().getBundle( config.getBundleName()); _editors = new ParamEditor[gamedef.params.length]; for (int ii = 0; ii < _editors.length; ii++) { _editors[ii] = createEditor(msgs, gamedef.params[ii]); add((JPanel)_editors[ii]); } } // now read our parameters for (int ii = 0; ii < gamedef.params.length; ii++) { _editors[ii].readParameter(gamedef.params[ii], config); } } // documentation inherited protected void flushGameConfig () { super.flushGameConfig(); ToyBoxGameConfig config = (ToyBoxGameConfig)_config; GameDefinition gamedef = config.getGameDefinition(); for (int ii = 0; ii < gamedef.params.length; ii++) { _editors[ii].writeParameter(gamedef.params[ii], config); } } protected ParamEditor createEditor (MessageBundle msgs, Parameter param) { if (param instanceof RangeParameter) { return new RangeEditor(msgs, (RangeParameter)param); } else if (param instanceof ToggleParameter) { return new ToggleEditor(msgs, (ToggleParameter)param); } else if (param instanceof ChoiceParameter) { return new ChoiceEditor(msgs, (ChoiceParameter)param); } else { log.warning("Unknown parameter type! " + param + "."); return null; } } /** Provides a uniform interface to our UI components. */ protected static interface ParamEditor { public void readParameter (Parameter param, ToyBoxGameConfig config); public void writeParameter (Parameter param, ToyBoxGameConfig config); } protected class RangeEditor extends SimpleSlider implements ParamEditor { public RangeEditor (MessageBundle msgs, RangeParameter param) { super(msgs.get("m.range_" + param.ident), param.minimum, param.maximum, param.start); } public void readParameter (Parameter param, ToyBoxGameConfig config) { setValue((Integer)config.params.get(param.ident)); } public void writeParameter (Parameter param, ToyBoxGameConfig config) { config.params.put(param.ident, getValue()); } } protected class ToggleEditor extends JPanel implements ParamEditor { public ToggleEditor (MessageBundle msgs, ToggleParameter param) { setLayout(new HGroupLayout(HGroupLayout.NONE, HGroupLayout.LEFT)); add(_box = new JCheckBox( msgs.get("m.toggle_" + param.ident), param.start)); } public void readParameter (Parameter param, ToyBoxGameConfig config) { _box.setSelected((Boolean)config.params.get(param.ident)); } public void writeParameter (Parameter param, ToyBoxGameConfig config) { config.params.put(param.ident, _box.isSelected()); } protected JCheckBox _box; } protected class ChoiceEditor extends JPanel implements ParamEditor { public ChoiceEditor (MessageBundle msgs, ChoiceParameter param) { setLayout(new HGroupLayout(HGroupLayout.NONE, HGroupLayout.LEFT)); Choice[] choices = new Choice[param.choices.length]; Choice selection = null; for (int ii = 0; ii < choices.length; ii++) { String choice = param.choices[ii]; choices[ii] = new Choice(); choices[ii].choice = choice; choices[ii].label = msgs.get("m.choice_" + choice); if (choice.equals(param.start)) { selection = choices[ii]; } } add(new JLabel(msgs.get("m.choice_" + param.ident))); add(_combo = new JComboBox(choices)); if (selection != null) { _combo.setSelectedItem(selection); } } public void readParameter (Parameter param, ToyBoxGameConfig config) { String choice = (String)config.params.get(param.ident); for (int ii = 0; ii < _combo.getItemCount(); ii++) { Choice item = (Choice)_combo.getItemAt(ii); if (item.choice.equals(choice)) { _combo.setSelectedIndex(ii); break; } } } public void writeParameter (Parameter param, ToyBoxGameConfig config) { config.params.put( param.ident, ((Choice)_combo.getSelectedItem()).choice); } protected JComboBox _combo; } protected static class Choice { public String choice; public String label; public String toString () { return label; } } protected ParamEditor[] _editors; }
projects/toybox/src/java/com/threerings/toybox/client/ToyBoxGameConfigurator.java
// // $Id$ // // ToyBox library - framework for matchmaking networked games // Copyright (C) 2005 Three Rings Design, Inc., All Rights Reserved // http://www.gamegardens.com/code/ // // This library is free software; you can redistribute it and/or modify it // under the terms of the GNU Lesser General Public License as published // by the Free Software Foundation; either version 2.1 of the License, or // (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA package com.threerings.toybox.client; import javax.swing.JCheckBox; import javax.swing.JPanel; import com.samskivert.swing.HGroupLayout; import com.samskivert.swing.SimpleSlider; import com.threerings.util.MessageBundle; import com.threerings.parlor.client.GameConfigurator; import com.threerings.toybox.data.ChoiceParameter; import com.threerings.toybox.data.GameDefinition; import com.threerings.toybox.data.Parameter; import com.threerings.toybox.data.RangeParameter; import com.threerings.toybox.data.ToggleParameter; import com.threerings.toybox.data.ToyBoxGameConfig; import com.threerings.toybox.util.ToyBoxContext; import static com.threerings.toybox.Log.log; /** * Handles the configuration of a ToyBox game. This works in conjunction * with the {@link ToyBoxGameConfig} to provide a generic mechanism for * defining and obtaining game configuration settings. */ public class ToyBoxGameConfigurator extends GameConfigurator { // documentation inherited protected void createConfigInterface () { super.createConfigInterface(); } // documentation inherited protected void gotGameConfig () { super.gotGameConfig(); ToyBoxContext ctx = (ToyBoxContext)_ctx; ToyBoxGameConfig config = (ToyBoxGameConfig)_config; GameDefinition gamedef = config.getGameDefinition(); // create our parameter editors if (_editors == null) { // TODO: make sure this works when we're in the real // dynamically loaded toybox environment MessageBundle msgs = ctx.getMessageManager().getBundle( config.getBundleName()); _editors = new ParamEditor[gamedef.params.length]; for (int ii = 0; ii < _editors.length; ii++) { _editors[ii] = createEditor(msgs, gamedef.params[ii]); add((JPanel)_editors[ii]); } } // now read our parameters for (int ii = 0; ii < gamedef.params.length; ii++) { _editors[ii].readParameter(gamedef.params[ii], config); } } // documentation inherited protected void flushGameConfig () { super.flushGameConfig(); ToyBoxGameConfig config = (ToyBoxGameConfig)_config; GameDefinition gamedef = config.getGameDefinition(); for (int ii = 0; ii < gamedef.params.length; ii++) { _editors[ii].writeParameter(gamedef.params[ii], config); } } protected ParamEditor createEditor (MessageBundle msgs, Parameter param) { if (param instanceof RangeParameter) { return new RangeEditor(msgs, (RangeParameter)param); } else if (param instanceof ToggleParameter) { return new ToggleEditor(msgs, (ToggleParameter)param); } else if (param instanceof ChoiceParameter) { return new ChoiceEditor(msgs, (ChoiceParameter)param); } else { log.warning("Unknown parameter type! " + param + "."); return null; } } /** Provides a uniform interface to our UI components. */ protected static interface ParamEditor { public void readParameter (Parameter param, ToyBoxGameConfig config); public void writeParameter (Parameter param, ToyBoxGameConfig config); } protected class RangeEditor extends SimpleSlider implements ParamEditor { public RangeEditor (MessageBundle msgs, RangeParameter param) { super(msgs.get("m.range_" + param.ident), param.minimum, param.maximum, param.start); getSlider().setPaintTicks(true); int range = param.maximum - param.minimum; getSlider().setMajorTickSpacing(Math.min(10, range)); } public void readParameter (Parameter param, ToyBoxGameConfig config) { setValue((Integer)config.params.get(param.ident)); } public void writeParameter (Parameter param, ToyBoxGameConfig config) { config.params.put(param.ident, getValue()); } } protected class ToggleEditor extends JPanel implements ParamEditor { public ToggleEditor (MessageBundle msgs, ToggleParameter param) { setLayout(new HGroupLayout(HGroupLayout.NONE, HGroupLayout.LEFT)); add(_box = new JCheckBox( msgs.get("m.toggle_" + param.ident), param.start)); } public void readParameter (Parameter param, ToyBoxGameConfig config) { _box.setSelected((Boolean)config.params.get(param.ident)); } public void writeParameter (Parameter param, ToyBoxGameConfig config) { config.params.put(param.ident, _box.isSelected()); } protected JCheckBox _box; } protected class ChoiceEditor extends JPanel implements ParamEditor { public ChoiceEditor (MessageBundle msgs, ChoiceParameter param) { } public void readParameter (Parameter param, ToyBoxGameConfig config) { } public void writeParameter (Parameter param, ToyBoxGameConfig config) { } } protected ParamEditor[] _editors; }
Implemented the ChoiceEditor.
projects/toybox/src/java/com/threerings/toybox/client/ToyBoxGameConfigurator.java
Implemented the ChoiceEditor.
<ide><path>rojects/toybox/src/java/com/threerings/toybox/client/ToyBoxGameConfigurator.java <ide> package com.threerings.toybox.client; <ide> <ide> import javax.swing.JCheckBox; <add>import javax.swing.JComboBox; <add>import javax.swing.JLabel; <ide> import javax.swing.JPanel; <ide> <ide> import com.samskivert.swing.HGroupLayout; <ide> { <ide> super(msgs.get("m.range_" + param.ident), <ide> param.minimum, param.maximum, param.start); <del> <del> getSlider().setPaintTicks(true); <del> int range = param.maximum - param.minimum; <del> getSlider().setMajorTickSpacing(Math.min(10, range)); <ide> } <ide> <ide> public void readParameter (Parameter param, ToyBoxGameConfig config) <ide> { <ide> public ChoiceEditor (MessageBundle msgs, ChoiceParameter param) <ide> { <add> setLayout(new HGroupLayout(HGroupLayout.NONE, <add> HGroupLayout.LEFT)); <add> Choice[] choices = new Choice[param.choices.length]; <add> Choice selection = null; <add> for (int ii = 0; ii < choices.length; ii++) { <add> String choice = param.choices[ii]; <add> choices[ii] = new Choice(); <add> choices[ii].choice = choice; <add> choices[ii].label = msgs.get("m.choice_" + choice); <add> if (choice.equals(param.start)) { <add> selection = choices[ii]; <add> } <add> } <add> add(new JLabel(msgs.get("m.choice_" + param.ident))); <add> add(_combo = new JComboBox(choices)); <add> if (selection != null) { <add> _combo.setSelectedItem(selection); <add> } <ide> } <ide> <ide> public void readParameter (Parameter param, ToyBoxGameConfig config) <ide> { <add> String choice = (String)config.params.get(param.ident); <add> for (int ii = 0; ii < _combo.getItemCount(); ii++) { <add> Choice item = (Choice)_combo.getItemAt(ii); <add> if (item.choice.equals(choice)) { <add> _combo.setSelectedIndex(ii); <add> break; <add> } <add> } <ide> } <ide> <ide> public void writeParameter (Parameter param, ToyBoxGameConfig config) <ide> { <add> config.params.put( <add> param.ident, ((Choice)_combo.getSelectedItem()).choice); <add> } <add> <add> protected JComboBox _combo; <add> } <add> <add> protected static class Choice <add> { <add> public String choice; <add> public String label; <add> public String toString () { <add> return label; <ide> } <ide> } <ide>