answer
stringlengths 17
10.2M
|
|---|
package org.jsoup.parser;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Comment;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.nodes.TextNode;
import org.jsoup.select.Elements;
import org.junit.Test;
import java.util.List;
import static org.junit.Assert.*;
/**
Tests for the Parser
@author Jonathan Hedley, jonathan@hedley.net */
public class ParserTest {
@Test public void parsesSimpleDocument() {
String html = "<html><head><title>First!</title></head><body><p>First post! <img src=\"foo.png\" /></p></body></html>";
Document doc = Jsoup.parse(html);
// need a better way to verify these:
Element p = doc.getBody().child(0);
assertEquals("p", p.tagName());
Element img = p.child(0);
assertEquals("foo.png", img.attr("src"));
assertEquals("img", img.tagName());
}
@Test public void parsesRoughAttributes() {
String html = "<html><head><title>First!</title></head><body><p class=\"foo > bar\">First post! <img src=\"foo.png\" /></p></body></html>";
Document doc = Jsoup.parse(html);
// need a better way to verify these:
Element p = doc.getBody().child(0);
assertEquals("p", p.tagName());
assertEquals("foo > bar", p.attr("class"));
}
@Test public void parsesComments() {
String html = "<html><head></head><body><img src=foo><!-- <table><tr><td></table> --><p>Hello</p></body></html>";
Document doc = Jsoup.parse(html);
Element body = doc.getBody();
Comment comment = (Comment) body.childNode(1); // comment should not be sub of img, as it's an empty tag
assertEquals(" <table><tr><td></table> ", comment.getData());
Element p = body.child(1);
TextNode text = (TextNode) p.childNode(0);
assertEquals("Hello", text.getWholeText());
}
@Test public void parsesUnterminatedComments() {
String html = "<p>Hello<!-- <tr><td>";
Document doc = Jsoup.parse(html);
Element p = doc.getElementsByTag("p").get(0);
assertEquals("Hello", p.text());
TextNode text = (TextNode) p.childNode(0);
assertEquals("Hello", text.getWholeText());
Comment comment = (Comment) p.childNode(1);
assertEquals(" <tr><td>", comment.getData());
}
@Test public void parsesUnterminatedTag() {
String h1 = "<p";
Document doc = Jsoup.parse(h1);
assertEquals(1, doc.getElementsByTag("p").size());
String h2 = "<div id=1<p id='2'";
doc = Jsoup.parse(h2);
Element d = doc.getElementById("1");
assertEquals(1, d.children().size());
Element p = doc.getElementById("2");
assertNotNull(p);
}
@Test public void parsesUnterminatedAttribute() {
String h1 = "<p id=\"foo";
Document doc = Jsoup.parse(h1);
Element p = doc.getElementById("foo");
assertNotNull(p);
assertEquals("p", p.tagName());
}
@Test public void createsDocumentStructure() {
String html = "<meta name=keywords /><link rel=stylesheet /><title>jsoup</title><p>Hello world</p>";
Document doc = Jsoup.parse(html);
Element head = doc.getHead();
Element body = doc.getBody();
assertEquals(1, doc.children().size()); // root node: contains html node
assertEquals(2, doc.child(0).children().size()); // html node: head and body
assertEquals(3, head.children().size());
assertEquals(1, body.children().size());
assertEquals("keywords", head.getElementsByTag("meta").get(0).attr("name"));
assertEquals(0, body.getElementsByTag("meta").size());
assertEquals("jsoup", doc.getTitle());
assertEquals("Hello world", body.text());
assertEquals("Hello world", body.children().get(0).text());
}
@Test public void handlesEscapedData() {
String html = "<div title='Surf & Turf'>Reef & Beef</div>";
Document doc = Jsoup.parse(html);
Element div = doc.getElementsByTag("div").get(0);
assertEquals("Surf & Turf", div.attr("title"));
assertEquals("Reef & Beef", div.text());
}
@Test public void handlesDataOnlyTags() {
String t = "<textarea><p>Foo</p>\n<p>Bar</p></TEXTAREA>";
List<Element> tels = Jsoup.parse(t).getElementsByTag("textarea");
assertEquals("<p>Foo</p>\n<p>Bar</p>", tels.get(0).data());
String s = "<p>Hello</p><script>Nope</script><p>There</p>";
Document doc = Jsoup.parse(s);
assertEquals("Hello There", doc.text());
assertEquals("Nope", doc.data());
}
@Test public void createsImplicitLists() {
String h = "<li>Point one<li>Point two";
Document doc = Jsoup.parse(h);
Elements ol = doc.select("ul"); // should have created a default ul.
assertEquals(1, ol.size());
assertEquals(2, ol.get(0).children().size());
// no fiddling with non-implicit lists
String h2 = "<ol><li><p>Point the first<li><p>Point the second";
Document doc2 = Jsoup.parse(h2);
assertEquals(0, doc2.select("ul").size());
assertEquals(1, doc2.select("ol").size());
assertEquals(2, doc2.select("ol li").size());
assertEquals(2, doc2.select("ol li p").size());
assertEquals(1, doc2.select("ol li").get(0).children().size()); // one p in first li
}
@Test public void createsImplicitTable() {
String h = "<td>Hello<td><p>There<p>now";
Document doc = Jsoup.parse(h);
assertEquals("<table><tr><td>Hello</td><td><p>There</p><p>now</p></td></tr></table>", doc.getBody().html());
}
@Test public void handlesBaseTags() {
String h = "<a href=1>
Document doc = Jsoup.parse(h, "http://foo/");
assertEquals("http://foo/", doc.baseUri());
Elements anchors = doc.getElementsByTag("a");
assertEquals(3, anchors.size());
assertEquals("http://foo/", anchors.get(0).baseUri());
assertEquals("http://foo/2/", anchors.get(1).baseUri());
assertEquals("http://bar", anchors.get(2).baseUri());
assertEquals("http://foo/1", anchors.get(0).absUrl("href"));
assertEquals("http://foo/2/3", anchors.get(1).absUrl("href"));
assertEquals("http://bar/4", anchors.get(2).absUrl("href"));
}
@Test public void handlesCdata() {
String h = "<div id=1><![CData[<html>\n<foo><&]]></div>"; // "cdata" insensitive. the & in there should remain literal
Document doc = Jsoup.parse(h);
Element div = doc.getElementById("1");
assertEquals("<html>\n<foo><&", div.text());
assertEquals(0, div.children().size());
assertEquals(1, div.childNodes().size()); // no elements, one text node
}
@Test public void handlesInvalidStartTags() {
String h = "<div>Hello < There <&></div>"; // parse to <div {#text=Hello < There <&>}>
Document doc = Jsoup.parse(h);
assertEquals("Hello < There <&>", doc.select("div").first().text());
}
@Test public void handlesUnknownTags() {
String h = "<div><foo title=bar>Hello<foo title=qux>there</foo></div>";
Document doc = Jsoup.parse(h);
Elements foos = doc.select("foo");
assertEquals(2, foos.size());
assertEquals("bar", foos.first().attr("title"));
assertEquals("qux", foos.last().attr("title"));
assertEquals("there", foos.last().text());
}
}
|
package org.wso2.carbon.cep;
import junit.framework.Assert;
import org.junit.Test;
import java.util.Properties;
public class testCEP {
@Test
public void testLocalCEP(){
LocalCEP localCEP = new LocalCEP();
Properties properties = new Properties();
properties.put("name","API1");
localCEP.init();
}
@Test
public void testRemoteCEP() {
RemoteCEP remoteCEP = new RemoteCEP();
Properties properties = new Properties();
properties.put("name", "API1");
remoteCEP.addThrottlingType(ThrottlingManager.ThrottlingType.Rule1, properties);
remoteCEP.addThrottlingType(ThrottlingManager.ThrottlingType.Rule2, properties);
remoteCEP.init();
}
@Test
public void testSynchronousBehaviour() throws InterruptedException {
final ResultContainer result = new ResultContainer(2);
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
Assert.assertTrue("Assert the throttling result", result.isThrottled());
}
});
thread.start();
Thread.sleep(1000);
result.addResult(true);
result.addResult(false);
}
@Test
public void testRule1() throws InterruptedException {
Properties API1Properties = new Properties();
API1Properties.put("name", "API1");
Properties API2Properties = new Properties();
API2Properties.put("name", "API2");
ThrottlingManager.addThrottling(ThrottlingManager.ThrottlingType.Rule1, API1Properties);
ThrottlingManager.addThrottling(ThrottlingManager.ThrottlingType.Rule2, API1Properties);
ThrottlingManager.addThrottling(ThrottlingManager.ThrottlingType.Rule2, API2Properties);
ThrottlingManager.init();
ThrottlingManager.isThrottled(new Request("API1", "10.100.5.99"));
ThrottlingManager.isThrottled(new Request("API1", "10.100.5.99"));
ThrottlingManager.isThrottled(new Request("API1", "10.100.5.99"));
ThrottlingManager.isThrottled(new Request("API1", "10.100.5.99"));
ThrottlingManager.isThrottled(new Request("API1", "10.100.5.99"));
Thread.sleep(100);
Assert.assertTrue("Assert the throttling result", ThrottlingManager.isThrottled(new Request("API1",
"10.100.5.99")));
}
@Test
public void testRule2() throws InterruptedException {
Properties API1Properties = new Properties();
API1Properties.put("name", "API1");
Properties API2Properties = new Properties();
API2Properties.put("name", "API2");
ThrottlingManager.addThrottling(ThrottlingManager.ThrottlingType.Rule1, API1Properties);
ThrottlingManager.addThrottling(ThrottlingManager.ThrottlingType.Rule2, API1Properties);
ThrottlingManager.addThrottling(ThrottlingManager.ThrottlingType.Rule2, API2Properties);
ThrottlingManager.init();
ThrottlingManager.isThrottled(new Request("API1", "10.100.5.99"));
ThrottlingManager.isThrottled(new Request("API1", "10.100.5.99"));
ThrottlingManager.isThrottled(new Request("API1", "10.100.5.99"));
ThrottlingManager.isThrottled(new Request("API1", "10.100.5.99"));
ThrottlingManager.isThrottled(new Request("API2", "10.100.5.99"));
Thread.sleep(100);
Assert.assertTrue("Assert the throttling result", ThrottlingManager.isThrottled(new Request("API2",
"10.100.5.99")));
Assert.assertFalse("Assert the throttling result", ThrottlingManager.isThrottled(new Request("API1",
"10.100.5.100")));
}
}
|
/* -*- mode: java; c-basic-offset: 2; indent-tabs-mode: nil -*- */
package processing.app.debug;
import static processing.app.I18n._;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.SortedSet;
import java.util.TreeSet;
import cc.arduino.packages.BoardPort;
import cc.arduino.packages.Uploader;
import cc.arduino.packages.UploaderFactory;
import processing.app.BaseNoGui;
import processing.app.I18n;
import processing.app.PreferencesData;
import processing.app.SketchCode;
import processing.app.SketchData;
import processing.app.helpers.*;
import processing.app.helpers.filefilters.OnlyDirs;
import processing.app.packages.Library;
import processing.app.packages.LibraryList;
import processing.app.preproc.PdePreprocessor;
import processing.app.legacy.PApplet;
public class Compiler implements MessageConsumer {
/**
* File inside the build directory that contains the build options
* used for the last build.
*/
static final public String BUILD_PREFS_FILE = "buildprefs.txt";
private SketchData sketch;
private PreferencesMap prefs;
private boolean verbose;
private List<File> objectFiles;
private boolean sketchIsCompiled;
private RunnerException exception;
/**
* Listener interface for progress update on the GUI
*/
public interface ProgressListener {
public void progress(int percent);
}
private ProgressListener progressListener;
static public String build(SketchData data, String buildPath, File tempBuildFolder, ProgressListener progListener, boolean verbose) throws RunnerException, PreferencesMapException {
if (SketchData.checkSketchFile(data.getPrimaryFile()) == null)
BaseNoGui.showError(_("Bad file selected"),
_("Bad sketch primary file or bad sketch directory structure"), null);
String primaryClassName = data.getName() + ".cpp";
Compiler compiler = new Compiler(data, buildPath, primaryClassName);
File buildPrefsFile = new File(buildPath, BUILD_PREFS_FILE);
String newBuildPrefs = compiler.buildPrefsString();
// Do a forced cleanup (throw everything away) if the previous
// build settings do not match the previous ones
boolean prefsChanged = compiler.buildPreferencesChanged(buildPrefsFile, newBuildPrefs);
compiler.cleanup(prefsChanged, tempBuildFolder);
if (prefsChanged) {
try {
PrintWriter out = new PrintWriter(buildPrefsFile);
out.print(newBuildPrefs);
out.close();
} catch (IOException e) {
System.err.println(_("Could not write build preferences file"));
}
}
compiler.setProgressListener(progListener);
// compile the program. errors will happen as a RunnerException
// that will bubble up to whomever called build().
if (compiler.compile(verbose)) {
compiler.size(compiler.getBuildPreferences());
return primaryClassName;
}
return null;
}
static public Uploader getUploaderByPreferences(boolean noUploadPort) {
TargetPlatform target = BaseNoGui.getTargetPlatform();
String board = PreferencesData.get("board");
if (noUploadPort)
{
return new UploaderFactory().newUploader(target.getBoards().get(board), null, noUploadPort);
}
else
{
BoardPort boardPort = BaseNoGui.getDiscoveryManager().find(PreferencesData.get("serial.port"));
return new UploaderFactory().newUploader(target.getBoards().get(board), boardPort, noUploadPort);
}
}
static public boolean upload(SketchData data, Uploader uploader, String buildPath, String suggestedClassName, boolean usingProgrammer, boolean noUploadPort, List<String> warningsAccumulator) throws Exception {
if (uploader == null)
uploader = getUploaderByPreferences(noUploadPort);
boolean success = false;
if (uploader.requiresAuthorization() && !PreferencesData.has(uploader.getAuthorizationKey())) {
BaseNoGui.showError(_("Authorization required"),
_("No athorization data found"), null);
}
boolean useNewWarningsAccumulator = false;
if (warningsAccumulator == null) {
warningsAccumulator = new LinkedList<String>();
useNewWarningsAccumulator = true;
}
try {
success = uploader.uploadUsingPreferences(data.getFolder(), buildPath, suggestedClassName, usingProgrammer, warningsAccumulator);
} finally {
if (uploader.requiresAuthorization() && !success) {
PreferencesData.remove(uploader.getAuthorizationKey());
}
}
if (useNewWarningsAccumulator) {
for (String warning : warningsAccumulator) {
System.out.print(_("Warning"));
System.out.print(": ");
System.out.println(warning);
}
}
return success;
}
/**
* Create a new Compiler
* @param _sketch Sketch object to be compiled.
* @param _buildPath Where the temporary files live and will be built from.
* @param _primaryClassName the name of the combined sketch file w/ extension
*/
public Compiler(SketchData _sketch, String _buildPath, String _primaryClassName)
throws RunnerException {
sketch = _sketch;
prefs = createBuildPreferences(_buildPath, _primaryClassName);
// Start with an empty progress listener
progressListener = new ProgressListener() {
@Override
public void progress(int percent) {
}
};
}
/**
* Check if the build preferences used on the previous build in
* buildPath match the ones given.
*/
protected boolean buildPreferencesChanged(File buildPrefsFile, String newBuildPrefs) {
// No previous build, so no match
if (!buildPrefsFile.exists())
return true;
String previousPrefs;
try {
previousPrefs = FileUtils.readFileToString(buildPrefsFile);
} catch (IOException e) {
System.err.println(_("Could not read prevous build preferences file, rebuilding all"));
return true;
}
if (!previousPrefs.equals(newBuildPrefs)) {
System.out.println(_("Build options changed, rebuilding all"));
return true;
} else {
return false;
}
}
/**
* Returns the build preferences of the given compiler as a string.
* Only includes build-specific preferences, to make sure unrelated
* preferences don't cause a rebuild (in particular preferences that
* change on every start, like last.ide.xxx.daterun). */
protected String buildPrefsString() {
PreferencesMap buildPrefs = getBuildPreferences();
String res = "";
SortedSet<String> treeSet = new TreeSet<String>(buildPrefs.keySet());
for (String k : treeSet) {
if (k.startsWith("build.") || k.startsWith("compiler.") || k.startsWith("recipes."))
res += k + " = " + buildPrefs.get(k) + "\n";
}
return res;
}
protected void setProgressListener(ProgressListener _progressListener) {
progressListener = (_progressListener == null ?
new ProgressListener() {
@Override
public void progress(int percent) {
}
} : _progressListener);
}
/**
* Cleanup temporary files used during a build/run.
*/
protected void cleanup(boolean force, File tempBuildFolder) {
// if the java runtime is holding onto any files in the build dir, we
// won't be able to delete them, so we need to force a gc here
System.gc();
if (force) {
// delete the entire directory and all contents
// when we know something changed and all objects
// need to be recompiled, or if the board does not
// use setting build.dependency
//Base.removeDir(tempBuildFolder);
// note that we can't remove the builddir itself, otherwise
// the next time we start up, internal runs using Runner won't
// work because the build dir won't exist at startup, so the classloader
// will ignore the fact that that dir is in the CLASSPATH in run.sh
BaseNoGui.removeDescendants(tempBuildFolder);
} else {
// delete only stale source files, from the previously
// compiled sketch. This allows multiple windows to be
// used. Keep everything else, which might be reusable
if (tempBuildFolder.exists()) {
String files[] = tempBuildFolder.list();
for (String file : files) {
if (file.endsWith(".c") || file.endsWith(".cpp") || file.endsWith(".s")) {
File deleteMe = new File(tempBuildFolder, file);
if (!deleteMe.delete()) {
System.err.println("Could not delete " + deleteMe);
}
}
}
}
}
// Create a fresh applet folder (needed before preproc is run below)
//tempBuildFolder.mkdirs();
}
protected void size(PreferencesMap prefs) throws RunnerException {
String maxTextSizeString = prefs.get("upload.maximum_size");
String maxDataSizeString = prefs.get("upload.maximum_data_size");
if (maxTextSizeString == null)
return;
long maxTextSize = Integer.parseInt(maxTextSizeString);
long maxDataSize = -1;
if (maxDataSizeString != null)
maxDataSize = Integer.parseInt(maxDataSizeString);
Sizer sizer = new Sizer(prefs);
long[] sizes;
try {
sizes = sizer.computeSize();
} catch (RunnerException e) {
System.err.println(I18n.format(_("Couldn't determine program size: {0}"),
e.getMessage()));
return;
}
long textSize = sizes[0];
long dataSize = sizes[1];
System.out.println();
System.out.println(I18n
.format(_("Sketch uses {0} bytes ({2}%%) of program storage space. Maximum is {1} bytes."),
textSize, maxTextSize, textSize * 100 / maxTextSize));
if (dataSize >= 0) {
if (maxDataSize > 0) {
System.out
.println(I18n
.format(
_("Global variables use {0} bytes ({2}%%) of dynamic memory, leaving {3} bytes for local variables. Maximum is {1} bytes."),
dataSize, maxDataSize, dataSize * 100 / maxDataSize,
maxDataSize - dataSize));
} else {
System.out.println(I18n
.format(_("Global variables use {0} bytes of dynamic memory."), dataSize));
}
}
if (textSize > maxTextSize)
throw new RunnerException(
_("Sketch too big; see http://www.arduino.cc/en/Guide/Troubleshooting#size for tips on reducing it."));
if (maxDataSize > 0 && dataSize > maxDataSize)
throw new RunnerException(
_("Not enough memory; see http://www.arduino.cc/en/Guide/Troubleshooting#size for tips on reducing your footprint."));
int warnDataPercentage = Integer.parseInt(prefs.get("build.warn_data_percentage"));
if (maxDataSize > 0 && dataSize > maxDataSize*warnDataPercentage/100)
System.err.println(_("Low memory available, stability problems may occur."));
}
/**
* Compile sketch.
* @param _verbose
*
* @return true if successful.
* @throws RunnerException Only if there's a problem. Only then.
*/
public boolean compile(boolean _verbose) throws RunnerException, PreferencesMapException {
preprocess(prefs.get("build.path"));
verbose = _verbose || PreferencesData.getBoolean("build.verbose");
sketchIsCompiled = false;
objectFiles = new ArrayList<File>();
// 0. include paths for core + all libraries
progressListener.progress(20);
List<File> includeFolders = new ArrayList<File>();
includeFolders.add(prefs.getFile("build.core.path"));
if (prefs.getFile("build.variant.path") != null)
includeFolders.add(prefs.getFile("build.variant.path"));
for (Library lib : importedLibraries) {
if (verbose)
System.out.println(I18n
.format(_("Using library {0} in folder: {1} {2}"), lib.getName(),
lib.getFolder(), lib.isLegacy() ? "(legacy)" : ""));
includeFolders.add(lib.getSrcFolder());
}
if (verbose)
System.out.println();
List<String> archs = new ArrayList<String>();
archs.add(BaseNoGui.getTargetPlatform().getId());
if (prefs.containsKey("architecture.override_check")) {
String[] overrides = prefs.get("architecture.override_check").split(",");
archs.addAll(Arrays.asList(overrides));
}
for (Library lib : importedLibraries) {
if (!lib.supportsArchitecture(archs)) {
System.err.println(I18n
.format(_("WARNING: library {0} claims to run on {1} "
+ "architecture(s) and may be incompatible with your"
+ " current board which runs on {2} architecture(s)."), lib
.getName(), lib.getArchitectures(), archs));
System.err.println();
}
}
// 1. compile the sketch (already in the buildPath)
progressListener.progress(30);
compileSketch(includeFolders);
sketchIsCompiled = true;
// 2. compile the libraries, outputting .o files to: <buildPath>/<library>/
// Doesn't really use configPreferences
progressListener.progress(40);
compileLibraries(includeFolders);
// 3. compile the core, outputting .o files to <buildPath> and then
// collecting them into the core.a library file.
progressListener.progress(50);
compileCore();
// 4. link it all together into the .elf file
progressListener.progress(60);
compileLink();
// 5. extract EEPROM data (from EEMEM directive) to .eep file.
progressListener.progress(70);
runRecipe("recipe.objcopy.eep.pattern");
// 6. build the .hex file
progressListener.progress(80);
runRecipe("recipe.objcopy.hex.pattern");
progressListener.progress(90);
return true;
}
private PreferencesMap createBuildPreferences(String _buildPath,
String _primaryClassName)
throws RunnerException {
if (BaseNoGui.getBoardPreferences() == null) {
RunnerException re = new RunnerException(
_("No board selected; please choose a board from the Tools > Board menu."));
re.hideStackTrace();
throw re;
}
// Check if the board needs a platform from another package
TargetPlatform targetPlatform = BaseNoGui.getTargetPlatform();
TargetPlatform corePlatform = null;
PreferencesMap boardPreferences = BaseNoGui.getBoardPreferences();
String core = boardPreferences.get("build.core");
if (core.contains(":")) {
String[] split = core.split(":");
core = split[1];
corePlatform = BaseNoGui.getTargetPlatform(split[0], targetPlatform.getId());
if (corePlatform == null) {
RunnerException re = new RunnerException(I18n
.format(_("Selected board depends on '{0}' core (not installed)."),
split[0]));
re.hideStackTrace();
throw re;
}
}
// Merge all the global preference configuration in order of priority
PreferencesMap p = new PreferencesMap();
p.putAll(PreferencesData.getMap());
if (corePlatform != null)
p.putAll(corePlatform.getPreferences());
p.putAll(targetPlatform.getPreferences());
p.putAll(BaseNoGui.getBoardPreferences());
for (String k : p.keySet()) {
if (p.get(k) == null)
p.put(k, "");
}
p.put("build.path", _buildPath);
p.put("build.project_name", _primaryClassName);
p.put("build.arch", targetPlatform.getId().toUpperCase());
// Platform.txt should define its own compiler.path. For
// compatibility with earlier 1.5 versions, we define a (ugly,
// avr-specific) default for it, but this should be removed at some
// point.
if (!p.containsKey("compiler.path")) {
System.err.println(_("Third-party platform.txt does not define compiler.path. Please report this to the third-party hardware maintainer."));
p.put("compiler.path", BaseNoGui.getAvrBasePath());
}
// Core folder
TargetPlatform tp = corePlatform;
if (tp == null)
tp = targetPlatform;
File coreFolder = new File(tp.getFolder(), "cores");
coreFolder = new File(coreFolder, core);
p.put("build.core", core);
p.put("build.core.path", coreFolder.getAbsolutePath());
// System Folder
File systemFolder = tp.getFolder();
systemFolder = new File(systemFolder, "system");
p.put("build.system.path", systemFolder.getAbsolutePath());
// Variant Folder
String variant = p.get("build.variant");
if (variant != null) {
TargetPlatform t;
if (!variant.contains(":")) {
t = targetPlatform;
} else {
String[] split = variant.split(":", 2);
t = BaseNoGui.getTargetPlatform(split[0], targetPlatform.getId());
variant = split[1];
}
File variantFolder = new File(t.getFolder(), "variants");
variantFolder = new File(variantFolder, variant);
p.put("build.variant.path", variantFolder.getAbsolutePath());
} else {
p.put("build.variant.path", "");
}
return p;
}
private List<File> compileFiles(File outputPath, File sourcePath,
boolean recurse, List<File> includeFolders)
throws RunnerException, PreferencesMapException {
List<File> sSources = findFilesInFolder(sourcePath, "S", recurse);
List<File> cSources = findFilesInFolder(sourcePath, "c", recurse);
List<File> cppSources = findFilesInFolder(sourcePath, "cpp", recurse);
List<File> objectPaths = new ArrayList<File>();
for (File file : sSources) {
File objectFile = new File(outputPath, file.getName() + ".o");
objectPaths.add(objectFile);
String[] cmd = getCommandCompilerByRecipe(includeFolders, file, objectFile, "recipe.S.o.pattern");
execAsynchronously(cmd);
}
for (File file : cSources) {
File objectFile = new File(outputPath, file.getName() + ".o");
File dependFile = new File(outputPath, file.getName() + ".d");
objectPaths.add(objectFile);
if (isAlreadyCompiled(file, objectFile, dependFile, prefs))
continue;
String[] cmd = getCommandCompilerByRecipe(includeFolders, file, objectFile, "recipe.c.o.pattern");
execAsynchronously(cmd);
}
for (File file : cppSources) {
File objectFile = new File(outputPath, file.getName() + ".o");
File dependFile = new File(outputPath, file.getName() + ".d");
objectPaths.add(objectFile);
if (isAlreadyCompiled(file, objectFile, dependFile, prefs))
continue;
String[] cmd = getCommandCompilerByRecipe(includeFolders, file, objectFile, "recipe.cpp.o.pattern");
execAsynchronously(cmd);
}
return objectPaths;
}
protected static String unescapeDepFile(String line) {
// Replaces: "\\" -> "\"
// Replaces: "\ " -> " "
// Replaces: "\
line = line.replaceAll("\\\\([
// Replaces: "$$" -> "$"
line = line.replace("$$", "$");
return line;
}
private boolean isAlreadyCompiled(File src, File obj, File dep, Map<String, String> prefs) {
boolean ret=true;
try {
//System.out.println("\n isAlreadyCompiled: begin checks: " + obj.getPath());
if (!obj.exists()) return false; // object file (.o) does not exist
if (!dep.exists()) return false; // dep file (.d) does not exist
long src_modified = src.lastModified();
long obj_modified = obj.lastModified();
if (src_modified >= obj_modified) return false; // source modified since object compiled
if (src_modified >= dep.lastModified()) return false; // src modified since dep compiled
BufferedReader reader = new BufferedReader(new FileReader(dep.getPath()));
String line;
boolean need_obj_parse = true;
while ((line = reader.readLine()) != null) {
if (line.endsWith("\\")) {
line = line.substring(0, line.length() - 1);
}
line = line.trim();
line = unescapeDepFile(line);
if (line.length() == 0) continue; // ignore blank lines
if (need_obj_parse) {
// line is supposed to be the object file - make sure it really is!
if (line.endsWith(":")) {
line = line.substring(0, line.length() - 1);
String objpath = obj.getCanonicalPath();
File linefile = new File(line);
String linepath = linefile.getCanonicalPath();
//System.out.println(" isAlreadyCompiled: obj = " + objpath);
//System.out.println(" isAlreadyCompiled: line = " + linepath);
if (objpath.compareTo(linepath) == 0) {
need_obj_parse = false;
continue;
} else {
ret = false; // object named inside .d file is not the correct file!
break;
}
} else {
ret = false; // object file supposed to end with ':', but didn't
break;
}
} else {
// line is a prerequisite file
File prereq = new File(line);
if (!prereq.exists()) {
ret = false; // prerequisite file did not exist
break;
}
if (prereq.lastModified() >= obj_modified) {
ret = false; // prerequisite modified since object was compiled
break;
}
//System.out.println(" isAlreadyCompiled: prerequisite ok");
}
}
reader.close();
} catch (Exception e) {
return false; // any error reading dep file = recompile it
}
if (ret && verbose) {
System.out.println(I18n.format(_("Using previously compiled file: {0}"), obj.getPath()));
}
return ret;
}
/**
* Either succeeds or throws a RunnerException fit for public consumption.
*/
private void execAsynchronously(String[] command) throws RunnerException {
// eliminate any empty array entries
List<String> stringList = new ArrayList<String>();
for (String string : command) {
string = string.trim();
if (string.length() != 0)
stringList.add(string);
}
command = stringList.toArray(new String[stringList.size()]);
if (command.length == 0)
return;
int result = 0;
if (verbose) {
for (String c : command)
System.out.print(c + " ");
System.out.println();
}
Process process;
try {
process = ProcessUtils.exec(command);
} catch (IOException e) {
RunnerException re = new RunnerException(e.getMessage());
re.hideStackTrace();
throw re;
}
MessageSiphon in = new MessageSiphon(process.getInputStream(), this);
MessageSiphon err = new MessageSiphon(process.getErrorStream(), this);
// wait for the process to finish. if interrupted
// before waitFor returns, continue waiting
boolean compiling = true;
while (compiling) {
try {
in.join();
err.join();
result = process.waitFor();
//System.out.println("result is " + result);
compiling = false;
} catch (InterruptedException ignored) { }
}
// an error was queued up by message(), barf this back to compile(),
// which will barf it back to Editor. if you're having trouble
// discerning the imagery, consider how cows regurgitate their food
// to digest it, and the fact that they have five stomaches.
//System.out.println("throwing up " + exception);
if (exception != null)
throw exception;
if (result > 1) {
// a failure in the tool (e.g. unable to locate a sub-executable)
System.err
.println(I18n.format(_("{0} returned {1}"), command[0], result));
}
if (result != 0) {
RunnerException re = new RunnerException(_("Error compiling."));
re.hideStackTrace();
throw re;
}
}
/**
* Part of the MessageConsumer interface, this is called
* whenever a piece (usually a line) of error message is spewed
* out from the compiler. The errors are parsed for their contents
* and line number, which is then reported back to Editor.
*/
public void message(String s) {
int i;
// remove the build path so people only see the filename
// can't use replaceAll() because the path may have characters in it which
// have meaning in a regular expression.
if (!verbose) {
String buildPath = prefs.get("build.path");
while ((i = s.indexOf(buildPath + File.separator)) != -1) {
s = s.substring(0, i) + s.substring(i + (buildPath + File.separator).length());
}
}
// look for error line, which contains file name, line number,
// and at least the first line of the error message
String[] pieces = null;
if(OSUtils.isLinux()){
pieces = PApplet.match(s, "([\\w\\d_]+.\\w+):(\\d+):\\d+:\\s*error:\\s*(.*)\\s*");
}else{
pieces = PApplet.match(s, "([\\w\\d_]+.\\w+):(\\d+):\\s*error:\\s*(.*)\\s*");
}
// if (pieces != null && exception == null) {
// exception = sketch.placeException(pieces[3], pieces[1], PApplet.parseInt(pieces[2]) - 1);
// if (exception != null) exception.hideStackTrace();
if (pieces != null) {
String error = pieces[3], msg = "";
if (pieces[3].trim().equals("SPI.h: No such file or directory")) {
error = _("Please import the SPI library from the Sketch > Import Library menu.");
msg = _("\nAs of Arduino 0019, the Ethernet library depends on the SPI library." +
"\nYou appear to be using it or another library that depends on the SPI library.\n\n");
}
if (pieces[3].trim().equals("'BYTE' was not declared in this scope")) {
error = _("The 'BYTE' keyword is no longer supported.");
msg = _("\nAs of Arduino 1.0, the 'BYTE' keyword is no longer supported." +
"\nPlease use Serial.write() instead.\n\n");
}
if (pieces[3].trim().equals("no matching function for call to 'Server::Server(int)'")) {
error = _("The Server class has been renamed EthernetServer.");
msg = _("\nAs of Arduino 1.0, the Server class in the Ethernet library " +
"has been renamed to EthernetServer.\n\n");
}
if (pieces[3].trim().equals("no matching function for call to 'Client::Client(byte [4], int)'")) {
error = _("The Client class has been renamed EthernetClient.");
msg = _("\nAs of Arduino 1.0, the Client class in the Ethernet library " +
"has been renamed to EthernetClient.\n\n");
}
if (pieces[3].trim().equals("'Udp' was not declared in this scope")) {
error = _("The Udp class has been renamed EthernetUdp.");
msg = _("\nAs of Arduino 1.0, the Udp class in the Ethernet library " +
"has been renamed to EthernetUdp.\n\n");
}
if (pieces[3].trim().equals("'class TwoWire' has no member named 'send'")) {
error = _("Wire.send() has been renamed Wire.write().");
msg = _("\nAs of Arduino 1.0, the Wire.send() function was renamed " +
"to Wire.write() for consistency with other libraries.\n\n");
}
if (pieces[3].trim().equals("'class TwoWire' has no member named 'receive'")) {
error = _("Wire.receive() has been renamed Wire.read().");
msg = _("\nAs of Arduino 1.0, the Wire.receive() function was renamed " +
"to Wire.read() for consistency with other libraries.\n\n");
}
if (pieces[3].trim().equals("'Mouse' was not declared in this scope")) {
error = _("'Mouse' only supported on the Arduino Leonardo");
//msg = _("\nThe 'Mouse' class is only supported on the Arduino Leonardo.\n\n");
}
if (pieces[3].trim().equals("'Keyboard' was not declared in this scope")) {
error = _("'Keyboard' only supported on the Arduino Leonardo");
//msg = _("\nThe 'Keyboard' class is only supported on the Arduino Leonardo.\n\n");
}
RunnerException e = null;
if (!sketchIsCompiled) {
// Place errors when compiling the sketch, but never while compiling libraries
// or the core. The user's sketch might contain the same filename!
e = placeException(error, pieces[1], PApplet.parseInt(pieces[2]) - 1);
}
// replace full file path with the name of the sketch tab (unless we're
// in verbose mode, in which case don't modify the compiler output)
if (e != null && !verbose) {
SketchCode code = sketch.getCode(e.getCodeIndex());
String fileName = (code.isExtension("ino") || code.isExtension("pde")) ? code.getPrettyName() : code.getFileName();
int lineNum = e.getCodeLine() + 1;
s = fileName + ":" + lineNum + ": error: " + pieces[3] + msg;
}
if (exception == null && e != null) {
exception = e;
exception.hideStackTrace();
}
}
if (s.contains("undefined reference to `SPIClass::begin()'") &&
s.contains("libraries/Robot_Control")) {
String error = _("Please import the SPI library from the Sketch > Import Library menu.");
exception = new RunnerException(error);
}
if (s.contains("undefined reference to `Wire'") &&
s.contains("libraries/Robot_Control")) {
String error = _("Please import the Wire library from the Sketch > Import Library menu.");
exception = new RunnerException(error);
}
System.err.print(s);
}
private String[] getCommandCompilerByRecipe(List<File> includeFolders, File sourceFile, File objectFile, String recipe) throws PreferencesMapException, RunnerException {
String includes = prepareIncludes(includeFolders);
PreferencesMap dict = new PreferencesMap(prefs);
dict.put("ide_version", "" + BaseNoGui.REVISION);
dict.put("includes", includes);
dict.put("source_file", sourceFile.getAbsolutePath());
dict.put("object_file", objectFile.getAbsolutePath());
String cmd = prefs.getOrExcept(recipe);
try {
return StringReplacer.formatAndSplit(cmd, dict, true);
} catch (Exception e) {
throw new RunnerException(e);
}
}
private void createFolder(File folder) throws RunnerException {
if (folder.isDirectory())
return;
if (!folder.mkdir())
throw new RunnerException("Couldn't create: " + folder);
}
static public List<File> findFilesInFolder(File folder, String extension,
boolean recurse) {
List<File> files = new ArrayList<File>();
if (FileUtils.isSCCSOrHiddenFile(folder)) {
return files;
}
File[] listFiles = folder.listFiles();
if (listFiles == null) {
return files;
}
for (File file : listFiles) {
if (FileUtils.isSCCSOrHiddenFile(file)) {
continue; // skip hidden files
}
if (file.getName().endsWith("." + extension))
files.add(file);
if (recurse && file.isDirectory()) {
files.addAll(findFilesInFolder(file, extension, true));
}
}
return files;
}
// 1. compile the sketch (already in the buildPath)
void compileSketch(List<File> includeFolders) throws RunnerException, PreferencesMapException {
File buildPath = prefs.getFile("build.path");
objectFiles.addAll(compileFiles(buildPath, buildPath, false, includeFolders));
}
// 2. compile the libraries, outputting .o files to:
// <buildPath>/<library>/
void compileLibraries(List<File> includeFolders) throws RunnerException, PreferencesMapException {
for (Library lib : importedLibraries) {
compileLibrary(lib, includeFolders);
}
}
private void compileLibrary(Library lib, List<File> includeFolders)
throws RunnerException, PreferencesMapException {
File libFolder = lib.getSrcFolder();
File libBuildFolder = prefs.getFile(("build.path"), lib.getName());
if (lib.useRecursion()) {
// libBuildFolder == {build.path}/LibName
// libFolder == {lib.path}/src
recursiveCompileFilesInFolder(libBuildFolder, libFolder, includeFolders);
} else {
// libFolder == {lib.path}/
// utilityFolder == {lib.path}/utility
// libBuildFolder == {build.path}/LibName
// utilityBuildFolder == {build.path}/LibName/utility
File utilityFolder = new File(libFolder, "utility");
File utilityBuildFolder = new File(libBuildFolder, "utility");
includeFolders.add(utilityFolder);
compileFilesInFolder(libBuildFolder, libFolder, includeFolders);
compileFilesInFolder(utilityBuildFolder, utilityFolder, includeFolders);
// other libraries should not see this library's utility/ folder
includeFolders.remove(utilityFolder);
}
}
private void recursiveCompileFilesInFolder(File srcBuildFolder, File srcFolder, List<File> includeFolders) throws RunnerException, PreferencesMapException {
compileFilesInFolder(srcBuildFolder, srcFolder, includeFolders);
for (File subFolder : srcFolder.listFiles(new OnlyDirs())) {
File subBuildFolder = new File(srcBuildFolder, subFolder.getName());
recursiveCompileFilesInFolder(subBuildFolder, subFolder, includeFolders);
}
}
private void compileFilesInFolder(File buildFolder, File srcFolder, List<File> includeFolders) throws RunnerException, PreferencesMapException {
createFolder(buildFolder);
List<File> objects = compileFiles(buildFolder, srcFolder, false, includeFolders);
objectFiles.addAll(objects);
}
// 3. compile the core, outputting .o files to <buildPath> and then
// collecting them into the core.a library file.
// Also compiles the variant (if it supplies actual source files),
// which are included in the link directly (not through core.a)
void compileCore()
throws RunnerException, PreferencesMapException {
File coreFolder = prefs.getFile("build.core.path");
File variantFolder = prefs.getFile("build.variant.path");
File buildFolder = prefs.getFile("build.path");
List<File> includeFolders = new ArrayList<File>();
includeFolders.add(coreFolder); // include core path only
if (variantFolder != null)
includeFolders.add(variantFolder);
if (variantFolder != null)
objectFiles.addAll(compileFiles(buildFolder, variantFolder, true,
includeFolders));
File afile = new File(buildFolder, "core.a");
List<File> coreObjectFiles = compileFiles(buildFolder, coreFolder, true,
includeFolders);
// See if the .a file is already uptodate
if (afile.exists()) {
boolean changed = false;
for (File file : coreObjectFiles) {
if (file.lastModified() > afile.lastModified()) {
changed = true;
break;
}
}
// If none of the object files is newer than the .a file, don't
// bother rebuilding the .a file. There is a small corner case
// here: If a source file was removed, but no other source file
// was modified, this will not rebuild core.a even when it
// should. It's hard to fix and not a realistic case, so it
// shouldn't be a problem.
if (!changed) {
if (verbose)
System.out.println(I18n.format(_("Using previously compiled file: {0}"), afile.getPath()));
return;
}
}
// Delete the .a file, to prevent any previous code from lingering
afile.delete();
try {
for (File file : coreObjectFiles) {
PreferencesMap dict = new PreferencesMap(prefs);
dict.put("ide_version", "" + BaseNoGui.REVISION);
dict.put("archive_file", afile.getName());
dict.put("object_file", file.getAbsolutePath());
String[] cmdArray;
String cmd = prefs.getOrExcept("recipe.ar.pattern");
try {
cmdArray = StringReplacer.formatAndSplit(cmd, dict, true);
} catch (Exception e) {
throw new RunnerException(e);
}
execAsynchronously(cmdArray);
}
} catch (RunnerException e) {
afile.delete();
throw e;
}
}
// 4. link it all together into the .elf file
void compileLink()
throws RunnerException, PreferencesMapException {
// TODO: Make the --relax thing in configuration files.
// For atmega2560, need --relax linker option to link larger
// programs correctly.
String optRelax = "";
if (prefs.get("build.mcu").equals("atmega2560"))
optRelax = ",--relax";
String objectFileList = "";
for (File file : objectFiles)
objectFileList += " \"" + file.getAbsolutePath() + '"';
objectFileList = objectFileList.substring(1);
PreferencesMap dict = new PreferencesMap(prefs);
String flags = dict.get("compiler.c.elf.flags") + optRelax;
dict.put("compiler.c.elf.flags", flags);
dict.put("archive_file", "core.a");
dict.put("object_files", objectFileList);
dict.put("ide_version", "" + BaseNoGui.REVISION);
String[] cmdArray;
String cmd = prefs.getOrExcept("recipe.c.combine.pattern");
try {
cmdArray = StringReplacer.formatAndSplit(cmd, dict, true);
} catch (Exception e) {
throw new RunnerException(e);
}
execAsynchronously(cmdArray);
}
void runRecipe(String recipe) throws RunnerException, PreferencesMapException {
PreferencesMap dict = new PreferencesMap(prefs);
dict.put("ide_version", "" + BaseNoGui.REVISION);
String[] cmdArray;
String cmd = prefs.getOrExcept(recipe);
try {
cmdArray = StringReplacer.formatAndSplit(cmd, dict, true);
} catch (Exception e) {
throw new RunnerException(e);
}
execAsynchronously(cmdArray);
}
private static String prepareIncludes(List<File> includeFolders) {
String res = "";
for (File p : includeFolders)
res += " \"-I" + p.getAbsolutePath() + '"';
// Remove first space
return res.substring(1);
}
public PreferencesMap getBuildPreferences() {
return prefs;
}
/**
* Build all the code for this sketch.
*
* In an advanced program, the returned class name could be different,
* which is why the className is set based on the return value.
* A compilation error will burp up a RunnerException.
*
* Setting purty to 'true' will cause exception line numbers to be incorrect.
* Unless you know the code compiles, you should first run the preprocessor
* with purty set to false to make sure there are no errors, then once
* successful, re-export with purty set to true.
*
* @param buildPath Location to copy all the .java files
* @return null if compilation failed, main class name if not
*/
public void preprocess(String buildPath) throws RunnerException {
preprocess(buildPath, new PdePreprocessor());
}
public void preprocess(String buildPath, PdePreprocessor preprocessor) throws RunnerException {
// 1. concatenate all .pde files to the 'main' pde
// store line number for starting point of each code bit
StringBuffer bigCode = new StringBuffer();
int bigCount = 0;
for (SketchCode sc : sketch.getCodes()) {
if (sc.isExtension("ino") || sc.isExtension("pde")) {
sc.setPreprocOffset(bigCount);
// These #line directives help the compiler report errors with
// correct the filename and line number (issue 281 & 907)
bigCode.append("#line 1 \"" + sc.getFileName() + "\"\n");
bigCode.append(sc.getProgram());
bigCode.append('\n');
bigCount += sc.getLineCount();
}
}
// Note that the headerOffset isn't applied until compile and run, because
// it only applies to the code after it's been written to the .java file.
int headerOffset = 0;
try {
headerOffset = preprocessor.writePrefix(bigCode.toString());
} catch (FileNotFoundException fnfe) {
fnfe.printStackTrace();
String msg = _("Build folder disappeared or could not be written");
throw new RunnerException(msg);
}
// 2. run preproc on that code using the sugg class name
// to create a single .java file and write to buildpath
try {
// Output file
File streamFile = new File(buildPath, sketch.getName() + ".cpp");
FileOutputStream outputStream = new FileOutputStream(streamFile);
preprocessor.write(outputStream);
outputStream.close();
} catch (FileNotFoundException fnfe) {
fnfe.printStackTrace();
String msg = _("Build folder disappeared or could not be written");
throw new RunnerException(msg);
} catch (RunnerException pe) {
// RunnerExceptions are caught here and re-thrown, so that they don't
// get lost in the more general "Exception" handler below.
throw pe;
} catch (Exception ex) {
// TODO better method for handling this?
System.err.println(I18n.format(_("Uncaught exception type: {0}"), ex.getClass()));
ex.printStackTrace();
throw new RunnerException(ex.toString());
}
// grab the imports from the code just preproc'd
importedLibraries = new LibraryList();
for (String item : preprocessor.getExtraImports()) {
Library lib = BaseNoGui.importToLibraryTable.get(item);
if (lib != null && !importedLibraries.contains(lib)) {
importedLibraries.add(lib);
}
}
// 3. then loop over the code[] and save each .java file
for (SketchCode sc : sketch.getCodes()) {
if (sc.isExtension("c") || sc.isExtension("cpp") || sc.isExtension("h")) {
// no pre-processing services necessary for java files
// just write the the contents of 'program' to a .java file
// into the build directory. uses byte stream and reader/writer
// shtuff so that unicode bunk is properly handled
String filename = sc.getFileName(); //code[i].name + ".java";
try {
BaseNoGui.saveFile(sc.getProgram(), new File(buildPath, filename));
} catch (IOException e) {
e.printStackTrace();
throw new RunnerException(I18n.format(_("Problem moving {0} to the build folder"), filename));
}
} else if (sc.isExtension("ino") || sc.isExtension("pde")) {
// The compiler and runner will need this to have a proper offset
sc.addPreprocOffset(headerOffset);
}
}
}
/**
* List of library folders.
*/
private LibraryList importedLibraries;
/**
* Map an error from a set of processed .java files back to its location
* in the actual sketch.
* @param message The error message.
* @param dotJavaFilename The .java file where the exception was found.
* @param dotJavaLine Line number of the .java file for the exception (0-indexed!)
* @return A RunnerException to be sent to the editor, or null if it wasn't
* possible to place the exception to the sketch code.
*/
public RunnerException placeException(String message,
String dotJavaFilename,
int dotJavaLine) {
// Placing errors is simple, because we inserted #line directives
// into the preprocessed source. The compiler gives us correct
// the file name and line number. :-)
for (SketchCode code : sketch.getCodes()) {
if (dotJavaFilename.equals(code.getFileName())) {
return new RunnerException(message, sketch.indexOfCode(code), dotJavaLine);
}
}
return null;
}
}
|
package picocli;
import org.junit.Ignore;
import org.junit.Rule;
import org.junit.Test;
import org.junit.contrib.java.lang.system.ProvideSystemProperty;
import org.junit.contrib.java.lang.system.RestoreSystemProperties;
import org.junit.rules.TestRule;
import picocli.CommandLine.Command;
import picocli.CommandLine.DuplicateOptionAnnotationsException;
import picocli.CommandLine.Model.CommandSpec;
import picocli.CommandLine.Model.OptionSpec;
import picocli.CommandLine.Model.PositionalParamSpec;
import picocli.CommandLine.Option;
import picocli.CommandLine.ParameterException;
import picocli.CommandLine.Parameters;
import picocli.CommandLine.ParseResult;
import java.util.*;
import static org.junit.Assert.*;
import static picocli.CommandLine.ScopeType.INHERIT;
import static picocli.CommandLine.ScopeType.LOCAL;
public class InheritedOptionTest {
@Rule
public final ProvideSystemProperty ansiOFF = new ProvideSystemProperty("picocli.ansi", "false");
@Rule
// allows tests to set any kind of properties they like, without having to individually roll them back
public final TestRule restoreSystemProperties = new RestoreSystemProperties();
@Command(subcommands = Sub.class)
static class Top {
@Option(names = "--verbose", scope = INHERIT)
boolean verbose;
}
@Command(name = "sub", subcommands = SubSub.class)
static class Sub implements Runnable {
public void run() {
}
}
@Command(name = "subsub")
static class SubSub implements Runnable {
public void run() {
}
@Command
public void subsubsub() {
}
}
@Test
public void testGlobalOptionIsAddedToSubcommand() {
Top top = new Top();
CommandLine cmd = new CommandLine(top);
cmd.parseArgs("sub", "--verbose");
assertTrue(top.verbose);
}
@Test
public void testGlobalOptionIsAddedToSubSubcommand() {
Top top = new Top();
CommandLine cmd = new CommandLine(top);
cmd.parseArgs("sub", "subsub", "--verbose");
assertTrue(top.verbose);
}
@Test
public void testGlobalOptionDisallowedIfSubcommandAlreadyHasGlobalOptionWithSameName() {
Top top = new Top();
CommandLine cmd = new CommandLine(top);
class Other {
@Option(names = "--verbose", scope = INHERIT)
boolean verbose;
}
Other other = new Other();
try {
cmd.addSubcommand("other", other);
fail("Expected exception");
} catch (DuplicateOptionAnnotationsException ex) {
String msg = String.format("Option name '--verbose' is used by both field boolean %s.verbose and field boolean %s.verbose",
top.getClass().getName(), other.getClass().getName());
assertEquals(msg, ex.getMessage());
}
//cmd.parseArgs("other", "--verbose");
//assertTrue(top.verbose);
//assertFalse(other.verbose);
}
@Test
public void testGlobalOptionDisallowedIfSubcommandAlreadyHasNonGlobalOptionWithSameName() {
Top top = new Top();
CommandLine cmd = new CommandLine(top);
class Other {
@Option(names = "--verbose") // local
boolean verbose;
}
Other other = new Other();
try {
cmd.addSubcommand("other", other);
fail("Expected exception");
} catch (DuplicateOptionAnnotationsException ex) {
String msg = String.format("Option name '--verbose' is used by both field boolean %s.verbose and field boolean %s.verbose",
top.getClass().getName(), other.getClass().getName());
assertEquals(msg, ex.getMessage());
}
}
static class Base {
@Option(names = "--verbose", scope = INHERIT)
boolean verbose;
}
@Command(name = "ext",
subcommands = ExtSub.class,
resourceBundle = "picocli.InheritedOptionTest$MyBundle") //MyBundle.class.getName()
static class Ext extends Base{
}
@Command(name = "sub")
static class ExtSub {
@Command void subsub() {}
}
@Test
public void testGlobalOptionInBaseClass() {
//TestUtil.setTraceLevel("DEBUG");
// both top-level command and subcommand extend from a base class where global option is defined
Ext ext = new Ext();
CommandLine cmd = new CommandLine(ext);
cmd.parseArgs("sub", "subsub", "--verbose");
assertTrue(ext.verbose);
}
public static class MyBundle extends ListResourceBundle { // used in Ext
protected Object[][] getContents() {
return new Object[][] {
{"verbose", "VERBOSE DESCRIPTION"},
{"sub.verbose", "SUB CUSTOM VERBOSE DESCRIPTION IS IGNORED"}
};
}
}
@Test
public void testGlobalOptionDescriptionFromResourceBundle() {
CommandLine cmd = new CommandLine(new Ext());
String top = cmd.getUsageMessage();
String expected = String.format("" +
"Usage: ext [--verbose] [COMMAND]%n" +
" --verbose VERBOSE DESCRIPTION%n" +
"Commands:%n" +
" sub%n");
assertEquals(expected, top);
CommandLine subCmd = cmd.getSubcommands().get("sub");
String sub = subCmd.getUsageMessage();
String expectedSub = String.format("" +
"Usage: ext sub [--verbose] [COMMAND]%n" +
" --verbose VERBOSE DESCRIPTION%n" +
"Commands:%n" +
" subsub%n");
assertEquals(expectedSub, sub);
CommandLine subsubCmd = subCmd.getSubcommands().get("subsub");
String subsub = subsubCmd.getUsageMessage();
String expectedSubSub = String.format("" +
"Usage: ext sub subsub [--verbose]%n" +
" --verbose VERBOSE DESCRIPTION%n");
assertEquals(expectedSubSub, subsub);
}
@Test
public void testProgrammaticOptionBuilderScopeLocalByDefault() {
assertEquals(LOCAL, OptionSpec.builder("-a").scopeType());
}
@Test
public void testProgrammaticOptionBuilderScopeMutable() {
assertEquals(INHERIT, OptionSpec.builder("-a").scopeType(INHERIT).scopeType());
assertEquals(INHERIT, OptionSpec.builder("-a").scopeType(INHERIT).build().scopeType());
}
@Test
public void testProgrammaticOptionLocalByDefault() {
assertEquals(LOCAL, OptionSpec.builder("-a").build().scopeType());
}
@Test
public void testProgrammaticOptionBuilderInheritedFalseByDefault() {
assertFalse(OptionSpec.builder("-a").inherited());
}
@Test
public void testProgrammaticOptionBuilderInheritedMutable() {
assertTrue(OptionSpec.builder("-a").inherited(true).inherited());
assertTrue(OptionSpec.builder("-a").inherited(true).build().inherited());
}
@Test
public void testProgrammaticOptionInheritedFalseByDefault() {
assertFalse(OptionSpec.builder("-a").build().inherited());
}
@Test
public void testProgrammaticAddOptionBeforeSub() {
OptionSpec optA = OptionSpec.builder("-a").scopeType(INHERIT).build();
CommandSpec spec = CommandSpec.create();
spec.add(optA);
assertFalse(optA.inherited());
CommandSpec sub = CommandSpec.create();
spec.addSubcommand("sub", sub);
assertNotNull(spec.findOption("-a"));
assertNotNull(sub.findOption("-a"));
assertFalse(spec.findOption("-a").inherited());
assertTrue(sub.findOption("-a").inherited());
}
@Test
public void testProgrammaticAddOptionAfterSub() {
OptionSpec optA = OptionSpec.builder("-a").scopeType(INHERIT).build();
CommandSpec spec = CommandSpec.create();
CommandSpec sub = CommandSpec.create();
spec.addSubcommand("sub", sub);
spec.add(optA);
assertFalse(optA.inherited());
assertNotNull(spec.findOption("-a"));
assertNotNull(sub.findOption("-a"));
assertFalse(spec.findOption("-a").inherited());
assertTrue(sub.findOption("-a").inherited());
}
@Test
public void testProgrammaticPositionalParamBuilderScopeLocalByDefault() {
assertEquals(LOCAL, PositionalParamSpec.builder().scopeType());
}
@Test
public void testProgrammaticPositionalParamBuilderScopeMutable() {
assertEquals(INHERIT, PositionalParamSpec.builder().scopeType(INHERIT).scopeType());
assertEquals(INHERIT, PositionalParamSpec.builder().scopeType(INHERIT).build().scopeType());
}
@Test
public void testProgrammaticPositionalParamLocalByDefault() {
assertEquals(LOCAL, PositionalParamSpec.builder().build().scopeType());
}
@Test
public void testProgrammaticPositionalParamBuilderInheritedFalseByDefault() {
assertFalse(PositionalParamSpec.builder().inherited());
}
@Test
public void testProgrammaticPositionalParamBuilderInheritedMutable() {
assertTrue(PositionalParamSpec.builder().inherited(true).inherited());
assertTrue(PositionalParamSpec.builder().inherited(true).build().inherited());
}
@Test
public void testProgrammaticPositionalParamInheritedFalseByDefault() {
assertFalse(PositionalParamSpec.builder().build().inherited());
}
@Test
public void testProgrammaticAddPositionalParamBeforeSub() {
PositionalParamSpec positional = PositionalParamSpec.builder().scopeType(INHERIT).build();
CommandSpec spec = CommandSpec.create();
spec.add(positional);
assertFalse(positional.inherited());
CommandSpec sub = CommandSpec.create();
spec.addSubcommand("sub", sub);
assertFalse(spec.positionalParameters().isEmpty());
assertFalse(sub.positionalParameters().isEmpty());
assertFalse(spec.positionalParameters().get(0).inherited());
assertTrue(sub.positionalParameters().get(0).inherited());
}
@Test
public void testProgrammaticAddPositionalParamAfterSub() {
PositionalParamSpec positional = PositionalParamSpec.builder().scopeType(INHERIT).build();
CommandSpec spec = CommandSpec.create();
CommandSpec sub = CommandSpec.create();
spec.addSubcommand("sub", sub);
spec.add(positional);
assertFalse(positional.inherited());
assertFalse(spec.positionalParameters().isEmpty());
assertFalse(sub.positionalParameters().isEmpty());
assertFalse(spec.positionalParameters().get(0).inherited());
assertTrue(sub.positionalParameters().get(0).inherited());
}
@Command(name = "TopWithDefault", subcommands = SubWithDefault.class)
static class TopWithDefault {
List<String> xvalues = new ArrayList<String>();
@Option(names = "-x", defaultValue = "xxx", scope = INHERIT)
public void setX(String x) {
xvalues.add(x);
}
@Option(names = "-y", scope = INHERIT)
String y = "yyy";
@Option(names = "-z", defaultValue = "zzz", scope = INHERIT)
String z;
}
@Command(name = "sub", subcommands = SubSubWithDefault.class)
static class SubWithDefault { }
@Command(name = "subsub")
static class SubSubWithDefault { }
@Test
public void testInheritedOptionsWithDefault() {
TopWithDefault bean = new TopWithDefault();
CommandLine cmd = new CommandLine(bean);
cmd.parseArgs();
assertEquals(Arrays.asList("xxx"), bean.xvalues);
assertEquals("yyy", bean.y);
assertEquals("zzz", bean.z);
cmd.parseArgs("-y=1", "-z=2", "sub");
assertEquals("1", bean.y);
assertEquals("2", bean.z);
assertEquals(Arrays.asList("xxx", "xxx"), bean.xvalues); // setters cannot be initialized
cmd.parseArgs("sub", "subsub");
assertEquals("zzz", bean.z);
assertEquals(Arrays.asList("xxx", "xxx", "xxx"), bean.xvalues); // setters cannot be initialized
assertEquals("yyy", bean.y);
}
@Test
public void testInheritedRequiredArgs() {
//System.setProperty("picocli.trace", "DEBUG");
@Command
class App {
@Option(names = "-x", required = true, scope = INHERIT) int x;
@Command void sub() {}
}
CommandLine cmd0 = new CommandLine(new App());
cmd0.parseArgs("-x=2");
CommandLine cmd1 = new CommandLine(new App());
cmd1.parseArgs("sub", "-x=2");
CommandLine cmd2 = new CommandLine(new App());
try {
cmd2.parseArgs();
fail("Expected exception");
} catch (ParameterException ex) {
assertEquals("Missing required option: '-x=<x>'", ex.getMessage());
}
CommandLine cmd3 = new CommandLine(new App());
try {
cmd3.parseArgs("sub");
fail("Expected exception");
} catch (ParameterException ex) {
assertEquals("Missing required option: '-x=<x>'", ex.getMessage());
}
}
@Command(subcommands = Sub.class)
static class TopWithRequiredArg implements Runnable {
@Option(names = "-x", required = true, scope = INHERIT)
int x;
@Parameters(index = "0", scope = INHERIT)
String p0;
@Parameters(index = "1", scope = INHERIT)
String p1;
@Parameters(index = "2..*", scope = INHERIT)
String[] remainder;
public void run() {
}
}
@Test
public void testInheritedRequiredArgsDeepNesting() {
//System.setProperty("picocli.trace", "DEBUG");
CommandLine cmdx = new CommandLine(new TopWithRequiredArg());
cmdx.parseArgs("-x=2", "0", "1");
CommandLine cmdSubX = new CommandLine(new TopWithRequiredArg());
cmdSubX.parseArgs("sub", "-x=2", "0", "1");
CommandLine cmdSubSubX = new CommandLine(new TopWithRequiredArg());
cmdSubSubX.parseArgs("sub", "subsub", "-x=2", "0", "1");
TopWithRequiredArg top4 = new TopWithRequiredArg();
CommandLine cmdSubSubSubX = new CommandLine(top4);
cmdSubSubSubX.parseArgs("sub", "subsub", "subsubsub", "-x=2", "0", "1", "2", "3");
assertEquals(2, top4.x);
assertEquals("0", top4.p0);
assertEquals("1", top4.p1);
assertArrayEquals(new String[]{"2", "3"}, top4.remainder);
CommandLine cmd2 = new CommandLine(new TopWithRequiredArg());
try {
cmd2.parseArgs();
fail("Expected exception");
} catch (ParameterException ex) {
assertEquals("Missing required options and parameters: '-x=<x>', '<p0>', '<p1>'", ex.getMessage());
}
CommandLine cmd3 = new CommandLine(new TopWithRequiredArg());
try {
cmd3.parseArgs("sub");
fail("Expected exception");
} catch (ParameterException ex) {
assertEquals("Missing required options and parameters: '-x=<x>', '<p0>', '<p1>'", ex.getMessage());
}
CommandLine cmd4 = new CommandLine(new TopWithRequiredArg());
try {
cmd4.parseArgs("sub", "subsub");
fail("Expected exception");
} catch (ParameterException ex) {
assertEquals("Missing required options and parameters: '-x=<x>', '<p0>', '<p1>'", ex.getMessage());
}
CommandLine cmd5 = new CommandLine(new TopWithRequiredArg());
try {
cmd5.parseArgs("sub", "subsub", "subsubsub");
fail("Expected exception");
} catch (ParameterException ex) {
assertEquals("Missing required options and parameters: '-x=<x>', '<p0>', '<p1>'", ex.getMessage());
}
}
@Test
public void testIssue1042InheritedOptionsWithCommandMethods() {
@Command(name = "issue1042")
class Issue1042 implements Runnable {
boolean debug;
boolean run;
boolean subRun;
@Option(names = {"--debug", "-d"}, scope = INHERIT)
protected void setDebug(boolean debug) {
this.debug = debug;
}
public void run() { run = true; }
@Command
void sub() { subRun = true; }
}
Issue1042 bean = new Issue1042();
new CommandLine(bean).execute("sub", "--debug");
assertTrue(bean.debug);
assertTrue(bean.subRun);
assertFalse(bean.run);
}
@Command(name = "Issue1159")
static class Issue1159 {
@Option(names = "--xxx-yyy", scope = INHERIT)
int x;
@Command
void sub() {
}
}
@Test
public void testIssue1159() {
Issue1159 bean = new Issue1159();
CommandLine cmd = new CommandLine(bean);
cmd.setAbbreviatedOptionsAllowed(true);
cmd.parseArgs("--x-y", "123");
assertEquals(123, bean.x);
cmd.parseArgs("sub", "--x-y", "345");
assertEquals(345, bean.x);
}
@Test
public void testIssue1159WithEquals() {
Issue1159 bean = new Issue1159();
CommandLine cmd = new CommandLine(bean);
cmd.setAbbreviatedOptionsAllowed(true);
cmd.parseArgs("--x-y=123");
assertEquals(123, bean.x);
cmd.parseArgs("sub", "--x-y=345");
assertEquals(345, bean.x);
}
@Test
public void testIssue1159ParseResult() {
Issue1159 bean = new Issue1159();
CommandLine cmd = new CommandLine(bean).setAbbreviatedOptionsAllowed(true);
ParseResult parseResult = cmd.parseArgs("sub", "--x", "345");
assertEquals(345, bean.x);
assertTrue(parseResult.hasSubcommand());
ParseResult subResult = parseResult.subcommand();
assertTrue("Matched on the subcommand", subResult.hasMatchedOption("--xxx-yyy"));
Object subValue = subResult.matchedOption("--xxx-yyy").getValue();
assertEquals(345, subValue);
assertFalse("Abbreviated options not supported in ParseResult...",
subResult.hasMatchedOption("--x")); // this does not work
assertFalse("Not matched on the parent command",
parseResult.hasMatchedOption("--xxx-yyy"));
}
}
|
package primegen;
import com.github.approval.Approval;
import com.github.approval.converters.Converters;
import com.github.approval.converters.ListConverter;
import com.github.approval.pathmappers.JunitPathMapper;
import com.github.approval.reporters.Reporters;
import org.junit.Rule;
import org.junit.Test;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import static org.junit.Assert.assertEquals;
public class PrimeGeneratorTest {
private final Path PARENT_PATH = Paths.get("src/test/resources");
@Rule
public JunitPathMapper pathMapper = new JunitPathMapper(PARENT_PATH);
private Approval<List<String>> APPROVAL = Approval
.of(List.class)
.withPathMapper(pathMapper)
.withReporter(Reporters.console())
.withConveter(new ListConverter(Converters.STRING))
.build();
@Test
public void should_generate_primes() {
int[] nullArray = new PrimeGenerator().generatePrimes(0);
assertEquals(0, nullArray.length);
int[] minArray = new PrimeGenerator().generatePrimes(2);
assertEquals(1, minArray.length);
assertEquals(2, minArray[0]);
int[] threeArray = new PrimeGenerator().generatePrimes(3);
assertEquals(2, threeArray.length);
assertEquals(2, threeArray[0]);
assertEquals(3, threeArray[1]);
}
@Test
public void should_generate_primes_from_0_to_500() {
List<String> actual = new ArrayList<>();
for (int i = 0; i <= 500; i++) {
int[] primes = new PrimeGenerator().generatePrimes(i);
actual.add(Arrays.toString(primes));
}
APPROVAL.verify(actual, Paths.get("0 to 500"));
}
}
|
package org.opennms.features.topology.plugins.topo.graphml;
import java.util.Map;
import org.opennms.features.topology.api.topo.AbstractEdge;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Maps;
public class GraphMLEdge extends AbstractEdge {
private Map<String, Object> properties = Maps.newHashMap();
public GraphMLEdge(org.opennms.features.graphml.model.GraphMLEdge graphMLEdge, GraphMLVertex source, GraphMLVertex target) {
super(graphMLEdge.getProperty(GraphMLProperties.NAMESPACE),
graphMLEdge.getProperty(GraphMLProperties.ID),
source,
target);
setTooltipText(graphMLEdge.getProperty(GraphMLProperties.TOOLTIP_TEXT));
setProperties(graphMLEdge.getProperties());
}
protected GraphMLEdge(GraphMLEdge other) {
super(other);
properties = ImmutableMap.copyOf(properties);
}
public Map<String, Object> getProperties() {
return properties;
}
public void setProperties(Map<String, Object> properties) {
this.properties = properties;
}
@Override
public AbstractEdge clone() {
// Ensures that the properties are also copied when cloned
return new GraphMLEdge(this);
}
}
|
package com.xpn.xwiki.plugin.activitystream.impl;
import java.io.StringWriter;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
import org.hibernate.Query;
import org.hibernate.Session;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.xwiki.annotation.event.AnnotationAddedEvent;
import org.xwiki.annotation.event.AnnotationDeletedEvent;
import org.xwiki.annotation.event.AnnotationUpdatedEvent;
import org.xwiki.bridge.event.DocumentCreatedEvent;
import org.xwiki.bridge.event.DocumentDeletedEvent;
import org.xwiki.bridge.event.DocumentUpdatedEvent;
import org.xwiki.configuration.ConfigurationSource;
import org.xwiki.model.reference.DocumentReference;
import org.xwiki.model.reference.EntityReferenceSerializer;
import org.xwiki.observation.EventListener;
import org.xwiki.observation.ObservationContext;
import org.xwiki.observation.ObservationManager;
import org.xwiki.observation.event.BeginFoldEvent;
import org.xwiki.observation.event.Event;
import org.xwiki.observation.remote.RemoteObservationManagerContext;
import org.xwiki.rendering.syntax.Syntax;
import com.sun.syndication.feed.synd.SyndContentImpl;
import com.sun.syndication.feed.synd.SyndEntry;
import com.sun.syndication.feed.synd.SyndEntryImpl;
import com.sun.syndication.feed.synd.SyndFeed;
import com.sun.syndication.feed.synd.SyndFeedImpl;
import com.sun.syndication.io.SyndFeedOutput;
import com.xpn.xwiki.XWikiContext;
import com.xpn.xwiki.XWikiException;
import com.xpn.xwiki.doc.XWikiDocument;
import com.xpn.xwiki.internal.event.AttachmentAddedEvent;
import com.xpn.xwiki.internal.event.AttachmentDeletedEvent;
import com.xpn.xwiki.internal.event.AttachmentUpdatedEvent;
import com.xpn.xwiki.internal.event.CommentAddedEvent;
import com.xpn.xwiki.internal.event.CommentDeletedEvent;
import com.xpn.xwiki.internal.event.CommentUpdatedEvent;
import com.xpn.xwiki.plugin.activitystream.api.ActivityEvent;
import com.xpn.xwiki.plugin.activitystream.api.ActivityEventPriority;
import com.xpn.xwiki.plugin.activitystream.api.ActivityEventType;
import com.xpn.xwiki.plugin.activitystream.api.ActivityStream;
import com.xpn.xwiki.plugin.activitystream.api.ActivityStreamException;
import com.xpn.xwiki.plugin.activitystream.plugin.ActivityStreamPlugin;
import com.xpn.xwiki.store.XWikiHibernateStore;
import com.xpn.xwiki.web.Utils;
/**
* Default implementation for {@link ActivityStream}.
*
* @version $Id$
*/
@SuppressWarnings("serial")
public class ActivityStreamImpl implements ActivityStream, EventListener
{
/** Logging helper object. */
private static final Logger LOGGER = LoggerFactory.getLogger(ActivityStreamImpl.class);
/**
* Key used to store the request ID in the context.
*/
private static final String REQUEST_ID_CONTEXT_KEY = "activitystream_requestid";
/**
* Character used as a separator in event IDs.
*/
private static final String EVENT_ID_ELEMENTS_SEPARATOR = "-";
/**
* The name of the listener.
*/
private static final String LISTENER_NAME = "activitystream";
/**
* The events to match.
*/
private static final List<Event> LISTENER_EVENTS = new ArrayList<Event>()
{
{
add(new DocumentCreatedEvent());
add(new DocumentUpdatedEvent());
add(new DocumentDeletedEvent());
add(new CommentAddedEvent());
add(new CommentDeletedEvent());
add(new CommentUpdatedEvent());
add(new AttachmentAddedEvent());
add(new AttachmentDeletedEvent());
add(new AttachmentUpdatedEvent());
add(new AnnotationAddedEvent());
add(new AnnotationDeletedEvent());
add(new AnnotationUpdatedEvent());
}
};
/**
* Set fields related to the document which fired the event in the given event object.
*
* @param event the event to prepare
* @param doc document which fired the event
* @param context the XWiki context
*/
private void setEventDocumentRelatedInformation(ActivityEvent event, XWikiDocument doc, XWikiContext context)
{
if (doc != null) {
if (event.getStream() == null) {
event.setStream(getStreamName(doc.getSpace(), context));
}
if (event.getSpace() == null) {
event.setSpace(doc.getSpace());
}
if (event.getPage() == null) {
event.setPage(doc.getFullName());
}
if (event.getUrl() == null) {
// Protection against NPEs, events can happen before the URL factory gets created.
if (context.getURLFactory() != null) {
event.setUrl(doc.getURL("view", context));
}
}
}
}
/**
* Set fields in the given event object.
*
* @param event the event to prepare
* @param doc document which fired the event
* @param context the XWiki context
*/
protected void prepareEvent(ActivityEvent event, XWikiDocument doc, XWikiContext context)
{
if (event.getUser() == null) {
event.setUser(getSerializedReference(context.getUserReference()));
}
if (event.getWiki() == null) {
event.setWiki(context.getWikiId());
}
if (event.getApplication() == null) {
event.setApplication("xwiki");
}
if (event.getDate() == null) {
event.setDate(new Date());
}
if (event.getEventId() == null) {
event.setEventId(generateEventId(event, context));
}
if (event.getRequestId() == null) {
event.setRequestId((String) context.get(REQUEST_ID_CONTEXT_KEY));
}
setEventDocumentRelatedInformation(event, doc, context);
}
/**
* Generate event ID for the given ID. Note that this method does not perform the set of the ID in the event object.
*
* @param event event to generate the ID for
* @param context the XWiki context
* @return the generated ID
*/
protected String generateEventId(ActivityEvent event, XWikiContext context)
{
String keySeparator = EVENT_ID_ELEMENTS_SEPARATOR;
String wikiSpaceSeparator = ":";
String key =
event.getStream() + keySeparator + event.getApplication() + keySeparator + event.getWiki()
+ wikiSpaceSeparator + event.getPage() + keySeparator + event.getType();
long hash = key.hashCode();
if (hash < 0) {
hash = -hash;
}
String id =
"" + hash + keySeparator + event.getDate().getTime() + keySeparator
+ RandomStringUtils.randomAlphanumeric(8);
if (context.get(REQUEST_ID_CONTEXT_KEY) == null) {
context.put(REQUEST_ID_CONTEXT_KEY, id);
}
return id;
}
/**
* @return a new instance of {@link ActivityEventImpl}.
*/
protected ActivityEvent newActivityEvent()
{
return new ActivityEventImpl();
}
@Override
public void init(XWikiContext context) throws XWikiException
{
// Listent to Events.
ObservationManager observationManager = Utils.getComponent(ObservationManager.class);
if (observationManager.getListener(getName()) == null) {
observationManager.addListener(this);
}
// Init activitystream cleaner.
ActivityStreamCleaner.getInstance().init(context);
}
@Override
public String getStreamName(String space, XWikiContext context)
{
return space;
}
@Override
public void addActivityEvent(ActivityEvent event, XWikiContext context) throws ActivityStreamException
{
addActivityEvent(event, null, context);
}
/**
* This method determine if events must be store in the local wiki. If the activitystream is set not to store events
* in the main wiki, the method will return true. If events are stored in the main wiki, the method retrieves the
* 'platform.plugin.activitystream.uselocalstore' configuration option. If the option is not found the method
* returns true (default behavior).
*
* @param context the XWiki context
* @return true if the activity stream is configured to store events in the main wiki, false otherwise
*/
private boolean useLocalStore(XWikiContext context)
{
if (!useMainStore(context)) {
// If the main store is disabled, force local store.
return true;
}
ActivityStreamPlugin plugin =
(ActivityStreamPlugin) context.getWiki().getPlugin(ActivityStreamPlugin.PLUGIN_NAME, context);
return Integer.parseInt(plugin.getActivityStreamPreference("uselocalstore", "1", context)) == 1;
}
/**
* This method determine if events must be store in the main wiki. If the current wiki is the main wiki, this method
* returns false, otherwise if retrieves the 'platform.plugin.activitystream.usemainstore' configuration option. If
* the option is not found the method returns true (default behavior).
*
* @param context the XWiki context
* @return true if the activity stream is configured to store events in the main wiki, false otherwise
*/
private boolean useMainStore(XWikiContext context)
{
if (context.isMainWiki()) {
// We're in the main database, we don't have to store the data twice.
return false;
}
ActivityStreamPlugin plugin =
(ActivityStreamPlugin) context.getWiki().getPlugin(ActivityStreamPlugin.PLUGIN_NAME, context);
return Integer.parseInt(plugin.getActivityStreamPreference("usemainstore", "1", context)) == 1;
}
/**
* @param event event to add to the stream
* @param doc which fired the event
* @param context the XWiki context
* @throws ActivityStreamException if the addition to the stream fails
*/
public void addActivityEvent(ActivityEvent event, XWikiDocument doc, XWikiContext context)
throws ActivityStreamException
{
prepareEvent(event, doc, context);
if (useLocalStore(context)) {
// store event in the local database
XWikiHibernateStore localHibernateStore = context.getWiki().getHibernateStore();
try {
localHibernateStore.beginTransaction(context);
Session session = localHibernateStore.getSession(context);
session.save(event);
localHibernateStore.endTransaction(context, true);
} catch (XWikiException e) {
localHibernateStore.endTransaction(context, false);
}
}
if (useMainStore(context)) {
// store event in the main database
String oriDatabase = context.getWikiId();
context.setWikiId(context.getMainXWiki());
XWikiHibernateStore mainHibernateStore = context.getWiki().getHibernateStore();
try {
mainHibernateStore.beginTransaction(context);
Session session = mainHibernateStore.getSession(context);
session.save(event);
mainHibernateStore.endTransaction(context, true);
} catch (XWikiException e) {
mainHibernateStore.endTransaction(context, false);
} finally {
context.setWikiId(oriDatabase);
}
}
}
@Override
public void addActivityEvent(String streamName, String type, String title, XWikiContext context)
throws ActivityStreamException
{
addActivityEvent(streamName, type, title, null, context);
}
@Override
public void addActivityEvent(String streamName, String type, String title, List<String> params, XWikiContext context)
throws ActivityStreamException
{
ActivityEvent event = newActivityEvent();
event.setStream(streamName);
event.setType(type);
event.setTitle(title);
event.setBody(title);
event.setParams(params);
addActivityEvent(event, context);
}
@Override
public void addDocumentActivityEvent(String streamName, XWikiDocument doc, String type, String title,
XWikiContext context) throws ActivityStreamException
{
addDocumentActivityEvent(streamName, doc, type, ActivityEventPriority.NOTIFICATION, title, null, context);
}
@Override
public void addDocumentActivityEvent(String streamName, XWikiDocument doc, String type, int priority, String title,
XWikiContext context) throws ActivityStreamException
{
addDocumentActivityEvent(streamName, doc, type, priority, title, null, context);
}
@Override
public void addDocumentActivityEvent(String streamName, XWikiDocument doc, String type, String title,
List<String> params, XWikiContext context) throws ActivityStreamException
{
addDocumentActivityEvent(streamName, doc, type, ActivityEventPriority.NOTIFICATION, title, params, context);
}
@Override
public void addDocumentActivityEvent(String streamName, XWikiDocument doc, String type, int priority, String title,
List<String> params, XWikiContext context) throws ActivityStreamException
{
ActivityEventImpl event = new ActivityEventImpl();
event.setStream(streamName);
event.setPage(doc.getFullName());
if (doc.getDatabase() != null) {
event.setWiki(doc.getDatabase());
}
event.setDate(doc.getDate());
event.setPriority(priority);
event.setType(type);
event.setTitle(title);
event.setBody(title);
event.setVersion(doc.getVersion());
event.setParams(params);
// This might be wrong once non-altering events will be logged.
event.setUser(getSerializedReference(doc.getAuthorReference()));
event.setHidden(doc.isHidden());
addActivityEvent(event, doc, context);
}
/**
* @param event the event
* @param bTransaction true if inside a transaction
* @param context the XWiki Context
* @return the event
* @throws ActivityStreamException
*/
private ActivityEventImpl loadActivityEvent(ActivityEvent event, boolean bTransaction, XWikiContext context)
throws ActivityStreamException
{
boolean bTransactionMutable = bTransaction;
ActivityEventImpl act = null;
String eventId = event.getEventId();
if (useLocalStore(context)) {
// load event from the local database
XWikiHibernateStore hibstore = context.getWiki().getHibernateStore();
try {
if (bTransactionMutable) {
hibstore.checkHibernate(context);
bTransactionMutable = hibstore.beginTransaction(false, context);
}
Session session = hibstore.getSession(context);
Query query =
session
.createQuery("select act.eventId from ActivityEventImpl as act where act.eventId = :eventId");
query.setString("eventId", eventId);
if (query.uniqueResult() != null) {
act = new ActivityEventImpl();
session.load(act, eventId);
}
if (bTransactionMutable) {
hibstore.endTransaction(context, false, false);
}
} catch (Exception e) {
throw new ActivityStreamException();
} finally {
try {
if (bTransactionMutable) {
hibstore.endTransaction(context, false, false);
}
} catch (Exception e) {
// Do nothing.
}
}
} else if (useMainStore(context)) {
// load event from the main database
String oriDatabase = context.getWikiId();
context.setWikiId(context.getMainXWiki());
XWikiHibernateStore hibstore = context.getWiki().getHibernateStore();
try {
if (bTransactionMutable) {
hibstore.checkHibernate(context);
bTransactionMutable = hibstore.beginTransaction(false, context);
}
Session session = hibstore.getSession(context);
Query query =
session
.createQuery("select act.eventId from ActivityEventImpl as act where act.eventId = :eventId");
query.setString("eventId", eventId);
if (query.uniqueResult() != null) {
act = new ActivityEventImpl();
session.load(act, eventId);
}
if (bTransactionMutable) {
hibstore.endTransaction(context, false, false);
}
} catch (Exception e) {
throw new ActivityStreamException();
} finally {
context.setWikiId(oriDatabase);
try {
if (bTransactionMutable) {
hibstore.endTransaction(context, false, false);
}
} catch (Exception e) {
// Do nothing.
}
}
}
return act;
}
@Override
public void deleteActivityEvent(ActivityEvent event, XWikiContext context) throws ActivityStreamException
{
boolean bTransaction = true;
ActivityEventImpl evImpl = loadActivityEvent(event, true, context);
String oriDatabase = context.getWikiId();
if (useLocalStore(context)) {
XWikiHibernateStore hibstore;
// delete event from the local database
if (context.getWikiId().equals(event.getWiki())) {
hibstore = context.getWiki().getHibernateStore();
} else {
context.setWikiId(event.getWiki());
hibstore = context.getWiki().getHibernateStore();
}
try {
if (bTransaction) {
hibstore.checkHibernate(context);
bTransaction = hibstore.beginTransaction(context);
}
Session session = hibstore.getSession(context);
session.delete(evImpl);
if (bTransaction) {
hibstore.endTransaction(context, true);
}
} catch (XWikiException e) {
throw new ActivityStreamException();
} finally {
try {
if (bTransaction) {
hibstore.endTransaction(context, false);
}
if (context.getWikiId().equals(oriDatabase)) {
context.setWikiId(oriDatabase);
}
} catch (Exception e) {
// Do nothing.
}
}
}
if (useMainStore(context)) {
// delete event from the main database
context.setWikiId(context.getMainXWiki());
XWikiHibernateStore hibstore = context.getWiki().getHibernateStore();
try {
if (bTransaction) {
hibstore.checkHibernate(context);
bTransaction = hibstore.beginTransaction(context);
}
Session session = hibstore.getSession(context);
session.delete(evImpl);
if (bTransaction) {
hibstore.endTransaction(context, true);
}
} catch (XWikiException e) {
throw new ActivityStreamException();
} finally {
try {
if (bTransaction) {
hibstore.endTransaction(context, false);
}
context.setWikiId(oriDatabase);
} catch (Exception e) {
// Do nothing
}
}
}
}
@Override
public List<ActivityEvent> searchEvents(String hql, boolean filter, int nb, int start, XWikiContext context)
throws ActivityStreamException
{
return searchEvents("", hql, filter, nb, start, context);
}
@Override
public List<ActivityEvent> searchEvents(String hql, boolean filter, boolean globalSearch, int nb, int start,
XWikiContext context) throws ActivityStreamException
{
return searchEvents("", hql, filter, globalSearch, nb, start, context);
}
@Override
public List<ActivityEvent> searchEvents(String hql, boolean filter, boolean globalSearch, int nb, int start,
List<Object> parameterValues, XWikiContext context) throws ActivityStreamException
{
return searchEvents("", hql, filter, globalSearch, nb, start, parameterValues, context);
}
@Override
public List<ActivityEvent> searchEvents(String fromHql, String hql, boolean filter, int nb, int start,
XWikiContext context) throws ActivityStreamException
{
return searchEvents(fromHql, hql, filter, nb, start, null, context);
}
@Override
public List<ActivityEvent> searchEvents(String fromHql, String hql, boolean filter, boolean globalSearch, int nb,
int start, XWikiContext context) throws ActivityStreamException
{
return searchEvents(fromHql, hql, filter, globalSearch, nb, start, null, context);
}
@Override
public List<ActivityEvent> searchEvents(String fromHql, String hql, boolean filter, int nb, int start,
List<Object> parameterValues, XWikiContext context) throws ActivityStreamException
{
return searchEvents(fromHql, hql, filter, false, nb, start, parameterValues, context);
}
/**
* This method will add a where clause to filter events fired from hidden documents. The clause will not be added to
* the query if the user has specified that he wish to see hidden documents in his profile. If the clause is added
* this method will also add a 'where' to the query if it is missing.
*
* @param query The query to add the filter to
*/
private void addHiddenEventsFilter(StringBuffer query)
{
ConfigurationSource source = Utils.getComponent(ConfigurationSource.class, "user");
Integer preference = source.getProperty("displayHiddenDocuments", Integer.class);
if (preference == null || preference != 1) {
if (!query.toString().contains(" where ")) {
query.append(" where ");
}
query.append(" (act.hidden <> true or act.hidden is null) and ");
}
}
/**
* This method will add the passed optional where clause to the given query if the optional clause is not an empty
* string nor null. If the clause is added this method will also add a 'where' to the query if it is missing.
*
* @param query The query to add the where clause to
* @param optionalWhereClause The optional where clause to add
*/
private void addOptionalEventsFilter(StringBuffer query, String optionalWhereClause)
{
if (StringUtils.isNotBlank(optionalWhereClause)) {
if (!query.toString().contains(" where ")) {
query.append(" where ");
}
query.append(optionalWhereClause);
}
}
@Override
public List<ActivityEvent> searchEvents(String fromHql, String hql, boolean filter, boolean globalSearch, int nb,
int start, List<Object> parameterValues, XWikiContext context) throws ActivityStreamException
{
StringBuffer searchHql = new StringBuffer();
List<ActivityEvent> results;
if (filter) {
searchHql.append("select act from ActivityEventImpl as act, ActivityEventImpl as act2 ");
searchHql.append(fromHql);
searchHql.append(" where act.eventId=act2.eventId and ");
addHiddenEventsFilter(searchHql);
searchHql.append(hql);
searchHql.append(" group by act.requestId having (act.priority)=max(act2.priority) order by act.date desc");
} else {
searchHql.append("select act from ActivityEventImpl as act ");
searchHql.append(fromHql);
searchHql.append(" where ");
addHiddenEventsFilter(searchHql);
searchHql.append(hql);
searchHql.append(" order by act.date desc");
}
if (globalSearch) {
// Search in the main database
String oriDatabase = context.getWikiId();
try {
context.setWikiId(context.getMainXWiki());
results =
context.getWiki().getStore().search(searchHql.toString(), nb, start, parameterValues, context);
} catch (XWikiException e) {
throw new ActivityStreamException(e);
} finally {
context.setWikiId(oriDatabase);
}
} else {
try {
// Search in the local database
results =
context.getWiki().getStore().search(searchHql.toString(), nb, start, parameterValues, context);
} catch (XWikiException e) {
throw new ActivityStreamException(e);
}
}
return results;
}
@Override
public List<ActivityEvent> getEvents(boolean filter, int nb, int start, XWikiContext context)
throws ActivityStreamException
{
return searchEvents("1=1", filter, nb, start, context);
}
@Override
public List<ActivityEvent> getEventsForSpace(String space, boolean filter, int nb, int start, XWikiContext context)
throws ActivityStreamException
{
return searchEvents("act.space='" + space + "'", filter, nb, start, context);
}
@Override
public List<ActivityEvent> getEventsForUser(String user, boolean filter, int nb, int start, XWikiContext context)
throws ActivityStreamException
{
return searchEvents("act.user='" + user + "'", filter, nb, start, context);
}
@Override
public List<ActivityEvent> getEvents(String stream, boolean filter, int nb, int start, XWikiContext context)
throws ActivityStreamException
{
return searchEvents("act.stream='" + stream + "'", filter, nb, start, context);
}
@Override
public List<ActivityEvent> getEventsForSpace(String stream, String space, boolean filter, int nb, int start,
XWikiContext context) throws ActivityStreamException
{
return searchEvents("act.space='" + space + "' and act.stream='" + stream + "'", filter, nb, start, context);
}
@Override
public List<ActivityEvent> getEventsForUser(String stream, String user, boolean filter, int nb, int start,
XWikiContext context) throws ActivityStreamException
{
return searchEvents("act.user='" + user + "' and act.stream='" + stream + "'", filter, nb, start, context);
}
@Override
public SyndEntry getFeedEntry(ActivityEvent event, XWikiContext context)
{
return getFeedEntry(event, "", context);
}
@Override
public SyndEntry getFeedEntry(ActivityEvent event, String suffix, XWikiContext context)
{
SyndEntry entry = new SyndEntryImpl();
String user = event.getUser();
String displayUser = context.getWiki().getUserName(user, null, false, context);
entry.setAuthor(displayUser);
event.setTitle(event.getTitle() + ".rss.title" + suffix);
entry.setTitle(event.getDisplayTitle(context));
event.setBody(event.getBody() + ".rss.body" + suffix);
SyndContentImpl sc = new SyndContentImpl();
sc.setValue(event.getDisplayBody(context));
sc.setType("text/html");
entry.setDescription(sc);
String url;
try {
url = (new URL(context.getURL(), event.getUrl())).toString();
} catch (MalformedURLException e) {
url = event.getUrl();
}
entry.setLink(url);
entry.setPublishedDate(event.getDate());
entry.setUpdatedDate(event.getDate());
return entry;
}
@Override
public SyndFeed getFeed(List<ActivityEvent> events, XWikiContext context)
{
return getFeed(events, "", context);
}
@Override
public SyndFeed getFeed(List<ActivityEvent> events, String suffix, XWikiContext context)
{
SyndFeed feed = new SyndFeedImpl();
List<SyndEntry> entries = new ArrayList<SyndEntry>();
for (ActivityEvent event : events) {
SyndEntry entry = getFeedEntry(event, suffix, context);
entries.add(entry);
}
feed.setEntries(entries);
return feed;
}
@Override
public SyndFeed getFeed(List<ActivityEvent> events, String author, String title, String description,
String copyright, String encoding, String url, XWikiContext context)
{
return getFeed(events, author, title, description, copyright, encoding, url, "", context);
}
@Override
public SyndFeed getFeed(List<ActivityEvent> events, String author, String title, String description,
String copyright, String encoding, String url, String suffix, XWikiContext context)
{
SyndFeed feed = getFeed(events, suffix, context);
feed.setAuthor(author);
feed.setDescription(description);
feed.setCopyright(copyright);
feed.setEncoding(encoding);
feed.setLink(url);
feed.setTitle(title);
return feed;
}
@Override
public String getFeedOutput(List<ActivityEvent> events, String author, String title, String description,
String copyright, String encoding, String url, String type, XWikiContext context)
{
return getFeedOutput(events, author, title, description, copyright, encoding, url, type, "", context);
}
@Override
public String getFeedOutput(List<ActivityEvent> events, String author, String title, String description,
String copyright, String encoding, String url, String type, String suffix, XWikiContext context)
{
SyndFeed feed = getFeed(events, author, title, description, copyright, encoding, url, suffix, context);
return getFeedOutput(feed, type);
}
@Override
public String getFeedOutput(SyndFeed feed, String type)
{
feed.setFeedType(type);
StringWriter writer = new StringWriter();
SyndFeedOutput output = new SyndFeedOutput();
try {
output.output(feed, writer);
writer.close();
return writer.toString();
} catch (Exception e) {
return "";
}
}
@Override
public List<Event> getEvents()
{
return LISTENER_EVENTS;
}
@Override
public String getName()
{
return LISTENER_NAME;
}
private static BeginFoldEvent IGNORED_EVENTS = new BeginFoldEvent()
{
@Override
public boolean matches(Object otherEvent)
{
return otherEvent instanceof BeginFoldEvent;
}
};
@Override
public void onEvent(Event event, Object source, Object data)
{
// Do not record some ignored events
ObservationContext observationContext = Utils.getComponent(ObservationContext.class);
if (observationContext.isIn(IGNORED_EVENTS)) {
return;
}
XWikiDocument currentDoc = (XWikiDocument) source;
XWikiDocument originalDoc = currentDoc.getOriginalDocument();
XWikiContext context = (XWikiContext) data;
String wiki = context.getWikiId();
String msgPrefix = "activitystream.event.";
String streamName = getStreamName(currentDoc.getSpace(), context);
// If we haven't found a stream to store the event or if both currentDoc and originalDoc are null: exit
if (streamName == null) {
return;
}
// Take events into account only once in a cluster
if (!Utils.getComponent(RemoteObservationManagerContext.class).isRemoteState()) {
String eventType;
String displayTitle;
String additionalIdentifier = null;
if (event instanceof DocumentCreatedEvent) {
eventType = ActivityEventType.CREATE;
displayTitle = currentDoc.getRenderedTitle(Syntax.XHTML_1_0, context);
} else if (event instanceof DocumentUpdatedEvent) {
eventType = ActivityEventType.UPDATE;
displayTitle = originalDoc.getRenderedTitle(Syntax.XHTML_1_0, context);
} else if (event instanceof DocumentDeletedEvent) {
eventType = ActivityEventType.DELETE;
displayTitle = originalDoc.getRenderedTitle(Syntax.XHTML_1_0, context);
// When we receive a DELETE event, the given document is blank and does not have version & hidden tag
// properly set.
currentDoc.setVersion(originalDoc.getVersion());
currentDoc.setHidden(originalDoc.isHidden());
} else if (event instanceof CommentAddedEvent) {
eventType = ActivityEventType.ADD_COMMENT;
displayTitle = currentDoc.getRenderedTitle(Syntax.XHTML_1_0, context);
additionalIdentifier = ((CommentAddedEvent) event).getIdentifier();
} else if (event instanceof CommentDeletedEvent) {
eventType = ActivityEventType.DELETE_COMMENT;
displayTitle = currentDoc.getRenderedTitle(Syntax.XHTML_1_0, context);
additionalIdentifier = ((CommentDeletedEvent) event).getIdentifier();
} else if (event instanceof CommentUpdatedEvent) {
eventType = ActivityEventType.UPDATE_COMMENT;
displayTitle = currentDoc.getRenderedTitle(Syntax.XHTML_1_0, context);
additionalIdentifier = ((CommentUpdatedEvent) event).getIdentifier();
} else if (event instanceof AttachmentAddedEvent) {
eventType = ActivityEventType.ADD_ATTACHMENT;
displayTitle = currentDoc.getRenderedTitle(Syntax.XHTML_1_0, context);
additionalIdentifier = ((AttachmentAddedEvent) event).getName();
} else if (event instanceof AttachmentDeletedEvent) {
eventType = ActivityEventType.DELETE_ATTACHMENT;
displayTitle = currentDoc.getRenderedTitle(Syntax.XHTML_1_0, context);
additionalIdentifier = ((AttachmentDeletedEvent) event).getName();
} else if (event instanceof AttachmentUpdatedEvent) {
eventType = ActivityEventType.UPDATE_ATTACHMENT;
displayTitle = currentDoc.getRenderedTitle(Syntax.XHTML_1_0, context);
additionalIdentifier = ((AttachmentUpdatedEvent) event).getName();
} else if (event instanceof AnnotationAddedEvent) {
eventType = ActivityEventType.ADD_ANNOTATION;
displayTitle = currentDoc.getRenderedTitle(Syntax.XHTML_1_0, context);
additionalIdentifier = ((AnnotationAddedEvent) event).getIdentifier();
} else if (event instanceof AnnotationDeletedEvent) {
eventType = ActivityEventType.DELETE_ANNOTATION;
displayTitle = currentDoc.getRenderedTitle(Syntax.XHTML_1_0, context);
additionalIdentifier = ((AnnotationDeletedEvent) event).getIdentifier();
} else { // update annotation
eventType = ActivityEventType.UPDATE_ANNOTATION;
displayTitle = currentDoc.getRenderedTitle(Syntax.XHTML_1_0, context);
additionalIdentifier = ((AnnotationUpdatedEvent) event).getIdentifier();
}
List<String> params = new ArrayList<String>();
params.add(displayTitle);
if (additionalIdentifier != null) {
params.add(additionalIdentifier);
}
try {
addDocumentActivityEvent(streamName, currentDoc, eventType, msgPrefix + eventType, params, context);
} catch (ActivityStreamException e) {
LOGGER.error("Exception while trying to add a document activity event, updated document: [" + wiki
+ ":" + currentDoc + "]");
}
}
}
@Override
public List<ActivityEvent> getRelatedEvents(ActivityEvent event, XWikiContext context)
throws ActivityStreamException
{
List<Object> params = new ArrayList<Object>();
params.add(event.getRequestId());
return this.searchEvents("", "act.requestId= ? ", false, false, 0, 0, params, context);
}
@Override
public List<Object[]> searchUniquePages(String optionalWhereClause, int maxItems, int startAt, XWikiContext context)
throws ActivityStreamException
{
return searchUniquePages(optionalWhereClause, null, maxItems, startAt, context);
}
@Override
public List<Object[]> searchUniquePages(String optionalWhereClause, List<Object> parametersValues, int maxItems,
int startAt, XWikiContext context) throws ActivityStreamException
{
StringBuffer searchHql = new StringBuffer();
List<Object[]> results;
searchHql.append("select act.page, max(act.date) from ActivityEventImpl as act");
addHiddenEventsFilter(searchHql);
addOptionalEventsFilter(searchHql, optionalWhereClause);
searchHql.append(" group by act.page order by 2 desc");
String originalDatabase = context.getWikiId();
try {
context.setWikiId(context.getMainXWiki());
results =
context.getWiki().getStore().search(searchHql.toString(), maxItems, startAt, parametersValues, context);
} catch (XWikiException e) {
throw new ActivityStreamException(e);
} finally {
context.setWikiId(originalDatabase);
}
return results;
}
@Override
public List<Object[]> searchDailyPages(String optionalWhereClause, int maxItems, int startAt, XWikiContext context)
throws ActivityStreamException
{
return searchDailyPages(optionalWhereClause, null, maxItems, startAt, context);
}
@Override
public List<Object[]> searchDailyPages(String optionalWhereClause, List<Object> parametersValues, int maxItems,
int startAt, XWikiContext context) throws ActivityStreamException
{
StringBuffer searchHql = new StringBuffer();
List<Object[]> results = new ArrayList<Object[]>();
searchHql.append("select year(act.date), month(act.date), day(act.date), act.page, max(act.date), act.wiki "
+ "from ActivityEventImpl as act");
addHiddenEventsFilter(searchHql);
addOptionalEventsFilter(searchHql, optionalWhereClause);
searchHql.append(" group by year(act.date), month(act.date), day(act.date), act.page, act.wiki "
+ "order by 5 desc");
String originalDatabase = context.getWikiId();
try {
context.setWikiId(context.getMainXWiki());
List<Object[]> rawResults =
context.getWiki().getStore().search(searchHql.toString(), maxItems, startAt, parametersValues, context);
for (Object[] rawResult : rawResults) {
results.add(new Object[] { rawResult[3], rawResult[4], rawResult[5] });
}
} catch (XWikiException e) {
throw new ActivityStreamException(e);
} finally {
context.setWikiId(originalDatabase);
}
return results;
}
/**
* @param documentReference to be serialized
* @return the default (absolute) string serialized document reference
*/
private static String getSerializedReference(DocumentReference documentReference)
{
EntityReferenceSerializer<String> serializer = Utils.getComponent(EntityReferenceSerializer.TYPE_STRING);
String stringSerialization = serializer.serialize(documentReference);
return stringSerialization;
}
}
|
package org.xwiki.security.authorization.internal;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import javax.inject.Inject;
import javax.inject.Named;
import javax.inject.Singleton;
import org.slf4j.Logger;
import org.xwiki.component.annotation.Component;
import org.xwiki.context.Execution;
import org.xwiki.model.EntityType;
import org.xwiki.model.reference.DocumentReference;
import org.xwiki.model.reference.DocumentReferenceResolver;
import org.xwiki.model.reference.EntityReference;
import org.xwiki.model.reference.SpaceReference;
import org.xwiki.model.reference.WikiReference;
import org.xwiki.security.SecurityReference;
import org.xwiki.security.authorization.AuthorizationException;
import org.xwiki.security.authorization.EntityTypeNotSupportedException;
import org.xwiki.security.authorization.Right;
import org.xwiki.security.authorization.RightSet;
import org.xwiki.security.authorization.RuleState;
import org.xwiki.security.authorization.SecurityEntryReader;
import org.xwiki.security.authorization.SecurityRule;
import org.xwiki.security.authorization.SecurityRuleEntry;
import org.xwiki.security.internal.XWikiConstants;
import com.xpn.xwiki.XWikiContext;
import com.xpn.xwiki.XWikiException;
import com.xpn.xwiki.doc.XWikiDocument;
import com.xpn.xwiki.objects.BaseObject;
/**
* The default implementation of the security rules reader, which reads rules from documents in a wiki.
*
* @version $Id$
* @since 4.0M2
*/
@Component
@Singleton
public class DefaultSecurityEntryReader implements SecurityEntryReader
{
/** A security rules to deny everyone the edit right by allowing edit to no one. */
private static final SecurityRule DENY_EDIT = new AllowEditToNoOneRule();
/** Right set allowed for wiki owner. */
private static final Set<Right> OWNER_RIGHTS = new RightSet(Right.ADMIN);
/** Right set allowed for document creators. */
private static final Set<Right> CREATOR_RIGHTS = new RightSet(Right.CREATOR);
/** Logger. **/
@Inject
private Logger logger;
/** Resolver for user and group names. */
@Inject
@Named("user")
private DocumentReferenceResolver<String> resolver;
/** Execution object. */
@Inject
private Execution execution;
/**
* @return the current {@code XWikiContext}
*/
private XWikiContext getXWikiContext() {
return ((XWikiContext) execution.getContext().getProperty(XWikiContext.EXECUTIONCONTEXT_KEY));
}
/**
* Internal implementation of the SecurityRuleEntry.
*/
private final class InternalSecurityRuleEntry extends AbstractSecurityRuleEntry
{
/** Reference of the related entity. */
private final SecurityReference reference;
/** The list of objects. */
private final Collection<SecurityRule> rules;
/**
* @param reference reference of the related entity
* @param rules collection of security rules applied on the entity.
*/
private InternalSecurityRuleEntry(SecurityReference reference, Collection<SecurityRule> rules)
{
this.reference = reference;
this.rules = Collections.unmodifiableCollection(rules);
}
/**
* @return all rules available for this entity
*/
@Override
public SecurityReference getReference()
{
return reference;
}
/**
* @return all rules available for this entity
*/
@Override
public Collection<SecurityRule> getRules()
{
return rules;
}
}
/**
* Load the rules from wiki documents.
*
* @param entity Any entity reference that is either a WIKI or a SPACE, or an entity containing a DOCUMENT entity.
* @return the access rules that could be loaded into the cache.
* @throws org.xwiki.security.authorization.AuthorizationException if an issue arise while reading these rules
* from the wiki.
*/
public SecurityRuleEntry read(SecurityReference entity) throws AuthorizationException
{
if (entity == null) {
return null;
}
if (entity.getOriginalReference() == null) {
// Public users (not logged in) are not stored anywhere and does not have their own rules
// More generally, any reference without a valid original reference should not be considered.
return new InternalSecurityRuleEntry(entity, Collections.<SecurityRule>emptyList());
}
DocumentReference documentReference;
DocumentReference classReference;
WikiReference wikiReference;
switch (entity.getType()) {
case WIKI:
wikiReference = new WikiReference(entity);
SpaceReference wikiSpace = new SpaceReference(XWikiConstants.XWIKI_SPACE, wikiReference);
documentReference = new DocumentReference(XWikiConstants.WIKI_DOC, wikiSpace);
classReference = new DocumentReference(XWikiConstants.GLOBAL_CLASSNAME, wikiSpace);
break;
case SPACE:
wikiReference = new WikiReference(entity.extractReference(EntityType.WIKI));
documentReference = new DocumentReference(XWikiConstants.SPACE_DOC, new SpaceReference(entity));
classReference = new DocumentReference(XWikiConstants.GLOBAL_CLASSNAME,
new SpaceReference(XWikiConstants.XWIKI_SPACE, wikiReference));
break;
default:
EntityReference relatedDocument = entity.extractReference(EntityType.DOCUMENT);
if (relatedDocument != null) {
wikiReference = new WikiReference(relatedDocument.extractReference(EntityType.WIKI));
documentReference = new DocumentReference(relatedDocument);
classReference = new DocumentReference(XWikiConstants.LOCAL_CLASSNAME,
new SpaceReference(XWikiConstants.XWIKI_SPACE, wikiReference));
} else {
this.logger.debug("Rights on entities of type {} is not supported by this reader!",
entity.getType());
throw new EntityTypeNotSupportedException(entity.getType(), this);
}
}
return new InternalSecurityRuleEntry(entity,
getSecurityRules(documentReference, classReference, wikiReference));
}
/**
* Get the document.
* @param documentReference reference to the document to be loaded.
* @return a list of matching base objects, or null if none where found.
* @throws AuthorizationException if an unexpected error occurs during retrieval.
*/
private XWikiDocument getDocument(DocumentReference documentReference) throws AuthorizationException
{
XWikiContext context = getXWikiContext();
try {
XWikiDocument doc = context.getWiki().getDocument(documentReference, context);
if (doc == null || doc.isNew()) {
return null;
}
return doc;
} catch (XWikiException e) {
throw new AuthorizationException(documentReference,
"Could not retrieve the document to check security access", e);
}
}
/**
* @param wikiReference the wiki to look for owner
* @return a reference to the owner of the wiki
* @throws AuthorizationException if the owner could not be retrieved.
*/
private DocumentReference getWikiOwner(WikiReference wikiReference) throws AuthorizationException
{
XWikiContext context = getXWikiContext();
String wikiOwner;
try {
wikiOwner = context.getWiki().getWikiOwner(wikiReference.getName(), context);
} catch (XWikiException e) {
throw new AuthorizationException(wikiReference,
"Could not retrieve the owner of this wiki", e);
}
if (wikiOwner == null) {
return null;
}
return resolver.resolve(wikiOwner, wikiReference);
}
/**
* Read right objects from an XWikiDocument and return them as XWikiSecurityRule.
* @param documentReference reference to document to read
* @param classReference reference to the right class to read
* @param wikiReference reference to the wiki of the document
* @return a collection of rules read from the document
* @throws AuthorizationException on error reading object from the document
*/
private Collection<SecurityRule> getSecurityRules(DocumentReference documentReference,
DocumentReference classReference, WikiReference wikiReference) throws AuthorizationException
{
boolean isGlobalRightsReference = isGlobalRightsReference(documentReference);
boolean isGlobalRightRequested = classReference.getName().equals(XWikiConstants.GLOBAL_CLASSNAME);
XWikiDocument doc = getDocument(documentReference);
// Get implied rules (creator, owner, global rights restriction)
List<SecurityRule> securityRules =
getImpliedRules(documentReference, doc, isGlobalRightsReference, isGlobalRightRequested);
if (doc == null) {
return securityRules;
}
// Convert existing rules on the entity
List<BaseObject> baseObjects = doc.getXObjects(classReference);
if (baseObjects != null) {
for (BaseObject obj : baseObjects) {
if (obj != null) {
SecurityRule rule;
try {
// Thanks to the resolver, the users and groups listed by the rights object, inherit
// the wiki from the document, unless explicitly given.
rule = XWikiSecurityRule.createNewRule(obj, resolver, wikiReference,
isGlobalRightsReference && !isGlobalRightRequested);
} catch (IllegalArgumentException e) {
// Do not add badly formed security rules.
continue;
}
securityRules.add(rule);
}
}
}
return securityRules;
}
/**
* Get rules implied by wiki owners, document creators, and global rights documents.
* @param documentReference reference to the document requested.
* @param document the document requested.
* @param isGlobalRightsReference true when the document is a document which host global rights.
* @param isGlobalRightRequested true when the request concern global rights.
* @return a list of implied security rules, or an empty list of there none.
* @throws AuthorizationException if anything goes wrong.
*/
private List<SecurityRule> getImpliedRules(DocumentReference documentReference, XWikiDocument document,
boolean isGlobalRightsReference, boolean isGlobalRightRequested) throws AuthorizationException
{
List<SecurityRule> rules = new ArrayList<SecurityRule>();
if (isGlobalRightsReference) {
if (isGlobalRightRequested) {
DocumentReference owner = getWikiOwner(documentReference.getWikiReference());
if (owner != null) {
// Allow global rights to wiki owner
rules.add(new XWikiSecurityRule(OWNER_RIGHTS, RuleState.ALLOW, Collections.singleton(owner), null));
}
} else {
// Deny local edit right on documents hosting global rights for anyone but admins.
rules.add(DENY_EDIT);
}
}
if (!isGlobalRightRequested && document != null) {
DocumentReference creator = document.getCreatorReference();
// Allow local rights to document creator (unless it is a public creator)
if (creator != null && !XWikiConstants.GUEST_USER.equals(creator.getName())) {
rules.add(new XWikiSecurityRule(CREATOR_RIGHTS, RuleState.ALLOW, Collections.singleton(creator), null));
}
}
return rules;
}
/**
* Check if the entity reference refers to a document that may contain global rights objects. In other words
* '*:XWiki.XWikiPreferences' or '*:*.WebPreferences'.
*
* @param documentReference the document reference to check.
* @return true if the document is scanned for global rights objects during authorization.
*/
private boolean isGlobalRightsReference(DocumentReference documentReference) {
return (XWikiConstants.SPACE_DOC.equals(documentReference.getName())
|| (XWikiConstants.WIKI_DOC.equals(documentReference.getName())
&& XWikiConstants.XWIKI_SPACE.equals(documentReference.getParent().getName())));
}
}
|
package com.exedio.cope;
import java.io.File;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import com.exedio.dsmf.SQLRuntimeException;
public final class Properties extends com.exedio.cope.util.Properties
{
private static final String DIALECT_FROM_URL = "from url";
private final StringField dialectCode = new StringField("dialect", DIALECT_FROM_URL);
private final StringField databaseUrl = new StringField("database.url");
private final StringField databaseUser = new StringField("database.user");
private final StringField databasePassword = new StringField("database.password", true);
private final BooleanField databaseLog = new BooleanField("database.log", false);
private final BooleanField databaseLogStatementInfo = new BooleanField("database.logStatementInfo", false);
private final BooleanField databaseDontSupportPreparedStatements = new BooleanField("database.dontSupport.preparedStatements", false);
private final BooleanField databaseDontSupportEmptyStrings = new BooleanField("database.dontSupport.emptyStrings", false);
private final BooleanField databaseDontSupportNativeDate = new BooleanField("database.dontSupport.nativeDate", false);
private final BooleanField databaseDontSupportLimit = new BooleanField("database.dontSupport.limit", false);
private final MapField databaseForcedNames = new MapField("database.forcename");
private final MapField databaseTableOptions = new MapField("database.tableOption");
private final MapField databaseCustomProperties;
static final String PKSOURCE_BUTTERFLY = "pksource.butterfly";
private final BooleanField pksourceButterfly = new BooleanField(PKSOURCE_BUTTERFLY, false);
private final BooleanField fulltextIndex = new BooleanField("fulltextIndex", false);
private final IntField connectionPoolIdleInitial = new IntField("connectionPool.idleInitial", 0, 0);
private final IntField connectionPoolIdleLimit = new IntField("connectionPool.idleLimit", 10, 0);
private final BooleanField transactionLog = new BooleanField("transaction.log", false);
private final IntField cacheLimit = new IntField("cache.limit", 10000, 0);
private final IntField cacheQueryLimit = new IntField("cache.queryLimit", 10000, 0);
public static final String CACHE_QUERY_HISTOGRAM = "cache.queryHistogram";
private final BooleanField cacheQueryHistogram = new BooleanField(CACHE_QUERY_HISTOGRAM, false);
final IntField dataFieldBufferSizeDefault = new IntField("dataField.bufferSizeDefault", 20*1024, 1);
final IntField dataFieldBufferSizeLimit = new IntField("dataField.bufferSizeLimit", 1024*1024, 1);
private final FileField datadirPath = new FileField("datadir.path");
private final StringField mediaRooturl = new StringField("media.rooturl", "media/");
private final IntField mediaOffsetExpires = new IntField("media.offsetExpires", 1000 * 5, 0);
private final Constructor<? extends Dialect> dialect;
public Properties()
{
this(getDefaultPropertyFile());
}
public static final File getDefaultPropertyFile()
{
String result = System.getProperty("com.exedio.cope.properties");
if(result==null)
result = "cope.properties";
return new File(result);
}
public Properties(final File file)
{
this(loadProperties(file), file.getAbsolutePath());
}
public Properties(final java.util.Properties properties, final String source)
{
super(properties, source);
final String dialectCodeRaw = this.dialectCode.getStringValue();
final String dialectCode;
if(DIALECT_FROM_URL.equals(dialectCodeRaw))
{
final String url = databaseUrl.getStringValue();
final String prefix = "jdbc:";
if(!url.startsWith(prefix))
throw new RuntimeException("cannot parse " + databaseUrl.getKey() + '=' + url + ", missing prefix '" + prefix + '\'');
final int pos = url.indexOf(':', prefix.length());
if(pos<0)
throw new RuntimeException("cannot parse " + databaseUrl.getKey() + '=' + url + ", missing second colon");
dialectCode = url.substring(prefix.length(), pos);
}
else
dialectCode = dialectCodeRaw;
dialect = getDialectConstructor(dialectCode, source);
databaseCustomProperties = new MapField("database." + dialectCode);
if(connectionPoolIdleInitial.getIntValue()>connectionPoolIdleLimit.getIntValue())
throw new RuntimeException("value for " + connectionPoolIdleInitial.getKey() + " must not be greater than " + connectionPoolIdleLimit.getKey());
if(datadirPath.getFileValue()!=null)
{
final File value = datadirPath.getFileValue();
if(!value.exists())
throw new RuntimeException(datadirPath.getKey() + ' ' + value.getAbsolutePath() + " does not exist.");
if(!value.isDirectory())
throw new RuntimeException(datadirPath.getKey() + ' ' + value.getAbsolutePath() + " is not a directory.");
if(!value.canRead())
throw new RuntimeException(datadirPath.getKey() + ' ' + value.getAbsolutePath() + " is not readable.");
if(!value.canWrite())
throw new RuntimeException(datadirPath.getKey() + ' ' + value.getAbsolutePath() + " is not writable.");
}
ensureValidity(new String[]{"x-build"});
}
private static final Constructor<? extends Dialect> getDialectConstructor(final String dialectCode, final String source)
{
if(dialectCode.length()<=2)
throw new RuntimeException("dialect from " + source + " must have at least two characters, but was " + dialectCode);
final String dialectName =
"com.exedio.cope." +
Character.toUpperCase(dialectCode.charAt(0)) +
dialectCode.substring(1) +
"Dialect";
final Class<?> dialectClassRaw;
try
{
dialectClassRaw = Class.forName(dialectName);
}
catch(ClassNotFoundException e)
{
throw new RuntimeException("class " + dialectName + " from " + source + " not found.");
}
if(!Dialect.class.isAssignableFrom(dialectClassRaw))
{
throw new RuntimeException(dialectClassRaw.toString() + " from " + source + " not a subclass of " + Dialect.class.getName() + '.');
}
final Class<? extends Dialect> dialectClass = dialectClassRaw.asSubclass(Dialect.class);
try
{
return dialectClass.getDeclaredConstructor(new Class[]{DialectParameters.class});
}
catch(NoSuchMethodException e)
{
throw new RuntimeException("class " + dialectName + " from " + source + " does not have the required constructor.");
}
}
private final RuntimeException newNotSetException(final String key)
{
return new RuntimeException("property " + key + " in " + getSource() + " not set.");
}
Database createDatabase(final boolean migrationSupported)
{
final DialectParameters parameters;
Connection probeConnection = null;
try
{
probeConnection = DriverManager.getConnection(getDatabaseUrl(), getDatabaseUser(), getDatabasePassword());
parameters = new DialectParameters(this, probeConnection);
}
catch(SQLException e)
{
throw new SQLRuntimeException(e, "create");
}
finally
{
if(probeConnection!=null)
{
try
{
probeConnection.close();
probeConnection = null;
}
catch(SQLException e)
{
throw new SQLRuntimeException(e, "close");
}
}
}
final Dialect dialect;
try
{
dialect = this.dialect.newInstance(parameters);
}
catch(InstantiationException e)
{
throw new RuntimeException(e);
}
catch(IllegalAccessException e)
{
throw new RuntimeException(e);
}
catch(InvocationTargetException e)
{
throw new RuntimeException(e);
}
return new Database(dialect.driver, parameters, dialect, migrationSupported);
}
public String getDialect()
{
return dialect.getDeclaringClass().getName();
}
/**
* @deprecated Has been renamed to {@link #getDialect()}.
*/
@Deprecated
public String getDatabase()
{
return getDialect();
}
public String getDatabaseUrl()
{
return databaseUrl.getStringValue();
}
public String getDatabaseUser()
{
return databaseUser.getStringValue();
}
public String getDatabasePassword()
{
return databasePassword.getStringValue();
}
public boolean getDatabaseLog()
{
return databaseLog.getBooleanValue();
}
public boolean getDatabaseLogStatementInfo()
{
return databaseLogStatementInfo.getBooleanValue();
}
public boolean getDatabaseDontSupportPreparedStatements()
{
return databaseDontSupportPreparedStatements.getBooleanValue();
}
public boolean getDatabaseDontSupportEmptyStrings()
{
return databaseDontSupportEmptyStrings.getBooleanValue();
}
public boolean getDatabaseDontSupportLimit()
{
return databaseDontSupportLimit.getBooleanValue();
}
public boolean getDatabaseDontSupportNativeDate()
{
return databaseDontSupportNativeDate.getBooleanValue();
}
java.util.Properties getDatabaseForcedNames()
{
return databaseForcedNames.getMapValue();
}
java.util.Properties getDatabaseTableOptions()
{
return databaseTableOptions.getMapValue();
}
String getDatabaseCustomProperty(final String key)
{
return databaseCustomProperties.getValue(key);
}
public boolean getPkSourceButterfly()
{
return pksourceButterfly.getBooleanValue();
}
public boolean getFulltextIndex()
{
return fulltextIndex.getBooleanValue();
}
public int getConnectionPoolIdleInitial()
{
return connectionPoolIdleInitial.getIntValue();
}
public int getConnectionPoolIdleLimit()
{
return connectionPoolIdleLimit.getIntValue();
}
public boolean getTransactionLog()
{
return transactionLog.getBooleanValue();
}
public int getCacheLimit()
{
return cacheLimit.getIntValue();
}
public int getCacheQueryLimit()
{
return cacheQueryLimit.getIntValue();
}
public boolean getCacheQueryHistogram()
{
return cacheQueryHistogram.getBooleanValue();
}
public boolean hasDatadirPath()
{
return datadirPath.getFileValue()!=null;
}
public File getDatadirPath()
{
final File result = datadirPath.getFileValue();
if(result==null)
throw newNotSetException(datadirPath.getKey());
return result;
}
public String getMediaRootUrl()
{
return mediaRooturl.getStringValue();
}
/**
* Returns the offset, the Expires http header of media
* is set into the future.
* Together with a http reverse proxy this ensures,
* that for that time no request for that data will reach the servlet.
* This may reduce the load on the server.
* If zero, no Expires header is sent.
*
* TODO: make this configurable per media as well.
*/
public int getMediaOffsetExpires()
{
return mediaOffsetExpires.getIntValue();
}
}
|
package authoringEnvironment.objects;
import imageselectorTEMP.util.ScaleImage;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import javafx.animation.FadeTransition;
import javafx.animation.ScaleTransition;
import javafx.animation.SequentialTransition;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.geometry.Pos;
import javafx.scene.Node;
import javafx.scene.control.ComboBox;
import javafx.scene.control.TextField;
import javafx.scene.control.Tooltip;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.HBox;
import javafx.scene.layout.StackPane;
import javafx.scene.layout.VBox;
import javafx.scene.paint.Color;
import javafx.scene.text.Text;
import javafx.scene.text.TextAlignment;
import javafx.stage.FileChooser;
import javafx.util.Duration;
import authoringEnvironment.Controller;
import authoringEnvironment.setting.SpriteSetting;
/**
* Creates the visual selector for adding a unit/wave and the time delay. Stores
* the information for the WaveEditor
*
* @author Megan Gutter
*
*/
public class FlowView extends HBox {
private TextField delayTextField;
private FileChooser fileChooser;
private Controller myController;
private int myHeight;
private final static String ENEMIES = "Enemies";
private final static String TIMES = "Times";
private static final int PADDING = 10;
private List<String> partFileNames;
private List<Double> delays;
private VBox selector;
/**
* Creates the visual and input elements for the "timeline" in the
* WaveEditor. Contains buttons to add a unit or wave and the delay time
* between units/waves in a wave.
*
* @param height
* Height of the hbox display
*/
public FlowView(int height, Controller c) {
super(PADDING);
this.setAlignment(Pos.CENTER);
c = myController;
myHeight = height;
fileChooser = new FileChooser();
partFileNames = new ArrayList<String>();
delays = new ArrayList<Double>();
selector = new VBox(0.5*PADDING);
selector.setAlignment(Pos.CENTER);
ArrayList<String> options = new ArrayList<>();
options.add("Unit");
options.add("Wave");
ObservableList<String> optionsList = FXCollections.observableArrayList(options);
final ComboBox<String> partSelectorBox = new ComboBox<>(optionsList);
Tooltip tooltip = new Tooltip("Select something to add!");
tooltip.setTextAlignment(TextAlignment.CENTER);
Tooltip.install(partSelectorBox, tooltip);
//TODO: use lambda for selectUnit/selectWave method?
partSelectorBox.setPromptText("...");
partSelectorBox.valueProperty().addListener((obs, oldValue, newValue) -> {
if(newValue.equals("Unit"))
selectUnit();
else if(newValue.equals("Wave"))
selectWave();
});
selector.getChildren().add(partSelectorBox);
this.getChildren().add(selector);
VBox arrow = createArrowAndDelayVisuals();
this.getChildren().add(arrow);
this.setPrefHeight(myHeight);
}
private void showArrowAnimation(ImageView arrow, TextField field){
ScaleTransition showArrow = new ScaleTransition(Duration.millis(500), arrow);
showArrow.setFromX(0.0);
showArrow.setToX(1.0);
FadeTransition showField = new FadeTransition(Duration.millis(250), field);
showField.setFromValue(0.0);
showField.setToValue(1.0);
SequentialTransition animation = new SequentialTransition(showArrow, showField);
animation.play();
}
private VBox createArrowAndDelayVisuals() {
ImageView arrowImage = new ImageView(new Image("images/arrow_icon.png"));
ScaleImage.scaleByWidth(arrowImage, 120);
delayTextField = new TextField();
delayTextField.setPromptText("(sec)");
delayTextField.setAlignment(Pos.CENTER);
delayTextField.setMaxWidth(50);
VBox arrow = new VBox(0.5*PADDING);
arrow.getChildren().addAll(delayTextField, arrowImage);
arrow.setAlignment(Pos.CENTER);
showArrowAnimation(arrowImage, delayTextField);
return arrow;
}
private void selectUnit() {
SpriteSetting chooseUnit = new SpriteSetting(ENEMIES, ENEMIES);
chooseUnit.getChildren().remove(0);
chooseUnit.setTextColor(Color.BLACK);
insertElement(chooseUnit);
List<Double> unitDelay = new ArrayList<Double>();
List<String> fileNames = new ArrayList<String>();
try {
unitDelay.add(Double.parseDouble(delayTextField.getText()));
delays = unitDelay;
} catch (NumberFormatException e) {
}
}
private void selectWave() {
File file = fileChooser.showOpenDialog(null);
Text waveNameDisplay = new Text(file.getName());
insertElement(waveNameDisplay);
Map<String, Object> waveInfo = myController.loadPart(file
.getAbsolutePath());
try {
delays = (List<Double>) waveInfo.get(TIMES);
partFileNames = (List<String>) waveInfo.get(ENEMIES);
} catch (NullPointerException e) {
}
}
private void insertElement(Node node) {
if(selector.getChildren().size() > 1){
selector.getChildren().remove(1);
}
selector.getChildren().add(1, node);
}
/**
* Gets the file names of units/other waves in the wave.
*
* @return List<String> of file names
*/
public List<String> getFileNames() {
return partFileNames;
}
/**
* Gets the doubles corresponding to delay times between units in the wave.
*
* @return List<Double> of delay times between units in the wave
*/
public List<Double> getDelays() {
return delays;
}
}
|
import java.util.*;
public class EulerCycle {
public static List<Integer> eulerCycleUndirected(List<Integer>[] graph, int u) {
Set<Long> usedEdges = new HashSet<>();
int n = graph.length;
int[] curEdge = new int[n];
List<Integer> res = new ArrayList<>();
dfs(graph, curEdge, usedEdges, res, u);
Collections.reverse(res);
return res;
}
static void dfs(List<Integer>[] graph, int[] curEdge, Set<Long> usedEdges, List<Integer> res, int u) {
while (curEdge[u] < graph[u].size()) {
int v = graph[u].get(curEdge[u]++);
if (usedEdges.add(((long) Math.min(u, v) << 32) + Math.max(u, v)))
dfs(graph, curEdge, usedEdges, res, v);
}
res.add(u);
}
public static List<Integer> eulerCycleUndirected2(List<Integer>[] graph, int u) {
int[] curEdge = new int[graph.length];
List<Integer> res = new ArrayList<>();
Stack<Integer> stack = new Stack<>();
Set<Long> usedEdges = new HashSet<>();
stack.add(u);
while (!stack.isEmpty()) {
u = stack.pop();
while (curEdge[u] < graph[u].size()) {
int v = graph[u].get(curEdge[u]++);
if (usedEdges.add((((long) Math.min(u, v) << 32) + Math.max(u, v)))) {
stack.push(u);
u = v;
}
}
res.add(u);
}
Collections.reverse(res);
return res;
}
public static List<Integer> eulerCycleDirected(List<Integer>[] graph, int u) {
int n = graph.length;
int[] curEdge = new int[n];
List<Integer> res = new ArrayList<>();
dfs(graph, curEdge, res, u);
Collections.reverse(res);
return res;
}
static void dfs(List<Integer>[] graph, int[] curEdge, List<Integer> res, int u) {
while (curEdge[u] < graph[u].size()) {
dfs(graph, curEdge, res, graph[u].get(curEdge[u]++));
}
res.add(u);
}
public static List<Integer> eulerCycleDirected2(List<Integer>[] graph, int v) {
int[] curEdge = new int[graph.length];
List<Integer> res = new ArrayList<>();
Stack<Integer> stack = new Stack<>();
stack.add(v);
while (!stack.isEmpty()) {
v = stack.pop();
while (curEdge[v] < graph[v].size()) {
stack.push(v);
v = graph[v].get(curEdge[v]++);
}
res.add(v);
}
Collections.reverse(res);
return res;
}
// Usage example
public static void main(String[] args) {
int n = 5;
List<Integer>[] g = new List[n];
for (int i = 0; i < n; i++) {
g[i] = new ArrayList<>();
}
g[0].add(1);
g[1].add(2);
g[2].add(0);
g[1].add(3);
g[3].add(4);
g[4].add(1);
System.out.println(eulerCycleDirected(g, 0));
System.out.println(eulerCycleDirected2(g, 0));
n = 5;
g = new List[n];
for (int i = 0; i < n; i++) {
g[i] = new ArrayList<>();
}
g[0].add(1);
g[1].add(0);
g[1].add(2);
g[2].add(1);
g[2].add(3);
g[3].add(2);
g[0].add(3);
g[3].add(0);
g[0].add(4);
g[4].add(0);
g[1].add(4);
g[4].add(1);
g[0].add(2);
g[2].add(0);
g[1].add(3);
g[3].add(1);
System.out.println(eulerCycleUndirected(g, 2));
System.out.println(eulerCycleUndirected2(g, 2));
}
}
|
package org.gemoc.gemoc_modeling_workbench.ui.launcher;
import java.util.ArrayList;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IConfigurationElement;
import org.eclipse.core.runtime.Platform;
import org.eclipse.debug.core.ILaunchConfiguration;
import org.eclipse.debug.core.ILaunchConfigurationWorkingCopy;
import org.eclipse.debug.ui.AbstractLaunchConfigurationTab;
import org.eclipse.jface.dialogs.Dialog;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.ModifyEvent;
import org.eclipse.swt.events.ModifyListener;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.graphics.Font;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Combo;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Group;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.Text;
import org.eclipse.ui.PlatformUI;
import org.gemoc.gemoc_language_workbench.utils.ui.dialogs.SelectAnyIFileDialog;
import org.gemoc.gemoc_modeling_workbench.ui.Activator;
import fr.obeo.dsl.debug.ide.launch.AbstractDSLLaunchConfigurationDelegate;
import fr.obeo.dsl.debug.ide.sirius.ui.launch.AbstractDSLLaunchConfigurationDelegateUI;
public class GemocModelLauncherMainTab extends AbstractLaunchConfigurationTab {
protected Text modelLocationText;
protected Text siriusRepresentationLocationText;
protected Combo languageCombo;
protected Combo deciderCombo;
protected Text modelofexecutionglml_LocationText;
protected Text extendedccslLocationText;
public int GRID_DEFAULT_WIDTH = 200;
@Override
public void createControl(Composite parent) {
Composite area = new Composite(parent, SWT.NULL);
GridLayout gl = new GridLayout(1, false);
gl.marginHeight = 0;
area.setLayout(gl);
area.layout();
setControl(area);
Group modelArea = new Group(area, SWT.NULL);
modelArea.setText("Model:");
modelArea.setLayout(new FillLayout());
// Create the area for the filename to get
createModelLayout(modelArea, null);
Group languageArea = new Group(area, SWT.NULL);
languageArea.setText("Language:");
languageArea.setLayout(new FillLayout());
createLanguageLayout(languageArea, null);
Group prototypeArea = new Group(area, SWT.NULL);
prototypeArea
.setText("Gemoc Engine Prototype parameters (these info will probably be removed in future version):");
prototypeArea.setLayout(new FillLayout());
createPrototypeLayout(prototypeArea, null);
}
@Override
public void setDefaults(ILaunchConfigurationWorkingCopy configuration) {
// TODO Auto-generated method stub
}
@Override
public void initializeFrom(ILaunchConfiguration configuration) {
try {
this.modelLocationText.setText(configuration.getAttribute(
AbstractDSLLaunchConfigurationDelegate.RESOURCE_URI, ""));
this.languageCombo
.setText(configuration
.getAttribute(
GemocModelLauncherConfigurationConstants.LAUNCH_SELECTED_LANGUAGE,
""));
this.modelofexecutionglml_LocationText
.setText(configuration
.getAttribute(
GemocModelLauncherConfigurationConstants.LAUNCH_MODELOFEXECUTION_GLML_PATH,
""));
this.extendedccslLocationText
.setText(configuration
.getAttribute(
GemocModelLauncherConfigurationConstants.LAUNCH_EXTENDEDCCSL_FILE_PATH,
""));
} catch (CoreException e) {
Activator.error(e.getMessage(), e);
}
}
@Override
public void performApply(ILaunchConfigurationWorkingCopy configuration) {
configuration.setAttribute(
AbstractDSLLaunchConfigurationDelegate.RESOURCE_URI,
this.modelLocationText.getText());
configuration.setAttribute(
AbstractDSLLaunchConfigurationDelegateUI.SIRIUS_RESOURCE_URI,
this.siriusRepresentationLocationText.getText());
configuration
.setAttribute(
GemocModelLauncherConfigurationConstants.LAUNCH_SELECTED_LANGUAGE,
this.languageCombo.getText());
configuration
.setAttribute(
GemocModelLauncherConfigurationConstants.LAUNCH_MODELOFEXECUTION_GLML_PATH,
this.modelofexecutionglml_LocationText.getText());
configuration
.setAttribute(
GemocModelLauncherConfigurationConstants.LAUNCH_EXTENDEDCCSL_FILE_PATH,
this.extendedccslLocationText.getText());
}
@Override
public String getName() {
return "Main";
}
/**
* Basic modify listener that can be reused if there is no more precise need
*/
private ModifyListener fBasicModifyListener = new ModifyListener() {
@Override
public void modifyText(ModifyEvent arg0) {
updateLaunchConfigurationDialog();
}
};
/***
* Create the Field where user enters model to execute
*
* @param parent
* @param font
* @return
*/
public Composite createModelLayout(Composite parent, Font font) {
createTextLabelLayout(parent, "Model to execute");
GridData gd = new GridData(GridData.FILL_HORIZONTAL);
// gd.horizontalSpan = 1;
gd.widthHint = GRID_DEFAULT_WIDTH;
// Create the project selector button
// Model location text
modelLocationText = new Text(parent, SWT.SINGLE | SWT.BORDER);
modelLocationText.setLayoutData(gd);
modelLocationText.setFont(font);
modelLocationText.addModifyListener(fBasicModifyListener);
Button modelLocationButton = createPushButton(parent, "Browse", null);
modelLocationButton.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent evt) {
// handleModelLocationButtonSelected();
// TODO launch the appropriate selector
SelectAnyIFileDialog dialog = new SelectAnyIFileDialog(
PlatformUI.getWorkbench().getActiveWorkbenchWindow()
.getShell());
if (dialog.open() == Dialog.OK) {
String modelPath = ((IResource) dialog.getResult()[0])
.getFullPath().toPortableString();
modelLocationText.setText(modelPath);
updateLaunchConfigurationDialog();
}
}
});
//return parent;
createTextLabelLayout(parent, "Sirius representation");
//GridData gd = new GridData(GridData.FILL_HORIZONTAL);
// gd.horizontalSpan = 1;
//gd.widthHint = GRID_DEFAULT_WIDTH;
// Create the project selector button
// Animation view location text
siriusRepresentationLocationText = new Text(parent, SWT.SINGLE | SWT.BORDER);
siriusRepresentationLocationText.setLayoutData(gd);
siriusRepresentationLocationText.setFont(font);
siriusRepresentationLocationText.addModifyListener(fBasicModifyListener);
Button siriusRepresentationLocationButton = createPushButton(parent, "Browse", null);
siriusRepresentationLocationButton.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent evt) {
// handleModelLocationButtonSelected();
// TODO launch the appropriate selector
SelectAnyIFileDialog dialog = new SelectAnyIFileDialog(
PlatformUI.getWorkbench().getActiveWorkbenchWindow()
.getShell());
if (dialog.open() == Dialog.OK) {
String modelPath = ((IResource) dialog.getResult()[0])
.getFullPath().toPortableString();
siriusRepresentationLocationText.setText(modelPath);
updateLaunchConfigurationDialog();
}
}
});
return parent;
}
/***
* Create the Field where user enters the language used to execute
*
* @param parent
* @param font
* @return
*/
public Composite createLanguageLayout(Composite parent, Font font) {
createTextLabelLayout(parent, "xDSML");
GridData gd = new GridData(GridData.FILL_HORIZONTAL);
// gd.horizontalSpan = 1;
gd.widthHint = GRID_DEFAULT_WIDTH;
// Create the project selector button
languageCombo = new Combo(parent, SWT.NONE);
ArrayList<String> xdsmlNames = new ArrayList<String>();
IConfigurationElement[] confElements = Platform.getExtensionRegistry()
.getConfigurationElementsFor(
"org.gemoc.gemoc_language_workbench.xdsml");
for (int i = 0; i < confElements.length; i++) {
xdsmlNames.add(confElements[i].getAttribute("name"));
}
if (confElements.length == 0) {
xdsmlNames.add("<No xdml available>");
}
String[] empty = {};
languageCombo.setItems(xdsmlNames.toArray(empty));
languageCombo.addModifyListener(fBasicModifyListener);
/*
* languageCombo.addListener (SWT.DefaultSelection, new Listener () {
* public void handleEvent (Event e) { //System.out.println (e.widget +
* " - Default Selection");
*
* updateLaunchConfigurationDialog(); } });
*/
// button to deal with dynamic language creation and provisionning
Button projectLocationButton = createPushButton(parent,
"Dynamic Language Variants...", null);
projectLocationButton.setEnabled(false);
projectLocationButton.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent evt) {
// handleModelLocationButtonSelected();
// TODO launch the appropriate selector
MessageDialog.openWarning(PlatformUI.getWorkbench()
.getActiveWorkbenchWindow().getShell(),
"Dynamic Language Variants",
"Action not implemented yet");
updateLaunchConfigurationDialog();
}
});
deciderCombo = new Combo(parent, SWT.NONE);
String[] deciderChoice = {
GemocModelLauncherConfigurationConstants.DECIDER_SOLVER_PROPOSITION,
GemocModelLauncherConfigurationConstants.DECIDER_RANDOM };
deciderCombo.setItems(deciderChoice);
deciderCombo.select(0);
deciderCombo.addModifyListener(fBasicModifyListener);
return parent;
}
/***
* Create the Field where user enters model to execute
*
* @param parent
* @param font
* @return
*/
public Composite createPrototypeLayout(Composite parent, Font font) {
GridData gd = new GridData(GridData.FILL_HORIZONTAL);
// gd.horizontalSpan = 1;
gd.widthHint = GRID_DEFAULT_WIDTH;
createTextLabelLayout(parent, "used defined ModelOfExecution glml File");
modelofexecutionglml_LocationText = new Text(parent, SWT.SINGLE
| SWT.BORDER);
modelofexecutionglml_LocationText.setLayoutData(gd);
modelofexecutionglml_LocationText.setFont(font);
modelofexecutionglml_LocationText
.addModifyListener(fBasicModifyListener);
createTextLabelLayout(parent, "used defined extendedCCSL File");
// metamodel location text
extendedccslLocationText = new Text(parent, SWT.SINGLE | SWT.BORDER);
extendedccslLocationText.setLayoutData(gd);
extendedccslLocationText.setFont(font);
extendedccslLocationText.addModifyListener(fBasicModifyListener);
return parent;
}
/**
*
* @param parent
* the Parent of this argument tab
* @param labelString
* the label of the input text to create
* @param adapter
* the event that is triggered when clicking on OK button
*/
public void createTextLabelLayout(Composite parent, String labelString) {
GridLayout locationLayout = new GridLayout();
locationLayout.numColumns = 2;
locationLayout.marginHeight = 10;
locationLayout.marginWidth = 10;
parent.setLayout(locationLayout);
GridData gd = new GridData(GridData.FILL_HORIZONTAL);
parent.setLayoutData(gd);
// parent.setFont(null);
Label inputLabel = new Label(parent, SWT.NONE);
inputLabel.setText(labelString); //$NON-NLS-1$
gd = new GridData();
gd.horizontalSpan = 2;
inputLabel.setLayoutData(gd);
}
}
|
package edu.cuny.citytech.defaultrefactoring.core.refactorings;
import static org.eclipse.jdt.ui.JavaElementLabels.ALL_FULLY_QUALIFIED;
import static org.eclipse.jdt.ui.JavaElementLabels.getElementLabel;
import static org.eclipse.jdt.ui.JavaElementLabels.getTextLabel;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.function.BiFunction;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import org.eclipse.core.runtime.Assert;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.NullProgressMonitor;
import org.eclipse.core.runtime.OperationCanceledException;
import org.eclipse.core.runtime.Status;
import org.eclipse.core.runtime.SubProgressMonitor;
import org.eclipse.jdt.core.Flags;
import org.eclipse.jdt.core.IAnnotatable;
import org.eclipse.jdt.core.IAnnotation;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.IField;
import org.eclipse.jdt.core.IInitializer;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.core.IJavaProject;
import org.eclipse.jdt.core.ILocalVariable;
import org.eclipse.jdt.core.IMember;
import org.eclipse.jdt.core.IMemberValuePair;
import org.eclipse.jdt.core.IMethod;
import org.eclipse.jdt.core.IType;
import org.eclipse.jdt.core.ITypeHierarchy;
import org.eclipse.jdt.core.ITypeParameter;
import org.eclipse.jdt.core.ITypeRoot;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.core.dom.ASTMatcher;
import org.eclipse.jdt.core.dom.ASTNode;
import org.eclipse.jdt.core.dom.ASTVisitor;
import org.eclipse.jdt.core.dom.Assignment;
import org.eclipse.jdt.core.dom.Block;
import org.eclipse.jdt.core.dom.ClassInstanceCreation;
import org.eclipse.jdt.core.dom.CompilationUnit;
import org.eclipse.jdt.core.dom.ConstructorInvocation;
import org.eclipse.jdt.core.dom.CreationReference;
import org.eclipse.jdt.core.dom.Expression;
import org.eclipse.jdt.core.dom.FieldAccess;
import org.eclipse.jdt.core.dom.IBinding;
import org.eclipse.jdt.core.dom.IMethodBinding;
import org.eclipse.jdt.core.dom.ITypeBinding;
import org.eclipse.jdt.core.dom.IVariableBinding;
import org.eclipse.jdt.core.dom.MethodDeclaration;
import org.eclipse.jdt.core.dom.MethodInvocation;
import org.eclipse.jdt.core.dom.Modifier;
import org.eclipse.jdt.core.dom.Name;
import org.eclipse.jdt.core.dom.Modifier.ModifierKeyword;
import org.eclipse.jdt.core.dom.ReturnStatement;
import org.eclipse.jdt.core.dom.SimpleName;
import org.eclipse.jdt.core.dom.SingleVariableDeclaration;
import org.eclipse.jdt.core.dom.SuperConstructorInvocation;
import org.eclipse.jdt.core.dom.SuperFieldAccess;
import org.eclipse.jdt.core.dom.SuperMethodInvocation;
import org.eclipse.jdt.core.dom.SuperMethodReference;
import org.eclipse.jdt.core.dom.ThisExpression;
import org.eclipse.jdt.core.dom.Type;
import org.eclipse.jdt.core.dom.VariableDeclarationFragment;
import org.eclipse.jdt.core.dom.rewrite.ASTRewrite;
import org.eclipse.jdt.core.dom.rewrite.ITrackedNodePosition;
import org.eclipse.jdt.core.dom.rewrite.ListRewrite;
import org.eclipse.jdt.core.refactoring.CompilationUnitChange;
import org.eclipse.jdt.core.dom.rewrite.ImportRewrite.ImportRewriteContext;
import org.eclipse.jdt.core.search.IJavaSearchConstants;
import org.eclipse.jdt.core.search.IJavaSearchScope;
import org.eclipse.jdt.core.search.SearchEngine;
import org.eclipse.jdt.core.search.SearchMatch;
import org.eclipse.jdt.core.search.SearchParticipant;
import org.eclipse.jdt.core.search.SearchPattern;
import org.eclipse.jdt.core.search.SearchRequestor;
import org.eclipse.jdt.internal.corext.codemanipulation.CodeGenerationSettings;
import org.eclipse.jdt.internal.corext.codemanipulation.ContextSensitiveImportRewriteContext;
import org.eclipse.jdt.internal.corext.codemanipulation.StubUtility;
import org.eclipse.jdt.internal.corext.refactoring.RefactoringCoreMessages;
import org.eclipse.jdt.internal.corext.refactoring.base.JavaStatusContext;
import org.eclipse.jdt.internal.corext.refactoring.changes.DynamicValidationRefactoringChange;
import org.eclipse.jdt.internal.corext.refactoring.structure.ASTNodeSearchUtil;
import org.eclipse.jdt.internal.corext.refactoring.structure.CompilationUnitRewrite;
import org.eclipse.jdt.internal.corext.refactoring.structure.ImportRewriteUtil;
import org.eclipse.jdt.internal.corext.refactoring.structure.ReferenceFinderUtil;
import org.eclipse.jdt.internal.corext.refactoring.structure.TypeVariableMaplet;
import org.eclipse.jdt.internal.corext.refactoring.structure.HierarchyProcessor.TypeVariableMapper;
import org.eclipse.jdt.internal.corext.refactoring.util.RefactoringASTParser;
import org.eclipse.jdt.internal.corext.refactoring.util.TextEditBasedChangeManager;
import org.eclipse.jdt.internal.corext.util.JavaModelUtil;
import org.eclipse.jdt.internal.corext.util.JdtFlags;
import org.eclipse.jdt.internal.corext.util.Strings;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.ui.viewsupport.BasicElementLabels;
import org.eclipse.jdt.ui.JavaElementLabels;
import org.eclipse.jface.text.BadLocationException;
import org.eclipse.jface.text.Document;
import org.eclipse.jface.text.IDocument;
import org.eclipse.ltk.core.refactoring.Change;
import org.eclipse.ltk.core.refactoring.GroupCategory;
import org.eclipse.ltk.core.refactoring.GroupCategorySet;
import org.eclipse.ltk.core.refactoring.NullChange;
import org.eclipse.ltk.core.refactoring.RefactoringDescriptor;
import org.eclipse.ltk.core.refactoring.RefactoringStatus;
import org.eclipse.ltk.core.refactoring.RefactoringStatusContext;
import org.eclipse.ltk.core.refactoring.RefactoringStatusEntry;
import org.eclipse.ltk.core.refactoring.participants.CheckConditionsContext;
import org.eclipse.ltk.core.refactoring.participants.RefactoringParticipant;
import org.eclipse.ltk.core.refactoring.participants.RefactoringProcessor;
import org.eclipse.ltk.core.refactoring.participants.SharableParticipants;
import org.eclipse.text.edits.MalformedTreeException;
import org.eclipse.text.edits.TextEdit;
import org.osgi.framework.FrameworkUtil;
import com.google.common.collect.HashBasedTable;
import com.google.common.collect.Table;
import edu.cuny.citytech.defaultrefactoring.core.descriptors.MigrateSkeletalImplementationToInterfaceRefactoringDescriptor;
import edu.cuny.citytech.defaultrefactoring.core.messages.Messages;
import edu.cuny.citytech.defaultrefactoring.core.messages.PreconditionFailure;
import edu.cuny.citytech.defaultrefactoring.core.utils.RefactoringAvailabilityTester;
import edu.cuny.citytech.defaultrefactoring.core.utils.TimeCollector;
import edu.cuny.citytech.defaultrefactoring.core.utils.TypeVariableUtil;
import edu.cuny.citytech.defaultrefactoring.core.utils.Util;
/**
* The activator class controls the plug-in life cycle
*
* @author <a href="mailto:rkhatchadourian@citytech.cuny.edu">Raffi
* Khatchadourian</a>
*/
@SuppressWarnings({ "restriction" })
public class MigrateSkeletalImplementationToInterfaceRefactoringProcessor extends RefactoringProcessor {
private final class SourceMethodBodyAnalysisVisitor extends ASTVisitor {
private boolean methodContainsSuperReference;
private boolean methodContainsCallToProtectedObjectMethod;
private boolean methodContainsTypeIncompatibleThisReference;
private boolean methodContainsQualifiedThisExpression;
private Set<IMethod> calledProtectedObjectMethodSet = new HashSet<>();
private IMethod sourceMethod;
private Optional<IProgressMonitor> monitor;
public SourceMethodBodyAnalysisVisitor(IMethod sourceMethod, Optional<IProgressMonitor> monitor) {
super(false);
this.sourceMethod = sourceMethod;
this.monitor = monitor;
}
protected Set<IMethod> getCalledProtectedObjectMethodSet() {
return calledProtectedObjectMethodSet;
}
@Override
public boolean visit(SuperConstructorInvocation node) {
this.methodContainsSuperReference = true;
return super.visit(node);
}
protected boolean doesMethodContainsSuperReference() {
return methodContainsSuperReference;
}
protected boolean doesMethodContainsCallToProtectedObjectMethod() {
return methodContainsCallToProtectedObjectMethod;
}
protected boolean doesMethodContainsTypeIncompatibleThisReference() {
return methodContainsTypeIncompatibleThisReference;
}
protected boolean doesMethodContainQualifiedThisExpression() {
return methodContainsQualifiedThisExpression;
}
@Override
public boolean visit(SuperFieldAccess node) {
this.methodContainsSuperReference = true;
return super.visit(node);
}
@Override
public boolean visit(SuperMethodInvocation node) {
this.methodContainsSuperReference = true;
return super.visit(node);
}
@Override
public boolean visit(SuperMethodReference node) {
this.methodContainsSuperReference = true;
return super.visit(node);
}
@Override
public boolean visit(MethodInvocation node) {
// check for calls to particular java.lang.Object
// methods #144.
IMethodBinding methodBinding = node.resolveMethodBinding();
if (methodBinding.getDeclaringClass().getQualifiedName().equals("java.lang.Object")) {
IMethod calledObjectMethod = (IMethod) methodBinding.getJavaElement();
try {
if (Flags.isProtected(calledObjectMethod.getFlags())) {
this.methodContainsCallToProtectedObjectMethod = true;
this.calledProtectedObjectMethodSet.add(calledObjectMethod);
}
} catch (JavaModelException e) {
throw new RuntimeException(e);
}
}
return super.visit(node);
}
@Override
public boolean visit(ThisExpression node) {
// #153: Precondition missing for compile-time type of this
// TODO: #153 There is actually a lot more checks we should add
// here.
/*
* TODO: Actually need to examine every kind of expression where
* `this` may appear. #149. Really, type constraints can (or should)
* be used for this. Actually, similar to enum problem, especially
* with finding the parameter from where the `this` expression came.
* Assignment is only one kind of expression, we need to also look
* at comparison and switches.
*/
if (node.getQualifier() != null)
this.methodContainsQualifiedThisExpression = true;
ASTNode parent = node.getParent();
process(parent, node);
return super.visit(node);
}
private void process(ASTNode node, ThisExpression thisExpression) {
switch (node.getNodeType()) {
case ASTNode.METHOD_INVOCATION:
case ASTNode.CLASS_INSTANCE_CREATION:
case ASTNode.CONSTRUCTOR_INVOCATION:
// NOTE: super isn't allowed inside the source method body.
case ASTNode.ASSIGNMENT:
case ASTNode.RETURN_STATEMENT:
case ASTNode.VARIABLE_DECLARATION_FRAGMENT: {
// get the target method.
IMethod targetMethod = null;
try {
targetMethod = getTargetMethod(this.sourceMethod,
this.monitor.map(m -> new SubProgressMonitor(m, IProgressMonitor.UNKNOWN)));
} catch (JavaModelException e) {
throw new RuntimeException(e);
}
IType destinationInterface = targetMethod.getDeclaringType();
// get the destination interface.
ITypeBinding destinationInterfaceTypeBinding = null;
try {
destinationInterfaceTypeBinding = ASTNodeSearchUtil.getTypeDeclarationNode(destinationInterface,
getCompilationUnit(destinationInterface.getTypeRoot(), new SubProgressMonitor(
this.monitor.orElseGet(NullProgressMonitor::new), IProgressMonitor.UNKNOWN)))
.resolveBinding();
} catch (JavaModelException e) {
throw new RuntimeException(e);
}
if (node.getNodeType() == ASTNode.CONSTRUCTOR_INVOCATION) {
ConstructorInvocation constructorInvocation = (ConstructorInvocation) node;
List<?> arguments = constructorInvocation.arguments();
IMethodBinding methodBinding = constructorInvocation.resolveConstructorBinding();
processArguments(arguments, methodBinding, thisExpression, destinationInterfaceTypeBinding);
} else if (node.getNodeType() == ASTNode.CLASS_INSTANCE_CREATION) {
ClassInstanceCreation classInstanceCreation = (ClassInstanceCreation) node;
List<?> arguments = classInstanceCreation.arguments();
IMethodBinding methodBinding = classInstanceCreation.resolveConstructorBinding();
processArguments(arguments, methodBinding, thisExpression, destinationInterfaceTypeBinding);
} else if (node.getNodeType() == ASTNode.METHOD_INVOCATION) {
MethodInvocation methodInvocation = (MethodInvocation) node;
List<?> arguments = methodInvocation.arguments();
IMethodBinding methodBinding = methodInvocation.resolveMethodBinding();
processArguments(arguments, methodBinding, thisExpression, destinationInterfaceTypeBinding);
} else if (node.getNodeType() == ASTNode.ASSIGNMENT) {
Assignment assignment = (Assignment) node;
Expression leftHandSide = assignment.getLeftHandSide();
Expression rightHandSide = assignment.getRightHandSide();
processAssignment(assignment, thisExpression, destinationInterfaceTypeBinding, leftHandSide,
rightHandSide);
} else if (node.getNodeType() == ASTNode.VARIABLE_DECLARATION_FRAGMENT) {
VariableDeclarationFragment vdf = (VariableDeclarationFragment) node;
Expression initializer = vdf.getInitializer();
SimpleName name = vdf.getName();
processAssignment(vdf, thisExpression, destinationInterfaceTypeBinding, name, initializer);
} else if (node.getNodeType() == ASTNode.RETURN_STATEMENT) {
ReturnStatement returnStatement = (ReturnStatement) node;
// sanity check.
Expression expression = returnStatement.getExpression();
expression = (Expression) Util.stripParenthesizedExpressions(expression);
Assert.isTrue(expression == thisExpression, "The return expression should be this.");
MethodDeclaration targetMethodDeclaration = null;
try {
targetMethodDeclaration = ASTNodeSearchUtil
.getMethodDeclarationNode(targetMethod,
getCompilationUnit(targetMethod.getTypeRoot(),
new SubProgressMonitor(this.monitor.orElseGet(NullProgressMonitor::new),
IProgressMonitor.UNKNOWN)));
} catch (JavaModelException e) {
throw new RuntimeException(e);
}
ITypeBinding returnType = targetMethodDeclaration.resolveBinding().getReturnType();
// ensure that the destination type is assignment compatible
// with the return type.
if (!isAssignmentCompatible(destinationInterfaceTypeBinding, returnType))
this.methodContainsTypeIncompatibleThisReference = true;
} else
throw new IllegalStateException("Unexpected node type: " + node.getNodeType());
break;
}
case ASTNode.PARENTHESIZED_EXPRESSION: {
process(node.getParent(), thisExpression);
}
}
}
/**
* Process a list of arguments stemming from a method-like call.
*
* @param arguments
* The list of arguments to process.
* @param methodBinding
* The binding of the corresponding method call.
* @param thisExpression
* The this expression we are looking for.
* @param destinationInterfaceTypeBinding
* The binding of the destination interface.
*/
private void processArguments(List<?> arguments, IMethodBinding methodBinding, ThisExpression thisExpression,
ITypeBinding destinationInterfaceTypeBinding) {
// find where (or if) the this expression occurs in the
// method
// invocation arguments.
for (int i = 0; i < arguments.size(); i++) {
Object object = arguments.get(i);
// if we are at the argument where this appears.
if (object == thisExpression) {
// get the type binding from the corresponding
// parameter.
ITypeBinding parameterTypeBinding;
// varargs case.
// if we are at or past the last parameter and the method is
// vararg.
if (i >= methodBinding.getParameterTypes().length - 1 && methodBinding.isVarargs()) {
// assign the parameter type binding to be the scalar
// type of the last parameter type.
parameterTypeBinding = methodBinding
.getParameterTypes()[methodBinding.getParameterTypes().length - 1].getElementType();
Assert.isNotNull(parameterTypeBinding,
"The last parameter of a vararg method should be an array.");
} else
parameterTypeBinding = methodBinding.getParameterTypes()[i];
// the type of this will change to the destination
// interface. Let's check whether an expression of
// the destination type can be assigned to a
// variable of
// the parameter type.
// TODO: Does `isAssignmentCompatible()` also work
// with
// comparison?
if (!isAssignmentCompatible(destinationInterfaceTypeBinding, parameterTypeBinding)) {
this.methodContainsTypeIncompatibleThisReference = true;
break;
}
}
}
}
private void processAssignment(ASTNode node, ThisExpression thisExpression,
ITypeBinding destinationInterfaceTypeBinding, Expression leftHandSide, Expression rightHandSide) {
// if `this` appears on the LHS.
if (leftHandSide == thisExpression) {
// in this case, we need to check that the RHS can be
// assigned to a variable of the destination type.
if (!isAssignmentCompatible(rightHandSide.resolveTypeBinding(), destinationInterfaceTypeBinding))
this.methodContainsTypeIncompatibleThisReference = true;
} else if (rightHandSide == thisExpression) {
// otherwise, if `this` appears on the RHS. Then, we
// need to check that the LHS can receive a variable of
// the destination type.
if (!isAssignmentCompatible(destinationInterfaceTypeBinding, leftHandSide.resolveTypeBinding()))
this.methodContainsTypeIncompatibleThisReference = true;
} else {
throw new IllegalStateException(
"this: " + thisExpression + " must appear either on the LHS or RHS of the assignment: " + node);
}
}
}
private final class FieldAccessAnalysisSearchRequestor extends SearchRequestor {
private final Optional<IProgressMonitor> monitor;
private boolean accessesFieldsFromImplicitParameter;
private FieldAccessAnalysisSearchRequestor(Optional<IProgressMonitor> monitor) {
this.monitor = monitor;
}
@Override
public void acceptSearchMatch(SearchMatch match) throws CoreException {
if (match.isInsideDocComment())
return;
// get the AST node corresponding to the field
// access. It should be some kind of name
// (simple of qualified).
ASTNode node = ASTNodeSearchUtil.getAstNode(match, getCompilationUnit(
((IMember) match.getElement()).getTypeRoot(),
new SubProgressMonitor(monitor.orElseGet(NullProgressMonitor::new), IProgressMonitor.UNKNOWN)));
// examine the node's parent.
ASTNode parent = node.getParent();
switch (parent.getNodeType()) {
case ASTNode.FIELD_ACCESS: {
FieldAccess fieldAccess = (FieldAccess) parent;
// the expression is the LHS of the
// selection operator.
Expression expression = fieldAccess.getExpression();
if (expression == null || expression.getNodeType() == ASTNode.THIS_EXPRESSION)
// either there is nothing on the LHS
// or it's this, in which case we fail.
this.accessesFieldsFromImplicitParameter = true;
break;
}
case ASTNode.SUPER_FIELD_ACCESS: {
// super will also tell us that it's an
// instance field access of this.
this.accessesFieldsFromImplicitParameter = true;
break;
}
default: {
// it must be an unqualified field access,
// meaning that it's an instance field access of this.
this.accessesFieldsFromImplicitParameter = true;
}
}
}
public boolean hasAccessesToFieldsFromImplicitParameter() {
return accessesFieldsFromImplicitParameter;
}
}
private final class MethodReceiverAnalysisVisitor extends ASTVisitor {
private IMethod accessedMethod;
private boolean encounteredThisReceiver;
public boolean hasEncounteredThisReceiver() {
return encounteredThisReceiver;
}
private MethodReceiverAnalysisVisitor(IMethod accessedMethod) {
this.accessedMethod = accessedMethod;
}
@Override
public boolean visit(MethodInvocation methodInvocation) {
IMethodBinding methodBinding = methodInvocation.resolveMethodBinding();
IJavaElement javaElement = methodBinding.getJavaElement();
if (javaElement == null)
logWarning("Could not get Java element from binding: " + methodBinding + " while processing: "
+ methodInvocation);
else if (javaElement.equals(accessedMethod)) {
Expression expression = methodInvocation.getExpression();
expression = (Expression) Util.stripParenthesizedExpressions(expression);
// FIXME: It's not really that the expression is a `this`
// expression but that the type of the expression comes from a
// `this` expression. In other words, we may need to climb the
// AST.
if (expression == null || expression.getNodeType() == ASTNode.THIS_EXPRESSION) {
this.encounteredThisReceiver = true;
}
}
return super.visit(methodInvocation);
}
@Override
public boolean visit(SuperMethodInvocation node) {
if (node.resolveMethodBinding().getJavaElement().equals(accessedMethod))
this.encounteredThisReceiver = true;
return super.visit(node);
}
}
private Set<IMethod> sourceMethods = new LinkedHashSet<>();
private Set<IMethod> unmigratableMethods = new UnmigratableMethodSet(sourceMethods);
private static final String FUNCTIONAL_INTERFACE_ANNOTATION_NAME = "FunctionalInterface";
private Map<ICompilationUnit, CompilationUnitRewrite> compilationUnitToCompilationUnitRewriteMap = new HashMap<>();
private Map<ITypeRoot, CompilationUnit> typeRootToCompilationUnitMap = new HashMap<>();
@SuppressWarnings("unused")
private static final GroupCategorySet SET_MIGRATE_METHOD_IMPLEMENTATION_TO_INTERFACE = new GroupCategorySet(
new GroupCategory("edu.cuny.citytech.defaultrefactoring", //$NON-NLS-1$
Messages.CategoryName, Messages.CategoryDescription));
private static Map<IMethod, IMethod> methodToTargetMethodMap = new HashMap<>();
/** The code generation settings, or <code>null</code> */
private CodeGenerationSettings settings;
/** Does the refactoring use a working copy layer? */
private final boolean layer;
private static Table<IMethod, IType, IMethod> methodTargetInterfaceTargetMethodTable = HashBasedTable.create();
private SearchEngine searchEngine = new SearchEngine();
/**
* For excluding AST parse time.
*/
private TimeCollector excludedTimeCollector = new TimeCollector();
/**
* The minimum logging level, one of the constants in
* org.eclipse.core.runtime.IStatus.
*/
private static int loggingLevel = IStatus.WARNING;
/**
* Creates a new refactoring with the given methods to refactor.
*
* @param methods
* The methods to refactor.
* @throws JavaModelException
*/
public MigrateSkeletalImplementationToInterfaceRefactoringProcessor(final IMethod[] methods,
final CodeGenerationSettings settings, boolean layer, Optional<IProgressMonitor> monitor)
throws JavaModelException {
try {
this.settings = settings;
this.layer = layer;
Collections.addAll(this.getSourceMethods(), methods);
monitor.ifPresent(m -> m.beginTask("Finding target methods ...", methods.length));
for (IMethod method : methods) {
// this will populate the map if needed.
getTargetMethod(method, monitor);
monitor.ifPresent(m -> m.worked(1));
}
} finally {
monitor.ifPresent(IProgressMonitor::done);
}
}
public MigrateSkeletalImplementationToInterfaceRefactoringProcessor(final IMethod[] methods,
final CodeGenerationSettings settings, Optional<IProgressMonitor> monitor) throws JavaModelException {
this(methods, settings, false, monitor);
}
public MigrateSkeletalImplementationToInterfaceRefactoringProcessor(Optional<IProgressMonitor> monitor)
throws JavaModelException {
this(null, null, false, monitor);
}
public MigrateSkeletalImplementationToInterfaceRefactoringProcessor() throws JavaModelException {
this(null, null, false, Optional.empty());
}
/**
* {@inheritDoc}
*/
@Override
public Object[] getElements() {
return getMigratableMethods().toArray();
}
public Set<IMethod> getMigratableMethods() {
Set<IMethod> difference = new LinkedHashSet<>(this.getSourceMethods());
difference.removeAll(this.getUnmigratableMethods());
return difference;
}
@Override
public RefactoringStatus checkInitialConditions(IProgressMonitor pm)
throws CoreException, OperationCanceledException {
try {
this.clearCaches();
this.getExcludedTimeCollector().clear();
if (this.getSourceMethods().isEmpty())
return RefactoringStatus.createFatalErrorStatus(Messages.MethodsNotSpecified);
else {
RefactoringStatus status = new RefactoringStatus();
pm.beginTask(Messages.CheckingPreconditions, this.getSourceMethods().size());
for (IMethod sourceMethod : this.getSourceMethods()) {
status.merge(checkDeclaringType(sourceMethod, Optional.of(new SubProgressMonitor(pm, 0))));
status.merge(checkCandidateDestinationInterfaces(sourceMethod,
Optional.of(new SubProgressMonitor(pm, 0))));
pm.worked(1);
}
return status;
}
} catch (Exception e) {
JavaPlugin.log(e);
throw e;
} finally {
pm.done();
}
}
private RefactoringStatus checkDestinationInterfaceTargetMethods(IMethod sourceMethod) throws JavaModelException {
RefactoringStatus status = new RefactoringStatus();
logInfo("Checking destination interface target methods...");
// Ensure that target methods are not already default methods.
// For each method to move, add a warning if the associated target
// method is already default.
IMethod targetMethod = getTargetMethod(sourceMethod, Optional.empty());
if (targetMethod != null) {
int targetMethodFlags = targetMethod.getFlags();
if (Flags.isDefaultMethod(targetMethodFlags)) {
RefactoringStatusEntry entry = addError(status, sourceMethod,
PreconditionFailure.TargetMethodIsAlreadyDefault, targetMethod);
addUnmigratableMethod(sourceMethod, entry);
}
}
return status;
}
private RefactoringStatus checkDestinationInterfaces(Optional<IProgressMonitor> monitor) throws JavaModelException {
try {
RefactoringStatus status = new RefactoringStatus();
monitor.ifPresent(m -> m.beginTask("Checking destination interfaces ...", this.getSourceMethods().size()));
for (IMethod sourceMethod : this.getSourceMethods()) {
final Optional<IType> targetInterface = this.getDestinationInterface(sourceMethod);
// Can't be empty.
if (!targetInterface.isPresent()) {
addErrorAndMark(status, PreconditionFailure.NoDestinationInterface, sourceMethod);
return status;
}
// Must be a pure interface.
if (!isPureInterface(targetInterface.get())) {
RefactoringStatusEntry error = addError(status, sourceMethod,
PreconditionFailure.DestinationTypeMustBePureInterface, targetInterface.get());
addUnmigratableMethod(sourceMethod, error);
}
// Make sure it exists.
RefactoringStatus existence = checkExistence(targetInterface.get(),
PreconditionFailure.DestinationInterfaceDoesNotExist);
status.merge(existence);
if (!existence.isOK())
addUnmigratableMethod(sourceMethod, existence.getEntryWithHighestSeverity());
// Make sure we can write to it.
RefactoringStatus writabilitiy = checkWritabilitiy(targetInterface.get(),
PreconditionFailure.DestinationInterfaceNotWritable);
status.merge(writabilitiy);
if (!writabilitiy.isOK())
addUnmigratableMethod(sourceMethod, writabilitiy.getEntryWithHighestSeverity());
// Make sure it doesn't have compilation errors.
RefactoringStatus structure = checkStructure(targetInterface.get());
status.merge(structure);
if (!structure.isOK())
addUnmigratableMethod(sourceMethod, structure.getEntryWithHighestSeverity());
// #35: The target interface should not be a
// @FunctionalInterface.
if (isInterfaceFunctional(targetInterface.get())) {
RefactoringStatusEntry error = addError(status, sourceMethod,
PreconditionFailure.DestinationInterfaceIsFunctional, targetInterface.get());
addUnmigratableMethod(sourceMethod, error);
}
// Can't be strictfp if all the methods to be migrated aren't
// also strictfp
if (Flags.isStrictfp(targetInterface.get().getFlags())
&& !allMethodsToMoveInTypeAreStrictFP(sourceMethod.getDeclaringType())) {
RefactoringStatusEntry error = addError(status, sourceMethod,
PreconditionFailure.DestinationInterfaceIsStrictFP, targetInterface.get());
addUnmigratableMethod(sourceMethod, error);
}
status.merge(checkDestinationInterfaceTargetMethods(sourceMethod));
monitor.ifPresent(m -> m.worked(1));
}
return status;
} finally {
monitor.ifPresent(IProgressMonitor::done);
}
}
private IType[] getTypesReferencedInMovedMembers(IMethod sourceMethod, final Optional<IProgressMonitor> monitor)
throws JavaModelException {
// TODO: Cache this result.
final IType[] types = ReferenceFinderUtil.getTypesReferencedIn(new IJavaElement[] { sourceMethod },
monitor.orElseGet(NullProgressMonitor::new));
final List<IType> result = new ArrayList<IType>(types.length);
final List<IMember> members = Arrays.asList(new IMember[] { sourceMethod });
for (int index = 0; index < types.length; index++) {
if (!members.contains(types[index]) && !types[index].equals(sourceMethod.getDeclaringType()))
result.add(types[index]);
}
return result.toArray(new IType[result.size()]);
}
private boolean canBeAccessedFrom(IMethod sourceMethod, final IMember member, final IType target,
final ITypeHierarchy hierarchy) throws JavaModelException {
Assert.isTrue(!(member instanceof IInitializer));
if (member.exists()) {
if (target.equals(member.getDeclaringType()))
return true;
if (target.equals(member))
return true;
// NOTE: We are not creating stubs (for now).
/*
* if (member instanceof IMethod) { final IMethod method = (IMethod)
* member; final IMethod stub =
* target.getMethod(method.getElementName(),
* method.getParameterTypes()); if (stub.exists()) return true; }
*/
if (member.getDeclaringType() == null) {
if (!(member instanceof IType))
return false;
if (JdtFlags.isPublic(member))
return true;
if (!JdtFlags.isPackageVisible(member))
return false;
if (JavaModelUtil.isSamePackage(((IType) member).getPackageFragment(), target.getPackageFragment()))
return true;
final IType type = member.getDeclaringType();
if (type != null)
return hierarchy.contains(type);
return false;
}
final IType declaringType = member.getDeclaringType();
// if the member's declaring type isn't accessible from the target
// type.
if (!canBeAccessedFrom(sourceMethod, declaringType, target, hierarchy))
return false; // then, the member isn't accessible from the
// target type.
// otherwise, the member's declaring type is accessible from the
// target type.
// We are going to be moving the source method from it's
// declaring type.
// We know that the member's declaring type is accessible from
// the target.
// We also know that the member's declaring type and the target
// type are different.
// The question now is if the target type can access the
// particular member given that
// the target type can access the member's declaring type.
// if it's public, the answer is yes.
if (JdtFlags.isPublic(member))
return true;
// if the member is private, the answer is no.
else if (JdtFlags.isPrivate(member))
return false;
// if it's package-private or protected.
else if (JdtFlags.isPackageVisible(member) || JdtFlags.isProtected(member)) {
// then, if the member's declaring type in the same package
// as the target's declaring type, the answer is yes.
if (JavaModelUtil.isVisible(member, target.getPackageFragment()))
return true;
// otherwise, if it's protected.
else if (JdtFlags.isProtected(member))
// then, the answer is yes if the target type is a
// sub-type of the member's declaring type. Otherwise,
// the answer is no.
return hierarchy.contains(declaringType);
else
return false; // not accessible.
} else
throw new IllegalStateException("Member: " + member + " has no known visibility.");
}
return false;
}
private RefactoringStatus checkAccessedTypes(IMethod sourceMethod, final Optional<IProgressMonitor> monitor,
final ITypeHierarchy hierarchy) throws JavaModelException {
final RefactoringStatus result = new RefactoringStatus();
final IType[] accessedTypes = getTypesReferencedInMovedMembers(sourceMethod, monitor);
final IType destination = getDestinationInterface(sourceMethod).get();
final List<IMember> pulledUpList = Arrays.asList(sourceMethod);
for (int index = 0; index < accessedTypes.length; index++) {
final IType type = accessedTypes[index];
if (!type.exists())
continue;
if (!canBeAccessedFrom(sourceMethod, type, destination, hierarchy) && !pulledUpList.contains(type)) {
final String message = org.eclipse.jdt.internal.corext.util.Messages
.format(PreconditionFailure.TypeNotAccessible.getMessage(),
new String[] { JavaElementLabels.getTextLabel(type,
JavaElementLabels.ALL_FULLY_QUALIFIED),
JavaElementLabels.getTextLabel(destination, JavaElementLabels.ALL_FULLY_QUALIFIED) });
result.addEntry(RefactoringStatus.ERROR, message, JavaStatusContext.create(type),
MigrateSkeletalImplementationToInterfaceRefactoringDescriptor.REFACTORING_ID,
PreconditionFailure.TypeNotAccessible.ordinal(), sourceMethod);
this.getUnmigratableMethods().add(sourceMethod);
}
}
monitor.ifPresent(IProgressMonitor::done);
return result;
}
private RefactoringStatus checkAccessedFields(IMethod sourceMethod, final Optional<IProgressMonitor> monitor,
final ITypeHierarchy destinationInterfaceSuperTypeHierarchy) throws CoreException {
monitor.ifPresent(m -> m.beginTask(RefactoringCoreMessages.PullUpRefactoring_checking_referenced_elements, 2));
final RefactoringStatus result = new RefactoringStatus();
final List<IMember> pulledUpList = Arrays.asList(sourceMethod);
final IField[] accessedFields = ReferenceFinderUtil.getFieldsReferencedIn(new IJavaElement[] { sourceMethod },
new SubProgressMonitor(monitor.orElseGet(NullProgressMonitor::new), 1));
final IType destination = getDestinationInterface(sourceMethod).orElseThrow(() -> new IllegalArgumentException(
"Source method: " + sourceMethod + " has no destiantion interface."));
for (int index = 0; index < accessedFields.length; index++) {
final IField accessedField = accessedFields[index];
if (!accessedField.exists())
continue;
boolean isAccessible = pulledUpList.contains(accessedField) || canBeAccessedFrom(sourceMethod,
accessedField, destination, destinationInterfaceSuperTypeHierarchy)
|| Flags.isEnum(accessedField.getFlags());
if (!isAccessible) {
final String message = org.eclipse.jdt.internal.corext.util.Messages
.format(PreconditionFailure.FieldNotAccessible.getMessage(),
new String[] {
JavaElementLabels.getTextLabel(accessedField,
JavaElementLabels.ALL_FULLY_QUALIFIED),
JavaElementLabels.getTextLabel(destination, JavaElementLabels.ALL_FULLY_QUALIFIED) });
result.addEntry(RefactoringStatus.ERROR, message, JavaStatusContext.create(accessedField),
MigrateSkeletalImplementationToInterfaceRefactoringDescriptor.REFACTORING_ID,
PreconditionFailure.FieldNotAccessible.ordinal(), sourceMethod);
this.getUnmigratableMethods().add(sourceMethod);
} else if (!JdtFlags.isStatic(accessedField) && !accessedField.getDeclaringType().isInterface()) {
// it's accessible and it's an instance field.
// Let's decide if the source method is accessing it from this
// object or another. If it's from this object, we fail.
// First, find all references of the accessed field in the
// source method.
FieldAccessAnalysisSearchRequestor requestor = new FieldAccessAnalysisSearchRequestor(monitor);
this.getSearchEngine()
.search(SearchPattern.createPattern(accessedField, IJavaSearchConstants.REFERENCES,
SearchPattern.R_EXACT_MATCH),
new SearchParticipant[] { SearchEngine.getDefaultSearchParticipant() },
SearchEngine.createJavaSearchScope(new IJavaElement[] { sourceMethod }), requestor,
new SubProgressMonitor(monitor.orElseGet(NullProgressMonitor::new), IProgressMonitor.UNKNOWN));
if (requestor.hasAccessesToFieldsFromImplicitParameter())
addErrorAndMark(result, PreconditionFailure.SourceMethodAccessesInstanceField, sourceMethod,
accessedField);
}
}
monitor.ifPresent(IProgressMonitor::done);
return result;
}
private RefactoringStatus checkAccessedMethods(IMethod sourceMethod, final Optional<IProgressMonitor> monitor,
final ITypeHierarchy destinationInterfaceSuperTypeHierarchy) throws CoreException {
monitor.ifPresent(m -> m.beginTask(RefactoringCoreMessages.PullUpRefactoring_checking_referenced_elements, 3));
final RefactoringStatus result = new RefactoringStatus();
final List<IMember> pulledUpList = Arrays.asList(sourceMethod);
final Set<IMethod> accessedMethods = new LinkedHashSet<>(
Arrays.asList(ReferenceFinderUtil.getMethodsReferencedIn(new IJavaElement[] { sourceMethod },
new SubProgressMonitor(monitor.orElseGet(NullProgressMonitor::new), 1))));
// also add constructors.
accessedMethods.addAll(getConstructorsReferencedIn(new IJavaElement[] { sourceMethod },
monitor.map(m -> new SubProgressMonitor(m, 1))));
final IType destination = getDestinationInterface(sourceMethod).orElseThrow(() -> new IllegalArgumentException(
"Source method: " + sourceMethod + " has no destiantion interface."));
for (IMethod accessedMethod : accessedMethods) {
if (!accessedMethod.exists())
continue;
boolean isAccessible = pulledUpList.contains(accessedMethod) || canBeAccessedFrom(sourceMethod,
accessedMethod, destination, destinationInterfaceSuperTypeHierarchy);
if (!isAccessible) {
final String message = org.eclipse.jdt.internal.corext.util.Messages.format(
PreconditionFailure.MethodNotAccessible.getMessage(),
new String[] { getTextLabel(accessedMethod, ALL_FULLY_QUALIFIED),
getTextLabel(destination, ALL_FULLY_QUALIFIED) });
result.addEntry(RefactoringStatus.ERROR, message, JavaStatusContext.create(accessedMethod),
MigrateSkeletalImplementationToInterfaceRefactoringDescriptor.REFACTORING_ID,
PreconditionFailure.MethodNotAccessible.ordinal(), sourceMethod);
this.getUnmigratableMethods().add(sourceMethod);
} else if (!JdtFlags.isStatic(accessedMethod)) {
// it's accessible and it's not static.
// we'll need to check the implicit parameters.
MethodDeclaration sourceMethodDeclaration = ASTNodeSearchUtil.getMethodDeclarationNode(sourceMethod,
getCompilationUnit(sourceMethod.getTypeRoot(), new SubProgressMonitor(
monitor.orElseGet(NullProgressMonitor::new), IProgressMonitor.UNKNOWN)));
MethodReceiverAnalysisVisitor visitor = new MethodReceiverAnalysisVisitor(accessedMethod);
sourceMethodDeclaration.getBody().accept(visitor);
// if this is the implicit parameter.
if (visitor.hasEncounteredThisReceiver()) {
// let's check to see if the method is somewhere in the
// hierarchy.
IType methodDeclaringType = accessedMethod.getDeclaringType();
// is this method declared in a type that is in the
// declaring type's super type hierarchy?
ITypeHierarchy declaringTypeSuperTypeHierarchy = getSuperTypeHierarchy(
sourceMethod.getDeclaringType(),
monitor.map(m -> new SubProgressMonitor(m, IProgressMonitor.UNKNOWN)));
if (declaringTypeSuperTypeHierarchy.contains(methodDeclaringType)) {
// if so, then we need to check that it is in the
// destination interface's super type hierarchy.
boolean methodInHiearchy = isMethodInHierarchy(accessedMethod,
destinationInterfaceSuperTypeHierarchy);
if (!methodInHiearchy) {
final String message = org.eclipse.jdt.internal.corext.util.Messages.format(
PreconditionFailure.MethodNotAccessible.getMessage(),
new String[] { getTextLabel(accessedMethod, ALL_FULLY_QUALIFIED),
getTextLabel(destination, ALL_FULLY_QUALIFIED) });
result.addEntry(RefactoringStatus.ERROR, message, JavaStatusContext.create(accessedMethod),
MigrateSkeletalImplementationToInterfaceRefactoringDescriptor.REFACTORING_ID,
PreconditionFailure.MethodNotAccessible.ordinal(), sourceMethod);
this.getUnmigratableMethods().add(sourceMethod);
}
}
}
}
}
monitor.ifPresent(IProgressMonitor::done);
return result;
}
private Collection<? extends IMethod> getConstructorsReferencedIn(IJavaElement[] elements,
final Optional<IProgressMonitor> monitor) throws CoreException {
Collection<IMethod> ret = new LinkedHashSet<>();
SearchPattern pattern = SearchPattern.createPattern("*", IJavaSearchConstants.CONSTRUCTOR,
IJavaSearchConstants.REFERENCES, SearchPattern.R_PATTERN_MATCH);
IJavaSearchScope scope = SearchEngine.createJavaSearchScope(elements, true);
SearchParticipant[] participants = new SearchParticipant[] { SearchEngine.getDefaultSearchParticipant() };
this.getSearchEngine().search(pattern, participants, scope, new SearchRequestor() {
@Override
public void acceptSearchMatch(SearchMatch match) throws CoreException {
if (match.isInsideDocComment())
return;
ASTNode node = ASTNodeSearchUtil.getAstNode(match, getCompilationUnit(
((IMember) match.getElement()).getTypeRoot(),
new SubProgressMonitor(monitor.orElseGet(NullProgressMonitor::new), IProgressMonitor.UNKNOWN)));
node = Util.stripParenthesizedExpressions(node);
IMethod constructor = extractConstructor(node);
if (constructor != null)
ret.add(constructor);
}
private IMethod extractConstructor(ASTNode node) {
if (node == null)
throw new IllegalArgumentException("Node is null");
else {
switch (node.getNodeType()) {
case ASTNode.CLASS_INSTANCE_CREATION: {
ClassInstanceCreation creation = (ClassInstanceCreation) node;
IMethodBinding binding = creation.resolveConstructorBinding();
return (IMethod) binding.getJavaElement();
}
case ASTNode.CONSTRUCTOR_INVOCATION: {
ConstructorInvocation invocation = (ConstructorInvocation) node;
IMethodBinding binding = invocation.resolveConstructorBinding();
return (IMethod) binding.getJavaElement();
}
case ASTNode.SUPER_CONSTRUCTOR_INVOCATION: {
SuperConstructorInvocation invocation = (SuperConstructorInvocation) node;
IMethodBinding binding = invocation.resolveConstructorBinding();
return (IMethod) binding.getJavaElement();
}
case ASTNode.CREATION_REFERENCE: {
CreationReference reference = (CreationReference) node;
IMethodBinding binding = reference.resolveMethodBinding();
if (binding == null) {
logWarning("Could not resolve method binding from creation reference: " + reference);
return null;
}
IMethod javaElement = (IMethod) binding.getJavaElement();
return javaElement;
}
case ASTNode.TYPE_DECLARATION: {
//no ctor reference here.
return null;
}
default: {
// try the parent node.
return extractConstructor(node.getParent());
}
}
}
}
}, monitor.orElseGet(NullProgressMonitor::new));
return ret;
}
private static boolean isMethodInHierarchy(IMethod method, ITypeHierarchy hierarchy) {
// TODO: Cache this?
return Stream.of(hierarchy.getAllTypes()).parallel().anyMatch(t -> {
IMethod[] methods = t.findMethods(method);
return methods != null && methods.length > 0;
});
}
private RefactoringStatus checkAccesses(IMethod sourceMethod, final Optional<IProgressMonitor> monitor)
throws CoreException {
final RefactoringStatus result = new RefactoringStatus();
try {
monitor.ifPresent(
m -> m.beginTask(RefactoringCoreMessages.PullUpRefactoring_checking_referenced_elements, 4));
IType destinationInterface = getDestinationInterface(sourceMethod)
.orElseThrow(() -> new IllegalArgumentException(
"Source method: " + sourceMethod + " has no destination interface."));
final ITypeHierarchy destinationInterfaceSuperTypeHierarchy = getSuperTypeHierarchy(destinationInterface,
monitor.map(m -> new SubProgressMonitor(m, 1)));
result.merge(checkAccessedTypes(sourceMethod, monitor.map(m -> new SubProgressMonitor(m, 1)),
destinationInterfaceSuperTypeHierarchy));
result.merge(checkAccessedFields(sourceMethod, monitor.map(m -> new SubProgressMonitor(m, 1)),
destinationInterfaceSuperTypeHierarchy));
result.merge(checkAccessedMethods(sourceMethod, monitor.map(m -> new SubProgressMonitor(m, 1)),
destinationInterfaceSuperTypeHierarchy));
} finally {
monitor.ifPresent(IProgressMonitor::done);
}
return result;
}
private boolean allMethodsToMoveInTypeAreStrictFP(IType type) throws JavaModelException {
for (Iterator<IMethod> iterator = this.getSourceMethods().iterator(); iterator.hasNext();) {
IMethod method = iterator.next();
if (method.getDeclaringType().equals(type) && !Flags.isStrictfp(method.getFlags()))
return false;
}
return true;
}
private static boolean isInterfaceFunctional(final IType anInterface) throws JavaModelException {
// TODO: #37: Compute effectively functional interfaces.
return Stream.of(anInterface.getAnnotations()).parallel().map(IAnnotation::getElementName)
.anyMatch(s -> s.contains(FUNCTIONAL_INTERFACE_ANNOTATION_NAME));
}
private RefactoringStatus checkValidInterfacesInDeclaringTypeHierarchy(IMethod sourceMethod,
Optional<IProgressMonitor> monitor) throws JavaModelException {
RefactoringStatus status = new RefactoringStatus();
monitor.ifPresent(m -> m.beginTask("Checking valid interfaces in declaring type hierarchy ...",
IProgressMonitor.UNKNOWN));
try {
ITypeHierarchy hierarchy = this.getDeclaringTypeHierarchy(sourceMethod, monitor);
IType[] declaringTypeSuperInterfaces = hierarchy.getAllSuperInterfaces(sourceMethod.getDeclaringType());
// the number of methods sourceMethod is implementing.
long numberOfImplementedMethods = Arrays.stream(declaringTypeSuperInterfaces).parallel().distinct().flatMap(
i -> Arrays.stream(Optional.ofNullable(i.findMethods(sourceMethod)).orElse(new IMethod[] {})))
.count();
if (numberOfImplementedMethods > 1)
addErrorAndMark(status, PreconditionFailure.SourceMethodImplementsMultipleMethods, sourceMethod);
// for each subclass of the declaring type.
for (IType subclass : hierarchy.getSubclasses(sourceMethod.getDeclaringType())) {
status.merge(checkClassForMissingSourceMethodImplementation(sourceMethod, subclass, hierarchy,
monitor.map(m -> new SubProgressMonitor(m, IProgressMonitor.UNKNOWN))));
}
} finally {
monitor.ifPresent(IProgressMonitor::done);
}
return status;
}
/**
* Checks the given class and its subclasses for any required
* implementations of the source method. The required implementations are
* deemed by the interfaces the given class implements.
*
* @param sourceMethod
* The source method being migrated to an interface.
* @param clazz
* The class to check for any missing needed implementations of
* the source method.
* @param declaringTypeHierarchy
* Hierarchy of the source method's declaring type.
* @return {@link RefactoringStatus} indicating the result of the
* precondition check.
* @throws JavaModelException
* When asserting that the given {@link IType} is indeed a
* class.
*/
private RefactoringStatus checkClassForMissingSourceMethodImplementation(IMethod sourceMethod, IType clazz,
ITypeHierarchy declaringTypeHierarchy, Optional<IProgressMonitor> monitor) throws JavaModelException {
RefactoringStatus status = new RefactoringStatus();
// does the class have an implementation or declaration of the source
// method?
IMethod[] classMethodMatchingSourceMethod = clazz.findMethods(sourceMethod);
if (classMethodMatchingSourceMethod != null && classMethodMatchingSourceMethod.length > 0)
// in this case, the class has an implementation. No need to check
// any interfaces or subclasses.
// because any interfaces would be satisfied and any unsatisfied
// interfaces will inherit the method from this class.
return status;
// otherwise, no matching methods were found in the given class.
else {
// retrieve super interfaces of the class.
IType[] superInterfaces = getSuperInterfaces(clazz, declaringTypeHierarchy,
monitor.map(m -> new SubProgressMonitor(m, IProgressMonitor.UNKNOWN)));
try {
monitor.ifPresent(m -> m.beginTask("Checking class for missing source method implementation ...",
superInterfaces.length));
// retrieve the destination interface.
IType destinationInterface = getTargetMethod(sourceMethod,
monitor.map(m -> new SubProgressMonitor(m, IProgressMonitor.UNKNOWN))).getDeclaringType();
// for each super interface of the given class.
for (IType superInterface : superInterfaces) {
// if it is not equal to the destination interface.
if (!superInterface.equals(destinationInterface)) {
IMethod[] interfaceMethodMatchingSourceMethod = superInterface.findMethods(sourceMethod);
if (interfaceMethodMatchingSourceMethod != null
&& interfaceMethodMatchingSourceMethod.length > 0)
// there are multiple method definitions stemming
// from
// interfaces.
// this class doesn't have an implementation of the
// source
// method nor does it inherit it.
addErrorAndMark(status,
PreconditionFailure.SourceMethodProvidesImplementationsForMultipleMethods,
sourceMethod, superInterface);
}
monitor.ifPresent(m -> m.worked(1));
}
// check subclasses of the given class.
for (IType subclass : declaringTypeHierarchy.getSubclasses(clazz))
status.merge(checkClassForMissingSourceMethodImplementation(sourceMethod, subclass,
declaringTypeHierarchy,
monitor.map(m -> new SubProgressMonitor(m, IProgressMonitor.UNKNOWN))));
return status;
} finally {
monitor.ifPresent(IProgressMonitor::done);
}
}
}
private static IType[] getSuperInterfaces(IType type, ITypeHierarchy typeHierarchy,
Optional<IProgressMonitor> monitor) throws JavaModelException {
Set<IType> ret = new LinkedHashSet<>();
IType[] superInterfaces = typeHierarchy.getSuperInterfaces(type);
ret.addAll(Arrays.asList(superInterfaces));
monitor.ifPresent(m -> m.beginTask("Retreiving super interfaces ...", superInterfaces.length));
try {
for (IType superInterface : superInterfaces) {
ret.addAll(Arrays
.asList(getSuperInterfaces(superInterface, monitor.map(m -> new SubProgressMonitor(m, 1)))));
}
} finally {
monitor.ifPresent(IProgressMonitor::done);
}
return ret.toArray(new IType[ret.size()]);
}
private Optional<IType> getDestinationInterface(IMethod sourceMethod) throws JavaModelException {
return Optional.ofNullable(getTargetMethod(sourceMethod, Optional.empty())).map(IMethod::getDeclaringType);
}
private RefactoringStatus checkValidClassesInDeclaringTypeHierarchy(IMethod sourceMethod,
final ITypeHierarchy declaringTypeHierarchy) throws JavaModelException {
RefactoringStatus status = new RefactoringStatus();
IType[] allDeclaringTypeSuperclasses = declaringTypeHierarchy
.getAllSuperclasses(sourceMethod.getDeclaringType());
// is the source method overriding anything in the declaring type
// hierarchy? If so, don't allow the refactoring to proceed #107.
if (Stream.of(allDeclaringTypeSuperclasses).parallel().anyMatch(c -> {
IMethod[] methods = c.findMethods(sourceMethod);
return methods != null && methods.length > 0;
}))
addErrorAndMark(status, PreconditionFailure.SourceMethodOverridesMethod, sourceMethod);
return status;
}
private void addWarning(RefactoringStatus status, IMethod sourceMethod, PreconditionFailure failure) {
addWarning(status, sourceMethod, failure, new IJavaElement[] {});
}
private RefactoringStatus checkDeclaringType(IMethod sourceMethod, Optional<IProgressMonitor> monitor)
throws JavaModelException {
RefactoringStatus status = new RefactoringStatus();
IType type = sourceMethod.getDeclaringType();
if (type.isAnnotation())
addErrorAndMark(status, PreconditionFailure.NoMethodsInAnnotationTypes, sourceMethod, type);
if (type.isInterface())
addErrorAndMark(status, PreconditionFailure.NoMethodsInInterfaces, sourceMethod, type);
if (type.isBinary())
addErrorAndMark(status, PreconditionFailure.NoMethodsInBinaryTypes, sourceMethod, type);
if (type.isReadOnly())
addErrorAndMark(status, PreconditionFailure.NoMethodsInReadOnlyTypes, sourceMethod, type);
if (type.isAnonymous())
addErrorAndMark(status, PreconditionFailure.NoMethodsInAnonymousTypes, sourceMethod, type);
if (type.isLambda())
// TODO for now.
addErrorAndMark(status, PreconditionFailure.NoMethodsInLambdas, sourceMethod, type);
if (type.isLocal())
// TODO for now.
addErrorAndMark(status, PreconditionFailure.NoMethodsInLocals, sourceMethod, type);
// TODO enclosing type must implement an interface, at least for
// now,
// which one of which will become the target interface.
// it is probably possible to still perform the refactoring
// without this condition but I believe that this is
// the particular pattern we are targeting.
status.merge(checkDeclaringTypeHierarchy(sourceMethod, monitor.map(m -> new SubProgressMonitor(m, 1))));
return status;
}
private void addErrorAndMark(RefactoringStatus status, PreconditionFailure failure, IMethod sourceMethod,
IMember... related) {
RefactoringStatusEntry error = addError(status, sourceMethod, failure, sourceMethod, related);
addUnmigratableMethod(sourceMethod, error);
}
private RefactoringStatus checkDeclaringTypeHierarchy(IMethod sourceMethod, Optional<IProgressMonitor> monitor)
throws JavaModelException {
try {
RefactoringStatus status = new RefactoringStatus();
monitor.ifPresent(m -> m.subTask("Checking declaring type hierarchy..."));
final ITypeHierarchy declaringTypeHierarchy = this.getDeclaringTypeHierarchy(sourceMethod, monitor);
status.merge(checkValidClassesInDeclaringTypeHierarchy(sourceMethod, declaringTypeHierarchy));
status.merge(checkValidInterfacesInDeclaringTypeHierarchy(sourceMethod, monitor));
return status;
} finally {
monitor.ifPresent(IProgressMonitor::done);
}
}
private RefactoringStatus checkCandidateDestinationInterfaces(IMethod sourceMethod,
final Optional<IProgressMonitor> monitor) throws JavaModelException {
RefactoringStatus status = new RefactoringStatus();
IType[] interfaces = getCandidateDestinationInterfaces(sourceMethod,
monitor.map(m -> new SubProgressMonitor(m, 1)));
if (interfaces.length == 0)
addErrorAndMark(status, PreconditionFailure.NoMethodsInTypesWithNoCandidateTargetTypes, sourceMethod,
sourceMethod.getDeclaringType());
else if (interfaces.length > 1)
// TODO: For now, let's make sure there's only one candidate type
// #129.
addErrorAndMark(status, PreconditionFailure.NoMethodsInTypesWithMultipleCandidateTargetTypes, sourceMethod,
sourceMethod.getDeclaringType());
return status;
}
/**
* Returns the possible target interfaces for the migration. NOTE: One
* difference here between this refactoring and pull up is that we can have
* a much more complex type hierarchy due to multiple interface inheritance
* in Java.
* <p>
* TODO: It should be possible to pull up a method into an interface (i.e.,
* "Pull Up Method To Interface") that is not implemented explicitly. For
* example, there may be a skeletal implementation class that implements all
* the target interface's methods without explicitly declaring so.
* Effectively skeletal?
*
* @param monitor
* A progress monitor.
* @return The possible target interfaces for the migration.
* @throws JavaModelException
* upon Java model problems.
*/
public static IType[] getCandidateDestinationInterfaces(IMethod sourcMethod,
final Optional<IProgressMonitor> monitor) throws JavaModelException {
try {
monitor.ifPresent(m -> m.beginTask("Retrieving candidate types...", IProgressMonitor.UNKNOWN));
IType[] superInterfaces = getSuperInterfaces(sourcMethod.getDeclaringType(),
monitor.map(m -> new SubProgressMonitor(m, 1)));
Stream<IType> candidateStream = Stream.of(superInterfaces).parallel().filter(Objects::nonNull)
.filter(IJavaElement::exists).filter(t -> !t.isReadOnly()).filter(t -> !t.isBinary());
Set<IType> ret = new HashSet<>();
for (Iterator<IType> iterator = candidateStream.iterator(); iterator.hasNext();) {
IType superInterface = iterator.next();
IMethod[] interfaceMethods = superInterface.findMethods(sourcMethod);
if (interfaceMethods != null)
// the matching methods cannot already be default.
for (IMethod method : interfaceMethods)
if (!JdtFlags.isDefaultMethod(method))
ret.add(superInterface);
}
return ret.toArray(new IType[ret.size()]);
} finally {
monitor.ifPresent(IProgressMonitor::done);
}
}
private static IType[] getSuperInterfaces(IType type, final Optional<IProgressMonitor> monitor)
throws JavaModelException {
try {
monitor.ifPresent(m -> m.beginTask("Retrieving type super interfaces...", IProgressMonitor.UNKNOWN));
return getSuperTypeHierarchy(type, monitor.map(m -> new SubProgressMonitor(m, 1)))
.getAllSuperInterfaces(type);
} finally {
monitor.ifPresent(IProgressMonitor::done);
}
}
private ITypeHierarchy getDeclaringTypeHierarchy(IMethod sourceMethod, final Optional<IProgressMonitor> monitor)
throws JavaModelException {
try {
monitor.ifPresent(m -> m.subTask("Retrieving declaring type hierarchy..."));
IType declaringType = sourceMethod.getDeclaringType();
return this.getTypeHierarchy(declaringType, monitor);
} finally {
monitor.ifPresent(IProgressMonitor::done);
}
}
@SuppressWarnings("unused")
private ITypeHierarchy getDestinationInterfaceHierarchy(IMethod sourceMethod,
final Optional<IProgressMonitor> monitor) throws JavaModelException {
try {
monitor.ifPresent(m -> m.subTask("Retrieving destination type hierarchy..."));
IType destinationInterface = getDestinationInterface(sourceMethod).get();
return this.getTypeHierarchy(destinationInterface, monitor);
} finally {
monitor.ifPresent(IProgressMonitor::done);
}
}
private static Map<IType, ITypeHierarchy> typeToSuperTypeHierarchyMap = new HashMap<>();
private static Map<IType, ITypeHierarchy> getTypeToSuperTypeHierarchyMap() {
return typeToSuperTypeHierarchyMap;
}
private static ITypeHierarchy getSuperTypeHierarchy(IType type, final Optional<IProgressMonitor> monitor)
throws JavaModelException {
try {
monitor.ifPresent(m -> m.subTask("Retrieving declaring super type hierarchy..."));
if (getTypeToSuperTypeHierarchyMap().containsKey(type))
return getTypeToSuperTypeHierarchyMap().get(type);
else {
ITypeHierarchy newSupertypeHierarchy = type
.newSupertypeHierarchy(monitor.orElseGet(NullProgressMonitor::new));
getTypeToSuperTypeHierarchyMap().put(type, newSupertypeHierarchy);
return newSupertypeHierarchy;
}
} finally {
monitor.ifPresent(IProgressMonitor::done);
}
}
private RefactoringStatus checkSourceMethods(Optional<IProgressMonitor> pm) throws CoreException {
try {
RefactoringStatus status = new RefactoringStatus();
pm.ifPresent(m -> m.beginTask(Messages.CheckingPreconditions, this.getSourceMethods().size()));
for (IMethod sourceMethod : this.getSourceMethods()) {
RefactoringStatus existenceStatus = checkExistence(sourceMethod,
PreconditionFailure.MethodDoesNotExist);
if (!existenceStatus.isOK()) {
status.merge(existenceStatus);
addUnmigratableMethod(sourceMethod, existenceStatus.getEntryWithHighestSeverity());
}
RefactoringStatus writabilityStatus = checkWritabilitiy(sourceMethod,
PreconditionFailure.CantChangeMethod);
if (!writabilityStatus.isOK()) {
status.merge(writabilityStatus);
addUnmigratableMethod(sourceMethod, writabilityStatus.getEntryWithHighestSeverity());
}
RefactoringStatus structureStatus = checkStructure(sourceMethod);
if (!structureStatus.isOK()) {
status.merge(structureStatus);
addUnmigratableMethod(sourceMethod, structureStatus.getEntryWithHighestSeverity());
}
if (sourceMethod.isConstructor()) {
RefactoringStatusEntry entry = addError(status, sourceMethod, PreconditionFailure.NoConstructors,
sourceMethod);
addUnmigratableMethod(sourceMethod, entry);
}
status.merge(checkAnnotations(sourceMethod));
// synchronized methods aren't allowed in interfaces (even
// if they're default).
if (Flags.isSynchronized(sourceMethod.getFlags())) {
RefactoringStatusEntry entry = addError(status, sourceMethod,
PreconditionFailure.NoSynchronizedMethods, sourceMethod);
addUnmigratableMethod(sourceMethod, entry);
}
if (Flags.isStatic(sourceMethod.getFlags())) {
RefactoringStatusEntry entry = addError(status, sourceMethod, PreconditionFailure.NoStaticMethods,
sourceMethod);
addUnmigratableMethod(sourceMethod, entry);
}
if (Flags.isAbstract(sourceMethod.getFlags())) {
RefactoringStatusEntry entry = addError(status, sourceMethod, PreconditionFailure.NoAbstractMethods,
sourceMethod);
addUnmigratableMethod(sourceMethod, entry);
}
// final methods aren't allowed in interfaces.
if (Flags.isFinal(sourceMethod.getFlags())) {
RefactoringStatusEntry entry = addError(status, sourceMethod, PreconditionFailure.NoFinalMethods,
sourceMethod);
addUnmigratableMethod(sourceMethod, entry);
}
// native methods don't have bodies. As such, they can't
// be skeletal implementors.
if (JdtFlags.isNative(sourceMethod)) {
RefactoringStatusEntry entry = addError(status, sourceMethod, PreconditionFailure.NoNativeMethods,
sourceMethod);
addUnmigratableMethod(sourceMethod, entry);
}
if (sourceMethod.isLambdaMethod()) {
RefactoringStatusEntry entry = addError(status, sourceMethod, PreconditionFailure.NoLambdaMethods,
sourceMethod);
addUnmigratableMethod(sourceMethod, entry);
}
status.merge(checkExceptions(sourceMethod));
// ensure that the method has a target.
if (getTargetMethod(sourceMethod,
pm.map(m -> new SubProgressMonitor(m, IProgressMonitor.UNKNOWN))) == null)
addErrorAndMark(status, PreconditionFailure.SourceMethodHasNoTargetMethod, sourceMethod);
else {
status.merge(checkParameters(sourceMethod, pm.map(m -> new SubProgressMonitor(m, 1))));
status.merge(checkReturnType(sourceMethod, pm.map(m -> new SubProgressMonitor(m, 1))));
status.merge(checkAccesses(sourceMethod, pm.map(m -> new SubProgressMonitor(m, 1))));
status.merge(checkGenericDeclaringType(sourceMethod, pm.map(m -> new SubProgressMonitor(m, 1))));
status.merge(checkProjectCompliance(sourceMethod));
}
pm.ifPresent(m -> m.worked(1));
}
return status;
} finally {
pm.ifPresent(IProgressMonitor::done);
}
}
private RefactoringStatus checkGenericDeclaringType(IMethod sourceMethod, Optional<IProgressMonitor> monitor)
throws JavaModelException {
final RefactoringStatus status = new RefactoringStatus();
try {
final IMember[] pullables = new IMember[] { sourceMethod };
monitor.ifPresent(m -> m.beginTask(RefactoringCoreMessages.PullUpRefactoring_checking, pullables.length));
final IType declaring = sourceMethod.getDeclaringType();
final ITypeParameter[] parameters = declaring.getTypeParameters();
if (parameters.length > 0) {
monitor.ifPresent(m -> m.beginTask("Retrieving target method.", IProgressMonitor.UNKNOWN));
IMethod targetMethod = getTargetMethod(sourceMethod,
monitor.map(m -> new SubProgressMonitor(m, IProgressMonitor.UNKNOWN)));
final TypeVariableMaplet[] mapping = TypeVariableUtil.subTypeToInheritedType(declaring,
targetMethod.getDeclaringType());
IMember member = null;
int length = 0;
for (int index = 0; index < pullables.length; index++) {
member = pullables[index];
final String[] unmapped = TypeVariableUtil.getUnmappedVariables(mapping, declaring, member);
length = unmapped.length;
String superClassLabel = BasicElementLabels
.getJavaElementName(targetMethod.getDeclaringType().getElementName());
switch (length) {
case 0:
break;
case 1:
status.addEntry(RefactoringStatus.ERROR,
String.format(PreconditionFailure.TypeVariableNotAvailable.getMessage(), unmapped[0],
superClassLabel),
JavaStatusContext.create(member),
MigrateSkeletalImplementationToInterfaceRefactoringDescriptor.REFACTORING_ID,
PreconditionFailure.TypeVariableNotAvailable.ordinal(), sourceMethod);
addUnmigratableMethod(sourceMethod, status.getEntryWithHighestSeverity());
break;
case 2:
status.addEntry(RefactoringStatus.ERROR,
MessageFormat.format(PreconditionFailure.TypeVariable2NotAvailable.getMessage(),
unmapped[0], unmapped[1], superClassLabel),
JavaStatusContext.create(member),
MigrateSkeletalImplementationToInterfaceRefactoringDescriptor.REFACTORING_ID,
PreconditionFailure.TypeVariable2NotAvailable.ordinal(), sourceMethod);
addUnmigratableMethod(sourceMethod, status.getEntryWithHighestSeverity());
break;
case 3:
status.addEntry(RefactoringStatus.ERROR,
MessageFormat.format(PreconditionFailure.TypeVariable3NotAvailable.getMessage(),
unmapped[0], unmapped[1], unmapped[2], superClassLabel),
JavaStatusContext.create(member),
MigrateSkeletalImplementationToInterfaceRefactoringDescriptor.REFACTORING_ID,
PreconditionFailure.TypeVariable3NotAvailable.ordinal(), sourceMethod);
addUnmigratableMethod(sourceMethod, status.getEntryWithHighestSeverity());
break;
default:
status.addEntry(RefactoringStatus.ERROR,
MessageFormat.format(PreconditionFailure.TypeVariablesNotAvailable.getMessage(),
superClassLabel),
JavaStatusContext.create(member),
MigrateSkeletalImplementationToInterfaceRefactoringDescriptor.REFACTORING_ID,
PreconditionFailure.TypeVariablesNotAvailable.ordinal(), sourceMethod);
addUnmigratableMethod(sourceMethod, status.getEntryWithHighestSeverity());
}
monitor.ifPresent(m -> m.worked(1));
monitor.ifPresent(m -> {
if (m.isCanceled())
throw new OperationCanceledException();
});
}
}
} finally {
monitor.ifPresent(IProgressMonitor::done);
}
return status;
}
/**
* Annotations between source and target methods must be consistent. Related
* to #45.
*
* @param sourceMethod
* The method to check annotations.
* @return The resulting {@link RefactoringStatus}.
* @throws JavaModelException
* If the {@link IAnnotation}s cannot be retrieved.
*/
private RefactoringStatus checkAnnotations(IMethod sourceMethod) throws JavaModelException {
RefactoringStatus status = new RefactoringStatus();
IMethod targetMethod = getTargetMethod(sourceMethod, Optional.empty());
if (targetMethod != null && (!checkAnnotations(sourceMethod, targetMethod).isOK()
|| !checkAnnotations(sourceMethod.getDeclaringType(), targetMethod.getDeclaringType()).isOK()))
addErrorAndMark(status, PreconditionFailure.AnnotationMismatch, sourceMethod, targetMethod);
return status;
}
private void addUnmigratableMethod(IMethod method, Object reason) {
this.getUnmigratableMethods().add(method);
this.logInfo(
"Method " + getElementLabel(method, ALL_FULLY_QUALIFIED) + " is not migratable because: " + reason);
}
private RefactoringStatus checkAnnotations(IAnnotatable source, IAnnotatable target) throws JavaModelException {
// a set of annotations from the source method.
Set<IAnnotation> sourceAnnotationSet = new HashSet<>(Arrays.asList(source.getAnnotations()));
// remove any annotations to not consider.
removeSpecialAnnotations(sourceAnnotationSet);
// a set of source method annotation names.
Set<String> sourceMethodAnnotationElementNames = sourceAnnotationSet.parallelStream()
.map(IAnnotation::getElementName).collect(Collectors.toSet());
// a set of target method annotation names.
Set<String> targetAnnotationElementNames = getAnnotationElementNames(target);
// if the source method annotation names don't match the target method
// annotation names.
if (!sourceMethodAnnotationElementNames.equals(targetAnnotationElementNames))
return RefactoringStatus.createErrorStatus(PreconditionFailure.AnnotationNameMismatch.getMessage(),
new RefactoringStatusContext() {
@Override
public Object getCorrespondingElement() {
return source;
}
});
else { // otherwise, we have the same annotations names. Check the
// values.
for (IAnnotation sourceAnnotation : sourceAnnotationSet) {
IMemberValuePair[] sourcePairs = sourceAnnotation.getMemberValuePairs();
IAnnotation targetAnnotation = target.getAnnotation(sourceAnnotation.getElementName());
IMemberValuePair[] targetPairs = targetAnnotation.getMemberValuePairs();
// sanity check.
Assert.isTrue(sourcePairs.length == targetPairs.length, "Source and target pairs differ.");
Arrays.parallelSort(sourcePairs, Comparator.comparing(IMemberValuePair::getMemberName));
Arrays.parallelSort(targetPairs, Comparator.comparing(IMemberValuePair::getMemberName));
for (int i = 0; i < sourcePairs.length; i++)
if (!sourcePairs[i].getMemberName().equals(targetPairs[i].getMemberName())
|| sourcePairs[i].getValueKind() != targetPairs[i].getValueKind()
|| !(sourcePairs[i].getValue().equals(targetPairs[i].getValue())))
return RefactoringStatus.createErrorStatus(
formatMessage(PreconditionFailure.AnnotationValueMismatch.getMessage(),
sourceAnnotation, targetAnnotation),
JavaStatusContext.create(findEnclosingMember(sourceAnnotation)));
}
}
return new RefactoringStatus();
}
/**
* Remove any annotations that we don't want considered.
*
* @param annotationSet
* The set of annotations to work with.
*/
private void removeSpecialAnnotations(Set<IAnnotation> annotationSet) {
// Special case: don't consider the @Override annotation in the source
// (the target will never have this)
annotationSet.removeIf(a -> a.getElementName().equals(Override.class.getName()));
annotationSet.removeIf(a -> a.getElementName().equals(Override.class.getSimpleName()));
}
private static IMember findEnclosingMember(IJavaElement element) {
if (element == null)
return null;
else if (element instanceof IMember)
return (IMember) element;
else
return findEnclosingMember(element.getParent());
}
private Set<String> getAnnotationElementNames(IAnnotatable annotatable) throws JavaModelException {
return Arrays.stream(annotatable.getAnnotations()).parallel().map(IAnnotation::getElementName)
.collect(Collectors.toSet());
}
/**
* #44: Ensure that exception types between the source and target methods
* match.
*
* @param sourceMethod
* The source method.
* @return The corresponding {@link RefactoringStatus}.
* @throws JavaModelException
* If there is trouble retrieving exception types from
* sourceMethod.
*/
private RefactoringStatus checkExceptions(IMethod sourceMethod) throws JavaModelException {
RefactoringStatus status = new RefactoringStatus();
IMethod targetMethod = getTargetMethod(sourceMethod, Optional.empty());
if (targetMethod != null) {
Set<String> sourceMethodExceptionTypeSet = getExceptionTypeSet(sourceMethod);
Set<String> targetMethodExceptionTypeSet = getExceptionTypeSet(targetMethod);
if (!sourceMethodExceptionTypeSet.equals(targetMethodExceptionTypeSet)) {
RefactoringStatusEntry entry = addError(status, sourceMethod, PreconditionFailure.ExceptionTypeMismatch,
sourceMethod, targetMethod);
addUnmigratableMethod(sourceMethod, entry);
}
}
return status;
}
private static Set<String> getExceptionTypeSet(IMethod method) throws JavaModelException {
return Stream.of(method.getExceptionTypes()).parallel().collect(Collectors.toSet());
}
/**
* Check that the annotations in the parameters are consistent between the
* source and target, as well as type arguments.
*
* FIXME: What if the annotation type is not available in the target?
*
* @param sourceMethod
* The method to check.
* @param monitor
* An optional {@link IProgressMonitor}.
* @return {@link RefactoringStatus} indicating the result of the check.
* @throws JavaModelException
*/
private RefactoringStatus checkParameters(IMethod sourceMethod, Optional<IProgressMonitor> monitor)
throws JavaModelException {
RefactoringStatus status = new RefactoringStatus();
ILocalVariable[] sourceMethodParameters = sourceMethod.getParameters();
monitor.ifPresent(m -> m.beginTask(RefactoringCoreMessages.PullUpRefactoring_checking,
sourceMethodParameters.length * 2 + 1));
try {
IMethod targetMethod = getTargetMethod(sourceMethod, monitor.map(m -> new SubProgressMonitor(m, 1)));
// for each parameter.
for (int i = 0; i < sourceMethodParameters.length; i++) {
ILocalVariable sourceParameter = sourceMethodParameters[i];
// get the corresponding target parameter.
ILocalVariable targetParameter = targetMethod.getParameters()[i];
if (!checkAnnotations(sourceParameter, targetParameter).isOK())
addErrorAndMark(status, PreconditionFailure.MethodContainsInconsistentParameterAnnotations,
sourceMethod, targetMethod);
monitor.ifPresent(m -> m.worked(1));
}
// check generics #160.
IMethodBinding sourceMethodBinding = resolveMethodBinding(sourceMethod, monitor);
IMethodBinding targetMethodBinding = resolveMethodBinding(targetMethod, monitor);
if (targetMethodBinding != null) {
ITypeBinding[] sourceMethodParameterTypes = sourceMethodBinding.getParameterTypes();
ITypeBinding[] targetMethodParameterTypes = targetMethodBinding.getParameterTypes();
for (int i = 0; i < sourceMethodParameterTypes.length; i++) {
monitor.ifPresent(m -> m.worked(1));
ITypeBinding[] sourceMethodParameterTypeParameters = sourceMethodParameterTypes[i]
.getTypeArguments();
ITypeBinding[] targetMethodParamaterTypeParameters = targetMethodParameterTypes[i]
.getTypeArguments();
boolean hasAssignmentIncompatibleTypeParameter = false;
if (sourceMethodParameterTypeParameters.length != targetMethodParamaterTypeParameters.length) {
addErrorAndMark(status, PreconditionFailure.MethodContainsIncompatibleParameterTypeParameters,
sourceMethod, targetMethod);
break; // no more parameter types.
} else
for (int j = 0; j < sourceMethodParameterTypeParameters.length; j++) {
// if both aren't type variables.
if (!typeArgumentsAreTypeVariables(sourceMethodParameterTypeParameters[j],
targetMethodParamaterTypeParameters[j])) {
// then check if they are assignment compatible.
if (!isAssignmentCompatible(sourceMethodParameterTypeParameters[j],
targetMethodParamaterTypeParameters[j])) {
addErrorAndMark(status,
PreconditionFailure.MethodContainsIncompatibleParameterTypeParameters,
sourceMethod, targetMethod);
hasAssignmentIncompatibleTypeParameter = true;
break; // no more type parameters.
}
}
}
if (hasAssignmentIncompatibleTypeParameter)
break; // no more parameter types.
}
}
} finally {
monitor.ifPresent(IProgressMonitor::done);
}
return status;
}
private IMethodBinding resolveMethodBinding(IMethod method, Optional<IProgressMonitor> monitor)
throws JavaModelException {
MethodDeclaration methodDeclarationNode = ASTNodeSearchUtil.getMethodDeclarationNode(method,
getCompilationUnit(method.getTypeRoot(),
new SubProgressMonitor(monitor.orElseGet(NullProgressMonitor::new), IProgressMonitor.UNKNOWN)));
if (methodDeclarationNode != null)
return methodDeclarationNode.resolveBinding();
else
return null;
}
/**
* Check that return types are compatible between the source and target
* methods.
*
* @param sourceMethod
* The method to check.
* @param monitor
* Optional progress monitor.
* @return {@link RefactoringStatus} indicating the result of the check.
* @throws JavaModelException
*/
private RefactoringStatus checkReturnType(IMethod sourceMethod, Optional<IProgressMonitor> monitor)
throws JavaModelException {
RefactoringStatus status = new RefactoringStatus();
monitor.ifPresent(m -> m.beginTask(RefactoringCoreMessages.PullUpRefactoring_checking, 4));
try {
IMethod targetMethod = getTargetMethod(sourceMethod, monitor.map(m -> new SubProgressMonitor(m, 1)));
String sourceMethodReturnType = Util.getQualifiedNameFromTypeSignature(sourceMethod.getReturnType(),
sourceMethod.getDeclaringType());
String targetMethodReturnType = Util.getQualifiedNameFromTypeSignature(targetMethod.getReturnType(),
targetMethod.getDeclaringType());
if (!sourceMethodReturnType.equals(targetMethodReturnType)) {
addErrorAndMark(status, PreconditionFailure.IncompatibleMethodReturnTypes, sourceMethod, targetMethod);
monitor.ifPresent(m -> m.worked(3));
} else {
monitor.ifPresent(m -> m.worked(1));
// check generics #160.
ITypeBinding sourceMethodReturnTypeBinding = resolveReturnTypeBinding(sourceMethod, Optional.empty());
ITypeBinding[] sourceMethodReturnTypeTypeArguments = sourceMethodReturnTypeBinding.getTypeArguments();
if (sourceMethodReturnTypeTypeArguments.length > 0) {
// type arguments exist in the return type of the source
// method.
ITypeBinding targetMethodReturnTypeBinding = resolveReturnTypeBinding(targetMethod,
Optional.empty());
ITypeBinding[] targetMethodReturnTypeTypeArguments = targetMethodReturnTypeBinding
.getTypeArguments();
// are the type arguments the same length?
if (sourceMethodReturnTypeTypeArguments.length != targetMethodReturnTypeTypeArguments.length) {
addErrorAndMark(status, PreconditionFailure.IncompatibleMethodReturnTypes, sourceMethod,
targetMethod);
monitor.ifPresent(m -> m.worked(2));
} else {
monitor.ifPresent(m -> m.worked(1));
// are the type arguments compatible?
for (int i = 0; i < sourceMethodReturnTypeTypeArguments.length; i++) {
if (!typeArgumentsAreTypeVariables(sourceMethodReturnTypeTypeArguments[i],
targetMethodReturnTypeTypeArguments[i])) {
// then, we should check their assignment
// compatibility.
if (!isAssignmentCompatible(sourceMethodReturnTypeTypeArguments[i],
targetMethodReturnTypeTypeArguments[i])) {
addErrorAndMark(status, PreconditionFailure.IncompatibleMethodReturnTypes,
sourceMethod, targetMethod);
break;
}
}
monitor.ifPresent(m -> m.worked(1));
}
}
}
}
} finally {
monitor.ifPresent(IProgressMonitor::done);
}
return status;
}
private boolean typeArgumentsAreTypeVariables(ITypeBinding typeArgument, ITypeBinding otherTypeArgument) {
return typeArgument.isTypeVariable() && otherTypeArgument.isTypeVariable();
}
private static boolean isAssignmentCompatible(ITypeBinding typeBinding, ITypeBinding otherTypeBinding) {
// Workaround
if (typeBinding == null && otherTypeBinding == null)
return true;
else if (typeBinding == null || otherTypeBinding == null)
return false;
else
return typeBinding.isAssignmentCompatible(otherTypeBinding) || typeBinding.isInterface()
&& otherTypeBinding.isInterface() && (typeBinding.isEqualTo(otherTypeBinding) || Arrays
.stream(typeBinding.getInterfaces()).anyMatch(itb -> itb.isEqualTo(otherTypeBinding)));
}
private ITypeBinding resolveReturnTypeBinding(IMethod method, Optional<IProgressMonitor> monitor)
throws JavaModelException {
MethodDeclaration methodDeclarationNode = ASTNodeSearchUtil.getMethodDeclarationNode(method,
getCompilationUnit(method.getTypeRoot(),
new SubProgressMonitor(monitor.orElseGet(NullProgressMonitor::new), IProgressMonitor.UNKNOWN)));
if (methodDeclarationNode != null) {
Type returnType = methodDeclarationNode.getReturnType2();
return returnType.resolveBinding();
} else
return null;
}
private RefactoringStatus checkStructure(IMember member) throws JavaModelException {
if (!member.isStructureKnown()) {
return RefactoringStatus.createErrorStatus(
MessageFormat.format(Messages.CUContainsCompileErrors, getElementLabel(member, ALL_FULLY_QUALIFIED),
getElementLabel(member.getCompilationUnit(), ALL_FULLY_QUALIFIED)),
JavaStatusContext.create(member.getCompilationUnit()));
}
return new RefactoringStatus();
}
private static RefactoringStatusEntry getLastRefactoringStatusEntry(RefactoringStatus status) {
return status.getEntryAt(status.getEntries().length - 1);
}
private RefactoringStatus checkWritabilitiy(IMember member, PreconditionFailure failure) {
if (member.isBinary() || member.isReadOnly()) {
return createError(failure, member);
}
return new RefactoringStatus();
}
private RefactoringStatus checkExistence(IMember member, PreconditionFailure failure) {
if (member == null || !member.exists()) {
return createError(failure, member);
}
return new RefactoringStatus();
}
public Set<IMethod> getSourceMethods() {
return this.sourceMethods;
}
public Set<IMethod> getUnmigratableMethods() {
return this.unmigratableMethods;
}
private RefactoringStatus checkSourceMethodBodies(Optional<IProgressMonitor> pm) throws JavaModelException {
try {
RefactoringStatus status = new RefactoringStatus();
pm.ifPresent(m -> m.beginTask("Checking source method bodies ...", this.getSourceMethods().size()));
Iterator<IMethod> it = this.getSourceMethods().iterator();
while (it.hasNext()) {
IMethod sourceMethod = it.next();
MethodDeclaration declaration = getMethodDeclaration(sourceMethod, pm);
if (declaration != null) {
Block body = declaration.getBody();
if (body != null) {
SourceMethodBodyAnalysisVisitor visitor = new SourceMethodBodyAnalysisVisitor(sourceMethod, pm);
body.accept(visitor);
if (visitor.doesMethodContainsSuperReference())
addErrorAndMark(status, PreconditionFailure.MethodContainsSuperReference, sourceMethod);
if (visitor.doesMethodContainsCallToProtectedObjectMethod())
addErrorAndMark(status, PreconditionFailure.MethodContainsCallToProtectedObjectMethod,
sourceMethod,
visitor.getCalledProtectedObjectMethodSet().stream().findAny().orElseThrow(
() -> new IllegalStateException("No associated object method")));
if (visitor.doesMethodContainsTypeIncompatibleThisReference()) {
// FIXME: The error context should be the this
// reference that caused the error.
addErrorAndMark(status, PreconditionFailure.MethodContainsTypeIncompatibleThisReference,
sourceMethod);
}
if (sourceMethod.getDeclaringType().isMember()
&& visitor.doesMethodContainQualifiedThisExpression()) {
// FIXME: The error context should be the this
// reference that caused the error.
addErrorAndMark(status, PreconditionFailure.MethodContainsQualifiedThisExpression,
sourceMethod);
}
}
}
pm.ifPresent(m -> m.worked(1));
}
return status;
} finally {
pm.ifPresent(IProgressMonitor::done);
}
}
private MethodDeclaration getMethodDeclaration(IMethod method, Optional<IProgressMonitor> pm)
throws JavaModelException {
ITypeRoot root = method.getCompilationUnit();
CompilationUnit unit = this.getCompilationUnit(root,
new SubProgressMonitor(pm.orElseGet(NullProgressMonitor::new), IProgressMonitor.UNKNOWN));
MethodDeclaration declaration = ASTNodeSearchUtil.getMethodDeclarationNode(method, unit);
return declaration;
}
private static void addWarning(RefactoringStatus status, IMethod sourceMethod, PreconditionFailure failure,
IJavaElement... relatedElementCollection) {
addEntry(status, sourceMethod, RefactoringStatus.WARNING, failure, relatedElementCollection);
}
private static RefactoringStatusEntry addError(RefactoringStatus status, IMethod sourceMethod,
PreconditionFailure failure, IJavaElement... relatedElementCollection) {
addEntry(status, sourceMethod, RefactoringStatus.ERROR, failure, relatedElementCollection);
return getLastRefactoringStatusEntry(status);
}
private static void addEntry(RefactoringStatus status, IMethod sourceMethod, int severity,
PreconditionFailure failure, IJavaElement... relatedElementCollection) {
String message = formatMessage(failure.getMessage(), relatedElementCollection);
// add the first element as the context if appropriate.
if (relatedElementCollection.length > 0 && relatedElementCollection[0] instanceof IMember) {
IMember member = (IMember) relatedElementCollection[0];
RefactoringStatusContext context = JavaStatusContext.create(member);
status.addEntry(new RefactoringStatusEntry(severity, message, context,
MigrateSkeletalImplementationToInterfaceRefactoringDescriptor.REFACTORING_ID, failure.ordinal(),
sourceMethod));
} else // otherwise, just add the message.
status.addEntry(new RefactoringStatusEntry(severity, message, null,
MigrateSkeletalImplementationToInterfaceRefactoringDescriptor.REFACTORING_ID, failure.ordinal(),
sourceMethod));
}
private static String formatMessage(String message, IJavaElement... relatedElementCollection) {
Object[] elementNames = Arrays.stream(relatedElementCollection).parallel().filter(Objects::nonNull)
.map(re -> getElementLabel(re, ALL_FULLY_QUALIFIED)).toArray();
message = MessageFormat.format(message, elementNames);
return message;
}
private static RefactoringStatusEntry addError(RefactoringStatus status, IMethod sourceMethod,
PreconditionFailure failure, IMember member, IMember... more) {
List<String> elementNames = new ArrayList<>();
elementNames.add(getElementLabel(member, ALL_FULLY_QUALIFIED));
Stream<String> stream = Arrays.asList(more).parallelStream().map(m -> getElementLabel(m, ALL_FULLY_QUALIFIED));
Stream<String> concat = Stream.concat(elementNames.stream(), stream);
List<String> collect = concat.collect(Collectors.toList());
status.addEntry(RefactoringStatus.ERROR, MessageFormat.format(failure.getMessage(), collect.toArray()),
JavaStatusContext.create(member),
MigrateSkeletalImplementationToInterfaceRefactoringDescriptor.REFACTORING_ID, failure.ordinal(),
sourceMethod);
return getLastRefactoringStatusEntry(status);
}
private static RefactoringStatus createWarning(String message, IMember member) {
return createRefactoringStatus(message, member, RefactoringStatus::createWarningStatus);
}
private RefactoringStatus createError(PreconditionFailure failure, IMember member) {
return createRefactoringStatus(failure.getMessage(), member, RefactoringStatus::createErrorStatus);
}
private static RefactoringStatus createFatalError(String message, IMember member) {
return createRefactoringStatus(message, member, RefactoringStatus::createFatalErrorStatus);
}
private static RefactoringStatus createRefactoringStatus(String message, IMember member,
BiFunction<String, RefactoringStatusContext, RefactoringStatus> function) {
String elementName = getElementLabel(member, ALL_FULLY_QUALIFIED);
return function.apply(MessageFormat.format(message, elementName), JavaStatusContext.create(member));
}
/**
* Creates a working copy layer if necessary.
*
* @param monitor
* the progress monitor to use
* @return a status describing the outcome of the operation
*/
private RefactoringStatus createWorkingCopyLayer(IProgressMonitor monitor) {
try {
monitor.beginTask(Messages.CheckingPreconditions, 1);
// TODO ICompilationUnit unit =
// getDeclaringType().getCompilationUnit();
// if (fLayer)
// unit = unit.findWorkingCopy(fOwner);
// resetWorkingCopies(unit);
return new RefactoringStatus();
} finally {
monitor.done();
}
}
@Override
public RefactoringStatus checkFinalConditions(final IProgressMonitor monitor, final CheckConditionsContext context)
throws CoreException, OperationCanceledException {
try {
monitor.beginTask(Messages.CheckingPreconditions, 12);
final RefactoringStatus status = new RefactoringStatus();
if (!this.getSourceMethods().isEmpty())
status.merge(createWorkingCopyLayer(new SubProgressMonitor(monitor, 4)));
if (status.hasFatalError())
return status;
if (monitor.isCanceled())
throw new OperationCanceledException();
status.merge(checkSourceMethods(Optional.of(new SubProgressMonitor(monitor, 1))));
if (status.hasFatalError())
return status;
if (monitor.isCanceled())
throw new OperationCanceledException();
status.merge(checkSourceMethodBodies(Optional.of(new SubProgressMonitor(monitor, 1))));
if (status.hasFatalError())
return status;
if (monitor.isCanceled())
throw new OperationCanceledException();
// TODO: Should this be a separate method?
status.merge(checkDestinationInterfaces(Optional.of(new SubProgressMonitor(monitor, 1))));
if (status.hasFatalError())
return status;
if (monitor.isCanceled())
throw new OperationCanceledException();
status.merge(checkTargetMethods(Optional.of(new SubProgressMonitor(monitor, 1))));
// check if there are any methods left to migrate.
if (this.getUnmigratableMethods().containsAll(this.getSourceMethods()))
// if not, we have a fatal error.
status.addFatalError(Messages.NoMethodsHavePassedThePreconditions);
// TODO:
// Checks.addModifiedFilesToChecker(ResourceUtil.getFiles(fChangeManager.getAllCompilationUnits()),
// context);
return status;
} catch (Exception e) {
JavaPlugin.log(e);
throw e;
} finally {
monitor.done();
}
}
private RefactoringStatus checkTargetMethods(Optional<IProgressMonitor> monitor) throws JavaModelException {
RefactoringStatus status = new RefactoringStatus();
// first, create a map of target methods to their set of migratable
// source methods.
Map<IMethod, Set<IMethod>> targetMethodToMigratableSourceMethodsMap = createTargetMethodToMigratableSourceMethodsMap(
monitor.map(m -> new SubProgressMonitor(m, IProgressMonitor.UNKNOWN)));
monitor.ifPresent(m -> m.beginTask("Checking target methods ...",
targetMethodToMigratableSourceMethodsMap.keySet().size()));
// for each target method.
for (IMethod targetMethod : targetMethodToMigratableSourceMethodsMap.keySet()) {
Set<IMethod> migratableSourceMethods = targetMethodToMigratableSourceMethodsMap.get(targetMethod);
// if the target method is associated with multiple source methods.
if (migratableSourceMethods.size() > 1) {
// we need to decide which of the source methods will be
// migrated and which will not. We'll build equivalence sets to
// see which of the source method bodies are the same. Then,
// we'll pick the largest equivalence set to migrate. That will
// reduce the greatest number of methods in the system. The
// other sets will become unmigratable. Those methods will just
// override the new default method.
// (MakeSet).
Set<Set<IMethod>> equivalenceSets = createEquivalenceSets(migratableSourceMethods);
// merge the sets.
mergeEquivalenceSets(equivalenceSets, monitor);
// find the largest set size.
equivalenceSets.stream().map(s -> s.size()).max(Integer::compareTo)
// find the first set with this size.
.flatMap(size -> equivalenceSets.stream().filter(s -> s.size() == size).findFirst()).ifPresent(
// for all of the methods in the other sets ...
fls -> equivalenceSets.stream().filter(s -> s != fls).flatMap(s -> s.stream())
// mark them as unmigratable.
.forEach(m -> addErrorAndMark(status,
PreconditionFailure.TargetMethodHasMultipleSourceMethods, m,
targetMethod)));
}
monitor.ifPresent(m -> m.worked(1));
}
monitor.ifPresent(IProgressMonitor::done);
return status;
}
private void mergeEquivalenceSets(Set<Set<IMethod>> equivalenceSets, Optional<IProgressMonitor> monitor)
throws JavaModelException {
// A map of methods to their equivalence set.
Map<IMethod, Set<IMethod>> methodToEquivalenceSetMap = new LinkedHashMap<>();
for (Set<IMethod> set : equivalenceSets) {
for (IMethod method : set) {
methodToEquivalenceSetMap.put(method, set);
}
}
monitor.ifPresent(
m -> m.beginTask("Merging method equivalence sets ...", methodToEquivalenceSetMap.keySet().size()));
for (IMethod method : methodToEquivalenceSetMap.keySet()) {
for (IMethod otherMethod : methodToEquivalenceSetMap.keySet()) {
if (method != otherMethod) {
Set<IMethod> methodSet = methodToEquivalenceSetMap.get(method); // Find(method)
Set<IMethod> otherMethodSet = methodToEquivalenceSetMap.get(otherMethod); // Find(otherMethod)
// if they are different sets and the elements are
// equivalent.
if (methodSet != otherMethodSet && isEquivalent(method, otherMethod,
monitor.map(m -> new SubProgressMonitor(m, IProgressMonitor.UNKNOWN)))) {
// Union(Find(method), Find(otherMethod))
methodSet.addAll(otherMethodSet);
equivalenceSets.remove(otherMethodSet);
// update the map.
for (IMethod methodInOtherMethodSet : otherMethodSet) {
methodToEquivalenceSetMap.put(methodInOtherMethodSet, methodSet);
}
}
}
}
monitor.ifPresent(m -> m.worked(1));
}
monitor.ifPresent(IProgressMonitor::done);
}
private boolean isEquivalent(IMethod method, IMethod otherMethod, Optional<IProgressMonitor> monitor)
throws JavaModelException {
monitor.ifPresent(m -> m.beginTask("Checking method equivalence ...", 2));
MethodDeclaration methodDeclaration = this.getMethodDeclaration(method,
monitor.map(m -> new SubProgressMonitor(m, 1)));
MethodDeclaration otherMethodDeclaration = this.getMethodDeclaration(otherMethod,
monitor.map(m -> new SubProgressMonitor(m, 1)));
monitor.ifPresent(IProgressMonitor::done);
Block methodDeclarationBody = methodDeclaration.getBody();
Block otherMethodDeclarationBody = otherMethodDeclaration.getBody();
boolean match = methodDeclarationBody.subtreeMatch(new ASTMatcher(), otherMethodDeclarationBody);
return match;
}
private static Set<Set<IMethod>> createEquivalenceSets(Set<IMethod> migratableSourceMethods) {
Set<Set<IMethod>> ret = new LinkedHashSet<>();
migratableSourceMethods.stream().forEach(m -> {
Set<IMethod> set = new LinkedHashSet<>();
set.add(m);
ret.add(set);
});
return ret;
}
private Map<IMethod, Set<IMethod>> createTargetMethodToMigratableSourceMethodsMap(
Optional<IProgressMonitor> monitor) throws JavaModelException {
Map<IMethod, Set<IMethod>> ret = new LinkedHashMap<>();
Set<IMethod> migratableMethods = this.getMigratableMethods();
monitor.ifPresent(m -> m.beginTask("Finding migratable source methods for each target method ...",
migratableMethods.size()));
for (IMethod sourceMethod : migratableMethods) {
IMethod targetMethod = getTargetMethod(sourceMethod, Optional.empty());
ret.compute(targetMethod, (k, v) -> {
if (v == null) {
Set<IMethod> sourceMethodSet = new LinkedHashSet<>();
sourceMethodSet.add(sourceMethod);
return sourceMethodSet;
} else {
v.add(sourceMethod);
return v;
}
});
monitor.ifPresent(m -> m.worked(1));
}
monitor.ifPresent(IProgressMonitor::done);
return ret;
}
private void clearCaches() {
getTypeToSuperTypeHierarchyMap().clear();
getMethodToTargetMethodMap().clear();
getTypeToTypeHierarchyMap().clear();
getCompilationUnitToCompilationUnitRewriteMap().clear();
}
public TimeCollector getExcludedTimeCollector() {
return excludedTimeCollector;
}
private RefactoringStatus checkProjectCompliance(IMethod sourceMethod) throws JavaModelException {
RefactoringStatus status = new RefactoringStatus();
IMethod targetMethod = getTargetMethod(sourceMethod, Optional.empty());
IJavaProject destinationProject = targetMethod.getJavaProject();
if (!JavaModelUtil.is18OrHigher(destinationProject))
addErrorAndMark(status, PreconditionFailure.DestinationProjectIncompatible, sourceMethod, targetMethod);
return status;
}
@Override
public Change createChange(IProgressMonitor pm) throws CoreException, OperationCanceledException {
try {
pm.beginTask(Messages.CreatingChange, 1);
final TextEditBasedChangeManager manager = new TextEditBasedChangeManager();
Set<IMethod> migratableMethods = this.getMigratableMethods();
if (migratableMethods.isEmpty())
return new NullChange(Messages.NoMethodsToMigrate);
// the set of target methods that we transformed to default methods.
Set<IMethod> transformedTargetMethods = new HashSet<>(migratableMethods.size());
for (IMethod sourceMethod : migratableMethods) {
// get the source method declaration.
CompilationUnit sourceCompilationUnit = getCompilationUnit(sourceMethod.getTypeRoot(), pm);
MethodDeclaration sourceMethodDeclaration = ASTNodeSearchUtil.getMethodDeclarationNode(sourceMethod,
sourceCompilationUnit);
logInfo("Source method declaration: " + sourceMethodDeclaration);
CompilationUnitRewrite sourceRewrite = getCompilationUnitRewrite(sourceMethod.getCompilationUnit(),
sourceCompilationUnit);
// Find the target method.
IMethod targetMethod = getTargetMethod(sourceMethod,
Optional.of(new SubProgressMonitor(pm, IProgressMonitor.UNKNOWN)));
// if we have not already transformed this method
if (!transformedTargetMethods.contains(targetMethod)) {
IType destinationInterface = targetMethod.getDeclaringType();
logInfo("Migrating method: " + getElementLabel(sourceMethod, ALL_FULLY_QUALIFIED)
+ " to interface: " + destinationInterface.getFullyQualifiedName());
CompilationUnit destinationCompilationUnit = this
.getCompilationUnit(destinationInterface.getTypeRoot(), pm);
CompilationUnitRewrite destinationCompilationUnitRewrite = getCompilationUnitRewrite(
targetMethod.getCompilationUnit(), destinationCompilationUnit);
ImportRewriteContext context = new ContextSensitiveImportRewriteContext(destinationCompilationUnit,
destinationCompilationUnitRewrite.getImportRewrite());
MethodDeclaration targetMethodDeclaration = ASTNodeSearchUtil.getMethodDeclarationNode(targetMethod,
destinationCompilationUnit);
final TypeVariableMaplet[] mapping = TypeVariableUtil.subTypeToSuperType(
sourceMethod.getDeclaringType(), targetMethod.getDeclaringType(),
targetMethod.getDeclaringType());
// tack on the source method body to the target method.
pm.beginTask("Copying source method body ...", IProgressMonitor.UNKNOWN);
copyMethodBody(sourceRewrite, destinationCompilationUnitRewrite, sourceMethod,
sourceMethodDeclaration, targetMethodDeclaration, mapping,
new SubProgressMonitor(pm, IProgressMonitor.UNKNOWN));
// add any static imports needed to the target method's
// compilation unit for static fields referenced in the
// source method.
addStaticImports(sourceMethodDeclaration, targetMethodDeclaration,
destinationCompilationUnitRewrite, context);
// alter the target parameter names to match that of the
// source method if necessary #148.
changeTargetMethodParametersToMatchSource(sourceMethodDeclaration, targetMethodDeclaration,
destinationCompilationUnitRewrite.getASTRewrite());
// Change the target method to default.
convertToDefault(targetMethodDeclaration, destinationCompilationUnitRewrite.getASTRewrite());
// Remove any abstract modifiers from the target method as
// both abstract and default are not allowed.
removeAbstractness(targetMethodDeclaration, destinationCompilationUnitRewrite.getASTRewrite());
// TODO: Do we need to worry about preserving ordering of
// the
// modifiers?
// if the source method is strictfp.
// FIXME: Actually, I think we need to check that, in the
// case the target method isn't already strictfp, that the
// other
// methods in the hierarchy are.
if ((Flags.isStrictfp(sourceMethod.getFlags())
|| Flags.isStrictfp(sourceMethod.getDeclaringType().getFlags()))
&& !Flags.isStrictfp(targetMethod.getFlags()))
// change the target method to strictfp.
convertToStrictFP(targetMethodDeclaration, destinationCompilationUnitRewrite.getASTRewrite());
// deal with imports
ImportRewriteUtil.addImports(destinationCompilationUnitRewrite, context, sourceMethodDeclaration,
new HashMap<Name, String>(), new HashMap<Name, String>(), false);
transformedTargetMethods.add(targetMethod);
}
// Remove the source method.
removeMethod(sourceMethodDeclaration, sourceRewrite.getASTRewrite());
sourceRewrite.getImportRemover().registerRemovedNode(sourceMethodDeclaration);
}
// save the source changes.
ICompilationUnit[] units = this.getCompilationUnitToCompilationUnitRewriteMap().keySet().stream()
.filter(cu -> !manager.containsChangesIn(cu)).toArray(ICompilationUnit[]::new);
for (ICompilationUnit cu : units) {
CompilationUnit compilationUnit = getCompilationUnit(cu, pm);
manageCompilationUnit(manager, getCompilationUnitRewrite(cu, compilationUnit),
Optional.of(new SubProgressMonitor(pm, IProgressMonitor.UNKNOWN)));
}
final Map<String, String> arguments = new HashMap<>();
int flags = RefactoringDescriptor.STRUCTURAL_CHANGE | RefactoringDescriptor.MULTI_CHANGE;
// TODO: Fill in description.
MigrateSkeletalImplementationToInterfaceRefactoringDescriptor descriptor = new MigrateSkeletalImplementationToInterfaceRefactoringDescriptor(
null, "TODO", null, arguments, flags);
return new DynamicValidationRefactoringChange(descriptor, getProcessorName(), manager.getAllChanges());
} finally {
pm.done();
this.clearCaches();
}
}
/**
* Add any static imports needed to the target method's compilation unit for
* static fields referenced in the source method.
*
* @param sourceMethodDeclaration
* The method being migrated.
* @param targetMethodDeclaration
* The target for the migration.
* @param destinationCompilationUnitRewrite
* The rewrite associated with the target's compilation unit.
* @param context
* The context in which to add static imports if necessary.
*/
private void addStaticImports(MethodDeclaration sourceMethodDeclaration, MethodDeclaration targetMethodDeclaration,
CompilationUnitRewrite destinationCompilationUnitRewrite, ImportRewriteContext context) {
sourceMethodDeclaration.accept(new ASTVisitor() {
@Override
public boolean visit(SimpleName node) {
// add any necessary static imports.
if (node.getParent().getNodeType() != ASTNode.QUALIFIED_NAME) {
IBinding binding = node.resolveBinding();
if (binding.getKind() == IBinding.VARIABLE) {
IVariableBinding variableBinding = ((IVariableBinding) binding);
if (variableBinding.isField()) {
ITypeBinding declaringClass = variableBinding.getDeclaringClass();
processStaticImport(variableBinding, declaringClass, targetMethodDeclaration,
destinationCompilationUnitRewrite, context);
}
}
}
return super.visit(node);
}
private void processStaticImport(IBinding binding, ITypeBinding declaringClass,
MethodDeclaration targetMethodDeclaration, CompilationUnitRewrite destinationCompilationUnitRewrite,
ImportRewriteContext context) {
if (Modifier.isStatic(binding.getModifiers())
&& !declaringClass.isEqualTo(targetMethodDeclaration.resolveBinding().getDeclaringClass()))
destinationCompilationUnitRewrite.getImportRewrite().addStaticImport(binding, context);
}
@Override
public boolean visit(MethodInvocation node) {
if (node.getExpression() == null) { // it's an
// unqualified
// method call.
IMethodBinding methodBinding = node.resolveMethodBinding();
ITypeBinding declaringClass = methodBinding.getDeclaringClass();
processStaticImport(methodBinding, declaringClass, targetMethodDeclaration,
destinationCompilationUnitRewrite, context);
}
return super.visit(node);
}
});
}
private CompilationUnit getCompilationUnit(ITypeRoot root, IProgressMonitor pm) {
CompilationUnit compilationUnit = this.typeRootToCompilationUnitMap.get(root);
if (compilationUnit == null) {
this.getExcludedTimeCollector().start();
compilationUnit = RefactoringASTParser.parseWithASTProvider(root, true, pm);
this.getExcludedTimeCollector().stop();
this.typeRootToCompilationUnitMap.put(root, compilationUnit);
}
return compilationUnit;
}
private CompilationUnitRewrite getCompilationUnitRewrite(ICompilationUnit unit, CompilationUnit root) {
CompilationUnitRewrite rewrite = this.getCompilationUnitToCompilationUnitRewriteMap().get(unit);
if (rewrite == null) {
rewrite = new CompilationUnitRewrite(unit, root);
this.getCompilationUnitToCompilationUnitRewriteMap().put(unit, rewrite);
}
return rewrite;
}
private void manageCompilationUnit(final TextEditBasedChangeManager manager, CompilationUnitRewrite rewrite,
Optional<IProgressMonitor> monitor) throws CoreException {
monitor.ifPresent(m -> m.beginTask("Creating change ...", IProgressMonitor.UNKNOWN));
CompilationUnitChange change = rewrite.createChange(false, monitor.orElseGet(NullProgressMonitor::new));
change.setTextType("java");
manager.manage(rewrite.getCu(), change);
}
private void changeTargetMethodParametersToMatchSource(MethodDeclaration sourceMethodDeclaration,
MethodDeclaration targetMethodDeclaration, ASTRewrite destinationRewrite) {
Assert.isLegal(sourceMethodDeclaration.parameters().size() == targetMethodDeclaration.parameters().size());
// iterate over the source method parameters.
for (int i = 0; i < sourceMethodDeclaration.parameters().size(); i++) {
// get the parameter for the source method.
SingleVariableDeclaration sourceParameter = (SingleVariableDeclaration) sourceMethodDeclaration.parameters()
.get(i);
// get the corresponding target method parameter.
SingleVariableDeclaration targetParameter = (SingleVariableDeclaration) targetMethodDeclaration.parameters()
.get(i);
// if the names don't match.
if (!sourceParameter.getName().equals(targetParameter.getName())) {
// change the target method parameter to match it since that is
// what the body will use.
ASTNode sourceParameterNameCopy = ASTNode.copySubtree(destinationRewrite.getAST(),
sourceParameter.getName());
destinationRewrite.replace(targetParameter.getName(), sourceParameterNameCopy, null);
}
}
}
private void copyMethodBody(final CompilationUnitRewrite sourceRewrite, final CompilationUnitRewrite targetRewrite,
final IMethod method, final MethodDeclaration oldMethod, final MethodDeclaration newMethod,
final TypeVariableMaplet[] mapping, final IProgressMonitor monitor) throws JavaModelException {
final Block body = oldMethod.getBody();
if (body == null) {
newMethod.setBody(null);
return;
}
try {
final IDocument document = new Document(method.getCompilationUnit().getBuffer().getContents());
final ASTRewrite rewrite = ASTRewrite.create(body.getAST());
final ITrackedNodePosition position = rewrite.track(body);
body.accept(new TypeVariableMapper(rewrite, mapping));
rewrite.rewriteAST(document, method.getJavaProject().getOptions(true)).apply(document, TextEdit.NONE);
String content = document.get(position.getStartPosition(), position.getLength());
final String[] lines = Strings.convertIntoLines(content);
Strings.trimIndentation(lines, method.getJavaProject(), false);
content = Strings.concatenate(lines, StubUtility.getLineDelimiterUsed(method));
ASTNode stringPlaceholder = targetRewrite.getASTRewrite().createStringPlaceholder(content, ASTNode.BLOCK);
targetRewrite.getASTRewrite().set(newMethod, MethodDeclaration.BODY_PROPERTY, stringPlaceholder, null);
} catch (MalformedTreeException exception) {
JavaPlugin.log(exception);
} catch (BadLocationException exception) {
JavaPlugin.log(exception);
}
}
private void removeMethod(MethodDeclaration methodDeclaration, ASTRewrite rewrite) {
// TODO: Do we need an edit group??
rewrite.remove(methodDeclaration, null);
}
private void convertToDefault(MethodDeclaration methodDeclaration, ASTRewrite rewrite) {
addModifierKeyword(methodDeclaration, ModifierKeyword.DEFAULT_KEYWORD, rewrite);
}
private void removeAbstractness(MethodDeclaration methodDeclaration, ASTRewrite rewrite) {
removeModifierKeyword(methodDeclaration, ModifierKeyword.ABSTRACT_KEYWORD, rewrite);
}
private void convertToStrictFP(MethodDeclaration methodDeclaration, ASTRewrite rewrite) {
addModifierKeyword(methodDeclaration, ModifierKeyword.STRICTFP_KEYWORD, rewrite);
}
private void addModifierKeyword(MethodDeclaration methodDeclaration, ModifierKeyword modifierKeyword,
ASTRewrite rewrite) {
Modifier modifier = rewrite.getAST().newModifier(modifierKeyword);
ListRewrite listRewrite = rewrite.getListRewrite(methodDeclaration, methodDeclaration.getModifiersProperty());
listRewrite.insertLast(modifier, null);
}
@SuppressWarnings("unchecked")
private void removeModifierKeyword(MethodDeclaration methodDeclaration, ModifierKeyword modifierKeyword,
ASTRewrite rewrite) {
ListRewrite listRewrite = rewrite.getListRewrite(methodDeclaration, methodDeclaration.getModifiersProperty());
listRewrite.getOriginalList().stream().filter(o -> o instanceof Modifier).map(Modifier.class::cast)
.filter(m -> ((Modifier) m).getKeyword().equals(modifierKeyword)).findAny()
.ifPresent(m -> listRewrite.remove((ASTNode) m, null));
}
private static Map<IMethod, IMethod> getMethodToTargetMethodMap() {
return methodToTargetMethodMap;
}
/**
* Finds the target (interface) method declaration in the destination
* interface for the given source method.
*
* TODO: Something is very wrong here. There can be multiple targets for a
* given source method because it can be declared in multiple interfaces up
* and down the hierarchy. What this method right now is really doing is
* finding the target method for the given source method in the destination
* interface. As such, we should be sure what the destination is prior to
* this call.
*
* @param sourceMethod
* The method that will be migrated to the target interface.
* @return The target method that will be manipulated or null if not found.
* @throws JavaModelException
*/
public static IMethod getTargetMethod(IMethod sourceMethod, Optional<IProgressMonitor> monitor)
throws JavaModelException {
IMethod targetMethod = getMethodToTargetMethodMap().get(sourceMethod);
if (targetMethod == null) {
IType destinationInterface = getDestinationInterface(sourceMethod, monitor);
if (getMethodTargetInterfaceTargetMethodTable().contains(sourceMethod, destinationInterface))
targetMethod = getMethodTargetInterfaceTargetMethodTable().get(sourceMethod, destinationInterface);
else if (destinationInterface != null) {
targetMethod = findTargetMethod(sourceMethod, destinationInterface);
if (targetMethod == null)
logWarning("Could not retrieve target method for source method: " + sourceMethod
+ " and destination interface: " + destinationInterface);
else
getMethodTargetInterfaceTargetMethodTable().put(sourceMethod, destinationInterface, targetMethod);
}
getMethodToTargetMethodMap().put(sourceMethod, targetMethod);
}
return targetMethod;
}
private static IType getDestinationInterface(IMethod sourceMethod, Optional<IProgressMonitor> monitor)
throws JavaModelException {
try {
IType[] candidateDestinationInterfaces = getCandidateDestinationInterfaces(sourceMethod,
monitor.map(m -> new SubProgressMonitor(m, 1)));
// FIXME: Really just returning the first match here
return Arrays.stream(candidateDestinationInterfaces).findFirst().orElse(null);
} finally {
monitor.ifPresent(IProgressMonitor::done);
}
}
/**
* Finds the target (interface) method declaration in the given type for the
* given source method.
*
* @param sourceMethod
* The method that will be migrated to the target interface.
* @param targetInterface
* The interface for which sourceMethod will be migrated.
* @return The target method that will be manipulated or null if not found.
* @throws JavaModelException
*/
private static IMethod findTargetMethod(IMethod sourceMethod, IType targetInterface) throws JavaModelException {
if (targetInterface == null)
return null; // not found.
Assert.isNotNull(sourceMethod);
Assert.isLegal(sourceMethod.exists(), "Source method does not exist.");
Assert.isLegal(targetInterface.exists(), "Target interface does not exist.");
Assert.isLegal(targetInterface.isInterface(), "Target interface must be an interface.");
IMethod ret = null;
for (IMethod method : targetInterface.getMethods()) {
if (method.exists() && method.getElementName().equals(sourceMethod.getElementName())) {
ILocalVariable[] parameters = method.getParameters();
ILocalVariable[] sourceParameters = sourceMethod.getParameters();
if (parameterListMatches(parameters, method, sourceParameters, sourceMethod)) {
if (ret != null)
throw new IllegalStateException("Found multiple matches of method: "
+ sourceMethod.getElementName() + " in interface: " + targetInterface.getElementName());
else
ret = method;
}
}
}
return ret;
}
private static boolean parameterListMatches(ILocalVariable[] parameters, IMethod method,
ILocalVariable[] sourceParameters, IMethod sourceMethod) throws JavaModelException {
if (parameters.length == sourceParameters.length) {
for (int i = 0; i < parameters.length; i++) {
String paramString = Util.getQualifiedNameFromTypeSignature(parameters[i].getTypeSignature(),
method.getDeclaringType());
String sourceParamString = Util.getQualifiedNameFromTypeSignature(
sourceParameters[i].getTypeSignature(), sourceMethod.getDeclaringType());
if (!paramString.equals(sourceParamString))
return false;
}
return true;
} else
return false;
}
private static void log(int severity, String message) {
if (severity >= getLoggingLevel()) {
String name = FrameworkUtil.getBundle(MigrateSkeletalImplementationToInterfaceRefactoringProcessor.class)
.getSymbolicName();
IStatus status = new Status(severity, name, message);
JavaPlugin.log(status);
}
}
private void logInfo(String message) {
log(IStatus.INFO, message);
}
private static void logWarning(String message) {
log(IStatus.WARNING, message);
}
@Override
public String getIdentifier() {
return MigrateSkeletalImplementationToInterfaceRefactoringDescriptor.REFACTORING_ID;
}
@Override
public String getProcessorName() {
return Messages.Name;
}
@Override
public boolean isApplicable() throws CoreException {
return RefactoringAvailabilityTester.isInterfaceMigrationAvailable(getSourceMethods().parallelStream()
.filter(m -> !this.getUnmigratableMethods().contains(m)).toArray(IMethod[]::new), Optional.empty());
}
/**
* Returns true if the given type is a pure interface, i.e., it is an
* interface but not an annotation.
*
* @param type
* The type to check.
* @return True if the given type is a pure interface and false otherwise.
* @throws JavaModelException
*/
private static boolean isPureInterface(IType type) throws JavaModelException {
return type != null && type.isInterface() && !type.isAnnotation();
}
private Map<IType, ITypeHierarchy> typeToTypeHierarchyMap = new HashMap<>();
private Map<IType, ITypeHierarchy> getTypeToTypeHierarchyMap() {
return typeToTypeHierarchyMap;
}
private ITypeHierarchy getTypeHierarchy(IType type, Optional<IProgressMonitor> monitor) throws JavaModelException {
try {
ITypeHierarchy ret = this.getTypeToTypeHierarchyMap().get(type);
if (ret == null) {
ret = type.newTypeHierarchy(monitor.orElseGet(NullProgressMonitor::new));
this.getTypeToTypeHierarchyMap().put(type, ret);
}
return ret;
} finally {
monitor.ifPresent(IProgressMonitor::done);
}
}
@Override
public RefactoringParticipant[] loadParticipants(RefactoringStatus status, SharableParticipants sharedParticipants)
throws CoreException {
return new RefactoringParticipant[0];
}
private static Table<IMethod, IType, IMethod> getMethodTargetInterfaceTargetMethodTable() {
return methodTargetInterfaceTargetMethodTable;
}
private SearchEngine getSearchEngine() {
return searchEngine;
}
/**
* Minimum logging level. One of the constants in
* org.eclipse.core.runtime.IStatus.
*
* @param level
* The minimum logging level to set.
* @see org.eclipse.core.runtime.IStatus.
*/
public static void setLoggingLevel(int level) {
loggingLevel = level;
}
protected static int getLoggingLevel() {
return loggingLevel;
}
protected Map<ICompilationUnit, CompilationUnitRewrite> getCompilationUnitToCompilationUnitRewriteMap() {
return this.compilationUnitToCompilationUnitRewriteMap;
}
}
|
package org.xwiki.extension.repository.internal.local;
import java.io.IOException;
import java.io.InputStream;
import java.util.Collection;
import java.util.Collections;
import java.util.Map;
import javax.inject.Inject;
import javax.inject.Singleton;
import org.apache.commons.io.FileUtils;
import org.slf4j.Logger;
import org.xwiki.component.annotation.Component;
import org.xwiki.component.manager.ComponentLookupException;
import org.xwiki.component.manager.ComponentManager;
import org.xwiki.component.phase.Initializable;
import org.xwiki.component.phase.InitializationException;
import org.xwiki.extension.Extension;
import org.xwiki.extension.ExtensionId;
import org.xwiki.extension.ExtensionManagerConfiguration;
import org.xwiki.extension.LocalExtension;
import org.xwiki.extension.ResolveException;
import org.xwiki.extension.repository.DefaultExtensionRepositoryDescriptor;
import org.xwiki.extension.repository.LocalExtensionRepository;
import org.xwiki.extension.repository.LocalExtensionRepositoryException;
import org.xwiki.extension.repository.internal.AbstractCachedExtensionRepository;
/**
* Default implementation of {@link LocalExtensionRepository}.
*
* @version $Id$
* @since 4.0M1
*/
@Component
@Singleton
// TODO: make it threadsafe bulletproofs
public class DefaultLocalExtensionRepository extends AbstractCachedExtensionRepository<DefaultLocalExtension>
implements LocalExtensionRepository, Initializable
{
private static final String ID = "local";
/**
* Used to get repository path.
*/
@Inject
private transient ExtensionManagerConfiguration configuration;
/**
* The logger to log.
*/
@Inject
private transient Logger logger;
/**
* The component manager.
*/
@Inject
private transient ComponentManager componentManager;
/**
* Used to manipulate filesystem repository storage.
*/
private transient LocalExtensionStorage storage;
/**
* Make the repository ignore features.
*/
public DefaultLocalExtensionRepository()
{
super(true);
}
@Override
public void initialize() throws InitializationException
{
try {
this.storage =
new LocalExtensionStorage(this, this.configuration.getLocalRepository(), this.componentManager);
} catch (ComponentLookupException e) {
throw new InitializationException("Failed to intialize local extension storage", e);
}
setDescriptor(new DefaultExtensionRepositoryDescriptor(ID, ID, this.storage.getRootFolder().toURI()));
try {
this.storage.loadExtensions();
} catch (IOException e) {
throw new InitializationException("Failed to load load etensions", e);
}
}
/**
* Register a new local extension.
*
* @param localExtension the new local extension
*/
protected void addLocalExtension(DefaultLocalExtension localExtension)
{
addCachedExtension(localExtension);
}
// LocalRepository
@Override
public LocalExtension getLocalExtension(ExtensionId extensionId)
{
return this.extensions.get(extensionId);
}
@Override
public Collection<LocalExtension> getLocalExtensions()
{
return Collections.<LocalExtension>unmodifiableCollection(this.extensions.values());
}
@Override
public Collection<LocalExtension> getLocalExtensionVersions(String id)
{
Collection<DefaultLocalExtension> versions = this.extensionsVersions.get(id);
return versions != null ? Collections.<LocalExtension>unmodifiableCollection(versions)
: Collections.<LocalExtension>emptyList();
}
/**
* Create a new local extension from a remote extension.
*
* @param extension the extension to copy
* @return the new local extension
*/
private DefaultLocalExtension createExtension(Extension extension)
{
DefaultLocalExtension localExtension = new DefaultLocalExtension(this, extension);
localExtension.setFile(this.storage.getNewExtensionFile(localExtension.getId(), localExtension.getType()));
return localExtension;
}
@Override
public int countExtensions()
{
return this.extensions.size();
}
@Override
public LocalExtension storeExtension(Extension extension) throws LocalExtensionRepositoryException
{
DefaultLocalExtension localExtension = this.extensions.get(extension.getId());
if (localExtension == null) {
try {
localExtension = createExtension(extension);
InputStream is = extension.getFile().openStream();
FileUtils.copyInputStreamToFile(is, localExtension.getFile().getFile());
this.storage.saveDescriptor(localExtension);
// Cache extension
addLocalExtension(localExtension);
} catch (Exception e) {
// TODO: clean
throw new LocalExtensionRepositoryException("Failed to save extension [" + extension + "] descriptor",
e);
}
} else {
throw new LocalExtensionRepositoryException(
"Extension [" + extension + "] already exists in local repository");
}
return localExtension;
}
@Override
public void setProperties(LocalExtension localExtension, Map<String, Object> properties)
throws LocalExtensionRepositoryException
{
DefaultLocalExtension extension = this.extensions.get(localExtension.getId());
if (extension != null) {
extension.setProperties(properties);
try {
this.storage.saveDescriptor(extension);
} catch (Exception e) {
throw new LocalExtensionRepositoryException(
"Failed to save descriptor for extension [" + localExtension + "]", e);
}
}
}
@Override
public void removeExtension(LocalExtension extension) throws ResolveException
{
DefaultLocalExtension localExtension = resolve(extension.getId());
try {
this.storage.removeExtension(localExtension);
} catch (IOException e) {
// Should not happen if the local extension exists
this.logger.error("Failed to remove extension [" + extension + "]", e);
}
// Remove the extension from the caches
removeCachedExtension(localExtension);
}
}
|
package beast.app.beauti;
import java.awt.Component;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import javax.swing.Box;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JOptionPane;
import beast.app.draw.BEASTObjectPanel;
import beast.app.draw.InputEditor;
import beast.app.draw.ListInputEditor;
import beast.app.draw.SmallButton;
import beast.core.BEASTInterface;
import beast.core.Distribution;
import beast.core.Input;
import beast.core.Logger;
import beast.core.State;
import beast.core.StateNode;
import beast.core.parameter.RealParameter;
import beast.core.util.Log;
import beast.evolution.alignment.Taxon;
import beast.evolution.alignment.TaxonSet;
import beast.evolution.tree.Tree;
import beast.evolution.tree.TreeDistribution;
import beast.evolution.tree.TreeInterface;
import beast.math.distributions.MRCAPrior;
import beast.math.distributions.OneOnX;
import beast.math.distributions.Prior;
public class PriorListInputEditor extends ListInputEditor {
private static final long serialVersionUID = 1L;
List<JButton> rangeButtons;
List<JButton> taxonButtons;
public PriorListInputEditor(BeautiDoc doc) {
super(doc);
}
@Override
public Class<?> type() {
return List.class;
}
@Override
public Class<?> baseType() {
return Distribution.class;
}
@Override
public void init(Input<?> input, BEASTInterface beastObject, int itemNr, ExpandOption isExpandOption, boolean addButtons) {
List<?> list = (List<?>) input.get();
Collections.sort(list, (Object o1, Object o2) -> {
if (o1 instanceof BEASTInterface && o2 instanceof BEASTInterface) {
String d1 = ((BEASTInterface)o1).getID();
String id2 = ((BEASTInterface)o2).getID();
// first the tree priors
if (o1 instanceof TreeDistribution) {
if (o2 instanceof TreeDistribution) {
TreeInterface tree1 = ((TreeDistribution)o1).treeInput.get();
if (tree1 == null) {
tree1 = ((TreeDistribution)o1).treeIntervalsInput.get().treeInput.get();
}
TreeInterface tree2 = ((TreeDistribution)o2).treeInput.get();
if (tree2 == null) {
tree2 = ((TreeDistribution)o2).treeIntervalsInput.get().treeInput.get();
}
return d1.compareTo(id2);
} else {
return -1;
}
} else if (o1 instanceof MRCAPrior) {
// last MRCA priors
if (o2 instanceof MRCAPrior) {
return d1.compareTo(id2);
} else {
return 1;
}
} else {
if (o2 instanceof TreeDistribution) {
return 1;
}
if (o2 instanceof MRCAPrior) {
return -1;
}
if (o1 instanceof Prior) {
d1 = ((Prior) o1).getParameterName();
}
if (o2 instanceof Prior) {
id2 = ((Prior) o2).getParameterName();
}
return d1.compareTo(id2);
}
}
return 0;
}
);
rangeButtons = new ArrayList<>();
taxonButtons = new ArrayList<>();
//m_buttonStatus = ButtonStatus.NONE;
super.init(input, beastObject, itemNr, isExpandOption, addButtons);
if (beastObject instanceof BeautiPanelConfig) {
BeautiPanelConfig config = (BeautiPanelConfig) beastObject;
if (config.parentBEASTObjects != null && config.parentBEASTObjects.size() > 0 && config.parentBEASTObjects.get(0).getID().equals("speciescoalescent")) {
m_buttonStatus = ButtonStatus.NONE;
}
}
if (m_buttonStatus == ButtonStatus.ALL || m_buttonStatus == ButtonStatus.ADD_ONLY) {
addButton = new SmallButton("+", true);
addButton.setName("addItem");
addButton.setToolTipText("Add item to the list");
addButton.addActionListener(e -> {
addItem();
});
buttonBox.add(addButton);
buttonBox.add(Box.createHorizontalGlue());
}
}
/**
* add components to box that are specific for the beastObject.
* By default, this just inserts a label with the beastObject ID
*
* @param itemBox box to add components to
* @param beastObject beastObject to add
*/
@Override
protected InputEditor addPluginItem(Box itemBox, BEASTInterface beastObject) {
try {
int listItemNr = ((List<?>) m_input.get()).indexOf(beastObject);
InputEditor editor = doc.getInputEditorFactory().createInputEditor(m_input, listItemNr, beastObject, false, ExpandOption.FALSE, ButtonStatus.NONE, null, doc);
itemBox.add((Component) editor);
return editor;
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return this;
}
String paramToString(RealParameter p) {
Double lower = p.lowerValueInput.get();
Double upper = p.upperValueInput.get();
return "initial = " + p.valuesInput.get() +
" [" + (lower == null ? "-\u221E" : lower + "") +
"," + (upper == null ? "\u221E" : upper + "") + "]";
}
Set<Taxon> getTaxonCandidates(MRCAPrior prior) {
Set<Taxon> candidates = new HashSet<>();
Tree tree = prior.treeInput.get();
String [] taxa = null;
if (tree.m_taxonset.get() != null) {
try {
TaxonSet set = tree.m_taxonset.get();
set.initAndValidate();
taxa = set.asStringList().toArray(new String[0]);
} catch (Exception e) {
taxa = prior.treeInput.get().getTaxaNames();
}
} else {
taxa = prior.treeInput.get().getTaxaNames();
}
for (String taxon : taxa) {
candidates.add(doc.getTaxon(taxon));
}
return candidates;
}
/**
* class to deal with toggling monophyletic flag on an MRCAPrior *
*/
class MRCAPriorActionListener implements ActionListener {
MRCAPrior m_prior;
MRCAPriorActionListener(MRCAPrior prior) {
m_prior = prior;
}
@Override
public void actionPerformed(ActionEvent e) {
try {
m_prior.isMonophyleticInput.setValue(((JCheckBox) e.getSource()).isSelected(), m_prior);
refreshPanel();
} catch (Exception ex) {
Log.err.println("PriorListInputEditor " + ex.getMessage());
}
}
}
@Override
protected void addItem() {
super.addItem();
sync();
refreshPanel();
} // addItem
@Override
protected List<BEASTInterface> pluginSelector(Input<?> input, BEASTInterface parent, List<String> tabooList) {
MRCAPrior prior = new MRCAPrior();
try {
List<Tree> trees = new ArrayList<>();
getDoc().scrubAll(true, false);
State state = (State) doc.pluginmap.get("state");
for (StateNode node : state.stateNodeInput.get()) {
if (node instanceof Tree) { // && ((Tree) node).m_initial.get() != null) {
trees.add((Tree) node);
}
}
int treeIndex = 0;
if (trees.size() > 1) {
String[] treeIDs = new String[trees.size()];
for (int j = 0; j < treeIDs.length; j++) {
treeIDs[j] = trees.get(j).getID();
}
treeIndex = JOptionPane.showOptionDialog(null, "Select a tree", "MRCA selector",
JOptionPane.OK_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE, null,
treeIDs, trees.get(0));
}
if (treeIndex < 0) {
return null;
}
prior.treeInput.setValue(trees.get(treeIndex), prior);
TaxonSet taxonSet = new TaxonSet();
TaxonSetDialog dlg = new TaxonSetDialog(taxonSet, getTaxonCandidates(prior), doc);
if (!dlg.showDialog() || dlg.taxonSet.getID() == null || dlg.taxonSet.getID().trim().equals("")) {
return null;
}
taxonSet = dlg.taxonSet;
BEASTObjectPanel.addPluginToMap(taxonSet, doc);
prior.taxonsetInput.setValue(taxonSet, prior);
prior.setID(taxonSet.getID() + ".prior");
// this sets up the type
prior.distInput.setValue(new OneOnX(), prior);
// this removes the parametric distribution
prior.distInput.setValue(null, prior);
Logger logger = (Logger) doc.pluginmap.get("tracelog");
logger.loggersInput.setValue(prior, logger);
} catch (Exception e) {
// TODO: handle exception
}
List<BEASTInterface> selectedPlugins = new ArrayList<>();
selectedPlugins.add(prior);
g_collapsedIDs.add(prior.getID());
return selectedPlugins;
}
}
|
package com.backendless.property;
public enum DateTypeEnum
{
UNKNOWN,
INT,
STRING,
BOOLEAN,
DATETIME,
DOUBLE,
RELATION,
COLLECTION,
RELATION_LIST,
STRING_ID,
TEXT,
FILE_REF;
}
|
package org.raku.rakudo;
import java.util.*;
import org.raku.nqp.runtime.*;
import org.raku.nqp.sixmodel.*;
import org.raku.nqp.sixmodel.reprs.ContextRefInstance;
import org.raku.nqp.sixmodel.reprs.P6int;
import org.raku.nqp.sixmodel.reprs.P6str;
import org.raku.nqp.sixmodel.reprs.P6num;
import org.raku.nqp.sixmodel.reprs.P6OpaqueREPRData;
@SuppressWarnings("unused")
public final class Binder {
/* Possible results of binding. */
public static final int BIND_RESULT_OK = 0;
public static final int BIND_RESULT_FAIL = 1;
public static final int BIND_RESULT_JUNCTION = 2;
/* Compile time trial binding result indicators. */
public static final int TRIAL_BIND_NOT_SURE = 0; /* Plausible, but need to check at runtime. */
public static final int TRIAL_BIND_OK = 1; /* Bind will always work out. */
public static final int TRIAL_BIND_NO_WAY = -1; /* Bind could never work out. */
/* Flags. */
private static final int SIG_ELEM_BIND_CAPTURE = 1;
private static final int SIG_ELEM_BIND_PRIVATE_ATTR = 2;
private static final int SIG_ELEM_BIND_PUBLIC_ATTR = 4;
private static final int SIG_ELEM_BIND_ATTRIBUTIVE = (SIG_ELEM_BIND_PRIVATE_ATTR | SIG_ELEM_BIND_PUBLIC_ATTR);
private static final int SIG_ELEM_SLURPY_POS = 8;
private static final int SIG_ELEM_SLURPY_NAMED = 16;
private static final int SIG_ELEM_SLURPY_LOL = 32;
private static final int SIG_ELEM_INVOCANT = 64;
private static final int SIG_ELEM_MULTI_INVOCANT = 128;
private static final int SIG_ELEM_IS_RW = 256;
private static final int SIG_ELEM_IS_COPY = 512;
private static final int SIG_ELEM_IS_RAW = 1024;
private static final int SIG_ELEM_IS_OPTIONAL = 2048;
private static final int SIG_ELEM_ARRAY_SIGIL = 4096;
private static final int SIG_ELEM_HASH_SIGIL = 8192;
private static final int SIG_ELEM_DEFAULT_FROM_OUTER = 16384;
private static final int SIG_ELEM_IS_CAPTURE = 32768;
private static final int SIG_ELEM_UNDEFINED_ONLY = 65536;
private static final int SIG_ELEM_DEFINED_ONLY = 131072;
private static final int SIG_ELEM_DEFINEDNES_CHECK = (SIG_ELEM_UNDEFINED_ONLY | SIG_ELEM_DEFINED_ONLY);
private static final int SIG_ELEM_TYPE_GENERIC = 524288;
private static final int SIG_ELEM_DEFAULT_IS_LITERAL = 1048576;
private static final int SIG_ELEM_NATIVE_INT_VALUE = 2097152;
private static final int SIG_ELEM_NATIVE_NUM_VALUE = 4194304;
private static final int SIG_ELEM_NATIVE_STR_VALUE = 8388608;
private static final int SIG_ELEM_NATIVE_VALUE = (SIG_ELEM_NATIVE_INT_VALUE | SIG_ELEM_NATIVE_NUM_VALUE | SIG_ELEM_NATIVE_STR_VALUE);
private static final int SIG_ELEM_SLURPY_ONEARG = 16777216;
private static final int SIG_ELEM_SLURPY = (SIG_ELEM_SLURPY_POS | SIG_ELEM_SLURPY_NAMED | SIG_ELEM_SLURPY_LOL | SIG_ELEM_SLURPY_ONEARG);
private static final int SIG_ELEM_CODE_SIGIL = 33554432;
private static final int SIG_ELEM_IS_COERCIVE = 67108864;
/* Hints for Parameter attributes. */
private static final int HINT_variable_name = 0;
private static final int HINT_named_names = 1;
private static final int HINT_type_captures = 2;
private static final int HINT_flags = 3;
private static final int HINT_type = 4;
private static final int HINT_post_constraints = 5;
private static final int HINT_sub_signature = 6;
private static final int HINT_default_value = 7;
private static final int HINT_container_descriptor = 8;
private static final int HINT_attr_package = 9;
/* Other hints. */
private static final int HINT_ENUMMAP_storage = 0;
private static final int HINT_CAPTURE_list = 0;
private static final int HINT_CAPTURE_hash = 1;
private static final int HINT_LIST_reified = 0;
private static final int HINT_SIG_params = 0;
private static SixModelObject createBox(ThreadContext tc, RakOps.GlobalExt gcx, Object arg, int flag) {
switch (flag) {
case CallSiteDescriptor.ARG_INT:
return Ops.box_i((long)arg, gcx.Int, tc);
case CallSiteDescriptor.ARG_NUM:
return Ops.box_n((double)arg, gcx.Num, tc);
case CallSiteDescriptor.ARG_STR:
return Ops.box_s((String)arg, gcx.Str, tc);
default:
throw new RuntimeException("Impossible case reached in createBox");
}
}
private static String arityFail(ThreadContext tc, RakOps.GlobalExt gcx, SixModelObject params,
int numParams, int numPosArgs, boolean tooMany) {
int arity = 0;
int count = 0;
String fail = tooMany ? "Too many" : "Too few";
/* Work out how many we could have been passed. */
for (int i = 0; i < numParams; i++) {
SixModelObject param = params.at_pos_boxed(tc, i);
param.get_attribute_native(tc, gcx.Parameter, "$!flags", HINT_flags);
int flags = (int)tc.native_i;
SixModelObject namedNames = param.get_attribute_boxed(tc,
gcx.Parameter, "@!named_names", HINT_named_names);
if (namedNames != null)
continue;
if ((flags & SIG_ELEM_SLURPY_NAMED) != 0)
continue;
if ((flags & SIG_ELEM_SLURPY) != 0) {
count = -1000; // cargo-culted from BOOTSTRAP.nqp: "in case a pos can sneak past a slurpy somehow"
}
else if ((flags & SIG_ELEM_IS_OPTIONAL) != 0) {
count++;
}
else {
count++;
arity++;
}
}
/* Now generate decent error. */
if (arity == count)
return String.format(
"%s positionals passed; expected %d arguments but got %d",
fail, arity, numPosArgs);
else if (count <= -1)
return String.format(
"%s positionals passed; expected at least %d arguments but got only %d",
fail, arity, numPosArgs);
else
return String.format(
"%s positionals passed; expected %d %s %d arguments but got %d",
fail, arity, arity + 1 == count ? "or" : "to" , count, numPosArgs);
}
/* Binds any type captures. */
public static void bindTypeCaptures(ThreadContext tc, SixModelObject typeCaps, CallFrame cf, SixModelObject type) {
long elems = typeCaps.elems(tc);
StaticCodeInfo sci = cf.codeRef.staticInfo;
for (long i = 0; i < elems; i++) {
typeCaps.at_pos_native(tc, i);
String name = tc.native_s;
cf.oLex[sci.oTryGetLexicalIdx(name)] = type;
}
}
/* Assigns an attributive parameter to the desired attribute. */
private static int assignAttributive(ThreadContext tc, CallFrame cf, String varName,
int paramFlags, SixModelObject attrPackage, SixModelObject value, Object[] error) {
/* Find self. */
StaticCodeInfo sci = cf.codeRef.staticInfo;
Integer selfIdx = sci.oTryGetLexicalIdx("self");
SixModelObject self = null;
if (selfIdx == null) {
self = Ops.getlexouter("self", tc);
if (self == null) {
if (error != null)
error[0] = String.format(
"Unable to bind attributive parameter '%s' - could not find self",
varName);
return BIND_RESULT_FAIL;
}
}
else {
self = cf.oLex[selfIdx];
}
/* If it's private, just need to fetch the attribute. */
SixModelObject assignee;
if ((paramFlags & SIG_ELEM_BIND_PRIVATE_ATTR) != 0) {
/* If we have a native Attribute we can't get a container for it, and
since *trying* to get a container would throw already, we first check
if the target Attribute is native. */
int hint = -1;
for (HashMap<String, Integer> map : ((P6OpaqueREPRData) (attrPackage.st.REPRData)).nameToHintMap) {
try {
hint = map.get(varName);
}
catch (Exception e) {
continue;
}
}
REPR attrREPR = null;
if (((P6OpaqueREPRData) (attrPackage.st.REPRData)).flattenedSTables[hint] != null) {
/* We sometimes don't have flattenedSTables. I'm not sure that's okay, honestly... */
attrREPR = ((P6OpaqueREPRData) (attrPackage.st.REPRData)).flattenedSTables[hint].REPR;
}
if (attrREPR instanceof P6int) {
Ops.bindattr_i(self, attrPackage, varName, Ops.unbox_i(value, tc), tc);
}
else if (attrREPR instanceof P6num) {
Ops.bindattr_n(self, attrPackage, varName, Ops.unbox_n(value, tc), tc);
}
else if (attrREPR instanceof P6str) {
Ops.bindattr_s(self, attrPackage, varName, Ops.unbox_s(value, tc), tc);
}
else {
/* ...but we'll just assume it's probably some boxed Attribute. */
assignee = self.get_attribute_boxed(tc, attrPackage, varName, STable.NO_HINT);
RakOps.p6store(assignee, value, tc);
}
}
/* Otherwise if it's public, do a method call to get the assignee. */
else {
throw new RuntimeException("$.x parameters NYI");
}
return BIND_RESULT_OK;
}
/* Returns an appropriate failure mode (junction fail or normal fail). */
private static int juncOrFail(ThreadContext tc, RakOps.GlobalExt gcx, SixModelObject value) {
if (value.st.WHAT == gcx.Junction && Ops.isconcrete(value, tc) != 0)
return BIND_RESULT_JUNCTION;
else
return BIND_RESULT_FAIL;
}
/* Binds a single argument into the lexpad, after doing any checks that are
* needed. Also handles any type captures. If there is a sub signature, then
* re-enters the binder. Returns one of the BIND_RESULT_* codes. */
private static final CallSiteDescriptor genIns = new CallSiteDescriptor(
new byte[] { CallSiteDescriptor.ARG_OBJ, CallSiteDescriptor.ARG_OBJ, CallSiteDescriptor.ARG_OBJ }, null);
private static final CallSiteDescriptor targetType = new CallSiteDescriptor(
new byte[] { CallSiteDescriptor.ARG_OBJ, CallSiteDescriptor.ARG_OBJ }, null);
private static final CallSiteDescriptor ACCEPTS_o = new CallSiteDescriptor(
new byte[] { CallSiteDescriptor.ARG_OBJ, CallSiteDescriptor.ARG_OBJ }, null);
private static final CallSiteDescriptor ACCEPTS_i = new CallSiteDescriptor(
new byte[] { CallSiteDescriptor.ARG_OBJ, CallSiteDescriptor.ARG_INT }, null);
private static final CallSiteDescriptor ACCEPTS_n = new CallSiteDescriptor(
new byte[] { CallSiteDescriptor.ARG_OBJ, CallSiteDescriptor.ARG_NUM }, null);
private static final CallSiteDescriptor ACCEPTS_s = new CallSiteDescriptor(
new byte[] { CallSiteDescriptor.ARG_OBJ, CallSiteDescriptor.ARG_STR }, null);
private static final CallSiteDescriptor bindParamThrower = new CallSiteDescriptor(
new byte[] { CallSiteDescriptor.ARG_OBJ, CallSiteDescriptor.ARG_OBJ,
CallSiteDescriptor.ARG_STR, CallSiteDescriptor.ARG_OBJ,
CallSiteDescriptor.ARG_INT
}, null);
private static final CallSiteDescriptor bindConcreteThrower = new CallSiteDescriptor(
new byte[] { CallSiteDescriptor.ARG_STR, CallSiteDescriptor.ARG_STR,
CallSiteDescriptor.ARG_STR, CallSiteDescriptor.ARG_STR,
CallSiteDescriptor.ARG_INT, CallSiteDescriptor.ARG_INT
}, null);
private static final CallSiteDescriptor paramReadWriteThrower = new CallSiteDescriptor(
new byte[] { CallSiteDescriptor.ARG_OBJ, CallSiteDescriptor.ARG_STR }, null);
private static int bindOneParam(ThreadContext tc, RakOps.GlobalExt gcx, CallFrame cf, SixModelObject param,
Object origArg, byte origFlag, boolean noNomTypeCheck, boolean isSlurpyNamed, Object[] error) {
/* Get parameter flags and variable name. */
param.get_attribute_native(tc, gcx.Parameter, "$!flags", HINT_flags);
int paramFlags = (int)tc.native_i;
param.get_attribute_native(tc, gcx.Parameter, "$!variable_name", HINT_variable_name);
String varName = tc.native_s;
boolean hasVarName = true;
if (varName == null || varName.isEmpty()) {
varName = "<anon>";
hasVarName = false;
}
if (RakOps.DEBUG_MODE)
System.err.println(varName);
/* We'll put the value to bind into one of the following locals, and
* flag will indicate what type of thing it is. */
int flag;
long arg_i = 0;
double arg_n = 0.0;
String arg_s = null;
SixModelObject arg_o = null;
/* Check if boxed/unboxed expectations are met. */
int desiredNative = paramFlags & SIG_ELEM_NATIVE_VALUE;
boolean is_rw = (paramFlags & SIG_ELEM_IS_RW) != 0;
int gotNative = origFlag & (CallSiteDescriptor.ARG_INT | CallSiteDescriptor.ARG_NUM | CallSiteDescriptor.ARG_STR);
if (is_rw && desiredNative != 0) {
switch (desiredNative) {
case SIG_ELEM_NATIVE_INT_VALUE:
if (gotNative != 0 || Ops.iscont_i((SixModelObject)origArg) == 0) {
if (error != null)
error[0] = String.format(
"Expected a modifiable native int argument for '%s'",
varName);
return BIND_RESULT_FAIL;
}
break;
case SIG_ELEM_NATIVE_NUM_VALUE:
if (gotNative != 0 || Ops.iscont_n((SixModelObject)origArg) == 0) {
if (error != null)
error[0] = String.format(
"Expected a modifiable native num argument for '%s'",
varName);
return BIND_RESULT_FAIL;
}
break;
case SIG_ELEM_NATIVE_STR_VALUE:
if (gotNative != 0 || Ops.iscont_s((SixModelObject)origArg) == 0) {
if (error != null)
error[0] = String.format(
"Expected a modifiable native str argument for '%s'",
varName);
return BIND_RESULT_FAIL;
}
break;
}
flag = CallSiteDescriptor.ARG_OBJ;
arg_o = (SixModelObject)origArg;
}
else if (desiredNative == 0 && gotNative == CallSiteDescriptor.ARG_OBJ) {
flag = gotNative;
arg_o = (SixModelObject)origArg;
}
else if (desiredNative == SIG_ELEM_NATIVE_INT_VALUE && gotNative == CallSiteDescriptor.ARG_INT) {
flag = gotNative;
arg_i = (long)origArg;
}
else if (desiredNative == SIG_ELEM_NATIVE_NUM_VALUE && gotNative == CallSiteDescriptor.ARG_NUM) {
flag = gotNative;
arg_n = (double)origArg;
}
else if (desiredNative == SIG_ELEM_NATIVE_STR_VALUE && gotNative == CallSiteDescriptor.ARG_STR) {
flag = gotNative;
arg_s = (String)origArg;
}
else if (desiredNative == 0) {
/* We need to do a boxing operation. */
flag = CallSiteDescriptor.ARG_OBJ;
arg_o = createBox(tc, gcx, origArg, gotNative);
}
else {
/* We need to do an unboxing operation. */
SixModelObject decontValue = Ops.decont((SixModelObject)origArg, tc);
StorageSpec spec = decontValue.st.REPR.get_storage_spec(tc, decontValue.st);
switch (desiredNative) {
case SIG_ELEM_NATIVE_INT_VALUE:
if ((spec.can_box & StorageSpec.CAN_BOX_INT) != 0) {
flag = CallSiteDescriptor.ARG_INT;
arg_i = decontValue.get_int(tc);
}
else {
if (error != null)
error[0] = String.format(
"Cannot unbox argument to '%s' as a native int",
varName);
return BIND_RESULT_FAIL;
}
break;
case SIG_ELEM_NATIVE_NUM_VALUE:
if ((spec.can_box & StorageSpec.CAN_BOX_NUM) != 0) {
flag = CallSiteDescriptor.ARG_NUM;
arg_n = decontValue.get_num(tc);
}
else {
if (error != null)
error[0] = String.format(
"Cannot unbox argument to '%s' as a native num",
varName);
return BIND_RESULT_FAIL;
}
break;
case SIG_ELEM_NATIVE_STR_VALUE:
if ((spec.can_box & StorageSpec.CAN_BOX_STR) != 0) {
flag = CallSiteDescriptor.ARG_STR;
arg_s = decontValue.get_str(tc);
}
else {
if (error != null)
error[0] = String.format(
"Cannot unbox argument to '%s' as a native str",
varName);
return BIND_RESULT_FAIL;
}
break;
default:
if (error != null)
error[0] = String.format(
"Cannot unbox argument to '%s' as a native type",
varName);
return BIND_RESULT_FAIL;
}
}
/* By this point, we'll either have an object that we might be able to
* bind if it passes the type check, or a native value that needs no
* further checking. */
SixModelObject decontValue = null;
boolean didHLLTransform = false;
SixModelObject paramType = param.get_attribute_boxed(tc, gcx.Parameter, "$!type", HINT_type);
SixModelObject ContextRef = null;
SixModelObject HOW = null;
if (flag == CallSiteDescriptor.ARG_OBJ && !(is_rw && desiredNative != 0)) {
/* We need to work on the decontainerized value. */
decontValue = Ops.decont(arg_o, tc);
/* HLL map it as needed. */
SixModelObject beforeHLLize = decontValue;
decontValue = Ops.hllize(decontValue, tc);
if (decontValue != beforeHLLize)
didHLLTransform = true;
/* Skip nominal type check if not needed. */
if (!noNomTypeCheck) {
/* Is the nominal type generic and in need of instantiation? (This
* can happen in (::T, T) where we didn't learn about the type until
* during the signature bind.) */
if ((paramFlags & SIG_ELEM_TYPE_GENERIC) != 0) {
HOW = paramType.st.HOW;
SixModelObject ig = Ops.findmethod(HOW,
"instantiate_generic", tc);
ContextRef = tc.gc.ContextRef;
SixModelObject cc = ContextRef.st.REPR.allocate(tc, ContextRef.st);
((ContextRefInstance)cc).context = cf;
Ops.invokeDirect(tc, ig, genIns,
new Object[] { HOW, paramType, cc });
paramType = Ops.result_o(tc.curFrame);
}
/* If the expected type is Positional, see if we need to do the
* positional bind failover. */
if (paramType == gcx.Positional) {
if (Ops.istype_nd(arg_o, gcx.PositionalBindFailover, tc) != 0) {
SixModelObject ig = Ops.findmethod(arg_o, "cache", tc);
Ops.invokeDirect(tc, ig, Ops.invocantCallSite, new Object[] { arg_o });
arg_o = Ops.result_o(tc.curFrame);
decontValue = Ops.decont(arg_o, tc);
}
else if (Ops.istype_nd(decontValue, gcx.PositionalBindFailover, tc) != 0) {
SixModelObject ig = Ops.findmethod(decontValue, "cache", tc);
Ops.invokeDirect(tc, ig, Ops.invocantCallSite, new Object[] { decontValue });
decontValue = Ops.result_o(tc.curFrame);
}
}
/* If not, do the check. If the wanted nominal type is Mu, then
* anything goes.
* When binding a slurpy named hash while compiling the setting don't check for Associative.
*/
if (paramType != gcx.Mu && !(isSlurpyNamed && paramType == gcx.Associative) && Ops.istype_nd(decontValue, paramType, tc) == 0) {
/* Type check failed; produce error if needed. */
/* Try to figure out the most helpful name for the expected. */
SixModelObject expectedType = null;
SixModelObject postConstraints = param.get_attribute_boxed(tc, gcx.Parameter,
"$!post_contraints", HINT_post_constraints);
if (postConstraints != null) {
SixModelObject consType = postConstraints.at_pos_boxed(tc, 0);
expectedType = (Ops.istype(consType, gcx.Code, tc) != 0)
? paramType.st.WHAT
: consType.st.WHAT;
}
else {
expectedType = paramType.st.WHAT;
}
if (error != null) {
SixModelObject thrower = RakOps.getThrower(tc, "X::TypeCheck::Binding::Parameter");
if (thrower != null) {
error[0] = thrower;
error[1] = bindParamThrower;
error[2] = new Object[] { decontValue, expectedType.st.WHAT,
varName, param, (long)0 };
}
else {
error[0] = String.format(
"Nominal type check failed for parameter '%s'",
varName);
}
}
/* Report junction failure mode if it's a junction. */
return juncOrFail(tc, gcx, decontValue);
}
/* Also enforce definedness check */
if ( (paramFlags & SIG_ELEM_DEFINEDNES_CHECK) != 0) {
/* Don't check decontValue for concreteness though, but arg_o,
seeing as we don't have a isconcrete_nodecont */
Boolean shouldBeConcrete = (paramFlags & SIG_ELEM_DEFINED_ONLY) != 0 && Ops.isconcrete(arg_o, tc) != 1;
if (shouldBeConcrete || ((paramFlags & SIG_ELEM_UNDEFINED_ONLY) != 0 && Ops.isconcrete(arg_o, tc) == 1)) {
if (error != null) {
String typeName = Ops.typeName(param.get_attribute_boxed(tc,
gcx.Parameter, "$!type", HINT_type), tc);
String argName = Ops.typeName(arg_o, tc);
String methodName = cf.codeRef.name;
SixModelObject thrower = RakOps.getThrower(tc, "X::Parameter::InvalidConcreteness");
if (thrower != null) {
error[0] = thrower;
error[1] = bindConcreteThrower;
error[2] = new Object[] { typeName, argName, methodName,
varName, (long)(shouldBeConcrete ? 1 : 0),
(long)(paramFlags & SIG_ELEM_INVOCANT) };
}
else {
if (methodName == null || methodName.isEmpty())
methodName = "<anon>";
error[0] = ((paramFlags & SIG_ELEM_INVOCANT) != 0)
? shouldBeConcrete
? String.format(
"Invocant of method '%s' must be an object instance of type '%s', not a type object of type '%s'. Did you forget a '.new'?",
methodName, typeName, argName)
: String.format(
"Invocant of method '%s' must be a type object of type '%s', not an object instance of type '%s'. Did you forget a 'multi'?",
methodName, typeName, argName)
: shouldBeConcrete
? String.format(
"Parameter '%s' of routine '%s' must be an object instance of type '%s', not a type object of type '%s'. Did you forget a '.new'?",
varName, methodName, typeName, argName)
: String.format(
"Parameter '%s' of routine '%s' must be a type object of type '%s', not an object instance of type '%s'. Did you forget a 'multi'?",
varName, methodName, typeName, argName);
}
}
return juncOrFail(tc, gcx, decontValue);
}
}
}
}
/* Type captures. */
SixModelObject typeCaps = param.get_attribute_boxed(tc, gcx.Parameter,
"@!type_captures", HINT_type_captures);
if (typeCaps != null)
bindTypeCaptures(tc, typeCaps, cf, decontValue.st.WHAT);
/* Do a coercion, if one is needed. */
HOW = paramType.st.HOW;
SixModelObject archetypesMeth = Ops.findmethod(HOW, "archetypes", tc);
Ops.invokeDirect(tc, archetypesMeth, Ops.invocantCallSite, new Object[] { HOW });
SixModelObject Archetypes = Ops.result_o(tc.curFrame);
SixModelObject coerciveMeth = Ops.findmethodNonFatal(Archetypes, "coercive", tc);
if (coerciveMeth != null) {
Ops.invokeDirect(tc, coerciveMeth, Ops.invocantCallSite, new Object[] { Archetypes });
if (Ops.istrue(Ops.result_o(tc.curFrame), tc) == 1) {
/* Coercing natives not possible - nothing to call a method on. */
if (flag != CallSiteDescriptor.ARG_OBJ) {
if (error != null)
error[0] = String.format(
"Unable to coerce natively typed parameter '%s'",
varName);
return BIND_RESULT_FAIL;
}
SixModelObject coerceMeth = Ops.findmethod(HOW, "coerce", tc);
Ops.invokeDirect(tc, coerceMeth, genIns, new Object[] { HOW, paramType, arg_o });
arg_o = Ops.result_o(tc.curFrame);
decontValue = Ops.decont(arg_o, tc);
}
}
/* If it's not got attributive binding, we'll go about binding it into the
* lex pad. */
StaticCodeInfo sci = cf.codeRef.staticInfo;
if ((paramFlags & SIG_ELEM_BIND_ATTRIBUTIVE) == 0) {
/* Is it native? If so, just go ahead and bind it. */
if (flag != CallSiteDescriptor.ARG_OBJ) {
if (hasVarName) {
switch (flag) {
case CallSiteDescriptor.ARG_INT:
cf.iLex[sci.iTryGetLexicalIdx(varName)] = arg_i;
break;
case CallSiteDescriptor.ARG_NUM:
cf.nLex[sci.nTryGetLexicalIdx(varName)] = arg_n;
break;
case CallSiteDescriptor.ARG_STR:
cf.sLex[sci.sTryGetLexicalIdx(varName)] = arg_s;
break;
}
}
}
/* Otherwise it's some objecty case. */
else if (is_rw) {
if (Ops.isrwcont(arg_o, tc) == 1) {
if (hasVarName)
cf.oLex[sci.oTryGetLexicalIdx(varName)] = arg_o;
} else {
SixModelObject thrower = RakOps.getThrower(tc, "X::Parameter::RW");
if (thrower == null) {
error[0] = "Parameter expected a writable container";
} else {
error[0] = thrower;
error[1] = paramReadWriteThrower;
error[2] = new Object[] { decontValue, varName};
}
return BIND_RESULT_FAIL;
}
}
else if (hasVarName) {
if ((paramFlags & SIG_ELEM_IS_RAW) != 0) {
/* Just bind the thing as is into the lexpad. */
cf.oLex[sci.oTryGetLexicalIdx(varName)] = didHLLTransform ? decontValue : arg_o;
}
else {
/* If it's an array, copy means make a new one and store,
* and a normal bind is a straightforward binding plus
* adding a constraint. */
if ((paramFlags & SIG_ELEM_ARRAY_SIGIL) != 0) {
SixModelObject bindee = decontValue;
if ((paramFlags & SIG_ELEM_IS_COPY) != 0) {
SixModelObject BOOTArray = tc.gc.BOOTArray;
bindee = gcx.Array.st.REPR.allocate(tc, gcx.Array.st);
bindee.bind_attribute_boxed(tc, gcx.List, "$!reified",
HINT_LIST_reified, BOOTArray.st.REPR.allocate(tc, BOOTArray.st));
RakOps.p6store(bindee, decontValue, tc);
}
cf.oLex[sci.oTryGetLexicalIdx(varName)] = bindee;
}
/* If it's a hash, similar approach to array. */
else if ((paramFlags & SIG_ELEM_HASH_SIGIL) != 0) {
SixModelObject bindee = decontValue;
if ((paramFlags & SIG_ELEM_IS_COPY) != 0) {
SixModelObject BOOTHash = tc.gc.BOOTHash;
bindee = gcx.Hash.st.REPR.allocate(tc, gcx.Hash.st);
bindee.bind_attribute_boxed(tc, gcx.Map, "$!storage",
HINT_ENUMMAP_storage, BOOTHash.st.REPR.allocate(tc, BOOTHash.st));
RakOps.p6store(bindee, decontValue, tc);
}
cf.oLex[sci.oTryGetLexicalIdx(varName)] = bindee;
}
/* If it's a scalar, we always need to wrap it into a new
* container and store it, for copy or ro case (the rw bit
* in the container descriptor takes care of the rest). */
else {
boolean wrap = (paramFlags & SIG_ELEM_IS_COPY) != 0;
if (!wrap && paramType != null && gcx.Iterable != null) {
wrap = Ops.istype(gcx.Iterable, paramType, tc) != 0
|| Ops.istype(paramType, gcx.Iterable, tc) != 0;
}
if (wrap || varName.equals("$_")) {
STable stScalar = gcx.Scalar.st;
SixModelObject new_cont = stScalar.REPR.allocate(tc, stScalar);
SixModelObject desc = param.get_attribute_boxed(tc, gcx.Parameter,
"$!container_descriptor", HINT_container_descriptor);
new_cont.bind_attribute_boxed(tc, gcx.Scalar, "$!descriptor",
RakudoContainerSpec.HINT_descriptor, desc);
new_cont.bind_attribute_boxed(tc, gcx.Scalar, "$!value",
RakudoContainerSpec.HINT_value, decontValue);
cf.oLex[sci.oTryGetLexicalIdx(varName)] = new_cont;
}
else {
cf.oLex[sci.oTryGetLexicalIdx(varName)] = decontValue;
}
}
}
}
}
/* Is it the invocant? If so, also have to bind to self lexical. */
if ((paramFlags & SIG_ELEM_INVOCANT) != 0)
cf.oLex[sci.oTryGetLexicalIdx("self")] = decontValue;
/* Handle any constraint types (note that they may refer to the parameter by
* name, so we need to have bound it already). */
SixModelObject postConstraints = param.get_attribute_boxed(tc, gcx.Parameter,
"$!post_contraints", HINT_post_constraints);
if (postConstraints != null) {
long numConstraints = postConstraints.elems(tc);
for (long i = 0; i < numConstraints; i++) {
/* Check we meet the constraint. */
SixModelObject consType = postConstraints.at_pos_boxed(tc, i);
SixModelObject acceptsMeth = Ops.findmethod(consType, "ACCEPTS", tc);
if (Ops.isconcrete(consType, tc) == 1 && Ops.istype(consType, gcx.Code, tc) != 0)
RakOps.p6capturelex(consType, tc);
switch (flag) {
case CallSiteDescriptor.ARG_INT:
Ops.invokeDirect(tc, acceptsMeth,
ACCEPTS_i, new Object[] { consType, arg_i });
break;
case CallSiteDescriptor.ARG_NUM:
Ops.invokeDirect(tc, acceptsMeth,
ACCEPTS_n, new Object[] { consType, arg_n });
break;
case CallSiteDescriptor.ARG_STR:
Ops.invokeDirect(tc, acceptsMeth,
ACCEPTS_s, new Object[] { consType, arg_s });
break;
default:
Ops.invokeDirect(tc, acceptsMeth,
ACCEPTS_o, new Object[] { consType, arg_o });
break;
}
if (Ops.istrue(Ops.result_o(tc.curFrame), tc) == 0) {
/* Constraint type check failed; produce error if needed. */
if (error != null) {
SixModelObject thrower = RakOps.getThrower(tc, "X::TypeCheck::Binding::Parameter");
if (thrower != null) {
error[0] = thrower;
error[1] = bindParamThrower;
error[2] = new Object[] { (SixModelObject)origArg,
consType.st.WHAT, varName, param, (long)1 };
}
else {
error[0] = String.format(
"Constraint type check failed for parameter '%s'",
varName);
}
}
return BIND_RESULT_FAIL;
}
}
}
/* TODO: attributives. */
if ((paramFlags & SIG_ELEM_BIND_ATTRIBUTIVE) != 0) {
if (flag != CallSiteDescriptor.ARG_OBJ) {
if (error != null)
error[0] = "Native attributive binding not yet implemented";
return BIND_RESULT_FAIL;
}
int result = assignAttributive(tc, cf, varName, paramFlags,
param.get_attribute_boxed(tc, gcx.Parameter, "$!attr_package", HINT_attr_package),
decontValue, error);
if (result != BIND_RESULT_OK)
return result;
}
/* If it has a sub-signature, bind that. */
SixModelObject subSignature = param.get_attribute_boxed(tc, gcx.Parameter,
"$!sub_signature", HINT_sub_signature);
if (subSignature != null && flag == CallSiteDescriptor.ARG_OBJ) {
/* Turn value into a capture, unless we already have one. */
SixModelObject capture = null;
int result;
if ((paramFlags & SIG_ELEM_IS_CAPTURE) != 0) {
capture = decontValue;
}
else {
SixModelObject meth = Ops.findmethodNonFatal(decontValue, "Capture", tc);
if (meth == null) {
if (error != null)
error[0] = "Could not turn argument into capture";
return BIND_RESULT_FAIL;
}
Ops.invokeDirect(tc, meth, Ops.invocantCallSite, new Object[] { decontValue });
capture = Ops.result_o(tc.curFrame);
}
SixModelObject subParams = subSignature
.get_attribute_boxed(tc, gcx.Signature, "@!params", HINT_SIG_params);
/* Recurse into signature binder. */
CallSiteDescriptor subCsd = explodeCapture(tc, gcx, capture);
result = bind(tc, gcx, cf, subParams, subCsd, tc.flatArgs, noNomTypeCheck, error);
if (result != BIND_RESULT_OK)
{
if (error != null && error[0] instanceof String) {
/* Note in the error message that we're in a sub-signature. */
error[0] += " in sub-signature";
/* Have we a variable name? */
if (varName != null) {
error[0] += " of parameter " + varName;
}
}
return result;
}
}
if (RakOps.DEBUG_MODE)
System.err.println("bindOneParam NYFI");
return BIND_RESULT_OK;
}
private static final CallSiteDescriptor exploder = new CallSiteDescriptor(new byte[] {
CallSiteDescriptor.ARG_OBJ | CallSiteDescriptor.ARG_FLAT,
CallSiteDescriptor.ARG_OBJ | CallSiteDescriptor.ARG_FLAT | CallSiteDescriptor.ARG_NAMED
}, null);
public static CallSiteDescriptor explodeCapture(ThreadContext tc, RakOps.GlobalExt gcx, SixModelObject capture) {
capture = Ops.decont(capture, tc);
SixModelObject capType = gcx.Capture;
SixModelObject list = capture.get_attribute_boxed(tc, capType, "@!list", HINT_CAPTURE_list);
SixModelObject hash = capture.get_attribute_boxed(tc, capType, "%!hash", HINT_CAPTURE_hash);
if (list == null)
list = gcx.EMPTYARR;
if (hash == null)
hash = gcx.EMPTYHASH;
return exploder.explodeFlattening(tc.curFrame, new Object[] { list, hash });
}
/* This takes a signature element and either runs the closure to get a default
* value if there is one, or creates an appropriate undefined-ish thingy. */
private static SixModelObject handleOptional(ThreadContext tc, RakOps.GlobalExt gcx, int flags, SixModelObject param, CallFrame cf) {
/* Is the "get default from outer" flag set? */
if ((flags & SIG_ELEM_DEFAULT_FROM_OUTER) != 0) {
param.get_attribute_native(tc, gcx.Parameter, "$!variable_name", HINT_variable_name);
String varName = tc.native_s;
CallFrame curOuter = cf.outer;
while (curOuter != null) {
Integer idx = curOuter.codeRef.staticInfo.oTryGetLexicalIdx(varName);
if (idx != null)
return curOuter.oLex[idx];
curOuter = curOuter.outer;
}
return null;
}
/* Do we have a default value or value closure? */
SixModelObject defaultValue = param.get_attribute_boxed(tc, gcx.Parameter,
"$!default_value", HINT_default_value);
if (defaultValue != null) {
if ((flags & SIG_ELEM_DEFAULT_IS_LITERAL) != 0) {
return defaultValue;
}
else {
/* Thunk; run it to get a value. */
Ops.invokeArgless(tc, defaultValue);
return Ops.result_o(tc.curFrame);
}
}
/* Otherwise, go by sigil to pick the correct default type of value. */
else {
if ((flags & SIG_ELEM_ARRAY_SIGIL) != 0) {
SixModelObject res = gcx.Array.st.REPR.allocate(tc, gcx.Array.st);
return res;
}
else if ((flags & SIG_ELEM_HASH_SIGIL) != 0) {
SixModelObject res = gcx.Hash.st.REPR.allocate(tc, gcx.Hash.st);
return res;
}
else {
param.get_attribute_native(tc, gcx.Parameter, "$!flags", HINT_flags);
int paramFlags = (int)tc.native_i;
switch (paramFlags & SIG_ELEM_NATIVE_VALUE) {
case SIG_ELEM_NATIVE_INT_VALUE:
return createBox(tc, gcx, (long)0, CallSiteDescriptor.ARG_INT);
case SIG_ELEM_NATIVE_NUM_VALUE:
return createBox(tc, gcx, (double)0.0, CallSiteDescriptor.ARG_NUM);
case SIG_ELEM_NATIVE_STR_VALUE:
return createBox(tc, gcx, null, CallSiteDescriptor.ARG_STR);
default:
/* Do a coercion, if one is needed. */
SixModelObject paramType = param.get_attribute_boxed(tc, gcx.Parameter, "$!type", HINT_type);
SixModelObject HOW = paramType.st.HOW;
SixModelObject archetypesMeth = Ops.findmethod(HOW, "archetypes", tc);
Ops.invokeDirect(tc, archetypesMeth, Ops.invocantCallSite, new Object[] { HOW });
SixModelObject Archetypes = Ops.result_o(tc.curFrame);
SixModelObject coerciveMeth = Ops.findmethodNonFatal(Archetypes, "coercive", tc);
if (coerciveMeth != null) {
Ops.invokeDirect(tc, coerciveMeth, Ops.invocantCallSite, new Object[] { Archetypes });
if (Ops.istrue(Ops.result_o(tc.curFrame), tc) == 1) {
SixModelObject targetTypeMeth = Ops.findmethod(HOW, "target_type", tc);
Ops.invokeDirect(tc, targetTypeMeth, targetType, new Object[] { HOW, paramType });
return Ops.result_o(tc.curFrame);
}
}
return paramType;
}
}
}
}
/* Takes a signature along with positional and named arguments and binds them
* into the provided callframe. Returns BIND_RESULT_OK if binding works out,
* BIND_RESULT_FAIL if there is a failure and BIND_RESULT_JUNCTION if the
* failure was because of a Junction being passed (meaning we need to auto-thread). */
private static final CallSiteDescriptor slurpyFromArgs = new CallSiteDescriptor(
new byte[] { CallSiteDescriptor.ARG_OBJ, CallSiteDescriptor.ARG_OBJ }, null);
public static int bind(ThreadContext tc, RakOps.GlobalExt gcx, CallFrame cf, SixModelObject params,
CallSiteDescriptor csd, Object[] args,
boolean noNomTypeCheck, Object[] error) {
int bindFail = BIND_RESULT_OK;
int curPosArg = 0;
/* If we have a |$foo that's followed by slurpies, then we can suppress
* any future arity checks. */
boolean suppressArityFail = false;
/* If we do have some named args, we want to make a clone of the hash
* to work on. We'll delete stuff from it as we bind, and what we have
* left over can become the slurpy hash or - if we aren't meant to be
* taking one - tell us we have a problem. */
HashMap<String, Integer> namedArgsCopy = csd.nameMap == null
? null
: new HashMap<String, Integer>(csd.nameMap);
/* Now we'll walk through the signature and go about binding things. */
int numPosArgs = csd.numPositionals;
long numParams = params.elems(tc);
for (long i = 0; i < numParams; i++) {
/* Get parameter, its flags and any named names. */
SixModelObject param = params.at_pos_boxed(tc, i);
param.get_attribute_native(tc, gcx.Parameter, "$!flags", HINT_flags);
int flags = (int)tc.native_i;
SixModelObject namedNames = param.get_attribute_boxed(tc,
gcx.Parameter, "@!named_names", HINT_named_names);
/* Is it looking for us to bind a capture here? */
if ((flags & SIG_ELEM_IS_CAPTURE) != 0) {
/* Capture the arguments from this point forwards into a Capture.
* Of course, if there's no variable name we can (cheaply) do pretty
* much nothing. */
param.get_attribute_native(tc, gcx.Parameter, "$!variable_name", HINT_variable_name);
if (tc.native_s == null) {
bindFail = BIND_RESULT_OK;
}
else {
SixModelObject posArgs = gcx.EMPTYARR.clone(tc);
for (int k = curPosArg; k < numPosArgs; k++) {
switch (csd.argFlags[k]) {
case CallSiteDescriptor.ARG_OBJ:
posArgs.push_boxed(tc, (SixModelObject)args[k]);
break;
case CallSiteDescriptor.ARG_INT:
posArgs.push_boxed(tc, RakOps.p6box_i((long)args[k], tc));
break;
case CallSiteDescriptor.ARG_NUM:
posArgs.push_boxed(tc, RakOps.p6box_n((double)args[k], tc));
break;
case CallSiteDescriptor.ARG_STR:
posArgs.push_boxed(tc, RakOps.p6box_s((String)args[k], tc));
break;
}
}
SixModelObject namedArgs = vmHashOfRemainingNameds(tc, gcx, namedArgsCopy, args);
SixModelObject capType = gcx.Capture;
SixModelObject capSnap = capType.st.REPR.allocate(tc, capType.st);
capSnap.bind_attribute_boxed(tc, capType, "@!list", HINT_CAPTURE_list, posArgs);
capSnap.bind_attribute_boxed(tc, capType, "%!hash", HINT_CAPTURE_hash, namedArgs);
bindFail = bindOneParam(tc, gcx, cf, param, capSnap, CallSiteDescriptor.ARG_OBJ,
noNomTypeCheck, false, error);
}
if (bindFail != 0) {
return bindFail;
}
else if (i + 1 == numParams) {
/* Since a capture acts as "the ultimate slurpy" in a sense, if
* this is the last parameter in the signature we can return
* success right off the bat. */
return BIND_RESULT_OK;
}
else {
SixModelObject nextParam = params.at_pos_boxed(tc, i + 1);
nextParam.get_attribute_native(tc, gcx.Parameter, "$!flags", HINT_flags);
if (((int)tc.native_i & (SIG_ELEM_SLURPY_POS | SIG_ELEM_SLURPY_NAMED)) != 0)
suppressArityFail = true;
}
}
/* Could it be a named slurpy? */
else if ((flags & SIG_ELEM_SLURPY_NAMED) != 0) {
SixModelObject slurpy = vmHashOfRemainingNameds(tc, gcx, namedArgsCopy, args);
SixModelObject bindee = gcx.Hash.st.REPR.allocate(tc, gcx.Hash.st);
bindee.bind_attribute_boxed(tc, gcx.Map, "$!storage",
HINT_ENUMMAP_storage, slurpy);
bindFail = bindOneParam(tc, gcx, cf, param, bindee, CallSiteDescriptor.ARG_OBJ,
noNomTypeCheck, true, error);
if (bindFail != 0)
return bindFail;
/* Nullify named arguments hash now we've consumed it, to mark all
* is well. */
namedArgsCopy = null;
}
/* Otherwise, maybe it's a positional of some kind. */
else if (namedNames == null) {
/* Slurpy or LoL-slurpy? */
if ((flags & (SIG_ELEM_SLURPY_POS | SIG_ELEM_SLURPY_LOL | SIG_ELEM_SLURPY_ONEARG)) != 0) {
/* Create Raku array, create VM array of all remaining things,
* then store it. */
SixModelObject slurpy = gcx.EMPTYARR.clone(tc);
while (curPosArg < numPosArgs) {
switch (csd.argFlags[curPosArg]) {
case CallSiteDescriptor.ARG_OBJ:
slurpy.push_boxed(tc, (SixModelObject)args[curPosArg]);
break;
case CallSiteDescriptor.ARG_INT:
slurpy.push_boxed(tc, RakOps.p6box_i((long)args[curPosArg], tc));
break;
case CallSiteDescriptor.ARG_NUM:
slurpy.push_boxed(tc, RakOps.p6box_n((double)args[curPosArg], tc));
break;
case CallSiteDescriptor.ARG_STR:
slurpy.push_boxed(tc, RakOps.p6box_s((String)args[curPosArg], tc));
break;
}
curPosArg++;
}
SixModelObject slurpyType = (flags & SIG_ELEM_IS_RAW) != 0 ? gcx.List : gcx.Array;
SixModelObject sm = Ops.findmethod(slurpyType,
(flags & SIG_ELEM_SLURPY_ONEARG) != 0 ? "from-slurpy-onearg" :
(flags & SIG_ELEM_SLURPY_POS) != 0 ? "from-slurpy-flat" : "from-slurpy",
tc);
Ops.invokeDirect(tc, sm, slurpyFromArgs, new Object[] { slurpyType, slurpy });
SixModelObject bindee = Ops.result_o(tc.curFrame);
bindFail = bindOneParam(tc, gcx, cf, param, bindee, CallSiteDescriptor.ARG_OBJ,
noNomTypeCheck, false, error);
if (bindFail != 0)
return bindFail;
}
/* Otherwise, a positional. */
else {
/* Do we have a value? */
if (curPosArg < numPosArgs) {
/* Easy - just bind that. */
bindFail = bindOneParam(tc, gcx, cf, param, args[curPosArg],
csd.argFlags[curPosArg], noNomTypeCheck, false, error);
if (bindFail != 0)
return bindFail;
curPosArg++;
}
else {
/* No value. If it's optional, fetch a default and bind that;
* if not, we're screwed. Note that we never nominal type check
* an optional with no value passed. */
if ((flags & SIG_ELEM_IS_OPTIONAL) != 0) {
bindFail = bindOneParam(tc, gcx, cf, param,
handleOptional(tc, gcx, flags, param, cf),
CallSiteDescriptor.ARG_OBJ, false, false, error);
if (bindFail != 0)
return bindFail;
}
else {
if (error != null)
error[0] = arityFail(tc, gcx, params, (int)numParams, numPosArgs, false);
return BIND_RESULT_FAIL;
}
}
}
}
/* Else, it's a non-slurpy named. */
else {
/* Try and get hold of value. */
Integer lookup = null;
if (namedArgsCopy != null) {
long numNames = namedNames.elems(tc);
for (long j = 0; j < numNames; j++) {
namedNames.at_pos_native(tc, j);
String name = tc.native_s;
lookup = namedArgsCopy.remove(name);
if (lookup != null)
break;
}
}
/* Did we get one? */
if (lookup == null) {
/* Nope. We'd better hope this param was optional... */
if ((flags & SIG_ELEM_IS_OPTIONAL) != 0) {
bindFail = bindOneParam(tc, gcx, cf, param,
handleOptional(tc, gcx, flags, param, cf),
CallSiteDescriptor.ARG_OBJ, false, false, error);
}
else if (!suppressArityFail) {
if (error != null) {
namedNames.at_pos_native(tc, 0);
error[0] = "Required named argument '" +
tc.native_s +
"' not passed";
}
return BIND_RESULT_FAIL;
}
}
else {
bindFail = bindOneParam(tc, gcx, cf, param, args[lookup >> 3],
(byte)(lookup & 7), noNomTypeCheck, false, error);
}
/* If we got a binding failure, return it. */
if (bindFail != 0)
return bindFail;
}
}
/* Do we have any left-over args? */
if (curPosArg < numPosArgs && !suppressArityFail) {
/* Oh noes, too many positionals passed. */
if (error != null)
error[0] = arityFail(tc, gcx, params, (int)numParams, numPosArgs, true);
return BIND_RESULT_FAIL;
}
if (namedArgsCopy != null && namedArgsCopy.size() > 0) {
/* Oh noes, unexpected named args. */
if (error != null) {
int numExtra = namedArgsCopy.size();
if (numExtra == 1) {
for (String name : namedArgsCopy.keySet())
error[0] = "Unexpected named argument '" + name + "' passed";
}
else {
boolean first = true;
error[0] = numExtra + " unexpected named arguments passed (";
for (String name : namedArgsCopy.keySet()) {
if (!first)
error[0] += ", ";
else
first = false;
error[0] += name;
}
error[0] += ")";
}
}
return BIND_RESULT_FAIL;
}
/* If we get here, we're done. */
return BIND_RESULT_OK;
}
/* Takes any nameds we didn't capture yet and makes a VM Hash of them. */
private static SixModelObject vmHashOfRemainingNameds(ThreadContext tc, RakOps.GlobalExt gcx, HashMap<String, Integer> namedArgsCopy, Object[] args) {
SixModelObject slurpy = gcx.Mu;
if (namedArgsCopy != null) {
SixModelObject BOOTHash = tc.gc.BOOTHash;
slurpy = BOOTHash.st.REPR.allocate(tc, BOOTHash.st);
for (String name : namedArgsCopy.keySet()) {
int lookup = namedArgsCopy.get(name);
switch (lookup & 7) {
case CallSiteDescriptor.ARG_OBJ:
slurpy.bind_key_boxed(tc, name, (SixModelObject)args[lookup >> 3]);
break;
case CallSiteDescriptor.ARG_INT:
slurpy.bind_key_boxed(tc, name, RakOps.p6box_i((long)args[lookup >> 3], tc));
break;
case CallSiteDescriptor.ARG_NUM:
slurpy.bind_key_boxed(tc, name, RakOps.p6box_n((double)args[lookup >> 3], tc));
break;
case CallSiteDescriptor.ARG_STR:
slurpy.bind_key_boxed(tc, name, RakOps.p6box_s((String)args[lookup >> 3], tc));
break;
}
}
}
return slurpy;
}
}
|
package com.haxademic.app.haxmapper;
import java.awt.Rectangle;
import java.util.ArrayList;
import com.haxademic.app.haxmapper.distribution.MappingGroup;
import com.haxademic.app.haxmapper.polygons.IMappedPolygon;
import com.haxademic.app.haxmapper.polygons.MappedQuad;
import com.haxademic.app.haxmapper.polygons.MappedTriangle;
import com.haxademic.app.haxmapper.textures.BaseTexture;
import com.haxademic.core.app.P;
import com.haxademic.core.app.PAppletHax;
import com.haxademic.core.data.ConvertUtil;
import com.haxademic.core.draw.util.DrawUtil;
import com.haxademic.core.draw.util.OpenGLUtil;
import com.haxademic.core.hardware.midi.AbletonNotes;
import com.haxademic.core.hardware.midi.AkaiMpdPads;
import com.haxademic.core.hardware.osc.TouchOscPads;
import com.haxademic.core.hardware.shared.InputTrigger;
import com.haxademic.core.image.filters.shaders.BadTVLinesFilter;
import com.haxademic.core.image.filters.shaders.BrightnessFilter;
import com.haxademic.core.image.filters.shaders.ColorDistortionFilter;
import com.haxademic.core.image.filters.shaders.CubicLensDistortionFilter;
import com.haxademic.core.image.filters.shaders.DeformBloomFilter;
import com.haxademic.core.image.filters.shaders.DeformTunnelFanFilter;
import com.haxademic.core.image.filters.shaders.EdgesFilter;
import com.haxademic.core.image.filters.shaders.HalftoneFilter;
import com.haxademic.core.image.filters.shaders.InvertFilter;
import com.haxademic.core.image.filters.shaders.KaleidoFilter;
import com.haxademic.core.image.filters.shaders.MirrorFilter;
import com.haxademic.core.image.filters.shaders.PixelateFilter;
import com.haxademic.core.image.filters.shaders.RadialRipplesFilter;
import com.haxademic.core.image.filters.shaders.SphereDistortionFilter;
import com.haxademic.core.image.filters.shaders.WobbleFilter;
import com.haxademic.core.math.MathUtil;
import oscP5.OscMessage;
import processing.core.PConstants;
import processing.core.PGraphics;
@SuppressWarnings("serial")
public class HaxMapper
extends PAppletHax {
public static int MAX_ACTIVE_TEXTURES = 4;
public static int MAX_ACTIVE_TEXTURES_PER_GROUP = 2;
public static int MAX_ACTIVE_MOVIE_TEXTURES = 2;
protected String _inputFileLines[];
protected PGraphics _overlayPG;
protected Rectangle _boundingBox;
protected float[] extentsX = {-1,-1};
protected float[] extentsY = {-1,-1};
protected ArrayList<MappingGroup> _mappingGroups;
protected ArrayList<BaseTexture> _texturePool;
protected ArrayList<BaseTexture> _curTexturePool;
protected ArrayList<BaseTexture> _movieTexturePool;
protected ArrayList<BaseTexture> _activeTextures;
protected boolean _debugTextures = false;
protected InputTrigger _colorTrigger = new InputTrigger(new char[]{'c'},new String[]{TouchOscPads.PAD_01},new Integer[]{AkaiMpdPads.PAD_01, AbletonNotes.NOTE_01});
protected InputTrigger _rotationTrigger = new InputTrigger(new char[]{'v'},new String[]{TouchOscPads.PAD_02},new Integer[]{AkaiMpdPads.PAD_02, AbletonNotes.NOTE_02});
protected InputTrigger _timingTrigger = new InputTrigger(new char[]{'n'},new String[]{TouchOscPads.PAD_03},new Integer[]{AkaiMpdPads.PAD_03, AbletonNotes.NOTE_03});
protected InputTrigger _modeTrigger = new InputTrigger(new char[]{'m'},new String[]{TouchOscPads.PAD_04},new Integer[]{AkaiMpdPads.PAD_04, AbletonNotes.NOTE_04});
protected InputTrigger _timingSectionTrigger = new InputTrigger(new char[]{'f'},new String[]{TouchOscPads.PAD_05},new Integer[]{AkaiMpdPads.PAD_05, AbletonNotes.NOTE_05});
protected InputTrigger _allSameTextureTrigger = new InputTrigger(new char[]{'a'},new String[]{TouchOscPads.PAD_06},new Integer[]{AkaiMpdPads.PAD_06, AbletonNotes.NOTE_06});
protected InputTrigger _bigChangeTrigger = new InputTrigger(new char[]{' '},new String[]{TouchOscPads.PAD_07},new Integer[]{AkaiMpdPads.PAD_07, AbletonNotes.NOTE_07});
protected InputTrigger _lineModeTrigger = new InputTrigger(new char[]{'l'},new String[]{TouchOscPads.PAD_08},new Integer[]{AkaiMpdPads.PAD_08, AbletonNotes.NOTE_08});
protected InputTrigger _audioInputUpTrigger = new InputTrigger(new char[]{},new String[]{"/7/nav1"},new Integer[]{});
protected InputTrigger _audioInputDownTrigger = new InputTrigger(new char[]{},new String[]{"/7/nav2"},new Integer[]{});
protected InputTrigger _brightnessUpTrigger = new InputTrigger(new char[]{']'},new String[]{},new Integer[]{});
protected InputTrigger _brightnessDownTrigger = new InputTrigger(new char[]{'['},new String[]{},new Integer[]{});
protected InputTrigger _debugTexturesTrigger = new InputTrigger(new char[]{'d'},new String[]{},new Integer[]{});
protected int _lastInputMillis = 0;
protected int numBeatsDetected = 0;
// protected PShader _brightness;
// protected float _brightnessVal = 1f;
// protected PShader _blurH;
// protected PShader _blurV;
protected int[] _textureEffectsIndices = {0,0,0,0,0,0,0}; // store a effects number for each texture position after the first
protected int _numTextureEffects = 15 + 8; // +8 to give a good chance at removing the filter from the texture slot
public void oscEvent(OscMessage theOscMessage) {
super.oscEvent(theOscMessage);
String oscMsg = theOscMessage.addrPattern();
// handle brightness slider
if( oscMsg.indexOf("/7/fader0") != -1) {
// _brightnessVal = theOscMessage.get(0).floatValue() * 3.0f;
}
}
protected void overridePropsFile() {
_appConfig.setProperty( "rendering", "false" );
_appConfig.setProperty( "fullscreen", "true" );
_appConfig.setProperty( "fills_screen", "true" );
_appConfig.setProperty( "osc_active", "true" );
}
public void setup() {
super.setup();
p.smooth(OpenGLUtil.SMOOTH_HIGH);
noStroke();
importPolygons();
P.println("_boundingBox", _boundingBox);
for( int i=0; i < _mappingGroups.size(); i++ ) _mappingGroups.get(i).completePolygonImport();
buildTextures();
}
protected void importPolygons() {
_boundingBox = new Rectangle(-1, -1, 0, 0);
_overlayPG = P.p.createGraphics( p.width, p.height, PConstants.OPENGL );
_overlayPG.smooth(OpenGLUtil.SMOOTH_MEDIUM);
_mappingGroups = new ArrayList<MappingGroup>();
if( _appConfig.getString("mapping_file", "") == "" ) {
_mappingGroups.add( new MappingGroup( this, _overlayPG ) );
for(int i=0; i < 200; i++ ) {
// create triangle
float startX = p.random(0,p.width);
float startY = p.random(0,p.height);
float x2 = startX + p.random(-300,300);
float y2 = startY + p.random(-300,300);
// float x3 = startX + p.random(-300,300);
float x3 = startY + p.random(-300,300);
float y3 = startY + p.random(-300,300);
// add polygon
_mappingGroups.get(0).addPolygon( new MappedTriangle( startX, startY, x2, y2, x3, y3 ) );
// update bounding box as we build
updateBoundingBox(startX, startY);
updateBoundingBox(x2, y2);
updateBoundingBox(x3, y3);
}
_mappingGroups.get(0).addPolygon( new MappedTriangle( 100, 200, 400, 700, 650, 300 ) );
} else {
_inputFileLines = loadStrings(_appConfig.getString("mapping_file", ""));
for( int i=0; i < _inputFileLines.length; i++ ) {
String inputLine = _inputFileLines[i];
// count lines that contain characters
if( inputLine.indexOf("#group#") != -1 ) {
_mappingGroups.add( new MappingGroup( this, _overlayPG ) );
} else if( inputLine.indexOf("#poly#") != -1 ) {
// poly!
inputLine = inputLine.replace("#poly#", "");
String polyPoints[] = inputLine.split(",");
if(polyPoints.length == 6) {
// add polygons
_mappingGroups.get(_mappingGroups.size()-1).addPolygon( new MappedTriangle(
ConvertUtil.stringToFloat( polyPoints[0] ),
ConvertUtil.stringToFloat( polyPoints[1] ),
ConvertUtil.stringToFloat( polyPoints[2] ),
ConvertUtil.stringToFloat( polyPoints[3] ),
ConvertUtil.stringToFloat( polyPoints[4] ),
ConvertUtil.stringToFloat( polyPoints[5] )
) );
// update bounding box as we build
updateBoundingBox(ConvertUtil.stringToFloat( polyPoints[0] ), ConvertUtil.stringToFloat( polyPoints[1] ));
updateBoundingBox(ConvertUtil.stringToFloat( polyPoints[2] ), ConvertUtil.stringToFloat( polyPoints[3] ));
updateBoundingBox(ConvertUtil.stringToFloat( polyPoints[4] ), ConvertUtil.stringToFloat( polyPoints[5] ));
} else if(polyPoints.length == 8) {
// add polygons
_mappingGroups.get(_mappingGroups.size()-1).addPolygon( new MappedQuad(
ConvertUtil.stringToFloat( polyPoints[0] ),
ConvertUtil.stringToFloat( polyPoints[1] ),
ConvertUtil.stringToFloat( polyPoints[2] ),
ConvertUtil.stringToFloat( polyPoints[3] ),
ConvertUtil.stringToFloat( polyPoints[4] ),
ConvertUtil.stringToFloat( polyPoints[5] ),
ConvertUtil.stringToFloat( polyPoints[6] ),
ConvertUtil.stringToFloat( polyPoints[7] )
) );
// update bounding box as we build
updateBoundingBox(ConvertUtil.stringToFloat( polyPoints[0] ), ConvertUtil.stringToFloat( polyPoints[1] ));
updateBoundingBox(ConvertUtil.stringToFloat( polyPoints[2] ), ConvertUtil.stringToFloat( polyPoints[3] ));
updateBoundingBox(ConvertUtil.stringToFloat( polyPoints[4] ), ConvertUtil.stringToFloat( polyPoints[5] ));
updateBoundingBox(ConvertUtil.stringToFloat( polyPoints[6] ), ConvertUtil.stringToFloat( polyPoints[7] ));
}
}
}
}
}
protected void updateBoundingBox(float x, float y) {
if(x < extentsX[0] || extentsX[0] == -1) extentsX[0] = x;
if(x > extentsX[1] || extentsX[1] == -1) extentsX[1] = x;
if(y < extentsY[0] || extentsY[0] == -1) extentsY[0] = y;
if(y > extentsY[1] || extentsY[1] == -1) extentsY[1] = y;
_boundingBox.x = (int) Math.floor(extentsX[0]);
_boundingBox.width = (int) Math.ceil(extentsX[1] - extentsX[0]);
_boundingBox.y = (int) Math.floor(extentsY[0]);
_boundingBox.height= (int) Math.ceil(extentsY[1] - extentsY[0]);
}
protected void buildTextures() {
_texturePool = new ArrayList<BaseTexture>();
_curTexturePool = new ArrayList<BaseTexture>();
_movieTexturePool = new ArrayList<BaseTexture>();
_activeTextures = new ArrayList<BaseTexture>();
addTexturesToPool();
buildMappingGroups();
}
protected void buildMappingGroups() {
// override this!
}
protected void addTexturesToPool() {
// override this!
}
public void drawApp() {
background(0);
checkBeat();
updateActiveTextures();
filterActiveTextures();
traverseGroups();
drawPolygonGroups();
drawOverlays();
postProcessFilters();
if(_debugTextures == true) debugTextures();
}
protected void updateActiveTextures() {
// reset active texture pool array
while( _activeTextures.size() > 0 ) {
_activeTextures.remove( _activeTextures.size() - 1 ).resetUseCount();
}
// figure out which textures are being used and rebuild array, telling active textures that they're active
for( int i=0; i < _mappingGroups.size(); i++ ) {
ArrayList<BaseTexture> textures = _mappingGroups.get(i).textures();
for( int j=0; j < textures.size(); j++ ) {
if( _activeTextures.indexOf( textures.get(j) ) == -1 ) {
textures.get(j).setActive(true);
_activeTextures.add( textures.get(j) );
}
}
}
// set inactive pool textures' _active state to false (mostly for turning off video players)
for( int i=0; i < _texturePool.size(); i++ ) {
if( _texturePool.get(i).useCount() == 0 && _texturePool.get(i).isActive() == true ) {
_texturePool.get(i).setActive(false);
// P.println("Deactivated: ", _texturePool.get(i).getClass().getName());
}
}
// update active textures, once each
for( int i=0; i < _activeTextures.size(); i++ ) {
_activeTextures.get(i).update();
}
// P.println(_activeTextures.size());
}
protected void selectNewActiveTextureFilters() {
for(int i=1; i < _textureEffectsIndices.length; i++) {
if(MathUtil.randRange(0, 10) > 8) {
_textureEffectsIndices[i] = MathUtil.randRange(0, _numTextureEffects);
}
}
}
protected void filterActiveTextures() {
for( int i=0; i < _activeTextures.size(); i++ ) {
PGraphics pg = _activeTextures.get(i).texture();
float filterTime = p.frameCount / 40f;
if(_textureEffectsIndices[i] == 1) {
KaleidoFilter.instance(p).setSides(4);
KaleidoFilter.instance(p).setAngle(filterTime / 10f);
KaleidoFilter.instance(p).applyTo(pg);
} else if(_textureEffectsIndices[i] == 2) {
DeformTunnelFanFilter.instance(p).setTime(filterTime);
DeformTunnelFanFilter.instance(p).applyTo(p);
} else if(_textureEffectsIndices[i] == 3) {
EdgesFilter.instance(p).applyTo(pg);
} else if(_textureEffectsIndices[i] == 4) {
MirrorFilter.instance(p).applyTo(pg);
} else if(_textureEffectsIndices[i] == 5) {
WobbleFilter.instance(p).setTime(filterTime);
WobbleFilter.instance(p).setSpeed(0.5f);
WobbleFilter.instance(p).setStrength(0.0004f);
WobbleFilter.instance(p).setSize( 200f);
WobbleFilter.instance(p).applyTo(pg);
} else if(_textureEffectsIndices[i] == 6) {
InvertFilter.instance(p).applyTo(pg);
} else if(_textureEffectsIndices[i] == 7) {
RadialRipplesFilter.instance(p).setTime(filterTime);
RadialRipplesFilter.instance(p).setAmplitude(0.5f + 0.5f * P.sin(filterTime));
RadialRipplesFilter.instance(p).applyTo(pg);
} else if(_textureEffectsIndices[i] == 8) {
BadTVLinesFilter.instance(p).applyTo(pg);
} else if(_textureEffectsIndices[i] == 9) {
EdgesFilter.instance(p).applyTo(pg);
} else if(_textureEffectsIndices[i] == 10) {
CubicLensDistortionFilter.instance(p).setTime(filterTime);
CubicLensDistortionFilter.instance(p).applyTo(pg);
} else if(_textureEffectsIndices[i] == 11) {
SphereDistortionFilter.instance(p).applyTo(pg);
} else if(_textureEffectsIndices[i] == 12) {
HalftoneFilter.instance(p).applyTo(pg);
} else if(_textureEffectsIndices[i] == 13) {
PixelateFilter.instance(p).setDivider(15f, 15f * pg.height/pg.width);
PixelateFilter.instance(p).applyTo(pg);
} else if(_textureEffectsIndices[i] == 14) {
DeformBloomFilter.instance(p).setTime(filterTime);
DeformBloomFilter.instance(p).applyTo(pg);
} else if(_textureEffectsIndices[i] == 15) {
DeformTunnelFanFilter.instance(p).setTime(filterTime);
DeformTunnelFanFilter.instance(p).applyTo(pg);
}
// WarperFilter.instance(p).setTime( _timeEaseInc / 5f);
// WarperFilter.instance(p).applyTo(pg);
// ColorDistortionFilter.instance(p).setTime( _timeEaseInc / 5f);
// ColorDistortionFilter.instance(p).setAmplitude(1.5f + 1.5f * P.sin(radsComplete));
// ColorDistortionFilter.instance(p).applyTo(pg);
// OpenGLUtil.setTextureRepeat(_buffer);
}
}
protected void drawPolygonGroups() {
for( int i=0; i < _mappingGroups.size(); i++ ) {
_mappingGroups.get(i).draw();
}
}
protected void drawOverlays() {
DrawUtil.setColorForPImage(p);
DrawUtil.resetPImageAlpha(p);
// draw mesh on top
_overlayPG.beginDraw();
_overlayPG.clear();
for( int i=0; i < _mappingGroups.size(); i++ ) {
_mappingGroups.get(i).drawOverlay();
}
_overlayPG.endDraw();
// _overlayPG.filter(_blurH);
// _overlayPG.filter(_blurV);
p.image( _overlayPG, 0, 0, _overlayPG.width, _overlayPG.height );
}
protected void postProcessFilters() {
// brightness
float brightMult = 6f;
if(p.frameCount < 3) p.midi.controllerChange(3, 41, P.round(127f/brightMult));
float brightnessVal = p.midi.midiCCPercent(3, 41) * brightMult;
BrightnessFilter.instance(p).setBrightness(brightnessVal);
BrightnessFilter.instance(p).applyTo(p);
// color distortion auto
int distAutoFrame = p.frameCount % 6000;
float distFrames = 100f;
if(distAutoFrame <= distFrames) {
float distAmpAuto = P.sin(distAutoFrame/distFrames * P.PI);
p.midi.controllerChange(3, 42, P.round(127 * distAmpAuto));
p.midi.controllerChange(3, 43, P.round(127 * distAmpAuto));
}
// color distortion
float colorDistortionAmp = p.midi.midiCCPercent(3, 42) * 0.5f;
float colorDistortionTimeMult = p.midi.midiCCPercent(3, 43);
if(colorDistortionAmp > 0) {
float prevTime = ColorDistortionFilter.instance(p).getTime();
ColorDistortionFilter.instance(p).setTime(prevTime + 1/100f * colorDistortionTimeMult);
ColorDistortionFilter.instance(p).setAmplitude(colorDistortionAmp);
ColorDistortionFilter.instance(p).applyTo(p);
}
}
protected void debugTextures() {
// debug current textures
for( int i=0; i < _activeTextures.size(); i++ ) {
p.image(_activeTextures.get(i).texture(), i * 100, 0, 100, 100);
}
}
protected void checkBeat() {
}
public void resetBeatDetectMode() {
_lastInputMillis = p.millis();
numBeatsDetected = 1;
}
protected void handleInput( boolean isMidi ) {
super.handleInput( isMidi );
// if( p.key == 'a' || p.key == 'A' ){
// _isAutoPilot = !_isAutoPilot;
// P.println("_isAutoPilot = "+_isAutoPilot);
// if( p.key == 'S' ){
// _isStressTesting = !_isStressTesting;
// P.println("_isStressTesting = "+_isStressTesting);
if ( _colorTrigger.active() == true ) {
resetBeatDetectMode();
updateColor();
}
if ( _modeTrigger.active() == true ) {
newMode();
traverseTrigger();
}
if ( _lineModeTrigger.active() == true ) {
resetBeatDetectMode();
updateLineMode();
}
if ( _rotationTrigger.active() == true ) {
resetBeatDetectMode();
updateRotation();
}
if ( _timingTrigger.active() == true ) {
resetBeatDetectMode();
updateTiming();
}
if ( _timingSectionTrigger.active() == true ) {
updateTimingSection();
}
if ( _bigChangeTrigger.active() == true ) {
resetBeatDetectMode();
bigChangeTrigger();
}
if ( _allSameTextureTrigger.active() == true ) {
resetBeatDetectMode();
setAllSameTexture();
}
if ( _audioInputUpTrigger.active() == true ) audioIn.gainUp();
if ( _audioInputDownTrigger.active() == true ) audioIn.gainDown();
// if ( _brightnessUpTrigger.active() == true ) _brightnessVal += 0.1f;
// if ( _brightnessDownTrigger.active() == true ) _brightnessVal -= 0.1f;
if ( _debugTexturesTrigger.active() == true ) _debugTextures = !_debugTextures;
}
protected void newMode() {
for( int i=0; i < _mappingGroups.size(); i++ ) {
_mappingGroups.get(i).newMode();
}
}
protected void updateColor() {
for( int i=0; i < _mappingGroups.size(); i++ ) {
_mappingGroups.get(i).newColor();
_mappingGroups.get(i).pulseColor();
}
}
protected void updateLineMode() {
for( int i=0; i < _mappingGroups.size(); i++ ) {
_mappingGroups.get(i).newLineMode();
}
}
protected void updateRotation() {
for( int i=0; i < _mappingGroups.size(); i++ ) {
// _mappingGroups.get(i).newRotation();
_mappingGroups.get(i).newRandomRotation();
}
}
protected void updateTiming() {
for( int i=0; i < _activeTextures.size(); i++ ) {
_activeTextures.get(i).updateTiming();
}
}
protected void updateTimingSection() {
for( int i=0; i < _activeTextures.size(); i++ ) {
_activeTextures.get(i).updateTimingSection();
}
}
protected void bigChangeTrigger() {
for( int i=0; i < _mappingGroups.size(); i++ ) {
_mappingGroups.get(i).randomTextureToRandomPolygon();
}
selectNewActiveTextureFilters();
}
protected void setAllSameTexture() {
boolean mode = MathUtil.randBoolean(p);
BaseTexture newTexture = _texturePool.get( MathUtil.randRange(0, _texturePool.size()-1 ) );
for( int i=0; i < _mappingGroups.size(); i++ ) {
_mappingGroups.get(i).clearAllTextures();
_mappingGroups.get(i).pushTexture( newTexture );
_mappingGroups.get(i).setAllPolygonsToTexture(0);
if( mode == true ) {
_mappingGroups.get(i).setAllPolygonsTextureStyle( IMappedPolygon.MAP_STYLE_CONTAIN_RANDOM_TEX_AREA );
} else {
_mappingGroups.get(i).setAllPolygonsTextureStyle( IMappedPolygon.MAP_STYLE_MASK );
}
}
}
protected void traverseTrigger() {
for( int i=0; i < _mappingGroups.size(); i++ ) {
_mappingGroups.get(i).traverseStart();
}
}
protected void traverseGroups() {
for( int i=0; i < _mappingGroups.size(); i++ ) {
_mappingGroups.get(i).traverseUpdate();
}
}
}
|
package com.inet.lib.less;
import java.io.BufferedReader;
import java.io.Closeable;
import java.io.IOException;
import java.io.Reader;
import java.io.StringReader;
import java.util.Scanner;
/**
* A reader with some special look ahead reading.
*/
class LessLookAheadReader extends LessObject implements Closeable {
private final Reader reader;
private final StringBuilder cache = new StringBuilder();
private StringReader cache2;
private final boolean isReference, isMultiple;
private int cachePos;
/**
* Create a new instance.
* @param reader the underlying reader
* @param fileName the filename of the less file or null if a String is parsed.
* @param isReference true, if the less file is imported as reference
* @param isMultiple true, if the less file is imported with keyword "multiple"
*/
LessLookAheadReader( Reader reader, String fileName, boolean isReference, boolean isMultiple ) {
super( fileName );
this.reader = reader.markSupported() ? reader : new BufferedReader( reader );
this.isReference = isReference;
this.isMultiple = isMultiple;
line = 1;
column = 0;
}
/**
* Read the next character in the method nextBlockMarker()
*
* @return next char
* @throws IOException
* if an I/O error occur
*/
private int readCharBlockMarker() throws IOException {
if( cache2 != null ) {
int ch = cache2.read();
if( ch != -1 ) {
return ch;
}
cache2 = null;
}
return reader.read();
}
/**
* Get the next parse type. This can be -1, ';', '{' or '}'. It copy the input until this marker in the look ahead
* cache.
*
* @return the block type of the next data.
* @throws LessException if any parsing error occur.
*/
int nextBlockMarker() throws LessException {
if( cachePos < cache.length() ) {
String str = cache.substring( cachePos );
if( cache2 != null ) { // occur with detached rulset inside another detached ruleset
try (Scanner scanner = new Scanner( cache2 ).useDelimiter( "\\A" )) {
if( scanner.hasNext() ) {
str = scanner.next() + str;
}
}
}
cache2 = new StringReader( str );
}
cache.setLength( cachePos = 0 );
int parenthesis = 0;
boolean isSlash = false;
try {
for( ;; ) {
int ch = readCharBlockMarker();
if( ch < 0 ) {
for( int i = 0; i < cache.length(); i++ ) {
if( !Character.isWhitespace( cache.charAt( i ) ) ) {
return ';'; // a not terminated line is like a lime with semicolon
}
}
return -1;
}
cache.append( (char)ch );
switch( ch ) {
case '/':
if( isSlash ) {
if( parenthesis > 0 && cache.indexOf( "url" ) > 0 ) {
break;
}
cache.setLength( cache.length() - 2 );
skipLine();
ch = 0;
}
break;
case '*':
if( isSlash ) {
boolean isAsterix = false;
for( ;; ) {
ch = readCharBlockMarker();
if( ch < 0 ) {
throw createException( "Unrecognized input: '" + cache.toString().trim() + "'" );
}
cache.append( (char)ch );
if( ch == '/' && isAsterix ) {
ch = 0;
break;
}
isAsterix = ch == '*';
}
}
break;
case '{':
boolean isBlock = true;
if( cache.length() > 1 && cache.charAt( cache.length() - 2 ) == '@' ) { // @{ --> a inline variable and not a block start
isBlock = false;
} else {
for( int i = cache.length()-2; i > 0; i
char c = cache.charAt( i );
if( !Character.isWhitespace( c ) ) {
isBlock = c != ':'; // detached ruleset that will assign to a variable
break;
}
}
}
if( !isBlock ) {
int braces = 1;
do {
ch = readCharBlockMarker();
switch( ch ) {
case -1:
throw createException( "Unrecognized input: '" + cache.toString().trim() + "'" );
case '}':
braces
break;
case '{':
braces++;
break;
}
cache.append( (char)ch );
} while( braces > 0 );
break;
}
//$FALL-THROUGH$
case '}':
case ';':
if( parenthesis == 0 ) {
return ch;
}
break;
case '(':
parenthesis++;
break;
case ')':
if( --parenthesis < 0 ) {
throw createException( "Unrecognized input: '" + cache.toString().trim() + "'" );
}
break;
case '"':
case '\'':
case '`':
int ch2;
isSlash = false;
for( ;; ) {
ch2 = readCharBlockMarker();
if( ch2 < 0 ) {
return ';'; // a not terminated line is like a lime with semicolon
}
cache.append( (char)ch2 );
if( ch == ch2 && !isSlash ) {
break;
}
isSlash = ch2 == '\\';
}
break;
case '\\':
cache.append( (char)readCharBlockMarker() );
break;
default:
}
isSlash = ch == '/';
}
} catch( IOException ex ) {
throw new LessException( ex );
}
}
/**
* The read data from nextBlockMarker(). Is used for an error message only.
* @return the look ahead cache.
*/
String getLookAhead(){
return cache.toString();
}
/**
* If the next data which are already in the cache are a mixin parameter or part of a selector name.
* This is call after a left parenthesis.
* Samples for selectors:<ul>
* <li>(min-resolution: 192dpi)
* <li>(.clearfix all)
* <li>(audio:not([controls]))
* <li>(odd)
* <li>(@{color})
* </ul>
* Samples for mixin params<ul>
* <li>(.65)
* <li>(@color)
* <li>()
* <li>(...)
* <li>(red)
* <li>(1)
* <li>({color: green})
* </ul>
* @param isBlock selector of a block or a semicolon line
* @return true, if it is a mixin parameter
*/
boolean nextIsMixinParam( boolean isBlock ) {
boolean isFirst = true;
for( int i=cachePos; i < cache.length(); i++ ) {
char ch = cache.charAt( i );
switch( ch ) {
case ')':
return true;
case '@':
return cache.charAt( i+1 ) != '{';
case '~':
return true;
case '"':
return !isBlock;
case '.':
if( !isFirst ) {
continue;
} else {
if( Character.isDigit( cache.charAt( i + 1 ) ) ) { //Number with a starting point
return true;
}
}
if( i + 2 < cache.length() && cache.charAt( i + 1 ) == '.' && cache.charAt( i + 2 ) == '.' ) {
return true;
}
return false;
case ':':
case '[':
return false;
case '{':
return true; // detached ruleset as mixin parameter
case ' ':
continue;
default:
isFirst = false;
}
}
return false;
}
/**
* Read a single character from reader or from back buffer
*
* @return a character or -1 if EOF
* @throws LessException
* If an I/O error occurs
*/
char read() {
try {
if( cachePos < cache.length() ) {
return incLineColumn( cache.charAt( cachePos++ ) );
}
int ch = readCharBlockMarker();
if( ch == -1 ) {
throw createException( "Unexpected end of Less data" );
}
return incLineColumn( ch );
} catch( IOException ex ) {
throw new LessException( ex );
}
}
/**
* Push a char back to the stream
*
* @param ch
* the char
*/
void back( char ch ) {
cachePos
cache.setCharAt( cachePos, ch );
column--; // reverse of incLineColumn()
}
/**
* Skip all data until a newline occur or an EOF
*
* @throws LessException if an IO error occur
*/
void skipLine() {
int ch;
do {
try {
ch = reader.read();
} catch( IOException ex ) {
throw new LessException( ex );
}
incLineColumn( ch );
} while( ch != '\n' && ch != -1 );
}
/**
* Increment the line and column count depending on the character.
* @param ch current character
* @return the character parameter
*/
private char incLineColumn( int ch ) {
if( ch == '\n' ) {
line++;
column = 0;
} else {
column++;
}
return (char)ch;
}
/**
* The current line number for error messages.
* @return line number
*/
int getLine() {
return line;
}
/**
* The current column number for error messages.
* @return column number.
*/
int getColumn() {
return column;
}
/**
* {@inheritDoc}
*/
@Override
public void close() throws IOException {
reader.close();
}
/**
* If the less file of this reader was import with "reference" keyword.
* @return true, if reference
*/
boolean isReference() {
return isReference;
}
/**
* If the less file of this reader was import with "multiple" keyword.
* @return true, if multiple
*/
boolean isMultiple() {
return isMultiple;
}
}
|
package com.muxter.TemplateMethodPattern;
public class Main {
public static void main(String[] args) {
CaffeineBeverage beverage = new Coffee();
beverage.prepareRecipe();
System.out.println("
beverage = new Tea();
beverage.prepareRecipe();
}
}
|
package com.opencms.flex.jsp;
import com.opencms.file.CmsFile;
import com.opencms.file.CmsObject;
import com.opencms.file.CmsResource;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.Map;
import java.util.Vector;
/**
* Bean to provide a convenient way to build navigation structures based on
* {@link com.opencms.flex.jsp.CmsJspNavElement}.<p>
*
* @author Alexander Kandzior (a.kandzior@alkacon.com)
* @version $Revision: 1.9 $
*
* @see com.opencms.flex.jsp.CmsJspNavElement
*
* @since 5.0
*/
public class CmsJspNavBuilder {
// Member variables
private CmsObject m_cms = null;
private String m_requestUri = null;
private String m_requestUriFolder = null;
/**
* Empty constructor, so that this bean can be initialized from a JSP.<p>
*
* @see java.lang.Object#Object()
*/
public CmsJspNavBuilder() {}
/**
* Default constructor.<p>
*
* @param cms context provider for the current request
*/
public CmsJspNavBuilder(CmsObject cms) {
init(cms);
}
/**
* Initiliazes this bean.<p>
*
* @param cms context provider for the current request
*/
public void init(CmsObject cms) {
m_cms = cms;
m_requestUri = m_cms.getRequestContext().getUri();
m_requestUriFolder = CmsResource.getPath(m_requestUri);
}
/**
* Returns a CmsJspNavElement for the resource of the current request URI.<p>
*
* @return CmsJspNavElement a CmsJspNavElement for the resource of the current request URI
*/
public CmsJspNavElement getNavigationForResource() {
return getNavigationForResource(m_cms, m_requestUri);
}
/**
* Returns a CmsJspNavElement for the named resource.<p>
*
* @param resource the resource name to get the nav information for,
* must be a full path name, e.g. "/docs/index.html".
* @return CmsJspNavElement a CmsJspNavElement for the given resource
*/
public CmsJspNavElement getNavigationForResource(String resource) {
return getNavigationForResource(m_cms, resource);
}
/**
* Returns a CmsJspNavElement for the named resource.<p>
*
* @param cms context provider for the current request
* @param resource the resource name to get the nav information for,
* must be a full path name, e.g. "/docs/index.html".
* @return a CmsJspNavElement for the given resource
*/
public static CmsJspNavElement getNavigationForResource(CmsObject cms, String resource) {
Map properties;
try {
properties = cms.readProperties(resource);
} catch (Exception e) {
return null;
}
int level = CmsResource.getPathLevel(resource);
if (resource.endsWith("/")) level
return new CmsJspNavElement(resource, properties, level);
}
/**
* Collect all navigation elements from the files of the folder of the current request URI,
* navigation elements are of class CmsJspNavElement.<p>
*
* @return a sorted (ascending to nav position) ArrayList of navigation elements.
*/
public ArrayList getNavigationForFolder() {
return getNavigationForFolder(m_cms, m_requestUriFolder);
}
/**
* Collect all navigation elements from the files in the given folder,
* navigation elements are of class CmsJspNavElement.<p>
*
* @param folder the selected folder
* @return A sorted (ascending to nav position) ArrayList of navigation elements.
*/
public ArrayList getNavigationForFolder(String folder) {
return getNavigationForFolder(m_cms, folder);
}
/**
* Collect all navigation elements from the files in the given folder,
* navigation elements are of class CmsJspNavElement.<p>
*
* @param cms context provider for the current request
* @param folder the selected folder
* @return a sorted (ascending to nav position) ArrayList of navigation elements
*/
public static ArrayList getNavigationForFolder(CmsObject cms, String folder) {
folder = CmsFile.getPath(folder);
ArrayList list = new ArrayList();
Vector v = null, dir = null;
try {
// v = cms.getResourcesInFolder(folder);
v = cms.getFilesInFolder(folder);
dir = cms.getSubFolders(folder);
} catch (Exception e) {
return new ArrayList(0);
}
v.addAll(dir);
Iterator i = v.iterator();
while (i.hasNext()) {
CmsResource r = (CmsResource)i.next();
if (r.getState() != CmsResource.C_STATE_DELETED) {
CmsJspNavElement element = getNavigationForResource(cms, r.getAbsolutePath());
if ((element != null) && element.isInNavigation()) {
list.add(element);
}
}
}
Collections.sort(list);
return list;
}
/**
* Build a navigation for the folder that is either minus levels up
* from of the folder of the current request URI, or that is plus levels down from the
* root folder towards the current request URI.<p>
*
* If level is set to zero the root folder is used by convention.<p>
*
* @param level if negative, walk this many levels up, if positive, walk this many
* levels down from root folder
* @return a sorted (ascending to nav position) ArrayList of navigation elements
*/
public ArrayList getNavigationForFolder(int level) {
return getNavigationForFolder(m_cms, m_requestUriFolder, level);
}
/**
* Build a navigation for the folder that is either minus levels up
* from the given folder, or that is plus levels down from the
* root folder towards the given folder.<p>
*
* If level is set to zero the root folder is used by convention.<p>
*
* @param folder the selected folder
* @param level if negative, walk this many levels up, if positive, walk this many
* levels down from root folder
* @return a sorted (ascending to nav position) ArrayList of navigation elements
*/
public ArrayList getNavigationForFolder(String folder, int level) {
return getNavigationForFolder(m_cms, folder, level);
}
/**
* Build a navigation for the folder that is either minus levels up
* from the given folder, or that is plus levels down from the
* root folder towards the given folder.<p>
*
* If level is set to zero the root folder is used by convention.<p>
*
* @param cms context provider for the current request
* @param folder the selected folder
* @param level if negative, walk this many levels up, if positive, walk this many
* levels down from root folder
* @return a sorted (ascending to nav position) ArrayList of navigation elements
*/
public static ArrayList getNavigationForFolder(CmsObject cms, String folder, int level) {
folder = CmsFile.getPath(folder);
// If level is one just use root folder
if (level == 0) return getNavigationForFolder(cms, "/");
String navfolder = CmsResource.getPathPart(folder, level);
// If navfolder found use it to build navigation
if (navfolder != null) return getNavigationForFolder(cms, navfolder);
// Nothing found, return empty list
return new ArrayList(0);
}
/**
* @see #getNavigationTreeForFolder(CmsObject, String, int, int)
*/
public ArrayList getNavigationTreeForFolder(int startlevel, int endlevel) {
return getNavigationTreeForFolder(m_cms, m_requestUriFolder, startlevel, endlevel);
}
/**
* @see #getNavigationTreeForFolder(CmsObject, String, int, int)
*/
public ArrayList getNavigationTreeForFolder(String folder, int startlevel, int endlevel) {
return getNavigationTreeForFolder(m_cms, folder, startlevel, endlevel);
}
/**
* Builds a tree navigation for the folders between the provided start and end level.<p>
*
* A tree navigation includes all nav elements that are required to display a tree structure.
* However, the data structure is a simple list.
* Each of the nav elements in the list has the {@link CmsJspNavElement#getNavTreeLevel()} set
* to the level it belongs to. Use this information to distinguish between the nav levels.<p>
*
* @param cms context provider for the current request
* @param folder the selected folder
* @param startlevel the start level
* @param endlevel the end level
* @return a sorted list of nav elements with the nav tree level property set
*/
public static ArrayList getNavigationTreeForFolder(CmsObject cms, String folder, int startlevel, int endlevel) {
folder = CmsFile.getPath(folder);
// Make sure start and end level make sense
if (endlevel < startlevel) return new ArrayList(0);
int currentlevel = CmsResource.getPathLevel(folder);
if (currentlevel < endlevel) endlevel = currentlevel;
if (startlevel == endlevel) return getNavigationForFolder(cms, CmsResource.getPathPart(folder, startlevel), startlevel);
ArrayList result = new ArrayList(0);
Iterator it = null;
float parentcount = 0;
for (int i=startlevel; i<=endlevel; i++) {
String currentfolder = CmsResource.getPathPart(folder, i);
ArrayList entries = getNavigationForFolder(cms, currentfolder);
// Check for parent folder
if (parentcount > 0) {
it = entries.iterator();
while (it.hasNext()) {
CmsJspNavElement e = (CmsJspNavElement)it.next();
e.setNavPosition(e.getNavPosition() + parentcount);
}
}
// Add new entries to result
result.addAll(entries);
Collections.sort(result);
// Finally spread the values of the nav items so that there is enough room for further items.
float pos = 0;
int count = 0;
it = result.iterator();
String nextfolder = CmsResource.getPathPart(folder, i+1);
parentcount = 0;
while (it.hasNext()) {
pos = 10000 * (++count);
CmsJspNavElement e = (CmsJspNavElement)it.next();
e.setNavPosition(pos);
if (e.getResourceName().startsWith(nextfolder)) parentcount = pos;
}
if (parentcount == 0) parentcount = pos;
}
return result;
}
/**
* @see #getNavigationBreadCrumb(String, int, int, boolean)
*/
public ArrayList getNavigationBreadCrumb() {
return getNavigationBreadCrumb(m_requestUriFolder, 0, -1, true);
}
/**
* @see #getNavigationBreadCrumb(String, int, int, boolean)
*/
public ArrayList getNavigationBreadCrumb(int startlevel, int endlevel) {
return getNavigationBreadCrumb(m_requestUriFolder, startlevel, endlevel, true);
}
/**
* @see #getNavigationBreadCrumb(String, int, int, boolean)
*/
public ArrayList getNavigationBreadCrumb(int startlevel, boolean currentFolder) {
return getNavigationBreadCrumb(m_requestUriFolder, startlevel, -1, currentFolder);
}
/**
* Build a "bread crump" path navigation to the given folder.<p>
*
* The startlevel marks the point where the navigation starts from, if negative,
* the count of steps to go down from the given folder.
* The endlevel is the maximum level of the navigation path, set it to -1 to build the
* complete navigation to the given folder.
* You can include the given folder in the navigation by setting currentFolder to true,
* otherwise false.<p>
*
* @param folder the selected folder
* @param startlevel the start level, if negative, go down |n| steps from selected folder
* @param endlevel the end level, if -1, build navigation to selected folder
* @param currentFolder include the selected folder in navigation or not
* @return ArrayList sorted list of navigation elements
*/
public ArrayList getNavigationBreadCrumb(String folder, int startlevel, int endlevel, boolean currentFolder) {
ArrayList result = new ArrayList(0);
int level = CmsResource.getPathLevel(folder);
// decrease folder level if current folder is not displayed
if (!currentFolder) {
level -= 1;
}
// check current level and change endlevel if it is higher or -1
if (level < endlevel || endlevel == -1) {
endlevel = level;
}
// if startlevel is negative, display only |startlevel| links
if (startlevel < 0) {
startlevel = endlevel + startlevel +1;
if (startlevel < 0) {
startlevel = 0;
}
}
// create the list of navigation elements
for (int i=startlevel; i<=endlevel; i++) {
String navFolder = CmsResource.getPathPart(folder, i);
CmsJspNavElement e = getNavigationForResource(navFolder);
// add element to list
result.add(e);
}
return result;
}
/**
* This method builds a complete navigation tree with entries of all branches
* from the specified folder.<p>
*
* For an unlimited depth of the navigation (i.e. no endLevel), set the endLevel to
* a value < 0.<p>
*
*
* @param cms the current CmsJspActionElement.
* @param folder the root folder of the navigation tree.
* @param endLevel the end level of the navigation.
* @return ArrayList of CmsJspNavElement, in depth first order.
*/
public static ArrayList getSiteNavigation(CmsObject cms, String folder, int endLevel){
// check if a specific end level was given, if not, build the complete navigation
boolean noLimit = false;
if (endLevel < 0) {
noLimit = true;
}
ArrayList list = new ArrayList();
// get the navigation for this folder
ArrayList curnav = getNavigationForFolder(cms, folder);
Iterator i = curnav.iterator();
// loop through all nav entrys
while (i.hasNext()) {
CmsJspNavElement ne = (CmsJspNavElement)i.next();
// add the naventry to the result list
list.add(ne);
// check if naventry is a folder and below the max level -> if so, get the navigation from this folder as well
if (ne.isFolderLink() && (noLimit || (ne.getNavTreeLevel() < endLevel))) {
ArrayList subnav = getSiteNavigation(cms, ne.getResourceName(), endLevel);
// copy the result of the subfolder to the result list
list.addAll(subnav);
}
}
return list;
}
/**
* This method builds a complete navigation tree with entries of all branches
* from the specified folder.<p>
*
* @see #getSiteNavigation(CmsObject, String, int)
*
* @param folder folder the root folder of the navigation tree.
* @param endLevel the end level of the navigation.
* @return ArrayList of CmsJspNavElement, in depth first order.
*/
public ArrayList getSiteNavigation(String folder, int endLevel) {
return getSiteNavigation(m_cms, folder, endLevel);
}
/**
* This method builds a complete site navigation tree with entries of all branches.<p>
*
* @see #getSiteNavigation(CmsObject, String, int)
*
* @return ArrayList of CmsJspNavElement, in depth first order.
*/
public ArrayList getSiteNavigation() {
return getSiteNavigation(m_cms, "/", -1);
}
/**
* Returns all subfolders of a sub channel that has
* the given parent channel, or an empty array if
* that combination does not exist or has no subfolders.<p>
*
* @param parentChannel the parent channel
* @param subChannel the sub channel
* @return an unsorted list of CmsResources
*/
public ArrayList getChannelSubFolders(String parentChannel, String subChannel) {
return getChannelSubFolders(m_cms, parentChannel, subChannel);
}
/**
* Returns all subfolders of a sub channel that has
* the given parent channel, or an empty array if
* that combination does not exist or has no subfolders.<p>
*
* @param cms context provider for the current request
* @param parentChannel the parent channel
* @param subChannel the sub channel
* @return an unsorted list of CmsResources
*/
public static ArrayList getChannelSubFolders(CmsObject cms, String parentChannel, String subChannel) {
String channel = null;
if (subChannel == null) {
subChannel = "";
} else if (subChannel.startsWith("/")) {
subChannel = subChannel.substring(1);
}
if (parentChannel == null) parentChannel = "";
if (parentChannel.endsWith("/")) {
channel = parentChannel + subChannel;
} else {
channel = parentChannel + "/" + subChannel;
}
return getChannelSubFolders(cms, channel);
}
/**
* Returns all subfolders of a channel, or an empty array if
* the folder does not exist or has no subfolders.<p>
*
* @param channel the channel to look for subfolders in
* @return an unsorted list of CmsResources
*/
public ArrayList getChannelSubFolders(String channel) {
return getChannelSubFolders(m_cms, channel);
}
/**
* Returns all subfolders of a channel, or an empty array if
* the folder does not exist or has no subfolders.<p>
*
* @param cms context provider for the current request
* @param channel the channel to look for subfolders in
* @return an unsorted list of CmsResources
*/
public static ArrayList getChannelSubFolders(CmsObject cms, String channel) {
if (! channel.startsWith("/")) channel = "/" + channel;
if (! channel.endsWith("/")) channel += "/";
// Now read all subchannels of this channel
java.util.Vector subChannels = new java.util.Vector();
try {
cms.setContextToCos();
subChannels = cms.getSubFolders(channel);
} catch (Exception e) {
System.err.println("Exception: " + e);
} finally {
cms.setContextToVfs();
}
// Create an ArrayList out of the Vector
java.util.ArrayList list = new java.util.ArrayList(subChannels.size());
list.addAll(subChannels);
return list;
}
/**
* Returns all subfolders of a channel,
* sorted by "Title" property ascending, or an empty array if
* the folder does not exist or has no subfolders.
*
* @param channel the parent channel
* @param subChannel the sub channel
* @return a sorted list of CmsResources
*/
public ArrayList getChannelSubFoldersSortTitleAsc(String channel, String subChannel) {
return getChannelSubFoldersSortTitleAsc(m_cms, channel, subChannel);
}
/**
* Returns all subfolders of a channel,
* sorted by "Title" property ascending, or an empty array if
* the folder does not exist or has no subfolders.
*
* @param cms context provider for the current request
* @param channel the parent channel
* @param subChannel the sub channel
* @return a sorted list of CmsResources
*/
public static ArrayList getChannelSubFoldersSortTitleAsc(CmsObject cms, String channel, String subChannel) {
ArrayList subChannels = getChannelSubFolders(cms, channel, subChannel);
// Create an ArrayList out of the Vector
java.util.ArrayList tmpList = new java.util.ArrayList(subChannels.size());
Iterator i = subChannels.iterator();
while (i.hasNext()) {
CmsResource res = (CmsResource)i.next();
ResourceTitleContainer container = new ResourceTitleContainer(cms, res);
tmpList.add(container);
}
Collections.sort(tmpList);
java.util.ArrayList list = new java.util.ArrayList(subChannels.size());
i = tmpList.iterator();
while (i.hasNext()) {
ResourceTitleContainer container = (ResourceTitleContainer)i.next();
list.add(container.m_res);
}
return list;
}
/**
* Internal helper class to get a title - comparable CmsResource for channels.<p>
*/
private static class ResourceTitleContainer implements Comparable {
// member variables
public CmsResource m_res = null;
public String m_title = null;
/**
* @param cms context provider for the current request
* @param res the resource to compare
*/
ResourceTitleContainer(CmsObject cms, CmsResource res) {
m_res = res;
try {
cms.setContextToCos();
m_title = cms.readProperty(res.getAbsolutePath(), com.opencms.core.I_CmsConstants.C_PROPERTY_TITLE);
cms.setContextToVfs();
} catch (Exception e) {
m_title = "";
}
}
/**
* @see java.lang.Comparable#compareTo(Object)
*/
public int compareTo(Object obj) {
if (! (obj instanceof ResourceTitleContainer)) return 0;
if (m_title == null) return 1;
return (m_title.toLowerCase().compareTo(((ResourceTitleContainer)obj).m_title.toLowerCase()));
}
}
}
|
package com.telmomenezes.synthetic.cli;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.CommandLineParser;
import org.apache.commons.cli.GnuParser;
import org.apache.commons.cli.HelpFormatter;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.ParseException;
/**
* @author telmo
*
*/
public class SynCLI {
private Options options;
private CommandLine cline;
private void printHelpMessage() {
HelpFormatter formatter = new HelpFormatter();
formatter.printHelp("syn", options);
}
private void printErrorMessage(String msg) {
System.err.println(msg);
printHelpMessage();
}
public void run(String[] args) {
//args = new String[]{"evo", "-inet", "ownership.txt", "-odir", "test"};
//args = new String[]{"evo", "-inet", "/Users/telmo/Desktop/Networks/polblogs/polblogs.gml", "-odir", "test"};
//args = new String[]{"evo", "-inet", "celegansneural.gml", "-odir", "test", "-gentype", "full"};
CommandLineParser parser = new GnuParser();
options = new Options();
options.addOption("inet", true, "input net file");
options.addOption("inet2", true, "second input net file");
options.addOption("odir", true, "output directory");
options.addOption("prg", true, "generator program file");
options.addOption("oprg", true, "generator output program file");
options.addOption("gentype", true, "generator type (FAST / full)");
options.addOption("gens", true, "number of generations");
options.addOption("bins", true, "number of distribution bins");
options.addOption("maxnodes", true, "max nodes (sampling)");
options.addOption("maxedges", true, "max edges (sampling)");
try {
cline = parser.parse(options, args);
String cmd = args[0];
Command cmdObj = null;
if (cmd.equals("help")) {
printHelpMessage();
}
else if (cmd.equals("netstats")) {
cmdObj = new NetStats();
}
else if (cmd.equals("evo")) {
cmdObj = new Evolve();
}
else {
printErrorMessage("Command '" + cmd + "' does not exist.");
}
if (cmdObj != null) {
if (!cmdObj.run(cline)) {
printErrorMessage(cmdObj.getErrorMessage());
}
}
}
catch (ParseException e) {
String msg = e.getMessage();
if (msg == null) {
msg = "unkown error";
}
printErrorMessage(msg);
}
System.exit(0);
}
public static void main(String[] args) {
(new SynCLI()).run(args);
}
}
|
package com.valkryst.VTerminal;
import com.valkryst.VRadio.Radio;
import com.valkryst.VTerminal.misc.ImageCache;
import lombok.Getter;
import lombok.NonNull;
import lombok.Setter;
import lombok.ToString;
import javax.swing.Timer;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.Rectangle;
import java.util.Objects;
@ToString
public class AsciiCharacter {
/** The hash value, of the character, used by the image cache. */
@Getter protected int cacheHash;
/** Whether or not to update the cache hash. */
protected boolean updateCacheHash = true;
/** The character. */
@Getter private char character;
/** Whether or not the foreground should be drawn using the background color. */
@Getter @Setter private boolean isHidden = false;
/** The background color. Defaults to black. */
@Getter private Color backgroundColor = Color.BLACK;
/** The foreground color. Defaults to white. */
@Getter private Color foregroundColor = Color.WHITE;
/** The bounding box of the character's area. */
@Getter private final Rectangle boundingBox;
/** Whether or not to draw the character as underlined. */
@Getter @Setter private boolean isUnderlined = false;
/** The thickness of the underline to draw beneath the character. */
@Getter private int underlineThickness = 2;
/** Whether or not the character should be flipped horizontally when drawn. */
@Getter private boolean isFlippedHorizontally = false;
/** Whether or not the character should be flipped vertically when drawn. */
@Getter private boolean isFlippedVertically = false;
private Timer blinkTimer;
/** The amount of time, in milliseconds, before the blink effect can occur. */
@Getter private short millsBetweenBlinks = 1000;
@Getter private boolean foregroundAndBackgroundColorEqual = false;
/**
* Constructs a new AsciiCharacter.
*
* @param character
* The character.
*/
public AsciiCharacter(final char character) {
this.character = character;
boundingBox = new Rectangle();
}
/**
* Constructs a new AsciiCharacter by copying the data of an AsciiCharacter.
*
* Does not copy the blinkTimer.
*
* @param character
* The AsciiCharacter.
*
* @throws NullPointerException
* If the character is null.
*/
public AsciiCharacter(final @NonNull AsciiCharacter character) {
boundingBox = new Rectangle();
copy(character);
}
/**
* Copies the settings of an AsciiCharacter to this AsciiCharacter.
*
* Does not copy the blinkTimer.
*
* @param character
* The other AsciiCharacter.
*/
public void copy(final @NonNull AsciiCharacter character) {
this.character = character.getCharacter();
isHidden = character.isHidden();
backgroundColor = character.getBackgroundColor();
foregroundColor = character.getForegroundColor();
boundingBox.setSize(character.getBoundingBox().getSize());
boundingBox.setLocation(character.getBoundingBox().getLocation());
isUnderlined = character.isUnderlined();
underlineThickness = character.getUnderlineThickness();
isFlippedHorizontally = character.isFlippedHorizontally();
isFlippedVertically = character.isFlippedVertically();
foregroundAndBackgroundColorEqual = character.isForegroundAndBackgroundColorEqual();
updateCacheHash = true;
}
/** Updates the cache hash value. */
protected void updateCacheHash() {
cacheHash = Objects.hash(character, backgroundColor, foregroundColor, isFlippedHorizontally, isFlippedVertically);
}
/**
* Draws the character onto the specified context.
*
* @param gc
* The graphics context to draw with.
*
* @param imageCache
* The image cache to retrieve character images from.
*
* @param columnIndex
* The x-axis (column) coordinate where the character is to be drawn.
*
* @param rowIndex
* The y-axis (row) coordinate where the character is to be drawn.
*
* @throws NullPointerException
* If the gc or image cache are null.
*/
public void draw(final @NonNull Graphics2D gc, final @NonNull ImageCache imageCache, int columnIndex, int rowIndex) {
if (updateCacheHash) {
updateCacheHash();
updateCacheHash = false;
}
final int fontWidth = imageCache.getFont().getWidth();
final int fontHeight = imageCache.getFont().getHeight();
columnIndex *= fontWidth;
rowIndex *= fontHeight;
boundingBox.setLocation(columnIndex, rowIndex);
boundingBox.setSize(fontWidth, fontHeight);
// Handle hidden state:
if (isHidden || isForegroundAndBackgroundColorEqual()) {
gc.setColor(backgroundColor);
gc.fillRect(columnIndex, rowIndex, fontWidth, fontHeight);
} else {
final Image image = imageCache.retrieveFromCache(this);
gc.drawImage(image, columnIndex, rowIndex, null);
// Draw underline:
if (isUnderlined) {
gc.setColor(foregroundColor);
final int y = rowIndex + fontHeight - underlineThickness;
gc.fillRect(columnIndex, y, fontWidth, underlineThickness);
}
}
}
/**
* Enables the blink effect.
*
* @param millsBetweenBlinks
* The amount of time, in milliseconds, before the blink effect can occur.
*
* @param radio
* The Radio to transmit a DRAW event to whenever a blink occurs.
*/
public void enableBlinkEffect(final short millsBetweenBlinks, final Radio<String> radio) {
if (radio == null) {
throw new NullPointerException("You must specify a Radio when enabling a blink effect.");
}
if (millsBetweenBlinks <= 0) {
this.millsBetweenBlinks = 1000;
} else {
this.millsBetweenBlinks = millsBetweenBlinks;
}
blinkTimer = new Timer(this.millsBetweenBlinks, e -> {
isHidden = !isHidden;
radio.transmit("DRAW");
});
blinkTimer.setInitialDelay(this.millsBetweenBlinks);
blinkTimer.setRepeats(true);
blinkTimer.start();
}
/** Disables the blink effect. */
public void disableBlinkEffect() {
if (blinkTimer != null) {
blinkTimer.stop();
blinkTimer = null;
}
}
/** Swaps the background and foreground colors. */
public void invertColors() {
final Color temp = backgroundColor;
setBackgroundColor(foregroundColor);
setForegroundColor(temp);
}
/**
* Sets the new character.
*
* @param character
* The new character.
*/
public void setCharacter(final char character) {
if (this.character != character) {
this.character = character;
updateCacheHash = true;
}
}
/**
* Sets the new background color.
*
* @param color
* The new background color.
*
* @throws NullPointerException
* If the color is null.
*/
public void setBackgroundColor(final @NonNull Color color) {
if (backgroundColor.equals(color) == false) {
backgroundColor = color;
updateCacheHash = true;
foregroundAndBackgroundColorEqual = foregroundColor.equals(backgroundColor);
}
}
/**
* Sets the new foreground color.
*
* @param color
* The new foreground color.
*
* @throws NullPointerException
* If the color is null.
*/
public void setForegroundColor(final @NonNull Color color) {
if (foregroundColor.equals(color) == false) {
foregroundColor = color;
updateCacheHash = true;
foregroundAndBackgroundColorEqual = foregroundColor.equals(backgroundColor);
}
}
/**
* Sets whether or not the character is flipped horizontally.
*
* @param isFlippedHorizontally
* Whether or not the character is flipped horizontally.
*/
public void setFlippedHorizontally(final boolean isFlippedHorizontally) {
if (this.isFlippedHorizontally != isFlippedHorizontally) {
this.isFlippedHorizontally = isFlippedHorizontally;
updateCacheHash = true;
}
}
/**
* Sets whether or not the character is flipped vertically.
*
* @param isFlippedVertically
* Whether or not the character is flipped vertically.
*/
public void setFlippedVertically(final boolean isFlippedVertically) {
if (this.isFlippedVertically != isFlippedVertically) {
this.isFlippedVertically = isFlippedVertically;
updateCacheHash = true;
}
}
/**
* Sets the new underline thickness.
*
* If the specified thickness is negative, then the thickness is set to 1.
*
* If the specified thickness is greater than the font height, then the
* thickness is set to the font height.
*
* If the font height is greater than Byte.MAX_VALUE, then the thickness is
* set to Byte.MAX_VALUE.
*
* @param underlineThickness
* The new underline thickness.
*/
public void setUnderlineThickness(final int underlineThickness) {
if (underlineThickness > boundingBox.getHeight()) {
this.underlineThickness = (int) boundingBox.getHeight();
} else if (underlineThickness <= 0) {
this.underlineThickness = 1;
} else {
this.underlineThickness = underlineThickness;
}
}
}
|
package de.diddiz.utils.formatters;
import java.text.MessageFormat;
import java.util.Collection;
import java.util.Iterator;
public class Formatters
{
/**
* Transforms all values to a {@code String} and returns the as array.
*/
public static <T> String[] format(Collection<T> col, Formatter<T> formatter) {
final String[] entries = new String[col.size()];
int idx = 0;
for (final Iterator<T> itr = col.iterator(); itr.hasNext();)
entries[idx++] = formatter.format(itr.next());
return entries;
}
/**
* Divides each {@code Integer} by {@code max} and returns it in percent format.
*/
public static Formatter<Integer> normalizingPercentFormatter(final float max) {
return new Formatter<Integer>() {
private final MessageFormat format = new MessageFormat("{0,number,0.0%}");
@Override
public String format(Integer integer) {
return format.format(new Object[]{integer / max});
}
};
}
/**
* A formatter that simply returns toString().
*/
@SuppressWarnings("unchecked")
public static <T> Formatter<T> toStringFormatter() {
return (Formatter<T>)ToStringFormatter.INSTANCE;
}
private static class ToStringFormatter implements Formatter<Object>
{
private static final Formatter<Object> INSTANCE = new ToStringFormatter();
@Override
public String format(Object obj) {
return obj.toString();
}
}
}
|
package com.net2plan.gui.plugins.networkDesign.viewEditTopolTables.specificTables;
import cern.colt.matrix.tdouble.DoubleFactory1D;
import cern.colt.matrix.tdouble.DoubleMatrix1D;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import com.net2plan.gui.plugins.GUINetworkDesign;
import com.net2plan.gui.plugins.networkDesign.CellRenderers;
import com.net2plan.gui.plugins.networkDesign.interfaces.ITableRowFilter;
import com.net2plan.gui.plugins.networkDesign.viewEditTopolTables.tableVisualizationFilters.TBFToFromCarriedTraffic;
import com.net2plan.gui.utils.*;
import com.net2plan.interfaces.networkDesign.*;
import com.net2plan.internal.Constants.NetworkElementType;
import com.net2plan.internal.ErrorHandling;
import com.net2plan.libraries.GraphUtils;
import com.net2plan.utils.CollectionUtils;
import com.net2plan.utils.StringUtils;
import com.net2plan.utils.SwingUtils;
import net.miginfocom.swing.MigLayout;
import javax.swing.*;
import javax.swing.border.LineBorder;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableModel;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import java.util.List;
@SuppressWarnings("unchecked")
public class AdvancedJTable_route extends AdvancedJTable_networkElement
{
private static final int COLUMN_ID = 0;
private static final int COLUMN_INDEX = 1;
private static final int COLUMN_DEMAND = 2;
private static final int COLUMN_INGRESSNODE = 3;
private static final int COLUMN_EGRESSNODE = 4;
private static final int COLUMN_DEMANDOFFEREDTRAFFIC = 5;
private static final int COLUMN_CARRIEDTRAFFIC = 6;
private static final int COLUMN_OCCUPIEDCAPACITY = 7;
private static final int COLUMN_SEQUENCEOFLINKSANDRESOURCES = 8;
private static final int COLUMN_SEQUENCEOFNODES = 9;
private static final int COLUMN_NUMHOPS = 10;
private static final int COLUMN_LENGTH = 11;
private static final int COLUMN_PROPDELAY = 12;
private static final int COLUMN_BOTTLENECKUTILIZATION = 13;
private static final int COLUMN_ISBACKUP = 14;
private static final int COLUMN_HASBACKUPROUTES = 15;
private static final int COLUMN_TAGS = 16;
private static final int COLUMN_ATTRIBUTES = 17;
private static final String netPlanViewTabName = "Routes";
private static final String[] netPlanViewTableHeader = StringUtils.arrayOf("Unique identifier", "Index", "Demand", "Ingress node", "Egress node",
"Demand offered traffic", "Carried traffic", "Occupied capacity", "Sequence of links/resources", "Sequence of nodes", "Number of hops", "Length (km)",
"Propagation delay (ms)", "Bottleneck utilization", "Is backup?", "Has backup?", "Tags", "Attributes");
private static final String[] netPlanViewTableTips = StringUtils.arrayOf(
"Unique identifier (never repeated in the same netPlan object, never changes, long)", "Index (consecutive integer starting in zero)", "Demand", "Ingress node", "Egress node", "Demand offered traffic",
"Carried traffic", "Occupied capacity", "Sequence of indexes of the links (Lxx) and resources (Rxx) traversed",
"Sequence of nodes traversed, in parenthesis the indexes of the resources in each node",
"Number of hops", "Total route length", "Propagation delay (ms)", "Highest utilization among all traversed links",
"Indicates if this route is designated as a backup route, of other route for the same demand. If so, shows the index of the primary route that this route is backing up",
"Indicates if this route has backup routes. If so, their indexes are shown in parenthesis",
"Route-specific tags", "Route-specific attributes");
public AdvancedJTable_route(final GUINetworkDesign callback)
{
super(createTableModel(callback), callback, NetworkElementType.ROUTE, true);
setDefaultCellRenderers(callback);
setSpecificCellRenderers();
setColumnRowSortingFixedAndNonFixedTable();
fixedTable.setDefaultRenderer(Boolean.class, this.getDefaultRenderer(Boolean.class));
fixedTable.setDefaultRenderer(Double.class, this.getDefaultRenderer(Double.class));
fixedTable.setDefaultRenderer(Object.class, this.getDefaultRenderer(Object.class));
fixedTable.setDefaultRenderer(Float.class, this.getDefaultRenderer(Float.class));
fixedTable.setDefaultRenderer(Long.class, this.getDefaultRenderer(Long.class));
fixedTable.setDefaultRenderer(Integer.class, this.getDefaultRenderer(Integer.class));
fixedTable.setDefaultRenderer(String.class, this.getDefaultRenderer(String.class));
fixedTable.getTableHeader().setDefaultRenderer(new CellRenderers.FixedTableHeaderRenderer());
}
public static int getBottleneckColumnIndex()
{
return COLUMN_BOTTLENECKUTILIZATION;
}
public List<Object[]> getAllData(NetPlan currentState, ArrayList<String> attributesColumns)
{
List<Object[]> allRouteData = new LinkedList<Object[]>();
final List<Route> rowVisibleRoutes = getVisibleElementsInTable();
for (Route route : rowVisibleRoutes)
{
final Demand demand = route.getDemand();
final double maxUtilization = route.getSeqLinks().stream().mapToDouble(e -> e.getUtilization()).max().orElse(0);
final Node ingressNode = route.getDemand().getIngressNode();
final Node egressNode = route.getDemand().getEgressNode();
final String ingressNodeName = ingressNode.getName();
final String egressNodeName = egressNode.getName();
final Object[] routeData = new Object[netPlanViewTableHeader.length + attributesColumns.size()];
routeData[COLUMN_ID] = route.getId();
routeData[COLUMN_INDEX] = route.getIndex();
routeData[COLUMN_DEMAND] = demand.getIndex();
routeData[COLUMN_INGRESSNODE] = ingressNode.getIndex() + (ingressNodeName.isEmpty() ? "" : " (" + ingressNodeName + ")");
routeData[COLUMN_EGRESSNODE] = egressNode.getIndex() + (egressNodeName.isEmpty() ? "" : " (" + egressNodeName + ")");
routeData[COLUMN_DEMANDOFFEREDTRAFFIC] = demand.getOfferedTraffic();
routeData[COLUMN_CARRIEDTRAFFIC] = route.getCarriedTraffic();
routeData[COLUMN_OCCUPIEDCAPACITY] = getSequenceOccupiedCapacities(route);
routeData[COLUMN_SEQUENCEOFLINKSANDRESOURCES] = getSequenceLinkResourceIndexes(route);
routeData[COLUMN_SEQUENCEOFNODES] = getSequenceNodeIndexesWithResourceInfo(route);
routeData[COLUMN_NUMHOPS] = route.getNumberOfHops();
routeData[COLUMN_LENGTH] = route.getLengthInKm();
routeData[COLUMN_PROPDELAY] = route.getPropagationDelayInMiliseconds();
routeData[COLUMN_BOTTLENECKUTILIZATION] = maxUtilization;
routeData[COLUMN_ISBACKUP] = (route.isBackupRoute() ? "yes (" + (CollectionUtils.join(NetPlan.getIndexes(route.getRoutesIAmBackup()), ", ")) + ")" : "no");
routeData[COLUMN_HASBACKUPROUTES] = (route.hasBackupRoutes() ? "yes (" + (CollectionUtils.join(NetPlan.getIndexes(route.getBackupRoutes()), ", ")) + ")" : "no");
routeData[COLUMN_TAGS] = StringUtils.listToString(Lists.newArrayList(route.getTags()));
routeData[COLUMN_ATTRIBUTES] = StringUtils.mapToString(route.getAttributes());
for (int i = netPlanViewTableHeader.length; i < netPlanViewTableHeader.length + attributesColumns.size(); i++)
{
if (route.getAttributes().containsKey(attributesColumns.get(i - netPlanViewTableHeader.length)))
{
routeData[i] = route.getAttribute(attributesColumns.get(i - netPlanViewTableHeader.length));
}
}
allRouteData.add(routeData);
}
/* Add the aggregation row with the aggregated statistics */
final double aggDemandOffered = rowVisibleRoutes.stream().mapToDouble(e -> e.getDemand().getOfferedTraffic()).sum();
final double aggCarried = rowVisibleRoutes.stream().mapToDouble(e -> e.getCarriedTraffic()).sum();
final double aggLinkOccupied = rowVisibleRoutes.stream().mapToDouble(e -> e.isDown() ? 0 : e.getSeqOccupiedCapacitiesIfNotFailing().stream().mapToDouble(ee -> ee).sum()).sum();
final int aggMaxNumHops = rowVisibleRoutes.stream().mapToInt(e -> e.getNumberOfHops()).sum();
final double aggMaxLength = rowVisibleRoutes.stream().mapToDouble(e -> e.getLengthInKm()).sum();
final double aggMaxPropDelay = rowVisibleRoutes.stream().mapToDouble(e -> e.getPropagationDelayInMiliseconds()).sum();
final int aggIsBackup = (int) rowVisibleRoutes.stream().filter(e -> e.isBackupRoute()).count();
final int aggHasBackup = (int) rowVisibleRoutes.stream().filter(e -> e.hasBackupRoutes()).count();
final LastRowAggregatedValue[] aggregatedData = new LastRowAggregatedValue[netPlanViewTableHeader.length + attributesColumns.size()];
Arrays.fill(aggregatedData, new LastRowAggregatedValue());
aggregatedData[COLUMN_DEMANDOFFEREDTRAFFIC] = new LastRowAggregatedValue(aggDemandOffered);
aggregatedData[COLUMN_CARRIEDTRAFFIC] = new LastRowAggregatedValue(aggCarried);
aggregatedData[COLUMN_OCCUPIEDCAPACITY] = new LastRowAggregatedValue(aggLinkOccupied);
aggregatedData[COLUMN_NUMHOPS] = new LastRowAggregatedValue(aggMaxNumHops);
aggregatedData[COLUMN_LENGTH] = new LastRowAggregatedValue(aggMaxLength);
aggregatedData[COLUMN_PROPDELAY] = new LastRowAggregatedValue(aggMaxPropDelay);
aggregatedData[COLUMN_ISBACKUP] = new LastRowAggregatedValue(aggIsBackup);
aggregatedData[COLUMN_HASBACKUPROUTES] = new LastRowAggregatedValue(aggHasBackup);
allRouteData.add(aggregatedData);
return allRouteData;
}
public String getTabName()
{
return netPlanViewTabName;
}
public String[] getTableHeaders()
{
return netPlanViewTableHeader;
}
public String[] getCurrentTableHeaders()
{
ArrayList<String> attColumnsHeaders = getAttributesColumnsHeaders();
String[] headers = new String[netPlanViewTableHeader.length + attColumnsHeaders.size()];
for (int i = 0; i < headers.length; i++)
{
if (i < netPlanViewTableHeader.length)
{
headers[i] = netPlanViewTableHeader[i];
} else
{
headers[i] = "Att: " + attColumnsHeaders.get(i - netPlanViewTableHeader.length);
}
}
return headers;
}
public String[] getTableTips()
{
return netPlanViewTableTips;
}
public boolean hasElements()
{
final ITableRowFilter rf = callback.getVisualizationState().getTableRowFilter();
final NetworkLayer layer = callback.getDesign().getNetworkLayerDefault();
return rf == null ? callback.getDesign().hasRoutes(layer) : rf.hasRoutes(layer);
}
@Override
public int getAttributesColumnIndex()
{
return COLUMN_ATTRIBUTES;
}
// public int[] getColumnsOfSpecialComparatorForSorting() {
// return new int[]{};
private static TableModel createTableModel(final GUINetworkDesign callback)
{
TableModel routeTableModel = new ClassAwareTableModel(new Object[1][netPlanViewTableHeader.length], netPlanViewTableHeader)
{
private static final long serialVersionUID = 1L;
@Override
public boolean isCellEditable(int rowIndex, int columnIndex)
{
if (!callback.getVisualizationState().isNetPlanEditable()) return false;
if (columnIndex >= netPlanViewTableHeader.length) return true;
if (getValueAt(rowIndex, columnIndex) == null) return false;
if (rowIndex == getRowCount() - 1) return false;
return columnIndex == COLUMN_CARRIEDTRAFFIC || columnIndex == COLUMN_OCCUPIEDCAPACITY
|| columnIndex >= netPlanViewTableHeader.length;
}
@Override
public void setValueAt(Object newValue, int row, int column)
{
Object oldValue = getValueAt(row, column);
if (newValue.equals(oldValue)) return;
NetPlan netPlan = callback.getDesign();
if (getValueAt(row, 0) == null) row = row - 1;
final long routeId = (Long) getValueAt(row, 0);
final Route route = netPlan.getRouteFromId(routeId);
/* Perform checks, if needed */
try
{
switch (column)
{
case COLUMN_CARRIEDTRAFFIC:
route.setCarriedTraffic(Double.parseDouble(newValue.toString()), route.getOccupiedCapacity());
callback.updateVisualizationAfterChanges(Sets.newHashSet(NetworkElementType.ROUTE));
callback.getVisualizationState().pickRoute(route);
callback.updateVisualizationAfterPick();
callback.addNetPlanChange();
break;
case COLUMN_OCCUPIEDCAPACITY:
route.setCarriedTraffic(route.getCarriedTraffic(), Double.parseDouble(newValue.toString()));
callback.updateVisualizationAfterChanges(Sets.newHashSet(NetworkElementType.ROUTE));
callback.getVisualizationState().pickRoute(route);
callback.updateVisualizationAfterPick();
callback.addNetPlanChange();
break;
default:
break;
}
} catch (Throwable ex)
{
ErrorHandling.showErrorDialog(ex.getMessage(), "Error modifying route");
return;
}
/* Set new value */
super.setValueAt(newValue, row, column);
}
};
return routeTableModel;
}
private void setDefaultCellRenderers(final GUINetworkDesign callback)
{
setDefaultRenderer(Boolean.class, new CellRenderers.CheckBoxRenderer());
setDefaultRenderer(Double.class, new CellRenderers.NumberCellRenderer());
setDefaultRenderer(Object.class, new CellRenderers.NonEditableCellRenderer());
setDefaultRenderer(Float.class, new CellRenderers.NumberCellRenderer());
setDefaultRenderer(Long.class, new CellRenderers.NumberCellRenderer());
setDefaultRenderer(Integer.class, new CellRenderers.NumberCellRenderer());
setDefaultRenderer(String.class, new CellRenderers.NonEditableCellRenderer());
setDefaultRenderer(Boolean.class, new CellRenderers.RouteRenderer(getDefaultRenderer(Boolean.class), callback));
setDefaultRenderer(Double.class, new CellRenderers.RouteRenderer(getDefaultRenderer(Double.class), callback));
setDefaultRenderer(Object.class, new CellRenderers.RouteRenderer(getDefaultRenderer(Object.class), callback));
setDefaultRenderer(Float.class, new CellRenderers.RouteRenderer(getDefaultRenderer(Float.class), callback));
setDefaultRenderer(Long.class, new CellRenderers.RouteRenderer(getDefaultRenderer(Long.class), callback));
setDefaultRenderer(Integer.class, new CellRenderers.RouteRenderer(getDefaultRenderer(Integer.class), callback));
setDefaultRenderer(String.class, new CellRenderers.RouteRenderer(getDefaultRenderer(String.class), callback));
}
private void setSpecificCellRenderers()
{
}
@Override
public void setColumnRowSortingFixedAndNonFixedTable()
{
setAutoCreateRowSorter(true);
final Set<Integer> columnsWithDoubleAndThenParenthesis = Sets.newHashSet();
DefaultRowSorter rowSorter = ((DefaultRowSorter) getRowSorter());
for (int col = 0; col <= COLUMN_ATTRIBUTES; col++)
rowSorter.setComparator(col, new AdvancedJTable_networkElement.ColumnComparator(rowSorter, columnsWithDoubleAndThenParenthesis.contains(col)));
fixedTable.setAutoCreateRowSorter(true);
fixedTable.setRowSorter(this.getRowSorter());
rowSorter = ((DefaultRowSorter) fixedTable.getRowSorter());
for (int col = 0; col <= COLUMN_ATTRIBUTES; col++)
rowSorter.setComparator(col, new AdvancedJTable_networkElement.ColumnComparator(rowSorter, columnsWithDoubleAndThenParenthesis.contains(col)));
}
public int getNumberOfDecoratorColumns()
{
return 2;
}
@Override
public ArrayList<String> getAttributesColumnsHeaders()
{
ArrayList<String> attColumnsHeaders = new ArrayList<>();
for (Route route : getVisibleElementsInTable())
for (Map.Entry<String, String> entry : route.getAttributes().entrySet())
if (attColumnsHeaders.contains(entry.getKey()) == false)
attColumnsHeaders.add(entry.getKey());
return attColumnsHeaders;
}
@Override
public void doPopup(final MouseEvent e, final int row, final Object[] itemIds)
{
JPopupMenu popup = new JPopupMenu();
final ITableRowFilter rf = callback.getVisualizationState().getTableRowFilter();
final List<Route> routeRowsInTheTable = getVisibleElementsInTable();
/* Add the popup menu option of the filters */
final List<Route> selectedRoutes = (List<Route>) (List<?>) getSelectedElements().getFirst();
final JMenu submenuFilters = new JMenu("Filters");
if (!selectedRoutes.isEmpty())
{
final JMenuItem filterKeepElementsAffectedThisLayer = new JMenuItem("This layer: Keep elements associated to this route traffic");
final JMenuItem filterKeepElementsAffectedAllLayers = new JMenuItem("All layers: Keep elements associated to this route traffic");
submenuFilters.add(filterKeepElementsAffectedThisLayer);
if (callback.getDesign().getNumberOfLayers() > 1) submenuFilters.add(filterKeepElementsAffectedAllLayers);
filterKeepElementsAffectedThisLayer.addActionListener(new ActionListener()
{
@Override
public void actionPerformed(ActionEvent e)
{
if (selectedRoutes.size() > 1) throw new RuntimeException();
TBFToFromCarriedTraffic filter = new TBFToFromCarriedTraffic(selectedRoutes.get(0), true);
callback.getVisualizationState().updateTableRowFilter(filter);
callback.updateVisualizationJustTables();
}
});
filterKeepElementsAffectedAllLayers.addActionListener(new ActionListener()
{
@Override
public void actionPerformed(ActionEvent e)
{
if (selectedRoutes.size() > 1) throw new RuntimeException();
TBFToFromCarriedTraffic filter = new TBFToFromCarriedTraffic(selectedRoutes.get(0), false);
callback.getVisualizationState().updateTableRowFilter(filter);
callback.updateVisualizationJustTables();
}
});
}
final JMenuItem tagFilter = new JMenuItem("This layer: Keep elements of tag...");
submenuFilters.add(tagFilter);
tagFilter.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent e) { dialogToFilterByTag (true); } });
final JMenuItem tagFilterAllLayers = new JMenuItem("All layers: Keep elements of tag...");
submenuFilters.add(tagFilterAllLayers);
tagFilterAllLayers.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent e) { dialogToFilterByTag (false); } });
popup.add(submenuFilters);
popup.addSeparator();
if (callback.getVisualizationState().isNetPlanEditable())
{
popup.add(getAddOption());
for (JComponent item : getExtraAddOptions())
popup.add(item);
}
if (!routeRowsInTheTable.isEmpty())
{
if (callback.getVisualizationState().isNetPlanEditable())
{
if (row != -1)
{
if (popup.getSubElements().length > 0) popup.addSeparator();
JMenuItem removeItem = new JMenuItem("Remove " + networkElementType);
removeItem.addActionListener(new ActionListener()
{
@Override
public void actionPerformed(ActionEvent e)
{
NetPlan netPlan = callback.getDesign();
try
{
for (Object itemId : itemIds)
{
netPlan.getRouteFromId((long) itemId).remove();
}
callback.getVisualizationState().resetPickedState();
callback.updateVisualizationAfterChanges(Sets.newHashSet(NetworkElementType.ROUTE));
callback.addNetPlanChange();
} catch (Throwable ex)
{
ErrorHandling.addErrorOrException(ex, getClass());
ErrorHandling.showErrorDialog("Unable to remove " + networkElementType);
}
}
});
popup.add(removeItem);
}
JMenuItem removeItems = new JMenuItem("Remove all table " + networkElementType + "s");
removeItems.addActionListener(new ActionListener()
{
@Override
public void actionPerformed(ActionEvent e)
{
final NetPlan netPlan = callback.getDesign();
try
{
if (rf == null)
netPlan.removeAllRoutes();
else
for (Route r : routeRowsInTheTable) r.remove();
callback.getVisualizationState().resetPickedState();
callback.updateVisualizationAfterChanges(Sets.newHashSet(NetworkElementType.ROUTE));
callback.addNetPlanChange();
} catch (Throwable ex)
{
ex.printStackTrace();
ErrorHandling.showErrorDialog(ex.getMessage(), "Unable to remove all " + networkElementType + "s");
}
}
});
popup.add(removeItems);
addPopupMenuAttributeOptions(e, row, itemIds, popup);
List<JComponent> extraOptions = getExtraOptions(row, itemIds);
if (!extraOptions.isEmpty())
{
if (popup.getSubElements().length > 0) popup.addSeparator();
for (JComponent item : extraOptions) popup.add(item);
}
}
List<JComponent> forcedOptions = getForcedOptions();
if (!forcedOptions.isEmpty())
{
if (popup.getSubElements().length > 0) popup.addSeparator();
for (JComponent item : forcedOptions) popup.add(item);
}
}
popup.show(e.getComponent(), e.getX(), e.getY());
}
@Override
public void showInCanvas(MouseEvent e, Object itemId)
{
if (getVisibleElementsInTable().isEmpty()) return;
callback.getVisualizationState().pickRoute(callback.getDesign().getRouteFromId((long) itemId));
callback.updateVisualizationAfterPick();
}
private JMenuItem getAddOption()
{
JMenuItem addItem = new JMenuItem("Add " + networkElementType);
addItem.addActionListener(new ActionListener()
{
@Override
public void actionPerformed(ActionEvent e)
{
try
{
createRouteGUI(callback);
callback.getVisualizationState().resetPickedState();
callback.updateVisualizationAfterChanges(Sets.newHashSet(NetworkElementType.ROUTE));
callback.addNetPlanChange();
} catch (Throwable ex)
{
ErrorHandling.showErrorDialog(ex.getMessage(), "Unable to add " + networkElementType);
}
}
});
NetPlan netPlan = callback.getDesign();
if (!netPlan.hasDemands()) addItem.setEnabled(false);
return addItem;
}
private static void createRouteGUI(final GUINetworkDesign callback)
{
final NetPlan netPlan = callback.getDesign();
final Collection<Long> demandIds = NetPlan.getIds(netPlan.getDemands());
final JComboBox demandSelector = new WiderJComboBox();
if (netPlan.getNumberOfLinks() == 0)
throw new Net2PlanException("The network has no links at this network layer");
final JTextField txt_carriedTraffic = new JTextField();
final JTextField txt_occupiedCapacity = new JTextField();
final List<JComboBox> seqLinks_cmb = new LinkedList<JComboBox>();
final JPanel seqLinks_pnl = new JPanel();
seqLinks_pnl.setLayout(new BoxLayout(seqLinks_pnl, BoxLayout.Y_AXIS));
demandSelector.addItemListener(new ItemListener()
{
@Override
public void itemStateChanged(ItemEvent e)
{
StringLabeller item = (StringLabeller) e.getItem();
long demandId = (Long) item.getObject();
Demand demand = netPlan.getDemandFromId(demandId);
double h_d = demand.getOfferedTraffic();
double r_d = demand.getCarriedTraffic();
txt_carriedTraffic.setText(Double.toString(Math.max(0, h_d - r_d)));
txt_occupiedCapacity.setText(Double.toString(Math.max(0, h_d - r_d)));
seqLinks_cmb.clear();
seqLinks_pnl.removeAll();
Node ingressNode = demand.getIngressNode();
String ingressNodeName = ingressNode.getName();
Collection<Link> outgoingLinks = ingressNode.getOutgoingLinks();
final JComboBox firstLink = new WiderJComboBox();
for (Link link : outgoingLinks)
{
long destinationNodeId = link.getDestinationNode().getId();
String destinationNodeName = link.getDestinationNode().getName();
firstLink.addItem(StringLabeller.of(link.getId(), String.format("e%d: n%d (%s) => n%d (%s)", link.getId(), ingressNode.getId(), ingressNodeName, destinationNodeId, destinationNodeName)));
}
firstLink.addItemListener(new ItemListener()
{
@Override
public void itemStateChanged(ItemEvent e)
{
JComboBox me = (JComboBox) e.getSource();
Iterator<JComboBox> it = seqLinks_cmb.iterator();
while (it.hasNext()) if (it.next() == me) break;
while (it.hasNext())
{
JComboBox aux = it.next();
seqLinks_pnl.remove(aux);
it.remove();
}
seqLinks_pnl.revalidate();
List<Link> seqLinks = new LinkedList<Link>();
for (JComboBox link : seqLinks_cmb)
seqLinks.add(netPlan.getLinkFromId((Long) ((StringLabeller) link.getSelectedItem()).getObject()));
callback.putTransientColorInElementTopologyCanvas(seqLinks, Color.BLUE);
}
});
setMaxSize(firstLink);
seqLinks_cmb.add(firstLink);
seqLinks_pnl.add(firstLink);
JPanel pane = new JPanel(new FlowLayout());
JButton addLink_btn = new JButton("Add new link");
addLink_btn.addActionListener(new ActionListener()
{
@Override
public void actionPerformed(ActionEvent e)
{
long linkId = (Long) ((StringLabeller) seqLinks_cmb.get(seqLinks_cmb.size() - 1).getSelectedItem()).getObject();
Link link = netPlan.getLinkFromId(linkId);
long destinationNodeId = link.getDestinationNode().getId();
String destinationNodeName = link.getDestinationNode().getName();
Set<Link> outgoingLinks = link.getDestinationNode().getOutgoingLinks();
if (outgoingLinks.isEmpty())
{
ErrorHandling.showErrorDialog("Last node has no outgoing links", "Error");
return;
}
final JComboBox newLink = new WiderJComboBox();
for (Link nextLink : outgoingLinks)
{
long nextDestinationNodeId = nextLink.getDestinationNode().getId();
String nextDestinationNodeName = nextLink.getDestinationNode().getName();
newLink.addItem(StringLabeller.of(nextLink.getId(), String.format("e%d: n%d (%s) => n%d (%s)", nextLink.getId(), destinationNodeId, destinationNodeName, nextDestinationNodeId, nextDestinationNodeName)));
}
newLink.addItemListener(new ItemListener()
{
@Override
public void itemStateChanged(ItemEvent e)
{
JComboBox me = (JComboBox) e.getSource();
Iterator<JComboBox> it = seqLinks_cmb.iterator();
while (it.hasNext()) if (it.next() == me) break;
while (it.hasNext())
{
JComboBox aux = it.next();
seqLinks_pnl.remove(aux);
it.remove();
}
seqLinks_pnl.revalidate();
List<Link> seqLinks = new LinkedList<Link>();
for (JComboBox link : seqLinks_cmb)
seqLinks.add(netPlan.getLinkFromId((Long) ((StringLabeller) link.getSelectedItem()).getObject()));
callback.putTransientColorInElementTopologyCanvas(seqLinks, Color.BLUE);
}
});
setMaxSize(newLink);
seqLinks_cmb.add(newLink);
seqLinks_pnl.add(newLink, seqLinks_pnl.getComponentCount() - 1);
seqLinks_pnl.revalidate();
List<Link> seqLinks = new LinkedList<Link>();
for (JComboBox auxLink : seqLinks_cmb)
{
seqLinks.add(netPlan.getLinkFromId((Long) ((StringLabeller) auxLink.getSelectedItem()).getObject()));
}
callback.putTransientColorInElementTopologyCanvas(seqLinks, Color.BLUE);
}
});
pane.add(addLink_btn);
JButton removeLink_btn = new JButton("Remove last link");
removeLink_btn.addActionListener(new ActionListener()
{
@Override
public void actionPerformed(ActionEvent e)
{
if (seqLinks_cmb.size() < 2)
{
ErrorHandling.showErrorDialog("Initial link cannot be removed", "Error");
return;
}
JComboBox cmb = seqLinks_cmb.get(seqLinks_cmb.size() - 1);
seqLinks_cmb.remove(cmb);
seqLinks_pnl.remove(cmb);
seqLinks_pnl.revalidate();
List<Link> seqLinks = new LinkedList<Link>();
for (JComboBox link : seqLinks_cmb)
seqLinks.add(netPlan.getLinkFromId((Long) ((StringLabeller) link.getSelectedItem()).getObject()));
callback.putTransientColorInElementTopologyCanvas(seqLinks, Color.BLUE);
}
});
pane.add(removeLink_btn);
seqLinks_pnl.add(pane);
seqLinks_pnl.revalidate();
List<Link> seqLinks = new LinkedList<Link>();
for (JComboBox link : seqLinks_cmb)
seqLinks.add(netPlan.getLinkFromId((Long) ((StringLabeller) link.getSelectedItem()).getObject()));
callback.putTransientColorInElementTopologyCanvas(seqLinks, Color.BLUE);
}
});
for (long demandId : demandIds)
{
Demand demand = netPlan.getDemandFromId(demandId);
Node ingressNode = demand.getIngressNode();
Node egressNode = demand.getEgressNode();
long ingressNodeId = ingressNode.getId();
long egressNodeId = egressNode.getId();
final String ingressNodeName = ingressNode.getName();
final String egressNodeName = egressNode.getName();
final Set<Link> outgoingLinks = ingressNode.getOutgoingLinks();
if (outgoingLinks.isEmpty()) continue;
String demandLabel = "Demand " + demandId;
demandLabel += ": n" + ingressNodeId;
if (!ingressNodeName.isEmpty()) demandLabel += " (" + ingressNodeName + ")";
demandLabel += " => n" + egressNodeId;
if (!egressNodeName.isEmpty()) demandLabel += " (" + egressNodeName + ")";
double h_d = demand.getOfferedTraffic();
double r_d = demand.getCarriedTraffic();
demandLabel += ", offered traffic = " + h_d;
demandLabel += ", carried traffic = " + r_d;
demandSelector.addItem(StringLabeller.of(demandId, demandLabel));
}
if (demandSelector.getItemCount() == 0) throw new Net2PlanException("Bad - No node has outgoing links");
demandSelector.setSelectedIndex(0);
final JScrollPane scrollPane = new JScrollPane(seqLinks_pnl, ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED, ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
scrollPane.setBorder(BorderFactory.createTitledBorder(new LineBorder(Color.BLACK), "Sequence of links"));
scrollPane.setAlignmentY(JScrollPane.TOP_ALIGNMENT);
final JPanel pane = new JPanel(new MigLayout("fill", "[][grow]", "[][grow][]"));
pane.add(new JLabel("Demand"));
pane.add(demandSelector, "growx, wrap, wmin 50");
pane.add(scrollPane, "grow, spanx 2, wrap");
pane.add(new JLabel("Carried traffic"));
pane.add(txt_carriedTraffic, "grow, wrap");
pane.add(new JLabel("Occupied capacity"));
pane.add(txt_occupiedCapacity, "grow");
pane.setPreferredSize(new Dimension(400, 400));
while (true)
{
int result = JOptionPane.showConfirmDialog(null, pane, "Add new route", JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE);
if (result != JOptionPane.OK_OPTION) break;
long demandId = (Long) ((StringLabeller) demandSelector.getSelectedItem()).getObject();
double carriedTraffic;
double occupiedCapacity = -1;
try
{
carriedTraffic = Double.parseDouble(txt_carriedTraffic.getText());
if (carriedTraffic < 0) throw new RuntimeException();
} catch (Throwable e)
{
ErrorHandling.showErrorDialog("Carried traffic must be a non-negative number", "Error adding route");
continue;
}
try
{
if (!txt_occupiedCapacity.getText().isEmpty())
{
occupiedCapacity = Double.parseDouble(txt_occupiedCapacity.getText());
if (occupiedCapacity < 0 && occupiedCapacity != -1) throw new RuntimeException();
}
} catch (Throwable e)
{
ErrorHandling.showErrorDialog("Occupied capacity must be a non-negative number, -1 or empty", "Error adding route");
continue;
}
List<Link> seqLinks = new LinkedList<Link>();
for (JComboBox link : seqLinks_cmb)
seqLinks.add(netPlan.getLinkFromId((Long) ((StringLabeller) link.getSelectedItem()).getObject()));
try
{
netPlan.addRoute(netPlan.getDemandFromId(demandId), carriedTraffic, occupiedCapacity, seqLinks, null);
} catch (Throwable e)
{
ErrorHandling.showErrorDialog(e.getMessage(), "Error adding route");
continue;
}
break;
}
callback.resetPickedStateAndUpdateView();
}
private static void setMaxSize(JComponent c)
{
final Dimension max = c.getMaximumSize();
final Dimension pref = c.getPreferredSize();
max.height = pref.height;
c.setMaximumSize(max);
}
private List<JComponent> getExtraAddOptions()
{
List<JComponent> options = new LinkedList<JComponent>();
NetPlan netPlan = callback.getDesign();
final JMenuItem oneRoutePerDemandSPFHops = new JMenuItem("Add one route per demand, shortest path (Service chain) in hops");
options.add(oneRoutePerDemandSPFHops);
oneRoutePerDemandSPFHops.addActionListener(new RouteSPFActionListener(true, false));
final JMenuItem oneRoutePerDemandSPFKm = new JMenuItem("Add one route per demand, shortest path (Service chain) in km");
options.add(oneRoutePerDemandSPFKm);
oneRoutePerDemandSPFKm.addActionListener(new RouteSPFActionListener(false, false));
final JMenuItem oneRouteAndLinkDisjointSegmentPerDemandSPFHops = new JMenuItem("Add one route and 1+1 link disjoint protection per demand (minimize total num hops)");
options.add(oneRouteAndLinkDisjointSegmentPerDemandSPFHops);
oneRouteAndLinkDisjointSegmentPerDemandSPFHops.addActionListener(new RouteSPFActionListener(true, true));
final JMenuItem oneRouteAndLinkDisjointSegmentPerDemandSPFKm = new JMenuItem("Add one route and 1+1 link disjoint protection per demand (minimize total km)");
options.add(oneRouteAndLinkDisjointSegmentPerDemandSPFKm);
oneRouteAndLinkDisjointSegmentPerDemandSPFKm.addActionListener(new RouteSPFActionListener(false, true));
return options;
}
private class RouteSPFActionListener implements ActionListener
{
final boolean isMinHops;
final boolean add11LinkDisjointSegment;
private RouteSPFActionListener(boolean isMinHops, boolean minCost)
{
this.isMinHops = isMinHops;
this.add11LinkDisjointSegment = minCost;
}
@Override
public void actionPerformed(ActionEvent e)
{
NetPlan netPlan = callback.getDesign();
List<Link> links = netPlan.getLinks();
final int E = links.size();
Map<Link, Double> linkCostMap = new HashMap<Link, Double>();
List<Route> addedRoutes = new LinkedList<Route>();
// Ask for current element removal
if (netPlan.hasRoutes(netPlan.getNetworkLayerDefault()))
{
final int answer = JOptionPane.showConfirmDialog(null, "Remove all existing routes?", "", JOptionPane.YES_NO_CANCEL_OPTION);
if (answer == JOptionPane.OK_OPTION) netPlan.removeAllRoutes(netPlan.getNetworkLayerDefault());
if (answer == JOptionPane.CANCEL_OPTION || answer == JOptionPane.CLOSED_OPTION) return;
}
for (Link link : netPlan.getLinks())
{
linkCostMap.put(link, isMinHops ? 1 : link.getLengthInKm());
}
DoubleMatrix1D linkCostVector = null;
if (isMinHops)
linkCostVector = DoubleFactory1D.dense.make(netPlan.getLinks().size(), 1.0);
else
{
linkCostVector = netPlan.getVectorLinkLengthInKm();
}
try
{
for (Demand d : netPlan.getDemands())
{
if (add11LinkDisjointSegment)
{
if (d.isServiceChainRequest())
{
List<NetworkElement> minCostServiceChain = GraphUtils.getMinimumCostServiceChain(netPlan.getLinks(), d.getIngressNode(), d.getEgressNode(), d.getServiceChainSequenceOfTraversedResourceTypes(), linkCostVector, null, -1, -1, -1).getFirst();
if (minCostServiceChain.isEmpty())
throw new Net2PlanException("Cannot find a route for demand of index " + d.getIndex() + ". No route is created");
DoubleMatrix1D linkCostModified = linkCostVector.copy();
Map<Resource, Double> resourceCostModified = new HashMap<Resource, Double>();
for (NetworkElement ee : minCostServiceChain)
if (ee instanceof Link) linkCostModified.set(ee.getIndex(), Double.MAX_VALUE);
else if (ee instanceof Resource)
resourceCostModified.put((Resource) ee, Double.MAX_VALUE);
List<NetworkElement> minCostServiceChain2 =
GraphUtils.getMinimumCostServiceChain(netPlan.getLinks(), d.getIngressNode(),
d.getEgressNode(), d.getServiceChainSequenceOfTraversedResourceTypes(),
linkCostModified, resourceCostModified, -1, -1, -1).getFirst();
if (minCostServiceChain2.isEmpty())
throw new Net2PlanException("Could not find two link and resource disjoint routes demand of index " + d.getIndex() + ". No route is created");
final Route r = netPlan.addServiceChain(d, d.getOfferedTraffic(),
Collections.nCopies(minCostServiceChain.size(), d.getOfferedTraffic()), minCostServiceChain, null);
final Route s = netPlan.addServiceChain(d, 0,
Collections.nCopies(minCostServiceChain2.size(), d.getOfferedTraffic()), minCostServiceChain2, null);
r.addBackupRoute(s);
addedRoutes.add(r);
addedRoutes.add(s);
} else
{
List<List<Link>> twoPaths = GraphUtils.getTwoLinkDisjointPaths(netPlan.getNodes(), netPlan.getLinks(), d.getIngressNode(), d.getEgressNode(), linkCostMap);
if (twoPaths.size() != 2)
throw new Net2PlanException("There are no two link disjoint paths for demand of index " + d.getIndex() + ". No route or protection segment is created");
final Route r = netPlan.addRoute(d, d.getOfferedTraffic(), d.getOfferedTraffic(), twoPaths.get(0), null);
final Route s = netPlan.addRoute(d, 0, d.getOfferedTraffic(), twoPaths.get(1), null);
r.addBackupRoute(s);
addedRoutes.add(r);
addedRoutes.add(s);
}
} else
{
List<NetworkElement> minCostServiceChain = GraphUtils.getMinimumCostServiceChain(netPlan.getLinks(), d.getIngressNode(), d.getEgressNode(), d.getServiceChainSequenceOfTraversedResourceTypes(), linkCostVector, null, -1, -1, -1).getFirst();
if (minCostServiceChain.isEmpty())
throw new Net2PlanException("Cannot find a route for demand of index " + d.getIndex() + ". No route is created");
Route r = netPlan.addServiceChain(d, d.getOfferedTraffic(),
Collections.nCopies(minCostServiceChain.size(), d.getOfferedTraffic()),
minCostServiceChain, null);
addedRoutes.add(r);
}
}
} catch (Exception ex)
{
ex.printStackTrace();
for (Route r : addedRoutes) r.remove();
ErrorHandling.showErrorDialog(ex.getMessage(), "Error adding routes and/or protection segments");
}
callback.getVisualizationState().resetPickedState();
callback.updateVisualizationAfterChanges(Sets.newHashSet(NetworkElementType.ROUTE));
callback.addNetPlanChange();
}
}
private List<JComponent> getExtraOptions(final int row, final Object itemId)
{
List<JComponent> options = new LinkedList<JComponent>();
final int numRows = model.getRowCount();
final NetPlan netPlan = callback.getDesign();
if (itemId != null)
{
JMenuItem viewEditBackupRoutes = new JMenuItem("View/edit backup routes");
viewEditBackupRoutes.addActionListener(new ActionListener()
{
@Override
public void actionPerformed(ActionEvent e)
{
try
{
viewEditBackupRoutesGUI(callback, (long) itemId);
} catch (Throwable ex)
{
ErrorHandling.showErrorDialog(ex.getMessage(), "Error viewing/editing backup routes");
}
}
});
options.add(viewEditBackupRoutes);
}
return options;
}
private static void viewEditBackupRoutesGUI(final GUINetworkDesign callback, final long routeId)
{
final NetPlan netPlan = callback.getDesign();
final Route route = netPlan.getRouteFromId(routeId);
if (route.isBackupRoute()) throw new Net2PlanException("A backup route cannot have backup routes itself.");
Set<Route> candidateBackupRoutes = route.getDemand().getRoutesAreNotBackup();
List<Route> currentBackupRoutes = route.getBackupRoutes();
final List<NetworkElement> seqLinksAndResources = route.getPath();
if (candidateBackupRoutes.isEmpty())
throw new Net2PlanException("No backup route can be applied to this route");
candidateBackupRoutes.removeAll(currentBackupRoutes);
final JComboBox backupRouteSelector = new WiderJComboBox();
final DefaultTableModel model = new ClassAwareTableModel(new Object[1][6], new String[]{"Id", "Seq. links/resources", "Seq. nodes", "Seq. occupied capacities", "", ""})
{
@Override
public boolean isCellEditable(int rowIndex, int columnIndex)
{
return columnIndex == 4 || columnIndex == 5;
}
};
final JTable table = new AdvancedJTable(model);
table.setEnabled(false);
final JPanel addSegment_pnl = new JPanel(new MigLayout("", "[grow][][]", "[]"));
JButton addSegment_btn = new JButton("Add");
addSegment_btn.addActionListener(new ActionListener()
{
@Override
public void actionPerformed(ActionEvent e)
{
Object selectedItem = backupRouteSelector.getSelectedItem();
long backupRouteId = (Long) ((StringLabeller) selectedItem).getObject();
Route backupRoute = netPlan.getRouteFromId(backupRouteId);
route.addBackupRoute(backupRoute);
callback.getVisualizationState().resetPickedState();
callback.updateVisualizationAfterChanges(Sets.newHashSet(NetworkElementType.ROUTE));
callback.addNetPlanChange();
backupRouteSelector.removeItem(selectedItem);
if (backupRouteSelector.getItemCount() == 0) addSegment_pnl.setVisible(false);
if (!table.isEnabled()) model.removeRow(0);
model.addRow(new Object[]
{backupRouteId,
getSequenceLinkResourceIndexes(backupRoute),
getSequenceNodeIndexesWithResourceInfo(backupRoute),
getSequenceOccupiedCapacities(backupRoute), "Remove", "View"});
table.setEnabled(true);
}
});
JButton viewSegment_btn1 = new JButton("View");
viewSegment_btn1.addActionListener(new ActionListener()
{
@Override
public void actionPerformed(ActionEvent e)
{
Object selectedItem = backupRouteSelector.getSelectedItem();
long backupRouteId = (Long) ((StringLabeller) selectedItem).getObject();
List<NetworkElement> backupRoutePath = netPlan.getRouteFromId(backupRouteId).getPath();
callback.putTransientColorInElementTopologyCanvas(seqLinksAndResources, Color.ORANGE);
callback.putTransientColorInElementTopologyCanvas(backupRoutePath, Color.ORANGE);
}
});
addSegment_pnl.add(backupRouteSelector, "growx, wmin 50");
addSegment_pnl.add(addSegment_btn);
addSegment_pnl.add(viewSegment_btn1);
Action delete = new AbstractAction()
{
@Override
public void actionPerformed(ActionEvent e)
{
try
{
JTable table = (JTable) e.getSource();
int modelRow = Integer.parseInt(e.getActionCommand());
final long backupRouteId = (Long) table.getModel().getValueAt(modelRow, 0);
final Route backupRoute = netPlan.getRouteFromId(backupRouteId);
netPlan.getRouteFromId(routeId).removeBackupRoute(backupRoute);
callback.getVisualizationState().resetPickedState();
callback.updateVisualizationAfterChanges(Sets.newHashSet(NetworkElementType.ROUTE));
callback.addNetPlanChange();
String segmentLabel = "Backup route id " + backupRouteId +
": path = " + getSequenceLinkResourceIndexes(backupRoute) +
", seq. nodes = " + getSequenceNodeIndexesWithResourceInfo(backupRoute) +
", occupied capacity = " + getSequenceOccupiedCapacities(backupRoute);
backupRouteSelector.addItem(StringLabeller.of(backupRouteId, segmentLabel));
((DefaultTableModel) table.getModel()).removeRow(modelRow);
table.setEnabled(true);
if (table.getModel().getRowCount() == 0)
{
((DefaultTableModel) table.getModel()).addRow(new Object[6]);
table.setEnabled(false);
}
} catch (Throwable e1)
{
}
}
};
Action view = new AbstractAction()
{
@Override
public void actionPerformed(ActionEvent e)
{
try
{
JTable table = (JTable) e.getSource();
int modelRow = Integer.parseInt(e.getActionCommand());
final long backupRouteId = (Long) table.getModel().getValueAt(modelRow, 0);
final Route backupRoute = netPlan.getRouteFromId(backupRouteId);
callback.putTransientColorInElementTopologyCanvas(seqLinksAndResources, Color.ORANGE);
callback.putTransientColorInElementTopologyCanvas(backupRoute.getPath(), Color.ORANGE);
} catch (Throwable e1)
{
}
}
};
new ButtonColumn(table, delete, 4);
new ButtonColumn(table, view, 5);
final JScrollPane scrollPane = new JScrollPane(table, ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED, ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
scrollPane.setBorder(BorderFactory.createTitledBorder(new LineBorder(Color.BLACK), "Current backup segment list"));
scrollPane.setAlignmentY(JScrollPane.TOP_ALIGNMENT);
final JDialog dialog = new JDialog();
dialog.setLayout(new BorderLayout());
dialog.add(addSegment_pnl, BorderLayout.NORTH);
dialog.add(scrollPane, BorderLayout.CENTER);
for (Route backupRoute : candidateBackupRoutes)
{
String segmentLabel = "Backup route id " + backupRoute.getId() +
": path = " + getSequenceLinkResourceIndexes(backupRoute) +
", seq. nodes = " + getSequenceNodeIndexesWithResourceInfo(backupRoute) +
", occupied capacity = " + getSequenceOccupiedCapacities(backupRoute);
backupRouteSelector.addItem(StringLabeller.of(backupRoute, segmentLabel));
}
if (backupRouteSelector.getItemCount() == 0)
{
addSegment_pnl.setVisible(false);
} else
{
backupRouteSelector.setSelectedIndex(0);
}
if (!currentBackupRoutes.isEmpty())
{
model.removeRow(0);
for (Route backupRoute : currentBackupRoutes)
{
model.addRow(new Object[]{backupRoute.getId(),
getSequenceLinkResourceIndexes(backupRoute), getSequenceNodeIndexesWithResourceInfo(backupRoute),
getSequenceOccupiedCapacities(backupRoute), "Remove", "View"});
}
table.setEnabled(true);
}
table.setDefaultRenderer(Boolean.class, new CellRenderers.UnfocusableCellRenderer());
table.setDefaultRenderer(Double.class, new CellRenderers.UnfocusableCellRenderer());
table.setDefaultRenderer(Object.class, new CellRenderers.UnfocusableCellRenderer());
table.setDefaultRenderer(Float.class, new CellRenderers.UnfocusableCellRenderer());
table.setDefaultRenderer(Long.class, new CellRenderers.UnfocusableCellRenderer());
table.setDefaultRenderer(Integer.class, new CellRenderers.UnfocusableCellRenderer());
table.setDefaultRenderer(String.class, new CellRenderers.UnfocusableCellRenderer());
double x_p = netPlan.getRouteFromId(routeId).getCarriedTraffic();
dialog.setTitle("View/edit backup route list for route " + routeId + " (carried traffic = " + x_p + ", occupied capacity = " + getSequenceOccupiedCapacities(netPlan.getRouteFromId(routeId)) + ")");
SwingUtils.configureCloseDialogOnEscape(dialog);
dialog.setModalityType(Dialog.ModalityType.APPLICATION_MODAL);
dialog.setSize(new Dimension(500, 300));
dialog.setLocationRelativeTo(null);
dialog.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
dialog.setVisible(true);
callback.resetPickedStateAndUpdateView();
}
private List<JComponent> getForcedOptions()
{
return new LinkedList<JComponent>();
}
private static String getSequenceLinkResourceIndexes(Route r)
{
StringBuffer buf = new StringBuffer();
for (NetworkElement e : r.getPath())
if (e instanceof Link) buf.append("L" + e.getIndex() + ",");
else if (e instanceof Resource) buf.append("R" + e.getIndex() + ",");
buf.setLength(buf.length() - 1);
return buf.toString();
}
private static String getSequenceNodeIndexesWithResourceInfo(Route r)
{
StringBuffer buf = new StringBuffer();
buf.append("N" + r.getIngressNode().getIndex());
for (NetworkElement e : r.getPath())
if (e instanceof Link) buf.append(",N" + ((Link) e).getDestinationNode().getIndex());
else if (e instanceof Resource) buf.append(",(R" + e.getIndex() + ")");
return buf.toString();
}
private static String getSequenceOccupiedCapacities(Route r)
{
if (r.isDown()) return "0";
if (r.getSeqOccupiedCapacitiesIfNotFailing().equals(Collections.nCopies(r.getPath().size(), r.getOccupiedCapacity())))
return "" + r.getOccupiedCapacity();
return CollectionUtils.join(r.getSeqOccupiedCapacitiesIfNotFailing(), ", ");
}
private List<Route> getVisibleElementsInTable()
{
final ITableRowFilter rf = callback.getVisualizationState().getTableRowFilter();
final NetworkLayer layer = callback.getDesign().getNetworkLayerDefault();
return rf == null ? callback.getDesign().getRoutes(layer) : rf.getVisibleRoutes(layer);
}
}
|
package org.xwiki.search.solr.internal.api;
/**
* Index component exception.
*
* @version $Id$
* @since 4.3M2
*/
public class SolrIndexException extends Exception
{
/** Needed for correctly implementing {@link java.io.Serializable}. */
private static final long serialVersionUID = -4795008341521444886L;
/**
* Constructor.
*
* @param message the exception message
* @param cause the exception that caused this exception
*/
public SolrIndexException(String message, Exception cause)
{
super(message, cause);
}
/**
* Constructor.
*
* @param message the exception message
*/
public SolrIndexException(String message)
{
super(message);
}
}
|
package com.net2plan.gui.plugins.networkDesign.viewEditTopolTables.specificTables;
import com.google.common.collect.Sets;
import com.net2plan.gui.plugins.networkDesign.CellRenderers;
import com.net2plan.gui.utils.AdvancedJTable;
import com.net2plan.gui.utils.ClassAwareTableModel;
import com.net2plan.gui.utils.StringLabeller;
import com.net2plan.gui.utils.WiderJComboBox;
import com.net2plan.gui.plugins.networkDesign.viewEditTopolTables.tableVisualizationFilters.TBFToFromCarriedTraffic;
import com.net2plan.gui.plugins.networkDesign.interfaces.ITableRowFilter;
import com.net2plan.gui.plugins.GUINetworkDesign;
import com.net2plan.interfaces.networkDesign.*;
import com.net2plan.internal.Constants;
import com.net2plan.internal.Constants.NetworkElementType;
import com.net2plan.internal.ErrorHandling;
import com.net2plan.utils.StringUtils;
import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableCellRenderer;
import javax.swing.table.TableModel;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.util.*;
import java.util.List;
import java.util.stream.Collectors;
@SuppressWarnings("unchecked")
public class AdvancedJTable_resource extends AdvancedJTable_NetworkElement
{
public static final int COLUMN_ID = 0;
public static final int COLUMN_INDEX = 1;
public static final int COLUMN_NAME = 2;
public static final int COLUMN_TYPE = 3;
public static final int COLUMN_HOSTNODE = 4;
public static final int COLUMN_CAPACITY = 5;
public static final int COLUMN_CAPACITYMUNITS= 6;
public static final int COLUMN_OCCUPIEDCAPACITY = 7;
public static final int COLUMN_TRAVERSINGROUTES = 8;
public static final int COLUMN_UPPERRESOURCES = 9;
public static final int COLUMN_BASERESOURCES = 10;
public static final int COLUMN_PROCESSINGTIME = 11;
public static final int COLUMN_TAGS = 12;
public static final int COLUMN_ATTRIBUTES = 13;
private static final String netPlanViewTabName = "Resources";
private static final String[] netPlanViewTableHeader = StringUtils.arrayOf("Unique Identifier","Index","Name","Type","Host Node","Capacity","Cap. Units","Ocuppied capacity","Traversing Routes","Upper Resources","Base Resources","Processing Time", "Tags", "Attributes");
private static final String[] netPlanViewTableTips = StringUtils.arrayOf("Unique Identifier","Index","Name","Type","Host Node","Capacity","Cap. Units","Ocuppied capacity","Traversing Routes","Upper Resources","Base Resources","Processing Time", "Tags", "Attributes");
public AdvancedJTable_resource(final GUINetworkDesign callback)
{
super(createTableModel(callback), callback, Constants.NetworkElementType.RESOURCE, true);
setDefaultCellRenderers(callback);
setSpecificCellRenderers();
setColumnRowSortingFixedAndNonFixedTable();
fixedTable.setDefaultRenderer(Boolean.class, this.getDefaultRenderer(Boolean.class));
fixedTable.setDefaultRenderer(Double.class, this.getDefaultRenderer(Double.class));
fixedTable.setDefaultRenderer(Object.class, this.getDefaultRenderer(Object.class));
fixedTable.setDefaultRenderer(Float.class, this.getDefaultRenderer(Float.class));
fixedTable.setDefaultRenderer(Long.class, this.getDefaultRenderer(Long.class));
fixedTable.setDefaultRenderer(Integer.class, this.getDefaultRenderer(Integer.class));
fixedTable.setDefaultRenderer(String.class, this.getDefaultRenderer(String.class));
fixedTable.getTableHeader().setDefaultRenderer(new CellRenderers.FixedTableHeaderRenderer());
setEnabled(true);
}
@Override
public List<Object[]> getAllData(NetPlan currentState, ArrayList<String> attributesTitles)
{
final List<Object[]> allResourceData = new LinkedList<Object[]>();
final List<Resource> rowVisibleResources = getVisibleElementsInTable ();
for (Resource res : rowVisibleResources)
{
Object[] resData = new Object[netPlanViewTableHeader.length + attributesTitles.size()];
resData[COLUMN_ID] = res.getId();
resData[COLUMN_INDEX] = res.getIndex();
resData[COLUMN_NAME] = res.getName();
resData[COLUMN_TYPE] = res.getType();
resData[COLUMN_HOSTNODE] = res.getHostNode();
resData[COLUMN_CAPACITY] = res.getCapacity();
resData[COLUMN_CAPACITYMUNITS] = res.getCapacityMeasurementUnits();
resData[COLUMN_OCCUPIEDCAPACITY] = res.getOccupiedCapacity();
resData[COLUMN_TRAVERSINGROUTES] = joinTraversingRoutesWithTheirCapacities(res);
resData[COLUMN_UPPERRESOURCES] = joinUpperResourcesWithTheirCapacities(res);
resData[COLUMN_BASERESOURCES] = joinBaseResourcesWithTheirCapacities(res);
resData[COLUMN_PROCESSINGTIME] = res.getProcessingTimeToTraversingTrafficInMs();
resData[COLUMN_TAGS] = res.getTags();
resData[COLUMN_ATTRIBUTES] = StringUtils.mapToString(res.getAttributes());
for(int i = netPlanViewTableHeader.length; i < netPlanViewTableHeader.length + attributesTitles.size();i++)
{
if(res.getAttributes().containsKey(attributesTitles.get(i-netPlanViewTableHeader.length)))
{
resData[i] = res.getAttribute(attributesTitles.get(i-netPlanViewTableHeader.length));
}
}
allResourceData.add(resData);
}
/* Add the aggregation row with the aggregated statistics */
final double aggCapacity = rowVisibleResources.stream().mapToDouble(e->e.getCapacity()).sum();
final double aggOccupiedCapacity = rowVisibleResources.stream().mapToDouble(e->e.getOccupiedCapacity()).sum();
final int aggTravSCs = rowVisibleResources.stream().mapToInt(e->e.getTraversingRoutes().size()).sum();
final double aggMaxProcTime = rowVisibleResources.stream().mapToDouble(e->e.getProcessingTimeToTraversingTrafficInMs()).max().orElse(0);
final LastRowAggregatedValue[] aggregatedData = new LastRowAggregatedValue [netPlanViewTableHeader.length + attributesTitles.size()];
Arrays.fill(aggregatedData, new LastRowAggregatedValue());
aggregatedData [COLUMN_CAPACITY] = new LastRowAggregatedValue(aggCapacity);
aggregatedData [COLUMN_OCCUPIEDCAPACITY] = new LastRowAggregatedValue(aggOccupiedCapacity);
aggregatedData [COLUMN_TRAVERSINGROUTES] = new LastRowAggregatedValue(aggTravSCs);
aggregatedData [COLUMN_PROCESSINGTIME] = new LastRowAggregatedValue(aggMaxProcTime);
allResourceData.add(aggregatedData);
return allResourceData;
}
@Override
public String getTabName() {
return netPlanViewTabName;
}
@Override
public String[] getTableHeaders() {
return netPlanViewTableHeader;
}
@Override
public String[] getCurrentTableHeaders() {
ArrayList<String> attColumnsHeaders = getAttributesColumnsHeaders();
String[] headers = new String[netPlanViewTableHeader.length + attColumnsHeaders.size()];
for(int i = 0; i < headers.length ;i++)
{
if(i<netPlanViewTableHeader.length)
{
headers[i] = netPlanViewTableHeader[i];
}
else{
headers[i] = "Att: "+attColumnsHeaders.get(i - netPlanViewTableHeader.length);
}
}
return headers;
}
@Override
public String[] getTableTips() {
return netPlanViewTableTips;
}
@Override
public boolean hasElements()
{
final ITableRowFilter rf = callback.getVisualizationState().getTableRowFilter();
final NetworkLayer layer = callback.getDesign().getNetworkLayerDefault();
return rf == null? callback.getDesign().hasResources() : rf.hasResources(layer);
}
@Override
public int getAttributesColumnIndex() {
return COLUMN_ATTRIBUTES;
}
// @Override
// public int[] getColumnsOfSpecialComparatorForSorting() {
// return new int[]{5};
private static TableModel createTableModel(final GUINetworkDesign callback)
{
TableModel resourceTableModel = new ClassAwareTableModel(new Object[1][netPlanViewTableHeader.length], netPlanViewTableHeader) {
private static final long serialVersionUID = 1L;
@Override
public boolean isCellEditable(int rowIndex, int columnIndex) {
if (!callback.getVisualizationState().isNetPlanEditable()) return false;
if( columnIndex >= netPlanViewTableHeader.length) return true;
if (getValueAt(rowIndex,columnIndex) == null) return false;
if (rowIndex == getRowCount() - 1) return false;
return columnIndex == COLUMN_NAME || columnIndex == COLUMN_CAPACITY || columnIndex == COLUMN_PROCESSINGTIME;
}
@Override
public void setValueAt(Object newValue, int row, int column) {
Object oldValue = getValueAt(row, column);
/* If value doesn't change, exit from function */
if (newValue != null && newValue.equals(oldValue)) return;
NetPlan netPlan = callback.getDesign();
if (getValueAt(row, 0) == null) row = row - 1;
final long resId = (Long) getValueAt(row, 0);
final Resource res = netPlan.getResourceFromId(resId);
try {
switch (column) {
case COLUMN_NAME:
res.setName(newValue.toString());
callback.updateVisualizationAfterChanges(Sets.newHashSet(NetworkElementType.RESOURCE));
callback.getVisualizationState ().pickResource(res);
callback.updateVisualizationAfterPick();
callback.addNetPlanChange();
break;
case COLUMN_CAPACITY:
if (newValue == null) return;
res.setCapacity((Double)newValue, netPlan.getResourceFromId(resId).getCapacityOccupiedInBaseResourcesMap());
callback.updateVisualizationAfterChanges(Sets.newHashSet(NetworkElementType.RESOURCE));
callback.getVisualizationState ().pickResource(res);
callback.updateVisualizationAfterPick();
callback.addNetPlanChange();
break;
case COLUMN_PROCESSINGTIME:
if(newValue == null) return;
res.setProcessingTimeToTraversingTrafficInMs((Double)newValue);
callback.updateVisualizationAfterChanges(Sets.newHashSet(NetworkElementType.RESOURCE));
callback.getVisualizationState ().pickResource(res);
callback.updateVisualizationAfterPick();
callback.addNetPlanChange();
break;
default:
break;
}
} catch (Throwable ex) {
ex.printStackTrace();
ErrorHandling.showErrorDialog(ex.getMessage(), "Error modifying resource");
return;
}
/* Set new value */
super.setValueAt(newValue, row, column);
}
};
return resourceTableModel;
}
private void setSpecificCellRenderers() {
}
private void setDefaultCellRenderers(final GUINetworkDesign callback) {
setDefaultRenderer(Boolean.class, new CellRenderers.CheckBoxRenderer());
setDefaultRenderer(Double.class, new CellRenderers.NumberCellRenderer());
setDefaultRenderer(Object.class, new CellRenderers.NonEditableCellRenderer());
setDefaultRenderer(Float.class, new CellRenderers.NumberCellRenderer());
setDefaultRenderer(Long.class, new CellRenderers.NumberCellRenderer());
setDefaultRenderer(Integer.class, new CellRenderers.NumberCellRenderer());
setDefaultRenderer(String.class, new CellRenderers.NonEditableCellRenderer());
}
@Override
public void setColumnRowSortingFixedAndNonFixedTable()
{
setAutoCreateRowSorter(true);
final Set<Integer> columnsWithDoubleAndThenParenthesis = Sets.newHashSet(COLUMN_CAPACITY);
DefaultRowSorter rowSorter = ((DefaultRowSorter) getRowSorter());
for (int col = 0; col <= COLUMN_ATTRIBUTES ; col ++)
rowSorter.setComparator(col, new AdvancedJTable_NetworkElement.ColumnComparator(rowSorter , columnsWithDoubleAndThenParenthesis.contains(col)));
fixedTable.setAutoCreateRowSorter(true);
fixedTable.setRowSorter(this.getRowSorter());
rowSorter = ((DefaultRowSorter) fixedTable.getRowSorter());
for (int col = 0; col <= COLUMN_ATTRIBUTES ; col ++)
rowSorter.setComparator(col, new AdvancedJTable_NetworkElement.ColumnComparator(rowSorter , columnsWithDoubleAndThenParenthesis.contains(col)));
}
@Override
public int getNumberOfDecoratorColumns() {
return 2;
}
@Override
public ArrayList<String> getAttributesColumnsHeaders() {
ArrayList<String> attColumnsHeaders = new ArrayList<>();
for(Resource res : getVisibleElementsInTable())
{
for (Map.Entry<String, String> entry : res.getAttributes().entrySet())
{
if(attColumnsHeaders.contains(entry.getKey()) == false)
{
attColumnsHeaders.add(entry.getKey());
}
}
}
return attColumnsHeaders;
}
private String joinTraversingRoutesWithTheirCapacities(Resource res)
{
Map<Route, Double> routesCapacities = res.getTraversingRouteOccupiedCapacityMap();
String t = "";
int counter = 0;
for(Map.Entry<Route, Double> entry : routesCapacities.entrySet())
{
if(counter == routesCapacities.size() - 1)
t = t + "R"+entry.getKey().getIndex()+" ("+entry.getValue()+") ";
else
t = t + "R"+entry.getKey().getIndex()+" ("+entry.getValue()+"), ";
counter++;
}
return t;
}
private String joinUpperResourcesWithTheirCapacities(Resource res)
{
Map<Resource, Double> upperResourcesCapacities = res.getCapacityOccupiedByUpperResourcesMap();
String t = "";
int counter = 0;
for(Map.Entry<Resource, Double> entry : upperResourcesCapacities.entrySet())
{
if(counter == upperResourcesCapacities.size() - 1)
t = t + "r"+entry.getKey().getIndex()+" ("+entry.getValue()+") ";
else
t = t + "r"+entry.getKey().getIndex()+" ("+entry.getValue()+"), ";
counter++;
}
return t;
}
private String joinBaseResourcesWithTheirCapacities(Resource res)
{
Map<Resource, Double> baseResourcesCapacities = res.getCapacityOccupiedInBaseResourcesMap();
String t = "";
int counter = 0;
for(Map.Entry<Resource, Double> entry : baseResourcesCapacities.entrySet())
{
if(counter == baseResourcesCapacities.size() - 1)
t = t + "r"+entry.getKey().getIndex()+" ("+entry.getValue()+") ";
else
t = t + "r"+entry.getKey().getIndex()+" ("+entry.getValue()+"), ";
counter++;
}
return t;
}
@Override
public void doPopup(MouseEvent e, int row, Object itemId) {
JPopupMenu popup = new JPopupMenu();
final ITableRowFilter rf = callback.getVisualizationState().getTableRowFilter();
final List<Resource> rowsInTheTable = getVisibleElementsInTable();
/* Add the popup menu option of the filters */
final List<Resource> selectedResources = (List<Resource>) (List<?>) getSelectedElements().getFirst();
if (!selectedResources.isEmpty())
{
final JMenu submenuFilters = new JMenu ("Filters");
final JMenuItem filterKeepElementsAffectedThisLayer = new JMenuItem("This layer: Keep elements associated to this resource traffic");
final JMenuItem filterKeepElementsAffectedAllLayers = new JMenuItem("All layers: Keep elements associated to this resource traffic");
submenuFilters.add(filterKeepElementsAffectedThisLayer);
if (callback.getDesign().getNumberOfLayers() > 1) submenuFilters.add(filterKeepElementsAffectedAllLayers);
filterKeepElementsAffectedThisLayer.addActionListener(new ActionListener()
{
@Override
public void actionPerformed(ActionEvent e)
{
if (selectedResources.size() > 1) throw new RuntimeException ();
TBFToFromCarriedTraffic filter = new TBFToFromCarriedTraffic(selectedResources.get(0), callback.getDesign().getNetworkLayerDefault() , true);
callback.getVisualizationState().updateTableRowFilter(filter);
callback.updateVisualizationJustTables();
}
});
filterKeepElementsAffectedAllLayers.addActionListener(new ActionListener()
{
@Override
public void actionPerformed(ActionEvent e)
{
if (selectedResources.size() > 1) throw new RuntimeException ();
TBFToFromCarriedTraffic filter = new TBFToFromCarriedTraffic(selectedResources.get(0), callback.getDesign().getNetworkLayerDefault() , false);
callback.getVisualizationState().updateTableRowFilter(filter);
callback.updateVisualizationJustTables();
}
});
popup.add(submenuFilters);
popup.addSeparator();
}
if (callback.getVisualizationState().isNetPlanEditable()) {
popup.add(getAddOption());
for (JComponent item : getExtraAddOptions())
popup.add(item);
}
if (!rowsInTheTable.isEmpty())
{
if (callback.getVisualizationState().isNetPlanEditable()) {
if (row != -1) {
if (popup.getSubElements().length > 0) popup.addSeparator();
JMenuItem removeItem = new JMenuItem("Remove " + networkElementType);
removeItem.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e)
{
try {
callback.getDesign().getResourceFromId((Long)itemId).remove();
callback.getVisualizationState().resetPickedState();
callback.updateVisualizationAfterChanges(Sets.newHashSet(NetworkElementType.RESOURCE));
callback.addNetPlanChange();
} catch (Throwable ex) {
ErrorHandling.addErrorOrException(ex, getClass());
ErrorHandling.showErrorDialog("Unable to remove " + networkElementType);
}
}
});
popup.add(removeItem);
}
JMenuItem removeItemsOfAType = new JMenuItem("Remove all table "+networkElementType+"s of a type");
removeItemsOfAType.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
NetPlan netPlan = callback.getDesign();
JComboBox typeSelector = new WiderJComboBox();
final Set<String> resourceTypes = rowsInTheTable.stream().map(ee->ee.getType()).collect(Collectors.toSet());
for(String type : resourceTypes)
typeSelector.addItem(type);
try{
JPanel pane = new JPanel();
pane.add(new JLabel("Resource Type"));
pane.add(typeSelector);
while (true) {
int result = JOptionPane.showConfirmDialog(null, pane, "Please choose the type of "+ networkElementType+" to remove", JOptionPane.OK_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE);
if (result != JOptionPane.OK_OPTION) return;
final String typeToRemove = typeSelector.getSelectedItem().toString();
final List<Resource> resourcesToRemove = rowsInTheTable.stream().filter(r->r.getType().equals(typeToRemove)).collect(Collectors.toList());
for(Resource res : resourcesToRemove)
res.remove();
callback.getVisualizationState().resetPickedState();
callback.updateVisualizationAfterChanges(Sets.newHashSet(NetworkElementType.RESOURCE));
callback.addNetPlanChange();
break;
}
}catch (Throwable ex) {
ErrorHandling.addErrorOrException(ex, getClass());
ErrorHandling.showErrorDialog("Unable to remove " + networkElementType+"s");
}
}
});
popup.add(removeItemsOfAType);
JMenuItem removeItems = new JMenuItem("Remove all table " + networkElementType + "s");
removeItems.addActionListener(new ActionListener()
{
@Override
public void actionPerformed(ActionEvent e) {
NetPlan netPlan = callback.getDesign();
try
{
if (rf == null)
netPlan.removeAllResources();
else
for (Resource r : rowsInTheTable) r.remove();
callback.getVisualizationState().resetPickedState();
callback.updateVisualizationAfterChanges(Sets.newHashSet(NetworkElementType.RESOURCE));
callback.addNetPlanChange();
} catch (Throwable ex) {
ex.printStackTrace();
ErrorHandling.showErrorDialog(ex.getMessage(), "Unable to remove all " + networkElementType + "s");
}
}
});
popup.add(removeItems);
addPopupMenuAttributeOptions(e, row, itemId, popup);
List<JComponent> extraOptions = getExtraOptions(row, itemId);
if (!extraOptions.isEmpty()) {
if (popup.getSubElements().length > 0) popup.addSeparator();
for (JComponent item : extraOptions) popup.add(item);
}
}
List<JComponent> forcedOptions = getForcedOptions();
if (!forcedOptions.isEmpty()) {
if (popup.getSubElements().length > 0) popup.addSeparator();
for (JComponent item : forcedOptions) popup.add(item);
}
}
popup.show(e.getComponent(), e.getX(), e.getY());
}
private JMenuItem getAddOption() {
JMenuItem addItem = addItem = new JMenuItem("Add " + networkElementType);
addItem.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
NetPlan netPlan = callback.getDesign();
try {
JComboBox hostNodeSelector = new WiderJComboBox();
JTextField capUnitsField = new JTextField(20);
JTextField typeSelector = new JTextField(20);
for (Node n : netPlan.getNodes()) {
final String nodeName = n.getName();
String nodeLabel = "Node " + n.getIndex();
if (!nodeName.isEmpty()) nodeLabel += " (" + nodeName + ")";
hostNodeSelector.addItem(StringLabeller.of(n.getId(), nodeLabel));
}
Node hostNode = null;
String capacityUnits = "";
String resType = "";
JPanel pane = new JPanel();
pane.add(new JLabel("Resource Type"));
pane.add(typeSelector);
pane.add(Box.createHorizontalStrut(30));
pane.add(new JLabel("Host Node"));
pane.add(hostNodeSelector);
pane.add(Box.createHorizontalStrut(30));
pane.add(new JLabel("Capacity Units"));
pane.add(capUnitsField);
while (true) {
int result = JOptionPane.showConfirmDialog(null, pane, "Please enter parameters for the new " + networkElementType, JOptionPane.OK_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE);
if (result != JOptionPane.OK_OPTION) return;
hostNode = netPlan.getNodeFromId((Long) ((StringLabeller) hostNodeSelector.getSelectedItem()).getObject());
capacityUnits = capUnitsField.getText();
resType = typeSelector.getText();
break;
}
JPanel panel = new JPanel();
Object [][] data = {null,null,null};
String [] headers = StringUtils.arrayOf("Base Resource","Is Base Resource","Capacity");
TableModel tm = new ClassAwareTableModelImpl(data,headers,new HashSet<Integer>(Arrays.asList(1,2)));
AdvancedJTable table = new AdvancedJTable(tm);
int baseResCounter = 0;
for(Resource r : netPlan.getResources())
{
if(r.getHostNode().toString().equals(hostNode.toString()))
{
baseResCounter++;
}
}
Object[][] newData = new Object[baseResCounter][headers.length];
int counter = 0;
for(Resource r : netPlan.getResources())
{
if(r.getHostNode().toString().equals(hostNode.toString())) {
newData[counter][0] = r.getName();
newData[counter][1] = false;
newData[counter][2] = 0;
addCheckboxCellEditor(false, counter, 1, table);
counter++;
}
}
panel.setLayout(new BorderLayout());
panel.add(new JLabel("Set new resource base resources"),BorderLayout.NORTH);
panel.add(new JScrollPane(table),BorderLayout.CENTER);
((DefaultTableModel)table.getModel()).setDataVector(newData, headers);
while (true) {
int result = JOptionPane.showConfirmDialog(null, panel, "Set base resources", JOptionPane.OK_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE);
if (result != JOptionPane.OK_OPTION) return;
Map<Resource, Double> newBaseResources = new HashMap<>();
for(int j = 0; j < table.getRowCount(); j++)
{
Resource r = netPlan.getResource(j);
String capacity = table.getModel().getValueAt(j,2).toString();
boolean isBaseResource = (boolean)table.getModel().getValueAt(j,1);
if(isBaseResource)
newBaseResources.put(r, Double.parseDouble(capacity));
}
netPlan.addResource(resType, "Resource n_" + netPlan.getResources().size(), hostNode,
0, capacityUnits, newBaseResources, 0, null);
callback.getVisualizationState().resetPickedState();
callback.updateVisualizationAfterChanges(Sets.newHashSet(NetworkElementType.RESOURCE));
callback.addNetPlanChange();
break;
}
}catch (Throwable ex) {
ErrorHandling.showErrorDialog(ex.getMessage(), "Unable to add " + networkElementType);
}
}
});
return addItem;
}
private List<JComponent> getExtraAddOptions() {
List<JComponent> options = new LinkedList<JComponent>();
return options;
}
private List<JComponent> getExtraOptions(final int row, final Object itemId) {
List<JComponent> options = new LinkedList<JComponent>();
final List<Resource> rowsInTheTable = getVisibleElementsInTable();
JMenuItem capacityInBaseResources = new JMenuItem("Set capacity to base resources");
capacityInBaseResources.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
NetPlan netPlan = callback.getDesign();
try
{
Resource res = netPlan.getResourceFromId((Long) itemId);
List<Resource> baseResources = new LinkedList<>(res.getBaseResources());
if(baseResources.size() == 0)
{
JOptionPane.showMessageDialog(null,"This resource hasn't any base resource");
return;
}
JPanel pane = new JPanel();
Object [][] data = {null,null,null};
String [] headers = StringUtils.arrayOf("Index","Type" , "Capacity");
TableModel tm = new ClassAwareTableModelImpl(data,headers,new HashSet<Integer>(Arrays.asList(2)));
AdvancedJTable table = new AdvancedJTable(tm);
Object[][] newData = new Object[baseResources.size()][headers.length];
int counter = 0;
for(Resource r : baseResources)
{
newData[counter][0] = r.getIndex();
newData[counter][1] = r.getType();
newData[counter][2] = res.getCapacityOccupiedInBaseResource(r);
counter++;
}
pane.setLayout(new BorderLayout());
pane.add(new JLabel("Setting the occupied capacity in base resource of index: " + res.getIndex()) , BorderLayout.NORTH);
pane.add(new JScrollPane(table) , BorderLayout.CENTER);
((DefaultTableModel)table.getModel()).setDataVector(newData, headers);
int result = JOptionPane.showConfirmDialog(null, pane, "Set capacity to base resources", JOptionPane.OK_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE);
if (result != JOptionPane.OK_OPTION) return;
Map<Resource,Double> newCapMap = new HashMap<> ();
for (int t = 0 ; t < table.getRowCount() ; t ++)
newCapMap.put(baseResources.get(t) , Double.parseDouble((String) table.getModel().getValueAt(t,2)));
res.setCapacity(res.getCapacity() , newCapMap);
callback.getVisualizationState().resetPickedState();
callback.updateVisualizationAfterChanges(Sets.newHashSet(NetworkElementType.RESOURCE));
callback.addNetPlanChange();
} catch (Throwable ex) {
ErrorHandling.showErrorDialog(ex.getMessage(), "Unable to set capacity to base resources");
}
}
});
options.add(capacityInBaseResources);
JMenuItem setCapacityToAll = new JMenuItem("Set capacity to all (base resources occupation unchanged)");
setCapacityToAll.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
NetPlan netPlan = callback.getDesign();
double cap;
while (true) {
String str = JOptionPane.showInputDialog(null, "Capacity value", "Set capacity to all table resources", JOptionPane.QUESTION_MESSAGE);
if (str == null) return;
try {
cap = Double.parseDouble(str);
if (cap < 0) throw new RuntimeException();
break;
} catch (Throwable ex) {
ErrorHandling.showErrorDialog("Please, introduce a non-negative number", "Error setting capacity");
}
}
try {
for(Resource r : rowsInTheTable)
r.setCapacity(cap , null);
callback.getVisualizationState().resetPickedState();
callback.updateVisualizationAfterChanges(Sets.newHashSet(NetworkElementType.RESOURCE));
callback.addNetPlanChange();
} catch (Throwable ex) {
ErrorHandling.showErrorDialog(ex.getMessage(), "Unable to set capacity to resources");
}
}
});
options.add(setCapacityToAll);
JMenuItem setTraversingTimeToAll = new JMenuItem("Set processing time to all table resources");
setTraversingTimeToAll.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
NetPlan netPlan = callback.getDesign();
double procTime;
while (true) {
String str = JOptionPane.showInputDialog(null, "Processing time in miliseconds value", "Set processing time in miliseconds to all resources", JOptionPane.QUESTION_MESSAGE);
if (str == null) return;
try {
procTime = Double.parseDouble(str);
if (procTime < 0) throw new RuntimeException();
break;
} catch (Throwable ex) {
ErrorHandling.showErrorDialog("Please, introduce a non-negative number", "Error setting processing time");
}
}
try {
for(Resource r : rowsInTheTable)
r.setProcessingTimeToTraversingTrafficInMs(procTime);
callback.getVisualizationState().resetPickedState();
callback.updateVisualizationAfterChanges(Sets.newHashSet(NetworkElementType.RESOURCE));
callback.addNetPlanChange();
} catch (Throwable ex) {
ErrorHandling.showErrorDialog(ex.getMessage(), "Unable to set processing time to resources");
}
}
});
options.add(setTraversingTimeToAll);
return options;
}
private List<JComponent> getForcedOptions() {
return new LinkedList<JComponent>();
}
@Override
public void showInCanvas(MouseEvent e, Object itemId)
{
if (getVisibleElementsInTable().isEmpty()) return;
callback.getVisualizationState ().pickResource(callback.getDesign().getResourceFromId((long) itemId));
callback.updateVisualizationAfterPick();
}
private class ClassAwareTableModelImpl extends ClassAwareTableModel
{
private final Set<Integer> editableColumns;
public ClassAwareTableModelImpl(Object[][] dataVector, Object[] columnIdentifiers , Set<Integer> editableColumns)
{
super(dataVector, columnIdentifiers);
this.editableColumns = editableColumns;
}
@Override
public Class getColumnClass(int col)
{
return Object.class;
}
@Override
public boolean isCellEditable(int rowIndex, int columnIndex)
{
return (this.editableColumns.contains(columnIndex));
}
@Override
public void setValueAt(Object value, int row, int column)
{
super.setValueAt(value, row, column);
}
}
private void addCheckboxCellEditor(boolean defaultValue, int rowIndex, int columnIndex, AdvancedJTable table)
{
JCheckBox checkBox = new JCheckBox();
checkBox.setHorizontalAlignment(JLabel.CENTER);
checkBox.setSelected(defaultValue);
table.setCellEditor(rowIndex, columnIndex, new DefaultCellEditor(checkBox));
table.setCellRenderer(rowIndex, columnIndex, new CheckBoxRenderer());
}
private static class CheckBoxRenderer extends JCheckBox implements TableCellRenderer
{
public CheckBoxRenderer()
{
setHorizontalAlignment(JLabel.CENTER);
}
@Override
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column)
{
if (isSelected)
{
setForeground(table.getSelectionForeground());
setBackground(table.getSelectionBackground());
} else
{
setForeground(table.getForeground());
setBackground(table.getBackground());
}
setSelected(value != null && Boolean.parseBoolean(value.toString()));
return this;
}
}
private List<Resource> getVisibleElementsInTable ()
{
final ITableRowFilter rf = callback.getVisualizationState().getTableRowFilter();
final NetworkLayer layer = callback.getDesign().getNetworkLayerDefault();
return rf == null? callback.getDesign().getResources() : rf.getVisibleResources(layer);
}
}
|
package org.opennms.features.topology.plugins.topo.linkd.internal;
import java.io.File;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.xml.bind.JAXB;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlElements;
import javax.xml.bind.annotation.XmlRootElement;
import org.opennms.features.topology.api.TopologyProvider;
import org.opennms.netmgt.dao.AlarmDao;
import org.opennms.netmgt.dao.DataLinkInterfaceDao;
import org.opennms.netmgt.dao.IpInterfaceDao;
import org.opennms.netmgt.dao.NodeDao;
import org.opennms.netmgt.dao.SnmpInterfaceDao;
import org.opennms.netmgt.model.DataLinkInterface;
import org.opennms.netmgt.model.OnmsAlarm;
import org.opennms.netmgt.model.OnmsIpInterface;
import org.opennms.netmgt.model.OnmsNode;
import org.opennms.netmgt.model.OnmsSeverity;
import org.opennms.netmgt.model.OnmsSnmpInterface;
import org.springframework.util.Assert;
import com.vaadin.data.Item;
import com.vaadin.data.util.BeanContainer;
import com.vaadin.data.util.BeanItem;
public class LinkdTopologyProvider implements TopologyProvider {
public static final String GROUP_ICON_KEY = "linkd-group";
public static final String SERVER_ICON_KEY = "linkd-server";
private boolean addNodeWithoutLink = true;
private DataLinkInterfaceDao m_dataLinkInterfaceDao;
private NodeDao m_nodeDao;
private IpInterfaceDao m_ipInterfaceDao;
private SnmpInterfaceDao m_snmpInterfaceDao;
private AlarmDao m_alarmDao;
private String m_configurationFile;
private Map<Integer, OnmsSeverity> m_nodeToSeveritymap;
public String getConfigurationFile() {
return m_configurationFile;
}
public void setConfigurationFile(String configurationFile) {
m_configurationFile = configurationFile;
}
public AlarmDao getAlarmDao() {
return m_alarmDao;
}
public void setAlarmDao(AlarmDao alarmDao) {
m_alarmDao = alarmDao;
}
public SnmpInterfaceDao getSnmpInterfaceDao() {
return m_snmpInterfaceDao;
}
public void setSnmpInterfaceDao(SnmpInterfaceDao snmpInterfaceDao) {
m_snmpInterfaceDao = snmpInterfaceDao;
}
public IpInterfaceDao getIpInterfaceDao() {
return m_ipInterfaceDao;
}
public void setIpInterfaceDao(IpInterfaceDao ipInterfaceDao) {
m_ipInterfaceDao = ipInterfaceDao;
}
public NodeDao getNodeDao() {
return m_nodeDao;
}
public void setNodeDao(NodeDao nodeDao) {
m_nodeDao = nodeDao;
}
public boolean isAddNodeWithoutLink() {
return addNodeWithoutLink;
}
public void setAddNodeWithoutLink(boolean addNodeWithoutLink) {
this.addNodeWithoutLink = addNodeWithoutLink;
}
private LinkdVertexContainer m_vertexContainer;
private BeanContainer<String, LinkdEdge> m_edgeContainer;
private int m_groupCounter = 0;
public DataLinkInterfaceDao getDataLinkInterfaceDao() {
return m_dataLinkInterfaceDao;
}
public void setDataLinkInterfaceDao(DataLinkInterfaceDao dataLinkInterfaceDao) {
m_dataLinkInterfaceDao = dataLinkInterfaceDao;
}
public void onInit() {
log("init: loading topology v1.2");
loadtopology();
}
public LinkdTopologyProvider() {
m_vertexContainer = new LinkdVertexContainer();
m_edgeContainer = new BeanContainer<String, LinkdEdge>(LinkdEdge.class);
m_edgeContainer.setBeanIdProperty("id");
m_nodeToSeveritymap = new HashMap<Integer, OnmsSeverity>();
}
@Override
public Object addGroup(String groupIcon) {
return addGroup(getNextGroupId(), groupIcon);
}
private Item addGroup(String groupId, String icon) {
if (m_vertexContainer.containsId(groupId)) {
throw new IllegalArgumentException("A vertex or group with id " + groupId + " already exists!");
}
System.err.println("Adding a group: " + groupId);
LinkdVertex vertex = new LinkdGroup(groupId, "Group " + groupId);
vertex.setIconKey(icon);
return m_vertexContainer.addBean(vertex);
}
public String getNextGroupId() {
return "linkdg" + m_groupCounter++;
}
@Override
public boolean containsVertexId(Object vertexId) {
return m_vertexContainer.containsId(vertexId);
}
@Override
public BeanContainer<String, LinkdEdge> getEdgeContainer() {
return m_edgeContainer;
}
@Override
public Collection<String> getEdgeIds() {
return m_edgeContainer.getItemIds();
}
@Override
public Collection<String> getEdgeIdsForVertex(Object vertexId) {
LinkdVertex vertex = getRequiredVertex(vertexId);
List<String> edges = new ArrayList<String>(vertex.getEdges().size());
for(LinkdEdge e : vertex.getEdges()) {
String edgeId = e.getId();
edges.add(edgeId);
}
return edges;
}
private LinkdVertex getRequiredVertex(Object vertexId) {
return getVertex(vertexId, true);
}
private LinkdVertex getVertex(Object vertexId, boolean required) {
BeanItem<LinkdVertex> item = m_vertexContainer.getItem(vertexId);
if (required && item == null) {
throw new IllegalArgumentException("required vertex " + vertexId + " not found.");
}
return item == null ? null : item.getBean();
}
@Override
public Item getEdgeItem(Object edgeId) {
return m_edgeContainer.getItem(edgeId);
}
@Override
public Collection<String> getEndPointIdsForEdge(Object edgeId) {
LinkdEdge edge= getRequiredEdge(edgeId);
List<String> endPoints = new ArrayList<String>(2);
endPoints.add(edge.getSource().getId());
endPoints.add(edge.getTarget().getId());
return endPoints;
}
private LinkdEdge getRequiredEdge(Object edgeId) {
return getEdge(edgeId, true);
}
private LinkdEdge getEdge(Object edgeId, boolean required) {
BeanItem<LinkdEdge> item = m_edgeContainer.getItem(edgeId);
if (required && item == null) {
throw new IllegalArgumentException("required edge " + edgeId + " not found.");
}
return item == null ? null : item.getBean();
}
@Override
public LinkdVertexContainer getVertexContainer() {
return m_vertexContainer;
}
@Override
public Collection<String> getVertexIds() {
return m_vertexContainer.getItemIds();
}
@Override
public Item getVertexItem(Object vertexId) {
return m_vertexContainer.getItem(vertexId);
}
@Override
public void load(String filename) {
if (filename == null) {
loadtopology();
} else {
loadfromfile(filename);
}
}
@XmlRootElement(name="graph")
@XmlAccessorType(XmlAccessType.FIELD)
private static class SimpleGraph {
@XmlElements({
@XmlElement(name="vertex", type=LinkdNodeVertex.class),
@XmlElement(name="group", type=LinkdGroup.class)
})
List<LinkdVertex> m_vertices = new ArrayList<LinkdVertex>();
@XmlElement(name="edge")
List<LinkdEdge> m_edges = new ArrayList<LinkdEdge>();
@SuppressWarnings("unused")
public SimpleGraph() {}
public SimpleGraph(List<LinkdVertex> vertices, List<LinkdEdge> edges) {
m_vertices = vertices;
m_edges = edges;
}
}
private SimpleGraph getGraphFromFile(File file) {
return JAXB.unmarshal(file, SimpleGraph.class);
}
private void loadfromfile(String filename) {
File file = new File(filename);
if (file.exists() && file.canRead()) {
SimpleGraph graph = getGraphFromFile(file);
m_vertexContainer.addAll(graph.m_vertices);
m_edgeContainer.addAll(graph.m_edges);
}
}
private void loadseveritymap() {
m_nodeToSeveritymap.clear();
for (OnmsAlarm alarm: m_alarmDao.findAll()) {
if (m_nodeToSeveritymap.containsKey(alarm.getNodeId())
&& alarm.getSeverity().isLessThan(m_nodeToSeveritymap.get(alarm.getNodeId())))
return;
m_nodeToSeveritymap.put(alarm.getNodeId(), alarm.getSeverity());
}
}
private void loadtopology() {
log("loadtopology: loading topology: configFile:" + m_configurationFile);
log("loadtopology: Clean Vertexcontainer");
getVertexContainer().removeAllItems();
log("loadtopology: Clean EdgeContainer");
getEdgeContainer().removeAllItems();
log("loadtopology: loading node to severity map");
loadseveritymap();
Map<String, LinkdVertex> vertexes = new HashMap<String, LinkdVertex>();
Collection<LinkdEdge> edges = new ArrayList<LinkdEdge>();
for (DataLinkInterface link: m_dataLinkInterfaceDao.findAll()) {
log("loadtopology: parsing link: " + link.getDataLinkInterfaceId());
OnmsNode node = m_nodeDao.get(link.getNode().getId());
log("loadtopology: found node: " + node.getLabel());
String sourceId = node.getNodeId();
LinkdVertex source;
if ( vertexes.containsKey(sourceId)) {
source = vertexes.get(sourceId);
} else {
log("loadtopology: adding source as vertex: " + node.getLabel());
OnmsIpInterface ip = getAddress(node);
source = new LinkdNodeVertex(node.getNodeId(), 0, 0, getIconName(node), node.getLabel(), ( ip == null ? null : ip.getIpAddress().getHostAddress()));
source.setTooltipText(getNodeTooltipText(node, source, ip));
vertexes.put(sourceId, source);
}
OnmsNode parentNode = m_nodeDao.get(link.getNodeParentId());
log("loadtopology: found parentnode: " + parentNode.getLabel());
String targetId = parentNode.getNodeId();
LinkdVertex target;
if (vertexes.containsKey(targetId)) {
target = vertexes.get(targetId);
} else {
log("loadtopology: adding target as vertex: " + parentNode.getLabel());
OnmsIpInterface ip = getAddress(parentNode);
target = new LinkdNodeVertex(parentNode.getNodeId(), 0, 0, getIconName(parentNode), parentNode.getLabel(), ( ip == null ? null : ip.getIpAddress().getHostAddress()));
target.setTooltipText(getNodeTooltipText(parentNode, target, ip));
vertexes.put(targetId, target);
}
LinkdEdge edge = new LinkdEdge(link.getDataLinkInterfaceId(),source,target);
edge.setTooltipText(getEdgeTooltipText(link,source,target));
edges.add(edge);
}
log("loadtopology: isAddNodeWithoutLink: " + isAddNodeWithoutLink());
if (isAddNodeWithoutLink()) {
for (OnmsNode onmsnode: m_nodeDao.findAll()) {
log("loadtopology: parsing link less node: " + onmsnode.getLabel());
String nodeId = onmsnode.getNodeId();
LinkdVertex linklessnode;
if (!vertexes.containsKey(nodeId)) {
log("loadtopology: adding link less node: " + onmsnode.getLabel());
OnmsIpInterface ip = getAddress(onmsnode);
linklessnode = new LinkdNodeVertex(onmsnode.getNodeId(), 0, 0, getIconName(onmsnode), onmsnode.getLabel(), ( ip == null ? null : ip.getIpAddress().getHostAddress()));
linklessnode.setTooltipText(getNodeTooltipText(onmsnode, linklessnode, ip));
vertexes.put(nodeId,linklessnode);
}
}
}
File configFile = new File(m_configurationFile);
if (configFile.exists() && configFile.canRead()) {
log("loadtopology: loading topology from configuration file: " + m_configurationFile);
m_groupCounter=0;
SimpleGraph graph = getGraphFromFile(configFile);
for (LinkdVertex vertex: graph.m_vertices) {
if (!vertex.isLeaf()) {
m_groupCounter++;
LinkdGroup group = (LinkdGroup) vertex;
log("loadtopology: found group: " + group.getId());
for (LinkdVertex vx: group.getMembers()) {
log("loadtopology: found group/member: " + group.getId()+"/"+ vx.getId());
if (vx.isLeaf() && !vertexes.containsKey(vx.getId()))
group.removeMember(vx);
}
vertexes.put(group.getId(), group);
}
}
}
log("Found Vertexes: #" + vertexes.size());
log("Found Edges: #" + edges.size());
log("Found Groups: #" + m_groupCounter);
m_vertexContainer.addAll(vertexes.values());
m_edgeContainer.addAll(edges);
}
private String getEdgeTooltipText(DataLinkInterface link,
LinkdVertex source, LinkdVertex target) {
String tooltipText="";
OnmsSnmpInterface sourceInterface = m_snmpInterfaceDao.findByNodeIdAndIfIndex(Integer.parseInt(source.getId()), link.getIfIndex());
OnmsSnmpInterface targetInterface = m_snmpInterfaceDao.findByNodeIdAndIfIndex(Integer.parseInt(target.getId()), link.getParentIfIndex());
if (sourceInterface == null || targetInterface == null) {
tooltipText+= "Type of the Link: Layer2";
} else if (sourceInterface.getNetMask() != null && !sourceInterface.getNetMask().isLoopbackAddress()
&& targetInterface.getNetMask() != null && !targetInterface.getNetMask().isLoopbackAddress()) {
tooltipText+= "Type of the Link: Layer3/Layer2";
}
tooltipText +="\n";
tooltipText += "Name: <endpoint1 " + source.getLabel() ;
if (sourceInterface != null )
tooltipText += ":"+sourceInterface.getIfName();
tooltipText += " ---- endpoint2 " + target.getLabel();
if (targetInterface != null)
tooltipText += ":"+targetInterface.getIfName();
tooltipText +=">\n";
if (targetInterface != null) {
tooltipText += "Bandwidth: " + getHumanReadableIfSpeed(targetInterface.getIfSpeed());
tooltipText +="\n";
tooltipText += "Link status: " + getIfStatusString(targetInterface.getIfAdminStatus()) + "/" + getIfStatusString(targetInterface.getIfOperStatus());
tooltipText +="\n";
} else if (sourceInterface != null) {
tooltipText += "Bandwidth: " + getHumanReadableIfSpeed(sourceInterface.getIfSpeed());
tooltipText +="\n";
tooltipText += "Link status: " + getIfStatusString(sourceInterface.getIfAdminStatus()) + "/" + getIfStatusString(sourceInterface.getIfOperStatus());
tooltipText +="\n";
}
tooltipText += "EndPoint1: " + source.getLabel() + ", " + source.getIpAddr();
tooltipText +="\n";
tooltipText += "EndPoint2: " + target.getLabel() + ", " + target.getIpAddr();
tooltipText +="\n";
log("getEdgeTooltipText\n" + tooltipText);
return tooltipText;
}
private String getNodeTooltipText(OnmsNode node, LinkdVertex vertex, OnmsIpInterface ip) {
String tooltipText="";
if (node.getSysDescription() != null && node.getSysDescription().length() >0) {
tooltipText +=node.getSysDescription();
tooltipText +="\n";
}
tooltipText += vertex.getIpAddr();
tooltipText +="\n";
tooltipText += vertex.getLabel();
tooltipText +="\n";
if (node.getSysLocation() != null && node.getSysLocation().length() >0) {
tooltipText +=node.getSysLocation();
tooltipText +="\n";
}
OnmsSeverity severity = OnmsSeverity.NORMAL;
if (m_nodeToSeveritymap.containsKey(node.getId()))
severity = m_nodeToSeveritymap.get(node.getId());
tooltipText += "Alarm Status: " + severity.getLabel();
tooltipText +="\n";
tooltipText += getNodeStatusString(node);
if (ip.isManaged()) {
tooltipText += "/Managed";
} else {
tooltipText += "/UnManaged";
}
tooltipText +="\n";
log("getNodeTooltipText:\n" + tooltipText);
return tooltipText;
}
protected String getIconName(OnmsNode node) {
String iconName = SERVER_ICON_KEY;
if (node.getSysObjectId() != null)
iconName = "snmp:"+node.getSysObjectId();
return iconName;
}
private OnmsIpInterface getAddress(OnmsNode node) {
return m_ipInterfaceDao.findPrimaryInterfaceByNodeId(node.getId());
}
@Override
public void save(String filename) {
if (filename == null)
filename=m_configurationFile;
List<LinkdVertex> vertices = getBeans(m_vertexContainer);
List<LinkdEdge> edges = getBeans(m_edgeContainer);
SimpleGraph graph = new SimpleGraph(vertices, edges);
JAXB.marshal(graph, new File(filename));
}
private <T> List<T> getBeans(BeanContainer<?, T> container) {
Collection<?> itemIds = container.getItemIds();
List<T> beans = new ArrayList<T>(itemIds.size());
for(Object itemId : itemIds) {
beans.add(container.getItem(itemId).getBean());
}
return beans;
}
@Override
public void setParent(Object vertexId, Object parentId) {
m_vertexContainer.setParent(vertexId, parentId);
}
private void log(final String string) {
System.err.println("LinkdTopologyProvider: "+ string);
}
/**
* Do not use directly. Call {@link #getNodeStatusMap
* getInterfaceStatusMap} instead.
*/
private static final Map<Character, String> m_nodeStatusMap;
/**
* Do not use directly. Call {@link #getInterfaceStatusMap
* getInterfaceStatusMap} instead.
*/
private static final Map<Character, String> m_interfaceStatusMap;
static {
m_nodeStatusMap = new HashMap<Character, String>();
m_nodeStatusMap.put('A', "Active");
m_nodeStatusMap.put(' ', "Unknown");
m_nodeStatusMap.put('D', "Deleted");
m_interfaceStatusMap = new HashMap<Character, String>();
m_interfaceStatusMap.put('M', "Managed");
m_interfaceStatusMap.put('U', "Unmanaged");
m_interfaceStatusMap.put('D', "Deleted");
m_interfaceStatusMap.put('F', "Forced Unmanaged");
m_interfaceStatusMap.put('N', "Not Monitored");
}
static final String[] OPER_ADMIN_STATUS = new String[] {
" ", //0 (not supported)
"Up",
"Down",
"Testing",
"Unknown",
"Dormant",
"NotPresent",
"LowerLayerDown"
};
private String getIfStatusString(int ifStatusNum) {
if (ifStatusNum < OPER_ADMIN_STATUS.length) {
return OPER_ADMIN_STATUS[ifStatusNum];
} else {
return "Unknown (" + ifStatusNum + ")";
}
}
/**
* Return the human-readable name for a node's status, may be null.
*
* @param node a {@link OnmsNode} object.
* @return a {@link java.lang.String} object.
*/
private String getNodeStatusString(OnmsNode node) {
Assert.notNull(node, "node argument cannot be null");
return getNodeStatusString(node.getType().charAt(0));
}
/**
* Return the human-readable name for a interface status character, may be
* null.
*
* @param c a char.
* @return a {@link java.lang.String} object.
*/
private String getNodeStatusString(char c) {
return m_nodeStatusMap.get(c);
}
/**
* Always print at least one digit after the decimal point,
* and at most three digits after the decimal point.
*/
private static final DecimalFormat s_oneDigitAfterDecimal = new DecimalFormat("0.0
/**
* Print no digits after the decimal point (heh, nor a decimal point).
*/
private static final DecimalFormat s_noDigitsAfterDecimal = new DecimalFormat("0");
/**
* Method used to convert an integer bits-per-second value to a more
* readable vale using commonly recognized abbreviation for network
* interface speeds. Feel free to expand it as necessary to accomodate
* different values.
*
* @param ifSpeed
* The bits-per-second value to be converted into a string
* description
* @return A string representation of the speed ("100 Mbps" for
* example)
*/
private String getHumanReadableIfSpeed(long ifSpeed) {
DecimalFormat formatter;
double displaySpeed;
String units;
if (ifSpeed >= 1000000000L) {
if ((ifSpeed % 1000000000L) == 0) {
formatter = s_noDigitsAfterDecimal;
} else {
formatter = s_oneDigitAfterDecimal;
}
displaySpeed = ((double) ifSpeed) / 1000000000;
units = "Gbps";
} else if (ifSpeed >= 1000000L) {
if ((ifSpeed % 1000000L) == 0) {
formatter = s_noDigitsAfterDecimal;
} else {
formatter = s_oneDigitAfterDecimal;
}
displaySpeed = ((double) ifSpeed) / 1000000;
units = "Mbps";
} else if (ifSpeed >= 1000L) {
if ((ifSpeed % 1000L) == 0) {
formatter = s_noDigitsAfterDecimal;
} else {
formatter = s_oneDigitAfterDecimal;
}
displaySpeed = ((double) ifSpeed) / 1000;
units = "kbps";
} else {
formatter = s_noDigitsAfterDecimal;
displaySpeed = (double) ifSpeed;
units = "bps";
}
return formatter.format(displaySpeed) + " " + units;
}
}
|
package test;
import java.util.Random;
import java.util.Scanner;
public class Sort {
public static void main(String[] args) {
// int[] arr = { 1, 6, 3, 8, 4, 3, 12, 5 };
Scanner scanner = new Scanner(System.in);
int sName = -1;
int[] arr = new int[200000];
Random random = new Random();
for (int i = 0; i < 200000; i++) {
arr[i] = random.nextInt(10000);
}
while (sName != 0) {
int[] tmp = arr.clone();
System.out.println(": 1. 2. 3. 4. 5. 6. 7. 0.");
sName = scanner.nextInt(); // next()
long t = System.currentTimeMillis();
switch (sName) {
case 0:
default:
System.exit(1);
break;
case 1:
bubbleSort(tmp);
break;
case 2:
selectionSort(tmp);
break;
case 3:
insertionSort(tmp);
break;
case 4:
mergeSort(tmp);
break;
case 5:
quickSort(tmp);
break;
case 6:
heapSort(tmp);
break;
case 7:
hellSort(tmp);
break;
}
System.out.println(" " + (System.currentTimeMillis() - t) + "ms");
print(tmp);
System.out.println();
}
}
private static void swap(int[] arr, int i, int j) {
int tmp = arr[i];
arr[i] = arr[j];
arr[j] = tmp;
}
private static void print(int[] arr) {
System.out.println();
for (int i = 0; i < arr.length / 100; i++) {
System.out.print(arr[i] + "*");
}
System.out.println();
}
private static void bubbleSort(int[] arr) {
for (int i = 0; i < arr.length; i++) {
for (int j = i + 1; j < arr.length; j++) {
if (arr[i] > arr[j]) {
swap(arr, i, j);
}
}
}
}
private static void selectionSort(int[] arr) {
int minIndex = 0;
for (int i = 0; i < arr.length; i++) {
minIndex = i;
for (int j = i + 1; j < arr.length; j++) {
if (arr[minIndex] > arr[j]) {
minIndex = j;
}
}
if (minIndex != i) {
swap(arr, i, minIndex);
}
}
}
private static void insertionSort(int[] arr) {
int current = 0;
// for (int i = 1; i < arr.length; i++) {
// current = arr[i];
// for (int j = i; j > 0; j--) {
// if (current < arr[j - 1]) {
// swap(arr, j - 1, j);
// } else {
// break;
int j;
for (int i = 1; i < arr.length; i++) {
current = arr[i];
for (j = i; j > 0; j
if (current < arr[j - 1]) {
arr[j] = arr[j - 1];
} else {
break;
}
}
arr[j] = current;
}
}
private static void mergeSort(int[] arr) {
int[] tmpArr = new int[arr.length];
mergeSort(arr, tmpArr, 0, arr.length - 1);
}
private static void mergeSort(int[] arr, int[] tmpArr, int left, int right) {
if (left >= right) {
return;
}
int center = (left + right) / 2;
mergeSort(arr, tmpArr, left, center);
mergeSort(arr, tmpArr, center + 1, right);
merge(arr, tmpArr, left, center, right);
}
private static void merge(int[] arr, int[] tmpArr, int left, int center, int right) {
int startLeft = left;
int startRight = center + 1;
int tmpLeft = left;
while (startLeft <= center && startRight <= right) {
if (arr[startLeft] < arr[startRight]) {
tmpArr[tmpLeft++] = arr[startLeft++];
} else {
tmpArr[tmpLeft++] = arr[startRight++];
}
}
while (startLeft <= center) {
tmpArr[tmpLeft++] = arr[startLeft++];
}
while (startRight <= right) {
tmpArr[tmpLeft++] = arr[startRight++];
}
while (left <= right) {
arr[left] = tmpArr[left++];
}
}
private static void quickSort(int[] arr) {
quickSort(arr, 0, arr.length - 1);
}
private static void quickSort(int[] arr, int left, int right) {
if (left >= right) {
return;
}
int partitionPos = (left + right) / 2;
swap(arr, partitionPos, right);
int index = left - 1;
for (int i = left; i < right; i++) {
if (arr[i] <= arr[right]) {
swap(arr, ++index, i);
}
}
swap(arr, ++index, right);
quickSort(arr, left, index - 1);
quickSort(arr, index + 1, right);
}
private static void heapSort(int[] arr) {
int lastIndex = arr.length - 1;
buildMaxHeap(arr, lastIndex);
while (lastIndex > 0) {
swap(arr, 0, lastIndex
percDown(arr, 0, lastIndex);
}
}
// 0(1)2 * i + 1
private static int leftChild(int parent) {
return parent * 2 + 1;
}
private static void buildMaxHeap(int[] arr, int lastIndex) {
for (int i = lastIndex / 2; i >= 0; i
percDown(arr, i, lastIndex);
}
}
private static void percDown(int[] arr, int parent, int lastIndex) {
int child = 0;
for (; leftChild(parent) <= lastIndex; parent = child) {
child = leftChild(parent);
if (child < lastIndex && arr[child] < arr[child + 1]) {
child++;
}
if (arr[parent] < arr[child]) {
swap(arr, parent, child);
}
}
}
private static void hellSort(int[] arr) {
int length = arr.length;
int i;
// for (int step = length / 2; step > 0; step /= 2) {
// // step,
// for (int index = step; index < length; index++) {
// // stepstep
// int tmp = arr[index];
// for (i = index; i >= step && arr[i - step] > tmp; i -= step) {
// // (tmp)tmp
// arr[i] = arr[i - step];
// // i<stepi >= step && arr[i - step]<=
// // tmparr[i]tmp
// arr[i] = tmp;
for (int step = length / 2; step > 0; step /= 2) {
// step,
for (int index = step; index < length; index++) {
// stepstep
int tmp = arr[index];
for (i = index; i >= step && arr[i - step] > tmp; i -= step) {
swap(arr, i, i - step);
}
}
}
}
}
|
package fr.openwide.core.wicket.more.markup.html.template.js.jquery.plugins.modal.component;
import org.apache.wicket.ajax.AjaxChannel;
import org.apache.wicket.ajax.AjaxEventBehavior;
import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.ajax.IAjaxCallDecorator;
import org.apache.wicket.ajax.calldecorator.CancelEventIfNoAjaxDecorator;
import org.apache.wicket.ajax.markup.html.AjaxLink;
import org.apache.wicket.markup.ComponentTag;
import org.apache.wicket.markup.html.IHeaderResponse;
import org.apache.wicket.model.IModel;
import fr.openwide.core.wicket.more.markup.html.template.js.jquery.plugins.modal.ModalJavaScriptResourceReference;
import fr.openwide.core.wicket.more.markup.html.template.js.jquery.plugins.modal.behavior.ConfirmContentBehavior;
import fr.openwide.core.wicket.more.markup.html.template.js.jquery.plugins.modal.misc.ConfirmAjaxCallDecorator;
public abstract class AjaxConfirmLink<O> extends AjaxLink<O> {
private static final long serialVersionUID = -645345859108195615L;
private static final IAjaxCallDecorator CONFIRM_DECORATOR = new ConfirmAjaxCallDecorator();
public AjaxConfirmLink(String id, IModel<O> model, IModel<String> titleModel, IModel<String> textModel,
IModel<String> yesLabelModel, IModel<String> noLabelModel) {
this(id, model, titleModel, textModel, yesLabelModel, noLabelModel, false);
}
public AjaxConfirmLink(String id, IModel<O> model, IModel<String> titleModel, IModel<String> textModel,
IModel<String> yesLabelModel, IModel<String> noLabelModel, boolean textNoEscape) {
super(id, model);
setOutputMarkupId(true);
add(new ConfirmContentBehavior(titleModel, textModel, yesLabelModel, noLabelModel, textNoEscape));
}
@Override
protected IAjaxCallDecorator getAjaxCallDecorator() {
return CONFIRM_DECORATOR;
}
@Override
public void renderHead(IHeaderResponse response) {
super.renderHead(response);
response.renderJavaScriptReference(ModalJavaScriptResourceReference.get());
}
@Override
protected AjaxEventBehavior newAjaxEventBehavior(String event) {
return new AjaxEventBehavior(event) {
private static final long serialVersionUID = 1L;
@Override
protected void onEvent(AjaxRequestTarget target) {
onClick(target);
}
@Override
protected IAjaxCallDecorator getAjaxCallDecorator() {
return AjaxConfirmLink.this.getAjaxCallDecorator();
}
@Override
protected void onComponentTag(ComponentTag tag) {
// add the onclick handler only if link is enabled
if (isLinkEnabled())
{
super.onComponentTag(tag);
}
}
@Override
protected AjaxChannel getChannel() {
return AjaxConfirmLink.this.getChannel();
}
};
}
}
|
package com.microsoft.windowsazure.services.media.implementation.templates.tokenrestriction;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import java.net.URI;
import java.net.URISyntaxException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.TimeZone;
import java.util.UUID;
import javax.xml.bind.JAXBException;
import org.junit.Test;
import org.xml.sax.SAXException;
public class TokenRestrictionTemplateSerializerTests {
private final String schemaFile = TokenRestrictionTemplateSerializerTests.class.getClassLoader().getResource("")
.getPath() + "schemas/TokenRestrictionTemplate.xsd";
private final String _sampleIssuer = "http://sampleIssuerUrl";
private final String _sampleAudience = "http://sampleAudience";
@Test
public void RoundTripTest() throws JAXBException, URISyntaxException {
TokenRestrictionTemplate template = new TokenRestrictionTemplate(TokenType.SWT);
template.setPrimaryVerificationKey(new SymmetricVerificationKey());
template.getAlternateVerificationKeys().add(new SymmetricVerificationKey());
template.setAudience(new URI(_sampleAudience));
template.setIssuer(new URI(_sampleIssuer));
template.getRequiredClaims().add(TokenClaim.getContentKeyIdentifierClaim());
template.getRequiredClaims().add(new TokenClaim("Rental", "true"));
String serializedTemplate = TokenRestrictionTemplateSerializer.serialize(template);
assertTrue(serializedTemplate != null && serializedTemplate.length() > 0);
TokenRestrictionTemplate template2 = TokenRestrictionTemplateSerializer.deserialize(serializedTemplate);
assertNotNull(template2);
assertEquals(template.getIssuer(), template2.getIssuer());
assertEquals(template.getAudience(), template2.getAudience());
assertEquals(template.getTokenType(), TokenType.SWT);
SymmetricVerificationKey fromTemplate = (SymmetricVerificationKey) template.getPrimaryVerificationKey();
SymmetricVerificationKey fromTemplate2 = (SymmetricVerificationKey) template2.getPrimaryVerificationKey();
assertArrayEquals(fromTemplate.getKeyValue(), fromTemplate2.getKeyValue());
}
@Test
public void KnownGoodInputForSwtOnlyScheme() throws JAXBException {
String tokenTemplate = "<TokenRestrictionTemplate xmlns:i=\"http:
TokenRestrictionTemplate template = TokenRestrictionTemplateSerializer.deserialize(tokenTemplate);
assertNotNull(template);
assertEquals(TokenType.SWT, template.getTokenType());
}
@Test
public void KnownGoodInputForJWT() throws JAXBException {
String tokenTemplate = "<TokenRestrictionTemplate xmlns:i=\"http:
TokenRestrictionTemplate template = TokenRestrictionTemplateSerializer.deserialize(tokenTemplate);
assertNotNull(template);
assertEquals(TokenType.JWT, template.getTokenType());
}
@Test
public void KnownGoodInputForSWT() throws JAXBException {
String tokenTemplate = "<TokenRestrictionTemplate xmlns:i=\"http:
TokenRestrictionTemplate template = TokenRestrictionTemplateSerializer.deserialize(tokenTemplate);
assertNotNull(template);
assertEquals(TokenType.SWT, template.getTokenType());
}
@Test
public void InputMissingIssuerShouldThrow() {
String tokenTemplate = "<TokenRestrictionTemplate xmlns:i=\"http:
try {
@SuppressWarnings("unused")
TokenRestrictionTemplate template = TokenRestrictionTemplateSerializer.deserialize(tokenTemplate,
schemaFile);
fail("Should throw");
} catch (JAXBException e) {
assertTrue(e.getLinkedException().getMessage().contains("Issuer"));
} catch (SAXException e) {
fail("Invalid Schema");
}
}
@Test
public void InputMissingAudienceShouldThrow() {
String tokenTemplate = "<TokenRestrictionTemplate xmlns:i=\"http:
try {
@SuppressWarnings("unused")
TokenRestrictionTemplate template = TokenRestrictionTemplateSerializer.deserialize(tokenTemplate,
schemaFile);
fail("Should throw");
} catch (JAXBException e) {
assertTrue(e.getLinkedException().getMessage().contains("Audience"));
} catch (SAXException e) {
fail("Invalid Schema");
}
}
@Test
public void InputMissingPrimaryKeyShouldThrow() {
String tokenTemplate = "<TokenRestrictionTemplate xmlns:i=\"http:
try {
@SuppressWarnings("unused")
TokenRestrictionTemplate template = TokenRestrictionTemplateSerializer.deserialize(tokenTemplate,
schemaFile);
fail("Should throw");
} catch (JAXBException e) {
assertTrue(e.getLinkedException().getMessage().contains("PrimaryVerificationKey"));
} catch (SAXException e) {
fail("Invalid Schema");
}
}
@Test
public void InputMissingRequiredClaimsOkay() throws JAXBException {
String tokenTemplate = "<TokenRestrictionTemplate xmlns:i=\"http:
TokenRestrictionTemplate template = TokenRestrictionTemplateSerializer.deserialize(tokenTemplate);
assertNotNull(template);
assertEquals(template.getTokenType(), TokenType.SWT);
}
@Test
public void knownGoodGenerateTestTokenSWT() throws Exception {
// Arrange
String expectedToken = "urn%3amicrosoft%3aazure%3amediaservices%3acontentkeyidentifier=24734598-f050-4cbb-8b98-2dad6eaa260a&Audience=http%3a%2f%2faudience.com&ExpiresOn=1451606400&Issuer=http%3a%2f%2fissuer.com&HMACSHA256=2XrNjMo1EIZflJOovHxt9dekEhb2DhqG9fU5MjQy9vI%3d";
byte[] knownSymetricKey = "64bytes6RNhi8EsxcYsdYQ9zpFuNR1Ks9milykbxYWGILaK0LKzd5dCtYonsr456".getBytes();
UUID knownGuid = UUID.fromString("24734598-f050-4cbb-8b98-2dad6eaa260a");
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd", Locale.ENGLISH);
sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
Date knownExpireOn = sdf.parse("2016-01-01");
String knownAudience = "http://audience.com";
String knownIssuer = "http://issuer.com";
TokenRestrictionTemplate template = new TokenRestrictionTemplate(TokenType.SWT);
template.setPrimaryVerificationKey(new SymmetricVerificationKey(knownSymetricKey));
template.setAudience(new URI(knownAudience));
template.setIssuer(new URI(knownIssuer));
template.getRequiredClaims().add(TokenClaim.getContentKeyIdentifierClaim());
// Act
String resultsToken = TokenRestrictionTemplateSerializer.generateTestToken(template,
template.getPrimaryVerificationKey(), knownGuid, knownExpireOn, null);
// Assert
assertEquals(expectedToken, resultsToken);
}
@Test
public void knownGoodGenerateTestTokenJWT() throws Exception {
// Arrange
String expectedToken = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJhdWQiOiJ1cm46Y29udG9zbyIsInVybjptaWNyb3NvZnQ6YXp1cmU6bWVkaWFzZXJ2aWNlczpjb250ZW50a2V5aWRlbnRpZmllciI6IjA5MTQ0MzVkLTE1MDAtODBjNC02YzJiLWYxZTUyZmRhNDdhZSIsImlzcyI6Imh0dHBzOi8vdHN0LmNvbnRvc28uY29tIiwiZXhwIjoxNDUxNjA2NDAwLCJpYXQiOjE0MjAwNzA0MDB9.Lv3YphKPyakYwcX3CAcA--VKOrvBG0CuAARejz3DDLM";
byte[] knownSymetricKey = "64bytes6RNhi8EsxcYsdYQ9zpFuNR1Ks9milykbxYWGILaK0LKzd5dCtYonsr456".getBytes();
String strUuid = "0914435d-1500-80c4-6c2b-f1e52fda47ae";
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd", Locale.ENGLISH);
sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
Date notBefore = sdf.parse("2015-01-01");
Date expires = sdf.parse("2016-01-01");
String knownAudience = "urn:contoso";
String knownIssuer = "https://tst.contoso.com";
TokenRestrictionTemplate template = new TokenRestrictionTemplate(TokenType.JWT);
template.setPrimaryVerificationKey(new SymmetricVerificationKey(knownSymetricKey));
template.setAudience(new URI(knownAudience));
template.setIssuer(new URI(knownIssuer));
template.getRequiredClaims().add(new TokenClaim(TokenClaim.getContentKeyIdentifierClaimType(), strUuid));
// Act
String resultsToken = TokenRestrictionTemplateSerializer.generateTestToken(template, null, null, expires, notBefore);
// Assert
assertEquals(expectedToken, resultsToken);
}
@Test
public void NullContentKeyIdentifierClaimShouldThrownSWT() throws Exception {
byte[] knownSymetricKey = "64bytes6RNhi8EsxcYsdYQ9zpFuNR1Ks9milykbxYWGILaK0LKzd5dCtYonsr456".getBytes();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd", Locale.ENGLISH);
sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
Date knownExpireOn = sdf.parse("2016-01-01");
String knownAudience = "http://audience.com";
String knownIssuer = "http://issuer.com";
TokenRestrictionTemplate template = new TokenRestrictionTemplate(TokenType.SWT);
template.setPrimaryVerificationKey(new SymmetricVerificationKey(knownSymetricKey));
template.setAudience(new URI(knownAudience));
template.setIssuer(new URI(knownIssuer));
template.getRequiredClaims().add(TokenClaim.getContentKeyIdentifierClaim());
// Act
try {
TokenRestrictionTemplateSerializer.generateTestToken(template,
template.getPrimaryVerificationKey(), null, knownExpireOn, null);
fail("Null ContentKeyIdentifier Claim Should thrown.");
} catch(IllegalArgumentException e) {
// Assert
assertTrue(e.getMessage().contains("keyIdForContentKeyIdentifierClaim"));
}
}
@Test
public void NullContentKeyIdentifierClaimShouldThrownJWT() throws Exception {
byte[] knownSymetricKey = "64bytes6RNhi8EsxcYsdYQ9zpFuNR1Ks9milykbxYWGILaK0LKzd5dCtYonsr456".getBytes();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd", Locale.ENGLISH);
sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
Date knownExpireOn = sdf.parse("2016-01-01");
String knownAudience = "http://audience.com";
String knownIssuer = "http://issuer.com";
TokenRestrictionTemplate template = new TokenRestrictionTemplate(TokenType.JWT);
template.setPrimaryVerificationKey(new SymmetricVerificationKey(knownSymetricKey));
template.setAudience(new URI(knownAudience));
template.setIssuer(new URI(knownIssuer));
template.getRequiredClaims().add(TokenClaim.getContentKeyIdentifierClaim());
// Act
try {
TokenRestrictionTemplateSerializer.generateTestToken(template,
template.getPrimaryVerificationKey(), null, knownExpireOn, null);
fail("Null ContentKeyIdentifier Claim Should thrown.");
} catch(IllegalArgumentException e) {
// Assert
assertTrue(e.getMessage().contains("keyIdForContentKeyIdentifierClaim"));
}
}
@Test
public void OpenIdDocumentAsVerificationKeyRoundTrip() throws JAXBException, URISyntaxException
{
String openConnectId = "https://openconnectIddiscoveryUri";
String expectedElement =
"<OpenIdDiscoveryUri>https://openconnectIddiscoveryUri</OpenIdDiscoveryUri>";
TokenRestrictionTemplate template = new TokenRestrictionTemplate(TokenType.JWT);
template.setAudience(new URI(_sampleAudience));
template.setIssuer(new URI(_sampleIssuer));
OpenIdConnectDiscoveryDocument openId = new OpenIdConnectDiscoveryDocument();
openId.setOpenIdDiscoveryUri(openConnectId);
template.setOpenIdConnectDiscoveryDocument(openId);
String templateAsString = TokenRestrictionTemplateSerializer.serialize(template);
assertTrue(templateAsString.contains("<PrimaryVerificationKey i:nil=\"true\"/>"));
assertTrue(templateAsString.contains(expectedElement));
TokenRestrictionTemplate output = TokenRestrictionTemplateSerializer.deserialize(templateAsString);
assertNotNull(output);
assertNotNull(output.getOpenIdConnectDiscoveryDocument());
assertNull(output.getPrimaryVerificationKey());
assertTrue(output.getAlternateVerificationKeys().isEmpty());
assertEquals(output.getOpenIdConnectDiscoveryDocument().getOpenIdDiscoveryUri(), openConnectId);
}
@Test
public void TokenRestrictionTemplateSerializeNotPrimaryKeyAndNoOpenConnectIdDocument() throws URISyntaxException
{
TokenRestrictionTemplate template = new TokenRestrictionTemplate(TokenType.JWT);
template.setAudience(new URI(_sampleAudience));
template.setIssuer(new URI(_sampleIssuer));
try {
TokenRestrictionTemplateSerializer.serialize(template);
fail();
}
catch (Exception ex) {
assertEquals("Both PrimaryVerificationKey and OpenIdConnectDiscoveryDocument are null.", ex.getMessage());
}
}
@Test
public void InputMissingPrimaryKeyShouldNotThrow()
{
String tokenTemplate = "<TokenRestrictionTemplate xmlns:i=\"http:
try {
TokenRestrictionTemplateSerializer.deserialize(tokenTemplate);
fail();
} catch (Exception ex) {
assertEquals("Both PrimaryVerificationKey and OpenIdConnectDiscoveryDocument are null.", ex.getMessage());
}
}
@Test
public void TokenRestrictionTemplateDeserializeNotAbsoluteDiscoveryUri()
{
String body =
"<TokenRestrictionTemplate xmlns:i=\"http:
try
{
TokenRestrictionTemplateSerializer.deserialize(body);
fail();
}
catch (Exception ex)
{
assertEquals("String representation of OpenIdConnectDiscoveryDocument.OpenIdDiscoveryUri is not valid absolute Uri.", ex.getMessage());
}
}
@Test
public void TokenRestrictionTemplateDeserializeNilOpenConnectIdDocumentUriNoPrimaryKey()
{
String body =
"<TokenRestrictionTemplate xmlns:i=\"http:
try
{
TokenRestrictionTemplateSerializer.deserialize(body);
fail();
}
catch (Exception ex)
{
assertEquals("OpenIdConnectDiscoveryDocument.OpenIdDiscoveryUri string value is null or empty.", ex.getMessage());
}
}
}
|
package org.xwiki.extension.xar.internal.handler;
import java.io.Closeable;
import java.io.File;
import java.io.IOException;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.xwiki.extension.ExtensionException;
import org.xwiki.extension.ExtensionId;
import org.xwiki.extension.InstalledExtension;
import org.xwiki.extension.LocalExtension;
import org.xwiki.extension.job.plan.ExtensionPlan;
import org.xwiki.extension.job.plan.ExtensionPlanAction;
import org.xwiki.extension.job.plan.ExtensionPlanAction.Action;
import org.xwiki.extension.repository.InstalledExtensionRepository;
import org.xwiki.extension.repository.LocalExtensionRepository;
import org.xwiki.extension.xar.internal.handler.packager.Packager;
import org.xwiki.extension.xar.internal.repository.XarInstalledExtension;
import org.xwiki.model.reference.DocumentReference;
import org.xwiki.model.reference.LocalDocumentReference;
import org.xwiki.model.reference.WikiReference;
import org.xwiki.xar.XarEntry;
import org.xwiki.xar.XarException;
import org.xwiki.xar.XarPackage;
import com.xpn.xwiki.doc.XWikiDocument;
/**
* @version $Id$
* @since 5.4M1
*/
public class XarExtensionPlan implements Closeable
{
public static final String CONTEXTKEY_XARINSTALLPLAN = "extension.xar.installplan";
/**
* Logging helper object.
*/
private static final Logger LOGGER = LoggerFactory.getLogger(XarExtensionPlan.class);
public final Map<String, Map<XarEntry, XarExtensionPlanEntry>> previousXAREntries;
/**
* Map<namespace, >
*/
public final Map<String, Map<XarEntry, LocalExtension>> nextXAREntries;
public XarExtensionPlan(ExtensionPlan plan, InstalledExtensionRepository xarRepository,
LocalExtensionRepository localReposirory) throws ExtensionException, XarException, IOException
{
this.previousXAREntries = new HashMap<>();
this.nextXAREntries = new HashMap<>();
Map<ExtensionId, XarExtensionPlanEntry> planEntry = new HashMap<>();
for (ExtensionPlanAction action : plan.getActions()) {
if (XarExtensionHandler.TYPE.equals(action.getExtension().getType())) {
// Get previous entries
Collection<InstalledExtension> previousExtensions = action.getPreviousExtensions();
for (InstalledExtension previousExtension : previousExtensions) {
if (previousExtension != null && previousExtension.getType().equals(XarExtensionHandler.TYPE)) {
XarInstalledExtension previousXARExtension =
(XarInstalledExtension) xarRepository.getInstalledExtension(previousExtension.getId());
if (previousXARExtension == null) {
// Very weird situation but let's be safe
LOGGER.error("Installed extension [{}] is not properly registered in"
+ " the virtual XAR installed extensions repository", previousExtension);
continue;
}
XarExtensionPlanEntry xarPlanEntry = planEntry.get(previousXARExtension.getId());
if (xarPlanEntry == null) {
xarPlanEntry =
new XarExtensionPlanEntry(previousXARExtension, previousXARExtension.getXarPackage());
planEntry.put(previousXARExtension.getId(), xarPlanEntry);
}
for (XarEntry entry : previousXARExtension.getXarPackage().getEntries()) {
String wiki;
try {
wiki = XarHandlerUtils.getWikiFromNamespace(action.getNamespace());
} catch (UnsupportedNamespaceException e) {
throw new ExtensionException("Failed to extract wiki id from namespace", e);
}
Map<XarEntry, XarExtensionPlanEntry> pages = previousXAREntries.get(wiki);
if (pages == null) {
pages = new HashMap<>();
this.previousXAREntries.put(wiki, pages);
}
// We want to replace the key too because the type might be different but HashMap keep the old one
pages.remove(entry);
pages.put(entry, xarPlanEntry);
}
}
}
// Get new entries
LocalExtension nextExtension = action.getAction() != Action.UNINSTALL && action.getExtension() != null
? localReposirory.getLocalExtension(action.getExtension().getId()) : null;
if (nextExtension != null) {
try {
Collection<XarEntry> entries =
XarPackage.getEntries(new File(nextExtension.getFile().getAbsolutePath()));
for (XarEntry entry : entries) {
String wiki;
try {
wiki = XarHandlerUtils.getWikiFromNamespace(action.getNamespace());
} catch (UnsupportedNamespaceException e) {
throw new ExtensionException("Failed to extract wiki id from namespace", e);
}
Map<XarEntry, LocalExtension> pages = this.nextXAREntries.get(wiki);
if (pages == null) {
pages = new HashMap<>();
this.nextXAREntries.put(wiki, pages);
}
// We want to replace the key too because the type might be different but HashMap keep the old one
pages.remove(entry);
pages.put(entry, nextExtension);
}
} catch (Exception e) {
LOGGER.error("Failed to parse extension file [{}]", nextExtension.getFile().getAbsolutePath(),
e);
}
}
}
}
}
public XarExtensionPlanEntry getPreviousXarExtensionPlanEntry(DocumentReference documentReference)
{
String wiki = documentReference.getWikiReference().getName();
LocalDocumentReference localDocumentReference = new LocalDocumentReference(documentReference);
return getPreviousXarExtensionPlanEntry(wiki, localDocumentReference);
}
public XarExtensionPlanEntry getPreviousXarExtensionPlanEntry(String wiki,
LocalDocumentReference localDocumentReference)
{
XarEntry xarEntry = new XarEntry(localDocumentReference);
XarExtensionPlanEntry planEntry = null;
Map<XarEntry, XarExtensionPlanEntry> wikiEntry = this.previousXAREntries.get(wiki);
if (wikiEntry != null) {
planEntry = wikiEntry.get(xarEntry);
}
if (planEntry == null) {
wikiEntry = this.previousXAREntries.get(null);
if (wikiEntry != null) {
planEntry = wikiEntry.get(xarEntry);
}
}
return planEntry;
}
public XarInstalledExtension getPreviousXarExtension(DocumentReference documentReference)
{
String wiki = documentReference.getWikiReference().getName();
LocalDocumentReference localDocumentReference = new LocalDocumentReference(documentReference);
return getPreviousXarExtension(wiki, localDocumentReference);
}
public XarInstalledExtension getPreviousXarExtension(String wiki, LocalDocumentReference localDocumentReference)
{
XarExtensionPlanEntry entry = getPreviousXarExtensionPlanEntry(wiki, localDocumentReference);
return entry != null ? entry.extension : null;
}
public LocalExtension getNextXarExtension(DocumentReference documentReference)
{
WikiReference wikiReference = documentReference.getWikiReference();
LocalDocumentReference localDocumentReference = new LocalDocumentReference(documentReference);
return getNextXarExtension(wikiReference.getName(), localDocumentReference);
}
public LocalExtension getNextXarExtension(String wiki, LocalDocumentReference localDocumentReference)
{
XarEntry xarEntry = new XarEntry(localDocumentReference);
LocalExtension nextExtension = null;
Map<XarEntry, LocalExtension> wikiEntry = this.nextXAREntries.get(wiki);
if (wikiEntry != null) {
nextExtension = wikiEntry.get(xarEntry);
}
if (nextExtension == null) {
wikiEntry = this.nextXAREntries.get(null);
if (wikiEntry != null) {
nextExtension = wikiEntry.get(xarEntry);
}
}
return nextExtension;
}
public XWikiDocument getPreviousXWikiDocument(DocumentReference documentReference, Packager packager)
throws XarException, IOException
{
WikiReference wikiReference = documentReference.getWikiReference();
LocalDocumentReference localDocumentReference = new LocalDocumentReference(documentReference);
return getPreviousXWikiDocument(wikiReference, localDocumentReference, packager);
}
public XWikiDocument getPreviousXWikiDocument(WikiReference wikiReference, LocalDocumentReference localReference,
Packager packager) throws XarException, IOException
{
XarExtensionPlanEntry xarPlanEntry = getPreviousXarExtensionPlanEntry(wikiReference.getName(), localReference);
return xarPlanEntry != null ? packager.getXWikiDocument(wikiReference, localReference, xarPlanEntry.xarFile)
: null;
}
@Override
public void close() throws IOException
{
for (Map<XarEntry, XarExtensionPlanEntry> wikiEntry : this.previousXAREntries.values()) {
for (XarExtensionPlanEntry entry : wikiEntry.values()) {
entry.close();
}
}
}
public boolean containsNewPage(DocumentReference documentReference)
{
WikiReference wikiReference = documentReference.getWikiReference();
LocalDocumentReference localDocumentReference = new LocalDocumentReference(documentReference);
return containsNewPage(wikiReference, localDocumentReference);
}
public boolean containsNewPage(WikiReference wikiReference, LocalDocumentReference localDocumentReference)
{
return getNextXarExtension(wikiReference.getName(), localDocumentReference) != null;
}
public boolean containsNewPages()
{
return !this.nextXAREntries.isEmpty();
}
}
|
package org.wso2.carbon.identity.data.publisher.application.authentication.impl;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.CarbonConstants;
import org.wso2.carbon.identity.application.authentication.framework.model.AuthenticationResult;
import org.wso2.carbon.identity.application.authentication.framework.util.FrameworkConstants;
import org.wso2.carbon.identity.core.bean.context.MessageContext;
import org.wso2.carbon.identity.core.handler.AbstractIdentityMessageHandler;
import org.wso2.carbon.identity.core.model.IdentityEventListenerConfig;
import org.wso2.carbon.identity.core.util.IdentityUtil;
import org.wso2.carbon.identity.data.publisher.application.authentication.AbstractAuthenticationDataPublisher;
import org.wso2.carbon.identity.data.publisher.application.authentication.AuthPublisherConstants;
import org.wso2.carbon.identity.data.publisher.application.authentication.AuthnDataPublisherUtils;
import org.wso2.carbon.identity.data.publisher.application.authentication.model.AuthenticationData;
import org.wso2.carbon.identity.data.publisher.application.authentication.model.SessionData;
import java.security.NoSuchAlgorithmException;
public class AuthenticationAuditLogger extends AbstractAuthenticationDataPublisher {
private static final Log AUDIT_LOG = CarbonConstants.AUDIT_LOG;
public static final Log LOG = LogFactory.getLog(AuthenticationAuditLogger.class);
@Override
public String getName() {
return "AuditDataPublisher";
}
@Override
public int getPriority(MessageContext messageContext) {
return 1;
}
@Override
public void doPublishAuthenticationStepSuccess(AuthenticationData authenticationData) {
String auditData = "\"" + "ContextIdentifier" + "\" : \"" + authenticationData.getContextId()
+ "\",\"" + "AuthenticatedUser" + "\" : \"" + authenticationData.getUsername()
+ "\",\"" + "AuthenticatedUserTenantDomain" + "\" : \"" + authenticationData.getTenantDomain()
+ "\",\"" + "ServiceProviderName" + "\" : \"" + authenticationData.getServiceProvider()
+ "\",\"" + "RequestType" + "\" : \"" + authenticationData.getInboundProtocol()
+ "\",\"" + "RelyingParty" + "\" : \"" + authenticationData.getParameter(AuthPublisherConstants
.RELYING_PARTY)
+ "\",\"" + "AuthenticatedIdP" + "\" : \"" + authenticationData.getIdentityProvider()
+ "\"";
AUDIT_LOG.info(String.format(
FrameworkConstants.AUDIT_MESSAGE,
authenticationData.getUsername(),
"LoginStepSuccess",
"ApplicationAuthenticationFramework", auditData, FrameworkConstants.AUDIT_SUCCESS));
}
@Override
public void doPublishAuthenticationStepFailure(AuthenticationData authenticationData) {
String auditData = "\"" + "ContextIdentifier" + "\" : \"" + authenticationData.getContextId()
+ "\",\"" + "ServiceProviderName" + "\" : \"" + authenticationData.getServiceProvider()
+ "\",\"" + "RequestType" + "\" : \"" + authenticationData.getInboundProtocol()
+ "\",\"" + "RelyingParty" + "\" : \"" + authenticationData.getParameter(AuthPublisherConstants
.RELYING_PARTY)
+ "\",\"" + "StepNo" + "\" : \"" + authenticationData.getStepNo()
+ "\"";
AUDIT_LOG.info(String.format(
FrameworkConstants.AUDIT_MESSAGE,
null,
"Login",
"ApplicationAuthenticationFramework", auditData, FrameworkConstants.AUDIT_FAILED));
}
@Override
public void doPublishAuthenticationSuccess(AuthenticationData authenticationData) {
AuthenticationResult authenticationResult = new AuthenticationResult();
authenticationResult.setAuthenticated(true);
String auditData = "\"" + "ContextIdentifier" + "\" : \"" + authenticationData.getContextId()
+ "\",\"" + "AuthenticatedUser" + "\" : \"" + authenticationData.getParameter(AuthPublisherConstants
.SUBJECT_IDENTIFIER)
+ "\",\"" + "AuthenticatedUserTenantDomain" + "\" : \"" + authenticationData.getTenantDomain()
+ "\",\"" + "ServiceProviderName" + "\" : \"" + authenticationData.getTenantDomain()
+ "\",\"" + "RequestType" + "\" : \"" + authenticationData.getInboundProtocol()
+ "\",\"" + "RelyingParty" + "\" : \"" + authenticationData.getParameter(AuthPublisherConstants
.RELYING_PARTY)
+ "\",\"" + "AuthenticatedIdPs" + "\" : \"" + authenticationData.getParameter(AuthPublisherConstants
.AUTHENTICATED_IDPS)
+ "\"";
AUDIT_LOG.info(String.format(
FrameworkConstants.AUDIT_MESSAGE,
authenticationData.getParameter(AuthPublisherConstants.SUBJECT_IDENTIFIER),
"Login",
"ApplicationAuthenticationFramework", auditData, FrameworkConstants.AUDIT_SUCCESS));
}
@Override
public void doPublishAuthenticationFailure(AuthenticationData authenticationData) {
String auditData = "\"" + "ContextIdentifier" + "\" : \"" + authenticationData.getContextId()
+ "\",\"" + "ServiceProviderName" + "\" : \"" + authenticationData.getServiceProvider()
+ "\",\"" + "RequestType" + "\" : \"" + authenticationData.getInboundProtocol()
+ "\",\"" + "RelyingParty" + "\" : \"" + authenticationData.getParameter(AuthPublisherConstants
.RELYING_PARTY)
+ "\",\"" + "StepNo" + "\" : \"" + authenticationData.getStepNo()
+ "\"";
AUDIT_LOG.info(String.format(
FrameworkConstants.AUDIT_MESSAGE,
null,
"Login",
"ApplicationAuthenticationFramework", auditData, FrameworkConstants.AUDIT_FAILED));
}
@Override
public void doPublishSessionCreation(SessionData sessionData) {
// Nothing to implement
}
@Override
public void doPublishSessionUpdate(SessionData sessionData) {
// Nothing to implement
}
@Override
public void doPublishSessionTermination(SessionData sessionData) {
String auditData = null;
try {
auditData = "\"" + "ContextIdentifier" + "\" : \"" + AuthnDataPublisherUtils.hashString(sessionData.getSessionId())
+ "\"";
AUDIT_LOG.info(String.format(
FrameworkConstants.AUDIT_MESSAGE,
sessionData.getUser(),
"Logout",
"ApplicationAuthenticationFramework", auditData, FrameworkConstants.AUDIT_SUCCESS));
} catch (NoSuchAlgorithmException e) {
LOG.debug("Error while hashing common auth ID");
}
}
@Override
public boolean isEnabled(MessageContext messageContext) {
IdentityEventListenerConfig identityEventListenerConfig = IdentityUtil.readEventListenerProperty
(AbstractIdentityMessageHandler.class.getName(), this.getClass().getName());
if (identityEventListenerConfig == null) {
return true;
}
return Boolean.parseBoolean(identityEventListenerConfig.getEnable());
}
@Override
public boolean canHandle(MessageContext messageContext) {
return true;
}
}
|
package org.xwiki.rendering.internal.macro.container;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.inject.Inject;
import javax.inject.Named;
import javax.inject.Singleton;
import org.apache.commons.lang3.StringUtils;
import org.xwiki.component.annotation.Component;
import org.xwiki.rendering.block.Block;
import org.xwiki.rendering.block.GroupBlock;
import org.xwiki.rendering.block.match.ClassBlockMatcher;
import org.xwiki.rendering.macro.container.LayoutManager;
import org.xwiki.skinx.SkinExtension;
/**
* Layout manager implementation to layout the group blocks inside a container as columns.
*
* @version $Id$
* @since 2.5M2
*/
@Component
@Named("columns")
@Singleton
public class ColumnsLayoutManager implements LayoutManager
{
/**
* The name of the parameter to convey style information to the HTML (html style attribute).
*/
private static final String CLASS_ATTRIBUTE = "class";
/**
* The javascript file skin extension, to fetch the columns layout css.
*/
@Inject
@Named("ssfx")
private SkinExtension ssfx;
@Override
public void layoutContainer(Block container)
{
List<GroupBlock> innerGroups =
container.getBlocks(new ClassBlockMatcher(GroupBlock.class), Block.Axes.CHILD);
// FIXME Should we cry and throw an exception if ever we meet something else than a group right under
// the container macro, or automatically put it in a group maybe ?
int count = innerGroups.size();
if (innerGroups.size() == 0) {
// nothing inside, nothing to layout
return;
}
Map<String, Object> skinxParams = new HashMap<String, Object>();
skinxParams.put("forceSkinAction", true);
ssfx.use("uicomponents/container/columns.css", skinxParams);
// add styles to all columns inside
for (int i = 0; i < count; i++) {
GroupBlock column = innerGroups.get(i);
String classValue = "column";
if (i == 0) {
// we're at the first element in the list, put a marker. Don't need it to do standard columns layout,
// but maybe somebody needs it for customization...
classValue = classValue + " first-column";
}
if (i == count - 1) {
// we're at the last element in the list, put a marker
classValue = classValue + " last-column";
}
String oldClass = column.getParameter(CLASS_ATTRIBUTE);
column.setParameter(CLASS_ATTRIBUTE, (StringUtils.isEmpty(oldClass) ? classValue : oldClass + " "
+ classValue));
}
// finally, clear the floats introduced by the columns
Map<String, String> clearFloatsParams = new HashMap<String, String>();
clearFloatsParams.put(CLASS_ATTRIBUTE, "clearfloats");
String oldClass = container.getParameter(CLASS_ATTRIBUTE);
String newClass = "container-columns container-columns-" + count;
container.setParameter(CLASS_ATTRIBUTE, StringUtils.isEmpty(oldClass) ? newClass : oldClass + " " + newClass);
container.addChild(new GroupBlock(clearFloatsParams));
}
@Override
public Object getParameter(String parameterName)
{
return null;
}
@Override
public void setParameter(String parameterName, Object parameterValue)
{
}
}
|
package fr.inria.aoste.timesquare.ccslkernel.solver.extension.statemachine;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import net.javabdd.BDD;
import org.gemoc.mocc.model.moccmetamodel.Action;
import org.gemoc.mocc.model.moccmetamodel.FinishClock;
import org.gemoc.mocc.model.moccmetamodel.IntegerAssignment;
import org.gemoc.mocc.model.moccmetamodel.State;
import org.gemoc.mocc.model.moccmetamodel.StateMachineRelationDefinition;
import org.gemoc.mocc.model.moccmetamodel.Transition;
import fr.inria.aoste.timesquare.ccslkernel.model.TimeModel.BasicType.DiscreteClockType;
import fr.inria.aoste.timesquare.ccslkernel.model.TimeModel.BasicType.IntegerElement;
import fr.inria.aoste.timesquare.ccslkernel.model.TimeModel.CCSLModel.ClassicalExpression.BooleanExpression;
import fr.inria.aoste.timesquare.ccslkernel.model.TimeModel.CCSLModel.ClassicalExpression.IntEqual;
import fr.inria.aoste.timesquare.ccslkernel.model.TimeModel.CCSLModel.ClassicalExpression.IntInf;
import fr.inria.aoste.timesquare.ccslkernel.model.TimeModel.CCSLModel.ClassicalExpression.IntPlus;
import fr.inria.aoste.timesquare.ccslkernel.model.TimeModel.CCSLModel.ClassicalExpression.IntSup;
import fr.inria.aoste.timesquare.ccslkernel.model.TimeModel.CCSLModel.ClassicalExpression.IntegerExpression;
import fr.inria.aoste.timesquare.ccslkernel.model.TimeModel.CCSLModel.ClassicalExpression.IntegerRef;
import fr.inria.aoste.timesquare.ccslkernel.model.TimeModel.CCSLModel.ClassicalExpression.IntegerVariableRef;
import fr.inria.aoste.timesquare.ccslkernel.model.TimeModel.CCSLModel.ClockExpressionAndRelation.AbstractEntity;
import fr.inria.aoste.timesquare.ccslkernel.model.TimeModel.CCSLModel.ClockExpressionAndRelation.ConcreteEntity;
import fr.inria.aoste.timesquare.ccslkernel.modelunfolding.AbstractConcreteMapping;
import fr.inria.aoste.timesquare.ccslkernel.solver.CCSLKernelSolver;
import fr.inria.aoste.timesquare.ccslkernel.solver.SolverElement;
import fr.inria.aoste.timesquare.ccslkernel.solver.SolverPrimitiveElement;
import fr.inria.aoste.timesquare.ccslkernel.solver.StepExecutor;
import fr.inria.aoste.timesquare.ccslkernel.solver.TimeModel.SolverClock;
import fr.inria.aoste.timesquare.ccslkernel.solver.exception.SolverException;
import fr.inria.aoste.timesquare.ccslkernel.solver.helpers.SemanticHelper;
import fr.inria.aoste.timesquare.ccslkernel.solver.relation.AbstractWrappedRelation;
public class StateMachineRelationDefinitionSemantics extends AbstractWrappedRelation {
private State _currentState=null;
private AbstractConcreteMapping<SolverElement> _abstract2concreteMap=null;
private StateMachineRelationDefinition _modelSTS=null;
private ArrayList<Transition> _sensitiveTransitition;
private List<AbstractEntity> _parameters = null;
private List<AbstractEntity> _clockParameters = null;
private List<SolverElement> _allClocks = null;
private Map<ConcreteEntity, IntegerElement> _localInteger = null;
public StateMachineRelationDefinitionSemantics(StateMachineRelationDefinition modelSTS, AbstractConcreteMapping<SolverElement> context) {
_modelSTS = modelSTS;
_abstract2concreteMap = context;
_currentState = _modelSTS.getInitialState();
_sensitiveTransitition = new ArrayList<Transition>();
_parameters = _modelSTS.getDeclaration().getParameters();
_clockParameters = keepOnlyClocks(_parameters);
_allClocks = getConcreteElements(_clockParameters);
_localInteger = new HashMap<ConcreteEntity, IntegerElement>();
for (ConcreteEntity ce : _modelSTS.getConcreteEntities()) {
if (ce instanceof IntegerElement){
IntegerElement ie = (IntegerElement)ce;
_localInteger.put(ce, ie);
}
}
}
@Override
public void start(SemanticHelper helper) throws SolverException {
_currentState = _modelSTS.getInitialState();
_sensitiveTransitition = new ArrayList<Transition>();
}
private List<SolverElement> getConcreteElements(List<? extends AbstractEntity> abstractTriggers){
ArrayList<SolverElement> triggers = new ArrayList<SolverElement>();
for (AbstractEntity ae : abstractTriggers) {
triggers.add(_abstract2concreteMap.getLocalValue(ae));
}
return triggers;
}
private List<AbstractEntity> keepOnlyClocks(List<AbstractEntity> l){
ArrayList<AbstractEntity> res = new ArrayList<AbstractEntity>();
for (AbstractEntity ae : l) {
if (ae.getType() instanceof DiscreteClockType){
res.add(ae);
}
}
return res;
}
@Override
public void semantic(SemanticHelper semanticHelper) throws SolverException {
if (semanticHelper.isSemanticDone(this)) {
return;
}
semanticHelper.registerSemanticDone(this);
BDD stateBDD =semanticHelper.createOne();
//always possible to do nothing
for (SolverElement se : _allClocks) {
stateBDD.andWith(semanticHelper.getFalseBDDVariable((SolverClock) se));
}
for (Transition t : _currentState.getOutputTransitions()) {
if (t.getGuard() != null){
if (! evaluate(t.getGuard())){
continue;
}
}
_sensitiveTransitition.add(t);
List<SolverElement> trueTrigger = getConcreteElements((List<? extends AbstractEntity>) t.getTrigger().getTrueTriggers());
List<SolverElement> falseTrigger = getConcreteElements((List<? extends AbstractEntity>) t.getTrigger().getFalseTriggers());
List<SolverElement> clocksNotInTrigger = new ArrayList<SolverElement>(_allClocks);
clocksNotInTrigger.removeAll(trueTrigger);
BDD triggersBDD =semanticHelper.createOne();
for (SolverElement se : trueTrigger) {
triggersBDD.andWith(semanticHelper.getBDDVariable((SolverClock)se));
}
for (SolverElement se : falseTrigger) {
triggersBDD.andWith(semanticHelper.getFalseBDDVariable((SolverClock) se));
}
for (SolverElement se : clocksNotInTrigger) {
triggersBDD.andWith(semanticHelper.getFalseBDDVariable((SolverClock) se));
}
stateBDD.orWith(triggersBDD);
}
semanticHelper.semanticBDDAnd(stateBDD);
semanticHelper.registerClockUse(_allClocks.toArray(new SolverClock[0]));
}
private boolean evaluate(BooleanExpression guard) {
if(guard instanceof IntEqual){
return evaluateIntEqual((IntEqual) guard);
}
if(guard instanceof IntInf){
return evaluateIntInf((IntInf) guard);
}
if(guard instanceof IntSup){
return evaluateIntSup((IntSup) guard);
}
return false;
}
@Override
public void deathSemantic(SemanticHelper helper)
throws SolverException {
//TODO: take into account the final states... !
}
@Override
public void update(CCSLKernelSolver solver, StepExecutor stepExecutor) throws SolverException {
allTransition: for (Transition t : _sensitiveTransitition) {
//construct three set, the one of clock that must tick and the clock that must not tick
List<SolverElement> trueTrigger = getConcreteElements((List<? extends AbstractEntity>) t.getTrigger().getTrueTriggers());
List<SolverElement> falseTrigger = getConcreteElements((List<? extends AbstractEntity>) t.getTrigger().getFalseTriggers());
List<SolverElement> clocksNotInTrigger = new ArrayList<SolverElement>(_allClocks);
clocksNotInTrigger.removeAll(trueTrigger);
for (SolverElement se : trueTrigger) {
if (! stepExecutor.clockHasFired((SolverClock) se)){
continue allTransition; //it is not a fired transition
}
}
for (SolverElement se : falseTrigger) {
if (stepExecutor.clockHasFired((SolverClock) se)){
continue allTransition; //it is not a fired transition
}
}
for (SolverElement se : clocksNotInTrigger) {
if (stepExecutor.clockHasFired((SolverClock) se)){
continue allTransition; //it is not a fired transition
}
}
//here, it is the fired transition
for (Action a : t.getActions()) {
if (a instanceof FinishClock){
SolverClock toKill = (SolverClock) _abstract2concreteMap.getLocalValue((AbstractEntity) ((FinishClock) a).getClock());
stepExecutor.getNewDeadClocks().add(toKill);
toKill.setDead(true);
}
if (a instanceof IntegerAssignment){
IntegerAssignment ia = (IntegerAssignment)a;
doAssignInt(ia);
}
}
_currentState = t.getTarget();
_sensitiveTransitition.clear();
break;
}
}
//TODO: make it clean either throw a visitor, or by using the timesquare mecanism
private void doAssignInt(IntegerAssignment ia) {
IntegerExpression leftExpr = ia.getLeftValue();
IntegerExpression rightExpr = ia.getRightValue();
if (!(rightExpr instanceof IntPlus)){
throw new IllegalArgumentException("only integer plus (IntPlus) expression as supported as right value of assignment");
}
IntPlus plus = (IntPlus)rightExpr;
int iToIncrement = getInteger(plus.getLeftValue());
int incrementValue = getInteger(plus.getRightValue());
if (! (leftExpr instanceof IntegerRef)){
throw new IllegalArgumentException("left value of assignment should be integerRef (to a local integer !)");
}
IntegerElement leftElement = ((IntegerRef)leftExpr).getIntegerElem();
leftElement.setValue(iToIncrement+incrementValue);
return;
}
private boolean evaluateIntEqual(IntEqual guard){
IntegerExpression leftExpr = guard.getLeftValue();
IntegerExpression rightExpr = guard.getRightValue();
int left = getInteger(leftExpr);
int right = getInteger(rightExpr);
return left == right;
}
private boolean evaluateIntInf(IntInf guard){
IntegerExpression leftExpr = guard.getLeftValue();
IntegerExpression rightExpr = guard.getRightValue();
int left = getInteger(leftExpr);
int right = getInteger(rightExpr);
return left < right;
}
private boolean evaluateIntSup(IntSup guard){
IntegerExpression leftExpr = guard.getLeftValue();
IntegerExpression rightExpr = guard.getRightValue();
int left = getInteger(leftExpr);
int right = getInteger(rightExpr);
return left > right;
}
private int getInteger(IntegerExpression expr){
if(expr instanceof IntegerRef){
return ((IntegerRef)expr).getIntegerElem().getValue();
}else{
if(expr instanceof IntegerVariableRef){
SolverElement ce = _abstract2concreteMap.getLocalValue(((IntegerVariableRef)expr).getReferencedVar());
if (ce instanceof SolverPrimitiveElement){
try{
return ((IntegerElement)((SolverPrimitiveElement)ce).getPrimitiveElement()).getValue();
}catch(Exception e){
throw new IllegalArgumentException("warning, you should only refer to IntegerVariable: "+e.toString());
}
}
}else{
throw new IllegalArgumentException("sorry for now only IntegerElement refered from IntegerRef is supported");
}
}
return -1;
}
}
|
package dr.app.beauti.traitspanel;
import dr.app.beauti.BeautiFrame;
import dr.app.beauti.BeautiPanel;
import dr.app.beauti.ComboBoxRenderer;
import dr.app.beauti.datapanel.DataPanel;
import dr.app.beauti.options.BeautiOptions;
import dr.app.beauti.options.TraitData;
import dr.app.beauti.options.TraitGuesser;
import dr.app.beauti.util.PanelUtils;
import dr.app.gui.table.TableEditorStopper;
import dr.app.gui.table.TableSorter;
import dr.evolution.util.Taxa;
import dr.evolution.util.Taxon;
import jam.framework.Exportable;
import jam.panels.ActionPanel;
import jam.table.TableRenderer;
import javax.swing.*;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.plaf.BorderUIResource;
import javax.swing.table.AbstractTableModel;
import javax.swing.table.TableColumn;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.util.*;
/**
* @author Andrew Rambaut
* @version $Id: DataPanel.java,v 1.17 2006/09/05 13:29:34 rambaut Exp $
*/
public class TraitsPanel extends BeautiPanel implements Exportable {
private static final long serialVersionUID = 5283922195494563924L;
private static final int MINIMUM_TABLE_WIDTH = 140;
private static final String ADD_TRAITS_TOOLTIP = "<html>Define a new trait for the current taxa</html>";
private static final String IMPORT_TRAITS_TOOLTIP = "<html>Import one or more traits for these taxa from a tab-delimited<br>" +
"file. Taxa should be in the first column and the trait names<br>" +
"in the first row</html>";
private static final String GUESS_TRAIT_VALUES_TOOLTIP = "<html>This attempts to extract values for this trait that are<br>" +
"encoded in the names of the selected taxa.</html>";
private static final String SET_TRAIT_VALUES_TOOLTIP = "<html>This sets values for this trait for all<br>" +
"the selected taxa.</html>";
private static final String CLEAR_TRAIT_VALUES_TOOLTIP = "<html>This clears all the values currently assigned to taxa for<br>" +
"this trait.</html>";
private static final String CREATE_TRAIT_PARTITIONS_TOOLTIP = "<html>Create a data partition for the selected traits.</html>";
public final JTable traitsTable;
private final TraitsTableModel traitsTableModel;
private final JTable dataTable;
private final DataTableModel dataTableModel;
private final BeautiFrame frame;
private final DataPanel dataPanel;
private BeautiOptions options = null;
private TraitData currentTrait = null; // current trait
private CreateTraitDialog createTraitDialog = null;
private GuessTraitDialog guessTraitDialog = null;
private TraitValueDialog traitValueDialog = null;
AddTraitAction addTraitAction = new AddTraitAction();
CreateTraitPartitionAction createTraitPartitionAction = new CreateTraitPartitionAction();
public TraitsPanel(BeautiFrame parent, DataPanel dataPanel, Action importTraitsAction) {
this.frame = parent;
this.dataPanel = dataPanel;
traitsTableModel = new TraitsTableModel();
// TableSorter sorter = new TableSorter(traitsTableModel);
// traitsTable = new JTable(sorter);
// sorter.setTableHeader(traitsTable.getTableHeader());
traitsTable = new JTable(traitsTableModel);
traitsTable.getTableHeader().setReorderingAllowed(false);
traitsTable.getTableHeader().setResizingAllowed(false);
// traitsTable.getTableHeader().setDefaultRenderer(
// new HeaderRenderer(SwingConstants.LEFT, new Insets(0, 4, 0, 4)));
TableColumn col = traitsTable.getColumnModel().getColumn(1);
ComboBoxRenderer comboBoxRenderer = new ComboBoxRenderer(TraitData.TraitType.values());
comboBoxRenderer.putClientProperty("JComboBox.isTableCellEditor", Boolean.TRUE);
col.setCellRenderer(comboBoxRenderer);
TableEditorStopper.ensureEditingStopWhenTableLosesFocus(traitsTable);
traitsTable.getSelectionModel().setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
traitsTable.getSelectionModel().addListSelectionListener(new ListSelectionListener() {
public void valueChanged(ListSelectionEvent evt) {
traitSelectionChanged();
// dataTableModel.fireTableDataChanged();
}
});
JScrollPane scrollPane1 = new JScrollPane(traitsTable,
JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
scrollPane1.setOpaque(false);
dataTableModel = new DataTableModel();
TableSorter sorter = new TableSorter(dataTableModel);
dataTable = new JTable(sorter);
sorter.setTableHeader(dataTable.getTableHeader());
dataTable.getTableHeader().setReorderingAllowed(false);
// dataTable.getTableHeader().setDefaultRenderer(
// new HeaderRenderer(SwingConstants.LEFT, new Insets(0, 4, 0, 4)));
dataTable.getColumnModel().getColumn(0).setCellRenderer(
new TableRenderer(SwingConstants.LEFT, new Insets(0, 4, 0, 4)));
dataTable.getColumnModel().getColumn(0).setPreferredWidth(80);
col = dataTable.getColumnModel().getColumn(1);
comboBoxRenderer = new ComboBoxRenderer();
comboBoxRenderer.putClientProperty("JComboBox.isTableCellEditor", Boolean.TRUE);
col.setCellRenderer(comboBoxRenderer);
TableEditorStopper.ensureEditingStopWhenTableLosesFocus(dataTable);
// dataTable.getSelectionModel().addListSelectionListener(new ListSelectionListener() {
// public void valueChanged(ListSelectionEvent evt) {
// traitSelectionChanged();
JScrollPane scrollPane2 = new JScrollPane(dataTable,
JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
scrollPane2.setOpaque(false);
JToolBar toolBar1 = new JToolBar();
toolBar1.setFloatable(false);
toolBar1.setOpaque(false);
toolBar1.setLayout(new FlowLayout(FlowLayout.LEFT, 0, 0));
JButton button;
button = new JButton(addTraitAction);
PanelUtils.setupComponent(button);
button.setToolTipText(ADD_TRAITS_TOOLTIP);
toolBar1.add(button);
button = new JButton(importTraitsAction);
PanelUtils.setupComponent(button);
button.setToolTipText(IMPORT_TRAITS_TOOLTIP);
toolBar1.add(button);
toolBar1.add(new JToolBar.Separator(new Dimension(12, 12)));
button = new JButton(new GuessTraitsAction());
PanelUtils.setupComponent(button);
button.setToolTipText(GUESS_TRAIT_VALUES_TOOLTIP);
toolBar1.add(button);
button = new JButton(new SetValueAction());
PanelUtils.setupComponent(button);
button.setToolTipText(SET_TRAIT_VALUES_TOOLTIP);
toolBar1.add(button);
// Don't see the need for a clear values button
// button = new JButton(new ClearTraitAction());
// PanelUtils.setupComponent(button);
// button.setToolTipText(CLEAR_TRAIT_VALUES_TOOLTIP);
// toolBar1.add(button);
button = new JButton(createTraitPartitionAction);
PanelUtils.setupComponent(button);
button.setToolTipText(CREATE_TRAIT_PARTITIONS_TOOLTIP);
toolBar1.add(button);
ActionPanel actionPanel1 = new ActionPanel(false);
actionPanel1.setAddAction(addTraitAction);
actionPanel1.setRemoveAction(removeTraitAction);
// actionPanel1.getAddActionButton().setTooltipText(ADD_TRAITS_TOOLTIP);
removeTraitAction.setEnabled(false);
JPanel controlPanel1 = new JPanel(new FlowLayout(FlowLayout.LEFT));
controlPanel1.setOpaque(false);
controlPanel1.add(actionPanel1);
JPanel panel1 = new JPanel(new BorderLayout(0, 0));
panel1.setOpaque(false);
panel1.add(scrollPane1, BorderLayout.CENTER);
panel1.add(controlPanel1, BorderLayout.SOUTH);
panel1.setMinimumSize(new Dimension(MINIMUM_TABLE_WIDTH, 0));
JPanel panel2 = new JPanel(new BorderLayout(0, 0));
panel2.setOpaque(false);
panel2.add(toolBar1, BorderLayout.NORTH);
panel2.add(scrollPane2, BorderLayout.CENTER);
JSplitPane splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT,
panel1, panel2);
splitPane.setDividerLocation(MINIMUM_TABLE_WIDTH);
splitPane.setContinuousLayout(true);
splitPane.setBorder(BorderFactory.createEmptyBorder());
splitPane.setOpaque(false);
setOpaque(false);
setBorder(new BorderUIResource.EmptyBorderUIResource(new Insets(12, 12, 12, 12)));
setLayout(new BorderLayout(0, 0));
add(splitPane, BorderLayout.CENTER);
add(toolBar1, BorderLayout.NORTH);
}
public void setOptions(BeautiOptions options) {
this.options = options;
// int selRow = traitsTable.getSelectedRow();
// traitsTableModel.fireTableDataChanged();
// if (selRow < 0) {
// selRow = 0;
// traitsTable.getSelectionModel().setSelectionInterval(selRow, selRow);
// if (selectedTrait == null) {
// traitsTable.getSelectionModel().setSelectionInterval(0, 0);
traitsTableModel.fireTableDataChanged();
dataTableModel.fireTableDataChanged();
validate();
repaint();
}
public void getOptions(BeautiOptions options) {
// int selRow = traitsTable.getSelectedRow();
// if (selRow >= 0 && options.traitsOptions.selecetedTraits.size() > 0) {
// selectedTrait = options.traitsOptions.selecetedTraits.get(selRow);
// options.datesUnits = unitsCombo.getSelectedIndex();
// options.datesDirection = directionCombo.getSelectedIndex();
}
public JComponent getExportableComponent() {
return dataTable;
}
public void fireTraitsChanged() {
if (currentTrait != null) {
// if (currentTrait.getName().equalsIgnoreCase(TraitData.Traits.TRAIT_SPECIES.toString())) {
// frame.setupStarBEAST();
// } else
if (currentTrait != null && currentTrait.getTraitType() == TraitData.TraitType.DISCRETE) {
frame.updateDiscreteTraitAnalysis();
}
// if (selRow > 0) {
// traitsTable.getSelectionModel().setSelectionInterval(selRow-1, selRow-1);
// } else if (selRow == 0 && options.traitsOptions.traits.size() > 0) { // options.traitsOptions.traits.size() after remove
// traitsTable.getSelectionModel().setSelectionInterval(0, 0);
traitsTableModel.fireTableDataChanged();
options.updatePartitionAllLinks();
frame.setDirty();
}
}
private void traitSelectionChanged() {
int selRow = traitsTable.getSelectedRow();
if (selRow >= 0) {
currentTrait = options.traits.get(selRow);
// traitsTable.getSelectionModel().setSelectionInterval(selRow, selRow);
removeTraitAction.setEnabled(true);
// } else {
// currentTrait = null;
// removeTraitAction.setEnabled(false);
}
if (options.traits.size() <= 0) {
currentTrait = null;
removeTraitAction.setEnabled(false);
}
dataTableModel.fireTableDataChanged();
// traitsTableModel.fireTableDataChanged();
}
public void clearTraitValues(String traitName) {
options.clearTraitValues(traitName);
dataTableModel.fireTableDataChanged();
}
public void guessTrait() {
if (options.taxonList == null) { // validation of check empty taxonList
return;
}
if (currentTrait == null) {
if (!addTrait()) {
return; // if addTrait() cancel then false
}
}
int result;
do {
TraitGuesser currentTraitGuesser = new TraitGuesser(currentTrait);
if (guessTraitDialog == null) {
guessTraitDialog = new GuessTraitDialog(frame);
}
guessTraitDialog.setDescription("Extract values for trait '" + currentTrait + "' from taxa labels");
result = guessTraitDialog.showDialog();
if (result == -1 || result == JOptionPane.CANCEL_OPTION) {
return;
}
guessTraitDialog.setupGuesserFromDialog(currentTraitGuesser);
try {
int[] selRows = dataTable.getSelectedRows();
if (selRows.length > 0) {
Taxa selectedTaxa = new Taxa();
for (int row : selRows) {
Taxon taxon = (Taxon) dataTable.getValueAt(row, 0);
selectedTaxa.addTaxon(taxon);
}
currentTraitGuesser.guessTrait(selectedTaxa);
} else {
currentTraitGuesser.guessTrait(options.taxonList);
}
} catch (IllegalArgumentException iae) {
JOptionPane.showMessageDialog(this, iae.getMessage(), "Unable to guess trait value", JOptionPane.ERROR_MESSAGE);
result = -1;
}
dataTableModel.fireTableDataChanged();
} while (result < 0);
}
public void setTraitValue() {
if (options.taxonList == null) { // validation of check empty taxonList
return;
}
int result;
do {
if (traitValueDialog == null) {
traitValueDialog = new TraitValueDialog(frame);
}
int[] selRows = dataTable.getSelectedRows();
if (selRows.length > 0) {
traitValueDialog.setDescription("Set values for trait '" + currentTrait + "' for selected taxa");
} else {
traitValueDialog.setDescription("Set values for trait '" + currentTrait + "' for all taxa");
}
result = traitValueDialog.showDialog();
if (result == -1 || result == JOptionPane.CANCEL_OPTION) {
return;
}
// currentTrait.guessTrait = true; // ?? no use?
String value = traitValueDialog.getTraitValue();
try {
if (selRows.length > 0) {
for (int row : selRows) {
Taxon taxon = (Taxon) dataTable.getValueAt(row, 0);
taxon.setAttribute(currentTrait.getName(), value);
}
} else {
for (Taxon taxon : options.taxonList) {
taxon.setAttribute(currentTrait.getName(), value);
}
}
} catch (IllegalArgumentException iae) {
JOptionPane.showMessageDialog(this, iae.getMessage(), "Unable to guess trait value", JOptionPane.ERROR_MESSAGE);
result = -1;
}
dataTableModel.fireTableDataChanged();
} while (result < 0);
}
public boolean addTrait() {
return addTrait("Untitled");
// The 'species' trait doesn't need to be a reserved keyword since the StarBEAST button was added
// if (options.traitExists(TraitData.TRAIT_SPECIES)) {
// JOptionPane.showMessageDialog(frame, "Keyword \"species\" has been reserved for *BEAST !" +
// options.removeTrait(TraitData.TRAIT_SPECIES);
//// options.useStarBEAST = false;
// traitsTableModel.fireTableDataChanged();
// dataTableModel.fireTableDataChanged();
// return false;
// return isAdd;
}
public boolean addTrait(String traitName) {
return addTrait(null, traitName, false);
}
public boolean addTrait(String message, String traitName, boolean isSpeciesTrait) {
if (createTraitDialog == null) {
createTraitDialog = new CreateTraitDialog(frame);
}
createTraitDialog.setSpeciesTrait(isSpeciesTrait);
createTraitDialog.setTraitName(traitName);
createTraitDialog.setMessage(message);
int result = createTraitDialog.showDialog();
if (result == JOptionPane.OK_OPTION) {
frame.tabbedPane.setSelectedComponent(this);
String name = createTraitDialog.getName();
TraitData.TraitType type = createTraitDialog.getType();
TraitData newTrait = new TraitData(options, name, "", type);
currentTrait = newTrait;
// The createTraitDialog will have already checked if the
// user is overwriting an existing trait
addTrait(newTrait);
if (createTraitDialog.createTraitPartition()) {
options.createPartitionForTraits(name, newTrait);
}
fireTraitsChanged();
// traitsTableModel.fireTableDataChanged();
// dataTableModel.fireTableDataChanged();
// traitSelectionChanged();
// AR we don't want to guess traits automatically - the user may
// be planning on typing them in. Also this method may have been
// called by guessTraits() anyway.
// guessTrait();
} else if (result == CreateTraitDialog.OK_IMPORT) {
return frame.doImportTraits();
} else if (result == JOptionPane.CANCEL_OPTION) {
return false;
}
return true;
}
public void addTrait(TraitData newTrait) {
int selRow = options.addTrait(newTrait);
traitsTable.getSelectionModel().setSelectionInterval(selRow, selRow);
}
private void removeTrait() {
int selRow = traitsTable.getSelectedRow();
removeTrait(traitsTable.getValueAt(selRow, 0).toString());
}
public void removeTrait(String traitName) {
if (options.useStarBEAST && traitName.equalsIgnoreCase(TraitData.TRAIT_SPECIES)) {
JOptionPane.showMessageDialog(this, "The trait named '" + traitName + "' is being used by *BEAST.\nTurn *BEAST off before deleting this trait.", "Trait in use", JOptionPane.ERROR_MESSAGE);
return;
}
TraitData traitData = options.getTrait(traitName);
if (options.getAllPartitionData(traitData).size() > 0) {
JOptionPane.showMessageDialog(this, "The trait named '" + traitName + "' is being used in a partition.\nRemove the partition before deleting this trait.", "Trait in use", JOptionPane.ERROR_MESSAGE);
return;
}
options.removeTrait(traitName);
fireTraitsChanged();
traitSelectionChanged();
}
public class ClearTraitAction extends AbstractAction {
private static final long serialVersionUID = -7281309694753868635L;
public ClearTraitAction() {
super("Clear trait values");
setToolTipText("Use this tool to remove trait values from each taxon");
}
public void actionPerformed(ActionEvent ae) {
if (currentTrait != null) clearTraitValues(currentTrait.getName()); // Clear trait values
}
}
public class GuessTraitsAction extends AbstractAction {
private static final long serialVersionUID = 8514706149822252033L;
public GuessTraitsAction() {
super("Guess trait values");
setToolTipText("Use this tool to guess the trait values from the taxon labels");
}
public void actionPerformed(ActionEvent ae) {
guessTrait();
}
}
public class AddTraitAction extends AbstractAction {
public AddTraitAction() {
super("Add trait");
setToolTipText("Use this button to add a new trait");
}
public void actionPerformed(ActionEvent ae) {
addTrait();
}
}
AbstractAction removeTraitAction = new AbstractAction() {
public void actionPerformed(ActionEvent ae) {
removeTrait();
}
};
public class SetValueAction extends AbstractAction {
public SetValueAction() {
super("Set trait values");
setToolTipText("Use this button to set the trait values of selected taxa");
}
public void actionPerformed(ActionEvent ae) {
setTraitValue();
}
}
class TraitsTableModel extends AbstractTableModel {
private static final long serialVersionUID = -6707994233020715574L;
String[] columnNames = {"Trait", "Type"};
public TraitsTableModel() {
}
public int getColumnCount() {
return columnNames.length;
}
public int getRowCount() {
if (options == null) return 0;
return options.traits.size();
}
public Object getValueAt(int row, int col) {
switch (col) {
case 0:
return options.traits.get(row).getName();
case 1:
return options.traits.get(row).getTraitType();
}
return null;
}
public void setValueAt(Object aValue, int row, int col) {
switch (col) {
case 0:
String oldName = options.traits.get(row).getName();
options.traits.get(row).setName(aValue.toString());
Object value;
for (Taxon t : options.taxonList) {
value = t.getAttribute(oldName);
t.setAttribute(aValue.toString(), value);
// cannot remvoe attribute in Attributable inteface
}
fireTraitsChanged();
break;
case 1:
options.traits.get(row).setTraitType((TraitData.TraitType) aValue);
break;
}
}
public boolean isCellEditable(int row, int col) {
// return !(options.getTraitsList().get(row).getName().equalsIgnoreCase(TraitData.Traits.TRAIT_SPECIES.toString())
// || options.getTraitsList().get(row).getName().equalsIgnoreCase(TraitData.Traits.TRAIT_LOCATIONS.toString()));
// return col == 0;
return true;
}
public String getColumnName(int column) {
return columnNames[column];
}
public Class getColumnClass(int c) {
return getValueAt(0, c).getClass();
}
public String toString() {
StringBuffer buffer = new StringBuffer();
buffer.append(getColumnName(0));
for (int j = 1; j < getColumnCount(); j++) {
buffer.append("\t");
buffer.append(getColumnName(j));
}
buffer.append("\n");
for (int i = 0; i < getRowCount(); i++) {
buffer.append(getValueAt(i, 0));
for (int j = 1; j < getColumnCount(); j++) {
buffer.append("\t");
buffer.append(getValueAt(i, j));
}
buffer.append("\n");
}
return buffer.toString();
}
}
class DataTableModel extends AbstractTableModel {
private static final long serialVersionUID = -6707994233020715574L;
String[] columnNames = {"Taxon", "Value"};
public DataTableModel() {
}
public int getColumnCount() {
return columnNames.length;
}
public int getRowCount() {
if (options == null) return 0;
if (options.taxonList == null) return 0;
if (currentTrait == null) return 0;
return options.taxonList.getTaxonCount();
}
public Object getValueAt(int row, int col) {
switch (col) {
case 0:
return options.taxonList.getTaxon(row);
case 1:
Object value = null;
if (currentTrait != null) {
value = options.taxonList.getTaxon(row).getAttribute(currentTrait.getName());
}
if (value != null) {
return value;
} else {
return "";
}
}
return null;
}
public void setValueAt(Object aValue, int row, int col) {
if (col == 1) {
// Location location = options.taxonList.getTaxon(row).getLocation();
// if (location != null) {
// options.taxonList.getTaxon(row).setLocation(location);
if (currentTrait != null) {
options.taxonList.getTaxon(row).setAttribute(currentTrait.getName(), aValue);
}
}
}
public boolean isCellEditable(int row, int col) {
if (col == 1) {
// Object t = options.taxonList.getTaxon(row).getAttribute(currentTrait.getName());
// return (t != null);
return true;
} else {
return false;
}
}
public String getColumnName(int column) {
return columnNames[column];
}
public Class getColumnClass(int c) {
return getValueAt(0, c).getClass();
}
public String toString() {
StringBuffer buffer = new StringBuffer();
buffer.append(getColumnName(0));
for (int j = 1; j < getColumnCount(); j++) {
buffer.append("\t");
buffer.append(getColumnName(j));
}
buffer.append("\n");
for (int i = 0; i < getRowCount(); i++) {
buffer.append(getValueAt(i, 0));
for (int j = 1; j < getColumnCount(); j++) {
buffer.append("\t");
buffer.append(getValueAt(i, j));
}
buffer.append("\n");
}
return buffer.toString();
}
}
public class CreateTraitPartitionAction extends AbstractAction {
public CreateTraitPartitionAction() {
super("Create partition from trait ...");
setToolTipText("Create a data partition from a trait. Traits can be defined in the Traits panel.");
}
public void actionPerformed(ActionEvent ae) {
int[] selRows = traitsTable.getSelectedRows();
java.util.List<TraitData> traits = new ArrayList<TraitData>();
for (int row : selRows) {
TraitData trait = options.traits.get(row);
traits.add(trait);
}
dataPanel.createFromTraits(traits);
}
}
}
|
package dr.app.beauti.traitspanel;
import dr.app.beauti.BeautiFrame;
import dr.app.beauti.BeautiPanel;
import dr.app.beauti.ComboBoxRenderer;
import dr.app.beauti.options.BeautiOptions;
import dr.app.beauti.options.TraitData;
import dr.app.beauti.options.TraitGuesser;
import dr.app.beauti.util.PanelUtils;
import dr.gui.table.TableSorter;
import org.virion.jam.framework.Exportable;
import org.virion.jam.panels.ActionPanel;
import org.virion.jam.table.HeaderRenderer;
import org.virion.jam.table.TableEditorStopper;
import org.virion.jam.table.TableRenderer;
import javax.swing.*;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.plaf.BorderUIResource;
import javax.swing.table.AbstractTableModel;
import javax.swing.table.TableColumn;
import java.awt.*;
import java.awt.event.ActionEvent;
/**
* @author Andrew Rambaut
* @version $Id: DataPanel.java,v 1.17 2006/09/05 13:29:34 rambaut Exp $
*/
public class TraitsPanel extends BeautiPanel implements Exportable {
private static final long serialVersionUID = 5283922195494563924L;
private static final int MINIMUM_TABLE_WIDTH = 140;
private static final String ADD_TRAITS_TOOLTIP = "<html>Define a new trait for the current taxa</html>";
private static final String IMPORT_TRAITS_TOOLTIP = "<html>Import one or more traits for these taxa from a tab-delimited<br>" +
"file. Taxa should be in the first column and the trait names<br>" +
"in the first row</html>";
private static final String GUESS_TRAIT_VALUES_TOOLTIP = "<html>This attempts to extract values for this trait that are<br>" +
"encoded in the names of the taxa.</html>";
private static final String CLEAR_TRAIT_VALUES_TOOLTIP = "<html>This clears all the values currently assigned to taxa for<br>" +
"this trait.</html>";
public final JTable traitsTable;
private final TraitsTableModel traitsTableModel;
private final JTable dataTable;
private final DataTableModel dataTableModel;
private final BeautiFrame frame;
private BeautiOptions options = null;
private TraitData currentTrait = null; // current trait
private CreateTraitDialog createTraitDialog = null;
// private GuessTraitDialog guessTraitDialog = null;
AddTraitAction addTraitAction = new AddTraitAction();
public TraitsPanel(BeautiFrame parent, Action importTraitsAction) {
this.frame = parent;
traitsTableModel = new TraitsTableModel();
// TableSorter sorter = new TableSorter(traitsTableModel);
// traitsTable = new JTable(sorter);
// sorter.setTableHeader(traitsTable.getTableHeader());
traitsTable = new JTable(traitsTableModel);
traitsTable.getTableHeader().setReorderingAllowed(false);
traitsTable.getTableHeader().setResizingAllowed(false);
traitsTable.getTableHeader().setDefaultRenderer(
new HeaderRenderer(SwingConstants.LEFT, new Insets(0, 4, 0, 4)));
TableColumn col = traitsTable.getColumnModel().getColumn(1);
ComboBoxRenderer comboBoxRenderer = new ComboBoxRenderer(TraitData.TraitType.values());
comboBoxRenderer.putClientProperty("JComboBox.isTableCellEditor", Boolean.TRUE);
col.setCellRenderer(comboBoxRenderer);
TableEditorStopper.ensureEditingStopWhenTableLosesFocus(traitsTable);
traitsTable.getSelectionModel().setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
traitsTable.getSelectionModel().addListSelectionListener(new ListSelectionListener() {
public void valueChanged(ListSelectionEvent evt) {
traitSelectionChanged();
// dataTableModel.fireTableDataChanged();
}
});
JScrollPane scrollPane1 = new JScrollPane(traitsTable,
JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
scrollPane1.setOpaque(false);
dataTableModel = new DataTableModel();
TableSorter sorter = new TableSorter(dataTableModel);
dataTable = new JTable(sorter);
sorter.setTableHeader(dataTable.getTableHeader());
dataTable.getTableHeader().setReorderingAllowed(false);
dataTable.getTableHeader().setDefaultRenderer(
new HeaderRenderer(SwingConstants.LEFT, new Insets(0, 4, 0, 4)));
dataTable.getColumnModel().getColumn(0).setCellRenderer(
new TableRenderer(SwingConstants.LEFT, new Insets(0, 4, 0, 4)));
dataTable.getColumnModel().getColumn(0).setPreferredWidth(80);
col = dataTable.getColumnModel().getColumn(1);
comboBoxRenderer = new ComboBoxRenderer();
comboBoxRenderer.putClientProperty("JComboBox.isTableCellEditor", Boolean.TRUE);
col.setCellRenderer(comboBoxRenderer);
TableEditorStopper.ensureEditingStopWhenTableLosesFocus(dataTable);
dataTable.getSelectionModel().addListSelectionListener(new ListSelectionListener() {
public void valueChanged(ListSelectionEvent evt) {
// traitSelectionChanged();
}
});
JScrollPane scrollPane2 = new JScrollPane(dataTable,
JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
scrollPane2.setOpaque(false);
JToolBar toolBar1 = new JToolBar();
toolBar1.setFloatable(false);
toolBar1.setOpaque(false);
toolBar1.setLayout(new FlowLayout(FlowLayout.LEFT, 0, 0));
JButton button;
// removed this button as there is already a "+" button at the bottom of the table.
// button = new JButton(addTraitAction);
// PanelUtils.setupComponent(button);
// button.setToolTipText(ADD_TRAITS_TOOLTIP);
// toolBar1.add(button);
button = new JButton(importTraitsAction);
PanelUtils.setupComponent(button);
button.setToolTipText(IMPORT_TRAITS_TOOLTIP);
toolBar1.add(button);
toolBar1.add(new JToolBar.Separator(new Dimension(12, 12)));
button = new JButton(new GuessTraitsAction());
PanelUtils.setupComponent(button);
button.setToolTipText(GUESS_TRAIT_VALUES_TOOLTIP);
toolBar1.add(button);
button = new JButton(new ClearTraitAction());
PanelUtils.setupComponent(button);
button.setToolTipText(CLEAR_TRAIT_VALUES_TOOLTIP);
toolBar1.add(button);
ActionPanel actionPanel1 = new ActionPanel(false);
actionPanel1.setAddAction(addTraitAction);
actionPanel1.setRemoveAction(removeTraitAction);
// actionPanel1.getAddActionButton().setTooltipText(ADD_TRAITS_TOOLTIP);
removeTraitAction.setEnabled(false);
JPanel controlPanel1 = new JPanel(new FlowLayout(FlowLayout.LEFT));
controlPanel1.setOpaque(false);
controlPanel1.add(actionPanel1);
JPanel panel1 = new JPanel(new BorderLayout(0, 0));
panel1.setOpaque(false);
panel1.add(scrollPane1, BorderLayout.CENTER);
panel1.add(controlPanel1, BorderLayout.SOUTH);
panel1.setMinimumSize(new Dimension(MINIMUM_TABLE_WIDTH, 0));
JPanel panel2 = new JPanel(new BorderLayout(0, 0));
panel2.setOpaque(false);
panel2.add(toolBar1, BorderLayout.NORTH);
panel2.add(scrollPane2, BorderLayout.CENTER);
JSplitPane splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT,
panel1, panel2);
splitPane.setDividerLocation(MINIMUM_TABLE_WIDTH);
splitPane.setContinuousLayout(true);
splitPane.setBorder(BorderFactory.createEmptyBorder());
splitPane.setOpaque(false);
setOpaque(false);
setBorder(new BorderUIResource.EmptyBorderUIResource(new Insets(12, 12, 12, 12)));
setLayout(new BorderLayout(0, 0));
add(splitPane, BorderLayout.CENTER);
add(toolBar1, BorderLayout.NORTH);
}
public void setOptions(BeautiOptions options) {
this.options = options;
// int selRow = traitsTable.getSelectedRow();
// traitsTableModel.fireTableDataChanged();
// if (selRow < 0) {
// selRow = 0;
// traitsTable.getSelectionModel().setSelectionInterval(selRow, selRow);
// if (selectedTrait == null) {
// traitsTable.getSelectionModel().setSelectionInterval(0, 0);
traitsTableModel.fireTableDataChanged();
dataTableModel.fireTableDataChanged();
validate();
repaint();
}
public void getOptions(BeautiOptions options) {
// int selRow = traitsTable.getSelectedRow();
// if (selRow >= 0 && options.traitsOptions.selecetedTraits.size() > 0) {
// selectedTrait = options.traitsOptions.selecetedTraits.get(selRow);
// options.datesUnits = unitsCombo.getSelectedIndex();
// options.datesDirection = directionCombo.getSelectedIndex();
}
public JComponent getExportableComponent() {
return dataTable;
}
public void fireTraitsChanged() {
if (currentTrait != null) {
if (currentTrait.getName().equalsIgnoreCase(TraitData.Traits.TRAIT_SPECIES.toString())) {
frame.setupSpeciesAnalysis();
} else if (currentTrait.getTraitType() == TraitData.TraitType.DISCRETE) {
frame.updateDiscreteTraitAnalysis();
}
}
traitsTableModel.fireTableDataChanged();
options.updatePartitionAllLinks();
frame.setDirty();
}
private void traitSelectionChanged() {
int selRow = traitsTable.getSelectedRow();
if (selRow >= 0) {
currentTrait = options.getTraitsList().get(selRow);
traitsTable.getSelectionModel().setSelectionInterval(selRow, selRow);
removeTraitAction.setEnabled(true);
// } else {
// currentTrait = null;
// removeTraitAction.setEnabled(false);
}
if (options.getTraitsList().size() <= 0) {
currentTrait = null;
removeTraitAction.setEnabled(false);
}
dataTableModel.fireTableDataChanged();
// traitsTableModel.fireTableDataChanged();
}
public void clearTraitValues(String traitName) {
options.clearTraitValues(traitName);
dataTableModel.fireTableDataChanged();
}
public void guessTrait() {
if (options.taxonList != null) { // validation of check empty taxonList
// TraitGuesser guesser = options.traitsOptions.cureentTraitGuesser;
if (currentTrait == null) addTrait();
// if (guessTraitDialog == null) {
// guessTraitDialog = new GuessTraitDialog(frame, currentTrait);
TraitGuesser currentTraitGuesser = new TraitGuesser(currentTrait);
GuessTraitDialog guessTraitDialog = new GuessTraitDialog(frame, currentTraitGuesser);
int result = guessTraitDialog.showDialog();
if (result == -1 || result == JOptionPane.CANCEL_OPTION) {
return;
}
// currentTrait.guessTrait = true; // ?? no use?
guessTraitDialog.setupGuesser();
try {
currentTraitGuesser.guessTrait(options);
} catch (IllegalArgumentException iae) {
JOptionPane.showMessageDialog(this, iae.getMessage(), "Unable to guess trait value", JOptionPane.ERROR_MESSAGE);
}
dataTableModel.fireTableDataChanged();
} else {
JOptionPane.showMessageDialog(this, "No taxa loaded yet, please import Alignment file!",
"No taxa loaded", JOptionPane.ERROR_MESSAGE);
}
}
private void addTrait() {
if (createTraitDialog == null) {
createTraitDialog = new CreateTraitDialog(frame);
}
int result = createTraitDialog.showDialog();
if (result != JOptionPane.CANCEL_OPTION) {
String name = createTraitDialog.getName();
TraitData.TraitType type = createTraitDialog.getType();
TraitData newTrait = new TraitData(options, name, "", type);
currentTrait = newTrait;
// The createTraitDialog will have already checked if the
// user is overwriting an existing trait
addTrait(newTrait);
fireTraitsChanged();
// traitsTableModel.fireTableDataChanged();
// dataTableModel.fireTableDataChanged();
// traitSelectionChanged();
}
}
public void addTrait(TraitData newTrait) {
int selRow = options.addTrait(newTrait);
traitsTable.getSelectionModel().setSelectionInterval(selRow, selRow);
}
public void removeTrait() {
int selRow = traitsTable.getSelectedRow();
options.removeTrait(traitsTable.getValueAt(selRow, 0).toString());
if (currentTrait != null) {
clearTraitValues(currentTrait.getName()); // Clear trait values
if (currentTrait.getName().equalsIgnoreCase(TraitData.Traits.TRAIT_SPECIES.toString())) {
frame.removeSepciesAnalysis();
} else if (currentTrait.getTraitType() == TraitData.TraitType.DISCRETE) {
frame.updateDiscreteTraitAnalysis();
}
// if (selRow > 0) {
// traitsTable.getSelectionModel().setSelectionInterval(selRow-1, selRow-1);
// } else if (selRow == 0 && options.traitsOptions.traits.size() > 0) { // options.traitsOptions.traits.size() after remove
// traitsTable.getSelectionModel().setSelectionInterval(0, 0);
}
fireTraitsChanged();
traitSelectionChanged();
}
public class ClearTraitAction extends AbstractAction {
private static final long serialVersionUID = -7281309694753868635L;
public ClearTraitAction() {
super("Clear trait values");
setToolTipText("Use this tool to remove trait values from each taxon");
}
public void actionPerformed(ActionEvent ae) {
if (currentTrait != null) clearTraitValues(currentTrait.getName()); // Clear trait values
}
}
public class GuessTraitsAction extends AbstractAction {
private static final long serialVersionUID = 8514706149822252033L;
public GuessTraitsAction() {
super("Guess trait values");
setToolTipText("Use this tool to guess the trait values from the taxon labels");
}
public void actionPerformed(ActionEvent ae) {
guessTrait();
}
}
public class AddTraitAction extends AbstractAction {
public AddTraitAction() {
super("Add trait");
setToolTipText("Use this button to add a new trait");
}
public void actionPerformed(ActionEvent ae) {
addTrait();
}
}
AbstractAction removeTraitAction = new AbstractAction() {
public void actionPerformed(ActionEvent ae) {
removeTrait();
}
};
class TraitsTableModel extends AbstractTableModel {
private static final long serialVersionUID = -6707994233020715574L;
String[] columnNames = {"Trait", "Type"};
public TraitsTableModel() {
}
public int getColumnCount() {
return columnNames.length;
}
public int getRowCount() {
if (options == null) return 0;
if (options.getTraitsList() == null) return 0;
return options.getTraitsList().size();
}
public Object getValueAt(int row, int col) {
switch (col) {
case 0:
return options.getTraitsList().get(row).getName();
case 1:
return options.getTraitsList().get(row).getTraitType();
}
return null;
}
public void setValueAt(Object aValue, int row, int col) {
switch (col) {
case 0:
options.getTraitsList().get(row).setName(aValue.toString());
fireTraitsChanged();
break;
case 1:
options.getTraitsList().get(row).setTraitType((TraitData.TraitType) aValue);
break;
}
}
public boolean isCellEditable(int row, int col) {
// return !getValueAt(row, 0).equals(TraitGuesser.Traits.TRAIT_SPECIES);
return !(options.getTraitsList().get(row).getName().equalsIgnoreCase(TraitData.Traits.TRAIT_SPECIES.toString())
|| options.getTraitsList().get(row).getName().equalsIgnoreCase(TraitData.Traits.TRAIT_LOCATIONS.toString()));
}
public String getColumnName(int column) {
return columnNames[column];
}
public Class getColumnClass(int c) {
return getValueAt(0, c).getClass();
}
public String toString() {
StringBuffer buffer = new StringBuffer();
buffer.append(getColumnName(0));
for (int j = 1; j < getColumnCount(); j++) {
buffer.append("\t");
buffer.append(getColumnName(j));
}
buffer.append("\n");
for (int i = 0; i < getRowCount(); i++) {
buffer.append(getValueAt(i, 0));
for (int j = 1; j < getColumnCount(); j++) {
buffer.append("\t");
buffer.append(getValueAt(i, j));
}
buffer.append("\n");
}
return buffer.toString();
}
}
class DataTableModel extends AbstractTableModel {
private static final long serialVersionUID = -6707994233020715574L;
String[] columnNames = {"Taxon", "Value"};
public DataTableModel() {
}
public int getColumnCount() {
return columnNames.length;
}
public int getRowCount() {
if (options == null) return 0;
if (options.taxonList == null) return 0;
return options.taxonList.getTaxonCount();
}
public Object getValueAt(int row, int col) {
switch (col) {
case 0:
return options.taxonList.getTaxonId(row);
case 1:
Object value = null;
if (currentTrait != null) {
value = options.taxonList.getTaxon(row).getAttribute(currentTrait.getName());
}
if (value != null) {
return value;
} else {
return "-";
}
}
return null;
}
public void setValueAt(Object aValue, int row, int col) {
if (col == 1) {
// Location location = options.taxonList.getTaxon(row).getLocation();
// if (location != null) {
// options.taxonList.getTaxon(row).setLocation(location);
if (currentTrait != null) {
options.taxonList.getTaxon(row).setAttribute(currentTrait.getName(), aValue);
}
}
}
public boolean isCellEditable(int row, int col) {
if (col == 1) {
Object t = options.taxonList.getTaxon(row).getAttribute(currentTrait.getName());
return (t != null);
} else {
return false;
}
}
public String getColumnName(int column) {
return columnNames[column];
}
public Class getColumnClass(int c) {
return getValueAt(0, c).getClass();
}
public String toString() {
StringBuffer buffer = new StringBuffer();
buffer.append(getColumnName(0));
for (int j = 1; j < getColumnCount(); j++) {
buffer.append("\t");
buffer.append(getColumnName(j));
}
buffer.append("\n");
for (int i = 0; i < getRowCount(); i++) {
buffer.append(getValueAt(i, 0));
for (int j = 1; j < getColumnCount(); j++) {
buffer.append("\t");
buffer.append(getValueAt(i, j));
}
buffer.append("\n");
}
return buffer.toString();
}
}
}
|
package dr.evolution.coalescent;
/**
* This class models exponential growth from an initial population size which
* then transitions back to a constant population size.
*
* @author Andrew Rambaut
* @author Alexei Drummond
*
* @version $ID$
*
*/
public class ConstExpConst extends ConstExponential {
/**
* Construct demographic model with default settings
*/
public ConstExpConst(Type units) {
super(units);
}
public double getTime1() {
return time1;
}
public void setTime1(double time1) {
this.time1 = time1;
}
public double getTime2() {
return time1 + (-Math.log(getN1()/getN0())/getGrowthRate());
}
public void setProportion(double p) {
this.setN1(getN0() * p);
}
// Implementation of abstract methods
public double getDemographic(double t) {
double N0 = getN0();
double N1 = getN1();
double r = getGrowthRate();
double t1 = getTime1();
if (t < t1) {
return N0;
}
double t2 = getTime2();
if (t >= t2) {
return N1;
}
return N0 * Math.exp(-r*(t - t1));
}
/**
* Returns value of demographic intensity function at time t
* (= integral 1/N(x) dx from 0 to t).
*/
public double getIntensity(double t) {
double time1 = getTime1();
double time2 = getTime2();
double oneOverN0 = 1.0 / getN0();
if (t < time1) {
return (t * oneOverN0);
}
double oneOverNt = 1.0 / getDemographic(t);
if (t > time1 && t < time2) {
return (t * oneOverN0) + ( 0.5 * (t-time1) * (oneOverNt-oneOverN0) );
}
double oneOverN1 = 1.0 / getN1();
if (t >= time2) {
return (t * oneOverN0) + ( 0.5 * (time2-time1) * (oneOverN1-oneOverN0) ) + (oneOverN1 * (t-time2));
}
throw new RuntimeException("Not implemented!");
}
public double getInverseIntensity(double x) {
throw new RuntimeException("Not implemented!");
}
public int getNumArguments() {
return 4;
}
public String getArgumentName(int n) {
switch (n) {
case 0: return "N0";
case 1: return "r";
case 2: return "N1";
case 3: return "time1";
}
throw new IllegalArgumentException("Argument " + n + " does not exist");
}
public double getArgument(int n) {
switch (n) {
case 0: return getN0();
case 1: return getGrowthRate();
case 2: return getN1();
case 3: return getTime1();
}
throw new IllegalArgumentException("Argument " + n + " does not exist");
}
public void setArgument(int n, double value) {
switch (n) {
case 0: setN0(value); break;
case 1: setGrowthRate(value); break;
case 2: setN1(value); break;
case 3: setTime1(value); break;
default: throw new IllegalArgumentException("Argument " + n + " does not exist");
}
}
public double getLowerBound(int n) {
return 0.0;
}
public double getUpperBound(int n) {
return Double.POSITIVE_INFINITY;
}
// private stuff
private double time1 = 0.0;
}
|
package dr.inference.markovjumps;
import dr.evolution.datatype.Codons;
import dr.evolution.datatype.DataType;
import dr.math.MathUtils;
import java.util.ArrayList;
import java.util.List;
/**
* A class to represent the complete state history of a continuous-time Markov chain in the
* interval [0,T].
* <p/>
* This work is supported by NSF grant 0856099
*
* @author Marc A. Suchard
*/
public class StateHistory {
// private StateHistory(int startingState, int stateCount) {
// this(0.0, startingState, stateCount);
public StateHistory(double startingTime, int startingState, int stateCount) {
stateList = new ArrayList<StateChange>();
stateList.add(new StateChange(startingTime, startingState));
this.stateCount = stateCount;
finalized = false;
}
public void addChange(StateChange stateChange) {
checkFinalized(false);
stateList.add(stateChange);
}
public void addEndingState(StateChange stateChange) {
checkFinalized(false);
stateList.add(stateChange);
finalized = true;
}
public int[] getJumpCounts() {
int[] counts = new int[stateCount * stateCount];
accumulateSufficientStatistics(counts, null);
return counts;
}
public double[] getWaitingTimes() {
double[] times = new double[stateCount];
accumulateSufficientStatistics(null, times);
return times;
}
public double getTotalRegisteredCounts(double[] register) {
int[] counts = getJumpCounts();
// double total = 0;
// for (int i = 0; i < counts.length; i++) {
// total += counts[i] * register[i];
// return total;
return dotProduct(counts, register);
}
private double dotProduct(int[] a, double[] b) {
double total = 0;
final int length = a.length;
for (int i = 0; i < length; i++) {
total += a[i] * b[i];
}
return total;
}
public double getTotalReward(double[] register) {
double[] times = getWaitingTimes();
double total = 0;
for (int i = 0; i < times.length; i++) {
total += times[i] * register[i]; // stateCount length vector
}
return total;
}
public void accumulateSufficientStatistics(int[] counts, double[] times) {
checkFinalized(true);
int nJumps = getNumberOfJumps();
StateChange initialState = stateList.get(0);
int currentState = initialState.getState();
double currentTime = initialState.getTime();
for (int i = 1; i <= nJumps; i++) {
StateChange nextStateChange = stateList.get(i);
int nextState = nextStateChange.getState();
double nextTime = nextStateChange.getTime();
if (counts != null) {
counts[currentState * stateCount + nextState]++;
}
if (times != null) {
times[currentState] += (nextTime - currentTime);
}
currentState = nextState;
currentTime = nextTime;
}
if (times != null) { // Add last waiting time
StateChange finalState = stateList.get(nJumps + 1);
times[currentState] += (finalState.getTime() - currentTime);
}
}
public int getNumberOfJumps() {
checkFinalized(true);
return stateList.size() - 2; // Discount starting and ending states
}
private void checkFinalized(boolean isTrue) {
if (isTrue != finalized) {
throw new IllegalAccessError("StateHistory " + (finalized ? "is" : "is not" + " finalized"));
}
}
public int getStartingState() {
return stateList.get(0).getState();
}
public int getEndingState() {
checkFinalized(true);
return stateList.get(stateList.size() - 1).getState();
}
public double getStartingTime() {
return stateList.get(0).getTime();
}
public double getEndingTime() {
checkFinalized(true);
return stateList.get(stateList.size() - 1).getTime();
}
public void rescaleTimesOfEvents(double inStartTime, double inEndTime) {
final double scale = (inEndTime - inStartTime) / (getEndingTime() - getStartingTime());
StateChange currentStateChange = stateList.get(0);
double oldCurrentTime = currentStateChange.getTime();
currentStateChange.setTime(inStartTime);
double newCurrentTime = inStartTime;
for (int i = 1; i < stateList.size(); ++i) {
StateChange nextStateChange = stateList.get(i);
double oldNextTime = nextStateChange.getTime();
double oldTimeDiff = oldNextTime - oldCurrentTime;
double newNextTime = oldTimeDiff * scale + newCurrentTime;
nextStateChange.setTime(newNextTime);
oldCurrentTime = oldNextTime;
newCurrentTime = newNextTime;
}
}
public String toString() {
StringBuilder sb = new StringBuilder("[");
for (int i = 0; i < stateList.size(); i++) {
if (i > 0) {
sb.append(",");
}
sb.append(stateList.get(i));
}
sb.append("]");
return sb.toString();
}
public static void main(String[] args) {
System.err.println("Testing time rescaling:");
StateHistory stateHistory = new StateHistory(1, 1, 4);
StateChange stateChange;
stateChange = new StateChange(2, 2);
stateHistory.addChange(stateChange);
stateChange = new StateChange(5, 2);
stateHistory.addEndingState(stateChange);
System.err.println("Initial history: " + stateHistory);
stateHistory.rescaleTimesOfEvents(8.0, 0.0);
System.err.println("Rescale history: " + stateHistory);
stateHistory.rescaleTimesOfEvents(0.0, 4.0);
System.err.println("Rescale history: " + stateHistory);
}
public StateHistory filterChanges(double[] register) {
if (getNumberOfJumps() == 0) {
return this;
}
StateChange currentState = stateList.get(0);
StateHistory newHistory = new StateHistory(currentState.getTime(), currentState.getState(), stateCount);
for (int i = 1; i < stateList.size() - 1; ++i) {
StateChange nextState = stateList.get(i);
if (register[currentState.getState() * stateCount + nextState.getState()] == 1) {
nextState = nextState.clone();
nextState.setPreviousState(currentState.getState());
newHistory.addChange(nextState);
}
currentState = nextState;
}
newHistory.addEndingState(stateList.get(stateList.size() - 1));
// This function can produce inconsistent histories when not all changes are reported.
isFiltered = true;
return newHistory;
}
public double getLogLikelihood(final double[] infinitesimalRates, final int stateCount) {
checkFinalized(true);
// TODO This function needs testing
double logLikelihood = 0.0;
final int totalChanges = getNumberOfJumps();
int currentState = stateList.get(0).getState();
double currentTime = stateList.get(0).getTime();
for (int i = 1; i < totalChanges; ++i) {
int nextState = stateList.get(i).getState();
double nextTime = stateList.get(i).getTime();
// Exponential pdf and destination choice
logLikelihood += Math.log(infinitesimalRates[currentState * stateCount + nextState])
+ infinitesimalRates[currentState * stateCount + currentState] * (nextTime - currentTime);
// terms involving Math.log(\lambda_{ii}) cancel
currentState = nextState;
currentTime = nextTime;
}
final int lastState = stateList.get(stateList.size() - 1).getState();
final double lastTime = stateList.get(stateList.size() - 1).getTime();
assert (lastState == currentState);
assert (lastTime >= currentTime);
// No event in last interval
logLikelihood += infinitesimalRates[currentState * stateCount + currentState] * (lastTime - currentTime);
return logLikelihood;
}
public String toStringChanges(int site, DataType dataType) {
return toStringChanges(site, dataType, true);
}
public String toStringChanges(int site, DataType dataType, boolean wrap) {
StringBuilder sb = wrap ? new StringBuilder("{") : new StringBuilder();
// site number gets put into each and every event string
// sb.append(site).append(",");
int currentState = stateList.get(0).getState();
boolean firstChange = true;
for (int i = 1; i < stateList.size() - 1; i++) { // TODO Code review: should this really be size() - 1?
int nextState = stateList.get(i).getState();
if (isFiltered) {
currentState = stateList.get(i).getPreviousState();
}
if (nextState != currentState) {
if (!firstChange) {
sb.append(",");
}
double time = stateList.get(i).getTime(); // + startTime;
if (dataType instanceof Codons) {
addEventToStringBuilder(sb, dataType.getTriplet(currentState), dataType.getTriplet(nextState), time, site);
} else {
addEventToStringBuilder(sb, dataType.getCode(currentState), dataType.getCode(nextState), time, site);
}
firstChange = false;
currentState = nextState;
}
}
if (wrap) {
sb.append("}"); // Always returns an array of arrays
}
return sb.toString();
}
public static void addEventToStringBuilder(StringBuilder sb, String source, String dest, double time, int site) {
// AR changed this to match an attribute array:
sb.append("{");
if (site > 0) {
sb.append(site).append(",");
}
sb.append(time).append(",").append(source).append(",").append(dest).append("}");
}
public static StateHistory simulateConditionalOnEndingState(double startingTime,
int startingState,
double endingTime,
int endingState,
double[] lambda,
int stateCount) {
throw new RuntimeException("Impossible to simulate a conditioned CTMC in StateHistory");
}
public static StateHistory simulateUnconditionalOnEndingState(double startingTime,
int startingState,
double endingTime,
double[] lambda,
int stateCount) {
StateHistory history = new StateHistory(startingTime, startingState, stateCount);
double[] multinomial = new double[stateCount];
double currentTime = startingTime;
int currentState = startingState;
while (currentTime < endingTime) {
double currentRate = -lambda[currentState * stateCount + currentState];
double waitingTime = MathUtils.nextExponential(currentRate);
currentTime += waitingTime;
if (currentTime < endingTime) { // Simulate a jump
System.arraycopy(lambda, currentState * stateCount, multinomial, 0, stateCount);
multinomial[currentState] = 0;
currentState = MathUtils.randomChoicePDF(multinomial); // Does not need to be normalized
history.addChange(new StateChange(currentTime, currentState));
}
}
history.addEndingState(new StateChange(endingTime, currentState));
return history;
}
private int stateCount;
private List<StateChange> stateList;
private boolean finalized;
private boolean isFiltered = false;
}
|
package dr.inference.operators;
import dr.inference.model.Parameter;
import dr.math.MathUtils;
import dr.xml.*;
public class UpDownOperator extends AbstractCoercableOperator {
public static final String UP_DOWN_OPERATOR = "upDownOperator";
public static final String UP = "up";
public static final String DOWN = "down";
public static final String SCALE_FACTOR = "scaleFactor";
private Scalable[] upParameter = null;
private Scalable[] downParameter = null;
private double scaleFactor;
public UpDownOperator(Scalable[] upParameter, Scalable[] downParameter,
double scale, double weight, CoercionMode mode) {
super(mode);
setWeight(weight);
this.upParameter = upParameter;
this.downParameter = downParameter;
this.scaleFactor = scale;
}
public final double getScaleFactor() {
return scaleFactor;
}
public final void setScaleFactor(double sf) {
if( (sf > 0.0) && (sf < 1.0) ) {
scaleFactor = sf;
} else {
throw new IllegalArgumentException("scale must be between 0 and 1");
}
}
/**
* change the parameter and return the hastings ratio.
*/
public final double doOperation() throws OperatorFailedException {
final double scale = (scaleFactor + (MathUtils.nextDouble() * ((1.0 / scaleFactor) - scaleFactor)));
int goingUp = 0, goingDown = 0;
if( upParameter != null ) {
for( Scalable up : upParameter ) {
goingUp += up.scale(scale, -1);
}
}
if( downParameter != null ) {
for( Scalable dn : downParameter ) {
goingDown += dn.scale(1.0 / scale, -1);
}
}
return (goingUp - goingDown - 2) * Math.log(scale);
}
public final String getPerformanceSuggestion() {
double prob = MCMCOperator.Utils.getAcceptanceProbability(this);
double targetProb = getTargetAcceptanceProbability();
double sf = OperatorUtils.optimizeScaleFactor(scaleFactor, prob, targetProb);
dr.util.NumberFormatter formatter = new dr.util.NumberFormatter(5);
if (prob < getMinimumGoodAcceptanceLevel()) {
return "Try setting scaleFactor to about " + formatter.format(sf);
} else if (prob > getMaximumGoodAcceptanceLevel()) {
return "Try setting scaleFactor to about " + formatter.format(sf);
} else return "";
}
public final String getOperatorName() {
String name = "";
if( upParameter != null ) {
name = "up:";
for( Scalable up : upParameter ) {
name = name + up.getName() + " ";
}
}
if( downParameter != null ) {
name += "down:";
for( Scalable dn : downParameter ) {
name = name + dn.getName() + " ";
}
}
return name;
}
public double getCoercableParameter() {
return Math.log(1.0 / scaleFactor - 1.0) / Math.log(10);
}
public void setCoercableParameter(double value) {
scaleFactor = 1.0 / (Math.pow(10.0, value) + 1.0);
}
public double getRawParameter() {
return scaleFactor;
}
public double getTargetAcceptanceProbability() {
return 0.234;
}
// Since this operator invariably modifies at least 2 parameters it
// should allow lower acceptance probabilities
// as it is known that optimal acceptance levels are inversely
// proportional to the number of dimensions operated on
// AD 16/3/2004
public double getMinimumAcceptanceLevel() {
return 0.05;
}
public double getMaximumAcceptanceLevel() {
return 0.3;
}
public double getMinimumGoodAcceptanceLevel() {
return 0.10;
}
public double getMaximumGoodAcceptanceLevel() {
return 0.20;
}
public static dr.xml.XMLObjectParser PARSER = new dr.xml.AbstractXMLObjectParser() {
public String getParserName() {
return UP_DOWN_OPERATOR;
}
private Scalable[] getArgs(final XMLObject list) throws XMLParseException {
Scalable[] args = new Scalable[list.getChildCount()];
for(int k = 0; k < list.getChildCount(); ++k) {
final Object child = list.getChild(k);
if( child instanceof Parameter ) {
args[k] = new Scalable.Default((Parameter) child);
} else if( child instanceof Scalable ) {
args[k] = (Scalable) child;
} else {
XMLObject xo = (XMLObject)child;
if( xo.hasAttribute("count") ) {
final int count = xo.getIntegerAttribute("count");
final Scalable s = (Scalable) xo.getChild(Scalable.class);
args[k] = new Scalable() {
public int scale(double factor, int nDims) throws OperatorFailedException {
return s.scale(factor, count);
}
public String getName() {
return s.getName() + "(" + count + ")";
}
};
} else if (xo.hasAttribute("df") ) {
final int df = xo.getIntegerAttribute("df");
final Scalable s = (Scalable) xo.getChild(Scalable.class);
args[k] = new Scalable() {
public int scale(double factor, int nDims) throws OperatorFailedException {
s.scale(factor, -1);
return df;
}
public String getName() {
return s.getName() + "[df=" + df + "]";
}
};
}
}
}
return args;
}
public Object parseXMLObject(XMLObject xo) throws XMLParseException {
final double scaleFactor = xo.getDoubleAttribute(SCALE_FACTOR);
final double weight = xo.getDoubleAttribute(WEIGHT);
final CoercionMode mode = CoercionMode.parseMode(xo);
final Scalable[] upArgs = getArgs(xo.getChild(UP));
final Scalable[] dnArgs = getArgs(xo.getChild(DOWN));
return new UpDownOperator(upArgs, dnArgs, scaleFactor, weight, mode);
}
public String getParserDescription() {
return "This element represents an operator that scales two parameters in different directions. " +
"Each operation involves selecting a scale uniformly at random between scaleFactor and 1/scaleFactor. " +
"The up parameter is multipled by this scale and the down parameter is divided by this scale.";
}
public Class getReturnType() {
return UpDownOperator.class;
}
public XMLSyntaxRule[] getSyntaxRules() {
return rules;
}
private final XMLSyntaxRule[] ee = {
new ElementRule(Scalable.class, true),
new ElementRule(Parameter.class, true),
new ElementRule("scale", new XMLSyntaxRule[]{
AttributeRule.newIntegerRule("count", true),
AttributeRule.newIntegerRule("df", true),
new ElementRule(Scalable.class),
}, true),
};
private final XMLSyntaxRule[] rules = {
AttributeRule.newDoubleRule(SCALE_FACTOR),
AttributeRule.newDoubleRule(WEIGHT),
AttributeRule.newBooleanRule(AUTO_OPTIMIZE, true),
// Allow an arbitrary number of Parameters or Scalable in up or down
new ElementRule(UP, ee, 1, Integer.MAX_VALUE),
new ElementRule(DOWN, ee, 1, Integer.MAX_VALUE),
};
};
}
// The old implementation for reference and until the new one is tested :)
//public class UpDownOperator extends AbstractCoercableOperator {
// public static final String UP_DOWN_OPERATOR = "upDownOperator";
// public static final String UP = "up";
// public static final String DOWN = "down";
// public static final String SCALE_FACTOR = "scaleFactor";
// public UpDownOperator(Parameter upParameter, Parameter downParameter,
// double scale, double weight, CoercionMode mode) {
// super(mode);
// this.upParameter = upParameter;
// this.downParameter = downParameter;
// this.scaleFactor = scale;
// setWeight(weight);
// public final int getPriorType() {
// return prior.getPriorType();
// public final double getScaleFactor() {
// return scaleFactor;
// public final void setPriorType(int type) {
// prior.setPriorType(type);
// public final void setScaleFactor(double sf) {
// if ((sf > 0.0) && (sf < 1.0)) scaleFactor = sf;
// /**
// * change the parameter and return the hastings ratio.
// */
// public final double doOperation() throws OperatorFailedException {
// final double scale = (scaleFactor + (MathUtils.nextDouble() * ((1.0 / scaleFactor) - scaleFactor)));
// if( upParameter != null ) {
// for(int i = 0; i < upParameter.getDimension(); i++) {
// upParameter.setParameterValue(i, upParameter.getParameterValue(i) * scale);
// for(int i = 0; i < upParameter.getDimension(); i++) {
// if( upParameter.getParameterValue(i) < upParameter.getBounds().getLowerLimit(i) ||
// upParameter.getParameterValue(i) > upParameter.getBounds().getUpperLimit(i) ) {
// throw new OperatorFailedException("proposed value outside boundaries");
// if( downParameter != null ) {
// for(int i = 0; i < downParameter.getDimension(); i++) {
// downParameter.setParameterValue(i, downParameter.getParameterValue(i) / scale);
// for(int i = 0; i < downParameter.getDimension(); i++) {
// if( downParameter.getParameterValue(i) < downParameter.getBounds().getLowerLimit(i) ||
// downParameter.getParameterValue(i) > downParameter.getBounds().getUpperLimit(i) ) {
// throw new OperatorFailedException("proposed value outside boundaries");
// final int goingUp = (upParameter == null) ? 0 : upParameter.getDimension();
// final int goingDown = (downParameter == null) ? 0 : downParameter.getDimension();
// final double logq = (goingUp - goingDown - 2) * Math.log(scale);
// return logq;
// public final String getPerformanceSuggestion() {
// double prob = MCMCOperator.Utils.getAcceptanceProbability(this);
// double targetProb = getTargetAcceptanceProbability();
// double sf = OperatorUtils.optimizeScaleFactor(scaleFactor, prob, targetProb);
// dr.util.NumberFormatter formatter = new dr.util.NumberFormatter(5);
// if (prob < getMinimumGoodAcceptanceLevel()) {
// return "Try setting scaleFactor to about " + formatter.format(sf);
// } else if (prob > getMaximumGoodAcceptanceLevel()) {
// return "Try setting scaleFactor to about " + formatter.format(sf);
// } else return "";
// //MCMCOperator INTERFACE
// public final String getOperatorName() {
// return (upParameter != null ? "up:" + upParameter.getParameterName() : "") +
// (downParameter != null ? " down:" + downParameter.getParameterName() : "");
// public double getCoercableParameter() {
// return Math.log(1.0 / scaleFactor - 1.0) / Math.log(10);
// public void setCoercableParameter(double value) {
// scaleFactor = 1.0 / (Math.pow(10.0, value) + 1.0);
// public double getRawParameter() {
// return scaleFactor;
// public double getTargetAcceptanceProbability() {
// return 0.234;
// // Since this operator invariably modifies at least 2 parameters it
// // should allow lower acceptance probabilities
// // as it is known that optimal acceptance levels are inversely
// // proportional to the number of dimensions operated on
// // AD 16/3/2004
// public double getMinimumAcceptanceLevel() {
// return 0.05;
// public double getMaximumAcceptanceLevel() {
// return 0.3;
// public double getMinimumGoodAcceptanceLevel() {
// return 0.10;
// public double getMaximumGoodAcceptanceLevel() {
// return 0.20;
// public static dr.xml.XMLObjectParser PARSER = new dr.xml.AbstractXMLObjectParser() {
// public String getParserName() {
// return UP_DOWN_OPERATOR;
// public Object parseXMLObject(XMLObject xo) throws XMLParseException {
// final double scaleFactor = xo.getDoubleAttribute(SCALE_FACTOR);
// final double weight = xo.getDoubleAttribute(WEIGHT);
// CoercionMode mode = CoercionMode.parseMode(xo);
// Parameter param1 = (Parameter) xo.getElementFirstChild(UP);
// Parameter param2 = (Parameter) xo.getElementFirstChild(DOWN);
// return new UpDownOperator(param1, param2, scaleFactor, weight, mode);
// public String getParserDescription() {
// return "This element represents an operator that scales two parameters in different directions. " +
// "Each operation involves selecting a scale uniformly at random between scaleFactor and 1/scaleFactor. " +
// "The up parameter is multipled by this scale and the down parameter is divided by this scale.";
// public Class getReturnType() {
// return UpDownOperator.class;
// public XMLSyntaxRule[] getSyntaxRules() {
// return rules;
// private final XMLSyntaxRule[] rules = {
// AttributeRule.newDoubleRule(SCALE_FACTOR),
// AttributeRule.newDoubleRule(WEIGHT),
// AttributeRule.newBooleanRule(AUTO_OPTIMIZE, true),
// new ElementRule(UP,
// new XMLSyntaxRule[]{new ElementRule(Parameter.class)}),
// new ElementRule(DOWN,
// new XMLSyntaxRule[]{new ElementRule(Parameter.class)})
// //PRIVATE STUFF
// private Parameter upParameter = null;
// private Parameter downParameter = null;
// private final ContinuousVariablePrior prior = new ContinuousVariablePrior();
// private double scaleFactor = 0.5;
|
package election.tally;
//@ refine "AbstractBallotCounting.java-refined";
public abstract class AbstractBallotCounting extends ElectionStatus {
protected static final int NONE_FOUND_YET = -1;
/** List of decisions made */
protected transient/*@ spec_public @*/ Decision[] decisions
= new Decision[Decision.MAX_DECISIONS];
//@ protected represents decisionsMade <- decisions;
/** List of candidates for election */
protected transient/*@ spec_public @*/ Candidate[] candidates = new Candidate[0];
//@ protected represents candidateList <- candidates;
/** List of contents of each ballot paper that will be counted. */
protected transient /*@ spec_public @*/ Ballot[] ballots = new Ballot[0];
//@ public invariant ballots.owner == this;
//@ protected represents ballotsToCount <- ballots;
/** Total number of candidates for election */
protected transient/*@ spec_public @*/ int totalNumberOfCandidates;
//@ public represents totalCandidates <- totalNumberOfCandidates;
/** Number of candidates elected so far */
protected transient/*@ spec_public @*/ int numberOfCandidatesElected;
//@ public represents numberElected <- numberOfCandidatesElected;
/** Number of candidates excluded from election so far */
protected transient/*@ spec_public @*/ int numberOfCandidatesEliminated;
//@ public represents numberEliminated <- numberOfCandidatesEliminated;
/** Number of seats in this election */
protected transient/*@ spec_public @*/ int numberOfSeats;
//@ public represents seats <- numberOfSeats;
/** Number of seats in this constituency */
protected transient int totalNumberOfSeats;
//@ protected represents totalSeats <- totalNumberOfSeats;
/** Total number of valid ballot papers */
protected/*@ spec_public @*/transient int totalNumberOfVotes;
//@ protected represents totalVotes <- totalNumberOfVotes;
/** Number of votes needed to save deposit unless elected */
protected transient/*@ spec_public @*/int savingThreshold;
//@ protected represents depositSavingThreshold <- savingThreshold;
/** Number of rounds of counting so far. */
protected transient/*@ spec_public @*/int countNumberValue;
//@ protected represents countNumber <- countNumberValue;
/** Number of seats remaining to be filled */
protected transient/*@ spec_public @*/int totalRemainingSeats;
/*@ protected represents remainingSeats <-
@ numberOfSeats - numberOfCandidatesElected;
@*/
/** Number of decisions taken. */
//@ public invariant decisionsTaken <= Decision.MAX_DECISIONS;
protected transient/*@ spec_public @*/int decisionsTaken;
//@ represents numberOfDecisions <- decisionsTaken;
/**
* Default Constructor.
*/
/*@ also
@ public normal_behavior
@ assignable state, countNumber, numberElected, numberEliminated,
@ countNumberValue, numberOfCandidatesElected, seats, numberOfSeats,
@ totalVotes, numberOfCandidatesEliminated, decisions, decisionsTaken,
@ totalNumberOfVotes;
@ ensures state == ElectionStatus.EMPTY;
@ ensures countNumber == 0;
@ ensures numberElected == 0;
@*/
public AbstractBallotCounting() {
super();
status = ElectionStatus.EMPTY;
countNumberValue = 0;
numberOfCandidatesElected = 0;
numberOfCandidatesEliminated = 0;
decisionsTaken = 0;
for (int d=0; d < decisions.length; d++) {
decisions[d] = new Decision();
}
totalNumberOfVotes = 0;
numberOfSeats = 0;
}
/*@ also
@ public normal_behavior
@ requires 0 <= countNumber;
@ requires \nonnullelements (candidateList);
@ requires \nonnullelements (ballotsToCount);
@ ensures \result <==>
@ (countBallotsFor(candidate.getCandidateID()) >= getQuota());
@*/
public/*@ pure @*/boolean hasQuota(final/*@ non_null @*/Candidate candidate) {
// TODO 2009.10.14 ESC precondition violation warning
return (countBallotsFor(candidate.getCandidateID()) >= getQuota()); //@ nowarn;
}
/**
* Determine if the candidate was elected in any previous round <BON>query
* "Has the candidate been elected?"</BON>
*
* @param candidate
* The candidate
* @return True if the candidate has already been elected
*/
/*@ also
@ protected normal_behavior
@ requires candidate != null;
@ ensures (\result == true) <==>
@ (candidate.getStatus() == Candidate.ELECTED || hasQuota(candidate));
@*/
public/*@ pure @*/boolean isElected(final Candidate candidate) {
return ((candidate.getStatus() == CandidateStatus.ELECTED) || hasQuota(candidate));
}
/*@ also
@ public normal_behavior
@ requires 0 <= countNumber;
@ requires PRECOUNT <= state;
@ requires \nonnullelements (ballotsToCount);
@ ensures (hasQuota(candidate) == true) ==> \result ==
@ (countBallotsFor(candidate.getCandidateID()) - getQuota());
@ ensures (hasQuota(candidate) == false) ==> \result == 0;
@ ensures 0 <= \result;
@*/
public/*@ pure @*/int getSurplus(final/*@ non_null @*/Candidate candidate) {
// TODO 2009.10.14 ESC precondition violation warning
final int surplus = countBallotsFor(candidate.getCandidateID()) - getQuota(); //@ nowarn;
if (surplus < 0) {
return 0;
}
return surplus;
}
/**
* How many surplus votes are available for distribution?
*
* @return The total number of surplus votes for all candidates.
*/
public final/*@ pure @*/int getTotalSumOfSurpluses() {
int sumOfSurpluses = 0;
for (int c = 0; c < totalNumberOfCandidates; c++) {
final int surplus = getSurplus(candidates[c]);
if (surplus > 0) {
sumOfSurpluses += surplus;
}
}
return sumOfSurpluses;
}
/*@ also
@ requires (state == COUNTING) || (state == FINISHED);
@ requires \nonnullelements (candidateList);
@ requires 0 <= index;
@ requires index < totalNumberOfCandidates;
@ requires index < candidateList.length;
@ ensures \result <==>
@ (candidateList[index].getOriginalVote() >= depositSavingThreshold) ||
@ (isElected (candidateList[index]) == true);
@*/
public/*@ pure @*/boolean isDepositSaved(final int index) {
// TODO 2009.10.14 ESC negative index warning
final Candidate candidate = candidates[index]; //@ nowarn;
// TODO 2009.10.14 ESC precondition warning
final int originalVote = candidate.getOriginalVote(); //@ nowarn;
final boolean elected = isElected(candidate);
return ((originalVote >= savingThreshold) || elected);
}
/*@ also
@ protected normal_behavior
@ requires getSurplus (candidateList[candidateWithSurplus]) > 0;
@ requires state == COUNTING;
@ requires getNumberContinuing() > remainingSeats;
@ assignable candidates;
@ ensures getSurplus (candidateList[candidateWithSurplus]) == 0;
@*/
public abstract void distributeSurplus(int candidateWithSurplus);
/**
* Load candidate details and number of seats.
*
* @param electionParameters
* The candidate details and number of seats
*/
/*@ also
@ protected normal_behavior
@ requires state == EMPTY;
@ requires 0 <= constituency.getNumberOfCandidates();
@ assignable status;
@ assignable totalNumberOfCandidates;
@ assignable numberOfSeats, totalRemainingSeats;
@ assignable totalNumberOfSeats;
@ assignable candidates;
@ ensures state == PRELOAD;
@ ensures totalCandidates == constituency.getNumberOfCandidates();
@ ensures seats == constituency.getNumberOfSeatsInThisElection();
@ ensures totalSeats == constituency.getTotalNumberOfSeats();
@ ensures totalCandidates == candidateList.length;
@ ensures \nonnullelements (candidateList);
@*/
public void setup(final/*@ non_null @*/ Constituency constituency) {
this.totalNumberOfCandidates = constituency.getNumberOfCandidates();
this.numberOfSeats = constituency.getNumberOfSeatsInThisElection();
this.totalNumberOfSeats = constituency.getTotalNumberOfSeats();
this.status = PRELOAD;
candidates = new Candidate[this.totalNumberOfCandidates];
for (int i = 0; i < candidates.length; i++) {
// TODO 2009.10.14 ESC precondition
this.candidates[i] = constituency.getCandidate(i); //@ nowarn;
}
this.totalRemainingSeats = this.numberOfSeats;
// TODO 2009.10.14 ESC postcondition
} //@ nowarn;
/**
* Open the ballot box for counting.
*
* @param ballotBox
* The ballots to be counted, already "shuffled and mixed".
*/
/*@ also
@ protected normal_behavior
@ requires state == PRELOAD;
@ assignable state, totalVotes, ballotsToCount, ballots;
@ assignable totalNumberOfVotes;
@ ensures state == PRECOUNT;
@ ensures totalVotes == ballotBox.numberOfBallots;
@ ensures totalVotes == ballotsToCount.length;
@*/
public void load(final/*@ non_null @*/BallotBox ballotBox) {
totalNumberOfVotes = ballotBox.size();
ballots = new Ballot[totalNumberOfVotes];
int index = 0;
// TODO 2009.10.14 ESC invariant violation
while (ballotBox.isNextBallot()) { //@ nowarn;
// TODO 2009.10.14 ESC precondition warning
ballots[index++] = ballotBox.getNextBallot(); //@ nowarn;
}
status = PRECOUNT;
// Number of first preferences for each candidate
calculateFirstPreferences();
}
/**
* Droop quota; number of votes needed to guarantee election.
*
* @return Number of votes required to ensure election
*/
public/*@ pure @*/int getQuota() {
return 1 + (totalNumberOfVotes / (1 + numberOfSeats));
}
/**
* Calculate the first preference counts for each candidate.
*/
//@ requires PRECOUNT <= state;
//@ requires \nonnullelements (candidateList);
//@ requires \nonnullelements (ballotsToCount);
//@ assignable candidates[*];
protected void calculateFirstPreferences() {
for (int c = 0; c < candidates.length; c++) {
final int candidateID = candidates[c].getCandidateID();
final int numberOfBallotsInPile = countFirstPreferences(candidateID);
if (0 < numberOfBallotsInPile) {
// TODO 2009.10.14 ESC warning
candidates[c].addVote(numberOfBallotsInPile, countNumberValue); //@ nowarn;
}
}
}
/**
* Count the number of ballots in the pile for this candidate.
*
* @param candidateID
* The internal identifier of this candidate
* @return The number of ballots in this candidate's pile
*/
//@ also requires \nonnullelements (ballotsToCount);
public/*@ pure @*/int countBallotsFor(final int candidateID) {
int numberOfBallots = 0;
for (int b = 0; b < ballots.length; b++) {
//@ assert ballots[b] != null;
if (ballots[b].isAssignedTo(candidateID)) {
numberOfBallots++;
}
}
return numberOfBallots;
}
/**
* Count the number of first preferences for this candidate.
*
* @param candidateID
* The internal identifier of this candidate
* @return The number of ballots in this candidate's pile
*/
/*@ requires PRECOUNT <= state;
@ requires \nonnullelements (ballotsToCount);
@ ensures 0 <= \result;
@ ensures \result <= ballotsToCount.length;
@*/
public/*@ pure @*/int countFirstPreferences(final int candidateID) {
int numberOfBallots = 0;
for (int b = 0; b < ballots.length; b++) {
//@ assert ballots[b] != null;
if (ballots[b].isFirstPreference(candidateID)) {
numberOfBallots++;
}
}
return numberOfBallots;
}
/**
* Gets the potential number of transfers from one candidate to another.
*
* @design This method is needed to get the proportions to use when
* transferring surplus votes
* @param fromCandidate
* Candidate from which to check the transfers
* @param toCandidateID
* Candidate ID to check for receipt of transferred votes
* @return Number of votes potentially transferable from this candidate to
* that candidate
*/
/*@ also
@ requires \nonnullelements (ballotsToCount);
@ ensures \result== (\num_of int j; 0 <= j && j < totalVotes;
@ (ballotsToCount[j].isAssignedTo(fromCandidate.getCandidateID())) &&
@ (getNextContinuingPreference(ballotsToCount[j]) == toCandidateID));
@*/
protected/*@ pure spec_public @*/int getPotentialTransfers(
final Candidate fromCandidate,
final int toCandidateID) {
int numberOfBallots = 0;
// TODO 2009.10.14 ESC null reference warnings
for (int j = 0; j < ballots.length; j++) { //@ nowarn;
if (ballots[j].isAssignedTo(fromCandidate.getCandidateID()) //@ nowarn;
&& (getNextContinuingPreference(ballots[j]) == toCandidateID)) {
numberOfBallots++;
}
}
return numberOfBallots;
}
/**
* Gets the status of the algorithm in progress.
*
* @return The state variable value {@link #EMPTY}, {@link #SETTING_UP},
* {@link #PRELOAD}, {@link #LOADING}, {@link #PRECOUNT},
* {@link #COUNTING}, {@link #FINISHED}
*/
/*@ also
@ protected normal_behavior
@ ensures \result == state;
@*/
public /*@ pure @*/ byte getStatus() {
return status;
}
/**
* Gets the next preference continuing candidate.
*
* @param ballot
* Ballot paper from which to get the next preference
* @return Internal ID of next continuing candidate or
* <code>NONTRANSFERABLE</code>
*/
protected/*@ pure spec_public @*/int getNextContinuingPreference(
final/*@ non_null @*/Ballot ballot) {
for (int i = 1; i <= ballot.remainingPreferences(); i++) {
final int nextPreference = ballot.getNextPreference(i);
if (isContinuingCandidateID(nextPreference)) {
return nextPreference;
}
}
return Ballot.NONTRANSFERABLE;
}
/**
* Determine if a candidate ID belongs to a continuing candidate.
*
* @param candidateID
* The ID of candidate for which to check the status
* @return <code>true</code> if this candidate ID matches that of a continuing
* candidate
*/
/*@ also
@ requires \nonnullelements (candidateList);
@ ensures \result == (\exists int i;
@ 0 <= i && i < candidateList.length;
@ candidateID == candidateList[i].getCandidateID() &&
@ candidateList[i].getStatus() == CandidateStatus.CONTINUING);
@*/
public/*@ pure @*/boolean isContinuingCandidateID(final int candidateID) {
for (int i = 0; i < candidates.length; i++) {
if (candidateID == candidates[i].getCandidateID()) {
return candidates[i].getStatus() == CandidateStatus.CONTINUING;
}
}
return false; // not a candidate
// TODO 2009.10.14 ESC postcondition
} //@ nowarn;
/**
* Determine actual number of votes to transfer to this candidate
*
* @design The number of votes in a surplus transferred is in proportion to
* the number of transfers available throughout the candidate's ballot
* stack
* @param fromCandidate
* Candidate from which to count the transfers
* @param toCandidate
* Continuing candidate eligible to receive votes
* @return Number of votes available for transfer
*/
/*@ also
@ protected normal_behavior
@ requires state == COUNTING;
@ requires isElected (fromCandidate) ||
@ (fromCandidate.getStatus() == CandidateStatus.ELIMINATED);
@ requires toCandidate.getStatus() == CandidateStatus.CONTINUING;
@ requires ballotsToCount != null;
@ requires (\forall int b; 0 <= b && b < totalVotes;
@ ballotsToCount[b] != null);
@ ensures (isElected (fromCandidate) &&
@ (getSurplus(fromCandidate) < getTotalTransferableVotes(fromCandidate)))
@ ==>
@ (\result ==
@ (getSurplus (fromCandidate) *
@ getPotentialTransfers (fromCandidate,
@ toCandidate.getCandidateID()) /
@ getTotalTransferableVotes (fromCandidate)));
@ ensures ((fromCandidate.getStatus() == Candidate.ELIMINATED) ||
@ (getTotalTransferableVotes(fromCandidate) <= getSurplus(fromCandidate)))
@ ==>
@ (\result ==
@ (\num_of int j; 0 <= j && j < totalVotes;
@ ballotsToCount[j].isAssignedTo(fromCandidate.getCandidateID()) &&
@ getNextContinuingPreference(ballotsToCount[j]) ==
@ toCandidate.getCandidateID()));
@*/
protected/*@ pure spec_public @*/int getActualTransfers(
final/*@ non_null @*/Candidate fromCandidate,
final/*@ non_null @*/Candidate toCandidate) {
int numberOfVotes = getPotentialTransfers(fromCandidate,
toCandidate.getCandidateID());
final int surplus = getSurplus(fromCandidate);
final int totalTransferableVotes = getTotalTransferableVotes(fromCandidate);
if (isElected(fromCandidate) && surplus < totalTransferableVotes && 0 < totalTransferableVotes) {
numberOfVotes *= surplus;
numberOfVotes /= totalTransferableVotes;
}
return numberOfVotes;
// TODO 2009.10.14 ESC postcondition
} //@ nowarn;
/**
* Determine the rounded value of a fractional transfer.
*
* @design This depends on the shortfall and the relative size of the other
* fractional transfers.
* @param fromCandidate
* Elected candidate from which to distribute surplus
* @param toCandidate
* Continuing candidate potentially eligble to recieve transfers
* @return <code>1</code> if the fractional vote is to be rounded up
* <code>0</code> if the fractional vote is to be rounded down
*/
/*@ also
@ protected normal_behavior
@ requires state == COUNTING;
@ requires isElected (fromCandidate);
@ requires toCandidate.getStatus() == CandidateStatus.CONTINUING;
@ requires getSurplus(fromCandidate) <
@ getTotalTransferableVotes(fromCandidate);
@ requires 0 <= getTransferShortfall (fromCandidate);
@*/
protected/*@ pure spec_public @*/int getRoundedFractionalValue(
final/*@ non_null @*/Candidate fromCandidate,
final/*@ non_null @*/Candidate toCandidate) {
if (getOrder(fromCandidate, toCandidate) <= getTransferShortfall(fromCandidate)) {
return 1;
}
return 0;
}
/**
* Determine shortfall between sum of transfers rounded down and the size of
* surplus
*
* @param fromCandidate
* Elected candidate from which to distribute surplus
* @return The shortfall between the sum of the transfers and the size of surplus
*/
/*@ also
@ requires \nonnullelements (candidateList);
@ requires state == COUNTING;
@ requires (fromCandidate.getStatus() == CandidateStatus.ELECTED) ||
@ (fromCandidate.getStatus() == CandidateStatus.ELIMINATED);
@*/
protected/*@ pure spec_public @*/int getTransferShortfall(
final/*@ non_null @*/Candidate fromCandidate) {
int shortfall = 0;
for (int i = 0; i < totalNumberOfCandidates; i++) {
if (candidates[i].getStatus() == CandidateStatus.CONTINUING) {
shortfall += getActualTransfers(fromCandidate, candidates[i]);
}
}
return shortfall - getSurplus(fromCandidate);
}
/**
* Simulate random selection between two candidates.
*
* @design This needs to be random but consistent, so that same result is
* always given for the same pair of candidates.
* @param firstCandidate
* The first of the candidates to be selected from
* @param secondCandidate
* The second of the candidates to be selected from
* @return The candidate ID of the chosen candidate
*/
public/*@ pure @*/int randomSelection(
final/*@ non_null @*/Candidate firstCandidate,
final/*@ non_null @*/Candidate secondCandidate) {
if (firstCandidate.isAfter(secondCandidate)
|| firstCandidate.sameAs(secondCandidate)) {
return firstCandidate.getCandidateID();
}
return secondCandidate.getCandidateID();
}
/**
* Determine the individuals remainder after integer division by the transfer
* factor for surpluses.
*
* @design This can all be done with integer arithmetic; no need to use
* floating point numbers, which could introduce rounding errors.
* @param fromCandidate
* Elected candidate from which to count to transfers
* @param toCandidate
* Continuing candidate eligible to receive votes
* @return The size of the quotient remainder
*/
/*@ also
@ protected normal_behavior
@ requires \nonnullelements (candidateList);
@ requires state == COUNTING;
@ requires isElected (fromCandidate);
@ requires toCandidate.getStatus() == CandidateStatus.CONTINUING;
@ requires getSurplus(fromCandidate) < getTotalTransferableVotes(fromCandidate);
@ requires 0 <= getTransferShortfall (fromCandidate);
@ requires 0 < getSurplus(fromCandidate);
@*/
protected/*@ pure spec_public @*/int getTransferRemainder(
final/*@ non_null @*/Candidate fromCandidate,
final/*@ non_null @*/Candidate toCandidate) {
return getPotentialTransfers(fromCandidate, toCandidate.getCandidateID())
- getActualTransfers(fromCandidate, toCandidate);
}
/*@ also
@ protected normal_behavior
@ requires countNumberValue < CountConfiguration.MAXCOUNT;
@ requires firstCandidate.getStatus() == Candidate.CONTINUING;
@ requires secondCandidate.getStatus() == Candidate.CONTINUING;
@*/
protected/*@ pure spec_public @*/boolean isHigherThan(
final/*@ non_null @*/Candidate firstCandidate,
final/*@ non_null @*/Candidate secondCandidate) {
int firstNumberOfVotes;
int secondNumberOfVotes;
int count = countNumberValue;
while (0 <= count) {
// TODO 2009.10.14 ESC precondition warning
firstNumberOfVotes = firstCandidate.getTotalAtCount(count); //@ nowarn;
secondNumberOfVotes = secondCandidate.getTotalAtCount(count);
if (firstNumberOfVotes > secondNumberOfVotes) {
return true;
} else if (secondNumberOfVotes > firstNumberOfVotes) {
return false;
}
count
}
return secondCandidate.isAfter(firstCandidate);
// TODO 2009.10.14 ESC postcondition warning
} //@ nowarn;
/**
* Determine the number of continuing candidates with a higher remainder in
* their transfer quotient, or deemed to have a higher remainder.
*
* @design There must be a strict ordering of candidates for the purpose of
* allocating the transfer shortfall. If two or more candidates have
* equal remainders then use the number of transfers they are about to
* receive and if the number of transfers are equal then look at the
* number of votes all ready received.
* @param fromCandidate
* Candidate, already elected, with surplus votes to donate
* @param toCandidate
* Continuing candidate eligible to receive vote transfer
* @return The number of continuing candidates with a higher quotient remainder
* than this candidate
*/
/*@ also
@ protected normal_behavior
@ requires state == COUNTING;
@ requires isElected (fromCandidate);
@ requires toCandidate.getStatus() ==
@ election.tally.Candidate.CONTINUING;
@ requires getSurplus(fromCandidate) <
@ getTotalTransferableVotes(fromCandidate);
@ requires 0 <= getTransferShortfall (fromCandidate);
@ requires 0 <= getSurplus(fromCandidate);
@ ensures \result == getCandidateRanking (fromCandidate, toCandidate);
@*/
protected/*@ pure spec_public @*/int getOrder(
final/*@ non_null @*/Candidate fromCandidate,
final/*@ non_null @*/Candidate toCandidate) {
int numberHigherThan = 0;
final int actualTransfers = getActualTransfers(fromCandidate, toCandidate);
// TODO 2009.10.14 ESC precondition warning
final int transferRemainder
= getTransferRemainder(fromCandidate, toCandidate); //@ nowarn;
for (int i = 0; i < totalNumberOfCandidates; i++) {
if (candidates[i].getCandidateID() != toCandidate.getCandidateID()
&& candidates[i].getStatus() == CandidateStatus.CONTINUING) {
// TODO 2009.10.14 ESC precondition warning
numberHigherThan += compareCandidates(fromCandidate, toCandidate, //@ nowarn;
actualTransfers, transferRemainder, candidates[i]);
}
}
return numberHigherThan;
// TODO 2009.10.14 ESC postcondition warning
} //@ nowarn;
/*@ protected normal_behavior
@ requires state == COUNTING;
@ requires isElected (fromCandidate);
@ requires getSurplus(fromCandidate) < getTotalTransferableVotes(fromCandidate);
@ requires 0 <= getTransferShortfall (fromCandidate);
@ requires 0 <= getSurplus(fromCandidate);
@*/
protected /*@ pure @*/ int compareCandidates(
final /*@ non_null @*/ Candidate fromCandidate,
final /*@ non_null @*/ Candidate firstCandidate,
final int transfersToFirst,
final int firstTransferRemainder,
final /*@ non_null @*/ Candidate secondCandidate) {
// TODO 2009.10.14 ESC warning
final int secondTransferRemainder
= getTransferRemainder(fromCandidate, secondCandidate); //@ nowarn;
if (secondTransferRemainder > firstTransferRemainder) {
return 1;
}
final int transfersToSecond = getActualTransfers(fromCandidate,
secondCandidate);
if (secondTransferRemainder == firstTransferRemainder
&& transfersToSecond > transfersToFirst) {
return 1;
} else if (secondTransferRemainder == firstTransferRemainder
&& transfersToSecond == transfersToFirst
// TODO 2009.10.14 ESC precondition warning
&& isHigherThan(secondCandidate, firstCandidate)) { //@ nowarn;
return 1;
}
return 0;
}
/**
* Get the maximum number of votes transferable to continuing candidates.
*
* @param fromCandidate
* Candidate ID from which to check the transfers
* @return Number of votes potentially transferable from this candidate
*/
/*@ also
@ protected normal_behavior
@ requires state == COUNTING;
@ requires \nonnullelements (candidateList);
@ requires isElected (fromCandidate) ||
@ (fromCandidate.getStatus() == CandidateStatus.ELIMINATED);
@ ensures \result == numberTransferable (fromCandidate);
@ ensures 0 <= \result;
@*/
protected /*@ pure spec_public @*/ int getTotalTransferableVotes(
final /*@ non_null @*/ Candidate fromCandidate) {
int numberOfTransfers = 0;
for (int i = 0; i < totalNumberOfCandidates; i++) {
if (candidates[i].getStatus() == CandidateStatus.CONTINUING) {
numberOfTransfers +=
getPotentialTransfers(fromCandidate, candidates[i].getCandidateID());
}
}
return numberOfTransfers;
// TODO 2009.10.14 ESC postcondition
} //@ nowarn Post;
/**
* Transfer votes from one candidate to another.
*
* @param fromCandidate
* Elected or excluded candidate
* @param toCandidate
* Continuing candidate
* @param numberOfVotes
* Number of votes to be transferred <BON>command</BON>
*/
/*@ also
@ protected normal_behavior
@ requires fromCandidate.getStatus() != Candidate.CONTINUING;
@ requires toCandidate.getStatus() == Candidate.CONTINUING;
@ assignable ballotsToCount;
@*/
public abstract void transferVotes(
final/*@ non_null @*/Candidate fromCandidate,
final/*@ non_null @*/Candidate toCandidate,
final int numberOfVotes);
/**
* Who is the highest continuing candidate, not yet elected?
*
* @return The continuing candidate with the most votes
*/
/*@ requires 1 <= getNumberContinuing();
@ requires \nonnullelements (ballotsToCount);
@ ensures \result == -AbstractBallotCounting.NONE_FOUND_YET ||
@ (\max int i; 0 <= i && i < totalCandidates &&
@ candidateList[i].getStatus() == Candidate.CONTINUING;
@ countBallotsFor(candidateList[i].getCandidateID()))
@ == countBallotsFor(candidateList[\result].getCandidateID());
@ ensures \result == AbstractBallotCounting.NONE_FOUND_YET || (\exists int i; 0 <= i && i < totalCandidates &&
@ candidates[i].getStatus() == Candidate.CONTINUING; i == \result);
@ ensures 0 <= \result && \result < totalCandidates;
@ ensures candidateList[\result] != null;
@*/
public/*@ pure @*/int findHighestCandidate() {
int highestCandidate = AbstractBallotCounting.NONE_FOUND_YET;
long mostVotes = 0;
for (int i = 0; i < totalNumberOfCandidates; i++) {
if (candidates[i].getStatus() == CandidateStatus.CONTINUING) {
final int votes = countBallotsFor(candidates[i].getCandidateID());
if (votes > mostVotes) {
mostVotes = votes;
highestCandidate = i;
} else if (0 <= highestCandidate && votes == mostVotes
&& isHigherThan(candidates[i], candidates[highestCandidate])) {
highestCandidate = i; // TODO test coverage
}
}
}
return highestCandidate;
// TODO 2009.10.14 ESC postcondition
} //@ nowarn Post;
/**
* Who is the lowest continuing candidate?
*
* @return The continuing candidate with the least votes
*/
/*@ requires 1 <= totalCandidates;
@ requires \nonnullelements (ballotsToCount);
@ ensures AbstractBallotCounting.NONE_FOUND_YET == \result
@ || (\forall int i; 0 <= i && i < totalCandidates && i != \result &&
@ candidateList[i].getStatus() == CandidateStatus.CONTINUING;
@ countBallotsFor(candidateList[i].getCandidateID()) >=
@ countBallotsFor(candidateList[\result].getCandidateID()));
@ ensures AbstractBallotCounting.NONE_FOUND_YET == \result
@ || (\exists int i; 0 <= i && i < totalCandidates &&
@ candidateList[i].getStatus() == CandidateStatus.CONTINUING;
@ i == \result);
@*/
public/*@ pure @*/int findLowestCandidate() {
long leastVotes = CountConfiguration.MAXVOTES;
int lowest = AbstractBallotCounting.NONE_FOUND_YET;
for (int i = 0; i < totalNumberOfCandidates; i++) {
if (candidates[i].getStatus() == CandidateStatus.CONTINUING) {
final int votes = countBallotsFor(candidates[i].getCandidateID());
if (votes < leastVotes) {
leastVotes = votes;
lowest = i;
} else if (0 <= lowest && votes == leastVotes
&& isHigherThan(candidates[lowest], candidates[i])) {
lowest = i;
}
}
}
return lowest;
}
/**
* Exclude one candidate from the election.
*
* @param loser
* The candidate to be excluded
*/
/*@ requires candidateList[loser].getStatus() == Candidate.CONTINUING;
@ requires hasQuota (candidateList[loser]) == false;
@ requires remainingSeats < getNumberContinuing();
@ requires (state == COUNTING);
@ requires 0 <= loser && loser < totalCandidates;
@ requires loser == findLowestCandidate();
@ requires candidateList[loser].getCandidateID() != Ballot.NONTRANSFERABLE;
@ requires countNumber < CountConfiguration.MAXCOUNT;
@ requires \nonnullelements (ballotsToCount);
@ requires \nonnullelements (candidateList);
@ assignable candidateList, decisions[*], decisionsTaken;
@ assignable candidateList[loser], candidateList[*];
@ assignable numberOfCandidatesEliminated;
@ assignable candidateList[loser].state, ballotsToCount, ballots;
@ ensures remainingSeats <= getNumberContinuing();
@ ensures numberElected <= seats;
@ ensures candidateList[loser].getStatus() == Candidate.ELIMINATED;
@ ensures (\forall int b; 0 <= b && b < ballotsToCount.length;
@ ballotsToCount[b].getCandidateID() != candidateList[loser].getCandidateID());
@*/
public void eliminateCandidate(final int loser) {
final int candidateID = candidates[loser].getCandidateID();
candidates[loser].declareEliminated();
// TODO 2009.10.14 ESC warnings
redistributeBallots(candidateID); //@ nowarn;
makeDecision(DecisionStatus.EXCLUDE, candidateID); //@ nowarn;
numberOfCandidatesEliminated++;
} //@ nowarn;
/**
* Make a decision either to elect or exclude a candidate.
*
* @param decisionType The type of decision made
* @param candidateID The identity of the candidate about which the decision was made
*/
/*@ requires (\exists int i; 0 <= i && i < totalCandidates;
@ candidateList[i].getCandidateID() == candidateID);
@ requires (decisionType == DecisionStatus.EXCLUDE) ||
@ (decisionType == DecisionStatus.DEEM_ELECTED);
@ requires state == COUNTING;
@ requires 0 <= countNumberValue;
@ requires candidateID != Candidate.NO_CANDIDATE;
@ requires candidateID != Ballot.NONTRANSFERABLE;
@ requires 0 < candidateID;
@ assignable decisions[*], decisionsTaken, decisions[decisionsTaken].candidateID;
@ assignable decisions[decisionsTaken].atCountNumber;
@ assignable decisions[decisionsTaken].decisionTaken;
@ ensures \old(numberOfDecisions) <= numberOfDecisions;
@*/
protected void makeDecision(final byte decisionType, final int candidateID) {
final Decision decision = new Decision();
decision.setDecisionType(decisionType);
decision.setCountNumber(countNumberValue);
//@ assert countNumberValue == decision.getCountNumber();
decision.setCandidate(candidateID);
if (decisionsTaken < decisions.length) {
decisions[decisionsTaken].copy(decision);
decisionsTaken++;
}
//@ assert 0 <= numberOfDecisions;
//@ assert numberOfDecisions <= decisionsMade.length;
//@ assert 0 <= totalVotes;
//@ assert depositSavingThreshold <= totalVotes;
// TODO 2009.10.14 ESC object invariant warning
} //@ nowarn;
/**
* Redistribute the transferable ballots of an excluded candidate.
*
* @param candidateID The unique identifier for the excluded candidate
*/
/*@ requires candidateID != Ballot.NONTRANSFERABLE;
@ requires countNumberValue < CountConfiguration.MAXCOUNT;
@ requires \nonnullelements (ballotsToCount);
@ assignable ballots;
@*/
protected void redistributeBallots(final int candidateID) {
for (int b = 0; b < ballots.length; b++) {
if (ballots[b].getCandidateID() == candidateID) {
// TODO 2009.10.14 ESC precondition
transferBallot(ballots[b]); //@ nowarn;
}
}
}
/**
* Transfer the ballot to the next preference continuing candidate unless non-transferable.
*
* @param ballot The ballot
*/
/*@ assignable ballot.positionInList;
@ ensures ballot.getCandidateID() == Ballot.NONTRANSFERABLE
@ || (isContinuingCandidateID (ballot.getCandidateID())
@ && \old(ballot.getCandidateID()) != ballot.getCandidateID());
@*/
public void transferBallot(final /*@ non_null @*/ Ballot ballot) {
while ((ballot.getCandidateID() != Ballot.NONTRANSFERABLE)
&& (!isContinuingCandidateID(ballot.getCandidateID()))) {
ballot.transfer();
}
/*@ assert ballot.getCandidateID() == Ballot.NONTRANSFERABLE
@ || isContinuingCandidateID (ballot.getCandidateID());
@*/
// TODO 2009.10.14 ESC postcondition
} //@ nowarn;
/**
* Main count algorithm.
*/
public abstract void count();
/**
* Elect this winning candidate.
*
* @param winner
* The candidate with enough votes to win
*/
//@ requires 0 <= winner && winner < totalCandidates;
//@ requires candidateList[winner].getStatus() == Candidate.CONTINUING;
//@ requires numberElected < seats;
//@ requires 0 < remainingSeats;
//@ requires candidates[winner] != null;
/*@ requires (hasQuota(candidateList[winner]))
@ || (winner == findHighestCandidate())
@ || (getNumberContinuing() == totalRemainingSeats);
@ requires candidates[winner].getCandidateID() != Candidate.NO_CANDIDATE;
@*/
//@ requires state == ElectionStatus.COUNTING;
//@ requires 0 < candidateList[winner].getCandidateID();
//@ assignable candidates, decisions, decisionsTaken, numberOfCandidatesElected;
//@ assignable totalRemainingSeats;
//@ assignable candidates[winner], candidates[winner].state;
//@ ensures isElected (candidateList[winner]);
//@ ensures 1 + \old(numberElected) == numberElected;
//@ ensures \old(getNumberContinuing()) == 1 + getNumberContinuing();
//@ ensures \old(remainingSeats) == 1 + remainingSeats;
public void electCandidate(final int winner) {
//@ assert candidates != null && candidates[winner] != null;
candidates[winner].declareElected();
// TODO 2009.10.14 ESC warning
makeDecision(DecisionStatus.DEEM_ELECTED, candidates[winner].getCandidateID()); //@ nowarn;
numberOfCandidatesElected++;
totalRemainingSeats
// TODO 2009.10.14 ESC precondition
} //@ nowarn;
/**
* Get the number of continuing candidates, neither elected nor eliminated
* yet.
*
* @return The number of continuing candidates.
*/
public/*@ pure @*/int getNumberContinuing() {
return totalNumberOfCandidates
- (numberOfCandidatesElected + numberOfCandidatesEliminated);
}
}
|
package eu.project.rapid.common;
/**
* Control Messages for client-server communication Message IDs up to 255 - one byte only, as they
* are sent over sockets using write()/read() - only one byte read/written.
*/
public class RapidMessages {
// Generic Messages
public static final int OK = 1;
public static final int ERROR = 0;
public static final int PING = 11;
public static final int PONG = 12;
// Communication Phone <-> Clone
public static final int AC_REGISTER_AS = 13;
public static final int AS_APP_PRESENT_AC = 14;
public static final int AS_APP_REQ_AC = 15;
public static final int AC_OFFLOAD_REQ_AS = 16;
// Communication Phone <-> Clone (for testing purposes)
public static final int SEND_INT = 17;
public static final int SEND_BYTES = 18;
public static final int RECEIVE_INT = 19;
public static final int RECEIVE_BYTES = 20;
// Communication Main Clone <-> Helper Clone
public static final int CLONE_ID_SEND = 21;
// Communication Phone/Clone <-> DS/Manager
public static final int PHONE_CONNECTION = 30;
public static final int CLONE_CONNECTION = 31;
public static final int MANAGER_CONNECTION = 32;
public static final int PHONE_AUTHENTICATION = 33;
public static final int AC_REGISTER_NEW_DS = 34;
public static final int AC_REGISTER_PREV_DS = 35;
public static final int AC_REGISTER_SLAM = 36;
public static final int AS_RM_REGISTER_DS = 37;
public static final int AS_RM_REGISTER_VMM = 38;
public static final int AS_RM_NOTIFY_VMM = 39;
public static final int CLONE_AUTHENTICATION = 40;
public static final int MANAGER_AUTHENTICATION = 41;
public static final int GET_ASSOCIATED_CLONE_INFO = 42;
public static final int GET_NEW_CLONE_INFO = 43;
public static final int GET_PORT = 44;
public static final int GET_SSL_PORT = 45;
public static final int DOWNLOAD_FILE = 146;
public static final int UPLOAD_FILE = 147;
public static final int UPLOAD_FILE_RESULT = 48;
public static final int DATA_RATE_THROTTLE = 49;
public static final int DATA_RATE_UNTHROTTLE = 50;
public static final int FORWARD_REQ = 51;
public static final int FORWARD_START = 52;
public static final int FORWARD_END = 53;
public static final int PARALLEL_REQ = 54;
public static final int PARALLEL_START = 55;
public static final int PARALLEL_END = 56;
// Communication SLAM <-> VMM
public static final int SLAM_START_VM_VMM = 60;
// Communication DS <-> VMM
public static final int VMM_REGISTER_DS = 70;
public static final int VMM_NOTIFY_DS = 71;
public static final int VM_REGISTER_DS = 72;
public static final int VM_NOTIFY_DS = 73;
public static final int HELPER_NOTIFY_DS = 74;
public static final int DS_VM_DEREGISTER_VMM = 75;
// Communication Phone <-> Registration Manager
public static final int AC_HELLO_AC_RM = 1;
// Messages to send to the demo server, which will create the animation
// of the events happening on the system
public static final String DS_UP = "DS_UP";
// The VMM is started, registers with the DS and starts two VMs
public static final String VMM_UP = "VMM_UP";
public static final String VMM_REGISTER_DS_MSG =
"VMM_REGISTER_DS"; /*
* name is changed from VMM_REGISTER_DS to VMM_REGISTER_DS_MSG to avoid
* name conflict
*/
public static final String VMM_REGISTER_DS_OK = "VMM_REGISTER_DS_OK";
public static final String VMM_START_TWO_VMS = "VMM_START_TWO_VMS";
public static final String VMM_VM1_STARTED = "VMM_VM1_STARTED";
public static final String VMM_VM2_STARTED = "VMM_VM2_STARTED";
// The Acceleration Client (AC) on the User Device (UD) registers
// as a NEW device with the DS and the VMM and asks for a VM
public static final String AC_REGISTER_DS_NEW = "AC_REGISTER_DS_NEW";
public static final String DS_FIND_AVAILABLE_VMM = "DS_FIND_AVAILABLE_VMM";
public static final String AC_REGISTER_DS_NEW_OK = "AC_REGISTER_DS_NEW_OK";
public static final String AC_REGISTER_VMM_NEW = "AC_REGISTER_VMM_NEW";
public static final String VMM_FIND_AVAILABLE_VM = "VMM_FIND_AVAILABLE_VM";
public static final String AC_REGISTER_VMM_NEW_OK = "AC_REGISTER_VMM_NEW_OK";
// The Acceleration Client (AC) on the User Device (UD) registers
// as a PREV device with the DS and the VMM and asks for a VM
public static final String AC_REGISTER_DS_PREV = "AC_REGISTER_DS_PREV";
public static final String DS_FIND_PREV_VMM = "DS_FIND_PREV_VMM";
public static final String AC_REGISTER_DS_PREV_OK = "AC_REGISTER_DS_PREV_OK";
public static final String AC_REGISTER_VMM_PREV = "AC_REGISTER_VMM_PREV";
public static final String VMM_FIND_PREV_VM = "VMM_FIND_PREV_VM";
public static final String AC_REGISTER_VMM_PREV_OK = "AC_REGISTER_VMM_PREV_OK";
// The Acceleration Client (AC) on the User Device (UD) registers with the
// AS on the VM
// The registration phase goes through, connection, RTT, bandwidth
// measurements, etc.
public static final String AC_REGISTER_VM = "AC_REGISTER_VM";
public static final String AC_CONNECT_VM = "AC_CONNECT_VM";
public static final String AC_SEND_APK = "AC_SEND_APK";
public static final String AC_RTT_MEASUREMENT = "AC_RTT_MEASUREMENT";
public static final String AC_DL_MEASUREMENT = "AC_DW_MEASUREMENT";
public static final String AC_UL_MEASUREMENT = "AC_UW_MEASUREMENT";
public static final String AC_REGISTER_VM_OK = "AC_REGISTER_VM_OK";
public static final String AC_DISCONNECT_VM = "AC_DISCONNECT_VM";
// The method is run locally
public static final String AC_DECISION_LOCAL = "AC_DECISION_LOCAL";
public static final String AC_PREPARE_DATA = "AC_PREPARE_DATA";
public static final String AC_EXEC_LOCAL = "AC_EXEC_LOCAL";
public static final String AC_FINISHED_LOCAL = "AC_FINISHED_LOCAL";
// The method is run remotely
public static final String AC_DECISION_REMOTE = "AC_DECISION_REMOTE";
public static final String AC_REMOTE_SEND_DATA = "AC_REMOTE_SEND_DATA";
public static final String AC_EXEC_REMOTE = "AC_EXEC_REMOTE";
public static final String AC_RESULT_REMOTE = "AC_RESULT_REMOTE";
public static final String AC_FINISHED_REMOTE = "AC_FINISHED_REMOTE";
}
|
package fitnesse.ant;
import org.apache.tools.ant.BuildException;
import org.apache.tools.ant.Project;
import org.apache.tools.ant.Task;
import org.apache.tools.ant.taskdefs.Execute;
import org.apache.tools.ant.taskdefs.LogStreamHandler;
import org.apache.tools.ant.types.CommandlineJava;
import org.apache.tools.ant.types.Path;
import org.apache.tools.ant.types.Reference;
import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import fitnesse.util.StringUtil;
/**
* Task to run fit tests. This task runs fitnesse tests and publishes the results.
* <p/>
* <pre>
* Usage:
* <taskdef name="execute-fitnesse-tests"
* classname="fitnesse.ant.ExecuteFitnesseTestsTask"
* classpathref="classpath" />
* OR
* <taskdef classpathref="classpath"
* resource="tasks.properties" />
* <p/>
* <execute-fitnesse-tests
* suitepage="FitNesse.SuiteAcceptanceTests"
* fitnesseport="8082"
* resultsdir="${results.dir}"
* resultshtmlpage="fit-results.html"
* classpathref="classpath" />
* </pre>
*/
public class ExecuteFitnesseTestsTask extends Task {
private String fitnesseHost = "localhost";
private int fitnessePort;
private String suitePage;
private String suiteFilter;
private String resultsDir = ".";
private String resultsHTMLPage;
private String resultsXMLPage;
private boolean debug = true;
private boolean verbose = true;
private boolean failOnError = true;
private String testRunnerClass = "fitnesse.runner.TestRunner";
private Path classpath;
private String resultProperty;
@Override
public void execute() throws BuildException {
try {
int exitCode = executeRunnerClassAsForked();
if (exitCode != 0) {
log("Finished executing FitNesse tests: " + exitCode + " failures/exceptions");
if (failOnError) {
throw new BuildException(exitCode + " FitNesse test failures/exceptions");
} else {
getProject().setNewProperty(resultProperty, String.valueOf(exitCode));
}
} else {
log("Fitnesse Tests executed successfully");
}
}
catch (Exception e) {
if (failOnError) {
throw new BuildException(
"Got an unexpected error trying to run the fitnesse tests : " + e.getMessage(), e);
} else {
e.printStackTrace();
}
}
}
private int executeRunnerClassAsForked() throws BuildException {
CommandlineJava cmd = initializeJavaCommand();
Execute execute = new Execute(new LogStreamHandler(this, Project.MSG_INFO, Project.MSG_WARN));
String[] commandLine = cmd.getCommandline();
System.out.printf("Executing: %s\n", StringUtil.join(Arrays.asList(commandLine), " "));
execute.setCommandline(commandLine);
execute.setNewenvironment(false);
execute.setAntRun(getProject());
log(cmd.describeCommand(), Project.MSG_VERBOSE);
int retVal;
try {
retVal = execute.execute();
}
catch (IOException e) {
throw new BuildException("Process fork failed.", e, getLocation());
}
return retVal;
}
private CommandlineJava initializeJavaCommand() {
CommandlineJava cmd = new CommandlineJava();
cmd.setClassname(testRunnerClass);
if (debug)
cmd.createArgument().setValue("-debug");
if (verbose)
cmd.createArgument().setValue("-v");
if (resultsHTMLPage != null) {
String resultsHTMLPagePath = new File(resultsDir, resultsHTMLPage).getAbsolutePath();
cmd.createArgument().setValue("-html");
cmd.createArgument().setValue(resultsHTMLPagePath);
}
if (resultsXMLPage != null) {
String resultsHTMLPagePath = new File(resultsDir, resultsXMLPage).getAbsolutePath();
cmd.createArgument().setValue("-xml");
cmd.createArgument().setValue(resultsHTMLPagePath);
}
if (suiteFilter != null) {
cmd.createArgument().setValue("-suiteFilter");
cmd.createArgument().setValue(suiteFilter);
}
cmd.createArgument().setValue(fitnesseHost);
cmd.createArgument().setValue(String.valueOf(fitnessePort));
cmd.createArgument().setValue(suitePage);
cmd.createClasspath(getProject()).createPath().append(classpath);
return cmd;
}
/**
* Host address on which Fitnesse is running. Defaults to 'localhost'.
*
* @param fitnesseHost
*/
public void setFitnesseHost(String fitnesseHost) {
this.fitnesseHost = fitnesseHost;
}
/**
* Classpath of the TestRunner class. <b>MUST SET</b>
*
* @param classpath
*/
public void setClasspath(Path classpath) {
this.classpath = classpath;
}
/**
* Name of the filter to be passed to TestRunner to specify a subset of tests to run.
*
* @param suiteFilter
*/
public void setSuiteFilter(String suiteFilter) {
this.suiteFilter = suiteFilter;
}
/**
* Debug mode. Defaults to 'true'.
*
* @param debug
*/
public void setDebug(boolean debug) {
this.debug = debug;
}
/**
* Will fail the build if any Fitnesse tests fail. Defaults to 'true'.
*
* @param failOnError
*/
public void setFailOnError(boolean failOnError) {
this.failOnError = failOnError;
}
/**
* Port on which fitnesse would run. <b>MUST SET.</b>.
*
* @param fitnessePort
*/
public void setFitnessePort(int fitnessePort) {
this.fitnessePort = fitnessePort;
}
/**
* Name of the property which will store the test results. Only valid if failOnError attribute is set to false.
*
* @param resultProperty
*/
public void setResultProperty(String resultProperty) {
this.resultProperty = resultProperty;
}
/**
* Path to the folder that will contain the fitnesse results page after execution. Only valid if resultsHTMLPage or
* resultsXMLPage attributes are set. Defaults to current directory.
*
* @param resultsDir
*/
public void setResultsDir(String resultsDir) {
this.resultsDir = resultsDir;
}
/**
* If set, stores the fitnesse results in HTML format under the resultsdir folder with the given name. The file name
* must have a '.html' extension.
*
* @param resultsHTMLPage
*/
public void setResultsHTMLPage(String resultsHTMLPage) {
this.resultsHTMLPage = resultsHTMLPage;
}
/**
* If set, stores the fitnesse results in XML format under the resultsdir folder with the given name. The file name
* must have a '.xml' extension.
*
* @param resultsXMLPage
*/
public void setResultsXMLPage(String resultsXMLPage) {
this.resultsXMLPage = resultsXMLPage;
}
/**
* Fully qualifies class name of the fitnesse testrunner class. Defaults to 'fitnesse.runner.TestRunner'.
*
* @param runnerClass
*/
public void setTestRunnerClass(String runnerClass) {
this.testRunnerClass = runnerClass;
}
/**
* Partial URL of the wiki page which is declared as a Suite. Ex: FrontPage.SmokeTest,
* FitNesse.SuiteAcceptanceTests, or FitNesse.AcceptanceTestsSuite. <b>MUST SET.</b>
*
* @param suitePage
*/
public void setSuitePage(String suitePage) {
this.suitePage = suitePage;
}
/**
* Set verbose mode. Defaults to 'true'.
*
* @param verbose
*/
public void setVerbose(boolean verbose) {
this.verbose = verbose;
}
public Path createClasspath() {
if (classpath == null) {
classpath = new Path(getProject());
}
return classpath.createPath();
}
public void setClasspathRef(Reference r) {
createClasspath().setRefid(r);
}
}
|
package foam.nanos.crunch;
import foam.core.FObject;
import foam.core.X;
import foam.dao.ArraySink;
import foam.dao.DAO;
import foam.mlang.predicate.Predicate;
import foam.nanos.auth.Subject;
import foam.nanos.auth.User;
import foam.nanos.crunch.lite.CapablePayload;
import foam.nanos.logger.Logger;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.Queue;
import static foam.mlang.MLang.*;
public class ServerCrunchService implements CrunchService {
public List getGrantPath(X x, String rootId) {
return getCapabilityPath(x, rootId, true);
}
public List getCapabilityPath(X x, String rootId, boolean filterGrantedUCJ) {
Logger logger = (Logger) x.get("logger");
foam.nanos.pm.PM pm = foam.nanos.pm.PM.create(x, this.getClass().getSimpleName(), "getCapabilityPath");
DAO prerequisiteDAO = (DAO) x.get("prerequisiteCapabilityJunctionDAO");
DAO capabilityDAO = (DAO) x.get("capabilityDAO");
// Lookup for indices of previously observed capabilities
List<String> alreadyListed = new ArrayList<String>();
// List of capabilities required to grant the desired capability.
// Throughout the traversial algorithm this list starts with parents of
// prerequisites appearing earlier in the list. Before returning, this
// list is reversed so that the caller receives capabilities in order of
// expected completion (i.e. pre-order traversial)
List grantPath = new ArrayList<>();
Queue<String> nextSources = new ArrayDeque<String>();
nextSources.add(rootId);
// Doing this instead of "this" could prevent unexpected behaviour
// in the incident CrunchService's getJunction method is decorated
CrunchService crunchService = (CrunchService) x.get("crunchService");
while ( nextSources.size() > 0 ) {
String sourceCapabilityId = nextSources.poll();
if ( filterGrantedUCJ ) {
UserCapabilityJunction ucj = crunchService.getJunction(x, sourceCapabilityId);
if ( ucj != null && ucj.getStatus() == CapabilityJunctionStatus.GRANTED ) {
continue;
}
}
if ( alreadyListed.contains(sourceCapabilityId) ) continue;
// Add capability to grant path, and remember index in case it's replaced
Capability cap = (Capability) capabilityDAO.find(sourceCapabilityId);
// Skip missing capability
if ( cap == null ) {
continue;
}
alreadyListed.add(sourceCapabilityId);
if ( cap instanceof MinMaxCapability && ! rootId.equals(sourceCapabilityId) ) {
List minMaxArray = new ArrayList<>();
// Manually grab the direct prereqs to the MinMaxCapability
List prereqs = ( (ArraySink) prerequisiteDAO
.where(AND(
EQ(CapabilityCapabilityJunction.SOURCE_ID, sourceCapabilityId),
NOT(IN(CapabilityCapabilityJunction.TARGET_ID, alreadyListed))
))
.select(new ArraySink()) ).getArray();
for ( int i = prereqs.size() - 1 ; i >= 0 ; i
CapabilityCapabilityJunction prereq = (CapabilityCapabilityJunction) prereqs.get(i);
var prereqGrantPath = this.getGrantPath(x, prereq.getTargetId());
// Essentially we reserve arrays to denote ANDs and ORs, must be at least 2 elements
if ( prereqGrantPath.size() > 1 ) minMaxArray.add(prereqGrantPath);
else minMaxArray.add(prereqGrantPath.get(0));
}
/**
Format of a min max for getGrantPath
[[prereqsChoiceA, choiceA], [prereqsChoiceB,choiceB], minMaxCapa]
*/
minMaxArray.add(cap);
/**
Format of a min max for getGrantPath as a prereq for another capability
[[[prereqsChoiceA, choiceA], [prereqsChoiceB,choiceB], minMaxCap],cap]
*/
grantPath.add(minMaxArray);
continue;
}
grantPath.add(cap);
// Enqueue prerequisites for adding to grant path
List prereqs = ( (ArraySink) prerequisiteDAO
.where(AND(
EQ(CapabilityCapabilityJunction.SOURCE_ID, sourceCapabilityId),
NOT(IN(CapabilityCapabilityJunction.TARGET_ID, alreadyListed))
))
.select(new ArraySink())).getArray();
for ( int i = prereqs.size() - 1 ; i >= 0 ; i
CapabilityCapabilityJunction prereq = (CapabilityCapabilityJunction) prereqs.get(i);
nextSources.add(prereq.getTargetId());
}
}
Collections.reverse(grantPath);
pm.log(x);
return grantPath;
}
// Return capability path for multiple prerequisites without duplicates.
public List getMultipleCapabilityPath(
X x, String[] capabilityIds, boolean filterGrantedUCJ
) {
Set alreadyListed = new HashSet<String>();
List multiplePath = new ArrayList();
for ( String capId : capabilityIds ) {
List crunchyPath = getCapabilityPath(x, capId, filterGrantedUCJ);
for ( Object obj : crunchyPath ) {
Capability cap = null;
if ( obj instanceof List ) {
List list = (List) obj;
cap = (Capability) list.get(list.size() - 1);
} else {
cap = (Capability) obj;
}
if ( alreadyListed.contains(cap.getId()) ) continue;
multiplePath.add(obj);
}
}
return multiplePath;
}
public UserCapabilityJunction getJunction(X x, String capabilityId) {
Subject subject = (Subject) x.get("subject");
return this.getJunctionForSubject(x, capabilityId, subject);
}
public UserCapabilityJunction getJunctionForSubject(
X x, String capabilityId, Subject subject
) {
User user = subject.getUser();
User realUser = subject.getRealUser();
Predicate acjPredicate = INSTANCE_OF(AgentCapabilityJunction.class);
Predicate targetPredicate = EQ(UserCapabilityJunction.TARGET_ID, capabilityId);
try {
DAO userCapabilityJunctionDAO = (DAO) x.get("userCapabilityJunctionDAO");
Predicate associationPredicate = OR(
AND(
NOT(acjPredicate),
( user != realUser )
? OR(
EQ(UserCapabilityJunction.SOURCE_ID, realUser.getId()),
EQ(UserCapabilityJunction.SOURCE_ID, user.getId())
)
: EQ(UserCapabilityJunction.SOURCE_ID, realUser.getId())
),
AND(
acjPredicate,
EQ(UserCapabilityJunction.SOURCE_ID, realUser.getId()),
EQ(AgentCapabilityJunction.EFFECTIVE_USER, user.getId())
)
);
UserCapabilityJunction ucj = (UserCapabilityJunction)
userCapabilityJunctionDAO.find(AND(associationPredicate,targetPredicate));
if ( ucj != null ) {
return ucj;
}
} catch ( Exception e ) {
Logger logger = (Logger) x.get("logger");
logger.error("getJunction", capabilityId, e);
}
return null;
}
public void updateJunction(X x, String capabilityId, FObject data) {
Subject subject = (Subject) x.get("subject");
UserCapabilityJunction ucj = this.getJunction(x, capabilityId);
if ( ucj == null ) {
// Need Capability to associate UCJ correctly
DAO capabilityDAO = (DAO) x.get("capabilityDAO");
Capability cap = (Capability) capabilityDAO.find(capabilityId);
if ( cap == null ) {
throw new RuntimeException(String.format(
"Capability with id '%s' not found", capabilityId
));
}
AssociatedEntity associatedEntity = cap.getAssociatedEntity();
boolean isAssociation = associatedEntity == AssociatedEntity.ACTING_USER;
User associatedUser = associatedEntity == AssociatedEntity.USER
? subject.getUser()
: subject.getRealUser()
;
ucj = isAssociation
? new AgentCapabilityJunction.Builder(x)
.setSourceId(associatedUser.getId())
.setTargetId(capabilityId)
.setEffectiveUser(subject.getUser().getId())
.build()
: new UserCapabilityJunction.Builder(x)
.setSourceId(associatedUser.getId())
.setTargetId(capabilityId)
.build()
;
}
if ( data != null ) {
ucj.setData(data);
}
DAO userCapabilityJunctionDAO = (DAO) x.get("userCapabilityJunctionDAO");
userCapabilityJunctionDAO.inX(x).put(ucj);
}
public void maybeIntercept(X x, String[] capabilityOptions) {
if ( capabilityOptions.length < 1 ) {
Logger logger = (Logger) x.get("logger");
logger.warning("crunchService.maybeIntercept() performed with empty list");
return;
}
// Check that at least one capability option is satisfied
boolean satisfied = false;
for ( String capId : capabilityOptions ) {
UserCapabilityJunction ucj = this.getJunction(x, capId);
if ( ucj != null && ucj.getStatus() == CapabilityJunctionStatus.GRANTED ) {
satisfied = true;
break;
}
}
// Throw a capability intercept if none were satisfied
if ( ! satisfied ) {
CapabilityRuntimeException ex = new CapabilityRuntimeException(
"Missing a required capability."
);
for ( String capId : capabilityOptions ) {
ex.addCapabilityId(capId);
}
throw ex;
}
}
public boolean isRenewable(X x, String capabilityId) {
DAO capabilityDAO = (DAO) x.get("capabilityDAO");
DAO prerequisitesDAO = ((DAO) x.get("prerequisiteCapabilityJunctionDAO")).where(EQ(CapabilityCapabilityJunction.SOURCE_ID, capabilityId));
CrunchService crunchService = (CrunchService) x.get("crunchService");
Capability capability = (Capability) capabilityDAO.find(capabilityId);
UserCapabilityJunction ucj = crunchService.getJunction(x, capabilityId);
if ( ! capability.getEnabled() ) return false;
List<CapabilityCapabilityJunction> ccJunctions = ((ArraySink) prerequisitesDAO.select(new ArraySink())).getArray();
boolean topLevelRenewable = ucj.getStatus() == CapabilityJunctionStatus.GRANTED && ucj.getIsRenewable();
if ( ccJunctions.size() == 0 || topLevelRenewable ) return topLevelRenewable;
for ( CapabilityCapabilityJunction ccJunction : ccJunctions ) {
if ( isRenewable(x, ccJunction.getTargetId()) ) return true;
}
return false;
}
public boolean maybeReopen(X x, String capabilityId) {
DAO capabilityDAO = (DAO) x.get("capabilityDAO");
DAO prerequisitesDAO = ((DAO) x.get("prerequisiteCapabilityJunctionDAO")).where(EQ(CapabilityCapabilityJunction.SOURCE_ID, capabilityId));
CrunchService crunchService = (CrunchService) x.get("crunchService");
Capability capability = (Capability) capabilityDAO.find(capabilityId);
UserCapabilityJunction ucj = crunchService.getJunction(x, capabilityId);
if ( ! capability.getEnabled() ) return false;
List<CapabilityCapabilityJunction> ccJunctions = ((ArraySink) prerequisitesDAO.select(new ArraySink())).getArray();
boolean shouldReopenTopLevel = shouldReopenUserCapabilityJunction(ucj);
if ( ccJunctions.size() == 0 || shouldReopenTopLevel ) return shouldReopenTopLevel;
for ( CapabilityCapabilityJunction ccJunction : ccJunctions ) {
if ( maybeReopen(x, ccJunction.getTargetId()) ) return true;
}
return false;
}
public boolean shouldReopenUserCapabilityJunction(UserCapabilityJunction ucj) {
if ( ucj == null ) return true;
else if ( ucj.getStatus() == CapabilityJunctionStatus.GRANTED && ucj.getIsRenewable() ) return true;
else if ( ucj.getStatus() != CapabilityJunctionStatus.GRANTED &&
ucj.getStatus() != CapabilityJunctionStatus.PENDING &&
ucj.getStatus() != CapabilityJunctionStatus.APPROVED ) return true;
return false;
}
public CapablePayload[] getCapableObjectPayloads(X x, String[] capabilityIds) {
List<CapablePayload> payloads = new ArrayList<>();
CrunchService crunchService = (CrunchService) x.get("crunchService");
List crunchPath = crunchService.getMultipleCapabilityPath(
x, capabilityIds, false);
for ( Object obj : crunchPath ) {
if ( ! (obj instanceof Capability) ) {
// Lists correspond to capabilityIds with their own prerequisite
// logic, such as MinMaxCapability. Clients will need to be
// made aware of these capabilities separately.
if ( obj instanceof List ) {
List list = (List) obj;
// Add payload object prerequisites
List prereqs = new ArrayList();
for ( int i = 0 ; i < list.size() - 1 ; i++ ) {
Capability prereqCap = (Capability) list.get(i);
list.add(new CapablePayload.Builder(x)
.setCapability(prereqCap)
.build());
}
// Add payload object
/* TODO: Figure out why this is an error when adding
support for MinMaxCapability
Capability cap = (Capability) list.get(list.size() - 1);
payloads.add(new CapablePayload.Builder(x)
.setCapability(cap)
.setPrerequisites(prereqs.toArray(
new CapablePayload[list.size()]))
.build());
*/
continue;
}
throw new RuntimeException(
"Expected capability or list");
}
Capability cap = (Capability) obj;
payloads.add(new CapablePayload.Builder(x)
.setCapability(cap)
.build());
}
// Re-FObjectArray
return payloads.toArray(new CapablePayload[payloads.size()]);
}
}
|
// Region.java
package loci.common;
public class Region {
// -- Fields --
public int x;
public int y;
public int width;
public int height;
// -- Constructor --
public Region() { }
public Region(int x, int y, int width, int height) {
this.x = x;
this.y = y;
this.width = width;
this.height = height;
}
// -- Region API methods --
/** Returns true if this region intersects the given region. */
public boolean intersects(Region r) {
int tw = this.width;
int th = this.height;
int rw = r.width;
int rh = r.height;
if (rw <= 0 || rh <= 0 || tw <= 0 || th <= 0) {
return false;
}
int tx = this.x;
int ty = this.y;
int rx = r.x;
int ry = r.y;
rw += rx;
rh += ry;
tw += tx;
th += ty;
boolean rtn = ((rw < rx || rw > tx) && (rh < ry || rh > ty) &&
(tw < tx || tw > rx) && (th < ty || th > ry));
return rtn;
}
/**
* Returns a Region representing the intersection of this Region with the
* given Region. If the two Regions do not intersect, the result is an
* empty Region.
*/
public Region intersection(Region r) {
int x = Math.max(this.x, r.x);
int y = Math.max(this.y, r.y);
int w = Math.min(this.x + this.width, r.x + r.width) - x;
int h = Math.min(this.y + this.height, r.y + r.height) - y;
if (w < 0) w = 0;
if (h < 0) h = 0;
return new Region(x, y, w, h);
}
/**
* Returns true if the point specified by the given X and Y coordinates
* is contained within this region.
*/
public boolean containsPoint(int xc, int yc) {
return intersects(new Region(xc, yc, 1, 1));
}
public String toString() {
return "x=" + x + ", y=" + y + ", w=" + width + ", h=" + height;
}
public boolean equals(Object o) {
if (!(o instanceof Region)) return false;
Region that = (Region) o;
return this.x == that.x && this.y == that.y && this.width == that.width &&
this.height == that.height;
}
}
|
package info.tregmine.database.db;
import java.math.BigInteger;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.EnumMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import org.bukkit.entity.Player;
import info.tregmine.Tregmine;
import info.tregmine.api.Badge;
import info.tregmine.api.Rank;
import info.tregmine.api.TregminePlayer;
import info.tregmine.api.TregminePlayer.Property;
import info.tregmine.database.DAOException;
import info.tregmine.database.IPlayerDAO;
public class DBPlayerDAO implements IPlayerDAO {
private Connection conn;
private Tregmine plugin;
public DBPlayerDAO(Connection conn) {
this.conn = conn;
}
public DBPlayerDAO(Connection conn, Tregmine instance) {
this.conn = conn;
this.plugin = instance;
}
@Override
public TregminePlayer createPlayer(Player wrap) throws DAOException {
String sql = "INSERT INTO player (player_uuid, player_name, player_rank, player_keywords) VALUE (?, ?, ?, ?)";
TregminePlayer player = new TregminePlayer(wrap, plugin);
player.setStoredUuid(player.getUniqueId());
try (PreparedStatement stmt = conn.prepareStatement(sql)) {
stmt.setString(1, player.getUniqueId().toString());
stmt.setString(2, player.getName());
stmt.setString(3, player.getTrueRank().toString());
stmt.setString(4, player.getRealName());
stmt.execute();
stmt.executeQuery("SELECT LAST_INSERT_ID()");
try (ResultSet rs = stmt.getResultSet()) {
if (!rs.next()) {
throw new DAOException("Failed to get player id", sql);
}
player.setId(rs.getInt(1));
}
} catch (SQLException e) {
throw new DAOException(sql, e);
}
return player;
}
@Override
public boolean doesIgnore(TregminePlayer player, TregminePlayer victim) throws DAOException {
String sql = "SELECT * FROM player " +
"WHERE player_id = ? ";
try (PreparedStatement stmt = conn.prepareStatement(sql)) {
stmt.setInt(1, player.getId());
stmt.execute();
try (ResultSet rs = stmt.getResultSet()) {
if(!rs.next()) return false;
String stringofignored = rs.getString("player_ignore");
if(stringofignored == null || stringofignored.length() == 0){
return false;
}
String[] strings = stringofignored.split(",");
List<String> playerignore = new ArrayList<String>();
for (String i : strings){
if("".equalsIgnoreCase(i)) continue;
playerignore.add(i);
}
if (playerignore.contains(victim.getRealName())) {
return true;
} else {
return false;
}
}
} catch (SQLException e) {
throw new DAOException(sql, e);
}
}
@Override
public Map<Badge, Integer> getBadges(TregminePlayer player) throws DAOException {
String sql = "SELECT * FROM player_badge " + "WHERE player_id = ?";
Map<Badge, Integer> badges = new EnumMap<Badge, Integer>(Badge.class);
try (PreparedStatement stmt = conn.prepareStatement(sql)) {
stmt.setInt(1, player.getId());
stmt.execute();
try (ResultSet rs = stmt.getResultSet()) {
while (rs.next()) {
Badge badge = Badge.fromString(rs.getString("badge_name"));
int lvl = rs.getInt("badge_level");
badges.put(badge, lvl);
}
}
} catch (SQLException e) {
throw new DAOException(sql, e);
}
return badges;
}
@Override
public List<String> getIgnored(TregminePlayer to) throws DAOException {
String sql = "SELECT * FROM player " + "WHERE player_id = ? ";
try (PreparedStatement stmt = conn.prepareStatement(sql)) {
stmt.setInt(1, to.getId());
stmt.execute();
try (ResultSet rs = stmt.getResultSet()) {
if (!rs.next())
return null;
String[] strings;
String stringofignored = rs.getString("player_ignore");
if (stringofignored == null) {
strings = new String[0];
} else {
strings = stringofignored.split(",");
}
List<String> playerignore = new ArrayList<String>();
for (String i : strings) {
if ("".equalsIgnoreCase(i))
continue;
playerignore.add(i);
}
return playerignore;
}
} catch (SQLException e) {
throw new DAOException(sql, e);
}
}
@Override
public List<String> getKeywords(TregminePlayer to) throws DAOException {
String sql = "SELECT * FROM player " + "WHERE player_id = ? ";
try (PreparedStatement stmt = conn.prepareStatement(sql)) {
stmt.setInt(1, to.getId());
stmt.execute();
try (ResultSet rs = stmt.getResultSet()) {
if (!rs.next())
return null;
String stringofkeywords = rs.getString("player_keywords");
String[] strings = stringofkeywords.split(",");
List<String> playerkeywords = new ArrayList<String>();
for (String i : strings) {
if ("".equalsIgnoreCase(i))
continue;
playerkeywords.add(i);
}
return playerkeywords;
}
} catch (SQLException e) {
throw new DAOException(sql, e);
}
}
@Override
public TregminePlayer getPlayer(int id) throws DAOException {
String sql = "SELECT * FROM player WHERE player_id = ?";
TregminePlayer player = null;
try (PreparedStatement stmt = conn.prepareStatement(sql)) {
stmt.setInt(1, id);
stmt.execute();
try (ResultSet rs = stmt.getResultSet()) {
if (!rs.next()) {
return null;
}
player = new TregminePlayer(UUID.fromString(rs.getString("player_uuid")), plugin, rs.getString("player_name"));
player.setId(rs.getInt("player_id"));
String uniqueIdStr = rs.getString("player_uuid");
if (uniqueIdStr != null) {
player.setStoredUuid(UUID.fromString(uniqueIdStr));
}
player.setPasswordHash(rs.getString("player_password"));
player.setRank(Rank.fromString(rs.getString("player_rank")));
// if(rs.getString("player_referralcode") == null){
// player.setReferralCode(generateReferralCode(player));
// }else{
// player.setReferralCode(rs.getString("player_referralcode"));
if (rs.getString("player_inventory") == null) {
player.setCurrentInventory("survival");
} else {
player.setCurrentInventory(rs.getString("player_inventory"));
}
int flags = rs.getInt("player_flags");
for (TregminePlayer.Flags flag : TregminePlayer.Flags.values()) {
if ((flags & (1 << flag.ordinal())) != 0) {
player.setFlag(flag);
}
}
}
} catch (SQLException e) {
throw new DAOException(sql, e);
}
loadSettings(player);
return player;
}
@Override
public TregminePlayer getPlayer(String username) throws DAOException {
String sql = "SELECT * FROM player WHERE player_name = ?";
TregminePlayer player = null;
try (PreparedStatement stmt = conn.prepareStatement(sql)) {
stmt.setString(1, username);
stmt.execute();
try (ResultSet rs = stmt.getResultSet()) {
if (!rs.next()) {
return null;
}
player = new TregminePlayer(UUID.fromString(rs.getString("player_uuid")), plugin, rs.getString("player_name"));
player.setId(rs.getInt("player_id"));
String uniqueIdStr = rs.getString("player_uuid");
if (uniqueIdStr != null) {
player.setStoredUuid(UUID.fromString(uniqueIdStr));
}
player.setPasswordHash(rs.getString("player_password"));
player.setRank(Rank.fromString(rs.getString("player_rank")));
// if(rs.getString("player_referralcode") == null){
// player.setReferralCode(generateReferralCode(player));
// }else{
// player.setReferralCode(rs.getString("player_referralcode"));
if (rs.getString("player_inventory") == null) {
player.setCurrentInventory("survival");
} else {
player.setCurrentInventory(rs.getString("player_inventory"));
}
int flags = rs.getInt("player_flags");
for (TregminePlayer.Flags flag : TregminePlayer.Flags.values()) {
if ((flags & (1 << flag.ordinal())) != 0) {
player.setFlag(flag);
}
}
}
} catch (SQLException e) {
throw new DAOException(sql, e);
}
loadSettings(player);
return player;
}
@Override
public TregminePlayer getPlayer(UUID id) throws DAOException {
String sql = "SELECT * FROM player WHERE player_uuid = ?";
TregminePlayer player = null;
try (PreparedStatement stmt = conn.prepareStatement(sql)) {
stmt.setString(1, id.toString());
stmt.execute();
try (ResultSet rs = stmt.getResultSet()) {
if (!rs.next()) {
return null;
}
player = new TregminePlayer(UUID.fromString(rs.getString("player_uuid")), plugin, rs.getString("player_name"));
player.setId(rs.getInt("player_id"));
String uniqueIdStr = rs.getString("player_uuid");
if (uniqueIdStr != null) {
player.setStoredUuid(UUID.fromString(uniqueIdStr));
}
player.setPasswordHash(rs.getString("player_password"));
player.setRank(Rank.fromString(rs.getString("player_rank")));
// if(rs.getString("player_referralcode") == null){
// player.setReferralCode(generateReferralCode(player));
// }else{
// player.setReferralCode(rs.getString("player_referralcode"));
if (rs.getString("player_inventory") == null) {
player.setCurrentInventory("survival");
} else {
player.setCurrentInventory(rs.getString("player_inventory"));
}
int flags = rs.getInt("player_flags");
for (TregminePlayer.Flags flag : TregminePlayer.Flags.values()) {
if ((flags & (1 << flag.ordinal())) != 0) {
player.setFlag(flag);
}
}
}
} catch (SQLException e) {
throw new DAOException(sql, e);
}
loadSettings(player);
return player;
}
@Override
public TregminePlayer getPlayer(Player wrap) throws DAOException {
String sql = "SELECT * FROM player WHERE player_uuid = ?";
String sql1 = "UPDATE `player` SET player_name = ? WHERE player_uuid = ?";
try (PreparedStatement stmt1 = conn.prepareStatement(sql1)) {
stmt1.setString(1, wrap.getName());
stmt1.setString(2, wrap.getUniqueId().toString());
stmt1.execute();
} catch (SQLException e1) {
e1.printStackTrace();
}
TregminePlayer player;
if (wrap != null) {
player = new TregminePlayer(wrap, plugin);
} else {
return null;
}
try (PreparedStatement stmt = conn.prepareStatement(sql)) {
stmt.setString(1, wrap.getUniqueId().toString());
stmt.execute();
try (ResultSet rs = stmt.getResultSet()) {
if (!rs.next()) {
return null;
}
if (rs.getString("player_name") != wrap.getName()) {
// Name change! Call 911!
}
UUID uniqueId = wrap.getUniqueId();
player.setId(rs.getInt("player_id"));
player.setStoredUuid(uniqueId);
player.setPasswordHash(rs.getString("player_password"));
player.setRank(Rank.fromString(rs.getString("player_rank")));
// if(rs.getString("player_referralcode") == null){
// player.setReferralCode(generateReferralCode(player));
// }else{
// player.setReferralCode(rs.getString("player_referralcode"));
if (rs.getString("player_inventory") == null) {
player.setCurrentInventory("survival");
} else {
player.setCurrentInventory(rs.getString("player_inventory"));
}
int flags = rs.getInt("player_flags");
for (TregminePlayer.Flags flag : TregminePlayer.Flags.values()) {
if ((flags & (1 << flag.ordinal())) != 0) {
player.setFlag(flag);
}
}
}
} catch (SQLException e) {
throw new DAOException(sql, e);
}
loadSettings(player);
loadReports(player);
return player;
}
private void loadReports(TregminePlayer player) throws DAOException {
String sql = "SELECT * FROM player_report WHERE subject_id = ?";
try (PreparedStatement stmt = conn.prepareStatement(sql)) {
stmt.setInt(1, player.getId());
stmt.execute();
try (ResultSet rs = stmt.getResultSet()) {
while (rs.next()) {
if ("softwarn".equals(rs.getString("report_action"))) {
player.setTotalSofts(player.getTotalSofts() + 1);
}
if ("hardwarn".equals(rs.getString("report_action"))) {
player.setTotalHards(player.getTotalHards() + 1);
}
if ("kick".equals(rs.getString("report_action"))) {
player.setTotalKicks(player.getTotalKicks() + 1);
}
if ("ban".equals(rs.getString("report_action"))) {
player.setTotalBans(player.getTotalBans() + 1);
}
}
}
} catch (SQLException e) {
e.printStackTrace();
}
}
private void loadSettings(TregminePlayer player) throws DAOException {
String sql = "SELECT * FROM player_property WHERE player_id = ?";
try (PreparedStatement stmt = conn.prepareStatement(sql)) {
stmt.setInt(1, player.getId());
stmt.execute();
try (ResultSet rs = stmt.getResultSet()) {
while (rs.next()) {
String key = rs.getString("property_key");
String value = rs.getString("property_value");
if ("keyword".equals(key)) {
player.setKeyword(value);
} else if ("guardian".equals(key)) {
player.setGuardianRank(Integer.parseInt(value));
} else if ("quitmessage".equals(key)) {
player.setQuitMessage(value);
} else if ("playtime".equals(key)) {
player.setPlayTime(Integer.parseInt(value));
} else if ("afkkick".equals(key)) {
player.setAfkKick(Boolean.valueOf(value));
} else if ("cursewarned".equals(key)) {
player.setCurseWarned(Boolean.valueOf(value));
} else if ("nick".equals(key)) {
player.setProperty(Property.NICKNAME);
player.setTemporaryChatName(player.getRank().getName(plugin) + value);
}
}
}
} catch (SQLException e) {
throw new DAOException(sql, e);
}
}
// public String generateReferralCode(TregminePlayer source) throws DAOException {
// //Generate a six-character securely randomized string, to be used as a referral code.
// String referralCode = new BigInteger(130, this.plugin.getSecureRandom()).toString(32).substring(0, 6);
// String sql = "UPDATE player SET player_referralcode = ? WHERE player_id = ?";
// try(PreparedStatement stmt = conn.prepareStatement(sql)){
// stmt.setString(1, referralCode);
// stmt.setInt(2, source.getId());
// stmt.execute();
// }catch(SQLException e){
// throw new DAOException(sql, e);
// return referralCode;
@Override
public void updateBadges(TregminePlayer player) throws DAOException {
Map<Badge, Integer> dbBadges = player.getBadges();
Map<Badge, Integer> memBadges = getBadges(player);
Map<Badge, Integer> added = new EnumMap<Badge, Integer>(Badge.class);
Map<Badge, Integer> changed = new EnumMap<Badge, Integer>(Badge.class);
for (Map.Entry<Badge, Integer> entry : memBadges.entrySet()) {
if (dbBadges.containsKey(entry.getKey()) && dbBadges.get(entry.getKey()) != entry.getValue()) {
changed.put(entry.getKey(), entry.getValue());
} else if (!dbBadges.containsKey(entry.getKey())) {
added.put(entry.getKey(), entry.getValue());
}
}
Map<Badge, Integer> deleted = new EnumMap<Badge, Integer>(Badge.class);
for (Map.Entry<Badge, Integer> entry : dbBadges.entrySet()) {
if (!memBadges.containsKey(entry.getKey())) {
deleted.put(entry.getKey(), entry.getValue());
}
}
String sqlInsert = "INSERT INTO player_badge (player_id, badge_name, " + "badge_level, badge_timestamp) ";
sqlInsert += "VALUES (?, ?, ?, unix_timestamp())";
try (PreparedStatement stmt = conn.prepareStatement(sqlInsert)) {
for (Map.Entry<Badge, Integer> entry : added.entrySet()) {
stmt.setInt(1, player.getId());
stmt.setString(2, entry.getKey().toString());
stmt.setInt(3, entry.getValue());
stmt.execute();
}
} catch (SQLException e) {
throw new DAOException(sqlInsert, e);
}
String sqlUpdate = "UPDATE player_badge SET badge_level = ? " + "WHERE player_id = ? AND badge_name = ?";
try (PreparedStatement stmt = conn.prepareStatement(sqlUpdate)) {
for (Map.Entry<Badge, Integer> entry : changed.entrySet()) {
stmt.setInt(1, entry.getValue());
stmt.setInt(2, player.getId());
stmt.setString(3, entry.getKey().toString());
stmt.execute();
}
} catch (SQLException e) {
throw new DAOException(sqlUpdate, e);
}
String sqlDelete = "DELETE FROM player_badge " + "WHERE player_id = ? AND badge_name = ?";
try (PreparedStatement stmt = conn.prepareStatement(sqlDelete)) {
for (Map.Entry<Badge, Integer> entry : deleted.entrySet()) {
stmt.setInt(1, player.getId());
stmt.setString(2, entry.getKey().toString());
stmt.execute();
}
} catch (SQLException e) {
throw new DAOException(sqlDelete, e);
}
}
@Override
public void updateIgnore(TregminePlayer player, List<String> update) throws DAOException {
String sql = "UPDATE player SET player_ignore = ? " + "WHERE player_id = ?";
StringBuilder buffer = new StringBuilder();
String delim = "";
for (String ignored : update) {
buffer.append(delim);
buffer.append(ignored);
delim = ",";
}
String updateIgnoreString = buffer.toString();
try (PreparedStatement stmt = conn.prepareStatement(sql)) {
stmt.setString(1, updateIgnoreString);
stmt.setInt(2, player.getId());
stmt.execute();
} catch (SQLException e) {
throw new DAOException(sql, e);
}
}
@Override
public void updateKeywords(TregminePlayer player, List<String> update) throws DAOException {
String sql = "UPDATE player SET player_keywords = ? " + "WHERE player_id = ?";
StringBuilder buffer = new StringBuilder();
String delim = "";
for (String keyword : update) {
buffer.append(delim);
buffer.append(keyword);
delim = ",";
}
String keywordsString = buffer.toString();
try (PreparedStatement stmt = conn.prepareStatement(sql)) {
stmt.setString(1, keywordsString);
stmt.setInt(2, player.getId());
stmt.execute();
} catch (SQLException e) {
throw new DAOException(sql, e);
}
}
@Override
public void updatePlayer(TregminePlayer player) throws DAOException {
String sql = "UPDATE player SET player_uuid = ?, player_password = ?, "
+ "player_rank = ?, player_flags = ?, player_inventory = ? ";
sql += "WHERE player_id = ?";
int flags = 0;
for (TregminePlayer.Flags flag : TregminePlayer.Flags.values()) {
flags |= player.hasFlag(flag) ? 1 << flag.ordinal() : 0;
}
try (PreparedStatement stmt = conn.prepareStatement(sql)) {
stmt.setString(1, player.getStoredUuid().toString());
stmt.setString(2, player.getPasswordHash());
stmt.setString(3, player.getRank().toString());
stmt.setInt(4, flags);
stmt.setString(5, player.getCurrentInventory());
stmt.setInt(6, player.getId());
stmt.execute();
} catch (SQLException e) {
throw new DAOException(sql, e);
}
}
@Override
public void updatePlayerInfo(TregminePlayer player) throws DAOException {
updateProperty(player, "quitmessage", player.getQuitMessage());
}
@Override
public void updatePlayerKeyword(TregminePlayer player) throws DAOException {
updateProperty(player, "keyword", player.getKeyword());
}
@Override
public void updatePlayTime(TregminePlayer player) throws DAOException {
int playTime = player.getPlayTime() + player.getTimeOnline();
updateProperty(player, "playtime", String.valueOf(playTime));
}
private void updateProperty(TregminePlayer player, String key, boolean value) throws DAOException {
updateProperty(player, key, String.valueOf(value));
}
private void updateProperty(TregminePlayer player, String key, int value) throws DAOException {
updateProperty(player, key, String.valueOf(value));
}
@Override
public void updateProperty(TregminePlayer player, String key, String value) throws DAOException {
String sqlInsert = "REPLACE INTO player_property (player_id, "
+ "property_key, property_value) VALUE (?, ?, ?)";
if (value == null) {
return;
}
try (PreparedStatement stmt = conn.prepareStatement(sqlInsert)) {
stmt.setInt(1, player.getId());
stmt.setString(2, key);
stmt.setString(3, value);
stmt.execute();
} catch (SQLException e) {
throw new DAOException(sqlInsert, e);
}
}
}
|
package org.jaxen.expr;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import org.jaxen.Context;
import org.jaxen.ContextSupport;
import org.jaxen.JaxenException;
import org.jaxen.function.BooleanFunction;
public class PredicateSet implements Serializable
{
private List predicates;
public PredicateSet()
{
this.predicates = Collections.EMPTY_LIST;
}
public void addPredicate(Predicate predicate)
{
if ( this.predicates == Collections.EMPTY_LIST )
{
this.predicates = new ArrayList();
}
this.predicates.add( predicate );
}
public List getPredicates()
{
return this.predicates;
}
public void simplify()
{
Iterator predIter = this.predicates.iterator();
Predicate eachPred = null;
while ( predIter.hasNext() )
{
eachPred = (Predicate) predIter.next();
eachPred.simplify();
}
}
public String getText()
{
StringBuffer buf = new StringBuffer();
Iterator predIter = this.predicates.iterator();
Predicate eachPred = null;
while ( predIter.hasNext() )
{
eachPred = (Predicate) predIter.next();
buf.append( eachPred.getText() );
}
return buf.toString();
}
// FIXME: Note - this could be *MUCH* more efficient
// currently this creates many redundant collections and should halt
// evaluation on the first matching item.
protected boolean evaluateAsBoolean(List contextNodeSet,
ContextSupport support) throws JaxenException
{
List result = evaluatePredicates( contextNodeSet, support );
return ! result.isEmpty();
}
protected List evaluatePredicates(List contextNodeSet, ContextSupport support)
throws JaxenException {
// Easy way out (necessary)
if (predicates.size() == 0) {
return contextNodeSet;
}
Iterator predIter = predicates.iterator();
// initial list to filter
List nodes2Filter = contextNodeSet;
// apply all predicates
while(predIter.hasNext()) {
nodes2Filter =
applyPredicate((Predicate)predIter.next(), nodes2Filter, support);
}
return nodes2Filter;
}
public List applyPredicate(Predicate predicate, List nodes2Filter, ContextSupport support)
throws JaxenException {
final int nodes2FilterSize = nodes2Filter.size();
List filteredNodes = new ArrayList(nodes2FilterSize);
// Set up a dummy context with a list to hold each node
Context predContext = new Context(support);
List tempList = new ArrayList(1);
predContext.setNodeSet(tempList);
// loop through the current nodes to filter and add to the
// filtered nodes list if the predicate succeeds
for (int i = 0; i < nodes2FilterSize; ++i) {
Object contextNode = nodes2Filter.get(i);
tempList.clear();
tempList.add(contextNode);
predContext.setNodeSet(tempList);
predContext.setPosition(i + 1);
predContext.setSize(nodes2FilterSize);
Object predResult = predicate.evaluate(predContext);
if (predResult instanceof Number) {
// Here we assume nodes are in forward or reverse order
// as appropriate for axis
int proximity = ((Number) predResult).intValue();
if (proximity == (i + 1)) {
filteredNodes.add(contextNode);
}
}
else {
Boolean includes =
BooleanFunction.evaluate(predResult,
predContext.getNavigator());
if (includes.booleanValue()) {
filteredNodes.add(contextNode);
}
}
}
return filteredNodes;
}
}
|
package org.apache.velocity.app;
import java.io.Writer;
import java.util.Hashtable;
import java.util.Properties;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.io.IOException;
import java.io.Reader;
import java.io.BufferedReader;
import java.io.StringReader;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import org.apache.velocity.context.Context;
import org.apache.velocity.Template;
import org.apache.velocity.context.InternalContextAdapterImpl;
import org.apache.velocity.runtime.Runtime;
import org.apache.velocity.runtime.RuntimeConstants;
import org.apache.velocity.runtime.configuration.Configuration;
import org.apache.velocity.runtime.parser.ParserTreeConstants;
import org.apache.velocity.runtime.parser.node.SimpleNode;
import org.apache.velocity.runtime.directive.VelocimacroProxy;
import org.apache.velocity.exception.ResourceNotFoundException;
import org.apache.velocity.exception.ParseErrorException;
import org.apache.velocity.exception.MethodInvocationException;
import org.apache.velocity.runtime.parser.ParseException;
/**
* This class provides services to the application
* developer, such as :
* <ul>
* <li> Simple Velocity Runtime engine initialization methods.
* <li> Functions to apply the template engine to streams and strings
* to allow embedding and dynamic template generation.
* <li> Methods to access Velocimacros directly.
* </ul>
*
* <br><br>
* While the most common way to use Velocity is via templates, as
* Velocity is a general-purpose template engine, there are other
* uses that Velocity is well suited for, such as processing dynamically
* created templates, or processing content streams.
*
* <br><br>
* The methods herein were developed to allow easy access to the Velocity
* facilities without direct spelunking of the internals. If there is
* something you feel is necessary to add here, please, send a patch.
*
* @author <a href="mailto:geirm@optonline.net">Geir Magnusson Jr.</a>
* @author <a href="Christoph.Reck@dlr.de">Christoph Reck</a>
* @author <a href="jvanzyl@apache.org">Jason van Zyl</a>
* @version $Id: Velocity.java,v 1.15 2001/04/27 15:21:08 geirm Exp $
*/
public class Velocity implements RuntimeConstants
{
/**
* initialize the Velocity runtime engine, using the default
* properties of the Velocity distribution
*
* @return true if successful, false otherwise
*/
public static void init()
throws Exception
{
Runtime.init();
}
/**
* initialize the Velocity runtime engine, using default properties
* plus the properties in the properties file passed in as the arg
*
* @param propsFilename file containing properties to use to initialize
* the Velocity runtime
*
* @return true if successful, false otherwise. Check runtime log if
* false
*/
public static void init( String propsFilename )
throws Exception
{
Runtime.init(propsFilename);
}
/**
* initialize the Velocity runtime engine, using default properties
* plus the properties in the passed in java.util.Properties object
*
* @param p Proprties object containing initialization properties
*
* @return true if successful, false otherwise
*/
public static void init( Properties p )
throws Exception
{
Runtime.init( p );
}
/**
* Set a Velocity Runtime property.
*
* @param String key
* @param Object value
*/
public static void setProperty(String key, Object value)
{
Runtime.setProperty(key,value);
}
/**
* Add a Velocity Runtime property.
*
* @param String key
* @param Object value
*/
public static void addProperty(String key, Object value)
{
Runtime.addProperty(key,value);
}
/**
* Clear a Velocity Runtime property.
*
* @param key of property to clear
*/
public static void clearProperty(String key)
{
Runtime.clearProperty(key);
}
/**
* Set an entire configuration at once. This is
* useful in cases where the parent application uses
* the Configuration class and the velocity configuration
* is a subset of the parent application's configuration.
*
* @param Configuration configuration
*/
public static void setConfiguration(Configuration configuration)
{
Runtime.setConfiguration(configuration);
}
/**
* Get a Velocity Runtime property.
*
* @param key property to retrieve
* @return property value or null if the property
* not currently set
*/
public static Object getProperty( String key )
{
return Runtime.getProperty( key );
}
/**
* renders the input string using the context into the output writer.
* To be used when a template is dynamically constructed, or want to use
* Velocity as a token replacer.
*
* @param context context to use in rendering input string
* @param out Writer in which to render the output
* @param logTag string to be used as the template name for log
* messages in case of error
* @param instring input string containing the VTL to be rendered
*
* @return true if successful, false otherwise. If false, see
* Velocity runtime log
*/
public static boolean evaluate( Context context, Writer out,
String logTag, String instring )
throws ParseErrorException, MethodInvocationException, IOException
{
return evaluate( context, out, logTag, new BufferedReader( new StringReader( instring )) );
}
/**
* Renders the input stream using the context into the output writer.
* To be used when a template is dynamically constructed, or want to
* use Velocity as a token replacer.
*
* @param context context to use in rendering input string
* @param out Writer in which to render the output
* @param logTag string to be used as the template name for log messages
* in case of error
* @param instream input stream containing the VTL to be rendered
*
* @return true if successful, false otherwise. If false, see
* Velocity runtime log
* @deprecated Use
* {@link #evaluate( Context context, Writer writer,
* String logTag, Reader reader ) }
*/
public static boolean evaluate( Context context, Writer writer,
String logTag, InputStream instream )
throws ParseErrorException, MethodInvocationException, IOException
{
/*
* first, parse - convert ParseException if thrown
*/
BufferedReader br = null;
String encoding = null;
try
{
encoding = Runtime.getString(INPUT_ENCODING,ENCODING_DEFAULT);
br = new BufferedReader( new InputStreamReader( instream, encoding));
}
catch( UnsupportedEncodingException uce )
{
String msg = "Unsupported input encoding : " + encoding
+ " for template " + logTag;
throw new ParseErrorException( msg );
}
return evaluate( context, writer, logTag, br );
}
/**
* Renders the input reader using the context into the output writer.
* To be used when a template is dynamically constructed, or want to
* use Velocity as a token replacer.
*
* @param context context to use in rendering input string
* @param out Writer in which to render the output
* @param logTag string to be used as the template name for log messages
* in case of error
* @param reader Reader containing the VTL to be rendered
*
* @return true if successful, false otherwise. If false, see
* Velocity runtime log
*/
public static boolean evaluate( Context context, Writer writer,
String logTag, Reader reader )
throws ParseErrorException, MethodInvocationException, IOException
{
SimpleNode nodeTree = null;
try
{
nodeTree = Runtime.parse( reader, logTag );
}
catch ( ParseException pex )
{
throw new ParseErrorException( pex.getMessage() );
}
/*
* now we want to init and render
*/
if (nodeTree != null)
{
InternalContextAdapterImpl ica =
new InternalContextAdapterImpl( context );
ica.pushCurrentTemplateName( logTag );
try
{
try
{
nodeTree.init( ica, null );
}
catch( Exception e )
{
Runtime.error("Velocity.evaluate() : init exception for tag = "
+ logTag + " : " + e );
}
/*
* now render, and let any exceptions fly
*/
nodeTree.render( ica, writer );
}
finally
{
ica.popCurrentTemplateName();
}
return true;
}
return false;
}
/**
* Invokes a currently registered Velocimacro with the parms provided
* and places the rendered stream into the writer.
*
* Note : currently only accepts args to the VM if they are in the context.
*
* @param vmName name of Velocimacro to call
* @param params[] args used to invoke Velocimacro. In context key format :
* eg "foo","bar" (rather than "$foo","$bar")
* @param context Context object containing data/objects used for rendering.
* @param writer Writer for output stream
* @return true if Velocimacro exists and successfully invoked, false otherwise.
*/
public static boolean invokeVelocimacro( String vmName, String namespace,
String params[], Context context,
Writer writer )
{
/*
* check parms
*/
if ( vmName == null || params == null || context == null
|| writer == null || namespace == null)
{
Runtime.error( "Velocity.invokeVelocimacro() : invalid parameter");
return false;
}
/*
* does the VM exist?
*/
if (!Runtime.isVelocimacro( vmName, namespace ))
{
Runtime.error( "Velocity.invokeVelocimacro() : VM '"+ vmName
+ "' not registered.");
return false;
}
/*
* apparently. Ok, make one..
*/
VelocimacroProxy vp =
(VelocimacroProxy) Runtime.getVelocimacro( vmName, namespace );
if ( vp == null )
{
Runtime.error( "Velocity.invokeVelocimacro() : VM '"
+ vmName
+ "' : severe error. Unable to get VM from factory.");
return false;
}
/*
* if we get enough args?
*/
if ( vp.getNumArgs() > params.length )
{
Runtime.error( "Velocity.invokeVelocimacro() : VM '"
+ vmName + "' : invalid # of args. Needed "
+ vp.getNumArgs()
+ " but called with " + params.length);
return false;
}
/*
* ok. setup the vm
*/
/*
* fix the parms : since we don't require the $ from the caller,
* we need to add it
*/
int [] types = new int[vp.getNumArgs()];
String[] p = new String[vp.getNumArgs()];
for( int i = 0; i < types.length; i++)
{
types[i] = ParserTreeConstants.JJTREFERENCE;
p[i] = "$" + params[i];
}
vp.setupMacro( p, types );
try
{
InternalContextAdapterImpl ica
= new InternalContextAdapterImpl( context );
try
{
ica.pushCurrentTemplateName( namespace );
vp.render( ica, writer, null);
}
finally
{
ica.popCurrentTemplateName();
}
}
catch (Exception e )
{
Runtime.error("Velocity.invokeVelocimacro() : " + e );
return false;
}
return true;
}
/**
* merges a template and puts the rendered stream into the writer
*
* @param templateName name of template to be used in merge
* @param context filled context to be used in merge
* @param writer writer to write template into
*
* @return true if successful, false otherwise. Errors
* logged to velocity log.
* * @deprecated Use
* {@link #mergeTemplate( String templateName, String encoding,
* Context context, Writer writer )}
*/
public static boolean mergeTemplate( String templateName,
Context context, Writer writer )
throws ResourceNotFoundException, ParseErrorException, MethodInvocationException, Exception
{
return mergeTemplate( templateName, Runtime.getString(INPUT_ENCODING,ENCODING_DEFAULT),
context, writer );
}
/**
* merges a template and puts the rendered stream into the writer
*
* @param templateName name of template to be used in merge
* @param encoding encoding used in template
* @param context filled context to be used in merge
* @param writer writer to write template into
*
* @return true if successful, false otherwise. Errors
* logged to velocity log
*/
public static boolean mergeTemplate( String templateName, String encoding,
Context context, Writer writer )
throws ResourceNotFoundException, ParseErrorException, MethodInvocationException, Exception
{
Template template = Runtime.getTemplate(templateName, encoding);
if ( template == null )
{
Runtime.error("Velocity.parseTemplate() failed loading template '"
+ templateName + "'" );
return false;
}
else
{
template.merge(context, writer);
return true;
}
}
/**
* Returns a <code>Template</code> from the Velocity
* resource management system.
*
* @param name The file name of the desired template.
* @return The template.
* @throws ResourceNotFoundException if template not found
* from any available source.
* @throws ParseErrorException if template cannot be parsed due
* to syntax (or other) error.
* @throws Exception if an error occurs in template initialization
*/
public static Template getTemplate(String name)
throws ResourceNotFoundException, ParseErrorException, Exception
{
return Runtime.getTemplate( name );
}
/**
* Returns a <code>Template</code> from the Velocity
* resource management system.
*
* @param name The file name of the desired template.
* @param encoding The character encoding to use for the template.
* @return The template.
* @throws ResourceNotFoundException if template not found
* from any available source.
* @throws ParseErrorException if template cannot be parsed due
* to syntax (or other) error.
* @throws Exception if an error occurs in template initialization
*/
public static Template getTemplate(String name, String encoding)
throws ResourceNotFoundException, ParseErrorException, Exception
{
return Runtime.getTemplate( name, encoding );
}
/**
* Determines if a template is accessable via the currently
* configured resource loaders.
* <br><br>
* Note that the current implementation will <b>not</b>
* change the state of the system in any real way - so this
* cannot be used to pre-load the resource cache, as the
* previous implementation did as a side-effect.
* <br><br>
* The previous implementation exhibited extreme lazyness and
* sloth, and the author has been flogged.
*
* @param templateName name of the temlpate to search for
* @return true if found, false otherwise
*/
public static boolean templateExists( String templateName )
{
String loader = Runtime.getLoaderNameForResource( templateName );
if ( loader != null)
{
return true;
}
return false;
}
}
|
package org.concord.otrunk.view;
import java.awt.AWTEvent;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Frame;
import java.awt.KeyEventDispatcher;
import java.awt.KeyboardFocusManager;
import java.awt.Toolkit;
import java.awt.event.AWTEventListener;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.MouseEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Hashtable;
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JCheckBoxMenuItem;
import javax.swing.JComponent;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JSplitPane;
import javax.swing.JTabbedPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.JTree;
import javax.swing.SwingUtilities;
import javax.swing.WindowConstants;
import javax.swing.border.EmptyBorder;
import javax.swing.event.TreeSelectionEvent;
import javax.swing.event.TreeSelectionListener;
import javax.swing.tree.TreePath;
import org.concord.applesupport.AppleApplicationAdapter;
import org.concord.applesupport.AppleApplicationUtil;
import org.concord.framework.otrunk.OTChangeEvent;
import org.concord.framework.otrunk.OTChangeListener;
import org.concord.framework.otrunk.OTID;
import org.concord.framework.otrunk.OTObject;
import org.concord.framework.otrunk.OTObjectService;
import org.concord.framework.otrunk.OTrunk;
import org.concord.framework.otrunk.view.OTExternalAppService;
import org.concord.framework.otrunk.view.OTFrameManager;
import org.concord.framework.otrunk.view.OTJComponentServiceFactory;
import org.concord.framework.otrunk.view.OTViewContainer;
import org.concord.framework.otrunk.view.OTViewContainerListener;
import org.concord.framework.otrunk.view.OTViewContext;
import org.concord.framework.otrunk.view.OTViewFactory;
import org.concord.framework.text.UserMessageHandler;
import org.concord.framework.util.SimpleTreeNode;
import org.concord.otrunk.OTMLToXHTMLConverter;
import org.concord.otrunk.OTObjectServiceImpl;
import org.concord.otrunk.OTStateRoot;
import org.concord.otrunk.OTSystem;
import org.concord.otrunk.OTrunkImpl;
import org.concord.otrunk.datamodel.OTDataObject;
import org.concord.otrunk.datamodel.OTDatabase;
import org.concord.otrunk.user.OTUserObject;
import org.concord.otrunk.xml.ExporterJDOM;
import org.concord.otrunk.xml.XMLDatabase;
import org.concord.swing.CustomDialog;
import org.concord.swing.MostRecentFileDialog;
import org.concord.swing.StreamRecord;
import org.concord.swing.StreamRecordView;
import org.concord.swing.util.Util;
import org.concord.view.SimpleTreeModel;
import org.concord.view.SwingUserMessageHandler;
/**
* OTViewer Class name and description
*
* Date created: Dec 14, 2004
*
* @author scott
* <p>
*
*/
public class OTViewer extends JFrame
implements TreeSelectionListener, OTViewContainerListener,
AppleApplicationAdapter
{
/**
* first version of this class
*/
private static final long serialVersionUID = 1L;
public final static String TITLE_PROP = "otrunk.view.frame_title";
public final static String HIDE_TREE_PROP = "otrunk.view.hide_tree";
public final static String SHOW_CONSOLE_PROP = "otrunk.view.show_console";
public final static String HTTP_PUT = "PUT";
public final static String HTTP_POST = "POST";
private static OTrunkImpl otrunk;
private static OTViewFactory otViewFactory;
protected int userMode = OTViewerHelper.NO_USER_MODE;
OTUserObject currentUser = null;
URL currentURL = null;
String baseFrameTitle = "OTrunk Viewer";
OTViewContainerPanel bodyPanel;
OTFrameManagerImpl frameManager;
JTree folderTreeArea;
SimpleTreeModel folderTreeModel;
JTree dataTreeArea;
SimpleTreeModel dataTreeModel;
JSplitPane splitPane;
JFrame consoleFrame;
// Temp, to close the window
AbstractAction exitAction;
AbstractAction saveAsAction;
JMenuBar menuBar;
XMLDatabase xmlDB;
XMLDatabase userDataDB;
File currentAuthoredFile = null;
File currentUserFile = null;
Hashtable otContainers = new Hashtable();
String startupMessage = "";
boolean justStarted = false;
boolean showTree = false;
URL remoteURL;
private AbstractAction saveUserDataAsAction;
private AbstractAction saveUserDataAction;
private AbstractAction debugAction;
private AbstractAction showConsoleAction;
private AbstractAction newUserDataAction;
private AbstractAction loadUserDataAction;
private AbstractAction loadAction;
private AbstractAction reloadWindowAction;
private AbstractAction saveAction;
private AbstractAction saveRemoteAsAction;
private AbstractAction exportImageAction;
private AbstractAction exportHiResImageAction;
private AbstractAction exportToHtmlAction;
private JDialog commDialog;
/**
* This is true if the user was asked about saving user data after they
* initiated a close of the current view.
*/
private boolean askedAboutSavingUserData = false;
/**
* This is true if the user was asked about saving the user data, and said
* yes
*/
private boolean needToSaveUserData = false;
private boolean useScrollPane;
private OTChangeListener systemChangeListener;
private OTSystem userSystem;
public static void setOTViewFactory(OTViewFactory factory)
{
otViewFactory = factory;
}
public OTViewer()
{
super();
this.showTree = true;
AppleApplicationUtil.registerWithMacOSX(this);
try {
// this overrides the default base frame title
String title = System.getProperty(TITLE_PROP, null);
if (title != null) {
baseFrameTitle = title;
}
} catch (Throwable t) {
// do nothing, just use the default title
}
setTitle(baseFrameTitle);
setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE);
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e)
{
exitAction.actionPerformed(null);
}
});
consoleFrame = new JFrame("Console");
StreamRecord record = new StreamRecord(10000);
StreamRecordView view = new StreamRecordView(record);
consoleFrame.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
System.setOut((PrintStream) view.addOutputStream(System.out, "Console"));
System.setErr((PrintStream) view.addOutputStream(System.err, System.out));
consoleFrame.getContentPane().add(view);
consoleFrame.setSize(800, 600);
if (Boolean.getBoolean(SHOW_CONSOLE_PROP)){
consoleFrame.setVisible(true);
}
commDialog = new JDialog(this, true);
// for debugging
// add a breakpoint below, run in debugging mode, and then hit Meta-B
// the object you're currently focused on will be passed in here and you can
// start exploring the data structures, etc.
KeyboardFocusManager focusManager = KeyboardFocusManager.getCurrentKeyboardFocusManager();
KeyEventDispatcher deleteDispatcher = new KeyEventDispatcher(){
public boolean dispatchKeyEvent(KeyEvent e) {
if ( (e.getID() == java.awt.event.KeyEvent.KEY_RELEASED) &&
((e.getModifiersEx() & java.awt.event.InputEvent.META_DOWN_MASK) != 0) &&
(e.getKeyCode() == java.awt.event.KeyEvent.VK_B) ) {
Object o = e.getSource();
System.out.println(o.toString());
return true;
}
return false;
}
};
focusManager.addKeyEventDispatcher(deleteDispatcher);
// If the mouse click is a real right click event and alt is pressed then this code will print
// out the toString method of the object which the mouse is over.
AWTEventListener awtEventListener = new AWTEventListener(){
public void eventDispatched(AWTEvent event)
{
if(!(event instanceof MouseEvent)){
return;
}
MouseEvent mEvent = (MouseEvent) event;
if(mEvent.getID() == MouseEvent.MOUSE_CLICKED &&
(mEvent.getButton() == MouseEvent.BUTTON3) &&
(mEvent.getModifiersEx() & MouseEvent.ALT_DOWN_MASK) != 0){
System.out.println(event.getSource().toString());
}
}
};
Toolkit.getDefaultToolkit().addAWTEventListener(awtEventListener, AWTEvent.MOUSE_EVENT_MASK);
}
public void setUserMode(int mode)
{
userMode = mode;
}
public int getUserMode()
{
return userMode;
}
public void updateTreePane()
{
Dimension minimumSize = new Dimension(100, 50);
folderTreeArea = new JTree(folderTreeModel);
// we are just disabling this however if we want to
// use this tree for authoring, or for managing student
// created objects this will need to be some form of option
folderTreeArea.setEditable(false);
folderTreeArea.addTreeSelectionListener(this);
JComponent leftComponent = null;
JScrollPane folderTreeScrollPane = new JScrollPane(folderTreeArea);
if (System.getProperty(OTViewerHelper.DEBUG_PROP, "").equals("true")) {
// ViewFactory.getComponent(root);
dataTreeArea = new JTree(dataTreeModel);
dataTreeArea.setEditable(false);
dataTreeArea.addTreeSelectionListener(this);
JScrollPane dataTreeScrollPane = new JScrollPane(dataTreeArea);
JTabbedPane tabbedPane = new JTabbedPane();
tabbedPane.add("Folders", folderTreeScrollPane);
tabbedPane.add("Resources", dataTreeScrollPane);
// Provide minimum sizes for the two components in the split pane
folderTreeScrollPane.setMinimumSize(minimumSize);
dataTreeScrollPane.setMinimumSize(minimumSize);
tabbedPane.setMinimumSize(minimumSize);
leftComponent = tabbedPane;
} else {
leftComponent = folderTreeScrollPane;
}
if (splitPane == null) {
splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT,
leftComponent, bodyPanel);
} else {
splitPane.setLeftComponent(leftComponent);
}
splitPane.setOneTouchExpandable(true);
splitPane.setDividerLocation(200);
}
public void initArgs(String[] args)
{
if (args.length > 0) {
String urlStr = null;
if (args[0].equals("-f")) {
if (args.length > 1) {
File inFile = new File(args[1]);
currentAuthoredFile = inFile;
try {
URL url = inFile.toURL();
urlStr = url.toString();
} catch (Exception e) {
e.printStackTrace();
urlStr = null;
}
}
} else if (args[0].equals("-r")) {
if (args.length > 1) {
ClassLoader cl = OTViewer.class.getClassLoader();
URL url = cl.getResource(args[1]);
urlStr = url.toString();
}
} else {
urlStr = args[0];
}
initWithWizard(urlStr);
} else {
initWithWizard(null);
}
}
public void init(String url)
{
updateRemoteURL(url);
createActions();
updateMenuBar();
setJMenuBar(menuBar);
frameManager = new OTFrameManagerImpl();
bodyPanel = new OTViewContainerPanel(frameManager);
bodyPanel.addViewContainerListener(this);
if (showTree) {
dataTreeModel = new SimpleTreeModel();
folderTreeModel = new SimpleTreeModel();
updateTreePane();
getContentPane().add(splitPane);
} else {
getContentPane().add(bodyPanel);
}
SwingUtilities.invokeLater(new Runnable() {
public void run()
{
Dimension screenSize = Toolkit.getDefaultToolkit()
.getScreenSize();
if (screenSize.width < 1000 || screenSize.height < 700) {
setVisible(true);
int state = getExtendedState();
// Set the maximized bits
state |= Frame.MAXIMIZED_BOTH;
// Maximize the frame
setExtendedState(state);
} else {
int cornerX = 100;
int cornerY = 100;
int sizeX = 725;
int sizeY = 500;
// OTViewService viewService = otViewFactory.
setBounds(cornerX, cornerY, cornerX + sizeX, cornerY
+ sizeY);
setVisible(true);
}
}
});
if (url == null) {
return;
}
try {
initializeURL(new URL(url));
} catch (MalformedURLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (Exception e) {
// FIXME: this should popup a dialog
System.err.println("Can't load url");
e.printStackTrace();
return;
}
}
public void initializeURL(URL url) throws Exception
{
loadURL(url);
OTMainFrame mainFrame = (OTMainFrame) otrunk
.getService(OTMainFrame.class);
if (Boolean.getBoolean(HIDE_TREE_PROP) || !mainFrame.getShowLeftPanel()) {
splitPane.getLeftComponent().setVisible(false);
}
useScrollPane = true;
if (mainFrame.getFrame() != null) {
if (mainFrame.getFrame().isResourceSet("width")
&& mainFrame.getFrame().isResourceSet("height")) {
int cornerX = 100;
int cornerY = 100;
int sizeX = mainFrame.getFrame().getWidth();
int sizeY = mainFrame.getFrame().getHeight();
setBounds(cornerX, cornerY, cornerX + sizeX, cornerY
+ sizeY);
repaint();
}
useScrollPane = mainFrame.getFrame().getUseScrollPane();
}
bodyPanel.setUseScrollPane(useScrollPane);
setupBodyPanel();
}
public void initWithWizard(String url)
{
justStarted = true;
init(url);
if (userMode == OTViewerHelper.SINGLE_USER_MODE) {
SwingUtilities.invokeLater(new Runnable() {
public void run()
{
instructionPanel();
}
});
}
}
public void loadUserDataFile(File file)
{
currentUserFile = file;
try {
loadUserDataURL(file.toURL(), file.getName());
} catch (Exception e) {
e.printStackTrace();
}
}
public void loadUserDataURL(URL url, String name)
throws Exception
{
XMLDatabase db = new XMLDatabase(url);
db.loadObjects();
loadUserDataDb(db, name);
}
public void loadUserDataDb(XMLDatabase db, String name)
throws Exception
{
userDataDB = db;
currentUser = otrunk.registerUserDataDatabase(userDataDB, name);
reloadWindow();
}
public void reloadOverlays()
{
try {
otrunk.reloadOverlays(currentUser, userDataDB);
reloadWindow();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private void loadFile(File file)
{
currentAuthoredFile = file;
try {
initializeURL(currentAuthoredFile.toURL());
} catch (Exception e) {
e.printStackTrace();
}
}
private void loadURL(URL url)
throws Exception
{
XMLDatabase systemDB = null;
try {
// try loading in the system object if there is one
String systemOtmlUrlStr = OTViewerHelper.getStringProp(OTViewerHelper.SYSTEM_OTML_PROP);
if(systemOtmlUrlStr != null){
URL systemOtmlUrl = new URL(systemOtmlUrlStr);
systemDB = new XMLDatabase(systemOtmlUrl, System.out);
// don't track the resource info on the system db.
systemDB.loadObjects();
}
} catch (Exception e){
e.printStackTrace();
systemDB = null;
}
try {
xmlDB = new XMLDatabase(url, System.out);
// Only track the resource info when there isn't a user. Currently all classroom uses
// of OTViewer has NO_USER_MODE turned off, so using this setting safe to test
// the resource tracking without affecting real users.
if (userMode == OTViewerHelper.NO_USER_MODE) {
xmlDB.setTrackResourceInfo(true);
}
xmlDB.loadObjects();
} catch (org.jdom.input.JDOMParseException e) {
String xmlWarningTitle = "XML Decoding error";
String xmlWarningMessage = "There appears to a problem parsing the XML of this document. \n"
+ "Please show this error message to one of the workshop leaders. \n\n"
+ e.getMessage();
JOptionPane.showMessageDialog(null, xmlWarningMessage,
xmlWarningTitle, JOptionPane.ERROR_MESSAGE);
throw e;
}
otrunk = new OTrunkImpl(systemDB, xmlDB,
new Object[] { new SwingUserMessageHandler(this) },
new Class[] { UserMessageHandler.class });
OTViewFactory myViewFactory = (OTViewFactory) otrunk
.getService(OTViewFactory.class);
if (myViewFactory != null) {
otViewFactory = myViewFactory;
}
OTViewContext factoryContext = otViewFactory.getViewContext();
factoryContext.addViewService(OTrunk.class, otrunk);
factoryContext.addViewService(OTFrameManager.class, frameManager);
factoryContext.addViewService(OTJComponentServiceFactory.class,
new OTJComponentServiceFactoryImpl());
factoryContext.addViewService(OTExternalAppService.class,
new OTExternalAppServiceImpl());
currentURL = url;
}
// This method was refactored out of loadURL
private void setupBodyPanel()
throws Exception
{
bodyPanel.setTopLevelContainer(true);
bodyPanel.setOTViewFactory(otViewFactory);
// set the current mode from the viewservice to the main bodyPanel
// bodyPanel.setViewMode(otViewFactory.getDefaultMode());
// set the viewFactory of the frame manager
frameManager.setViewFactory(otViewFactory);
xmlDB.setDirty(false);
reloadWindow();
}
protected OTObject getAuthoredRoot() throws Exception
{
String rootLocalId = OTViewerHelper.getStringProp(OTViewerHelper.ROOT_OBJECT_PROP);
if(rootLocalId != null){
OTID rootID = xmlDB.getOTIDFromLocalID(rootLocalId);
return otrunk.getOTObject(rootID);
}
return otrunk.getRoot();
}
private void reloadWindow()
throws Exception
{
OTObject root = null;
boolean overrideShowTree = false;
switch (userMode) {
case OTViewerHelper.NO_USER_MODE:
root = getAuthoredRoot();
break;
case OTViewerHelper.SINGLE_USER_MODE:
if (userDataDB == null) {
// FIXME This is an error
// the newAnonUserData should have been called before this
// method is
// called
// no user file has been started yet
overrideShowTree = true;
root = null;
} else {
OTObject otRoot = getAuthoredRoot();
root = otrunk.getUserRuntimeObject(otRoot, currentUser);
OTObject realRoot = otrunk.getRealRoot();
if (realRoot instanceof OTSystem) {
OTSystem localUserSystem = (OTSystem) otrunk
.getUserRuntimeObject(realRoot, currentUser);
// FIXME there should be a better way than this because we
// have to handle
// multiple users.
if (localUserSystem != userSystem) {
userSystem = localUserSystem;
systemChangeListener = new OTChangeListener() {
public void stateChanged(OTChangeEvent e)
{
if ("overlays".equals(e.getProperty())) {
reloadOverlays();
}
}
};
userSystem.addOTChangeListener(systemChangeListener);
}
}
}
}
if (showTree && !overrideShowTree) {
OTDataObject rootDataObject = xmlDB.getRoot();
dataTreeModel.setRoot(new OTDataObjectNode("root", rootDataObject,
otrunk));
folderTreeModel.setRoot(new OTFolderNode(root));
}
bodyPanel.setCurrentObject(root);
if (showTree && !overrideShowTree) {
folderTreeModel
.fireTreeStructureChanged(new TreePath((SimpleTreeNode) folderTreeModel
.getRoot()));
dataTreeModel
.fireTreeStructureChanged(new TreePath((SimpleTreeNode) dataTreeModel
.getRoot()));
}
Frame frame = (Frame) SwingUtilities.getRoot(this);
switch (userMode) {
case OTViewerHelper.NO_USER_MODE:
if (remoteURL != null) {
frame.setTitle(baseFrameTitle + ": " + remoteURL.toString());
} else {
frame.setTitle(baseFrameTitle + ": " + currentURL.toString());
}
break;
case OTViewerHelper.SINGLE_USER_MODE:
if (currentUserFile != null) {
frame.setTitle(baseFrameTitle + ": "
+ currentUserFile.toString());
} else if (System.getProperty(TITLE_PROP, null) != null) {
frame.setTitle(baseFrameTitle);
} else if (userDataDB != null) {
frame.setTitle(baseFrameTitle + ": Untitled");
} else {
frame.setTitle(baseFrameTitle);
}
break;
}
saveUserDataAction.setEnabled(userDataDB != null);
saveUserDataAsAction.setEnabled(userDataDB != null);
}
public void reload()
throws Exception
{
initializeURL(currentURL);
}
public OTDatabase getUserDataDb()
{
return userDataDB;
}
/**
* You should call reloadWindow after calling this method to make sure the
* display reflects this change
*
* @param userObject
*/
public void setCurrentUser(OTUserObject userObject)
{
currentUser = userObject;
}
public static void main(String[] args)
{
System.setProperty("apple.laf.useScreenMenuBar", "true");
OTViewer viewer = new OTViewer();
if (Boolean.getBoolean(OTViewerHelper.SINGLE_USER_PROP)) {
viewer.setUserMode(OTViewerHelper.SINGLE_USER_MODE);
} else if (Boolean.getBoolean(OTViewerHelper.NO_USER_PROP)) {
viewer.setUserMode(OTViewerHelper.NO_USER_MODE);
}
viewer.initArgs(args);
}
class ExitAction extends AbstractAction
{
/**
* nothing to serialize here.
*/
private static final long serialVersionUID = 1L;
public ExitAction()
{
super("Exit");
}
public void actionPerformed(ActionEvent e)
{
// If this suceeds then the VM will exit so
// the window will get disposed
exit();
}
}
/*
* (non-Javadoc)
*
* @see org.concord.otrunk.view.OTViewContainerListener#currentObjectChanged(org.concord.framework.otrunk.view.OTViewContainer)
*/
public void currentObjectChanged(OTViewContainer container)
{
final OTViewContainer myContainer = container;
// TODO Auto-generated method stub
SwingUtilities.invokeLater(new Runnable() {
public void run()
{
OTObject currentObject = myContainer.getCurrentObject();
if (folderTreeArea != null) {
OTFolderNode node = (OTFolderNode) folderTreeArea
.getLastSelectedPathComponent();
if (node == null)
return;
if (node.getPfObject() != currentObject) {
folderTreeArea.setSelectionPath(null);
}
}
}
});
}
/*
* (non-Javadoc)
*
* @see javax.swing.event.TreeSelectionListener#valueChanged(javax.swing.event.TreeSelectionEvent)
*/
public void valueChanged(TreeSelectionEvent event)
{
if (event.getSource() == folderTreeArea) {
OTFolderNode node = (OTFolderNode) folderTreeArea
.getLastSelectedPathComponent();
if (node == null)
return;
OTObject pfObject = node.getPfObject();
bodyPanel.setCurrentObject(pfObject);
if (splitPane.getRightComponent() != bodyPanel) {
splitPane.setRightComponent(bodyPanel);
}
} else if (event.getSource() == dataTreeArea) {
SimpleTreeNode node = (SimpleTreeNode) dataTreeArea
.getLastSelectedPathComponent();
Object resourceValue = null;
if (node != null) {
resourceValue = node.getObject();
if (resourceValue == null) {
resourceValue = "null resource value";
}
} else {
resourceValue = "no selected data object";
}
JComponent nodeView = null;
if (resourceValue instanceof OTDataObject) {
nodeView = new OTDataObjectView((OTDataObject) resourceValue);
} else {
nodeView = new JTextArea(resourceValue.toString());
}
JScrollPane scrollPane = new JScrollPane(nodeView);
splitPane.setRightComponent(scrollPane);
}
}
private void updateRemoteURL(String defaultURL)
{
String remote = System
.getProperty(OTViewerHelper.REMOTE_URL_PROP, null);
try {
if (remote == null) {
if (defaultURL.startsWith("http:")) {
remoteURL = new URL(defaultURL);
}
} else {
remoteURL = new URL(remote);
}
} catch (Exception e) {
remoteURL = null;
System.err.println("Remote URL is invalid.");
e.printStackTrace();
}
}
public void remoteSaveData(String method)
throws Exception
{
HttpURLConnection urlConn;
DataOutputStream urlDataOut;
BufferedReader urlDataIn;
// If method isn't "POST" or "PUT", throw an exception
if (!(method.compareTo(OTViewer.HTTP_POST) == 0 || method
.compareTo(OTViewer.HTTP_PUT) == 0)) {
throw new Exception("Invalid HTTP Request method for data saving");
}
urlConn = (HttpURLConnection) remoteURL.openConnection();
urlConn.setDoInput(true);
urlConn.setDoOutput(true);
urlConn.setUseCaches(false);
urlConn.setRequestMethod(method);
urlConn.setRequestProperty("Content-Type", "application/xml");
// Send POST output.
urlDataOut = new DataOutputStream(urlConn.getOutputStream());
ExporterJDOM.export(urlDataOut, xmlDB.getRoot(), xmlDB);
urlDataOut.flush();
urlDataOut.close();
// Get response data.
urlDataIn = new BufferedReader(new InputStreamReader(
new DataInputStream(urlConn.getInputStream())));
String str;
String response = "";
while (null != ((str = urlDataIn.readLine()))) {
response += str + "\n";
}
urlDataIn.close();
// Need to trap non-HTTP 200/300 responses and throw an exception (if an
// exception isn't thrown already) and capture the exceptions upstream
int code = urlConn.getResponseCode();
if (code >= 400) {
throw new Exception("HTTP Response: "
+ urlConn.getResponseMessage() + "\n\n" + response);
}
urlConn.disconnect();
xmlDB.setDirty(false);
setTitle(remoteURL.toString());
}
public void createActions()
{
newUserDataAction = new AbstractAction("New") {
/**
* nothing to serialize here
*/
private static final long serialVersionUID = 1L;
/*
* (non-Javadoc)
*
* @see java.awt.event.ActionListener#actionPerformed(java.awt.event.ActionEvent)
*/
public void actionPerformed(ActionEvent arg0)
{
createNewUser();
}
};
loadUserDataAction = new AbstractAction("Open...") {
/**
* nothing to serialize here. Just the parent class.
*/
private static final long serialVersionUID = 1L;
/*
* (non-Javadoc)
*
* @see java.awt.event.ActionListener#actionPerformed(java.awt.event.ActionEvent)
*/
public void actionPerformed(ActionEvent arg0)
{
openUserData();
}
};
exportToHtmlAction = new AbstractAction("Export to html...") {
/**
* nothing to serialize here
*/
private static final long serialVersionUID = 1L;
public void actionPerformed(ActionEvent arg0)
{
File fileToSave = getReportFile();
OTMLToXHTMLConverter otxc = new OTMLToXHTMLConverter(
otViewFactory, bodyPanel.getViewContainer());
otxc.setXHTMLParams(fileToSave, 800, 600);
(new Thread(otxc)).start();
}
};
// Isn't it enabled by default?
exportToHtmlAction.setEnabled(true);
saveUserDataAction = new AbstractAction("Save") {
/**
* Nothing to serialize here
*/
private static final long serialVersionUID = 1L;
/*
* (non-Javadoc)
*
* @see java.awt.event.ActionListener#actionPerformed(java.awt.event.ActionEvent)
*/
public void actionPerformed(ActionEvent arg0)
{
if (currentUserFile == null || !currentUserFile.exists()) {
saveUserDataAsAction.actionPerformed(arg0);
return;
}
if (currentUserFile.exists()) {
try {
ExporterJDOM.export(currentUserFile, userDataDB.getRoot(),
userDataDB);
userDataDB.setDirty(false);
} catch (Exception e) {
e.printStackTrace();
}
}
}
};
saveUserDataAsAction = new AbstractAction("Save As...") {
/**
* nothing to serizile here
*/
private static final long serialVersionUID = 1L;
/*
* (non-Javadoc)
*
* @see java.awt.event.ActionListener#actionPerformed(java.awt.event.ActionEvent)
*/
public void actionPerformed(ActionEvent arg0)
{
Frame frame = (Frame) SwingUtilities.getRoot(OTViewer.this);
MostRecentFileDialog mrfd = new MostRecentFileDialog(
"org.concord.otviewer.saveotml");
mrfd.setFilenameFilter("otml");
if (currentUserFile != null) {
mrfd.setCurrentDirectory(currentUserFile.getParentFile());
mrfd.setSelectedFile(currentUserFile);
}
int retval = mrfd.showSaveDialog(frame);
File file = null;
if (retval == MostRecentFileDialog.APPROVE_OPTION) {
file = mrfd.getSelectedFile();
String fileName = file.getPath();
currentUserFile = file;
if (!fileName.toLowerCase().endsWith(".otml")) {
currentUserFile = new File(currentUserFile
.getAbsolutePath()
+ ".otml");
}
try {
ExporterJDOM.export(currentUserFile, userDataDB.getRoot(),
userDataDB);
userDataDB.setDirty(false);
setTitle(baseFrameTitle + ": "
+ currentUserFile.toString());
} catch (Exception e) {
e.printStackTrace();
}
frame.setTitle(fileName);
}
}
};
loadAction = new AbstractAction("Open Authored Content...") {
/**
* nothing to serizile here
*/
private static final long serialVersionUID = 1L;
/*
* (non-Javadoc)
*
* @see java.awt.event.ActionListener#actionPerformed(java.awt.event.ActionEvent)
*/
public void actionPerformed(ActionEvent arg0)
{
Frame frame = (Frame) SwingUtilities.getRoot(OTViewer.this);
MostRecentFileDialog mrfd = new MostRecentFileDialog(
"org.concord.otviewer.openotml");
mrfd.setFilenameFilter("otml");
int retval = mrfd.showOpenDialog(frame);
File file = null;
if (retval == MostRecentFileDialog.APPROVE_OPTION) {
file = mrfd.getSelectedFile();
}
if (file != null && file.exists()) {
System.out.println("load file name: " + file);
loadFile(file);
exportToHtmlAction.setEnabled(true);
}
}
};
saveAction = new AbstractAction("Save Authored Content...") {
/**
* nothing to serizile here
*/
private static final long serialVersionUID = 1L;
/*
* (non-Javadoc)
*
* @see java.awt.event.ActionListener#actionPerformed(java.awt.event.ActionEvent)
*/
public void actionPerformed(ActionEvent arg0)
{
if (remoteURL != null) {
try {
if (Boolean
.getBoolean(OTViewerHelper.REST_ENABLED_PROP)) {
try {
remoteSaveData(OTViewer.HTTP_PUT);
} catch (Exception e) {
remoteSaveData(OTViewer.HTTP_POST);
}
} else {
remoteSaveData(OTViewer.HTTP_POST);
}
} catch (Exception e) {
JOptionPane
.showMessageDialog(
(Frame) SwingUtilities
.getRoot(OTViewer.this),
"There was an error saving. Check your URL and try again.",
"Error Saving",
JOptionPane.ERROR_MESSAGE);
e.printStackTrace();
}
} else {
if (currentAuthoredFile == null) {
saveAsAction.actionPerformed(arg0);
return;
}
if (checkForReplace(currentAuthoredFile)) {
try {
ExporterJDOM.export(currentAuthoredFile, xmlDB
.getRoot(), xmlDB);
xmlDB.setDirty(false);
} catch (Exception e) {
e.printStackTrace();
}
}
} // end if (remoteUrl == null)
}
};
saveAsAction = new AbstractAction("Save Authored Content As...") {
/**
* nothing to serizile here
*/
private static final long serialVersionUID = 1L;
/*
* (non-Javadoc)
*
* @see java.awt.event.ActionListener#actionPerformed(java.awt.event.ActionEvent)
*/
public void actionPerformed(ActionEvent arg0)
{
Frame frame = (Frame) SwingUtilities.getRoot(OTViewer.this);
MostRecentFileDialog mrfd = new MostRecentFileDialog(
"org.concord.otviewer.saveotml");
mrfd.setFilenameFilter("otml");
if (currentAuthoredFile != null) {
mrfd.setCurrentDirectory(currentAuthoredFile
.getParentFile());
mrfd.setSelectedFile(currentAuthoredFile);
}
int retval = mrfd.showSaveDialog(frame);
File file = null;
if (retval == MostRecentFileDialog.APPROVE_OPTION) {
file = mrfd.getSelectedFile();
String fileName = file.getPath();
if (!fileName.toLowerCase().endsWith(".otml")) {
file = new File(file.getAbsolutePath() + ".otml");
}
if (checkForReplace(file)) {
try {
ExporterJDOM.export(file, xmlDB.getRoot(), xmlDB);
currentAuthoredFile = file;
currentURL = file.toURL();
xmlDB.setDirty(false);
} catch (Exception e) {
e.printStackTrace();
}
}
frame.setTitle(fileName);
remoteURL = null;
updateMenuBar();
}
}
};
saveRemoteAsAction = new AbstractAction("Save Remotely As...") {
/**
* nothing to serizile here
*/
private static final long serialVersionUID = 1L;
/*
* (non-Javadoc)
*
* @see java.awt.event.ActionListener#actionPerformed(java.awt.event.ActionEvent)
*/
public void actionPerformed(ActionEvent arg0)
{
// Pop up a dialog asking for a URL
// Post the otml to the url
JPanel panel = new JPanel();
panel.setBorder(new EmptyBorder(10, 10, 10, 10));
panel.setLayout(new BorderLayout());
JLabel prompt = new JLabel(
"Please enter the URL to which you would like to save:");
prompt.setBorder(new EmptyBorder(0, 0, 10, 0));
JTextField textField = new JTextField();
if (remoteURL == null) {
textField.setText("http:
} else {
textField.setText(remoteURL.toString());
}
JPanel checkboxPanel = new JPanel();
JCheckBox restCheckbox = new JCheckBox("REST Enabled?");
restCheckbox.setSelected(Boolean
.getBoolean(OTViewerHelper.REST_ENABLED_PROP));
checkboxPanel.setBorder(new EmptyBorder(5, 5, 0, 0));
checkboxPanel.add(restCheckbox);
panel.add(prompt, BorderLayout.NORTH);
panel.add(textField, BorderLayout.CENTER);
panel.add(checkboxPanel, BorderLayout.SOUTH);
int returnVal = CustomDialog.showOKCancelDialog(
(Frame) SwingUtilities.getRoot(OTViewer.this), // parent
panel, // custom content
"Save URL", // title
false, // resizeable
true // modal
);
if (returnVal == 0) {
try {
remoteURL = new URL(textField.getText());
System.setProperty(OTViewerHelper.REST_ENABLED_PROP,
Boolean.toString(restCheckbox.isSelected()));
remoteSaveData(OTViewer.HTTP_POST);
updateMenuBar();
} catch (Exception e) {
System.err.println("Bad URL. Not saving.");
JOptionPane
.showMessageDialog(
(Frame) SwingUtilities
.getRoot(OTViewer.this),
"There was an error saving. Check your URL and try again.",
"Error Saving",
JOptionPane.ERROR_MESSAGE);
e.printStackTrace();
}
} else {
// CANCELLED
}
}
};
exportImageAction = new AbstractAction("Export Image...") {
/**
* nothing to serialize here
*/
private static final long serialVersionUID = 1L;
public void actionPerformed(ActionEvent e)
{
// this introduces a dependency on concord Swing project
// instead there needs to be a way to added these actions
// through
// the xml
Component currentComp = bodyPanel.getCurrentComponent();
Util.makeScreenShot(currentComp);
}
};
exportHiResImageAction = new AbstractAction("Export Hi Res Image...") {
/**
* nothing to serizile here
*/
private static final long serialVersionUID = 1L;
public void actionPerformed(ActionEvent e)
{
Component currentComp = bodyPanel.getCurrentComponent();
Util.makeScreenShot(currentComp, 2, 2);
}
};
debugAction = new AbstractAction("Debug Mode") {
/**
* nothing to serizile here
*/
private static final long serialVersionUID = 1L;
public void actionPerformed(ActionEvent e)
{
Object source = e.getSource();
if (((JCheckBoxMenuItem) source).isSelected()) {
System.setProperty(OTViewerHelper.DEBUG_PROP, "true");
} else {
System.setProperty(OTViewerHelper.DEBUG_PROP, "false");
}
try {
reloadWindow();
} catch (Exception exp) {
exp.printStackTrace();
}
SwingUtilities.invokeLater(new Runnable() {
public void run()
{
updateMenuBar();
}
});
exportToHtmlAction.setEnabled(true);
}
};
showConsoleAction = new AbstractAction("Show Console") {
/**
* nothing to serialize here
*/
private static final long serialVersionUID = 1L;
public void actionPerformed(ActionEvent e)
{
if (consoleFrame != null) {
consoleFrame.setVisible(true);
}
}
};
reloadWindowAction = new AbstractAction("Reload window") {
/**
* nothing to serialize here
*/
private static final long serialVersionUID = 1L;
public void actionPerformed(ActionEvent e)
{
try {
reload();
} catch (Exception e1) {
e1.printStackTrace();
}
}
};
exitAction = new ExitAction();
}
/**
* @return Returns the menuBar.
*/
public JMenuBar updateMenuBar()
{
JMenu fileMenu = null;
if (menuBar == null) {
menuBar = new JMenuBar();
fileMenu = new JMenu("File");
menuBar.add(fileMenu);
} else {
fileMenu = menuBar.getMenu(0);
fileMenu.removeAll();
}
if (OTViewerHelper.getBooleanProp(OTViewerHelper.AUTHOR_PROP, false)) {
userMode = OTViewerHelper.NO_USER_MODE;
}
if (userMode == OTViewerHelper.SINGLE_USER_MODE) {
fileMenu.setEnabled(!justStarted);
fileMenu.add(newUserDataAction);
fileMenu.add(loadUserDataAction);
fileMenu.add(saveUserDataAction);
fileMenu.add(saveUserDataAsAction);
}
if (Boolean.getBoolean(OTViewerHelper.DEBUG_PROP)) {
if (userMode == OTViewerHelper.SINGLE_USER_MODE) {
loadAction.putValue(Action.NAME, "Open Authored Content...");
saveAction.putValue(Action.NAME, "Save Authored Content");
saveAsAction.putValue(Action.NAME,
"Save Authored Content As...");
saveRemoteAsAction.putValue(Action.NAME,
"Save Authored Content Remotely As...");
} else {
loadAction.putValue(Action.NAME, "Open...");
saveAction.putValue(Action.NAME, "Save");
saveAsAction.putValue(Action.NAME, "Save As...");
saveRemoteAsAction.putValue(Action.NAME, "Save Remotely As...");
}
fileMenu.add(loadAction);
fileMenu.add(saveAction);
fileMenu.add(saveAsAction);
fileMenu.add(saveRemoteAsAction);
}
if (Boolean.getBoolean(OTViewerHelper.AUTHOR_PROP)
&& !Boolean.getBoolean(OTViewerHelper.DEBUG_PROP)) {
if (userMode == OTViewerHelper.SINGLE_USER_MODE) {
loadAction.putValue(Action.NAME, "Open Authored Content...");
saveAction.putValue(Action.NAME, "Save Authored Content");
saveAsAction.putValue(Action.NAME,
"Save Authored Content As...");
} else {
loadAction.putValue(Action.NAME, "Open...");
saveAction.putValue(Action.NAME, "Save");
saveAsAction.putValue(Action.NAME, "Save As...");
}
fileMenu.add(loadAction);
fileMenu.add(saveAction);
fileMenu.add(saveAsAction);
}
if (Boolean.getBoolean("otrunk.view.export_image")) {
fileMenu.add(exportImageAction);
fileMenu.add(exportHiResImageAction);
}
fileMenu.add(exportToHtmlAction);
fileMenu.add(showConsoleAction);
if (Boolean.getBoolean(OTViewerHelper.AUTHOR_PROP)
|| Boolean.getBoolean(OTViewerHelper.DEBUG_PROP)) {
fileMenu.add(reloadWindowAction);
}
JCheckBoxMenuItem debugItem = new JCheckBoxMenuItem(debugAction);
debugItem.setSelected(Boolean.getBoolean(OTViewerHelper.DEBUG_PROP));
fileMenu.add(debugItem);
fileMenu.add(exitAction);
return menuBar;
}
boolean checkForReplace(File file)
{
if (file == null){
return false;
}
if (!file.exists()) {
return true; // File doesn't exist, so go ahead and save
}
if (currentAuthoredFile != null && file.compareTo(currentAuthoredFile) == 0){
return true; // we're already authoring this file, so no need to
// prompt
}
final Object[] options = { "Yes", "No" };
return javax.swing.JOptionPane.showOptionDialog(null, "The file '"
+ file.getName() + "' already exists. "
+ "Replace existing file?", "Warning",
javax.swing.JOptionPane.YES_NO_OPTION,
javax.swing.JOptionPane.WARNING_MESSAGE, null, options,
options[1]) == javax.swing.JOptionPane.YES_OPTION;
}
/**
* Checks if the user has unsaved work. If they do then it prompts them to
* confirm what they are doing. If they cancel then it returns false.
*
* @return
*/
public boolean checkForUnsavedUserData()
{
if (currentUser != null && userDataDB != null) {
if (userDataDB.isDirty()) {
// show dialog message telling them they haven't
// saved their work
// FIXME
String options[] = { "Don't Save", "Cancel", "Save" };
askedAboutSavingUserData = true;
int chosenOption = JOptionPane.showOptionDialog(this,
"Save Changes?", "Save Changes?",
JOptionPane.DEFAULT_OPTION,
JOptionPane.WARNING_MESSAGE, null, options, options[2]);
switch (chosenOption) {
case 0:
System.err.println("Not saving work");
break;
case 1:
System.err.println("Canceling close");
return false;
case 2:
System.err.println("Set needToSaveUserData true");
needToSaveUserData = true;
break;
}
}
}
return true;
}
/**
* Checks if the user has unsaved authored data. If they do then it prompts
* them to confirm what they are doing. If they cancel then it returns
* false.
*
* @return
*/
public boolean checkForUnsavedAuthorData()
{
if (xmlDB != null) {
if (xmlDB.isDirty()) {
// show dialog message telling them they haven't
// saved their work
// FIXME
String options[] = { "Don't Save", "Cancel", "Save" };
int chosenOption = JOptionPane.showOptionDialog(this,
"Save Changes?", "Save Changes?",
JOptionPane.DEFAULT_OPTION,
JOptionPane.WARNING_MESSAGE, null, options, options[2]);
switch (chosenOption) {
case 0:
System.err.println("Not saving authored data");
break;
case 1:
System.err.println("Canceling close");
return false;
case 2:
System.err.println("Saving authored data");
saveAction.actionPerformed(null);
break;
}
}
}
return true;
}
/**
* This does not check for unsaved user data
*
*/
public void newAnonUserData()
{
// call some new method for creating a new un-saved user state
// this should set the currentUserFile to null, so the save check
// prompts
// for a file name
try {
// need to make a brand new stateDB
userDataDB = new XMLDatabase();
// System.out.println("otrunk: " + otrunk + " userDatabase: " +
// userDataDB);
OTObjectService objService = otrunk.createObjectService(userDataDB);
OTStateRoot stateRoot = (OTStateRoot) objService
.createObject(OTStateRoot.class);
userDataDB.setRoot(stateRoot.getGlobalId());
stateRoot.setFormatVersionString("1.0");
OTUserObject userObject = OTViewerHelper.createUser(
"anon_single_user", objService);
otrunk.initUserObjectService((OTObjectServiceImpl) objService,
userObject, stateRoot);
userDataDB.setDirty(false);
currentUserFile = null;
setCurrentUser(userObject);
reloadWindow();
} catch (Exception e) {
e.printStackTrace();
}
}
public boolean exit()
{
try {
if (!checkForUnsavedUserData()) {
// the user canceled the operation
return false;
}
if (Boolean.getBoolean(OTViewerHelper.AUTHOR_PROP)
&& !checkForUnsavedAuthorData()) {
// the user canceled the operation
return false;
}
// FIXME there is a problem with this logic. If the user saved data
// just before closing
// checkForUnsavedUserData will not see any unsaved data. But if
// some view creates
// data in the viewClosed method then that data will not get saved
// here.
// I think the key to solving this is to seperate the
// automatic/logging data from the
// user visible data. And then make a rule that saving data in the
// viewClosed method
// is not allowed.
bodyPanel.setCurrentObject(null);
conditionalSaveUserData();
if (otrunk != null)
otrunk.close();
} catch (Exception exp) {
exp.printStackTrace();
// exit anyhow
}
System.exit(0);
return true;
}
protected void conditionalSaveUserData()
{
if (!askedAboutSavingUserData) {
checkForUnsavedUserData();
}
if (needToSaveUserData) {
saveUserDataAction.actionPerformed(null);
} else {
System.err.println("Not saving work before closing.");
}
// Reset these back to false, so if the user is switching to a new
// user or loading a new file we are in a clean state, for that file or
// user
askedAboutSavingUserData = false;
needToSaveUserData = false;
}
public File getReportFile()
{
Frame frame = (Frame) SwingUtilities.getRoot(OTViewer.this);
MostRecentFileDialog mrfd = new MostRecentFileDialog(
"org.concord.otviewer.saveotml");
mrfd.setFilenameFilter("html");
if (currentUserFile != null) {
mrfd.setCurrentDirectory(currentUserFile.getParentFile());
}
int retval = mrfd.showSaveDialog(frame);
File file = null;
if (retval == MostRecentFileDialog.APPROVE_OPTION) {
file = mrfd.getSelectedFile();
String fileName = file.getPath();
if (!fileName.toLowerCase().endsWith(".html")) {
file = new File(file.getAbsolutePath() + ".html");
}
return file;
}
return null;
}
public void createNewUser()
{
if (!checkForUnsavedUserData()) {
// the user canceled the operation
return;
}
// This ensures viewClosed is called
bodyPanel.setCurrentObject(null);
conditionalSaveUserData();
// call some new method for creating a new un-saved user state
// this should set the currentUserFile to null, so the save check
// prompts
// for a file name
newAnonUserData();
exportToHtmlAction.setEnabled(true);
}
public void openUserData()
{
if (!checkForUnsavedUserData()) {
// the user canceled the operation
return;
}
// FIXME Calling the method below would insure the view is closed, and
// that any data that is
// is modified in that view closed operation will get saved, however if
// the user
// cancels the open dialog then we would be left in an unknown
// state. The current view would be closed which they would want to see
// again.
// bodyPanel.setCurrentObject(null);
conditionalSaveUserData();
Frame frame = (Frame) SwingUtilities.getRoot(OTViewer.this);
MostRecentFileDialog mrfd = new MostRecentFileDialog(
"org.concord.otviewer.openotml");
mrfd.setFilenameFilter("otml");
int retval = mrfd.showOpenDialog(frame);
File file = null;
if (retval == MostRecentFileDialog.APPROVE_OPTION) {
file = mrfd.getSelectedFile();
}
if (file != null && file.exists()) {
loadUserDataFile(file);
exportToHtmlAction.setEnabled(true);
}
}
public void instructionPanel()
{
commDialog.setResizable(false);
JPanel panel = new JPanel();
panel.setBackground(Color.WHITE);
panel.setLayout(null);
JLabel lNew = new JLabel(
"Click the \"New\" button to create a new portfolio:");
JLabel lOpen = new JLabel(
"Click the \"Open\" button to open a saved portfolio:");
JButton bNew = new JButton("New");
JButton bOpen = new JButton("Open");
panel.add(lNew);
panel.add(lOpen);
panel.add(bNew);
panel.add(bOpen);
lNew.setLocation(50, 100);
lOpen.setLocation(50, 150);
bNew.setLocation(400, 100);
bOpen.setLocation(400, 150);
lNew.setSize(340, 30);
lOpen.setSize(340, 30);
bNew.setSize(70, 25);
bOpen.setSize(70, 25);
bNew.setOpaque(false);
bOpen.setOpaque(false);
bNew.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
commDialog.setVisible(false);
createNewUser();
}
});
bOpen.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
commDialog.setVisible(false);
openUserData();
}
});
commDialog.getContentPane().add(panel);
commDialog.setBounds(200, 200, 500, 300);
SwingUtilities.invokeLater(new Runnable() {
public void run()
{
commDialog.setVisible(true);
justStarted = false;
updateMenuBar();
}
});
}
public OTViewContainerPanel getViewContainerPanel()
{
return this.bodyPanel;
}
public void setExitAction(AbstractAction exitAction)
{
this.exitAction = exitAction;
}
/*
* (non-Javadoc)
*
* @see org.concord.applesupport.AppleApplicationAdapter#about()
*/
public void about()
{
// TODO Auto-generated method stub
}
/*
* (non-Javadoc)
*
* @see org.concord.applesupport.AppleApplicationAdapter#preferences()
*/
public void preferences()
{
// TODO Auto-generated method stub
}
/*
* (non-Javadoc)
*
* @see org.concord.applesupport.AppleApplicationAdapter#quit()
*/
public void quit()
{
exitAction.actionPerformed(null);
}
} // @jve:decl-index=0:visual-constraint="10,10"
class HtmlFileFilter extends javax.swing.filechooser.FileFilter
{
public boolean accept(File f)
{
if (f == null)
return false;
if (f.isDirectory())
return true;
return (f.getName().toLowerCase().endsWith(".html"));
}
public String getDescription()
{
return "HTML files";
}
} // @jve:decl-index=0:visual-constraint="10,10"
|
package org.concord.otrunk.view;
import java.awt.AWTEvent;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Frame;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.KeyEventDispatcher;
import java.awt.KeyboardFocusManager;
import java.awt.Toolkit;
import java.awt.event.AWTEventListener;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.MouseEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.File;
import java.io.PrintStream;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Hashtable;
import java.util.Vector;
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.Box;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JCheckBoxMenuItem;
import javax.swing.JComponent;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JSplitPane;
import javax.swing.JTabbedPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.JTree;
import javax.swing.KeyStroke;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.WindowConstants;
import javax.swing.border.EmptyBorder;
import javax.swing.event.TreeSelectionEvent;
import javax.swing.event.TreeSelectionListener;
import javax.swing.tree.TreePath;
import org.concord.applesupport.AppleApplicationAdapter;
import org.concord.applesupport.AppleApplicationUtil;
import org.concord.framework.otrunk.OTChangeEvent;
import org.concord.framework.otrunk.OTChangeListener;
import org.concord.framework.otrunk.OTID;
import org.concord.framework.otrunk.OTObject;
import org.concord.framework.otrunk.OTObjectList;
import org.concord.framework.otrunk.OTrunk;
import org.concord.framework.otrunk.view.OTExternalAppService;
import org.concord.framework.otrunk.view.OTFrameManager;
import org.concord.framework.otrunk.view.OTJComponentServiceFactory;
import org.concord.framework.otrunk.view.OTUserListService;
import org.concord.framework.otrunk.view.OTViewContainer;
import org.concord.framework.otrunk.view.OTViewContainerChangeEvent;
import org.concord.framework.otrunk.view.OTViewContainerListener;
import org.concord.framework.otrunk.view.OTViewContext;
import org.concord.framework.otrunk.view.OTViewFactory;
import org.concord.framework.text.UserMessageHandler;
import org.concord.framework.util.SimpleTreeNode;
import org.concord.otrunk.OTMLToXHTMLConverter;
import org.concord.otrunk.OTSystem;
import org.concord.otrunk.OTrunkImpl;
import org.concord.otrunk.OTrunkServiceEntry;
import org.concord.otrunk.datamodel.OTDataObject;
import org.concord.otrunk.overlay.OTOverlayGroup;
import org.concord.otrunk.user.OTUserObject;
import org.concord.otrunk.xml.ExporterJDOM;
import org.concord.otrunk.xml.XMLDatabase;
import org.concord.otrunk.xml.XMLDatabaseChangeEvent;
import org.concord.otrunk.xml.XMLDatabaseChangeListener;
import org.concord.swing.CustomDialog;
import org.concord.swing.MemoryMonitorPanel;
import org.concord.swing.MostRecentFileDialog;
import org.concord.swing.StreamRecord;
import org.concord.swing.StreamRecordView;
import org.concord.swing.util.Util;
import org.concord.view.SimpleTreeModel;
import org.concord.view.SwingUserMessageHandler;
/**
* OTViewer Class name and description
*
* Date created: Dec 14, 2004
*
* @author scott
* <p>
*
*/
public class OTViewer extends JFrame
implements TreeSelectionListener, OTViewContainerListener, AppleApplicationAdapter
{
/**
* first version of this class
*/
private static final long serialVersionUID = 1L;
public final static String TITLE_PROP = "otrunk.view.frame_title";
public final static String HIDE_TREE_PROP = "otrunk.view.hide_tree";
public final static String SHOW_CONSOLE_PROP = "otrunk.view.show_console";
public final static String HTTP_PUT = "PUT";
public final static String HTTP_POST = "POST";
private static OTrunkImpl otrunk;
private static OTViewFactory otViewFactory;
protected int userMode = OTConfig.NO_USER_MODE;
URL currentURL = null;
String baseFrameTitle;
final static String DEFAULT_BASE_FRAME_TITLE = "OTrunk Viewer";
OTViewContainerPanel bodyPanel;
OTFrameManagerImpl frameManager;
JTree folderTreeArea;
SimpleTreeModel folderTreeModel;
JTree dataTreeArea;
SimpleTreeModel dataTreeModel;
JSplitPane splitPane;
JFrame consoleFrame;
// Temp, to close the window
AbstractAction exitAction;
AbstractAction saveAsAction;
JMenuBar menuBar;
XMLDatabase xmlDB;
OTUserSession userSession;
File currentAuthoredFile = null;
Hashtable otContainers = new Hashtable();
String startupMessage = "";
boolean justStarted = false;
boolean showTree = false;
URL remoteURL;
private AbstractAction saveUserDataAsAction;
private AbstractAction saveUserDataAction;
private AbstractAction debugAction;
private AbstractAction showConsoleAction;
private AbstractAction newUserDataAction;
private AbstractAction loadUserDataAction;
private AbstractAction loadAction;
private AbstractAction reloadWindowAction;
private AbstractAction saveAction;
private AbstractAction saveRemoteAsAction;
private AbstractAction exportImageAction;
private AbstractAction exportHiResImageAction;
private AbstractAction exportToHtmlAction;
private JDialog commDialog;
/**
* This is true if the user was asked about saving user data after they
* initiated a close of the current view.
*/
private boolean askedAboutSavingUserData = false;
/**
* This is true if the user was asked about saving the user data, and said
* yes
*/
private boolean needToSaveUserData = false;
private boolean useScrollPane;
private OTChangeListener systemChangeListener;
private OTSystem userSystem;
private ArrayList services = new ArrayList();
private JPanel statusPanel;
/**
* This is true if the SailOTViewer created this OTViewer
*/
private boolean launchedBySailOTViewer = false;
public static void setOTViewFactory(OTViewFactory factory)
{
otViewFactory = factory;
}
public OTViewer()
{
super();
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (Exception e) {
System.out.println("Error setting native LAF: " + e);
}
this.showTree = true;
AppleApplicationUtil.registerWithMacOSX(this);
baseFrameTitle = DEFAULT_BASE_FRAME_TITLE;
try {
// this overrides the default base frame title
String title = System.getProperty(TITLE_PROP, null);
if (title != null) {
baseFrameTitle = title;
}
} catch (Throwable t) {
// do nothing, just use the default title
}
setTitle(baseFrameTitle);
setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE);
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e)
{
exitAction.actionPerformed(null);
}
});
consoleFrame = new JFrame("Console");
StreamRecord record = new StreamRecord(50000);
StreamRecordView view = new StreamRecordView(record);
consoleFrame.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
System.setOut((PrintStream) view.addOutputStream(System.out, "Console"));
System.setErr((PrintStream) view.addOutputStream(System.err, System.out));
consoleFrame.getContentPane().add(view);
consoleFrame.setSize(800, 600);
if (OTConfig.getBooleanProp(SHOW_CONSOLE_PROP, false)) {
consoleFrame.setVisible(true);
}
commDialog = new JDialog(this, true);
// for debugging
// add a breakpoint below, run in debugging mode, and then hit Meta-B
// the object you're currently focused on will be passed in here and you
// can
// start exploring the data structures, etc.
KeyboardFocusManager focusManager =
KeyboardFocusManager.getCurrentKeyboardFocusManager();
KeyEventDispatcher deleteDispatcher = new KeyEventDispatcher(){
public boolean dispatchKeyEvent(KeyEvent e)
{
if ((e.getID() == java.awt.event.KeyEvent.KEY_RELEASED)
&& ((e.getModifiersEx() & java.awt.event.InputEvent.META_DOWN_MASK) != 0)
&& (e.getKeyCode() == java.awt.event.KeyEvent.VK_B)) {
Object o = e.getSource();
System.out.println(o.toString());
return true;
}
return false;
}
};
focusManager.addKeyEventDispatcher(deleteDispatcher);
// If the mouse click is a right click event and alt is pressed
// or on a Mac the ctrl and option keys are down
// then this code will print out the toString method of the
// object which the mouse is over to the console.
AWTEventListener awtEventListener = new AWTEventListener(){
public void eventDispatched(AWTEvent event)
{
if(!(event instanceof MouseEvent)){
return;
}
MouseEvent mEvent = (MouseEvent) event;
if (mEvent.getID() == MouseEvent.MOUSE_CLICKED
&& (mEvent.getModifiersEx() & MouseEvent.ALT_DOWN_MASK) != 0) {
System.out.println(event.getSource().toString());
}
}
};
Toolkit.getDefaultToolkit().addAWTEventListener(awtEventListener,
AWTEvent.MOUSE_EVENT_MASK);
}
/**
* this needs to be called before initialized.
*
* @param serviceInterface
* @param service
*/
public void addService(Class serviceInterface, Object service)
{
OTrunkServiceEntry entry = new OTrunkServiceEntry(service, serviceInterface);
services.add(entry);
}
public void setUserMode(int mode)
{
userMode = mode;
}
public int getUserMode()
{
return userMode;
}
public void updateTreePane()
{
Dimension minimumSize = new Dimension(100, 50);
folderTreeArea = new JTree(folderTreeModel);
// we are just disabling this however if we want to
// use this tree for authoring, or for managing student
// created objects this will need to be some form of option
folderTreeArea.setEditable(false);
folderTreeArea.addTreeSelectionListener(this);
JComponent leftComponent = null;
JScrollPane folderTreeScrollPane = new JScrollPane(folderTreeArea);
if (System.getProperty(OTConfig.DEBUG_PROP, "").equals("true")) {
// ViewFactory.getComponent(root);
dataTreeArea = new JTree(dataTreeModel);
dataTreeArea.setEditable(false);
dataTreeArea.addTreeSelectionListener(this);
JScrollPane dataTreeScrollPane = new JScrollPane(dataTreeArea);
JTabbedPane tabbedPane = new JTabbedPane();
tabbedPane.add("Folders", folderTreeScrollPane);
tabbedPane.add("Resources", dataTreeScrollPane);
// Provide minimum sizes for the two components in the split pane
folderTreeScrollPane.setMinimumSize(minimumSize);
dataTreeScrollPane.setMinimumSize(minimumSize);
tabbedPane.setMinimumSize(minimumSize);
leftComponent = tabbedPane;
} else {
leftComponent = folderTreeScrollPane;
}
if (splitPane == null) {
splitPane =
new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, leftComponent, bodyPanel);
} else {
splitPane.setLeftComponent(leftComponent);
}
splitPane.setOneTouchExpandable(true);
splitPane.setDividerLocation(200);
}
public void initArgs(String[] args)
{
URL authorOTMLURL = OTViewerHelper.getURLFromArgs(args);
if (authorOTMLURL == null) {
authorOTMLURL = OTViewer.class.getResource("no-arguments-page.otml");
}
if ("file".equalsIgnoreCase(authorOTMLURL.getProtocol())) {
currentAuthoredFile = new File(authorOTMLURL.getPath());
}
String urlStr = authorOTMLURL.toString();
initWithWizard(urlStr);
}
/**
* @param args
* @return
*/
public String getURL(String[] args)
{
URL authorOTMLURL = OTViewerHelper.getURLFromArgs(args);
if ("file".equalsIgnoreCase(authorOTMLURL.getProtocol())) {
try {
URI authorOTMLURI = new URI(authorOTMLURL.toString());
currentAuthoredFile = new File(authorOTMLURI);
} catch (URISyntaxException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return authorOTMLURL.toString();
}
public void init(String url)
{
updateRemoteURL(url);
createActions();
updateMenuBar();
setJMenuBar(menuBar);
frameManager = new OTFrameManagerImpl();
bodyPanel = new OTViewContainerPanel(frameManager);
bodyPanel.addViewContainerListener(this);
if (showTree) {
dataTreeModel = new SimpleTreeModel();
folderTreeModel = new SimpleTreeModel();
updateTreePane();
getContentPane().add(splitPane);
} else {
getContentPane().add(bodyPanel);
}
if (OTConfig.isShowStatus()) {
statusPanel = new JPanel(new FlowLayout(FlowLayout.TRAILING, 3, 1));
final JLabel saveStateLabel = new JLabel("File saved");
statusPanel.add(saveStateLabel);
statusPanel.add(Box.createHorizontalStrut(20));
statusPanel.add(new MemoryMonitorPanel());
statusPanel.add(Box.createHorizontalStrut(5));
getContentPane().add(statusPanel, BorderLayout.SOUTH);
// It takes a while for xmlDM to be initialized...
Thread waitForDB = new Thread() {
public void run()
{
while (xmlDB == null) {
try {
sleep(1000);
} catch (Exception e) {
}
}
xmlDB.addXMLDatabaseChangeListener(new XMLDatabaseChangeListener() {
public void stateChanged(XMLDatabaseChangeEvent e)
{
if (xmlDB.isDirty()) {
saveStateLabel.setText("Unsaved changes");
} else {
saveStateLabel.setText("File saved");
}
statusPanel.repaint();
}
});
}
};
waitForDB.start();
}
SwingUtilities.invokeLater(new Runnable() {
public void run()
{
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
if (screenSize.width < 1000 || screenSize.height < 700) {
setVisible(true);
int state = getExtendedState();
// Set the maximized bits
state |= Frame.MAXIMIZED_BOTH;
// Maximize the frame
setExtendedState(state);
} else {
int cornerX = 50;
int cornerY = 50;
int sizeX = 800;
int sizeY = 500;
// OTViewService viewService = otViewFactory.
setBounds(cornerX, cornerY, cornerX + sizeX, cornerY + sizeY);
setVisible(true);
}
}
});
if (url == null) {
return;
}
try {
initializeURL(new URL(url));
} catch (MalformedURLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (Exception e) {
// FIXME: this should popup a dialog
System.err.println("Can't load url");
e.printStackTrace();
return;
}
}
public void initializeURL(URL url)
throws Exception
{
loadURL(url);
OTMainFrame mainFrame = (OTMainFrame) otrunk.getService(OTMainFrame.class);
if (OTConfig.getBooleanProp(HIDE_TREE_PROP, false)
|| !mainFrame.getShowLeftPanel()) {
splitPane.getLeftComponent().setVisible(false);
}
useScrollPane = true;
if (mainFrame.getFrame() != null) {
if (mainFrame.getFrame().isResourceSet("width")
&& mainFrame.getFrame().isResourceSet("height")) {
int cornerX = mainFrame.getFrame().getPositionX();
int cornerY = mainFrame.getFrame().getPositionY();
int sizeX = mainFrame.getFrame().getWidth();
int sizeY = mainFrame.getFrame().getHeight();
// See if title is set for main frame (only if name is
// still default, so that jnlp prop will still
// overrides this)
if (baseFrameTitle == DEFAULT_BASE_FRAME_TITLE &&
mainFrame.getFrame().isResourceSet("title")){
System.out.println("change");
baseFrameTitle = mainFrame.getFrame().getTitle();
setTitle(baseFrameTitle);
}
setBounds(cornerX, cornerY, cornerX + sizeX, cornerY + sizeY);
repaint();
}
useScrollPane = mainFrame.getFrame().getUseScrollPane();
}
bodyPanel.setUseScrollPane(useScrollPane);
setupBodyPanel();
}
public void initWithWizard(String url)
{
justStarted = true;
init(url);
if (userMode == OTConfig.SINGLE_USER_MODE) {
SwingUtilities.invokeLater(new Runnable() {
public void run()
{
instructionPanel();
}
});
}
}
public void loadUserDataFile(File file)
{
try {
OTMLUserSession xmlUserSession = new OTMLUserSession(file, null);
loadUserSession(xmlUserSession);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* This method just sets the viewers userSession without loading it.
* This is useful if a user needs to select the data they want to use
* when the load method is called. Currently this is used by the "wizard" in
* the ot viewer.
*
* @param userSession
*/
public void setUserSession(OTUserSession userSession)
{
this.userSession = userSession;
userSession.setOTrunk(otrunk);
}
/**
* This method loads in a user session, and reloads the window.
*
* @param userSession
* @throws Exception
*/
public void loadUserSession(OTUserSession userSession)
throws Exception
{
this.userSession = userSession;
otrunk.registerUserSession(userSession);
reloadWindow();
}
public void updateOverlayGroupListeners()
{
OTObjectList overlays = userSystem.getOverlays();
for(int i=0; i<overlays.size(); i++){
OTObject item = overlays.get(i);
if(item instanceof OTOverlayGroup){
((OTOverlayGroup) item).addOTChangeListener(systemChangeListener);
}
}
}
public void reloadOverlays()
{
try {
otrunk.reloadOverlays(userSession);
updateOverlayGroupListeners();
reloadWindow();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private void loadFile(File file)
{
currentAuthoredFile = file;
try {
initializeURL(currentAuthoredFile.toURL());
} catch (Exception e) {
e.printStackTrace();
}
}
public void loadURL(URL url)
throws Exception
{
XMLDatabase systemDB = null;
try {
// try loading in the system object if there is one
String systemOtmlUrlStr =
OTConfig.getStringProp(OTConfig.SYSTEM_OTML_PROP);
if(systemOtmlUrlStr != null){
URL systemOtmlUrl = new URL(systemOtmlUrlStr);
systemDB = new XMLDatabase(systemOtmlUrl, System.out);
// don't track the resource info on the system db.
systemDB.loadObjects();
}
} catch (Exception e){
e.printStackTrace();
systemDB = null;
}
try {
xmlDB = new XMLDatabase(url, System.out);
// Only track the resource info when there isn't a user. Currently
// all classroom uses
// of OTViewer has NO_USER_MODE turned off, so using this setting
// safe to test
// the resource tracking without affecting real users.
if (userMode == OTConfig.NO_USER_MODE) {
xmlDB.setTrackResourceInfo(true);
}
xmlDB.loadObjects();
} catch (org.jdom.input.JDOMParseException e) {
String xmlWarningTitle = "XML Decoding error";
String xmlWarningMessage =
"There appears to a problem parsing the XML of this document. \n"
+ "Please show this error message to one of the workshop leaders. \n\n"
+ e.getMessage();
JOptionPane.showMessageDialog(null, xmlWarningMessage, xmlWarningTitle,
JOptionPane.ERROR_MESSAGE);
throw e;
}
addService(UserMessageHandler.class, new SwingUserMessageHandler(this));
otrunk = new OTrunkImpl(systemDB, xmlDB, services);
OTViewFactory myViewFactory =
(OTViewFactory) otrunk.getService(OTViewFactory.class);
if (myViewFactory != null) {
otViewFactory = myViewFactory;
}
OTViewContext factoryContext = otViewFactory.getViewContext();
factoryContext.addViewService(OTrunk.class, otrunk);
factoryContext.addViewService(OTFrameManager.class, frameManager);
factoryContext.addViewService(OTJComponentServiceFactory.class,
new OTJComponentServiceFactoryImpl());
factoryContext.addViewService(OTExternalAppService.class,
new OTExternalAppServiceImpl());
factoryContext.addViewService(OTUserListService.class, new OTUserListService() {
public Vector getUserList() {
return otrunk.getUsers();
}
});
currentURL = url;
}
// This method was refactored out of loadURL
private void setupBodyPanel()
throws Exception
{
bodyPanel.setTopLevelContainer(true);
bodyPanel.setOTViewFactory(otViewFactory);
// set the current mode from the viewservice to the main bodyPanel
// bodyPanel.setViewMode(otViewFactory.getDefaultMode());
// set the viewFactory of the frame manager
frameManager.setViewFactory(otViewFactory);
xmlDB.setDirty(false);
reloadWindow();
}
public OTObject getAuthoredRoot()
throws Exception
{
String rootLocalId =
OTConfig.getStringProp(OTConfig.ROOT_OBJECT_PROP);
if(rootLocalId != null){
OTID rootID = xmlDB.getOTIDFromLocalID(rootLocalId);
return otrunk.getOTObject(rootID);
}
return otrunk.getRoot();
}
public OTObject getRoot()
throws Exception
{
switch (userMode) {
case OTConfig.NO_USER_MODE:
return getAuthoredRoot();
case OTConfig.SINGLE_USER_MODE:
if (userSession == null) {
return null;
}
OTObject otRoot = getAuthoredRoot();
return otrunk.getUserRuntimeObject(otRoot, getCurrentUser());
}
return null;
}
public void reloadWindow()
throws Exception
{
OTObject root = getRoot();
boolean overrideShowTree = false;
if (userMode == OTConfig.SINGLE_USER_MODE) {
if (root == null) {
// FIXME This is an error
// the newAnonUserData should have been called before this
// method is
// called
// no user file has been started yet
overrideShowTree = true;
} else {
OTObject realRoot = otrunk.getRealRoot();
if (realRoot instanceof OTSystem) {
OTSystem localUserSystem =
(OTSystem) otrunk.getUserRuntimeObject(realRoot, getCurrentUser());
// FIXME there should be a better way than this because we
// have to handle
// multiple users.
if (localUserSystem != userSystem) {
userSystem = localUserSystem;
systemChangeListener = new OTChangeListener() {
public void stateChanged(OTChangeEvent e)
{
if ("overlays".equals(e.getProperty())) {
reloadOverlays();
}
}
};
updateOverlayGroupListeners();
userSystem.addOTChangeListener(systemChangeListener);
}
}
}
}
if (showTree && !overrideShowTree) {
OTDataObject rootDataObject = xmlDB.getRoot();
dataTreeModel.setRoot(new OTDataObjectNode("root", rootDataObject, otrunk));
folderTreeModel.setRoot(new OTFolderNode(root));
}
bodyPanel.setCurrentObject(root);
if (showTree && !overrideShowTree) {
folderTreeModel.fireTreeStructureChanged(new TreePath(
(SimpleTreeNode) folderTreeModel.getRoot()));
dataTreeModel.fireTreeStructureChanged(new TreePath(
(SimpleTreeNode) dataTreeModel.getRoot()));
}
Frame frame = (Frame) SwingUtilities.getRoot(this);
switch (userMode) {
case OTConfig.NO_USER_MODE:
if (remoteURL != null) {
frame.setTitle(baseFrameTitle + ": " + remoteURL.toString());
} else {
frame.setTitle(baseFrameTitle + ": " + currentURL.toString());
}
break;
case OTConfig.SINGLE_USER_MODE:
String userSessionLabel = null;
if (userSession != null) {
userSessionLabel = userSession.getLabel();
}
if(userSessionLabel != null){
frame.setTitle(baseFrameTitle + ": " + userSessionLabel);
} else {
frame.setTitle(baseFrameTitle);
}
break;
}
if(userSession == null){
saveUserDataAction.setEnabled(false);
saveUserDataAsAction.setEnabled(false);
} else {
saveUserDataAction.setEnabled(userSession.allowSave());
saveUserDataAsAction.setEnabled(userSession.allowSaveAs());
}
}
public void reload()
throws Exception
{
initializeURL(currentURL);
}
public OTUserSession getUserSession()
{
return userSession;
}
public OTUserObject getCurrentUser()
{
if(userSession == null){
return null;
}
return userSession.getUserObject();
}
public static void main(String[] args)
{
System.setProperty("apple.laf.useScreenMenuBar", "true");
OTViewer viewer = new OTViewer();
if (OTConfig.getBooleanProp(OTConfig.SINGLE_USER_PROP, false)) {
viewer.setUserMode(OTConfig.SINGLE_USER_MODE);
} else if (OTConfig.getBooleanProp(OTConfig.NO_USER_PROP, false)) {
viewer.setUserMode(OTConfig.NO_USER_MODE);
}
viewer.initArgs(args);
}
class ExitAction extends AbstractAction
{
/**
* nothing to serialize here.
*/
private static final long serialVersionUID = 1L;
public ExitAction()
{
super("Exit");
}
public void actionPerformed(ActionEvent e)
{
// If this suceeds then the VM will exit so
// the window will get disposed
exit();
}
}
/*
* (non-Javadoc)
*
* @see org.concord.otrunk.view.OTViewContainerListener#currentObjectChanged(org.concord.framework.otrunk.view.OTViewContainer)
*/
public void currentObjectChanged(OTViewContainerChangeEvent evt)
{
final OTViewContainer myContainer = (OTViewContainer) evt.getSource();
// TODO Auto-generated method stub
SwingUtilities.invokeLater(new Runnable() {
public void run()
{
OTObject currentObject = myContainer.getCurrentObject();
if (folderTreeArea != null) {
OTFolderNode node =
(OTFolderNode) folderTreeArea.getLastSelectedPathComponent();
if (node == null)
return;
if (node.getPfObject() != currentObject) {
folderTreeArea.setSelectionPath(null);
}
}
}
});
}
/*
* (non-Javadoc)
*
* @see javax.swing.event.TreeSelectionListener#valueChanged(javax.swing.event.TreeSelectionEvent)
*/
public void valueChanged(TreeSelectionEvent event)
{
if (event.getSource() == folderTreeArea) {
OTFolderNode node =
(OTFolderNode) folderTreeArea.getLastSelectedPathComponent();
if (node == null)
return;
OTObject pfObject = node.getPfObject();
bodyPanel.setCurrentObject(pfObject);
if (splitPane.getRightComponent() != bodyPanel) {
splitPane.setRightComponent(bodyPanel);
}
} else if (event.getSource() == dataTreeArea) {
SimpleTreeNode node =
(SimpleTreeNode) dataTreeArea.getLastSelectedPathComponent();
Object resourceValue = null;
if (node != null) {
resourceValue = node.getObject();
if (resourceValue == null) {
resourceValue = "null resource value";
}
} else {
resourceValue = "no selected data object";
}
JComponent nodeView = null;
if (resourceValue instanceof OTDataObject) {
nodeView = new OTDataObjectView((OTDataObject) resourceValue);
} else {
nodeView = new JTextArea(resourceValue.toString());
}
JScrollPane scrollPane = new JScrollPane(nodeView);
splitPane.setRightComponent(scrollPane);
}
}
private void updateRemoteURL(String defaultURL)
{
String remote = System.getProperty(OTConfig.REMOTE_URL_PROP, null);
try {
if (remote == null) {
if (defaultURL != null && defaultURL.startsWith("http:")) {
remoteURL = new URL(defaultURL);
}
} else {
remoteURL = new URL(remote);
}
} catch (Exception e) {
remoteURL = null;
System.err.println("Remote URL is invalid.");
e.printStackTrace();
}
}
public void createActions()
{
newUserDataAction = new AbstractAction("New") {
/**
* nothing to serialize here
*/
private static final long serialVersionUID = 1L;
/*
* (non-Javadoc)
*
* @see java.awt.event.ActionListener#actionPerformed(java.awt.event.ActionEvent)
*/
public void actionPerformed(ActionEvent arg0)
{
createNewUser();
}
};
loadUserDataAction = new AbstractAction("Open...") {
/**
* nothing to serialize here. Just the parent class.
*/
private static final long serialVersionUID = 1L;
/*
* (non-Javadoc)
*
* @see java.awt.event.ActionListener#actionPerformed(java.awt.event.ActionEvent)
*/
public void actionPerformed(ActionEvent arg0)
{
openUserData(true);
}
};
exportToHtmlAction = new AbstractAction("Export to html...") {
/**
* nothing to serialize here
*/
private static final long serialVersionUID = 1L;
public void actionPerformed(ActionEvent arg0)
{
File fileToSave = getReportFile();
OTMLToXHTMLConverter otxc =
new OTMLToXHTMLConverter(otViewFactory, bodyPanel.getViewContainer());
otxc.setXHTMLParams(fileToSave, 800, 600);
(new Thread(otxc)).start();
}
};
// Isn't it enabled by default?
exportToHtmlAction.setEnabled(true);
saveUserDataAction = new AbstractAction("Save") {
/**
* Nothing to serialize here
*/
private static final long serialVersionUID = 1L;
/*
* (non-Javadoc)
*
* @see java.awt.event.ActionListener#actionPerformed(java.awt.event.ActionEvent)
*/
public void actionPerformed(ActionEvent arg0)
{
userSession.save();
// the save operation might change the label used by the session
setTitle(baseFrameTitle + ": " + userSession.getLabel());
}
};
saveUserDataAsAction = new AbstractAction("Save As...") {
/**
* nothing to serizile here
*/
private static final long serialVersionUID = 1L;
/*
* (non-Javadoc)
*
* @see java.awt.event.ActionListener#actionPerformed(java.awt.event.ActionEvent)
*/
public void actionPerformed(ActionEvent arg0)
{
if(userSession instanceof OTMLUserSession){
((OTMLUserSession)userSession).setDialogParent(SwingUtilities.getRoot(OTViewer.this));
}
userSession.saveAs();
}
};
loadAction = new AbstractAction("Open Authored Content...") {
/**
* nothing to serizile here
*/
private static final long serialVersionUID = 1L;
/*
* (non-Javadoc)
*
* @see java.awt.event.ActionListener#actionPerformed(java.awt.event.ActionEvent)
*/
public void actionPerformed(ActionEvent arg0)
{
Frame frame = (Frame) SwingUtilities.getRoot(OTViewer.this);
MostRecentFileDialog mrfd =
new MostRecentFileDialog("org.concord.otviewer.openotml");
mrfd.setFilenameFilter("otml");
int retval = mrfd.showOpenDialog(frame);
File file = null;
if (retval == MostRecentFileDialog.APPROVE_OPTION) {
file = mrfd.getSelectedFile();
}
if (file != null && file.exists()) {
System.out.println("load file name: " + file);
// if they open an authored file then they are overriding
// the remoteURL,
// at least for now. This makes the title bar update
// correctly, and
// fixes a lockup that happens when they have opened a local
// file and then
// try to save it again.
remoteURL = null;
loadFile(file);
exportToHtmlAction.setEnabled(true);
}
}
};
loadAction.putValue(Action.ACCELERATOR_KEY, KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_O,
java.awt.Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()));
saveAction = new AbstractAction("Save Authored Content...") {
/**
* nothing to serialize here
*/
private static final long serialVersionUID = 1L;
/*
* (non-Javadoc)
*
* @see java.awt.event.ActionListener#actionPerformed(java.awt.event.ActionEvent)
*/
public void actionPerformed(ActionEvent arg0)
{
if (OTConfig.isRemoteSaveData() && remoteURL != null) {
try {
if (OTConfig.isRestEnabled()) {
try {
otrunk.remoteSaveData(xmlDB, remoteURL, OTViewer.HTTP_PUT);
setTitle(remoteURL.toString());
} catch (Exception e) {
otrunk.remoteSaveData(xmlDB, remoteURL, OTViewer.HTTP_POST);
setTitle(remoteURL.toString());
}
} else {
otrunk.remoteSaveData(xmlDB, remoteURL, OTViewer.HTTP_POST);
setTitle(remoteURL.toString());
}
} catch (Exception e) {
JOptionPane.showMessageDialog(
(Frame) SwingUtilities.getRoot(OTViewer.this),
"There was an error saving. Check your URL and try again.",
"Error Saving", JOptionPane.ERROR_MESSAGE);
e.printStackTrace();
}
} else {
if (currentAuthoredFile == null) {
saveAsAction.actionPerformed(arg0);
return;
}
if (checkForReplace(currentAuthoredFile)) {
try {
ExporterJDOM.export(currentAuthoredFile, xmlDB.getRoot(),
xmlDB);
xmlDB.setDirty(false);
} catch (Exception e) {
e.printStackTrace();
}
}
} // end if (remoteUrl == null)
}
};
saveAction.putValue(Action.ACCELERATOR_KEY, KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_S,
java.awt.Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()));
saveAsAction = new AbstractAction("Save Authored Content As...") {
/**
* nothing to serialize here
*/
private static final long serialVersionUID = 1L;
/*
* (non-Javadoc)
*
* @see java.awt.event.ActionListener#actionPerformed(java.awt.event.ActionEvent)
*/
public void actionPerformed(ActionEvent arg0)
{
Frame frame = (Frame) SwingUtilities.getRoot(OTViewer.this);
MostRecentFileDialog mrfd =
new MostRecentFileDialog("org.concord.otviewer.saveotml");
mrfd.setFilenameFilter("otml");
if (currentAuthoredFile != null) {
mrfd.setCurrentDirectory(currentAuthoredFile.getParentFile());
mrfd.setSelectedFile(currentAuthoredFile);
}
int retval = mrfd.showSaveDialog(frame);
File file = null;
if (retval == MostRecentFileDialog.APPROVE_OPTION) {
file = mrfd.getSelectedFile();
String fileName = file.getPath();
if (!fileName.toLowerCase().endsWith(".otml")) {
file = new File(file.getAbsolutePath() + ".otml");
}
if (checkForReplace(file)) {
try {
ExporterJDOM.export(file, xmlDB.getRoot(), xmlDB);
currentAuthoredFile = file;
currentURL = file.toURL();
xmlDB.setDirty(false);
} catch (Exception e) {
e.printStackTrace();
}
}
frame.setTitle(fileName);
remoteURL = null;
updateMenuBar();
}
}
};
saveRemoteAsAction = new AbstractAction("Save Remotely As...") {
/**
* nothing to serizile here
*/
private static final long serialVersionUID = 1L;
/*
* (non-Javadoc)
*
* @see java.awt.event.ActionListener#actionPerformed(java.awt.event.ActionEvent)
*/
public void actionPerformed(ActionEvent arg0)
{
// Pop up a dialog asking for a URL
// Post the otml to the url
JPanel panel = new JPanel();
panel.setBorder(new EmptyBorder(10, 10, 10, 10));
panel.setLayout(new BorderLayout());
JLabel prompt =
new JLabel("Please enter the URL to which you would like to save:");
prompt.setBorder(new EmptyBorder(0, 0, 10, 0));
JTextField textField = new JTextField();
if (remoteURL == null) {
textField.setText("http:
} else {
textField.setText(remoteURL.toString());
}
JPanel checkboxPanel = new JPanel();
JCheckBox restCheckbox = new JCheckBox("REST Enabled?");
restCheckbox.setSelected(OTConfig.isRestEnabled());
checkboxPanel.setBorder(new EmptyBorder(5, 5, 0, 0));
checkboxPanel.add(restCheckbox);
panel.add(prompt, BorderLayout.NORTH);
panel.add(textField, BorderLayout.CENTER);
panel.add(checkboxPanel, BorderLayout.SOUTH);
int returnVal =
CustomDialog.showOKCancelDialog(
(Frame) SwingUtilities.getRoot(OTViewer.this), // parent
panel, // custom content
"Save URL", // title
false, // resizeable
true // modal
);
if (returnVal == 0) {
try {
remoteURL = new URL(textField.getText());
// WARNING this will cause a security exception if we
// are running in a applet or jnlp which
// has a security sandbox.
System.setProperty(OTConfig.REST_ENABLED_PROP,
Boolean.toString(restCheckbox.isSelected()));
otrunk.remoteSaveData(xmlDB, remoteURL, OTViewer.HTTP_POST);
setTitle(remoteURL.toString());
updateMenuBar();
} catch (Exception e) {
System.err.println("Bad URL. Not saving.");
JOptionPane.showMessageDialog(
(Frame) SwingUtilities.getRoot(OTViewer.this),
"There was an error saving. Check your URL and try again.",
"Error Saving", JOptionPane.ERROR_MESSAGE);
e.printStackTrace();
}
} else {
// CANCELLED
}
}
};
exportImageAction = new AbstractAction("Export Image...") {
/**
* nothing to serialize here
*/
private static final long serialVersionUID = 1L;
public void actionPerformed(ActionEvent e)
{
// this introduces a dependency on concord Swing project
// instead there needs to be a way to added these actions
// through
// the xml
Component currentComp = bodyPanel.getCurrentComponent();
Util.makeScreenShot(currentComp);
}
};
exportHiResImageAction = new AbstractAction("Export Hi Res Image...") {
/**
* nothing to serialize here
*/
private static final long serialVersionUID = 1L;
public void actionPerformed(ActionEvent e)
{
Component currentComp = bodyPanel.getCurrentComponent();
Util.makeScreenShot(currentComp, 2, 2);
}
};
debugAction = new AbstractAction("Debug Mode") {
/**
* nothing to serialize here
*/
private static final long serialVersionUID = 1L;
public void actionPerformed(ActionEvent e)
{
Object source = e.getSource();
if (((JCheckBoxMenuItem) source).isSelected()) {
System.setProperty(OTConfig.DEBUG_PROP, "true");
} else {
System.setProperty(OTConfig.DEBUG_PROP, "false");
}
try {
reloadWindow();
} catch (Exception exp) {
exp.printStackTrace();
}
SwingUtilities.invokeLater(new Runnable() {
public void run()
{
updateMenuBar();
}
});
exportToHtmlAction.setEnabled(true);
}
};
showConsoleAction = new AbstractAction("Show Console") {
/**
* nothing to serialize here
*/
private static final long serialVersionUID = 1L;
public void actionPerformed(ActionEvent e)
{
if (consoleFrame != null) {
consoleFrame.setVisible(true);
}
}
};
reloadWindowAction = new AbstractAction("Reload window") {
/**
* nothing to serialize here
*/
private static final long serialVersionUID = 1L;
public void actionPerformed(ActionEvent e)
{
try {
reload();
} catch (Exception e1) {
e1.printStackTrace();
}
}
};
reloadWindowAction.putValue(Action.ACCELERATOR_KEY, KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_R,
java.awt.Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()));
exitAction = new ExitAction();
}
/**
* @return Returns the menuBar.
*/
public JMenuBar updateMenuBar()
{
JMenu fileMenu = null;
if (menuBar == null) {
menuBar = new JMenuBar();
fileMenu = new JMenu("File");
menuBar.add(fileMenu);
} else {
fileMenu = menuBar.getMenu(0);
fileMenu.removeAll();
}
if (OTConfig.isAuthorMode()) {
userMode = OTConfig.NO_USER_MODE;
}
if (userMode == OTConfig.SINGLE_USER_MODE) {
fileMenu.setEnabled(!justStarted);
// we add new and load ("open") menu items only if this is NOT launched
// by sail or if otrunk.view.destructive_menu is set to true
if (!isLaunchedBySailOTViewer() || (OTConfig.isShowDestructiveMenuItems())){
fileMenu.add(newUserDataAction);
fileMenu.add(loadUserDataAction);
}
fileMenu.add(saveUserDataAction);
fileMenu.add(saveUserDataAsAction);
}
if (OTConfig.isDebug()) {
if (userMode == OTConfig.SINGLE_USER_MODE) {
loadAction.putValue(Action.NAME, "Open Authored Content...");
saveAction.putValue(Action.NAME, "Save Authored Content");
saveAsAction.putValue(Action.NAME, "Save Authored Content As...");
saveRemoteAsAction.putValue(Action.NAME,
"Save Authored Content Remotely As...");
} else {
loadAction.putValue(Action.NAME, "Open...");
saveAction.putValue(Action.NAME, "Save");
saveAsAction.putValue(Action.NAME, "Save As...");
saveRemoteAsAction.putValue(Action.NAME, "Save Remotely As...");
}
fileMenu.add(loadAction);
fileMenu.add(saveAction);
fileMenu.add(saveAsAction);
fileMenu.add(saveRemoteAsAction);
}
if (OTConfig.isAuthorMode() && !OTConfig.isDebug()) {
if (userMode == OTConfig.SINGLE_USER_MODE) {
loadAction.putValue(Action.NAME, "Open Authored Content...");
saveAction.putValue(Action.NAME, "Save Authored Content");
saveAsAction.putValue(Action.NAME, "Save Authored Content As...");
} else {
loadAction.putValue(Action.NAME, "Open...");
saveAction.putValue(Action.NAME, "Save");
saveAsAction.putValue(Action.NAME, "Save As...");
}
fileMenu.add(loadAction);
fileMenu.add(saveAction);
fileMenu.add(saveAsAction);
}
if (OTConfig.getBooleanProp("otrunk.view.export_image", false)) {
fileMenu.add(exportImageAction);
fileMenu.add(exportHiResImageAction);
}
fileMenu.add(exportToHtmlAction);
fileMenu.add(showConsoleAction);
if (OTConfig.isAuthorMode() || OTConfig.isDebug()) {
fileMenu.add(reloadWindowAction);
}
JCheckBoxMenuItem debugItem = new JCheckBoxMenuItem(debugAction);
debugItem.setSelected(OTConfig.isDebug());
fileMenu.add(debugItem);
fileMenu.add(exitAction);
return menuBar;
}
boolean checkForReplace(File file)
{
if (file == null){
return false;
}
if (!file.exists()) {
return true; // File doesn't exist, so go ahead and save
}
if (currentAuthoredFile != null && file.compareTo(currentAuthoredFile) == 0){
return true; // we're already authoring this file, so no need to
// prompt
}
final Object[] options = { "Yes", "No" };
return javax.swing.JOptionPane.showOptionDialog(null, "The file '"
+ file.getName() + "' already exists. " + "Replace existing file?",
"Warning", javax.swing.JOptionPane.YES_NO_OPTION,
javax.swing.JOptionPane.WARNING_MESSAGE, null, options, options[1]) == javax.swing.JOptionPane.YES_OPTION;
}
/**
* FIXME This method name is confusing. The method first checks for unsaved
* changes, and if there are unsaved changes it asks the user if they want to
* "don't save", "cancel" or "save"
*
* @return
*/
public boolean checkForUnsavedUserData()
{
if(userSession == null){
return true;
}
if(userSession.hasUnsavedChanges()) {
// show dialog message telling them they haven't
// saved their work
// FIXME
String options[] = { "Don't Save", "Cancel", "Save" };
askedAboutSavingUserData = true;
int chosenOption =
JOptionPane.showOptionDialog(this, "Save Changes?", "Save Changes?",
JOptionPane.DEFAULT_OPTION, JOptionPane.WARNING_MESSAGE, null,
options, options[2]);
switch (chosenOption) {
case 0:
System.err.println("Not saving work");
break;
case 1:
System.err.println("Canceling close");
return false;
case 2:
System.err.println("Set needToSaveUserData true");
needToSaveUserData = true;
break;
}
}
return true;
}
/**
* Checks if the user has unsaved authored data. If they do then it prompts
* them to confirm what they are doing. If they cancel then it returns
* false.
*
* @return
*/
public boolean checkForUnsavedAuthorData()
{
if (xmlDB != null) {
if (xmlDB.isDirty()) {
// show dialog message telling them they haven't
// saved their work
// FIXME
String options[] = { "Don't Save", "Cancel", "Save" };
int chosenOption =
JOptionPane.showOptionDialog(this, "Save Changes?", "Save Changes?",
JOptionPane.DEFAULT_OPTION, JOptionPane.WARNING_MESSAGE, null,
options, options[2]);
switch (chosenOption) {
case 0:
System.err.println("Not saving authored data");
break;
case 1:
System.err.println("Canceling close");
return false;
case 2:
System.err.println("Saving authored data");
saveAction.actionPerformed(null);
break;
}
}
}
return true;
}
/**
* This does not check for unsaved user data
*
*/
public void newAnonUserData()
{
newUserData(OTViewerHelper.ANON_SINGLE_USER_NAME);
}
public void newUserData(String userName)
{
// call some new method for creating a new un-saved user state
// this should set the currentUserFile to null, so the save check
// prompts
// for a file name
if(userSession == null) {
throw new IllegalStateException("a OTUserSession must be supplied before newUserData can be called");
}
try {
userSession.newLayer();
OTUserObject userObject = userSession.getUserObject();
if(userName != null){
userObject.setName(userName);
}
// This will request the label from the userSession
reloadWindow();
} catch (Exception e) {
e.printStackTrace();
}
}
public boolean exit()
{
try {
if (!checkForUnsavedUserData()) {
// the user canceled the operation
return false;
}
if (OTConfig.isAuthorMode() && !checkForUnsavedAuthorData()) {
// the user canceled the operation
return false;
}
// FIXME there is a problem with this logic. If the user saved data
// just before closing
// checkForUnsavedUserData will not see any unsaved data. But if
// some view creates
// data in the viewClosed method then that data will not get saved
// here.
// I think the key to solving this is to separate the
// automatic/logging data from the
// user visible data. And then make a rule that saving data in the
// viewClosed method
// is not allowed.
bodyPanel.setCurrentObject(null);
conditionalSaveUserData();
if (otrunk != null)
otrunk.close();
} catch (Exception exp) {
exp.printStackTrace();
// exit anyhow
}
System.exit(0);
return true;
}
protected void conditionalSaveUserData()
{
if (!askedAboutSavingUserData) {
checkForUnsavedUserData();
}
if (needToSaveUserData) {
saveUserDataAction.actionPerformed(null);
} else {
System.err.println("Not saving work before closing.");
}
// Reset these back to false, so if the user is switching to a new
// user or loading a new file we are in a clean state, for that file or
// user
askedAboutSavingUserData = false;
needToSaveUserData = false;
}
public File getReportFile()
{
Frame frame = (Frame) SwingUtilities.getRoot(OTViewer.this);
MostRecentFileDialog mrfd =
new MostRecentFileDialog("org.concord.otviewer.saveotml");
mrfd.setFilenameFilter("html");
if (userSession instanceof OTMLUserSession){
OTMLUserSession otmlUserSession = (OTMLUserSession) userSession;
if(otmlUserSession.currentUserFile != null){
mrfd.setCurrentDirectory(otmlUserSession.currentUserFile.getParentFile());
}
}
int retval = mrfd.showSaveDialog(frame);
File file = null;
if (retval == MostRecentFileDialog.APPROVE_OPTION) {
file = mrfd.getSelectedFile();
String fileName = file.getPath();
if (!fileName.toLowerCase().endsWith(".html")) {
file = new File(file.getAbsolutePath() + ".html");
}
return file;
}
return null;
}
public void createNewUser()
{
if (!checkForUnsavedUserData()) {
// the user canceled the operation
return;
}
// This ensures viewClosed is called
bodyPanel.setCurrentObject(null);
conditionalSaveUserData();
// call some new method for creating a new un-saved user state
// this should set the currentUserFile to null, so the save check
// prompts
// for a file name
newAnonUserData();
exportToHtmlAction.setEnabled(true);
}
public void openUserData(boolean saveCurrentData)
{
if(saveCurrentData){
if (!checkForUnsavedUserData()) {
// the user canceled the operation
return;
}
// FIXME Calling the method below would insure the view is closed, and
// that any data that is
// is modified in that view closed operation will get saved, however if
// the user
// cancels the open dialog then we would be left in an unknown
// state. The current view would be closed which they would want to see
// again.
// bodyPanel.setCurrentObject(null);
conditionalSaveUserData();
}
if(userSession == null){
throw new IllegalStateException("can't open user data without a userSession");
}
boolean success = userSession.open();
try {
reloadWindow();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if(success){
exportToHtmlAction.setEnabled(true);
}
}
public void instructionPanel()
{
commDialog.setResizable(false);
JPanel panel = new JPanel();
panel.setBackground(Color.WHITE);
panel.setLayout(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
c.fill = GridBagConstraints.HORIZONTAL;
c.weightx = 0.5;
c.insets = new Insets(5,10,5,10);
JLabel lNew = new JLabel("Click the \"New\" button to create a new portfolio:");
JLabel lOpen = new JLabel("Click the \"Open\" button to open a saved portfolio:");
JButton bNew = new JButton("New");
JButton bOpen = new JButton("Open");
c.gridx = 0;
c.gridy = 0;
panel.add(lNew, c);
c.gridx = 1;
panel.add(bNew, c);
c.gridx = 0;
c.gridy = 1;
panel.add(lOpen, c);
c.gridx = 1;
panel.add(bOpen, c);
bNew.setOpaque(false);
bOpen.setOpaque(false);
setUserSession(new OTMLUserSession());
bNew.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
commDialog.setVisible(false);
newAnonUserData();
exportToHtmlAction.setEnabled(true);
}
});
bOpen.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
commDialog.setVisible(false);
openUserData(false);
}
});
commDialog.getContentPane().add(panel);
commDialog.setBounds(200, 200, 450, 200);
SwingUtilities.invokeLater(new Runnable() {
public void run()
{
commDialog.setVisible(true);
justStarted = false;
updateMenuBar();
}
});
}
public OTViewContainerPanel getViewContainerPanel()
{
return this.bodyPanel;
}
public void setExitAction(AbstractAction exitAction)
{
this.exitAction = exitAction;
}
/*
* (non-Javadoc)
*
* @see org.concord.applesupport.AppleApplicationAdapter#about()
*/
public void about()
{
// TODO Auto-generated method stub
}
/*
* (non-Javadoc)
*
* @see org.concord.applesupport.AppleApplicationAdapter#preferences()
*/
public void preferences()
{
// TODO Auto-generated method stub
}
public void setLaunchedBySailOTViewer(boolean launchedBySailOTViewer){
this.launchedBySailOTViewer = launchedBySailOTViewer;
}
public boolean isLaunchedBySailOTViewer(){
return launchedBySailOTViewer;
}
/*
* (non-Javadoc)
*
* @see org.concord.applesupport.AppleApplicationAdapter#quit()
*/
public void quit()
{
exitAction.actionPerformed(null);
}
public OTrunk getOTrunk()
{
return otrunk;
}
} // @jve:decl-index=0:visual-constraint="10,10"
class HtmlFileFilter extends javax.swing.filechooser.FileFilter
{
public boolean accept(File f)
{
if (f == null)
return false;
if (f.isDirectory())
return true;
return (f.getName().toLowerCase().endsWith(".html"));
}
public String getDescription()
{
return "HTML files";
}
} // @jve:decl-index=0:visual-constraint="10,10"
|
package org.jdesktop.swingx;
import java.awt.Component;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.Transferable;
import java.awt.event.ActionEvent;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.io.IOException;
import java.io.Reader;
import java.io.StringReader;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import java.util.Vector;
import java.util.regex.MatchResult;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.swing.ActionMap;
import javax.swing.DefaultComboBoxModel;
import javax.swing.DefaultListCellRenderer;
import javax.swing.JComboBox;
import javax.swing.JComponent;
import javax.swing.JEditorPane;
import javax.swing.JList;
import javax.swing.KeyStroke;
import javax.swing.SwingUtilities;
import javax.swing.event.CaretEvent;
import javax.swing.event.CaretListener;
import javax.swing.event.UndoableEditEvent;
import javax.swing.event.UndoableEditListener;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.Document;
import javax.swing.text.EditorKit;
import javax.swing.text.Element;
import javax.swing.text.MutableAttributeSet;
import javax.swing.text.Position;
import javax.swing.text.Segment;
import javax.swing.text.SimpleAttributeSet;
import javax.swing.text.StyleConstants;
import javax.swing.text.StyledDocument;
import javax.swing.text.StyledEditorKit;
import javax.swing.text.html.HTML;
import javax.swing.text.html.HTMLDocument;
import javax.swing.text.html.HTMLEditorKit;
import javax.swing.undo.CannotRedoException;
import javax.swing.undo.CannotUndoException;
import javax.swing.undo.UndoManager;
import org.jdesktop.swingx.action.ActionManager;
import org.jdesktop.swingx.action.Targetable;
/**
* An extended editor pane which has the following features built in:
* <ul>
* <li>Text search
* <li>undo/redo
* <li>simple html/plain text editing
* </ul>
*
* @author Mark Davidson
*/
public class JXEditorPane extends JEditorPane implements /*Searchable, */Targetable {
// private Matcher matcher;
private UndoableEditListener undoHandler;
private UndoManager undoManager;
private CaretListener caretHandler;
private JComboBox selector;
// The ids of supported actions. Perhaps this should be public.
private final static String ACTION_FIND = "find";
private final static String ACTION_UNDO = "undo";
private final static String ACTION_REDO = "redo";
/*
* These next 3 actions are part of a *HACK* to get cut/copy/paste
* support working in the same way as find, undo and redo. in JTextComponent
* the cut/copy/paste actions are _not_ added to the ActionMap. Instead,
* a default "transfer handler" system is used, apparently to get the text
* onto the system clipboard.
* Since there aren't any CUT/COPY/PASTE actions in the JTextComponent's action
* map, they cannot be referenced by the action framework the same way that
* find/undo/redo are. So, I added the actions here. The really hacky part
* is that by defining an Action to go along with the cut/copy/paste keys,
* I loose the default handling in the cut/copy/paste routines. So, I have
* to remove cut/copy/paste from the action map, call the appropriate
* method (cut, copy, or paste) and then add the action back into the
* map. Yuck!
*/
private final static String ACTION_CUT = "cut";
private final static String ACTION_COPY = "copy";
private final static String ACTION_PASTE = "paste";
private TargetableSupport targetSupport = new TargetableSupport(this);
private Searchable searchable;
public JXEditorPane() {
init();
}
public JXEditorPane(String url) throws IOException {
super(url);
init();
}
public JXEditorPane(String type, String text) {
super(type, text);
init();
}
public JXEditorPane(URL initialPage) throws IOException {
super(initialPage);
init();
}
private void init() {
setEditorKitForContentType("text/html", new SloppyHTMLEditorKit());
addPropertyChangeListener(new PropertyHandler());
getDocument().addUndoableEditListener(getUndoableEditListener());
initActions();
}
private class PropertyHandler implements PropertyChangeListener {
public void propertyChange(PropertyChangeEvent evt) {
String name = evt.getPropertyName();
if (name.equals("document")) {
Document doc = (Document)evt.getOldValue();
if (doc != null) {
doc.removeUndoableEditListener(getUndoableEditListener());
}
doc = (Document)evt.getNewValue();
if (doc != null) {
doc.addUndoableEditListener(getUndoableEditListener());
}
}
}
}
// pp for testing
CaretListener getCaretListener() {
return caretHandler;
}
// pp for testing
UndoableEditListener getUndoableEditListener() {
if (undoHandler == null) {
undoHandler = new UndoHandler();
undoManager = new UndoManager();
}
return undoHandler;
}
/**
* Overidden to perform document initialization based on type.
*/
public void setEditorKit(EditorKit kit) {
super.setEditorKit(kit);
if (kit instanceof StyledEditorKit) {
if (caretHandler == null) {
caretHandler = new CaretHandler();
}
addCaretListener(caretHandler);
}
}
/**
* Register the actions that this class can handle.
*/
protected void initActions() {
ActionMap map = getActionMap();
map.put(ACTION_FIND, new Actions(ACTION_FIND));
map.put(ACTION_UNDO, new Actions(ACTION_UNDO));
map.put(ACTION_REDO, new Actions(ACTION_REDO));
map.put(ACTION_CUT, new Actions(ACTION_CUT));
map.put(ACTION_COPY, new Actions(ACTION_COPY));
map.put(ACTION_PASTE, new Actions(ACTION_PASTE));
// this should be handled by the LF!
KeyStroke findStroke = KeyStroke.getKeyStroke("control F");
getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT).put(findStroke, "find");
}
// undo/redo implementation
private class UndoHandler implements UndoableEditListener {
public void undoableEditHappened(UndoableEditEvent evt) {
undoManager.addEdit(evt.getEdit());
updateActionState();
}
}
/**
* Updates the state of the actions in response to an undo/redo operation.
*/
private void updateActionState() {
// Update the state of the undo and redo actions
Runnable doEnabled = new Runnable() {
public void run() {
ActionManager manager = ActionManager.getInstance();
manager.setEnabled(ACTION_UNDO, undoManager.canUndo());
manager.setEnabled(ACTION_REDO, undoManager.canRedo());
}
};
SwingUtilities.invokeLater(doEnabled);
}
/**
* A small class which dispatches actions.
* TODO: Is there a way that we can make this static?
*/
private class Actions extends UIAction {
Actions(String name) {
super(name);
}
public void actionPerformed(ActionEvent evt) {
String name = getName();
if (ACTION_FIND.equals(name)) {
find();
}
else if (ACTION_UNDO.equals(name)) {
try {
undoManager.undo();
} catch (CannotUndoException ex) {
ex.printStackTrace();
}
updateActionState();
}
else if (ACTION_REDO.equals(name)) {
try {
undoManager.redo();
} catch (CannotRedoException ex) {
ex.printStackTrace();
}
updateActionState();
} else if (ACTION_CUT.equals(name)) {
ActionMap map = getActionMap();
map.remove(ACTION_CUT);
cut();
map.put(ACTION_CUT, this);
} else if (ACTION_COPY.equals(name)) {
ActionMap map = getActionMap();
map.remove(ACTION_COPY);
copy();
map.put(ACTION_COPY, this);
} else if (ACTION_PASTE.equals(name)) {
ActionMap map = getActionMap();
map.remove(ACTION_PASTE);
paste();
map.put(ACTION_PASTE, this);
}
else {
System.out.println("ActionHandled: " + name);
}
}
}
/**
* Retrieves a component which will be used as the paragraph selector.
* This can be placed in the toolbar.
* <p>
* Note: This is only valid for the HTMLEditorKit
*/
public JComboBox getParagraphSelector() {
if (selector == null) {
selector = new ParagraphSelector();
}
return selector;
}
/**
* A control which should be placed in the toolbar to enable
* paragraph selection.
*/
private class ParagraphSelector extends JComboBox implements ItemListener {
private Map itemMap;
public ParagraphSelector() {
// The item map is for rendering
itemMap = new HashMap();
itemMap.put(HTML.Tag.P, "Paragraph");
itemMap.put(HTML.Tag.H1, "Heading 1");
itemMap.put(HTML.Tag.H2, "Heading 2");
itemMap.put(HTML.Tag.H3, "Heading 3");
itemMap.put(HTML.Tag.H4, "Heading 4");
itemMap.put(HTML.Tag.H5, "Heading 5");
itemMap.put(HTML.Tag.H6, "Heading 6");
itemMap.put(HTML.Tag.PRE, "Preformatted");
// The list of items
Vector items = new Vector();
items.addElement(HTML.Tag.P);
items.addElement(HTML.Tag.H1);
items.addElement(HTML.Tag.H2);
items.addElement(HTML.Tag.H3);
items.addElement(HTML.Tag.H4);
items.addElement(HTML.Tag.H5);
items.addElement(HTML.Tag.H6);
items.addElement(HTML.Tag.PRE);
setModel(new DefaultComboBoxModel(items));
setRenderer(new ParagraphRenderer());
addItemListener(this);
setFocusable(false);
}
public void itemStateChanged(ItemEvent evt) {
if (evt.getStateChange() == ItemEvent.SELECTED) {
applyTag((HTML.Tag)evt.getItem());
}
}
private class ParagraphRenderer extends DefaultListCellRenderer {
public ParagraphRenderer() {
setOpaque(true);
}
public Component getListCellRendererComponent(JList list,
Object value,
int index,
boolean isSelected,
boolean cellHasFocus) {
super.getListCellRendererComponent(list, value, index, isSelected,
cellHasFocus);
setText((String)itemMap.get(value));
return this;
}
}
// TODO: Should have a rendererer which does stuff like:
// Paragraph, Heading 1, etc...
}
/**
* Applys the tag to the current selection
*/
protected void applyTag(HTML.Tag tag) {
Document doc = getDocument();
if (!(doc instanceof HTMLDocument)) {
return;
}
HTMLDocument hdoc = (HTMLDocument)doc;
int start = getSelectionStart();
int end = getSelectionEnd();
Element element = hdoc.getParagraphElement(start);
MutableAttributeSet newAttrs = new SimpleAttributeSet(element.getAttributes());
newAttrs.addAttribute(StyleConstants.NameAttribute, tag);
hdoc.setParagraphAttributes(start, end - start, newAttrs, true);
}
// private JXFindDialog dialog = null;
/**
* The paste method has been overloaded to strip off the <html><body> tags
* This doesn't really work.
*/
public void paste() {
Clipboard clipboard = getToolkit().getSystemClipboard();
Transferable content = clipboard.getContents(this);
if (content != null) {
DataFlavor[] flavors = content.getTransferDataFlavors();
try {
for (int i = 0; i < flavors.length; i++) {
if (String.class.equals(flavors[i].getRepresentationClass())) {
Object data = content.getTransferData(flavors[i]);
if (flavors[i].isMimeTypeEqual("text/plain")) {
// This works but we lose all the formatting.
replaceSelection(data.toString());
break;
} /*
else if (flavors[i].isMimeTypeEqual("text/html")) {
// This doesn't really work since we would
// have to strip off the <html><body> tags
Reader reader = flavors[i].getReaderForText(content);
int start = getSelectionStart();
int end = getSelectionEnd();
int length = end - start;
EditorKit kit = getUI().getEditorKit(this);
Document doc = getDocument();
if (length > 0) {
doc.remove(start, length);
}
kit.read(reader, doc, start);
break;
} */
}
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
private void find() {
SearchFactory.getInstance().showFindInput(this, getSearchable());
// if (dialog == null) {
// dialog = new JXFindDialog(this);
// dialog.setVisible(true);
}
/**
*
* @returns a not-null Searchable for this editor.
*/
public Searchable getSearchable() {
if (searchable == null) {
searchable = new DocumentSearchable();
}
return searchable;
}
/**
* sets the Searchable for this editor. If null, a default
* searchable will be used.
*
* @param searchable
*/
public void setSearchable(Searchable searchable) {
this.searchable = searchable;
}
public class DocumentSearchable implements Searchable {
public int search(String searchString) {
return search(searchString, -1);
}
public int search(String searchString, int columnIndex) {
Pattern pattern = null;
if (searchString != null) {
return search(Pattern.compile(searchString, 0), columnIndex);
}
return -1;
}
public int search(Pattern pattern) {
return search(pattern, -1);
}
public int search(Pattern pattern, int startIndex) {
return search(pattern, startIndex, false);
}
// Position lastFound;
int lastFoundIndex = -1;
MatchResult lastMatchResult;
String lastRegEx;
/**
* @return start position of matching string or -1
*/
public int search(Pattern pattern, final int startIndex,
boolean backwards) {
if ((pattern == null)
|| (getDocument().getLength() == 0)
|| ((startIndex > -1) && (getDocument().getLength() < startIndex))) {
updateStateAfterNotFound();
return -1;
}
int start = startIndex;
if (maybeExtendedMatch(startIndex)) {
if (foundExtendedMatch(pattern, start)) {
return lastFoundIndex;
}
start++;
}
int length;
if (backwards) {
start = 0;
if (startIndex < 0) {
length = getDocument().getLength() - 1;
} else {
length = -1 + startIndex;
}
} else {
// start = startIndex + 1;
if (start < 0)
start = 0;
length = getDocument().getLength() - start;
}
// Position position = getDocument().createPosition(startIndex);
Segment segment = new Segment();
try {
getDocument().getText(start, length, segment);
} catch (Exception ex) {
ex.printStackTrace();
}
Matcher matcher = pattern.matcher(segment.toString());
MatchResult currentResult = getMatchResult(matcher, !backwards);
if (currentResult != null) {
updateStateAfterFound(currentResult, start);
} else {
updateStateAfterNotFound();
}
return lastFoundIndex;
}
/**
* Search from same startIndex as the previous search.
* Checks if the match is different from the last (either
* extended/reduced) at the same position. Returns true
* if the current match result represents a different match
* than the last, false if no match or the same.
*
* @param pattern
* @param start
* @return
*/
private boolean foundExtendedMatch(Pattern pattern, int start) {
// JW: logic still needs cleanup...
if (pattern.pattern().equals(lastRegEx)) {
return false;
}
int length = getDocument().getLength() - start;
// Position position = getDocument().createPosition(startIndex);
Segment segment = new Segment();
try {
getDocument().getText(start, length, segment);
} catch (Exception ex) {
ex.printStackTrace();
}
Matcher matcher = pattern.matcher(segment.toString());
MatchResult currentResult = getMatchResult(matcher, true);
if (currentResult != null) {
// JW: how to compare match results reliably?
// the group().equals probably isn't the best idea...
// better check pattern?
if ((currentResult.start() == 0) &&
(!lastMatchResult.group().equals(currentResult.group()))) {
updateStateAfterFound(currentResult, start);
return true;
}
}
return false;
}
/**
* Checks if the startIndex is a candidate for trying a re-match.
*
*
* @param startIndex
* @return true if the startIndex should be re-matched, false if not.
*/
private boolean maybeExtendedMatch(final int startIndex) {
return (startIndex >= 0) && (startIndex == lastFoundIndex);
}
/**
* @param currentResult
* @param offset
* @return
*/
private int updateStateAfterFound(MatchResult currentResult, final int offset) {
int end = currentResult.end() + offset;
int found = currentResult.start() + offset;
select(found, end);
getCaret().setSelectionVisible(true);
lastFoundIndex = found;
lastMatchResult = currentResult;
lastRegEx = ((Matcher) lastMatchResult).pattern().pattern();
return found;
}
/**
* @param matcher
* @return
*/
private MatchResult getMatchResult(Matcher matcher, boolean useFirst) {
MatchResult currentResult = null;
while (matcher.find()) {
currentResult = matcher.toMatchResult();
if (useFirst) break;
}
return currentResult;
}
private void updateStateAfterNotFound() {
lastFoundIndex = -1;
lastMatchResult = null;
lastRegEx = null;
setCaretPosition(getSelectionEnd());
}
}
public boolean hasCommand(Object command) {
return targetSupport.hasCommand(command);
}
public Object[] getCommands() {
return targetSupport.getCommands();
}
public boolean doCommand(Object command, Object value) {
return targetSupport.doCommand(command, value);
}
/**
* Listens to the caret placement and adjusts the editing
* properties as appropriate.
*
* Should add more attributes as required.
*/
private class CaretHandler implements CaretListener {
public void caretUpdate(CaretEvent evt) {
StyledDocument document = (StyledDocument)getDocument();
int dot = evt.getDot();
Element elem = document.getCharacterElement(dot);
AttributeSet set = elem.getAttributes();
ActionManager manager = ActionManager.getInstance();
manager.setSelected("font-bold", StyleConstants.isBold(set));
manager.setSelected("font-italic", StyleConstants.isItalic(set));
manager.setSelected("font-underline", StyleConstants.isUnderline(set));
elem = document.getParagraphElement(dot);
set = elem.getAttributes();
// Update the paragraph selector if applicable.
if (selector != null) {
selector.setSelectedItem(set.getAttribute(StyleConstants.NameAttribute));
}
switch (StyleConstants.getAlignment(set)) {
// XXX There is a bug here. the setSelected method
// should only affect the UI actions rather than propagate
// down into the action map actions.
case StyleConstants.ALIGN_LEFT:
manager.setSelected("left-justify", true);
break;
case StyleConstants.ALIGN_CENTER:
manager.setSelected("center-justify", true);
break;
case StyleConstants.ALIGN_RIGHT:
manager.setSelected("right-justify", true);
break;
}
}
}
/**
* Handles sloppy HTML. This implementation currently only looks for
* tags that have a / at the end (self-closing tags) and fixes them
* to work with the version of HTML supported by HTMLEditorKit
* <p>TODO: Need to break this functionality out so it can take pluggable
* replacement code blocks, allowing people to write custom replacement
* routines. The idea is that with some simple modifications a lot more
* sloppy HTML can be rendered correctly.
*
* @author rbair
*/
private static final class SloppyHTMLEditorKit extends HTMLEditorKit {
public void read(Reader in, Document doc, int pos) throws IOException, BadLocationException {
//read the reader into a String
StringBuffer buffer = new StringBuffer();
int length = -1;
char[] data = new char[1024];
while ((length = in.read(data)) != -1) {
buffer.append(data, 0, length);
}
//TODO is this regex right?
StringReader reader = new StringReader(buffer.toString().replaceAll("/>", ">"));
super.read(reader, doc, pos);
}
}
}
|
package org.jdesktop.swingx;
import java.awt.Cursor;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.Insets;
import java.awt.Rectangle;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.File;
import java.lang.ref.SoftReference;
import java.net.URL;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.FutureTask;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JFileChooser;
import javax.swing.SwingUtilities;
/**
* <p>
* A panel that draws an image. The standard mode is to draw the specified image
* centered and unscaled. The component&s preferred size is based on the
* image, unless explicitly set by the user.
* </p>
* <p>
* Images to be displayed can be set based on URL, Image, etc. This is
* accomplished by passing in an image loader.
*
* <pre>
* public class URLImageLoader extends Callable<Image> {
* private URL url;
*
* public URLImageLoader(URL url) {
* url.getClass(); //null check
* this.url = url;
* }
*
* public Image call() throws Exception {
* return ImageIO.read(url);
* }
* }
*
* imagePanel.setImageLoader(new URLImageLoader(url));
* </pre>
*
* </p>
* <p>
* This component also supports allowing the user to set the image. If the
* <code>JXImagePanel</code> is editable, then when the user clicks on the
* <code>JXImagePanel</code> a FileChooser is shown allowing the user to pick
* some other image to use within the <code>JXImagePanel</code>.
* </p>
* <p>
* TODO In the future, the JXImagePanel will also support tiling of images,
* scaling, resizing, cropping, segues etc.
* </p>
* <p>
* TODO other than the image loading this component can be replicated by a
* JXPanel with the appropriate Painter. What's the point?
* </p>
*
* @author rbair
* @deprecated (pre-1.6.2) use a JXPanel with an ImagePainter; see Issue 988
*/
@Deprecated
public class JXImagePanel extends JXPanel {
public static enum Style {
CENTERED, TILED, SCALED, SCALED_KEEP_ASPECT_RATIO
}
private static final Logger LOG = Logger.getLogger(JXImagePanel.class.getName());
/**
* Text informing the user that clicking on this component will allow them
* to set the image
*/
private static final String TEXT = "<html><i><b>Click here<br>to set the image</b></i></html>";
/**
* The image to draw
*/
private SoftReference<Image> img = new SoftReference<Image>(null);
/**
* If true, then the image can be changed. Perhaps a better name is
* "readOnly", but editable was chosen to be more consistent with
* other Swing components.
*/
private boolean editable = false;
/**
* The mouse handler that is used if the component is editable
*/
private MouseHandler mhandler = new MouseHandler();
/**
* Specifies how to draw the image, i.e. what kind of Style to use when
* drawing
*/
private Style style = Style.CENTERED;
private Image defaultImage;
private Callable<Image> imageLoader;
private static final ExecutorService service = Executors.newFixedThreadPool(5);
public JXImagePanel() {
}
//TODO remove this constructor; no where else can a URL be used in this class
public JXImagePanel(URL imageUrl) {
try {
setImage(ImageIO.read(imageUrl));
} catch (Exception e) {
// TODO need convert to something meaningful
LOG.log(Level.WARNING, "", e);
}
}
/**
* Sets the image to use for the background of this panel. This image is
* painted whether the panel is opaque or translucent.
*
* @param image if null, clears the image. Otherwise, this will set the
* image to be painted. If the preferred size has not been explicitly
* set, then the image dimensions will alter the preferred size of
* the panel.
*/
public void setImage(Image image) {
if (image != img.get()) {
Image oldImage = img.get();
img = new SoftReference<Image>(image);
firePropertyChange("image", oldImage, img);
invalidate();
repaint();
}
}
/**
* @return the image used for painting the background of this panel
*/
public Image getImage() {
Image image = img.get();
//TODO perhaps we should have a default image loader?
if (image == null && imageLoader != null) {
try {
image = imageLoader.call();
img = new SoftReference<Image>(image);
} catch (Exception e) {
LOG.log(Level.WARNING, "", e);
}
}
return image;
}
/**
* @param editable
*/
public void setEditable(boolean editable) {
if (editable != this.editable) {
// if it was editable, remove the mouse handler
if (this.editable) {
removeMouseListener(mhandler);
}
this.editable = editable;
// if it is now editable, add the mouse handler
if (this.editable) {
addMouseListener(mhandler);
}
setToolTipText(editable ? TEXT : "");
firePropertyChange("editable", !editable, editable);
repaint();
}
}
/**
* @return whether the image for this panel can be changed or not via the
* UI. setImage may still be called, even if <code>isEditable</code>
* returns false.
*/
public boolean isEditable() {
return editable;
}
/**
* Sets what style to use when painting the image
*
* @param s
*/
public void setStyle(Style s) {
if (style != s) {
Style oldStyle = style;
style = s;
firePropertyChange("style", oldStyle, s);
repaint();
}
}
/**
* @return the Style used for drawing the image (CENTERED, TILED, etc).
*/
public Style getStyle() {
return style;
}
/**
* {@inheritDoc}
* The old property value in PCE fired by this method might not be always correct!
*/
@Override
public Dimension getPreferredSize() {
if (!isPreferredSizeSet() && img != null) {
Image img = this.img.get();
// was img GCed in the mean time?
if (img != null) {
// it has not been explicitly set, so return the width/height of
// the image
int width = img.getWidth(null);
int height = img.getHeight(null);
if (width == -1 || height == -1) {
return super.getPreferredSize();
}
Insets insets = getInsets();
width += insets.left + insets.right;
height += insets.top + insets.bottom;
return new Dimension(width, height);
}
}
return super.getPreferredSize();
}
/**
* Overridden to paint the image on the panel
*
* @param g
*/
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
Image img = this.img.get();
if (img == null && imageLoader != null) {
// schedule for loading (will repaint itself once loaded)
// have to use new future task every time as it holds strong
// reference to the object it retrieved and doesn't allow to reset
service.execute(new FutureTask<Image>(imageLoader) {
@Override
protected void done() {
super.done();
SwingUtilities.invokeLater(new Runnable() {
public void run() {
try {
JXImagePanel.this.setImage(get());
} catch (InterruptedException e) {
// ignore - canceled image load
} catch (ExecutionException e) {
LOG.log(Level.WARNING, "", e);
}
}
});
}
});
img = defaultImage;
}
if (img != null) {
final int imgWidth = img.getWidth(null);
final int imgHeight = img.getHeight(null);
if (imgWidth == -1 || imgHeight == -1) {
// image hasn't completed loading, return
return;
}
Insets insets = getInsets();
final int pw = getWidth() - insets.left - insets.right;
final int ph = getHeight() - insets.top - insets.bottom;
switch (style) {
case CENTERED:
Rectangle clipRect = g2.getClipBounds();
int imageX = (pw - imgWidth) / 2 + insets.left;
int imageY = (ph - imgHeight) / 2 + insets.top;
Rectangle r = SwingUtilities.computeIntersection(imageX, imageY, imgWidth, imgHeight, clipRect);
if (r.x == 0 && r.y == 0 && (r.width == 0 || r.height == 0)) {
return;
}
// I have my new clipping rectangle "r" in clipRect space.
// It is therefore the new clipRect.
clipRect = r;
// since I have the intersection, all I need to do is adjust the
// x & y values for the image
int txClipX = clipRect.x - imageX;
int txClipY = clipRect.y - imageY;
int txClipW = clipRect.width;
int txClipH = clipRect.height;
g2.drawImage(img, clipRect.x, clipRect.y, clipRect.x + clipRect.width, clipRect.y + clipRect.height, txClipX, txClipY, txClipX + txClipW, txClipY + txClipH, null);
break;
case TILED:
g2.translate(insets.left, insets.top);
Rectangle clip = g2.getClipBounds();
g2.setClip(0, 0, pw, ph);
int totalH = 0;
while (totalH < ph) {
int totalW = 0;
while (totalW < pw) {
g2.drawImage(img, totalW, totalH, null);
totalW += img.getWidth(null);
}
totalH += img.getHeight(null);
}
g2.setClip(clip);
g2.translate(-insets.left, -insets.top);
break;
case SCALED:
g2.drawImage(img, insets.left, insets.top, pw, ph, null);
break;
case SCALED_KEEP_ASPECT_RATIO:
int w = pw;
int h = ph;
final float ratioW = ((float) w) / ((float) imgWidth);
final float ratioH = ((float) h) / ((float) imgHeight);
if (ratioW < ratioH) {
h = (int) (imgHeight * ratioW);
} else {
w = (int) (imgWidth * ratioH);
}
final int x = (pw - w) / 2 + insets.left;
final int y = (ph - h) / 2 + insets.top;
g2.drawImage(img, x, y, w, h, null);
break;
default:
LOG.fine("unimplemented");
g2.drawImage(img, insets.left, insets.top, this);
break;
}
}
}
/**
* Handles click events on the component
*/
private class MouseHandler extends MouseAdapter {
private Cursor oldCursor;
private JFileChooser chooser;
@Override
public void mouseClicked(MouseEvent evt) {
if (chooser == null) {
chooser = new JFileChooser();
}
int retVal = chooser.showOpenDialog(JXImagePanel.this);
if (retVal == JFileChooser.APPROVE_OPTION) {
File file = chooser.getSelectedFile();
try {
setImage(new ImageIcon(file.toURI().toURL()).getImage());
} catch (Exception ex) {
}
}
}
@Override
public void mouseEntered(MouseEvent evt) {
if (oldCursor == null) {
oldCursor = getCursor();
setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
}
}
@Override
public void mouseExited(MouseEvent evt) {
if (oldCursor != null) {
setCursor(oldCursor);
oldCursor = null;
}
}
}
public void setDefaultImage(Image def) {
this.defaultImage = def;
}
public void setImageLoader(Callable<Image> loadImage) {
this.imageLoader = loadImage;
}
}
|
package org.ccnx.ccn.utils;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.security.InvalidKeyException;
import java.util.logging.Level;
import org.ccnx.ccn.CCNHandle;
import org.ccnx.ccn.config.ConfigurationException;
import org.ccnx.ccn.config.UserConfiguration;
import org.ccnx.ccn.impl.support.Log;
import org.ccnx.ccn.io.CCNFileOutputStream;
import org.ccnx.ccn.io.CCNOutputStream;
import org.ccnx.ccn.io.RepositoryFileOutputStream;
import org.ccnx.ccn.io.RepositoryOutputStream;
import org.ccnx.ccn.profiles.namespace.NamespaceManager;
import org.ccnx.ccn.profiles.security.access.group.GroupAccessControlManager;
import org.ccnx.ccn.protocol.ContentName;
import org.ccnx.ccn.protocol.MalformedContentNameStringException;
/**
* Command-line utility to write a file to ccnd; requires a corresponding ccngetfile
* to pull the data or it will not move (flow balance).
**/
public class ccnputfile {
private static int BLOCK_SIZE = 8096;
private static boolean rawMode = false;
private static Integer timeout = null;
private static boolean unversioned = false;
private static boolean verbose = false;
private static ContentName userStorage = ContentName.fromNative(UserConfiguration.defaultNamespace(), "Users");
private static ContentName groupStorage = ContentName.fromNative(UserConfiguration.defaultNamespace(), "Groups");
/**
* @param args
*/
public static void main(String[] args) {
Log.setDefaultLevel(Level.WARNING);
int startArg = 0;
for (int i = 0; i < args.length - 2; i++) {
if (args[i].equals(("-raw"))) {
if (startArg <= i)
startArg = i + 1;
rawMode = true;
} else if (args[i].equals("-unversioned")) {
if (startArg <= i)
startArg = i + 1;
unversioned = true;
} else if (args[i].equals("-timeout")) {
if (args.length < (i + 2)) {
usage();
}
try {
timeout = Integer.parseInt(args[++i]);
} catch (NumberFormatException nfe) {
usage();
}
if (startArg <= i)
startArg = i + 1;
} else if (args[i].equals("-log")) {
Level level = null;
if (args.length < (i + 2)) {
usage();
}
try {
level = Level.parse(args[++i]);
} catch (NumberFormatException nfe) {
usage();
}
Log.setLevel(level);
if (startArg <= i)
startArg = i + 1;
} else if (args[i].equals("-v")) {
verbose = true;
if (startArg <= i)
startArg = i + 1;
} else if (args[i].equals("-as")) {
if (args.length < (i + 2)) {
usage();
}
setUser(args[++i]);
if (startArg <= i)
startArg = i + 1;
} else if (args[i].equals("-ac")) {
setAccessControl();
if (startArg <= i)
startArg = i + 1;
}
else {
usage();
}
}
if (args.length < startArg + 2) {
usage();
}
long starttime = System.currentTimeMillis();
try {
// If we get one file name, put as the specific name given.
// If we get more than one, put underneath the first as parent.
// Ideally want to use newVersion to get latest version. Start
// with random version.
ContentName argName = ContentName.fromURI(args[startArg]);
CCNHandle handle = CCNHandle.open();
if (args.length == (startArg + 2)) {
if (verbose)
Log.info("ccnputfile: putting file " + args[startArg + 1]);
doPut(handle, args[startArg + 1], argName);
if (verbose)
System.out.println("ccnputfile took: "+(System.currentTimeMillis() - starttime)+" ms");
System.exit(0);
} else {
for (int i=startArg + 1; i < args.length; ++i) {
// put as child of name
ContentName nodeName = ContentName.fromURI(argName, args[i]);
doPut(handle, args[i], nodeName);
}
if (verbose)
System.out.println("ccnputfile took: "+(System.currentTimeMillis() - starttime)+" ms");
System.exit(0);
}
} catch (ConfigurationException e) {
System.out.println("Configuration exception in put: " + e.getMessage());
e.printStackTrace();
} catch (MalformedContentNameStringException e) {
System.out.println("Malformed name: " + args[startArg] + " " + e.getMessage());
e.printStackTrace();
} catch (IOException e) {
System.out.println("Cannot read file. " + e.getMessage());
e.printStackTrace();
} catch (InvalidKeyException e) {
System.out.println("Cannot publish invalid key: " + e.getMessage());
e.printStackTrace();
}
System.exit(1);
}
protected static void doPut(CCNHandle handle, String fileName,
ContentName nodeName) throws IOException, InvalidKeyException, ConfigurationException {
InputStream is;
if (verbose)
System.out.printf("filename %s\n", fileName);
if (fileName.startsWith("http:
if (verbose)
System.out.printf("filename is http\n");
is = new URL(fileName).openStream();
} else {
if (verbose)
System.out.printf("filename is file\n");
File theFile = new File(fileName);
if (!theFile.exists()) {
System.out.println("No such file: " + theFile.getName());
usage();
}
is = new FileInputStream(theFile);
}
// If we are using a repository, make sure our key is available to
// repository clients. For now, write an unversioned form of key.
if (!rawMode) {
handle.keyManager().publishKeyToRepository();
}
CCNOutputStream ostream;
// Use file stream in both cases to match behavior. CCNOutputStream doesn't do
// versioning and neither it nor CCNVersionedOutputStream add headers.
if (rawMode) {
if (unversioned)
ostream = new CCNOutputStream(nodeName, handle);
else
ostream = new CCNFileOutputStream(nodeName, handle);
} else {
if (unversioned)
ostream = new RepositoryOutputStream(nodeName, handle);
else
ostream = new RepositoryFileOutputStream(nodeName, handle);
}
if (timeout != null)
ostream.setTimeout(timeout);
do_write(ostream, is);
// leave this one as always printing for now
System.out.println("Inserted file " + fileName + ".");
}
private static void do_write(CCNOutputStream ostream, InputStream is) throws IOException {
long time = System.currentTimeMillis();
int size = BLOCK_SIZE;
int readLen = 0;
byte [] buffer = new byte[BLOCK_SIZE];
Log.finer("do_write: " + is.available() + " bytes left.");
while ((readLen = is.read(buffer, 0, size)) != -1){
ostream.write(buffer, 0, readLen);
Log.finer("do_write: wrote " + size + " bytes.");
Log.finer("do_write: " + is.available() + " bytes left.");
}
ostream.close();
Log.fine("finished write: "+(System.currentTimeMillis() - time));
}
public static void usage() {
System.out.println("usage: ccnputfile [-v (verbose)] [-raw] [-unversioned] [-timeout millis] [-log level] [-as pathToKeystore] [-ac (access control)] <ccnname> (<filename>|<url>)*");
System.exit(1);
}
private static void setUser(String pathToKeystore) {
File userDirectory = new File(pathToKeystore);
String userConfigDir = userDirectory.getAbsolutePath();
System.out.println("Loading keystore from: " + userConfigDir);
UserConfiguration.setUserConfigurationDirectory(userConfigDir);
// Assume here that the name of the file is the userName
String userName = userDirectory.getName();
if (userName != null) {
System.out.println("User: " + userName);
UserConfiguration.setUserName(userName);
}
}
private static void setAccessControl() {
// register a group access control manager with the namespace manager
try {
GroupAccessControlManager gacm = new GroupAccessControlManager(ContentName.fromNative("/"), groupStorage, userStorage, CCNHandle.open());
NamespaceManager.registerACM(gacm);
} catch (Exception e) {
e.printStackTrace();
System.exit(1);
}
}
}
|
package aQute.bnd.build;
import java.io.*;
import java.lang.ref.*;
import java.util.*;
import java.util.concurrent.*;
import java.util.concurrent.locks.*;
import java.util.jar.*;
import javax.naming.*;
import aQute.bnd.maven.support.*;
import aQute.bnd.service.*;
import aQute.bnd.service.action.*;
import aQute.lib.deployer.*;
import aQute.lib.io.*;
import aQute.lib.osgi.*;
import aQute.libg.reporter.*;
public class Workspace extends Processor {
public static final String BUILDFILE = "build.bnd";
public static final String CNFDIR = "cnf";
public static final String BNDDIR = "bnd";
public static final String CACHEDIR = "cache";
static Map<File,WeakReference<Workspace>> cache = newHashMap();
final Map<String,Project> models = newHashMap();
final Map<String,Action> commands = newMap();
final File buildDir;
final Maven maven = new Maven(Processor.getExecutor());
/**
* This static method finds the workspace and creates a project (or returns
* an existing project)
*
* @param projectDir
* @return
*/
public static Project getProject(File projectDir) throws Exception {
projectDir = projectDir.getAbsoluteFile();
assert projectDir.isDirectory();
Workspace ws = getWorkspace(projectDir.getParentFile());
return ws.getProject(projectDir.getName());
}
public static Workspace getWorkspace(File parent) throws Exception {
File workspaceDir = parent.getAbsoluteFile();
// the cnf directory can actually be a
// file that redirects
while (workspaceDir.isDirectory()) {
File test = new File(workspaceDir, CNFDIR);
if (!test.exists())
test = new File(workspaceDir, BNDDIR);
if (test.isDirectory())
break;
if (test.isFile()) {
String redirect = IO.collect(test).trim();
test = getFile(test.getParentFile(), redirect).getAbsoluteFile();
workspaceDir = test;
}
if (!test.exists())
throw new IllegalArgumentException("No Workspace found from: " + parent);
}
synchronized (cache) {
WeakReference<Workspace> wsr = cache.get(workspaceDir);
Workspace ws;
if (wsr == null || (ws = wsr.get()) == null) {
ws = new Workspace(workspaceDir);
cache.put(workspaceDir, new WeakReference<Workspace>(ws));
}
return ws;
}
}
public Workspace(File dir) throws Exception {
dir = dir.getAbsoluteFile();
dir.mkdirs();
assert dir.isDirectory();
File buildDir = new File(dir, BNDDIR).getAbsoluteFile();
if (!buildDir.isDirectory())
buildDir = new File(dir, CNFDIR).getAbsoluteFile();
this.buildDir = buildDir;
File buildFile = new File(buildDir, BUILDFILE).getAbsoluteFile();
if (!buildFile.isFile())
warning("No Build File in " + dir);
setProperties(buildFile, dir);
propertiesChanged();
}
public Project getProject(String bsn) throws Exception {
synchronized (models) {
Project project = models.get(bsn);
if (project != null)
return project;
File projectDir = getFile(bsn);
project = new Project(this, projectDir);
if (!project.isValid())
return null;
models.put(bsn, project);
return project;
}
}
public boolean isPresent(String name) {
return models.containsKey(name);
}
public Collection<Project> getCurrentProjects() {
return models.values();
}
public boolean refresh() {
if (super.refresh()) {
for (Project project : getCurrentProjects()) {
project.propertiesChanged();
}
return true;
}
return false;
}
@Override
public void propertiesChanged() {
super.propertiesChanged();
File extDir = new File(this.buildDir, "ext");
File[] extensions = extDir.listFiles();
if (extensions != null) {
for (File extension : extensions) {
String extensionName = extension.getName();
if (extensionName.endsWith(".bnd")) {
extensionName = extensionName.substring(0, extensionName.length() - ".bnd".length());
try {
doIncludeFile(extension, false, getProperties(), "ext." + extensionName);
}
catch (Exception e) {
error("PropertiesChanged: " + e.getMessage());
}
}
}
}
}
public String _workspace(String args[]) {
return getBase().getAbsolutePath();
}
public void addCommand(String menu, Action action) {
commands.put(menu, action);
}
public void removeCommand(String menu) {
commands.remove(menu);
}
public void fillActions(Map<String,Action> all) {
all.putAll(commands);
}
public Collection<Project> getAllProjects() throws Exception {
List<Project> projects = new ArrayList<Project>();
for (File file : getBase().listFiles()) {
if (new File(file, Project.BNDFILE).isFile())
projects.add(getProject(file));
}
return projects;
}
/**
* Inform any listeners that we changed a file (created/deleted/changed).
*
* @param f
* The changed file
*/
public void changedFile(File f) {
List<BndListener> listeners = getPlugins(BndListener.class);
for (BndListener l : listeners)
try {
l.changed(f);
}
catch (Exception e) {
e.printStackTrace();
}
}
public void bracket(boolean begin) {
List<BndListener> listeners = getPlugins(BndListener.class);
for (BndListener l : listeners)
try {
if (begin)
l.begin();
else
l.end();
}
catch (Exception e) {
// who cares?
}
}
/**
* Signal a BndListener plugin. We ran an infinite bug loop :-(
*/
final ThreadLocal<Reporter> signalBusy = new ThreadLocal<Reporter>();
public void signal(Reporter reporter) {
if (signalBusy.get() != null)
return;
signalBusy.set(reporter);
try {
List<BndListener> listeners = getPlugins(BndListener.class);
for (BndListener l : listeners)
try {
l.signal(this);
}
catch (Exception e) {
// who cares?
}
}
catch (Exception e) {
// Ignore
}
finally {
signalBusy.set(null);
}
}
@Override
public void signal() {
signal(this);
}
void copy(InputStream in, OutputStream out) throws Exception {
byte data[] = new byte[10000];
int size = in.read(data);
while (size > 0) {
out.write(data, 0, size);
size = in.read(data);
}
}
class CachedFileRepo extends FileRepo {
final Lock lock = new ReentrantLock();
boolean inited;
CachedFileRepo() {
super("cache", getFile(buildDir, CACHEDIR), false);
}
public String toString() {
return "bnd-cache";
}
protected void init() throws Exception {
if (lock.tryLock(50, TimeUnit.SECONDS) == false)
throw new TimeLimitExceededException("Cached File Repo is locked and can't acquire it");
try {
if (!inited) {
inited = true;
root.mkdirs();
if (!root.isDirectory())
throw new IllegalArgumentException("Cannot create cache dir " + root);
InputStream in = getClass().getResourceAsStream(EMBEDDED_REPO);
if (in != null)
unzip(in, root);
else {
System.err.println("!!!! Couldn't find embedded-repo.jar in bundle ");
error("Couldn't find embedded-repo.jar in bundle ");
}
}
}
finally {
lock.unlock();
}
}
void unzip(InputStream in, File dir) throws Exception {
try {
JarInputStream jin = new JarInputStream(in);
JarEntry jentry = jin.getNextJarEntry();
while (jentry != null) {
if (!jentry.isDirectory()) {
File dest = Processor.getFile(dir, jentry.getName());
if (!dest.isFile() || dest.lastModified() < jentry.getTime() || jentry.getTime() == 0) {
dest.getParentFile().mkdirs();
FileOutputStream out = new FileOutputStream(dest);
try {
copy(jin, out);
}
finally {
out.close();
}
}
}
jentry = jin.getNextJarEntry();
}
}
finally {
in.close();
}
}
}
public List<RepositoryPlugin> getRepositories() {
return getPlugins(RepositoryPlugin.class);
}
public Collection<Project> getBuildOrder() throws Exception {
List<Project> result = new ArrayList<Project>();
for (Project project : getAllProjects()) {
Collection<Project> dependsOn = project.getDependson();
getBuildOrder(dependsOn, result);
if (!result.contains(project)) {
result.add(project);
}
}
return result;
}
private void getBuildOrder(Collection<Project> dependsOn, List<Project> result) throws Exception {
for (Project project : dependsOn) {
Collection<Project> subProjects = project.getDependson();
for (Project subProject : subProjects) {
if (!result.contains(subProject)) {
result.add(subProject);
}
}
if (!result.contains(project)) {
result.add(project);
}
}
}
public static Workspace getWorkspace(String path) throws Exception {
File file = IO.getFile(new File(""), path);
return getWorkspace(file);
}
public Maven getMaven() {
return maven;
}
@Override
protected void setTypeSpecificPlugins(Set<Object> list) {
super.setTypeSpecificPlugins(list);
list.add(maven);
list.add(new CachedFileRepo());
}
}
|
package aQute.bnd.http;
import java.io.Closeable;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.reflect.Type;
import java.net.Authenticator;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.PasswordAuthentication;
import java.net.ProtocolException;
import java.net.SocketTimeoutException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.net.URLConnection;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Map.Entry;
import java.util.TimeZone;
import java.util.concurrent.Callable;
import java.util.zip.GZIPInputStream;
import java.util.zip.InflaterInputStream;
import aQute.bnd.connection.settings.ConnectionSettings;
import aQute.bnd.http.URLCache.Info;
import aQute.bnd.osgi.Processor;
import aQute.bnd.service.Registry;
import aQute.bnd.service.progress.ProgressPlugin;
import aQute.bnd.service.progress.ProgressPlugin.Task;
import aQute.bnd.service.url.ProxyHandler;
import aQute.bnd.service.url.ProxyHandler.ProxySetup;
import aQute.bnd.service.url.State;
import aQute.bnd.service.url.TaggedData;
import aQute.bnd.service.url.URLConnectionHandler;
import aQute.bnd.service.url.URLConnector;
import aQute.lib.io.IO;
import aQute.lib.json.JSONCodec;
import aQute.libg.reporter.ReporterAdapter;
import aQute.libg.reporter.slf4j.Slf4jReporter;
import aQute.service.reporter.Reporter;
/**
* A simple Http Client that inter-works with the bnd registry. It provides an
* easy way to construct a URL request. The request is then decorated with third
* parties that are in the bnd registry for proxies and authentication models.
*/
public class HttpClient implements Closeable, URLConnector {
public static final SimpleDateFormat sdf = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss z", Locale.ENGLISH);
static {
sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
}
private final List<ProxyHandler> proxyHandlers = new ArrayList<>();
private final List<URLConnectionHandler> connectionHandlers = new ArrayList<>();
private ThreadLocal<PasswordAuthentication> passwordAuthentication = new ThreadLocal<>();
private boolean inited;
private static JSONCodec codec = new JSONCodec();
private URLCache cache = new URLCache(IO.getFile("~/.bnd/urlcache"));
private Registry registry = null;
private Reporter reporter = new Slf4jReporter(HttpClient.class);
private ProgressPlugin progress;
public HttpClient() {}
synchronized void init() {
if (inited)
return;
inited = true;
progress = registry != null ? registry.getPlugin(ProgressPlugin.class) : null;
Authenticator.setDefault(new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return passwordAuthentication.get();
}
});
}
public void close() {
Authenticator.setDefault(null);
}
@Override
public InputStream connect(URL url) throws Exception {
return build().get(InputStream.class).go(url);
}
@Override
public TaggedData connectTagged(URL url) throws Exception {
return build().get(TaggedData.class).go(url);
}
@Override
public TaggedData connectTagged(URL url, String tag) throws Exception {
return build().get(TaggedData.class).ifNoneMatch(tag).go(url);
}
public HttpRequest<Object> build() {
return new HttpRequest<Object>(this);
}
public Object send(final HttpRequest< ? > request) throws Exception {
if (request.isCache()) {
return doCached(request);
} else {
TaggedData in = send0(request);
if (request.download == TaggedData.class)
return in;
switch (in.getState()) {
case NOT_FOUND :
return null;
case OTHER :
in.throwIt();
return null;
case UNMODIFIED :
case UPDATED :
default :
break;
}
return convert(request.download, in.getInputStream());
}
}
Object doCached(final HttpRequest< ? > request) throws Exception, IOException {
TaggedData tag = doCached0(request);
if (request.download == TaggedData.class)
return tag;
if (request.download == State.class)
return tag.getState();
switch (tag.getState()) {
case NOT_FOUND :
return null;
case OTHER :
throw new HttpRequestException(tag);
case UNMODIFIED :
case UPDATED :
default :
return convert(request.download, request.useCacheFile, tag);
}
}
TaggedData doCached0(final HttpRequest< ? > request) throws Exception, IOException {
reporter.trace("cached %s", request.url);
try (Info info = cache.get(request.useCacheFile, request.url.toURI())) {
request.useCacheFile = info.file;
if (info.isPresent()) {
// We have a file in the cache, check if it is within
// our accepted stale period
if (info.file.lastModified() + request.maxStale < System.currentTimeMillis()) {
// Ok, expired. So check if there is a newer one on the
// server
request.ifNoneMatch(info.getETag());
TaggedData in = send0(request);
if (in.isOk()) {
// update the cache from the input stream
info.update(in.getInputStream(), in.getTag(), in.getModified());
}
return in;
} else {
return new TaggedData(request.url.toURI(), HttpURLConnection.HTTP_NOT_MODIFIED, info.file);
}
} else {
// No entry in the cache, but we are cached
request.ifMatch = null;
request.ifNoneMatch = null;
request.ifModifiedSince = -1;
TaggedData in = send0(request);
if (in.isOk()) {
info.update(in.getInputStream(), in.getTag(), in.getModified());
}
return in;
}
}
}
public TaggedData send0(final HttpRequest< ? > request) throws Exception {
final ProxySetup proxy = getProxySetup(request.url);
final URLConnection con = getProxiedAndConfiguredConnection(request.url, proxy);
final HttpURLConnection hcon = (HttpURLConnection) (con instanceof HttpURLConnection ? con : null);
if (request.ifNoneMatch != null) {
request.headers.put("If-None-Match", entitytag(request.ifNoneMatch));
}
if (request.ifMatch != null) {
request.headers.put("If-Match", "\"" + entitytag(request.ifMatch));
}
if (request.ifModifiedSince > 0) {
synchronized (sdf) {
sdf.setTimeZone(TimeZone.getTimeZone("GMT"));
String format = sdf.format(new Date(request.ifModifiedSince));
request.headers.put("If-Modified-Since", format);
}
}
if (request.ifUnmodifiedSince != 0) {
synchronized (sdf) {
sdf.setTimeZone(TimeZone.getTimeZone("GMT"));
String format = sdf.format(new Date(request.ifUnmodifiedSince));
request.headers.put("If-Unmodified-Since", format);
}
}
setHeaders(request.headers, con);
configureHttpConnection(request.verb, hcon);
final ProgressPlugin.Task task = getTask(request);
try {
TaggedData td = connectWithProxy(proxy, new Callable<TaggedData>() {
@Override
public TaggedData call() throws Exception {
return doConnect(request.upload, request.download, con, hcon, request, task);
}
});
reporter.trace("result %s", td);
task.done(td.toString(), null);
return td;
} catch (Throwable t) {
task.done("Failed " + t.getMessage(), t);
throw t;
}
}
ProgressPlugin.Task getTask(final HttpRequest< ? > request) {
final ProgressPlugin.Task task;
if (progress != null) {
task = progress.startTask("Download " + request.url, 100);
} else {
task = new ProgressPlugin.Task() {
@Override
public void worked(int units) {}
@Override
public void done(String message, Throwable e) {}
@Override
public boolean isCanceled() {
return Thread.currentThread().isInterrupted();
}
};
}
return task;
}
private String entitytag(String entity) {
if (entity == null || entity.isEmpty() || "*".equals(entity))
return entity;
return entity;
// return "\"" + entity + "\"";
}
public ProxySetup getProxySetup(URL url) throws Exception {
init();
for (ProxyHandler ph : getProxyHandlers()) {
ProxySetup setup = ph.forURL(url);
if (setup != null) {
reporter.trace("Proxy %s", setup);
return setup;
}
}
return null;
}
public <T> T connectWithProxy(ProxySetup proxySetup, Callable<T> r) throws Exception {
if (proxySetup == null)
return r.call();
passwordAuthentication.set(proxySetup.authentication);
try {
return r.call();
} finally {
passwordAuthentication.set(null);
}
}
private URLConnection getProxiedAndConfiguredConnection(URL url, ProxySetup proxy) throws IOException, Exception {
final URLConnection urlc = proxy != null ? url.openConnection(proxy.proxy) : url.openConnection();
URLConnectionHandler matching = findMatchingHandler(url);
if (matching == null)
return urlc;
matching.handle(urlc);
return urlc;
}
public URLConnectionHandler findMatchingHandler(URL url) throws Exception {
for (URLConnectionHandler urlh : getURLConnectionHandlers()) {
if (urlh.matches(url)) {
reporter.trace("Decorate %s with handler %s", url, urlh);
return urlh;
} else
reporter.trace("No match for %s, handler %s", url, urlh);
}
return null;
}
private synchronized Collection< ? extends URLConnectionHandler> getURLConnectionHandlers() throws Exception {
if (connectionHandlers.isEmpty() && registry != null) {
List<URLConnectionHandler> connectionHandlers = registry.getPlugins(URLConnectionHandler.class);
this.connectionHandlers.addAll(connectionHandlers);
reporter.trace("URL Connection handlers %s", connectionHandlers);
}
return connectionHandlers;
}
private synchronized Collection< ? extends ProxyHandler> getProxyHandlers() throws Exception {
if (proxyHandlers.isEmpty() && registry != null) {
List<ProxyHandler> proxyHandlers = registry.getPlugins(ProxyHandler.class);
proxyHandlers.addAll(proxyHandlers);
reporter.trace("Proxy handlers %s", proxyHandlers);
}
return proxyHandlers;
}
private InputStream createProgressWrappedStream(InputStream inputStream, String name, int size, Task task,
long timeout) {
if (registry == null)
return inputStream;
return new ProgressWrappingStream(inputStream, name, size, task, timeout);
}
private TaggedData doConnect(Object put, Type ref, final URLConnection con, final HttpURLConnection hcon,
HttpRequest< ? > request, ProgressPlugin.Task task) throws IOException, Exception {
if (put != null) {
task.worked(1);
doOutput(put, con, request);
} else
reporter.trace("%s %s", request.verb, request.url);
if (request.timeout > 0) {
con.setConnectTimeout((int) request.timeout * 10);
con.setReadTimeout((int) (5000 > request.timeout ? request.timeout : 5000));
} else {
con.setConnectTimeout(120000);
con.setReadTimeout(60000);
}
try {
if (hcon == null) {
// not http
try {
con.connect();
InputStream in = con.getInputStream();
return new TaggedData(con, in, request.useCacheFile);
} catch (FileNotFoundException e) {
return new TaggedData(con.getURL().toURI(), 404, request.useCacheFile);
}
}
int code = hcon.getResponseCode();
if (code == -1)
System.out.println("WTF?");
// Though we ask Java to handle the redirects
// it does not do it for https <-> http :-(
if (code == HttpURLConnection.HTTP_MOVED_TEMP || code == HttpURLConnection.HTTP_MOVED_PERM
|| code == HttpURLConnection.HTTP_SEE_OTHER) {
if (request.redirects
String location = hcon.getHeaderField("Location");
request.url = new URL(location);
return send0(request);
}
}
if (isUpdateInfo(con, request, code)) {
File file = (File) request.upload;
String etag = con.getHeaderField("ETag");
try (Info info = cache.get(file, con.getURL().toURI());) {
info.update(etag);
}
}
if ((code / 100) != 2) {
return new TaggedData(con, null, request.useCacheFile);
}
// Do not enclose in resource try! InputStream is potentially
// used
// later
InputStream xin = con.getInputStream();
InputStream in = handleContentEncoding(hcon, xin);
in = createProgressWrappedStream(in, con.toString(), con.getContentLength(), task, request.timeout);
return new TaggedData(con, in, request.useCacheFile);
} catch (SocketTimeoutException ste) {
ste.printStackTrace();
return new TaggedData(request.url.toURI(), HttpURLConnection.HTTP_GATEWAY_TIMEOUT, request.useCacheFile);
}
}
boolean isUpdateInfo(final URLConnection con, HttpRequest< ? > request, int code) {
return request.upload instanceof File && request.updateTag && code == HttpURLConnection.HTTP_CREATED
&& con.getHeaderField("ETag") != null;
}
private Object convert(Type type, File in, TaggedData tag) throws IOException, Exception {
if (type == TaggedData.class)
return in;
if (type == File.class)
return in;
try (FileInputStream fin = new FileInputStream(in)) {
return convert(type, fin);
}
}
private Object convert(Type ref, InputStream in) throws IOException, Exception {
if (ref instanceof Class) {
Class< ? > refc = (Class< ? >) ref;
if (refc == byte[].class) {
return IO.read(in);
} else if (InputStream.class.isAssignableFrom((refc))) {
return in;
} else if (String.class == refc) {
return IO.collect(in);
}
}
String s = IO.collect(in);
return codec.dec().from(s).get(ref);
}
private InputStream handleContentEncoding(final HttpURLConnection con, InputStream in) throws IOException {
if (con == null)
return in;
String encoding = con.getHeaderField("Content-Encoding");
if (encoding != null) {
if (encoding.equalsIgnoreCase("deflate")) {
in = new InflaterInputStream(in);
reporter.trace("inflate");
} else if (encoding.equalsIgnoreCase("gzip")) {
in = new GZIPInputStream(in);
reporter.trace("gzip");
}
}
return in;
}
private void doOutput(Object put, final URLConnection con, HttpRequest< ? > rq) throws IOException, Exception {
con.setDoOutput(true);
try (OutputStream out = con.getOutputStream();) {
if (put instanceof InputStream) {
reporter.trace("out %s input stream %s", rq.verb, rq.url);
IO.copy((InputStream) put, out);
} else if (put instanceof String) {
reporter.trace("out %s string %s", rq.verb, rq.url);
IO.store(put, out);
} else if (put instanceof byte[]) {
reporter.trace("out %s byte[] 5s", rq.verb, rq.url);
IO.copy((byte[]) put, out);
} else if (put instanceof File) {
reporter.trace("out %s file %s %s", rq.verb, put, rq.url);
IO.copy((File) put, out);
} else {
reporter.trace("out %s JSON %s %s", rq.verb, put, rq.url);
codec.enc().to(out).put(put).flush();
}
}
}
private void configureHttpConnection(String verb, final HttpURLConnection hcon) throws ProtocolException {
if (hcon != null) {
hcon.setRequestProperty("Accept-Encoding", "deflate, gzip");
hcon.setInstanceFollowRedirects(false); // we handle it
hcon.setRequestMethod(verb);
}
}
private void setHeaders(Map<String,String> headers, final URLConnection con) {
if (headers != null) {
for (Entry<String,String> e : headers.entrySet()) {
reporter.trace("set header %s=%s", e.getKey(), e.getValue());
con.setRequestProperty(e.getKey(), e.getValue());
}
}
}
public void setCache(File cache) {
this.cache = new URLCache(cache);
}
public void setReporter(Reporter reporter) {
this.reporter = reporter;
}
public void setRegistry(Registry registry) {
this.registry = registry;
}
public void addURLConnectionHandler(URLConnectionHandler handler) {
connectionHandlers.add(handler);
}
public Reporter getReporter() {
return reporter;
}
public void addProxyHandler(ProxyHandler proxyHandler) {
proxyHandlers.add(proxyHandler);
}
public void setLog(File log) throws IOException {
log.getParentFile().mkdirs();
reporter = new ReporterAdapter(IO.writer(log));
}
public String getUserFor(String base) throws MalformedURLException, Exception {
URLConnectionHandler handler = findMatchingHandler(new URL(base));
if (handler == null)
return null;
return handler.toString();
}
public String toName(URI url) throws Exception {
return URLCache.toName(url);
}
public File getCacheFileFor(URI url) throws Exception {
return cache.getCacheFileFor(url);
}
public void readSettings(Processor processor) throws IOException, Exception {
try (ConnectionSettings cs = new ConnectionSettings(processor, this);) {
cs.readSettings();
}
}
public URI makeDir(URI uri) throws URISyntaxException {
if (uri.getPath() != null && uri.getPath().endsWith("/")) {
String string = uri.toString();
return new URI(string.substring(0, string.length() - 1));
}
else
return uri;
}
}
|
package io.moquette.server;
import io.moquette.BrokerConstants;
import io.moquette.interception.InterceptHandler;
import io.moquette.proto.messages.PublishMessage;
import io.moquette.server.config.MemoryConfig;
import io.moquette.spi.impl.SimpleMessaging;
import io.moquette.server.config.FilesystemConfig;
import io.moquette.server.config.IConfig;
import io.moquette.server.netty.NettyAcceptor;
import io.moquette.spi.impl.ProtocolProcessor;
import io.moquette.spi.security.IAuthenticator;
import io.moquette.spi.security.IAuthorizator;
import io.moquette.spi.security.ISslContextCreator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.io.IOException;
import java.util.Collections;
import java.util.List;
import java.util.Properties;
/**
* Launch a configured version of the server.
* @author andrea
*/
public class Server {
private static final Logger LOG = LoggerFactory.getLogger(Server.class);
private ServerAcceptor m_acceptor;
private volatile boolean m_initialized;
private ProtocolProcessor m_processor;
public static void main(String[] args) throws IOException {
final Server server = new Server();
server.startServer();
System.out.println("Server started, version 0.8.1");
//Bind a shutdown hook
Runtime.getRuntime().addShutdownHook(new Thread() {
@Override
public void run() {
server.stopServer();
}
});
}
/**
* Starts Moquette bringing the configuration from the file
* located at m_config/moquette.conf
*/
public void startServer() throws IOException {
final IConfig config = new FilesystemConfig();
startServer(config);
}
/**
* Starts Moquette bringing the configuration from the given file
*/
public void startServer(File configFile) throws IOException {
LOG.info("Using m_config file: " + configFile.getAbsolutePath());
final IConfig config = new FilesystemConfig(configFile);
startServer(config);
}
/**
* Starts the server with the given properties.
*
* Its suggested to at least have the following properties:
* <ul>
* <li>port</li>
* <li>password_file</li>
* </ul>
*/
public void startServer(Properties configProps) throws IOException {
final IConfig config = new MemoryConfig(configProps);
startServer(config);
}
/**
* Starts Moquette bringing the configuration files from the given Config implementation.
*/
public void startServer(IConfig config) throws IOException {
startServer(config, null);
}
/**
* Starts Moquette with config provided by an implementation of IConfig class and with the
* set of InterceptHandler.
* */
public void startServer(IConfig config, List<? extends InterceptHandler> handlers) throws IOException {
startServer(config, handlers, null, null, null);
}
public void startServer(IConfig config, List<? extends InterceptHandler> handlers,
ISslContextCreator sslCtxCreator, IAuthenticator authenticator,
IAuthorizator authorizator) throws IOException {
if (handlers == null) {
handlers = Collections.emptyList();
}
final String handlerProp = System.getProperty("intercept.handler");
if (handlerProp != null) {
config.setProperty("intercept.handler", handlerProp);
}
LOG.info("Persistent store file: " + config.getProperty(BrokerConstants.PERSISTENT_STORE_PROPERTY_NAME));
final ProtocolProcessor processor = SimpleMessaging.getInstance().init(config, handlers, authenticator, authorizator);
if (sslCtxCreator == null) {
sslCtxCreator = new DefaultMoquetteSslContextCreator(config);
}
m_acceptor = new NettyAcceptor();
m_acceptor.initialize(processor, config, sslCtxCreator);
m_processor = processor;
m_initialized = true;
}
public void internalPublishToClient(String clientId, String message) {
if (!m_initialized) {
throw new IllegalStateException("Can't publish on a server is not yet started");
}
try {
m_processor.internalPublishToClient(clientId, message);
} catch (RuntimeException ex) {
LOG.error("Error sending message to client {}, message <{}>", clientId, message, ex);
}
}
public void internalPublish(PublishMessage msg) {
if (!m_initialized) {
throw new IllegalStateException("Can't publish on a server is not yet started");
}
m_processor.internalPublish(msg);
}
public void stopServer() {
LOG.info("Server stopping...");
m_acceptor.close();
SimpleMessaging.getInstance().shutdown();
m_initialized = false;
LOG.info("Server stopped");
}
/**
* Disconnects client
*
* @param clientId The id of the client
*/
public void disconnectClient(String clientId, String error) {
if (!m_initialized) {
throw new IllegalStateException("Server is not yet started");
}
m_processor.disconnectClient(clientId, error);
}
}
|
package cgeo.geocaching.maps;
import cgeo.geocaching.DirectionProvider;
import cgeo.geocaching.IGeoData;
import cgeo.geocaching.IWaypoint;
import cgeo.geocaching.LiveMapInfo;
import cgeo.geocaching.R;
import cgeo.geocaching.SearchResult;
import cgeo.geocaching.Settings;
import cgeo.geocaching.StoredList;
import cgeo.geocaching.cgCache;
import cgeo.geocaching.cgWaypoint;
import cgeo.geocaching.cgeoapplication;
import cgeo.geocaching.cgeocaches;
import cgeo.geocaching.activity.ActivityMixin;
import cgeo.geocaching.connector.ConnectorFactory;
import cgeo.geocaching.connector.gc.Login;
import cgeo.geocaching.enumerations.CacheType;
import cgeo.geocaching.enumerations.LiveMapStrategy.Strategy;
import cgeo.geocaching.enumerations.LoadFlags;
import cgeo.geocaching.enumerations.StatusCode;
import cgeo.geocaching.enumerations.WaypointType;
import cgeo.geocaching.geopoint.Geopoint;
import cgeo.geocaching.geopoint.Viewport;
import cgeo.geocaching.go4cache.Go4Cache;
import cgeo.geocaching.go4cache.Go4CacheUser;
import cgeo.geocaching.maps.interfaces.CachesOverlayItemImpl;
import cgeo.geocaching.maps.interfaces.GeoPointImpl;
import cgeo.geocaching.maps.interfaces.MapActivityImpl;
import cgeo.geocaching.maps.interfaces.MapControllerImpl;
import cgeo.geocaching.maps.interfaces.MapItemFactory;
import cgeo.geocaching.maps.interfaces.MapProvider;
import cgeo.geocaching.maps.interfaces.MapSource;
import cgeo.geocaching.maps.interfaces.MapViewImpl;
import cgeo.geocaching.maps.interfaces.OnMapDragListener;
import cgeo.geocaching.maps.interfaces.OtherCachersOverlayItemImpl;
import cgeo.geocaching.utils.CancellableHandler;
import cgeo.geocaching.utils.GeoDirHandler;
import cgeo.geocaching.utils.LeastRecentlyUsedSet;
import cgeo.geocaching.utils.Log;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.builder.HashCodeBuilder;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.LayerDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.SparseArray;
import android.view.Menu;
import android.view.MenuItem;
import android.view.SubMenu;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.widget.ImageSwitcher;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;
import android.widget.TextView;
import android.widget.ViewSwitcher.ViewFactory;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
/**
* Class representing the Map in c:geo
*/
public class CGeoMap extends AbstractMap implements OnMapDragListener, ViewFactory {
/** max. number of caches displayed in the Live Map */
public static final int MAX_CACHES = 500;
/** Handler Messages */
private static final int HIDE_PROGRESS = 0;
private static final int SHOW_PROGRESS = 1;
private static final int UPDATE_TITLE = 0;
private static final int INVALIDATE_MAP = 1;
private static final int UPDATE_PROGRESS = 0;
private static final int FINISHED_LOADING_DETAILS = 1;
//Menu
private static final String EXTRAS_GEOCODE = "geocode";
private static final String EXTRAS_COORDS = "coords";
private static final String EXTRAS_WPTTYPE = "wpttype";
private static final String EXTRAS_MAPSTATE = "mapstate";
private static final String EXTRAS_SEARCH = "search";
private static final int MENU_SELECT_MAPVIEW = 1;
private static final int MENU_MAP_LIVE = 2;
private static final int MENU_STORE_CACHES = 3;
private static final int MENU_TRAIL_MODE = 4;
private static final int SUBMENU_STRATEGY = 5;
private static final int MENU_STRATEGY_FASTEST = 51;
private static final int MENU_STRATEGY_FAST = 52;
private static final int MENU_STRATEGY_AUTO = 53;
private static final int MENU_STRATEGY_DETAILED = 74;
private static final int MENU_CIRCLE_MODE = 6;
private static final int MENU_AS_LIST = 7;
private static final String EXTRAS_MAP_TITLE = "mapTitle";
private static final String BUNDLE_MAP_SOURCE = "mapSource";
private static final String BUNDLE_MAP_STATE = "mapState";
private Resources res = null;
private MapItemFactory mapItemFactory = null;
private Activity activity = null;
private MapViewImpl mapView = null;
private cgeoapplication app = null;
final private GeoDirHandler geoDirUpdate = new UpdateLoc();
private SearchResult searchIntent = null;
private String geocodeIntent = null;
private Geopoint coordsIntent = null;
private WaypointType waypointTypeIntent = null;
private int[] mapStateIntent = null;
// status data
private SearchResult search = null;
private String[] tokens = null;
private boolean noMapTokenShowed = false;
// map status data
private boolean followMyLocation = false;
private Viewport viewport = null;
private Viewport viewportUsers = null;
private int zoom = -100;
// threads
private LoadTimer loadTimer = null;
private Go4CacheTimer go4CacheTimer = null;
private LoadDetails loadDetailsThread = null;
/** Time of last {@link LoadRunnable} run */
private volatile long loadThreadRun = 0L;
/** Time of last {@link Go4CacheRunnable} run */
private volatile long go4CacheThreadRun = 0L;
//Interthread communication flag
private volatile boolean downloaded = false;
// overlays
private CachesOverlay overlayCaches = null;
private OtherCachersOverlay overlayGo4Cache = null;
private ScaleOverlay overlayScale = null;
private PositionOverlay overlayPosition = null;
// data for overlays
private static final int[][] INSET_RELIABLE = { { 0, 0, 0, 0 }, { 0, 0, 0, 0 } }; // center, 33x40 / 45x51
private static final int[][] INSET_TYPE = { { 5, 8, 6, 10 }, { 4, 4, 5, 11 } }; // center, 22x22 / 36x36
private static final int[][] INSET_OWN = { { 21, 0, 0, 26 }, { 25, 0, 0, 35 } }; // top right, 12x12 / 16x16
private static final int[][] INSET_FOUND = { { 0, 0, 21, 28 }, { 0, 0, 25, 35 } }; // top left, 12x12 / 16x16
private static final int[][] INSET_USERMODIFIEDCOORDS = { { 21, 28, 0, 0 }, { 19, 25, 0, 0 } }; // bottom right, 12x12 / 26x26
private static final int[][] INSET_PERSONALNOTE = { { 0, 28, 21, 0 }, { 0, 25, 19, 0 } }; // bottom left, 12x12 / 26x26
private static SparseArray<LayerDrawable> overlaysCache = new SparseArray<LayerDrawable>();
private int cachesCnt = 0;
/** List of caches in the viewport */
private LeastRecentlyUsedSet<cgCache> caches = null;
/** List of waypoints in the viewport */
private final LeastRecentlyUsedSet<cgWaypoint> waypoints = new LeastRecentlyUsedSet<cgWaypoint>(MAX_CACHES);
// storing for offline
private ProgressDialog waitDialog = null;
private int detailTotal = 0;
private int detailProgress = 0;
private long detailProgressTime = 0L;
// views
private ImageSwitcher myLocSwitch = null;
// other things
private boolean live = true; // live map (live, dead) or rest (displaying caches on map)
private boolean liveChanged = false; // previous state for loadTimer
private boolean centered = false; // if map is already centered
private boolean alreadyCentered = false; // -""- for setting my location
private static Set<String> dirtyCaches = null;
// Thread pooling
private static BlockingQueue<Runnable> displayQueue = new ArrayBlockingQueue<Runnable>(1);
private static ThreadPoolExecutor displayExecutor = new ThreadPoolExecutor(1, 1, 60, TimeUnit.SECONDS, displayQueue, new ThreadPoolExecutor.DiscardOldestPolicy());
private static BlockingQueue<Runnable> downloadQueue = new ArrayBlockingQueue<Runnable>(1);
private static ThreadPoolExecutor downloadExecutor = new ThreadPoolExecutor(1, 1, 60, TimeUnit.SECONDS, downloadQueue, new ThreadPoolExecutor.DiscardOldestPolicy());
private static BlockingQueue<Runnable> loadQueue = new ArrayBlockingQueue<Runnable>(1);
private static ThreadPoolExecutor loadExecutor = new ThreadPoolExecutor(1, 1, 60, TimeUnit.SECONDS, loadQueue, new ThreadPoolExecutor.DiscardOldestPolicy());
private static BlockingQueue<Runnable> Go4CacheQueue = new ArrayBlockingQueue<Runnable>(1);
private static ThreadPoolExecutor Go4CacheExecutor = new ThreadPoolExecutor(1, 1, 60, TimeUnit.SECONDS, Go4CacheQueue, new ThreadPoolExecutor.DiscardOldestPolicy());
private static BlockingQueue<Runnable> go4CacheDisplayQueue = new ArrayBlockingQueue<Runnable>(1);
private static ThreadPoolExecutor go4CacheDisplayExecutor = new ThreadPoolExecutor(1, 1, 60, TimeUnit.SECONDS, go4CacheDisplayQueue, new ThreadPoolExecutor.DiscardOldestPolicy());
// handlers
/** Updates the titles */
final private Handler displayHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
final int what = msg.what;
switch (what) {
case UPDATE_TITLE:
// set title
final StringBuilder title = new StringBuilder();
if (live) {
title.append(res.getString(R.string.map_live));
} else {
title.append(mapTitle);
}
countVisibleCaches();
if (caches != null && caches.size() > 0 && !mapTitle.contains("[")) {
title.append(" [").append(cachesCnt);
if (cachesCnt != caches.size()) {
title.append('/').append(caches.size());
}
title.append(']');
}
if (Settings.isDebug() && search != null && StringUtils.isNotBlank(search.getUrl())) {
title.append('[').append(search.getUrl()).append(']');
}
ActivityMixin.setTitle(activity, title.toString());
break;
case INVALIDATE_MAP:
mapView.repaintRequired(null);
break;
default:
break;
}
}
};
/** Updates the progress. */
final private Handler showProgressHandler = new Handler() {
private int counter = 0;
@Override
public void handleMessage(Message msg) {
final int what = msg.what;
if (what == HIDE_PROGRESS) {
if (--counter == 0) {
ActivityMixin.showProgress(activity, false);
}
} else if (what == SHOW_PROGRESS) {
ActivityMixin.showProgress(activity, true);
counter++;
}
}
};
final private class LoadDetailsHandler extends CancellableHandler {
@Override
public void handleRegularMessage(Message msg) {
if (msg.what == UPDATE_PROGRESS) {
if (waitDialog != null) {
int secondsElapsed = (int) ((System.currentTimeMillis() - detailProgressTime) / 1000);
int secondsRemaining;
if (detailProgress > 0) {
secondsRemaining = (detailTotal - detailProgress) * secondsElapsed / detailProgress;
} else {
secondsRemaining = (detailTotal - detailProgress) * secondsElapsed;
}
waitDialog.setProgress(detailProgress);
if (secondsRemaining < 40) {
waitDialog.setMessage(res.getString(R.string.caches_downloading) + " " + res.getString(R.string.caches_eta_ltm));
} else if (secondsRemaining < 90) {
waitDialog.setMessage(res.getString(R.string.caches_downloading) + " " + (secondsRemaining / 60) + " " + res.getString(R.string.caches_eta_min));
} else {
waitDialog.setMessage(res.getString(R.string.caches_downloading) + " " + (secondsRemaining / 60) + " " + res.getString(R.string.caches_eta_mins));
}
}
} else if (msg.what == FINISHED_LOADING_DETAILS) {
if (waitDialog != null) {
waitDialog.dismiss();
waitDialog.setOnCancelListener(null);
}
geoDirUpdate.startDir();
}
}
@Override
public void handleCancel(final Object extra) {
if (loadDetailsThread != null) {
loadDetailsThread.stopIt();
}
geoDirUpdate.startDir();
}
}
final private Handler noMapTokenHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
if (!noMapTokenShowed) {
ActivityMixin.showToast(activity, res.getString(R.string.map_token_err));
noMapTokenShowed = true;
}
}
};
/**
* calling activities can set the map title via extras
*/
private String mapTitle;
/* Current source id */
private int currentSourceId;
public CGeoMap(MapActivityImpl activity) {
super(activity);
}
protected void countVisibleCaches() {
final List<cgCache> protectedCaches = caches.getAsList();
int count = 0;
if (protectedCaches.size() > 0) {
final Viewport viewport = mapView.getViewport();
for (final cgCache cache : protectedCaches) {
if (cache != null && cache.getCoords() != null) {
if (viewport.contains(cache)) {
count++;
}
}
}
}
cachesCnt = count;
}
@Override
public void onSaveInstanceState(final Bundle outState) {
outState.putInt(BUNDLE_MAP_SOURCE, currentSourceId);
outState.putIntArray(BUNDLE_MAP_STATE, currentMapState());
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// class init
res = this.getResources();
activity = this.getActivity();
app = (cgeoapplication) activity.getApplication();
int countBubbleCnt = app.getAllStoredCachesCount(true, CacheType.ALL);
caches = new LeastRecentlyUsedSet<cgCache>(MAX_CACHES + countBubbleCnt);
final MapProvider mapProvider = Settings.getMapProvider();
mapItemFactory = mapProvider.getMapItemFactory();
// Get parameters from the intent
final Bundle extras = activity.getIntent().getExtras();
if (extras != null) {
searchIntent = (SearchResult) extras.getParcelable(EXTRAS_SEARCH);
geocodeIntent = extras.getString(EXTRAS_GEOCODE);
coordsIntent = (Geopoint) extras.getParcelable(EXTRAS_COORDS);
waypointTypeIntent = WaypointType.findById(extras.getString(EXTRAS_WPTTYPE));
mapStateIntent = extras.getIntArray(EXTRAS_MAPSTATE);
mapTitle = extras.getString(EXTRAS_MAP_TITLE);
}
if (StringUtils.isBlank(mapTitle)) {
mapTitle = res.getString(R.string.map_map);
}
// Get fresh map information from the bundle if any
if (savedInstanceState != null) {
currentSourceId = savedInstanceState.getInt(BUNDLE_MAP_SOURCE, Settings.getMapSource());
mapStateIntent = savedInstanceState.getIntArray(BUNDLE_MAP_STATE);
} else {
currentSourceId = Settings.getMapSource();
}
// If recreating from an obsolete map source, we may need a restart
if (changeMapSource(Settings.getMapSource())) {
return;
}
// reset status
noMapTokenShowed = false;
ActivityMixin.keepScreenOn(activity, true);
// set layout
ActivityMixin.setTheme(activity);
activity.setContentView(mapProvider.getMapLayoutId());
ActivityMixin.setTitle(activity, res.getString(R.string.map_map));
// initialize map
mapView = (MapViewImpl) activity.findViewById(mapProvider.getMapViewId());
mapView.setMapSource();
mapView.setBuiltInZoomControls(true);
mapView.displayZoomControls(true);
mapView.preLoad();
mapView.setOnDragListener(this);
// initialize overlays
mapView.clearOverlays();
if (overlayPosition == null) {
overlayPosition = mapView.createAddPositionOverlay(activity);
}
if (Settings.isPublicLoc() && overlayGo4Cache == null) {
overlayGo4Cache = mapView.createAddUsersOverlay(activity, getResources().getDrawable(R.drawable.user_location));
}
if (overlayCaches == null) {
overlayCaches = mapView.createAddMapOverlay(mapView.getContext(), getResources().getDrawable(R.drawable.marker));
}
if (overlayScale == null) {
overlayScale = mapView.createAddScaleOverlay(activity);
}
mapView.repaintRequired(null);
mapView.getMapController().setZoom(Settings.getMapZoom());
// live map, if no arguments are given
live = (searchIntent == null && geocodeIntent == null && coordsIntent == null);
if (null == mapStateIntent) {
followMyLocation = live;
} else {
followMyLocation = 1 == mapStateIntent[3];
}
if (geocodeIntent != null || searchIntent != null || coordsIntent != null || mapStateIntent != null) {
centerMap(geocodeIntent, searchIntent, coordsIntent, mapStateIntent);
}
// prepare my location button
myLocSwitch = (ImageSwitcher) activity.findViewById(R.id.my_position);
myLocSwitch.setFactory(this);
myLocSwitch.setInAnimation(activity, android.R.anim.fade_in);
myLocSwitch.setOutAnimation(activity, android.R.anim.fade_out);
myLocSwitch.setOnClickListener(new MyLocationListener());
switchMyLocationButton();
prepareFilterBar();
if (!Settings.getHideLiveMapHint()) {
Intent hintIntent = new Intent(activity, LiveMapInfo.class);
activity.startActivity(hintIntent);
}
}
private void prepareFilterBar() {
// show the filter warning bar if the filter is set
if (Settings.getCacheType() != CacheType.ALL) {
String cacheType = Settings.getCacheType().getL10n();
((TextView) activity.findViewById(R.id.filter_text)).setText(cacheType);
activity.findViewById(R.id.filter_bar).setVisibility(View.VISIBLE);
} else {
activity.findViewById(R.id.filter_bar).setVisibility(View.GONE);
}
}
@Override
public void onResume() {
super.onResume();
app.setAction(StringUtils.defaultIfBlank(geocodeIntent, null));
addGeoDirObservers();
if (!CollectionUtils.isEmpty(dirtyCaches)) {
for (String geocode : dirtyCaches) {
cgCache cache = app.loadCache(geocode, LoadFlags.LOAD_WAYPOINTS);
// remove to update the cache
caches.remove(cache);
caches.add(cache);
}
dirtyCaches.clear();
// Update display
displayExecutor.execute(new DisplayRunnable(mapView.getViewport()));
}
startTimer();
}
private void addGeoDirObservers() {
geoDirUpdate.startGeoAndDir();
}
private void deleteGeoDirObservers() {
geoDirUpdate.stopGeoAndDir();
}
@Override
public void onPause() {
if (loadTimer != null) {
loadTimer.stopIt();
loadTimer = null;
}
if (go4CacheTimer != null) {
go4CacheTimer.stopIt();
go4CacheTimer = null;
}
deleteGeoDirObservers();
savePrefs();
if (mapView != null) {
mapView.destroyDrawingCache();
}
super.onPause();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
SubMenu submenu = menu.addSubMenu(1, MENU_SELECT_MAPVIEW, 0, res.getString(R.string.map_view_map)).setIcon(R.drawable.ic_menu_mapmode);
addMapViewMenuItems(submenu);
menu.add(0, MENU_MAP_LIVE, 0, res.getString(R.string.map_live_disable)).setIcon(R.drawable.ic_menu_refresh);
menu.add(0, MENU_STORE_CACHES, 0, res.getString(R.string.caches_store_offline)).setIcon(R.drawable.ic_menu_set_as).setEnabled(false);
menu.add(0, MENU_TRAIL_MODE, 0, res.getString(R.string.map_trail_hide)).setIcon(R.drawable.ic_menu_trail);
Strategy strategy = Settings.getLiveMapStrategy();
SubMenu subMenuStrategy = menu.addSubMenu(0, SUBMENU_STRATEGY, 0, res.getString(R.string.map_strategy)).setIcon(R.drawable.ic_menu_preferences);
subMenuStrategy.setHeaderTitle(res.getString(R.string.map_strategy_title));
subMenuStrategy.add(2, MENU_STRATEGY_FASTEST, 0, Strategy.FASTEST.getL10n()).setCheckable(true).setChecked(strategy == Strategy.FASTEST);
subMenuStrategy.add(2, MENU_STRATEGY_FAST, 0, Strategy.FAST.getL10n()).setCheckable(true).setChecked(strategy == Strategy.FAST);
subMenuStrategy.add(2, MENU_STRATEGY_AUTO, 0, Strategy.AUTO.getL10n()).setCheckable(true).setChecked(strategy == Strategy.AUTO);
subMenuStrategy.add(2, MENU_STRATEGY_DETAILED, 0, Strategy.DETAILED.getL10n()).setCheckable(true).setChecked(strategy == Strategy.DETAILED);
subMenuStrategy.setGroupCheckable(2, true, true);
menu.add(0, MENU_CIRCLE_MODE, 0, res.getString(R.string.map_circles_hide)).setIcon(R.drawable.ic_menu_circle);
menu.add(0, MENU_AS_LIST, 0, res.getString(R.string.map_as_list)).setIcon(R.drawable.ic_menu_agenda);
return true;
}
private static void addMapViewMenuItems(final Menu menu) {
MapProviderFactory.addMapviewMenuItems(menu, 1, Settings.getMapSource());
menu.setGroupCheckable(1, true, true);
}
@Override
public boolean onPrepareOptionsMenu(Menu menu) {
super.onPrepareOptionsMenu(menu);
for (Integer mapSourceId : MapProviderFactory.getMapSources().keySet()) {
final MenuItem menuItem = menu.findItem(mapSourceId);
if (menuItem != null) {
final MapSource mapSource = MapProviderFactory.getMapSource(mapSourceId);
if (mapSource != null) {
menuItem.setEnabled(mapSource.isAvailable());
}
}
}
MenuItem item;
try {
item = menu.findItem(MENU_TRAIL_MODE); // show trail
if (Settings.isMapTrail()) {
item.setTitle(res.getString(R.string.map_trail_hide));
} else {
item.setTitle(res.getString(R.string.map_trail_show));
}
item = menu.findItem(MENU_MAP_LIVE); // live map
if (live) {
if (Settings.isLiveMap()) {
item.setTitle(res.getString(R.string.map_live_disable));
} else {
item.setTitle(res.getString(R.string.map_live_enable));
}
} else {
item.setEnabled(false);
item.setTitle(res.getString(R.string.map_live_enable));
}
menu.findItem(MENU_STORE_CACHES).setEnabled(live && !isLoading() && CollectionUtils.isNotEmpty(caches) && app.hasUnsavedCaches(search));
item = menu.findItem(MENU_CIRCLE_MODE); // show circles
if (overlayCaches != null && overlayCaches.getCircles()) {
item.setTitle(res.getString(R.string.map_circles_hide));
} else {
item.setTitle(res.getString(R.string.map_circles_show));
}
item = menu.findItem(MENU_AS_LIST);
item.setEnabled(live && CollectionUtils.isNotEmpty(caches));
menu.findItem(SUBMENU_STRATEGY).setEnabled(live);
} catch (Exception e) {
Log.e("cgeomap.onPrepareOptionsMenu: " + e.toString());
}
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
final int id = item.getItemId();
switch (id) {
case MENU_TRAIL_MODE:
Settings.setMapTrail(!Settings.isMapTrail());
ActivityMixin.invalidateOptionsMenu(activity);
return true;
case MENU_MAP_LIVE:
Settings.setLiveMap(!Settings.isLiveMap());
liveChanged = true;
search = null;
searchIntent = null;
ActivityMixin.invalidateOptionsMenu(activity);
return true;
case MENU_STORE_CACHES:
if (live && !isLoading() && CollectionUtils.isNotEmpty(caches)) {
final List<String> geocodes = new ArrayList<String>();
final List<cgCache> cachesProtected = caches.getAsList();
try {
if (cachesProtected.size() > 0) {
final Viewport viewport = mapView.getViewport();
for (final cgCache cache : cachesProtected) {
if (cache != null && cache.getCoords() != null) {
if (viewport.contains(cache) && !app.isOffline(cache.getGeocode(), null)) {
geocodes.add(cache.getGeocode());
}
}
}
}
} catch (Exception e) {
Log.e("cgeomap.onOptionsItemSelected.#4: " + e.toString());
}
detailTotal = geocodes.size();
detailProgress = 0;
if (detailTotal == 0) {
ActivityMixin.showToast(activity, res.getString(R.string.warn_save_nothing));
return true;
}
final LoadDetailsHandler loadDetailsHandler = new LoadDetailsHandler();
waitDialog = new ProgressDialog(activity);
waitDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
waitDialog.setCancelable(true);
waitDialog.setCancelMessage(loadDetailsHandler.cancelMessage());
waitDialog.setMax(detailTotal);
waitDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
@Override
public void onCancel(DialogInterface arg0) {
try {
if (loadDetailsThread != null) {
loadDetailsThread.stopIt();
}
geoDirUpdate.startDir();
} catch (Exception e) {
Log.e("cgeocaches.onPrepareOptionsMenu.onCancel: " + e.toString());
}
}
});
float etaTime = detailTotal * 7.0f / 60.0f;
if (etaTime < 0.4) {
waitDialog.setMessage(res.getString(R.string.caches_downloading) + " " + res.getString(R.string.caches_eta_ltm));
} else if (etaTime < 1.5) {
waitDialog.setMessage(res.getString(R.string.caches_downloading) + " " + Math.round(etaTime) + " " + res.getString(R.string.caches_eta_min));
} else {
waitDialog.setMessage(res.getString(R.string.caches_downloading) + " " + Math.round(etaTime) + " " + res.getString(R.string.caches_eta_mins));
}
waitDialog.show();
detailProgressTime = System.currentTimeMillis();
loadDetailsThread = new LoadDetails(loadDetailsHandler, geocodes);
loadDetailsThread.start();
}
return true;
case MENU_CIRCLE_MODE:
if (overlayCaches == null) {
return false;
}
overlayCaches.switchCircles();
mapView.repaintRequired(overlayCaches);
ActivityMixin.invalidateOptionsMenu(activity);
return true;
case MENU_AS_LIST: {
cgeocaches.startActivityMap(activity, search);
return true;
}
case MENU_STRATEGY_FASTEST: {
item.setChecked(true);
Settings.setLiveMapStrategy(Strategy.FASTEST);
return true;
}
case MENU_STRATEGY_FAST: {
item.setChecked(true);
Settings.setLiveMapStrategy(Strategy.FAST);
return true;
}
case MENU_STRATEGY_AUTO: {
item.setChecked(true);
Settings.setLiveMapStrategy(Strategy.AUTO);
return true;
}
case MENU_STRATEGY_DETAILED: {
item.setChecked(true);
Settings.setLiveMapStrategy(Strategy.DETAILED);
return true;
}
default:
int mapSource = MapProviderFactory.getMapSourceFromMenuId(id);
if (MapProviderFactory.isValidSourceId(mapSource)) {
item.setChecked(true);
changeMapSource(mapSource);
return true;
}
}
return false;
}
/**
* Restart the current activity if the map provider has changed, or change the map source if needed.
*
* @param mapSource
* the new map source, which can be the same as the current one
* @return true if a restart is needed, false otherwise
*/
private boolean changeMapSource(final int mapSource) {
final boolean restartRequired = !MapProviderFactory.isSameActivity(currentSourceId, mapSource);
Settings.setMapSource(mapSource);
currentSourceId = mapSource;
if (restartRequired) {
mapRestart();
} else if (mapView != null) {
mapView.setMapSource();
}
return restartRequired;
}
/**
* Restart the current activity with the default map source.
*/
private void mapRestart() {
// close old mapview
activity.finish();
// prepare information to restart a similar view
Intent mapIntent = new Intent(activity, Settings.getMapProvider().getMapClass());
mapIntent.putExtra(EXTRAS_SEARCH, searchIntent);
mapIntent.putExtra(EXTRAS_GEOCODE, geocodeIntent);
if (coordsIntent != null) {
mapIntent.putExtra(EXTRAS_COORDS, coordsIntent);
}
mapIntent.putExtra(EXTRAS_WPTTYPE, waypointTypeIntent != null ? waypointTypeIntent.id : null);
mapIntent.putExtra(EXTRAS_MAP_TITLE, mapTitle);
final int[] mapState = currentMapState();
if (mapState != null) {
mapIntent.putExtra(EXTRAS_MAPSTATE, mapState);
}
// start the new map
activity.startActivity(mapIntent);
}
/**
* Get the current map state from the map view if it exists or from the mapStateIntent field otherwise.
*
* @return the current map state as an array of int, or null if no map state is available
*/
private int[] currentMapState() {
if (mapView == null) {
return mapStateIntent;
}
final GeoPointImpl mapCenter = mapView.getMapViewCenter();
return new int[] {
mapCenter.getLatitudeE6(),
mapCenter.getLongitudeE6(),
mapView.getMapZoomLevel(),
followMyLocation ? 1 : 0
};
}
private void savePrefs() {
if (mapView == null) {
return;
}
Settings.setMapZoom(mapView.getMapZoomLevel());
}
// Set center of map to my location if appropriate.
private void myLocationInMiddle(final IGeoData geo) {
if (followMyLocation) {
centerMap(geo.getCoords());
}
}
// class: update location
private class UpdateLoc extends GeoDirHandler {
@Override
protected void updateGeoData(final IGeoData geo) {
try {
boolean repaintRequired = false;
if (overlayPosition == null && mapView != null) {
overlayPosition = mapView.createAddPositionOverlay(activity);
}
if ((overlayPosition != null && geo.getLocation() != null)) {
overlayPosition.setCoordinates(geo.getLocation());
}
if (geo.getCoords() != null) {
if (followMyLocation) {
myLocationInMiddle(geo);
} else {
repaintRequired = true;
}
}
if (!Settings.isUseCompass() || geo.getSpeed() > 5) { // use GPS when speed is higher than 18 km/h
overlayPosition.setHeading(geo.getBearing());
repaintRequired = true;
}
if (repaintRequired && mapView != null) {
mapView.repaintRequired(overlayPosition);
}
} catch (Exception e) {
Log.w("Failed to update location.");
}
}
@Override
public void updateDirection(final float direction) {
if (overlayPosition != null && mapView != null && (app.currentGeo().getSpeed() <= 5)) { // use compass when speed is lower than 18 km/h
overlayPosition.setHeading(DirectionProvider.getDirectionNow(activity, direction));
mapView.repaintRequired(overlayPosition);
}
}
}
/**
* Starts the {@link LoadTimer} and {@link Go4CacheTimer}.
*/
public synchronized void startTimer() {
if (coordsIntent != null) {
// display just one point
(new DisplayPointThread()).start();
} else {
// start timer
if (loadTimer != null) {
loadTimer.stopIt();
loadTimer = null;
}
loadTimer = new LoadTimer();
loadTimer.start();
}
if (Settings.isPublicLoc()) {
if (go4CacheTimer != null) {
go4CacheTimer.stopIt();
go4CacheTimer = null;
}
go4CacheTimer = new Go4CacheTimer();
go4CacheTimer.start();
}
}
/**
* loading timer Triggers every 250ms and checks for viewport change and starts a {@link LoadRunnable}.
*/
private class LoadTimer extends Thread {
public LoadTimer() {
super("Load Timer");
}
private volatile boolean stop = false;
public void stopIt() {
stop = true;
}
@Override
public void run() {
while (!stop) {
try {
sleep(250);
if (mapView != null) {
// get current viewport
final Viewport viewportNow = mapView.getViewport();
// Since zoomNow is used only for local comparison purposes,
// it is ok to use the Google Maps compatible zoom level of OSM Maps
final int zoomNow = mapView.getMapZoomLevel();
// check if map moved or zoomed
//TODO Portree Use Rectangle inside with bigger search window. That will stop reloading on every move
boolean moved = false;
if (liveChanged) {
moved = true;
} else if (live && Settings.isLiveMap() && !downloaded) {
moved = true;
} else if (viewport == null) {
moved = true;
} else if (zoomNow != zoom) {
moved = true;
} else if (mapMoved(viewport, viewportNow) && (cachesCnt <= 0 || CollectionUtils.isEmpty(caches) || !viewport.includes(viewportNow))) {
moved = true;
}
// update title on any change
if (moved || zoomNow != zoom || !viewportNow.equals(viewport)) {
displayHandler.sendEmptyMessage(UPDATE_TITLE);
}
zoom = zoomNow;
// save new values
if (moved) {
liveChanged = false;
long currentTime = System.currentTimeMillis();
if (1000 < (currentTime - loadThreadRun)) {
viewport = viewportNow;
loadExecutor.execute(new LoadRunnable(viewport));
}
}
}
yield();
} catch (Exception e) {
Log.w("cgeomap.LoadTimer.run: " + e.toString());
}
}
}
public boolean isLoading() {
return loadExecutor.getActiveCount() > 0 ||
downloadExecutor.getActiveCount() > 0 ||
displayExecutor.getActiveCount() > 0;
}
}
/**
* Timer triggering every 250 ms to start the {@link Go4CacheRunnable} for displaying user.
*/
private class Go4CacheTimer extends Thread {
public Go4CacheTimer() {
super("Users Timer");
}
private volatile boolean stop = false;
public void stopIt() {
stop = true;
}
@Override
public void run() {
while (!stop) {
try {
sleep(250);
if (mapView != null) {
// get current viewport
final Viewport viewportNow = mapView.getViewport();
// check if map moved or zoomed
boolean moved = false;
long currentTime = System.currentTimeMillis();
if (60000 < (currentTime - go4CacheThreadRun)) {
moved = true;
} else if (viewportUsers == null) {
moved = true;
} else if (mapMoved(viewportUsers, viewportNow) && !viewportUsers.includes(viewportNow)) {
moved = true;
}
// save new values
if (moved && (1000 < (currentTime - go4CacheThreadRun))) {
viewportUsers = viewportNow;
Go4CacheExecutor.execute(new Go4CacheRunnable(viewportUsers));
}
}
yield();
} catch (Exception e) {
Log.w("cgeomap.LoadUsersTimer.run: " + e.toString());
}
}
}
}
/**
* Worker thread that loads caches and waypoints from the database and then spawns the {@link DownloadRunnable}.
* started by {@link LoadTimer}
*/
private class LoadRunnable extends DoRunnable {
public LoadRunnable(final Viewport viewport) {
super(viewport);
}
@Override
public void run() {
try {
showProgressHandler.sendEmptyMessage(SHOW_PROGRESS);
loadThreadRun = System.currentTimeMillis();
// stage 1 - pull and render from the DB only for live map
if (searchIntent != null || geocodeIntent != null) {
// map started from another activity
search = new SearchResult(searchIntent);
if (geocodeIntent != null) {
search.addGeocode(geocodeIntent);
}
} else {
// live map
if (!live || !Settings.isLiveMap()) {
search = new SearchResult(app.getStoredInViewport(viewport, Settings.getCacheType()));
} else {
search = new SearchResult(app.getCachedInViewport(viewport, Settings.getCacheType()));
}
}
if (search != null) {
downloaded = true;
Set<cgCache> cachesFromSearchResult = search.getCachesFromSearchResult(LoadFlags.LOAD_WAYPOINTS);
caches.addAll(cachesFromSearchResult);
}
if (live) {
final boolean excludeMine = Settings.isExcludeMyCaches();
final boolean excludeDisabled = Settings.isExcludeDisabledCaches();
final List<cgCache> tempList = caches.getAsList();
for (cgCache cache : tempList) {
if ((cache.isFound() && excludeMine) || (cache.isOwn() && excludeMine) || (cache.isDisabled() && excludeDisabled)) {
caches.remove(cache);
}
}
}
countVisibleCaches();
if (cachesCnt < Settings.getWayPointsThreshold() || geocodeIntent != null)
{
waypoints.clear();
if (searchIntent == null && geocodeIntent == null) {
//All visible waypoints
waypoints.addAll(app.getWaypointsInViewport(viewport, Settings.isExcludeMyCaches(), Settings.isExcludeDisabledCaches()));
} else {
//All waypoints from the viewed caches
for (cgCache c : caches.getAsList()) {
waypoints.addAll(c.getWaypoints());
}
}
}
//render
displayExecutor.execute(new DisplayRunnable(viewport));
if (live && Settings.isLiveMap()) {
downloadExecutor.execute(new DownloadRunnable(viewport));
}
} finally {
showProgressHandler.sendEmptyMessage(HIDE_PROGRESS); // hide progress
}
}
}
/**
* Worker thread downloading caches from the internet.
* Started by {@link LoadRunnable}. Duplicate Code with {@link Go4CacheRunnable}
*/
private class DownloadRunnable extends DoRunnable {
public DownloadRunnable(final Viewport viewport) {
super(viewport);
}
@Override
public void run() {
try {
showProgressHandler.sendEmptyMessage(SHOW_PROGRESS); // show progress
int count = 0;
do {
if (tokens == null) {
tokens = Login.getMapTokens();
if (noMapTokenHandler != null && tokens == null) {
noMapTokenHandler.sendEmptyMessage(0);
}
}
search = ConnectorFactory.searchByViewport(viewport.resize(0.8), tokens);
if (search != null) {
downloaded = true;
if (search.getError() == StatusCode.NOT_LOGGED_IN) {
Login.login();
tokens = null;
} else {
break;
}
}
count++;
} while (count < 2);
if (search != null) {
Set<cgCache> result = search.getCachesFromSearchResult(LoadFlags.LOAD_CACHE_OR_DB);
// to update the caches they have to be removed first
caches.removeAll(result);
caches.addAll(result);
}
//render
displayExecutor.execute(new DisplayRunnable(viewport));
} catch (ThreadDeath e) {
Log.d("DownloadThread stopped");
displayHandler.sendEmptyMessage(UPDATE_TITLE);
} finally {
showProgressHandler.sendEmptyMessage(HIDE_PROGRESS); // hide progress
}
}
}
/**
* Thread to Display (down)loaded caches. Started by {@link LoadRunnable} and {@link DownloadRunnable}
*/
private class DisplayRunnable extends DoRunnable {
public DisplayRunnable(final Viewport viewport) {
super(viewport);
}
@Override
public void run() {
try {
showProgressHandler.sendEmptyMessage(SHOW_PROGRESS);
if (mapView == null || caches == null) {
throw new ThreadDeath();
}
// display caches
final List<cgCache> cachesToDisplay = caches.getAsList();
final List<cgWaypoint> waypointsToDisplay = new ArrayList<cgWaypoint>(waypoints);
final List<CachesOverlayItemImpl> itemsToDisplay = new ArrayList<CachesOverlayItemImpl>();
if (!cachesToDisplay.isEmpty()) {
// Only show waypoints for single view or setting
// when less than showWaypointsthreshold Caches shown
if (cachesToDisplay.size() == 1 || (cachesCnt < Settings.getWayPointsThreshold())) {
for (cgWaypoint waypoint : waypointsToDisplay) {
if (waypoint.getCoords() == null) {
continue;
}
itemsToDisplay.add(getItem(waypoint, null, waypoint));
}
}
for (cgCache cache : cachesToDisplay) {
if (cache.getCoords() == null) {
continue;
}
itemsToDisplay.add(getItem(cache, cache, null));
}
overlayCaches.updateItems(itemsToDisplay);
displayHandler.sendEmptyMessage(INVALIDATE_MAP);
cachesCnt = cachesToDisplay.size();
} else {
overlayCaches.updateItems(itemsToDisplay);
displayHandler.sendEmptyMessage(INVALIDATE_MAP);
}
displayHandler.sendEmptyMessage(UPDATE_TITLE);
} catch (ThreadDeath e) {
Log.d("DisplayThread stopped");
displayHandler.sendEmptyMessage(UPDATE_TITLE);
} finally {
showProgressHandler.sendEmptyMessage(HIDE_PROGRESS);
}
}
}
/**
* Thread to load users from Go 4 Cache
*/
private class Go4CacheRunnable extends DoRunnable {
public Go4CacheRunnable(final Viewport viewport) {
super(viewport);
}
@Override
public void run() {
go4CacheThreadRun = System.currentTimeMillis();
List<Go4CacheUser> go4CacheUsers = Go4Cache.getGeocachersInViewport(Settings.getUsername(), viewport.resize(1.5));
go4CacheDisplayExecutor.execute(new Go4CacheDisplayRunnable(go4CacheUsers, viewport));
}
}
/**
* Thread to display users of Go 4 Cache started from {@link Go4CacheRunnable}
*/
private class Go4CacheDisplayRunnable extends DoRunnable {
private List<Go4CacheUser> users = null;
public Go4CacheDisplayRunnable(List<Go4CacheUser> usersIn, final Viewport viewport) {
super(viewport);
users = usersIn;
}
@Override
public void run() {
if (mapView == null || CollectionUtils.isEmpty(users)) {
return;
}
// display users
List<OtherCachersOverlayItemImpl> items = new ArrayList<OtherCachersOverlayItemImpl>();
int counter = 0;
OtherCachersOverlayItemImpl item;
for (Go4CacheUser userOne : users) {
if (userOne.getCoords() == null) {
continue;
}
item = mapItemFactory.getOtherCachersOverlayItemBase(activity, userOne);
items.add(item);
counter++;
if ((counter % 10) == 0) {
overlayGo4Cache.updateItems(items);
displayHandler.sendEmptyMessage(INVALIDATE_MAP);
}
}
overlayGo4Cache.updateItems(items);
}
}
/**
* Thread to display one point. Started on opening if in single mode.
*/
private class DisplayPointThread extends Thread {
@Override
public void run() {
if (mapView == null || caches == null) {
return;
}
if (coordsIntent != null) {
final cgWaypoint waypoint = new cgWaypoint("some place", waypointTypeIntent != null ? waypointTypeIntent : WaypointType.WAYPOINT, false);
waypoint.setCoords(coordsIntent);
final CachesOverlayItemImpl item = getItem(waypoint, null, waypoint);
overlayCaches.updateItems(item);
displayHandler.sendEmptyMessage(INVALIDATE_MAP);
cachesCnt = 1;
} else {
cachesCnt = 0;
}
displayHandler.sendEmptyMessage(UPDATE_TITLE);
}
}
private static abstract class DoRunnable implements Runnable {
final protected Viewport viewport;
public DoRunnable(final Viewport viewport) {
this.viewport = viewport;
}
@Override
public abstract void run();
}
/**
* get if map is loading something
*
* @return
*/
private synchronized boolean isLoading() {
if (loadTimer != null) {
return loadTimer.isLoading();
}
return false;
}
/**
* Thread to store the caches in the viewport. Started by Activity.
*/
private class LoadDetails extends Thread {
final private CancellableHandler handler;
final private List<String> geocodes;
private long last = 0L;
public LoadDetails(final CancellableHandler handler, final List<String> geocodes) {
this.handler = handler;
this.geocodes = geocodes;
}
public void stopIt() {
handler.cancel();
}
@Override
public void run() {
if (CollectionUtils.isEmpty(geocodes)) {
return;
}
deleteGeoDirObservers();
for (final String geocode : geocodes) {
try {
if (handler.isCancelled()) {
break;
}
if (!app.isOffline(geocode, null)) {
if ((System.currentTimeMillis() - last) < 1500) {
try {
int delay = 1000 + (int) (Math.random() * 1000.0) - (int) (System.currentTimeMillis() - last);
if (delay < 0) {
delay = 500;
}
sleep(delay);
} catch (Exception e) {
// nothing
}
}
if (handler.isCancelled()) {
Log.i("Stopped storing process.");
break;
}
cgCache.storeCache(null, geocode, StoredList.STANDARD_LIST_ID, false, handler);
}
} catch (Exception e) {
Log.e("cgeocaches.LoadDetails.run: " + e.toString());
} finally {
// one more cache over
detailProgress++;
handler.sendEmptyMessage(UPDATE_PROGRESS);
}
// FIXME: what does this yield() do here?
yield();
last = System.currentTimeMillis();
}
// we're done
handler.sendEmptyMessage(FINISHED_LOADING_DETAILS);
addGeoDirObservers();
}
}
private static boolean mapMoved(final Viewport referenceViewport, final Viewport newViewport) {
return Math.abs(newViewport.getLatitudeSpan() - referenceViewport.getLatitudeSpan()) > 50e-6 ||
Math.abs(newViewport.getLongitudeSpan() - referenceViewport.getLongitudeSpan()) > 50e-6 ||
Math.abs(newViewport.center.getLatitude() - referenceViewport.center.getLatitude()) > referenceViewport.getLatitudeSpan() / 4 ||
Math.abs(newViewport.center.getLongitude() - referenceViewport.center.getLongitude()) > referenceViewport.getLongitudeSpan() / 4;
}
// center map to desired location
private void centerMap(final Geopoint coords) {
if (coords == null) {
return;
}
if (mapView == null) {
return;
}
final MapControllerImpl mapController = mapView.getMapController();
final GeoPointImpl target = makeGeoPoint(coords);
if (alreadyCentered) {
mapController.animateTo(target);
} else {
mapController.setCenter(target);
}
alreadyCentered = true;
}
// move map to view results of searchIntent
private void centerMap(String geocodeCenter, final SearchResult searchCenter, final Geopoint coordsCenter, int[] mapState) {
final MapControllerImpl mapController = mapView.getMapController();
if (!centered && mapState != null) {
try {
mapController.setCenter(mapItemFactory.getGeoPointBase(new Geopoint(mapState[0] / 1.0e6, mapState[1] / 1.0e6)));
mapController.setZoom(mapState[2]);
} catch (Exception e) {
// nothing at all
}
centered = true;
alreadyCentered = true;
} else if (!centered && (geocodeCenter != null || searchIntent != null)) {
try {
Viewport viewport = null;
if (geocodeCenter != null) {
viewport = app.getBounds(geocodeCenter);
} else if (searchCenter != null) {
viewport = app.getBounds(searchCenter.getGeocodes());
}
if (viewport == null) {
return;
}
mapController.setCenter(mapItemFactory.getGeoPointBase(viewport.center));
if (viewport.getLatitudeSpan() != 0 && viewport.getLongitudeSpan() != 0) {
mapController.zoomToSpan((int) (viewport.getLatitudeSpan() * 1e6), (int) (viewport.getLongitudeSpan() * 1e6));
}
} catch (Exception e) {
// nothing at all
}
centered = true;
alreadyCentered = true;
} else if (!centered && coordsCenter != null) {
try {
mapController.setCenter(makeGeoPoint(coordsCenter));
} catch (Exception e) {
// nothing at all
}
centered = true;
alreadyCentered = true;
}
}
// switch My Location button image
private void switchMyLocationButton() {
if (followMyLocation) {
myLocSwitch.setImageResource(R.drawable.actionbar_mylocation_on);
myLocationInMiddle(app.currentGeo());
} else {
myLocSwitch.setImageResource(R.drawable.actionbar_mylocation_off);
}
}
// set my location listener
private class MyLocationListener implements View.OnClickListener {
@Override
public void onClick(View view) {
followMyLocation = !followMyLocation;
switchMyLocationButton();
}
}
@Override
public void onDrag() {
if (followMyLocation) {
followMyLocation = false;
switchMyLocationButton();
}
}
// make geopoint
private GeoPointImpl makeGeoPoint(final Geopoint coords) {
return mapItemFactory.getGeoPointBase(coords);
}
// close activity and open homescreen
@Override
public void goHome(View view) {
ActivityMixin.goHome(activity);
}
// open manual entry
@Override
public void goManual(View view) {
ActivityMixin.goManual(activity, "c:geo-live-map");
}
@Override
public View makeView() {
ImageView imageView = new ImageView(activity);
imageView.setScaleType(ScaleType.CENTER);
imageView.setLayoutParams(new ImageSwitcher.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
return imageView;
}
private static Intent newIntent(final Context context) {
return new Intent(context, Settings.getMapProvider().getMapClass());
}
public static void startActivitySearch(final Activity fromActivity, final SearchResult search, final String title) {
final Intent mapIntent = newIntent(fromActivity);
mapIntent.putExtra(EXTRAS_SEARCH, search);
if (StringUtils.isNotBlank(title)) {
mapIntent.putExtra(CGeoMap.EXTRAS_MAP_TITLE, title);
}
fromActivity.startActivity(mapIntent);
}
public static void startActivityLiveMap(final Activity fromActivity) {
fromActivity.startActivity(newIntent(fromActivity));
}
public static void startActivityCoords(final Activity fromActivity, final Geopoint coords, final WaypointType type, final String title) {
final Intent mapIntent = newIntent(fromActivity);
mapIntent.putExtra(EXTRAS_COORDS, coords);
if (type != null) {
mapIntent.putExtra(EXTRAS_WPTTYPE, type.id);
}
if (StringUtils.isNotBlank(title)) {
mapIntent.putExtra(EXTRAS_MAP_TITLE, title);
}
fromActivity.startActivity(mapIntent);
}
public static void startActivityGeoCode(final Activity fromActivity, final String geocode) {
final Intent mapIntent = newIntent(fromActivity);
mapIntent.putExtra(EXTRAS_GEOCODE, geocode);
mapIntent.putExtra(EXTRAS_MAP_TITLE, geocode);
fromActivity.startActivity(mapIntent);
}
public static void markCacheAsDirty(final String geocode) {
if (dirtyCaches == null) {
dirtyCaches = new HashSet<String>();
}
dirtyCaches.add(geocode);
}
/**
* Returns a OverlayItem represented by an icon
*
* @param coord
* The coords
* @param cache
* Cache
* @param waypoint
* Waypoint. Mutally exclusive with cache
* @return
*/
private CachesOverlayItemImpl getItem(final IWaypoint coord, final cgCache cache, final cgWaypoint waypoint) {
if (cache != null) {
final CachesOverlayItemImpl item = mapItemFactory.getCachesOverlayItem(coord, cache.getType());
final int hashcode = new HashCodeBuilder()
.append(cache.isReliableLatLon())
.append(cache.getType().id)
.append(cache.isDisabled() || cache.isArchived())
.append(cache.isOwn())
.append(cache.isFound())
.append(cache.hasUserModifiedCoords())
.append(cache.getPersonalNote())
.append(cache.isLogOffline())
.append(cache.getListId() > 0)
.toHashCode();
final LayerDrawable ldFromCache = CGeoMap.overlaysCache.get(hashcode);
if (ldFromCache != null) {
item.setMarker(ldFromCache);
return item;
}
// Set initial capacities to the maximum of layers and insets to avoid dynamic reallocation
final ArrayList<Drawable> layers = new ArrayList<Drawable>(9);
final ArrayList<int[]> insets = new ArrayList<int[]>(8);
// background: disabled or not
final Drawable marker = getResources().getDrawable(cache.isDisabled() || cache.isArchived() ? R.drawable.marker_disabled : R.drawable.marker);
layers.add(marker);
final int resolution = marker.getIntrinsicWidth() > 40 ? 1 : 0;
// reliable or not
if (!cache.isReliableLatLon()) {
insets.add(INSET_RELIABLE[resolution]);
layers.add(getResources().getDrawable(R.drawable.marker_notreliable));
}
// cache type
layers.add(getResources().getDrawable(cache.getType().markerId));
insets.add(INSET_TYPE[resolution]);
// own
if (cache.isOwn()) {
layers.add(getResources().getDrawable(R.drawable.marker_own));
insets.add(INSET_OWN[resolution]);
// if not, checked if stored
} else if (cache.getListId() > 0) {
layers.add(getResources().getDrawable(R.drawable.marker_stored));
insets.add(INSET_OWN[resolution]);
}
// found
if (cache.isFound()) {
layers.add(getResources().getDrawable(R.drawable.marker_found));
insets.add(INSET_FOUND[resolution]);
// if not, perhaps logged offline
} else if (cache.isLogOffline()) {
layers.add(getResources().getDrawable(R.drawable.marker_found_offline));
insets.add(INSET_FOUND[resolution]);
}
// user modified coords
if (cache.hasUserModifiedCoords()) {
layers.add(getResources().getDrawable(R.drawable.marker_usermodifiedcoords));
insets.add(INSET_USERMODIFIEDCOORDS[resolution]);
}
// personal note
if (cache.getPersonalNote() != null) {
layers.add(getResources().getDrawable(R.drawable.marker_personalnote));
insets.add(INSET_PERSONALNOTE[resolution]);
}
final LayerDrawable ld = new LayerDrawable(layers.toArray(new Drawable[layers.size()]));
int index = 1;
for (final int[] inset : insets) {
ld.setLayerInset(index++, inset[0], inset[1], inset[2], inset[3]);
}
CGeoMap.overlaysCache.put(hashcode, ld);
item.setMarker(ld);
return item;
}
if (waypoint != null) {
final CachesOverlayItemImpl item = mapItemFactory.getCachesOverlayItem(coord, null);
Drawable[] layers = new Drawable[2];
layers[0] = getResources().getDrawable(R.drawable.marker);
layers[1] = getResources().getDrawable(waypoint.getWaypointType().markerId);
LayerDrawable ld = new LayerDrawable(layers);
if (layers[0].getIntrinsicWidth() > 40) {
ld.setLayerInset(1, 9, 12, 10, 13);
} else {
ld.setLayerInset(1, 9, 12, 8, 12);
}
item.setMarker(ld);
return item;
}
return null;
}
}
|
package hudson.util;
import java.util.concurrent.TimeUnit;
/**
* A <tt>TimeUnit</tt> represents time durations at a given unit of
* granularity and provides utility methods to convert across units,
* and to perform timing and delay operations in these units. A
* <tt>TimeUnit</tt> does not maintain time information, but only
* helps organize and use time representations that may be maintained
* separately across various contexts. A nanosecond is defined as one
* thousandth of a microsecond, a microsecond as one thousandth of a
* millisecond, a millisecond as one thousandth of a second, a minute
* as sixty seconds, an hour as sixty minutes, and a day as twenty four
* hours.
*
* <p>A <tt>TimeUnit</tt> is mainly used to inform time-based methods
* how a given timing parameter should be interpreted. For example,
* the following code will timeout in 50 milliseconds if the {@link
* java.util.concurrent.locks.Lock lock} is not available:
*
* <pre> Lock lock = ...;
* if ( lock.tryLock(50L, TimeUnit.MILLISECONDS) ) ...
* </pre>
* while this code will timeout in 50 seconds:
* <pre>
* Lock lock = ...;
* if ( lock.tryLock(50L, TimeUnit.SECONDS) ) ...
* </pre>
*
* Note however, that there is no guarantee that a particular timeout
* implementation will be able to notice the passage of time at the
* same granularity as the given <tt>TimeUnit</tt>.
*
* @since 1.5
* @author Doug Lea
* @deprecated use {@link TimeUnit}. (Java 5 did not have all the units required, so TimeUnit2 was introduced because it
* had better conversion until Java 6 went out.)
*/
@Deprecated
public enum TimeUnit2 {
NANOSECONDS {
@Override public long toNanos(long d) { return d; }
@Override public long toMicros(long d) { return d/(C1/C0); }
@Override public long toMillis(long d) { return d/(C2/C0); }
@Override public long toSeconds(long d) { return d/(C3/C0); }
@Override public long toMinutes(long d) { return d/(C4/C0); }
@Override public long toHours(long d) { return d/(C5/C0); }
@Override public long toDays(long d) { return d/(C6/C0); }
@Override public long convert(long d, TimeUnit2 u) { return u.toNanos(d); }
@Override public long convert(long d, TimeUnit u) { return u.toNanos(d); }
int excessNanos(long d, long m) { return (int)(d - (m*C2)); }
},
MICROSECONDS {
@Override public long toNanos(long d) { return x(d, C1/C0, MAX/(C1/C0)); }
@Override public long toMicros(long d) { return d; }
@Override public long toMillis(long d) { return d/(C2/C1); }
@Override public long toSeconds(long d) { return d/(C3/C1); }
@Override public long toMinutes(long d) { return d/(C4/C1); }
@Override public long toHours(long d) { return d/(C5/C1); }
@Override public long toDays(long d) { return d/(C6/C1); }
@Override public long convert(long d, TimeUnit2 u) { return u.toMicros(d); }
@Override public long convert(long d, TimeUnit u) { return u.toMicros(d); }
int excessNanos(long d, long m) { return (int)((d*C1) - (m*C2)); }
},
MILLISECONDS {
@Override public long toNanos(long d) { return x(d, C2/C0, MAX/(C2/C0)); }
@Override public long toMicros(long d) { return x(d, C2/C1, MAX/(C2/C1)); }
@Override public long toMillis(long d) { return d; }
@Override public long toSeconds(long d) { return d/(C3/C2); }
@Override public long toMinutes(long d) { return d/(C4/C2); }
@Override public long toHours(long d) { return d/(C5/C2); }
@Override public long toDays(long d) { return d/(C6/C2); }
@Override public long convert(long d, TimeUnit2 u) { return u.toMillis(d); }
@Override public long convert(long d, TimeUnit u) { return u.toMillis(d); }
int excessNanos(long d, long m) { return 0; }
},
SECONDS {
@Override public long toNanos(long d) { return x(d, C3/C0, MAX/(C3/C0)); }
@Override public long toMicros(long d) { return x(d, C3/C1, MAX/(C3/C1)); }
@Override public long toMillis(long d) { return x(d, C3/C2, MAX/(C3/C2)); }
@Override public long toSeconds(long d) { return d; }
@Override public long toMinutes(long d) { return d/(C4/C3); }
@Override public long toHours(long d) { return d/(C5/C3); }
@Override public long toDays(long d) { return d/(C6/C3); }
@Override public long convert(long d, TimeUnit2 u) { return u.toSeconds(d); }
@Override public long convert(long d, TimeUnit u) { return u.toSeconds(d); }
int excessNanos(long d, long m) { return 0; }
},
MINUTES {
@Override public long toNanos(long d) { return x(d, C4/C0, MAX/(C4/C0)); }
@Override public long toMicros(long d) { return x(d, C4/C1, MAX/(C4/C1)); }
@Override public long toMillis(long d) { return x(d, C4/C2, MAX/(C4/C2)); }
@Override public long toSeconds(long d) { return x(d, C4/C3, MAX/(C4/C3)); }
@Override public long toMinutes(long d) { return d; }
@Override public long toHours(long d) { return d/(C5/C4); }
@Override public long toDays(long d) { return d/(C6/C4); }
@Override public long convert(long d, TimeUnit2 u) { return u.toMinutes(d); }
@Override public long convert(long d, TimeUnit u) { return SECONDS.toMinutes(u.toSeconds(d)); }
int excessNanos(long d, long m) { return 0; }
},
HOURS {
@Override public long toNanos(long d) { return x(d, C5/C0, MAX/(C5/C0)); }
@Override public long toMicros(long d) { return x(d, C5/C1, MAX/(C5/C1)); }
@Override public long toMillis(long d) { return x(d, C5/C2, MAX/(C5/C2)); }
@Override public long toSeconds(long d) { return x(d, C5/C3, MAX/(C5/C3)); }
@Override public long toMinutes(long d) { return x(d, C5/C4, MAX/(C5/C4)); }
@Override public long toHours(long d) { return d; }
@Override public long toDays(long d) { return d/(C6/C5); }
@Override public long convert(long d, TimeUnit2 u) { return u.toHours(d); }
@Override public long convert(long d, TimeUnit u) { return SECONDS.toHours(u.toSeconds(d)); }
int excessNanos(long d, long m) { return 0; }
},
DAYS {
@Override public long toNanos(long d) { return x(d, C6/C0, MAX/(C6/C0)); }
@Override public long toMicros(long d) { return x(d, C6/C1, MAX/(C6/C1)); }
@Override public long toMillis(long d) { return x(d, C6/C2, MAX/(C6/C2)); }
@Override public long toSeconds(long d) { return x(d, C6/C3, MAX/(C6/C3)); }
@Override public long toMinutes(long d) { return x(d, C6/C4, MAX/(C6/C4)); }
@Override public long toHours(long d) { return x(d, C6/C5, MAX/(C6/C5)); }
@Override public long toDays(long d) { return d; }
@Override public long convert(long d, TimeUnit2 u) { return u.toDays(d); }
@Override public long convert(long d, TimeUnit u) { return SECONDS.toDays(u.toSeconds(d)); }
int excessNanos(long d, long m) { return 0; }
};
// Handy constants for conversion methods
static final long C0 = 1L;
static final long C1 = C0 * 1000L;
static final long C2 = C1 * 1000L;
static final long C3 = C2 * 1000L;
static final long C4 = C3 * 60L;
static final long C5 = C4 * 60L;
static final long C6 = C5 * 24L;
static final long MAX = Long.MAX_VALUE;
/**
* Scale d by m, checking for overflow.
* This has a short name to make above code more readable.
*/
static long x(long d, long m, long over) {
if (d > over) return Long.MAX_VALUE;
if (d < -over) return Long.MIN_VALUE;
return d * m;
}
// To maintain full signature compatibility with 1.5, and to improve the
// clarity of the generated javadoc (see 6287639: Abstract methods in
// enum classes should not be listed as abstract), method convert
// etc. are not declared abstract but otherwise act as abstract methods.
/**
* Convert the given time duration in the given unit to this
* unit. Conversions from finer to coarser granularities
* truncate, so lose precision. For example converting
* <tt>999</tt> milliseconds to seconds results in
* <tt>0</tt>. Conversions from coarser to finer granularities
* with arguments that would numerically overflow saturate to
* <tt>Long.MIN_VALUE</tt> if negative or <tt>Long.MAX_VALUE</tt>
* if positive.
*
* <p>For example, to convert 10 minutes to milliseconds, use:
* <tt>TimeUnit.MILLISECONDS.convert(10L, TimeUnit.MINUTES)</tt>
*
* @param sourceDuration the time duration in the given <tt>sourceUnit</tt>
* @param sourceUnit the unit of the <tt>sourceDuration</tt> argument
* @return the converted duration in this unit,
* or <tt>Long.MIN_VALUE</tt> if conversion would negatively
* overflow, or <tt>Long.MAX_VALUE</tt> if it would positively overflow.
*/
public long convert(long sourceDuration, TimeUnit2 sourceUnit) {
throw new AbstractMethodError();
}
/**
* Convert the given time duration in the given unit to this
* unit. Conversions from finer to coarser granularities
* truncate, so lose precision. For example converting
* <tt>999</tt> milliseconds to seconds results in
* <tt>0</tt>. Conversions from coarser to finer granularities
* with arguments that would numerically overflow saturate to
* <tt>Long.MIN_VALUE</tt> if negative or <tt>Long.MAX_VALUE</tt>
* if positive.
*
* <p>For example, to convert 10 minutes to milliseconds, use:
* <tt>TimeUnit.MILLISECONDS.convert(10L, TimeUnit.MINUTES)</tt>
*
* @param sourceDuration the time duration in the given <tt>sourceUnit</tt>
* @param sourceUnit the unit of the <tt>sourceDuration</tt> argument
* @return the converted duration in this unit,
* or <tt>Long.MIN_VALUE</tt> if conversion would negatively
* overflow, or <tt>Long.MAX_VALUE</tt> if it would positively overflow.
*/
public long convert(long sourceDuration, TimeUnit sourceUnit) {
throw new AbstractMethodError();
}
/**
* Equivalent to <tt>NANOSECONDS.convert(duration, this)</tt>.
* @param duration the duration
* @return the converted duration,
* or <tt>Long.MIN_VALUE</tt> if conversion would negatively
* overflow, or <tt>Long.MAX_VALUE</tt> if it would positively overflow.
* @see #convert
*/
public long toNanos(long duration) {
throw new AbstractMethodError();
}
/**
* Equivalent to <tt>MICROSECONDS.convert(duration, this)</tt>.
* @param duration the duration
* @return the converted duration,
* or <tt>Long.MIN_VALUE</tt> if conversion would negatively
* overflow, or <tt>Long.MAX_VALUE</tt> if it would positively overflow.
* @see #convert
*/
public long toMicros(long duration) {
throw new AbstractMethodError();
}
/**
* Equivalent to <tt>MILLISECONDS.convert(duration, this)</tt>.
* @param duration the duration
* @return the converted duration,
* or <tt>Long.MIN_VALUE</tt> if conversion would negatively
* overflow, or <tt>Long.MAX_VALUE</tt> if it would positively overflow.
* @see #convert
*/
public long toMillis(long duration) {
throw new AbstractMethodError();
}
/**
* Equivalent to <tt>SECONDS.convert(duration, this)</tt>.
* @param duration the duration
* @return the converted duration,
* or <tt>Long.MIN_VALUE</tt> if conversion would negatively
* overflow, or <tt>Long.MAX_VALUE</tt> if it would positively overflow.
* @see #convert
*/
public long toSeconds(long duration) {
throw new AbstractMethodError();
}
/**
* Equivalent to <tt>MINUTES.convert(duration, this)</tt>.
* @param duration the duration
* @return the converted duration,
* or <tt>Long.MIN_VALUE</tt> if conversion would negatively
* overflow, or <tt>Long.MAX_VALUE</tt> if it would positively overflow.
* @see #convert
* @since 1.6
*/
public long toMinutes(long duration) {
throw new AbstractMethodError();
}
/**
* Equivalent to <tt>HOURS.convert(duration, this)</tt>.
* @param duration the duration
* @return the converted duration,
* or <tt>Long.MIN_VALUE</tt> if conversion would negatively
* overflow, or <tt>Long.MAX_VALUE</tt> if it would positively overflow.
* @see #convert
* @since 1.6
*/
public long toHours(long duration) {
throw new AbstractMethodError();
}
/**
* Equivalent to <tt>DAYS.convert(duration, this)</tt>.
* @param duration the duration
* @return the converted duration
* @see #convert
* @since 1.6
*/
public long toDays(long duration) {
throw new AbstractMethodError();
}
/**
* Utility to compute the excess-nanosecond argument to wait,
* sleep, join.
* @param d the duration
* @param m the number of milliseconds
* @return the number of nanoseconds
*/
abstract int excessNanos(long d, long m);
/**
* Performs a timed <tt>Object.wait</tt> using this time unit.
* This is a convenience method that converts timeout arguments
* into the form required by the <tt>Object.wait</tt> method.
*
* <p>For example, you could implement a blocking <tt>poll</tt>
* method (see {@link java.util.concurrent.BlockingQueue#poll BlockingQueue.poll})
* using:
*
* <pre> public synchronized Object poll(long timeout, TimeUnit unit) throws InterruptedException {
* while (empty) {
* unit.timedWait(this, timeout);
* ...
* }
* }</pre>
*
* @param obj the object to wait on
* @param timeout the maximum time to wait. If less than
* or equal to zero, do not wait at all.
* @throws InterruptedException if interrupted while waiting.
* @see Object#wait(long, int)
*/
public void timedWait(Object obj, long timeout)
throws InterruptedException {
if (timeout > 0) {
long ms = toMillis(timeout);
int ns = excessNanos(timeout, ms);
obj.wait(ms, ns);
}
}
/**
* Performs a timed <tt>Thread.join</tt> using this time unit.
* This is a convenience method that converts time arguments into the
* form required by the <tt>Thread.join</tt> method.
* @param thread the thread to wait for
* @param timeout the maximum time to wait. If less than
* or equal to zero, do not wait at all.
* @throws InterruptedException if interrupted while waiting.
* @see Thread#join(long, int)
*/
public void timedJoin(Thread thread, long timeout)
throws InterruptedException {
if (timeout > 0) {
long ms = toMillis(timeout);
int ns = excessNanos(timeout, ms);
thread.join(ms, ns);
}
}
/**
* Performs a <tt>Thread.sleep</tt> using this unit.
* This is a convenience method that converts time arguments into the
* form required by the <tt>Thread.sleep</tt> method.
* @param timeout the minimum time to sleep. If less than
* or equal to zero, do not sleep at all.
* @throws InterruptedException if interrupted while sleeping.
* @see Thread#sleep
*/
public void sleep(long timeout) throws InterruptedException {
if (timeout > 0) {
long ms = toMillis(timeout);
int ns = excessNanos(timeout, ms);
Thread.sleep(ms, ns);
}
}
}
|
package org.judal.storage;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import static java.nio.file.StandardOpenOption.READ;
import java.util.Hashtable;
import java.util.Map;
import java.util.Properties;
import javax.servlet.ServletConfig;
import com.knowgate.stringutils.Str;
import com.knowgate.debug.DebugFile;
import static org.judal.storage.DataSource.PropertyNames;
import static org.judal.storage.DataSource.DefaultValues;
/**
* <p>Helper methods to read properties from environment to create data sources and other objects.</p>
* The list of recognized properties and their default values are kept as static variables at
* org.judal.storage.DataSource class
* @author Sergio Montoro Ten
* @version 1.0
*/
public class Env {
/**
* <p>Get default value for a property (if present).</p>
* @param propertyName String
* @return String Default property value or <b>null</b> if property has no default value.
*/
public static String getDataSourceDefault(String propertyName) {
for (String[] nameValue : DefaultValues)
if (nameValue[0].equalsIgnoreCase(propertyName))
return nameValue[1];
return null;
}
/**
* <p>Read DataSource properties from ServletConfig parameters into a Map
* DataSource property names names are listed at DataSource.PropertyNames</p>
* If namespace is not empty then parameter names will be read as namespace.parameterName
* @param obj ServletConfig
* @param namespace String
* @return Map containing the property name as key and its value at ServletConfig or a default value taken from DataSource interface static variables
* @throws ClassCastException If obj is not an instance of class javax.servlet.ServletConfig
*/
public static Map<String,String> getDataSourcePropertiesFromServletConfig(Object obj, String namespace) throws ClassCastException {
ServletConfig cfg = (ServletConfig) obj;
Hashtable<String,String> props = new Hashtable<String,String>();
if (namespace==null) namespace = "";
String prefix = namespace.length()==0 ? "" : namespace + ".";
for (String propName : PropertyNames) {
String prop = cfg.getInitParameter(prefix + propName);
if (DebugFile.trace)
DebugFile.writeln(prop==null ? "init parameter "+propName+" not found" : "read init parameter "+propName+"="+prop);
if (prop!=null)
setProperty(props, propName, prop);
}
return props;
}
/**
* <p>Read DataSource properties from a properties input stream into a Map
* If namespace is not empty then property names will be read as namespace.parameterName</p>
* @param inStrm InputStream
* @param namespace String
* @return
* @throws IOException
*/
public static Map<String,String> getDataSourceProperties(InputStream inStrm, String namespace) throws IOException {
Hashtable<String,String> props = new Hashtable<String,String>();
if (DebugFile.trace) {
DebugFile.writeln("Begin Env.getDataSourceProperties(InputStream, namespace=\""+namespace+"\")");
DebugFile.incIdent();
}
if (namespace==null) namespace = "";
String prefix = namespace.length()==0 ? "" : namespace + ".";
Properties reader = new Properties();
reader.load(inStrm);
for (String propName : PropertyNames) {
String prop = reader.getProperty(prefix + propName);
if (DebugFile.trace)
DebugFile.writeln(prop==null ? "property "+propName+" not found" : "read "+propName+"="+prop);
if (prop!=null)
setProperty(props, propName, prop);
}
if (DebugFile.trace) {
DebugFile.decIdent();
DebugFile.writeln("End Env.getDataSourceProperties()");
}
return props;
}
/**
* <p>Read DataSource properties from a properties input stream into a Map
* If namespace is not empty then property names will be read as namespace.parameterName</p>
* @param inPath Path
* @param namespace String
* @return
* @throws IOException
*/
public static Map<String,String> getDataSourceProperties(Path inPath, String namespace) throws IOException {
InputStream inStrm = Files.newInputStream(inPath, READ);
Map<String,String> retval = getDataSourceProperties(inStrm, namespace);
inStrm.close();
return retval;
}
/**
* <p>Get the value of a property that represents a boolean type.</p>
* @param oProperties Map<String,String>
* @param sVarName Property Name
* @param bDefault Default Value
* @return If no property named sVarName is found at sProfile then bDefault value is returned.
* If sVarName is one of {true , yes, on, 1} then return value is <b>true</b>.
* If sVarName is one of {false, no, off, 0} then return value is <b>false</b>.
* If sVarName is any other value then then return value is bDefault
*/
public static boolean getBoolean(Map<String,String> oProperties, String sVarName, boolean bDefault) {
boolean bRetVal = bDefault;
String sBool = oProperties.get(sVarName);
if (null==sBool)
sBool = bDefault ? "true" : "false";
if (null!=sBool) {
sBool = sBool.trim();
if (sBool.equalsIgnoreCase("true") || sBool.equalsIgnoreCase("yes") || sBool.equalsIgnoreCase("on") || sBool.equals("1"))
bRetVal = true;
else if (sBool.equalsIgnoreCase("false") || sBool.equalsIgnoreCase("no") || sBool.equalsIgnoreCase("off") || sBool.equals("0"))
bRetVal = false;
else
bRetVal = bDefault;
}
return bRetVal;
} // getProfileBool
/**
* <p>Get a property representing a file path.</p>
* <p>This method ensures that a file separator is always appended to the end of the readed value.</p>
* @param oProperties Map<String,String>
* @param sVarName Property Name
* @return Value terminated with a file separator or <b>null</b> if no property with such name was found.
*/
public static String getPath(Map<String,String> oProperties, String sVarName) {
String sPath = oProperties.get(sVarName);
return Str.chomp(sPath, System.getProperty("file.separator"));
}
public static String getString(Map<String,String> oProperties, String sVarName, String sDefault) {
String sValue = oProperties.get(sVarName);
return null==sValue ? sDefault : sValue;
}
/**
* <p>Get a property representing a positive integer value.</p>
* <p>This method ensures that a file separator is always appended to the end of the read value.</p>
* @param oProperties Map<String,String>
* @param sVarName Property Name
* @param iDefault int
* @return Value terminated with a file separator or <b>null</b> if no property with such name was found.
* @throws NumberFormatException
*/
public static int getPositiveInteger(Map<String,String> oProperties, String sVarName, int iDefault) {
int iRetVal;
String sValue = oProperties.get(sVarName);
if (null==sValue) {
iRetVal = iDefault;
} else {
try {
iRetVal = Integer.parseInt(sValue);
if (iRetVal<0) throw new NumberFormatException();
}
catch (NumberFormatException nfe) {
if (DebugFile.trace) {
DebugFile.writeln(sVarName + " property must be a positive integer value");
DebugFile.decIdent();
}
throw new NumberFormatException(sVarName + " property must be a positive integer value");
}
}
return iRetVal;
}
private static void setProperty(Hashtable<String,String> props, String propName, String propValue) {
if (null==propValue) {
if (getDataSourceDefault(propName)!=null)
props.put(propName, getDataSourceDefault(propName));
} else if (propValue.length()==0) {
if (getDataSourceDefault(propName)!=null)
props.put(propName, getDataSourceDefault(propName));
} else {
props.put(propName, propValue);
}
}
}
|
package com.sailthru.client.params;
import com.google.gson.reflect.TypeToken;
import com.sailthru.client.ApiAction;
import java.lang.reflect.Type;
import java.util.Map;
/**
* Event params
* @author Ben Bartholomew <bbartholomew@sailthru.com>
*/
public class Event extends AbstractApiParams implements ApiParams {
protected String id;
protected String key;
protected Map<String, Object> vars;
protected String event;
protected String schedule_time;
public Event(String id) {
this.id = id;
}
public Event() {
// this will be used when new user_id is to be created
}
public Event setKey(String key) {
this.key = key;
return this;
}
public Event setEvent(String eventName) {
this.event = eventName;
return this;
}
public Event setVars(Map<String, Object> vars) {
this.vars = vars;
return this;
}
public Event setScheduleTime(String scheduleTime) {
this.schedule_time = scheduleTime;
return this;
}
public Type getType() {
java.lang.reflect.Type _type = new TypeToken<Event>() {}.getType();
return _type;
}
public ApiAction getApiCall() {
return ApiAction.event;
}
}
|
// JSPyObjectWrapper.java
package ed.lang.python;
import java.util.*;
import org.python.core.*;
import ed.js.*;
import ed.js.func.*;
import ed.js.engine.*;
import static ed.lang.python.Python.*;
public class JSPyObjectWrapper extends JSFunctionCalls0 {
static final boolean DEBUG = Boolean.getBoolean( "DEBUG.JSPYOBJECTWRAPPER" );
static JSFunction _apply = new ed.js.func.JSFunctionCalls3(){
public Object call( Scope s , Object obj , Object args , Object explodeArgs , Object [] foo ){
JSPyObjectWrapper func = (JSPyObjectWrapper)s.getThis();
if ( args == null )
args = new JSArray();
if( ! (args instanceof JSArray) )
throw new RuntimeException("second argument to JSPyObjectWrapper.prototype.apply must be an array, not a " + args.getClass() );
JSArray jary = (JSArray)args;
if ( ! (explodeArgs instanceof JSObject ) ){
throw new RuntimeException("third argument to JSPyObjectWrapper.prototype.apply must be an Object, not a " + args.getClass() );
}
JSObject jo = (JSObject)explodeArgs;
s.setThis( obj );
try {
return toJS( func.callPython( jary.toArray() , jo ) );
}
finally {
s.clearThisNormal( null );
}
}
};
public static class JSPyObjectWrapperCons extends JSFunctionCalls1 {
public JSObject _throwException(){
throw new RuntimeException("you shouldn't be able to instantiate an object wrapper from JS");
}
public JSObject newOne(){
return _throwException();
}
public Object call( Scope scope , Object a , Object[] extra ){
return _throwException();
}
protected void init(){
JSFunction._init( this );
_prototype.set( "apply" , _apply );
}
}
private final static JSFunction _cons = new JSPyObjectWrapperCons();
private JSPyObjectWrapper( ){
setConstructor( _cons );
_p = null;
}
public JSPyObjectWrapper( PyObject o ){
setConstructor( _cons );
_p = o;
if ( _p == null )
throw new NullPointerException( "don't think you should create a JSPyObjectWrapper for null" );
}
public static JSPyObjectWrapper newShell( ){
return new JSPyObjectWrapper();
}
public void setContained( PyObject p ){
// Be careful with this
_p = p;
}
public PyObject getContained( ){
return _p;
}
public boolean isCallable(){
// All python objects are *potentially* callable, so we subclass
// JSFunction.
// This function checks whether the wrapped object is callable.
return __builtin__.callable( _p );
}
public Object set( Object n , Object v ){
if( _p == null && n.equals( "prototype" ) ){
if( DEBUG )
System.err.println("I'm not set up yet! Ignoring set to " + n);
return v;
}
_p.__setitem__( toPython( n ) , toPython( v ) );
return v;
}
public Object get( Object n ){
PyObject p = toPython( n );
Object o = null;
try {
o = _p.__finditem__( p );
} catch(PyException e){
if ( D ) System.out.println("JSPyObjectWrapper.get FIXME: " + e.type);
}
if ( o == null )
o = _p.__findattr__( n.toString() );
if ( o == null )
return super.get( n );
return toJS( o );
}
public Object setInt( int n , Object v ){
_p.__setitem__( toPython( n ) , toPython( v ) );
return v;
}
public Object getInt( int n ){
return toJS( _p.__getitem__( toPython ( n ) ) );
}
public Object removeField( Object n ){
super.removeField( n );
_p.__delattr__( n.toString() );
return null; // FIXME: we removed both of them, who cares
}
public boolean containsKey( String s ){
// TODO: make less awful
return keySet().contains( s );
}
public Object call( Scope s , Object [] params ){
return toJS( callPython( params , null ) );
}
public PyObject callPython( Object [] params , JSObject kwargs ){
Collection<String> keys = null;
String [] pykeys = null;
int length = 0;
if( params != null ){
length += params.length;
}
if( kwargs != null ){
keys = kwargs.keySet();
length += keys.size();
pykeys = new String[ keys.size() ];
}
PyObject [] pParams = new PyObject[ length ];
int i;
for( i = 0; i < params.length; ++i ){
pParams[ i ] = toPython( params[ i ] );
}
int j = 0;
if( kwargs != null ){
for( String key : keys ){
pykeys[ j ] = key;
pParams[ i + j ] = toPython( kwargs.get( key ) );
++j;
}
}
else{
pykeys = new String[0];
}
return _p.__call__( pParams , pykeys );
}
public Collection<String> keySet( boolean includePrototype ){
List<String> keys = new ArrayList<String>();
if ( _p instanceof PyDictionary ){
for ( Object o : ((PyDictionary)_p).keySet() )
keys.add( o.toString() );
}
else try {
for ( PyObject o : _p.asIterable() ){
keys.add( o.toString() );
}
return keys;
}
catch( PyException e ){
PyObject dict = _p.getDict();
if( dict == null ){
// try dir()??
return keys;
}
if( dict instanceof PyStringMap ){
for ( Object o : ((PyStringMap)dict).keys() ){
keys.add( o.toString() );
}
}
else {
PyObject pykeys;
pykeys = dict.invoke( "keys" );
if( pykeys instanceof PySequenceList ){
for( Object o : ((PySequenceList)pykeys) )
keys.add( o.toString() );
}
else
throw new RuntimeException("can't figure out how to get keyset for " + dict.getClass() );
}
}
return keys;
}
public JSFunction getConstructor(){
throw new RuntimeException( "not implemented" );
}
public JSObject getSuper(){
// FIXME: This is probably wrong; since we treat all Python objects as
// functions, why shouldn't we return JSFunction._prototype?
return JSObjectBase._objectLowFunctions;
}
public String toString(){
return _p.toString();
}
protected PyObject _p;
}
|
package groovy.text;
import groovy.lang.Binding;
import groovy.lang.GroovyShell;
import groovy.lang.Script;
import groovy.lang.Writable;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.Reader;
import java.io.StringWriter;
import java.io.Writer;
import java.util.Map;
import org.codehaus.groovy.control.CompilationFailedException;
import org.codehaus.groovy.runtime.InvokerHelper;
/**
* This simple template engine uses JSP <% %> script and <%= %> expression syntax. It also lets you use normal groovy expressions in
* the template text much like the new JSP EL functionality. The variable 'out' is bound to the writer that the template is being written to.
*
* @author sam
* @author Christian Stein
*/
public class SimpleTemplateEngine extends TemplateEngine {
public Template createTemplate(Reader reader) throws CompilationFailedException, IOException {
SimpleTemplate template = new SimpleTemplate();
GroovyShell shell = new GroovyShell();
String script = template.parse(reader);
template.script = shell.parse(script);
return template;
}
private static class SimpleTemplate implements Template {
protected Script script;
public Writable make() {
return make(null);
}
public Writable make(final Map map) {
return new Writable() {
/**
* Write the template document with the set binding applied to the writer.
*
* @see groovy.lang.Writable#writeTo(java.io.Writer)
*/
public Writer writeTo(Writer writer) {
Binding binding;
if (map == null)
binding = new Binding();
else
binding = new Binding(map);
Script scriptObject = InvokerHelper.createScript(script.getClass(), binding);
PrintWriter pw = new PrintWriter(writer);
scriptObject.setProperty("out", pw);
scriptObject.run();
pw.flush();
return writer;
}
/**
* Convert the template and binding into a result String.
*
* @see java.lang.Object#toString()
*/
public String toString() {
try {
StringWriter sw = new StringWriter();
writeTo(sw);
return sw.toString();
} catch (Exception e) {
return e.toString();
}
}
};
}
/**
* Parse the text document looking for <% or <%= and then call out to the appropriate handler, otherwise copy the text directly
* into the script while escaping quotes.
*
* @param reader
* @return
* @throws IOException
*/
protected String parse(Reader reader) throws IOException {
if (!reader.markSupported()) {
reader = new BufferedReader(reader);
}
StringWriter sw = new StringWriter();
startScript(sw);
boolean start = false;
int c;
while ((c = reader.read()) != -1) {
if (c == '<') {
reader.mark(1);
c = reader.read();
if (c != '%') {
sw.write('<');
reader.reset();
} else {
reader.mark(1);
c = reader.read();
if (c == '=') {
groovyExpression(reader, sw);
} else {
reader.reset();
groovySection(reader, sw);
}
}
continue; // at least '<' is consumed ... read next chars.
}
if (c == '\"') {
sw.write('\\');
}
/*
* Handle raw new line characters.
*/
if (c == '\n' || c == '\r') {
if (c == '\r') { // on Windows, "\r\n" is a new line.
reader.mark(1);
c = reader.read();
if (c != '\n') {
reader.reset();
}
}
sw.write("\\n\");\nout.print(\"");
continue;
}
sw.write(c);
}
endScript(sw);
String result = sw.toString();
//System.err.println("source text:\n" + result);
return result;
}
private void startScript(StringWriter sw) {
sw.write("/* Generated by SimpleTemplateEngine */\n");
sw.write("out.print(\"");
}
private void endScript(StringWriter sw) {
sw.write("\");\n");
}
/**
* Closes the currently open write and writes out the following text as a GString expression until it reaches an end %>.
*
* @param reader
* @param sw
* @throws IOException
*/
private void groovyExpression(Reader reader, StringWriter sw) throws IOException {
sw.write("\");out.print(\"${");
int c;
while ((c = reader.read()) != -1) {
if (c == '%') {
c = reader.read();
if (c != '>') {
sw.write('%');
} else {
break;
}
}
if (c != '\n' && c != '\r') {
sw.write(c);
}
}
sw.write("}\");\nout.print(\"");
}
/**
* Closes the currently open write and writes the following text as normal Groovy script code until it reaches an end %>.
*
* @param reader
* @param sw
* @throws IOException
*/
private void groovySection(Reader reader, StringWriter sw) throws IOException {
sw.write("\");");
int c;
while ((c = reader.read()) != -1) {
if (c == '%') {
c = reader.read();
if (c != '>') {
sw.write('%');
} else {
break;
}
}
if (c != '\n' && c != '\r') {
sw.write(c);
}
}
sw.write(";\nout.print(\"");
}
}
}
|
package backend.stub;
import backend.resource.TurboIssue;
import backend.resource.TurboLabel;
import backend.resource.TurboMilestone;
import backend.resource.TurboUser;
import github.TurboIssueEvent;
import org.apache.commons.lang3.tuple.ImmutablePair;
import org.apache.commons.lang3.tuple.ImmutableTriple;
import org.eclipse.egit.github.core.Comment;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
public class DummyRepoState {
private String dummyRepoId;
private List<TurboIssue> issues = new ArrayList<>();
private List<TurboLabel> labels = new ArrayList<>();
private List<TurboMilestone> milestones = new ArrayList<>();
private List<TurboUser> users = new ArrayList<>();
private List<TurboIssue> updatedIssues = new ArrayList<>();
private List<TurboLabel> updatedLabels = new ArrayList<>();
private List<TurboMilestone> updatedMilestones = new ArrayList<>();
private List<TurboUser> updatedUsers = new ArrayList<>();
public DummyRepoState(String repoId) {
this.dummyRepoId = repoId;
for (int i = 0; i < 10; i++) {
issues.add(makeDummyIssue());
labels.add(makeDummyLabel());
milestones.add(makeDummyMilestone());
users.add(makeDummyUser());
}
}
protected ImmutableTriple<List<TurboIssue>, String, Date>
getUpdatedIssues(String ETag, Date lastCheckTime) {
ImmutableTriple<List<TurboIssue>, String, Date> toReturn
= new ImmutableTriple<>(updatedIssues, ETag, lastCheckTime);
updatedIssues = new ArrayList<>();
return toReturn;
}
protected ImmutablePair<List<TurboLabel>, String> getUpdatedLabels(String ETag) {
ImmutablePair<List<TurboLabel>, String> toReturn
= new ImmutablePair<>(updatedLabels, ETag);
updatedLabels = new ArrayList<>();
return toReturn;
}
protected ImmutablePair<List<TurboMilestone>, String> getUpdatedMilestones(String ETag) {
ImmutablePair<List<TurboMilestone>, String> toReturn
= new ImmutablePair<>(updatedMilestones, ETag);
updatedMilestones = new ArrayList<>();
return toReturn;
}
protected ImmutablePair<List<TurboUser>, String> getUpdatedCollaborators(String ETag) {
ImmutablePair<List<TurboUser>, String> toReturn
= new ImmutablePair<>(updatedUsers, ETag);
updatedUsers = new ArrayList<>();
return toReturn;
}
protected List<TurboIssue> getIssues() {
return issues;
}
protected List<TurboLabel> getLabels() {
return labels;
}
protected List<TurboMilestone> getMilestones() {
return milestones;
}
protected List<TurboUser> getCollaborators() {
return users;
}
private TurboIssue makeDummyIssue() {
return new TurboIssue(dummyRepoId, issues.size() + 1, "Issue " + (issues.size() + 1));
}
private TurboLabel makeDummyLabel() {
return new TurboLabel(dummyRepoId, "Label " + (labels.size() + 1));
}
private TurboMilestone makeDummyMilestone() {
return new TurboMilestone(dummyRepoId, milestones.size() + 1, "Milestone " + (milestones.size() + 1));
}
private TurboUser makeDummyUser() {
return new TurboUser(dummyRepoId, "User " + (users.size() + 1));
}
protected List<TurboIssueEvent> getEvents() {
return new ArrayList<>();
}
protected List<Comment> getComments() {
return new ArrayList<>();
}
// UpdateEvent methods to directly mutate the repo state
protected void makeNewIssue() {
TurboIssue toAdd = makeDummyIssue();
issues.add(toAdd);
updatedIssues.add(toAdd);
}
protected void makeNewLabel() {
TurboLabel toAdd = makeDummyLabel();
labels.add(toAdd);
updatedLabels.add(toAdd);
}
protected void makeNewMilestone() {
TurboMilestone toAdd = makeDummyMilestone();
milestones.add(toAdd);
updatedMilestones.add(toAdd);
}
protected void makeNewUser() {
TurboUser toAdd = makeDummyUser();
users.add(toAdd);
updatedUsers.add(toAdd);
}
// Only updating of issues is possible. Labels, milestones and users are immutable.
protected TurboIssue updateIssue(int itemId, String updateText) {
int toUpdate = 0;
// Linear search
for (TurboIssue issue : issues) {
if (issue.getId() == itemId) break;
toUpdate++;
}
if (toUpdate < issues.size()) { // Found
TurboIssue issueToUpdate = issues.get(toUpdate);
issueToUpdate.setTitle(updateText);
updatedIssues.add(issueToUpdate);
return issueToUpdate;
}
return null;
}
protected TurboIssue deleteIssue(int itemId) {
int toDelete = 0;
for (TurboIssue issue : issues) {
if (issue.getId() == itemId) break;
toDelete++;
}
int toDeleteUpdated = 0;
for (TurboIssue updatedIssue : updatedIssues) {
if (updatedIssue.getId() == itemId) break;
toDeleteUpdated++;
}
if (toDeleteUpdated < updatedIssues.size()) updatedIssues.remove(toDeleteUpdated);
if (toDelete < issues.size()) { // Found
return issues.remove(toDelete);
}
return null;
}
protected TurboLabel deleteLabel(String idString) {
int toDelete = 0;
for (TurboLabel label : labels) {
if (label.getActualName().equalsIgnoreCase(idString)) break;
toDelete++;
}
int toDeleteUpdated = 0;
for (TurboLabel updatedLabel : updatedLabels) {
if (updatedLabel.getActualName().equalsIgnoreCase(idString)) break;
toDeleteUpdated++;
}
if (toDeleteUpdated < updatedLabels.size()) updatedLabels.remove(toDeleteUpdated);
if (toDelete < labels.size()) { // Found
return labels.remove(toDelete);
}
return null;
}
protected TurboMilestone deleteMilestone(int itemId) {
int toDelete = 0;
for (TurboMilestone milestone : milestones) {
if (milestone.getId() == itemId) break;
toDelete++;
}
int toDeleteUpdated = 0;
for (TurboMilestone updatedMilestone : updatedMilestones) {
if (updatedMilestone.getId() == itemId) break;
toDeleteUpdated++;
}
if (toDeleteUpdated < updatedMilestones.size()) updatedMilestones.remove(toDeleteUpdated);
if (toDelete < milestones.size()) { // Found
return milestones.remove(toDelete);
}
return null;
}
protected TurboUser deleteUser(String idString) {
int toDelete = 0;
for (TurboUser user : users) {
if (user.getLoginName().equalsIgnoreCase(idString)) break;
toDelete++;
}
int toDeleteUpdated = 0;
for (TurboUser updatedUser : updatedUsers) {
if (updatedUser.getLoginName().equalsIgnoreCase(idString)) break;
toDeleteUpdated++;
}
if (toDeleteUpdated < updatedUsers.size()) updatedUsers.remove(toDeleteUpdated);
if (toDelete < users.size()) { // Found
return users.remove(toDelete);
}
return null;
}
}
|
package blog.model;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import blog.common.numerical.MatrixFactory;
import blog.common.numerical.MatrixLib;
import blog.objgen.ObjectSet;
import blog.type.Timestep;
/**
* Class with static methods and constants for built-in non-random functions
* (including built-in constants). This class cannot be instantiated.
*
* @author unknown
* @author leili
* @date 2/11/2014
*/
public class BuiltInFunctions {
/**
* internal names for builtin functions, these are not supposed to be called
* by users
*/
public static final String PLUS_NAME = "__PLUS";
public static final String MINUS_NAME = "__MINUS";
public static final String MULT_NAME = "__MULT";
public static final String DIV_NAME = "__DIV";
public static final String MOD_NAME = "__MOD";
public static final String POWER_NAME = "__POWER";
public static final String SUB_MAT_NAME = "__SUB_MAT";
public static final String SUB_ARRAY_NAME = "__SUB_ARRAY";
public static final String GT_NAME = "__GREATERTHAN";
public static final String GEQ_NAME = "__GREATERTHANOREQUAL";
public static final String LT_NAME = "__LESSTHAN";
public static final String LEQ_NAME = "__LESSTHANOREQUAL";
public static final String CASE_EXPR_NAME = "__CASEINEXPR";
// can be called by user
public static final String SUCC_NAME = "succ";
public static final String PRED_NAME = "pred";
public static final String PREV_NAME = "prev";
public static final String INV_NAME = "inv";
public static final String DET_NAME = "det";
public static final String IS_EMPTY_NAME = "isEmptyString";
public static final String MIN_NAME = "min";
public static final String MAX_NAME = "max";
public static final String ROUND_NAME = "round";
public static final String DIAG_NAME = "diag";
public static final String REPMAT_NAME = "repmat";
public static final String TRANSPOSE_NAME = "transpose";
public static final String SIN_NAME = "sin";
public static final String COS_NAME = "cos";
public static final String TAN_NAME = "tan";
public static final String ATAN2_NAME = "atan2";
public static final String SUM_NAME = "sum";
public static final String SIZE_NAME = "size";
public static final String VSTACK_NAME = "vstack";
public static final String HSTACK_NAME = "hstack";
public static final String EYE_NAME = "eye";
public static final String ZEROS_NAME = "zeros";
public static final String ONES_NAME = "ones";
public static final String TOINT_NAME = "toInt";
public static final String TOREAL_NAME = "toReal";
public static final String LOAD_REAL_MATRIX_NAME = "loadRealMatrix";
public static final String ABS_NAME = "abs";
public static final String EXP_NAME = "exp";
public static final String IOTA_NAME = "iota";
/**
* Constant that always denotes Model.NULL.
*/
public static final FixedFunction NULL;
/**
* Constant that denotes the natural number 0. The parser creates
* NonRandomConstant objects as needed to represent numeric constants that it
* actually encounters in a file, but some internal compilation code may need
* to use this constant even if it doesn't occur in a file.
*/
public static final FixedFunction ZERO;
/**
* Constant that denotes the timestep 0. The parser creates NonRandomConstant
* objects as needed to represent timestep constants that it actually
* encounters in a file, but some internal compilation code may need to use
* this constant even if it doesn't occur in a file.
*/
public static final FixedFunction EPOCH;
/**
* Constant that denotes E.
*/
public static final FixedFunction E;
/**
* Constant that denotes PI.
*/
public static final FixedFunction PI;
/**
* The LessThan relation on type Real (and its subtypes).
*/
public static FixedFunction LT;
/**
* The LessThanOrEqual relation on type Real (and its subtypes).
*/
public static FixedFunction LEQ;
/**
* The GreaterThan relation on type Real (and its subtypes)
*/
public static FixedFunction GT;
/**
* The GreaterThanOrEqual relation on type Real (and its subtypes).
*/
public static FixedFunction GEQ;
/**
* The successor function on natural numbers. Given a number n, it returns
* n+1.
*/
public static FixedFunction SUCC;
/**
* The predecessor function on natural numbers. Given a positive number n, it
* returns n-1. Given the number 0, it returns Model.NULL.
*/
public static FixedFunction PRED;
/**
* A function from integers to natural numbers that yields the non-negative
* part of the given integer <code>x</code>: that is, <code>min(x, 0)</code>.
*/
public static FixedFunction NON_NEG_PART;
/**
* The function on integers <code>x<code>, <code>y</code> that returns x + y.
*/
public static FixedFunction PLUS;
/**
* The function on integers <code>x<code>, <code>y</code> that returns x - y.
*/
public static FixedFunction MINUS;
/**
* The function on integers <code>x<code>, <code>y</code> that returns x * y.
*/
public static FixedFunction MULT;
/**
* The function on integers <code>x<code>, <code>y</code> that returns x / y.
*/
public static FixedFunction DIV;
/**
* The function on integers <code>x<code>, <code>y</code> that returns x % y.
*/
public static FixedFunction MOD;
/**
* The function on timestep <code>x<code>, integer <code>y</code> that returns
* x + y.
*/
public static FixedFunction TSPLUS;
/**
* The function on timestep <code>x<code>, integer <code>y</code> that returns
* x - y.
*/
public static FixedFunction TSMINUS;
/**
* The function on timestep <code>x<code>, integer <code>y</code> that returns
* x * y.
*/
public static FixedFunction TSMULT;
/**
* The function on timestep <code>x<code>, integer <code>y</code> that returns
* x / y.
*/
public static FixedFunction TSDIV;
/**
* The function on timestep <code>x<code>, integer <code>y</code> that returns
* x % y.
*/
public static FixedFunction TSMOD;
/**
* The function on reals <code>x<code>, <code>y</code> that returns x + y.
*/
public static FixedFunction RPLUS;
/**
* The function on reals <code>x<code>, <code>y</code> that returns x - y.
*/
public static FixedFunction RMINUS;
/**
* The function on reals <code>x<code>, <code>y</code> that returns x * y.
*/
public static FixedFunction RMULT;
/**
* The function on reals <code>x<code>, <code>y</code> that returns x ^ y.
*/
public static FixedFunction POWER;
/**
* The function on reals <code>x<code>, <code>y</code> that returns x / y.
*/
public static FixedFunction RDIV;
/**
* RealMatrix + RealMatrix returns RealMatrix
*/
public static FixedFunction PLUS_MAT;
/**
* RealMatrix - RealMatrix returns RealMatrix
*/
public static FixedFunction MINUS_MAT;
/**
* RealMatrix * RealMatrix returns RealMatrix (matrix multiplication)
*/
public static FixedFunction TIMES_MAT;
/**
* RealMatrix * Real returns RealMatrix
*/
public static FixedFunction TIMES_MAT_SCALAR;
/**
* Real * RealMatrix returns RealMatrix
*/
public static FixedFunction TIMES_SCALAR_MAT;
/**
* inv(RealMatrix) returns RealMatrix (matrix inverse)
*/
public static FixedFunction INV_MAT;
/**
* det(RealMatrix) returns Real (matrix determinant)
*/
public static FixedFunction DET_MAT;
/**
* The predecessor function on timesteps. Given a positive timestep n, it
* returns n-1. Given the timestep 0, it returns Model.NULL.
*/
public static FixedFunction PREV;
/**
* A function on strings <code>x</code>, <code>y</code> that returns the
* concatenation of <code>x</code> and <code>y</code>.
*/
public static FixedFunction CONCAT;
/**
* RealMatrix[Integer] returns RealMatrix (i-th row of matrix)
*/
public static FixedFunction SUB_MAT;
/**
* RealArray[Integer] returns Real (i-th element of array)
*/
public static FixedFunction SUB_REAL_ARRAY;
/**
* IntegerArray[Integer] returns Integer (i-th element of array)
*/
public static FixedFunction SUB_INT_ARRAY;
/**
* a function on Set <code>x</code> returns the minimal value from the set
*/
public static FixedFunction MIN;
/**
* a function on Set <code>x</code> returns the maximal value from the set
*/
public static FixedFunction MAX;
/**
* a function on Real <code>x</code> returns the nearest integer to
* <code>x</code>
*/
public static FixedFunction ROUND;
/**
* Diagonal(RealMatrix) returns RealMatrix
*/
public static FixedFunction DIAG_REAL_MAT;
/**
* Repmat(RealMatrix) returns RealMatrix
*/
public static FixedFunction REPMAT_REAL;
/**
* transpose(RealMatrix) returns RealMatrix
*/
public static FixedFunction TRANSPOSE_REAL_MAT;
/**
* transpose(IntegerMatrix) returns IntegerMatrix
*/
public static FixedFunction TRANSPOSE_INT_MAT;
/**
* A function that takes a string and returns true if the string is empty.
*/
public static FixedFunction IS_EMPTY_STRING;
/**
* Take scalar <code>x</code> (in radians) and return <code>sin(x)</code>.
*/
public static FixedFunction SIN;
/**
* Take scalar <code>x</code> (in radians) and return <code>cos(x)</code>.
*/
public static FixedFunction COS;
/**
* Take scalar <code>x</code> (in radians) and return <code>tan(x)</code>.
*/
public static FixedFunction TAN;
/**
* Take scalars <code>x</code> and <code>y</code> and return
* <code>atan2(y, x)</code>.
*/
public static FixedFunction ATAN2;
/**
* Take RealMatrix x and return RealMatrix y where elements are the sum of
* columns of x.
*/
public static FixedFunction COL_SUM;
/**
* Take a Set x of Real values, and return the sum of its elements.
*/
public static FixedFunction SET_SUM;
/**
* Take a Set x of values (any type, including user declared type), and return
* the number of elements in the Set.
*/
public static FixedFunction SET_SIZE;
/**
* Special case for VSTACK when arguments are all matrices
*/
private static FunctionInterp VSTACK_MATRIX_INTERP;
/**
* Special case for VSTACK when arguments are all scalars
*/
private static FunctionInterp VSTACK_SCALAR_INTERP;
/**
* Take RealMatrices [x; y; ...] and return RealMatrix z which is the
* vertical concatenation
* Arguments could be either all matrices or all scalars
*/
public static TemplateFunction VSTACK;
/**
* Special case for HSTACK when arguments are all matrices
*/
private static FunctionInterp HSTACK_MATRIX_INTERP;
/**
* Special case for HSTACK when arguments are all scalars
*/
private static FunctionInterp HSTACK_SCALAR_INTERP;
/**
* Take RealMatrices [x, y, ...] and return RealMatrix z which is the
* horizontal concatenation
* Arguments could be either all matrices or all scalars
*/
public static TemplateFunction HSTACK;
/**
* Return an identity matrix.
*/
public static FixedFunction EYE;
/**
* Return a matrix of zeros.
*/
public static FixedFunction ZEROS;
/**
* Return a matrix of ones.
*/
public static FixedFunction ONES;
/**
* The function takes an Integer, an Real or a MatrixLib with single element,
* and converts it to an Integer
*/
public static FixedFunction TO_INT;
/**
* The function takes a Real or a MatrixLib with single element,
* and converts it to a Real
*/
public static FixedFunction TO_REAL;
/**
* Return the absolute value of a Real value.
*/
public static FixedFunction ABS;
/**
* Return the absolute value of a Integer value.
*/
public static FixedFunction ABS_INT;
/**
* Return the absolute value of every element of a Real matrix.
*/
public static FixedFunction ABS_MAT;
/**
* Return the exponential value of a Real value.
*/
public static FixedFunction EXP;
/**
* Return the exponential value of a Integer value.
*/
public static FixedFunction EXP_INT;
/**
* Return the exponential value of every element in the matrix.
*/
public static FixedFunction EXP_MAT;
/**
* Return the element from a singleton set.
*/
public static FixedFunction IOTA;
/**
* Interpret the case expression in fixed function, also used for if then else
* in fixed function
*/
public static TemplateFunction CASE_IN_FIXED_FUNC;
/**
* Load RealMatrix from space-separeted text file.
*/
public static FixedFunction LOAD_REAL_MATRIX;
private BuiltInFunctions() {
// prevent instantiation
}
/**
* Returns the built-in function (or constant) with the given signature.
* Returns null if there is no such built-in function, or if the given name is
* a numeric, character, or string literal that is only created as needed by
* the parser.
*/
public static FixedFunction getFunction(FunctionSignature sig) {
// TODO change to another hashmap from signature to function
List funcsWithName = (List) functions.get(sig.getName());
if (funcsWithName != null) {
for (Iterator iter = funcsWithName.iterator(); iter.hasNext();) {
FixedFunction f = (FixedFunction) iter.next();
if (Arrays.equals(sig.getArgTypes(), f.getArgTypes())) {
return f;
}
}
}
// find template functions compatible with sig
TemplateFunction tempfun = templateFunctions.get(sig.getName());
if (tempfun != null) {
FixedFunction f = tempfun.getConcreteFunction(sig.getArgTypes());
if (f != null)
return f;
}
return null;
}
/**
* Returns the built-in constant symbol with the given name, which has the
* given return type and denotes the given value. Creates the constant symbol
* automatically if it hasn't been created yet.
*/
public static FixedFunction getLiteral(String name, Type type, Object value) {
FixedFunction f = getFunction(new FunctionSignature(name));
if (f == null) {
List params = Collections.singletonList(value);
f = new FixedFunction(name, Collections.EMPTY_LIST, type,
new ConstantInterp(params));
addFunction(f);
}
return f;
}
/**
* Returns the built-in functions (and constants) with the given name.
*
* @return unmodifiable List of Function
*/
public static List getFuncsWithName(String name) {
List funcsWithName = (List) functions.get(name);
return (funcsWithName == null) ? Collections.EMPTY_LIST : Collections
.unmodifiableList(funcsWithName);
}
private static void addFunction(Function f) {
List funcsWithName = (List) functions.get(f.getName());
if (funcsWithName != null) {
for (Iterator iter = funcsWithName.iterator(); iter.hasNext();) {
Function g = (Function) iter.next();
if (Arrays.equals(g.getArgTypes(), f.getArgTypes())) {
System.err.println("Warning: overwriting existing " + "function "
+ g.getSig());
iter.remove();
}
}
} else {
funcsWithName = new ArrayList();
functions.put(f.getName(), funcsWithName);
}
funcsWithName.add(f);
}
static Map functions = new HashMap(); // from String to List of Function
private static void addTemplate(TemplateFunction t) {
templateFunctions.put(t.getName(), t);
}
static Map<String, TemplateFunction> templateFunctions = new HashMap<String, TemplateFunction>();
static {
// Add non-random constants
NULL = getLiteral("null", BuiltInTypes.NULL, Model.NULL);
ZERO = getLiteral("0", BuiltInTypes.INTEGER, new Integer(0));
EPOCH = getLiteral("@0", BuiltInTypes.TIMESTEP, Timestep.at(0));
E = getLiteral("e", BuiltInTypes.REAL, new Double(Math.E));
PI = getLiteral("pi", BuiltInTypes.REAL, new Double(Math.PI));
// Add non-random functions from (real x real) to Boolean
List<Type> argTypes = new ArrayList<Type>();
argTypes.add(BuiltInTypes.REAL);
argTypes.add(BuiltInTypes.REAL);
Type retType = BuiltInTypes.BOOLEAN;
FunctionInterp ltInterp = new AbstractFunctionInterp() {
public Object getValue(List args) {
double arg1 = ((Number) args.get(0)).doubleValue();
double arg2 = ((Number) args.get(1)).doubleValue();
return Boolean.valueOf(arg1 < arg2);
}
};
LT = new FixedFunction(LT_NAME, argTypes, retType, ltInterp);
addFunction(LT);
FunctionInterp leqInterp = new AbstractFunctionInterp() {
public Object getValue(List args) {
double arg1 = ((Number) args.get(0)).doubleValue();
double arg2 = ((Number) args.get(1)).doubleValue();
return Boolean.valueOf(arg1 <= arg2);
}
};
LEQ = new FixedFunction(LEQ_NAME, argTypes, retType, leqInterp);
addFunction(LEQ);
FunctionInterp gtInterp = new AbstractFunctionInterp() {
public Object getValue(List args) {
double arg1 = ((Number) args.get(0)).doubleValue();
double arg2 = ((Number) args.get(1)).doubleValue();
return Boolean.valueOf(arg1 > arg2);
}
};
GT = new FixedFunction(GT_NAME, argTypes, retType, gtInterp);
addFunction(GT);
FunctionInterp geqInterp = new AbstractFunctionInterp() {
public Object getValue(List args) {
double arg1 = ((Number) args.get(0)).doubleValue();
double arg2 = ((Number) args.get(1)).doubleValue();
return Boolean.valueOf(arg1 >= arg2);
}
};
GEQ = new FixedFunction(GEQ_NAME, argTypes, retType, geqInterp);
addFunction(GEQ);
// Add non-random functions from natural number to natural number
argTypes.clear();
argTypes.add(BuiltInTypes.NATURAL_NUM);
retType = BuiltInTypes.NATURAL_NUM;
FunctionInterp succInterp = new AbstractFunctionInterp() {
public Object getValue(List args) {
Integer arg = (Integer) args.get(0);
return new Integer(arg.intValue() + 1);
}
};
SUCC = new FixedFunction(SUCC_NAME, argTypes, retType, succInterp);
addFunction(SUCC);
FunctionInterp predInterp = new AbstractFunctionInterp() {
public Object getValue(List args) {
Integer arg = (Integer) args.get(0);
if (arg.intValue() <= 0) {
return Model.NULL;
}
return new Integer(arg.intValue() - 1);
}
};
PRED = new FixedFunction(PRED_NAME, argTypes, retType, predInterp);
addFunction(PRED);
// Add non-random functions from integer to natural number
argTypes.clear();
argTypes.add(BuiltInTypes.INTEGER);
retType = BuiltInTypes.NATURAL_NUM;
FunctionInterp nonNegPartInterp = new AbstractFunctionInterp() {
public Object getValue(List args) {
Integer arg = (Integer) args.get(0);
int n = arg.intValue();
return new Integer((n < 0) ? 0 : n);
}
};
NON_NEG_PART = new FixedFunction("NonNegPart", argTypes, retType,
nonNegPartInterp);
addFunction(NON_NEG_PART);
// Add non-random functions from (integer x integer) to integer
argTypes.clear();
argTypes.add(BuiltInTypes.INTEGER);
argTypes.add(BuiltInTypes.INTEGER);
retType = BuiltInTypes.INTEGER;
FunctionInterp plusInterp = new AbstractFunctionInterp() {
public Object getValue(List args) {
Integer arg1 = (Integer) args.get(0);
Integer arg2 = (Integer) args.get(1);
return new Integer(arg1.intValue() + arg2.intValue());
}
};
PLUS = new FixedFunction(PLUS_NAME, argTypes, retType, plusInterp);
addFunction(PLUS);
// Multiply non-random functions from (integer x integer) to integer
FunctionInterp multInterp = new AbstractFunctionInterp() {
public Object getValue(List args) {
Integer arg1 = (Integer) args.get(0);
Integer arg2 = (Integer) args.get(1);
return new Integer(arg1.intValue() * arg2.intValue());
}
};
MULT = new FixedFunction(MULT_NAME, argTypes, retType, multInterp);
addFunction(MULT);
FunctionInterp minusInterp = new AbstractFunctionInterp() {
public Object getValue(List args) {
Integer arg1 = (Integer) args.get(0);
Integer arg2 = (Integer) args.get(1);
return new Integer(arg1.intValue() - arg2.intValue());
}
};
MINUS = new FixedFunction(MINUS_NAME, argTypes, retType, minusInterp);
addFunction(MINUS);
// Divide non-random functions from (integer x integer) to integer
FunctionInterp divInterp = new AbstractFunctionInterp() {
public Object getValue(List args) {
Integer arg1 = (Integer) args.get(0);
Integer arg2 = (Integer) args.get(1);
return new Integer(arg1.intValue() / arg2.intValue());
}
};
DIV = new FixedFunction(DIV_NAME, argTypes, retType, divInterp);
addFunction(DIV);
// Mod non-random functions from (integer x integer) to integer
FunctionInterp modInterp = new AbstractFunctionInterp() {
public Object getValue(List args) {
Integer arg1 = (Integer) args.get(0);
Integer arg2 = (Integer) args.get(1);
return new Integer(arg1.intValue() % arg2.intValue());
}
};
MOD = new FixedFunction(MOD_NAME, argTypes, retType, modInterp);
addFunction(MOD);
// Add non-random functions from (real x real) to real
argTypes.clear();
argTypes.add(BuiltInTypes.REAL);
argTypes.add(BuiltInTypes.REAL);
retType = BuiltInTypes.REAL;
FunctionInterp rplusInterp = new AbstractFunctionInterp() {
public Object getValue(List args) {
Number arg1 = (Number) args.get(0);
Number arg2 = (Number) args.get(1);
return new Double(arg1.doubleValue() + arg2.doubleValue());
}
};
RPLUS = new FixedFunction(PLUS_NAME, argTypes, retType, rplusInterp);
addFunction(RPLUS);
FunctionInterp rminusInterp = new AbstractFunctionInterp() {
public Object getValue(List args) {
Number arg1 = (Number) args.get(0);
Number arg2 = (Number) args.get(1);
return new Double(arg1.doubleValue() - arg2.doubleValue());
}
};
RMINUS = new FixedFunction(MINUS_NAME, argTypes, retType, rminusInterp);
addFunction(RMINUS);
FunctionInterp rmultInterp = new AbstractFunctionInterp() {
public Object getValue(List args) {
Number arg1 = (Number) args.get(0);
Number arg2 = (Number) args.get(1);
return new Double(arg1.doubleValue() * arg2.doubleValue());
}
};
RMULT = new FixedFunction(MULT_NAME, argTypes, retType, rmultInterp);
addFunction(RMULT);
FunctionInterp rdivInterp = new AbstractFunctionInterp() {
public Object getValue(List args) {
Number arg1 = (Number) args.get(0);
Number arg2 = (Number) args.get(1);
return new Double(arg1.doubleValue() / arg2.doubleValue());
}
};
RDIV = new FixedFunction(DIV_NAME, argTypes, retType, rdivInterp);
addFunction(RDIV);
FunctionInterp powerInterp = new AbstractFunctionInterp() {
public Object getValue(List args) {
Number arg1 = (Number) args.get(0);
Number arg2 = (Number) args.get(1);
return new Double(Math.pow(arg1.doubleValue(), arg2.doubleValue()));
}
};
POWER = new FixedFunction(POWER_NAME, argTypes, retType, powerInterp);
addFunction(POWER);
// Add non-random functions from timestep to timestep
argTypes.clear();
argTypes.add(BuiltInTypes.TIMESTEP);
retType = BuiltInTypes.TIMESTEP;
FunctionInterp prevInterp = new AbstractFunctionInterp() {
public Object getValue(List args) {
Timestep arg = (Timestep) args.get(0);
if (arg.getValue() <= 0) {
return Model.NULL;
}
return Timestep.at(arg.getValue() - 1);
}
};
PREV = new FixedFunction(PREV_NAME, argTypes, retType, prevInterp);
addFunction(PREV);
// Add non-random functions from (TimeStep x Integer) to TimeStep
argTypes.clear();
argTypes.add(BuiltInTypes.TIMESTEP);
argTypes.add(BuiltInTypes.INTEGER);
retType = BuiltInTypes.TIMESTEP;
FunctionInterp tsplusInterp = new AbstractFunctionInterp() {
public Object getValue(List args) {
Timestep arg1 = (Timestep) args.get(0);
Integer arg2 = (Integer) args.get(1);
if (arg1.getValue() + arg2.intValue() < 0)
return Model.NULL;
return Timestep.at(arg1.getValue() + arg2.intValue());
}
};
TSPLUS = new FixedFunction(PLUS_NAME, argTypes, retType, tsplusInterp);
addFunction(TSPLUS);
FunctionInterp tsminusInterp = new AbstractFunctionInterp() {
public Object getValue(List args) {
Timestep arg1 = (Timestep) args.get(0);
Integer arg2 = (Integer) args.get(1);
if (arg1.getValue() < arg2.intValue())
return Model.NULL;
return Timestep.at(arg1.getValue() - arg2.intValue());
}
};
TSMINUS = new FixedFunction(MINUS_NAME, argTypes, retType, tsminusInterp);
addFunction(TSMINUS);
FunctionInterp tsmultInterp = new AbstractFunctionInterp() {
public Object getValue(List args) {
Timestep arg1 = (Timestep) args.get(0);
Integer arg2 = (Integer) args.get(1);
if (arg2.intValue() < 0)
return Model.NULL;
return Timestep.at(arg1.getValue() * arg2.intValue());
}
};
TSMULT = new FixedFunction(MULT_NAME, argTypes, retType, tsmultInterp);
addFunction(TSMULT);
FunctionInterp tsdivInterp = new AbstractFunctionInterp() {
public Object getValue(List args) {
Timestep arg1 = (Timestep) args.get(0);
Integer arg2 = (Integer) args.get(1);
if (arg2.intValue() <= 0)
return Model.NULL;
return Timestep.at(arg1.getValue() / arg2.intValue());
}
};
TSDIV = new FixedFunction(DIV_NAME, argTypes, retType, tsdivInterp);
addFunction(TSDIV);
FunctionInterp tsmodInterp = new AbstractFunctionInterp() {
public Object getValue(List args) {
Timestep arg1 = (Timestep) args.get(0);
Integer arg2 = (Integer) args.get(1);
if (arg2.intValue() <= 0)
return Model.NULL;
return Timestep.at(arg1.getValue() % arg2.intValue());
}
};
TSMOD = new FixedFunction(MOD_NAME, argTypes, retType, tsmodInterp);
addFunction(TSMOD);
// Add non-random functions from (string x string) to string
argTypes.clear();
argTypes.add(BuiltInTypes.STRING);
argTypes.add(BuiltInTypes.STRING);
retType = BuiltInTypes.STRING;
FunctionInterp concatInterp = new AbstractFunctionInterp() {
public Object getValue(List args) {
String arg1 = (String) args.get(0);
String arg2 = (String) args.get(1);
return arg1.concat(arg2);
}
};
CONCAT = new FixedFunction(PLUS_NAME, argTypes, retType, concatInterp);
addFunction(CONCAT);
// Add non-random functions from string to Boolean
argTypes.clear();
argTypes.add(BuiltInTypes.STRING);
retType = BuiltInTypes.BOOLEAN;
FunctionInterp isEmptyStringInterp = new AbstractFunctionInterp() {
public Object getValue(List args) {
return Boolean.valueOf(((String) args.get(0)).length() == 0);
}
};
IS_EMPTY_STRING = new FixedFunction(IS_EMPTY_NAME, argTypes, retType,
isEmptyStringInterp);
addFunction(IS_EMPTY_STRING);
// Add non-random functions from (RealMatrix x int) to RealMatrix
argTypes.clear();
argTypes.add(BuiltInTypes.REAL_MATRIX);
argTypes.add(BuiltInTypes.INTEGER);
retType = BuiltInTypes.REAL_MATRIX;
// Return the i-th row of the matrix,
// or if the matrix has a single row, return the i-th column.
FunctionInterp subMatInterp = new AbstractFunctionInterp() {
public Object getValue(List args) {
MatrixLib mat = (MatrixLib) args.get(0);
int i = (Integer) args.get(1);
if (mat.numRows() > 1) {
return mat.sliceRow(i);
} else {
return mat.elementAt(0, i);
}
}
};
SUB_MAT = new FixedFunction(SUB_MAT_NAME, argTypes, retType, subMatInterp);
addFunction(SUB_MAT);
// Array subscription (aka indexing)
FunctionInterp subVecInterp = new AbstractFunctionInterp() {
public Object getValue(List args) {
MatrixLib mat = (MatrixLib) args.get(0);
int i = (Integer) args.get(1);
if (mat.numRows() == 1) {
return mat.elementAt(0, i);
} else if (mat.numCols() == 1) {
return mat.elementAt(i, 0);
} else {
throw new IllegalArgumentException(
"subVecInterp expected vector, but given 2D matrix");
}
}
};
// Array indexing for Real arrays:
argTypes.clear();
argTypes.add(BuiltInTypes.REAL_ARRAY);
argTypes.add(BuiltInTypes.INTEGER);
retType = BuiltInTypes.REAL;
SUB_REAL_ARRAY = new FixedFunction(SUB_ARRAY_NAME, argTypes, retType,
subVecInterp);
addFunction(SUB_REAL_ARRAY);
// Array indexing for Integer arrays:
argTypes.clear();
argTypes.add(BuiltInTypes.INTEGER_ARRAY);
argTypes.add(BuiltInTypes.INTEGER);
retType = BuiltInTypes.INTEGER;
SUB_INT_ARRAY = new FixedFunction(SUB_ARRAY_NAME, argTypes, retType,
subVecInterp);
addFunction(SUB_INT_ARRAY);
// Add non-random functions from (RealMatrix x RealMatrix) to RealMatrix
argTypes.clear();
argTypes.add(BuiltInTypes.REAL_MATRIX);
argTypes.add(BuiltInTypes.REAL_MATRIX);
retType = BuiltInTypes.REAL_MATRIX;
// matrix plus
FunctionInterp matPlusInterp = new AbstractFunctionInterp() {
public Object getValue(List args) {
MatrixLib mat1 = (MatrixLib) args.get(0);
MatrixLib mat2 = (MatrixLib) args.get(1);
return mat1.plus(mat2);
}
};
PLUS_MAT = new FixedFunction(PLUS_NAME, argTypes, retType, matPlusInterp);
addFunction(PLUS_MAT);
// matrix minus
FunctionInterp matMinusInterp = new AbstractFunctionInterp() {
public Object getValue(List args) {
MatrixLib mat1 = (MatrixLib) args.get(0);
MatrixLib mat2 = (MatrixLib) args.get(1);
return mat1.minus(mat2);
}
};
MINUS_MAT = new FixedFunction(MINUS_NAME, argTypes, retType, matMinusInterp);
addFunction(MINUS_MAT);
// matrix multiplication
FunctionInterp matTimesInterp = new AbstractFunctionInterp() {
public Object getValue(List args) {
MatrixLib mat1 = (MatrixLib) args.get(0);
MatrixLib mat2 = (MatrixLib) args.get(1);
return mat1.timesMat(mat2);
}
};
TIMES_MAT = new FixedFunction(MULT_NAME, argTypes, retType, matTimesInterp);
addFunction(TIMES_MAT);
// Add non-random functions from (RealMatrix x Real) to RealMatrix
argTypes.clear();
argTypes.add(BuiltInTypes.REAL_MATRIX);
argTypes.add(BuiltInTypes.REAL);
retType = BuiltInTypes.REAL_MATRIX;
// matrix scalar multiplication
FunctionInterp matScalarTimesInterp = new AbstractFunctionInterp() {
public Object getValue(List args) {
double val = (Double) args.get(1);
MatrixLib mat = (MatrixLib) args.get(0);
return mat.timesScale(val);
}
};
TIMES_MAT_SCALAR = new FixedFunction(MULT_NAME, argTypes, retType,
matScalarTimesInterp);
addFunction(TIMES_MAT_SCALAR);
// Add non-random functions from (Real x RealMatrix) to RealMatrix
argTypes.clear();
argTypes.add(BuiltInTypes.REAL);
argTypes.add(BuiltInTypes.REAL_MATRIX);
retType = BuiltInTypes.REAL_MATRIX;
// scalar matrix multiplication
FunctionInterp scalarMatTimesInterp = new AbstractFunctionInterp() {
public Object getValue(List args) {
double val = (Double) args.get(0);
MatrixLib mat2 = (MatrixLib) args.get(1);
return mat2.timesScale(val);
}
};
TIMES_SCALAR_MAT = new FixedFunction(MULT_NAME, argTypes, retType,
scalarMatTimesInterp);
addFunction(TIMES_SCALAR_MAT);
// Add non-random functions from RealMatrix to RealMatrix
argTypes.clear();
argTypes.add(BuiltInTypes.REAL_MATRIX);
retType = BuiltInTypes.REAL_MATRIX;
// matrix inverse
FunctionInterp matInverseInterp = new AbstractFunctionInterp() {
public Object getValue(List args) {
MatrixLib mat1 = (MatrixLib) args.get(0);
return mat1.inverse();
}
};
INV_MAT = new FixedFunction(INV_NAME, argTypes, retType, matInverseInterp);
addFunction(INV_MAT);
// Add non-random functions from RealMatrix to Real
argTypes.clear();
argTypes.add(BuiltInTypes.REAL_MATRIX);
retType = BuiltInTypes.REAL;
// matrix determinant
FunctionInterp matDeterminantInterp = new AbstractFunctionInterp() {
public Object getValue(List args) {
MatrixLib mat1 = (MatrixLib) args.get(0);
return mat1.det();
}
};
DET_MAT = new FixedFunction(DET_NAME, argTypes, retType,
matDeterminantInterp);
addFunction(DET_MAT);
// now adding support for min of set
argTypes.clear();
argTypes.add(BuiltInTypes.SET);
retType = BuiltInTypes.INTEGER;
FunctionInterp minInterp = new AbstractFunctionInterp() {
public Object getValue(List args) {
// TODO
ObjectSet s = (ObjectSet) args.get(0);
Iterator oi = s.iterator();
if (!oi.hasNext())
return Model.NULL;
Comparable o = (Comparable) oi.next();
while (oi.hasNext()) {
Comparable no = (Comparable) oi.next();
if (no.compareTo(o) < 0)
o = no;
}
return o;
}
};
MIN = new FixedFunction(MIN_NAME, argTypes, retType, minInterp);
addFunction(MIN);
FunctionInterp maxInterp = new AbstractFunctionInterp() {
public Object getValue(List args) {
// TODO
ObjectSet s = (ObjectSet) args.get(0);
Iterator oi = s.iterator();
if (!oi.hasNext())
return Model.NULL;
Comparable o = (Comparable) oi.next();
while (oi.hasNext()) {
Comparable no = (Comparable) oi.next();
if (no.compareTo(o) > 0)
o = no;
}
return o;
}
};
MAX = new FixedFunction(MAX_NAME, argTypes, retType, maxInterp);
addFunction(MAX);
// Add non-random functions from Real to Integer
argTypes.clear();
argTypes.add(BuiltInTypes.REAL);
retType = BuiltInTypes.INTEGER;
FunctionInterp roundInterp = new AbstractFunctionInterp() {
public Object getValue(List args) {
Double num = (Double) args.get(0);
return new Integer((int) Math.round(num));
}
};
ROUND = new FixedFunction(ROUND_NAME, argTypes, retType, roundInterp);
addFunction(ROUND);
// Diag function for Real matrices
argTypes.clear();
argTypes.add(BuiltInTypes.REAL_MATRIX);
retType = BuiltInTypes.REAL_MATRIX;
FunctionInterp diagInterp = new AbstractFunctionInterp() {
public Object getValue(List args) {
MatrixLib matrix = (MatrixLib) args.get(0);
if (matrix.numCols() == 1) {
MatrixLib diagMatrix = MatrixFactory.eye(matrix.numRows());
for (int i = 0; i < matrix.numRows(); i++) {
diagMatrix.setElement(i, i, matrix.elementAt(i, 0));
}
return diagMatrix;
} else {
throw new IllegalArgumentException("diag expected " + "column vector");
}
}
};
DIAG_REAL_MAT = new FixedFunction(DIAG_NAME, argTypes, retType, diagInterp);
addFunction(DIAG_REAL_MAT);
// Repmat function for Real matrices
argTypes.clear();
argTypes.add(BuiltInTypes.REAL_MATRIX);
argTypes.add(BuiltInTypes.INTEGER);
argTypes.add(BuiltInTypes.INTEGER);
retType = BuiltInTypes.REAL_MATRIX;
FunctionInterp repMatReal = new AbstractFunctionInterp() {
public Object getValue(List args) {
MatrixLib matrix = (MatrixLib) args.get(0);
Integer rowTimes = (Integer) args.get(1);
Integer colTimes = (Integer) args.get(2);
return matrix.repmat(rowTimes, colTimes);
}
};
REPMAT_REAL = new FixedFunction(REPMAT_NAME, argTypes, retType, repMatReal);
addFunction(REPMAT_REAL);
// Transpose function for Real matrices
argTypes.clear();
argTypes.add(BuiltInTypes.REAL_MATRIX);
retType = BuiltInTypes.REAL_MATRIX;
FunctionInterp transposeInterp = new AbstractFunctionInterp() {
public Object getValue(List args) {
MatrixLib matrix = (MatrixLib) args.get(0);
return matrix.transpose();
}
};
TRANSPOSE_REAL_MAT = new FixedFunction(TRANSPOSE_NAME, argTypes, retType,
transposeInterp);
addFunction(TRANSPOSE_REAL_MAT);
// Transpose function for Integer matrices (uses the same FunctionInterp
// above)
// Does not work yet ("java.util.ArrayList cannot be cast to
// blog.common.numerical.MatrixLib")
argTypes.clear();
argTypes.add(BuiltInTypes.INTEGER_MATRIX);
retType = BuiltInTypes.INTEGER_MATRIX;
TRANSPOSE_INT_MAT = new FixedFunction(TRANSPOSE_NAME, argTypes, retType,
transposeInterp);
addFunction(TRANSPOSE_INT_MAT);
// Trigonometric functions on scalars:
argTypes.clear();
argTypes.add(BuiltInTypes.REAL);
retType = BuiltInTypes.REAL;
FunctionInterp sinInterp = new AbstractFunctionInterp() {
public Object getValue(List args) {
Double radians = (Double) args.get(0);
return Math.sin(radians);
}
};
SIN = new FixedFunction(SIN_NAME, argTypes, retType, sinInterp);
addFunction(SIN);
FunctionInterp cosInterp = new AbstractFunctionInterp() {
public Object getValue(List args) {
Double radians = (Double) args.get(0);
return Math.cos(radians);
}
};
COS = new FixedFunction(COS_NAME, argTypes, retType, cosInterp);
addFunction(COS);
FunctionInterp tanInterp = new AbstractFunctionInterp() {
public Object getValue(List args) {
Double radians = (Double) args.get(0);
return Math.tan(radians);
}
};
TAN = new FixedFunction(TAN_NAME, argTypes, retType, tanInterp);
addFunction(TAN);
FunctionInterp atan2Interp = new AbstractFunctionInterp() {
public Object getValue(List args) {
Double y = (Double) args.get(0);
Double x = (Double) args.get(1);
return Math.atan2(y, x);
}
};
argTypes.clear();
argTypes.add(BuiltInTypes.REAL);
argTypes.add(BuiltInTypes.REAL);
retType = BuiltInTypes.REAL;
ATAN2 = new FixedFunction(ATAN2_NAME, argTypes, retType, atan2Interp);
addFunction(ATAN2);
FunctionInterp colSumInterp = new AbstractFunctionInterp() {
public Object getValue(List args) {
MatrixLib matrix = (MatrixLib) args.get(0);
return matrix.columnSum();
}
};
argTypes.clear();
argTypes.add(BuiltInTypes.REAL_MATRIX);
retType = BuiltInTypes.REAL_MATRIX;
COL_SUM = new FixedFunction(SUM_NAME, argTypes, retType, colSumInterp);
addFunction(COL_SUM);
FunctionInterp setSumInterp = new AbstractFunctionInterp() {
public Object getValue(List args) {
Collection set = (Collection) args.get(0);
double sum = 0;
for (Object obj : set) {
sum += ((Number) obj).doubleValue();
}
return sum;
}
};
argTypes.clear();
argTypes.add(BuiltInTypes.SET);
retType = BuiltInTypes.REAL;
SET_SUM = new FixedFunction(SUM_NAME, argTypes, retType, setSumInterp);
addFunction(SET_SUM);
/**
* defining size(set) function
*/
FunctionInterp setSizeInterp = new AbstractFunctionInterp() {
public Object getValue(List args) {
Collection<?> set = (Collection<?>) args.get(0);
return set.size();
}
};
argTypes.clear();
argTypes.add(BuiltInTypes.SET);
retType = BuiltInTypes.INTEGER;
SET_SIZE = new FixedFunction(SIZE_NAME, argTypes, retType, setSizeInterp);
addFunction(SET_SIZE);
/**
* return the element in a singleton set
*/
FunctionInterp iotaInterp = new AbstractFunctionInterp() {
public Object getValue(List args) {
Collection<?> set = (Collection<?>) args.get(0);
if (set.size() != 1) {
throw new IllegalArgumentException("iota expects a singleton set");
}
return set.iterator().next();
}
};
argTypes.clear();
argTypes.add(BuiltInTypes.SET);
retType = BuiltInTypes.ANY;
IOTA = new FixedFunction(IOTA_NAME, argTypes, retType, iotaInterp);
addFunction(IOTA);
HSTACK_SCALAR_INTERP = new AbstractFunctionInterp() {
public Object getValue(List args) {
int m = args.size();
double[][] val = new double[1][m];
for (int i = 0; i < m; ++i)
val[0][i] = (Double) args.get(i);
return MatrixFactory.fromArray(val);
}
};
HSTACK_MATRIX_INTERP = new AbstractFunctionInterp() {
public Object getValue(List args) {
MatrixLib ret = (MatrixLib) args.get(0);
for (int i = 1; i < args.size(); ++i)
ret = MatrixFactory.hstack(ret, (MatrixLib) args.get(i));
return ret;
}
};
HSTACK = new TemplateFunction(HSTACK_NAME) {
@Override
public FixedFunction getConcreteFunction(Type[] argTypes) {
if (argTypes == null || argTypes.length < 1)
return null;
/*
* Currently only support convert elements to Real Matrix!!!
* TODO: to support other types in the future
*/
List<Type> args = new ArrayList<Type>();
boolean all_real = true, all_matrix = true;
for (Type ty : argTypes) {
if (ty.isSubtypeOf(BuiltInTypes.REAL)) {
all_matrix = false; // has a real number, so not all are matrices
args.add(BuiltInTypes.REAL);
continue;
}
if (ty.isSubtypeOf(BuiltInTypes.REAL_MATRIX)) {
all_real = false; // has a matrix, so not all are real numbers
args.add(BuiltInTypes.REAL_MATRIX);
continue;
}
return null;
}
FunctionInterp HStackInterp = null;
if (all_real) { // only scalars
HStackInterp = HSTACK_SCALAR_INTERP;
} else if (all_matrix) { // only matrices
HStackInterp = HSTACK_MATRIX_INTERP;
} else {
// Currently not support mixture of types
return null;
}
FixedFunction retFunc = new FixedFunction(HSTACK_NAME, args,
BuiltInTypes.REAL_MATRIX, HStackInterp);
return retFunc;
}
};
addTemplate(HSTACK);
VSTACK_SCALAR_INTERP = new AbstractFunctionInterp() {
public Object getValue(List args) {
int n = args.size();
double[][] val = new double[n][1];
for (int i = 0; i < n; ++i)
val[i][0] = (Double) args.get(i);
return MatrixFactory.fromArray(val);
}
};
VSTACK_MATRIX_INTERP = new AbstractFunctionInterp() {
public Object getValue(List args) {
MatrixLib ret = (MatrixLib) args.get(0);
for (int i = 1; i < args.size(); ++i)
ret = MatrixFactory.vstack(ret, (MatrixLib) args.get(i));
return ret;
}
};
VSTACK = new TemplateFunction(VSTACK_NAME) {
@Override
public FixedFunction getConcreteFunction(Type[] argTypes) {
if (argTypes == null || argTypes.length < 1)
return null;
/*
* Currently only support convert elements to Real Matrix!!!
* TODO: to support other types in the future
*/
List<Type> args = new ArrayList<Type>();
boolean all_real = true, all_matrix = true;
for (Type ty : argTypes) {
if (ty.isSubtypeOf(BuiltInTypes.REAL)) {
all_matrix = false;// has a real number, so not all are matrices
args.add(BuiltInTypes.REAL);
continue;
}
if (ty.isSubtypeOf(BuiltInTypes.REAL_MATRIX)) {
all_real = false; // has a matrix, so not all are real numbers
args.add(BuiltInTypes.REAL_MATRIX);
continue;
}
return null;
}
FunctionInterp VStackInterp = null;
if (all_real) { // only scalars
VStackInterp = VSTACK_SCALAR_INTERP;
} else if (all_matrix) { // only matrices
VStackInterp = VSTACK_MATRIX_INTERP;
} else {
// Currently we do not support mixture of types
return null;
}
FixedFunction retFunc = new FixedFunction(VSTACK_NAME, args,
BuiltInTypes.REAL_MATRIX, VStackInterp);
return retFunc;
}
};
addTemplate(VSTACK);
FunctionInterp eyeInterp = new AbstractFunctionInterp() {
public Object getValue(List args) {
Integer size = (Integer) args.get(0);
return MatrixFactory.eye(size);
}
};
argTypes.clear();
argTypes.add(BuiltInTypes.INTEGER);
retType = BuiltInTypes.REAL_MATRIX;
EYE = new FixedFunction(EYE_NAME, argTypes, retType, eyeInterp);
addFunction(EYE);
FunctionInterp zerosInterp = new AbstractFunctionInterp() {
public Object getValue(List args) {
Integer rows = (Integer) args.get(0);
Integer cols = (Integer) args.get(1);
return MatrixFactory.zeros(rows, cols);
}
};
argTypes.clear();
argTypes.add(BuiltInTypes.INTEGER);
argTypes.add(BuiltInTypes.INTEGER);
retType = BuiltInTypes.REAL_MATRIX;
ZEROS = new FixedFunction(ZEROS_NAME, argTypes, retType, zerosInterp);
addFunction(ZEROS);
FunctionInterp onesInterp = new AbstractFunctionInterp() {
public Object getValue(List args) {
Integer rows = (Integer) args.get(0);
Integer cols = (Integer) args.get(1);
return MatrixFactory.ones(rows, cols);
}
};
argTypes.clear();
argTypes.add(BuiltInTypes.INTEGER);
argTypes.add(BuiltInTypes.INTEGER);
retType = BuiltInTypes.REAL_MATRIX;
ONES = new FixedFunction(ONES_NAME, argTypes, retType, onesInterp);
addFunction(ONES);
FunctionInterp toIntInterp = new AbstractFunctionInterp() {
public Object getValue(List args) {
Object obj = args.get(0);
if (obj instanceof Number) {
return ((Number) obj).intValue();
} else if (obj instanceof Boolean) {
return ((Boolean) obj).booleanValue() ? 1 : 0;
} else if (obj instanceof MatrixLib) {
return (int) ((MatrixLib) obj).elementAt(0, 0);
} else {
System.err.println(obj.toString()
+ " cannot be converted to Integer ");
return 0;
}
}
};
argTypes.clear();
argTypes.add(BuiltInTypes.BUILT_IN);
retType = BuiltInTypes.INTEGER;
TO_INT = new FixedFunction(TOINT_NAME, argTypes, retType, toIntInterp);
addFunction(TO_INT);
FunctionInterp toRealInterp = new AbstractFunctionInterp() {
public Object getValue(List args) {
Object obj = args.get(0);
if (obj instanceof Number) {
return ((Number) obj).doubleValue();
} else if (obj instanceof Boolean) {
return ((Boolean) obj).booleanValue() ? 1 : 0;
} else if (obj instanceof MatrixLib) {
return ((MatrixLib) obj).elementAt(0, 0);
} else {
System.err.println(obj.toString() + " cannot be converted to Real");
return 0;
}
}
};
argTypes.clear();
argTypes.add(BuiltInTypes.BUILT_IN);
retType = BuiltInTypes.REAL;
TO_REAL = new FixedFunction(TOREAL_NAME, argTypes, retType, toRealInterp);
addFunction(TO_REAL);
FunctionInterp loadRealMatrixInterp = new AbstractFunctionInterp() {
public Object getValue(List args) {
String filename = (String) args.get(0);
return MatrixFactory.fromTxt(filename);
}
};
argTypes.clear();
argTypes.add(BuiltInTypes.STRING);
retType = BuiltInTypes.REAL_MATRIX;
LOAD_REAL_MATRIX = new FixedFunction(LOAD_REAL_MATRIX_NAME, argTypes,
retType, loadRealMatrixInterp);
addFunction(LOAD_REAL_MATRIX);
/**
* absolute value for Real
*/
FunctionInterp absInterp = new AbstractFunctionInterp() {
public Object getValue(List args) {
double val = ((Number) args.get(0)).doubleValue();
return Math.abs(val);
}
};
argTypes.clear();
argTypes.add(BuiltInTypes.REAL);
retType = BuiltInTypes.REAL;
ABS = new FixedFunction(ABS_NAME, argTypes, retType, absInterp);
addFunction(ABS);
/**
* absolute value for Integer
*/
argTypes.clear();
argTypes.add(BuiltInTypes.INTEGER);
retType = BuiltInTypes.INTEGER;
ABS_INT = new FixedFunction(ABS_NAME, argTypes, retType, absInterp);
addFunction(ABS_INT);
/**
* absolute value for Real matrix
*/
FunctionInterp absMatInterp = new AbstractFunctionInterp() {
public Object getValue(List args) {
return ((MatrixLib) args.get(0)).abs();
}
};
argTypes.clear();
argTypes.add(BuiltInTypes.REAL_MATRIX);
retType = BuiltInTypes.REAL_MATRIX;
ABS_MAT = new FixedFunction(ABS_NAME, argTypes, retType, absMatInterp);
addFunction(ABS_MAT);
/**
* exponential function for real argument
*/
FunctionInterp expInterp = new AbstractFunctionInterp() {
public Object getValue(List args) {
double val = ((Number) args.get(0)).doubleValue();
return Math.exp(val);
}
};
argTypes.clear();
argTypes.add(BuiltInTypes.REAL);
retType = BuiltInTypes.REAL;
EXP = new FixedFunction(EXP_NAME, argTypes, retType, expInterp);
addFunction(EXP);
/**
* exponential function for integer argument
*/
argTypes.clear();
argTypes.add(BuiltInTypes.INTEGER);
retType = BuiltInTypes.REAL;
EXP_INT = new FixedFunction(EXP_NAME, argTypes, retType, expInterp);
addFunction(EXP_INT);
/**
* exponential function for real matrix argument
*/
FunctionInterp expMatInterp = new AbstractFunctionInterp() {
public Object getValue(List args) {
return ((MatrixLib) args.get(0)).exp();
}
};
argTypes.clear();
argTypes.add(BuiltInTypes.REAL_MATRIX);
retType = BuiltInTypes.REAL_MATRIX;
EXP_MAT = new FixedFunction(EXP_NAME, argTypes, retType, expMatInterp);
addFunction(EXP_MAT);
/*
* Case expression in fixed function body
*/
CASE_IN_FIXED_FUNC = new TemplateFunction(CASE_EXPR_NAME) {
@Override
public FixedFunction getConcreteFunction(Type[] argTypes) {
if (argTypes == null || argTypes.length < 3
|| (argTypes.length % 2 != 1))
return null;
/*
* type checking
*/
List<Type> args = new ArrayList<Type>();
Type test = argTypes[0];
Type fromTy = argTypes[1];
Type toTy = argTypes[2];
if (test != fromTy)
return null;
args.add(test);
for (int i = 1; i < argTypes.length; i += 2) {
if (argTypes[i] != fromTy)
return null;
if (argTypes[i + 1] != toTy)
return null;
args.add(argTypes[i]);
args.add(argTypes[i + 1]);
}
// interpreter
FunctionInterp CaseInterp = new AbstractFunctionInterp() {
public Object getValue(List args) {
Object test = args.get(0);
for (int i = 1; i < args.size(); i += 2)
if (test.equals(args.get(i)))
return args.get(i + 1);
return Model.NULL;
}
};
FixedFunction retFunc = new FixedFunction(CASE_EXPR_NAME, args, toTy,
CaseInterp);
return retFunc;
}
};
addTemplate(CASE_IN_FIXED_FUNC);
};
}
abstract class TemplateFunction {
private String name;
public TemplateFunction(String _name) {
name = _name;
}
public String getName() {
return name;
}
public abstract FixedFunction getConcreteFunction(Type[] argTypes);
}
|
package edu.teco.dnd.eclipse;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.*;
import org.eclipse.ui.IMemento;
import org.eclipse.ui.IViewSite;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.part.ViewPart;
import edu.teco.dnd.module.Module;
/**
* ModuleView: Shows available modules, Start / Stop Server.
*
* @author jung
*
*/
public class ViewModule extends ViewPart implements ModuleManagerListener {
/**
* The logger for this class.
*/
private static final Logger LOGGER = LogManager.getLogger(ViewModule.class);
private Composite parent;
private Button button;
private Label serverStatus;
private Table moduleTable;
private Activator activator;
private ModuleManager manager;
private Map<UUID, TableItem> map = new HashMap<UUID, TableItem>();
private Display display;
public ViewModule() {
super();
}
@Override
public void setFocus() {
}
@Override
public void init(IViewSite site, IMemento memento) throws PartInitException {
LOGGER.entry(site, memento);
super.init(site, memento);
activator = Activator.getDefault();
display = Display.getCurrent();
manager = activator.getModuleManager();
if (display == null) {
display = Display.getDefault();
LOGGER.trace(
"Display.getCurrent() returned null, using Display.getDefault(): {}",
display);
}
manager.addModuleManagerListener(this);
LOGGER.exit();
}
@Override
public void dispose() {
manager.removeModuleManagerListener(this);
}
@Override
public void createPartControl(Composite parent) {
this.parent = parent;
GridLayout layout = new GridLayout();
layout.numColumns = 2;
this.parent.setLayout(layout);
createStartButton();
createServerInfo();
createModuleTable();
}
/**
* Creates a Button that starts the Server when pressed
*
* @param parent
* Composite containing the button
*/
private void createStartButton() {
button = new Button(parent, SWT.NONE);
if (activator.isRunning()) {
button.setText("Stop Server");
} else {
button.setText("Start Server");
}
button.setToolTipText("Start / Stop the server. duh.");
button.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
new Thread() {
@Override
public void run() {
if (ViewModule.this.activator.isRunning()) {
ViewModule.this.serverStatus
.setText("Stopping server…");
ViewModule.this.activator.shutdownServer();
} else {
ViewModule.this.serverStatus
.setText("Starting server…");
ViewModule.this.activator.startServer();
}
}
}.run();
}
});
}
private void createServerInfo() {
GridData gridData = new GridData();
gridData.verticalAlignment = GridData.BEGINNING;
gridData.horizontalAlignment = GridData.FILL;
serverStatus = new Label(parent, 0);
if (activator.isRunning()) {
serverStatus.setText("Server running");
} else {
serverStatus.setText("Server down");
}
serverStatus.setLayoutData(gridData);
}
/**
* Creates a Table containing currently available modules.
*
* @param parent
* Composite containing the table
*/
private void createModuleTable() {
GridData grid = new GridData();
grid.horizontalSpan = 2;
grid.verticalAlignment = GridData.FILL;
grid.horizontalAlignment = GridData.FILL;
grid.grabExcessHorizontalSpace = true;
grid.grabExcessVerticalSpace = true;
moduleTable = new Table(parent, 0);
moduleTable.setLinesVisible(true);
moduleTable.setHeaderVisible(true);
moduleTable.setLayoutData(grid);
TableColumn column1 = new TableColumn(moduleTable, SWT.None);
column1.setText("Module ID");
TableColumn column2 = new TableColumn(moduleTable, SWT.None);
column2.setText("Name");
TableColumn column3 = new TableColumn(moduleTable, SWT.None);
column3.setText("Location");
moduleTable.setToolTipText("Currently available modules");
/**
* Collection<UUID> modules = getModules();
*
* for (UUID moduleID : modules) { addID(moduleID); }
**/
moduleTable.getColumn(0).pack();
moduleTable.getColumn(1).pack();
moduleTable.getColumn(2).pack();
}
/**
* Adds a Module ID to the table.
*
* @param id
* the ID to add
*/
private synchronized void addID(final UUID id) {
LOGGER.entry(id);
if (!map.containsKey(id)) {
LOGGER.trace("id {} is new, adding", id);
TableItem item = new TableItem(moduleTable, SWT.NONE);
item.setText(0, id.toString());
map.put(id, item);
} else {
LOGGER.debug("trying to add existing id {}", id);
}
LOGGER.exit();
}
/**
* Removes a Module ID from the table.
*
* @param id
* the ID to remove
*/
private synchronized void removeID(final UUID id) {
LOGGER.entry(id);
TableItem item = map.get(id);
if (item != null) {
LOGGER.trace("found item {} for id {}", item, id);
moduleTable.remove(moduleTable.indexOf(item));
map.remove(id);
} else {
LOGGER.debug("trying to remove nonexistant id {}", id);
}
LOGGER.exit();
}
@Override
public void moduleOnline(final UUID id) {
LOGGER.entry(id);
display.asyncExec(new Runnable() {
@Override
public void run() {
addID(id);
}
});
LOGGER.exit();
}
@Override
public void moduleOffline(final UUID id) {
LOGGER.entry(id);
display.asyncExec(new Runnable() {
@Override
public void run() {
removeID(id);
}
});
LOGGER.exit();
}
@Override
public void moduleResolved(final UUID id, final Module module) {
display.asyncExec(new Runnable() {
@Override
public void run() {
if (!map.containsKey(id)){
addID(id);
}
TableItem item = map.get(id);
if (module.getName() != null){
item.setText(1, module.getName());
}
if (module.getLocation() != null){
item.setText(2, module.getLocation());
}
}
});
}
@Override
public void serverOnline(final Map<UUID, Module> modules) {
display.asyncExec(new Runnable() {
@Override
public void run() {
serverStatus.setText("Server running");
button.setText("Stop Server");
synchronized (ViewModule.this) {
for (UUID id : new ArrayList<UUID>(map.keySet())) {
removeID(id);
}
for (UUID moduleID : modules.keySet()) {
addID(moduleID);
}
}
}
});
}
@Override
public void serverOffline() {
display.asyncExec(new Runnable() {
@Override
public void run() {
synchronized (ViewModule.this) {
for (UUID id : new ArrayList<UUID>(map.keySet())) {
removeID(id);
}
}
if (serverStatus != null && button != null) {
serverStatus.setText("Server down");
button.setText("Start Server");
}
}
});
}
}
|
package cc.mrlda.util;
public class Approximation {
/**
* Approximate digamma of x.
*
* @param x
* @return
*/
public static double digamma(double x) {
double r = 0.0;
while (x <= 5) {
r -= 1 / x;
x += 1;
}
double f = 1.0 / (x * x);
double t = f
* (-1.0 / 12.0 + f
* (1.0 / 120.0 + f
* (-1.0 / 252.0 + f
* (1.0 / 240.0 + f
* (-1.0 / 132.0 + f
* (691.0 / 32760.0 + f * (-1.0 / 12.0 + f * 3617.0 / 8160.0)))))));
return r + Math.log(x) - 0.5 / x + t;
}
/**
* Approximate the trigamma of x.
*
* @param x
* @return
*/
public static double trigamma(double x) {
double p;
int i;
x = x + 6;
p = 1 / (x * x);
p = (((((0.075757575757576 * p - 0.033333333333333) * p + 0.0238095238095238) * p - 0.033333333333333)
* p + 0.166666666666667)
* p + 1)
/ x + 0.5 * p;
for (i = 0; i < 6; i++) {
x = x - 1;
p = 1 / (x * x) + p;
}
if (Double.isNaN(p)) {
throw new ArithmeticException("invalid input at trigamma function: " + x);
}
return p;
}
/**
* Approximate the lngamma of x.
*
* @param x
* @return
*/
public static double lnGamma(double x) {
double z = 1 / (x * x);
x = x + 6;
z = (((-0.000595238095238 * z + 0.000793650793651) * z - 0.002777777777778) * z + 0.083333333333333)
/ x;
z = (x - 0.5) * Math.log(x) - x + 0.918938533204673 + z - Math.log(x - 1) - Math.log(x - 2)
- Math.log(x - 3) - Math.log(x - 4) - Math.log(x - 5) - Math.log(x - 6);
if (Double.isNaN(z)) {
throw new ArithmeticException("invalid input at lnGamma function: " + x);
}
return z;
}
}
|
package com.conveyal.geom2gtfs;
import com.vividsolutions.jts.geom.Geometry;
import org.geotools.data.DataStore;
import org.geotools.data.DataStoreFinder;
import org.geotools.data.simple.SimpleFeatureCollection;
import org.geotools.data.simple.SimpleFeatureIterator;
import org.geotools.data.simple.SimpleFeatureSource;
import org.geotools.geometry.jts.JTS;
import org.geotools.referencing.CRS;
import org.geotools.referencing.crs.DefaultGeographicCRS;
import org.onebusaway.gtfs.model.*;
import org.onebusaway.gtfs.model.calendar.ServiceDate;
import org.onebusaway.gtfs.serialization.GtfsWriter;
import org.opengis.feature.Feature;
import org.opengis.feature.simple.SimpleFeature;
import org.opengis.feature.simple.SimpleFeatureType;
import org.opengis.referencing.crs.CoordinateReferenceSystem;
import org.opengis.referencing.operation.MathTransform;
import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.*;
import java.util.Map.Entry;
public class Main {
static final String DEFAULT_AGENCY_ID = "0";
private static final String DEFAULT_CAL_ID = "0";
static Config config;
// used to generate ids and names for routes that do not have them
private static int nextId = 0;
static GtfsQueue queue = null;
public static void main(String[] args) throws Exception {
if (args.length < 3) {
System.out.println("usage: cmd shapefile_fn config_fn output_fn");
return;
}
String fn = args[0];
String config_fn = args[1];
String output_fn = args[2];
config = new Config(config_fn);
// check if config specifies a csv join
CsvJoinTable csvJoin = config.getCsvJoin();
queue = new GtfsQueue();
ServiceCalendar cal = new ServiceCalendar();
cal.setMonday(1);
cal.setTuesday(1);
cal.setWednesday(1);
cal.setThursday(1);
cal.setFriday(1);
cal.setSaturday(1);
cal.setSunday(1);
cal.setStartDate(new ServiceDate(config.getStartDate()));
cal.setEndDate(new ServiceDate(config.getEndDate()));
cal.setServiceId(new AgencyAndId(DEFAULT_AGENCY_ID, DEFAULT_CAL_ID));
queue.calendars.add(cal);
Agency agency = new Agency();
agency.setId(DEFAULT_AGENCY_ID);
agency.setName(config.getAgencyName());
agency.setUrl(config.getAgencyUrl());
agency.setTimezone(config.getAgencyTimezone());
queue.agencies.add(agency);
List<Feature> features = getFeatures(fn);
List<ExtendedFeature> extFeatures = joinFeatures( features, csvJoin );
extFeatures = filterFeatures( extFeatures );
Map<String, List<ExtendedFeature>> featureGroups = groupFeatures( extFeatures );
StopGenerator stopGenerator = config.getStopGenerator();
for( Entry<String, List<ExtendedFeature>> group : featureGroups.entrySet() ){
featToGtfs(group.getValue(), agency, stopGenerator, group.getKey());
}
System.out.println( "writing to "+output_fn );
GtfsWriter gtfsWriter = new GtfsWriter();
gtfsWriter.setOutputLocation(new File(output_fn));
queue.dumpToWriter(gtfsWriter);
gtfsWriter.close();
System.out.println( "done" );
}
private static Map<String, List<ExtendedFeature>> groupFeatures(List<ExtendedFeature> extFeatures) {
Map<String, List<ExtendedFeature>> ret = new HashMap<String, List<ExtendedFeature>>();
// gather by route id
for( ExtendedFeature exft : extFeatures ){
String id = exft.getProperty( config.getRouteIdPropName() );
if (id == null) {
id = "generated_" + nextId++;
}
List<ExtendedFeature> group = ret.get(id);
if(group==null){
group = new ArrayList<ExtendedFeature>();
ret.put(id, group);
}
group.add(exft);
}
// order each group by segment
for( List<ExtendedFeature> group : ret.values() ){
Collections.sort(group, new Comparator<ExtendedFeature>(){
@Override
public int compare(ExtendedFeature o1, ExtendedFeature o2) {
String segStr1 = o1.getProperty("segment");
Integer seg1;
try{
seg1 = Integer.parseInt(segStr1);
} catch (NumberFormatException ex){
seg1 = 0;
}
String segStr2 = o2.getProperty("segment");
Integer seg2;
try{
seg2 = Integer.parseInt(segStr2);
} catch (NumberFormatException ex){
seg2 = 0;
}
return seg1-seg2;
}
});
}
return ret;
}
private static List<ExtendedFeature> filterFeatures(List<ExtendedFeature> extFeatures) {
List<ExtendedFeature> ret = new ArrayList<ExtendedFeature>();
for( ExtendedFeature exft : extFeatures ){
if (config.passesFilter(exft)) {
ret.add(exft);
}
}
return ret;
}
private static List<ExtendedFeature> joinFeatures(List<Feature> features, CsvJoinTable csvJoin) {
List<ExtendedFeature> ret = new ArrayList<ExtendedFeature>();
for (Feature feat : features) {
ExtendedFeature exft = new ExtendedFeature(feat, csvJoin);
ret.add( exft );
}
return ret;
}
private static void featToGtfs(List<ExtendedFeature> group, Agency agency,
StopGenerator stopGenerator, String routeId) throws Exception {
ExtendedFeature exemplar = group.get(0);
// get route type
Integer mode = config.getMode(exemplar);
// generate route
String routeName = exemplar.getProperty(config.getRouteNamePropName());
if (routeName == null)
routeName = routeId;
System.out.println("generating elements for \"" + routeName + "\"");
Route route = new Route();
route.setId(new AgencyAndId(DEFAULT_AGENCY_ID, routeId));
route.setShortName(routeName);
route.setAgency(agency);
route.setType(mode);
queue.routes.add(route);
List<ProtoRoute> protoRoutes = new ArrayList<ProtoRoute>();
for(ExtendedFeature exft : group){
// figure out spacing and speed for mode
Double speed = config.getSpeed(exft);
ProtoRoute protoroute = stopGenerator.makeProtoRoute(exft, speed);
protoRoutes.add( protoroute );
}
Map<ProtoRouteStop, Stop> prsStops = new HashMap<ProtoRouteStop, Stop>();
for(ProtoRoute protoroute : protoRoutes ){
for (ProtoRouteStop prs : protoroute.ret) {
// generate stops
Stop stop = prs.stop;
if (!queue.stops.contains(stop))
queue.stops.add(stop);
prsStops.put(prs, stop);
}
}
if( !config.isExact() ){
makeFrequencyTrip(exemplar, protoRoutes, route, prsStops, false, config.usePeriods());
if (config.isBidirectional()) {
makeFrequencyTrip(exemplar, protoRoutes, route, prsStops, true, config.usePeriods());
}
} else {
makeTimetableTrips(exemplar, protoRoutes, route, prsStops, false, config.usePeriods());
if (config.isBidirectional()) {
makeTimetableTrips(exemplar, protoRoutes, route, prsStops, true, config.usePeriods());
}
}
}
private static void makeTimetableTrips(ExtendedFeature exft, List<ProtoRoute> protoRoutes, Route route,
Map<ProtoRouteStop, Stop> prsStops, boolean reverse, boolean usePeriods) throws FeatureDoesntDefineTimeWindowException {
// for each window
for (ServiceWindow window : config.getServiceWindows()) {
Double headway;
try{
headway = getHeadway(exft, window.propName, usePeriods);
} catch (FeatureDoesntDefineTimeWindowException ex){
System.out.println( "route id:"+route.getId().getId()+" has no value for time window "+window.propName );
if( config.tolerant() ){
continue;
} else {
throw ex;
}
}
if(headway==null){
continue;
}
// generate a series of trips
for(int t=window.startSecs(); t<window.endSecs(); t+=headway){
Trip trip = makeNewTrip(route, reverse);
queue.trips.add(trip);
int segStart = t;
int firstStopTimeSeq=0;
List<StopTime> stopTimes = new ArrayList<StopTime>();
for(int i=0; i<protoRoutes.size(); i++){
int index=i;
if(reverse)
index = protoRoutes.size()-1-i;
ProtoRoute protoRoute = protoRoutes.get(index);
List<StopTime> segStopTimes = createStopTimes(protoRoute.ret, prsStops, reverse, protoRoute.speed, trip, segStart, firstStopTimeSeq, protoRoute.length);
stopTimes.addAll(segStopTimes);
segStart += protoRoute.getDuration();
firstStopTimeSeq += segStopTimes.size();
}
queue.stoptimes.addAll(stopTimes);
}
}
}
private static void makeFrequencyTrip(ExtendedFeature exft, List<ProtoRoute> protoRoutes, Route route,
Map<ProtoRouteStop, Stop> prsStops, boolean reverse, boolean usePeriods) throws FeatureDoesntDefineTimeWindowException {
// generate a trip
Trip trip = makeNewTrip(route, reverse);
queue.trips.add(trip);
// generate a frequency
for (ServiceWindow window : config.getServiceWindows()) {
Double headway;
try{
headway = getHeadway(exft, window.propName, usePeriods);
} catch (FeatureDoesntDefineTimeWindowException ex){
System.out.println( "feature for route id:"+route.getId().getId()+" does not define time window '"+window.propName+"'" );
if( config.tolerant() ){
continue;
} else {
throw ex;
}
}
if (headway == null)
continue; // no service in this time window
headway /= config.waitFactor();
Frequency freq = makeFreq(headway, window.startSecs(), window.endSecs(), trip);
queue.frequencies.add(freq);
}
int segStart = 0;
int firstStopTimeSeq=0;
List<StopTime> newStopTimes = new ArrayList<StopTime>();
for( ProtoRoute protoRoute : protoRoutes ){
List<StopTime> segStopTimes = createStopTimes(protoRoute.ret, prsStops, reverse, protoRoute.speed, trip, segStart, firstStopTimeSeq, protoRoute.length);
newStopTimes.addAll(segStopTimes);
segStart += protoRoute.getDuration();
firstStopTimeSeq += segStopTimes.size();
}
queue.stoptimes.addAll(newStopTimes);
}
private static Trip makeNewTrip(Route route, boolean reverse) {
Trip trip = new Trip();
trip.setRoute(route);
trip.setId(new AgencyAndId(DEFAULT_AGENCY_ID, String.valueOf(queue.trips.size())));
trip.setServiceId(new AgencyAndId(DEFAULT_AGENCY_ID, DEFAULT_CAL_ID));
if(reverse){
trip.setDirectionId("1");
} else {
trip.setDirectionId("0");
}
return trip;
}
private static List<StopTime> createStopTimes(List<ProtoRouteStop> prss, Map<ProtoRouteStop, Stop> prsStops,
boolean reverse, double speed, Trip trip, int tripStart, int firstStopTimeSequence, double segLen) {
List<StopTime> newStopTimes = new ArrayList<StopTime>();
for (int i = 0; i < prss.size(); i++) {
int ix = i;
if (reverse) {
ix = prss.size() - 1 - i;
}
ProtoRouteStop prs = prss.get(ix);
Stop stop = prsStops.get(prs);
// generate stoptime
StopTime stoptime = new StopTime();
stoptime.setStop(stop);
stoptime.setTrip(trip);
stoptime.setStopSequence(i+firstStopTimeSequence);
double dist;
if(reverse){
dist = segLen-prs.dist;
} else {
dist = prs.dist;
}
int time = (int) (dist / speed) + tripStart;
stoptime.setArrivalTime(time);
stoptime.setDepartureTime(time);
newStopTimes.add(stoptime);
}
return newStopTimes;
}
private static Frequency makeFreq(double headway, int beginSecs, int endSecs, Trip trip) {
Frequency freq;
freq = new Frequency();
freq.setStartTime(beginSecs);
freq.setEndTime(endSecs);
freq.setHeadwaySecs((int) (headway));
freq.setTrip(trip);
return freq;
}
private static Double getHeadway(ExtendedFeature exft, String propName, boolean usePeriods) throws FeatureDoesntDefineTimeWindowException {
double headway;
String freqStr = exft.getProperty(propName);
Double freqDbl;
if (freqStr == null || freqStr.equals("None")) {
freqDbl = config.getDefaultServiceLevel();
System.err.println("warning: using default frequency for feature " + exft.toString());
} else {
freqDbl = Double.parseDouble(freqStr);
}
if (freqDbl == 0.0 || freqDbl == null) {
throw new FeatureDoesntDefineTimeWindowException(propName);
}
if (usePeriods) {
headway = freqDbl * 60; // minutes to seconds
} else {
headway = 3600 / freqDbl;
}
return headway;
}
static List<Feature> getFeatures(String shp_filename) throws MalformedURLException, IOException {
// construct shapefile factory
File file = new File(shp_filename);
Map<String, URL> map = new HashMap<String, URL>();
map.put("url", file.toURI().toURL());
DataStore dataStore = DataStoreFinder.getDataStore(map);
// get shapefile as generic 'feature source'
String typeName = dataStore.getTypeNames()[0];
SimpleFeatureSource featureSource = dataStore.getFeatureSource(dataStore.getTypeNames()[0]);
SimpleFeatureType schema = featureSource.getSchema();
CoordinateReferenceSystem shpCRS = schema.getCoordinateReferenceSystem();
SimpleFeatureCollection collection = featureSource.getFeatures();
SimpleFeatureIterator iterator = collection.features();
List<Feature> ret = new ArrayList<Feature>(collection.size());
if (shpCRS != null && !shpCRS.equals(DefaultGeographicCRS.WGS84)) {
try {
MathTransform transform = CRS.findMathTransform(shpCRS, DefaultGeographicCRS.WGS84, true);
while (iterator.hasNext()) {
SimpleFeature next = iterator.next();
Geometry geom = (Geometry) next.getDefaultGeometry();
next.setDefaultGeometry(JTS.transform(geom, transform));
ret.add(next);
}
} catch (Exception e) {
throw new RuntimeException(e);
}
}
else {
while (iterator.hasNext()) {
ret.add(iterator.next());
}
}
return ret;
}
}
|
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import spark.Request;
import spark.Response;
import spark.servlet.SparkApplication;
import spark.utils.IOUtils;
import javax.mail.Authenticator;
import javax.mail.PasswordAuthentication;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.math.BigInteger;
import java.nio.charset.Charset;
import java.util.Base64;
import java.util.Date;
import java.util.Iterator;
import java.util.Set;
import java.util.logging.FileHandler;
import java.util.logging.Logger;
import java.util.logging.SimpleFormatter;
import static spark.Spark.*;
public class SparkServer implements SparkApplication {
private static final Logger logger = Logger.getLogger(SparkServer.class.getName());
static PrintClass print = new PrintClass();
static private JsonPersistency jsonPersistency;
static Bank bank;
static FileHandler fh;
//Change to true when using authentication
boolean authentication = false;
private class SMTPAuth extends Authenticator {
public PasswordAuthentication authenticateSender() {
return new PasswordAuthentication("username@gmail.com", "password");
}
}
static public void main(String args[]) {
SparkApplication sparkApplication = new SparkServer();
sparkApplication.init();
}
public void init() {
Runtime.getRuntime().addShutdownHook(new ShutdownThread());
apiLogSetup();
loadBank();
createAccounts();
|
package com.MainActivities;
import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.view.MenuItem;
import com.Adapters.MainAdapters.PicturesAdapter;
import com.MainActivities.BaseClasses.MainActivity;
import com.rtomyj.Diary.R;
import java.util.ArrayList;
public class PicEntries extends MainActivity<PicturesAdapter, GridLayoutManager> {
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putStringArrayList("PIC_ARR_LIST", activityAdapter.getPicturesArrList());
int size = activityAdapter.getItemCount(), index = 0;
long[] lastModifiedArr = new long[size];
for (Long lastModified : activityAdapter.getLastModifiedArrList()){
lastModifiedArr[index] = lastModified;
index++;
}
outState.putLongArray("MODIFIED_LONG_FOR_PICS", lastModifiedArr);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
currentActivityIdentifier = PIC_ENTRIES;
super.onCreate(savedInstanceState);
if (savedInstanceState != null){
ArrayList<String> picArrList = savedInstanceState.getStringArrayList("PIC_ARR_LIST");
assert picArrList != null;
int size = picArrList.size();
ArrayList<Long> lastModifiedArrList = new ArrayList<>(size);
long[] lastModifiedArr = savedInstanceState.getLongArray("MODIFIED_LONG_FOR_PICS");
assert lastModifiedArr != null;
for (long lastModified: lastModifiedArr){
lastModifiedArrList.add(lastModified);
}
activityAdapter = new PicturesAdapter(this, picArrList, lastModifiedArrList, userUIPreferences);
}
if (activityAdapter == null) {
activityAdapter = new PicturesAdapter(this, userUIPreferences);
}
setupViews();
}
@Override
public boolean onNavigationItemSelected(final MenuItem item) {
switch (item.getItemId()){
case R.id.pictures:
closeNavDrawer();
break;
default:
super.onNavigationItemSelected(item);
}
return true;
}
}
|
package com.elibom.jogger.http;
/**
* Defines HTTP related constants.
*
* @author German Escobar
*/
public class Http {
public static class Headers {
public static final String ACCEPT = "Accept";
public static final String ACCEPT_CHARSET = "Accept-Charset";
public static final String ACCEPT_ENCODING = "Accept-Encoding";
public static final String ACCEPT_LANGUAGE = "Accept-Language";
public static final String ACCEPT_DATETIME = "Accept-Datetime";
public static final String AUTHORIZATION = "Authorization";
public static final String CACHE_CONTROL = "Cache-Control";
public static final String CONNECTION = "Connection";
public static final String CONTENT_TYPE = "Content-Type";
public static final String CONTENT_LENGTH = "Content-Length";
public static final String CONTENT_MD5 = "Content-MD5";
public static final String DATE = "Date";
public static final String IF_MATCH = "If-Match";
public static final String IF_MODIFIED_SINCE = "If-Modified-Since";
public static final String IF_NONE_MATCH = "If-None-Match";
public static final String USER_AGENT = "User-Agent";
}
public static class ContentType {
public static final String APPLICATION_FORM_URLENCODED = "application/x-www-form-urlencoded";
public static final String APPLICATION_JSON = "application/json";
public static final String APPLICATION_XML = "application/xml";
public static final String TEXT_HTML = "text/xml";
public static final String MULTIPART_FORM_DATA = "multipart/form-data";
}
}
|
package com.google.sps.data;
/** Listing object with the specified attributes returned from the places API **/
public class Listing {
private String name;
private MapLocation mapLocation;
private double rating;
private String image;
private String url;
private String businessType;
/**
* Creates a new Listing
* @param name Name of business
* @param mapLocation Location of business (lat/long coordinate)
* @param rating Numerical rating of business (1-5)
* @param image Image
* @param url Url to business' site
* @param businessType specifies business type from Places API (establishment, food, etc.)
* @return Listing object
**/
public Listing(String name, MapLocation mapLocation, double rating, String image, String url) {
this.name = name;
this.mapLocation = mapLocation;
this.rating = rating;
this.image = image;
this.url = url;
this.businessType = businessType;
}
public String getName() {
return name;
}
public MapLocation getMapLocation() {
return mapLocation;
}
public double getRating() {
return rating;
}
public String getImage() {
return image;
}
public String getUrl() {
return url;
}
public String getBusinessType() {
return businessType;
}
}
|
package org.xwiki.flamingo.sking.test.po;
import java.util.List;
import java.util.stream.Collectors;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.xwiki.test.ui.po.BaseElement;
import org.xwiki.tree.test.po.TreeElement;
/**
* Represents the opened panel "Other Formats" in the modal export.
*
* @version $Id$
* @since 10.9
*/
public class OtherFormatPane extends BaseElement
{
private static final String CONTAINER_TREE_CLASS = "exportModalTreeContainer";
private static final String FORM_ID = "export-form";
private static final String TREE_CLASS = "xtree";
private static final String XAR_EXPORT_LINK_TEXT = "Export as XAR";
private static final String VALUE_ATTR = "value";
/**
* @return true if the tree is displayed.
*/
public boolean isTreeAvailable()
{
return getDriver().hasElement(By.className(CONTAINER_TREE_CLASS));
}
/**
* @return the tree element to manipulate its nodes.
*/
public TreeElement getTreeElement()
{
getDriver().waitUntilElementIsVisible(By.className(TREE_CLASS));
WebElement element = getDriver()
.findElement(By.className(CONTAINER_TREE_CLASS))
.findElement(By.className(TREE_CLASS));
return new TreeElement(element);
}
/**
* @return true if the export XAR button exists.
*/
public boolean isExportAsXARButtonAvailable()
{
return isExportButtonAvailable(XAR_EXPORT_LINK_TEXT);
}
/**
* @param buttonText the text of the button to assert
* @return true if the export button exists.
* @since 11.2RC1
*/
public boolean isExportButtonAvailable(String buttonText)
{
return getDriver().findElementByLinkText(buttonText) != null;
}
/**
* Click on an export button.
*
* @param buttonText the text of the button to click
* @since 11.2RC1
*/
public void clickExportButton(String buttonText)
{
getDriver().findElementByLinkText(buttonText).click();
}
/**
* Click on the export XAR button.
*/
public void clickExportAsXARButton()
{
clickExportButton(XAR_EXPORT_LINK_TEXT);
}
/**
* @return the main form of the export other format pane.
*/
public WebElement getForm()
{
return getDriver().findElement(By.id(FORM_ID));
}
/**
* @return all the values of the "pages" hidden input fields aggregated in a list.
*/
public List<String> getPagesValues() {
return getForm().findElements(By.cssSelector("input[type=hidden][name=pages]")).stream()
.map(webElement -> webElement.getAttribute(VALUE_ATTR)).collect(Collectors.toList());
}
/**
* @return all the values of the "excludes" hidden input fields aggregated in a list.
*/
public List<String> getExcludesValues() {
return getForm()
.findElements(By.cssSelector("input[type=hidden][name=excludes]")).stream()
.map(webElement -> webElement.getAttribute(VALUE_ATTR)).collect(Collectors.toList());
}
}
|
package org.xwiki.notifications.notifiers.internal.email;
import java.util.ArrayDeque;
import java.util.Arrays;
import java.util.Iterator;
import java.util.Queue;
import javax.inject.Inject;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.xwiki.bridge.DocumentAccessBridge;
import org.xwiki.component.annotation.Component;
import org.xwiki.component.annotation.InstantiationStrategy;
import org.xwiki.component.descriptor.ComponentInstantiationStrategy;
import org.xwiki.model.reference.DocumentReference;
import org.xwiki.model.reference.DocumentReferenceResolver;
import org.xwiki.model.reference.WikiReference;
import org.xwiki.notifications.notifiers.email.NotificationEmailInterval;
import org.xwiki.query.Query;
import org.xwiki.query.QueryException;
import org.xwiki.query.QueryManager;
import org.xwiki.wiki.descriptor.WikiDescriptorManager;
/**
* Iterator that retrieve all users of the current wiki interested in the notifications emails at the specified
* interval.
*
* @version $Id$
* @since 9.5RC1
*/
@Component(roles = NotificationUserIterator.class)
@InstantiationStrategy(ComponentInstantiationStrategy.PER_LOOKUP)
public class NotificationUserIterator implements Iterator<DocumentReference>
{
private static final int BATCH_SIZE = 50;
/**
* The query to perform to get all users having a not-empty email address.
*
* Here, we re using <code>length(objUser.email) > 0</code> instead of <code>objUser.email <> ''</code> because
* ORACLE stores NULL instead of empty strings.
*
* But if we do
* <code>objUser.email <> NULL AND objUser.email <> ''</code>, then we have wrong results with MySQL.
*
* This <code>length()</code> trick allows us to use the same query on every database we support, but a better
* solution would be to write a different query for ORACLE than for the others, because this length() may be bad for
* performances.
*/
private static final String XWQL_QUERY = "select distinct doc.fullName from Document doc, "
+ "doc.object(XWiki.XWikiUsers) objUser where length(objUser.email) > 0 order by doc.fullName";
@Inject
private QueryManager queryManager;
@Inject
private DocumentReferenceResolver<String> resolver;
@Inject
private WikiDescriptorManager wikiDescriptorManager;
@Inject
private DocumentAccessBridge documentAccessBridge;
@Inject
private Logger logger;
private Queue<String> users = new ArrayDeque<>();
private NotificationEmailInterval interval;
private int offset;
private DocumentReference nextUser;
/**
* Initialize the user iterator.
* @param interval the interval that users must have configured
*/
public void initialize(NotificationEmailInterval interval)
{
this.interval = interval;
getNext();
}
private void getNext()
{
DocumentReference classReference = new DocumentReference(wikiDescriptorManager.getCurrentWikiId(),
Arrays.asList("XWiki", "Notifications", "Code"), "NotificationEmailPreferenceClass");
try {
nextUser = null;
while (!hasNext()) {
if (users.isEmpty()) {
doQuery();
if (users.isEmpty()) {
return;
}
}
while (!hasNext() && !users.isEmpty()) {
DocumentReference user = resolver.resolve(users.poll(),
new WikiReference(wikiDescriptorManager.getCurrentWikiId()));
Object userInterval
= documentAccessBridge.getProperty(user, classReference, "interval");
if (isDefaultInterval(userInterval) || isSameInterval(userInterval)) {
nextUser = user;
}
}
}
} catch (Exception e) {
logger.error("Fail to get next user.", e);
}
}
private void doQuery() throws QueryException
{
Query query = queryManager.createQuery(XWQL_QUERY, Query.XWQL);
query.setLimit(BATCH_SIZE);
query.setOffset(offset);
users.addAll(query.execute());
offset += BATCH_SIZE;
}
private boolean isDefaultInterval(Object interval)
{
return (interval == null || StringUtils.isBlank((String) interval))
&& this.interval == NotificationEmailInterval.DAILY;
}
private boolean isSameInterval(Object interval)
{
if (interval == null || !(interval instanceof String)) {
return false;
}
String stringInterval = (String) interval;
return StringUtils.isNotBlank(stringInterval)
&& this.interval.equals(NotificationEmailInterval.valueOf(StringUtils.upperCase(stringInterval)));
}
@Override
public boolean hasNext()
{
return nextUser != null;
}
@Override
public DocumentReference next()
{
DocumentReference userReference = this.nextUser;
getNext();
return userReference;
}
}
|
package com.litle.sdk;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.Properties;
import org.apache.http.HttpEntity;
import org.apache.http.HttpHost;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.params.ConnRoutePNames;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.CoreConnectionPNames;
import org.apache.http.util.EntityUtils;
import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;
import com.jcraft.jsch.SftpException;
import java.security.GeneralSecurityException;
import javax.net.ssl.SSLContext;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.impl.conn.BasicClientConnectionManager;
public class Communication {
private static final String[] SUPPORTED_PROTOCOLS = new String[] {"TLSv1.1", "TLSv1.2"};
private DefaultHttpClient httpclient;
private StreamData streamData;
public Communication() {
DefaultHttpClient temp = new DefaultHttpClient();
try {
if (getBestProtocol(SSLContext.getDefault().getDefaultSSLParameters().getProtocols()) == null) {
String protocol = getBestProtocol(SSLContext.getDefault().getSupportedSSLParameters().getProtocols());
if (protocol == null) {
throw new IllegalStateException("No supported TLS protocols available");
}
SchemeRegistry reg = new SchemeRegistry();
SSLContext ctx = SSLContext.getInstance(protocol);
ctx.init(null, null, null);
reg.register(new Scheme("https", 443, new SSLSocketFactory(ctx)));
ClientConnectionManager manager = new BasicClientConnectionManager(reg);
temp = new DefaultHttpClient(manager);
}
} catch (GeneralSecurityException ex) {
throw new IllegalStateException(ex);
}
httpclient = temp;
streamData = new StreamData();
}
private static String getBestProtocol(final String[] availableProtocols) {
for (int i = 0; i < availableProtocols.length; ++i) {
// Assuming best protocol is at end
for (int j = SUPPORTED_PROTOCOLS.length - 1; j >= 0; --j) {
if (SUPPORTED_PROTOCOLS[j].equals(availableProtocols[i])) {
return availableProtocols[i];
}
}
}
return null;
}
public String requestToServer(String xmlRequest, Properties configuration) {
String xmlResponse = null;
String proxyHost = configuration.getProperty("proxyHost");
String proxyPort = configuration.getProperty("proxyPort");
if (proxyHost != null && proxyHost.length() > 0 && proxyPort != null
&& proxyHost.length() > 0) {
HttpHost proxy = new HttpHost(proxyHost, Integer.valueOf(proxyPort));
httpclient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
httpclient.getParams().setParameter(CoreConnectionPNames.SO_LINGER, 0);
}
String httpTimeout = configuration.getProperty("timeout");
String httpReadTimeout = configuration.getProperty("readTimeout");
if (httpTimeout != null && httpTimeout.length() > 0) {
httpclient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT,Integer.valueOf(httpTimeout));
}
if (httpReadTimeout != null && httpReadTimeout.length() > 0) {
httpclient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT,Integer.valueOf(httpReadTimeout));
}
HttpPost post = new HttpPost(configuration.getProperty("url"));
post.setHeader("Content-Type", "text/xml");
post.setHeader("Connection","close");
HttpEntity entity = null;
try {
boolean printxml = configuration.getProperty("printxml") != null
&& configuration.getProperty("printxml").equalsIgnoreCase(
"true");
if (printxml) {
System.out.println("Request XML: " + xmlRequest);
}
post.setEntity(new StringEntity(xmlRequest));
HttpResponse response = httpclient.execute(post);
if(response.getStatusLine().getStatusCode() != 200) {
throw new LitleOnlineException(response.getStatusLine().getStatusCode() + ":" + response.getStatusLine().getReasonPhrase());
}
entity = response.getEntity();
xmlResponse = EntityUtils.toString(entity);
if (printxml) {
System.out.println("Response XML: " + xmlResponse);
}
} catch (IOException e) {
throw new LitleOnlineException("Exception connection to Litle", e);
} finally {
if(entity != null) {
EntityUtils.consumeQuietly(entity);
}
post.abort();
}
return xmlResponse;
}
/**
* This method is exclusively used for sending batch file to the communicator.
* @param requestFile
* @param responseFile
* @param configuration
* @throws IOException
*/
public void sendLitleBatchFileToIBC(File requestFile, File responseFile, Properties configuration) throws IOException {
String hostName = configuration.getProperty("batchHost");
String hostPort = configuration.getProperty("batchPort");
int tcpTimeout = Integer.parseInt(configuration.getProperty("batchTcpTimeout"));
boolean useSSL = configuration.getProperty("batchUseSSL") != null
&& configuration.getProperty("batchUseSSL").equalsIgnoreCase("true");
streamData.init(hostName, hostPort, tcpTimeout, useSSL);
streamData.dataOut(requestFile);
streamData.dataIn(responseFile);
streamData.closeSocket();
}
/**
* This method sends the request file to Litle's server sFTP
* @param requestFile
* @param configuration
* @throws IOException
*/
public void sendLitleRequestFileToSFTP(File requestFile, Properties configuration) throws IOException{
String username = configuration.getProperty("sftpUsername");
String password = configuration.getProperty("sftpPassword");
String hostname = configuration.getProperty("batchHost");
java.util.Properties config = new java.util.Properties();
config.put("StrictHostKeyChecking", "no");
JSch jsch = null;
Session session = null;
try{
jsch = new JSch();
session = jsch.getSession(username, hostname);
session.setConfig(config);
session.setPassword(password);
session.connect();
}
catch(JSchException e){
throw new LitleBatchException("Exception connection to Litle", e);
}
Channel channel = null;
try{
channel = session.openChannel("sftp");
channel.connect();
}
catch(JSchException e){
throw new LitleBatchException("Exception connection to Litle", e);
}
ChannelSftp sftp = (ChannelSftp) channel;
boolean printxml = configuration.getProperty("printxml") != null
&& configuration.getProperty("printxml").equalsIgnoreCase(
"true");
if(printxml){
BufferedReader reader = new BufferedReader(new FileReader(requestFile));
String line = "";
while((line = reader.readLine()) != null){
System.out.println(line);
}
}
try {
sftp.put(requestFile.getAbsolutePath(), "inbound/" + requestFile.getName() + ".prg");
sftp.rename("inbound/" + requestFile.getName() + ".prg", "inbound/" + requestFile.getName() + ".asc");
}
catch (SftpException e) {
throw new LitleBatchException("Exception SFTP operation", e);
}
channel.disconnect();
session.disconnect();
}
/**
* Grabs the response file from Litle's sFTP server. This method is blocking! It will continue to poll until the timeout has elapsed
* or the file has been retrieved!
* @param requestFile
* @param responseFile
* @param configuration
* @throws IOException
*/
public void receiveLitleRequestResponseFileFromSFTP(File requestFile, File responseFile, Properties configuration) throws IOException{
String username = configuration.getProperty("sftpUsername");
String password = configuration.getProperty("sftpPassword");
String hostname = configuration.getProperty("batchHost");
java.util.Properties config = new java.util.Properties();
config.put("StrictHostKeyChecking", "no");
JSch jsch = null;
Session session = null;
try{
jsch = new JSch();
session = jsch.getSession(username, hostname);
session.setConfig(config);
session.setPassword(password);
session.connect();
}
catch(JSchException e){
throw new LitleBatchException("Exception connection to Litle", e);
}
Channel channel = null;
try{
channel = session.openChannel("sftp");
channel.connect();
}
catch(JSchException e){
throw new LitleBatchException("Exception connection to Litle", e);
}
ChannelSftp sftp = (ChannelSftp) channel;
Long start = System.currentTimeMillis();
Long timeout = Long.parseLong(configuration.getProperty("sftpTimeout"));
System.out.println("Retrieving from sFTP...");
while(System.currentTimeMillis() - start < timeout){
try {
Thread.sleep(45000);
} catch (InterruptedException e) {
e.printStackTrace();
}
boolean success = true;
try{
sftp.get("outbound/" + requestFile.getName() + ".asc", responseFile.getAbsolutePath());
}
catch(SftpException e){
success = false;
}
if(success) {
try {
sftp.rm("outbound/" + requestFile.getName() + ".asc");
} catch (SftpException e) {
throw new LitleBatchException("Exception SFTP operation", e);
}
break;
}
System.out.print(".");
}
boolean printxml = configuration.getProperty("printxml") != null
&& configuration.getProperty("printxml").equalsIgnoreCase(
"true");
if(printxml){
BufferedReader reader = new BufferedReader(new FileReader(responseFile));
String line = "";
while((line = reader.readLine()) != null){
System.out.println(line);
}
}
channel.disconnect();
session.disconnect();
}
void setStreamData(StreamData streamData) {
this.streamData = streamData;
}
}
|
package com.wix.mysql;
import com.wix.mysql.config.MysqldConfig;
import com.wix.mysql.input.LogFileProcessor;
import de.flapdoodle.embed.process.collections.Collections;
import de.flapdoodle.embed.process.config.IRuntimeConfig;
import de.flapdoodle.embed.process.distribution.Distribution;
import de.flapdoodle.embed.process.extract.IExtractedFileSet;
import de.flapdoodle.embed.process.io.LogWatchStreamProcessor;
import de.flapdoodle.embed.process.io.Processors;
import de.flapdoodle.embed.process.io.StreamToLineProcessor;
import de.flapdoodle.embed.process.runtime.AbstractProcess;
import de.flapdoodle.embed.process.runtime.ProcessControl;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.lang.reflect.Field;
import java.nio.file.Files;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* @author viliusl
* @since 27/09/14
*/
public class MysqldProcess extends AbstractProcess<MysqldConfig, MysqldExecutable, MysqldProcess> {
private final static Logger log = Logger.getLogger("MysqldProcess");
private boolean stopped = false;
public MysqldProcess(
final Distribution distribution,
final MysqldConfig config,
final IRuntimeConfig runtimeConfig,
final MysqldExecutable executable) throws IOException {
super(distribution, config, runtimeConfig, executable);
}
@Override
protected List<String> getCommandLine(Distribution distribution, MysqldConfig config, IExtractedFileSet exe) throws IOException {
final String baseDir = exe.generatedBaseDir().getAbsolutePath();
return Collections.newArrayList(
exe.executable().getAbsolutePath(),
"--no-defaults",
"--log-output=NONE",
String.format("--basedir=%s", baseDir),
String.format("--datadir=%s/data", baseDir),
String.format("--plugin-dir=%s/lib/plugin", baseDir),
String.format("--pid-file=%s.pid", pidFile(exe.executable())),
String.format("--lc-messages-dir=%s/share", baseDir),
String.format("--socket=%s", sockFile(exe)),
String.format("--port=%s", config.getPort()),
String.format("--log-error=%s/data/error.log", baseDir));
//"--console");//does not properly work, dodgy between versions.
}
@Override
protected void stopInternal() {
//in cases when startup fails during ex 'onAfterProcessStart' class-scoped log is unavailabe as 'onAfterProcessStart'
//is called in base class constructor and this class is not yet instantiated.
//TODO: submit a pull request to make logger of {@AbstractProcess} protected instead of private.
Logger logger = Logger.getLogger("MysqldProcess");
synchronized (this) {
if (!stopped) {
stopped = true;
logger.info("try to stop mysqld");
if (!stopUsingMysqldadmin()) {
logger.warning("could not stop mysqld via mysqladmin, try next");
if (!sendKillToProcess()) {
logger.warning("could not stop mysqld, try next");
if (!sendTermToProcess()) {
logger.warning("could not stop mysqld, try next");
if (!tryKillToProcess()) {
logger.warning("could not stop mysqld the second time, try one last thing");
}
}
}
stopProcess();
}
}
}
}
@Override
protected void cleanupInternal() {}
@Override
public void onAfterProcessStart(final ProcessControl process, final IRuntimeConfig runtimeConfig) throws IOException {
Set<String> errors = new HashSet<String>();
errors.add("[ERROR]");
LogWatchStreamProcessor logWatch = new LogWatchStreamProcessor(
"ready for connections",
errors,
StreamToLineProcessor.wrap(runtimeConfig.getProcessOutput().getOutput()));
new LogFileProcessor(
new File(this.getExecutable().executable.generatedBaseDir() + "/data/error.log"),
logWatch);
logWatch.waitForResult(getConfig().getTimeout());
if (!logWatch.isInitWithSuccess()) {
throw new RuntimeException("mysql start failed with error: " + logWatch.getFailureFound());
}
try {
new MysqlConfigurer(getConfig()).configure();
} catch (Exception e) {
// emit IO exception for {@link AbstractProcess} would try to stop running process gracefully
throw new IOException(e);
}
}
private boolean stopUsingMysqldadmin() {
try {
Process p = Runtime.getRuntime().exec(new String[] {
"bin/mysqladmin",
"-uroot",//user, should be different if auth method is different, password is needed as well
"-hlocalhost",
"--protocol=tcp",
String.format("--port=%s", getConfig().getPort()),
"shutdown"},
null,
getExecutable().getFile().generatedBaseDir());
Processors.connect(new InputStreamReader(p.getInputStream()), Processors.logTo(log, Level.INFO));
Processors.connect(new InputStreamReader(p.getErrorStream()), Processors.logTo(log, Level.INFO));
return p.waitFor() == 0;
} catch (InterruptedException e) {
log.log(Level.WARNING, "Encountered error why shutting down process.", e);
return false;
} catch (IOException e) {
log.log(Level.WARNING, "Encountered error why shutting down process.", e);
return false;
}
}
/**
* Work-around to get Executable in hooks where it's not provided and as
* all init is done in base class constructor, local vars are still not
* initialized:/
*/
private MysqldExecutable getExecutable() {
try {
Field f = AbstractProcess.class.getDeclaredField("executable");
f.setAccessible(true);
return (MysqldExecutable)f.get(this);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
/**
* .sock file needs to be in system temp dir and not in ex. target/...
*
* This is due to possible problems with existing mysql installation and apparmor profiles
* in linuxes.
*/
private String sockFile(IExtractedFileSet exe) throws IOException {
File f = Files.createTempFile("mysql", "sock").toFile();
String path = f.getAbsolutePath();
f.delete();
return path;
}
}
|
package console;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.text.DecimalFormat;
public class GradeTrackerConsole {
public static void main(String[] args) {
String input;
int weighting;
double mark;
int total;
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println("** -- Grade Tracker Console -- **");
while (true) {
try {
System.out.println("Enter in assignment weighting (numeric): ");
input = br.readLine();
weighting = Integer.parseInt(input);
System.out.println("Enter in mark: ");
input = br.readLine();
mark = Double.parseDouble(input);
System.out.println("What was the mark out of? ");
input = br.readLine();
total = Integer.parseInt(input);
calculateValues(weighting, mark, total);
while (true) {
System.out.println("Do you want to submit another entry? Y/N: ");
input = br.readLine();
if (input.equals("Y") || input.equals("y")) {
break;
} else if (input.equals("N") || input.equals("n")) {
System.out.println("Thank you for using the Grade Tracker Console");
System.exit(0);
} else {
System.out.println("Invalid response, try again");
}
}
} catch (NumberFormatException e) {
System.out.println("Input error, use numbers only");
} catch (IOException e) {
System.out.println("I/O error, please try again");
}
}
}
private static void calculateValues(int weight, double mark, int total) {
DecimalFormat df = new DecimalFormat(".
System.out.println("Total percentage of assignment: " + df.format((mark/total * 100)) + "/100");
System.out.println("Total percentage in unit (weighted): " + df.format((mark/total * weight)) + "/100");
}
}
|
package coyote.loader;
import coyote.loader.log.Log;
import coyote.loader.log.LogMsg;
public class DefaultLoader extends AbstractLoader implements Loader {
/** Tag used in various class identifying locations. */
public static final String CLASS = "DefaultLoader";
public DefaultLoader() {
}
/**
* Start the components running.
*/
public void start() {
// only start once, this is not foolproof as the active flag is set only when
// the watchdog loop is entered
if ( isActive() ) {
return;
}
// Save the name of the thread that is running this class
final String oldName = Thread.currentThread().getName();
// Rename this thread to the name of this class
Thread.currentThread().setName( CLASS );
// very important to get park(millis) to operate
current_thread = Thread.currentThread();
// Parse through the configuration and initialize all the components
initComponents();
Log.info( LogMsg.createMsg( "Loader.components_initialized" ) );
// By this time all loggers (including the catch-all logger) should be open
final StringBuffer b = new StringBuffer( CLASS );
b.append( " initialized - Runtime: " );
b.append( System.getProperty( "java.version" ) );
b.append( " (" );
b.append( System.getProperty( "java.vendor" ) );
b.append( ")" );
b.append( " - Platform: " );
b.append( System.getProperty( "os.arch" ) );
b.append( " OS: " );
b.append( System.getProperty( "os.name" ) );
b.append( " (" );
b.append( System.getProperty( "os.version" ) );
b.append( ")" );
Log.info( b );
// enter a loop performing watchdog and maintenance functions
watchdog();
// The watchdog loop has exited, so we are done processing
terminateComponents();
Log.info( LogMsg.createMsg( "Loader.terminated" ) );
// Rename the thread back to what it was called before we were being run
Thread.currentThread().setName( oldName );
}
}
|
package cz.minecart.updater;
import java.awt.BorderLayout;
import java.awt.CardLayout;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashSet;
import java.util.Properties;
import java.util.ResourceBundle;
import java.util.Set;
import java.util.Timer;
import java.util.TimerTask;
import java.util.logging.Level;
import java.util.logging.LogRecord;
import java.util.logging.Logger;
import java.util.logging.StreamHandler;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.event.HyperlinkEvent;
import javax.swing.event.HyperlinkListener;
import javax.swing.filechooser.FileFilter;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
/**
* Minecart server updater.
*
* @author Minecart team
*/
public class Updater extends javax.swing.JFrame implements HyperlinkListener {
private static final String GAME_PATH_PROPERTY = "gamePath";
private static final String GAME_PATH_AUTO_PROPERTY = "gamePathAuto";
private static final String PROFILE_PATH_PROPERTY = "profilePath";
private static final String PROFILE_PATH_AUTO_PROPERTY = "profilePathAuto";
private static final String RUN_COMMAND_PROPERTY = "runCommand";
private static final String RUN_COMMAND_AUTO_PROPERTY = "runCommandAuto";
private static final String MOD_RECORD_PREFIX = "mod_";
private final ResourceBundle resourceBundle = ResourceBundle.getBundle("cz/minecart/updater/resources/Updater");
private final Properties config = new Properties();
private File configFile;
private OsType osType = OsType.LINUX;
private URL newsUrl;
private URL checkUpdateUrl;
private URL appDownloadUrl;
private URL websiteUrl;
private URL filesUpdateUrl;
private URL forgeUpdateUrl;
private URL updateDownloadUrl;
private String profileName;
private VersionNumbers updateVersion;
private Set<String> currentFiles = null;
private final Set<String> modsFiles = new HashSet<>();
private AnimatedBanner banner;
public Updater() {
initComponents();
init();
}
private void init() {
registerLogger();
newsTextPane.addHyperlinkListener(this);
configFile = new File("./minecart-updater.cfg");
if (configFile.exists()) {
try {
try (FileInputStream configInput = new FileInputStream(configFile)) {
config.load(configInput);
}
Logger.getLogger(Updater.class.getName()).log(Level.INFO, "Načten konfigurační soubor: " + configFile.getName());
} catch (FileNotFoundException ex) {
Logger.getLogger(Updater.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(Updater.class.getName()).log(Level.SEVERE, null, ex);
}
}
// Detect operating system type
String osName = System.getProperty("os.name").toLowerCase();
if (osName.contains("win")) {
osType = OsType.WINDOWS;
} else if (osName.contains("mac")) {
osType = OsType.MAC;
}
Logger.getLogger(Updater.class.getName()).log(Level.INFO, "Detekován operační systém: " + osType.name());
String gamePath = config.getProperty(GAME_PATH_PROPERTY, "");
boolean gamePathAuto = Boolean.valueOf(config.getProperty(GAME_PATH_AUTO_PROPERTY, Boolean.TRUE.toString()));
gamePathCheckBox.setSelected(gamePathAuto);
updateGamePathVisibility();
gamePathTextField.setText(gamePath);
String profilePath = config.getProperty(PROFILE_PATH_PROPERTY, "");
profilePathTextField.setText(profilePath);
boolean profilePathAuto = Boolean.valueOf(config.getProperty(PROFILE_PATH_AUTO_PROPERTY, Boolean.TRUE.toString()));
profilePathCheckBox.setSelected(profilePathAuto);
updateProfilePathVisibility();
String runCommand = config.getProperty(RUN_COMMAND_PROPERTY, "");
runCommandTextField.setText(runCommand);
boolean runCommandAuto = Boolean.valueOf(config.getProperty(RUN_COMMAND_AUTO_PROPERTY, Boolean.TRUE.toString()));
addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
super.windowClosing(e);
dispose();
System.exit(0);
}
});
banner = new AnimatedBanner();
headerPanel.add(banner, BorderLayout.CENTER);
Timer timer = new Timer();
timer.schedule(new TimerTask() {
@Override
public void run() {
if (isVisible()) {
banner.animate();
}
}
}, 0, 70);
setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
runCommandCheckBox = new javax.swing.JCheckBox();
headerPanel = new javax.swing.JPanel();
tabbedPane = new javax.swing.JTabbedPane();
newsScrollPane = new javax.swing.JScrollPane();
newsTextPane = new javax.swing.JTextPane();
optionsPanel = new javax.swing.JPanel();
optionsScrollPane = new javax.swing.JScrollPane();
optionsInnerPanel = new javax.swing.JPanel();
gamePathLabel = new javax.swing.JLabel();
gamePathCheckBox = new javax.swing.JCheckBox();
gamePathTextField = new javax.swing.JTextField();
gamePathButton = new javax.swing.JButton();
profilePathLabel = new javax.swing.JLabel();
profilePathCheckBox = new javax.swing.JCheckBox();
profilePathTextField = new javax.swing.JTextField();
profilePathButton = new javax.swing.JButton();
runCommandLabel = new javax.swing.JLabel();
runCommandTextField = new javax.swing.JTextField();
runCommandButton = new javax.swing.JButton();
checkUpdateButton = new javax.swing.JButton();
logPanel = new javax.swing.JPanel();
logScrollPane = new javax.swing.JScrollPane();
logTextArea = new javax.swing.JTextArea();
controlPanel = new javax.swing.JPanel();
checkingPanel = new javax.swing.JPanel();
checkingIconLabel = new javax.swing.JLabel();
errorPanel = new javax.swing.JPanel();
errorIconLabel = new javax.swing.JLabel();
warningPanel = new javax.swing.JPanel();
warningPlayButton = new javax.swing.JButton();
warningPlayIconLabel = new javax.swing.JLabel();
playPanel = new javax.swing.JPanel();
playButton = new javax.swing.JButton();
playIconLabel = new javax.swing.JLabel();
updatePanel = new javax.swing.JPanel();
updateIconLabel = new javax.swing.JLabel();
updateProgressBar = new javax.swing.JProgressBar();
newAppPanel = new javax.swing.JPanel();
newAppDownloadButton = new javax.swing.JButton();
newAppIconLabel = new javax.swing.JLabel();
forgePanel = new javax.swing.JPanel();
forgeIconLabel = new javax.swing.JLabel();
runCommandCheckBox.setText("Detekovat příkaz automaticky");
runCommandCheckBox.setEnabled(false);
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setTitle("Minecart Reloaded Updater");
setIconImage(new javax.swing.ImageIcon(getClass().getResource("/cz/minecart/updater/resources/images/icon.png")).getImage());
setSize(new java.awt.Dimension(781, 384));
headerPanel.setBackground(new java.awt.Color(0, 0, 0));
headerPanel.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR));
headerPanel.setMinimumSize(new java.awt.Dimension(0, 170));
headerPanel.setPreferredSize(new java.awt.Dimension(0, 170));
headerPanel.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
headerPanelMouseClicked(evt);
}
});
headerPanel.setLayout(new java.awt.BorderLayout());
getContentPane().add(headerPanel, java.awt.BorderLayout.NORTH);
newsTextPane.setEditable(false);
newsTextPane.setContentType("text/html"); // NOI18N
newsTextPane.setText("<html>\n <head>\n\n </head>\n <body>\n<p>Novinky se načítají...</p>\n </body>\n</html>\n");
newsScrollPane.setViewportView(newsTextPane);
tabbedPane.addTab("Novinky", newsScrollPane);
optionsPanel.setLayout(new javax.swing.BoxLayout(optionsPanel, javax.swing.BoxLayout.LINE_AXIS));
gamePathLabel.setText("Cesta k Minecraftu");
gamePathCheckBox.setSelected(true);
gamePathCheckBox.setText("Výchozí cesta");
gamePathCheckBox.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
gamePathCheckBoxActionPerformed(evt);
}
});
gamePathTextField.setEnabled(false);
gamePathButton.setText("Vybrat...");
gamePathButton.setEnabled(false);
gamePathButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
gamePathButtonActionPerformed(evt);
}
});
profilePathLabel.setText("Cesta k Minecraft profilu");
profilePathCheckBox.setSelected(true);
profilePathCheckBox.setText("Detekovat cestu automaticky");
profilePathCheckBox.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
profilePathCheckBoxActionPerformed(evt);
}
});
profilePathTextField.setEnabled(false);
profilePathButton.setText("Vybrat...");
profilePathButton.setEnabled(false);
profilePathButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
profilePathButtonActionPerformed(evt);
}
});
runCommandLabel.setText("Příkaz pro spuštění Minecraftu");
runCommandTextField.setText("java -jar Minecart.jar");
runCommandButton.setText("Vybrat...");
runCommandButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
runCommandButtonActionPerformed(evt);
}
});
checkUpdateButton.setText("Vyhledat aktualizace");
checkUpdateButton.setEnabled(false);
checkUpdateButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
checkUpdateButtonActionPerformed(evt);
}
});
javax.swing.GroupLayout optionsInnerPanelLayout = new javax.swing.GroupLayout(optionsInnerPanel);
optionsInnerPanel.setLayout(optionsInnerPanelLayout);
optionsInnerPanelLayout.setHorizontalGroup(
optionsInnerPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(optionsInnerPanelLayout.createSequentialGroup()
.addContainerGap()
.addGroup(optionsInnerPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(optionsInnerPanelLayout.createSequentialGroup()
.addComponent(runCommandLabel)
.addGap(214, 554, Short.MAX_VALUE))
.addGroup(optionsInnerPanelLayout.createSequentialGroup()
.addGroup(optionsInnerPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(optionsInnerPanelLayout.createSequentialGroup()
.addComponent(profilePathTextField)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(profilePathButton))
.addGroup(optionsInnerPanelLayout.createSequentialGroup()
.addComponent(gamePathTextField)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(gamePathButton))
.addGroup(optionsInnerPanelLayout.createSequentialGroup()
.addComponent(runCommandTextField)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(runCommandButton))
.addGroup(optionsInnerPanelLayout.createSequentialGroup()
.addGroup(optionsInnerPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(gamePathLabel)
.addComponent(gamePathCheckBox)
.addComponent(profilePathLabel)
.addComponent(profilePathCheckBox))
.addGap(0, 0, Short.MAX_VALUE)))
.addContainerGap())
.addGroup(optionsInnerPanelLayout.createSequentialGroup()
.addComponent(checkUpdateButton)
.addGap(0, 0, Short.MAX_VALUE))))
);
optionsInnerPanelLayout.setVerticalGroup(
optionsInnerPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(optionsInnerPanelLayout.createSequentialGroup()
.addContainerGap()
.addComponent(gamePathLabel)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(gamePathCheckBox)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(optionsInnerPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(gamePathTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(gamePathButton))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(profilePathLabel)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(profilePathCheckBox)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(optionsInnerPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(profilePathTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(profilePathButton))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(runCommandLabel)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(optionsInnerPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(runCommandTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(runCommandButton))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(checkUpdateButton)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
optionsScrollPane.setViewportView(optionsInnerPanel);
optionsPanel.add(optionsScrollPane);
tabbedPane.addTab("Nastavení", optionsPanel);
logPanel.setLayout(new java.awt.BorderLayout());
logTextArea.setEditable(false);
logTextArea.setColumns(20);
logTextArea.setRows(5);
logTextArea.setText("Aplikační log:\n");
logScrollPane.setViewportView(logTextArea);
logPanel.add(logScrollPane, java.awt.BorderLayout.CENTER);
tabbedPane.addTab("Log", logPanel);
getContentPane().add(tabbedPane, java.awt.BorderLayout.CENTER);
controlPanel.setLayout(new java.awt.CardLayout());
checkingIconLabel.setFont(new java.awt.Font("Dialog", 1, 18)); // NOI18N
checkingIconLabel.setIcon(new javax.swing.ImageIcon(getClass().getResource("/cz/minecart/updater/resources/images/icons/png/48x48/apps/internet-web-browser-7.png"))); // NOI18N
checkingIconLabel.setText("Kontroluji dostupnost aktualizací...");
checkingIconLabel.setToolTipText("");
javax.swing.GroupLayout checkingPanelLayout = new javax.swing.GroupLayout(checkingPanel);
checkingPanel.setLayout(checkingPanelLayout);
checkingPanelLayout.setHorizontalGroup(
checkingPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(checkingPanelLayout.createSequentialGroup()
.addContainerGap()
.addComponent(checkingIconLabel)
.addContainerGap(380, Short.MAX_VALUE))
);
checkingPanelLayout.setVerticalGroup(
checkingPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, checkingPanelLayout.createSequentialGroup()
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(checkingIconLabel)
.addContainerGap())
);
controlPanel.add(checkingPanel, "checking");
errorIconLabel.setFont(new java.awt.Font("Dialog", 1, 18)); // NOI18N
errorIconLabel.setIcon(new javax.swing.ImageIcon(getClass().getResource("/cz/minecart/updater/resources/images/icons/png/48x48/actions/dialog-no.png"))); // NOI18N
errorIconLabel.setText("Došlo k chybě při zpracování");
errorIconLabel.setToolTipText("");
javax.swing.GroupLayout errorPanelLayout = new javax.swing.GroupLayout(errorPanel);
errorPanel.setLayout(errorPanelLayout);
errorPanelLayout.setHorizontalGroup(
errorPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(errorPanelLayout.createSequentialGroup()
.addContainerGap()
.addComponent(errorIconLabel)
.addContainerGap(447, Short.MAX_VALUE))
);
errorPanelLayout.setVerticalGroup(
errorPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, errorPanelLayout.createSequentialGroup()
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(errorIconLabel)
.addContainerGap())
);
controlPanel.add(errorPanel, "error");
warningPlayButton.setFont(new java.awt.Font("Dialog", 1, 24)); // NOI18N
warningPlayButton.setText("Zavřít");
warningPlayButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
warningPlayButtonActionPerformed(evt);
}
});
warningPlayIconLabel.setFont(new java.awt.Font("Dialog", 1, 18)); // NOI18N
warningPlayIconLabel.setIcon(new javax.swing.ImageIcon(getClass().getResource("/cz/minecart/updater/resources/images/icons/png/48x48/actions/dialog-no.png"))); // NOI18N
warningPlayIconLabel.setText("Došlo k chybě");
javax.swing.GroupLayout warningPanelLayout = new javax.swing.GroupLayout(warningPanel);
warningPanel.setLayout(warningPanelLayout);
warningPanelLayout.setHorizontalGroup(
warningPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, warningPanelLayout.createSequentialGroup()
.addContainerGap()
.addComponent(warningPlayIconLabel)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 481, Short.MAX_VALUE)
.addComponent(warningPlayButton)
.addContainerGap())
);
warningPanelLayout.setVerticalGroup(
warningPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, warningPanelLayout.createSequentialGroup()
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(warningPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(warningPlayIconLabel)
.addComponent(warningPlayButton))
.addContainerGap())
);
controlPanel.add(warningPanel, "warning");
playButton.setFont(new java.awt.Font("Dialog", 1, 24)); // NOI18N
playButton.setText("Zavřít");
playButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
playButtonActionPerformed(evt);
}
});
playIconLabel.setFont(new java.awt.Font("Dialog", 1, 18)); // NOI18N
playIconLabel.setIcon(new javax.swing.ImageIcon(getClass().getResource("/cz/minecart/updater/resources/images/icons/png/48x48/actions/dialog-ok-5.png"))); // NOI18N
playIconLabel.setText("Nastavení je aktuální");
javax.swing.GroupLayout playPanelLayout = new javax.swing.GroupLayout(playPanel);
playPanel.setLayout(playPanelLayout);
playPanelLayout.setHorizontalGroup(
playPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, playPanelLayout.createSequentialGroup()
.addContainerGap()
.addComponent(playIconLabel)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 407, Short.MAX_VALUE)
.addComponent(playButton)
.addContainerGap())
);
playPanelLayout.setVerticalGroup(
playPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, playPanelLayout.createSequentialGroup()
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(playPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(playIconLabel)
.addComponent(playButton))
.addContainerGap())
);
controlPanel.add(playPanel, "play");
updateIconLabel.setFont(new java.awt.Font("Dialog", 1, 18)); // NOI18N
updateIconLabel.setIcon(new javax.swing.ImageIcon(getClass().getResource("/cz/minecart/updater/resources/images/icons/png/48x48/actions/upgrade_misc.png"))); // NOI18N
updateIconLabel.setText("Nastavení se aktualizuje...");
updateProgressBar.setIndeterminate(true);
javax.swing.GroupLayout updatePanelLayout = new javax.swing.GroupLayout(updatePanel);
updatePanel.setLayout(updatePanelLayout);
updatePanelLayout.setHorizontalGroup(
updatePanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(updatePanelLayout.createSequentialGroup()
.addContainerGap()
.addComponent(updateIconLabel)
.addGap(18, 18, 18)
.addComponent(updateProgressBar, javax.swing.GroupLayout.DEFAULT_SIZE, 445, Short.MAX_VALUE)
.addContainerGap())
);
updatePanelLayout.setVerticalGroup(
updatePanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(updatePanelLayout.createSequentialGroup()
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(updatePanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(updateIconLabel, javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(updateProgressBar, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap())
);
controlPanel.add(updatePanel, "update");
newAppDownloadButton.setFont(new java.awt.Font("Dialog", 1, 24)); // NOI18N
newAppDownloadButton.setText("STÁHNOUT");
newAppDownloadButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
newAppDownloadButtonActionPerformed(evt);
}
});
newAppIconLabel.setFont(new java.awt.Font("Dialog", 1, 18)); // NOI18N
newAppIconLabel.setIcon(new javax.swing.ImageIcon(getClass().getResource("/cz/minecart/updater/resources/images/icons/png/48x48/actions/update-product.png"))); // NOI18N
newAppIconLabel.setText("Je k dispozici novější verze této aplikace");
javax.swing.GroupLayout newAppPanelLayout = new javax.swing.GroupLayout(newAppPanel);
newAppPanel.setLayout(newAppPanelLayout);
newAppPanelLayout.setHorizontalGroup(
newAppPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, newAppPanelLayout.createSequentialGroup()
.addContainerGap()
.addComponent(newAppIconLabel)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 147, Short.MAX_VALUE)
.addComponent(newAppDownloadButton)
.addContainerGap())
);
newAppPanelLayout.setVerticalGroup(
newAppPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, newAppPanelLayout.createSequentialGroup()
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(newAppPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(newAppIconLabel)
.addComponent(newAppDownloadButton))
.addContainerGap())
);
controlPanel.add(newAppPanel, "newApp");
forgeIconLabel.setFont(new java.awt.Font("Dialog", 1, 18)); // NOI18N
forgeIconLabel.setIcon(new javax.swing.ImageIcon(getClass().getResource("/cz/minecart/updater/resources/images/icons/png/48x48/actions/upgrade_misc.png"))); // NOI18N
forgeIconLabel.setText("Aktualizuje se forge...");
javax.swing.GroupLayout forgePanelLayout = new javax.swing.GroupLayout(forgePanel);
forgePanel.setLayout(forgePanelLayout);
forgePanelLayout.setHorizontalGroup(
forgePanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(forgePanelLayout.createSequentialGroup()
.addContainerGap()
.addComponent(forgeIconLabel)
.addContainerGap(515, Short.MAX_VALUE))
);
forgePanelLayout.setVerticalGroup(
forgePanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(forgePanelLayout.createSequentialGroup()
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(forgeIconLabel)
.addContainerGap())
);
controlPanel.add(forgePanel, "forge");
getContentPane().add(controlPanel, java.awt.BorderLayout.SOUTH);
setSize(new java.awt.Dimension(806, 548));
setLocationRelativeTo(null);
}// </editor-fold>//GEN-END:initComponents
private void playButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_playButtonActionPerformed
String runCommand = runCommandTextField.getText();
if (!runCommand.isEmpty()) {
try {
Process p = Runtime.getRuntime().exec(runCommandTextField.getText());
} catch (IOException ex) {
Logger.getLogger(Updater.class.getName()).log(Level.SEVERE, null, ex);
}
}
save();
System.exit(0);
}//GEN-LAST:event_playButtonActionPerformed
private void newAppDownloadButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_newAppDownloadButtonActionPerformed
BareBonesBrowserLaunch.openDesktopURL(appDownloadUrl);
}//GEN-LAST:event_newAppDownloadButtonActionPerformed
private void gamePathButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_gamePathButtonActionPerformed
String gamePath = gamePathTextField.getText();
File gamePathFile = new File(gamePath);
if (!gamePathFile.exists() || gamePath == null || gamePath.isEmpty()) {
gamePathFile = new java.io.File(".");
}
JFileChooser chooser = new JFileChooser();
chooser.setCurrentDirectory(gamePathFile);
chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
chooser.setAcceptAllFileFilterUsed(false);
if (chooser.showOpenDialog(this) == JFileChooser.APPROVE_OPTION) {
gamePathTextField.setText(chooser.getSelectedFile().getAbsolutePath());
}
}//GEN-LAST:event_gamePathButtonActionPerformed
private void gamePathCheckBoxActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_gamePathCheckBoxActionPerformed
updateGamePathVisibility();
}//GEN-LAST:event_gamePathCheckBoxActionPerformed
private void profilePathButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_profilePathButtonActionPerformed
String profilePath = profilePathTextField.getText();
File profilePathFile = new File(profilePath);
if (!profilePathFile.exists() || profilePath == null || profilePath.isEmpty()) {
profilePathFile = new java.io.File(".");
}
JFileChooser chooser = new JFileChooser();
chooser.setCurrentDirectory(profilePathFile);
chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
chooser.setAcceptAllFileFilterUsed(false);
if (chooser.showOpenDialog(this) == JFileChooser.APPROVE_OPTION) {
profilePathTextField.setText(chooser.getSelectedFile().getAbsolutePath());
}
}//GEN-LAST:event_profilePathButtonActionPerformed
private void profilePathCheckBoxActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_profilePathCheckBoxActionPerformed
updateProfilePathVisibility();
}//GEN-LAST:event_profilePathCheckBoxActionPerformed
private void runCommandButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_runCommandButtonActionPerformed
String gamePath = gamePathTextField.getText();
File gamePathFile = new File(gamePath);
if (!gamePathFile.exists() || gamePath == null || gamePath.isEmpty()) {
gamePathFile = new java.io.File(".");
}
JFileChooser chooser = new JFileChooser();
chooser.setCurrentDirectory(gamePathFile);
chooser.addChoosableFileFilter(new FileFilter() {
@Override
public boolean accept(File file) {
String fileName = file.getName().toLowerCase();
return fileName.endsWith(".exe") || fileName.endsWith(".jar");
}
@Override
public String getDescription() {
return "Spustitelné soubory (*.exe, *.jar)";
}
});
chooser.setAcceptAllFileFilterUsed(true);
if (chooser.showOpenDialog(this) == JFileChooser.APPROVE_OPTION) {
runCommandTextField.setText(chooser.getSelectedFile().getAbsolutePath());
}
}//GEN-LAST:event_runCommandButtonActionPerformed
private void headerPanelMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_headerPanelMouseClicked
BareBonesBrowserLaunch.openDesktopURL(websiteUrl);
}//GEN-LAST:event_headerPanelMouseClicked
private void checkUpdateButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_checkUpdateButtonActionPerformed
checkUpdateButton.setEnabled(false);
((CardLayout) controlPanel.getLayout()).show(controlPanel, "checking");
Logger.getLogger(Updater.class.getName()).log(Level.INFO, "\nNové hledání aktualizací...");
performUpdate();
}//GEN-LAST:event_checkUpdateButtonActionPerformed
private void warningPlayButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_warningPlayButtonActionPerformed
playButtonActionPerformed(evt);
}//GEN-LAST:event_warningPlayButtonActionPerformed
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(Updater.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
//</editor-fold>
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
Updater app = new Updater();
app.setVisible(true);
app.performUpdate();
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton checkUpdateButton;
private javax.swing.JLabel checkingIconLabel;
private javax.swing.JPanel checkingPanel;
private javax.swing.JPanel controlPanel;
private javax.swing.JLabel errorIconLabel;
private javax.swing.JPanel errorPanel;
private javax.swing.JLabel forgeIconLabel;
private javax.swing.JPanel forgePanel;
private javax.swing.JButton gamePathButton;
private javax.swing.JCheckBox gamePathCheckBox;
private javax.swing.JLabel gamePathLabel;
private javax.swing.JTextField gamePathTextField;
private javax.swing.JPanel headerPanel;
private javax.swing.JPanel logPanel;
private javax.swing.JScrollPane logScrollPane;
private javax.swing.JTextArea logTextArea;
private javax.swing.JButton newAppDownloadButton;
private javax.swing.JLabel newAppIconLabel;
private javax.swing.JPanel newAppPanel;
private javax.swing.JScrollPane newsScrollPane;
private javax.swing.JTextPane newsTextPane;
private javax.swing.JPanel optionsInnerPanel;
private javax.swing.JPanel optionsPanel;
private javax.swing.JScrollPane optionsScrollPane;
private javax.swing.JButton playButton;
private javax.swing.JLabel playIconLabel;
private javax.swing.JPanel playPanel;
private javax.swing.JButton profilePathButton;
private javax.swing.JCheckBox profilePathCheckBox;
private javax.swing.JLabel profilePathLabel;
private javax.swing.JTextField profilePathTextField;
private javax.swing.JButton runCommandButton;
private javax.swing.JCheckBox runCommandCheckBox;
private javax.swing.JLabel runCommandLabel;
private javax.swing.JTextField runCommandTextField;
private javax.swing.JTabbedPane tabbedPane;
private javax.swing.JLabel updateIconLabel;
private javax.swing.JPanel updatePanel;
private javax.swing.JProgressBar updateProgressBar;
private javax.swing.JPanel warningPanel;
private javax.swing.JButton warningPlayButton;
private javax.swing.JLabel warningPlayIconLabel;
// End of variables declaration//GEN-END:variables
private void performUpdate() {
// Perform checking for updates
Thread updateThread = new Thread(new Runnable() {
@Override
public void run() {
try {
newsUrl = new URI(resourceBundle.getString("news_url")).toURL();
checkUpdateUrl = new URI(resourceBundle.getString("update_url")).toURL();
filesUpdateUrl = new URI(resourceBundle.getString("update_files_url")).toURL();
forgeUpdateUrl = new URI(resourceBundle.getString("update_forge_url")).toURL();
appDownloadUrl = new URI(resourceBundle.getString("download_laucher_url")).toURL();
websiteUrl = new URI(resourceBundle.getString("website_url")).toURL();
Logger.getLogger(Updater.class.getName()).log(Level.INFO, "Používá se web: " + websiteUrl);
updateDownloadUrl = new URI(resourceBundle.getString("update_download_url")).toURL();
profileName = resourceBundle.getString("profileName");
profilePathLabel.setText("Cesta k minecraft profilu (" + profileName + ")");
banner.setVersion("Verze aktualizátoru: " + resourceBundle.getString("Application.version"));
} catch (URISyntaxException | MalformedURLException ex) {
Logger.getLogger(Updater.class.getName()).log(Level.SEVERE, null, ex);
}
// Load news content
loadNewsContent();
// Check for application update
CheckAppUpdateResult appUpdate = checkForAppUpdate();
switch (appUpdate) {
case UPDATE_FOUND: {
((CardLayout) controlPanel.getLayout()).show(controlPanel, "newApp");
break;
}
case NOT_FOUND:
case CONNECTION_ISSUE: {
connectionIssues();
break;
}
case NO_UPDATE_AVAILABLE: {
UpdatePlan updatePlan = checkForModsUpdate();
switch (updatePlan.resultType) {
case UPDATE_FOUND: {
((CardLayout) controlPanel.getLayout()).show(controlPanel, "update");
ModsUpdateResult modsUpdateResult = performModsUpdate(updatePlan);
switch (modsUpdateResult) {
case DOWNLOAD_ERROR: {
connectionIssues();
break;
}
case UPDATE_OK: {
actionSucessful("Nastavení bylo aktualizováno.");
break;
}
}
break;
}
case NOT_FOUND:
case NO_CONNECTION:
case CONNECTION_ISSUE: {
connectionIssues();
break;
}
case NO_UPDATE_AVAILABLE: {
actionSucessful("Nastavení je aktuální");
break;
}
case NO_TARGET_DIRECTORY: {
actionFailed(updatePlan.errorMessage == null ? "Složka minecraft profilu je neplatná. Nastavte ji ručně." : updatePlan.errorMessage);
break;
}
case NO_TARGET_MOD_DIRECTORY: {
actionFailed("Nepodařilo se najít složku Minecraft profilu");
break;
}
default: {
actionFailed("Nepodařilo se zkontrolovat aktualizaci");
break;
}
}
break;
}
default: {
errorIconLabel.setText("Došlo k neznámé chybě");
((CardLayout) controlPanel.getLayout()).show(controlPanel, "error");
break;
}
}
checkUpdateButton.setEnabled(true);
}
});
updateThread.start();
}
private void actionSucessful(String okMessage) {
if (!runCommandTextField.getText().isEmpty()) {
playButton.setText("Hrát >>");
}
playIconLabel.setText(okMessage);
((CardLayout) controlPanel.getLayout()).show(controlPanel, "play");
}
private void actionFailed(String errorMessage) {
if (!runCommandTextField.getText().isEmpty()) {
warningPlayButton.setText("Hrát >>");
}
warningPlayIconLabel.setText(errorMessage);
((CardLayout) controlPanel.getLayout()).show(controlPanel, "warning");
}
/**
* Opens hyperlink in external browser.
*
* @param event hyperlink event
*/
@Override
public void hyperlinkUpdate(HyperlinkEvent event) {
if (event.getEventType() == HyperlinkEvent.EventType.ACTIVATED) {
BareBonesBrowserLaunch.openURL(event.getURL().toExternalForm());
}
}
private void loadNewsContent() {
try (InputStream newsStream = newsUrl.openStream()) {
ByteArrayOutputStream result = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int length;
do {
length = newsStream.read(buffer);
if (length >= 0) {
result.write(buffer, 0, length);
}
} while (length >= 0);
String news = result.toString("UTF-8");
newsTextPane.setText(news);
Logger.getLogger(Updater.class.getName()).log(Level.INFO, "Novinky načteny");
} catch (UnsupportedEncodingException ex) {
Logger.getLogger(Updater.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(Updater.class.getName()).log(Level.SEVERE, null, ex);
}
}
private CheckAppUpdateResult checkForAppUpdate() {
if (checkUpdateUrl == null) {
return CheckAppUpdateResult.UPDATE_URL_NOT_SET;
}
try {
try (InputStream checkUpdateStream = checkUpdateUrl.openStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(checkUpdateStream))) {
String line = reader.readLine();
if (line == null) {
return CheckAppUpdateResult.NOT_FOUND;
}
updateVersion = new VersionNumbers();
Logger.getLogger(Updater.class.getName()).log(Level.INFO, "Dostupná verze aktualizátoru z internetu: " + line);
updateVersion.versionFromString(line);
}
// Compare versions
if (updateVersion.isGreaterThan(getVersionNumbers())) {
return CheckAppUpdateResult.UPDATE_FOUND;
}
return CheckAppUpdateResult.NO_UPDATE_AVAILABLE;
} catch (FileNotFoundException ex) {
Logger.getLogger(Updater.class.getName()).log(Level.SEVERE, null, ex);
return CheckAppUpdateResult.NOT_FOUND;
} catch (IOException ex) {
Logger.getLogger(Updater.class.getName()).log(Level.SEVERE, null, ex);
return CheckAppUpdateResult.CONNECTION_ISSUE;
} catch (Exception ex) {
Logger.getLogger(Updater.class.getName()).log(Level.SEVERE, null, ex);
return CheckAppUpdateResult.CONNECTION_ISSUE;
}
}
private UpdatePlan checkForModsUpdate() {
if (filesUpdateUrl == null) {
return new UpdatePlan(CheckModsUpdateResult.UPDATE_URL_NOT_SET, null);
}
modsFiles.clear();
try {
try (InputStream checkUpdateStream = filesUpdateUrl.openStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(checkUpdateStream))) {
String line = reader.readLine();
while (line != null && !line.isEmpty()) {
modsFiles.add(line);
line = reader.readLine();
}
if (modsFiles.isEmpty()) {
Logger.getLogger(Updater.class.getName()).log(Level.WARNING, "Seznam modů na webu je prázdný");
return new UpdatePlan(CheckModsUpdateResult.NOT_FOUND, null);
}
}
// Compare list of mods
Set<String> installedMods = new HashSet<>();
Set<String> downloadMods = new HashSet<>();
Set<String> deleteMods = new HashSet<>();
Set<String> remoteMods = new HashSet<>();
currentFiles = getModRecords();
ProfilePathResult profilePathResult = getProfilePath();
String profilePath = profilePathResult.profilePath;
if (profilePath == null) {
return new UpdatePlan(CheckModsUpdateResult.NO_TARGET_DIRECTORY, profilePathResult.errorMessage);
}
String profileModsDir = profilePath + File.separator + "mods";
if (!new File(profileModsDir).exists()) {
return new UpdatePlan(CheckModsUpdateResult.NO_TARGET_MOD_DIRECTORY, null);
}
// List installed mods
File modsDirectory = new File(profileModsDir);
for (File modFile : modsDirectory.listFiles()) {
installedMods.add(modFile.getName().toLowerCase());
}
// Add missing mods to download list
for (String mod : modsFiles) {
remoteMods.add(mod.toLowerCase());
if (!installedMods.contains(mod.toLowerCase())) {
downloadMods.add(mod);
}
}
// Add mods which are no longer needed to delete list
for (String mod : currentFiles) {
File targetFile = new File(profileModsDir + File.separator + mod);
if (targetFile.exists() && !remoteMods.contains(mod.toLowerCase())) {
deleteMods.add(mod);
}
}
if (!downloadMods.isEmpty() || !deleteMods.isEmpty()) {
Logger.getLogger(Updater.class.getName()).log(Level.WARNING, "Modů ke stažení: " + downloadMods.size());
Logger.getLogger(Updater.class.getName()).log(Level.WARNING, "Modů ke smazání: " + deleteMods.size());
return new UpdatePlan(CheckModsUpdateResult.UPDATE_FOUND, profilePath, downloadMods, deleteMods);
}
return new UpdatePlan(CheckModsUpdateResult.NO_UPDATE_AVAILABLE, null);
} catch (FileNotFoundException ex) {
Logger.getLogger(Updater.class.getName()).log(Level.SEVERE, null, ex);
return new UpdatePlan(CheckModsUpdateResult.NOT_FOUND, null);
} catch (IOException ex) {
Logger.getLogger(Updater.class.getName()).log(Level.SEVERE, null, ex);
return new UpdatePlan(CheckModsUpdateResult.CONNECTION_ISSUE, null);
}
}
private ModsUpdateResult performModsUpdate(UpdatePlan updatePlan) {
String profilePath = updatePlan.profilePath;
String profileModsDir = profilePath + File.separator + "mods";
int downloadModsSize = updatePlan.downloadMods.size();
if (downloadModsSize > 0) {
updateProgressBar.setIndeterminate(false);
updateProgressBar.setValue(0);
updateProgressBar.setMaximum(100);
}
// Add new files not present in previous set
int index = 0;
for (String mod : updatePlan.downloadMods) {
String modsUrlPath;
try {
modsUrlPath = updateDownloadUrl.toURI().toString() + "/mods";
} catch (URISyntaxException ex) {
Logger.getLogger(Updater.class.getName()).log(Level.SEVERE, null, ex);
return ModsUpdateResult.DOWNLOAD_ERROR;
}
File targetFile = new File(profileModsDir + File.separator + mod);
try {
URL modFileUrl = new URI(modsUrlPath + "/" + URLEncoder.encode(mod, "UTF-8").replaceAll("\\+", "%20")).toURL();
try (InputStream modFileStream = modFileUrl.openStream()) {
targetFile.createNewFile();
try (OutputStream targetFileStream = new FileOutputStream(targetFile)) {
byte[] buffer = new byte[1024];
int length;
do {
length = modFileStream.read(buffer);
if (length >= 0) {
targetFileStream.write(buffer, 0, length);
}
} while (length >= 0);
}
}
} catch (URISyntaxException | IOException ex) {
Logger.getLogger(Updater.class.getName()).log(Level.SEVERE, null, ex);
return ModsUpdateResult.DOWNLOAD_ERROR;
}
index++;
updateProgressBar.setValue((index * 100) / downloadModsSize);
updateProgressBar.repaint();
currentFiles.add(mod);
}
// Delete all files not present in new mods list
updateProgressBar.setIndeterminate(true);
for (String mod : updatePlan.deleteMods) {
File targetFile = new File(profileModsDir + File.separator + mod);
if (targetFile.exists()) {
if (targetFile.delete()) {
currentFiles.remove(mod);
}
}
}
Logger.getLogger(Updater.class.getName()).log(Level.INFO, "Aktualizace byla provedena");
return ModsUpdateResult.UPDATE_OK;
}
private void connectionIssues() {
actionFailed("Došlo k problému s připojením");
}
public VersionNumbers getVersionNumbers() {
String releaseString = resourceBundle.getString("Application.version");
VersionNumbers versionNumbers = new VersionNumbers();
versionNumbers.versionFromString(releaseString);
return versionNumbers;
}
public Set<String> getModRecords() {
Set<String> files = new HashSet<>();
int index = 0;
String mod;
do {
mod = config.getProperty(MOD_RECORD_PREFIX + index, null);
if (mod != null && !mod.isEmpty()) {
files.add(mod);
}
index++;
} while (mod != null);
return files;
}
@Override
public void dispose() {
save();
super.dispose();
}
private void save() {
config.setProperty(GAME_PATH_PROPERTY, gamePathTextField.getText());
config.setProperty(GAME_PATH_AUTO_PROPERTY, Boolean.toString(gamePathCheckBox.isSelected()));
config.setProperty(PROFILE_PATH_PROPERTY, profilePathTextField.getText());
config.setProperty(PROFILE_PATH_AUTO_PROPERTY, Boolean.toString(profilePathCheckBox.isSelected()));
config.setProperty(RUN_COMMAND_PROPERTY, runCommandTextField.getText());
config.setProperty(RUN_COMMAND_AUTO_PROPERTY, Boolean.toString(runCommandCheckBox.isSelected()));
int index = 0;
for (String mod : currentFiles) {
config.setProperty(MOD_RECORD_PREFIX + index, mod);
index++;
}
config.setProperty(MOD_RECORD_PREFIX + index, "");
FileOutputStream configOutput;
try {
configOutput = new FileOutputStream(configFile);
config.store(configOutput, "Minecart Updater");
configOutput.close();
} catch (FileNotFoundException ex) {
Logger.getLogger(Updater.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(Updater.class.getName()).log(Level.SEVERE, null, ex);
}
}
private String getGamePath() {
if (!gamePathCheckBox.isSelected()) {
return gamePathTextField.getText();
}
switch (osType) {
case LINUX: {
return System.getProperty("user.home") + File.separator + ".minecraft";
}
case WINDOWS: {
return System.getenv("APPDATA") + File.separator + ".minecraft";
}
case MAC: {
return System.getProperty("user.home") + "Library/Application Support/minecraft";
}
}
return null;
}
private ProfilePathResult getProfilePath() {
String profilePath = null;
if (profilePathCheckBox.isSelected()) {
JSONParser parser = new JSONParser();
String gamePath = getGamePath();
Logger.getLogger(Updater.class.getName()).log(Level.INFO, "Cesta ke konfiguraci: " + gamePath);
File profilesFile = new File(gamePath + File.separator + "launcher_profiles.json");
if (!profilesFile.exists()) {
return new ProfilePathResult(null, "Nepodařilo se najít soubor s profily");
}
try {
FileReader fileReader = new FileReader(profilesFile);
JSONObject profileFile = (JSONObject) parser.parse(fileReader);
JSONObject profiles = (JSONObject) profileFile.get("profiles");
JSONObject minecartProfile = null;
minecartProfile = (JSONObject) profiles.get(profileName);
if (minecartProfile == null) {
// Scan for alternative names
Set keySet = profiles.keySet();
for (Object key : keySet) {
if (key instanceof String && ((String) key).equalsIgnoreCase(profileName)) {
profileName = (String) key;
minecartProfile = (JSONObject) profiles.get(key);
break;
}
}
}
if (minecartProfile == null) {
return new ProfilePathResult(null, "Nepodařilo se najít profil " + profileName);
}
Logger.getLogger(Updater.class.getName()).log(Level.WARNING, "Název profilu: " + profileName);
String minecartProfileDir = (String) minecartProfile.get("gameDir");
if (minecartProfileDir == null || minecartProfileDir.isEmpty()) {
profilePath = gamePath;
} else {
profilePath = minecartProfileDir;
}
Logger.getLogger(Updater.class.getName()).log(Level.WARNING, "Cesta k profilu: " + profilePath);
} catch (ParseException | FileNotFoundException ex) {
Logger.getLogger(Updater.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(Updater.class.getName()).log(Level.SEVERE, null, ex);
}
} else {
profilePath = profilePathTextField.getText();
}
return new ProfilePathResult(profilePath, null);
}
private void registerLogger() {
Logger.getLogger(Updater.class.getName()).addHandler(new StreamHandler() {
@Override
public void publish(LogRecord record) {
super.publish(record);
flush();
try {
logTextArea.append("\n");
String message = record.getMessage();
if (message != null) {
logTextArea.append(message);
}
Throwable thrown = record.getThrown();
if (thrown != null) {
logTextArea.append("Exception: " + thrown.toString());
}
} catch (Exception ex) {
// ignore
}
}
});
}
private static class ProfilePathResult {
public ProfilePathResult(String profilePath, String errorMessage) {
this.profilePath = profilePath;
this.errorMessage = errorMessage;
}
String profilePath;
String errorMessage;
}
private void updateGamePathVisibility() {
gamePathTextField.setEnabled(!gamePathCheckBox.isSelected());
gamePathButton.setEnabled(!gamePathCheckBox.isSelected());
}
private void updateProfilePathVisibility() {
profilePathTextField.setEnabled(!profilePathCheckBox.isSelected());
profilePathButton.setEnabled(!profilePathCheckBox.isSelected());
}
private static class UpdatePlan {
String profilePath;
CheckModsUpdateResult resultType;
String errorMessage;
Set<String> downloadMods;
Set<String> deleteMods;
public UpdatePlan(CheckModsUpdateResult resultType, String errorMessage) {
this.resultType = resultType;
this.errorMessage = errorMessage;
}
public UpdatePlan(CheckModsUpdateResult resultType, String profilePath, Set<String> downloadMods, Set<String> deleteMods) {
this.resultType = resultType;
this.profilePath = profilePath;
this.downloadMods = downloadMods;
this.deleteMods = deleteMods;
}
}
public static enum CheckAppUpdateResult {
UPDATE_URL_NOT_SET,
NO_CONNECTION,
CONNECTION_ISSUE,
NOT_FOUND,
NO_UPDATE_AVAILABLE,
UPDATE_FOUND
}
public static enum CheckModsUpdateResult {
UPDATE_URL_NOT_SET,
NO_CONNECTION,
CONNECTION_ISSUE,
NOT_FOUND,
NO_UPDATE_AVAILABLE,
NO_TARGET_DIRECTORY,
NO_TARGET_MOD_DIRECTORY,
UPDATE_FOUND
}
public static enum ModsUpdateResult {
UPDATE_OK,
DOWNLOAD_ERROR
}
public static enum OsType {
WINDOWS,
MAC,
LINUX
}
}
|
package org.xwiki.localization.messagetool.internal;
import javax.inject.Inject;
import javax.inject.Named;
import javax.inject.Singleton;
import org.xwiki.component.annotation.Component;
import org.xwiki.localization.message.TranslationMessage;
import org.xwiki.localization.message.TranslationMessageParser;
import org.xwiki.rendering.parser.Parser;
/**
* @version $Id$
* @since 4.3M2
*/
@Component
@Singleton
@Named(MessageToolTranslationMessageParser.HINT)
public class MessageToolTranslationMessageParser implements TranslationMessageParser
{
/**
* The role hint of the component.
*/
public static final String HINT = "messagetool/1.0";
/**
* The plain text parser.
*/
@Inject
@Named("plain/1.0")
private Parser plainParser;
@Override
public TranslationMessage parse(String messsage)
{
return new MessageFormatTranslationMessage(messsage, this.plainParser);
}
}
|
package de.dhbw.humbuch.view;
import java.util.NoSuchElementException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.eventbus.EventBus;
import com.google.common.eventbus.Subscribe;
import com.google.inject.Inject;
import com.vaadin.annotations.Theme;
import com.vaadin.annotations.Title;
import com.vaadin.annotations.Widgetset;
import com.vaadin.event.ShortcutAction.KeyCode;
import com.vaadin.navigator.Navigator;
import com.vaadin.navigator.Navigator.ComponentContainerViewDisplay;
import com.vaadin.navigator.View;
import com.vaadin.navigator.ViewChangeListener;
import com.vaadin.server.VaadinRequest;
import com.vaadin.ui.Button.ClickEvent;
import com.vaadin.ui.Button.ClickListener;
import com.vaadin.ui.GridLayout;
import com.vaadin.ui.Notification;
import com.vaadin.ui.Notification.Type;
import com.vaadin.ui.Panel;
import com.vaadin.ui.UI;
import com.vaadin.ui.VerticalLayout;
import com.vaadin.ui.Window;
import de.davherrmann.guice.vaadin.ScopedUI;
import de.davherrmann.mvvm.BasicState;
import de.davherrmann.mvvm.StateChangeListener;
import de.davherrmann.mvvm.ViewModelComposer;
import de.davherrmann.mvvm.annotations.BindState;
import de.dhbw.humbuch.event.LoginEvent;
import de.dhbw.humbuch.event.MessageEvent;
import de.dhbw.humbuch.util.ResourceLoader;
import de.dhbw.humbuch.view.components.Footer;
import de.dhbw.humbuch.view.components.Header;
import de.dhbw.humbuch.view.components.NavigationBar;
import de.dhbw.humbuch.viewmodel.LoginViewModel;
import de.dhbw.humbuch.viewmodel.LoginViewModel.IsLoggedIn;
@Theme("humbuch")
@SuppressWarnings("serial")
@Widgetset("com.vaadin.DefaultWidgetSet")
@Title("HumBuch Schulbuchverwaltung")
public class MainUI extends ScopedUI {
private final static Logger LOG = LoggerFactory.getLogger(MainUI.class);
public static final String LOGIN_VIEW = "login_view";
public static final String HOME_VIEW = "home_view";
public static final String BOOK_MANAGEMENT_VIEW = "book_management_view";
public static final String DUNNING_VIEW = "dunning_view";
public static final String LENDING_VIEW = "lending_view";
public static final String RETURN_VIEW = "return_view";
public static final String STUDENT_INFORMATION_VIEW = "student_information_view";
public static final String SETTINGS_VIEW = "settings_view";
@Inject
private LoginView loginView;
@Inject
private DunningView dunningView;
@Inject
private LendingView lendingView;
@Inject
private ReturnView returnView;
@Inject
private HomeView homeView;
@Inject
private BookManagementView bookManagementView;
@Inject
private StudentInformationView studentInformationView;
@Inject
private SettingsView settingsView;
@Inject
private Header header;
private VerticalLayout viewContainer = new VerticalLayout();;
private GridLayout gridLayoutRoot;
private ComponentContainerViewDisplay ccViewDisplay;
private Footer footer;
private NavigationBar navigationBar;
private Panel panelContent = new Panel();
private View currentView;
public Navigator navigator;
@BindState(IsLoggedIn.class)
private BasicState<Boolean> isLoggedIn = new BasicState<Boolean>(
Boolean.class);
@Inject
public MainUI(ViewModelComposer viewModelComposer,
LoginViewModel loginViewModel, EventBus eventBus) {
bindViewModel(viewModelComposer, loginViewModel);
eventBus.register(this);
}
@Override
protected void init(VaadinRequest request) {
ccViewDisplay = new ComponentContainerViewDisplay(viewContainer);
navigator = new Navigator(UI.getCurrent(), ccViewDisplay);
// TODO: Hack! Check how to save String in enums
navigator.addView("", homeView);
navigator.addView(LOGIN_VIEW, loginView);
navigator.addView(HOME_VIEW, homeView);
navigator.addView(BOOK_MANAGEMENT_VIEW, bookManagementView);
navigator.addView(DUNNING_VIEW, dunningView);
navigator.addView(LENDING_VIEW, lendingView);
navigator.addView(RETURN_VIEW, returnView);
navigator.addView(STUDENT_INFORMATION_VIEW, studentInformationView);
navigator.addView(SETTINGS_VIEW, settingsView);
// Make the displayed view as big as possible
viewContainer.setSizeFull();
if (!isLoggedIn.get()) {
buildMainView(true);
} else {
buildMainView(false);
}
attachListener();
}
/**
* Build the MainView with header, navigation bar and footer
*
* @param cancel
* Whether the MainView should be build or not
*/
private void buildMainView(boolean cancel) {
if (cancel) {
setContent(viewContainer);
return;
}
gridLayoutRoot = new GridLayout(2, 3);
footer = new Footer();
navigationBar = new NavigationBar();
panelContent.setSizeFull();
header.setWidth("100%");
footer.setWidth("100%");
navigationBar.setWidth("100%");
panelContent.setContent(viewContainer);
gridLayoutRoot.setSizeFull();
gridLayoutRoot.setRowExpandRatio(1, 1);
gridLayoutRoot.setColumnExpandRatio(0, 20);
gridLayoutRoot.setColumnExpandRatio(1, 80);
gridLayoutRoot.addComponent(panelContent, 1, 1);
gridLayoutRoot.addComponent(header, 0, 0, 1, 0);
gridLayoutRoot.addComponent(navigationBar, 0, 1);
gridLayoutRoot.addComponent(footer, 0, 2, 1, 2);
setContent(gridLayoutRoot);
}
private void attachListener() {
/**
* Checks if the user is logged in before the view changes
*/
navigator.addViewChangeListener(new ViewChangeListener() {
@Override
public boolean beforeViewChange(ViewChangeEvent event) {
currentView = event.getNewView();
boolean isLoginView = currentView instanceof LoginView;
if (!isLoggedIn.get() && !isLoginView) {
// Redirect to login view always if a user has not yet
// logged in
getNavigator().navigateTo(MainUI.LOGIN_VIEW);
return false;
} else if (isLoggedIn.get() && isLoginView) {
// If someone tries to access to login view while logged in,
// then cancel
return false;
}
return true;
}
@Override
public void afterViewChange(ViewChangeEvent event) {
if (isLoggedIn.get()) {
View newView = event.getNewView();
if (newView instanceof ViewInformation) {
panelContent.setCaption(((ViewInformation) newView)
.getTitle());
} else {
LOG.warn("New View does not implement ViewInformation interface."
+ " Could not set caption of panel correctly.");
}
}
}
});
/**
* Listens for a login or logout of a user an constructs the UI
* accordingly
*/
isLoggedIn.addStateChangeListener(new StateChangeListener() {
@Override
public void stateChange(Object arg0) {
if (isLoggedIn.get()) {
buildMainView(false);
} else {
buildMainView(true);
getNavigator().navigateTo(MainUI.LOGIN_VIEW);
}
}
});
header.getHelpButton().addClickListener(new ClickListener() {
@Override
public void buttonClick(ClickEvent event) {
Window window = createHelpWindow(new ResourceLoader("help/"
+ currentView.getClass().getSimpleName() + ".html")
.getContent());
getUI().addWindow(window);
getUI().setFocusedComponent(window);
}
});
}
/**
* Creates a {@link Window} with a specified help text
*
* @param helpText
* {@link String} containing the help text
* @return {@link Window}
*/
protected Window createHelpWindow(String helpText) {
HelpView helpView = new HelpView();
if (helpText != null) {
helpView.setHelpText(helpText);
}
Window window = new Window("Hilfe", helpView);
window.center();
window.setModal(true);
window.setResizable(false);
window.setCloseShortcut(KeyCode.ESCAPE, null);
return window;
}
/**
* Example for handling events posted via the {@link EventBus}
*
* @param loginEvent
* a {@link LoginEvent}
*/
@Subscribe
public void handleLoginEvent(LoginEvent loginEvent) {
Notification.show(loginEvent.message);
}
/**
* Handles {@link MessageEvent}s showing the message in a Vaadin
* {@link Notification}
*
* @param messageEvent
* {@link MessageEvent} containing the message to show
*/
@Subscribe
public void handleMessageEvent(MessageEvent messageEvent) {
Type notificationType;
switch (messageEvent.type) {
case ERROR:
notificationType = Type.ERROR_MESSAGE;
break;
case WARNING:
notificationType = Type.WARNING_MESSAGE;
break;
case TRAYINFO:
notificationType = Type.TRAY_NOTIFICATION;
break;
case INFO:
default:
notificationType = Type.HUMANIZED_MESSAGE;
}
Notification.show(messageEvent.caption, messageEvent.message, notificationType);
}
private void bindViewModel(ViewModelComposer viewModelComposer,
Object... viewModels) {
try {
viewModelComposer.bind(this, viewModels);
} catch (IllegalAccessException | NoSuchElementException
| UnsupportedOperationException e) {
e.printStackTrace();
}
}
}
|
package de.dhbw.humbuch.view;
import java.util.NoSuchElementException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.inject.Inject;
import com.vaadin.annotations.Theme;
import com.vaadin.annotations.Widgetset;
import com.vaadin.navigator.Navigator;
import com.vaadin.navigator.Navigator.ComponentContainerViewDisplay;
import com.vaadin.navigator.View;
import com.vaadin.navigator.ViewChangeListener;
import com.vaadin.server.VaadinRequest;
import com.vaadin.ui.GridLayout;
import com.vaadin.ui.Panel;
import com.vaadin.ui.UI;
import com.vaadin.ui.VerticalLayout;
import de.davherrmann.guice.vaadin.ScopedUI;
import de.davherrmann.mvvm.BasicState;
import de.davherrmann.mvvm.StateChangeListener;
import de.davherrmann.mvvm.ViewModelComposer;
import de.davherrmann.mvvm.annotations.BindState;
import de.dhbw.humbuch.view.components.Footer;
import de.dhbw.humbuch.view.components.Header;
import de.dhbw.humbuch.view.components.NavigationBar;
import de.dhbw.humbuch.viewmodel.LoginViewModel;
import de.dhbw.humbuch.viewmodel.LoginViewModel.IsLoggedIn;
@Theme("mytheme")
@SuppressWarnings("serial")
@Widgetset("com.vaadin.DefaultWidgetSet")
public class MainUI extends ScopedUI {
private final static Logger LOG = LoggerFactory.getLogger(MainUI.class);
public static final String LOGIN_VIEW = "login_view";
public static final String HOME_VIEW = "home_view";
public static final String BOOK_MANAGEMENT_VIEW = "book_management_view";
public static final String DUNNING_VIEW = "dunning_view";
public static final String LENDING_VIEW = "lending_view";
public static final String RETURN_VIEW = "return_view";
public static final String STUDENT_INFORMATION_VIEW = "student_information_view";
@Inject
private LoginView loginView;
@Inject
private DunningView dunningView;
@Inject
private LendingView lendingView;
@Inject
private ReturnView returnView;
@Inject
private HomeView homeView;
@Inject
private BookManagementView bookManagementView;
@Inject
private StudentInformationView studentInformationView;
@Inject
private Header header;
private VerticalLayout viewContainer = new VerticalLayout();;
private GridLayout gridLayoutRoot;
private ComponentContainerViewDisplay ccViewDisplay;
private Footer footer;
private NavigationBar navigationBar;
private Panel panelContent = new Panel();
public Navigator navigator;
@BindState(IsLoggedIn.class)
private BasicState<Boolean> isLoggedIn = new BasicState<Boolean>(
Boolean.class);
@Inject
public MainUI(ViewModelComposer viewModelComposer,
LoginViewModel loginViewModel) {
bindViewModel(viewModelComposer, loginViewModel);
}
@Override
protected void init(VaadinRequest request) {
ccViewDisplay = new ComponentContainerViewDisplay(viewContainer);
navigator = new Navigator(UI.getCurrent(), ccViewDisplay);
/**
* Add all views, that should be navigatable
*/
// TODO: Hack! Check how to save String in enums
navigator.addView("", homeView);
navigator.addView(LOGIN_VIEW, loginView);
navigator.addView(HOME_VIEW, homeView);
navigator.addView(BOOK_MANAGEMENT_VIEW, bookManagementView);
navigator.addView(DUNNING_VIEW, dunningView);
navigator.addView(LENDING_VIEW, lendingView);
navigator.addView(RETURN_VIEW, returnView);
navigator.addView(STUDENT_INFORMATION_VIEW, studentInformationView);
if (!isLoggedIn.get()) {
buildMainView(true);
} else {
buildMainView(false);
}
attachListener();
}
/**
* Build the MainView with header, navigation bar and footer
*
* @param cancel
* Whether the MainView should be build or not
*/
private void buildMainView(boolean cancel) {
if (cancel) {
viewContainer.setSizeFull();
setContent(viewContainer);
return;
}
gridLayoutRoot = new GridLayout(2, 3);
footer = new Footer();
navigationBar = new NavigationBar();
panelContent.setSizeFull();
header.setWidth("100%");
footer.setWidth("100%");
navigationBar.setWidth("100%");
panelContent.setContent(viewContainer);
gridLayoutRoot.setSizeFull();
gridLayoutRoot.setRowExpandRatio(1, 1);
gridLayoutRoot.setColumnExpandRatio(0, 20);
gridLayoutRoot.setColumnExpandRatio(1, 80);
gridLayoutRoot.addComponent(panelContent, 1, 1);
gridLayoutRoot.addComponent(header, 0, 0, 1, 0);
gridLayoutRoot.addComponent(navigationBar, 0, 1);
gridLayoutRoot.addComponent(footer, 0, 2, 1, 2);
viewContainer.setSizeUndefined();
viewContainer.setWidth("100%");
setContent(gridLayoutRoot);
}
private void attachListener() {
/**
* Checks if the user is logged in before the view changes
*/
navigator.addViewChangeListener(new ViewChangeListener() {
@Override
public boolean beforeViewChange(ViewChangeEvent event) {
boolean isLoginView = event.getNewView() instanceof LoginView;
if (!isLoggedIn.get() && !isLoginView) {
// Redirect to login view always if a user has not yet
// logged in
getNavigator().navigateTo(MainUI.LOGIN_VIEW);
return false;
} else if (isLoggedIn.get() && isLoginView) {
// If someone tries to access to login view while logged in,
// then cancel
return false;
}
return true;
}
@Override
public void afterViewChange(ViewChangeEvent event) {
if (isLoggedIn.get()) {
View newView = event.getNewView();
if (newView instanceof ViewInformation) {
panelContent.setCaption(((ViewInformation) newView)
.getTitle());
} else {
LOG.warn("New View does not implement ViewInformation interface."
+ " Could not set caption of panel correctly.");
}
}
}
});
/**
* Listens for a login or logout of a user an constructs the UI
* accordingly
*/
isLoggedIn.addStateChangeListener(new StateChangeListener() {
@Override
public void stateChange(Object arg0) {
if (isLoggedIn.get()) {
buildMainView(false);
} else {
buildMainView(true);
getNavigator().navigateTo(MainUI.LOGIN_VIEW);
}
}
});
}
private void bindViewModel(ViewModelComposer viewModelComposer,
Object... viewModels) {
try {
viewModelComposer.bind(this, viewModels);
} catch (IllegalAccessException | NoSuchElementException
| UnsupportedOperationException e) {
e.printStackTrace();
}
}
}
|
package de.predic8.util;
import org.apache.camel.Exchange;
import org.apache.camel.Processor;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.Charset;
public class GetLastHash implements Processor {
public void process(Exchange exchange) throws Exception {
String[] lastHashLine = getLastLine().split(" ");
exchange.getIn().setBody(lastHashLine[lastHashLine.length - 1]);
}
private String getLastLine() throws IOException {
String currentLine, lastLine = "";
try (BufferedReader br = new BufferedReader(new InputStreamReader(
new FileInputStream("document-archive/logs/log.txt"), Charset.forName("UTF-8")))) {
while ((currentLine = br.readLine()) != null) {
lastLine = currentLine;
}
}
return lastLine;
}
}
|
package filter.expression;
import backend.interfaces.IModel;
import backend.resource.TurboIssue;
import backend.resource.TurboLabel;
import backend.resource.TurboMilestone;
import backend.resource.TurboUser;
import filter.MetaQualifierInfo;
import filter.QualifierApplicationException;
import util.Utility;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import java.util.*;
import java.util.function.BiConsumer;
import java.util.function.Predicate;
import java.util.stream.Collectors;
public class Qualifier implements FilterExpression {
public static final String UPDATED = "updated";
public static final String REPO = "repo";
public static final String SORT = "sort";
public static final Qualifier EMPTY = new Qualifier("", "");
public static final String[] KEYWORDS = new String[] {
"assignees", "author", "body", "closed", "comments", "created", "creator",
"date", "desc", "description", "has", "id", "in", "involves", "is", "issue",
"keyword", "label", "labels", "merged", "milestone", "milestones", "no",
"open", "pr", "pullrequest", "read", "repo", "sort", "state", "status", "title",
"type", "unmerged", "unread", "updated", "user"
};
private final String name;
// Only one of these will be present at a time
private Optional<DateRange> dateRange = Optional.empty();
private Optional<String> content = Optional.empty();
private Optional<LocalDate> date = Optional.empty();
private Optional<NumberRange> numberRange = Optional.empty();
private Optional<Integer> number = Optional.empty();
private List<SortKey> sortKeys = new ArrayList<>();
// Copy constructor
public Qualifier(Qualifier other) {
this.name = other.getName();
if (other.getDateRange().isPresent()) {
this.dateRange = other.getDateRange();
} else if (other.getDate().isPresent()) {
this.date = other.getDate();
} else if (other.getContent().isPresent()) {
this.content = other.getContent();
} else if (other.getNumberRange().isPresent()) {
this.numberRange = other.getNumberRange();
} else if (other.getNumber().isPresent()) {
this.number = other.getNumber();
} else if (!other.sortKeys.isEmpty()) {
this.sortKeys = new ArrayList<>(other.sortKeys);
} else {
assert false : "Unrecognised content type! You may have forgotten to add it above";
}
}
public Qualifier(String name, String content) {
this.name = name;
this.content = Optional.of(content);
}
public Qualifier(String name, NumberRange numberRange) {
this.name = name;
this.numberRange = Optional.of(numberRange);
}
public Qualifier(String name, DateRange dateRange) {
this.name = name;
this.dateRange = Optional.of(dateRange);
}
public Qualifier(String name, LocalDate date) {
this.name = name;
this.date = Optional.of(date);
}
public Qualifier(String name, int number) {
this.name = name;
this.number = Optional.of(number);
}
public Qualifier(String name, List<SortKey> keys) {
this.name = name;
this.sortKeys = new ArrayList<>(keys);
}
/**
* Helper function for testing a filter expression against an issue.
* Ensures that meta-qualifiers are taken care of.
* Should always be used over isSatisfiedBy.
*/
public static boolean process(IModel model, FilterExpression expr, TurboIssue issue) {
FilterExpression exprWithNormalQualifiers = expr.filter(Qualifier::shouldNotBeStripped);
List<Qualifier> metaQualifiers = expr.find(Qualifier::isMetaQualifier);
// Preprocessing for repo qualifier
boolean containsRepoQualifier = metaQualifiers.stream()
.map(Qualifier::getName)
.collect(Collectors.toList())
.contains("repo");
if (!containsRepoQualifier) {
exprWithNormalQualifiers = new Conjunction(
new Qualifier("repo", model.getDefaultRepo()),
exprWithNormalQualifiers);
}
return exprWithNormalQualifiers.isSatisfiedBy(model, issue, new MetaQualifierInfo(metaQualifiers));
}
public static void processMetaQualifierEffects(FilterExpression expr, BiConsumer<Qualifier, MetaQualifierInfo> callback) {
List<Qualifier> qualifiers = expr.find(Qualifier::isMetaQualifier);
MetaQualifierInfo info = new MetaQualifierInfo(qualifiers);
qualifiers.forEach(q -> callback.accept(q, info));
}
private static LocalDateTime currentTime = null;
private static LocalDateTime getCurrentTime() {
if (currentTime == null) {
return LocalDateTime.now();
} else {
return currentTime;
}
}
/**
* For testing. Stubs the current time so time-related qualifiers work properly.
*/
public static void setCurrentTime(LocalDateTime dateTime) {
currentTime = dateTime;
}
public boolean isEmptyQualifier() {
return name.isEmpty() && content.isPresent() && content.get().isEmpty();
}
@Override
public boolean isSatisfiedBy(IModel model, TurboIssue issue, MetaQualifierInfo info) {
assert name != null && content != null;
// The empty qualifier is satisfied by anything
if (isEmptyQualifier()) return true;
switch (name) {
case "id":
return idSatisfies(issue);
case "keyword":
return keywordSatisfies(issue, info);
case "title":
return titleSatisfies(issue);
case "body":
case "desc":
case "description":
return bodySatisfies(issue);
case "milestone":
return milestoneSatisfies(model, issue);
case "label":
return labelsSatisfy(model, issue);
case "author":
case "creator":
return authorSatisfies(issue);
case "assignee":
return assigneeSatisfies(model, issue);
case "involves":
case "user":
return involvesSatisfies(model, issue);
case "type":
return typeSatisfies(issue);
case "state":
case "status":
return stateSatisfies(issue);
case "has":
return satisfiesHasConditions(issue);
case "no":
return satisfiesNoConditions(issue);
case "is":
return satisfiesIsConditions(issue);
case "created":
return satisfiesCreationDate(issue);
case "updated":
return satisfiesUpdatedHours(issue);
case "repo":
return satisfiesRepo(issue);
default:
return false;
}
}
@Override
public void applyTo(TurboIssue issue, IModel model) throws QualifierApplicationException {
assert name != null && content != null;
// The empty qualifier should not be applied to anything
assert !isEmptyQualifier();
switch (name) {
case "title":
case "desc":
case "description":
case "body":
case "keyword":
throw new QualifierApplicationException("Unnecessary filter: issue text cannot be changed by dragging");
case "id":
throw new QualifierApplicationException("Unnecessary filter: id is immutable");
case "created":
throw new QualifierApplicationException("Unnecessary filter: cannot change issue creation date");
case "has":
case "no":
case "is":
throw new QualifierApplicationException("Ambiguous filter: " + name);
case "milestone":
applyMilestone(issue, model);
break;
case "label":
applyLabel(issue, model);
break;
case "assignee":
applyAssignee(issue, model);
break;
case "author":
case "creator":
throw new QualifierApplicationException("Unnecessary filter: cannot change author of issue");
case "involves":
case "user":
throw new QualifierApplicationException("Ambiguous filter: cannot change users involved with issue");
case "state":
case "status":
applyState(issue);
break;
default:
break;
}
}
@Override
public boolean canBeAppliedToIssue() {
return true;
}
@Override
public List<String> getQualifierNames() {
return new ArrayList<>(Arrays.asList(name));
}
@Override
public FilterExpression filter(Predicate<Qualifier> pred) {
if (pred.test(this)) {
return new Qualifier(this);
} else {
return EMPTY;
}
}
@Override
public List<Qualifier> find(Predicate<Qualifier> pred) {
if (pred.test(this)) {
ArrayList<Qualifier> result = new ArrayList<>();
result.add(this);
return result;
} else {
return new ArrayList<>();
}
}
/**
* This method is used to serialise qualifiers. Thus whatever form returned
* should be syntactically valid.
*/
@Override
public String toString() {
if (this == EMPTY) {
return "";
} else if (content.isPresent()) {
if (name.equals("keyword")) {
return content.get();
} else {
String quotedContent = content.get();
if (quotedContent.contains(" ")) {
quotedContent = "\"" + quotedContent + "\"";
}
return name + ":" + quotedContent;
}
} else if (date.isPresent()) {
return name + ":" + date.get().toString();
} else if (dateRange.isPresent()) {
return name + ":" + dateRange.get().toString();
} else if (!sortKeys.isEmpty()) {
return name + ":" + sortKeys.toString();
} else if (numberRange.isPresent()) {
return name + ":" + numberRange.get().toString();
} else if (number.isPresent()) {
return name + ":" + number.get().toString();
} else {
assert false : "Should not happen";
return "";
}
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((content == null) ? 0 : content.hashCode());
result = prime * result + ((date == null) ? 0 : date.hashCode());
result = prime * result + ((dateRange == null) ? 0 : dateRange.hashCode());
result = prime * result + ((sortKeys == null) ? 0 : sortKeys.hashCode());
result = prime * result + ((name == null) ? 0 : name.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;
Qualifier other = (Qualifier) obj;
if (content == null) {
if (other.content != null)
return false;
} else if (!content.equals(other.content))
return false;
if (date == null) {
if (other.date != null)
return false;
} else if (!date.equals(other.date))
return false;
if (dateRange == null) {
if (other.dateRange != null)
return false;
} else if (!dateRange.equals(other.dateRange))
return false;
if (sortKeys == null) {
if (other.sortKeys != null)
return false;
} else if (!sortKeys.equals(other.sortKeys))
return false;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
return true;
}
private static boolean shouldNotBeStripped(Qualifier q) {
return !shouldBeStripped(q);
}
private static boolean shouldBeStripped(Qualifier q) {
switch (q.getName()) {
case "in":
case "sort":
return true;
default:
return false;
}
}
private static boolean isMetaQualifier(Qualifier q) {
switch (q.getName()) {
case "sort":
case "in":
case "repo":
return true;
default:
return false;
}
}
public Comparator<TurboIssue> getCompoundSortComparator(IModel model) {
if (sortKeys.isEmpty()) {
return (a, b) -> 0;
}
return (a, b) -> {
for (SortKey key : sortKeys) {
Comparator<TurboIssue> comparator = getSortComparator(model, key.key, key.inverted);
int result = comparator.compare(a, b);
if (result != 0) {
return result;
}
}
return 0;
};
}
public static Comparator<TurboIssue> getSortComparator(IModel model, String key, boolean inverted) {
Comparator<TurboIssue> comparator = (a, b) -> 0;
boolean isLabelGroup = false;
switch (key) {
case "comments":
comparator = (a, b) -> a.getCommentCount() - b.getCommentCount();
break;
case "repo":
comparator = (a, b) -> a.getRepoId().compareTo(b.getRepoId());
break;
case "updated":
case "date":
comparator = (a, b) -> a.getUpdatedAt().compareTo(b.getUpdatedAt());
break;
case "id":
comparator = (a, b) -> a.getId() - b.getId();
break;
default:
// Doesn't match anything; assume it's a label group
isLabelGroup = true;
break;
}
if (isLabelGroup) {
// Has a different notion of inversion
return getLabelGroupComparator(model, key, inverted);
} else {
// Use default behaviour for inverting
if (!inverted) {
return comparator;
} else {
final Comparator<TurboIssue> finalComparator = comparator;
return (a, b) -> -finalComparator.compare(a, b);
}
}
}
private static Comparator<TurboIssue> getLabelGroupComparator(IModel model, String key, boolean inverted) {
// Strip trailing ., if any
final String group = key.replaceAll("\\.$", "");
return (a, b) -> {
// Matches labels belong to the given group
Predicate<TurboLabel> sameGroup = l ->
l.getGroup().isPresent() && l.getGroup().get().equals(group);
Comparator<TurboLabel> labelComparator = (x, y) -> x.getName().compareTo(y.getName());
List<TurboLabel> aLabels = model.getLabelsOfIssue(a, sameGroup);
List<TurboLabel> bLabels = model.getLabelsOfIssue(b, sameGroup);
Collections.sort(aLabels, labelComparator);
Collections.sort(bLabels, labelComparator);
// Put empty lists at the back
if (aLabels.size() == 0 && bLabels.size() == 0) {
return 0;
} else if (aLabels.size() == 0) {
// a is larger
return 1;
} else if (bLabels.size() == 0) {
// b is larger
return -1;
}
// Compare lengths
int result = !inverted
? aLabels.size() - bLabels.size()
: bLabels.size() - aLabels.size();
if (result != 0) {
return result;
}
// Lexicographic label comparison
assert aLabels.size() == bLabels.size();
for (int i=0; i<aLabels.size(); i++) {
result = !inverted
? labelComparator.compare(aLabels.get(i), bLabels.get(i))
: labelComparator.compare(bLabels.get(i), aLabels.get(i));
if (result != 0) {
return result;
}
}
return 0;
};
}
private boolean idSatisfies(TurboIssue issue) {
if (number.isPresent()) {
return issue.getId() == number.get();
} else if (numberRange.isPresent()) {
return numberRange.get().encloses(issue.getId());
}
return false;
}
private boolean satisfiesUpdatedHours(TurboIssue issue) {
int hours = Utility.safeLongToInt(issue.getUpdatedAt().until(getCurrentTime(), ChronoUnit.HOURS));
if (numberRange.isPresent()) {
return numberRange.get().encloses(hours);
} else if (number.isPresent()) {
// Treat it as <
return new NumberRange(null, number.get(), true).encloses(hours);
} else {
return false;
}
}
private boolean satisfiesRepo(TurboIssue issue) {
if (!content.isPresent()) return false;
return issue.getRepoId().equals(content.get());
}
private boolean satisfiesCreationDate(TurboIssue issue) {
LocalDate creationDate = issue.getCreatedAt().toLocalDate();
if (date.isPresent()) {
return creationDate.isEqual(date.get());
} else if (dateRange.isPresent()) {
return dateRange.get().encloses(creationDate);
} else {
return false;
}
}
private boolean satisfiesHasConditions(TurboIssue issue) {
if (!content.isPresent()) return false;
switch (content.get()) {
case "label":
case "labels":
return issue.getLabels().size() > 0;
case "milestone":
case "milestones":
assert issue.getMilestone() != null;
return issue.getMilestone().isPresent();
case "assignee":
case "assignees":
assert issue.getMilestone() != null;
return issue.getAssignee().isPresent();
default:
return false;
}
}
private boolean satisfiesNoConditions(TurboIssue issue) {
return content.isPresent() && !satisfiesHasConditions(issue);
}
private boolean satisfiesIsConditions(TurboIssue issue) {
if (!content.isPresent()) return false;
switch (content.get()) {
case "open":
case "closed":
return stateSatisfies(issue);
case "pr":
case "issue":
return typeSatisfies(issue);
case "merged":
return issue.isPullRequest() && !issue.isOpen();
case "unmerged":
return issue.isPullRequest() && issue.isOpen();
case "read":
return issue.isCurrentlyRead();
case "unread":
return !issue.isCurrentlyRead();
default:
return false;
}
}
private boolean stateSatisfies(TurboIssue issue) {
if (!content.isPresent()) return false;
String content = this.content.get().toLowerCase();
if (content.contains("open")) {
return issue.isOpen();
} else if (content.contains("closed")) {
return !issue.isOpen();
} else {
return false;
}
}
private boolean assigneeSatisfies(IModel model, TurboIssue issue) {
if (!content.isPresent()) return false;
Optional<TurboUser> assignee = model.getAssigneeOfIssue(issue);
if (!assignee.isPresent()) return false;
String content = this.content.get().toLowerCase();
String login = assignee.get().getLoginName() == null ? "" : assignee.get().getLoginName().toLowerCase();
String name = assignee.get().getRealName() == null ? "" : assignee.get().getRealName().toLowerCase();
return login.contains(content) || name.contains(content);
}
private boolean authorSatisfies(TurboIssue issue) {
if (!content.isPresent()) return false;
String creator = issue.getCreator();
return creator.toLowerCase().contains(content.get().toLowerCase());
}
private boolean involvesSatisfies(IModel model, TurboIssue issue) {
return authorSatisfies(issue) || assigneeSatisfies(model, issue);
}
private boolean labelsSatisfy(IModel model, TurboIssue issue) {
if (!content.isPresent()) return false;
// Make use of TurboLabel constructor to parse the string, to avoid duplication
TurboLabel tokens = new TurboLabel("", content.get().toLowerCase());
String group = "";
if (tokens.getGroup().isPresent()) {
group = tokens.getGroup().get().toLowerCase();
}
String labelName = tokens.getName().toLowerCase();
for (TurboLabel label : model.getLabelsOfIssue(issue)) {
if (label.getGroup().isPresent()) {
if (labelName.isEmpty()) {
// Check the group
if (label.getGroup().get().toLowerCase().contains(group)) {
return true;
}
} else {
if (label.getGroup().get().toLowerCase().contains(group)
&& label.getName().toLowerCase().contains(labelName)) {
return true;
}
}
} else {
// Check only the label name
if (!group.isEmpty()) {
return false;
} else if (!labelName.isEmpty() && label.getName().toLowerCase().contains(labelName)) {
return true;
}
}
}
return false;
}
private boolean milestoneSatisfies(IModel model, TurboIssue issue) {
if (!content.isPresent()) return false;
Optional<TurboMilestone> milestone = model.getMilestoneOfIssue(issue);
if (!milestone.isPresent()) return false;
String contents = content.get().toLowerCase();
String title = milestone.get().getTitle().toLowerCase();
return title.contains(contents);
}
private boolean keywordSatisfies(TurboIssue issue, MetaQualifierInfo info) {
if (info.getIn().isPresent()) {
switch (info.getIn().get()) {
case "title":
return titleSatisfies(issue);
case "body":
case "desc":
case "description":
return bodySatisfies(issue);
default:
return false;
}
} else {
return titleSatisfies(issue) || bodySatisfies(issue);
}
}
private boolean bodySatisfies(TurboIssue issue) {
if (!content.isPresent()) return false;
return issue.getDescription().toLowerCase().contains(content.get().toLowerCase());
}
private boolean titleSatisfies(TurboIssue issue) {
if (!content.isPresent()) return false;
return issue.getTitle().toLowerCase().contains(content.get().toLowerCase());
}
private boolean typeSatisfies(TurboIssue issue) {
if (!content.isPresent()) return false;
String content = this.content.get().toLowerCase();
switch (content) {
case "issue":
return !issue.isPullRequest();
case "pr":
case "pullrequest":
return issue.isPullRequest();
default:
return false;
}
}
private void applyMilestone(TurboIssue issue, IModel model) throws QualifierApplicationException {
if (!content.isPresent()) {
throw new QualifierApplicationException("Invalid milestone " + (date.isPresent() ? date.get() : dateRange.get()));
}
// Find milestones containing the partial title
List<TurboMilestone> milestones = model.getMilestones().stream().filter(m -> m.getTitle().toLowerCase().contains(content.get().toLowerCase())).collect(Collectors.toList());
if (milestones.size() > 1) {
throw new QualifierApplicationException("Ambiguous filter: can apply any of the following milestones: " + milestones.toString());
} else {
issue.setMilestone(milestones.get(0));
}
}
private void applyLabel(TurboIssue issue, IModel model) throws QualifierApplicationException {
if (!content.isPresent()) {
throw new QualifierApplicationException("Invalid label " + (date.isPresent() ? date.get() : dateRange.get()));
}
// Find labels containing the label name
List<TurboLabel> labels = model.getLabels().stream()
.filter(l -> l.getActualName().toLowerCase().contains(content.get().toLowerCase()))
.collect(Collectors.toList());
if (labels.size() > 1) {
throw new QualifierApplicationException("Ambiguous filter: can apply any of the following labels: " + labels.toString());
} else {
issue.addLabel(labels.get(0));
}
}
private void applyAssignee(TurboIssue issue, IModel model) throws QualifierApplicationException {
if (!content.isPresent()) {
throw new QualifierApplicationException("Invalid assignee " + (date.isPresent() ? date.get() : dateRange.get()));
}
// Find assignees containing the partial title
List<TurboUser> assignees = model.getUsers().stream()
.filter(c -> c.getLoginName().toLowerCase().contains(content.get().toLowerCase()))
.collect(Collectors.toList());
if (assignees.size() > 1) {
throw new QualifierApplicationException("Ambiguous filter: can apply any of the following assignees: " + assignees.toString());
} else {
issue.setAssignee(assignees.get(0));
}
}
private void applyState(TurboIssue issue) throws QualifierApplicationException {
if (!content.isPresent()) {
throw new QualifierApplicationException("Invalid state " + (date.isPresent() ? date.get() : dateRange.get()));
}
if (content.get().toLowerCase().contains("open")) {
issue.setOpen(true);
} else if (content.get().toLowerCase().contains("closed")) {
issue.setOpen(false);
}
}
public Optional<Integer> getNumber() {
return number;
}
public Optional<NumberRange> getNumberRange() {
return numberRange;
}
public Optional<DateRange> getDateRange() {
return dateRange;
}
public Optional<String> getContent() {
return content;
}
public Optional<LocalDate> getDate() {
return date;
}
public String getName() {
return name;
}
}
|
package hu.bme.mit.spaceship;
/**
* A simple spaceship with two proton torpedos and four lasers
*/
public class GT4500 implements SpaceShip {
private TorpedoStore primaryTorpedoStore;
private TorpedoStore secondaryTorpedoStore;
private boolean wasPrimaryFiredLast = false;
public GT4500() {
this.primaryTorpedoStore = new TorpedoStore(10);
this.secondaryTorpedoStore = new TorpedoStore(10);
}
public boolean fireLasers(FiringMode firingMode) {
// TODO not implemented yet
return false;
}
/**
* Tries to fire the torpedo stores of the ship.
*
* @param firingMode how many torpedo bays to fire
* SINGLE: fires only one of the bays.
* - For the first time the primary store is fired.
* - To give some cooling time to the torpedo stores, torpedo stores are fired alternating.
* - But if the store next in line is empty the ship tries to fire the other store.
* - If the fired store reports a failure, the ship does not try to fire the other one.
* ALL: tries to fire both of the torpedo stores.
*
* @return whether at least one torpedo was fired successfully
*/
@Override
public boolean fireTorpedos(FiringMode firingMode) {
boolean firingSuccess = false;
switch (firingMode) {
case SINGLE:
if (wasPrimaryFiredLast) {
// try to fire the secondary first
if (! secondaryTorpedoStore.isEmpty()) {
firingSuccess = secondaryTorpedoStore.fire(1);
wasPrimaryFiredLast = false;
}
else {
// although primary was fired last time, but the secondary is empty
// thus try to fire primary again
if (! primaryTorpedoStore.isEmpty()) {
firingSuccess = primaryTorpedoStore.fire(1);
wasPrimaryFiredLast = true;
}
// if both of the stores are empty, nothing can be done, return failure
}
}
else {
// try to fire the primary first
if (! primaryTorpedoStore.isEmpty()) {
firingSuccess = primaryTorpedoStore.fire(1);
wasPrimaryFiredLast = true;
}
else {
// although secondary was fired last time, but primary is empty
// thus try to fire secondary again
if (! secondaryTorpedoStore.isEmpty()) {
firingSuccess = secondaryTorpedoStore.fire(1);
wasPrimaryFiredLast = false;
}
// if both of the stores are empty, nothing can be done, return failure
}
}
break;
case ALL:
// try to fire both of the torpedos
//TODO implement feature
while(!primaryTorpedoStore.isEmpty() || !primaryTorpedoStore.isEmpty()){
if (wasPrimaryFiredLast) {
// try to fire the secondary first
if (! secondaryTorpedoStore.isEmpty()) {
firingSuccess = secondaryTorpedoStore.fire(1);
wasPrimaryFiredLast = false;
}
else {
// although primary was fired last time, but the secondary is empty
// thus try to fire primary again
if (! primaryTorpedoStore.isEmpty()) {
firingSuccess = primaryTorpedoStore.fire(1);
wasPrimaryFiredLast = true;
}
}
}
else {
// try to fire the primary first
if (! primaryTorpedoStore.isEmpty()) {
firingSuccess = primaryTorpedoStore.fire(1);
wasPrimaryFiredLast = true;
}
else {
// although secondary was fired last time, but primary is empty
// thus try to fire secondary again
if (! secondaryTorpedoStore.isEmpty()) {
firingSuccess = secondaryTorpedoStore.fire(1);
wasPrimaryFiredLast = false;
}
}
}
}
break;
}
//Here is some other change...
return firingSuccess;
}
}
|
package hudson.plugins.ec2;
import com.xerox.amazonws.ec2.EC2Exception;
import com.xerox.amazonws.ec2.InstanceType;
import com.xerox.amazonws.ec2.Jec2;
import hudson.model.Computer;
import hudson.model.Descriptor.FormException;
import hudson.model.Hudson;
import hudson.model.Slave;
import hudson.plugins.ec2.ssh.EC2UnixLauncher;
import hudson.slaves.NodeProperty;
import hudson.Extension;
import hudson.Util;
import java.io.IOException;
import java.util.Collections;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.kohsuke.stapler.DataBoundConstructor;
/**
* Slave running on EC2.
*
* @author Kohsuke Kawaguchi
*/
public final class EC2Slave extends Slave {
/**
* Comes from {@link SlaveTemplate#initScript}.
*/
public final String initScript;
public final String remoteAdmin; // e.g. 'ubuntu'
public final String rootCommandPrefix; // e.g. 'sudo'
public final String jvmopts; //e.g. -Xmx1g
/**
* For data read from old Hudson, this is 0, so we use that to indicate 22.
*/
private final int sshPort;
public EC2Slave(String instanceId, String description, String remoteFS, int sshPort, int numExecutors, String labelString, String initScript, String remoteAdmin, String rootCommandPrefix, String jvmopts) throws FormException, IOException {
this(instanceId, description, remoteFS, sshPort, numExecutors, Mode.NORMAL, labelString, initScript, Collections.<NodeProperty<?>>emptyList(), remoteAdmin, rootCommandPrefix, jvmopts);
}
@DataBoundConstructor
public EC2Slave(String instanceId, String description, String remoteFS, int sshPort, int numExecutors, Mode mode, String labelString, String initScript, List<? extends NodeProperty<?>> nodeProperties, String remoteAdmin, String rootCommandPrefix, String jvmopts) throws FormException, IOException {
super(instanceId, description, remoteFS, numExecutors, mode, labelString, new EC2UnixLauncher(), new EC2RetentionStrategy(), nodeProperties);
this.initScript = initScript;
this.remoteAdmin = remoteAdmin;
this.rootCommandPrefix = rootCommandPrefix;
this.jvmopts = jvmopts;
this.sshPort = sshPort;
}
/**
* Constructor for debugging.
*/
public EC2Slave(String instanceId) throws FormException, IOException {
this(instanceId,"debug","/tmp/hudson", 22, 1, Mode.NORMAL, "debug", "", Collections.<NodeProperty<?>>emptyList(), null, null, null);
}
/*package*/ static int toNumExecutors(InstanceType it) {
switch (it) {
case DEFAULT: return 1;
case MEDIUM_HCPU: return 5;
case LARGE: return 4;
case XLARGE: return 8;
case XLARGE_HCPU: return 20;
default: throw new AssertionError();
}
}
/**
* EC2 instance ID.
*/
public String getInstanceId() {
return getNodeName();
}
@Override
public Computer createComputer() {
return new EC2Computer(this);
}
/**
* Terminates the instance in EC2.
*/
public void terminate() {
try {
Jec2 ec2 = EC2Cloud.get().connect();
ec2.terminateInstances(Collections.singletonList(getInstanceId()));
LOGGER.info("Terminated EC2 instance: "+getInstanceId());
Hudson.getInstance().removeNode(this);
} catch (EC2Exception e) {
LOGGER.log(Level.WARNING,"Failed to terminate EC2 instance: "+getInstanceId(),e);
} catch (IOException e) {
LOGGER.log(Level.WARNING,"Failed to terminate EC2 instance: "+getInstanceId(),e);
}
}
String getRemoteAdmin() {
if (remoteAdmin == null || remoteAdmin.length() == 0)
return "root";
return remoteAdmin;
}
String getRootCommandPrefix() {
if (rootCommandPrefix == null || rootCommandPrefix.length() == 0)
return "";
return rootCommandPrefix + " ";
}
String getJvmopts() {
return Util.fixNull(jvmopts);
}
public int getSshPort() {
return sshPort!=0 ? sshPort : 22;
}
@Extension
public static final class DescriptorImpl extends SlaveDescriptor {
public String getDisplayName() {
return "Amazon EC2";
}
@Override
public boolean isInstantiable() {
return false;
}
}
private static final Logger LOGGER = Logger.getLogger(EC2Slave.class.getName());
}
|
package hudson.plugins.git;
import hudson.Extension;
import hudson.tools.ToolProperty;
import org.jenkinsci.plugins.gitclient.Git;
import org.jenkinsci.plugins.gitclient.JGitAPIImpl;
import org.kohsuke.stapler.DataBoundConstructor;
import java.util.List;
/**
* JGit as {@link GitTool}
*
* @author Kohsuke Kawaguchi
*/
public class JGitTool extends GitTool {
@DataBoundConstructor
public JGitTool(List<? extends ToolProperty<?>> properties) {
super("jgit", MAGIC_EXENAME, properties);
}
@Override
public GitTool.DescriptorImpl getDescriptor() {
return super.getDescriptor();
}
@Extension
public static class DescriptorImpl extends GitTool.DescriptorImpl {
@Override
public String getDisplayName() {
return "JGit";
}
}
/**
* {@link Git} redcognizes this as a magic executable name to use {@link JGitAPIImpl}.
*/
public static final String MAGIC_EXENAME = "jgit";
}
|
package hudson.plugins.s3;
import hudson.FilePath;
import java.io.IOException;
import java.util.concurrent.atomic.AtomicReference;
import org.kohsuke.stapler.DataBoundConstructor;
import com.amazonaws.auth.BasicAWSCredentials;
import com.amazonaws.services.s3.AmazonS3Client;
import com.amazonaws.services.s3.model.ObjectMetadata;
import com.amazonaws.services.s3.internal.Mimetypes;
import hudson.util.Secret;
public class S3Profile {
private String name;
private String accessKey;
private Secret secretKey;
private static final AtomicReference<AmazonS3Client> client = new AtomicReference<AmazonS3Client>(null);
public S3Profile() {
}
@DataBoundConstructor
public S3Profile(String name, String accessKey, String secretKey) {
this.name = name;
this.accessKey = accessKey;
this.secretKey = Secret.fromString(secretKey);
client.set(new AmazonS3Client(new BasicAWSCredentials(accessKey, secretKey)));
}
public final String getAccessKey() {
return accessKey;
}
public void setAccessKey(String accessKey) {
this.accessKey = accessKey;
}
public final Secret getSecretKey() {
return secretKey;
}
public final String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
public AmazonS3Client getClient() {
if (client.get() == null) {
client.set(new AmazonS3Client(new BasicAWSCredentials(accessKey, secretKey.getPlainText())));
}
return client.get();
}
public void check() throws Exception {
getClient().listBuckets();
}
public void upload(String bucketName, FilePath filePath) throws IOException, InterruptedException {
if (filePath.isDirectory()) {
throw new IOException(filePath + " is a directory");
}
final Destination dest = new Destination(bucketName,filePath.getName());
ObjectMetadata metadata = new ObjectMetadata();
metadata.setContentType(Mimetypes.getInstance().getMimetype(filePath.getName()));
metadata.setContentLength(filePath.length());
try {
getClient().putObject(dest.bucketName, dest.objectName, filePath.read(), metadata);
} catch (Exception e) {
throw new IOException("put " + dest + ": " + e);
}
}
}
|
package com.ywen;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;
import javax.crypto.Cipher;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import javax.crypto.spec.IvParameterSpec;
import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.KeyFactory;
import java.security.NoSuchAlgorithmException;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
public class CryptoManager {
private RSAPrivateKey privateKey;
private RSAPublicKey publicKey;
public RSAPublicKey getPublicKey() {
return publicKey;
}
public CryptoManager(String privateKeyStr, String publicKeyStr) {
try {
this.setPrivateKey(privateKeyStr);
this.setPublicKey(publicKeyStr);
} catch (Exception e) {
e.printStackTrace();
}
}
public void setPublicKey(String publicKeyStr) throws Exception {
try {
BASE64Decoder decoder = new BASE64Decoder();
byte[] buffer = decoder.decodeBuffer(publicKeyStr);
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
X509EncodedKeySpec keySpec = new X509EncodedKeySpec(buffer);
this.publicKey = (RSAPublicKey)keyFactory.generatePublic(keySpec);
}
catch (NoSuchAlgorithmException e) {
throw new Exception("");
} catch (InvalidKeySpecException e) {
e.printStackTrace();
throw new Exception("");
} catch (IOException e) {
e.printStackTrace();
throw new Exception("");
}
}
public RSAPrivateKey getPrivateKey() {
return privateKey;
}
public void setPrivateKey(String privateKeyStr) throws Exception {
try {
BASE64Decoder decoder = new BASE64Decoder();
byte[] buffer = decoder.decodeBuffer(privateKeyStr);
PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(buffer);
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
this.privateKey = (RSAPrivateKey)keyFactory.generatePrivate(keySpec);
}
catch (NoSuchAlgorithmException e) {
throw new Exception("");
} catch (InvalidKeySpecException e) {
e.printStackTrace();
throw new Exception("");
} catch (IOException e) {
e.printStackTrace();
throw new Exception("");
}
}
public String rsaEncrypt(String text) throws Exception {
if (this.publicKey == null) {
throw new Exception("");
}
Cipher cipher = null;
String encryptStr = null;
try {
cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
cipher.init(Cipher.ENCRYPT_MODE, this.publicKey);
byte[] textData = text.getBytes("utf-8");
byte[] encryptData = cipher.doFinal(text.getBytes("utf-8"));
encryptStr = new BASE64Encoder().encodeBuffer(encryptData);
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (NoSuchPaddingException e) {
e.printStackTrace();
} catch (InvalidKeyException e) {
e.printStackTrace();
}
return encryptStr;
}
public String rsaDecrypt(String text) throws Exception {
if (this.privateKey == null) {
throw new Exception("");
}
Cipher cipher = null;
String decryptStr = null;
try {
cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
cipher.init(Cipher.DECRYPT_MODE, this.privateKey);
byte[] encryptData = new BASE64Decoder().decodeBuffer(text);
byte[] decryptData = cipher.doFinal(encryptData);
decryptStr = new String(decryptData);
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (NoSuchPaddingException e) {
e.printStackTrace();
} catch (InvalidKeyException e) {
e.printStackTrace();
}
return decryptStr;
}
public static String desEncrypt(String text, String key) throws Exception {
Cipher cipher = null;
String encryptStr = null;
try {
byte[] iv = {1, 2, 3, 4, 5, 6, 7, 8};
IvParameterSpec ivParameterSpec = new IvParameterSpec(iv);
cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
DESKeySpec desKeySpec = new DESKeySpec(key.getBytes());
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
SecretKey secretKey = keyFactory.generateSecret(desKeySpec);
cipher.init(Cipher.ENCRYPT_MODE, secretKey, ivParameterSpec);
byte[] encryptData = cipher.doFinal(text.getBytes());
encryptStr = new BASE64Encoder().encode(encryptData);
} catch (Exception e) {
e.printStackTrace();
}
return encryptStr;
}
public static String desDecrypt(String text, String key) throws Exception {
Cipher cipher = null;
String decryptStr = null;
try {
byte[] iv = {1, 2, 3, 4, 5, 6, 7, 8};
IvParameterSpec ivParameterSpec = new IvParameterSpec(iv);
cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
DESKeySpec desKeySpec = new DESKeySpec(key.getBytes());
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
SecretKey secretKey = keyFactory.generateSecret(desKeySpec);
cipher.init(Cipher.DECRYPT_MODE, secretKey, ivParameterSpec);
byte[] encryptData = new BASE64Decoder().decodeBuffer(text);
byte[] decryptData = cipher.doFinal(encryptData);
decryptStr = new String(decryptData);
} catch (Exception e) {
e.printStackTrace();
}
return decryptStr;
}
}
|
package jenkins.metrics.api;
import com.codahale.metrics.DerivativeGauge;
import com.codahale.metrics.Gauge;
import com.codahale.metrics.MetricFilter;
import com.codahale.metrics.MetricRegistry;
import com.codahale.metrics.MetricSet;
import com.codahale.metrics.Timer;
import com.codahale.metrics.health.HealthCheck;
import com.codahale.metrics.health.HealthCheck.Result;
import com.codahale.metrics.health.HealthCheckRegistry;
import com.infradna.tool.bridge_method_injector.WithBridgeMethods;
import hudson.init.InitMilestone;
import hudson.init.Initializer;
import jenkins.metrics.impl.MetricsFilter;
import edu.umd.cs.findbugs.annotations.CheckForNull;
import edu.umd.cs.findbugs.annotations.NonNull;
import hudson.Extension;
import hudson.Plugin;
import hudson.model.PeriodicWork;
import hudson.model.TaskListener;
import hudson.security.ACL;
import hudson.security.Permission;
import hudson.security.PermissionGroup;
import hudson.security.PermissionScope;
import hudson.util.PluginServletFilter;
import hudson.util.StreamTaskListener;
import hudson.util.TimeUnit2;
import jenkins.model.Jenkins;
import jenkins.metrics.util.HealthChecksThreadPool;
import org.kohsuke.accmod.Restricted;
import org.kohsuke.accmod.restrictions.NoExternalUse;
import org.kohsuke.stapler.HttpResponse;
import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.SortedMap;
import java.util.TreeMap;
import java.util.TreeSet;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Future;
import java.util.concurrent.RejectedExecutionException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.annotation.Nonnull;
import static com.codahale.metrics.MetricRegistry.name;
/**
* Entry point for all things metrics.
*/
public class Metrics extends Plugin {
/**
* The frequency with which to run health checks.
*/
public static final int HEALTH_CHECK_INTERVAL_MINS =
Integer.getInteger(Metrics.class.getName() + ".HEALTH_CHECK_INTERVAL_MINS", 1);
public static final PermissionGroup PERMISSIONS =
new PermissionGroup(Metrics.class, Messages._Metrics_PermissionGroup());
public static final Permission VIEW = new Permission(PERMISSIONS,
"View", Messages._Metrics_ViewPermission_Description(), Jenkins.ADMINISTER, PermissionScope.JENKINS);
public static final Permission THREAD_DUMP = new Permission(PERMISSIONS,
"ThreadDump", Messages._Metrics_ThreadDumpPermission_Description(), Jenkins.ADMINISTER, PermissionScope.JENKINS);
public static final Permission HEALTH_CHECK = new Permission(PERMISSIONS,
"HealthCheck", Messages._Metrics_HealthCheckPermission_Description(), Jenkins.ADMINISTER, PermissionScope.JENKINS);
/**
* Our logger.
*/
private static final Logger LOGGER = Logger.getLogger(Metrics.class.getName());
/**
* Thread pool for running health checks.
*/
private static ExecutorService threadPoolForHealthChecks;
/**
* The registry of metrics.
*/
private transient final MetricRegistry metricRegistry = new MetricRegistry();
/**
* The registry of health checks.
*/
private transient final HealthCheckRegistry healthCheckRegistry = new HealthCheckRegistry();
/**
* The servlet filter.
*/
private transient final MetricsFilter filter = new MetricsFilter();
/**
* Returns the {@link HealthCheckRegistry} for the current {@link Jenkins}.
*
* @return the {@link HealthCheckRegistry} for the current {@link Jenkins}
* @throws AssertionError if there is no {@link Jenkins} or {@link Metrics} or {@link HealthCheckRegistry}
*/
@NonNull
public static HealthCheckRegistry healthCheckRegistry() {
Jenkins jenkins = Jenkins.getInstance();
Metrics plugin = jenkins == null ? null : jenkins.getPlugin(Metrics.class);
if (plugin == null || plugin.healthCheckRegistry == null) {
throw new AssertionError(Metrics.class.getName() + " is missing its HealthCheckRegistry");
}
return plugin.healthCheckRegistry;
}
/**
* Get the last health check results
*
* @return a map with health check name -> health check result
*/
@Nonnull
public static SortedMap<String, Result> getHealthCheckResults() {
Jenkins jenkins = Jenkins.getInstance();
if (jenkins == null) {
LOGGER.warning("Unable to get health check results, client master is not ready (startup or shutdown)");
return new TreeMap<String, Result>();
}
HealthChecker healthChecker = jenkins.getExtensionList(PeriodicWork.class).get(HealthChecker.class);
if (healthChecker == null) {
LOGGER.warning("Unable to get health check results, HealthChecker is not available");
return new TreeMap<String, Result>();
}
return healthChecker.getHealthCheckResults();
}
/**
* Returns the {@link MetricRegistry} for the current {@link Jenkins}.
*
* @return the {@link MetricRegistry} for the current {@link Jenkins}
* @throws AssertionError if there is no {@link Jenkins} or {@link Metrics} or {@link MetricRegistry}
*/
@NonNull
public static MetricRegistry metricRegistry() {
Jenkins jenkins = Jenkins.getInstance();
Metrics plugin = jenkins == null ? null : jenkins.getPlugin(Metrics.class);
if (plugin == null || plugin.metricRegistry == null) {
throw new AssertionError(Metrics.class.getName() + " is missing its MetricRegistry");
}
return plugin.metricRegistry;
}
/**
* Checks an access key.
*
* @param accessKey the access key.
*/
public static void checkAccessKey(@CheckForNull String accessKey) {
Jenkins jenkins = Jenkins.getInstance();
MetricsAccessKey.DescriptorImpl descriptor = jenkins == null
? null
: jenkins.getDescriptorByType(MetricsAccessKey.DescriptorImpl.class);
if (descriptor == null) {
throw new IllegalStateException();
}
descriptor.checkAccessKey(accessKey);
}
/**
* Checks an access key.
*
* @param accessKey the access key.
*/
public static void checkAccessKeyPing(@CheckForNull String accessKey) {
Jenkins jenkins = Jenkins.getInstance();
MetricsAccessKey.DescriptorImpl descriptor = jenkins == null
? null
: jenkins.getDescriptorByType(MetricsAccessKey.DescriptorImpl.class);
if (descriptor == null) {
throw new IllegalStateException();
}
descriptor.checkAccessKeyPing(accessKey);
}
/**
* Checks an access key.
*
* @param accessKey the access key.
*/
public static void checkAccessKeyThreadDump(@CheckForNull String accessKey) {
Jenkins jenkins = Jenkins.getInstance();
MetricsAccessKey.DescriptorImpl descriptor = jenkins == null
? null
: jenkins.getDescriptorByType(MetricsAccessKey.DescriptorImpl.class);
if (descriptor == null) {
throw new IllegalStateException();
}
descriptor.checkAccessKeyThreadDump(accessKey);
}
/**
* Checks an access key.
*
* @param accessKey the access key.
*/
public static void checkAccessKeyHealthCheck(@CheckForNull String accessKey) {
Jenkins jenkins = Jenkins.getInstance();
MetricsAccessKey.DescriptorImpl descriptor = jenkins == null
? null
: jenkins.getDescriptorByType(MetricsAccessKey.DescriptorImpl.class);
if (descriptor == null) {
throw new IllegalStateException();
}
descriptor.checkAccessKeyHealthCheck(accessKey);
}
/**
* Checks an access key.
*
* @param accessKey the access key.
*/
public static void checkAccessKeyMetrics(@CheckForNull String accessKey) {
Jenkins jenkins = Jenkins.getInstance();
MetricsAccessKey.DescriptorImpl descriptor = jenkins == null
? null
: jenkins.getDescriptorByType(MetricsAccessKey.DescriptorImpl.class);
if (descriptor == null) {
throw new IllegalStateException();
}
descriptor.checkAccessKeyMetrics(accessKey);
}
public static HttpResponse cors(@CheckForNull String accessKey, final HttpResponse resp) {
Jenkins jenkins = Jenkins.getInstance();
MetricsAccessKey.DescriptorImpl descriptor = jenkins == null
? null
: jenkins.getDescriptorByType(MetricsAccessKey.DescriptorImpl.class);
if (descriptor == null) {
throw new IllegalStateException();
}
return descriptor.cors(accessKey, resp);
}
/**
* Re-indexes all the access keys from the different {@link MetricsAccessKey.Provider} extensions.
*/
public static void reindexAccessKeys() {
Jenkins jenkins = Jenkins.getInstance();
MetricsAccessKey.DescriptorImpl descriptor = jenkins == null
? null
: jenkins.getDescriptorByType(MetricsAccessKey.DescriptorImpl.class);
if (descriptor == null) {
throw new IllegalStateException();
}
descriptor.reindexAccessKeys();
}
/**
* {@inheritDoc}
*/
@Override
public void start() throws Exception {
PluginServletFilter.addFilter(filter);
}
/**
* Initializes all the metrics providers and health check providers. Ideally we would like this to be called
* earlier but there are occasional deadlocks that can arise if we attempt to enumerate the extensions prior
* to {@link InitMilestone#EXTENSIONS_AUGMENTED} so we had to move this functionality out of
* {@link #postInitialize()}
*/
@Initializer(after = InitMilestone.EXTENSIONS_AUGMENTED, before = InitMilestone.JOB_LOADED)
public static void afterExtensionsAugmented() {
LOGGER.log(Level.FINER, "Registering metric provider and health check provider extensions...");
Jenkins jenkins = Jenkins.getInstance();
Metrics plugin = jenkins == null ? null : jenkins.getPlugin(Metrics.class);
if (plugin == null) {
LOGGER.log(Level.WARNING, "Could not register metrics providers or health check providers as "
+ "metrics plugin appears to be disabled");
return;
}
if (plugin.metricRegistry == null || plugin.healthCheckRegistry == null) {
LOGGER.log(Level.WARNING, "Could not register metrics providers or health check providers as "
+ "metrics plugin appears have failed initialization");
return;
}
LOGGER.log(Level.FINER, "Confirmed metrics plugin initialized");
for (MetricProvider p : Jenkins.getInstance().getExtensionList(MetricProvider.class)) {
LOGGER.log(Level.FINER, "Registering metric provider {0} (type {1})", new Object[]{p, p.getClass()});
plugin.metricRegistry.registerAll(p.getMetricSet());
}
for (HealthCheckProvider p : Jenkins.getInstance().getExtensionList(HealthCheckProvider.class)) {
LOGGER.log(Level.FINER, "Registering health check provider {0} (type {1})", new Object[]{p, p.getClass()});
Map<String, HealthCheck> healthChecks = p.getHealthChecks();
for (Map.Entry<String, HealthCheck> c : healthChecks.entrySet()) {
plugin.healthCheckRegistry.register(c.getKey(), c.getValue());
}
LOGGER.log(Level.FINER, "Registered health check provider {0} (type {1}) with {2} checks: {3}",
new Object[] { p, p.getClass(), healthChecks.size(), healthChecks.keySet() });
}
threadPoolForHealthChecks = new HealthChecksThreadPool(healthCheckRegistry());
LOGGER.log(Level.FINE, "Metric provider and health check provider extensions registered");
}
/**
* {@inheritDoc}
*/
@Override
public void stop() throws Exception {
if (filter != null) {
PluginServletFilter.removeFilter(filter);
}
metricRegistry.removeMatching(MetricFilter.ALL);
for (String name : healthCheckRegistry.getNames()) {
healthCheckRegistry.unregister(name);
}
}
/**
* provides the health check related metrics.
*
* @deprecated use HealthCheckMetricsProvider
*/
@Deprecated
@Restricted(NoExternalUse.class)
public static class HeathCheckMetricsProvider extends HealthCheckMetricsProvider {
}
/**
* provides the health check related metrics.
*/
@Extension
public static class HealthCheckMetricsProvider extends MetricProvider {
/**
* {@inheritDoc}
*/
@NonNull
@Override
public MetricSet getMetricSet() {
HealthChecker c =
Jenkins.getInstance().getExtensionList(PeriodicWork.class).get(HealthChecker.class);
return metrics(
metric(name("jenkins", "health-check", "duration"), c.getHealthCheckDuration()),
metric(name("jenkins", "health-check", "count"), c.getHealthCheckCount()),
metric(name("jenkins", "health-check", "score"), c.getHealthCheckScore()),
metric(name("jenkins", "health-check", "inverse-score"), new DerivativeGauge<Double, Double>(c.getHealthCheckScore()) {
@Override
protected Double transform(Double value) {
return value == null ? null : 1.0 - value;
}
})
);
}
}
/**
* Performs the periodic running of health checks and re-indexing of access keys.
*/
@Extension
public static class HealthChecker extends PeriodicWork {
private final Timer healthCheckDuration = new Timer();
private SortedMap<String, HealthCheck.Result> healthCheckResults = new TreeMap<String, HealthCheck.Result>();
private final Gauge<Integer> healthCheckCount = new Gauge<Integer>() {
public Integer getValue() {
return healthCheckRegistry().getNames().size();
}
};
private final Gauge<Double> healthCheckScore = new Gauge<Double>() {
public Double getValue() {
return score;
}
};
private Future<?> future;
private volatile double score = 1.0;
private volatile Set<String> lastUnhealthy = null;
public HealthChecker() {
super();
}
public long getRecurrencePeriod() {
return TimeUnit2.MINUTES.toMillis(Math.min(Math.max(1, HEALTH_CHECK_INTERVAL_MINS),
TimeUnit2.DAYS.toMinutes(1)));
}
public Timer getHealthCheckDuration() {
return healthCheckDuration;
}
@WithBridgeMethods(Map.class)
public SortedMap<String, HealthCheck.Result> getHealthCheckResults() {
return healthCheckResults;
}
public Gauge<Integer> getHealthCheckCount() {
return healthCheckCount;
}
public Gauge<Double> getHealthCheckScore() {
return healthCheckScore;
}
/**
* Schedules this periodic work now in a new thread, if one isn't already running.
*/
public final void doRun() {
try {
if (future != null && !future.isDone()) {
logger.log(Level.INFO,
HealthChecker.class.getName() + " thread is still running. Execution aborted.");
return;
}
if (threadPoolForHealthChecks == null) {
LOGGER.info("Health checks thread pool not yet initialized, skipping until next execution");
return;
}
future = threadPoolForHealthChecks.submit(new Runnable() {
public void run() {
logger.log(Level.FINE, "Started " + HealthChecker.class.getName());
long startTime = System.currentTimeMillis();
StreamTaskListener l = null;
try {
l = new StreamTaskListener(new File(Jenkins.getInstance().getRootDir(),
HealthChecker.class.getName() + ".log"));
ACL.impersonate(ACL.SYSTEM);
execute(l);
} catch (IOException e) {
if (l != null) {
e.printStackTrace(l.fatalError(e.getMessage()));
} else {
logger.log(Level.SEVERE,
HealthChecker.class.getName() + " could not create listener", e);
}
} catch (InterruptedException e) {
e.printStackTrace(l.fatalError("aborted"));
} catch (Exception e) {
logger.log(Level.SEVERE, "Error running " + HealthChecker.class.getName(), e);
if (l != null) {
e.printStackTrace(l.fatalError(e.getMessage()));
}
} finally {
if (l != null) {
l.closeQuietly();
}
}
logger.log(Level.FINE, "Finished " + HealthChecker.class.getName() + ". " +
(System.currentTimeMillis() - startTime) + " ms");
}
});
} catch (Throwable t) {
logger.log(Level.SEVERE, HealthChecker.class.getName() + " thread failed with error", t);
}
}
private void execute(TaskListener listener) throws IOException, InterruptedException {
reindexAccessKeys();
HealthCheckRegistry registry = healthCheckRegistry();
// update the active health checks
Set<String> defined = registry.getNames();
Set<String> removed = new HashSet<String>(defined);
for (HealthCheckProvider p : Jenkins.getInstance().getExtensionList(HealthCheckProvider.class)) {
for (Map.Entry<String, HealthCheck> c : p.getHealthChecks().entrySet()) {
removed.remove(c.getKey());
if (!defined.contains(c.getKey())) {
registry.register(c.getKey(), c.getValue());
defined.add(c.getKey());
}
}
}
for (String key: removed) {
registry.unregister(key);
}
listener.getLogger().println("Starting health checks at " + new Date());
Timer.Context context = healthCheckDuration.time();
SortedMap<String, HealthCheck.Result> results;
try {
results = registry.runHealthChecks(threadPoolForHealthChecks);
} catch (RejectedExecutionException e) {
// should never happen, as we are using a DiscardOldestPolicy in the thread pool queue
listener.error("Health checks execution was rejected instead of queued: {0}", e);
LOGGER.log(Level.WARNING, "Health checks execution was rejected instead of queued: {0}", e);
return;
} finally {
context.stop();
}
listener.getLogger().println("Health check results at " + new Date() + ":");
Set<String> unhealthy = null;
Set<String> unhealthyName = null;
int count = 0;
int total = 0;
for (Map.Entry<String, HealthCheck.Result> e : results.entrySet()) {
count++;
listener.getLogger().println(" * " + e.getKey() + ": " + e.getValue());
healthCheckResults.put(e.getKey(), e.getValue());
if (e.getValue().isHealthy()) {
total++;
} else {
if (unhealthy == null) {
unhealthy = new TreeSet<String>();
unhealthyName = new TreeSet<String>();
}
unhealthy.add(e.getKey() + " : " + e.getValue().getMessage());
unhealthyName.add(e.getKey());
}
}
// delete any result whose health check had been removed
healthCheckResults.keySet().retainAll(results.keySet());
score = total / ((double) count);
Set<String> lastUnhealthy = this.lastUnhealthy;
this.lastUnhealthy = unhealthyName;
if (unhealthy != null) {
if (lastUnhealthy == null || lastUnhealthy.size() < unhealthyName.size() || !lastUnhealthy.equals(unhealthyName)) {
LOGGER.log(Level.WARNING, "Some health checks are reporting as unhealthy: {0}", unhealthy);
} else if (lastUnhealthy.equals(unhealthyName)) {
LOGGER.log(Level.FINE, "Some health checks are reporting as unhealthy: {0}", unhealthy);
} else {
LOGGER.log(Level.INFO, "{0} fewer health checks are reporting as unhealthy: {1}",
new Object[]{lastUnhealthy.size() - unhealthyName.size(), unhealthy});
}
} else if (lastUnhealthy != null) {
LOGGER.log(Level.INFO, "All health checks are reporting as healthy");
}
}
}
}
|
package net.ntg.ftl.parser;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.LinkedHashMap;
import java.util.Map;
import net.blerf.ftl.parser.SavedGameParser;
import net.ntg.ftl.FTLAdventureVisualiser;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.LogManager;
import org.supercsv.io.CsvMapReader;
import org.supercsv.io.CsvMapWriter;
import org.supercsv.io.ICsvMapReader;
import org.supercsv.io.ICsvMapWriter;
import org.supercsv.prefs.CsvPreference;
import org.supercsv.quote.AlwaysQuoteMode; // TODO check if AlwaysQouteMode is actually required
public class ParseCSV {
private static final Logger log = LogManager.getLogger(ParseCSV.class);
private static final CsvPreference FTLCSV = (
new CsvPreference.Builder('"', ';', "\n").useQuoteMode(new AlwaysQuoteMode()).surroundingSpacesNeedQuotes(true).build()
);
public void readCSV(String fileName) {
FTLAdventureVisualiser.recording.clear();
ICsvMapReader mapReader = null;
try {
mapReader = new CsvMapReader(new FileReader(fileName), FTLCSV);
final String[] header = mapReader.getHeader(true);
FTLAdventureVisualiser.recordingHeaders = header;
Map<String,String> customerMap;
while((customerMap = mapReader.read(header)) != null) {
log.info(String.format(
"lineNo=%s, rowNo=%s, customerMap=%s",
mapReader.getLineNumber(),
mapReader.getRowNumber(),
customerMap
));
FTLAdventureVisualiser.recording.add(customerMap);
}
} catch (Exception e) {
log.error("Something went wrong while reading " + fileName, e);
} finally {
if (mapReader != null) {
try {
mapReader.close();
} catch (IOException ex) {
log.error(ex);
}
}
}
}
public static boolean isValidCSV(String fileName) {
// TODO check if CSV file is valid
return true; // EVERYTHING IS FINE!
}
public void createCSV(String fileName) {
writeCSV(fileName, true);
}
public void writeCSV(String fileName) {
writeCSV(fileName, false);
}
private void writeCSV(String fileName, boolean isNewFile) {
int sectorNumber = FTLAdventureVisualiser.gameState.getSectorNumber();
LinkedHashMap<String, String> newRow = new LinkedHashMap<>();
newRow.put("TIME", FTLAdventureVisualiser.fileChangedTimeStamp);
newRow.put("SHIP NAME", FTLAdventureVisualiser.gameState.getPlayerShipName());
newRow.put("SHIP TYPE", ShipDataParser.getFullShipType());
newRow.put("DIFFICULTY", FTLAdventureVisualiser.gameState.getDifficulty().toString());
newRow.put("AE CONTENT", FTLAdventureVisualiser.gameState.isDLCEnabled() ? "enabled" : "disabled");
// Location
newRow.put("BEACON", Integer.toString(FTLAdventureVisualiser.gameState.getTotalBeaconsExplored()));
newRow.put("SECTOR NUMBER", Integer.toString(sectorNumber + 1));
newRow.put("SECTOR TYPE", FTLAdventureVisualiser.sectorArray.get(sectorNumber).getType());
newRow.put("SECTOR TITLE", FTLAdventureVisualiser.sectorArray.get(sectorNumber).getTitle());
newRow.put("FLEET ADVANCEMENT", ShipDataParser.getRebelFleetAdvancement() + "%");
// Log
newRow.put("TOTAL SHIPS DEFEATED", Integer.toString(FTLAdventureVisualiser.gameState.getTotalShipsDefeated()));
newRow.put("TOTAL SCRAP COLLECTED", Integer.toString(FTLAdventureVisualiser.gameState.getTotalScrapCollected()));
newRow.put("TOTAL CREW HIRED", Integer.toString(FTLAdventureVisualiser.gameState.getTotalCrewHired()));
newRow.put("SCORE", Integer.toString(ShipDataParser.getCurrentScore()));
// Encounter
newRow.put("HAZARDS", "\"" + ShipDataParser.getBeaconHazards() + "\"");
newRow.put("EVENT TEXT", "\"" + FTLAdventureVisualiser.gameState.getEncounter().getText().replaceAll("(\")|(\\n+)","") + "\"");
newRow.put("STORE", "\"" + ShipDataParser.getStoreListing() + "\"");
// Supplies
newRow.put("SCRAP", Integer.toString(FTLAdventureVisualiser.shipState.getScrapAmt()));
newRow.put("HULL", Integer.toString(FTLAdventureVisualiser.shipState.getHullAmt()));
newRow.put("FUEL", Integer.toString(FTLAdventureVisualiser.shipState.getFuelAmt()));
newRow.put("DRONE PARTS", Integer.toString(FTLAdventureVisualiser.shipState.getDronePartsAmt()));
newRow.put("MISSILES", Integer.toString(FTLAdventureVisualiser.shipState.getMissilesAmt()));
newRow.put("CREW SIZE", Integer.toString(FTLAdventureVisualiser.playerCrewState.size()));
newRow.put("CARGO", "\"" + ShipDataParser.getCargoListing() + "\"");
newRow.put("AUGMENTS", "\"" + ShipDataParser.getAugmentListing() + "\"");
newRow.put("OXYGEN LEVEL", Integer.toString(ShipDataParser.getShipOxygenLevel()));
// Systems
newRow.put("POWER CAPACITY", Integer.toString(FTLAdventureVisualiser.shipState.getReservePowerCapacity()));
newRow.put("SHIELD SYSTEM CAPACITY", Integer.toString(FTLAdventureVisualiser.shipState.getSystem(SavedGameParser.SystemType.SHIELDS).getCapacity()));
newRow.put("SHIELD SYSTEM POWER", Integer.toString(FTLAdventureVisualiser.shipState.getSystem(SavedGameParser.SystemType.SHIELDS).getPower()));
newRow.put("SHIELD SYSTEM DAMAGE", Integer.toString(FTLAdventureVisualiser.shipState.getSystem(SavedGameParser.SystemType.SHIELDS).getDamagedBars()));
newRow.put("ENGINE SYSTEM CAPACITY", Integer.toString(FTLAdventureVisualiser.shipState.getSystem(SavedGameParser.SystemType.ENGINES).getCapacity()));
newRow.put("ENGINE SYSTEM POWER", Integer.toString(FTLAdventureVisualiser.shipState.getSystem(SavedGameParser.SystemType.ENGINES).getPower()));
newRow.put("ENGINE SYSTEM DAMAGE", Integer.toString(FTLAdventureVisualiser.shipState.getSystem(SavedGameParser.SystemType.ENGINES).getDamagedBars()));
newRow.put("OXYGEN SYSTEM CAPACITY", Integer.toString(FTLAdventureVisualiser.shipState.getSystem(SavedGameParser.SystemType.OXYGEN).getCapacity()));
newRow.put("OXYGEN SYSTEM POWER", Integer.toString(FTLAdventureVisualiser.shipState.getSystem(SavedGameParser.SystemType.OXYGEN).getPower()));
newRow.put("OXYGEN SYSTEM DAMAGE", Integer.toString(FTLAdventureVisualiser.shipState.getSystem(SavedGameParser.SystemType.OXYGEN).getDamagedBars()));
newRow.put("WEAPONS SYSTEM CAPACITY", Integer.toString(FTLAdventureVisualiser.shipState.getSystem(SavedGameParser.SystemType.WEAPONS).getCapacity()));
newRow.put("WEAPONS SYSTEM POWER", Integer.toString(FTLAdventureVisualiser.shipState.getSystem(SavedGameParser.SystemType.WEAPONS).getPower()));
newRow.put("WEAPONS SYSTEM DAMAGE", Integer.toString(FTLAdventureVisualiser.shipState.getSystem(SavedGameParser.SystemType.WEAPONS).getDamagedBars()));
for (int w = 0; w < ShipDataParser.getWeaponSlotCount(); w++) {
try {
newRow.put("WEAPON SLOT " + (w+1), FTLAdventureVisualiser.shipState.getWeaponList().get(w).getWeaponId().replaceAll("_"," "));
} catch (IndexOutOfBoundsException e) {}
}
newRow.put("DRONE CONTROL SYSTEM CAPACITY", Integer.toString(FTLAdventureVisualiser.shipState.getSystem(SavedGameParser.SystemType.DRONE_CTRL).getCapacity()));
newRow.put("DRONE CONTROL SYSTEM POWER", Integer.toString(FTLAdventureVisualiser.shipState.getSystem(SavedGameParser.SystemType.DRONE_CTRL).getPower()));
newRow.put("DRONE CONTROL SYSTEM DAMAGE", Integer.toString(FTLAdventureVisualiser.shipState.getSystem(SavedGameParser.SystemType.DRONE_CTRL).getDamagedBars()));
for (int d = 0; d < ShipDataParser.getDroneSlotCount(); d++) {
try {
newRow.put("DRONE SLOT " + (d+1), FTLAdventureVisualiser.shipState.getDroneList().get(d).getDroneId().replaceAll("_"," "));
} catch (IndexOutOfBoundsException e) {}
}
newRow.put("MEDBAY SYSTEM CAPACITY", Integer.toString(FTLAdventureVisualiser.shipState.getSystem(SavedGameParser.SystemType.MEDBAY).getCapacity()));
newRow.put("MEDBAY SYSTEM POWER", Integer.toString(FTLAdventureVisualiser.shipState.getSystem(SavedGameParser.SystemType.MEDBAY).getPower()));
newRow.put("MEDBAY SYSTEM DAMAGE", Integer.toString(FTLAdventureVisualiser.shipState.getSystem(SavedGameParser.SystemType.MEDBAY).getDamagedBars()));
newRow.put("TELEPORTER SYSTEM CAPACITY", Integer.toString(FTLAdventureVisualiser.shipState.getSystem(SavedGameParser.SystemType.TELEPORTER).getCapacity()));
newRow.put("TELEPORTER SYSTEM POWER", Integer.toString(FTLAdventureVisualiser.shipState.getSystem(SavedGameParser.SystemType.TELEPORTER).getPower()));
newRow.put("TELEPORTER SYSTEM DAMAGE", Integer.toString(FTLAdventureVisualiser.shipState.getSystem(SavedGameParser.SystemType.TELEPORTER).getDamagedBars()));
newRow.put("CLOAKING SYSTEM CAPACITY", Integer.toString(FTLAdventureVisualiser.shipState.getSystem(SavedGameParser.SystemType.CLOAKING).getCapacity()));
newRow.put("CLOAKING SYSTEM POWER", Integer.toString(FTLAdventureVisualiser.shipState.getSystem(SavedGameParser.SystemType.CLOAKING).getPower()));
newRow.put("CLOAKING SYSTEM DAMAGE", Integer.toString(FTLAdventureVisualiser.shipState.getSystem(SavedGameParser.SystemType.CLOAKING).getDamagedBars()));
newRow.put("ARTILLERY SYSTEM CAPACITY", Integer.toString(FTLAdventureVisualiser.shipState.getSystem(SavedGameParser.SystemType.ARTILLERY).getCapacity()));
newRow.put("ARTILLERY SYSTEM POWER", Integer.toString(FTLAdventureVisualiser.shipState.getSystem(SavedGameParser.SystemType.ARTILLERY).getPower()));
newRow.put("ARTILLERY SYSTEM DAMAGE", Integer.toString(FTLAdventureVisualiser.shipState.getSystem(SavedGameParser.SystemType.ARTILLERY).getDamagedBars()));
newRow.put("CLONEBAY SYSTEM CAPACITY", Integer.toString(FTLAdventureVisualiser.shipState.getSystem(SavedGameParser.SystemType.CLONEBAY).getCapacity()));
newRow.put("CLONEBAY SYSTEM POWER", Integer.toString(FTLAdventureVisualiser.shipState.getSystem(SavedGameParser.SystemType.CLONEBAY).getPower()));
newRow.put("CLONEBAY SYSTEM DAMAGE", Integer.toString(FTLAdventureVisualiser.shipState.getSystem(SavedGameParser.SystemType.CLONEBAY).getDamagedBars()));
newRow.put("MINDCONTROL SYSTEM CAPACITY", Integer.toString(FTLAdventureVisualiser.shipState.getSystem(SavedGameParser.SystemType.MIND).getCapacity()));
newRow.put("MINDCONTROL SYSTEM POWER", Integer.toString(FTLAdventureVisualiser.shipState.getSystem(SavedGameParser.SystemType.MIND).getPower()));
newRow.put("MINDCONTROL SYSTEM DAMAGE", Integer.toString(FTLAdventureVisualiser.shipState.getSystem(SavedGameParser.SystemType.MIND).getDamagedBars()));
newRow.put("HACKING SYSTEM CAPACITY", Integer.toString(FTLAdventureVisualiser.shipState.getSystem(SavedGameParser.SystemType.HACKING).getCapacity()));
newRow.put("HACKING SYSTEM POWER", Integer.toString(FTLAdventureVisualiser.shipState.getSystem(SavedGameParser.SystemType.HACKING).getPower()));
newRow.put("HACKING SYSTEM DAMAGE", Integer.toString(FTLAdventureVisualiser.shipState.getSystem(SavedGameParser.SystemType.HACKING).getDamagedBars()));
newRow.put("PILOT SYSTEM CAPACITY", Integer.toString(FTLAdventureVisualiser.shipState.getSystem(SavedGameParser.SystemType.PILOT).getCapacity()));
newRow.put("PILOT SYSTEM DAMAGE", Integer.toString(FTLAdventureVisualiser.shipState.getSystem(SavedGameParser.SystemType.PILOT).getCapacity()));
newRow.put("SENSOR SYSTEM CAPACITY", Integer.toString(FTLAdventureVisualiser.shipState.getSystem(SavedGameParser.SystemType.SENSORS).getCapacity()));
newRow.put("SENSOR SYSTEM DAMAGE", Integer.toString(FTLAdventureVisualiser.shipState.getSystem(SavedGameParser.SystemType.SENSORS).getDamagedBars()));
newRow.put("DOOR SYSTEM CAPACITY", Integer.toString(FTLAdventureVisualiser.shipState.getSystem(SavedGameParser.SystemType.DOORS).getCapacity()));
newRow.put("DOOR SYSTEM DAMAGE", Integer.toString(FTLAdventureVisualiser.shipState.getSystem(SavedGameParser.SystemType.DOORS).getDamagedBars()));
newRow.put("BATTERY SYSTEM CAPACITY", Integer.toString(FTLAdventureVisualiser.shipState.getSystem(SavedGameParser.SystemType.BATTERY).getCapacity()));
newRow.put("BATTERY SYSTEM DAMAGE", Integer.toString(FTLAdventureVisualiser.shipState.getSystem(SavedGameParser.SystemType.BATTERY).getDamagedBars()));
// crew
for (int c = 0; c < FTLAdventureVisualiser.gameState.getTotalCrewHired(); c++) {
try {
newRow.put("CREW MEMBER " + (c+1) + " NAME", FTLAdventureVisualiser.playerCrewState.get(c).getName());
newRow.put("CREW MEMBER " + (c+1) + " SPECIES", ShipDataParser.getFullCrewType(c));
newRow.put("CREW MEMBER " + (c+1) + " HEALTH", Integer.toString(FTLAdventureVisualiser.playerCrewState.get(c).getHealth()));
newRow.put("CREW MEMBER " + (c+1) + " PILOT SKILL", Integer.toString(FTLAdventureVisualiser.playerCrewState.get(c).getPilotSkill()));
newRow.put("CREW MEMBER " + (c+1) + " ENGINE SKILL", Integer.toString(FTLAdventureVisualiser.playerCrewState.get(c).getEngineSkill()));
newRow.put("CREW MEMBER " + (c+1) + " SHIELD SKILL", Integer.toString(FTLAdventureVisualiser.playerCrewState.get(c).getShieldSkill()));
newRow.put("CREW MEMBER " + (c+1) + " WEAPON SKILL", Integer.toString(FTLAdventureVisualiser.playerCrewState.get(c).getWeaponSkill()));
newRow.put("CREW MEMBER " + (c+1) + " REPAIR SKILL", Integer.toString(FTLAdventureVisualiser.playerCrewState.get(c).getRepairSkill()));
newRow.put("CREW MEMBER " + (c+1) + " COMBAT SKILL", Integer.toString(FTLAdventureVisualiser.playerCrewState.get(c).getCombatSkill()));
newRow.put("CREW MEMBER " + (c+1) + " REPAIRS", Integer.toString(FTLAdventureVisualiser.playerCrewState.get(c).getRepairs()));
newRow.put("CREW MEMBER " + (c+1) + " COMBAT KILLS", Integer.toString(FTLAdventureVisualiser.playerCrewState.get(c).getCombatKills()));
newRow.put("CREW MEMBER " + (c+1) + " PILOTED EVASIONS", Integer.toString(FTLAdventureVisualiser.playerCrewState.get(c).getPilotedEvasions()));
newRow.put("CREW MEMBER " + (c+1) + " JUMPS SURVIVED", Integer.toString(FTLAdventureVisualiser.playerCrewState.get(c).getJumpsSurvived()));
newRow.put("CREW MEMBER " + (c+1) + " SKILLS MASTERED", Integer.toString(FTLAdventureVisualiser.playerCrewState.get(c).getSkillMasteries()));
} catch (IndexOutOfBoundsException e) {}
}
FTLAdventureVisualiser.recording.add((Map<String,String>) newRow);
String[] header = (String[]) newRow.keySet().toArray(new String[newRow.size()]);
// TODO use superCSV mapWriter to write the data (so it doesn't print null where it is empty or doesn't apply qoutes where needed)
// change Fileheader to a map cunstructor that assembles header + new data at the same time
// fileHeader.put("SENSORS SYSTEM DAMAGE", Integer.toString(FTLAdventureVisualiser.shipState.getSystem(SavedGameParser.SystemType.SENSORS).getDamagedBars()));
// then append the result FTLAdventureVisualiser.recording.add(fileHeader)
// then a loop writes FTLAdventureVisualiser.recording.get(i) to the CSV file, using the header of the last entry of FTLAdventureVisualiser.recording keys
// TODO prevent duplicate rows
ICsvMapWriter mapWriter = null;
try {
mapWriter = new CsvMapWriter(new FileWriter(fileName), FTLCSV);
// writer header
mapWriter.writeHeader(header);
// write all entries
for (int i = 0; i < FTLAdventureVisualiser.recording.size(); i++) {
// try {
// if (!FTLAdventureVisualiser.recording.get(i).equals(FTLAdventureVisualiser.recording.get(i+1))) {
mapWriter.write(FTLAdventureVisualiser.recording.get(i), header);
// } catch (IndexOutOfBoundsException e) {}
}
} catch (Exception e) {
log.error("Something went wrong while writing " + fileName, e);
} finally {
try {
mapWriter.close();
} catch (IOException ex) {
log.error("Something went wrong closing fileWriter", ex);
}
}
}
}
|
package org.basex.query.func;
import static org.basex.query.QueryTokens.*;
import static org.basex.query.item.SeqType.*;
import org.basex.query.expr.Expr;
import org.basex.query.item.SeqType;
import org.basex.util.InputInfo;
import org.basex.util.Util;
public enum FunDef {
/* FNAcc functions. */
/** XQuery function. */
POS(FNURI, FNAcc.class, 0, 0, "position()", ITR),
/** XQuery function. */
LAST(FNURI, FNAcc.class, 0, 0, "last()", ITR),
/** XQuery function. */
STRING(FNURI, FNAcc.class, 0, 1, "string(item?)", STR),
/** XQuery function. */
NUMBER(FNURI, FNAcc.class, 0, 1, "number(item?)", ITR),
/** XQuery function. */
STRLEN(FNURI, FNAcc.class, 0, 1, "string-length(item?)", ITR),
/** XQuery function. */
NORM(FNURI, FNAcc.class, 0, 1, "normalize-space(string?)", STR),
/** XQuery function. */
URIQNAME(FNURI, FNAcc.class, 1, 1, "namespace-uri-from-QName(qname)", URI_ZO),
/* FNAggr functions. */
/** XQuery function. */
AVG(FNURI, FNAggr.class, 1, 1, "avg(item)", ITEM_ZO),
/** XQuery function. */
COUNT(FNURI, FNAggr.class, 1, 1, "count(item)", ITR),
/** XQuery function. */
MAX(FNURI, FNAggr.class, 1, 2, "max(item, coll?)", ITEM_ZO),
/** XQuery function. */
MIN(FNURI, FNAggr.class, 1, 2, "min(item, coll?)", ITEM_ZO),
/** XQuery function. */
SUM(FNURI, FNAggr.class, 1, 2, "sum(item, zero?)", ITEM_ZO),
/* FNContext functions. */
/** XQuery function. */
CURRDATE(FNURI, FNContext.class, 0, 0, "current-date()", DAT),
/** XQuery function. */
CURRDTM(FNURI, FNContext.class, 0, 0, "current-dateTime()", DAT),
/** XQuery function. */
CURRTIME(FNURI, FNContext.class, 0, 0, "current-time()", DAT),
/** XQuery function. */
IMPLZONE(FNURI, FNContext.class, 0, 0, "implicit-timezone()", DAT),
/** XQuery function. */
COLLAT(FNURI, FNContext.class, 0, 0, "default-collation()", STR),
/** XQuery function. */
STBASEURI(FNURI, FNContext.class, 0, 0, "static-base-uri()", URI_ZO),
/* FNDate functions. */
/** XQuery function. */
DAYDAT(FNURI, FNDate.class, 1, 1, "day-from-date(item)", ITR_ZO),
/** XQuery function. */
DAYDTM(FNURI, FNDate.class, 1, 1, "day-from-dateTime(datetime)", ITR_ZO),
/** XQuery function. */
DAYDUR(FNURI, FNDate.class, 1, 1, "days-from-duration(dur)", ITR_ZO),
/** XQuery function. */
HOUDTM(FNURI, FNDate.class, 1, 1, "hours-from-dateTime(datetime)", ITR_ZO),
/** XQuery function. */
HOUDUR(FNURI, FNDate.class, 1, 1, "hours-from-duration(dur)", ITR_ZO),
/** XQuery function. */
HOUTIM(FNURI, FNDate.class, 1, 1, "hours-from-time(item)", ITR_ZO),
/** XQuery function. */
MINDTM(FNURI, FNDate.class, 1, 1, "minutes-from-dateTime(datetime)", ITR_ZO),
/** XQuery function. */
MINDUR(FNURI, FNDate.class, 1, 1, "minutes-from-duration(dur)", ITR_ZO),
/** XQuery function. */
MINTIM(FNURI, FNDate.class, 1, 1, "minutes-from-time(item)", ITR_ZO),
/** XQuery function. */
MONDAT(FNURI, FNDate.class, 1, 1, "month-from-date(item)", ITR_ZO),
/** XQuery function. */
MONDTM(FNURI, FNDate.class, 1, 1, "month-from-dateTime(datetime)", ITR_ZO),
/** XQuery function. */
MONDUR(FNURI, FNDate.class, 1, 1, "months-from-duration(dur)", ITR_ZO),
/** XQuery function. */
SECDTM(FNURI, FNDate.class, 1, 1, "seconds-from-dateTime(datetime)", ITR_ZO),
/** XQuery function. */
SECDUR(FNURI, FNDate.class, 1, 1, "seconds-from-duration(dur)", ITR_ZO),
/** XQuery function. */
SECTIM(FNURI, FNDate.class, 1, 1, "seconds-from-time(item)", ITR_ZO),
/** XQuery function. */
ZONDAT(FNURI, FNDate.class, 1, 1, "timezone-from-date(item)", DAT_ZM),
/** XQuery function. */
ZONDTM(FNURI, FNDate.class, 1, 1, "timezone-from-dateTime(item)", DAT_ZM),
/** XQuery function. */
ZONTIM(FNURI, FNDate.class, 1, 1, "timezone-from-time(item)", DAT_ZM),
/** XQuery function. */
YEADAT(FNURI, FNDate.class, 1, 1, "year-from-date(item)", ITR_ZO),
/** XQuery function. */
YEADTM(FNURI, FNDate.class, 1, 1, "year-from-dateTime(datetime)", ITR_ZO),
/** XQuery function. */
YEADUR(FNURI, FNDate.class, 1, 1, "years-from-duration(dur)", ITR_ZO),
/** XQuery function. */
DATZON(FNURI, FNDate.class, 1, 2, "adjust-date-to-timezone(date, zone?)",
DAT_ZM),
/** XQuery function. */
DTMZON(FNURI, FNDate.class, 1, 2, "adjust-dateTime-to-timezone(date, zone?)",
DAT_ZM),
/** XQuery function. */
TIMZON(FNURI, FNDate.class, 1, 2, "adjust-time-to-timezone(date, zone?)",
DAT_ZM),
/** XQuery function. */
DATETIME(FNURI, FNDate.class, 2, 2, "dateTime(date, time)", DAT_ZM),
/* FNFormat functions. */
/** XQuery function. */
FORMINT(FNURI, FNFormat.class, 2, 3,
"format-integer(number, picture, lang?)", STR),
/** XQuery function. */
FORMNUM(FNURI, FNFormat.class, 2, 3, "format-number(number, picture, name?)",
STR),
/** XQuery function. */
FORMDTM(FNURI, FNFormat.class, 2, 5,
"format-dateTime(number, picture, lang?, cal?, place?)", STR),
/** XQuery function. */
FORMDAT(FNURI, FNFormat.class, 2, 5,
"format-date(number, picture, lang?, cal?, place?)", STR),
/** XQuery function. */
FORMTIM(FNURI, FNFormat.class, 2, 5,
"format-time(number, picture, lang?, cal?, place?)", STR),
/* FNFunc functions. */
/** XQuery function. */
FILTER(FNURI, FNFunc.class, 2, 2, "filter(function, seq)", ITEM_ZM),
/** XQuery function. */
FUNCNAME(FNURI, FNFunc.class, 1, 1, "function-name(function)", STR),
/** XQuery function. */
FUNCARITY(FNURI, FNFunc.class, 1, 1, "function-arity(function)", ITR),
/** XQuery function. */
MAP(FNURI, FNFunc.class, 2, 2, "map(function, seq)", ITEM_ZM),
/** XQuery function. */
MAPPAIRS(FNURI, FNFunc.class, 2, 2, "map-pairs(function, seq1, seq2)",
ITEM_ZM),
/** XQuery function. */
FOLDLEFT(FNURI, FNFunc.class, 3, 3, "fold-left(function, zero, seq)",
ITEM_ZM),
/** XQuery function. */
FOLDRIGHT(FNURI, FNFunc.class, 3, 3, "fold-right(function, zero, seq)",
ITEM_ZM),
/* FNGen functions. */
/** XQuery function. */
DATA(FNURI, FNGen.class, 0, 1, "data(item?)", ITEM_ZM),
/** XQuery function. */
COLL(FNURI, FNGen.class, 0, 1, "collection(string?)", NOD_ZM),
/** XQuery function. */
DOC(FNURI, FNGen.class, 1, 1, "doc(string)", NOD_ZO),
/** XQuery function. */
DOCAVL(FNURI, FNGen.class, 1, 1, "doc-available(string)", BLN),
/** XQuery function. */
PUT(FNURI, FNGen.class, 2, 2, "put(node, string)", ITEM_ZM),
/** XQuery function. */
PARSETXT(FNURI, FNGen.class, 1, 2, "unparsed-text(uri, encoding?)", STR_ZO),
/** XQuery function. */
PARSETXTAVL(FNURI, FNGen.class, 1, 2,
"unparsed-text-available(uri, encoding?)", BLN),
/** XQuery function (might get obsolete). */
PARSE(FNURI, FNGen.class, 1, 2, "parse(string, base?)", NOD),
/** XQuery function. */
PARSEXML(FNURI, FNGen.class, 1, 2, "parse-xml(string, base?)", NOD),
/** XQuery function. */
URICOLL(FNURI, FNGen.class, 0, 1, "uri-collection(string?)", URI_ZM),
/** XQuery function. */
SERIALIZE(FNURI, FNGen.class, 1, 2, "serialize(node, params?)", NOD),
/* FNId functions. */
/** XQuery function. */
ID(FNURI, FNId.class, 1, 2, "id(string, item?)", NOD_ZM),
/** XQuery function. */
IDREF(FNURI, FNId.class, 1, 2, "idref(string, item?)", NOD_ZM),
/** XQuery function. */
LANG(FNURI, FNId.class, 1, 2, "lang(string, item?)", BLN),
/** XQuery function. */
ELID(FNURI, FNId.class, 1, 2, "element-with-id(string, item?)", NOD_ZM),
/* FNNode functions. */
/** XQuery function. */
DOCURI(FNURI, FNNode.class, 0, 1, "document-uri(node?)", URI_ZO),
/** XQuery function. */
NILLED(FNURI, FNNode.class, 1, 1, "nilled(node)", BLN_ZO),
/** XQuery function. */
NODENAME(FNURI, FNNode.class, 0, 1, "node-name(node?)", QNM_ZO),
/** XQuery function. */
LOCNAME(FNURI, FNNode.class, 0, 1, "local-name(node?)", STR),
/** XQuery function. */
NAME(FNURI, FNNode.class, 0, 1, "name(node?)", STR),
/** XQuery function. */
NSURI(FNURI, FNNode.class, 0, 1, "namespace-uri(node?)", URI),
/** XQuery function. */
ROOT(FNURI, FNNode.class, 0, 1, "root(node?)", NOD_ZO),
/** XQuery function. */
BASEURI(FNURI, FNNode.class, 0, 1, "base-uri(node?)", URI_ZO),
/** XQuery function. */
GENID(FNURI, FNNode.class, 0, 1, "generate-id(node?)", STR),
/* FNFile functions */
/** XQuery function */
FILEEXISTS(FILEURI, FNFile.class, 1, 1, "file-exists(path)", BLN),
/** XQuery function */
ISDIR(FILEURI, FNFile.class, 1, 1, "is-directory(path)", BLN),
/** XQuery function */
ISFILE(FILEURI, FNFile.class, 1, 1, "is-file(path)", BLN),
/** XQuery function */
ISREAD(FILEURI, FNFile.class, 1, 1, "is-readable(filepath)", BLN),
/** XQuery function */
ISWRITE(FILEURI, FNFile.class, 1, 1, "is-writeable(filepath)", BLN),
/** XQuery function */
LASTMOD(FILEURI, FNFile.class, 1, 1, "last-modified(path)", DAT),
/** XQuery function */
SIZE(FILEURI, FNFile.class, 1, 1, "size(path)", ITR),
/** XQuery function */
FILES(FILEURI, FNFile.class, 1, 2, "files(path, pattern?)", STR_ZM),
/** XQuery function */
PATHSEP(FILEURI, FNFile.class, 0, 0, "path-separator()", STR),
/** XQuery function */
PATHTOFULL(FILEURI, FNFile.class, 1, 1, "path-to-full-path(path)", STR),
/** XQuery function */
PATHTOURI(FILEURI, FNFile.class, 1, 1, "path-to-uri(path)", URI),
/** XQuery function */
MKDIR(FILEURI, FNFile.class, 1, 1, "mkdir(path)", ITEM_Z),
/** XQuery function */
MKDIRS(FILEURI, FNFile.class, 1, 1, "mkdirs(path)", ITEM_Z),
/** XQuery function */
DELETE(FILEURI, FNFile.class, 1, 1, "delete(path)", ITEM_Z),
/** XQuery function */
READFILE(FILEURI, FNFile.class, 1, 2, "read(filepath, encoding?)", STR),
/** XQuery function */
READBIN(FILEURI, FNFile.class, 1, 1, "read-binary(filepath)", B64),
/** XQuery function */
WRITE(FILEURI, FNFile.class, 2, 3, "write(filepath, data, params?)", ITEM_Z),
/** XQuery function */
WRITEBIN(FILEURI, FNFile.class, 2, 2, "write-binary(filepath, data)", ITEM_Z),
/** XQuery function */
COPY(FILEURI, FNFile.class, 2, 2, "copy(path, destination)", ITEM_Z),
/** XQuery function */
MOVE(FILEURI, FNFile.class, 2, 2, "move(path, destination)", ITEM_Z),
/* FNNum functions. */
/** XQuery function. */
ABS(FNURI, FNNum.class, 1, 1, "abs(num)", ITR_ZO),
/** XQuery function. */
CEIL(FNURI, FNNum.class, 1, 1, "ceiling(num)", ITR_ZO),
/** XQuery function. */
FLOOR(FNURI, FNNum.class, 1, 1, "floor(num)", ITR_ZO),
/** XQuery function. */
RND(FNURI, FNNum.class, 1, 2, "round(num, prec?)", ITR_ZO),
/** XQuery function. */
RNDHLF(FNURI, FNNum.class, 1, 2, "round-half-to-even(num, prec?)", ITR_ZO),
/* FNOut functions. */
/** XQuery function. */
ERROR(FNURI, FNInfo.class, 0, 3, "error(code?, desc?, object?)", ITEM_ZM),
/** XQuery function. */
TRACE(FNURI, FNInfo.class, 2, 2, "trace(item, message)", ITEM_ZM),
/** XQuery function. */
ENV(FNURI, FNInfo.class, 1, 1, "get-environment-variable(string)", STR_ZO),
/** XQuery function. */
ENVS(FNURI, FNInfo.class, 0, 0, "available-environment-variables()", STR_ZM),
/* FNPat functions. */
/** XQuery function. */
MATCH(FNURI, FNPat.class, 2, 3, "matches(item, pattern, mod?)", BLN),
/** XQuery function. */
REPLACE(FNURI, FNPat.class, 3, 4, "replace(item, pattern, replace, mod?)",
STR),
/** XQuery function. */
TOKEN(FNURI, FNPat.class, 2, 3, "tokenize(item, pattern, mod?)", STR_ZM),
/** XQuery function. */
ANALZYE(FNURI, FNPat.class, 2, 3, "analyze-string(input, pattern, mod?)",
NOD),
/* FNQName functions. */
/** XQuery function. */
INSCOPE(FNURI, FNQName.class, 1, 1, "in-scope-prefixes(elem)", STR_ZM),
/** XQuery function. */
LOCNAMEQNAME(FNURI, FNQName.class, 1, 1, "local-name-from-QName(qname)",
STR_ZO),
/** XQuery function. */
NSURIPRE(FNURI, FNQName.class, 2, 2, "namespace-uri-for-prefix(pref, elem)",
URI_ZO),
/** XQuery function. */
QNAME(FNURI, FNQName.class, 2, 2, "QName(uri, name)", QNM),
/** XQuery function. */
PREQNAME(FNURI, FNQName.class, 1, 1, "prefix-from-QName(qname)", STR_ZO),
/** XQuery function. */
RESQNAME(FNURI, FNQName.class, 2, 2, "resolve-QName(item, base)", QNM_ZO),
/** XQuery function. */
RESURI(FNURI, FNQName.class, 1, 2, "resolve-uri(name, elem?)", URI_ZO),
/* FNSeq functions. */
/** XQuery function. */
DISTINCT(FNURI, FNSeq.class, 1, 2, "distinct-values(item, coll?)", ITEM_ZM),
/** XQuery function. */
INDEXOF(FNURI, FNSeq.class, 2, 3, "index-of(seq, item, coll?)", ITR_ZM),
/** XQuery function. */
INSBEF(FNURI, FNSeq.class, 3, 3, "insert-before(seq, pos, seq2)", ITEM_ZM),
/** XQuery function. */
REMOVE(FNURI, FNSeq.class, 2, 2, "remove(seq, position)", ITEM_ZM),
/** XQuery function. */
REVERSE(FNURI, FNSeq.class, 1, 1, "reverse(seq)", ITEM_ZM),
/** XQuery function. */
SUBSEQ(FNURI, FNSeq.class, 2, 3, "subsequence(seq, start, len?)", ITEM_ZM),
/** XQuery function. */
HEAD(FNURI, FNSeq.class, 1, 1, "head(seq)", ITEM_ZO),
/** XQuery function. */
TAIL(FNURI, FNSeq.class, 1, 1, "tail(seq)", ITEM_ZM),
/* FNSimple functions. */
/** XQuery function. */
FALSE(FNURI, FNSimple.class, 0, 0, "false()", BLN),
/** XQuery function. */
TRUE(FNURI, FNSimple.class, 0, 0, "true()", BLN),
/** XQuery function. */
BOOLEAN(FNURI, FNSimple.class, 1, 1, "boolean(item)", BLN),
/** XQuery function. */
NOT(FNURI, FNSimple.class, 1, 1, "not(item)", BLN),
/** XQuery function. */
EMPTY(FNURI, FNSimple.class, 1, 1, "empty(item)", BLN),
/** XQuery function. */
EXISTS(FNURI, FNSimple.class, 1, 1, "exists(item)", BLN),
/** XQuery function. */
UNORDER(FNURI, FNSimple.class, 1, 1, "unordered(item)", ITEM_ZM),
/** XQuery function. */
ZEROORONE(FNURI, FNSimple.class, 1, 1, "zero-or-one(item)", ITEM_ZO),
/** XQuery function. */
EXACTLYONE(FNURI, FNSimple.class, 1, 1, "exactly-one(item)", ITEM),
/** XQuery function. */
ONEORMORE(FNURI, FNSimple.class, 1, 1, "one-or-more(item)", ITEM_OM),
/** XQuery function. */
DEEPEQUAL(FNURI, FNSimple.class, 2, 3, "deep-equal(item, item, coll?)", BLN),
/* FNStr functions. */
/** XQuery function. */
CODEPNT(FNURI, FNStr.class, 2, 2, "codepoint-equal(string, string)", BLN_ZO),
/** XQuery function. */
CODESTR(FNURI, FNStr.class, 1, 1, "codepoints-to-string(num*)", STR),
/** XQuery function. */
COMPARE(FNURI, FNStr.class, 2, 3, "compare(first, second, coll?)", ITR_ZO),
/** XQuery function. */
CONCAT(FNURI, FNStr.class, 2, Integer.MAX_VALUE, "concat(item, item+)", STR),
/** XQuery function. */
CONTAINS(FNURI, FNStr.class, 2, 3, "contains(item, item, coll?)", BLN),
/** XQuery function. */
ENCURI(FNURI, FNStr.class, 1, 1, "encode-for-uri(item)", STR),
/** XQuery function. */
ENDS(FNURI, FNStr.class, 2, 3, "ends-with(item, item, coll?)", BLN),
/** XQuery function. */
ESCURI(FNURI, FNStr.class, 1, 1, "escape-html-uri(item)", STR),
/** XQuery function. */
IRIURI(FNURI, FNStr.class, 1, 1, "iri-to-uri(item)", STR),
/** XQuery function. */
LOWER(FNURI, FNStr.class, 1, 1, "lower-case(item)", STR),
/** XQuery function. */
NORMUNI(FNURI, FNStr.class, 1, 2, "normalize-unicode(string, form?)", STR),
/** XQuery function. */
STARTS(FNURI, FNStr.class, 2, 3, "starts-with(item, item, coll?)", BLN),
/** XQuery function. */
STRJOIN(FNURI, FNStr.class, 1, 2, "string-join(item, sep?)", STR),
/** XQuery function. */
STCODE(FNURI, FNStr.class, 1, 1, "string-to-codepoints(string)", ITR_ZM),
/** XQuery function. */
SUBSTR(FNURI, FNStr.class, 2, 3, "substring(item, start, len?)", STR),
/** XQuery function. */
SUBAFTER(FNURI, FNStr.class, 2, 3, "substring-after(item, sub, coll?)", STR),
/** XQuery function. */
SUBBEFORE(FNURI, FNStr.class, 2, 3, "substring-before(item, sub, coll?)",
STR),
/** XQuery function. */
TRANS(FNURI, FNStr.class, 3, 3, "translate(arg, map, trans)", STR),
/** XQuery function. */
UPPER(FNURI, FNStr.class, 1, 1, "upper-case(item)", STR),
/* FNMath functions. */
/** XQuery math function. */
PI(MATHURI, FNMath.class, 0, 0, "pi()", ITR_ZO),
/** XQuery math function. */
SQRT(MATHURI, FNMath.class, 1, 1, "sqrt(number)", ITR_ZO),
/** XQuery math function. */
SIN(MATHURI, FNMath.class, 1, 1, "sin(number)", ITR_ZO),
/** XQuery math function. */
COS(MATHURI, FNMath.class, 1, 1, "cos(number)", ITR_ZO),
/** XQuery math function. */
TAN(MATHURI, FNMath.class, 1, 1, "tan(number)", ITR_ZO),
/** XQuery math function. */
ASIN(MATHURI, FNMath.class, 1, 1, "asin(number)", ITR_ZO),
/** XQuery math function. */
ACOS(MATHURI, FNMath.class, 1, 1, "acos(number)", ITR_ZO),
/** XQuery math function. */
ATAN(MATHURI, FNMath.class, 1, 1, "atan(number)", ITR_ZO),
/* FNBaseX functions. */
/** Project specific function - evaluates the specified query. */
EVAL(BXURI, FNBaseX.class, 1, 1, "eval(string)", ITEM_ZM),
/** Project specific function - returns a random number. */
RANDOM(BXURI, FNBaseX.class, 0, 0, "random()", ITR),
/** Project specific function - accesses an index. */
INDEX(BXURI, FNBaseX.class, 2, 2, "index(item, type)", NOD_ZM),
/** Project specific function - evaluates the specified query file. */
RUN(BXURI, FNBaseX.class, 1, 1, "run(string)", ITEM_ZM),
/** Project specific function - opens a database node. */
DB(BXURI, FNBaseX.class, 1, 2, "db(string, pre?)", NOD_ZM),
/** Project specific function - returns the id of a node. */
NODEID(BXURI, FNBaseX.class, 1, 1, "node-id(item)", ITR),
/** Project specific function - returns a filesystem path. */
FSPATH(BXURI, FNBaseX.class, 1, 1, "fspath(item)", STR),
/** Project specific function - returns a text sentiment. */
SENT(SENTURI, FNSent.class, 2, 2, "polarity(string, uri)", ITR),
/** Project specific function - returns a normed polarity value. */
NORMSENT(SENTURI, FNSent.class, 2, 2, "normed-polarity(string, uri)", ITR);
/** Function classes. */
final Class<? extends Fun> func;
/** Function uri. */
final byte[] uri;
/** Descriptions. */
final String desc;
/** Minimum number of arguments. */
final int min;
/** Maximum number of arguments. */
final int max;
/** Return type. */
final SeqType ret;
/**
* Constructor.
* @param ur uri
* @param fun function class
* @param mn minimum number of arguments
* @param mx maximum number of arguments
* @param dsc description
* @param rt return value
*/
private FunDef(final byte[] ur, final Class<? extends Fun> fun, final int mn,
final int mx, final String dsc, final SeqType rt) {
uri = ur;
func = fun;
min = mn;
max = mx;
desc = dsc;
ret = rt;
}
/**
* Creates a new instance of the function.
* @param ii input info
* @param e expression array
* @return function
*/
public Fun newInstance(final InputInfo ii, final Expr... e) {
try {
return func.getDeclaredConstructor(InputInfo.class, FunDef.class,
Expr[].class).newInstance(ii, this, e);
} catch(final Exception ex) {
Util.notexpected(ex);
return null;
}
}
@Override
public final String toString() {
return desc;
}
}
|
package org.hcjf.layers.query;
import org.hcjf.bson.BsonDocument;
import org.hcjf.errors.HCJFRuntimeException;
import org.hcjf.layers.Layer;
import org.hcjf.layers.Layers;
import org.hcjf.layers.crud.IdentifiableLayerInterface;
import org.hcjf.layers.crud.ReadRowsLayerInterface;
import org.hcjf.layers.query.functions.*;
import org.hcjf.properties.SystemProperties;
import org.hcjf.service.Service;
import org.hcjf.service.ServiceSession;
import org.hcjf.service.ServiceThread;
import org.hcjf.utils.Introspection;
import org.hcjf.utils.LruMap;
import org.hcjf.utils.NamedUuid;
import org.hcjf.utils.Strings;
import org.hcjf.utils.bson.BsonCustomBuilderLayer;
import org.hcjf.utils.bson.BsonParcelable;
import java.text.ParseException;
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
/**
* This class contains all the parameter needed to create a query.
* This kind of queries works over any data collection.
* @author javaito
*/
public class Query extends EvaluatorCollection implements Queryable {
private static final String QUERY_BSON_FIELD_NAME = "__query__";
private static final LruMap<String,Query> cache;
private final QueryId id;
private final QueryResource resource;
private final List<QueryResource> resources;
private Integer limit;
private Integer underlyingLimit;
private Integer start;
private Integer underlyingStart;
private final List<QueryReturnParameter> groupParameters;
private final List<QueryOrderParameter> orderParameters;
private final List<QueryReturnParameter> returnParameters;
private final List<Join> joins;
private boolean returnAll;
private String stringRepresentation;
static {
//Init query compiler cache
cache = new LruMap<>(SystemProperties.getInteger(SystemProperties.Query.COMPILER_CACHE_SIZE));
//Publishing default function layers...
Layers.publishLayer(MathQueryFunctionLayer.class);
Layers.publishLayer(StringQueryFunctionLayer.class);
Layers.publishLayer(DateQueryFunctionLayer.class);
Layers.publishLayer(ReferenceFunctionLayer.class);
Layers.publishLayer(BsonQueryFunctionLayer.class);
Layers.publishLayer(CollectionQueryFunction.class);
Layers.publishLayer(ObjectQueryFunction.class);
Layers.publishLayer(QueryBsonBuilderLayer.class);
Layers.publishLayer(GeoQueryFunctionLayer.class);
//Publishing default aggregate function layers...
Layers.publishLayer(CountQueryAggregateFunctionLayer.class);
Layers.publishLayer(SumAggregateFunctionLayer.class);
Layers.publishLayer(ProductAggregateFunctionLayer.class);
Layers.publishLayer(MeanAggregateFunctionLayer.class);
Layers.publishLayer(MaxAggregateFunctionLayer.class);
Layers.publishLayer(MinAggregateFunctionLayer.class);
Layers.publishLayer(DistinctQueryAggregateFunction.class);
Layers.publishLayer(GeoUnionAggregateFunctionLayer.class);
Layers.publishLayer(GeoDistanceAggregateFunctionLayer.class);
Layers.publishLayer(EvalExpressionAggregateFunctionLayer.class);
}
public Query(String resource, QueryId id) {
this.id = id;
this.groupParameters = new ArrayList<>();
this.orderParameters = new ArrayList<>();
this.returnParameters = new ArrayList<>();
this.joins = new ArrayList<>();
this.resource = new QueryResource(resource);
this.resources = new ArrayList<>();
this.resources.add(this.resource);
}
public Query(String resource){
this(resource, new QueryId());
}
private Query(Query source) {
super(source);
this.id = new QueryId();
this.resource = source.resource;
this.resources = new ArrayList<>();
this.resources.add(this.resource);
this.limit = source.limit;
this.start = source.start;
this.returnAll = source.returnAll;
this.orderParameters = new ArrayList<>();
this.orderParameters.addAll(source.orderParameters);
this.returnParameters = new ArrayList<>();
this.returnParameters.addAll(source.returnParameters);
this.groupParameters = new ArrayList<>();
this.groupParameters.addAll(source.groupParameters);
this.joins = new ArrayList<>();
this.joins.addAll(source.joins);
}
private QueryParameter checkQueryParameter(QueryParameter queryParameter) {
if(queryParameter instanceof QueryField) {
QueryField queryField = (QueryField) queryParameter;
QueryResource resource = queryField.getResource();
} else if(queryParameter instanceof QueryFunction) {
QueryFunction function = (QueryFunction) queryParameter;
for(Object functionParameter : function.getParameters()) {
if(functionParameter instanceof QueryParameter) {
checkQueryParameter((QueryParameter) functionParameter);
}
}
}
return queryParameter;
}
@Override
protected Evaluator checkEvaluator(Evaluator evaluator) {
if(evaluator instanceof FieldEvaluator) {
FieldEvaluator fieldEvaluator = (FieldEvaluator) evaluator;
if(fieldEvaluator.getLeftValue() instanceof QueryParameter) {
checkQueryParameter((QueryParameter) fieldEvaluator.getLeftValue());
}
if(fieldEvaluator.getRightValue() instanceof QueryParameter) {
checkQueryParameter((QueryParameter) fieldEvaluator.getRightValue());
}
}
return evaluator;
}
/**
* Verify if the query indicates return all the fields of the result set.
* @return Return all.
*/
public final boolean returnAll() {
return returnAll || returnParameters.isEmpty();
}
/**
* Returns the parameterized query based in this instance of query.
* @return Parameterized query instance.
*/
public final ParameterizedQuery getParameterizedQuery() {
return new ParameterizedQuery(this);
}
/**
* Return the id of the query.
* @return Id of the query.
*/
public final QueryId getId() {
return id;
}
/**
* Return the list of joins.
* @return Joins.
*/
public List<Join> getJoins() {
return Collections.unmodifiableList(joins);
}
/**
* Return the resource query object.
* @return Resource query.
*/
public QueryResource getResource() {
return resource;
}
/**
* Return the resource name.
* @return Resource name.
*/
public final String getResourceName() {
return resource.getResourceName();
}
/**
* Returns the list of resource of the query.
* @return List of resource fo the query.
*/
public List<QueryResource> getResources() {
return resources;
}
/**
* Return the limit of the query.
* @return Query limit.
*/
public final Integer getLimit() {
return limit;
}
/**
* Set the query limit.
* @param limit Query limit.
*/
public final void setLimit(Integer limit) {
this.limit = limit;
}
/**
* Returns the query underlying limit.
* @return Underlying limit.
*/
public Integer getUnderlyingLimit() {
return underlyingLimit;
}
/**
* Set the underlying limit.
* @param underlyingLimit Underlying limit value.
*/
public void setUnderlyingLimit(Integer underlyingLimit) {
this.underlyingLimit = underlyingLimit;
}
/**
* Return the object that represents the first element of the result.
* @return Firts object of the result.
*/
public final Integer getStart() {
return start != null ? start : 0;
}
/**
* Set the first object of the result.
* @param start First object of the result.
*/
public final void setStart(Integer start) {
this.start = start;
}
/**
* Returns the underlying start.
* @return Underlying start value.
*/
public Integer getUnderlyingStart() {
return underlyingStart;
}
/**
* Set the underlying start.
* @param underlyingStart Underlying start value.
*/
public void setUnderlyingStart(Integer underlyingStart) {
this.underlyingStart = underlyingStart;
}
/**
* Return all the group fields of the query.
* @return Group field of the query.
*/
public List<QueryReturnParameter> getGroupParameters() {
return Collections.unmodifiableList(groupParameters);
}
/**
* Add a name of the field for group the data collection. This name must be exist
* like a setter/getter method in the instances of the data collection.
* @param groupField Name of the pair getter/setter.
* @return Return the same instance of this class.
*/
public final Query addGroupField(String groupField) {
return addGroupField(new QueryReturnField(this, groupField));
}
/**
* Add a name of the field for group the data collection. This name must be exist
* like a setter/getter method in the instances of the data collection.
* @param groupField Name of the pair getter/setter.
* @return Return the same instance of this class.
*/
public final Query addGroupField(QueryReturnParameter groupField) {
groupParameters.add((QueryReturnParameter)checkQueryParameter((QueryParameter) groupField));
return this;
}
/**
* Return the unmodifiable list with order fields.
* @return Order fields.
*/
public final List<QueryOrderParameter> getOrderParameters() {
return Collections.unmodifiableList(orderParameters);
}
/**
* Add a name of the field for order the data collection. This name must be exist
* like a setter/getter method in the instances of the data collection.
* @param orderField Name of the pair getter/setter.
* @return Return the same instance of this class.
*/
public final Query addOrderField(String orderField) {
return addOrderField(orderField, SystemProperties.getBoolean(SystemProperties.Query.DEFAULT_DESC_ORDER));
}
/**
* Add a name of the field for order the data collection. This name must be exist
* like a setter/getter method in the instances of the data collection.
* @param orderField Name of the pair getter/setter.
* @param desc Desc property.
* @return Return the same instance of this class.
*/
public final Query addOrderField(String orderField, boolean desc) {
return addOrderField(new QueryOrderField(this, orderField, desc));
}
/**
* Add a name of the field for order the data collection. This name must be exist
* like a setter/getter method in the instances of the data collection.
* @param orderParameter Order parameter.
* @return Return the same instance of this class.
*/
public final Query addOrderField(QueryOrderParameter orderParameter) {
orderParameters.add((QueryOrderParameter) checkQueryParameter((QueryParameter) orderParameter));
return this;
}
/**
* Return an unmodifiable list with the return fields.
* @return Return fields.
*/
public final List<QueryReturnParameter> getReturnParameters() {
return Collections.unmodifiableList(returnParameters);
}
/**
* Add the name of the field to be returned in the result set.
* @param returnField Field name.
* @return Return the same instance of this class.
*/
public final Query addReturnField(String returnField) {
if(returnField.equals(SystemProperties.get(SystemProperties.Query.ReservedWord.RETURN_ALL))) {
returnAll = true;
} else {
addReturnField(new QueryReturnField(this, returnField));
}
return this;
}
/**
* Add the name of the field to be returned in the result set.
* @param returnParameter Return parameter.
* @return Return the same instance of this class.
*/
public final Query addReturnField(QueryReturnParameter returnParameter) {
if(returnParameter instanceof QueryReturnField && ((QueryReturnField)returnParameter).getFieldPath().equals(
SystemProperties.get(SystemProperties.Query.ReservedWord.RETURN_ALL))) {
returnAll = true;
} else {
returnParameters.add((QueryReturnParameter) checkQueryParameter((QueryParameter) returnParameter));
}
return this;
}
/**
* Add join instance to the query.
* @param join Join instance.
*/
public final void addJoin(Join join) {
if(join != null && !joins.contains(join)) {
joins.add(join);
} else {
if(join == null) {
throw new NullPointerException("Null join instance");
}
}
}
/**
* This method evaluate each object of the collection and sort filtered
* object to create a result add with the object filtered and sorted.
* If there are order fields added then the result implementation is a
* {@link TreeSet} implementation else the result implementation is a
* {@link LinkedHashSet} implementation in order to guarantee the data order
* from the source
* @param dataSource Data source to evaluate the query.
* @param <O> Kind of instances of the data collection.
* @return Result add filtered and sorted.
*/
@Override
public final <O extends Object> Collection<O> evaluate(Collection<O> dataSource) {
return evaluate((query) -> dataSource, new Queryable.IntrospectionConsumer<>());
}
/**
* This method evaluate each object of the collection and sort filtered
* object to create a result add with the object filtered and sorted.
* If there are order fields added then the result implementation is a
* {@link TreeSet} implementation else the result implementation is a
* {@link LinkedHashSet} implementation in order to guarantee the data order
* from the source
* @param dataSource Data source to evaluate the query.
* @param consumer Data source consumer.
* @param <O> Kind of instances of the data collection.
* @return Result add filtered and sorted.
*/
@Override
public final <O extends Object> Collection<O> evaluate(Collection<O> dataSource, Queryable.Consumer<O> consumer) {
return evaluate((query) -> dataSource, consumer);
}
/**
* This method evaluate each object of the collection and sort filtered
* object to create a result add with the object filtered and sorted.
* If there are order fields added then the result implementation is a
* {@link TreeSet} implementation else the result implementation is a
* {@link LinkedHashSet} implementation in order to guarantee the data order
* from the source
* @param dataSource Data source to evaluate the query.
* @param <O> Kind of instances of the data collection.
* @return Result add filtered and sorted.
*/
@Override
public final <O extends Object> Collection<O> evaluate(Queryable.DataSource<O> dataSource) {
return evaluate(dataSource, new Queryable.IntrospectionConsumer<>());
}
/**
* This method evaluate each object of the collection and sort filtered
* object to create a result add with the object filtered and sorted.
* If there are order fields added then the result implementation is a
* {@link TreeSet} implementation else the result implementation is a
* {@link LinkedHashSet} implementation in order to guarantee the data order
* from the source
* @param dataSource Data source to evaluate the query.
* @param consumer Data source consumer.
* @param <O> Kind of instances of the data collection.
* @return Result add filtered and sorted.
*/
@Override
public final <O extends Object> Collection<O> evaluate(Queryable.DataSource<O> dataSource, Queryable.Consumer<O> consumer) {
Collection<O> result;
Map<String, Groupable> groupables = null;
List<QueryReturnFunction> aggregateFunctions = new ArrayList<>();
if(!(Thread.currentThread() instanceof ServiceThread)) {
//If the current thread is not a service thread then we call this
//method again using a service thread.
result = Service.call(()->evaluate(dataSource, consumer), ServiceSession.getGuestSession());
} else {
//Initialize the evaluators cache because the evaluators in the simple
//query are valid into the platform evaluation environment.
initializeEvaluatorsCache();
//Creating result data collection.
if (orderParameters.size() > 0) {
//If the query has order fields then creates a tree set with
//a comparator using the order fields.
result = new TreeSet<>((o1, o2) -> {
int compareResult = 0;
Comparable<Object> comparable1;
Comparable<Object> comparable2;
for (QueryOrderParameter orderField : orderParameters) {
try {
if (orderField instanceof QueryOrderFunction) {
comparable1 = consumer.resolveFunction(((QueryOrderFunction) orderField), o1, dataSource);
comparable2 = consumer.resolveFunction(((QueryOrderFunction) orderField), o2, dataSource);
} else {
comparable1 = consumer.get(o1, (QueryParameter) orderField, dataSource);
comparable2 = consumer.get(o2, (QueryParameter) orderField, dataSource);
}
} catch (ClassCastException ex) {
throw new HCJFRuntimeException("Order field must be comparable");
}
if (comparable1 == null ^ comparable2 == null) {
compareResult = (comparable1 == null) ? -1 : 1;
} else if (comparable1 == null && comparable2 == null) {
compareResult = 0;
} else {
compareResult = comparable1.compareTo(comparable2) * (orderField.isDesc() ? -1 : 1);
}
if (compareResult != 0) {
break;
}
}
if (compareResult == 0) {
compareResult = o1.hashCode() - o2.hashCode();
}
return compareResult;
});
} else {
//If the query has not order fields then creates a linked hash set to
//maintain the natural order of the data.
result = new ArrayList<>();
}
//Getting data from data source.
Collection<O> data;
try {
//Creates the first query for the original resource.
Query resolveQuery = new Query(getResourceName());
resolveQuery.returnAll = true;
resolveQuery.setLimit(getLimit());
resolveQuery.setUnderlyingLimit(getUnderlyingLimit());
resolveQuery.setStart(getStart());
resolveQuery.setUnderlyingStart(getUnderlyingStart());
copyEvaluators(resolveQuery, this);
if (joins.size() > 0) {
data = (Collection<O>) join((DataSource<Joinable>) dataSource, (Consumer<Joinable>) consumer);
} else {
//If the query has not joins then data source must return data from
//resource of the query.
data = dataSource.getResourceData(verifyInstance(resolveQuery, consumer));
}
//Filtering data
boolean add;
//Collect all the aggregate functions into the array list.
List<String> returnParametersAsArray = new ArrayList<>();
for (QueryReturnParameter returnParameter : getReturnParameters()) {
if(returnParameter instanceof QueryReturnFunction && ((QueryReturnFunction)returnParameter).isAggregate()) {
aggregateFunctions.add((QueryReturnFunction) returnParameter);
}
returnParametersAsArray.add(returnParameter.getAlias());
}
StringBuilder hashCode;
Groupable groupable;
if (!groupParameters.isEmpty()) {
groupables = new HashMap<>();
}
for (O object : data) {
add = verifyCondition(object, dataSource, consumer);
if (add) {
if (object instanceof Enlarged) {
Enlarged enlargedObject;
if(returnAll) {
enlargedObject = ((Enlarged) object).clone();
} else {
enlargedObject = ((Enlarged) object).clone(returnParametersAsArray.toArray(new String[]{}));
}
object = (O) enlargedObject;
String name;
Object value;
for (QueryReturnParameter returnParameter : getReturnParameters()) {
name = null;
value = null;
if (returnParameter instanceof QueryReturnField) {
QueryReturnField returnField = (QueryReturnField) returnParameter;
name = returnField.getAlias();
value = consumer.get((O) enlargedObject, returnField, dataSource);
} else if (returnParameter instanceof QueryReturnFunction && !((QueryReturnFunction)returnParameter).isAggregate()) {
QueryReturnFunction function = (QueryReturnFunction) returnParameter;
name = function.getAlias();
value = consumer.resolveFunction(function, enlargedObject, dataSource);
}
if(name != null && value != null) {
enlargedObject.put(name, value);
}
}
}
if (!groupParameters.isEmpty() && object instanceof Groupable) {
groupable = (Groupable) object;
hashCode = new StringBuilder();
Object groupValue;
for (QueryReturnParameter returnParameter : groupParameters) {
if (returnParameter instanceof QueryReturnField) {
groupValue = consumer.get(object, ((QueryReturnField) returnParameter), dataSource);
} else {
groupValue = consumer.resolveFunction(((QueryReturnFunction) returnParameter), object, dataSource);
}
if(groupValue == null) {
hashCode.append(SystemProperties.get(SystemProperties.Query.ReservedWord.NULL).hashCode());
} else {
hashCode.append(groupValue.hashCode());
}
}
if (groupables.containsKey(hashCode.toString())) {
groupables.get(hashCode.toString()).group(groupable);
} else {
groupables.put(hashCode.toString(), groupable);
}
} else {
result.add(object);
}
}
}
if(groupables != null) {
result.addAll((Collection<? extends O>) groupables.values());
}
} finally {
clearEvaluatorsCache();
}
if(aggregateFunctions.size() > 0) {
for (QueryReturnFunction function : aggregateFunctions) {
result = consumer.resolveFunction(function, result, dataSource);
}
}
if(result.size() > 0 && result.iterator().next() instanceof Enlarged && !returnAll) {
result.forEach(O -> ((Enlarged)O).purge());
}
if(getStart() != 0 || getLimit() != null) {
if (getLimit() != null) {
result = result.stream().skip(getStart()).limit(getLimit()).collect(Collectors.toList());
} else {
result = result.stream().skip(getStart()).collect(Collectors.toList());
}
}
}
return result;
}
private Queryable verifyInstance(Query query, Consumer consumer) {
Queryable result = query;
if(consumer instanceof ParameterizedQuery.ParameterizedConsumer &&
((ParameterizedQuery.ParameterizedConsumer)consumer).getParameters().size() > 0) {
ParameterizedQuery parameterizedQuery = query.getParameterizedQuery();
for(Object parameter : ((ParameterizedQuery.ParameterizedConsumer)consumer).getParameters()) {
parameterizedQuery.add(parameter);
}
result = parameterizedQuery;
}
return result;
}
/**
* This method verify if the conditions of the query are true or not.
* @param object Object to use as condition parameters.
* @return Returns if the evaluation of conditions are true or false in the otherwise.
*/
public final boolean verifyCondition(Object object) {
Consumer consumer = new Queryable.IntrospectionConsumer<>();
Collection collection = List.of(object);
return verifyCondition(object, Q->collection, consumer);
}
/**
* This method verify if the conditions of the query are true or not.
* @param object Object to use as condition parameters.
* @param dataSource Data source.
* @param consumer Consumer.
* @return Returns if the evaluation of conditions are true or false in the otherwise.
*/
private boolean verifyCondition(Object object, DataSource dataSource, Consumer consumer) {
Boolean result = true;
for (Evaluator evaluator : getEvaluators()) {
if (evaluator instanceof BooleanEvaluator &&
((BooleanEvaluator) evaluator).getValue() instanceof QueryParameter &&
((QueryParameter)((BooleanEvaluator) evaluator).getValue()).isUnderlying()) {
continue;
}
if (!isEvaluatorDone(evaluator)) {
result &= evaluator.evaluate(object, dataSource, consumer);
if (!result) {
break;
}
}
}
return result;
}
/**
* This method check if the evaluator is evaluated previously into the current session.
* @param evaluator Checking evaluator.
* @return Return true if the evaluator is done and false in the otherwise.
*/
private boolean isEvaluatorDone(Evaluator evaluator) {
boolean result = false;
ServiceSession session = ServiceSession.getCurrentSession();
if(session != null) {
List<Evaluator> evaluatorsCache = (List<Evaluator>) session.getProperties().get(
SystemProperties.get(SystemProperties.Query.EVALUATORS_CACHE_NAME));
if(evaluatorsCache != null) {
result = evaluatorsCache.contains(evaluator);
}
}
return result;
}
/**
* Initialize the evaluators cache into the current session.
*/
private void initializeEvaluatorsCache() {
ServiceSession session = ServiceSession.getCurrentIdentity();
if(session != null) {
session.put(SystemProperties.get(SystemProperties.Query.EVALUATORS_CACHE_NAME),
new ArrayList<Evaluator>());
session.put(SystemProperties.get(SystemProperties.Query.EVALUATOR_LEFT_VALUES_CACHE_NAME),
new HashMap<Evaluator, Object>());
session.put(SystemProperties.get(SystemProperties.Query.EVALUATOR_RIGHT_VALUES_CACHE_NAME),
new HashMap<Evaluator, Object>());
}
}
/**
* Removes the evaluators cache of the current session.
*/
private void clearEvaluatorsCache() {
ServiceSession session = ServiceSession.getCurrentIdentity();
if(session != null) {
session.remove(SystemProperties.get(SystemProperties.Query.EVALUATORS_CACHE_NAME));
session.remove(SystemProperties.get(SystemProperties.Query.EVALUATOR_LEFT_VALUES_CACHE_NAME));
session.remove(SystemProperties.get(SystemProperties.Query.EVALUATOR_RIGHT_VALUES_CACHE_NAME));
}
}
/**
* This method add into the current session an instance that must be skipped of the
* platform evaluation process.
* @param evaluator Evaluator to skip.
*/
public static void skipEvaluator(Evaluator evaluator) {
ServiceSession session = ServiceSession.getCurrentSession();
if(session != null) {
List<Evaluator> evaluatorsCache = (List<Evaluator>) session.getProperties().get(
SystemProperties.get(SystemProperties.Query.EVALUATORS_CACHE_NAME));
if(evaluatorsCache != null) {
evaluatorsCache.add(evaluator);
}
}
}
/**
* Copy all the evaluator from the source collection to destiny collection.
* @param dest Destiny collection.
* @param src Source collection.
*/
private void copyEvaluators(EvaluatorCollection dest, EvaluatorCollection src) {
for(Evaluator evaluator : src.getEvaluators()) {
if(evaluator instanceof FieldEvaluator) {
dest.addEvaluator(((FieldEvaluator)evaluator).copy());
} else if(evaluator instanceof And) {
copyEvaluators(dest.and(), (EvaluatorCollection) evaluator);
} else if(evaluator instanceof Or) {
copyEvaluators(dest.or(), (EvaluatorCollection) evaluator);
}
}
}
/**
* Evaluates the join operation.
* @param dataSource Data source instance.
* @param consumer Consumer instance.
* @return Collection that is the result of the join operation.
*/
private Collection<Joinable> join(Queryable.DataSource<Joinable> dataSource, Queryable.Consumer<Joinable> consumer) {
Query query = new Query(getResource().getResourceName());
query.addReturnField(SystemProperties.get(SystemProperties.Query.ReservedWord.RETURN_ALL));
for (Evaluator evaluator : getEvaluatorsFromResource(this, query, query.getResource())) {
query.addEvaluator(evaluator);
}
Collection<Joinable> currentResult = dataSource.getResourceData(verifyInstance(query, consumer));
for(Join join : getJoins()) {
//Creates the first query for the original resource.
query = new Query(join.getResourceName());
query.addReturnField(SystemProperties.get(SystemProperties.Query.ReservedWord.RETURN_ALL));
for (Evaluator evaluator : optimizeJoin(currentResult, join)) {
query.addEvaluator(evaluator);
}
for (Evaluator evaluator : getEvaluatorsFromResource(this, query, join.getResource())) {
query.addEvaluator(evaluator);
}
currentResult = product(currentResult, dataSource.getResourceData(query), join, dataSource, consumer);
}
return currentResult;
}
/**
* This method analyze the join structure and creates a set of evaluators in order to improve the performance of
* the sub queries used to select the objects of the right resource of the join.
* @param leftData Collection with the left data.
* @param join Join structure.
* @return Returns a set of the new filters in order to reduce the information of the right data.
*/
private Collection<Evaluator> optimizeJoin(Collection<Joinable> leftData, Join join) {
Collection<Evaluator> result = new ArrayList<>();
if(join.getType().equals(Join.JoinType.JOIN) ||
join.getType().equals(Join.JoinType.INNER) ||
join.getType().equals(Join.JoinType.LEFT)) {
if(join.getEvaluators().size() == 1) {
if(join.getEvaluators().stream().findFirst().get() instanceof Equals) {
//the join was identified with only one equality (...ON resource1.field = resource2.field)
Equals equals = (Equals) join.getEvaluators().stream().findFirst().get();
if(equals.getLeftValue() instanceof QueryField && equals.getRightValue() instanceof QueryField) {
QueryField foreignKey = null;
QueryField key = null;
if (!((QueryField) equals.getLeftValue()).getResource().equals(join.getResource()) &&
((QueryField) equals.getRightValue()).getResource().equals(join.getResource())) {
foreignKey = (QueryField) equals.getLeftValue();
key = (QueryField) equals.getRightValue();
} else if (!((QueryField) equals.getRightValue()).getResource().equals(join.getResource()) &&
((QueryField) equals.getLeftValue()).getResource().equals(join.getResource())) {
foreignKey = (QueryField) equals.getRightValue();
key = (QueryField) equals.getLeftValue();
}
if(foreignKey != null) {
Collection reducerList = new HashSet();
for(Object currentObject : leftData) {
Object foreignKeyValue = Introspection.resolve(currentObject, foreignKey.getFieldPath());
if(foreignKeyValue != null) {
reducerList.add(foreignKeyValue);
}
}
In inEvaluator = new In(key, reducerList);
result.add(inEvaluator);
}
}
}
}
}
return result;
}
/**
* Evaluates the join and creates the product of the intersection between the first resource and the second resource.
* @param left Left data to the product.
* @param right Right data to the product.
* @param join Join object to evaluate the kind and the evaluators of the product.
* @param dataSource Datasource instance.
* @param consumer Consumer instance.
* @return Collection that is the result of the join operation.
*/
private Collection<Joinable> product(Collection<Joinable> left, Collection<Joinable> right, Join join,
Queryable.DataSource<Joinable> dataSource, Queryable.Consumer<Joinable> consumer) {
Collection<Joinable> leftCopy = null;
Collection<Joinable> rightCopy = null;
switch (join.getType()) {
case LEFT: {
leftCopy = new ArrayList<>();
leftCopy.addAll(left);
break;
}
case RIGHT: {
rightCopy = new ArrayList<>();
rightCopy.addAll(right);
break;
}
case FULL: {
leftCopy = new ArrayList<>();
leftCopy.addAll(left);
rightCopy = new ArrayList<>();
rightCopy.addAll(right);
break;
}
}
Collection<Joinable> result = new ArrayList<>();
Joinable row;
Boolean rowEvaluation;
for(Joinable leftJoinable : left) {
for(Joinable rightJoinable : right) {
row = leftJoinable.join(getResourceName(), join.getResourceName(), rightJoinable);
rowEvaluation = false;
for(Evaluator evaluator : join.getEvaluators()) {
if(!(rowEvaluation = evaluator.evaluate(row, dataSource, consumer))) {
break;
}
}
if(rowEvaluation) {
result.add(row);
switch (join.getType()) {
case LEFT: {
leftCopy.remove(leftJoinable);
break;
}
case RIGHT: {
rightCopy.remove(rightJoinable);
break;
}
case FULL: {
leftCopy.remove(leftJoinable);
rightCopy.remove(rightJoinable);
break;
}
}
}
}
}
switch (join.getType()) {
case LEFT: {
result.addAll(leftCopy);
break;
}
case RIGHT: {
result.addAll(rightCopy);
break;
}
case FULL: {
result.addAll(leftCopy);
result.addAll(rightCopy);
break;
}
}
return result;
}
/**
* Return the list of evaluator for the specific resource.
* @param collection Evaluator collection.
* @param resource Resource type.
* @return List of evaluators.
*/
private List<Evaluator> getEvaluatorsFromResource(EvaluatorCollection collection, EvaluatorCollection parent, QueryResource resource) {
List<Evaluator> result = new ArrayList<>();
QueryParameter queryParameter;
for(Evaluator evaluator : collection.getEvaluators()) {
if(evaluator instanceof FieldEvaluator) {
FieldEvaluator fieldEvaluator = (FieldEvaluator) evaluator;
boolean evaluatorAdded = false;
if (fieldEvaluator.getLeftValue() instanceof QueryParameter) {
queryParameter = (QueryParameter) fieldEvaluator.getLeftValue();
if(queryParameter.verifyResource(resource)) {
result.add(evaluator);
evaluatorAdded = true;
}
}
if (!evaluatorAdded) {
if (fieldEvaluator.getRightValue() instanceof QueryParameter) {
queryParameter = (QueryParameter) fieldEvaluator.getRightValue();
if(queryParameter.verifyResource(resource)) {
result.add(evaluator);
}
}
}
} else if(evaluator instanceof BooleanEvaluator) {
if(((BooleanEvaluator)evaluator).getValue() instanceof QueryParameter) {
queryParameter = (QueryParameter) ((BooleanEvaluator)evaluator).getValue();
if(queryParameter.verifyResource(resource)) {
result.add(evaluator);
}
}
} else if(evaluator instanceof EvaluatorCollection) {
EvaluatorCollection subCollection = null;
if(evaluator instanceof And) {
subCollection = new And(parent);
} else if(evaluator instanceof Or) {
subCollection = new Or(parent);
}
for(Evaluator subEvaluator : getEvaluatorsFromResource((EvaluatorCollection)evaluator, subCollection, resource)) {
subCollection.addEvaluator(subEvaluator);
}
}
}
return result;
}
/**
* Return a copy of this query without all the evaluator and order fields of the
* parameter collections.
* @param evaluatorsToRemove Evaluators to optimizeJoin.
* @return Reduced copy of the query.
*/
public final Query reduce(Collection<Evaluator> evaluatorsToRemove) {
Query copy = new Query(this);
copy.evaluators.addAll(this.evaluators);
if(evaluatorsToRemove != null && !evaluatorsToRemove.isEmpty()) {
reduceCollection(copy, evaluatorsToRemove);
}
return copy;
}
public final Query reduceFieldEvaluator(String fieldName, Class<? extends FieldEvaluator>... evaluatorType) {
return reduce(getFieldEvaluators(fieldName, evaluatorType));
}
/**
* Reduce recursively all the collection into the query.
* @param collection Collection to optimizeJoin.
* @param evaluatorsToRemove Evaluator to remove.
*/
private final void reduceCollection(EvaluatorCollection collection, Collection<Evaluator> evaluatorsToRemove) {
for(Evaluator evaluatorToRemove : evaluatorsToRemove) {
collection.evaluators.remove(evaluatorToRemove);
collection.addEvaluator(new TrueEvaluator());
}
for(Evaluator evaluator : collection.evaluators) {
if(evaluator instanceof Or || evaluator instanceof And) {
reduceCollection((EvaluatorCollection)evaluator, evaluatorsToRemove);
}
}
}
/**
* Creates a string representation of the query object.
* @return String representation.
*/
@Override
public synchronized String toString() {
if(stringRepresentation == null) {
Strings.Builder resultBuilder = new Strings.Builder();
//Print select
resultBuilder.append(SystemProperties.get(SystemProperties.Query.ReservedWord.SELECT));
resultBuilder.append(Strings.WHITE_SPACE);
if (returnAll) {
resultBuilder.append(SystemProperties.get(SystemProperties.Query.ReservedWord.RETURN_ALL));
SystemProperties.get(SystemProperties.Query.ReservedWord.ARGUMENT_SEPARATOR);
resultBuilder.append(Strings.WHITE_SPACE);
}
for (QueryReturnParameter field : getReturnParameters()) {
resultBuilder.append(field);
if (field.getAlias() != null) {
resultBuilder.append(Strings.WHITE_SPACE).append(SystemProperties.get(SystemProperties.Query.ReservedWord.AS));
resultBuilder.append(Strings.WHITE_SPACE).append(field.getAlias());
}
resultBuilder.append(Strings.EMPTY_STRING, SystemProperties.get(SystemProperties.Query.ReservedWord.ARGUMENT_SEPARATOR));
}
resultBuilder.cleanBuffer();
//Print from
resultBuilder.append(Strings.WHITE_SPACE);
resultBuilder.append(SystemProperties.get(SystemProperties.Query.ReservedWord.FROM));
resultBuilder.append(Strings.WHITE_SPACE);
resultBuilder.append(getResourceName());
resultBuilder.append(Strings.WHITE_SPACE);
//Print joins
for (Join join : joins) {
if (!(join.getType() == Join.JoinType.JOIN)) {
resultBuilder.append(join.getType());
resultBuilder.append(Strings.WHITE_SPACE);
}
resultBuilder.append(SystemProperties.get(SystemProperties.Query.ReservedWord.JOIN)).append(Strings.WHITE_SPACE);
resultBuilder.append(join.getResourceName()).append(Strings.WHITE_SPACE);
resultBuilder.append(SystemProperties.get(SystemProperties.Query.ReservedWord.ON)).append(Strings.WHITE_SPACE);
if (join.getEvaluators().size() > 0) {
toStringEvaluatorCollection(resultBuilder, join);
}
}
if (evaluators.size() > 0) {
resultBuilder.append(SystemProperties.get(SystemProperties.Query.ReservedWord.WHERE)).append(Strings.WHITE_SPACE);
toStringEvaluatorCollection(resultBuilder, this);
}
if (groupParameters.size() > 0) {
resultBuilder.append(SystemProperties.get(SystemProperties.Query.ReservedWord.GROUP_BY)).append(Strings.WHITE_SPACE);
for (QueryReturnParameter groupParameter : groupParameters) {
resultBuilder.append(groupParameter, SystemProperties.Query.ReservedWord.ARGUMENT_SEPARATOR);
}
resultBuilder.append(Strings.WHITE_SPACE);
resultBuilder.cleanBuffer();
}
if (orderParameters.size() > 0) {
resultBuilder.append(SystemProperties.get(SystemProperties.Query.ReservedWord.ORDER_BY)).append(Strings.WHITE_SPACE);
for (QueryOrderParameter orderField : orderParameters) {
resultBuilder.append(orderField);
if (orderField.isDesc()) {
resultBuilder.append(Strings.WHITE_SPACE).append(SystemProperties.get(SystemProperties.Query.ReservedWord.DESC));
}
resultBuilder.append(Strings.EMPTY_STRING, SystemProperties.get(SystemProperties.Query.ReservedWord.ARGUMENT_SEPARATOR));
}
resultBuilder.cleanBuffer();
}
if (getStart() != null) {
resultBuilder.append(Strings.WHITE_SPACE).append(SystemProperties.get(SystemProperties.Query.ReservedWord.START));
resultBuilder.append(Strings.WHITE_SPACE).append(getStart());
}
if (getUnderlyingStart() != null) {
if(getStart() == null) {
resultBuilder.append(Strings.WHITE_SPACE).append(SystemProperties.get(SystemProperties.Query.ReservedWord.START)).append(Strings.WHITE_SPACE);
}
resultBuilder.append(Strings.ARGUMENT_SEPARATOR).append(getUnderlyingStart());
}
if (getLimit() != null) {
resultBuilder.append(Strings.WHITE_SPACE).append(SystemProperties.get(SystemProperties.Query.ReservedWord.LIMIT));
resultBuilder.append(Strings.WHITE_SPACE).append(getLimit());
}
if (getUnderlyingLimit() != null) {
if(getLimit() == null) {
resultBuilder.append(Strings.WHITE_SPACE).append(SystemProperties.get(SystemProperties.Query.ReservedWord.LIMIT)).append(Strings.WHITE_SPACE);
}
resultBuilder.append(Strings.ARGUMENT_SEPARATOR).append(getUnderlyingLimit());
}
stringRepresentation = resultBuilder.toString();
}
return stringRepresentation;
}
/**
* Creates a string representation of evaluator collection.
* @param result Buffer with the current result.
* @param collection Collection in order to create the string representation.
*/
private void toStringEvaluatorCollection(Strings.Builder result, EvaluatorCollection collection) {
String separator = Strings.EMPTY_STRING;
String separatorValue = collection instanceof Or ?
SystemProperties.get(SystemProperties.Query.ReservedWord.OR) :
SystemProperties.get(SystemProperties.Query.ReservedWord.AND);
for(Evaluator evaluator : collection.getEvaluators()) {
if(evaluator instanceof Or) {
if(!separator.isEmpty()) {
result.append(SystemProperties.get(SystemProperties.Query.ReservedWord.OR));
}
result.append(Strings.WHITE_SPACE);
if(((Or)evaluator).getEvaluators().size() == 1) {
toStringEvaluatorCollection(result, (Or) evaluator);
} else {
result.append(Strings.START_GROUP);
toStringEvaluatorCollection(result, (Or) evaluator);
result.append(Strings.END_GROUP);
}
result.append(Strings.WHITE_SPACE);
} else if(evaluator instanceof And) {
if(!separator.isEmpty()) {
result.append(SystemProperties.get(SystemProperties.Query.ReservedWord.AND));
}
result.append(Strings.WHITE_SPACE);
if (collection instanceof Query) {
toStringEvaluatorCollection(result, (And) evaluator);
} else {
if (((And) evaluator).getEvaluators().size() == 1) {
toStringEvaluatorCollection(result, (And) evaluator);
} else {
result.append(Strings.START_GROUP);
toStringEvaluatorCollection(result, (And) evaluator);
result.append(Strings.END_GROUP);
}
}
result.append(Strings.WHITE_SPACE);
} else if(evaluator instanceof BooleanEvaluator) {
result.append(separator);
BooleanEvaluator booleanEvaluator = (BooleanEvaluator) evaluator;
if(booleanEvaluator.isTrueForced()) {
result.append(Boolean.TRUE.toString());
} else {
result = toStringFieldEvaluatorValue(booleanEvaluator.getValue(), booleanEvaluator.getClass(), result);
}
result.append(Strings.WHITE_SPACE);
} else if(evaluator instanceof FieldEvaluator) {
result.append(separator);
FieldEvaluator fieldEvaluator = (FieldEvaluator) evaluator;
if(fieldEvaluator.isTrueForced()) {
result.append(Boolean.TRUE.toString());
} else {
if (fieldEvaluator.getLeftValue() == null) {
result.append(SystemProperties.get(SystemProperties.Query.ReservedWord.NULL));
} else {
result = toStringFieldEvaluatorValue(fieldEvaluator.getLeftValue(), fieldEvaluator.getLeftValue().getClass(), result);
}
result.append(Strings.WHITE_SPACE);
if (fieldEvaluator instanceof Distinct) {
result.append(SystemProperties.get(SystemProperties.Query.ReservedWord.DISTINCT)).append(Strings.WHITE_SPACE);
} else if (fieldEvaluator instanceof Equals) {
result.append(SystemProperties.get(SystemProperties.Query.ReservedWord.EQUALS)).append(Strings.WHITE_SPACE);
} else if (fieldEvaluator instanceof GreaterThanOrEqual) {
result.append(SystemProperties.get(SystemProperties.Query.ReservedWord.GREATER_THAN_OR_EQUALS)).append(Strings.WHITE_SPACE);
} else if (fieldEvaluator instanceof GreaterThan) {
result.append(SystemProperties.get(SystemProperties.Query.ReservedWord.GREATER_THAN)).append(Strings.WHITE_SPACE);
} else if (fieldEvaluator instanceof NotIn) {
result.append(SystemProperties.get(SystemProperties.Query.ReservedWord.NOT_IN)).append(Strings.WHITE_SPACE);
} else if (fieldEvaluator instanceof In) {
result.append(SystemProperties.get(SystemProperties.Query.ReservedWord.IN)).append(Strings.WHITE_SPACE);
} else if (fieldEvaluator instanceof Like) {
result.append(SystemProperties.get(SystemProperties.Query.ReservedWord.LIKE)).append(Strings.WHITE_SPACE);
} else if (fieldEvaluator instanceof SmallerThanOrEqual) {
result.append(SystemProperties.get(SystemProperties.Query.ReservedWord.SMALLER_THAN_OR_EQUALS)).append(Strings.WHITE_SPACE);
} else if (fieldEvaluator instanceof SmallerThan) {
result.append(SystemProperties.get(SystemProperties.Query.ReservedWord.SMALLER_THAN)).append(Strings.WHITE_SPACE);
}
if (fieldEvaluator.getRightValue() == null) {
result.append(SystemProperties.get(SystemProperties.Query.ReservedWord.NULL));
} else {
result = toStringFieldEvaluatorValue(fieldEvaluator.getRightValue(), fieldEvaluator.getRightValue().getClass(), result);
}
}
result.append(Strings.WHITE_SPACE);
}
separator = separatorValue + Strings.WHITE_SPACE;
}
}
/**
* Creates the string representation of the field evaluator.
* @param value Object to create the string representation.
* @param type Object type.
* @param result Buffer with the current result.
* @return String representation of the field evaluator.
*/
private static Strings.Builder toStringFieldEvaluatorValue(Object value, Class type, Strings.Builder result) {
if(FieldEvaluator.ReplaceableValue.class.isAssignableFrom(type)) {
result.append(SystemProperties.get(SystemProperties.Query.ReservedWord.REPLACEABLE_VALUE));
} else if(FieldEvaluator.QueryValue.class.isAssignableFrom(type)) {
result.append(Strings.START_GROUP);
result.append(((FieldEvaluator.QueryValue)value).getQuery().toString());
result.append(Strings.END_GROUP);
} else if(String.class.isAssignableFrom(type)) {
result.append(SystemProperties.get(SystemProperties.Query.ReservedWord.STRING_DELIMITER));
result.append(value);
result.append(SystemProperties.get(SystemProperties.Query.ReservedWord.STRING_DELIMITER));
} else if(Date.class.isAssignableFrom(type)) {
result.append(SystemProperties.get(SystemProperties.Query.ReservedWord.STRING_DELIMITER));
result.append(SystemProperties.getDateFormat(SystemProperties.Query.DATE_FORMAT).format((Date)value));
result.append(SystemProperties.get(SystemProperties.Query.ReservedWord.STRING_DELIMITER));
} else if(Collection.class.isAssignableFrom(type)) {
result.append(Strings.START_GROUP);
String separator = Strings.EMPTY_STRING;
for(Object object : (Collection)value) {
if(object != null) {
result.append(separator);
result = toStringFieldEvaluatorValue(object, object.getClass(), result);
separator = SystemProperties.get(SystemProperties.Query.ReservedWord.ARGUMENT_SEPARATOR);
}
}
result.append(Strings.END_GROUP);
} else {
result.append(value.toString());
}
return result;
}
/**
* This method is a particular implementation to create a bson document from a query instance.
* @return Returns a bson document.
*/
@Override
public BsonDocument toBson() {
BsonDocument document = new BsonDocument();
document.put(PARCELABLE_CLASS_NAME, getClass().getName());
document.put(QUERY_BSON_FIELD_NAME, toString());
return document;
}
/**
* This particular implementation do nothing to populate the instance.
* @param document Bson document to populate the parcelable.
* @param <P> Expected bson parcelable type.
* @return Returns the same instance.
*/
@Override
public <P extends BsonParcelable> P populate(BsonDocument document) {
return (P) this;
}
/**
* Evaluates the query using a readable data source.
* @param query Query to evaluate.
* @return Collections of joinable map instances.
*/
public static Collection<JoinableMap> evaluate(String query) {
return evaluate(compile(query));
}
/**
* Evaluates the query using a readable data source.
* @param queryable Query to evaluate.
* @return Collections of joinable map instances.
*/
public static Collection<JoinableMap> evaluate(Queryable queryable) {
Collection<JoinableMap> result;
Query query;
if(queryable instanceof Query) {
query = (Query) queryable;
} else {
query = ((ParameterizedQuery)queryable).getQuery();
}
//if(query.getJoins().isEmpty() && query.getOrderParameters().isEmpty()) {
// result = Layers.get(ReadRowsLayerInterface.class, queryable.getResourceName()).readRows(queryable);
//} else {
// result = queryable.evaluate(new Queryable.ReadableDataSource());
//return result;
return queryable.evaluate(new Queryable.ReadableDataSource());
}
/**
* This method evaluate if the uuid instance is a uuid type 5 and contains
* some name of the registered resource and invoke the read method of the resource.
* @param uuid Resource id.
* @param <O> Expected data type.
* @return Resource instance.
*/
public static <O extends Object> O evaluate(UUID uuid) {
String resourceName = NamedUuid.getName(uuid);
IdentifiableLayerInterface identifiableLayerInterface = Layers.get(IdentifiableLayerInterface.class, resourceName);
return (O) identifiableLayerInterface.read(uuid);
}
/**
* Create a query instance from sql definition.
* @param sql Sql definition.
* @return Query instance.
*/
public static Query compile(String sql) {
return compile(sql, false);
}
/**
* Create a query instance from sql definition.
* @param sql Sql definition
* @param ignoreCache Boolean value to indicate if the cache must be ignored or not.
* @return Query instance.
*/
public static Query compile(String sql, boolean ignoreCache) {
Query result = null;
if(!ignoreCache) {
result = cache.get(sql);
}
if(result == null) {
List<String> richTexts = Strings.groupRichText(sql);
List<String> groups = Strings.replaceableGroup(Strings.removeLines(richTexts.get(richTexts.size() - 1)));
result = compile(groups, richTexts, groups.size() - 1);
cache.put(sql,result);
}
return result;
}
/**
* Create a query instance from sql definition.
* @param groups
* @param startGroup
* @return Query instance.
*/
private static Query compile(List<String> groups, List<String> richTexts, Integer startGroup) {
Query query;
Pattern pattern = SystemProperties.getPattern(SystemProperties.Query.SELECT_REGULAR_EXPRESSION);
Matcher matcher = pattern.matcher(groups.get(startGroup));
if(matcher.matches()) {
String selectBody = matcher.group(SystemProperties.getInteger(SystemProperties.Query.SELECT_GROUP_INDEX));
selectBody = selectBody.replaceFirst(Strings.CASE_INSENSITIVE_REGEX_FLAG+SystemProperties.get(SystemProperties.Query.ReservedWord.SELECT), Strings.EMPTY_STRING);
String fromBody = matcher.group(SystemProperties.getInteger(SystemProperties.Query.FROM_GROUP_INDEX));
fromBody = fromBody.replaceFirst(Strings.CASE_INSENSITIVE_REGEX_FLAG+SystemProperties.get(SystemProperties.Query.ReservedWord.FROM), Strings.EMPTY_STRING);
String conditionalBody = matcher.group(SystemProperties.getInteger(SystemProperties.Query.CONDITIONAL_GROUP_INDEX));
if(conditionalBody != null && conditionalBody.endsWith(SystemProperties.get(SystemProperties.Query.ReservedWord.STATEMENT_END))) {
conditionalBody = conditionalBody.substring(0, conditionalBody.indexOf(SystemProperties.get(SystemProperties.Query.ReservedWord.STATEMENT_END))-1);
}
query = new Query(fromBody.trim());
if(conditionalBody != null) {
Pattern conditionalPatter = SystemProperties.getPattern(SystemProperties.Query.CONDITIONAL_REGULAR_EXPRESSION, Pattern.CASE_INSENSITIVE);
String[] conditionalElements = conditionalPatter.split(conditionalBody);
String element;
String elementValue;
for (int i = 0; i < conditionalElements.length; i++) {
element = conditionalElements[i++].trim();
elementValue = conditionalElements[i].trim();
if (element.equalsIgnoreCase(SystemProperties.get(SystemProperties.Query.ReservedWord.JOIN)) ||
element.equalsIgnoreCase(SystemProperties.get(SystemProperties.Query.ReservedWord.FULL)) ||
element.equalsIgnoreCase(SystemProperties.get(SystemProperties.Query.ReservedWord.INNER)) ||
element.equalsIgnoreCase(SystemProperties.get(SystemProperties.Query.ReservedWord.LEFT)) ||
element.equalsIgnoreCase(SystemProperties.get(SystemProperties.Query.ReservedWord.RIGHT))) {
Join.JoinType type = Join.JoinType.valueOf(element.toUpperCase());
if(type != Join.JoinType.JOIN) {
elementValue = conditionalElements[++i].trim();
}
String[] joinElements = elementValue.split(SystemProperties.get(SystemProperties.Query.JOIN_REGULAR_EXPRESSION));
String joinResource = joinElements[SystemProperties.getInteger(SystemProperties.Query.JOIN_RESOURCE_NAME_INDEX)].trim();
String joinEvaluators = joinElements[SystemProperties.getInteger(SystemProperties.Query.JOIN_EVALUATORS_INDEX)].trim();
if(joinEvaluators.startsWith(Strings.REPLACEABLE_GROUP)) {
joinEvaluators = groups.get(Integer.parseInt(joinEvaluators.replace(Strings.REPLACEABLE_GROUP, Strings.EMPTY_STRING)));
}
Join join = new Join(query, joinResource, type);
query.getResources().add(join.getResource());
completeEvaluatorCollection(query, joinEvaluators, groups, richTexts, join, 0, new AtomicInteger(0));
query.addJoin(join);
} else if (element.equalsIgnoreCase(SystemProperties.get(SystemProperties.Query.ReservedWord.WHERE))) {
completeEvaluatorCollection(query, elementValue, groups, richTexts, query, 0, new AtomicInteger(0));
} else if (element.equalsIgnoreCase(SystemProperties.get(SystemProperties.Query.ReservedWord.ORDER_BY))) {
for (String orderField : elementValue.split(SystemProperties.get(
SystemProperties.Query.ReservedWord.ARGUMENT_SEPARATOR))) {
query.addOrderField((QueryOrderParameter)
processStringValue(query, groups, richTexts, orderField, null, QueryOrderParameter.class, new ArrayList<>()));
}
} else if (element.equalsIgnoreCase(SystemProperties.get(SystemProperties.Query.ReservedWord.GROUP_BY))) {
for (String orderField : elementValue.split(SystemProperties.get(
SystemProperties.Query.ReservedWord.ARGUMENT_SEPARATOR))) {
query.addGroupField((QueryReturnParameter)
processStringValue(query, groups, richTexts, orderField, null, QueryReturnParameter.class, new ArrayList<>()));
}
} else if (element.equalsIgnoreCase(SystemProperties.get(SystemProperties.Query.ReservedWord.LIMIT))) {
if(elementValue == null || elementValue.isBlank()) {
throw new HCJFRuntimeException("Undeclared limit value");
}
String[] limitValues = elementValue.split(Strings.ARGUMENT_SEPARATOR);
if(limitValues.length > 0 && !limitValues[0].isBlank()) {
try {
query.setLimit(Integer.parseInt(limitValues[0].trim()));
} catch (NumberFormatException ex) {
throw new HCJFRuntimeException("The limit value must be an integer", ex);
}
}
if(limitValues.length > 1 && !limitValues[1].isBlank()) {
try {
query.setUnderlyingLimit(Integer.parseInt(limitValues[1].trim()));
} catch (NumberFormatException ex) {
throw new HCJFRuntimeException("The underlying limit value must be an integer", ex);
}
}
} else if (element.equalsIgnoreCase(SystemProperties.get(SystemProperties.Query.ReservedWord.START))) {
if(elementValue == null || elementValue.isBlank()) {
throw new HCJFRuntimeException("Undeclared start value");
}
String[] startValues = elementValue.split(Strings.ARGUMENT_SEPARATOR);
if(startValues.length > 0 && !startValues[0].isBlank()) {
try {
query.setStart(Integer.parseInt(startValues[0].trim()));
} catch (NumberFormatException ex) {
throw new HCJFRuntimeException("The start value must be an integer", ex);
}
}
if(startValues.length > 1 && !startValues[1].isBlank()) {
try {
query.setUnderlyingStart(Integer.parseInt(startValues[1].trim()));
} catch (NumberFormatException ex) {
throw new HCJFRuntimeException("The underlying start value must be an integer", ex);
}
}
}
}
}
for(String returnField : selectBody.split(SystemProperties.get(
SystemProperties.Query.ReservedWord.ARGUMENT_SEPARATOR))) {
query.addReturnField((QueryReturnParameter)
processStringValue(query, groups, richTexts, returnField, null, QueryReturnParameter.class, new ArrayList<>()));
}
} else {
String value = groups.get(startGroup);
int place = Strings.getNoMatchPlace(matcher, groups.get(startGroup));
String nearFrom = Strings.getNearFrom(value, place, 5);
throw new HCJFRuntimeException("Query match fail near from ( '...%s...' ), query body: '%s'", nearFrom, value);
}
return query;
}
/**
* Complete the evaluator collections with all the evaluator definitions in the groups.
* @param groups Where groups.
* @param parentCollection Parent collection.
* @param definitionIndex Definition index into the groups.
*/
private static final void completeEvaluatorCollection(Query query, String startElement, List<String> groups, List<String> richTexts,
EvaluatorCollection parentCollection,
Integer definitionIndex,
AtomicInteger placesIndex) {
Pattern wherePatter = SystemProperties.getPattern(SystemProperties.Query.EVALUATOR_COLLECTION_REGULAR_EXPRESSION, Pattern.CASE_INSENSITIVE);
String[] evaluatorDefinitions;
if(startElement != null) {
evaluatorDefinitions = wherePatter.split(startElement);
} else {
evaluatorDefinitions = wherePatter.split(groups.get(definitionIndex));
}
EvaluatorCollection collection = null;
List<String> pendingDefinitions = new ArrayList<>();
for(String definition : evaluatorDefinitions) {
definition = definition.trim();
if (definition.equalsIgnoreCase(SystemProperties.get(SystemProperties.Query.ReservedWord.AND))) {
if (collection == null) {
if(parentCollection instanceof Query || parentCollection instanceof Join || parentCollection instanceof And) {
collection = parentCollection;
} else {
collection = parentCollection.and();
}
} else if (collection instanceof Or) {
if(parentCollection instanceof Query || parentCollection instanceof Join || parentCollection instanceof And) {
collection = parentCollection;
} else {
collection = parentCollection.and();
}
}
} else if (definition.equalsIgnoreCase(SystemProperties.get(SystemProperties.Query.ReservedWord.OR))) {
if (collection == null) {
if(parentCollection instanceof Or) {
collection = parentCollection;
} else {
collection = parentCollection.or();
}
} else if(collection instanceof Query || collection instanceof Join || collection instanceof And) {
if(parentCollection instanceof Or) {
collection = parentCollection;
} else {
collection = parentCollection.or();
}
}
} else {
pendingDefinitions.add(definition);
if(collection != null) {
for(String pendingDefinition : pendingDefinitions) {
processDefinition(query, pendingDefinition, collection, groups, richTexts, placesIndex);
}
pendingDefinitions.clear();
} else if(pendingDefinitions.size() > 1) {
throw new IllegalArgumentException("");
}
}
}
for(String pendingDefinition : pendingDefinitions) {
if(collection != null) {
processDefinition(query, pendingDefinition, collection, groups, richTexts, placesIndex);
} else {
processDefinition(query, pendingDefinition, parentCollection, groups, richTexts, placesIndex);
}
}
}
/**
* Creates a conditional evaluator from string representation.
* @param definition String definition of the conditional.
* @param collection Evaluator collection to put the conditional processed.
* @param groups Sub representation of the main representation.
* @param placesIndex Place counter of the group list.
*/
private static void processDefinition(Query query, String definition, EvaluatorCollection collection, List<String> groups, List<String> richTexts, AtomicInteger placesIndex) {
String[] evaluatorValues;
Object leftValue;
Object rightValue;
String firstArgument;
String secondArgument;
String operator;
Evaluator evaluator;
if (definition.startsWith(Strings.REPLACEABLE_GROUP)) {
Integer index = Integer.parseInt(definition.replace(Strings.REPLACEABLE_GROUP, Strings.EMPTY_STRING));
completeEvaluatorCollection(query, null, groups, richTexts, collection, index, placesIndex);
} else {
evaluatorValues = definition.split(SystemProperties.get(SystemProperties.Query.OPERATION_REGULAR_EXPRESSION));
boolean operatorDone = false;
firstArgument = Strings.EMPTY_STRING;
secondArgument = Strings.EMPTY_STRING;
operator = Strings.EMPTY_STRING;
for (String evaluatorValue : evaluatorValues) {
evaluatorValue = evaluatorValue.trim();
if (evaluatorValue.equalsIgnoreCase(SystemProperties.get(SystemProperties.Query.ReservedWord.NOT))) {
operator += evaluatorValue + Strings.WHITE_SPACE;
} else if (evaluatorValue.equalsIgnoreCase(SystemProperties.get(SystemProperties.Query.ReservedWord.NOT_2))) {
operator += evaluatorValue;
} else if (evaluatorValue.equalsIgnoreCase(SystemProperties.get(SystemProperties.Query.ReservedWord.DISTINCT))
|| evaluatorValue.equalsIgnoreCase(SystemProperties.get(SystemProperties.Query.ReservedWord.DISTINCT_2))
|| evaluatorValue.equalsIgnoreCase(SystemProperties.get(SystemProperties.Query.ReservedWord.EQUALS))
|| evaluatorValue.equalsIgnoreCase(SystemProperties.get(SystemProperties.Query.ReservedWord.GREATER_THAN))
|| evaluatorValue.equalsIgnoreCase(SystemProperties.get(SystemProperties.Query.ReservedWord.GREATER_THAN_OR_EQUALS))
|| evaluatorValue.equalsIgnoreCase(SystemProperties.get(SystemProperties.Query.ReservedWord.IN))
|| evaluatorValue.equalsIgnoreCase(SystemProperties.get(SystemProperties.Query.ReservedWord.LIKE))
|| evaluatorValue.equalsIgnoreCase(SystemProperties.get(SystemProperties.Query.ReservedWord.SMALLER_THAN))
|| evaluatorValue.equalsIgnoreCase(SystemProperties.get(SystemProperties.Query.ReservedWord.SMALLER_THAN_OR_EQUALS))) {
operator += evaluatorValue;
operatorDone = true;
} else if (operatorDone) {
secondArgument += evaluatorValue + Strings.WHITE_SPACE;
} else {
firstArgument += evaluatorValue + Strings.WHITE_SPACE;
}
}
List<QueryField> presentFields = new ArrayList<>();
if (operator == null || operator.trim().isEmpty()) {
leftValue = processStringValue(query, groups, richTexts, firstArgument.trim(), placesIndex, QueryParameter.class, presentFields);
evaluator = new BooleanEvaluator(leftValue);
} else {
leftValue = processStringValue(query, groups, richTexts, firstArgument.trim(), placesIndex, QueryParameter.class, presentFields);
if (leftValue instanceof String) {
leftValue = Strings.reverseGrouping((String) leftValue, groups);
}
rightValue = processStringValue(query, groups, richTexts, secondArgument.trim(), placesIndex, QueryParameter.class, presentFields);
if (rightValue instanceof String) {
rightValue = Strings.reverseGrouping((String) rightValue, groups);
}
operator = operator.trim();
if (operator.equalsIgnoreCase(SystemProperties.get(SystemProperties.Query.ReservedWord.DISTINCT)) ||
operator.equalsIgnoreCase(SystemProperties.get(SystemProperties.Query.ReservedWord.DISTINCT_2))) {
evaluator = new Distinct(leftValue, rightValue);
} else if (operator.equalsIgnoreCase(SystemProperties.get(SystemProperties.Query.ReservedWord.EQUALS))) {
evaluator = new Equals(leftValue, rightValue);
} else if (operator.equalsIgnoreCase(SystemProperties.get(SystemProperties.Query.ReservedWord.GREATER_THAN))) {
evaluator = new GreaterThan(leftValue, rightValue);
} else if (operator.equalsIgnoreCase(SystemProperties.get(SystemProperties.Query.ReservedWord.GREATER_THAN_OR_EQUALS))) {
evaluator = new GreaterThanOrEqual(leftValue, rightValue);
} else if (operator.equalsIgnoreCase(SystemProperties.get(SystemProperties.Query.ReservedWord.IN))) {
evaluator = new In(leftValue, rightValue);
} else if (operator.equalsIgnoreCase(SystemProperties.get(SystemProperties.Query.ReservedWord.LIKE))) {
evaluator = new Like(leftValue, rightValue);
} else if (operator.equalsIgnoreCase(SystemProperties.get(SystemProperties.Query.ReservedWord.NOT_IN))) {
evaluator = new NotIn(leftValue, rightValue);
} else if (operator.equalsIgnoreCase(SystemProperties.get(SystemProperties.Query.ReservedWord.SMALLER_THAN))) {
evaluator = new SmallerThan(leftValue, rightValue);
} else if (operator.equalsIgnoreCase(SystemProperties.get(SystemProperties.Query.ReservedWord.SMALLER_THAN_OR_EQUALS))) {
evaluator = new SmallerThanOrEqual(leftValue, rightValue);
} else {
throw new HCJFRuntimeException("Unsupported operator '%s', near '%s'", operator, definition);
}
}
if(evaluator instanceof BaseEvaluator) {
((BaseEvaluator)evaluator).setEvaluatorFields(presentFields);
}
collection.addEvaluator(evaluator);
}
}
/**
* Process the string representation to obtain the specific object type.
* @param groups Sub representation of the main representation.
* @param stringValue String representation to process.
* @param placesIndex Place counter of the group list.
* @param parameterClass Parameter class.
* @return Return the specific implementation of the string representation.
*/
private static Object processStringValue(Query query, List<String> groups, List<String> richTexts, String stringValue, AtomicInteger placesIndex, Class parameterClass, List<QueryField> presentFields) {
Object result = null;
String trimmedStringValue = stringValue.trim();
if(trimmedStringValue.equals(SystemProperties.get(SystemProperties.Query.ReservedWord.REPLACEABLE_VALUE))) {
//If the string value is equals than "?" then the value object is an instance of ReplaceableValue.
result = new FieldEvaluator.ReplaceableValue(placesIndex.getAndAdd(1));
} else if(trimmedStringValue.equalsIgnoreCase(SystemProperties.get(SystemProperties.Query.ReservedWord.NULL))) {
result = null;
} else if(trimmedStringValue.equalsIgnoreCase(SystemProperties.get(SystemProperties.Query.ReservedWord.TRUE))) {
result = true;
} else if(trimmedStringValue.equalsIgnoreCase(SystemProperties.get(SystemProperties.Query.ReservedWord.FALSE))) {
result = false;
} else if(trimmedStringValue.startsWith(SystemProperties.get(SystemProperties.Query.ReservedWord.STRING_DELIMITER))) {
if (trimmedStringValue.endsWith(SystemProperties.get(SystemProperties.Query.ReservedWord.STRING_DELIMITER))) {
//If the string value start and end with "'" then the value can be a string or a date object.
trimmedStringValue = trimmedStringValue.substring(1, trimmedStringValue.length() - 1);
trimmedStringValue = richTexts.get(Integer.parseInt(trimmedStringValue.replace(Strings.REPLACEABLE_RICH_TEXT, Strings.EMPTY_STRING)));
//Clean the value to remove all the skip characters into the string value.
trimmedStringValue = trimmedStringValue.replace(Strings.RICH_TEXT_SKIP_CHARACTER + Strings.RICH_TEXT_SEPARATOR, Strings.RICH_TEXT_SEPARATOR);
try {
result = SystemProperties.getDateFormat(SystemProperties.Query.DATE_FORMAT).parse(trimmedStringValue);
} catch (Exception ex) {
//The value is not a date then the value is a string
while(trimmedStringValue.contains(Strings.REPLACEABLE_GROUP)) {
trimmedStringValue = Strings.reverseGrouping(trimmedStringValue, groups);
}
result = trimmedStringValue;
}
} else {
throw new HCJFRuntimeException("Expecting string en delimiter, near %s", trimmedStringValue);
}
} else if(trimmedStringValue.startsWith(Strings.REPLACEABLE_GROUP)) {
Integer index = Integer.parseInt(trimmedStringValue.replace(Strings.REPLACEABLE_GROUP, Strings.EMPTY_STRING));
String group = groups.get(index);
if(group.toUpperCase().startsWith(SystemProperties.get(SystemProperties.Query.ReservedWord.SELECT))) {
result = new FieldEvaluator.QueryValue(Query.compile(groups, richTexts, index));
} else {
//If the string value start with "(" and end with ")" then the value is a collection.
Collection<Object> collection = new ArrayList<>();
for (String subStringValue : group.split(SystemProperties.get(SystemProperties.Query.ReservedWord.ARGUMENT_SEPARATOR))) {
collection.add(processStringValue(query, groups, richTexts, subStringValue.trim(), placesIndex, parameterClass, presentFields));
}
result = collection;
}
} else if(trimmedStringValue.matches(SystemProperties.get(SystemProperties.HCJF_UUID_REGEX))) {
result = UUID.fromString(trimmedStringValue);
} else if(trimmedStringValue.matches(SystemProperties.get(SystemProperties.HCJF_INTEGER_NUMBER_REGEX))) {
result = Long.parseLong(trimmedStringValue);
} else if(trimmedStringValue.matches(SystemProperties.get(SystemProperties.HCJF_DECIMAL_NUMBER_REGEX))) {
try {
result = SystemProperties.getDecimalFormat(SystemProperties.Query.DECIMAL_FORMAT).parse(trimmedStringValue);
} catch (ParseException e) {
throw new HCJFRuntimeException("Unable to parse decimal number");
}
} else if(trimmedStringValue.matches(SystemProperties.get(SystemProperties.HCJF_SCIENTIFIC_NUMBER_REGEX))) {
try {
result = SystemProperties.getDecimalFormat(SystemProperties.Query.SCIENTIFIC_NOTATION_FORMAT).parse(trimmedStringValue);
} catch (ParseException e) {
throw new HCJFRuntimeException("Unable to parse scientific number");
}
} else if(trimmedStringValue.matches(SystemProperties.get(SystemProperties.HCJF_MATH_CONNECTOR_REGULAR_EXPRESSION)) &&
trimmedStringValue.matches(SystemProperties.get(SystemProperties.HCJF_MATH_REGULAR_EXPRESSION))) {
String alias = null;
String[] asParts = trimmedStringValue.split(SystemProperties.get(SystemProperties.Query.AS_REGULAR_EXPRESSION));
if(asParts.length == 3) {
trimmedStringValue = asParts[0].trim();
alias = asParts[2].trim();
}
//If the string matchs with a math expression then creates a function that resolves this math expression.
String[] mathExpressionParts = trimmedStringValue.split(SystemProperties.get(SystemProperties.HCJF_MATH_SPLITTER_REGULAR_EXPRESSION));
List<Object> parameters = new ArrayList<>();
String currentValue;
boolean desc = false;
for (int i = 0; i < mathExpressionParts.length; i++) {
currentValue = mathExpressionParts[i];
if(i == mathExpressionParts.length - 1){
//This code run only one time for the last part.
if(parameterClass.equals(QueryReturnParameter.class)) {
//Check if the last part contains the 'AS' word
String[] parts = currentValue.split(SystemProperties.get(SystemProperties.Query.AS_REGULAR_EXPRESSION));
if (parts.length == 2) {
currentValue = parts[0].trim();
alias = parts[1].trim();
}
} else if(parameterClass.equals(QueryOrderParameter.class)) {
//Check if the last part contains the 'DESC' word
String[] parts = currentValue.split(SystemProperties.get(SystemProperties.Query.DESC_REGULAR_EXPRESSION));
if(parts.length == 3) {
currentValue = parts[0].trim();
if(parts[2].trim().equalsIgnoreCase(SystemProperties.get(SystemProperties.Query.ReservedWord.DESC))) {
desc = true;
}
}
}
}
if(currentValue.matches(SystemProperties.get(SystemProperties.HCJF_MATH_CONNECTOR_REGULAR_EXPRESSION))) {
//If the current value is a math connector (+-*/) the this connector is a function parameter.
parameters.add(currentValue.trim());
} else {
//If the current value is not a math connector then this string is evaluated recursively.
parameters.add(processStringValue(query, groups, richTexts, currentValue, placesIndex, QueryParameter.class, presentFields));
}
}
if(parameterClass.equals(QueryParameter.class)) {
result = new QueryFunction(query, Strings.reverseGrouping(trimmedStringValue, groups),
SystemProperties.get(SystemProperties.Query.Function.MATH_EVAL_EXPRESSION_NAME), parameters);
} else if(parameterClass.equals(QueryReturnParameter.class)) {
result = new QueryReturnFunction(query, Strings.reverseGrouping(trimmedStringValue, groups),
SystemProperties.get(SystemProperties.Query.Function.MATH_EVAL_EXPRESSION_NAME), parameters, alias);
} else if(parameterClass.equals(QueryOrderParameter.class)) {
result = new QueryOrderFunction(query, Strings.reverseGrouping(trimmedStringValue, groups),
SystemProperties.get(SystemProperties.Query.Function.MATH_EVAL_EXPRESSION_NAME), parameters, desc);
}
} else {
//Default case, only must be a query parameter.
String functionName = null;
String originalValue = null;
String replaceValue = null;
String group = null;
List<Object> functionParameters = null;
Boolean function = false;
if(trimmedStringValue.contains(Strings.REPLACEABLE_GROUP)) {
//If the string contains a replaceable group character then the parameter is a function.
replaceValue = Strings.getGroupIndex(trimmedStringValue);
group = groups.get(Integer.parseInt(replaceValue.replace(Strings.REPLACEABLE_GROUP,Strings.EMPTY_STRING)));
functionName = trimmedStringValue.substring(0, trimmedStringValue.indexOf(Strings.REPLACEABLE_GROUP));
originalValue = trimmedStringValue.replace(replaceValue, Strings.START_GROUP + group + Strings.END_GROUP);
functionParameters = new ArrayList<>();
for(String param : group.split(SystemProperties.get(SystemProperties.Query.ReservedWord.ARGUMENT_SEPARATOR))) {
functionParameters.add(processStringValue(query, groups, richTexts, param, placesIndex, parameterClass, presentFields));
}
function = true;
} else {
originalValue = trimmedStringValue;
}
if(parameterClass.equals(QueryParameter.class)) {
//If the parameter class is the default class then the result will be a
//QueryFunction.class instance or QueryField.class instance.
if(function) {
result = new QueryFunction(query, originalValue, functionName, functionParameters);
} else {
result = new QueryField(query, trimmedStringValue);
}
} else if(parameterClass.equals(QueryReturnParameter.class)) {
//If the parameter class is the QueryReturnParameter.class then the result will be a
//QueryReturnFunction.class instance or QueryReturnField.class instance.
String alias = null;
String[] parts = originalValue.split(SystemProperties.get(SystemProperties.Query.AS_REGULAR_EXPRESSION));
if(parts.length == 3) {
originalValue = parts[0].trim();
alias = parts[2].trim();
}
if(function) {
result = new QueryReturnFunction(query, originalValue, functionName, functionParameters, alias);
} else {
result = new QueryReturnField(query, originalValue, alias);
}
} else if(parameterClass.equals(QueryOrderParameter.class)) {
//If the parameter class is the QueryOrderParameter.class then the result will be a
//QueryOrderFunction.class instance or QueryOrderField.class instance.
boolean desc = false;
String[] parts = originalValue.split(SystemProperties.get(SystemProperties.Query.DESC_REGULAR_EXPRESSION));
if(parts.length == 2) {
originalValue = parts[0].trim();
if(parts[1].trim().equalsIgnoreCase(SystemProperties.get(SystemProperties.Query.ReservedWord.DESC))) {
desc = true;
}
}
if(function) {
result = new QueryOrderFunction(query, originalValue, functionName, functionParameters, desc) ;
} else {
result = new QueryOrderField(query, originalValue, desc);
}
}
}
if(result instanceof QueryField) {
presentFields.add((QueryField) result);
}
return result;
}
@Override
public boolean equals(Object obj) {
return (obj instanceof Query) && obj.toString().equals(toString());
}
/**
* Represents an query id. Wrapper of the UUID class.
*/
public static final class QueryId {
private final UUID id;
private QueryId() {
this.id = UUID.randomUUID();
}
public QueryId(UUID id) {
this.id = id;
}
/**
* Get the UUID instance.
* @return UUID instance.
*/
public UUID getId() {
return id;
}
}
/**
* Group all the query components.
*/
public interface QueryComponent {
/**
* Verify if the component is underlying.
* @return True if the component is underlying.
*/
boolean isUnderlying();
}
/**
* Represents any kind of resource.
*/
public static class QueryResource implements Comparable<QueryResource>, QueryComponent {
public static final QueryResource ANY = new QueryResource(Strings.ALL);
private String resourceName;
public QueryResource(String resourceName) {
this.resourceName = resourceName;
}
/**
* Set the name of the resource.
* @param resourceName Name of the resource
*/
public void setResourceName(String resourceName) {
this.resourceName = resourceName;
}
/**
* Return the resource name.
* @return Resource name.
*/
public String getResourceName() {
return resourceName;
}
@Override
public boolean equals(Object obj) {
boolean result = false;
if(obj instanceof QueryResource) {
result = resourceName.equals(((QueryResource)obj).getResourceName());
}
return result;
}
@Override
public boolean isUnderlying() {
return false;
}
@Override
public int compareTo(QueryResource o) {
return resourceName.compareTo(o.getResourceName());
}
@Override
public String toString() {
return getResourceName();
}
}
public static abstract class QueryParameter implements Comparable<QueryParameter>, QueryComponent {
private QueryResource resource;
private String fieldPath;
private final String originalValue;
private final boolean underlying;
public QueryParameter(Query query, String originalValue, String value) {
this.originalValue = originalValue.trim();
String cleanValue = value;
if(cleanValue.startsWith(Strings.AT)) {
cleanValue = value.substring(1);
underlying = true;
} else {
underlying = false;
}
this.resource = QueryResource.ANY;
if(cleanValue.contains(Strings.CLASS_SEPARATOR)) {
boolean resourceNameFounded = false;
for(QueryResource queryResource : query.getResources()) {
if(originalValue.startsWith(queryResource.resourceName + ".")) {
this.resource = queryResource;
resourceNameFounded = true;
break;
}
}
if(resourceNameFounded) {
this.fieldPath = cleanValue.substring((resource.resourceName).length() + 1);
} else {
this.fieldPath = cleanValue;
}
} else {
this.fieldPath = cleanValue;
}
}
/**
* Returns the resource of this parameter.
* @return Resource of this parameter.
*/
public QueryResource getResource() {
return resource;
}
/**
* Returns the field path.
* @return Field path.
*/
public String getFieldPath() {
return fieldPath;
}
/**
* Returns the original value.
* @return Original value.
*/
public String getOriginalValue() {
return originalValue;
}
/**
* Return the original representation of the field.
* @return Original representation.
*/
@Override
public String toString() {
return originalValue;
}
/**
* This method returns true if the component is underlying and false in the otherwise.
* @return Underlying value.
*/
@Override
public boolean isUnderlying() {
return underlying;
}
/**
* Compare the original value of the fields.
* @param obj Other field.
* @return True if the fields are equals.
*/
@Override
public boolean equals(Object obj) {
return toString().equals(obj.toString());
}
/**
* Compare the string representation of both objects.
* @param o Other object.
* @return Magnitude of the difference between both objects.
*/
@Override
public int compareTo(QueryParameter o) {
return toString().compareTo(o.toString());
}
/**
* Verify if the query parameter make reference to the specified resource.
* @param resource Resource instance to test.
* @return Returns true if the parameter make reference to the specified resource and false in the otherwise.
*/
public abstract boolean verifyResource(QueryResource resource);
}
public static class QueryFunction extends QueryParameter {
private final String functionName;
private final List<Object> parameters;
public QueryFunction(Query query, String originalFunction, String functionName, List<Object> parameters) {
super(query, originalFunction, functionName);
this.functionName = functionName;
this.parameters = parameters;
}
public String getFunctionName() {
return functionName;
}
public List<Object> getParameters() {
return parameters;
}
public Set<QueryResource> getResources() {
Set<QueryResource> queryResources = new TreeSet<>();
for(Object parameter : parameters) {
if(parameter instanceof QueryField) {
queryResources.add(((QueryField)parameter).getResource());
} else if(parameter instanceof QueryFunction) {
queryResources.addAll(((QueryFunction)parameter).getResources());
}
}
return queryResources;
}
@Override
public boolean verifyResource(QueryResource resource) {
return getResources().contains(resource);
}
}
/**
* This class represents any kind of query fields.
*/
public static class QueryField extends QueryParameter {
public QueryField(Query query, String fieldPath) {
super(query, fieldPath, fieldPath);
}
/**
* This method resolves the introspection over the instance using the information into the
* query field.
* @param instance Instance to resolve the introspection.
* @param <R> Expected data type.
* @return Introspection result.
*/
public <R extends Object> R resolve(Object instance) {
Object result = null;
if(instance instanceof JoinableMap && !((JoinableMap) instance).getResources().isEmpty()) {
if(getResource().equals(Query.QueryResource.ANY)) {
for(String resourceName : ((JoinableMap)instance).getResources()) {
result = Introspection.resolve(((JoinableMap) instance).
getResourceModel(resourceName), getFieldPath());
if(result != null) {
break;
}
}
} else {
result = Introspection.resolve(((JoinableMap) instance).
getResourceModel(getResource().getResourceName()), getFieldPath());
}
} else {
result = Introspection.resolve(instance, getFieldPath());
}
return (R) result;
}
@Override
public boolean verifyResource(QueryResource resource) {
return getResource().equals(resource);
}
}
public interface QueryReturnParameter extends QueryComponent {
/**
* Return the field alias, can be null.
* @return Field alias.
*/
String getAlias();
}
/**
* This kind of component represent the fields to be returned into the query.
*/
public static class QueryReturnField extends QueryField implements QueryReturnParameter {
private final String alias;
public QueryReturnField(Query query, String fieldPath) {
this(query, fieldPath, fieldPath);
}
public QueryReturnField(Query query, String fieldPath, String alias) {
super(query, fieldPath);
if(alias == null) {
this.alias = fieldPath;
} else {
this.alias = alias;
}
}
/**
* Return the field alias, can be null.
* @return Field alias.
*/
public String getAlias() {
return alias;
}
}
public static class QueryReturnFunction extends QueryFunction implements QueryReturnParameter {
private final String alias;
private boolean aggregate;
public QueryReturnFunction(Query query, String originalFunction, String functionName, List<Object> parameters, String alias) {
super(query, originalFunction, functionName, parameters);
aggregate = false;
try {
QueryAggregateFunctionLayerInterface aggregateFunctionLayerInterface =
Layers.get(QueryAggregateFunctionLayerInterface.class,
SystemProperties.get(SystemProperties.Query.Function.NAME_PREFIX) +functionName);
aggregate = aggregateFunctionLayerInterface != null;
} catch (Exception ex){}
if(alias != null) {
this.alias = alias;
} else {
this.alias = originalFunction;
}
}
/**
* Return the field alias, can be null.
* @return Field alias.
*/
public String getAlias() {
return alias;
}
/**
* Verify if the function is an aggregate function or not.
* @return True if the function is an aggregate function and false in the otherwise.
*/
public boolean isAggregate() {
return aggregate;
}
}
public interface QueryOrderParameter extends QueryComponent {
/**
* Return the desc property.
* @return Desc property.
*/
boolean isDesc();
}
/**
* This class represents a order field with desc property
*/
public static class QueryOrderField extends QueryField implements QueryOrderParameter {
private final boolean desc;
public QueryOrderField(Query query, String fieldPath, boolean desc) {
super(query, fieldPath);
this.desc = desc;
}
/**
* Return the desc property.
* @return Desc property.
*/
public boolean isDesc() {
return desc;
}
}
public static class QueryOrderFunction extends QueryFunction implements QueryOrderParameter {
private final boolean desc;
public QueryOrderFunction(Query query, String originalFunction, String functionName, List<Object> parameters, boolean desc) {
super(query, originalFunction, functionName, parameters);
this.desc = desc;
}
/**
* Return the desc property.
* @return Desc property.
*/
public boolean isDesc() {
return desc;
}
}
/**
* This inner class implements the custom method to create a query instance from a bson document.
*/
public static class QueryBsonBuilderLayer extends Layer implements BsonCustomBuilderLayer<Query> {
public QueryBsonBuilderLayer() {
super(Query.class.getName());
}
/**
* This implementation required that the document contains a field called '__query__' to create the query instance.
* @param document Bson document.
* @return Returns a query instance.
*/
@Override
public Query create(BsonDocument document) {
return Query.compile(document.get(QUERY_BSON_FIELD_NAME).getAsString());
}
}
}
|
package org.icij.task;
import org.icij.time.HumanDuration;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.Duration;
import java.util.*;
import java.util.function.Function;
import java.util.function.Supplier;
public class DefaultOption implements Option<DefaultOption, String, String> {
private static class DefaultSupplier implements Supplier<List<String>> {
private final List<String> values = new LinkedList<>();
@Override
public List<String> get() {
return values;
}
}
private final String name;
private Character code = null;
private String description = null;
private String parameter = null;
protected Supplier<List<String>> values = new DefaultSupplier();
private DefaultOption(final String name) {
this.name = name;
}
@Override
public Optional<Duration> asDuration() {
return value(HumanDuration::parse);
}
@Override
public Optional<Path> asPath() {
return value(Paths::get);
}
@Override
public Optional<Integer> asInteger() {
return value(Integer::valueOf);
}
@Override
public Optional<Boolean> asBoolean() {
return value((value)-> {
value = value.toLowerCase(Locale.ROOT);
if (value.equals("yes") || value.equals("on") || value.equals("true") || value.equals("1")) {
return Boolean.TRUE;
}
return Boolean.FALSE;
});
}
@Override
public boolean on() {
final Optional<Boolean> toggle = asBoolean();
return toggle.isPresent() && toggle.get();
}
@Override
public boolean off() {
final Optional<Boolean> toggle = asBoolean();
return toggle.isPresent() && !toggle.get();
}
@Override
public <E extends Enum<E>> Optional<E> asEnum(final Function<String, E> valueOf) {
return value(valueOf);
}
@Override
public DefaultOption code(final Character code) {
this.code = code;
return this;
}
@Override
public DefaultOption describe(final String description) {
this.description = description;
return this;
}
@Override
public String description() {
return description;
}
@Override
public String name() {
return name;
}
@Override
public Character code() {
return code;
}
@Override
public String parameter() {
return parameter;
}
@Override
public DefaultOption parameter(final String parameter) {
this.parameter = parameter;
return this;
}
@Override
public synchronized Optional<String> value() {
final List<String> values = this.values.get();
if (!values.isEmpty()) {
return Optional.of(values.get(0));
}
return Optional.empty();
}
@Override
public synchronized String[] values() {
final List<String> values = this.values.get();
return values.toArray(new String[values.size()]);
}
@Override
public synchronized DefaultOption update(final String value) {
final List<String> values = this.values.get();
values.clear();
values.add(value);
return this;
}
@Override
public synchronized DefaultOption update(final String[] values) {
this.values.get().clear();
this.values.get().addAll(Arrays.asList(values));
return this;
}
@Override
public synchronized DefaultOption update(final Supplier<List<String>> supplier) {
values = supplier;
return this;
}
@Override
public synchronized <R> Optional<R> value(final Function<String, R> parser) {
final List<String> values = this.values.get();
if (values.isEmpty()) {
return Optional.empty();
}
return Optional.of(parser.apply(values.get(0)));
}
@Override
public synchronized <R> Collection<R> values(final Function<String, R> parser) {
final List<String> values = this.values.get();
final Collection<R> results = new ArrayList<>(values.size());
for (String value : values) {
results.add(parser.apply(value));
}
return results;
}
public static class Set extends Option.Set<DefaultOption> {
@Override
public DefaultOption get(final String name) {
return super.get(name);
}
@Override
public DefaultOption.Set add(final DefaultOption option) {
map.put(option.name(), option);
return this;
}
@Override
public DefaultOption add(final String name) {
final DefaultOption option = new DefaultOption(name);
add(option);
return option;
}
}
}
|
package org.made.neohabitat;
import java.util.*;
import java.util.regex.Pattern;
import org.elkoserver.foundation.json.JSONMethod;
import org.elkoserver.foundation.json.OptBoolean;
import org.elkoserver.foundation.json.OptInteger;
import org.elkoserver.json.EncodeControl;
import org.elkoserver.json.JSONLiteral;
import org.elkoserver.server.context.BasicObject;
import org.elkoserver.server.context.Item;
import org.elkoserver.server.context.User;
import org.made.neohabitat.mods.Avatar;
import org.made.neohabitat.mods.Game_piece;
import org.made.neohabitat.mods.Paper;
import org.made.neohabitat.mods.Region;
import org.made.neohabitat.mods.Tokens;
/**
* an Elko Habitat superclass to handle magic state and specific behaviors.
*
* 1988 PL1 didn't understand classes. Chip wrote the Habitat code, simulating
* structures, classes, and a form of class inheritance by concatenating include
* files and careful management of procedure references.
*
*/
public abstract class Magical extends HabitatMod {
/** An index to the magic method to call for this item. 0 == not magical. */
protected int magic_type = 0;
/** How many more times can this magical item be activated? */
protected int charges = 0;
/** Per-type magic state - true type to be bound at execution time */
protected int magic_data = 0;
/** Per-type magic state - true type to be bound at execution time */
protected int magic_data2 = 0;
/** Per-type magic state - true type to be bound at execution time */
protected int magic_data3 = 0;
/** Per-type magic state - true type to be bound at execution time */
protected int magic_data4 = 0;
/** Per-type magic state - true type to be bound at execution time */
protected int magic_data5 = 0;
private static final int NO_CHARGES = -1;
public static final String[] TRICORDER_HELP = new String[]{
"The Tricorder helps you to get around",
"Habitat and meet new Avatars.",
"Commands:",
"h/help - Shows this help",
"l/listteleport - List teleport booths",
"l/listteleport PREFIX - Find booths",
"t/teleport WHERE - Teleport to booth",
"g/goavatar AVATAR - Goto Avatar",
"r/random - Teleport to a random booth",
"q/quit - Deactivates Tricorder"
};
public static final int MAX_RANDOM_TELEPORT_RETRIES = 50;
public Magical(OptInteger style, OptInteger x, OptInteger y, OptInteger orientation, OptInteger gr_state, OptBoolean restricted,
OptInteger magic_type, OptInteger charges, OptInteger magic_data, OptInteger magic_data2,
OptInteger magic_data3, OptInteger magic_data4, OptInteger magic_data5) {
super(style, x, y, orientation, gr_state, restricted);
setMagicalState(magic_type.value(0),
charges.value(NO_CHARGES),
magic_data.value(0),
magic_data2.value(0),
magic_data3.value(0),
magic_data4.value(0),
magic_data5.value(0));
}
public Magical(int style, int x, int y, int orientation, int gr_state, boolean restricted,
int magic_type, int charges, int magic_data, int magic_data2, int magic_data3, int magic_data4, int magic_data5) {
super(style, x, y, orientation, gr_state, restricted);
setMagicalState(magic_type, charges, magic_data, magic_data2, magic_data3, magic_data4, magic_data5);
}
protected void setMagicalState(int magic_type, int charges, int magic_data,
int magic_data2, int magic_data3, int magic_data4, int magic_data5) {
this.magic_type = magic_type;
this.charges = charges;
this.magic_data = magic_data;
this.magic_data2 = magic_data2;
this.magic_data3 = magic_data3;
this.magic_data4 = magic_data4;
this.magic_data5 = magic_data5;
}
public JSONLiteral encodeMagical(JSONLiteral result) {
result = super.encodeCommon(result);
if (pc_state_bytes() == 0 && result.control().toClient())
return result;
result.addParameter("magic_type", magic_type);
if (result.control().toRepository()) {
if (NO_CHARGES != charges) {
result.addParameter("charges", charges);
}
if (0 != magic_data) {
result.addParameter("magic_data", magic_data);
}
if (0 != magic_data2) {
result.addParameter("magic_data2", magic_data2);
}
if (0 != magic_data3) {
result.addParameter("magic_data3", magic_data3);
}
if (0 != magic_data4) {
result.addParameter("magic_data4", magic_data4);
}
if (0 != magic_data5) {
result.addParameter("magic_data5", magic_data4);
}
}
return result;
}
/** The number of magical methods available. NOTE: This is expandable */
private final static int NUMBER_OF_MAGICS = 31; /* This should grow! */
private final static int MAGIC_GOD_TOOL = 17;
private final static int TRICORDER_TOOL = 31;
/**
* Verb (Magical): Activate any magic on this, if there are charges left.
*
* @param from
* User representing the connection making the request.
* @param target
* TODO Why would we trust the client to specify a magic type?
*/
@JSONMethod({ "target" })
public void MAGIC(User from, OptInteger target) {
JSONLiteral msg = new JSONLiteral("changeposture", EncodeControl.forClient);
msg.addParameter("noid", avatar(from).noid);
msg.addParameter("newposture", OPERATE);
context().sendToNeighbors(from, msg);
if (!expendCharge(from)) {
send_reply_error(from);
return;
}
HabitatMod targetMod = current_region().noids[target.value(0)];
switch (magic_type) {
case 0:
/* not magical */
break;
case 1:
change_user_height(from);
break;
case 2:
make_target_avatar_jump(from, targetMod);
break;
case 3:
make_other_avatars_turn_blue(from);
break;
case 4:
send_target_avatar_home(from, targetMod);
break;
case 5:
magic_default(from, targetMod);
break;
case 6:
magic_default(from, targetMod);
break;
case 7:
magic_default(from, targetMod);
break;
case 8:
magic_default(from, targetMod);
break;
case 9:
change_avatar_style(from, targetMod);
break;
case 10:
magic_default(from, targetMod);
break;
case 11:
make_user_moonwalk(from);
break;
case 12:
switch_reset_chess(from);
break;
case 13:
switch_reset_checkers(from);
break;
case 14:
switch_reset_backgammon(from);
break;
case 15:
magic_default(from, targetMod);
break;
case 16:
magic_default(from, targetMod);
break;
case MAGIC_GOD_TOOL:
god_tool(from, targetMod);
break;
case 18:
magic_default(from, targetMod);
break;
case 19:
magic_default(from, targetMod);
break;
case 20:
magic_default(from, targetMod);
break;
case 21:
magic_default(from, targetMod);
break;
case 22:
magic_default(from, targetMod);
break;
case 23:
magic_default(from, targetMod);
break;
case 24:
money_tree(from, targetMod);
break;
case 25:
magic_default(from, targetMod);
break;
case 26:
magic_default(from, targetMod);
break;
case 27:
magic_default(from, targetMod);
break;
case 28:
magic_default(from, targetMod);
break;
case 29:
random_porter(from, targetMod);
break;
case 30:
magic_default(from, targetMod);
break;
case TRICORDER_TOOL:
tricorder(from, targetMod);
break;
}
}
private boolean expendCharge(User from) {
if (charges == NO_CHARGES)
return true;
if (charges == 0) {
object_say(from, noid, "This device is out of charge.");
return false;
}
charges = charges - 1;
gen_flags[MODIFIED] = true;
checkpoint_object(this);
return true;
}
private void magic_default(User from, HabitatMod target) {
object_broadcast(noid, "It's broken. Throw it away.");
}
private void change_user_height(User from) {
Avatar avatar = avatar(from);
int o = avatar.orientation;
avatar.orientation = (o & 0b11000111) | ((o + 16) & 0b00111000);
modify_variable(from, avatar, C64_ORIENT_OFFSET, avatar.orientation);
object_broadcast(noid, ">BAMPF<");
send_reply_success(from);
}
private void make_target_avatar_jump(User from, HabitatMod target) {
Avatar avatar = (Avatar) avatar_target_check(target);
if (avatar != null) {
object_broadcast(noid, "Ha!");
if (magic_data < AV_ACT_stand || magic_data > AV_ACT_sit_front) {
send_broadcast_msg(avatar.noid, "POSTURE$", "new_posture", AV_ACT_jump);
} else {
send_broadcast_msg(avatar.noid, "POSTURE$", "new_posture", magic_data);
}
send_reply_success(from);
} else {
object_say(from, "Nothing happens.");
send_reply_error(from);
}
}
private void make_other_avatars_turn_blue(User from) {
Region region = current_region();
Avatar avatar = avatar(from);
int turned = 0;
for (int i = 1; i < 255; i++) {
HabitatMod obj = region.noids[i];
if (obj != null && obj.HabitatClass() == CLASS_AVATAR && avatar.noid != obj.noid) {
Avatar target = (Avatar) obj;
turned++;
target.custom[0] = 0;
target.custom[1] = 0;
target.gen_flags[MODIFIED] = true;
send_fiddle_msg(THE_REGION, target.noid, C64_CUSTOMIZE_OFFSET, new int[] {0, 0});
}
}
if (turned > 0) {
object_broadcast(noid, "Isn't Blue awesome?");
send_reply_success(from);
} else {
object_say(from, "Nothing happens.");
send_reply_error(from);
}
}
private Avatar avatar_target_check(HabitatMod target) {
if (target == null)
return null;
if (target.HabitatClass() == CLASS_AVATAR)
return (Avatar) target;
if (target.HabitatClass() != CLASS_HEAD)
return null;
HabitatMod cont = target.container();
if (cont.HabitatClass() == CLASS_AVATAR && target.y == HEAD)
return (Avatar) cont;
return null;
}
private void send_target_avatar_home(User from, HabitatMod target ) {
Avatar avatar = (Avatar) avatar_target_check(target);
if (avatar != null) {
object_broadcast(noid, "Poof!");
send_reply_success(from);
/* Send the target home! */
avatar.x = 80;
avatar.y = 132;
avatar.change_regions(avatar.turf, AUTO_TELEPORT_DIR, TELEPORT_ENTRY);
} else {
object_say(from, "Nothing happens.");
send_reply_error(from);
}
}
private void change_avatar_style(User from, HabitatMod target) {
Avatar avatar = (Avatar) avatar_target_check(target);
Region region = current_region();
if (target != null && magic_data != 0) {
int new_style = 0;
int saved_style = style;
if (avatar.style != magic_data)
new_style = magic_data;
note_instance_deletion(target);
target.style = new_style;
note_object_creation(target);
if (mem_checks_ok(target)) {
object_broadcast(noid, "Yikes!");
send_reply_success(from);
avatar.change_regions(region.obj_id(), AUTO_TELEPORT_DIR, TELEPORT_ENTRY);
} else {
note_instance_deletion(target);
target.style = saved_style;
note_object_creation(target);
object_say(from, "That won't work here now.");
send_reply_error(from);
}
} else {
object_say(from, "Nothing happens.");
send_reply_error(from);
}
}
private void make_user_moonwalk(User from) {
Avatar avatar = avatar(from);
int g = avatar.gr_state;
avatar.gr_state = (g & 0b11111110) | ((g + 1) & 0x00000001);
send_fiddle_msg(THE_REGION, avatar.noid, C64_GR_STATE_OFFSET, g);
object_broadcast(noid, "POOF!!!");
send_reply_success(from);
}
/**
* The money tree drops a token in the denomination of magic_data on the ground for each user exactly one time.
*
* @param from
* @param target
*/
private void money_tree(User from, HabitatMod target) {
Avatar avatar = avatar(from);
Region region = current_region();
if (avatar.nitty_bits[MISC_FLAG3]) {
object_say(from, "Sorry! One to a customer!");
send_reply_error(from);
} else {
Tokens tokens = new Tokens(0, avatar.x, avatar.y - 1, 0, 0, false, magic_data & 0xFF, (magic_data & 0xFF00) >> 8);
Item item = create_object("Money Tree Tokens", tokens, region, false);
if (item == null)
return;
announce_object(item, region);
avatar.nitty_bits[MISC_FLAG3] = true;
avatar.gen_flags[MODIFIED] = true;
gen_flags[MODIFIED] = true;
object_say(from, "There you go. Enjoy!");
send_reply_success(from);
}
}
private static final int CHESS = 0;
private static final int CHECKERS = 1;
private static final int BACKGAMMON = 2;
private static final int X_INIT = 0;
private static final int Y_INIT = 1;
private static final int O_INIT = 2;
private static final int G_INIT = 3;
private static int [][][] BOARDGAME_PARAMS = {
// Chess
{ { 32, 44, 56, 68, 80, 92, 104, 116, 32, 44, 56, 68, 80, 92, 104, 116, 32, 44, 56, 68, 80, 92, 104, 116, 32, 44, 56, 68, 80, 92, 104, 116},
{ 97, 97, 97, 97, 97, 97, 97, 97, 113, 113, 113, 113, 113, 113, 113, 113, 17, 17, 17, 17, 17, 17, 17, 17, 1, 1, 1, 1, 1, 1, 1, 1},
{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16},
{ 0, 0, 0, 0, 0, 0, 0, 0, 3, 2, 1, 5, 4, 1, 2, 3, 0, 0, 0, 0, 0, 0, 0, 0, 3, 2, 1, 5, 4, 1, 2, 3}
},
// Checkers
{ { 32, 56, 80, 104, 44, 68, 92, 116, 32, 56, 80, 104, 44, 68, 92, 116, 32, 56, 80, 104, 44, 68, 92, 116},
{ 1, 1, 1, 1, 17, 17, 17, 17, 33, 33, 33, 33, 81, 81, 81, 81, 97, 97, 97, 97, 113, 113, 113, 113},
{ 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
{ 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6}
},
// Backgammon
{ { 24, 24, 72, 72, 72, 72, 72, 112, 112, 112, 148, 148, 148, 148, 148, 24, 24, 72, 72, 72, 72, 72, 112, 112, 112, 148, 148, 148, 148, 148},
{115, 103, 49, 37, 25, 13, 1, 25, 13, 1, 115, 103, 91, 79, 195, 13, 1, 115, 103, 91, 79, 67, 115, 103, 91, 49, 37, 25, 13, 1},
{ 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
{ 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8 }
} };
private void switch_reset_chess(User from) {
reset_generic_boardgame(from, CHESS);
}
private void switch_reset_checkers(User from) {
reset_generic_boardgame(from, CHECKERS);
}
private void switch_reset_backgammon(User from) {
reset_generic_boardgame(from, BACKGAMMON);
}
private void reset_generic_boardgame(User from, int game) {
int [] x_int = BOARDGAME_PARAMS[game][X_INIT];
int [] y_int = BOARDGAME_PARAMS[game][Y_INIT];
int [] o_int = BOARDGAME_PARAMS[game][O_INIT];
int [] g_int = BOARDGAME_PARAMS[game][G_INIT];
Region region = current_region();
send_reply_success(from);
// Delete all the old pieces... This deals with the case if some pieces leave...
for (int i = 1; i <255; i ++) {
HabitatMod target = region.noids[i];
if (null != target && target.HabitatClass() == CLASS_GAME_PIECE) {
send_goaway_msg(target.noid);
target.destroy_object(target);
}
}
int xoff = magic_data;
int yoff = magic_data2;
// Create new pieces from scratch, all set up properly.
for (int p = 0; p < x_int.length; p++) {
Game_piece piece = new Game_piece(0, x_int[p] + xoff, y_int[p] + yoff, o_int[p], g_int[p], true);
Item item = create_object("Game Piece", piece, region, false);
if (item != null)
announce_object(item, region);
}
}
private String identifyTarget(HabitatMod target) {
return "" + target.noid + ":" + target.obj_id();
}
private void god_tool(User from, HabitatMod target) {
Avatar avatar = avatar(from);
avatar.savedTarget = target; // Save the target for future GOD TOOL
// commands. Does not persist.
avatar.savedMagical = this; // We have to return to this object to keep
// running GOD commands.
if (!avatar.nitty_bits[GOD_FLAG]) {
object_say(from, "Nothing happens.");
message_to_god(this, avatar, "UNAUTHORIZED USE OF A GOD TOOL!");
send_reply_error(from);
} else {
object_say(from, identifyTarget(target) + " - Remember to exit GOD MODE before changing regions.");
send_private_msg(from, THE_REGION, from, "PROMPT_USER_$", GOD_TOOL_PROMPT + " ");
send_reply_success(from);
}
}
private void modify_variable(User from, HabitatMod target, int offset, int new_value) {
target.gen_flags[MODIFIED] = true;
send_fiddle_msg(THE_REGION, target.noid, offset, new_value);
}
/**
* Is the magical object actually a GOD TOOL?
*
* @param magic
* @return
*/
static public boolean isGodTool(Magical magic) {
return (magic.magic_type == MAGIC_GOD_TOOL);
}
public void tricorder(User from, HabitatMod target) {
Avatar avatar = avatar(from);
avatar.savedTarget = target;
avatar.savedMagical = this; // We have to return to this object to keep
object_say(from, "Tricorder activated.");
object_say(from, "Enter h for help.");
send_private_msg(from, THE_REGION, from, "PROMPT_USER_$", TRICORDER_PROMPT + " ");
send_reply_success(from);
}
/** CALLBACK for the Tricorder device
*
* @param from User holding the Tricorder device
* @param request_string contents of a user's command
*/
public void tricorder_revisited(User from, String request_string) {
Avatar avatar = avatar(from);
String[] split_command = request_string.split(" ");
String command = split_command[0];
String[] args = Arrays.copyOfRange(split_command, 1, split_command.length);
boolean hasArgs = args.length > 0;
@SuppressWarnings("unchecked")
TreeMap<String, String> directory = new TreeMap<>(
(Map <String, String>) context().getStaticObject("teleports"));
switch (command.toLowerCase()) {
case "g":
case "goavatar":
if (!hasArgs) {
send_private_msg(from, THE_REGION, from, "PROMPT_USER_$", TRICORDER_PROMPT + " ");
object_say(from, "Please enter a valid Avatar name.");
break;
}
User user = Region.getUserByName(args[0]);
if (user != null) {
Avatar otherAvatar = avatar(user);
if (current_region().object().ref().equals(otherAvatar.lastArrivedIn)) {
send_private_msg(from, THE_REGION, from, "PROMPT_USER_$", TRICORDER_PROMPT + " ");
object_say(from, "You're already there!");
} else if (Region.IsRoomForMyAvatarIn(otherAvatar.lastArrivedIn, from)) {
avatar.x = SAFE_X;
avatar.y = SAFE_Y;
avatar.action = STAND;
avatar.change_regions(otherAvatar.lastArrivedIn, AUTO_TELEPORT_DIR, TELEPORT_ENTRY);
} else {
send_private_msg(from, THE_REGION, from, "PROMPT_USER_$", TRICORDER_PROMPT + " ");
object_say(from, "Flash crowd detected at that destination. Try a different location.");
}
} else {
send_private_msg(from, THE_REGION, from, "PROMPT_USER_$", TRICORDER_PROMPT + " ");
object_say(from, "Unable to find: " + args[0]);
}
break;
case "l":
case "listteleport":
send_private_msg(from, THE_REGION, from, "PROMPT_USER_$", TRICORDER_PROMPT + " ");
String prefix = "";
if (hasArgs) {
prefix = args[0];
object_say(from, String.format("Teleports with prefix %s:", prefix));
} else {
object_say(from, "All teleports:");
}
boolean foundBooth = false;
for (String key : directory.navigableKeySet()) {
if (key.contains("End of Directory")) {
continue;
}
String[] splitKey = key.split("-");
String realm = splitKey[0];
if (!realm.equals("otis")) {
String booth = null;
if (splitKey.length > 1) {
booth = splitKey[1];
} else {
booth = splitKey[0];
}
if (booth.startsWith(prefix)) {
foundBooth = true;
object_say(from, booth);
}
}
}
if (!foundBooth) {
object_say(from, "No teleports found.");
}
break;
case "h":
case "help":
send_private_msg(from, THE_REGION, from, "PROMPT_USER_$", TRICORDER_PROMPT + " ");
for (String help_line : TRICORDER_HELP) {
object_say(from, help_line);
}
break;
case "r":
case "random":
String[] boothKeys = {};
boothKeys = directory.keySet().toArray(boothKeys);
int tries;
for (tries = 0; tries < MAX_RANDOM_TELEPORT_RETRIES; tries++) {
String randBooth = boothKeys[rand.nextInt(boothKeys.length - 1)];
if (!randBooth.startsWith("otis-")) {
avatar.change_regions(directory.get(randBooth), AUTO_TELEPORT_DIR, TELEPORT_ENTRY);
break;
}
}
if (tries == MAX_RANDOM_TELEPORT_RETRIES) {
send_private_msg(from, THE_REGION, from, "PROMPT_USER_$", TRICORDER_PROMPT + " ");
object_say(from, "Unable to teleport, please try again!");
}
break;
case "t":
case "teleport":
if (!hasArgs) {
send_private_msg(from, THE_REGION, from, "PROMPT_USER_$", TRICORDER_PROMPT + " ");
object_say(from, "Please enter a valid destination.");
break;
}
String directoryKey = squish(String.join("", args));
String destinationRegion = null;
if (directoryKey.equals("home")) {
destinationRegion = avatar.turf;
} else {
if (directoryKey.indexOf('-') == -1) {
directoryKey = "pop-" + directoryKey;
}
if (directory.containsKey(directoryKey)) {
destinationRegion = directory.get(directoryKey);
} else {
send_private_msg(from, THE_REGION, from, "PROMPT_USER_$", TRICORDER_PROMPT + " ");
object_say(from, "Invalid teleport destination: " + directoryKey);
break;
}
}
if (current_region().object().ref().equals(destinationRegion)) {
send_private_msg(from, THE_REGION, from, "PROMPT_USER_$", TRICORDER_PROMPT + " ");
object_say(from, "You're already there!");
} else if (Region.IsRoomForMyAvatarIn(destinationRegion, from)) {
avatar.x = SAFE_X;
avatar.y = SAFE_Y;
avatar.action = STAND;
avatar.change_regions(destinationRegion, AUTO_TELEPORT_DIR, TELEPORT_ENTRY);
} else {
send_private_msg(from, THE_REGION, from, "PROMPT_USER_$", TRICORDER_PROMPT + " ");
object_say(from, "Flash crowd detected at that destination. Try a different location.");
}
break;
default:
send_private_msg(from, THE_REGION, from, "PROMPT_USER_$", TRICORDER_PROMPT + " ");
object_say(from, "Unknown command, enter h for help.");
}
}
/**
* CALLBACK for the GOD TOOL - it must reconstruct the context for
* interpretation from an earlier request.
*
* @param from
* The user holding the magical GOD TOOL object, and pointing at
* avatar.saveTargetNoid.
*/
public void god_tool_revisited(User from, String request_string) {
Avatar avatar = avatar(from);
HabitatMod target = avatar.savedTarget;
if (null == target || !avatar.nitty_bits[GOD_FLAG]) {
object_say(from, "Nothing happens.");
message_to_god(this, avatar, "UNAUTHORIZED USE OF A GOD TOOL!");
send_reply_error(from);
return;
}
int len = request_string.length();
if (len > 0) {
char command = request_string.charAt(0);
int arg = 1;
if (len > 1 && Pattern.matches("[0-9]+", request_string.substring(1))) {
arg = Integer.parseInt(request_string.substring(1));
}
if (command != 'j') {
send_private_msg(from, THE_REGION, from, "PROMPT_USER_$", GOD_TOOL_PROMPT + " ");
}
switch (command) {
case ARROW_R: // Move right 1 or more pixels
target.x += arg;
modify_variable(from, target, C64_XPOS_OFFSET, target.x);
break;
case ARROW_L: // Move left 1 or more pixels
target.x -= arg;
modify_variable(from, target, C64_XPOS_OFFSET, target.x);
break;
case ARROW_U: // Move up 1 or more pixels
target.y += arg;
modify_variable(from, target, C64_YPOS_OFFSET, target.y);
break;
case ARROW_D: // Move down 1 or more pixels
target.y -= arg;
modify_variable(from, target, C64_YPOS_OFFSET, target.y);
break;
case 'b': // Put object in background
target.y &= ~FOREGROUND_BIT;
modify_variable(from, target, C64_YPOS_OFFSET, target.y);
break;
case 'f': // Put object in foreground
target.y |= FOREGROUND_BIT;
modify_variable(from, target, C64_YPOS_OFFSET, target.y);
break;
case 's': // Set gr_state to arg's value
target.gr_state = arg;
modify_variable(from, target, C64_GR_STATE_OFFSET, arg);
break;
case 'o': // Flip orientation left/right
target.orientation ^= 0b00000001;
modify_variable(from, target, C64_ORIENT_OFFSET, target.orientation);
break;
case 'p': // Set pattern (arg 0-14)
target.orientation = (target.orientation & FACING_BIT) | (arg << 3 & PATTERN_BITS) & BYTE_MASK;
modify_variable(from, target, C64_ORIENT_OFFSET, target.orientation);
break;
case 'c': // Set color (arg 0-63)
target.orientation = (target.orientation & FACING_BIT) | (COLOR_FLAG)
| (arg << 3 & COLOR_BITS) & BYTE_MASK;
modify_variable(from, target, C64_ORIENT_OFFSET, target.orientation);
break;
case 'd': // dump object
object_say(from, identifyTarget(target));
String dump = target.encode(EncodeControl.forRepository).toString();
dump = dump.substring(1, dump.length() - 1);
int start = 0; // Offset in JSON string dump
int countdown = 2; // Word balloons before we give up
// sending...
String chunk;
while (start < dump.length() && countdown > 0) {
chunk = dump.substring(start);
if (chunk.length() > MAX_WORD_BALLON_LEN) {
chunk = chunk.substring(0, MAX_WORD_BALLON_LEN);
}
if (start + chunk.length() < dump.length()) {
chunk = chunk.substring(0, chunk.lastIndexOf(',') + 1);
}
object_say(from, chunk);
start += chunk.length();
if (--countdown == 0) {
object_say(from, "...");
}
}
break;
case 't': // Set text field value
int textlen = (target.HabitatClass() == CLASS_SIGN) ? 40
: (target.HabitatClass() == CLASS_SHORT_SIGN) ? 10 : 0;
if (textlen > 0) {
String workstring = request_string.substring(1);
if (workstring.length() > textlen) {
return;
}
while (workstring.length() < textlen) {
StringBuffer sbuf = new StringBuffer(workstring);
while (sbuf.length() < textlen) {
sbuf.append(' ');
}
workstring = sbuf.toString();
}
JSONLiteral msg = new_broadcast_msg(THE_REGION, "FIDDLE_$");
msg.addParameter("target", target.noid);
msg.addParameter("offset", C64_TEXT_OFFSET);
msg.addParameter("argCount", textlen);
msg.addParameter("value", workstring);
msg.finish();
context().send(msg);
((Poster) target).setTextBytes(workstring);
target.gen_flags[MODIFIED] = true;
}
break;
case 'n': // enter god mode on a noid (useful for unclickable
// objects)
HabitatMod new_target = current_region().noids[arg];
god_tool(from, new_target);
return;
case 'l': // List of all the objects in the region, by noid
for (HabitatMod item : current_region().noids) {
if (item != null) {
object_say(from, identifyTarget(item));
}
}
break;
case 'j':
String context = request_string.substring(1);
if (context.indexOf('-') == -1) {
context = "context-" + context;
}
context = context.replace('{', '_'); // There is no underscore in VICE
send_reply_error(from); // Need to clear the GOD MODE flag on the client.
if (!Region.IsRoomForMyAvatarIn(context, from)) {
object_say(from, context + " is full.");
} else {
avatar.savedMagical = null;
avatar.savedTarget = null;
avatar.x = 80;
avatar.y = 132;
avatar.markAsChanged();
avatar.change_regions(context, AUTO_TELEPORT_DIR, TELEPORT_ENTRY);
}
break;
case '?':
case 'h':
object_say(from, "?-help l-list d-dump f-forgrnd b-back");
object_say(from, "o-flip c#-color p#-pattern n#-noid");
object_say(from, "s#-gr.state " + (char) ARROW_U + (char) ARROW_D + (char) ARROW_L + (char) ARROW_R
+ "#-move jCONTEXT-jump");
object_say(from, "tTEXT - sign null-exit");
break;
}
if (target.gen_flags[MODIFIED]) {
target.checkpoint_object(target);
}
return;
}
avatar.savedMagical = null;
avatar.savedTarget = null;
}
private void random_porter(User from, HabitatMod target) {
Avatar avatar = (Avatar) avatar_target_check(target);
if (avatar != null) {
object_broadcast(noid, "Where she stops, nobody knows!");
send_reply_success(from);
avatar.x = 80;
avatar.y = 132;
String destination = avatar.turf;
if(magic_data != 0) {
// Lookup a random teleport as destination! //
@SuppressWarnings("unchecked")
Map<String, String> directory = (Map <String, String>) context().getStaticObject("teleports");
List<String> keys = new ArrayList<String>(directory.keySet());
destination = directory.get(keys.get(rand.nextInt(keys.size() - 1) + 1));
}
avatar.change_regions(destination, AUTO_TELEPORT_DIR, TELEPORT_ENTRY);
} else {
object_say(from, "Nothing happens.");
send_reply_error(from);
}
}
/** The messages describing each magical type */
private static final String magic_help[] = { "Down, down, down, down takes you up.",
/* 1 -- change_user_height */
"Twylla probably wouldn't be amused.",
/* 2 -- make_target_avatar_jump */
"You got me singing the blues...",
/* 3 -- make_other_avatars_turn_blue */
"Home is where the target is.",
/* 4 -- send_target_avatar_home */
"Cryptic remark!",
/* 5 -- not yet used? */
"Oooh! Don't press this button!!",
/* 6 -- switch_give_user_cooties */
"CAPTURE-THE-FLAG: Press button to reset flags.",
/* 7 -- switch_start_end_capture_flag */
"Press button to win Region Rally",
/* 8 -- switch_region_rally_winner */
"Going in style!",
/* 9 -- change_avatar_style */
"BUZZ!",
/* 10 -- switch_gameshow_buzzer */
"Everybody's talking about a new way of walking!",
/* 11 -- make_user_moonwalk */
"CHESS: Press button to reset board",
/* 12 -- switch_reset_chess */
"CHECKERS: Press button to reset board",
/* 13 -- switch_reset_checkers */
"BACKGAMMON: Press button to reset board",
/* 14 -- switch_reset_backgammon */
"Amulet Of Wonderous Worth. Property of DadaSalesh",
/* 15 -- recover_amulet */
"Press button to vote.",
/* 16 -- vote in election */
"God Tool: If Found, Dispose of immediately. Severe penalty for unauthorized use ",
/* 17 -- God Tool */
"Publishing Machine: Cost $2 per document to bind. DO to operate",
/* 18 -- Publishing Machine */
"Bursting Machine: Cost $5 per page burst out of book. DO to operate",
/* 19 -- Bursting Machine */
"Copy Machine: Cost $2 per page of document to copy. DO to operate",
/* 20 -- Copy Machine */
"Where, oh where, have you gone?",
/* 21 -- Take me to an avatar */
"A voice booms out:I AM THE VAULTKEEPER!",
/* 22 -- The VaultKeeper */
"Push once for an Item of Significance",
/* 23 -- Free Dispenser */
"The Money Tree",
/* 24 -- Tokens dispenser */
"Press me.",
/* 25 -- Magic Opener */
"Lottery Vendroid. Hold $50 and DO to purchase a ticket.",
/* 26 -- lottery ticket machine */
"Lottery Redemption Center. Hold ticket and DO to recieve $.",
/* 27 -- lottery payoff machine */
"DO to activate.",
/* 28 -- death magic */
"Try your luck.",
/* 29 -- Random Porter */
"Clink!"
/* 30 -- Token Dispenser? */
};
/**
* Verb (Magical): Reply with the HELP for this magical item.
*
* @param from
* User representing the connection making the request.
*/
public void HELP(User from) {
String the_message = "Cryptic remark.";
if (magic_type > 0 && magic_type <= NUMBER_OF_MAGICS) {
the_message = magic_help[magic_type - 1];
}
send_reply_msg(from, the_message);
}
/**
* Children call this to get a string describing the magical nature of this
* the item.
*
* @return Magical help string
*/
public String magic_vendo_info() {
if (magic_type < 1)
return ("Dead magic item.");
else if (magic_type > NUMBER_OF_MAGICS)
return ("MAGIC, no information available (yet).");
else
return (magic_help[magic_type - 1]);
}
}
|
package com.RyanHodin.RPG;
import android.annotation.TargetApi;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.graphics.Color;
import android.os.Build;
import android.os.Parcel;
import android.os.Parcelable;
import android.text.InputType;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnFocusChangeListener;
import android.view.animation.AnimationUtils;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout.LayoutParams;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
class Cgame implements Serializable, Parcelable
{
public static final long serialVersionUID=1;
public int stage; // Where are we?
public int line; // Persistent input
public int inputted; // Overwritten per input
public boolean doCommitSuicide; // Does exiting the input menu execute user.commitSuicide() or return to runStage()?
public static MainActivity t;
public Cgame()
{
stage=0;
line=0;
inputted=-1;
}
private Cgame (Parcel in)
{
stage=in.readInt();
line=in.readInt();
inputted=in.readInt();
}
public void saveTo(SharedPreferences.Editor edit)
{
edit.putInt("gameStage", stage-1);
edit.putInt("gameLine", line);
edit.putInt("gameInputted", inputted);
if (Build.VERSION.SDK_INT>=9)
edit.apply();
else
edit.commit();
}
public void loadFrom(SharedPreferences sp)
{
stage=sp.getInt("gameStage", stage);
line=sp.getInt("gameLine", line);
inputted=sp.getInt("gameInputted", inputted);
}
public void runStage()
{
t.displayHandler.removeMessages(1);
if (Thread.interrupted())
return;
t.config.computerPaused=true;
doCommitSuicide=false;
t.user.dead=false;
if (t.config.autosave)
{
(new Thread(new Runnable() // We don't want to save on the runStage thread, that might cause a noticeable delay. Note that if saving takes too long, we may get a conflict between several saves occurring at once. Consider naming the save thread.
{
@Override
public void run()
{
t.saveGame();
}
})).start();
}
switch (stage)
{
case -1:
t.fadeout();
t.runOnUiThread(new Runnable()
{
@Override
public void run()
{
t.setContentView(R.layout.dead);
t.currentView=R.id.deadLayout;
t.setUi();
}
});
break;
case 0:
if (t.config.easterEggs && ("King Arthur".equalsIgnoreCase(t.user.name) || "King Arthur of Camelot".equalsIgnoreCase(t.user.name) || "Arthur, King of the Britons".equalsIgnoreCase(t.user.name) || "It is Arthur, King of the Britons".equalsIgnoreCase(t.user.name)))
{
runArthur((byte)0, null);
return;
}
if (t.config.gender)
{
t.th=new Thread (new Runnable()
{
@Override
public void run ()
{
t.say("Good.\n\n\tNow, "+t.user.name+", since it\'s too dark to see, and for my accounting purposes...");
}
});
t.th.start();
prepContinueButton();
}
else
{
stage=2;
runStage();
return;
}
break;
case 1:
t.fadeout();
t.runOnUiThread(new Runnable()
{
@TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1)
@Override
public void run()
{
LinearLayout l=prepInput("What gender are you?");
List<String> genders=new ArrayList<> (100);
genders.add("Male");
genders.add("Female");
if (!t.config.twoGender)
{
if (t.config.specialGender)
{
genders.add("Transsexual male");
genders.add("Transsexual female");
genders.add("Metrosexual male");
genders.add("Metrosexual female");
genders.add("Male to Female");
genders.add("Female to Male");
genders.add("Uncertain");
genders.add("Unwilling to say");
genders.add("It\'s complicated");
genders.add("Genderqueer");
genders.add("Dual");
genders.add("Male, but curious as to what being a female is like");
genders.add("Female, but curious as to what being a male is like");
genders.add("Male, but overweight, so have moobs");
genders.add("Female, but have Adam\'s apple");
genders.add("Hermaphrodite with strong male leanings");
genders.add("Hermaphrodite with strong female leanings");
genders.add("Hermaphrodite with no strong gender leanings");
genders.add("Conjoined twin - Male");
genders.add("Conjoined twin - Female");
genders.add("Conjoined twin - Other");
genders.add("Born without genitals - Identify as male");
genders.add("Born without genitals - Identify as female");
genders.add("Born without genitals - Identify otherwise");
genders.add("Born without genitals - and proud of it");
genders.add("Born male, had bad circumcision, raised female");
genders.add("WOMYN, thank you very much!");
genders.add("Angel");
genders.add("Mortal Angel");
genders.add("Sentient Artificial Intelligence - Identify as ungendered");
genders.add("Sentient Artificial Intelligence - Identify as male");
genders.add("Sentient Artificial Intelligence - Identify as female");
genders.add("Sentient Artificial Intelligence - Identify as other");
genders.add("Household pet that walked across the device - Male");
genders.add("Household pet that walked across the device - Female");
genders.add("Household pet that walked across the device - Other");
genders.add("Cross Dresser");
genders.add("In between");
genders.add("Intersex");
genders.add("Pangender");
genders.add("Two spirit");
genders.add("Other");
genders.add("Neutrois");
genders.add("Prefer not to say");
genders.add("None of your business");
if (t.config.easterEggs)
{
genders.add("Kanye West");
genders.add("Cheese");
genders.add("Raygun");
if (t.config.GoTEggs)
{
genders.add("The Dothraki do not follow your Genders");
genders.add("Khaleesi");
genders.add("Dragon - Male");
genders.add("Dragon - Female");
genders.add("Dragon - Other");
genders.add("Direwolf");
genders.add("White Walker");
genders.add("Child of the Forest");
}
if (t.config.ESEggs)
{
genders.add("Khajiit");
genders.add("Dovahkiin");
genders.add("Dovah");
genders.add("Draugr");
}
if (t.config.schoolEggs)
{
genders.add("Student");
genders.add("IB Student");
genders.add("Teacher");
genders.add("IB Teacher");
}
}
}
else
{
genders.add("Multiple");
genders.add("In between");
genders.add("Unsure");
genders.add("None");
genders.add("Prefer not to say");
genders.add("Other");
}
}
for (int i=0; i<genders.size(); ++i)
{
Button b=new Button(t);
b.setText(genders.get(i));
b.setOnClickListener(new OnClickListener ()
{
@Override
public void onClick(View v)
{
v.setOnClickListener(null);
t.user.gender=((TextView)v).getText().toString();
t.th=new Thread (new Runnable ()
{
@Override
public void run()
{
runStage();
}
});
t.th.start();
}
});
l.addView(b);
}
genders.clear();
if (t.config.customGender)
{
Button b=new Button (t);
b.setText("Custom");
b.setOnClickListener(new OnClickListener ()
{
@Override
public void onClick (View v)
{
v.setOnClickListener(null);
t.config.computerPaused=true;
ScrollView sv=new ScrollView (t);
int id=Build.VERSION.SDK_INT>=17 ? View.generateViewId() : 5;
sv.setId(id);
t.currentView=id;
LinearLayout.LayoutParams lp=new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
t.setContentView(sv);
LinearLayout l=new LinearLayout(t);
l.setOrientation(LinearLayout.VERTICAL);
sv.addView(l);
t.setUi();
lp.topMargin=10;
OnFocusChangeListener ofcl=new OnFocusChangeListener()
{
@Override
public void onFocusChange(View v, boolean hasFocus)
{
if (hasFocus && t.config.fullscreen)
{
t.setUi();
EditText ev=((EditText)t.findViewById(t.user.parsedGender));
LinearLayout.LayoutParams lp=(LinearLayout.LayoutParams)ev.getLayoutParams();
int result=0;
int resourceId = t.getResources().getIdentifier("status_bar_height", "dimen", "android");
if (resourceId > 0) {
result = t.getResources().getDimensionPixelSize(resourceId);
}
lp.topMargin=result+5;
}
}
};
EditText ev=new EditText(t);
t.user.parsedGender=999999999;
ev.setId(t.user.parsedGender);
ev.setOnFocusChangeListener(ofcl);
ev.setBackgroundColor(Color.rgb(128,128,128));
ev.setHint("What gender are you?");
ev.setHintTextColor(Color.WHITE);
ev.setTextColor(Color.BLACK);
ev.setShadowLayer(5.0f,5,5,Color.WHITE);
ev.setSingleLine(false);
ev.setInputType(InputType.TYPE_CLASS_TEXT|InputType.TYPE_TEXT_FLAG_AUTO_CORRECT|InputType.TYPE_TEXT_FLAG_MULTI_LINE|InputType.TYPE_TEXT_FLAG_CAP_SENTENCES);
ev.setImeOptions(EditorInfo.IME_FLAG_NO_ENTER_ACTION);
l.addView(ev, lp);
if (t.config.addressGender)
{
ev=new EditText(t);
lp=new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
lp.topMargin=20;
t.user.weapon.type=7; // Bad form, but we won't have a real parsed weapon for a while... It can be temporary storage until then.
ev.setId(t.user.weapon.type);
ev.setOnFocusChangeListener(ofcl);
ev.setBackgroundColor(Color.rgb(128,128,128));
ev.setHint("What should I address one of your gender as?");
ev.setHintTextColor(Color.WHITE);
ev.setTextColor(Color.BLACK);
ev.setShadowLayer(5.0f,5,5,Color.WHITE);
ev.setSingleLine(false);
ev.setInputType(InputType.TYPE_CLASS_TEXT|InputType.TYPE_TEXT_FLAG_AUTO_CORRECT|InputType.TYPE_TEXT_FLAG_MULTI_LINE|InputType.TYPE_TEXT_FLAG_CAP_SENTENCES);
ev.setImeOptions(EditorInfo.IME_FLAG_NO_ENTER_ACTION);
l.addView(ev, lp);
}
Button b=new Button(t);
b.setText("Submit");
lp=new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
lp.topMargin=250;
lp.gravity=Gravity.RIGHT;
b.setOnClickListener(new OnClickListener()
{
@Override
public void onClick (View v)
{
v.setOnClickListener(null);
t.th=new Thread (new Runnable ()
{
@Override
public void run ()
{
// Close the soft keyboard, now that there's nothing for it to write to.
((InputMethodManager)t.getSystemService(Context.INPUT_METHOD_SERVICE)).hideSoftInputFromWindow(t.findViewById(t.user.parsedGender).getWindowToken(), 0);
t.user.gender=((TextView)t.findViewById(t.user.parsedGender)).getText().toString().trim();
if (t.config.addressGender)
{
String str=((TextView)t.findViewById(t.user.weapon.type)).getText().toString().trim();
if (str.startsWith("the ") || str.startsWith("The "))
str=str.substring(4); // Trim off the 'the' to avoid the 'The The' quirk.
t.user.genderAddress="The "+str;
}
runStage();
}
});
t.th.start();
}
});
l.addView(b, lp);
}
});
l.addView(b);
}
}
});
break;
case 2:
t.th=new Thread (new Runnable()
{
@Override
public void run()
{
if (t.config.gender && t.config.addressGender && t.user.parsedGender!=999999999)
t.user.parseGenderAddress();
t.say("I see.\n\n\tWell, "+t.user+", it is time to make a decision.\n\n\tAre you going to try to escape?");
}
});
t.th.start();
prepContinueButton();
if (t.config.gender)
t.user.parseGender();
break;
case 3:
t.fadeout();
t.runOnUiThread (new Runnable ()
{
@Override
public void run()
{
LinearLayout l=prepInput();
Button b=new Button (t);
b.setText("Escape");
b.setOnClickListener(new OnClickListener ()
{
@Override
public void onClick(View v)
{
v.setOnClickListener(null);
t.th.interrupt();
t.th=new Thread (new Runnable ()
{
@Override
public void run ()
{
inputted=0;
runStage();
}
});
t.th.start();
}
});
l.addView(b);
b=new Button (t);
b.setText("Stay");
b.setOnClickListener(new OnClickListener()
{
@Override
public void onClick (View v)
{
v.setOnClickListener(null);
t.th.interrupt();
t.th=new Thread (new Runnable ()
{
@Override
public void run ()
{
inputted=1;
runStage();
}
});
t.th.start();
}
});
l.addView(b);
}
});
break;
case 4:
if (inputted==0)
{
if (onMove(99))
return;
t.th=new Thread (new Runnable()
{
@Override
public void run()
{
String creature;
boolean plural=false;
if (t.gen.nextBoolean())
{
if (t.gen.nextBoolean())
creature="troll";
else
creature="dinosaur";
}
else
{
if (t.gen.nextBoolean())
{
creature="alligator";
plural=true;
}
else
creature="goblin";
}
t.say("You start to escape...","But you see a shape.\n\tIt\'s "+(plural ? "an" : "a")+" "+creature+"!\n\n\tYou search for a weapon, but only find a stick.");
}
});
t.th.start();
prepContinueButton();
}
else
{
if (onMove(50))
return;
line=1;
if (t.config.triggerEgg(.1))
{
t.th=new Thread (new Runnable()
{
@Override
public void run()
{
t.say("You remain in the cave.","Despite the lack of any way to survive, you stubbornly stay in the cave, starving...\n\tSuddenly, Gandalf the Grey appears.\n\t\t\"Fly, you fool! You will die!!\"\nSince you make no move to escape, Gandalf sighs, and takes you with him.");
}
});
t.th.start();
prepContinueButton();
}
else
{
t.th=new Thread (new Runnable()
{
@Override
public void run()
{
t.say("You stay in the cave...","...And starve to death because there\'s no food in the cave.");
}
});
t.th.start();
t.user.dead=true;
prepContinueButton();
}
}
break;
case 5:
if (line==0)
{
t.fadeout();
t.runOnUiThread(new Runnable ()
{
@Override
public void run ()
{
doCommitSuicide=true;
LinearLayout l=prepInput();
Button b=new Button(t);
b.setText("Fight it with a stick");
b.setOnClickListener(new OnClickListener ()
{
@Override
public void onClick (View v)
{
v.setOnClickListener(null);
t.th=new Thread (new Runnable ()
{
@Override
public void run()
{
t.user.weapon.name="stick";
t.user.weapon.type=Cweapon.TYPE_BLUNT;
inputted=0;
runStage();
}
});
t.th.start();
}
});
l.addView(b);
b=new Button(t);
b.setText("Fight it with your fists");
b.setOnClickListener(new OnClickListener ()
{
@Override
public void onClick (View v)
{
v.setOnClickListener(null);
t.th=new Thread (new Runnable ()
{
@Override
public void run()
{
t.user.weapon.type=Cweapon.TYPE_HAND_TO_HAND;
inputted=0;
runStage();
}
});
t.th.start();
}
});
l.addView(b);
b=new Button(t);
b.setText("Run away!!");
b.setOnClickListener(new OnClickListener ()
{
@Override
public void onClick (View v)
{
v.setOnClickListener(null);
t.th=new Thread (new Runnable ()
{
@Override
public void run()
{
inputted=1;
runStage();
}
});
t.th.start();
}
});
l.addView(b);
}
});
}
else
{
t.th=new Thread (new Runnable()
{
@Override
public void run()
{
t.say("You win!","You have won the game of life.");
}
});
t.th.start();
doCommitSuicide=true;
prepContinueButton(onWin);
}
break;
case 6:
if (inputted==1)
{
if (onMove(78))
return;
t.th=new Thread(new Runnable()
{
@Override
public void run()
{
t.say("Run away!!!", "You try to run away from the creature, but it\'s too fast.");
}
});
t.th.start();
t.user.dead=true;
prepContinueButton();
}
else
{
if (t.user.weapon.type==Cweapon.TYPE_HAND_TO_HAND)
{
if (t.determineUserDeath(.5))
{
t.th=new Thread(new Runnable()
{
@Override
public void run()
{
t.say("Fight with fists!","You punch it, but it eats you anyway.");
}
});
t.th.start();
prepContinueButton();
}
else
{
t.th=new Thread(new Runnable()
{
@Override
public void run()
{
t.say("Fight with fists", "You punch the monster, and barely manage to scare it.\n\tYou take a deep breath, and continue.");
}
});
t.th.start();
prepContinueButton();
}
}
else
{
t.th=new Thread(new Runnable ()
{
@Override
public void run ()
{
t.say("You grab the stick, and beat the creature until it leaves.");
}
});
t.th.start();
prepContinueButton();
}
}
break;
case 7:
if (onMove(105))
return;
t.th=new Thread (new Runnable ()
{
@Override
public void run ()
{
t.say ("You Escape!", "You escape from the cave.\n\n\tIt is a bright and sunny day outside.\n\n\tHowever, there is nothing around you besides sand and dust.\nIt would appear that you are in a desert.\n\n\n\tHowever, a while away, there is a lush valley, full of greenery. You decide to head for it.\n\n\tAlong the way, you find a foreboding cave. A sharp iron sword is sitting by the mouth of the cave, glimmering in the sunlight.");
}
});
t.th.start();
prepContinueButton();
break;
case 8:
t.fadeout();
t.runOnUiThread(new Runnable()
{
@Override
public void run()
{
LinearLayout l=prepInput();
Button b=new Button (t);
b.setText("Grab the sword and enter the cave");
b.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View v)
{
v.setOnClickListener(null);
t.th.interrupt();
t.th=new Thread(new Runnable()
{
@Override
public void run()
{
if (t.user.isArthur) {
t.user.weapon.name="Excalibur"; // King Arthur gets the greatest of swords
t.user.weapon.setCharacteristics(Cweapon.ACCURATE|Cweapon.CLOSE_RANGE|Cweapon.CLOSE_RANGE_ONLY|Cweapon.HIGH_CALIBER|Cweapon.HIGH_POWER_ROUNDS|Cweapon.LEGENDARY|Cweapon.LIGHT|Cweapon.ONE_ROUND_MAGAZINE|Cweapon.QUICK_RELOAD);
t.user.weapon.strengthModifier=1+t.gen.nextDouble(); // Excalibur is in epic condition.
}
else {
t.user.weapon.name = "sword";
t.user.weapon.setCharacteristics(Cweapon.ACCURATE | Cweapon.CLOSE_RANGE | Cweapon.CLOSE_RANGE_ONLY | Cweapon.HIGH_CALIBER | Cweapon.ONE_ROUND_MAGAZINE | Cweapon.QUICK_RELOAD);
t.user.weapon.strengthModifier=-0.05*t.gen.nextDouble(); // The sword should be in poor condition
// This exaggerates the difference between the sword and Excalibur
}
t.user.weapon.type = Cweapon.TYPE_SHARP;
inputted=0;
runStage();
}
});
t.th.start();
}
});
l.addView(b);
b=new Button (t);
b.setText("Ignore the sword and enter the cave");
b.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View v)
{
v.setOnClickListener(null);
t.th.interrupt();
t.th=new Thread(new Runnable()
{
@Override
public void run()
{
inputted=0;
runStage();
}
});
t.th.start();
}
});
l.addView(b);
b=new Button (t);
b.setText("Ignore the sword and continue away from the cave");
b.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View v)
{
v.setOnClickListener(null);
t.th.interrupt();
t.th=new Thread(new Runnable()
{
@Override
public void run()
{
inputted=1;
runStage();
}
});
t.th.start();
}
});
l.addView(b);
b=new Button (t);
b.setText("Grab the sword and continue away from the cave");
b.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View v)
{
v.setOnClickListener(null);
t.th.interrupt();
t.th=new Thread(new Runnable()
{
@Override
public void run() {
if (t.user.isArthur) {
t.user.weapon.name="Excalibur"; // King Arthur gets the greatest of swords
t.user.weapon.setCharacteristics(Cweapon.ACCURATE|Cweapon.CLOSE_RANGE|Cweapon.CLOSE_RANGE_ONLY|Cweapon.HIGH_CALIBER|Cweapon.HIGH_POWER_ROUNDS|Cweapon.LEGENDARY|Cweapon.LIGHT|Cweapon.ONE_ROUND_MAGAZINE|Cweapon.QUICK_RELOAD);
t.user.weapon.strengthModifier=1+t.gen.nextDouble(); // Excalibur is in epic condition.
}
else {
t.user.weapon.name = "sword";
t.user.weapon.setCharacteristics(Cweapon.ACCURATE | Cweapon.CLOSE_RANGE | Cweapon.CLOSE_RANGE_ONLY | Cweapon.HIGH_CALIBER | Cweapon.ONE_ROUND_MAGAZINE | Cweapon.QUICK_RELOAD);
t.user.weapon.strengthModifier=-0.05*t.gen.nextDouble(); // The sword should be in poor condition
// This exaggerates the difference between the sword and Excalibur
}
t.user.weapon.type = Cweapon.TYPE_SHARP;
inputted=1;
runStage();
}
});
t.th.start();
}
});
l.addView(b);
}
});
break;
case 9:
if (inputted==0)
{
if (onMove(67))
return;
t.user.dead=(t.user.weapon.type<Cweapon.TYPE_SHARP);
t.th=new Thread(new Runnable()
{
@Override
public void run()
{
String title="You enter the cave";
if (t.user.dead)
t.say(title,"Ignoring the sword, you enter.\n\tImmediately, the creature from the last cave attacks you. It is incredibly angry, and no "+t.user.weapon+" will scare it off.");
else {
if (t.user.isArthur)
t.say(title,"You take the sword, and examine it.\n\nIt seemed to call to you like an old friend, and suddenly you recognize it: It is "+t.user.weapon+"!\n\n\n\tYou take a moment with the blade, twirling it about to remember.\n\n\tAll of a sudden, a shape approaches: You recognize it as the creature from the last cave.\n\tYou bring "+t.user.weapon+" to bear.");
else
t.say(title, "With the sword in hand, you enter.\n\tImmediately, the creature that fled the last cave attacks you. It is incredibly angry, and a stick will not be enough to make it flee.\n\n\tLuckily, you had the prudence to grab the " + t.user.weapon + ".\n\tYou ready it.");
}
}
});
t.th.start();
prepContinueButton();
}
else
{
stage=25;
runStage();
return;
}
break;
case 10:
t.fadeout();
t.runOnUiThread(new Runnable()
{
@Override
public void run()
{
doCommitSuicide=true;
LinearLayout l=prepInput();
Button b=new Button(t);
b.setText("Fight the monster");
b.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v)
{
v.setOnClickListener(null);
t.th.interrupt();
t.th=new Thread (new Runnable()
{
@Override
public void run()
{
inputted=0;
runStage();
}
});
t.th.start();
}
});
l.addView(b);
b=new Button(t);
b.setText("Run away!!");
b.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick (View v)
{
v.setOnClickListener(null);
t.th.interrupt();
t.th=new Thread (new Runnable()
{
@Override
public void run()
{
inputted=1;
runStage();
}
});
t.th.start();
}
});
l.addView(b);
}
});
break;
case 11:
if (onMove(45))
return;
t.user.dead=(inputted!=0);
t.th=new Thread(new Runnable()
{
@Override
public void run()
{
if (t.user.dead)
t.say("Run away!!!", "You turn to run, but the monster is far too fast.");
else
t.say("You fight the monster", "The monster lunges at you, but you swiftly dodge it, turn, and behead it.\n\n\n\tCovered in blood, you contemplate whether you should continue.");
}
});
t.th.start();
prepContinueButton();
break;
case 12:
t.fadeout();
t.runOnUiThread(new Runnable()
{
@Override
public void run()
{
LinearLayout l=prepInput();
Button b=new Button (t);
b.setText("Continue into the cave");
b.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick (View v)
{
v.setOnClickListener(null);
t.th.interrupt();
t.th=new Thread(new Runnable()
{
@Override
public void run()
{
runStage();
}
});
t.th.start();
}
});
l.addView(b);
b=new Button(t);
b.setText("Escape from the cave");
b.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick (View v)
{
v.setOnClickListener(null);
t.th.interrupt();
t.th=new Thread(new Runnable()
{
@Override
public void run()
{
stage=24;
runStage();
}
});
t.th.start();
}
});
l.addView(b);
}
});
break;
case 13:
if (onMove(15+t.gen.nextInt(20)))
return;
t.th=new Thread (new Runnable()
{
@Override
public void run()
{
t.say("Forward into Dusk","You continue into the cave.\n\tYou encounter a rather horrifying monster, one that chills you to the bone.\n\n\tIt seems to be extremely afraid of the light.\n\n\n\tUnfortunately, there is no way around it.");
}
});
t.th.start();
prepContinueButton();
break;
case 14:
t.fadeout();
t.runOnUiThread(new Runnable()
{
@Override
public void run()
{
LinearLayout l=prepInput();
Button b=new Button(t);
b.setText("Fight the grue");
b.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v)
{
v.setOnClickListener(null);
t.th.interrupt();
t.th=new Thread(new Runnable()
{
@Override
public void run()
{
runStage();
}
});
t.th.start();
}
});
l.addView(b);
b=new Button(t);
b.setText("Flee from the grue");
b.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v)
{
v.setOnClickListener(null);
t.th.interrupt();
t.th=new Thread(new Runnable()
{
@Override
public void run()
{
stage=24;
runStage();
}
});
t.th.start();
}
});
l.addView(b);
}
});
break;
case 15:
t.determineUserDeath(1, 3);
t.th=new Thread(new Runnable()
{
@Override
public void run()
{
if (t.user.dead)
{
if (t.config.specMon)
{
t.user.dead=false;
line=1;
}
t.say("You lunge at the grue", "But the grue is too strong, and you get eaten.");
}
else
t.say("You swing your sword...", "...and get in a lucky shot. The grue\'s head falls to the floor.\n\n\tYou again consider whether you should continue.");
}
});
t.th.start();
prepContinueButton();
break;
case 16:
if (line==1)
{
eatenByGrue();
prepContinueButton();
t.runOnUiThread(new Runnable()
{
@Override
public void run()
{
((TextView)t.findViewById(R.id.gameContinueButton)).setTextColor(Color.GREEN);
}
});
}
else
{
t.fadeout();
t.runOnUiThread(new Runnable()
{
@Override
public void run()
{
LinearLayout l=prepInput();
Button b=new Button(t);
b.setText("Continue into the depths of the cave");
b.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick (View v)
{
v.setOnClickListener(null);
t.th.interrupt();
t.th=new Thread(new Runnable()
{
@Override
public void run()
{
runStage();
}
});
t.th.start();
}
});
l.addView(b);
b=new Button(t);
b.setText("Escape from the monsters yet to be found within the cave");
b.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v)
{
v.setOnClickListener(null);
t.th.interrupt();
t.th=new Thread(new Runnable()
{
@Override
public void run()
{
stage=24;
runStage();
}
});
t.th.start();
}
});
l.addView(b);
}
});
}
break;
case 17:
if (onMove(5+t.gen.nextInt(10)))
return;
t.th=new Thread(new Runnable()
{
@Override
public void run()
{
t.say("Into the Darkness of Death", "You continue into the forboding darkness of the cave, trembling in fear, wondering what the next monster to come far too close to ending your life will be.\n\n\n\n\tYour fears are answered in a horrifying way when you see an enormous, hulking, towering shape in front of you.\n\n\tIt lumbers toward you, the ground quaking as it stomps.\n\n\tYou quickly contemplate taking flight.");
}
});
t.th.start();
prepContinueButton();
break;
case 18:
t.fadeout();
t.runOnUiThread(new Runnable()
{
@Override
public void run()
{
LinearLayout l=prepInput();
Button b=new Button(t);
b.setText("Run away before you get killed");
b.setTextColor(Color.rgb(250, 255, 250));
b.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v)
{
v.setOnClickListener(null);
t.th.interrupt();
t.th=new Thread (new Runnable()
{
@Override
public void run()
{
stage=24;
runStage();
}
});
t.th.start();
}
});
l.addView(b);
b=new Button(t);
b.setText("Challenge the utter despotic power of the creature before you");
b.setTextColor(Color.rgb(255, 250, 250));
b.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v)
{
v.setOnClickListener(null);
t.th.interrupt();
t.th=new Thread(new Runnable()
{
@Override
public void run()
{
runStage();
}
});
t.th.start();
}
});
l.addView(b);
}
});
break;
case 19:
t.determineUserDeath(2, 3);
t.th=new Thread(new Runnable()
{
@Override
public void run()
{
if (t.user.dead)
t.say("You fight the monster...", "... But it flattens you.");
else
t.say("David vs. Goliath", "David killed Goliath, and you killed.... Whatever that was.\n\n\tCollecting yourself as a massive thud rolls through the cave and the monster lies vanquished before you, you again consider whether you should continue further into the depths of the frightening cave.");
}
});
t.th.start();
prepContinueButton();
break;
case 20:
t.fadeout();
t.runOnUiThread(new Runnable()
{
@Override
public void run()
{
doCommitSuicide=t.config.easterEggs;
LinearLayout l=prepInput();
Button b=new Button(t);
b.setText("Get out of the cave now, before it is too late!");
b.setPadding(5, 5, 5, 5);
b.setTextColor(Color.rgb(245, 255, 245));
b.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v)
{
v.setOnClickListener(null);
t.th.interrupt();
t.th=new Thread(new Runnable()
{
@Override
public void run()
{
stage=24;
runStage();
}
});
t.th.start();
}
});
l.addView(b);
b=new Button(t);
b.setText("Bravely, yet perhaps foolishly, continue onwards towards the horrors you know not of");
b.setTextColor(Color.rgb(245, 235, 235));
b.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v)
{
v.setOnClickListener(null);
t.th.interrupt();
t.th=new Thread(new Runnable()
{
@Override
public void run()
{
runStage();
}
});
t.th.start();
}
});
l.addView(b);
}
});
break;
case 21:
if (line==1)
{
t.fadeout();
t.runOnUiThread(new Runnable()
{
@Override
public void run()
{
doCommitSuicide=true;
LinearLayout l=prepInput();
Button b=new Button(t);
b.setText("Ignore the weapon and exit the cave");
b.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v)
{
v.setOnClickListener(null);
t.th.interrupt();
t.th=new Thread(new Runnable()
{
@Override
public void run()
{
runStage();
}
});
t.th.start();
}
});
l.addView(b);
b=new Button(t);
b.setText("Grab the superweapon and exit the cave");
b.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v)
{
v.setOnClickListener(null);
t.th.interrupt();
t.th=new Thread(new Runnable()
{
@Override
public void run()
{
t.user.weapon.setPrimary(new Cweapon(Cweapon.TYPE_FUTURE, Cweapon.ACCURATE|Cweapon.AUTOMATIC|Cweapon.CLOSE_RANGE|Cweapon.EXPLOSIVE|Cweapon.HIGH_POWER_ROUNDS|Cweapon.LARGE_MAGAZINE|Cweapon.LEGENDARY|Cweapon.LIGHT|Cweapon.LONG_RANGE|Cweapon.SLOW_RELOAD, "raygun", null));
t.user.weapon.strengthModifier=1;
runStage();
}
});
t.th.start();
}
});
l.addView(b);
}
});
}
else
{
if (onMove(50))
return;
t.th=new Thread (new Runnable()
{
@Override
public void run()
{
t.say("You come to a dead end in the cave, sighing with relief.\n\n\tOn the ground before you, there is a semi-automatic pistol.");
}
});
t.th.start();
prepContinueButton();
}
break;
case 22:
if (line==1)
{
line=0;
if (t.user.weapon.type==Cweapon.TYPE_FUTURE)
{
t.th=new Thread (new Runnable()
{
@Override
public void run()
{
t.say("The "+t.capitalize(t.user.weapon.name), "You take the "+t.user.weapon+", considering it.\n\n\tSuddenly, a grue appears!\n\n\n\n\n\tWithout thinking, you aim the "+t.user.weapon+" at the grue, and pull the trigger.\n\n\tA bright green bolt shoots out of the superweapon, and where the grue was, there is only ash.\n\n\n\tYou consider the "+t.user.weapon+", thinking you\'ll never need to worry about any monster ever again.\n\n\tGrinning, you set off to leave the cave.");
}
});
}
else
{
t.th=new Thread(new Runnable()
{
@Override
public void run()
{
t.user.dead=true;
if (t.config.specMon)
{
t.user.dead=false;
line=1;
}
t.say("You ignore the superweapon, turning to head out of the cave.\n\n\tSuddenly, a grue appears!\n\n\tYou try to bring your sword to bear, but it\'s too slow.");
}
});
}
t.th.start();
prepContinueButton();
}
else
{
t.fadeout();
t.runOnUiThread(new Runnable()
{
@Override
public void run()
{
LinearLayout l=prepInput();
Button b=new Button(t);
b.setText("Grab the pistol and escape the cave");
b.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick (View v)
{
v.setOnClickListener(null);
t.th.interrupt();
t.th=new Thread(new Runnable()
{
@Override
public void run()
{
t.user.weapon.setPrimary(new Cweapon(Cweapon.TYPE_MODERN, Cweapon.CLOSE_RANGE|Cweapon.LARGE_MAGAZINE|Cweapon.LIGHT|Cweapon.QUICK_RELOAD, "pistol", null));
runStage();
}
});
t.th.start();
}
});
l.addView(b);
b=new Button(t);
b.setText("Foolishly ignore the pistol and leave the cave");
b.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick (View v)
{
v.setOnClickListener(null);
t.th.interrupt();
t.th=new Thread(new Runnable()
{
@Override
public void run()
{
runStage();
}
});
t.th.start();
}
});
l.addView(b);
}
});
}
break;
case 23:
if (line==1)
{
eatenByGrue();
t.frameTick();
prepContinueButton();
t.runOnUiThread(new Runnable()
{
@Override
public void run()
{
((TextView)t.findViewById(R.id.gameContinueButton)).setTextColor(Color.GREEN);
}
});
break;
}
++stage;
// Fall through
case 24:
if (onMove(70))
return;
t.th=new Thread(new Runnable()
{
@Override
public void run()
{
t.say("You escape!", "You leave the cave, and gaze towards the lush valley in the distance.");
}
});
t.th.start();
prepContinueButton();
break;
case 25:
if (onMove(90))
return;
t.th=new Thread(new Runnable()
{
@Override
public void run()
{
String address;
String pronoun;
if (t.gen.nextBoolean())
{
address="him";
pronoun="he";
}
else
{
address="her";
pronoun="she";
}
t.say("Continuation", "You continue, towards the lush valley.\n\n\tAlong the way, you encounter an archer.\n\tBefore you\'re able to greet "+address+", "+pronoun+" readies "+address+"self to shoot you.");
}
});
t.th.start();
prepContinueButton();
break;
case 26:
t.fadeout();
t.runOnUiThread(new Runnable()
{
@Override
public void run()
{
doCommitSuicide=true;
LinearLayout l=prepInput();
Button b=new Button(t);
String action;
switch(t.user.weapon.type)
{
case Cweapon.TYPE_HAND_TO_HAND:
case Cweapon.TYPE_BLUNT:
action="Fight";
break;
case Cweapon.TYPE_SHARP:
action="Stab";
break;
case Cweapon.TYPE_MODERN:
case Cweapon.TYPE_FUTURE:
action="Shoot";
break;
default:
action="Kill";
}
b.setText(action+" the archer");
b.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick (View v)
{
v.setOnClickListener(null);
t.th.interrupt();
t.th=new Thread(new Runnable()
{
@Override
public void run()
{
inputted=0;
runStage();
}
});
t.th.start();
}
});
l.addView(b);
t.user.weapon.addSwapperTo(l);
b=new Button(t);
b.setText("Run away");
b.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick (View v)
{
v.setOnClickListener(null);
t.th.interrupt();
t.th=new Thread(new Runnable()
{
@Override
public void run()
{
inputted=1;
runStage();
}
});
t.th.start();
}
});
l.addView(b);
}
});
break;
case 27:
if (inputted==0)
{
t.th=new Thread (new Runnable()
{
@Override
public void run()
{
switch (t.user.weapon.type)
{
case Cweapon.TYPE_HAND_TO_HAND:
t.user.dead=true;
t.say("Fistfight!", "You try to get in punching range of the archer, but an arrow appears in your chest before you get close.");
break;
case Cweapon.TYPE_BLUNT:
t.user.dead=true;
t.say(t.capitalize(t.user.weapon.name)+"fight", "You run up to the archer, barely managing to get in a swing, when the archer shoots you.");
break;
case Cweapon.TYPE_SHARP:
t.determineUserDeath(.5);
t.say(t.capitalize(t.user.weapon.name)+" battle!", "You run up to the archer, and lunge!\n\n\t"+(t.user.dead ? "Unfortunately, you miss, and get shot in the "+(t.config.easterEggs && t.config.ESEggs && t.config.triggerEgg(.9) ? "knee." : "back.") : "You connect!\n\n\tThe archer falls, dead.\n\n\tThe bow drops to the ground.\n\tYou eye it."));
break;
case Cweapon.TYPE_MODERN:
t.determineUserDeath(1, 3);
t.say(t.capitalize(t.user.weapon.name)+" vs. bow", "You carefully take aim at the archer, and pull the trigger.\n\n\t"+(t.user.dead ? "Unfortunately, you miss, and get shot before you can aim again." : (t.gen.nextBoolean() ? "A neat hole appears in the archer\'s chest." : "You wing the archer, the bow swinging off it\'s aim, and then you shoot again, scoring a fatal hit.")+"\n\n\tThe bow falls to the ground.\n\tYou eye it, but decide that you prefer your "+t.user.weapon+"."));
break;
case Cweapon.TYPE_FUTURE:
t.say(t.capitalize(t.user.weapon.name)+" Kill", "You calmly aim at the archer, and pull the trigger.\n\n\tWhere the archer was standing, there is only ash.");
break;
default:
t.user.dead=true;
t.logError("Unknown weapon code: "+t.user.weapon.type+". Weapon: "+t.user.weapon+".");
t.say("Your weapon is unknowable to the mere humans, so...");
}
}
});
t.th.start();
if (t.user.weapon.type<Cweapon.TYPE_HAND_TO_HAND || t.user.weapon.type==Cweapon.TYPE_ARCHERY || t.user.weapon.type>Cweapon.TYPE_FUTURE)
prepContinueButton(new OnClickListener ()
{
@Override
public void onClick (View v)
{
t.user.weapon.type=Cweapon.TYPE_USED_FOR_CONVENIENCE;
t.user.commitSuicide();
}
});
else
prepContinueButton();
}
else
{
if (onMove(65))
return;
t.user.dead=true;
t.th=new Thread(new Runnable()
{
@Override
public void run()
{
t.say("Run away!!!", "You try to run away, but you "+(t.config.easterEggs && t.config.ESEggs ? "take an arrow in the knee." : "get shot before you can get away."));
}
});
t.th.start();
prepContinueButton();
}
break;
case 28:
if (t.user.weapon.type==Cweapon.TYPE_MODERN || t.user.weapon.type==Cweapon.TYPE_FUTURE)
{
++stage;
runStage();
return;
}
t.fadeout();
t.runOnUiThread(new Runnable()
{
@Override
public void run()
{
LinearLayout l=prepInput("Do you take the bow?");
Button b=new Button(t);
b.setText("Yes");
b.setOnClickListener(new OnClickListener ()
{
@Override
public void onClick (View v)
{
v.setOnClickListener(null);
t.th.interrupt();
t.th=new Thread(new Runnable()
{
@Override
public void run ()
{
t.user.weapon.name="bow";
t.user.weapon.type=Cweapon.TYPE_ARCHERY;
t.user.weapon.setCharacteristics(Cweapon.BOLT_FIRE|Cweapon.CLOSE_RANGE|Cweapon.LOW_POWER|Cweapon.ONE_ROUND_MAGAZINE);
runStage();
}
});
t.th.start();
}
});
l.addView(b);
b=new Button(t);
b.setText("No");
b.setOnClickListener(new OnClickListener()
{
@Override
public void onClick (View v)
{
v.setOnClickListener(null);
t.th.interrupt();
t.th=new Thread (new Runnable()
{
@Override
public void run ()
{
runStage();
}
});
t.th.start();
}
});
l.addView(b);
}
});
break;
case 29:
if (onMove(80))
return;
t.th=new Thread(new Runnable()
{
@Override
public void run()
{
t.say("Weaponry is King", "Movng away from the cave yet again, you encounter an abandoned gunstore.\n\n\tInside, there are two shapes.");
}
});
t.th.start();
prepContinueButton();
break;
case 30:
t.fadeout();
t.runOnUiThread(new Runnable()
{
@Override
public void run()
{
LinearLayout l=prepInput();
Button b=new Button(t);
b.setText("Enter the store");
b.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View v)
{
v.setOnClickListener(null);
t.th.interrupt();
t.th=new Thread(new Runnable()
{
@Override
public void run()
{
runStage();
}
});
t.th.start();
}
});
l.addView(b);
b=new Button(t);
b.setText("Continue away from the gunstore");
b.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View v)
{
v.setOnClickListener(null);
t.th.interrupt();
t.th=new Thread(new Runnable()
{
@Override
public void run()
{
stage=37;
runStage();
}
});
t.th.start();
}
});
l.addView(b);
}
});
break;
case 31:
if (onMove(75+t.gen.nextInt(75)))
return;
t.th=new Thread(new Runnable()
{
@Override
public void run()
{
String monster;
if (t.gen.nextBoolean())
{
if (t.gen.nextBoolean())
monster="alligators";
else
monster="trolls";
}
else
{
if (t.gen.nextBoolean())
monster="goblins";
else
monster="dinosaurs";
}
t.say("The Gunstore", "Inside the gunstore, you\'re finally able to identify the shapes...\n\tThey\'re "+monster+"!\n\n\tYou eye the shelves, rife with weaponry you could have, if not for the "+monster+"...");
}
});
t.th.start();
prepContinueButton();
break;
case 32:
t.fadeout();
t.runOnUiThread(new Runnable()
{
@Override
public void run()
{
doCommitSuicide=true;
LinearLayout l=prepInput();
Button b=new Button(t);
b.setText("Fight the deadly creatures");
b.setOnClickListener(new OnClickListener ()
{
@Override
public void onClick (View v)
{
v.setOnClickListener(null);
t.th.interrupt();
t.th=new Thread(new Runnable()
{
@Override
public void run()
{
inputted=0;
runStage();
}
});
t.th.start();
}
});
l.addView(b);
t.user.weapon.addSwapperTo(l);
b=new Button(t);
b.setText("Run away!!");
b.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View v)
{
v.setOnClickListener(null);
t.th.interrupt();
t.th=new Thread(new Runnable()
{
@Override
public void run ()
{
inputted=1;
runStage();
}
});
t.th.start();
}
});
l.addView(b);
}
});
break;
case 33:
t.user.dead=(inputted==1);
if (!t.user.dead && onMove(60))
return;
if (!t.user.dead && t.user.weapon.type==Cweapon.TYPE_ARCHERY)
{
archeryMinigame((int)Math.round(25*(.5+(.5*t.config.difficultyMult))), 5+t.gen.nextGaussian());
t.th=new Thread(new Runnable()
{
@Override
public void run()
{
t.say("Archery", "You shoot one creature, felling it. The other lunges towards you...\n\tYou shoot an arrow at it, "+(t.user.dead ? "but miss." : "and hit it, square in between the eyes.\n\n\tIt falls to the ground, dead."));
}
});
t.th.start();
if (!t.user.dead)
t.user.gold.amount=(int)((99*Math.abs(t.gen.nextGaussian()))+1);
prepContinueButton();
break;
}
t.th=new Thread(new Runnable()
{
@Override
public void run()
{
if (t.user.dead)
t.say("Run away!!", "You try to run, but the closer creature catches you in the doorway, and drags you back.\n\n\tThey make a delicious meal of you.");
else
{
switch (t.user.weapon.type)
{
case Cweapon.TYPE_SHARP:
t.determineUserDeath(.75);
if (t.user.dead)
t.say ("Swordfight!", "You slash at one creature, then the other, trying to keep the creatures away from you, but they overwhelm you.");
else
t.say ("Slash and Stab", "You slash at one creature, barely slicing some flesh off.\n\tIt jumps back, stunned by the injury.\n\tYou take the opportunity to focus on the other one, barely managing to defeat it in time to swing around and duel the other.\n\n\tAfter killing it too, you stand in the center of the store, blood dripping off you, examining the shelves.");
break;
case Cweapon.TYPE_ARCHERY:
break;
case Cweapon.TYPE_MODERN:
if (t.determineUserDeath(.25))
t.say("A hit and a miss", "You place one shot cleanly between the eyes of the nearest creaure.\n\tIt falls, dead.\n\n\tThe second creature lunges toward you, and you fire, hitting it in the shoulder, failing to kill it.");
else
t.say("Sharpshooter", "You cleanly shoot the near creature between the eyes, killing it instantly.\n\n\tYou spin around, and quickly shoot the far creature.\n\tIt stumbles, and you fire another round into it\'s skull.");
break;
case Cweapon.TYPE_FUTURE:
t.say(t.capitalize(t.user.weapon.name)+" kill", "You level your "+t.user.weapon.name+" at the near creature, calmly turning it to ash.\n\n\tThe second creature seems frightened.\n\n\n\tNo matter. You burn it too.");
break;
default:
t.say("Your weapon is unknown to this universe as of the time being, so...");
t.user.weapon.type=Cweapon.TYPE_USED_FOR_CONVENIENCE;
t.user.commitSuicide();
}
}
}
});
t.th.start();
Thread.yield();
if (!t.user.dead)
{
Random gen=new Random();
t.user.gold.amount=(int)((99*Math.abs(gen.nextGaussian()))+1); // If the user is still alive,then they're going to the gunstore. It will be more persistent here.
}
prepContinueButton();
break;
case 34:
if (inputted!=-1 && onMove(90))
return;
t.th=new Thread(new Runnable()
{
@Override
public void run()
{
if (inputted==-1)
t.say("With the monsters defeated, you clean their remnants off of you, then survey your prize, walls and walls full of weapons"+(t.user.gold.amount==0 ? "" : ", and the contents of the cash register"+(t.user.gold.amount==1 ? ": " : ", which is oddly full of ")+t.user.gold)+".\n\n\tYou decide to grab a weapon, then depart.");
else
t.say("Return", "You return to the gunstore.\n\n\tLuckily, it\'s still lacking as far as things that want to kill and eat you are concerned.\n\n\tYou look to the walls, filled with more weapons than you can count, again resolving to grab one, then go back to the valley.");
}
});
t.th.start();
prepContinueButton();
break;
case 35:
t.fadeout();
t.runOnUiThread(new Runnable()
{
@Override
public void run()
{
doCommitSuicide=true;
LinearLayout l=prepInput("Choose your weapon");
Button b=new Button(t);
b.setText("Combat knife");
b.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v)
{
v.setOnClickListener(null);
t.th.interrupt();
t.th=new Thread(new Runnable()
{
@Override
public void run()
{
t.user.weapon.setPrimary(new Cweapon(Cweapon.TYPE_SHARP, Cweapon.ACCURATE|Cweapon.CLOSE_RANGE|Cweapon.HIGH_POWER_ROUNDS|Cweapon.LEGENDARY|Cweapon.LIGHT|Cweapon.QUICK_RELOAD|Cweapon.WEAK_ROUNDS, .05, "combat knife", null));
t.game.runStage();
}
});
t.th.start();
}
});
l.addView(b);
b=new Button(t);
b.setText("Crossbow");
b.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick (View v)
{
v.setOnClickListener(null);
t.th.interrupt();
t.th=new Thread(new Runnable()
{
@Override
public void run()
{
t.user.weapon.setPrimary(new Cweapon(Cweapon.TYPE_ARCHERY, Cweapon.ACCURATE|Cweapon.BOLT_FIRE|Cweapon.CLOSE_RANGE|Cweapon.HIGH_POWER_ROUNDS|Cweapon.ONE_ROUND_MAGAZINE|Cweapon.SLOW_RELOAD, .1, "crossbow", null));
t.game.runStage();
}
});
t.th.start();
}
});
l.addView(b);
b=new Button(t);
b.setText("Composite bow");
b.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View v)
{
v.setOnClickListener(null);
t.th.interrupt();
t.th=new Thread(new Runnable()
{
@Override
public void run()
{
t.user.weapon.setPrimary(new Cweapon(Cweapon.TYPE_ARCHERY, Cweapon.BOLT_FIRE|Cweapon.HIGH_POWER_ROUNDS|Cweapon.LIGHT|Cweapon.LONG_RANGE|Cweapon.LOW_POWER|Cweapon.ONE_ROUND_MAGAZINE, .025, "composite bow", null));
t.game.runStage();
}
});
t.th.start();
}
});
l.addView(b);
b=new Button(t);
if (t.user.weapon.type!=Cweapon.TYPE_MODERN)
{
b.setText("Pistol");
b.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View v)
{
v.setOnClickListener(null);
t.th.interrupt();
t.th=new Thread(new Runnable()
{
@Override
public void run()
{
t.user.weapon.setPrimary(new Cweapon(Cweapon.TYPE_MODERN, Cweapon.CLOSE_RANGE|Cweapon.HIGH_CALIBER|Cweapon.LARGE_MAGAZINE|Cweapon.LIGHT|Cweapon.QUICK_RELOAD, "pistol", null));
t.game.runStage();
}
});
t.th.start();
}
});
l.addView(b);
b=new Button(t);
}
b.setText("Revolver");
b.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View v)
{
v.setOnClickListener(null);
t.th.interrupt();
t.th=new Thread(new Runnable()
{
@Override
public void run()
{
t.user.weapon.setPrimary(new Cweapon(Cweapon.TYPE_MODERN, Cweapon.CLOSE_RANGE|Cweapon.HIGH_CALIBER|Cweapon.LIGHT|Cweapon.SLOW_RELOAD, -.01, t.gen.nextBoolean() ? "revolver" : "six-shot", null));
t.game.runStage();
}
});
t.th.start();
}
});
l.addView(b);
b=new Button(t);
b.setText("M16 Assault Rifle");
b.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View v)
{
v.setOnClickListener(null);
t.th.interrupt();
t.th=new Thread(new Runnable()
{
@Override
public void run()
{
t.user.weapon.setPrimary(new Cweapon(Cweapon.TYPE_MODERN, Cweapon.ACCURATE|Cweapon.AUTOMATIC|Cweapon.LARGE_MAGAZINE|Cweapon.LONG_RANGE|Cweapon.QUICK_RELOAD, .1, "M16", null));
t.game.runStage();
}
});
t.th.start();
}
});
l.addView(b);
b=new Button(t);
b.setText("M4A1 Assault Rifle");
b.setOnClickListener(new OnClickListener()
{
@Override
public void onClick (View v)
{
v.setOnClickListener(null);
t.th.interrupt();
t.th=new Thread(new Runnable()
{
@Override
public void run()
{
t.user.weapon.setPrimary(new Cweapon(Cweapon.TYPE_MODERN, Cweapon.ACCURATE|Cweapon.AUTOMATIC|Cweapon.CLOSE_RANGE|Cweapon.LARGE_MAGAZINE|Cweapon.LIGHT|Cweapon.QUICK_RELOAD, .05, "M4", null));
t.game.runStage();
}
});
t.th.start();
}
});
l.addView(b);
b=new Button(t);
b.setText("AK47 Assault Rifle");
b.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View v)
{
v.setOnClickListener(null);
t.th.interrupt();
t.th=new Thread(new Runnable()
{
@Override
public void run()
{
t.user.weapon.setPrimary(new Cweapon(Cweapon.TYPE_MODERN, Cweapon.ACCURATE|Cweapon.AUTOMATIC|Cweapon.HIGH_CALIBER|Cweapon.LARGE_MAGAZINE|Cweapon.LEGENDARY|Cweapon.LONG_RANGE|Cweapon.QUICK_RELOAD, .1, t.gen.nextBoolean() ? "AK47" : (t.gen.nextBoolean() ? "AK" : "Kalashnikov"), null));
t.game.runStage();
}
});
t.th.start();
}
});
l.addView(b);
b=new Button(t);
b.setText("AK74 Assault Rifle");
b.setOnClickListener(new OnClickListener()
{
@Override
public void onClick (View v)
{
v.setOnClickListener(null);
t.th.interrupt();
t.th=new Thread(new Runnable()
{
@Override
public void run()
{
t.user.weapon.setPrimary(new Cweapon(Cweapon.TYPE_MODERN, Cweapon.ACCURATE|Cweapon.AUTOMATIC|Cweapon.CLOSE_RANGE|Cweapon.LARGE_MAGAZINE|Cweapon.QUICK_RELOAD, -.1, "AK74", null));
t.game.runStage();
}
});
t.th.start();
}
});
l.addView(b);
b=new Button(t);
b.setText("M14 Designated Marksman\'s Rifle");
b.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View v)
{
v.setOnClickListener(null);
t.th.interrupt();
t.th=new Thread(new Runnable()
{
@Override
public void run()
{
t.user.weapon.setPrimary(new Cweapon(Cweapon.TYPE_MODERN, Cweapon.ACCURATE|Cweapon.HIGH_CALIBER|Cweapon.LARGE_MAGAZINE|Cweapon.LONG_RANGE|Cweapon.SLOW_RELOAD, .075, "M14", null));
t.game.runStage();
}
});
t.th.start();
}
});
l.addView(b);
b=new Button(t);
b.setText("FN FAL Designated Marksman\'s Rifle");
b.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View v)
{
v.setOnClickListener(null);
t.th.interrupt();
t.th=new Thread(new Runnable()
{
@Override
public void run()
{
t.user.weapon.setPrimary(new Cweapon(Cweapon.TYPE_MODERN, Cweapon.ACCURATE|Cweapon.HIGH_POWER_ROUNDS|Cweapon.HIGH_RECOIL|Cweapon.LARGE_MAGAZINE|Cweapon.LONG_RANGE|Cweapon.QUICK_RELOAD, -.025, "FN FAL", null));
t.game.runStage();
}
});
t.th.start();
}
});
l.addView(b);
b=new Button(t);
b.setText("Dragunov SVU Designated Marksman\'s Rifle");
b.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View v)
{
v.setOnClickListener(null);
t.th.interrupt();
t.th=new Thread(new Runnable()
{
@Override
public void run()
{
t.user.weapon.setPrimary(new Cweapon(Cweapon.TYPE_MODERN, Cweapon.ACCURATE|Cweapon.CLOSE_RANGE|Cweapon.HIGH_POWER_ROUNDS|Cweapon.LARGE_MAGAZINE|Cweapon.LONG_RANGE|Cweapon.LOW_POWER|Cweapon.QUICK_RELOAD, .01, "SVU", null));
t.game.runStage();
}
});
t.th.start();
}
});
l.addView(b);
b=new Button(t);
b.setText("Zastava M76 Designated Marksman\'s Rifle");
b.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View v)
{
v.setOnClickListener(null);
t.th.interrupt();
t.th=new Thread(new Runnable()
{
@Override
public void run()
{
t.user.weapon.setPrimary(new Cweapon(Cweapon.TYPE_MODERN, Cweapon.ACCURATE|Cweapon.CLOSE_RANGE|Cweapon.HIGH_CALIBER|Cweapon.HIGH_POWER_ROUNDS|Cweapon.LARGE_MAGAZINE|Cweapon.LEGENDARY|Cweapon.LONG_RANGE|Cweapon.QUICK_RELOAD, "Zastava", null));
t.user.weapon.strengthModifier=.25; // Here to circumvent the block on construction of weapons this strong
t.game.runStage();
}
});
t.th.start();
}
});
l.addView(b);
b=new Button(t);
b.setText("Barrett M95 Sniper Rifle");
b.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View v)
{
v.setOnClickListener(null);
t.th.interrupt();
t.th=new Thread(new Runnable()
{
@Override
public void run()
{
t.user.weapon.setPrimary(new Cweapon(Cweapon.TYPE_MODERN, Cweapon.ACCURATE|Cweapon.CUMBERSOME|Cweapon.HIGH_CALIBER|Cweapon.HIGH_POWER_ROUNDS|Cweapon.LARGE_MAGAZINE|Cweapon.LONG_RANGE|Cweapon.QUICK_RELOAD, .05, "Barrett .50", null));
t.game.runStage();
}
});
t.th.start();
}
});
l.addView(b);
b=new Button(t);
b.setText("Barrett XM109 Sniper Rifle");
b.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View v)
{
v.setOnClickListener(null);
t.th.interrupt();
t.th=new Thread(new Runnable()
{
@Override
public void run()
{
t.user.weapon.setPrimary(new Cweapon(Cweapon.TYPE_MODERN, Cweapon.ACCURATE|Cweapon.BOLT_FIRE|Cweapon.CUMBERSOME|Cweapon.EXPLOSIVE|Cweapon.HIGH_CALIBER|Cweapon.HIGH_POWER_ROUNDS|Cweapon.HIGH_RECOIL|Cweapon.LONG_RANGE|Cweapon.LONG_RANGE_ONLY|Cweapon.QUICK_RELOAD, .1, "Barrett grenade-firing sniper rifle", null));
t.game.runStage();
}
});
t.th.start();
}
});
l.addView(b);
b=new Button(t);
b.setText("L115A3 AWM Sniper Rifle");
b.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View v)
{
v.setOnClickListener(null);
t.th.interrupt();
t.th=new Thread(new Runnable()
{
@Override
public void run()
{
t.user.weapon.setPrimary(new Cweapon(Cweapon.TYPE_MODERN, Cweapon.ACCURATE|Cweapon.BOLT_FIRE|Cweapon.HIGH_CALIBER|Cweapon.HIGH_POWER_ROUNDS|Cweapon.HIGH_RECOIL|Cweapon.LONG_RANGE|Cweapon.LONG_RANGE_ONLY|Cweapon.QUICK_RELOAD, .2, "L115", null));
t.game.runStage();
}
});
t.th.start();
}
});
l.addView(b);
b=new Button(t);
b.setText("Anzio 20mm Anti-Material rifle");
b.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View v)
{
v.setOnClickListener(null);
t.th.interrupt();
t.th=new Thread(new Runnable()
{
@Override
public void run()
{
t.user.weapon.setPrimary(new Cweapon(Cweapon.TYPE_MODERN, Cweapon.ACCURATE|Cweapon.BOLT_FIRE|Cweapon.CUMBERSOME|Cweapon.EXPLOSIVE|Cweapon.HIGH_CALIBER|Cweapon.HIGH_POWER_ROUNDS|Cweapon.HIGH_RECOIL|Cweapon.LONG_RANGE|Cweapon.LONG_RANGE_ONLY|Cweapon.QUICK_RELOAD, .25, "extra heavy rifle", null));
t.game.runStage();
}
});
t.th.start();
}
});
l.addView(b);
b=new Button(t);
b.setText("P90 submachine gun");
b.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View v)
{
v.setOnClickListener(null);
t.th.interrupt();
t.th=new Thread(new Runnable()
{
@Override
public void run()
{
t.user.weapon.setPrimary(new Cweapon(Cweapon.TYPE_MODERN, Cweapon.AUTOMATIC|Cweapon.CLOSE_RANGE|Cweapon.CLOSE_RANGE_ONLY|Cweapon.LARGE_MAGAZINE|Cweapon.LIGHT|Cweapon.LOW_CALIBER|Cweapon.QUICK_RELOAD, .5, "P90", null));
t.game.runStage();
}
});
t.th.start();
}
});
l.addView(b);
b=new Button(t);
b.setText("MP5K submachine gun");
b.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View v)
{
v.setOnClickListener(null);
t.th.interrupt();
t.th=new Thread(new Runnable()
{
@Override
public void run()
{
t.user.weapon.setPrimary(new Cweapon(Cweapon.TYPE_MODERN, Cweapon.AUTOMATIC|Cweapon.CLOSE_RANGE|Cweapon.CLOSE_RANGE_ONLY|Cweapon.HIGH_RECOIL|Cweapon.LARGE_MAGAZINE|Cweapon.LIGHT|Cweapon.LOW_POWER|Cweapon.QUICK_RELOAD, .1, "MP5K", null));
t.game.runStage();
}
});
t.th.start();
}
});
l.addView(b);
b=new Button(t);
b.setText("UMP45 Submachine gun");
b.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View v)
{
v.setOnClickListener(null);
t.th.interrupt();
t.th=new Thread(new Runnable()
{
@Override
public void run()
{
t.user.weapon.setPrimary(new Cweapon(Cweapon.TYPE_MODERN, Cweapon.AUTOMATIC|Cweapon.CLOSE_RANGE|Cweapon.HIGH_CALIBER|Cweapon.HIGH_RECOIL|Cweapon.LARGE_MAGAZINE|Cweapon.LIGHT|Cweapon.LOW_POWER|Cweapon.QUICK_RELOAD, .02, "UMP45", null));
t.game.runStage();
}
});
t.th.start();
}
});
l.addView(b);
b=new Button(t);
b.setText("Thompson Submachine gun");
b.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View v)
{
v.setOnClickListener(null);
t.th.interrupt();
t.th=new Thread(new Runnable()
{
@Override
public void run()
{
String weapon;
if (t.gen.nextBoolean())
{
if (t.gen.nextBoolean())
weapon="Annihilator";
else
weapon="Tommy gun";
}
else
{
if (t.gen.nextBoolean())
weapon="M1928";
else
weapon="Thompson";
}
t.user.weapon.setPrimary(new Cweapon(Cweapon.TYPE_MODERN, Cweapon.ANCIENT|Cweapon.AUTOMATIC|Cweapon.CLOSE_RANGE|Cweapon.HIGH_CALIBER|Cweapon.LARGE_MAGAZINE|Cweapon.LIGHT|Cweapon.LOW_POWER|Cweapon.QUICK_RELOAD, .1, weapon, null));
t.game.runStage();
}
});
t.th.start();
}
});
l.addView(b);
b=new Button(t);
b.setText("Uzi submachine gun");
b.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View v)
{
v.setOnClickListener(null);
t.th.interrupt();
t.th=new Thread(new Runnable()
{
@Override
public void run()
{
t.user.weapon.setPrimary(new Cweapon(Cweapon.TYPE_MODERN, Cweapon.AUTOMATIC|Cweapon.CLOSE_RANGE|Cweapon.HIGH_POWER_ROUNDS|Cweapon.HIGH_RECOIL|Cweapon.LARGE_MAGAZINE|Cweapon.LEGENDARY|Cweapon.LIGHT|Cweapon.QUICK_RELOAD, .075, "Uzi", null));
t.game.runStage();
}
});
t.th.start();
}
});
l.addView(b);
b=new Button(t);
b.setText("AA-12 Shotgun");
b.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View v)
{
v.setOnClickListener(null);
t.th.interrupt();
t.th=new Thread(new Runnable()
{
@Override
public void run()
{
t.user.weapon.setPrimary(new Cweapon(Cweapon.TYPE_MODERN, Cweapon.AUTOMATIC|Cweapon.CLOSE_RANGE|Cweapon.CLOSE_RANGE_ONLY|Cweapon.HIGH_CALIBER|Cweapon.HIGH_POWER_ROUNDS|Cweapon.LIGHT|Cweapon.QUICK_RELOAD, -.01, "AA-12", null));
t.game.runStage();
}
});
t.th.start();
}
});
l.addView(b);
b=new Button(t);
b.setText("SPAS-12");
b.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View v)
{
v.setOnClickListener(null);
t.th.interrupt();
t.th=new Thread(new Runnable()
{
@Override
public void run()
{
t.user.weapon.setPrimary(new Cweapon(Cweapon.TYPE_MODERN, Cweapon.ACCURATE|Cweapon.CLOSE_RANGE|Cweapon.CLOSE_RANGE_ONLY|Cweapon.HIGH_CALIBER|Cweapon.HIGH_POWER_ROUNDS|Cweapon.LEGENDARY|Cweapon.LIGHT|Cweapon.SLOW_RELOAD, .05, "SPAS-12", null));
t.game.runStage();
}
});
t.th.start();
}
});
l.addView(b);
b=new Button(t);
b.setText("Remington 870 Shotgun");
b.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View v)
{
v.setOnClickListener(null);
t.th.interrupt();
t.th=new Thread(new Runnable()
{
@Override
public void run()
{
t.user.weapon.setPrimary(new Cweapon(Cweapon.TYPE_MODERN, Cweapon.ACCURATE|Cweapon.BOLT_FIRE|Cweapon.CLOSE_RANGE|Cweapon.CLOSE_RANGE_ONLY|Cweapon.HIGH_CALIBER|Cweapon.HIGH_POWER_ROUNDS|Cweapon.LIGHT|Cweapon.SLOW_RELOAD, .1, "Remington 870", null));
t.game.runStage();
}
});
t.th.start();
}
});
l.addView(b);
b=new Button(t);
b.setText("KS-23");
b.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View v)
{
v.setOnClickListener(null);
t.th.interrupt();
t.th=new Thread(new Runnable()
{
@Override
public void run()
{
t.user.weapon.setPrimary(new Cweapon(Cweapon.TYPE_MODERN, Cweapon.ACCURATE|Cweapon.BOLT_FIRE|Cweapon.CLOSE_RANGE|Cweapon.CLOSE_RANGE_ONLY|Cweapon.HIGH_CALIBER|Cweapon.HIGH_POWER_ROUNDS|Cweapon.HIGH_RECOIL|Cweapon.LIGHT|Cweapon.SLOW_RELOAD, .15, "KS-23", null));
t.game.runStage();
}
});
t.th.start();
}
});
l.addView(b);
b=new Button(t);
b.setText("Custom-made 3 gauge shotgun");
b.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View v)
{
v.setOnClickListener(null);
t.th.interrupt();
t.th=new Thread(new Runnable()
{
@Override
public void run()
{
t.user.weapon.setPrimary(new Cweapon(Cweapon.TYPE_MODERN, Cweapon.BOLT_FIRE|Cweapon.CLOSE_RANGE|Cweapon.CLOSE_RANGE_ONLY|Cweapon.EXPLOSIVE|Cweapon.HIGH_CALIBER|Cweapon.HIGH_POWER_ROUNDS|Cweapon.HIGH_RECOIL|Cweapon.SLOW_RELOAD, .1, "custom shotgun", null));
t.game.runStage();
}
});
t.th.start();
}
});
l.addView(b);
b=new Button(t);
b.setText("M27-IAR");
b.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View v)
{
v.setOnClickListener(null);
t.th.interrupt();
t.th=new Thread(new Runnable()
{
@Override
public void run()
{
t.user.weapon.setPrimary(new Cweapon(Cweapon.TYPE_MODERN, Cweapon.ACCURATE|Cweapon.AUTOMATIC|Cweapon.HIGH_POWER_ROUNDS|Cweapon.LARGE_MAGAZINE|Cweapon.LONG_RANGE, .05, "M27", null));
t.game.runStage();
}
});
t.th.start();
}
});
l.addView(b);
b=new Button(t);
b.setText("HK21");
b.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View v)
{
v.setOnClickListener(null);
t.th.interrupt();
t.th=new Thread(new Runnable()
{
@Override
public void run()
{
t.user.weapon.setPrimary(new Cweapon(Cweapon.TYPE_MODERN, Cweapon.AUTOMATIC|Cweapon.HIGH_RECOIL|Cweapon.LARGE_MAGAZINE|Cweapon.LONG_RANGE, -.075, "HK21", null));
t.game.runStage();
}
});
t.th.start();
}
});
l.addView(b);
b=new Button(t);
b.setText("LSAT");
b.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View v)
{
v.setOnClickListener(null);
t.th.interrupt();
t.th=new Thread(new Runnable()
{
@Override
public void run()
{
t.user.weapon.setPrimary(new Cweapon(Cweapon.TYPE_MODERN, Cweapon.ACCURATE|Cweapon.AUTOMATIC|Cweapon.HIGH_CALIBER|Cweapon.LARGE_MAGAZINE|Cweapon.LEGENDARY|Cweapon.LIGHT|Cweapon.LONG_RANGE, .075, "LSAT", null));
t.game.runStage();
}
});
t.th.start();
}
});
l.addView(b);
b=new Button(t);
b.setText("M60");
b.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View v)
{
v.setOnClickListener(null);
t.th.interrupt();
t.th=new Thread(new Runnable()
{
@Override
public void run()
{
t.user.weapon.setPrimary(new Cweapon(Cweapon.TYPE_MODERN, Cweapon.ACCURATE|Cweapon.AUTOMATIC|Cweapon.CLOSE_RANGE|Cweapon.CUMBERSOME|Cweapon.HIGH_CALIBER|Cweapon.HIGH_POWER_ROUNDS|Cweapon.HIGH_RECOIL|Cweapon.LARGE_MAGAZINE|Cweapon.LONG_RANGE|Cweapon.SLOW_RELOAD, .025, "M60", null));
t.game.runStage();
}
});
t.th.start();
}
});
l.addView(b);
if (t.config.triggerEgg(.5+(t.gen.nextDouble()/2)))
{
b=new Button(t);
b.setText("M134");
b.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View v)
{
v.setOnClickListener(null);
t.th.interrupt();
t.th=new Thread(new Runnable()
{
@Override
public void run()
{
t.user.weapon.setPrimary(new Cweapon(Cweapon.TYPE_MODERN, Cweapon.AUTOMATIC|Cweapon.CLOSE_RANGE|Cweapon.CUMBERSOME|Cweapon.EXPLOSIVE|Cweapon.HIGH_CALIBER|Cweapon.HIGH_POWER_ROUNDS|Cweapon.HIGH_RECOIL|Cweapon.LARGE_MAGAZINE|Cweapon.LEGENDARY|Cweapon.LONG_RANGE, t.gen.nextBoolean() ? "minigun" : "M134", null));
t.user.weapon.strengthModifier=.5;
t.game.runStage();
}
});
t.th.start();
}
});
l.addView(b);
}
b=new Button(t);
b.setText("RPG-7 Launcher");
b.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View v)
{
v.setOnClickListener(null);
t.th.interrupt();
t.th=new Thread(new Runnable()
{
@Override
public void run()
{
t.user.weapon.setPrimary(new Cweapon(Cweapon.TYPE_MODERN, Cweapon.CUMBERSOME|Cweapon.EXPLOSIVE|Cweapon.HIGH_POWER_ROUNDS|Cweapon.ONE_ROUND_MAGAZINE|Cweapon.SLOW_RELOAD, "RPG", null));
t.game.runStage();
}
});
t.th.start();
}
});
l.addView(b);
b=new Button(t);
b.setText("Bazooka");
b.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View v)
{
v.setOnClickListener(null);
t.th.interrupt();
t.th=new Thread(new Runnable()
{
@Override
public void run()
{
t.user.weapon.setPrimary(new Cweapon(Cweapon.TYPE_MODERN, Cweapon.CUMBERSOME|Cweapon.EXPLOSIVE|Cweapon.HIGH_CALIBER|Cweapon.ONE_ROUND_MAGAZINE|Cweapon.SLOW_RELOAD, .01, "bazooka", null));
t.game.runStage();
}
});
t.th.start();
}
});
l.addView(b);
b=new Button(t);
b.setText("Panzerschreck rocket launcher");
b.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View v)
{
v.setOnClickListener(null);
t.th.interrupt();
t.th=new Thread(new Runnable()
{
@Override
public void run()
{
t.user.weapon.setPrimary(new Cweapon(Cweapon.TYPE_MODERN, Cweapon.CUMBERSOME|Cweapon.EXPLOSIVE|Cweapon.HIGH_CALIBER|Cweapon.HIGH_POWER_ROUNDS|Cweapon.LONG_RANGE|Cweapon.ONE_ROUND_MAGAZINE|Cweapon.SLOW_RELOAD, .05, "panzerschreck", null));
t.game.runStage();
}
});
t.th.start();
}
});
l.addView(b);
b=new Button(t);
b.setText("Shoulder launched Multipurpose Assault Weapon");
b.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View v)
{
v.setOnClickListener(null);
t.th.interrupt();
t.th=new Thread(new Runnable()
{
@Override
public void run()
{
t.user.weapon.setPrimary(new Cweapon(Cweapon.TYPE_MODERN, Cweapon.ACCURATE|Cweapon.CUMBERSOME|Cweapon.EXPLOSIVE|Cweapon.HIGH_POWER_ROUNDS|Cweapon.LONG_RANGE|Cweapon.ONE_ROUND_MAGAZINE|Cweapon.SLOW_RELOAD, .1, "SMAW", null));
t.game.runStage();
}
});
t.th.start();
}
});
l.addView(b);
b=new Button(t);
b.setText("FIM-92");
b.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View v)
{
v.setOnClickListener(null);
t.th.interrupt();
t.th=new Thread(new Runnable()
{
@Override
public void run()
{
t.user.weapon.setPrimary(new Cweapon(Cweapon.TYPE_MODERN, Cweapon.ACCURATE|Cweapon.CUMBERSOME|Cweapon.EXPLOSIVE|Cweapon.HIGH_CALIBER|Cweapon.LONG_RANGE|Cweapon.ONE_ROUND_MAGAZINE, .075, "Stinger", null));
t.game.runStage();
}
});
t.th.start();
}
});
l.addView(b);
b=new Button(t);
b.setText("M67 Fragmentation Grenade");
b.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View v)
{
v.setOnClickListener(null);
t.th.interrupt();
t.th=new Thread(new Runnable()
{
@Override
public void run()
{
t.user.weapon.setPrimary(new Cweapon(Cweapon.TYPE_MODERN, Cweapon.EXPLOSIVE|Cweapon.HIGH_POWER_ROUNDS|Cweapon.LIGHT|Cweapon.ONE_ROUND_MAGAZINE|Cweapon.QUICK_RELOAD, .175, "frag", null));
t.game.runStage();
}
});
t.th.start();
}
});
l.addView(b);
b=new Button(t);
b.setText("MK-54");
b.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View v)
{
v.setOnClickListener(null);
t.th.interrupt();
t.th=new Thread(new Runnable()
{
@Override
public void run()
{
t.user.weapon.setPrimary(new Cweapon(Cweapon.TYPE_NUCLEAR, Cweapon.LIGHT, "Davy Crockett nuke", null));
t.game.runStage();
}
});
t.th.start();
}
});
l.addView(b);
b=new Button(t);
b.setText("Lightsaber");
b.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View v)
{
v.setOnClickListener(null);
t.th.interrupt();
t.th=new Thread(new Runnable()
{
@Override
public void run()
{
if (t.config.triggerEgg(.5-(t.gen.nextDouble()/2))) // We do NOT always want a working lightsaber.
t.user.weapon.setPrimary(new Cweapon(Cweapon.TYPE_FUTURE, Cweapon.CLOSE_RANGE|Cweapon.CLOSE_RANGE_ONLY|Cweapon.LIGHT, "lightsaber", null));
else
t.user.weapon.setPrimary(new Cweapon(Cweapon.TYPE_BLUNT, Cweapon.CLOSE_RANGE|Cweapon.CLOSE_RANGE_ONLY|Cweapon.LIGHT|Cweapon.LEGENDARY, (t.gen.nextBoolean() ? "broken" : "model")+" lightsaber", null));
t.game.runStage();
}
});
t.th.start();
}
});
l.addView(b);
b=new Button(t);
b.setText("Keep your current weapon");
b.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View v)
{
v.setOnClickListener(null);
t.th.interrupt();
t.th=new Thread(new Runnable()
{
@Override
public void run()
{
inputted=0;
runStage();
}
});
t.th.start();
}
});
l.addView(b);
}
});
break;
case 36:
t.th=new Thread(new Runnable()
{
@Override
public void run()
{
if (inputted==-1)
t.say("You examine your new "+t.user.weapon+", and put your old "+t.user.weapon.backup+" away, making room for your new main weapon, but still keeping your backup within reach.");
else
t.say("You decide your "+t.user.weapon+" is better than any weapon in the gunstore, and move off toward the valley.");
}
});
t.th.start();
prepContinueButton();
break;
case 37:
if (onMove(58))
return;
t.th=new Thread(new Runnable()
{
@Override
public void run()
{
t.say("The Valley", "You move away from the gunstore.\n\n\tAfter a good amount of walking, you finally enter the lush valley.\n\tYou find yourself surrounded by greenery and life, but the valley is much smaller than it seemed from a distance. Unfortunately, you need to leave it.\n\n\n\tYou search for a way away.\n\n\tStraight away from the path that leads to the gunstore is a downtrodden set of stones, almost as a staircase, leadng to a familiar skyline.\n\n\tFacing it, you see smoke out of the corner of your eye. Turning to your right, you see the light of a huge, hellish inferno on the horizon. You can almost see the fires. A large highway leads directly towards this pit.");
}
});
t.th.start();
prepContinueButton();
break;
case 38:
t.fadeout();
t.runOnUiThread(new Runnable()
{
@Override
public void run()
{
LinearLayout l=prepInput();
Button b=new Button(t);
b.setText("Go to familiarity");
b.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View v)
{
v.setOnClickListener(null);
t.th.interrupt();
t.th=new Thread(new Runnable()
{
@Override
public void run()
{
inputted=0;
runStage();
}
});
t.th.start();
}
});
l.addView(b);
b=new Button(t);
b.setText("Take the highway");
b.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View v)
{
v.setOnClickListener(null);
t.th.interrupt();
t.th=new Thread(new Runnable()
{
@Override
public void run()
{
inputted=1;
runStage();
}
});
t.th.start();
}
});
l.addView(b);
b=new Button(t);
b.setText("Return to the gunstore, and grab another weapon");
b.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View v)
{
v.setOnClickListener(null);
t.th.interrupt();
t.th=new Thread(new Runnable()
{
@Override
public void run()
{
inputted=0;
stage=34;
runStage();
}
});
t.th.start();
}
});
l.addView(b);
}
});
break;
case 39:
if (inputted==0)
{
if (onMove(1+t.gen.nextInt(10)))
return;
t.th=new Thread(new Runnable()
{
@Override
public void run()
{
String str=new String();
boolean say=true;
if (t.user.weapon.type<=Cweapon.TYPE_BLUNT)
{
if (t.user.weapon.backup!=null && t.user.weapon.backup.type<=Cweapon.TYPE_BLUNT) // We do not want to discuss trying to walk the chain of backups with the user. Just kill them.
{
t.user.dead=true;
say=false; // Prevent the usual speech.
t.say("Familiarity", "You barely manage to reach the summit of the staircase, gazing upon a line of destroyed buildings.\n\n\tAmong the ruined houses and fragmented skyscrapers, you see Gandalf running towards you, as if he was running late to meet you thanks to your choice of weapons, and miss the beast which destroys you.");
}
else
{
str=", watching your "+t.user.weapon+" slip out of your hand, seemingly floating away.\n\n\tYou feel yourself start to come to earth";
t.user.weapon=t.user.weapon.backup; // Remove the primary from existence. We don't need any TYPE_BLUNTs floating around.
}
}
else if (t.user.weapon.backup!=null && t.user.weapon.backup.type<=Cweapon.TYPE_BLUNT) // We know we don't need to walk the chain of weapon backups, since the prior if specifies that we already have a valid weapon in hand.
{
str=", gazing at your "+t.user.weapon.backup+" as it drifts out of its sheath and disappears.\n\n\tYou watch as you float away from familiarity";
if (t.user.weapon.backup.backup!=null && t.user.weapon.backup.backup.type>Cweapon.TYPE_BLUNT) // Transparently allow a valid weapon to be swapped in if its only one layer away from being valid.
t.user.weapon.backup=t.user.weapon.backup.backup;
else // Just remove the existence of a backup
t.user.weapon.backup=null;
}
if (say)
t.say("Familiarity", "You go to familiarity.\n\n\n\n\tAs you reach the summit of the stairs, you see a destroyed line of buildings, from tall skyscapers fallen into pieces, to houses in shambles.\n\n\tBefore you can continue further, Gandalf appears!\n\tHe yells,\n\n\t\tNo!\n\t\tYou must not!\n\t\tYour journey is not complete!\n\n\tBefore you can reply, he slaps you.\n\n\tYou go flying"+str+", and land in the pits.");
}
});
t.th.start();
prepContinueButton(new OnClickListener()
{
@Override
public void onClick(View v)
{
t.th=new Thread(new Runnable()
{
@Override
public void run()
{
stage=41;
runStage();
}
});
t.th.start();
}
});
}
else
{
if (onMove(80))
return;
t.th=new Thread(new Runnable()
{
@Override
public void run()
{
t.say("The Highway", "You take the Highway towards the fiery pits.\n\n\tAlong the way, you see a shadow!\n\n\tIt approaches you menacingly.");
}
});
t.th.start();
prepContinueButton();
}
break;
case 40:
runShadows((byte)((t.config.difficultyMult*t.gen.nextInt(10))+3), (byte)0, (byte)0);
break;
case 41:
if (onMove(85))
return;
t.th=new Thread(new Runnable()
{
@Override
public void run()
{
t.say(t.gen.nextBoolean() ? "The Pits" : "Hell", "You arrive in the fiery pits.\n\n\tYour first impression of them is hellish, full of fire everywhere, and generally not the place any person should ever be.\n\n\tSomehow, your second impression is even worse.\n\n\tOff in the distance, you see a structure of some sort, surrounded by shadows: Probably their home.\n\n\tBesides that, there is little more than ruins to be explored.");
}
});
t.th.start();
prepContinueButton();
break;
case 42:
runPits((byte)(t.gen.nextInt(6)+3), (byte)0, (byte)0, (byte)0, false);
break;
default:
t.logWarning("Unknown stage: "+stage);
t.th=new Thread (new Runnable()
{
@Override
public void run ()
{
String who=t.gen.nextBoolean() ? "Author" : "Programmer";
String occurence;
if (t.gen.nextBoolean())
{
if (t.gen.nextBoolean())
occurence="a meteor appears, and flattens you.";
else
occurence="a lightning bolt strikes you, and fries you.";
}
else
{
if (t.gen.nextBoolean())
occurence="a dinosaur appears, and eats you.";
else
occurence="a nuclear bomb appears under your feet and explodes, vaporizing you.";
}
t.say("The End of the World...?","The "+who+" has run out of ideas, so "+occurence);
}
});
t.th.start();
t.user.dead=true;
prepContinueButton();
}
++stage;
if (stage%(t.gen.nextInt(5)+2)==0 || t.gen.nextInt(100)==0)
t.config.requestDifficultyUpdate();
else
t.config.updateDifficultyOnce();
}
public static void signalGameContinue ()
{
if (!Thread.interrupted())
t.runOnUiThread (new Runnable ()
{
@Override
public void run()
{
View v=t.findViewById(R.id.gameContinueButton);
if (v==null)
{
t.displayHandler.removeMessages(1);
return;
}
((TextView)v).setTextColor(Color.GREEN);
}
});
}
public static void unSignalGameContinue () // Undoes the above signaling. Necessary for the use of sayWhat() in non-say() contexts.
{
if (!Thread.interrupted())
t.runOnUiThread (new Runnable ()
{
@Override
public void run()
{
View v=t.findViewById(R.id.gameContinueButton);
if (v==null)
{
t.displayHandler.removeMessages(1);
return;
}
((TextView)v).setTextColor(Color.RED);
}
});
}
public void runArthur(final byte stage, String input)
{
t.user.isArthur=true;
switch (stage)
{
case 0:
t.th.interrupt();
t.th=new Thread(new Runnable()
{
@Override
public void run()
{
t.say("Bridge of Death", "What is your quest?");
t.findViewById(R.id.gameContinueButton).setVisibility(View.GONE);
t.runOnUiThread(new Runnable ()
{
@Override
public void run()
{
EditText ev=new EditText(t);
ev.setOnFocusChangeListener(new OnFocusChangeListener()
{
@Override
public void onFocusChange(View v, boolean hasFocus)
{
if (hasFocus && t.config.fullscreen)
{
t.setUi();
TextView tv=((TextView)t.findViewById(R.id.gameTitle));
LinearLayout.LayoutParams lp=(LinearLayout.LayoutParams)tv.getLayoutParams();
int result=0;
int resourceId = t.getResources().getIdentifier("status_bar_height", "dimen", "android");
if (resourceId > 0) {
result = t.getResources().getDimensionPixelSize(resourceId);
}
lp.topMargin=result+10;
tv.setAlpha(1);
}
}
});
ev.setBackgroundColor(Color.rgb(128,128,128));
ev.setHint("What is your quest?");
ev.setHintTextColor(Color.WHITE);
ev.setTextColor(Color.BLACK);
ev.setShadowLayer(5.0f,5,5,Color.WHITE);
ev.setImeActionLabel("Submit", KeyEvent.KEYCODE_ENTER); // Consider changing this label.
ev.setImeOptions(EditorInfo.IME_ACTION_SEND);
ev.setInputType(InputType.TYPE_CLASS_TEXT|InputType.TYPE_TEXT_VARIATION_PERSON_NAME);
View v=t.findViewById(R.id.gameLayout);
if (v!=null)
((LinearLayout)v).addView(ev);
ev.requestFocus();
((InputMethodManager)t.getSystemService(Context.INPUT_METHOD_SERVICE)).showSoftInput(ev, InputMethodManager.SHOW_FORCED); // Force the soft keyboard open.
t.setUi(); // Doubly ensure sanity. See above comment.
ev.setOnEditorActionListener(new TextView.OnEditorActionListener() // Listen for submit or enter.
{
@Override
public boolean onEditorAction(TextView view, int actionId, KeyEvent event)
{
if (actionId==EditorInfo.IME_ACTION_SEND || actionId==EditorInfo.IME_NULL)
{
view.setOnEditorActionListener(null);
final EditText ev=(EditText)view;
ev.setVisibility(View.GONE);
// Close the soft keyboard, now that there's nothing for it to write to.
((InputMethodManager)t.getSystemService(Context.INPUT_METHOD_SERVICE)).hideSoftInputFromWindow(view.getWindowToken(), 0);
final String str=ev.getText().toString().trim();
((TextView)t.findViewById(R.id.gameText)).append("\n\n\""+str+"\"\n\n");
t.th=new Thread (new Runnable()
{
@Override
public void run ()
{
runArthur((byte)1, str);
}
});
t.th.start();
return true;
}
return false;
}
});
t.config.computerPaused=true;
}
});
}
});
t.th.start();
break;
case 1:
if (!"To seek the Holy Grail".equalsIgnoreCase(input))
{
t.sayWhat("Your voice echoes \"Auuuuuuuugh!\" across the Gorge of Eternal Peril as you are flung from the bridge.");
t.user.dead=true;
prepContinueButton();
return;
}
t.sayWhat("What is the air-speed velocity of an unladen swallow?");
t.findViewById(R.id.gameContinueButton).setVisibility(View.GONE);
t.runOnUiThread(new Runnable ()
{
@Override
public void run()
{
EditText ev=new EditText(t);
ev.setOnFocusChangeListener(new OnFocusChangeListener()
{
@Override
public void onFocusChange(View v, boolean hasFocus)
{
if (hasFocus && t.config.fullscreen)
{
t.setUi();
TextView tv=((TextView)t.findViewById(R.id.gameTitle));
LinearLayout.LayoutParams lp=(LinearLayout.LayoutParams)tv.getLayoutParams();
int result=0;
int resourceId = t.getResources().getIdentifier("status_bar_height", "dimen", "android");
if (resourceId > 0) {
result = t.getResources().getDimensionPixelSize(resourceId);
}
lp.topMargin=result+10;
tv.setAlpha(1);
}
}
});
ev.setBackgroundColor(Color.rgb(128,128,128));
ev.setHint("What is the air-speed velocity of an unladen swallow?");
ev.setHintTextColor(Color.WHITE);
ev.setTextColor(Color.BLACK);
ev.setShadowLayer(5.0f,5,5,Color.WHITE);
ev.setImeActionLabel("Submit", KeyEvent.KEYCODE_ENTER); // Consider changing this label.
ev.setImeOptions(EditorInfo.IME_ACTION_SEND);
ev.setInputType(InputType.TYPE_CLASS_TEXT|InputType.TYPE_TEXT_VARIATION_PERSON_NAME);
View v=t.findViewById(R.id.gameLayout);
if (v!=null)
((LinearLayout)v).addView(ev);
ev.requestFocus();
((InputMethodManager)t.getSystemService(Context.INPUT_METHOD_SERVICE)).showSoftInput(ev, InputMethodManager.SHOW_FORCED); // Force the soft keyboard open.
t.setUi(); // Doubly ensure sanity. See above comment.
ev.setOnEditorActionListener(new TextView.OnEditorActionListener() // Listen for submit or enter.
{
@Override
public boolean onEditorAction(TextView view, int actionId, KeyEvent event)
{
if (actionId==EditorInfo.IME_ACTION_SEND || actionId==EditorInfo.IME_NULL)
{
view.setOnEditorActionListener(null);
final EditText ev=(EditText)view;
ev.setVisibility(View.GONE);
// Close the soft keyboard, now that there's nothing for it to write to.
((InputMethodManager)t.getSystemService(Context.INPUT_METHOD_SERVICE)).hideSoftInputFromWindow(view.getWindowToken(), 0);
final String str=ev.getText().toString().trim();
((TextView)t.findViewById(R.id.gameText)).append("\n\n\""+str+"\"\n\n");
t.th=new Thread (new Runnable()
{
@Override
public void run ()
{
runArthur((byte)2, str);
}
});
t.th.start();
return true;
}
return false;
}
});
t.config.computerPaused=true;
}
});
break;
case 2:
if (!("What do you mean? An African or European swallow?".equalsIgnoreCase(input) || "What do you mean? African or European swallow?".equalsIgnoreCase(input)))
{
t.sayWhat("Your voice echoes \"Auuuuuuuugh!\" across the Gorge of Eternal Peril as you are flung from the bridge.");
t.user.dead=true;
prepContinueButton();
return;
}
t.sayWhat("What? I don\'t know that!\n\tAuuuuuuuugh!\n\n\n\n");
t.findViewById(R.id.gameContinueButton).setVisibility(View.GONE);
t.snooze(2500);
t.sayWhat("How do you know so much about swallows?");
t.findViewById(R.id.gameContinueButton).setVisibility(View.GONE);
t.runOnUiThread(new Runnable ()
{
@Override
public void run()
{
EditText ev=new EditText(t);
ev.setOnFocusChangeListener(new OnFocusChangeListener()
{
@Override
public void onFocusChange(View v, boolean hasFocus)
{
if (hasFocus && t.config.fullscreen)
{
t.setUi();
TextView tv=((TextView)t.findViewById(R.id.gameTitle));
LinearLayout.LayoutParams lp=(LinearLayout.LayoutParams)tv.getLayoutParams();
int result=0;
int resourceId = t.getResources().getIdentifier("status_bar_height", "dimen", "android");
if (resourceId > 0) {
result = t.getResources().getDimensionPixelSize(resourceId);
}
lp.topMargin=result+10;
tv.setAlpha(1);
}
}
});
ev.setBackgroundColor(Color.rgb(128,128,128));
ev.setHint("How do you know so much about swallows?");
ev.setHintTextColor(Color.WHITE);
ev.setTextColor(Color.BLACK);
ev.setShadowLayer(5.0f,5,5,Color.WHITE);
ev.setImeActionLabel("Submit", KeyEvent.KEYCODE_ENTER); // Consider changing this label.
ev.setImeOptions(EditorInfo.IME_ACTION_SEND);
ev.setInputType(InputType.TYPE_CLASS_TEXT|InputType.TYPE_TEXT_VARIATION_PERSON_NAME);
View v=t.findViewById(R.id.gameLayout);
if (v!=null)
((LinearLayout)v).addView(ev);
ev.requestFocus();
((InputMethodManager)t.getSystemService(Context.INPUT_METHOD_SERVICE)).showSoftInput(ev, InputMethodManager.SHOW_FORCED); // Force the soft keyboard open.
t.setUi(); // Doubly ensure sanity. See above comment.
ev.setOnEditorActionListener(new TextView.OnEditorActionListener() // Listen for submit or enter.
{
@Override
public boolean onEditorAction(TextView view, int actionId, KeyEvent event)
{
if (actionId==EditorInfo.IME_ACTION_SEND || actionId==EditorInfo.IME_NULL)
{
view.setOnEditorActionListener(null);
final EditText ev=(EditText)view;
ev.setVisibility(View.GONE);
// Close the soft keyboard, now that there's nothing for it to write to.
((InputMethodManager)t.getSystemService(Context.INPUT_METHOD_SERVICE)).hideSoftInputFromWindow(view.getWindowToken(), 0);
final String str=ev.getText().toString().trim();
((TextView)t.findViewById(R.id.gameText)).append("\n\n\""+str+"\"\n\n");
t.th=new Thread (new Runnable()
{
@Override
public void run ()
{
runArthur((byte)3, str);
}
});
t.th.start();
return true;
}
return false;
}
});
t.config.computerPaused=true;
}
});
break;
case 3:
if (!"Well, you have to know these things when you\'re a king you know".equalsIgnoreCase(input))
{
t.sayWhat("Your voice echoes \"Auuuuuuuugh!\" across the Gorge of Eternal Peril as you are flung from the bridge.");
t.user.dead=true;
prepContinueButton();
return;
}
t.sayWhat("Ohh.");
prepContinueButton(new View.OnClickListener()
{
@Override
public void onClick(View v)
{
t.th=new Thread(new Runnable()
{
@Override
public void run()
{
t.user.name="Arthur"; // So the egg doesn't trigger again.
t.game.stage=0;
t.game.runStage();
}
});
t.th.start();
}
});
break;
}
}
public void runShadows(final byte number, final byte stage, final byte input)
{
if (t.config.autosave)
{
(new Thread(new Runnable() // We don't want to save on the runStage thread, that might cause a noticeable delay. Note that if saving takes too long, we may get a conflict between several saves occuring at once. Consider naming the save thread.
{
@Override
public void run()
{
t.saveGame();
}
})).start();
}
if (number==0)
runStage();
else
{
if (stage==0)
{
t.fadeout();
if (t.user.weapon.type<=Cweapon.TYPE_BLUNT)
{
if (t.user.weapon.backup==null || t.user.weapon.backup.type<=Cweapon.TYPE_BLUNT)
{
t.user.dead=true;
t.th=new Thread(new Runnable()
{
@Override
public void run()
{
t.say("Unprepared", "You prepare to engage the fearsome figure with your "+t.user.weapon+", but it only seems to laugh.\n\n\tDiscarding your weapon, you ready your "+(t.user.weapon.backup==null ? "body for hand-to-hand combat" : t.user.weapon.backup)+", and charge.");
}
});
t.th.start();
prepContinueButton();
return;
}
else
{
t.th=new Thread(new Runnable()
{
@Override
public void run()
{
t.say("Always prepared", "You prepare to fight the spirit with your "+t.user.weapon+".\n\n\n\tIt seemingly finds your effort humorous, as it pauses its approach to laugh.\n\n\n\n\tThinking your "+t.user.weapon.backup+" more suited to the task, you discard the "+t.user.weapon+", throwing it to the side and away from your presence, and draw your "+t.user.weapon.backup+".\n\n\tThe shadow thinks this a more seriosu threat, as it stops its laughter and prepares itself to engage you.");
}
});
t.th.start();
prepContinueButton(new OnClickListener()
{
@Override
public void onClick(View v)
{
t.user.weapon=t.user.weapon.backup;
t.th=new Thread(new Runnable()
{
@Override
public void run()
{
runShadows(number, stage, input);
}
});
t.th.start();
}
});
return;
}
}
else if (t.user.weapon.backup!=null && t.user.weapon.backup.type<=Cweapon.TYPE_BLUNT)
{
t.th=new Thread(new Runnable()
{
@Override
public void run()
{
t.say("In your rush to prepare to defend yourself against the strange and mysterious figure before you, you fail to notice that your "+t.user.weapon.backup+" has slipped out of its holster.");
}
});
t.th.start();
prepContinueButton(new OnClickListener()
{
@Override
public void onClick(View v)
{
if (t.user.weapon.backup.backup!=null && t.user.weapon.backup.backup.type>Cweapon.TYPE_BLUNT)
t.user.weapon.backup=t.user.weapon.backup.backup;
else
t.user.weapon.backup=null;
t.th=new Thread(new Runnable()
{
@Override
public void run()
{
runShadows(number, stage, input);
}
});
t.th.start();
}
});
return;
}
t.runOnUiThread(new Runnable()
{
@Override
public void run()
{
LinearLayout l=prepInput();
doCommitSuicide=true;
Button b=new Button(t);
b.setText("Fight the "+(t.gen.nextBoolean() ? "shadow" : "apparition")+" with your primary weapon, a "+t.user.weapon);
b.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v)
{
v.setOnClickListener(null);
t.th.interrupt();
t.th=new Thread(new Runnable()
{
@Override
public void run()
{
runShadows(number, (byte)1, (byte)0);
}
});
t.th.start();
}
});
l.addView(b);
t.user.weapon.addSwapperTo(l, new Runnable()
{
@Override
public void run()
{
runShadows(number, stage, input);
}
});
b=new Button(t);
b.setText((t.gen.nextBoolean() ? "Run away" : "Flee")+" from the "+(t.gen.nextBoolean() ? "ghostly" : "shadowy")+" vision before you");
b.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View v)
{
v.setOnClickListener(null);
t.th.interrupt();
t.th=new Thread(new Runnable()
{
@Override
public void run()
{
runShadows(number, (byte)1, (byte)1);
}
});
t.th.start();
}
});
l.addView(b);
if (t.config.triggerEgg((t.gen.nextInt(10)+1)/11))
{
b=new Button(t);
b.setText("Make friends with the creature");
b.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View v)
{
v.setOnClickListener(null);
t.th.interrupt();
t.th=new Thread(new Runnable()
{
@Override
public void run()
{
runShadows(number, (byte)1, (byte)2);
}
});
t.th.start();
}
});
l.addView(b);
}
}
});
}
else
{
t.displayHandler.removeMessages(1);
if (Thread.interrupted() || onMove(t.gen.nextInt(85)+1))
return;
switch (input)
{
case 0:
Runnable r;
switch (t.user.weapon.type)
{
case Cweapon.TYPE_SHARP:
t.determineUserDeath(t.user.weapon.getRelativeStrength(Cweapon.CLOSE_RANGE|Cweapon.CLOSE_RANGE_ONLY|Cweapon.LIGHT)*.5);
r=new Runnable()
{
@Override
public void run()
{
if (t.user.dead)
t.say("Swordfight", "You swing at the "+(t.gen.nextBoolean() ? "shadow" : "vision")+", and miss.\n\n\tBefore you can ready yourself, the shadow consumes you, and you are no more.");
else
{
String word;
switch (t.gen.nextInt(3))
{
case 0:
word="even ";
break;
case 1:
word="yet ";
break;
case 2:
word="";
break;
default:
word="considerably ";
}
t.say("Close call", "You swing your sword, and connect.\n\n\n\tThe moment your sword touches the "+(t.gen.nextBoolean() ? "shadow" : "shape")+", the creature dissolves into a swirl of smoke, and your sword continues as if it wasn\'t there.\n\n\n\n\n\tYou shiver, questioning reality, and your sanity, "+word+"more than you already were.\n\n\n\n\n\n\n\tTryijg to walk it off, you deicide to continue along the highway.");
}
}
};
break;
case Cweapon.TYPE_ARCHERY:
t.determineUserDeath(t.user.weapon.getRelativeStrength(Cweapon.ACCURATE|Cweapon.CLOSE_RANGE), 3);
r=new Runnable()
{
@Override
public void run()
{
if (t.user.dead)
t.say("Bowman", "You ready your "+t.user.weapon+", and aim it at the shadow.\n\tJust as you loose the arrow, almost as if it were inside your mind, the shadow dodges, and lunges at you.\n\n\tThe last thing you hear is your "+t.user.gold+" spilling onto the highway.");
else
t.say("Deadeye", "You bring your "+t.user.weapon+" up to bear, and fire it at the shadow.\n\n\n\tThe projectile soars to the shadow, hitting it.\n\n\tThe moment it touches the vision, the shadow disappears into a swirl of smoke, and the arrow falls straight to the ground, as if it had hit an invisible wall.\n\n\n\n\tBy the time you reach it, it\'s gone.\n\n\n\n\n\tYou shiver.\n\n\tYou wonder how sane you are...");
}
};
break;
case Cweapon.TYPE_MODERN:
t.determineUserDeath(t.user.weapon.getRelativeStrength(Cweapon.ACCURATE|Cweapon.CLOSE_RANGE|Cweapon.HIGH_POWER_ROUNDS|Cweapon.QUICK_RELOAD), 4);
r=new Runnable()
{
@Override
public void run()
{
if (t.user.dead)
{
if (t.config.triggerEgg(6))
t.say("Alas, poor Yorick...","...I knew that one once.\n\n\tThey also called that adventurer \""+t.user+"\".\n\n\n\tThen, one day, a shadow appeared along the Highway to Hell, and the "+t.user.weapon+" the poor fool was carrying jammed, and no more was poor Yorick.");
else
t.say("A shot and a miss", "You take aim, your sights leveled at the "+(t.gen.nextBoolean() ? "shadow" : "figure")+".\n\n\tJust as you pull the trigger, the pits rumble with fiery power, shaking the ground, making you miss.\n\n\n\tOne day, years later, when the pits will have cooled, a child will come across the spot where the shadow consumed you, and all "+(t.gen.nextBoolean() ? "he" : "she")+" will find of you is your "+t.user.weapon+".");
}
else
t.say("Sharpshooter","You level your "+t.user.weapon+" directly at the shadow, and fire.\n\n\tThe round hits it, and the shadow disappears into a swirl of smoke.\n\n\tThe fired round clatters straight to the ground, as the smoke dissipates.\n\n\n\tYou walk over to it, but you can\'t find the round.\n\n\tYou can\'t quite shake the feeling that what you know isn\'t real.");
}
};
break;
case Cweapon.TYPE_NUCLEAR:
t.user.dead=true;
r=new Runnable()
{
@Override
public void run()
{
t.say("Doomsday", "You get out your "+t.user.weapon+", arm it, set the timer to one second, and start it.\n\n\tFrom familiarity, the shopkeepers gaze at the mushroom cloud from where you once stood, as the shadow of a dragon looms behind them.");
}
};
break;
case Cweapon.TYPE_FUTURE:
t.user.dead=false;
r=new Runnable()
{
@Override
public void run()
{
if (t.user.weapon.characteristicSet(Cweapon.CLOSE_RANGE_ONLY))
t.say("Jedi","You meet the "+(t.gen.nextBoolean() ? "shadow" : "vision")+", and swing your lightsaber.\n\n\tThe shadow disappears into smoke at the edges of your visoon as the "+t.user.weapon+" slices through it.\n\n\tYou continue, not particularly caring if it was real.");
else
t.say(t.capitalize(t.user.weapon.toString())+" über alles", "You level your "+t.user.weapon+" at the "+(t.gen.nextBoolean() ? "shadow" : "figure")+", and pull the trigger.\n\n\tBy the time the splash from the impact of the shot clears, the shadow is gone, but strangely there\'s no ash.\n\n\tYou ignore it, not caring about your own sanity.");
}
};
break;
default:
t.logError("Invalid weapon code: "+t.user.weapon.type);
t.user.weapon.type=Cweapon.TYPE_USED_FOR_CONVENIENCE;
r=new Runnable()
{
@Override
public void run()
{
t.say("Unknown","Your weapon "+(t.user.weapon.name==null || "".equals(t.user.weapon.name) ? "" : ", a "+t.user.weapon.name)+", is unknown to the universe, so...");
}
};
}
t.th=new Thread(r);
t.th.start();
prepContinueButton(new View.OnClickListener()
{
public void onClick(View v)
{
t.th=new Thread(new Runnable()
{
@Override
public void run()
{
if (t.user.weapon.type==Cweapon.TYPE_USED_FOR_CONVENIENCE)
t.user.commitSuicide();
else if (t.user.dead)
{
t.game.stage=-1;
t.game.runStage();
}
else
runShadows((byte)(number-1), (byte)0, input);
}
});
t.th.start();
}
});
break;
case 1:
t.user.dead=true;
t.th=new Thread(new Runnable()
{
@Override
public void run()
{
t.say("Deserter", "You try to run, but the shadow disappears, and reappears in front of you.");
}
});
t.th.start();
prepContinueButton();
break;
case 2:
t.user.dead=true;
t.th=new Thread(new Runnable()
{
@Override
public void run()
{
if (t.config.triggerEgg(0.5))
{
String[] weapons=new String[t.gen.nextInt(3)+3];
for (int i=0; i<weapons.length; ++i)
{
switch (t.gen.nextInt(8))
{
case 0:
weapons[i]="sword";
break;
case 1:
weapons[i]="crossbow";
break;
case 2:
weapons[i]="pistol";
break;
case 3:
weapons[i]="rifle";
break;
case 4:
weapons[i]="machine gun";
break;
case 5:
weapons[i]=((t.user.weapon.type!=Cweapon.TYPE_NUCLEAR && t.user.weapon.type!=Cweapon.TYPE_FUTURE) ? t.user.weapon.name : "strangely frightening weapon");
break;
case 6:
weapons[i]="M16";
break;
case 7:
weapons[i]="P90";
break;
default:
weapons[i]="sniper rifle";
}
}
String message="";
for (int i=1; i<weapons.length; ++i)
{
for (int n=0, m=(t.gen.nextInt(4)+2); n<m; ++n)
message+="\n";
message+="\tAfter a while of wandering along the Highway, yet another adventurer appears, this time with a "+weapons[i]+"!\n\n\tBegrudingly, you kill "+(t.gen.nextBoolean() ? "him" : "her")+", and continue walking along the Highway, caring even less about the humans.";
}
t.say("Assimilation", "You try to make friends with the "+(t.gen.nextBoolean() ? "shadow" : "vision")+"...\n\n\tMiraculously, it accepts you!\n\n\n\tIt escorts you to the pits, where you are brought to the shadow headquarters.\n\n\tThe "+(t.gen.nextBoolean() ? "shadows" : "mystical beings")+" perform some sort of ritual, and you watch as your body slips away from you as you become one of them.\n\n\n\tYou move out to the Highway, and immediately, you\'re attacked by an adventurer with a "+weapons[0]+"!\n\n\tYou try to befriend "+(t.gen.nextBoolean() ? "him" : "her")+", but you\'re forced to retailiate.\n\n\tYou can\'t help but lose some faith in humans."+message+"\n\n\tSuddenly, you find an adventurer!\n\t"+(t.gen.nextBoolean() ? "He" : "She")+" tries to run, but you can\'t help but kill any adventurer in your path.\n\n\n\tBarely afterward, another comes along, and tries to make friends.\n\n\tPerhaps if you hadn\'t spent so long on the Highway, you\'d accept, but now...\n\tYou kill "+(t.gen.nextBoolean() ? "him" : "her")+".\n\n\n\tThree days later, an adventurer appears with a "+(t.gen.nextBoolean() ? "raygun" : "lightsaber")+", and ends you.\n\n\n\tGandalf nods in approval, as you disappear into a swirl of smoke.");
}
else
{
String address;
switch (t.gen.nextInt(3))
{
case 0:
address="shadow";
break;
case 1:
address="vision";
break;
case 2:
address="other";
break;
default:
address="creature";
}
t.say("Friendship", "Friends are not so easily earned.\n\n\tThe "+address+" is not interested.");
}
}
});
t.th.start();
if (t.config.easterEggs)
t.delay(50); // If the easter egg is triggered, processing might take some time. We delay the UI work just to be sure.
prepContinueButton();
}
}
}
}
public void runPits(final byte number, final byte stage, final byte input, final byte input2, final boolean hasAssaultedHQ)
{
if (t.config.autosave)
{
(new Thread(new Runnable() // We don't want to save on the runStage thread, that might cause a noticeable delay. Note that if saving takes too long, we may get a conflict between several saves occuring at once. Consider naming the save thread.
{
@Override
public void run()
{
t.saveGame();
}
})).start();
}
if (number==0)
runStage();
else
{
switch(stage)
{
case 0: // Stage 0: User input on direction
t.fadeout();
t.runOnUiThread(new Runnable()
{
@Override
public void run()
{
LinearLayout l=prepInput();
Button b=new Button(t);
if (!hasAssaultedHQ)
{
b.setText("Mount an assault on the House of Shadows");
b.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View v)
{
v.setOnClickListener(null);
t.th=new Thread(new Runnable()
{
@Override
public void run()
{
runPits(number, (byte)1, (byte)0, input2, true);
}
});
t.th.start();
}
});
l.addView(b);
b=new Button(t);
}
if (t.gen.nextBoolean())
{
b.setText("Explore to your left");
b.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View v)
{
v.setOnClickListener(null);
t.th=new Thread(new Runnable()
{
@Override
public void run()
{
runPits(number, (byte)1, (byte)1, input2, hasAssaultedHQ);
}
});
t.th.start();
}
});
l.addView(b);
b=new Button(t);
}
if (t.gen.nextBoolean())
{
b.setText("Continue straight ahead");
b.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View v)
{
v.setOnClickListener(null);
t.th=new Thread(new Runnable()
{
@Override
public void run()
{
runPits(number, (byte)1, (byte)2, input2, hasAssaultedHQ);
}
});
t.th.start();
}
});
l.addView(b);
b=new Button(t);
}
if (t.gen.nextBoolean())
{
b.setText("Explore to your right");
b.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View v)
{
v.setOnClickListener(null);
t.th=new Thread(new Runnable()
{
@Override
public void run()
{
runPits(number, (byte)1, (byte)3, input2, hasAssaultedHQ);
}
});
t.th.start();
}
});
l.addView(b);
b=new Button(t);
}
b.setText("Make your way to the depression at the center of the pits");
b.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View v)
{
v.setOnClickListener(null);
t.th=new Thread(new Runnable()
{
@Override
public void run()
{
runPits((byte)0, stage, input, input2, hasAssaultedHQ);
}
});
t.th.start();
}
});
l.addView(b);
}
});
break;
case 1: // Stage 1: Describe findings
if (onMove(111))
return;
switch (input)
{
case 0: // Input 0: Assault HoS
t.th=new Thread(new Runnable()
{
@Override
public void run()
{
t.say(t.gen.nextBoolean() ? "Assault" : "Infiltration", "You charge the House of Shadows.\n\n\tAs you approach, you find more and more shadows.\n\n\tYou suspect that they know you\'re coming.\n\n\tYou try to sneak in, planning to use stealth to kill each shadow alone.\n\n\tUnfortunately, you\'re caught trying to enter by a sentry group of three shadows.\n\n\n\tInside the House, you see an object.\n\n\tUpon closer examination, you can read the label: \"US Army M183 Demolition Charge: 20 lbs.\"\n\n\tFrom what little you know about explosives, you think that that charge would be large enough to turn the House of Shadows into one large fragmentation grenade.\n\n\n\n\n\tThe "+(t.gen.nextBoolean() ? "shadows" : "visions")+" ready for battle.");
}
});
t.th.start();
prepContinueButton(new OnClickListener()
{
@Override
public void onClick(View v)
{
v.setOnClickListener(null);
t.th=new Thread(new Runnable()
{
@Override
public void run()
{
runPits(number, (byte)2, input, input2, hasAssaultedHQ);
}
});
t.th.start();
}
});
break;
case 1: // Input 1: Explore left
if (t.gen.nextBoolean())
{
t.th=new Thread(new Runnable()
{
@Override
public void run()
{
t.say("Explorer", "You head to an abandoned shop in ruins...\n\n\tBut a shadow catches you along the way!");
}
});
t.th.start();
prepContinueButton(new OnClickListener()
{
@Override
public void onClick(View v)
{
v.setOnClickListener(null);
t.th=new Thread(new Runnable()
{
@Override
public void run()
{
runPits(number, (byte)2, input, input2, hasAssaultedHQ);
}
});
t.th.start();
}
});
}
else
runPits(number, (byte)100, input, input2, hasAssaultedHQ);
break;
case 2: // Input 2: Continue straight
if (t.gen.nextBoolean())
{
t.th=new Thread(new Runnable()
{
@Override
public void run()
{
t.say("Conquest", "You march straight ahead, towards the destroyed remains of a household.\n\n\n\tA "+(t.gen.nextBoolean() ? "shadow" : "figure")+" blocks your path, guarding the ruined house as if it had been "+(t.gen.nextBoolean() ? "his" : "her")+" home.");
}
});
t.th.start();
prepContinueButton(new OnClickListener()
{
@Override
public void onClick(View v)
{
v.setOnClickListener(null);
t.th=new Thread(new Runnable()
{
@Override
public void run()
{
runPits(number, (byte)2, input, input2, hasAssaultedHQ);
}
});
t.th.start();
}
});
}
else
runPits(number, (byte)100, input, input2, hasAssaultedHQ);
break;
case 3: // Input 3: Explore right
if (t.gen.nextBoolean())
{
t.th=new Thread(new Runnable()
{
@Override
public void run()
{
t.say("Pits: The Final Frontier", "You travel towards what appears to be a bank.\n\n\tJust as you approach, a shadow opens the door.");
}
});
t.th.start();
prepContinueButton(new OnClickListener()
{
@Override
public void onClick(View v)
{
v.setOnClickListener(null);
t.th=new Thread(new Runnable()
{
@Override
public void run()
{
runPits(number, (byte)2, input, input2, hasAssaultedHQ);
}
});
t.th.start();
}
});
}
else
runPits(number, (byte)100, input, input2, hasAssaultedHQ);
break;
}
break;
case 2: // Stage 2: Combat
Runnable r;
switch (input)
{
case 0: // Input 0: Assault HoS
r=new Runnable()
{
@Override
public void run()
{
LinearLayout l=prepInput();
doCommitSuicide=true;
Button b=new Button(t);
b.setText("Fight the trio of shadows with your primary "+t.user.weapon);
b.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View v)
{
v.setOnClickListener(null);
t.th=new Thread(new Runnable()
{
@Override
public void run()
{
runPits(number, (byte)3, input, (byte)0, hasAssaultedHQ);
}
});
t.th.start();
}
});
l.addView(b);
t.user.weapon.addSwapperTo(l, new Runnable()
{
@Override
public void run()
{
runPits(number, stage, input, input2, hasAssaultedHQ);
}
});
b=new Button(t);
b.setText("Make a run for the demolition charge");
b.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View v)
{
v.setOnClickListener(null);
t.th=new Thread(new Runnable()
{
@Override
public void run()
{
runPits(number, (byte)3, input, (byte)1, hasAssaultedHQ);
}
});
}
});
l.addView(b);
b=new Button(t);
b.setText(t.gen.nextBoolean() ? "Run away!" : "Flee");
b.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View v)
{
v.setOnClickListener(null);
t.th=new Thread(new Runnable()
{
@Override
public void run()
{
runPits(number, (byte)3, input, (byte)2, hasAssaultedHQ);
}
});
t.th.start();
}
});
l.addView(b);
}
};
break;
case 1: // Input 1: Explore left
case 2: // Input 2: Continue straight
case 3: // Input 3: Explore right - All these are duplicate cases.
r=new Runnable()
{
@Override
public void run()
{
LinearLayout l=prepInput();
doCommitSuicide=true;
Button b=new Button(t);
String word;
switch (t.gen.nextInt(4))
{
case 0:
word="shadow";
break;
case 1:
word="figure";
break;
case 2:
word="vision";
break;
case 3:
word="monster";
break;
default:
word="creature";
}
b.setText("Fight the "+word+" with your primary "+t.user.weapon);
b.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View v)
{
v.setOnClickListener(null);
t.th=new Thread(new Runnable()
{
@Override
public void run()
{
runPits(number, (byte)3, input, (byte)0, hasAssaultedHQ);
}
});
t.th.start();
}
});
l.addView(b);
t.user.weapon.addSwapperTo(l, new Runnable()
{
@Override
public void run()
{
runPits(number, stage, input, input2, hasAssaultedHQ);
}
});
b=new Button(t);
b.setText(t.gen.nextBoolean() ? "Run away" : "Flee");
b.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View v)
{
v.setOnClickListener(null);
t.th=new Thread(new Runnable()
{
@Override
public void run()
{
runPits(number, (byte)3, input, (byte)1, hasAssaultedHQ);
}
});
t.th.start();
}
});
l.addView(b);
}
};
break;
default:
r=new Runnable()
{
@Override
public void run()
{
LinearLayout l=prepInput("Your situation is unknown");
doCommitSuicide=true;
Button b=new Button(t);
b.setText("Try this again");
b.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View v)
{
v.setOnClickListener(null);
t.th=new Thread(new Runnable()
{
@Override
public void run()
{
runPits(number, (byte)0, (byte)0, (byte)0, true);
}
});
t.th.start();
}
});
l.addView(b);
b=new Button(t);
b.setText("Be done with it");
b.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View v)
{
v.setOnClickListener(null);
t.th=new Thread(new Runnable()
{
@Override
public void run()
{
t.user.commitSuicide();
}
});
t.th.start();
}
});
l.addView(b);
}
};
}
t.fadeout();
t.runOnUiThread(r);
break;
case 3: // Stage 3: Results of combat
switch (input)
{
case 0:
switch (input2)
{
case 0:
if (t.user.weapon.type==Cweapon.TYPE_ARCHERY && .5>(t.config.difficultyMult*.75*t.user.weapon.getAbsoluteStrength()))
{
archeryMinigame((int)Math.ceil(t.gen.nextInt(40)+(t.config.difficultyMult*10)+5), ((20*(1-t.config.difficultyMult))+5)/5);
t.th=new Thread(new Runnable()
{
@Override
public void run()
{
if (t.user.dead)
{
String title;
switch (t.gen.nextInt(3))
{
case 0:
title="Archer";
break;
case 1:
title="Bowman";
break;
case 2:
title="Outnumbered";
break;
default:
title="Outdone by the dark";
}
switch (t.gen.nextInt(3))
{
case 0:
t.say(title, "You turn to face the "+(t.gen.nextBoolean() ? "figures" : "shadows")+", but you\'re immediately killed by the leading shadow.");
break;
case 1:
t.say(title, "You draw your "+t.user.weapon+", turning against the "+(t.gen.nextBoolean() ? "shadows" : "figures")+", shooting the leading one, and turning it to swirling smoke, but the others reach you before you can ready another shot.");
break;
case 2:
t.say(title, "You quickly turn and fire an arrow at the lead "+(t.gen.nextBoolean() ? "shadow" : "vision")+", turning it into a cloud of smoke. Quickly, you dodge to the side of the remaining two attacks.\n\n\tYou ready and fire a second shot, eliminating another opponent, but the last defeats you.");
break;
default:
Log.wtf("Cgame at House of Shadows", "Invalid return from Random.nextInt()");
t.say(title, "The enemies that stand before you overpower you.");
}
}
else
t.say("Veteran", "Despite the odds against you, your archery skills prevail in a tale that will be sung throughout time: You shoot the leading "+(t.gen.nextBoolean() ? "shadow" : "figure")+", and dodge the attack of the next without pausing to watch the smoke swirl away.\n\n\tIn the blink of an eye, the second "+(t.gen.nextBoolean() ? "shadow" : "vision")+" recuperates, but you ready your "+t.user.weapon+" even faster, and shoot it too.\n\n\tThe third is upon you quickly, and you defend yourself by blocking with your "+t.user.weapon+", which gets tossed aside in the process.\n\n\n\tBefore the final "+(t.gen.nextBoolean() ? "shadow" : "creature")+" can "+(t.gen.nextBoolean() ? "attack" : "assault")+" you, you draw "+("crossbow".equalsIgnoreCase(t.user.weapon.name) ? "a bolt" : "an arrow")+" from your stockpile, and stab it.\n\n\tIt vanishes in a swirling cloud of smoke.\n\n\tYou note your spent ammunition has disappeared entirely.\n\n\n\tBrushing this fact aside, you turn your attention to the House of Shadows.");
}
});
t.th.start();
if (t.user.dead)
prepContinueButton();
else
prepContinueButton(new OnClickListener()
{
@Override
public void onClick(View v)
{
t.th=new Thread(new Runnable()
{
@Override
public void run()
{
runPits(number, (byte)4, input, input2, hasAssaultedHQ);
}
});
t.th.start();
}
});
}
else
{
boolean undead=false;
switch (t.user.weapon.type)
{
case Cweapon.TYPE_SHARP:
t.determineUserDeath((t.user.weapon.getUnneededFlags(Cweapon.CLOSE_RANGE_ONLY, 5)+(1-t.user.weapon.getNeededFlags(Cweapon.ACCURATE|Cweapon.CLOSE_RANGE|Cweapon.LIGHT|Cweapon.QUICK_RELOAD, 2)))*.99);
r=new Runnable()
{
@Override
public void run()
{
if (t.user.dead)
{
switch (t.gen.nextInt(3))
{
case 0:
t.say("Outnumbered and outdone", "You face the creatures with your "+t.user.weapon+", fending them away, but one gets past you long before you can strike any.");
break;
case 1:
t.say("Death "+(t.gen.nextBoolean() ? "Unbounded" : "knows no bounds"), "You swing your sword at the leading "+(t.gen.nextBoolean() ? "shadow" : "figure")+", and, miraculously, connect.\n\n\tThe lead shafow disappears in a swirl of smoke, and you turn to face the next, but you\'re caught from behind by the last.");
break;
case 2:
t.say("The Darkness of Death", "You move quickly, as quickly as you ever have in your life.\n\n\tYou turn the leading shadow into a swirl of smoke, then the second.\n\nThe third, however, evades your swing, not letting it touch, and ends you.");
break;
default:
Log.wtf("Cgame at House of Shadows", "Invalid result from Random.nextInt()");
t.say("Nonexistence", "You corrupt the state of the Universe and cease to exist.");
}
}
else
t.say(t.gen.nextBoolean() ? "Swordsman" : "Sword master", "You swing your sword as fast as humanly possible, turning one, then two, "+(t.gen.nextBoolean() ? "shadows" : "figures")+" into swirling smoke.\n\n\tThe last shadow charges toward you, but your sword nicks it, and it disapears.\n\n\tA booming voice, almost like Gandalf\'s, echoes from the clouds:\n\n\t\tWhy do you still carry that puny "+t.user.weapon+"??\n\t\tFind a new weapon.\n\t\tNow.\n\n\n\n\n\tYou turn your attention away from the voice, and to the House of Shadows.");
}
};
break;
case Cweapon.TYPE_ARCHERY:
t.determineUserDeath(.75*t.user.weapon.getAbsoluteStrength());
r=new Runnable()
{
@Override
public void run()
{
if (t.user.dead)
{
String title;
switch (t.gen.nextInt(4))
{
case 0:
title="Archer";
break;
case 1:
title="Bowman";
break;
case 2:
title="Outnumbered";
break;
default:
title="Outdone by the dark";
}
switch (t.gen.nextInt(3))
{
case 0:
t.say(title, "You turn to face the shadows, but they easily defeat you before you get off a single shot.");
break;
case 1:
t.say(title, "You spin to face your enemy, and fire a single "+("crossbow".equalsIgnoreCase(t.user.weapon.name) ? "bolt" : "arrow")+" at the leading "+(t.gen.nextBoolean() ? "shadow" : "apparition")+".\n\n\tYour aim "+(t.gen.nextBoolean() ? "is true" : (t.gen.nextBoolean() ? "is that of a master" : "is masterful"))+", turning the leader of the trio into a swirl of smoke.\n\n\tHowever, before you can ready yourself again, the other two elminate you.");
break;
case 2:
t.say(title, "You load one "+("crossbow".equalsIgnoreCase(t.user.weapon.name) ? "bolt" : "arrow")+", and thoughtlessly fire it at the lead "+(t.gen.nextBoolean() ? "shadow" : "figure")+".\n\n\tYou\'ve practiced your archery considerably, and the shot flies directly into its target.\n\n\tYou ignore the sight as your opponent disappears into a swirling cloud of shadowy smoke, and dodge the advance of your second adversary, which you shoot shortly afterwards.\n\n\n\tAlas, you lost track of the third shadow, which comes from behind you, and kills you.");
break;
default:
Log.wtf("Cgame at the House of Shadows", "Invalid output from Random.nextInt()");
}
}
else
t.say((t.config.GoTEggs && t.config.triggerEgg(.8)) ? "Lightbringer" : "Defeater of Shadows", "You turn, snappily aiming your "+t.user.weapon+" directly at the leading "+(t.gen.nextBoolean() ? "shadow" : "apparition")+", and shooting it.\n\n\tPaying it no attention as it disappears into swirling smoke.\n\n\tInstead, as if by instinct, you roll towards the House of Shadows."+(t.gen.nextBoolean() ? "" : "\n\n\tYou quickly recover from the pain of your miscalculation after you slam into the outer wall.")+"\n\n\tWithout taking the time to stand, you adjust your aim, directly at the second enemy.\n\n\tQuickly, you release your shot, sending "+("crossbow".equalsIgnoreCase(t.user.weapon.name) ? "a bolt" : "an arrow")+" flying into the second shape, then clattering to the ground as your opponent swirls away.\n\n\n\tThe third charges, but you pull one "+("crossbow".equalsIgnoreCase(t.user.weapon.name) ? "bolt" : "arrow")+" from your reserves, and drive it through your final adversary, noting the lack of resistance as it goes through.\n\n\tYou watch the remmains of your opponent swirl away, and note your two fired shots have vanished.");
}
};
break;
case Cweapon.TYPE_MODERN:
final targetingMinigame.output res=aimMinigame();
undead=(res.type==targetingMinigame.output.BULLSEYE);
final String title=res.toString();
r=new Runnable()
{
@Override
public void run()
{
if (t.user.weapon.characteristicSet(Cweapon.AUTOMATIC))
{
t.user.dead=(res.distance/(.8*targetingMinigame.output.MAX_DISTANCE))<((.5*(t.gen.nextDouble()+t.config.difficultyMult))+.5);
if (t.user.dead)
{
switch (res.type)
{
case targetingMinigame.output.MISSED:
t.say(title, "You fire a burst of bullets towards the shadows, but your aim is off, and the "+(t.gen.nextBoolean() ? "shadows" : "figures")+" end you.");
break;
case targetingMinigame.output.GRAZED:
t.say(title, "You turn at the shadows, and fire a burst of automatic fire. One shot hits the nearest "+(t.gen.nextBoolean() ? "shadow" : "vision")+", turning it to a swirl of smoke, but the remaining two intercept you.");
break;
case targetingMinigame.output.POOR:
t.say(title, "You fire at the shadows, grazing one, turning it to swirling smoke, and barely hitting another.\n\n\tThe last consumes you as the second disappears.");
break;
case targetingMinigame.output.HIT:
t.say(title, "You fire at the shadows, hitting one with a solid shot, and "+(t.gen.nextBoolean() ? "turning" : "converting")+" it into a swirling cloud.\n\n\tAnother bullet strikes the second, eliminating it as well, but "+(t.user.weapon.characteristicSet(Cweapon.HIGH_RECOIL) ? "the recoil of your "+t.user.weapon+" throws off your aim." : "the last shadow moves out of your sights too quickly."));
break;
case targetingMinigame.output.GOOD:
t.say(title, "You hit two shadows with near perfect shots.\n\n\tThe shadows disappear into swirling smoke, as the third approaches you.\n\n\n\n\n\tYou quickly twist, aiming directly at the last shadow.\n\n\n\n\n\n\tYou pull the trigger, just as it reaches you."+(t.config.triggerEgg(.5) ? "\n\n\n\tThe shadow of a dragon looms over the pits, the rush of air stirring everything around, as you both become swirling smoke, and "+t.user.gold+", along with your "+t.user.weapon+", clatter to the ground." : ""));
break;
case targetingMinigame.output.CRITICAL:
t.say(title, "You hit the first two shadows with perfect shots, but find that the third seems to have disappeared.\n\n\tYou twist and turn, searching for it, "+(t.config.triggerEgg(.75) ? "and feel a thud, and a weight.\n\n\tYou fall, watching the shadow run, and attempt to give chase.\n\n\tSoon, it leaves your sight. Contented, you enter the House of Shadows, grabbing the detonator, assuming that the charge is at it was.\n\n\n\n\tYou walk clear of the House, wondering why you feel as if there is a huge weight on your back.\n\n\n\tYou realize that the shadow planted the charge on your back a moment too late, as you trigger the explosive." : "and soon finding it, right behind you.\n\n\tYou dodge its lunge, dropping your "+t.user.weapon+" in your haste to "+(t.gen.nextBoolean() ? "escape" : "survive")+", and, just as you think you\'ve escaped, you trip, rolling down a hill, coming to a stop in a ditch full of a hundred shadows."));
break;
case targetingMinigame.output.BULLSEYE:
t.user.dead=false;
t.say(title+", despite impossibility", "You fire three utterly perfect shots, cleanly converting two shadows into swirling smoke, and then you fire a hail of bullets into the third, ending it as well.\n\n\tDespite the incredibly difficult odds against you, you have prevailed.");
break;
default:
t.say("Gunshot", "You are easily defeated by the shadows.");
}
}
else
{
switch (res.type)
{
case targetingMinigame.output.MISSED:
t.say(title, "You miss every shot in your magazine, yet manage to kill all three shadows by using your "+t.user.weapon+" as a club.\n\n\n\tFrom the clouds, a booming voice, almost like Gandalf\'s, echoes through the pits:\n\n\t\tGet better aim!!\n\t\tSeriously, go to target practice or something...\n\t\tThat was ridiculous.\n\n\n\n\n\n\tYou shake it off and turn your attention to the House of Shadows.");
break;
case targetingMinigame.output.GRAZED:
t.say(title, "You fire at the enemies, full automatic fire, and yet the shadows keep managing to dodge your fire.\n\n\t"+(t.user.weapon.characteristicSet(Cweapon.HIGH_RECOIL) ? "You suspect that its because your "+t.user.weapon+" has too much recoil.\n\n\t" : "")+"Just as you begin to worry about the need to reload, one bullet grazes the leading shadow.\n\tSomehow, to your surprise, it disappears, turning into swirling smoke.\n\n\n\n\tThe remaining "+(t.gen.nextBoolean() ? "shadows" : "figures")+" mirror your surprise: They pause in shock.\n\n\tYou take advantage of their surprise to fire "+(t.gen.nextBoolean() ? "a trio" : "a hail")+" of "+(t.gen.nextBoolean() ? "rounds" : "bullets")+" at the second "+(t.gen.nextBoolean() ? "figure" : "shadow")+".\n\n\tIt disappears into a swirling cloud of smoke, and you continue firing, now at the last enemy, and barely manage to graze it.\n\n\n\tIgnoring what is now just a cloud of smoke, you turn on the House of Shadows.");
break;
case targetingMinigame.output.POOR:
t.say(title, "You level the sights of your "+t.user.weapon+" directly at the leading "+(t.gen.nextBoolean() ? "shadow" : "figure")+", and fire a "+(t.gen.nextBoolean() ? "hail" : "number")+" of rounds into it.\n\n\n\tIt "+(t.gen.nextBoolean() ? "becomes" : "disappears into")+" a swirling cloud of smoke, as you turn your attention to the second enemy.\n\n\tIt approaches "+(t.gen.nextBoolean() ? "menacingly" : "threateningly")+", but you "+(t.gen.nextBoolean() ? "are able" : "manage")+" to level your sights at it, and you squeeze the trigger, watching the bullets barely hit the "+(t.gen.nextBoolean() ? "shadow" : "figure")+".\n\n\tLuckily, it seems that any hit will "+(t.gen.nextBoolean() ? "dissolve" : "destroy")+" the shadow, and you watch as it disappears into a swirling cloud of smoke.\n\n\n\n\n\tUnfortunately, you seem to have lost track of the third...\n\n\n\n\tYou look left...\n\n\t...and right...\n\n\t...left...\n\n\t...and there it is!\n\n\n\n\tThe last "+(t.gen.nextBoolean() ? "shadow" : "figure")+" "+(t.gen.nextBoolean() ? "shows itself" : "appears")+" immediately just in front of you!\n\n\n\n\n\n\tYou hastily fire your "+t.user.weapon+", and turn it to smoke, barely surviving the encounter.\n\n\tYou shake yourself off, and turn to face the House of Shadows.");
break;
case targetingMinigame.output.HIT:
t.say(title, "You aim your "+t.user.weapon+" directly at the leading enemy, and "+(t.gen.nextBoolean() ? "squeeze" : "pull")+" the trigger.\n\n\tA "+(t.gen.nextBoolean() ? "burst" : "number")+" of rounds fly directly at it, and strike it, turning it into a swirling cloud of smoke.\n\n\tYou quickly turn, and aim at the second "+(t.gen.nextBoolean() ? "shadow" : "figure")+", and manage to send a hail of "+(t.gen.nextBoolean() ? "rounds" : "fire")+" flying directly at it.\n\n\n\tYou pause for a split second to watch as the "+(t.gen.nextBoolean() ? "apparition" : "shadow")+" dissolves into a cloud of smoke.\n\n\tThe final shadow seems to have disappeared.\n\n\t"+(t.gen.nextBoolean() ? "You" : "Your "+t.user.weapon)+" feels light, "+(t.user.weapon.characteristicSet(Cweapon.QUICK_RELOAD) ? "so you quickly switch cartridges." : "but you decide it would take too long to reload it.")+"\n\n\n\n\tYou return your attention to where it probably should be, the rather deadly "+(t.gen.nextBoolean() ? "shadow" : "apparition")+" that could reappear and kill you at any moment.\n\tSuddenly, it reappears: Right in front of you!\n\n\n\n\tYou quickly pull the trigger, firing several shots into the "+(t.gen.nextBoolean() ? "figure" : "shadow")+" before you.\n\n\n\tYou turn to oppose the House of Shadows as it disappears into a swirling cloud of smoke.");
break;
case targetingMinigame.output.GOOD:
t.say(title, "You aim, and fire your "+t.user.weapon+" directly at the "+(t.gen.nextBoolean() ? "nearest" : (t.gen.nextBoolean() ? "closest" : "nearest"))+" "+(t.gen.nextBoolean() ? "shadow" : "figure")+", sending a hail of bullets flying directly at its core.\n\n\n\tThe first round out of your "+(t.gen.nextBoolean() ? "weapon" : t.user.weapon)+" hits it, turning it into a swirling cloud of smoke.\n\n\n\tYou quickly shift your aim, leveling your sights at the next target, and "+(t.gen.nextBoolean() ? "squeeze" : "pull")+" the trigger, scoring a solid hit, and turning the shadow into a swirling cloud of smoke.\n\n\n\tThe third shadow comes around to face you, and dodges your first burst.\n\n\n\tYou quickly adjust your aim, and "+(t.gen.nextBoolean() ? "squeeze" : "pull")+" the trigger, scoring another hit and ending the shadow.\n\n\n\tYou turn to face the House of Shadows as it turns to swirling smoke.");
break;
case targetingMinigame.output.CRITICAL:
t.say(title, "You aim at the leading "+(t.gen.nextBoolean() ? "shadow" : "figure")+", and fire a hail of rounds from your "+t.user.weapon+", scoring an extremely solid shot and dissolving it.\n\n\n\tAs it disappears into smoke, you adjust your aim, aiming for the next "+(t.gen.nextBoolean() ? "shadow" : "apparition")+", and fire a trio of bullets into its core, turning it into a swirling cloud of smoke.\n\n\n\n\tThe last shadow attempts to disappear, to catch you from behind, but you fire, and hit it precisely in its center of mass.\n\n\n\tAs it dissolves into swirling smoke, you turn to face the House of Shadows.");
break;
case targetingMinigame.output.BULLSEYE:
t.say(title, "You level your "+t.user.weapon+" at the "+(t.gen.nextBoolean() ? "leading" : "nearest")+" "+(t.gen.nextBoolean() ? "shadow" : "figure")+", and squeeze the trigger, sending a hail of bullets flying directly towards it, striking it perfectly between the two glowing spots that pass for eyes.\n\n\tAs it disappears into swirling smoke, you let off the trigger, and adjust your aim, ready to eliminate the second one.\n\n\n\n\tJust as it begins to approach you, you fire again, and a trio of bullets score a perfect hit on your target.\n\n\n\tIt disappears into smoke, and you aim directly at the last target.\n\n\tIt attempts to flee, but you don\'t allow it the chance: You "+(t.gen.nextBoolean() ? "squeeze" : "pull")+" the trigger, sending a single round into the "+(t.gen.nextBoolean() ? "shadow" : "figure")+", hitting its forehead dead-center, and converting it into a swirling cloud of smoke.\n\n\n\n\tYou turn to face the House of Shadows.");
break;
default:
t.say("A "+t.user.weapon+" to a shadowfight", "You manage to defeat the shadows.");
}
}
}
else
{
t.user.dead=(res.distance/(.6*targetingMinigame.output.MAX_DISTANCE))<((.5*(t.gen.nextDouble()+t.config.difficultyMult))+.5);
if (t.user.dead)
{
switch (res.type)
{
case targetingMinigame.output.MISSED:
t.say(title, "You aim at the leading "+(t.gen.nextBoolean() ? "figure" : "shadow")+", and fire.\n\n\tYou miss.\n\tBadly.\n\n\t"+(t.config.triggerEgg(.5) ? ("Years from now, after the Fall of the Shadows, and after another explorer, perhaps even one called "+t.user+", has liberated the Great Familiar City, a small "+(t.gen.nextBoolean() ? "boy, and his" : "girl, and her")+" "+(t.gen.nextBoolean() ? "mother" : (t.config.triggerEgg(.2) ? "Big Daddy" : "father"))+" will come across the spot where you faced the shadows, and they will take all they find, your "+t.user.weapon+", home as a souvenir.") : (t.user.weapon.characteristicSet(Cweapon.BOLT_FIRE) ? "Before you can cycle the action, they are upon you." : "They take the chance to consume you.")));
break;
case targetingMinigame.output.GRAZED:
t.say(title, "You level your "+t.user.weapon+" at the lead "+(t.gen.nextBoolean() ? "shadow" : "figure")+", and squeeze the trigger.\n\n\n\tA single round flies into the side of it, and it vanishes from the slightest impact.\n\n\tIt would appear that the slightest impact will eliminate a shadow.\n\n\n\n\tYou level your weapon at the second shadow, but you have just enough time to notice that the third has disappeared from your sight when it appears behind you, and ends you.");
break;
case targetingMinigame.output.POOR:
t.say(title, "You place the sights of your "+t.user.weapon+" at the leading "+(t.gen.nextBoolean() ? "apparition" : "shadow")+", and pull the trigger.\n\n\n\tAlmost as if by instinct, you find that you're adjusting your aim to fire at the second "+(t.gen.nextBoolean() ? "shadow" : "figure")+".\n\n\n\tAlas, your instinct is not as skilled as your hand, and your shot flies wide.\n\n\n\n\tYou try to readjust your aim, but the "+(t.gen.nextBoolean() ? "shadows" : "figures")+" are too fast.");
break;
case targetingMinigame.output.HIT:
t.say(title, "You aim towards the leading shadow, and pull the trigger, sending a single round flying into it.\n\n\tThe shot scores a solid hit, and turns the "+(t.gen.nextBoolean() ? "shadow" : "figure")+" into a swirling cloud of smoke.\n\n\tWithout pausing to watch it, you adjust your aim, leveling your "+t.user.weapon+" at your second opponent.\n\n\tYou fire a shot, and barely nick it, turning it into smoke.\n\n\tThe last "+(t.gen.nextBoolean() ? "shadow" : "apparition")+" seems to have disappeared.\n\n\tYou look left..\n\t..and right..\n\n\n\n\t...left...\n\t...and right...\n\n\n\tCautiously, you turn to face the House of Shadows, only to find it in mid-air, flying directly towards you.");
break;
case targetingMinigame.output.GOOD:
t.say(title, "You direct your "+t.user.weapon+" at the "+(t.gen.nextBoolean() ? "lead" : "first")+" "+(t.gen.nextBoolean() ? "shadow" : "figure")+", and pull the trigger.\n\n\n\tA single round flies towards it, striking it right in the chest.\n\n\n\tAs it disappears into swirling smoke, you twist to aim at the second.\n\n\tJust as it lines up with your sight, you squeeze the trigger, and a "+(t.gen.nextBoolean() ? "single" : "solitary")+" round flies straight and true, "+(t.gen.nextBoolean() ? "hitting" : "striking")+" it right where its heart should be, and turning it to a swirling cloud of smoke.\n\n\n\tYou aim at the third, firing another round, but the "+(t.gen.nextBoolean() ? "shadow" : "apparition")+" manages to "+(t.gen.nextBoolean() ? "dodge" : "evade")+" your shot.\n\n\t"+(t.user.weapon.characteristicSet(Cweapon.ONE_ROUND_MAGAZINE) ? "Before you can switch magazines, " : "Before you can get off another round, ")+"it is upon you.");
break;
case targetingMinigame.output.CRITICAL:
t.say(title, "You aim your "+t.user.weapon+" at the "+(t.gen.nextBoolean() ? "leading" : "primary")+" "+(t.gen.nextBoolean() ? "shadow" : "apparition")+", and fire.\n\n\n\tYour aim was true, and your round flies directly into its head, turning it into swirling smoke.\n\n\n\tThe second shadow "+(t.gen.nextBoolean() ? "tries" : "attempts")+" to "+(t.gen.nextBoolean() ? "dodge" : "evade")+" your shot, but you are too skilled a "+(t.gen.nextBoolean() ? "gunslinger" : "sharpshooter")+", and it vanishes into swirling smoke.\n\n\n\tYou turn yor attention to the third.\n\n\n\n\n\tIt seems to have disappeared.\n\n\tYou look left...\n\t...and right...\n\n\n\n\t...left...\n\t...and right...\n\n\n\n\n\t...Suddenly, its in front of you!\n\n\n\n\t"+(t.user.weapon.characteristicSet(Cweapon.CLOSE_RANGE) ? "You jump away, bringing your "+t.user.weapon+" to bear.\n\n\n\n\tYou manage to get off a shot just as it is upon you, turning the "+(t.gen.nextBoolean() ? "shadow" : "apparition")+" into swirling smoke, just as your life is prematurely ended by it.\n\n\n\n\t" : "You try to get off a shot with your "+t.user.weapon+", but you find that it is too cumbersome to be used effectively at close range, and the shadow consumes you.\n\n\t")+t.capitalize(t.user.gold.toString())+" and your "+t.user.weapon+" clatter to the ground."+(t.config.triggerEgg(.4) ? "\n\n\n\tSomeday, years after the Great Shadow War, and after the Great Familiar City has been conquered by the Army of the Second Coming, a Little Sister of the Rapture, along with her Big Daddy, will come across the remnants of the Pits, and all they will find of you is "+t.user.gold+" and your "+t.user.weapon+"." : "Somewhere in the distance, another adventurer approaches the Pits."));
break;
case targetingMinigame.output.BULLSEYE:
t.user.dead=false;
t.say(title+" against the odds", "You level your "+t.user.weapon+" at the shadows.\n\n\n\n\tDespite the impossibility of the odds, you ready yourself to fight.\n\n\n\tIn quick succession, you fire a round at each shadow, adjusting your aim without pausing to see if your aim is true, hitting each shadow right where the bright spots that pass for their eyes are.\n\n\n\n\tDespite the impossibility of how outmatched you are by the shadows, you have emerged victorious.");
break;
default:
t.say("Absorbed", "Your aim is out of this world!\n\n\n\tNo, seriously, that shot was... I don't even know.\n\n\n\tLet\'s just say this...");
}
}
else
{
switch (res.type)
{
case targetingMinigame.output.MISSED:
t.say(title, "You fire one round at the "+(t.gen.nextBoolean() ? "nearest" : "leading")+" "+(t.gen.nextBoolean() ? "shadow" : "figure")+".\n\n\n\n\tYou miss."+(t.user.weapon.characteristicSet(Cweapon.ONE_ROUND_MAGAZINE) ? "You opt to forgo loading another shot, instead using your "+t.user.weapon+" as if it were a club." : "You aim again, and once more, you miss.\n\n\n\tThis process repeats itself over and over, until the "+(t.gen.nextBoolean() ? "shadows" : "apparitions")+" cease to worry about your shots, and instead process to laugh at you and your "+t.user.weapon+".\n\n\tAt that point, you decide it is better used as a club.")+"\n\n\n\tYou rush the shadows, striking one, and then proceeding to fight the others.\n\n\n\tMiraculously, it works.\n\n\n\tAs the "+(t.gen.nextBoolean() ? "last" : "final")+" "+(t.gen.nextBoolean() ? "shadow" : "figure")+" turns into swirling smoke, a voice, a great and majestic voice, echoes through the Pits:\n\n\n\n\t\tLearn to aim!!\n\t\tThat was awful!\n\t\tGo to the shooting range or something.\n\t\tNow!!\n\n\tIgnoring the voice, shaking off the fright, you turn to face the House of Shadows.");
break;
case targetingMinigame.output.GRAZED:
t.say(title, "You level your "+t.user.weapon+" at the nearest "+(t.gen.nextBoolean() ? "shadow" : "figure")+", and squeeze the trigger.\n\n\tThe round flies straight and true, flying towards its target.\n\tThe "+(t.gen.nextBoolean() ? "shadow" : "apparition")+", as if it had sensed that you were shooting at it, "+(t.gen.nextBoolean() ? "dodging" : "evading")+" the shot.\n\n\tUnfortunately, at least for it, the round barely grazes it.\n\n\n\n\tApparently, even such a small impact is plenty to end it, turning it into a swirling cloud of smoke.\n\n\n\tThe second pauses, if only for a split second, and you take the opportunity to aim at the second one.\n\n\tYour shot is imperfect, and the "+(t.gen.nextBoolean() ? "shadow" : "apparition")+" manages to "+(t.gen.nextBoolean() ? "evade" : "dodge")+" it.\n\n\n\tSwearing quietly, you "+(t.user.weapon.characteristicSet(Cweapon.BOLT_FIRE) ? "cycle the bolt on your "+t.user.weapon : "adjust your aim")+", firing again just in time to hit the second before it gets close.\n\n\n\n\tWithout pausing to watch it disappear into a cloud of smoke, you roll to the side, evading the lunge of the last "+(t.gen.nextBoolean() ? "shadow" : "figure")+".\n\n\tYou manage to bring your "+t.user.weapon+" to bear, and fire a single shot, managing to end it.\n\n\n\tShaking off your close encounter, you turn to face the House of Shadows.");
break;
case targetingMinigame.output.POOR:
t.say(title, "You aim your "+t.user.weapon+" directly at the leading "+(t.gen.nextBoolean() ? "shadow" : "figure")+", and fire.\n\n\n\tThe round flies at its target, hitting it off center, and turning it into a swirling cloud of smoke, as you adjust your aim to hit the second enemy.\n\n\n\tThe second "+(t.gen.nextBoolean() ? "figure" : "shadow")+" faces you as you "+(t.user.weapon.characteristicSet(Cweapon.BOLT_FIRE) ? "cycle the bolt on your"+t.user.weapon : "steady your aim")+", approaching as you do.\n\n\t"+(t.gen.nextBoolean() ? "Luckily" : "Fortunately")+", you\'re able to get off the shot before it gets close.\n\n\tThe round hits the "+(t.gen.nextBoolean() ? "shadow" : "apparition")+", barely, turning it into a swirling cloud of smoke.\n\n\tThe final shadow turns to flee, as you level your "+t.user.weapon+" directly at it.\n\n\n\tYou fire before it gets out of range or into cover, and the final shadow disappears into swirling smoke.\n\n\n\n\n\tSatisfied with your victory, you turn to face the House of Shadows.");
break;
case targetingMinigame.output.HIT:
t.say(title, "You ready yourself, aiming directly at the closest "+(t.gen.nextBoolean() ? "shadow" : "apparition")+".\n\n\n\tYou quickly fire a shot, fully aware of the threat of the two remaining shadows, and watch only for a moment as the round flies through the air, and hits its mark.\n\n\n\tThe "+(t.gen.nextBoolean() ? "shadow" : "figure")+" turns into a swirling cloud of smoke, and you swing your "+t.user.weapon+" to fire at its lieutenant.\n\n\n\tYour enemy advances towards you, and you calmly "+(t.gen.nextBoolean() ? "squeeze" : "pull")+" the trigger.\n\n\n\tYour aim was near-perfect, but the "+(t.gen.nextBoolean() ? "figure" : "shadow")+" sees it coming, and moves to "+(t.gen.nextBoolean() ? "evade" : "dodge")+" it.\n\n\tThe shadow is not quite quick enough, and the round strikes it, turning it to smoke.\n\n\n\tThe final shadow seems to have disappeared, but you see a hint of motion in the corner of your eye, and, almost as if by instinct, turn to face it.\n\n\n\n\n\n\tThe shadow is charging at you, doing its best to end you and defend the House of Shadows, but you are too quick for it, deftly pulling the trigger, and turning the shadow into a cloud of smoke.\n\n\n\tAfter contently watching it swirl away, you turn to face the House of Shadows.");
break;
case targetingMinigame.output.GOOD:
t.say(title, "You quickly survey the field before you, and the three shadows that are before you.\n\n\n\tYou adjust your aim, leveling your "+t.user.weapon+" at the "+(t.gen.nextBoolean() ? "nearest" : "leading")+" "+(t.gen.nextBoolean() ? "apparition" : "shadow")+", prepared to fire.\n\n\n\tAs the "+(t.gen.nextBoolean() ? "figures" : "shadows")+" begin to approach you, you grin ever-so-slightly, and "+(t.gen.nextBoolean() ? "squeeze" : "pull")+" the trigger.\n\n\n\tThe round glides smoothly towards its target, impacting it, and converting it into a swirling cloud of smoke.\n\n\n\tYou turn slightly, ready to fire at the next enemy, and "+(t.gen.nextBoolean() ? "adjust" : "calibrate")+" your aim.\n\n\n\n\tWhen your sights are in place, you fire, and turn the second "+(t.gen.nextBoolean() ? "enemy" : "apparition")+" into swirling smoke.\n\n\n\n\tYou frown slightly.\n\n\tYou could have sworn there where three, yet an empty battlefield and two kills seems to sugest otherwise.\n\n\n\tYou cautiously survey the area, then slowly start to move towards the House of Shadows.\n\n\n\tSuddenly, you see a dark smudge on the edge of your vision, and you turn to grab a better look.\n\n\n\tThe "+(t.gen.nextBoolean() ? "shadow" : "apparition")+", seeing that you found it, charges, as if it was hoping to eliminate you before you can do the same to it, but you fire, and it vanishes, replaced only by smoke.");
break;
case targetingMinigame.output.CRITICAL:
t.say(title, "You stare down the three approaching "+(t.gen.nextBoolean() ? "shadows" : "figures")+", sizing up your opposition.\n\n\n\tThe moment they move to attack, you start to fire, cleanly eliminating your leading "+(t.gen.nextBoolean() ? "target" : "enemy")+", and adjust your aim, targeting the second.\n\n\tIt makes an attempt to flee, but you fire, hitting it in what passes as its head.\n\n\n\tThe last shadow attempts to dodge your line of sight, but you follow it, and eliminate it too.\n\n\n\n\n\tYou pause for only a second to watch the trio disappear into swirling smoke as it diffuses, then turn towards the House of Shadows.");
break;
case targetingMinigame.output.BULLSEYE:
t.say(title, "You effortlessly fire a perfect shot at the "+(t.gen.nextBoolean() ? "nearest" : "leading")+"shadow, a single blast from your"+t.user.weapon+" turning it to smoke.\n\n\tThe remaining shadows hesitate, and thus, you get in a shot at the second "+(t.gen.nextBoolean() ? "figure" : "shadow")+", turning it as well into a swirling cloud of smoke.\n\n\n\tThe last one attempts to flee, but you allow it no such luxury.\n\n\n\n\tWith all three shadows dispatched, you turn to face the House of Shadows.");
break;
default:
t.say("The brightness of a "+t.user.weapon, "In a long and drawn-out engagement, you and your "+t.user.weapon+" outshine the darkness of the shadows.\n\n\n\tFeeling invincible, you turn to face the House of Shadows.");
}
}
}
}
};
break;
case Cweapon.TYPE_NUCLEAR:
t.user.dead=true;
r=new Runnable()
{
@Override
public void run()
{
t.say("A"+(t.gen.nextBoolean() ? " second" : "nother")+" sun", "You hit the detonator on your "+t.user.weapon+".\n\n\n\tA second fireball appears on the horizon, as the people stand in a familiar landscape, and watch you disappear.\n\n\n\tBehind them, the deadly, sickly glow illuminates a terrifying figure.");
}
};
break;
case Cweapon.TYPE_FUTURE:
r=new Runnable()
{
@Override
public void run()
{
if (t.user.weapon.characteristicSet(Cweapon.CLOSE_RANGE_ONLY)) // CLOSE_RANGE_ONLY is the identifying flag for future weapons. If it's set, we're dealing with a lightsaber. Else, we (probably) have a raygun. These two get different dialogue.
t.say("Sword of light", "You charge the "+(t.gen.nextBoolean() ? "figures" : "shadows")+", holding your "+t.user.weapon+" up on high.\n\n\n\tThe leading shadow, seemingly feeling courageous, steps toward you, but you counter its approach, dissolving it.\n\n\n\tThe other two "+(t.gen.nextBoolean() ? "shadows" : "apparitions")+" step away, deterred slightly by your charge, but not far enough.\n\n\n\n\n\tA lunge and a quick extension of the arm is enough to turn the shadow to ash almost akin to a hallucination.\n\n\tThe third shadow begins full flight, perhaps attempting to survive, perhaps attempting to draw you away from the House of Shadows.\n\tTo you, it doesn't matter: You chase it down, and eliminate it.\n\n\n\n\tHaving won a simple victory, you grin, and move towards the House of Shadows.");
else
t.say("The "+t.capitalize(t.user.weapon.name), "You aim your "+t.user.weapon+" directly at the leading "+t.user.weapon+", and pull the trigger.\n\n\n\tThe bolt of brilliant energy glides to its target, and hits it squarely.\n\n\n\tIt disappears into a mere wisp of smoke, leaving not a mere grain of ash.\n\n\n\n\tThe second and third shadows each seem afraid of you, and your "+t.user.weapon+", but you pay them no attention.\n\n\tYou place your sights in between the bright spots on the second "+(t.gen.nextBoolean() ? "apparition" : "figure")+", and pull the trigger.\n\n\n\tIt attempts to maneuver out of the way, but the bolt strikes it nonetheless, and it disappears as if it were never there.\n\n\n\tThe third turns to "+(t.gen.nextBoolean() ? "escape" : "run away")+", but your bolt outruns it by a factor of several million, and disintegrates it.\n\n\n\n\n\t"+(t.gen.nextBoolean() ? "Victorious" : "Feeling invincible")+", you turn towards the House of Shadows.");
}
};
break;
default:
t.user.dead=true;
r=new Runnable()
{
@Override
public void run()
{
t.say("Unknowable", "You suddenly find yourself unable to "+(t.gen.nextBoolean() ? "use" : (t.gen.nextBoolean() ? "grip" : "hold"))+" your "+t.user.weapon+".");
}
};
}
t.th=new Thread(r);
t.th.start();
t.snooze(25); // We need a bit longer to insure processing finishes.
if (t.user.dead && !undead)
prepContinueButton();
else
prepContinueButton(new OnClickListener()
{
@Override
public void onClick(View v)
{
t.th.interrupt();
t.th=new Thread(new Runnable()
{
@Override
public void run()
{
runPits(number, (byte)4, input, input2, hasAssaultedHQ);
}
});
t.th.start();
}
});
}
break;
case 1:
t.th.interrupt();
Runnable r1;
if (t.config.triggerEgg(.05))
{
t.user.dead=false;
r1=new Runnable()
{
@Override
public void run()
{
t.say("Impossible", "You face the "+(t.gen.nextBoolean() ? "shadows" : "figures")+" for only a split second before turning, and sprinting for the House of Shadows.\n\n\tYou "+(t.gen.nextBoolean() ? "grab" : "snatch")+" the detonator from its resting place, glancing only for an instant at the cratering charge it controls.\n\n\n\n\tClosely followed by the shadows, you grimace, hoping your distance from the charge is sufficient.\n\n\n\n\n\n\tYou hit the detonator, and the charge goes off, destroying the House and the shadows with it.\n\n\tThe three shadows that had assaulted you are not alone in disappearing, as an invisible wave passes over the pits, turning each shadow it finds into swirling smoke.\n\n\tUnfortunately, you were not quite far enough from the charge, and it throws you up and away, towards the center of the Pits.\n\n\n\n\n\n\n\tIn the mere seconds of flight you get, you resign yourself to your fate of dying, and of never finding out what exists beyond the image of the familiar landscape.\n\n\tAs soon as you do, as if it had been waiting, a strange force slows you and gently redirects your path.\n\n\tYou land, safe but not intact, in the center of "+(t.gen.nextBoolean() ? "Hell." : "the Pits."));
}
};
}
else
{
t.user.dead=true;
r1=new Runnable()
{
@Override
public void run()
{
t.say("Foolhardy", "You quickly turn and sprint towards the House of Shadows.\n\n\n\tUnfortunately, the "+(t.gen.nextBoolean() ? "apparitions" : "shadows")+" sense your advance, and absorb you.");
}
};
}
t.th.interrupt();
t.th=new Thread(r1);
t.th.start();
if (t.user.dead)
prepContinueButton();
else
{
prepContinueButton(new View.OnClickListener()
{
@Override
public void onClick(View v)
{
t.th.interrupt();
t.th=new Thread(new Runnable()
{
@Override
public void run()
{
runPits((byte)0, stage, input, input2, true);
}
});
t.th.start();
}
});
}
break;
case 2:
t.user.dead=true;
t.th.interrupt();
t.th=new Thread(new Runnable()
{
@Override
public void run()
{
t.say("Outdone", "You attempt to flee from the shadows. They give chase, herding you using their superior numbers.\n\n\tJust when you think you\'ve lost them, you trip on a well, or poorly, placed rock, and tumble down a hill.\n\n\n\n\tWhen you stop, you look at a black sky, only to realize that you\'re staring at a shadow.");
}
});
t.th.start();
prepContinueButton();
break;
default:
dataError();
}
break;
case 1:
switch (input2)
{
case 0:
if (t.user.weapon.type==Cweapon.TYPE_ARCHERY && .65>(t.config.difficultyMult*.75*t.user.weapon.getAbsoluteStrength()))
{
archeryMinigame((int)Math.ceil(t.gen.nextInt(40)+(t.config.difficultyMult*10)+5), ((20*(1-t.config.difficultyMult))+5)/5);
t.th=new Thread(new Runnable()
{
@Override
public void run()
{
if (t.user.dead)
{
String title;
switch (t.gen.nextInt(3))
{
case 0:
title="Archer";
break;
case 1:
title="Bowman";
break;
case 2:
title="Shoplifter";
break;
default:
title="Outdone by the dark";
}
if (t.user.weapon.characteristicSet(Cweapon.SLOW_RELOAD)) // Crossbow
t.say(title, "You "+(t.gen.nextBoolean() ? "bring" : "swing")+" your "+t.user.weapon+" to bear, and fire it at your target.\n\n\tThe bolt flies straight and true, towards a point just slightly away from the "+(t.gen.nextBoolean() ? "shadow" : "being")+".\n\n\tYou quickly "+(t.gen.nextBoolean() ? "grab" : "snatch")+" another bolt, trying your best to load your weapon.\n\n\tJust when you\'re ready, you look up to find a pair of glowing eyes staring into your soul.");
else
t.say(title, "You immediately draw an arrow, bringing it to bear against your foe.\n\n\tUnfortunately, you miss.\n\tYou quickly "+(t.gen.nextBoolean() ? "draw" : "grab")+" another "+(t.gen.nextBoolean() ? "arrow" : "shot")+", and barely manage to draw your "+t.user.weapon+" before the "+(t.gen.nextBoolean() ? "shadow " : "figure ")+(t.gen.nextBoolean() ? "absorbs" : "ends")+" you.");
}
else
t.say(t.gen.nextBoolean() ? "Shopkeeper" : "Veteran", "Your "+(t.gen.nextBoolean() ? "enemy" : "foe")+" charges at you, swaying to "+(t.gen.nextBoolean() ? "evade" : "avoid")+" your line of fire.\n\n\tUnfortunately, for it, you manage to follow its movements, and thusly "+(t.gen.nextBoolean() ? "end" : "kill")+" it, turning it into swirling smoke. You turn your gaze towards the now-cleared shop.");
}
});
t.th.start();
if (t.user.dead)
prepContinueButton();
else
prepContinueButton(new OnClickListener()
{
@Override
public void onClick(View v)
{
t.th=new Thread(new Runnable()
{
@Override
public void run()
{
runPits(number, (byte)4, input, input2, hasAssaultedHQ);
}
});
t.th.start();
}
});
}
else
{
boolean undead=false;
switch (t.user.weapon.type)
{
case Cweapon.TYPE_SHARP:
t.determineUserDeath((1-t.user.weapon.getNeededFlags(Cweapon.CLOSE_RANGE|Cweapon.LIGHT, 2))*.99);
r=new Runnable()
{
@Override
public void run()
{
if (t.user.dead)
{
if (t.gen.nextBoolean())
t.say("You swing your "+(t.gen.nextBoolean() ? "blade" : t.user.weapon)+", catching the "+(t.gen.nextBoolean() ? "shadow" : "figure")+" off guard."+t.multiplyString('\n', t.gen.nextInt(5)+2)+"\tUnfortunately, it manages to dance its way out of the way, and it ends you.");
else
t.say(t.gen.nextBoolean() ? "Newcomer" : "Novice", "You bring your "+t.user.weapon+" to bear, fumbling only slightly, then beginning to "+(t.gen.nextBoolean() ? "slash" : "stab")+" at the "+(t.gen.nextBoolean() ? "shadow" : "figure")+", but it evades you at every thrust."+t.multiplyString('\n', t.gen.nextInt(4)+2)+"\tFinally, after a number of mistakes, it outmaneuvers you."+t.multiplyString('\n', t.gen.nextInt(5)+2)+"\tThe last thought in your head before your "+(t.gen.nextBoolean() ? "time" : "existence")+" is ended, "+((t.config.litEggs && t.config.triggerEgg(.8)) ? ("if you had been allowed to give an utterance to the thoughts that were inspiring you, and they were prophetic, they would have been these:"+t.multiplyString('\n', 2+t.gen.nextInt(3))+"\t\t\"I see a great evil fall across a skyline, a city I thought I used to know.\n\t\t\"I see a man, old, bearded, watching in disappointment as the blots form on my name. I see him, foremost of judges and honored men, bringing another, all too much like me, to this place - Then fair to look upon, without a trace of this day\'s disfigurement - and I hear him tell my replacement my story, with a disappointed and somber voice.\n\t\t\"It is a far, far, sorrier thing that I do, than I have ever done; it is a far, far more dismaying rest that I go to than I have ever known.\""+t.multiplyString('\n', t.gen.nextInt(4)+2)+"\tUnfortunately for your memory, you failed to realize that this was not, in fact, \"A Tale of Two Shadows\".") /* Note that adding some gender-specific pronouns to that might not be the worst idea. */ : "is one of sadness: Sadness that you were never able to properly use your "+t.user.weapon+" well enough to defeat the Shadow in the Pits."));
}
else
t.say(t.gen.nextBoolean() ? "Swordsman" : "Sword master", "You swing your sword as fast as humanly possible, turning one, then two, "+(t.gen.nextBoolean() ? "shadows" : "figures")+" into swirling smoke.\n\n\tThe last shadow charges toward you, but your sword nicks it, and it disapears.\n\n\tA booming voice, almost like Gandalf\'s, echoes from the clouds:\n\n\t\tWhy do you still carry that puny "+t.user.weapon+"??\n\t\tFind a new weapon.\n\t\tNow.\n\n\n\n\n\tYou turn your attention away from the voice, and to the House of Shadows.");
}
};
break;
case Cweapon.TYPE_ARCHERY:
t.determineUserDeath(.75*t.user.weapon.getAbsoluteStrength());
r=new Runnable()
{
@Override
public void run()
{
if (t.user.dead)
{
String title;
switch (t.gen.nextInt(4))
{
case 0:
title="Archer";
break;
case 1:
title="Bowman";
break;
case 2:
title="Outnumbered";
break;
default:
title="Outdone by the dark";
}
switch (t.gen.nextInt(3))
{
case 0:
t.say(title, "You turn to face the shadows, but they easily defeat you before you get off a single shot.");
break;
case 1:
t.say(title, "You spin to face your enemy, and fire a single "+("crossbow".equalsIgnoreCase(t.user.weapon.name) ? "bolt" : "arrow")+" at the leading "+(t.gen.nextBoolean() ? "shadow" : "apparition")+".\n\n\tYour aim "+(t.gen.nextBoolean() ? "is true" : (t.gen.nextBoolean() ? "is that of a master" : "is masterful"))+", turning the leader of the trio into a swirl of smoke.\n\n\tHowever, before you can ready yourself again, the other two elminate you.");
break;
case 2:
t.say(title, "You load one "+("crossbow".equalsIgnoreCase(t.user.weapon.name) ? "bolt" : "arrow")+", and thoughtlessly fire it at the lead "+(t.gen.nextBoolean() ? "shadow" : "figure")+".\n\n\tYou\'ve practiced your archery considerably, and the shot flies directly into its target.\n\n\tYou ignore the sight as your opponent disappears into a swirling cloud of shadowy smoke, and dodge the advance of your second adversary, which you shoot shortly afterwards.\n\n\n\tAlas, you lost track of the third shadow, which comes from behind you, and kills you.");
break;
default:
Log.wtf("Cgame at the House of Shadows", "Invalid output from Random.nextInt()");
}
}
else
t.say((t.config.GoTEggs && t.config.triggerEgg(.8)) ? "Lightbringer" : "Defeater of Shadows", "You turn, snappily aiming your "+t.user.weapon+" directly at the leading "+(t.gen.nextBoolean() ? "shadow" : "apparition")+", and shooting it.\n\n\tPaying it no attention as it disappears into swirling smoke.\n\n\tInstead, as if by instinct, you roll towards the House of Shadows."+(t.gen.nextBoolean() ? "" : "\n\n\tYou quickly recover from the pain of your miscalculation after you slam into the outer wall.")+"\n\n\tWithout taking the time to stand, you adjust your aim, directly at the second enemy.\n\n\tQuickly, you release your shot, sending "+("crossbow".equalsIgnoreCase(t.user.weapon.name) ? "a bolt" : "an arrow")+" flying into the second shape, then clattering to the ground as your opponent swirls away.\n\n\n\tThe third charges, but you pull one "+("crossbow".equalsIgnoreCase(t.user.weapon.name) ? "bolt" : "arrow")+" from your reserves, and drive it through your final adversary, noting the lack of resistance as it goes through.\n\n\tYou watch the remmains of your opponent swirl away, and note your two fired shots have vanished.");
}
};
break;
case Cweapon.TYPE_MODERN:
final targetingMinigame.output res=aimMinigame();
undead=(res.type==targetingMinigame.output.BULLSEYE);
final String title=res.toString();
r=new Runnable()
{
@Override
public void run()
{
if (t.user.weapon.characteristicSet(Cweapon.AUTOMATIC))
{
t.user.dead=(res.distance/(.8*targetingMinigame.output.MAX_DISTANCE))<((.5*(t.gen.nextDouble()+t.config.difficultyMult))+.5);
if (t.user.dead)
{
switch (res.type)
{
case targetingMinigame.output.MISSED:
t.say(title, "You fire a burst of bullets towards the shadows, but your aim is off, and the "+(t.gen.nextBoolean() ? "shadows" : "figures")+" end you.");
break;
case targetingMinigame.output.GRAZED:
t.say(title, "You turn at the shadows, and fire a burst of automatic fire. One shot hits the nearest "+(t.gen.nextBoolean() ? "shadow" : "vision")+", turning it to a swirl of smoke, but the remaining two intercept you.");
break;
case targetingMinigame.output.POOR:
t.say(title, "You fire at the shadows, grazing one, turning it to swirling smoke, and barely hitting another.\n\n\tThe last consumes you as the second disappears.");
break;
case targetingMinigame.output.HIT:
t.say(title, "You fire at the shadows, hitting one with a solid shot, and "+(t.gen.nextBoolean() ? "turning" : "converting")+" it into a swirling cloud.\n\n\tAnother bullet strikes the second, eliminating it as well, but "+(t.user.weapon.characteristicSet(Cweapon.HIGH_RECOIL) ? "the recoil of your "+t.user.weapon+" throws off your aim." : "the last shadow moves out of your sights too quickly."));
break;
case targetingMinigame.output.GOOD:
t.say(title, "You hit two shadows with near perfect shots.\n\n\tThe shadows disappear into swirling smoke, as the third approaches you.\n\n\n\n\n\tYou quickly twist, aiming directly at the last shadow.\n\n\n\n\n\n\tYou pull the trigger, just as it reaches you."+(t.config.triggerEgg(.5) ? "\n\n\n\tThe shadow of a dragon looms over the pits, the rush of air stirring everything around, as you both become swirling smoke, and "+t.user.gold+", along with your "+t.user.weapon+", clatter to the ground." : ""));
break;
case targetingMinigame.output.CRITICAL:
t.say(title, "You hit the first two shadows with perfect shots, but find that the third seems to have disappeared.\n\n\tYou twist and turn, searching for it, "+(t.config.triggerEgg(.75) ? "and feel a thud, and a weight.\n\n\tYou fall, watching the shadow run, and attempt to give chase.\n\n\tSoon, it leaves your sight. Contented, you enter the House of Shadows, grabbing the detonator, assuming that the charge is at it was.\n\n\n\n\tYou walk clear of the House, wondering why you feel as if there is a huge weight on your back.\n\n\n\tYou realize that the shadow planted the charge on your back a moment too late, as you trigger the explosive." : "and soon finding it, right behind you.\n\n\tYou dodge its lunge, dropping your "+t.user.weapon+" in your haste to "+(t.gen.nextBoolean() ? "escape" : "survive")+", and, just as you think you\'ve escaped, you trip, rolling down a hill, coming to a stop in a ditch full of a hundred shadows."));
break;
case targetingMinigame.output.BULLSEYE:
t.user.dead=false;
t.say(title+", despite impossibility", "You fire three utterly perfect shots, cleanly converting two shadows into swirling smoke, and then you fire a hail of bullets into the third, ending it as well.\n\n\tDespite the incredibly difficult odds against you, you have prevailed.");
break;
default:
t.say("Gunshot", "You are easily defeated by the shadows.");
}
}
else
{
switch (res.type)
{
case targetingMinigame.output.MISSED:
t.say(title, "You miss every shot in your magazine, yet manage to kill all three shadows by using your "+t.user.weapon+" as a club.\n\n\n\tFrom the clouds, a booming voice, almost like Gandalf\'s, echoes through the pits:\n\n\t\tGet better aim!!\n\t\tSeriously, go to target practice or something...\n\t\tThat was ridiculous.\n\n\n\n\n\n\tYou shake it off and turn your attention to the House of Shadows.");
break;
case targetingMinigame.output.GRAZED:
t.say(title, "You fire at the enemies, full automatic fire, and yet the shadows keep managing to dodge your fire.\n\n\t"+(t.user.weapon.characteristicSet(Cweapon.HIGH_RECOIL) ? "You suspect that its because your "+t.user.weapon+" has too much recoil.\n\n\t" : "")+"Just as you begin to worry about the need to reload, one bullet grazes the leading shadow.\n\tSomehow, to your surprise, it disappears, turning into swirling smoke.\n\n\n\n\tThe remaining "+(t.gen.nextBoolean() ? "shadows" : "figures")+" mirror your surprise: They pause in shock.\n\n\tYou take advantage of their surprise to fire "+(t.gen.nextBoolean() ? "a trio" : "a hail")+" of "+(t.gen.nextBoolean() ? "rounds" : "bullets")+" at the second "+(t.gen.nextBoolean() ? "figure" : "shadow")+".\n\n\tIt disappears into a swirling cloud of smoke, and you continue firing, now at the last enemy, and barely manage to graze it.\n\n\n\tIgnoring what is now just a cloud of smoke, you turn on the House of Shadows.");
break;
case targetingMinigame.output.POOR:
t.say(title, "You level the sights of your "+t.user.weapon+" directly at the leading "+(t.gen.nextBoolean() ? "shadow" : "figure")+", and fire a "+(t.gen.nextBoolean() ? "hail" : "number")+" of rounds into it.\n\n\n\tIt "+(t.gen.nextBoolean() ? "becomes" : "disappears into")+" a swirling cloud of smoke, as you turn your attention to the second enemy.\n\n\tIt approaches "+(t.gen.nextBoolean() ? "menacingly" : "threateningly")+", but you "+(t.gen.nextBoolean() ? "are able" : "manage")+" to level your sights at it, and you squeeze the trigger, watching the bullets barely hit the "+(t.gen.nextBoolean() ? "shadow" : "figure")+".\n\n\tLuckily, it seems that any hit will "+(t.gen.nextBoolean() ? "dissolve" : "destroy")+" the shadow, and you watch as it disappears into a swirling cloud of smoke.\n\n\n\n\n\tUnfortunately, you seem to have lost track of the third...\n\n\n\n\tYou look left...\n\n\t...and right...\n\n\t...left...\n\n\t...and there it is!\n\n\n\n\tThe last "+(t.gen.nextBoolean() ? "shadow" : "figure")+" "+(t.gen.nextBoolean() ? "shows itself" : "appears")+" immediately just in front of you!\n\n\n\n\n\n\tYou hastily fire your "+t.user.weapon+", and turn it to smoke, barely surviving the encounter.\n\n\tYou shake yourself off, and turn to face the House of Shadows.");
break;
case targetingMinigame.output.HIT:
t.say(title, "You aim your "+t.user.weapon+" directly at the leading enemy, and "+(t.gen.nextBoolean() ? "squeeze" : "pull")+" the trigger.\n\n\tA "+(t.gen.nextBoolean() ? "burst" : "number")+" of rounds fly directly at it, and strike it, turning it into a swirling cloud of smoke.\n\n\tYou quickly turn, and aim at the second "+(t.gen.nextBoolean() ? "shadow" : "figure")+", and manage to send a hail of "+(t.gen.nextBoolean() ? "rounds" : "fire")+" flying directly at it.\n\n\n\tYou pause for a split second to watch as the "+(t.gen.nextBoolean() ? "apparition" : "shadow")+" dissolves into a cloud of smoke.\n\n\tThe final shadow seems to have disappeared.\n\n\t"+(t.gen.nextBoolean() ? "You" : "Your "+t.user.weapon)+" feels light, "+(t.user.weapon.characteristicSet(Cweapon.QUICK_RELOAD) ? "so you quickly switch cartridges." : "but you decide it would take too long to reload it.")+"\n\n\n\n\tYou return your attention to where it probably should be, the rather deadly "+(t.gen.nextBoolean() ? "shadow" : "apparition")+" that could reappear and kill you at any moment.\n\tSuddenly, it reappears: Right in front of you!\n\n\n\n\tYou quickly pull the trigger, firing several shots into the "+(t.gen.nextBoolean() ? "figure" : "shadow")+" before you.\n\n\n\tYou turn to oppose the House of Shadows as it disappears into a swirling cloud of smoke.");
break;
case targetingMinigame.output.GOOD:
t.say(title, "You aim, and fire your "+t.user.weapon+" directly at the "+(t.gen.nextBoolean() ? "nearest" : (t.gen.nextBoolean() ? "closest" : "nearest"))+" "+(t.gen.nextBoolean() ? "shadow" : "figure")+", sending a hail of bullets flying directly at its core.\n\n\n\tThe first round out of your "+(t.gen.nextBoolean() ? "weapon" : t.user.weapon)+" hits it, turning it into a swirling cloud of smoke.\n\n\n\tYou quickly shift your aim, leveling your sights at the next target, and "+(t.gen.nextBoolean() ? "squeeze" : "pull")+" the trigger, scoring a solid hit, and turning the shadow into a swirling cloud of smoke.\n\n\n\tThe third shadow comes around to face you, and dodges your first burst.\n\n\n\tYou quickly adjust your aim, and "+(t.gen.nextBoolean() ? "squeeze" : "pull")+" the trigger, scoring another hit and ending the shadow.\n\n\n\tYou turn to face the House of Shadows as it turns to swirling smoke.");
break;
case targetingMinigame.output.CRITICAL:
t.say(title, "You aim at the leading "+(t.gen.nextBoolean() ? "shadow" : "figure")+", and fire a hail of rounds from your "+t.user.weapon+", scoring an extremely solid shot and dissolving it.\n\n\n\tAs it disappears into smoke, you adjust your aim, aiming for the next "+(t.gen.nextBoolean() ? "shadow" : "apparition")+", and fire a trio of bullets into its core, turning it into a swirling cloud of smoke.\n\n\n\n\tThe last shadow attempts to disappear, to catch you from behind, but you fire, and hit it precisely in its center of mass.\n\n\n\tAs it dissolves into swirling smoke, you turn to face the House of Shadows.");
break;
case targetingMinigame.output.BULLSEYE:
t.say(title, "You level your "+t.user.weapon+" at the "+(t.gen.nextBoolean() ? "leading" : "nearest")+" "+(t.gen.nextBoolean() ? "shadow" : "figure")+", and squeeze the trigger, sending a hail of bullets flying directly towards it, striking it perfectly between the two glowing spots that pass for eyes.\n\n\tAs it disappears into swirling smoke, you let off the trigger, and adjust your aim, ready to eliminate the second one.\n\n\n\n\tJust as it begins to approach you, you fire again, and a trio of bullets score a perfect hit on your target.\n\n\n\tIt disappears into smoke, and you aim directly at the last target.\n\n\tIt attempts to flee, but you don\'t allow it the chance: You "+(t.gen.nextBoolean() ? "squeeze" : "pull")+" the trigger, sending a single round into the "+(t.gen.nextBoolean() ? "shadow" : "figure")+", hitting its forehead dead-center, and converting it into a swirling cloud of smoke.\n\n\n\n\tYou turn to face the House of Shadows.");
break;
default:
t.say("A "+t.user.weapon+" to a shadowfight", "You manage to defeat the shadows.");
}
}
}
else
{
t.user.dead=(res.distance/(.6*targetingMinigame.output.MAX_DISTANCE))<((.5*(t.gen.nextDouble()+t.config.difficultyMult))+.5);
if (t.user.dead)
{
switch (res.type)
{
case targetingMinigame.output.MISSED:
t.say(title, "You aim at the leading "+(t.gen.nextBoolean() ? "figure" : "shadow")+", and fire.\n\n\tYou miss.\n\tBadly.\n\n\t"+(t.config.triggerEgg(.5) ? ("Years from now, after the Fall of the Shadows, and after another explorer, perhaps even one called "+t.user+", has liberated the Great Familiar City, a small "+(t.gen.nextBoolean() ? "boy, and his" : "girl, and her")+" "+(t.gen.nextBoolean() ? "mother" : (t.config.triggerEgg(.2) ? "Big Daddy" : "father"))+" will come across the spot where you faced the shadows, and they will take all they find, your "+t.user.weapon+", home as a souvenir.") : (t.user.weapon.characteristicSet(Cweapon.BOLT_FIRE) ? "Before you can cycle the action, they are upon you." : "They take the chance to consume you.")));
break;
case targetingMinigame.output.GRAZED:
t.say(title, "You level your "+t.user.weapon+" at the lead "+(t.gen.nextBoolean() ? "shadow" : "figure")+", and squeeze the trigger.\n\n\n\tA single round flies into the side of it, and it vanishes from the slightest impact.\n\n\tIt would appear that the slightest impact will eliminate a shadow.\n\n\n\n\tYou level your weapon at the second shadow, but you have just enough time to notice that the third has disappeared from your sight when it appears behind you, and ends you.");
break;
case targetingMinigame.output.POOR:
t.say(title, "You place the sights of your "+t.user.weapon+" at the leading "+(t.gen.nextBoolean() ? "apparition" : "shadow")+", and pull the trigger.\n\n\n\tAlmost as if by instinct, you find that you're adjusting your aim to fire at the second "+(t.gen.nextBoolean() ? "shadow" : "figure")+".\n\n\n\tAlas, your instinct is not as skilled as your hand, and your shot flies wide.\n\n\n\n\tYou try to readjust your aim, but the "+(t.gen.nextBoolean() ? "shadows" : "figures")+" are too fast.");
break;
case targetingMinigame.output.HIT:
t.say(title, "You aim towards the leading shadow, and pull the trigger, sending a single round flying into it.\n\n\tThe shot scores a solid hit, and turns the "+(t.gen.nextBoolean() ? "shadow" : "figure")+" into a swirling cloud of smoke.\n\n\tWithout pausing to watch it, you adjust your aim, leveling your "+t.user.weapon+" at your second opponent.\n\n\tYou fire a shot, and barely nick it, turning it into smoke.\n\n\tThe last "+(t.gen.nextBoolean() ? "shadow" : "apparition")+" seems to have disappeared.\n\n\tYou look left..\n\t..and right..\n\n\n\n\t...left...\n\t...and right...\n\n\n\tCautiously, you turn to face the House of Shadows, only to find it in mid-air, flying directly towards you.");
break;
case targetingMinigame.output.GOOD:
t.say(title, "You direct your "+t.user.weapon+" at the "+(t.gen.nextBoolean() ? "lead" : "first")+" "+(t.gen.nextBoolean() ? "shadow" : "figure")+", and pull the trigger.\n\n\n\tA single round flies towards it, striking it right in the chest.\n\n\n\tAs it disappears into swirling smoke, you twist to aim at the second.\n\n\tJust as it lines up with your sight, you squeeze the trigger, and a "+(t.gen.nextBoolean() ? "single" : "solitary")+" round flies straight and true, "+(t.gen.nextBoolean() ? "hitting" : "striking")+" it right where its heart should be, and turning it to a swirling cloud of smoke.\n\n\n\tYou aim at the third, firing another round, but the "+(t.gen.nextBoolean() ? "shadow" : "apparition")+" manages to "+(t.gen.nextBoolean() ? "dodge" : "evade")+" your shot.\n\n\t"+(t.user.weapon.characteristicSet(Cweapon.ONE_ROUND_MAGAZINE) ? "Before you can switch magazines, " : "Before you can get off another round, ")+"it is upon you.");
break;
case targetingMinigame.output.CRITICAL:
t.say(title, "You aim your "+t.user.weapon+" at the "+(t.gen.nextBoolean() ? "leading" : "primary")+" "+(t.gen.nextBoolean() ? "shadow" : "apparition")+", and fire.\n\n\n\tYour aim was true, and your round flies directly into its head, turning it into swirling smoke.\n\n\n\tThe second shadow "+(t.gen.nextBoolean() ? "tries" : "attempts")+" to "+(t.gen.nextBoolean() ? "dodge" : "evade")+" your shot, but you are too skilled a "+(t.gen.nextBoolean() ? "gunslinger" : "sharpshooter")+", and it vanishes into swirling smoke.\n\n\n\tYou turn yor attention to the third.\n\n\n\n\n\tIt seems to have disappeared.\n\n\tYou look left...\n\t...and right...\n\n\n\n\t...left...\n\t...and right...\n\n\n\n\n\t...Suddenly, its in front of you!\n\n\n\n\t"+(t.user.weapon.characteristicSet(Cweapon.CLOSE_RANGE) ? "You jump away, bringing your "+t.user.weapon+" to bear.\n\n\n\n\tYou manage to get off a shot just as it is upon you, turning the "+(t.gen.nextBoolean() ? "shadow" : "apparition")+" into swirling smoke, just as your life is prematurely ended by it.\n\n\n\n\t" : "You try to get off a shot with your "+t.user.weapon+", but you find that it is too cumbersome to be used effectively at close range, and the shadow consumes you.\n\n\t")+t.capitalize(t.user.gold.toString())+" and your "+t.user.weapon+" clatter to the ground."+(t.config.triggerEgg(.4) ? "\n\n\n\tSomeday, years after the Great Shadow War, and after the Great Familiar City has been conquered by the Army of the Second Coming, a Little Sister of the Rapture, along with her Big Daddy, will come across the remnants of the Pits, and all they will find of you is "+t.user.gold+" and your "+t.user.weapon+"." : "Somewhere in the distance, another adventurer approaches the Pits."));
break;
case targetingMinigame.output.BULLSEYE:
t.user.dead=false;
t.say(title+" against the odds", "You level your "+t.user.weapon+" at the shadows.\n\n\n\n\tDespite the impossibility of the odds, you ready yourself to fight.\n\n\n\tIn quick succession, you fire a round at each shadow, adjusting your aim without pausing to see if your aim is true, hitting each shadow right where the bright spots that pass for their eyes are.\n\n\n\n\tDespite the impossibility of how outmatched you are by the shadows, you have emerged victorious.");
break;
default:
t.say("Absorbed", "Your aim is out of this world!\n\n\n\tNo, seriously, that shot was... I don't even know.\n\n\n\tLet\'s just say this...");
}
}
else
{
switch (res.type)
{
case targetingMinigame.output.MISSED:
t.say(title, "You fire one round at the "+(t.gen.nextBoolean() ? "nearest" : "leading")+" "+(t.gen.nextBoolean() ? "shadow" : "figure")+".\n\n\n\n\tYou miss."+(t.user.weapon.characteristicSet(Cweapon.ONE_ROUND_MAGAZINE) ? "You opt to forgo loading another shot, instead using your "+t.user.weapon+" as if it were a club." : "You aim again, and once more, you miss.\n\n\n\tThis process repeats itself over and over, until the "+(t.gen.nextBoolean() ? "shadows" : "apparitions")+" cease to worry about your shots, and instead process to laugh at you and your "+t.user.weapon+".\n\n\tAt that point, you decide it is better used as a club.")+"\n\n\n\tYou rush the shadows, striking one, and then proceeding to fight the others.\n\n\n\tMiraculously, it works.\n\n\n\tAs the "+(t.gen.nextBoolean() ? "last" : "final")+" "+(t.gen.nextBoolean() ? "shadow" : "figure")+" turns into swirling smoke, a voice, a great and majestic voice, echoes through the Pits:\n\n\n\n\t\tLearn to aim!!\n\t\tThat was awful!\n\t\tGo to the shooting range or something.\n\t\tNow!!\n\n\tIgnoring the voice, shaking off the fright, you turn to face the House of Shadows.");
break;
case targetingMinigame.output.GRAZED:
t.say(title, "You level your "+t.user.weapon+" at the nearest "+(t.gen.nextBoolean() ? "shadow" : "figure")+", and squeeze the trigger.\n\n\tThe round flies straight and true, flying towards its target.\n\tThe "+(t.gen.nextBoolean() ? "shadow" : "apparition")+", as if it had sensed that you were shooting at it, "+(t.gen.nextBoolean() ? "dodging" : "evading")+" the shot.\n\n\tUnfortunately, at least for it, the round barely grazes it.\n\n\n\n\tApparently, even such a small impact is plenty to end it, turning it into a swirling cloud of smoke.\n\n\n\tThe second pauses, if only for a split second, and you take the opportunity to aim at the second one.\n\n\tYour shot is imperfect, and the "+(t.gen.nextBoolean() ? "shadow" : "apparition")+" manages to "+(t.gen.nextBoolean() ? "evade" : "dodge")+" it.\n\n\n\tSwearing quietly, you "+(t.user.weapon.characteristicSet(Cweapon.BOLT_FIRE) ? "cycle the bolt on your "+t.user.weapon : "adjust your aim")+", firing again just in time to hit the second before it gets close.\n\n\n\n\tWithout pausing to watch it disappear into a cloud of smoke, you roll to the side, evading the lunge of the last "+(t.gen.nextBoolean() ? "shadow" : "figure")+".\n\n\tYou manage to bring your "+t.user.weapon+" to bear, and fire a single shot, managing to end it.\n\n\n\tShaking off your close encounter, you turn to face the House of Shadows.");
break;
case targetingMinigame.output.POOR:
t.say(title, "You aim your "+t.user.weapon+" directly at the leading "+(t.gen.nextBoolean() ? "shadow" : "figure")+", and fire.\n\n\n\tThe round flies at its target, hitting it off center, and turning it into a swirling cloud of smoke, as you adjust your aim to hit the second enemy.\n\n\n\tThe second "+(t.gen.nextBoolean() ? "figure" : "shadow")+" faces you as you "+(t.user.weapon.characteristicSet(Cweapon.BOLT_FIRE) ? "cycle the bolt on your"+t.user.weapon : "steady your aim")+", approaching as you do.\n\n\t"+(t.gen.nextBoolean() ? "Luckily" : "Fortunately")+", you\'re able to get off the shot before it gets close.\n\n\tThe round hits the "+(t.gen.nextBoolean() ? "shadow" : "apparition")+", barely, turning it into a swirling cloud of smoke.\n\n\tThe final shadow turns to flee, as you level your "+t.user.weapon+" directly at it.\n\n\n\tYou fire before it gets out of range or into cover, and the final shadow disappears into swirling smoke.\n\n\n\n\n\tSatisfied with your victory, you turn to face the House of Shadows.");
break;
case targetingMinigame.output.HIT:
t.say(title, "You ready yourself, aiming directly at the closest "+(t.gen.nextBoolean() ? "shadow" : "apparition")+".\n\n\n\tYou quickly fire a shot, fully aware of the threat of the two remaining shadows, and watch only for a moment as the round flies through the air, and hits its mark.\n\n\n\tThe "+(t.gen.nextBoolean() ? "shadow" : "figure")+" turns into a swirling cloud of smoke, and you swing your "+t.user.weapon+" to fire at its lieutenant.\n\n\n\tYour enemy advances towards you, and you calmly "+(t.gen.nextBoolean() ? "squeeze" : "pull")+" the trigger.\n\n\n\tYour aim was near-perfect, but the "+(t.gen.nextBoolean() ? "figure" : "shadow")+" sees it coming, and moves to "+(t.gen.nextBoolean() ? "evade" : "dodge")+" it.\n\n\tThe shadow is not quite quick enough, and the round strikes it, turning it to smoke.\n\n\n\tThe final shadow seems to have disappeared, but you see a hint of motion in the corner of your eye, and, almost as if by instinct, turn to face it.\n\n\n\n\n\n\tThe shadow is charging at you, doing its best to end you and defend the House of Shadows, but you are too quick for it, deftly pulling the trigger, and turning the shadow into a cloud of smoke.\n\n\n\tAfter contently watching it swirl away, you turn to face the House of Shadows.");
break;
case targetingMinigame.output.GOOD:
t.say(title, "You quickly survey the field before you, and the three shadows that are before you.\n\n\n\tYou adjust your aim, leveling your "+t.user.weapon+" at the "+(t.gen.nextBoolean() ? "nearest" : "leading")+" "+(t.gen.nextBoolean() ? "apparition" : "shadow")+", prepared to fire.\n\n\n\tAs the "+(t.gen.nextBoolean() ? "figures" : "shadows")+" begin to approach you, you grin ever-so-slightly, and "+(t.gen.nextBoolean() ? "squeeze" : "pull")+" the trigger.\n\n\n\tThe round glides smoothly towards its target, impacting it, and converting it into a swirling cloud of smoke.\n\n\n\tYou turn slightly, ready to fire at the next enemy, and "+(t.gen.nextBoolean() ? "adjust" : "calibrate")+" your aim.\n\n\n\n\tWhen your sights are in place, you fire, and turn the second "+(t.gen.nextBoolean() ? "enemy" : "apparition")+" into swirling smoke.\n\n\n\n\tYou frown slightly.\n\n\tYou could have sworn there where three, yet an empty battlefield and two kills seems to sugest otherwise.\n\n\n\tYou cautiously survey the area, then slowly start to move towards the House of Shadows.\n\n\n\tSuddenly, you see a dark smudge on the edge of your vision, and you turn to grab a better look.\n\n\n\tThe "+(t.gen.nextBoolean() ? "shadow" : "apparition")+", seeing that you found it, charges, as if it was hoping to eliminate you before you can do the same to it, but you fire, and it vanishes, replaced only by smoke.");
break;
case targetingMinigame.output.CRITICAL:
t.say(title, "You stare down the three approaching "+(t.gen.nextBoolean() ? "shadows" : "figures")+", sizing up your opposition.\n\n\n\tThe moment they move to attack, you start to fire, cleanly eliminating your leading "+(t.gen.nextBoolean() ? "target" : "enemy")+", and adjust your aim, targeting the second.\n\n\tIt makes an attempt to flee, but you fire, hitting it in what passes as its head.\n\n\n\tThe last shadow attempts to dodge your line of sight, but you follow it, and eliminate it too.\n\n\n\n\n\tYou pause for only a second to watch the trio disappear into swirling smoke as it diffuses, then turn towards the House of Shadows.");
break;
case targetingMinigame.output.BULLSEYE:
t.say(title, "You effortlessly fire a perfect shot at the "+(t.gen.nextBoolean() ? "nearest" : "leading")+"shadow, a single blast from your"+t.user.weapon+" turning it to smoke.\n\n\tThe remaining shadows hesitate, and thus, you get in a shot at the second "+(t.gen.nextBoolean() ? "figure" : "shadow")+", turning it as well into a swirling cloud of smoke.\n\n\n\tThe last one attempts to flee, but you allow it no such luxury.\n\n\n\n\tWith all three shadows dispatched, you turn to face the House of Shadows.");
break;
default:
t.say("The brightness of a "+t.user.weapon, "In a long and drawn-out engagement, you and your "+t.user.weapon+" outshine the darkness of the shadows.\n\n\n\tFeeling invincible, you turn to face the House of Shadows.");
}
}
}
}
};
break;
case Cweapon.TYPE_NUCLEAR:
t.user.dead=true;
r=new Runnable()
{
@Override
public void run()
{
t.say("A"+(t.gen.nextBoolean() ? " second" : "nother")+" sun", "You hit the detonator on your "+t.user.weapon+".\n\n\n\tA second fireball appears on the horizon, as the people stand in a familiar landscape, and watch you disappear.\n\n\n\tBehind them, the deadly, sickly glow illuminates a terrifying figure.");
}
};
break;
case Cweapon.TYPE_FUTURE:
r=new Runnable()
{
@Override
public void run()
{
if (t.user.weapon.characteristicSet(Cweapon.CLOSE_RANGE_ONLY)) // CLOSE_RANGE_ONLY is the identifying flag for future weapons. If it's set, we're dealing with a lightsaber. Else, we (probably) have a raygun. These two get different dialogue.
t.say("Sword of light", "You charge the "+(t.gen.nextBoolean() ? "figures" : "shadows")+", holding your "+t.user.weapon+" up on high.\n\n\n\tThe leading shadow, seemingly feeling courageous, steps toward you, but you counter its approach, dissolving it.\n\n\n\tThe other two "+(t.gen.nextBoolean() ? "shadows" : "apparitions")+" step away, deterred slightly by your charge, but not far enough.\n\n\n\n\n\tA lunge and a quick extension of the arm is enough to turn the shadow to ash almost akin to a hallucination.\n\n\tThe third shadow begins full flight, perhaps attempting to survive, perhaps attempting to draw you away from the House of Shadows.\n\tTo you, it doesn't matter: You chase it down, and eliminate it.\n\n\n\n\tHaving won a simple victory, you grin, and move towards the House of Shadows.");
else
t.say("The "+t.capitalize(t.user.weapon.name), "You aim your "+t.user.weapon+" directly at the leading "+t.user.weapon+", and pull the trigger.\n\n\n\tThe bolt of brilliant energy glides to its target, and hits it squarely.\n\n\n\tIt disappears into a mere wisp of smoke, leaving not a mere grain of ash.\n\n\n\n\tThe second and third shadows each seem afraid of you, and your "+t.user.weapon+", but you pay them no attention.\n\n\tYou place your sights in between the bright spots on the second "+(t.gen.nextBoolean() ? "apparition" : "figure")+", and pull the trigger.\n\n\n\tIt attempts to maneuver out of the way, but the bolt strikes it nonetheless, and it disappears as if it were never there.\n\n\n\tThe third turns to "+(t.gen.nextBoolean() ? "escape" : "run away")+", but your bolt outruns it by a factor of several million, and disintegrates it.\n\n\n\n\n\t"+(t.gen.nextBoolean() ? "Victorious" : "Feeling invincible")+", you turn towards the House of Shadows.");
}
};
break;
default:
t.user.dead=true;
r=new Runnable()
{
@Override
public void run()
{
t.say("Unknowable", "You suddenly find yourself unable to "+(t.gen.nextBoolean() ? "use" : (t.gen.nextBoolean() ? "grip" : "hold"))+" your "+t.user.weapon+".");
}
};
}
t.th=new Thread(r);
t.th.start();
t.snooze(25); // We need a bit longer to insure processing finishes.
if (t.user.dead && !undead)
prepContinueButton();
else
prepContinueButton(new OnClickListener()
{
@Override
public void onClick(View v)
{
t.th.interrupt();
t.th=new Thread(new Runnable()
{
@Override
public void run()
{
runPits(number, (byte)4, input, input2, hasAssaultedHQ);
}
});
t.th.start();
}
});
}
break;
case 1:
t.th.interrupt();
Runnable r1;
if (t.config.triggerEgg(.05))
{
t.user.dead=false;
r1=new Runnable()
{
@Override
public void run()
{
t.say("Impossible", "You face the "+(t.gen.nextBoolean() ? "shadows" : "figures")+" for only a split second before turning, and sprinting for the House of Shadows.\n\n\tYou "+(t.gen.nextBoolean() ? "grab" : "snatch")+" the detonator from its resting place, glancing only for an instant at the cratering charge it controls.\n\n\n\n\tClosely followed by the shadows, you grimace, hoping your distance from the charge is sufficient.\n\n\n\n\n\n\tYou hit the detonator, and the charge goes off, destroying the House and the shadows with it.\n\n\tThe three shadows that had assaulted you are not alone in disappearing, as an invisible wave passes over the pits, turning each shadow it finds into swirling smoke.\n\n\tUnfortunately, you were not quite far enough from the charge, and it throws you up and away, towards the center of the Pits.\n\n\n\n\n\n\n\tIn the mere seconds of flight you get, you resign yourself to your fate of dying, and of never finding out what exists beyond the image of the familiar landscape.\n\n\tAs soon as you do, as if it had been waiting, a strange force slows you and gently redirects your path.\n\n\tYou land, safe but not intact, in the center of "+(t.gen.nextBoolean() ? "Hell." : "the Pits."));
}
};
}
else
{
t.user.dead=true;
r1=new Runnable()
{
@Override
public void run()
{
t.say("Foolhardy", "You quickly turn and sprint towards the House of Shadows.\n\n\n\tUnfortunately, the "+(t.gen.nextBoolean() ? "apparitions" : "shadows")+" sense your advance, and absorb you.");
}
};
}
t.th.interrupt();
t.th=new Thread(r1);
t.th.start();
if (t.user.dead)
prepContinueButton();
else
{
prepContinueButton(new View.OnClickListener()
{
@Override
public void onClick(View v)
{
t.th.interrupt();
t.th=new Thread(new Runnable()
{
@Override
public void run()
{
runPits((byte)0, stage, input, input2, true);
}
});
t.th.start();
}
});
}
break;
case 2:
t.user.dead=true;
t.th.interrupt();
t.th=new Thread(new Runnable()
{
@Override
public void run()
{
t.say("Outdone", "You attempt to flee from the shadows. They give chase, herding you using their superior numbers.\n\n\tJust when you think you\'ve lost them, you trip on a well, or poorly, placed rock, and tumble down a hill.\n\n\n\n\tWhen you stop, you look at a black sky, only to realize that you\'re staring at a shadow.");
}
});
t.th.start();
prepContinueButton();
break;
default:
dataError();
}
break;
}
break;
}
}
}
public void inputClear()
{
if (doCommitSuicide)
t.user.commitSuicide();
else
{
stage-=2;
runStage();
}
}
public void dataError() // Called when a switch goes to a default case, when this is nonsensical of course.
{
t.user.dead=true;
t.th.interrupt();
t.th=new Thread(new Runnable()
{
@Override
public void run()
{
t.say(t.gen.nextBoolean() ? "Unknowable" : "Legend", "A vortex of Infinite Improbability opens, and consumes you.\n\n\n\n\n\n");
t.snooze(750+t.gen.nextInt(500));
Cgame.unSignalGameContinue();
t.snooze(2500);
t.sayWhat("That means you have a bug.\n\n");
Cgame.unSignalGameContinue();
t.snooze(1500);
t.sayWhat("Specifically, the game engine managed to set your state to one that makes negative amounts of sense.\n\n");
Cgame.unSignalGameContinue();
t.snooze(500);
t.sayWhat("Look buddy, you got a kill-bug.\n\tJust play it again, hopefully the bug won\'t rear its ugly head.");
}
});
}
public void prepContinueButton()
{
t.snooze(AnimationUtils.loadAnimation(t, R.anim.fadeout).getDuration());
while(t.waiting)
t.frameTick();
t.delay(t.gen.nextInt(250)+250);
t.runOnUiThread(new Runnable ()
{
@Override
public void run()
{
View v=t.findViewById(R.id.gameContinueButton);
if (v!=null)
{
Button b=(Button)v;
b.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick (View v)
{
v.setOnClickListener(null);
inputted=-1;
t.th.interrupt();
t.displayHandler.removeMessages(1);
t.th=new Thread (new Runnable ()
{
@Override
public void run ()
{
t.displayHandler.removeMessages(1);
if (t.user.dead)
{
stage=-1;
t.config.computerPaused=true;
}
else
t.config.computerPaused=false;
runStage();
}
});
t.th.start();
}
});
b.setVisibility(View.VISIBLE);
}
else
t.logError("prepContinueButton() called, but could not find button.");
}
});
}
public void prepContinueButton(final View.OnClickListener onClick)
{
t.snooze(AnimationUtils.loadAnimation(t, R.anim.fadeout).getDuration());
while(t.waiting)
t.frameTick();
t.delay(t.gen.nextInt(250)+250);
t.runOnUiThread(new Runnable ()
{
@Override
public void run()
{
View v=t.findViewById(R.id.gameContinueButton);
if (v!=null)
{
Button b=(Button)v;
b.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick (View v)
{
v.setOnClickListener(null);
inputted=-1;
t.th.interrupt();
t.displayHandler.removeMessages(1);
onClick.onClick(v);
}
});
b.setVisibility(View.VISIBLE);
}
else
t.logError("prepContinueButton() called, but could not find button.");
}
});
}
private static LinearLayout prepInput()
{
t.setContentView(R.layout.input);
t.currentView=R.id.inputLayout;
t.setUi();
return (LinearLayout)t.findViewById(R.id.inputButtonBar);
}
private static LinearLayout prepInput(String inputTitle)
{
t.setContentView(R.layout.input);
t.currentView=R.id.inputLayout;
((TextView)t.findViewById(R.id.inputTitle)).setText(inputTitle);
t.setUi();
return (LinearLayout)t.findViewById(R.id.inputButtonBar);
}
private static void eatenByGrue()
{
t.user.dead=true;
t.config.computerPaused=true;
t.fadeout();
t.runOnUiThread(new Runnable()
{
@Override
public void run()
{
t.setContentView(R.layout.grue);
t.currentView=R.id.grueLayout;
t.setUi();
if (t.config.triggerEgg(1, 3))
((TextView)t.findViewById(R.id.grueContent)).setTextColor(Color.rgb(255, t.gen.nextInt(256), t.gen.nextInt(256)));
}
});
}
public boolean onMove(double IBOdds)
{
t.user.gold.accrueInterest();
if (t.config.schoolEggs && t.config.triggerEgg(IBOdds))
{
t.user.dead=!t.config.triggerEgg(99);
t.th=new Thread(new Runnable()
{
@Override
public void run()
{
if (t.user.dead)
{
String message="You black out, and wake up in an IB HL English classroom.\n\n\tAs you look around in confusion, the teacher says,\n\n\t\tEssay test today!\n\t\tHere\'s the book!\n\n\tAs the students prepare themselves for an essay test, and the teacher passes out their books, you decide you have no choice.\n\n\tYou close your eyes...";
if (t.user.weapon.type==Cweapon.TYPE_FUTURE)
{
if (t.user.weapon.characteristicSet(Cweapon.CLOSE_RANGE_ONLY)) // This is the identifying trait of the lightsaber.
message+="\n\n\n\n\n\n\t...And draw your "+t.user.weapon+"!\n\n\tYou charge at the teacher, intending to fight your way out.\n\n\tAll of a sudden, a student blocks your path, hitting you, saying something about the teacher not yet having handed out the homework.\n\n\tAs you try to stop, your lightsaber slices cleanly through a girl next to you.\n\n\tShe collapses, dead.\n\n\tBefore you can react, ";
else
message+="\n\n\n\n\n\t...And draw your "+t.user.weapon+"!\n\n\tYou aim at the teacher, and tense.\n\n\n\tJust as you\'re ready to fire, a student hits you, yelling something about the homework needing explanation.\n\n\t"+(t.gen.nextBoolean() ? "She" : "He")+" throws off your balance, and your aim as well.\n\n\n\tYour shot strikes another student, turning "+(t.gen.nextBoolean() ? "him" : "her")+" into ash.\n\n\tSuddenly, ";
message+="Gandalf appears.\n\n\tHe yells,\n\n\t\tHow dare you do this!\n\t\tYou are unworthy!!!\n\n\tWith that...";
}
t.say("Baccalaureate", message);
}
else
{
String[] topics={
"differentiation",
"integration",
"the Fundamental Theorem of Calculus",
"how to find volume via integrals",
"Riemann sums",
"limits",
"relative rates",
"Taylor polynomials",
"series",
"vectors",
"proof by induction",
"differential equations",
"optimization"
};
t.say("The Diploma", "You black out, and awake in an IB HL Math classroom.\n\n\tAs you look around in confusion, the teacher begins to teach "+topics[t.gen.nextInt(topics.length)]+".\n\n\tYou feel...\n\tMotivated, strangely enough.\n\n\n\n\tThrough hard work, perserverance, and worship of Lord 2-19, you get the IB diploma.");
}
}
});
t.th.start();
prepContinueButton(t.user.dead ? new OnClickListener()
{
@Override
public void onClick(View v)
{
t.th.interrupt();
t.th=new Thread(new Runnable()
{
@Override
public void run()
{
if (t.user.weapon.type==Cweapon.TYPE_FUTURE)
{
t.user.weapon.type=Cweapon.TYPE_USED_FOR_CONVENIENCE;
t.user.commitSuicide();
}
else if (t.config.triggerEgg(.2))
t.user.commitSuicide();
else
{
stage=-1;
runStage();
}
}
});
t.th.start();
}
} : onWin);
return true;
}
return false;
}
public boolean onMove (double IBNumerator, double IBDenominator)
{
return onMove(IBNumerator/IBDenominator);
}
public boolean onMove (int oneIn)
{
return onMove(1, oneIn);
}
public OnClickListener onWin=new OnClickListener()
{
@Override
public void onClick(View v)
{
t.th.interrupt();
t.setContentView(R.layout.quit);
t.currentView=R.id.quitLayout;
t.setUi();
((TextView)t.findViewById(R.id.quitTitle)).setText("You win!!");
((Button)t.findViewById(R.id.quitContinueButton)).setText("Play again");
}
};
private boolean archeryMinigame (final int threshold, final double time) // Reimplement this like KEYSEC.
{
final keypressMinigame game=new keypressMinigame((threshold/time)*.25);
t.fadeout();
t.runOnUiThread(new Runnable()
{
@Override
public void run()
{
t.setContentView(R.layout.archery);
t.currentView=R.id.archeryLayout;
t.setUi();
game.button=t.findViewById(R.id.archeryBullseye);
((TextView)t.findViewById(R.id.archeryThreshold)).setText(Integer.toString(threshold));
((TextView)t.findViewById(R.id.archeryCurrent)).setText("0");
((TextView)t.findViewById(R.id.archeryTiming)).setText(Long.toString((long)game.timeRemaining));
}
});
if (t.snooze((long)((1000*game.timeRemaining)-((long)(1000*game.timeRemaining)))))
return true;
while (game.timeRemaining>=1)
{
if (t.snooze(1000))
return true;
--game.timeRemaining;
t.runOnUiThread(new Runnable()
{
@Override
public void run()
{
((TextView)t.findViewById(R.id.archeryTiming)).setText(Long.toString((long)game.timeRemaining));
}
});
}
game.timeRemaining=time;
t.runOnUiThread(new Runnable()
{
@Override
public void run()
{
Configuration c=t.getResources().getConfiguration();
boolean landscape=(c.orientation==Configuration.ORIENTATION_LANDSCAPE); // If we're in landscape mode, we need all the space we can get.
t.findViewById(R.id.archeryWait).setVisibility(landscape || t.gen.nextBoolean() ? View.GONE : View.INVISIBLE);
((TextView)t.findViewById(R.id.archeryTimingLabel)).setText("Time ends in:");
((TextView)t.findViewById(R.id.archeryTiming)).setText(Long.toString((long)game.timeRemaining));
game.button.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View v)
{
game.deltaX+=Math.copySign(Math.max(Math.abs(t.gen.nextGaussian()), t.gen.nextDouble()), game.deltaX);
game.deltaY+=Math.copySign(Math.max(Math.abs(t.gen.nextGaussian()), t.gen.nextDouble()), game.deltaY);
++game.presses;
((TextView)t.findViewById(R.id.archeryCurrent)).setText(Integer.toString(game.presses));
}
});
}
});
Thread ticker=new Thread(new Runnable()
{
@Override
public void run()
{
LinearLayout.LayoutParams lp=(LinearLayout.LayoutParams)game.button.getLayoutParams();
Runnable r=new Runnable()
{
@TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2)
@Override
public void run()
{
if (!(Build.VERSION.SDK_INT>=18 && game.button.isInLayout()))
game.button.requestLayout();
}
};
while (!game.done)
{
double factor=60.0/MainActivity.TARGET_FPS;
int dX=(int)Math.round(game.deltaX*factor);
int dY=(int)Math.round(game.deltaY*factor);
if ((lp.leftMargin+dX)<0 || (lp.leftMargin+dX)>(t.findViewById(R.id.archeryBullseyeLayout).getWidth()-game.button.getWidth()))
{
game.deltaX*=-1;
dX*=-1;
}
if ((lp.topMargin+dY)<0 || (lp.topMargin+dY)>(t.findViewById(R.id.archeryBullseyeLayout).getHeight()-game.button.getHeight()))
{
game.deltaY*=-1;
dY*=-1;
}
lp.topMargin+=dY;
lp.leftMargin+=dX;
t.runOnUiThread(r);
if (t.frameTick())
return;
}
}
});
ticker.start();
t.snooze((long)(1000*(game.timeRemaining-Math.floor(game.timeRemaining))));
game.timeRemaining=Math.floor(game.timeRemaining);
while (game.timeRemaining>=1)
{
t.snooze(1000);
--game.timeRemaining;
t.runOnUiThread(new Runnable()
{
@Override
public void run()
{
((TextView)t.findViewById(R.id.archeryTiming)).setText(Long.toString((long)game.timeRemaining));
}
});
}
game.done=true;
t.user.dead=(game.presses<threshold);
return t.user.dead;
}
public targetingMinigame.output aimMinigame()
{
final targetingMinigame game=new targetingMinigame();
t.fadeout();
t.runOnUiThread(new Runnable()
{
@Override
public void run()
{
t.setContentView(R.layout.aimer);
t.currentView=R.id.aimerLayout;
game.crosshairs=t.findViewById(R.id.aimerCrosshairs);
game.layout=t.findViewById(R.id.aimerBullseyeLayout);
game.bullseye=t.findViewById(R.id.aimerBullseye);
game.crosshairCoord=(RelativeLayout.LayoutParams)game.crosshairs.getLayoutParams();
((TextView)t.findViewById(R.id.aimerTiming)).setText(Long.toString((long)Math.floor(game.timeRemaining)));
Configuration c=t.getResources().getConfiguration();
if (c.orientation==Configuration.ORIENTATION_LANDSCAPE)
game.layout.getLayoutParams().width=game.layout.getHeight();
}
});
if (t.snooze((long)((1000*game.timeRemaining)-((long)(1000*game.timeRemaining)))))
return new targetingMinigame.output();
game.timeRemaining=Math.floor(game.timeRemaining);
while (game.timeRemaining>=1)
{
if (t.snooze(1000))
return new targetingMinigame.output();
--game.timeRemaining;
t.runOnUiThread(new Runnable()
{
@Override
public void run()
{
((TextView)t.findViewById(R.id.aimerTiming)).setText(Long.toString((long)game.timeRemaining));
}
});
}
game.timeRemaining=t.gen.nextGaussian()+(t.config.difficultyMult*8)+5;
t.runOnUiThread(new Runnable()
{
@Override
public void run()
{
game.crosshairs.setVisibility(View.VISIBLE);
((TextView)t.findViewById(R.id.aimerTimingTitle)).setText("Time remaining:");
((TextView)t.findViewById(R.id.aimerTiming)).setText(Long.toString((long)Math.floor(game.timeRemaining)));
game.crosshairCoord.leftMargin=t.gen.nextInt(game.layout.getWidth()-game.crosshairs.getWidth());
game.crosshairCoord.topMargin=t.gen.nextInt(game.layout.getHeight()-game.crosshairs.getHeight());
t.findViewById(R.id.aimerUpArrow).setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View v)
{
double delta=Math.abs(t.gen.nextGaussian()+((t.gen.nextDouble()+game.deltaY)));
if (game.crosshairCoord.topMargin<=delta)
game.crosshairCoord.topMargin=0;
else
game.crosshairCoord.topMargin-=delta;
}
});
t.findViewById(R.id.aimerRightArrow).setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View v)
{
double delta=Math.abs(t.gen.nextGaussian()+((t.gen.nextDouble()+game.deltaX)));
if (game.crosshairCoord.topMargin+delta+game.crosshairs.getHeight()>=game.layout.getHeight())
game.crosshairCoord.topMargin=game.layout.getHeight()-game.crosshairs.getHeight();
else
game.crosshairCoord.leftMargin+=delta;
}
});
t.findViewById(R.id.aimerDownArrow).setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View v)
{
double delta=Math.abs(t.gen.nextGaussian()+((t.gen.nextDouble()+game.deltaY)));
if (game.crosshairCoord.topMargin+delta+game.crosshairs.getHeight()>=game.layout.getHeight())
game.crosshairCoord.topMargin=game.layout.getHeight()-game.crosshairs.getHeight();
else
game.crosshairCoord.topMargin+=delta;
}
});
t.findViewById(R.id.aimerLeftArrow).setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View v)
{
double delta=Math.abs(t.gen.nextGaussian()+((t.gen.nextDouble()+game.deltaX)));
if (game.crosshairCoord.topMargin<=delta)
game.crosshairCoord.topMargin=0;
else
game.crosshairCoord.leftMargin-=delta;
}
});
}
});
game.startSway();
t.snooze((long)(1000*(game.timeRemaining-Math.floor(game.timeRemaining))));
game.timeRemaining=Math.floor(game.timeRemaining);
while (game.timeRemaining>=1)
{
t.snooze(1000);
--game.timeRemaining;
t.runOnUiThread(new Runnable()
{
@Override
public void run()
{
((TextView)t.findViewById(R.id.aimerTiming)).setText(Long.toString((long)game.timeRemaining));
}
});
}
game.swayer.interrupt();
game.swayer=null;
return game.result();
}
@Override
public int describeContents ()
{
return 4;
}
@Override
public void writeToParcel (Parcel out, int n)
{
out.writeInt(--stage);
out.writeInt(line);
out.writeInt(inputted);
}
public static final Parcelable.Creator<Cgame> CREATOR=new Parcelable.Creator<Cgame> ()
{
@Override
public Cgame createFromParcel (Parcel in)
{
return new Cgame(in);
}
@Override
public Cgame[] newArray (int n)
{
return new Cgame[n];
}
};
// Data-Only classes: NOT CONSERVED through onRestoreInstanceState()
private static class keypressMinigame
{
public int presses;
public double deltaX;
public double deltaY;
public double timeRemaining;
public boolean done;
public View button;
public keypressMinigame()
{
presses=0;
deltaX=t.gen.nextGaussian();
deltaY=t.gen.nextGaussian();
timeRemaining=t.gen.nextInt(3)+3+t.gen.nextGaussian();
done=false;
}
public keypressMinigame(double speedMult)
{
presses=0;
deltaX=speedMult*t.gen.nextGaussian();
deltaY=speedMult*t.gen.nextGaussian();
timeRemaining=t.gen.nextInt(3)+3+t.gen.nextGaussian();
done=false;
}
}
private static class targetingMinigame
{
public static class output // The type for returned data.
{
public double distance; // Distance from a true bullseye
public int type; // The classification of this shot
public output()
{
distance=-1;
type=-1;
MAX_DISTANCE=-1;
}
public static final int MISSED=6;
public static final int GRAZED=5;
public static final int POOR=4;
public static final int HIT=3;
public static final int GOOD=2;
public static final int CRITICAL=1;
public static final int BULLSEYE=0;
public static double MAX_DISTANCE;
public static String toString (int n)
{
switch (n)
{
case MISSED:
return t.gen.nextBoolean() ? "Miss" : "Fail";
case GRAZED:
return "Close"+(t.gen.nextBoolean() ? (" only counts in "+(t.config.triggerEgg(1, 3) ? "handshoes and horse grenades" : "horseshoes and hand grenades")) : ", but no cigar");
case POOR:
return t.gen.nextBoolean() ? "Needs practice" : "Just barely";
case HIT:
return "Solid "+(t.gen.nextBoolean() ? "shot" : "hit");
case GOOD:
return "Good "+(t.gen.nextBoolean() ? "shot" : "hit");
case CRITICAL:
String[] roots={
"Critical",
"Excellent",
"Great",
"Incredible",
"Sharpshooter\'s",
"Master\'s",
"Masterful"
};
String[] suffixes={
"hit",
"shot",
"impact"
};
return roots[t.gen.nextInt(roots.length)]+" "+suffixes[t.gen.nextInt(suffixes.length)];
case BULLSEYE:
return t.gen.nextBoolean() ? "Bullseye" : "Perfect "+(t.gen.nextBoolean() ? "shot" : "aim");
default:
return "Gunshot";
}
}
public static String toString(output o)
{
return o.toString();
}
@Override
public String toString()
{
return toString(type);
}
}
public View crosshairs;
public View bullseye;
public View layout;
RelativeLayout.LayoutParams crosshairCoord;
public double weaponSwayMultiplier;
public int weaponSwayMaximum;
public double timeRemaining;
public double deltaX;
public double deltaY;
public Thread swayer;
public targetingMinigame()
{
weaponSwayMultiplier=.75+(.25*t.gen.nextGaussian());
weaponSwayMaximum=3+t.gen.nextInt(4);
timeRemaining=t.gen.nextInt(3)+3+t.gen.nextGaussian();
deltaX=2*(t.gen.nextDouble()+t.gen.nextInt(21)+10);
deltaY=2*(t.gen.nextDouble()+t.gen.nextInt(21)+10);
}
public void startSway()
{
if (swayer!=null)
swayer.interrupt();
swayer=new Thread(new Runnable() // Improvement target
{
@Override
public void run()
{
final Runnable r=new Runnable()
{
@TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2)
@Override
public void run()
{
if (!(Build.VERSION.SDK_INT>=18 && layout.isInLayout()))
layout.requestLayout();
}
};
double angle=t.gen.nextDouble()*2*Math.PI;
while (!Thread.interrupted())
{
double velocity=weaponSwayMultiplier*weaponSwayMaximum*Math.max(.25, t.gen.nextDouble())*(MainActivity.TARGET_FPS/60.0);
if (0==t.gen.nextInt((int)(MainActivity.TARGET_FPS+1)))
{
angle+=Math.max(Math.PI/6, t.gen.nextDouble()*Math.PI)*(t.gen.nextBoolean() ? -1 : 1);
velocity*=.5;
}
crosshairCoord.leftMargin=(int)Math.round(Math.max(0, Math.min(layout.getWidth()-crosshairs.getWidth(), crosshairCoord.leftMargin+(Math.cos(angle)*velocity))));
crosshairCoord.topMargin=(int)Math.round(Math.max(0, Math.min(layout.getHeight()-crosshairs.getHeight(), crosshairCoord.topMargin-(Math.sin(angle)*velocity))));
t.runOnUiThread(r);
t.frameTick(1);
}
}
});
swayer.start();
}
public output result()
{
output out=new output();
RelativeLayout.LayoutParams bulls=(RelativeLayout.LayoutParams)bullseye.getLayoutParams();
RelativeLayout.LayoutParams cross=(RelativeLayout.LayoutParams)crosshairs.getLayoutParams();
double tmp=(bulls.leftMargin+(bullseye.getWidth()*.5))-(cross.leftMargin+(crosshairs.getWidth()*.5));
double num=(bulls.topMargin+(bullseye.getHeight()*.5))-(cross.topMargin+(crosshairs.getHeight()*.5));
out.distance=Math.sqrt((tmp*tmp)+(num*num));
output.MAX_DISTANCE=.5*bullseye.getWidth();
// out.type=(int)Math.ceil(out.distance/bullseye.getWidth()/12); // Mathematical way. Found to be buggy and disabled: If fixed, this will be more efficient.
double diff=bullseye.getWidth()/10;
if (out.distance==0)
out.type=output.BULLSEYE;
else if (out.distance<diff)
out.type=output.CRITICAL;
else if (out.distance<(2*diff))
out.type=output.GOOD;
else if (out.distance<(3*diff))
out.type=output.HIT;
else if (out.distance<(4*diff))
out.type=output.POOR;
else if (out.distance<(5*diff))
out.type=output.GRAZED;
else
out.type=output.MISSED;
return out;
}
}
}
|
package com.bkp.minerva;
import android.app.Application;
import android.content.Context;
import com.karumi.dexter.Dexter;
import io.realm.Realm;
import io.realm.RealmConfiguration;
/**
* Custom Application class.
*/
public class Minerva extends Application {
/**
* Static instance to (CAREFULLY) allow getting Application Context anywhere.
*/
private static Minerva instance;
@Override
public void onCreate() {
super.onCreate();
// Stash application context.
instance = this;
// Init Dexter.
Dexter.initialize(this);
// Set up Realm.
setupRealm();
}
/**
* Set up Realm's default configuration.
*/
private void setupRealm() {
RealmConfiguration config = new RealmConfiguration.Builder(this)
.name("minerva.realm")
.schemaVersion(0)
.build();
Realm.setDefaultConfiguration(config);
}
/**
* Get the application context. DO NOT use the context returned by this method in methods which affect the UI (such
* as when inflating a layout, for example).
* @return Application context.
*/
public static Context getAppCtx() {
return instance.getApplicationContext();
}
}
|
package sc.fiji.threed;
import cleargl.GLMatrix;
import cleargl.GLVector;
import com.jogamp.opengl.GLAutoDrawable;
import ij.ImagePlus;
import net.imagej.ImageJ;
import net.imglib2.RealLocalizable;
import sc.fiji.threed.process.MeshConverter;
import org.scijava.ui.behaviour.ClickBehaviour;
import scenery.*;
import scenery.controls.behaviours.ArcballCameraControl;
import scenery.controls.behaviours.FPSCameraControl;
import scenery.backends.Renderer;
import scenery.backends.opengl.OpenGLRenderer;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
import java.nio.FloatBuffer;
import java.util.concurrent.CopyOnWriteArrayList;
public class ThreeDViewer extends SceneryDefaultApplication {
static ImageJ ij;
static ThreeDViewer viewer;
static Thread animationThread;
static Mesh aMesh = null;
static Boolean defaultArcBall = true;
public ThreeDViewer() {
super("ThreeDViewer", 800, 600);
}
public ThreeDViewer(String applicationName, int windowWidth, int windowHeight) {
super(applicationName, windowWidth, windowHeight);
}
public void init() {
setRenderer( Renderer.Companion.createRenderer( getApplicationName(), getScene(), 512, 512));
getHub().add(SceneryElement.RENDERER, getRenderer());
PointLight[] lights = new PointLight[2];
for( int i = 0; i < lights.length; i++ ) {
lights[i] = new PointLight();
lights[i].setPosition( new GLVector(2.0f * i, 2.0f * i, 2.0f * i) );
lights[i].setEmissionColor( new GLVector(1.0f, 0.0f, 1.0f) );
lights[i].setIntensity( 0.2f*(i+1) );
getScene().addChild( lights[i] );
}
Camera cam = new DetachedHeadCamera();
cam.setPosition( new GLVector(0.0f, 0.0f, -5.0f) );
cam.setView( new GLMatrix().setCamera(cam.getPosition(), cam.getPosition().plus(cam.getForward()), cam.getUp()) );
cam.setProjection( new GLMatrix().setPerspectiveProjectionMatrix( (float) (70.0f / 180.0f * java.lang.Math.PI), 1024f / 1024f, 0.1f, 2000.0f) );
cam.setActive( true );
getScene().addChild(cam);
viewer = this;
}
public void inputSetup() {
//setInputHandler((ClearGLInputHandler) viewer.getHub().get(SceneryElement.INPUT));
ClickBehaviour objectSelector = new ClickBehaviour() {
public void click( int x, int y ) {
System.out.println( "Clicked at x=" + x + " y=" + y );
}
};
viewer.getInputHandler().useDefaultBindings("");
viewer.getInputHandler().addBehaviour("object_selection_mode", objectSelector);
enableArcBallControl();
}
public static void addBox() {
addBox( new GLVector(0.0f, 0.0f, 0.0f) );
}
public static void addBox( GLVector position ) {
addBox( position, new GLVector(10.0f, 10.0f, 10.0f) );
}
public static void addBox( GLVector position, GLVector size ) {
addBox( position, size, new GLVector( 0.9f, 0.9f, 0.9f ) );
}
public static void addBox( GLVector position, GLVector size, GLVector color ) {
Material boxmaterial = new Material();
boxmaterial.setAmbient( new GLVector(1.0f, 0.0f, 0.0f) );
boxmaterial.setDiffuse( color );
boxmaterial.setSpecular( new GLVector(1.0f, 1.0f, 1.0f) );
boxmaterial.setDoubleSided(true);
//boxmaterial.getTextures().put("diffuse", SceneViewer3D.class.getResource("textures/helix.png").getFile() );
final Box box = new Box( size );
box.setMaterial( boxmaterial );
box.setPosition( position );
//System.err.println( "Num elements in scene: " + viewer.getSceneNodes().size() );
viewer.getScene().addChild(box);
if( defaultArcBall ) enableArcBallControl();
//System.err.println( "Num elements in scene: " + viewer.getSceneNodes().size() );
}
public static void addSphere() {
addSphere( new GLVector(0.0f, 0.0f, 0.0f), 1 );
}
public static void addSphere( GLVector position, float radius ) {
addSphere( position, radius, new GLVector( 0.9f, 0.9f, 0.9f ) );
}
public static void addSphere( GLVector position, float radius, GLVector color ) {
Material material = new Material();
material.setAmbient( new GLVector(1.0f, 0.0f, 0.0f) );
material.setDiffuse( color );
material.setSpecular( new GLVector(1.0f, 1.0f, 1.0f) );
//boxmaterial.getTextures().put("diffuse", SceneViewer3D.class.getResource("textures/helix.png").getFile() );
final Sphere sphere = new Sphere( radius, 20 );
sphere.setMaterial( material );
sphere.setPosition( position );
viewer.getScene().addChild(sphere);
if( defaultArcBall ) enableArcBallControl();
}
public static void addPointLight() {
Material material = new Material();
material.setAmbient( new GLVector(1.0f, 0.0f, 0.0f) );
material.setDiffuse( new GLVector(0.0f, 1.0f, 0.0f) );
material.setSpecular( new GLVector(1.0f, 1.0f, 1.0f) );
//boxmaterial.getTextures().put("diffuse", SceneViewer3D.class.getResource("textures/helix.png").getFile() );
final PointLight light = new PointLight();
light.setMaterial( material );
light.setPosition( new GLVector(0.0f, 0.0f, 0.0f) );
viewer.getScene().addChild(light);
}
/* java.nio.FloatBuffer.array version
public static void writeSCMesh( String filename, Mesh scMesh ) {
File f = new File( filename );
BufferedOutputStream out;
try {
out = new BufferedOutputStream( new FileOutputStream( f ) );
out.write( "solid STL generated by FIJI\n".getBytes() );
float[] verts = scMesh.getVertices().array();
float[] norms = scMesh.getNormals().array();
for( int k = 0; k < verts.length/9; k++ ) {
int offset = k * 9;
out.write( ("facet normal " + norms[offset] + " " + norms[offset+1] + " " + norms[offset+2] + "\n").getBytes() );
out.write( "outer loop\n".getBytes() );
for( int v = 0; v < 3; v++ ) {
int voff = v*3;
out.write( ( "vertex\t" + verts[offset+voff] + " " + verts[offset+voff+1] + " " + verts[offset+voff+2] + "\n" ).getBytes() );
}
out.write( "endloop\n".getBytes() );
out.write( "endfacet\n".getBytes() );
}
out.write( "endsolid vcg\n".getBytes() );
out.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
*/
public static void writeSCMesh( String filename, Mesh scMesh ) {
File f = new File( filename );
BufferedOutputStream out;
try {
out = new BufferedOutputStream( new FileOutputStream( f ) );
out.write( "solid STL generated by FIJI\n".getBytes() );
FloatBuffer normalsFB = scMesh.getNormals();
FloatBuffer verticesFB = scMesh.getVertices();
while( verticesFB.hasRemaining() && normalsFB.hasRemaining() ) {
out.write( ("facet normal " + normalsFB.get() + " " + normalsFB.get() + " " + normalsFB.get() + "\n").getBytes() );
out.write( "outer loop\n".getBytes() );
for( int v = 0; v < 3; v++ ) {
out.write( ( "vertex\t" + verticesFB.get() + " " + verticesFB.get() + " " + verticesFB.get() + "\n" ).getBytes() );
}
out.write( "endloop\n".getBytes() );
out.write( "endfacet\n".getBytes() );
}
out.write( "endsolid vcg\n".getBytes() );
out.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void addSTL( String filename ) {
Mesh scMesh = new Mesh();
scMesh.readFromSTL( filename );
scMesh.generateBoundingBox();
System.out.println( "Read STL: " + scMesh.getBoundingBox() );
net.imagej.ops.geom.geom3d.mesh.Mesh opsMesh = MeshConverter.getOpsMesh( scMesh );
System.out.println( "Loaded and converted mesh: " + opsMesh.getVertices().size() );
//((DefaultMesh) opsMesh).centerMesh();
addMesh( opsMesh );
}
public static void addObj( String filename ) {
Mesh scMesh = new Mesh();
scMesh.readFromOBJ( filename, false );// Could check if there is a MTL to use to toggle flag
net.imagej.ops.geom.geom3d.mesh.Mesh opsMesh = MeshConverter.getOpsMesh( scMesh );
//((DefaultMesh) opsMesh).centerMesh();
addMesh( opsMesh );
}
public static void addMesh( net.imagej.ops.geom.geom3d.mesh.Mesh mesh ) {
Mesh scMesh = MeshConverter.getSceneryMesh( mesh );
Material material = new Material();
material.setAmbient( new GLVector(1.0f, 0.0f, 0.0f) );
material.setDiffuse( new GLVector(0.0f, 1.0f, 0.0f) );
material.setSpecular( new GLVector(1.0f, 1.0f, 1.0f) );
material.setDoubleSided(true);
scMesh.setMaterial( material );
scMesh.setPosition( new GLVector(1.0f, 1.0f, 1.0f) );
aMesh = scMesh;
viewer.getScene().addChild( scMesh );
if( defaultArcBall ) enableArcBallControl();
// System.err.println( "Number of nodes in scene: " + ThreeDViewer.getSceneNodes().size() );
}
public static void removeMesh( Mesh scMesh ) {
viewer.getScene().removeChild( scMesh );
}
public static Mesh getSelectedMesh() {
return aMesh;
}
public static Thread getAnimationThread() {
return ThreeDViewer.animationThread;
}
public static void setAnimationThread( Thread newAnimator ) {
ThreeDViewer.animationThread = newAnimator;
}
public static void takeScreenshot() {
float[] bounds = viewer.getRenderer().getWindow().getClearglWindow().getBounds();
// if we're in a jpanel, this isn't the way to get bounds
try {
Robot robot = new Robot();
BufferedImage screenshot = robot.createScreenCapture( new Rectangle( (int)bounds[0], (int)bounds[1], (int)bounds[2], (int)bounds[3] ) );
ImagePlus imp = new ImagePlus( "ThreeDViewer_Screenshot", screenshot );
imp.show();
} catch (AWTException e) {
e.printStackTrace();
}
}
public static void enableArcBallControl() {
GLVector target;
if( getSelectedMesh() == null ) {
target = new GLVector( 0, 0, 0 );
} else {
net.imagej.ops.geom.geom3d.mesh.Mesh opsMesh = MeshConverter.getOpsMesh( getSelectedMesh() );
RealLocalizable center = MeshUtils.getCenter(opsMesh);
target = new GLVector( center.getFloatPosition(0), center.getFloatPosition(1), center.getFloatPosition(2) );
}
ArcballCameraControl targetArcball = new ArcballCameraControl("mouse_control", viewer.getScene().findObserver(),
viewer.getRenderer().getWindow().getClearglWindow().getWidth(),
viewer.getRenderer().getWindow().getClearglWindow().getHeight(), target);
targetArcball.setMaximumDistance(Float.MAX_VALUE);
viewer.getInputHandler().addBehaviour("mouse_control", targetArcball);
viewer.getInputHandler().addBehaviour("scroll_arcball", targetArcball);
viewer.getInputHandler().addKeyBinding("scroll_arcball", "scroll");
}
public static void enableFPSControl() {
FPSCameraControl fpsControl = new FPSCameraControl("mouse_control", viewer.getScene().findObserver(),
viewer.getRenderer().getWindow().getClearglWindow().getWidth(),
viewer.getRenderer().getWindow().getClearglWindow().getHeight());
viewer.getInputHandler().addBehaviour("mouse_control", fpsControl);
viewer.getInputHandler().removeBehaviour("scroll_arcball");
}
public static ThreeDViewer getViewer() {
return viewer;
}
public static Node[] getSceneNodes() {
CopyOnWriteArrayList<Node> children = viewer.getScene().getChildren();
return viewer.getScene().getChildren().toArray( new Node[children.size()] );
}
public static void deleteSelectedMesh() {
viewer.getScene().removeChild( ThreeDViewer.getSelectedMesh() );
}
public static void main(String... args)
{
if( ij == null )
ij = new ImageJ();
if( !ij.ui().isVisible() )
ij.ui().showUI();
ThreeDViewer viewer = new ThreeDViewer( "ThreeDViewer", 800, 600 );
viewer.main();
}
}
|
package ph.pakete.model;
import com.google.gson.annotations.SerializedName;
import java.util.Date;
import io.realm.RealmList;
import io.realm.RealmObject;
import io.realm.annotations.Ignore;
import io.realm.annotations.PrimaryKey;
public class Package extends RealmObject {
@PrimaryKey
@SerializedName("tracking_number")
private String trackingNumber;
private String name;
@SerializedName("track_history")
private RealmList<PackageTrackHistory> trackHistory = new RealmList<>();
private Courier courier;
private Boolean completed = false;
private Boolean archived = false;
private Date createdAt = new Date();
@Ignore
private Boolean updating = false;
public String getTrackingNumber() {
return trackingNumber;
}
public void setTrackingNumber(String trackingNumber) {
this.trackingNumber = trackingNumber;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public RealmList<PackageTrackHistory> getTrackHistory() {
return trackHistory;
}
public Courier getCourier() {
return courier;
}
public void setCourier(Courier courier) {
this.courier = courier;
}
public Boolean getCompleted() {
return completed;
}
public void setCompleted(Boolean completed) {
this.completed = completed;
}
public Boolean getArchived() {
return archived;
}
public void setArchived(Boolean archived) {
this.archived = archived;
}
public Boolean getUpdating() {
return updating;
}
public void setUpdating(Boolean updating) {
this.updating = updating;
}
public Date getCreatedAt() {
return createdAt;
}
public PackageTrackHistory latestTrackHistory() {
if (getTrackHistory().size() > 0) {
return getTrackHistory().first();
} else {
return null;
}
}
}
|
package se.kth.csc.persist;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Repository;
import se.kth.csc.model.*;
import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.PersistenceContext;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
@Repository
public class JPAStore implements QueuePositionStore, QueueStore, AccountStore {
private static final Logger log = LoggerFactory.getLogger(JPAStore.class);
@PersistenceContext
private EntityManager entityManager;
@Override
public Queue fetchQueueWithId(int id) {
return entityManager.find(Queue.class, id);
}
@Override
public List<Queue> fetchAllQueues() {
CriteriaBuilder cb = entityManager.getCriteriaBuilder();
CriteriaQuery<Queue> q = cb.createQuery(Queue.class);
return entityManager.createQuery(q.select(q.from(Queue.class))).getResultList();
}
@Override
public List<String> fetchAllQueueNames() {
List<String> queueNames = new LinkedList<String>();
for (Queue queue : fetchAllQueues()) {
queueNames.add(queue.getName());
}
return queueNames;
}
@Override
public List<Queue> fetchAllActiveQueues() {
CriteriaBuilder cb = entityManager.getCriteriaBuilder();
CriteriaQuery<Queue> q = cb.createQuery(Queue.class);
Root<Queue> queueRoot = q.from(Queue.class);
q.select(queueRoot).where(queueRoot.get(Queue_.active));
return entityManager.createQuery(q).getResultList();
}
@Override
public List<Queue> fetchAllModeratedQueues(Account account) {
CriteriaBuilder cb = entityManager.getCriteriaBuilder();
CriteriaQuery<Queue> q = cb.createQuery(Queue.class);
q.select(q.from(Queue.class));
List<Queue> list = entityManager.createQuery(q).getResultList();
List<Queue> tmpList = new LinkedList<Queue>();
for(Queue que : list){
if(que.getModerators().contains(account)){
tmpList.add(que);
}
}
return tmpList;
}
@Override
public List<Queue> fetchAllOwnedQueues(Account account) {
CriteriaBuilder cb = entityManager.getCriteriaBuilder();
CriteriaQuery<Queue> q = cb.createQuery(Queue.class);
q.select(q.from(Queue.class));
List<Queue> list = entityManager.createQuery(q).getResultList();
List<Queue> tmpList = new LinkedList<Queue>();
for(Queue que : list){
if(que.getOwners().contains(account)){
tmpList.add(que);
}
}
return tmpList;
}
@Override
public void storeQueue(Queue queue) {
entityManager.persist(queue);
log.info("Created a new queue with id {}", queue.getId());
}
@Override
public void removeQueue(Queue queue) {
for(Account a : queue.getOwners()) {
a.getOwnedQueues().remove(queue);
}
queue.setOwners(null);
entityManager.remove(queue);
log.info("Removed queue with id {}", queue.getId());
}
@Override
public Account fetchAccountWithId(int id) {
return entityManager.find(Account.class, id);
}
@Override
public Account fetchAccountWithPrincipalName(String principalName) {
CriteriaBuilder cb = entityManager.getCriteriaBuilder();
CriteriaQuery<Account> q = cb.createQuery(Account.class);
Root<Account> account = q.from(Account.class);
try {
return entityManager.createQuery(q.select(account).where(cb.equal(account.get(Account_.principalName), principalName))).getSingleResult();
} catch (NoResultException e) {
return null;
}
}
@Override
public Account fetchNewestAccount() {
CriteriaBuilder cb = entityManager.getCriteriaBuilder();
CriteriaQuery<Account> q = cb.createQuery(Account.class);
Root<Account> account = q.from(Account.class);
List<Account> candidates = entityManager.createQuery(q.select(account).orderBy(cb.desc(account.get(Account_.id))))
.setMaxResults(1).getResultList();
if (candidates.isEmpty()) {
return null;
} else {
return candidates.get(0);
}
}
@Override
public void storeAccount(Account account) {
entityManager.persist(account);
log.info("Created a new account with id {}", account.getId());
}
@Override
public QueuePosition fetchQueuePositionWithId(int id) {
return entityManager.find(QueuePosition.class, id);
}
@Override
public void storeQueuePosition(QueuePosition queuePosition) {
entityManager.persist(queuePosition);
log.info("Created a new queue position with id {}", queuePosition.getId());
}
@Override
public void removeQueuePosition(QueuePosition queuePosition) {
entityManager.remove(queuePosition);
log.info("Removed a queue position with id {}", queuePosition.getId());
}
}
|
package seedu.address.ui;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.scene.Scene;
import javafx.scene.control.MenuItem;
import javafx.scene.control.TextInputControl;
import javafx.scene.input.KeyCombination;
import javafx.scene.input.KeyEvent;
import javafx.scene.layout.AnchorPane;
import javafx.scene.layout.Region;
import javafx.stage.Stage;
import seedu.address.commons.core.Config;
import seedu.address.commons.core.GuiSettings;
import seedu.address.commons.events.ui.ExitAppRequestEvent;
import seedu.address.commons.util.FxViewUtil;
import seedu.address.logic.Logic;
import seedu.address.model.UserPrefs;
/**
* The Main Window. Provides the basic application layout containing
* a menu bar and space where other JavaFX elements can be placed.
*/
public class MainWindow extends UiPart<Region> {
private static final String ICON = "/images/address_book_32.png";
private static final String FXML = "MainWindow.fxml";
private static final int MIN_HEIGHT = 600;
private static final int MIN_WIDTH = 450;
private Stage primaryStage;
private Logic logic;
// Independent Ui parts residing in this Ui container
private TaskListPanel taskListPanel;
private Config config;
@FXML
private AnchorPane browserPlaceholder;
@FXML
private AnchorPane commandBoxPlaceholder;
@FXML
private MenuItem helpMenuItem;
@FXML
private AnchorPane taskListPanelPlaceholder;
@FXML
private AnchorPane resultDisplayPlaceholder;
@FXML
private AnchorPane statusbarPlaceholder;
public MainWindow(Stage primaryStage, Config config, UserPrefs prefs, Logic logic) {
super(FXML);
// Set dependencies
this.primaryStage = primaryStage;
this.logic = logic;
this.config = config;
// Configure the UI
setTitle(config.getAppTitle());
setIcon(ICON);
setWindowMinSize();
setWindowDefaultSize(prefs);
Scene scene = new Scene(getRoot());
primaryStage.setScene(scene);
setAccelerators();
}
public Stage getPrimaryStage() {
return primaryStage;
}
private void setAccelerators() {
setAccelerator(helpMenuItem, KeyCombination.valueOf("F1"));
}
/**
* Sets the accelerator of a MenuItem.
* @param keyCombination the KeyCombination value of the accelerator
*/
private void setAccelerator(MenuItem menuItem, KeyCombination keyCombination) {
menuItem.setAccelerator(keyCombination);
getRoot().addEventFilter(KeyEvent.KEY_PRESSED, event -> {
if (event.getTarget() instanceof TextInputControl && keyCombination.match(event)) {
menuItem.getOnAction().handle(new ActionEvent());
event.consume();
}
});
}
public void fillInnerParts() {
taskListPanel = new TaskListPanel(getTaskListPlaceholder(), logic.getFilteredTaskList());
new ResultDisplay(getResultDisplayPlaceholder());
new StatusBarFooter(getStatusbarPlaceholder(), config.getTaskManagerFilePath());
new CommandBox(getCommandBoxPlaceholder(), logic);
}
private AnchorPane getCommandBoxPlaceholder() {
return commandBoxPlaceholder;
}
private AnchorPane getStatusbarPlaceholder() {
return statusbarPlaceholder;
}
private AnchorPane getResultDisplayPlaceholder() {
return resultDisplayPlaceholder;
}
private AnchorPane getTaskListPlaceholder() {
return this.taskListPanelPlaceholder;
}
public void hide() {
primaryStage.hide();
}
private void setTitle(String appTitle) {
primaryStage.setTitle(appTitle);
}
/**
* Sets the given image as the icon of the main window.
* @param iconSource e.g. {@code "/images/help_icon.png"}
*/
private void setIcon(String iconSource) {
FxViewUtil.setStageIcon(primaryStage, iconSource);
}
/**
* Sets the default size based on user preferences.
*/
private void setWindowDefaultSize(UserPrefs prefs) {
primaryStage.setHeight(prefs.getGuiSettings().getWindowHeight());
primaryStage.setWidth(prefs.getGuiSettings().getWindowWidth());
if (prefs.getGuiSettings().getWindowCoordinates() != null) {
primaryStage.setX(prefs.getGuiSettings().getWindowCoordinates().getX());
primaryStage.setY(prefs.getGuiSettings().getWindowCoordinates().getY());
}
}
private void setWindowMinSize() {
primaryStage.setMinHeight(MIN_HEIGHT);
primaryStage.setMinWidth(MIN_WIDTH);
}
/**
* Returns the current size and the position of the main Window.
*/
GuiSettings getCurrentGuiSetting() {
return new GuiSettings(primaryStage.getWidth(), primaryStage.getHeight(),
(int) primaryStage.getX(), (int) primaryStage.getY());
}
@FXML
public void handleHelp() {
HelpWindow helpWindow = new HelpWindow();
helpWindow.show();
}
public void show() {
primaryStage.show();
}
/**
* Closes the application.
*/
@FXML
private void handleExit() {
raise(new ExitAppRequestEvent());
}
public TaskListPanel getTaskListPanel() {
return this.taskListPanel;
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.