answer
stringlengths 17
10.2M
|
|---|
package net.hearthstats;
import java.awt.image.BufferedImage;
import java.util.Observable;
public class HearthstoneAnalyzer extends Observable {
private boolean _coin;
private BufferedImage _image;
private String _mode;
private String _opponentClass;
private String _result;
private String _screen;
private String _yourClass;
private int _deckSlot;
private boolean _isNewArena = false;
public HearthstoneAnalyzer() {
}
public void analyze(BufferedImage image) {
_image = image;
if(getScreen() != "Main Menu" && getScreen() != "Playing") {
_testForMainMenuScreen();
}
if(getScreen() != "Play") {
_testForPlayScreen();
}
if(getScreen() != "Arena") {
_testForArenaModeScreen();
}
if(getScreen() == "Play" || getScreen() == "Arena") {
_testForFindingOpponent();
if (getScreen() == "Play") {
if(getMode() != "Casual")
_testForCasualMode();
if(getMode() != "Ranked")
_testForRankedMode();
_testForDeckSlot();
}
}
if(getScreen() == "Finding Opponent") {
_testForMatchStartScreen();
}
if(getScreen() == "Match Start") {
if(getYourClass() == null)
_testForYourClass();
if(getOpponentClass() == null)
_testForOpponentClass();
if(!getCoin())
_testForCoin();
_testForPlayingScreen();
}
if(getScreen() == "Result") {
_testForArenaEnd();
}
if(getScreen() == "Playing") {
_testForVictory();
_testForDefeat();
}
if(getScreen() == "Arena" && !isNewArena()) {
_testForNewArenaRun();
}
_image.flush();
}
public boolean getCoin() {
return _coin;
}
public int getDeckSlot() {
return _deckSlot;
}
public String getMode() {
return _mode;
}
public String getOpponentClass() {
return _opponentClass;
}
public String getResult() {
return _result;
}
public String getScreen() {
return _screen;
}
public String getYourClass() {
return _yourClass;
}
public boolean isNewArena() {
return _isNewArena;
}
private void _notifyObserversOfChangeTo(String property) {
setChanged();
notifyObservers(property);
}
public void setIsNewArena(boolean isNew) {
_isNewArena = isNew;
_notifyObserversOfChangeTo("newArena");
}
private void _setDeckSlot(int deckSlot) {
_deckSlot = deckSlot;
_notifyObserversOfChangeTo("deckSlot");
}
private void _setCoin(boolean coin) {
_coin = coin;
_notifyObserversOfChangeTo("coin");
}
private void _setMode(String screen) {
_mode = screen;
_notifyObserversOfChangeTo("mode");
}
private void _setOpponentClass(String opponentClass) {
_opponentClass = opponentClass;
_notifyObserversOfChangeTo("opponentClass");
}
private void _setResult(String result) {
_result = result;
_notifyObserversOfChangeTo("result");
}
private void _setScreen(String screen) {
_screen = screen;
_notifyObserversOfChangeTo("screen");
}
private void _setYourClass(String yourClass) {
_yourClass = yourClass;
_notifyObserversOfChangeTo("yourClass");
}
private void _testForArenaEnd() {
int[][] tests = {
{ 315, 387, 239, 32, 39 },
{ 399, 404, 237, 41, 33 },
{ 448, 408, 223, 8, 16 }
};
if((new PixelGroupTest(_image, tests)).passed()) {
_screen = "Arena";
_notifyObserversOfChangeTo("arenaEnd");
}
}
private void _testForArenaModeScreen() {
int[][] tests = {
{ 807, 707, 95, 84, 111 },
{ 324, 665, 77, 114, 169 },
{ 120, 685, 255, 215, 115 },
{ 697, 504, 78, 62, 56 }
};
if((new PixelGroupTest(_image, tests)).passed()) {
_setScreen("Arena");
_setMode("Arena");
}
}
private void _testForCasualMode() {
int[][] tests = {
{ 833, 94, 100, 22, 16 }, // ranked off
{ 698, 128, 200, 255, 255 } // casual blue
};
if((new PixelGroupTest(_image, tests)).passed())
_setMode("Casual");
}
private void _testForCoin() {
int[][] tests = {
{ 869, 389, 155, 250, 103 } // fourth card right edge
};
if((new PixelGroupTest(_image, tests)).passed())
_setCoin(true);
}
private void _testForDeckSlot() {
if(getDeckSlot() != 1) {
int[][] slotOnePixels = {
{ 163, 178, 33, 129, 242},
{ 183, 178, 33, 129, 242}
};
if((new PixelGroupTest(_image, slotOnePixels)).passedOr())
_setDeckSlot(1);
}
if(getDeckSlot() != 2) {
int[][] slotTwoPixels = {
{ 348, 178, 36, 144, 247 },
{ 368, 178, 36, 144, 247 }
};
if((new PixelGroupTest(_image, slotTwoPixels)).passedOr())
_setDeckSlot(2);
}
if(getDeckSlot() != 3) {
int[][] slotTwoPixels = {
{ 506, 178, 36, 144, 247 },
{ 526, 178, 36, 144, 247 }
};
if((new PixelGroupTest(_image, slotTwoPixels)).passedOr())
_setDeckSlot(3);
}
if(getDeckSlot() != 4) {
int[][] slotOnePixels = {
{ 163, 339, 33, 129, 242},
{ 183, 339, 33, 129, 242}
};
if((new PixelGroupTest(_image, slotOnePixels)).passedOr())
_setDeckSlot(4);
}
if(getDeckSlot() != 5) {
int[][] slotTwoPixels = {
{ 348, 339, 36, 144, 247 },
{ 368, 339, 36, 144, 247 }
};
if((new PixelGroupTest(_image, slotTwoPixels)).passedOr())
_setDeckSlot(5);
}
if(getDeckSlot() != 6) {
int[][] slotTwoPixels = {
{ 506, 339, 36, 144, 247 },
{ 526, 339, 36, 144, 247 }
};
if((new PixelGroupTest(_image, slotTwoPixels)).passedOr())
_setDeckSlot(6);
}
if(getDeckSlot() != 7) {
int[][] slotOnePixels = {
{ 163, 497, 33, 129, 242},
{ 183, 497, 33, 129, 242}
};
if((new PixelGroupTest(_image, slotOnePixels)).passedOr())
_setDeckSlot(7);
}
if(getDeckSlot() != 8) {
int[][] slotTwoPixels = {
{ 348, 497, 36, 144, 247 },
{ 368, 497, 36, 144, 247 }
};
if((new PixelGroupTest(_image, slotTwoPixels)).passedOr())
_setDeckSlot(8);
}
if(getDeckSlot() != 9) {
int[][] slotTwoPixels = {
{ 506, 497, 36, 144, 247 },
{ 526, 497, 36, 144, 247 }
};
if((new PixelGroupTest(_image, slotTwoPixels)).passedOr())
_setDeckSlot(9);
}
}
private void _testForDefeat() {
int[][] tests = {
{ 745, 219, 164, 162, 155 },
{ 344, 383, 134, 153, 239 },
{ 696, 357, 201, 197, 188 }
};
PixelGroupTest pxTest = new PixelGroupTest(_image, tests);
int[][] testsTwo = {
{ 347, 382, 129, 148, 236 },
{ 275, 345, 137, 138, 134 },
{ 537, 155, 235, 226, 67 }
};
PixelGroupTest pxTestTwo = new PixelGroupTest(_image, testsTwo);
int[][] testsThree = {
{ 347, 382, 129, 148, 236 },
{ 275, 345, 137, 138, 134 },
{ 537, 155, 235, 226, 67 }
};
PixelGroupTest pxTestThree = new PixelGroupTest(_image, testsThree);
if (pxTest.passed() || pxTestTwo.passed() || pxTestThree.passed()) {
_setScreen("Result");
_setResult("Defeat");
}
}
private void _testForClass(String className, int[][] pixelTests, boolean isYours) {
if((new PixelGroupTest(_image, pixelTests)).passed()) {
if(isYours)
_setYourClass(className);
else
_setOpponentClass(className);
}
}
private void _testForFindingOpponent() {
int[][] tests = {
{ 401, 143, 180, 122, 145 }, // title bar
{ 765, 583, 121, 72, 100 } // bottom bar
};
PixelGroupTest pxTest = new PixelGroupTest(_image, tests);
int[][] arenaTests = {
{ 393, 145, 205, 166, 135 }, // title bar
{ 819, 235, 109, 87, 79 },
{ 839, 585, 139, 113, 77 }
};
PixelGroupTest arenaPxTest = new PixelGroupTest(_image, arenaTests);
if (pxTest.passed() || arenaPxTest.passed()) {
_coin = false;
_yourClass = null;
_opponentClass = null;
_setScreen("Finding Opponent");
}
}
private void _testForMainMenuScreen() {
int[][] tests = {
{ 338, 453, 159, 96, 42 }, // box top
{ 211, 658, 228, 211, 116 }, // quest button exclamation mark
{ 513, 148, 36, 23, 24 } // dark vertical line in top center
};
if((new PixelGroupTest(_image, tests)).passed())
_setScreen("Main Menu");
}
private void _testForMatchStartScreen() {
int[][] tests = {
{ 403, 487, 201, 173, 94 }, // title bar
{ 946, 149, 203, 174, 96 } // bottom bar
};
if ((new PixelGroupTest(_image, tests)).passed()) {
_setScreen("Match Start");
}
}
private void _testForNewArenaRun() {
int[][] tests = {
{ 298, 170, 255, 239, 148 }, // key
//{ 492, 204, 128, 79, 47 }, // key stem
{ 382, 294, 255, 255, 255 }, // zero
{ 393, 281, 255, 255, 255 }, // zero
{ 321, 399, 209, 179, 127 }, // no red x
};
if ((new PixelGroupTest(_image, tests)).passed()) {
setIsNewArena(true);
}
}
private void _testForOpponentClass() {
// Druid Test
int[][] druidTests = {
{ 743, 118, 205, 255, 242 },
{ 882, 141, 231, 255, 252 },
{ 766, 215, 203, 160, 198 }
};
_testForClass("Druid", druidTests, false);
// Hunter Test
int[][] hunterTests = {
{ 825, 66, 173, 178, 183 },
{ 818, 175, 141, 37, 0 },
{ 739, 309, 216, 214, 211 }
};
_testForClass("Hunter", hunterTests, false);
// Mage Test
int[][] mageTests = {
{ 790, 68, 88, 23, 99 },
{ 788, 312, 215, 188, 177 },
{ 820, 247, 53, 64, 82 }
};
_testForClass("Mage", mageTests, false);
// Paladin Test
int[][] paladinTests = {
{ 895, 213, 255, 247, 147 },
{ 816, 301, 125, 237, 255 },
{ 767, 82, 133, 107, 168 }
};
_testForClass("Paladin", paladinTests, false);
// Priest Test
int[][] priestTests = {
{ 724, 189, 255, 236, 101 },
{ 796, 243, 58, 72, 138 },
{ 882, 148, 27, 20, 38 }
};
_testForClass("Priest", priestTests, false);
// Rogue Test
int[][] rogueTests = {
{ 889, 254, 132, 196, 72 },
{ 790, 273, 88, 21, 34 },
{ 841, 73, 100, 109, 183 }
};
_testForClass("Rogue", rogueTests, false);
// Shaman Test
int[][] shamanTests = {
{ 748, 94, 5, 50, 100 },
{ 887, 169, 234, 50, 32 },
{ 733, 206, 186, 255, 255 }
};
_testForClass("Shaman", shamanTests, false);
// Warlock Test
int[][] warlockTests = {
{ 711, 203, 127, 142, 36 },
{ 832, 264, 240, 244, 252 },
{ 832, 65, 98, 129, 0 }
};
_testForClass("Warlock", warlockTests, false);
// Warrior Test
int[][] warriorTests = {
{ 795, 64, 37, 4, 0 },
{ 780, 83, 167, 23, 4 },
{ 809, 92, 255, 247, 227 }
};
_testForClass("Warrior", warriorTests, false);
}
private void _testForPlayingScreen() {
// check for normal play boards
int[][] tests = {
{ 336, 203, 231, 198, 124 },
{ 763, 440, 234, 198, 124 }
};
PixelGroupTest normalPxTest = new PixelGroupTest(_image, tests);
// check for lighter orc board
int[][] orcBoardTests = {
{ 906, 283, 222, 158, 94 },
{ 120, 468, 195, 134, 78 }
};
PixelGroupTest orcPxTest = new PixelGroupTest(_image, orcBoardTests);
if (normalPxTest.passed() || orcPxTest.passed())
_setScreen("Playing");
}
private void _testForPlayScreen() {
int[][] tests = {
{ 543, 130, 121, 32, 22 }, // play mode red background
{ 254, 33, 197, 173, 132 }, // mode title light brown background
{ 956, 553, 24, 8, 8 },
{ 489, 688, 68, 65, 63 }
};
if((new PixelGroupTest(_image, tests)).passed())
_setScreen("Play");
}
private void _testForRankedMode() {
int[][] tests = {
{ 833, 88, 220, 255, 255 }, // ranked blue
{ 698, 120, 56, 16, 8 } // casual off
};
if((new PixelGroupTest(_image, tests)).passed())
_setMode("Ranked");
}
private void _testForVictory() {
int[][] tests = {
{ 334, 504, 88, 101, 192 },
{ 683, 510, 74, 88, 173 },
{ 549, 162, 255, 224, 119 }
};
PixelGroupTest pxTest = new PixelGroupTest(_image, tests);
int[][] testsTwo = {
{ 347, 469, 85, 102, 203 },
{ 737, 339, 63, 76, 148 },
{ 774, 214, 253, 243, 185 }
};
PixelGroupTest pxTestTwo = new PixelGroupTest(_image, testsTwo);
int[][] testsThree = {
{ 370, 528, 66, 81, 165 },
{ 690, 553, 63, 76, 162 },
{ 761, 228, 249, 234, 163 }
};
PixelGroupTest pxTestThree = new PixelGroupTest(_image, testsThree);
if(pxTest.passed() || pxTestTwo.passed() || pxTestThree.passed()) {
_setScreen("Result");
_setResult("Victory");
}
}
private void _testForYourClass() {
// Druid Test
int[][] druidTests = {
{ 225, 480, 210, 255, 246 },
{ 348, 510, 234, 255, 251 },
{ 237, 607, 193, 155, 195 }
};
_testForClass("Druid", druidTests, true);
// Hunter Test
int[][] hunterTests = {
{ 289, 438, 173, 161, 147 },
{ 366, 554, 250, 200, 81 },
{ 210, 675, 209, 209, 211 }
};
_testForClass("Hunter", hunterTests, true);
// Mage Test
int[][] mageTests = {
{ 259, 439, 96, 31, 102 },
{ 294, 677, 219, 210, 193 },
{ 216, 591, 0, 0, 56 }
};
_testForClass("Mage", mageTests, true);
// Paladin Test
int[][] paladinTests = {
{ 249, 447, 133, 105, 165 },
{ 304, 671, 74, 146, 234 },
{ 368, 581, 244, 238, 141 }
};
_testForClass("Paladin", paladinTests, true);
// Priest Test
int[][] priestTests = {
{ 229, 491, 180, 178, 166 },
{ 256, 602, 82, 104, 204 },
{ 350, 611, 22, 23, 27 }
};
_testForClass("Priest", priestTests, true);
// Rogue Test
int[][] rogueTests = {
{ 309, 446, 91, 107, 175 },
{ 291, 468, 187, 37, 25 },
{ 362, 623, 122, 186, 67 }
};
_testForClass("Rogue", rogueTests, true);
// Shaman Test
int[][] shamanTests = {
{ 223, 458, 4, 46, 93 },
{ 360, 533, 213, 32, 6 },
{ 207, 578, 177, 245, 249 }
};
_testForClass("Shaman", shamanTests, true);
// Warlock Test
int[][] warlockTests = {
{ 301, 435, 104, 138, 8 },
{ 265, 493, 221, 51, 32 },
{ 294, 680, 60, 75, 182 }
};
_testForClass("Warlock", warlockTests, true);
}
}
|
package nl.hsac.fitnesse.fixture.slim.web;
import fitnesse.slim.fixtureInteraction.FixtureInteraction;
import nl.hsac.fitnesse.fixture.slim.SlimFixture;
import nl.hsac.fitnesse.fixture.slim.SlimFixtureException;
import nl.hsac.fitnesse.fixture.slim.StopTestException;
import nl.hsac.fitnesse.fixture.slim.web.annotation.TimeoutPolicy;
import nl.hsac.fitnesse.fixture.slim.web.annotation.WaitUntil;
import nl.hsac.fitnesse.fixture.util.BinaryHttpResponse;
import nl.hsac.fitnesse.fixture.util.FileUtil;
import nl.hsac.fitnesse.fixture.util.HttpResponse;
import nl.hsac.fitnesse.fixture.util.ReflectionHelper;
import nl.hsac.fitnesse.fixture.util.selenium.ListItemBy;
import nl.hsac.fitnesse.fixture.util.selenium.PageSourceSaver;
import nl.hsac.fitnesse.fixture.util.selenium.SeleniumHelper;
import nl.hsac.fitnesse.fixture.util.selenium.by.ContainerBy;
import nl.hsac.fitnesse.fixture.util.selenium.by.GridBy;
import nl.hsac.fitnesse.fixture.util.selenium.by.OptionBy;
import nl.hsac.fitnesse.fixture.util.selenium.by.TextBy;
import nl.hsac.fitnesse.fixture.util.selenium.by.XPathBy;
import nl.hsac.fitnesse.slim.interaction.ExceptionHelper;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.apache.commons.text.StringEscapeUtils;
import org.openqa.selenium.Alert;
import org.openqa.selenium.By;
import org.openqa.selenium.Cookie;
import org.openqa.selenium.Dimension;
import org.openqa.selenium.Keys;
import org.openqa.selenium.SearchContext;
import org.openqa.selenium.TimeoutException;
import org.openqa.selenium.UnhandledAlertException;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebDriverException;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.ui.ExpectedCondition;
import org.openqa.selenium.support.ui.Select;
import org.openqa.selenium.support.ui.WebDriverWait;
import java.io.File;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import java.util.function.Function;
import java.util.function.Supplier;
public class BrowserTest extends SlimFixture {
private SeleniumHelper seleniumHelper = getEnvironment().getSeleniumHelper();
private ReflectionHelper reflectionHelper = getEnvironment().getReflectionHelper();
private NgBrowserTest ngBrowserTest;
private boolean implicitWaitForAngular = false;
private boolean implicitFindInFrames = true;
private int secondsBeforeTimeout;
private int secondsBeforePageLoadTimeout;
private int waitAfterScroll = 150;
private String screenshotBase = new File(filesDir, "screenshots").getPath() + "/";
private String screenshotHeight = "200";
private String downloadBase = new File(filesDir, "downloads").getPath() + "/";
private String pageSourceBase = new File(filesDir, "pagesources").getPath() + "/";
@Override
protected void beforeInvoke(Method method, Object[] arguments) {
super.beforeInvoke(method, arguments);
waitForAngularIfNeeded(method);
}
@Override
protected Object invoke(final FixtureInteraction interaction, final Method method, final Object[] arguments)
throws Throwable {
Object result;
WaitUntil waitUntil = reflectionHelper.getAnnotation(WaitUntil.class, method);
if (waitUntil == null) {
result = superInvoke(interaction, method, arguments);
} else {
result = invokedWrappedInWaitUntil(waitUntil, interaction, method, arguments);
}
return result;
}
protected Object invokedWrappedInWaitUntil(WaitUntil waitUntil, final FixtureInteraction interaction, final Method method, final Object[] arguments) {
ExpectedCondition<Object> condition = new ExpectedCondition<Object>() {
@Override
public Object apply(WebDriver webDriver) {
try {
return superInvoke(interaction, method, arguments);
} catch (Throwable e) {
Throwable realEx = ExceptionHelper.stripReflectionException(e);
if (realEx instanceof RuntimeException) {
throw (RuntimeException) realEx;
} else if (realEx instanceof Error) {
throw (Error) realEx;
} else {
throw new RuntimeException(realEx);
}
}
}
};
condition = wrapConditionForFramesIfNeeded(condition);
Object result;
switch (waitUntil.value()) {
case STOP_TEST:
result = waitUntilOrStop(condition);
break;
case RETURN_NULL:
result = waitUntilOrNull(condition);
break;
case RETURN_FALSE:
result = waitUntilOrNull(condition) != null;
break;
case THROW:
default:
result = waitUntil(condition);
break;
}
return result;
}
protected Object superInvoke(FixtureInteraction interaction, Method method, Object[] arguments) throws Throwable {
return super.invoke(interaction, method, arguments);
}
/**
* Determines whether the current method might require waiting for angular given the currently open site,
* and ensure it does if needed.
* @param method
*/
protected void waitForAngularIfNeeded(Method method) {
if (isImplicitWaitForAngularEnabled()) {
try {
if (ngBrowserTest == null) {
ngBrowserTest = new NgBrowserTest();
}
if (ngBrowserTest.requiresWaitForAngular(method) && currentSiteUsesAngular()) {
try {
ngBrowserTest.waitForAngularRequestsToFinish();
} catch (Exception e) {
// if something goes wrong, just use normal behavior: continue to invoke()
System.err.print("Found Angular, but encountered an error while waiting for it to be ready. ");
e.printStackTrace();
}
}
} catch (UnhandledAlertException e) {
System.err.println("Cannot determine whether Angular is present while alert is active.");
} catch (Exception e) {
// if something goes wrong, just use normal behavior: continue to invoke()
System.err.print("Error while determining whether Angular is present. ");
e.printStackTrace();
}
}
}
protected boolean currentSiteUsesAngular() {
Object windowHasAngular = getSeleniumHelper().executeJavascript("return window.angular?1:0;");
return Long.valueOf(1).equals(windowHasAngular);
}
@Override
protected Throwable handleException(Method method, Object[] arguments, Throwable t) {
Throwable result;
if (t instanceof UnhandledAlertException) {
UnhandledAlertException e = (UnhandledAlertException) t;
String alertText = e.getAlertText();
if (alertText == null) {
alertText = alertText();
}
String msgBase = "Unhandled alert: alert must be confirmed or dismissed before test can continue. Alert text: " + alertText;
String msg = getSlimFixtureExceptionMessage("alertException", msgBase, e);
result = new StopTestException(false, msg, t);
} else if (t instanceof SlimFixtureException) {
result = super.handleException(method, arguments, t);
} else {
String msg = getSlimFixtureExceptionMessage("exception", null, t);
result = new SlimFixtureException(false, msg, t);
}
return result;
}
public BrowserTest() {
secondsBeforeTimeout(seleniumHelper.getDefaultTimeoutSeconds());
ensureActiveTabIsNotClosed();
}
public BrowserTest(int secondsBeforeTimeout) {
secondsBeforeTimeout(secondsBeforeTimeout);
ensureActiveTabIsNotClosed();
}
public boolean open(String address) {
final String url = getUrl(address);
try {
getNavigation().to(url);
} catch (TimeoutException e) {
handleTimeoutException(e);
} finally {
switchToDefaultContent();
}
waitUntil(new ExpectedCondition<Boolean>() {
@Override
public Boolean apply(WebDriver webDriver) {
String readyState = getSeleniumHelper().executeJavascript("return document.readyState").toString();
// IE 7 is reported to return "loaded"
boolean done = "complete".equalsIgnoreCase(readyState) || "loaded".equalsIgnoreCase(readyState);
if (!done) {
System.err.printf("Open of %s returned while document.readyState was %s", url, readyState);
System.err.println();
}
return done;
}
});
return true;
}
public String location() {
return driver().getCurrentUrl();
}
public boolean back() {
getNavigation().back();
switchToDefaultContent();
// firefox sometimes prevents immediate back, if previous page was reached via POST
waitMilliseconds(500);
WebElement element = findElement(By.id("errorTryAgain"));
if (element != null) {
element.click();
// don't use confirmAlert as this may be overridden in subclass and to get rid of the
// firefox pop-up we need the basic behavior
getSeleniumHelper().getAlert().accept();
}
return true;
}
public boolean forward() {
getNavigation().forward();
switchToDefaultContent();
return true;
}
public boolean refresh() {
getNavigation().refresh();
switchToDefaultContent();
return true;
}
private WebDriver.Navigation getNavigation() {
return getSeleniumHelper().navigate();
}
@WaitUntil(TimeoutPolicy.RETURN_NULL)
public String alertText() {
Alert alert = getAlert();
String text = null;
if (alert != null) {
text = alert.getText();
}
return text;
}
@WaitUntil
public boolean confirmAlert() {
Alert alert = getAlert();
boolean result = false;
if (alert != null) {
alert.accept();
onAlertHandled(true);
result = true;
}
return result;
}
@WaitUntil
public boolean dismissAlert() {
Alert alert = getAlert();
boolean result = false;
if (alert != null) {
alert.dismiss();
onAlertHandled(false);
result = true;
}
return result;
}
/**
* Called when an alert is either dismissed or accepted.
* @param accepted true if the alert was accepted, false if dismissed.
*/
protected void onAlertHandled(boolean accepted) {
// if we were looking in nested frames, we could not go back to original frame
// because of the alert. Ensure we do so now the alert is handled.
getSeleniumHelper().resetFrameDepthOnAlertError();
}
protected Alert getAlert() {
return getSeleniumHelper().getAlert();
}
public boolean openInNewTab(String url) {
String cleanUrl = getUrl(url);
final int tabCount = tabCount();
getSeleniumHelper().executeJavascript("window.open('%s', '_blank')", cleanUrl);
// ensure new window is open
waitUntil(new ExpectedCondition<Boolean>() {
@Override
public Boolean apply(WebDriver webDriver) {
return tabCount() > tabCount;
}
});
return switchToNextTab();
}
@WaitUntil
public boolean switchToNextTab() {
boolean result = false;
List<String> tabs = getTabHandles();
if (tabs.size() > 1) {
int currentTab = getCurrentTabIndex(tabs);
int nextTab = currentTab + 1;
if (nextTab == tabs.size()) {
nextTab = 0;
}
goToTab(tabs, nextTab);
result = true;
}
return result;
}
@WaitUntil
public boolean switchToPreviousTab() {
boolean result = false;
List<String> tabs = getTabHandles();
if (tabs.size() > 1) {
int currentTab = getCurrentTabIndex(tabs);
int nextTab = currentTab - 1;
if (nextTab < 0) {
nextTab = tabs.size() - 1;
}
goToTab(tabs, nextTab);
result = true;
}
return result;
}
public boolean closeTab() {
boolean result = false;
List<String> tabs = getTabHandles();
int currentTab = getCurrentTabIndex(tabs);
int tabToGoTo = -1;
if (currentTab > 0) {
tabToGoTo = currentTab - 1;
} else {
if (tabs.size() > 1) {
tabToGoTo = 1;
}
}
if (tabToGoTo > -1) {
WebDriver driver = driver();
driver.close();
goToTab(tabs, tabToGoTo);
result = true;
}
return result;
}
public void ensureOnlyOneTab() {
ensureActiveTabIsNotClosed();
int tabCount = tabCount();
for (int i = 1; i < tabCount; i++) {
closeTab();
}
}
public boolean ensureActiveTabIsNotClosed() {
boolean result = false;
List<String> tabHandles = getTabHandles();
int currentTab = getCurrentTabIndex(tabHandles);
if (currentTab < 0) {
result = true;
goToTab(tabHandles, 0);
}
return result;
}
public int tabCount() {
return getTabHandles().size();
}
public int currentTabIndex() {
return getCurrentTabIndex(getTabHandles()) + 1;
}
protected int getCurrentTabIndex(List<String> tabHandles) {
return getSeleniumHelper().getCurrentTabIndex(tabHandles);
}
protected void goToTab(List<String> tabHandles, int indexToGoTo) {
getSeleniumHelper().goToTab(tabHandles, indexToGoTo);
}
protected List<String> getTabHandles() {
return getSeleniumHelper().getTabHandles();
}
/**
* Activates main/top-level iframe (i.e. makes it the current frame).
*/
public void switchToDefaultContent() {
getSeleniumHelper().switchToDefaultContent();
clearSearchContext();
}
/**
* Activates specified child frame of current iframe.
* @param technicalSelector selector to find iframe.
* @return true if iframe was found.
*/
public boolean switchToFrame(String technicalSelector) {
boolean result = false;
WebElement iframe = getElement(technicalSelector);
if (iframe != null) {
getSeleniumHelper().switchToFrame(iframe);
result = true;
}
return result;
}
/**
* Activates parent frame of current iframe.
* Does nothing if when current frame is the main/top-level one.
*/
public void switchToParentFrame() {
getSeleniumHelper().switchToParentFrame();
}
public String pageTitle() {
return getSeleniumHelper().getPageTitle();
}
/**
* @return current page's content type.
*/
public String pageContentType() {
String result = null;
Object ct = getSeleniumHelper().executeJavascript("return document.contentType;");
if (ct != null) {
result = ct.toString();
}
return result;
}
/**
* Replaces content at place by value.
* @param value value to set.
* @param place element to set value on.
* @return true, if element was found.
*/
@WaitUntil
public boolean enterAs(String value, String place) {
return enterAsIn(value, place, null);
}
/**
* Replaces content at place by value.
* @param value value to set.
* @param place element to set value on.
* @param container element containing place.
* @return true, if element was found.
*/
@WaitUntil
public boolean enterAsIn(String value, String place, String container) {
return enter(value, place, container, true);
}
/**
* Adds content to place.
* @param value value to add.
* @param place element to add value to.
* @return true, if element was found.
*/
@WaitUntil
public boolean enterFor(String value, String place) {
return enterForIn(value, place, null);
}
/**
* Adds content to place.
* @param value value to add.
* @param place element to add value to.
* @param container element containing place.
* @return true, if element was found.
*/
@WaitUntil
public boolean enterForIn(String value, String place, String container) {
return enter(value, place, container, false);
}
protected boolean enter(String value, String place, boolean shouldClear) {
return enter(value, place, null, shouldClear);
}
protected boolean enter(String value, String place, String container, boolean shouldClear) {
WebElement element = getElementToSendValue(place, container);
return enter(element, value, shouldClear);
}
protected boolean enter(WebElement element, String value, boolean shouldClear) {
boolean result = element != null && isInteractable(element);
if (result) {
if (isSelect(element)) {
result = clickSelectOption(element, value);
} else {
if (shouldClear) {
clear(element);
}
sendValue(element, value);
}
}
return result;
}
@WaitUntil
public boolean enterDateAs(String date, String place) {
WebElement element = getElementToSendValue(place);
boolean result = element != null && isInteractable(element);
if (result) {
getSeleniumHelper().fillDateInput(element, date);
}
return result;
}
protected WebElement getElementToSendValue(String place) {
return getElementToSendValue(place, null);
}
protected WebElement getElementToSendValue(String place, String container) {
return getElement(place, container);
}
/**
* Simulates pressing the 'Tab' key.
* @return true, if an element was active the key could be sent to.
*/
public boolean pressTab() {
return sendKeysToActiveElement(Keys.TAB);
}
/**
* Simulates pressing the 'Enter' key.
* @return true, if an element was active the key could be sent to.
*/
public boolean pressEnter() {
return sendKeysToActiveElement(Keys.ENTER);
}
/**
* Simulates pressing the 'Esc' key.
* @return true, if an element was active the key could be sent to.
*/
public boolean pressEsc() {
return sendKeysToActiveElement(Keys.ESCAPE);
}
/**
* Simulates typing a text to the current active element.
* @param text text to type.
* @return true, if an element was active the text could be sent to.
*/
public boolean type(String text) {
String value = cleanupValue(text);
return sendKeysToActiveElement(value);
}
public boolean press(String key) {
CharSequence s;
String[] parts = key.split("\\s*\\+\\s*");
if (parts.length > 1
&& !"".equals(parts[0]) && !"".equals(parts[1])) {
CharSequence[] sequence = new CharSequence[parts.length];
for (int i = 0; i < parts.length; i++) {
sequence[i] = parseKey(parts[i]);
}
s = Keys.chord(sequence);
} else {
s = parseKey(key);
}
return sendKeysToActiveElement(s);
}
protected CharSequence parseKey(String key) {
CharSequence s;
try {
s = Keys.valueOf(key.toUpperCase());
} catch (IllegalArgumentException e) {
s = key;
}
return s;
}
/**
* Simulates pressing keys.
* @param keys keys to press.
* @return true, if an element was active the keys could be sent to.
*/
protected boolean sendKeysToActiveElement(CharSequence keys) {
boolean result = false;
WebElement element = getSeleniumHelper().getActiveElement();
if (element != null) {
element.sendKeys(keys);
result = true;
}
return result;
}
/**
* Sends Fitnesse cell content to element.
* @param element element to call sendKeys() on.
* @param value cell content.
*/
protected void sendValue(WebElement element, String value) {
if (StringUtils.isNotEmpty(value)) {
String keys = cleanupValue(value);
element.sendKeys(keys);
}
}
@WaitUntil
public boolean selectAs(String value, String place) {
return selectFor(value, place);
}
@WaitUntil
public boolean selectFor(String value, String place) {
WebElement element = getElementToSelectFor(place);
return clickSelectOption(element, value);
}
@WaitUntil
public boolean selectForIn(String value, String place, String container) {
return doInContainer(container, () -> selectFor(value, place));
}
@WaitUntil
public boolean enterForHidden(final String value, final String idOrName) {
return getSeleniumHelper().setHiddenInputValue(idOrName, value);
}
protected WebElement getElementToSelectFor(String selectPlace) {
return getElement(selectPlace);
}
protected boolean clickSelectOption(WebElement element, String optionValue) {
boolean result = false;
if (element != null) {
if (isSelect(element)) {
optionValue = cleanupValue(optionValue);
By optionBy = new OptionBy(optionValue);
WebElement option = optionBy.findElement(element);
if (option != null) {
result = clickElement(option);
}
}
}
return result;
}
@WaitUntil
public boolean click(final String place) {
return clickImp(place, null);
}
@WaitUntil(TimeoutPolicy.RETURN_FALSE)
public boolean clickIfAvailable(String place) {
return clickIfAvailableIn(place, null);
}
@WaitUntil(TimeoutPolicy.RETURN_FALSE)
public boolean clickIfAvailableIn(String place, String container) {
return clickImp(place, container);
}
@WaitUntil
public boolean clickIn(String place, String container) {
return clickImp(place, container);
}
protected boolean clickImp(String place, String container) {
boolean result = false;
place = cleanupValue(place);
try {
WebElement element = getElementToClick(place, container);
result = clickElement(element);
} catch (WebDriverException e) {
// if other element hides the element (in Chrome) an exception is thrown
String msg = e.getMessage();
if (msg == null || !msg.contains("Other element would receive the click")) {
throw e;
}
}
return result;
}
@WaitUntil
public boolean doubleClick(String place) {
return doubleClickIn(place, null);
}
@WaitUntil
public boolean doubleClickIn(String place, String container) {
WebElement element = getElementToClick(place, container);
return doubleClick(element);
}
protected boolean doubleClick(WebElement element) {
boolean result = false;
if (element != null) {
scrollIfNotOnScreen(element);
if (isInteractable(element)) {
getSeleniumHelper().doubleClick(element);
result = true;
}
}
return result;
}
@WaitUntil
public boolean rightClick(String place) {
return rightClickIn(place, null);
}
@WaitUntil
public boolean rightClickIn(String place, String container) {
WebElement element = getElementToClick(place, container);
return rightClick(element);
}
protected boolean rightClick(WebElement element) {
boolean result = false;
if (element != null) {
scrollIfNotOnScreen(element);
if (isInteractable(element)) {
getSeleniumHelper().rightClick(element);
result = true;
}
}
return result;
}
@WaitUntil
public boolean dragAndDropTo(String source, String destination) {
WebElement sourceElement = getElementToClick(source);
WebElement destinationElement = getElementToClick(destination);
return dragAndDropTo(sourceElement, destinationElement);
}
protected boolean dragAndDropTo(WebElement sourceElement, WebElement destinationElement) {
boolean result = false;
if ((sourceElement != null) && (destinationElement != null)) {
scrollIfNotOnScreen(sourceElement);
if (isInteractable(sourceElement) && destinationElement.isDisplayed()) {
getSeleniumHelper().dragAndDrop(sourceElement, destinationElement);
result = true;
}
}
return result;
}
protected WebElement getElementToClick(String place) {
return getSeleniumHelper().getElementToClick(place);
}
protected WebElement getElementToClick(String place, String container) {
return doInContainer(container, () -> getElementToClick(place));
}
protected <T> T doInContainer(String container, Supplier<T> action) {
T result = null;
if (container == null) {
result = action.get();
} else {
WebElement containerElement = getContainerElement(container);
if (containerElement != null) {
result = doInContainer(containerElement, action);
}
}
return result;
}
protected <T> T doInContainer(WebElement container, Supplier<T> action) {
return getSeleniumHelper().doInContext(container, action);
}
@WaitUntil
public boolean setSearchContextTo(String container) {
boolean result = false;
WebElement containerElement = getContainerElement(container);
if (containerElement != null) {
setSearchContextTo(containerElement);
result = true;
}
return result;
}
protected void setSearchContextTo(SearchContext containerElement) {
getSeleniumHelper().setCurrentContext(containerElement);
}
public void clearSearchContext() {
getSeleniumHelper().setCurrentContext(null);
}
protected WebElement getContainerElement(String container) {
return findByTechnicalSelectorOr(container, this::getContainerImpl);
}
protected WebElement getContainerImpl(String container) {
return findElement(ContainerBy.heuristic(container));
}
protected boolean clickElement(WebElement element) {
boolean result = false;
if (element != null) {
scrollIfNotOnScreen(element);
if (isInteractable(element)) {
element.click();
result = true;
}
}
return result;
}
protected boolean isInteractable(WebElement element) {
return getSeleniumHelper().isInteractable(element);
}
@WaitUntil(TimeoutPolicy.STOP_TEST)
public boolean waitForPage(String pageName) {
return pageTitle().equals(pageName);
}
public boolean waitForTagWithText(String tagName, String expectedText) {
return waitForElementWithText(By.tagName(tagName), expectedText);
}
public boolean waitForClassWithText(String cssClassName, String expectedText) {
return waitForElementWithText(By.className(cssClassName), expectedText);
}
protected boolean waitForElementWithText(final By by, String expectedText) {
final String textToLookFor = cleanExpectedValue(expectedText);
return waitUntilOrStop(new ExpectedCondition<Boolean>() {
@Override
public Boolean apply(WebDriver webDriver) {
boolean ok = false;
List<WebElement> elements = webDriver.findElements(by);
if (elements != null) {
for (WebElement element : elements) {
// we don't want stale elements to make single
// element false, but instead we stop processing
// current list and do a new findElements
ok = hasText(element, textToLookFor);
if (ok) {
// no need to continue to check other elements
break;
}
}
}
return ok;
}
});
}
protected String cleanExpectedValue(String expectedText) {
return cleanupValue(expectedText);
}
protected boolean hasText(WebElement element, String textToLookFor) {
boolean ok;
String actual = getElementText(element);
if (textToLookFor == null) {
ok = actual == null;
} else {
if (StringUtils.isEmpty(actual)) {
String value = element.getAttribute("value");
if (!StringUtils.isEmpty(value)) {
actual = value;
}
}
if (actual != null) {
actual = actual.trim();
}
ok = textToLookFor.equals(actual);
}
return ok;
}
@WaitUntil(TimeoutPolicy.STOP_TEST)
public boolean waitForClass(String cssClassName) {
boolean ok = false;
WebElement element = findElement(By.className(cssClassName));
if (element != null) {
ok = true;
}
return ok;
}
@WaitUntil(TimeoutPolicy.STOP_TEST)
public boolean waitForVisible(String place) {
return waitForVisibleIn(place, null);
}
@WaitUntil(TimeoutPolicy.STOP_TEST)
public boolean waitForVisibleIn(String place, String container) {
Boolean result = Boolean.FALSE;
WebElement element = getElementToCheckVisibility(place, container);
if (element != null) {
scrollIfNotOnScreen(element);
result = element.isDisplayed();
}
return result;
}
/**
* @deprecated use #waitForVisible(xpath=) instead
*/
@Deprecated
public boolean waitForXPathVisible(String xPath) {
By by = By.xpath(xPath);
return waitForVisible(by);
}
@Deprecated
protected boolean waitForVisible(final By by) {
return waitUntilOrStop(new ExpectedCondition<Boolean>() {
@Override
public Boolean apply(WebDriver webDriver) {
Boolean result = Boolean.FALSE;
WebElement element = findElement(by);
if (element != null) {
scrollIfNotOnScreen(element);
result = element.isDisplayed();
}
return result;
}
});
}
@WaitUntil(TimeoutPolicy.RETURN_NULL)
public String valueOf(String place) {
return valueFor(place);
}
@WaitUntil(TimeoutPolicy.RETURN_NULL)
public String valueFor(String place) {
return valueForIn(place, null);
}
@WaitUntil(TimeoutPolicy.RETURN_NULL)
public String valueOfIn(String place, String container) {
return valueForIn(place, container);
}
@WaitUntil(TimeoutPolicy.RETURN_NULL)
public String valueForIn(String place, String container) {
WebElement element = getElementToRetrieveValue(place, container);
return valueFor(element);
}
@WaitUntil(TimeoutPolicy.RETURN_NULL)
public String normalizedValueOf(String place) {
return normalizedValueFor(place);
}
@WaitUntil(TimeoutPolicy.RETURN_NULL)
public String normalizedValueFor(String place) {
return normalizedValueForIn(place, null);
}
@WaitUntil(TimeoutPolicy.RETURN_NULL)
public String normalizedValueOfIn(String place, String container) {
return normalizedValueForIn(place, container);
}
@WaitUntil(TimeoutPolicy.RETURN_NULL)
public String normalizedValueForIn(String place, String container) {
String value = valueForIn(place, container);
return XPathBy.getNormalizedText(value);
}
@WaitUntil(TimeoutPolicy.RETURN_NULL)
public String tooltipFor(String place) {
return tooltipForIn(place, null);
}
@WaitUntil(TimeoutPolicy.RETURN_NULL)
public String tooltipForIn(String place, String container) {
return valueOfAttributeOnIn("title", place, container);
}
@WaitUntil
public String targetOfLink(String place) {
WebElement linkElement = getSeleniumHelper().getLink(place);
return getLinkTarget(linkElement);
}
protected String getLinkTarget(WebElement linkElement) {
String target = null;
if (linkElement != null) {
target = linkElement.getAttribute("href");
}
return target;
}
@WaitUntil(TimeoutPolicy.RETURN_NULL)
public String valueOfAttributeOn(String attribute, String place) {
return valueOfAttributeOnIn(attribute, place, null);
}
@WaitUntil(TimeoutPolicy.RETURN_NULL)
public String valueOfAttributeOnIn(String attribute, String place, String container) {
String result = null;
WebElement element = getElementToRetrieveValue(place, container);
if (element != null) {
result = element.getAttribute(attribute);
}
return result;
}
protected WebElement getElementToRetrieveValue(String place, String container) {
return getElement(place, container);
}
protected String valueFor(By by) {
WebElement element = getSeleniumHelper().findElement(by);
return valueFor(element);
}
protected String valueFor(WebElement element) {
String result = null;
if (element != null) {
if (isSelect(element)) {
Select s = new Select(element);
List<WebElement> options = s.getAllSelectedOptions();
if (options.size() > 0) {
result = getElementText(options.get(0));
}
} else {
String elementType = element.getAttribute("type");
if ("checkbox".equals(elementType)
|| "radio".equals(elementType)) {
result = String.valueOf(element.isSelected());
} else if ("li".equalsIgnoreCase(element.getTagName())) {
result = getElementText(element);
} else {
result = element.getAttribute("value");
if (result == null) {
result = getElementText(element);
}
}
}
}
return result;
}
private boolean isSelect(WebElement element) {
return "select".equalsIgnoreCase(element.getTagName());
}
@WaitUntil(TimeoutPolicy.RETURN_NULL)
public ArrayList<String> valuesOf(String place) {
return valuesFor(place);
}
@WaitUntil(TimeoutPolicy.RETURN_NULL)
public ArrayList<String> valuesOfIn(String place, String container) {
return valuesForIn(place, container);
}
@WaitUntil(TimeoutPolicy.RETURN_NULL)
public ArrayList<String> valuesFor(String place) {
return valuesForIn(place, null);
}
@WaitUntil(TimeoutPolicy.RETURN_NULL)
public ArrayList<String> valuesForIn(String place, String container) {
ArrayList<String> values = null;
WebElement element = getElementToRetrieveValue(place, container);
if (element != null) {
values = new ArrayList<String>();
String tagName = element.getTagName();
if ("ul".equalsIgnoreCase(tagName)
|| "ol".equalsIgnoreCase(tagName)) {
List<WebElement> items = element.findElements(By.tagName("li"));
for (WebElement item : items) {
if (item.isDisplayed()) {
values.add(getElementText(item));
}
}
} else if (isSelect(element)) {
Select s = new Select(element);
List<WebElement> options = s.getAllSelectedOptions();
for (WebElement item : options) {
values.add(getElementText(item));
}
} else {
values.add(valueFor(element));
}
}
return values;
}
@WaitUntil(TimeoutPolicy.RETURN_NULL)
public Integer numberFor(String place) {
Integer number = null;
WebElement element = findElement(ListItemBy.numbered(place));
if (element != null) {
scrollIfNotOnScreen(element);
number = getSeleniumHelper().getNumberFor(element);
}
return number;
}
@WaitUntil(TimeoutPolicy.RETURN_NULL)
public Integer numberForIn(String place, String container) {
return doInContainer(container, () -> numberFor(place));
}
public ArrayList<String> availableOptionsFor(String place) {
ArrayList<String> result = null;
WebElement element = getElementToSelectFor(place);
if (element != null) {
scrollIfNotOnScreen(element);
result = getSeleniumHelper().getAvailableOptions(element);
}
return result;
}
@WaitUntil
public boolean clear(String place) {
return clearIn(place, null);
}
@WaitUntil
public boolean clearIn(String place, String container) {
boolean result = false;
WebElement element = getElementToClear(place, container);
if (element != null) {
clear(element);
result = true;
}
return result;
}
protected void clear(WebElement element) {
element.clear();
}
protected WebElement getElementToClear(String place, String container) {
return getElementToSendValue(place, container);
}
@WaitUntil
public boolean enterAsInRowWhereIs(String value, String requestedColumnName, String selectOnColumn, String selectOnValue) {
By cellBy = GridBy.columnInRowWhereIs(requestedColumnName, selectOnColumn, selectOnValue);
WebElement element = findElement(cellBy);
return enter(element, value, true);
}
@WaitUntil(TimeoutPolicy.RETURN_NULL)
public String valueOfColumnNumberInRowNumber(int columnIndex, int rowIndex) {
By by = GridBy.coordinates(columnIndex, rowIndex);
return valueFor(by);
}
@WaitUntil(TimeoutPolicy.RETURN_NULL)
public String valueOfInRowNumber(String requestedColumnName, int rowIndex) {
By by = GridBy.columnInRow(requestedColumnName, rowIndex);
return valueFor(by);
}
@WaitUntil(TimeoutPolicy.RETURN_NULL)
public String valueOfInRowWhereIs(String requestedColumnName, String selectOnColumn, String selectOnValue) {
By by = GridBy.columnInRowWhereIs(requestedColumnName, selectOnColumn, selectOnValue);
return valueFor(by);
}
@WaitUntil(TimeoutPolicy.RETURN_FALSE)
public boolean rowExistsWhereIs(String selectOnColumn, String selectOnValue) {
return findElement(GridBy.rowWhereIs(selectOnColumn, selectOnValue)) != null;
}
@WaitUntil
public boolean clickInRowNumber(String place, int rowIndex) {
By rowBy = GridBy.rowNumber(rowIndex);
return clickInRow(rowBy, place);
}
@WaitUntil
public boolean clickInRowWhereIs(String place, String selectOnColumn, String selectOnValue) {
By rowBy = GridBy.rowWhereIs(selectOnColumn, selectOnValue);
return clickInRow(rowBy, place);
}
protected boolean clickInRow(By rowBy, String place) {
boolean result = false;
WebElement row = findElement(rowBy);
if (row != null) {
result = doInContainer(row, () -> click(place));
}
return result;
}
/**
* Downloads the target of a link in a grid's row.
* @param place which link to download.
* @param rowNumber (1-based) row number to retrieve link from.
* @return downloaded file if any, null otherwise.
*/
@WaitUntil
public String downloadFromRowNumber(String place, int rowNumber) {
return downloadFromRow(GridBy.linkInRow(place, rowNumber));
}
/**
* Downloads the target of a link in a grid, finding the row based on one of the other columns' value.
* @param place which link to download.
* @param selectOnColumn column header of cell whose value must be selectOnValue.
* @param selectOnValue value to be present in selectOnColumn to find correct row.
* @return downloaded file if any, null otherwise.
*/
@WaitUntil
public String downloadFromRowWhereIs(String place, String selectOnColumn, String selectOnValue) {
return downloadFromRow(GridBy.linkInRowWhereIs(place, selectOnColumn, selectOnValue));
}
protected String downloadFromRow(By linkBy) {
String result = null;
WebElement element = findElement(linkBy);
if (element != null) {
result = downloadLinkTarget(element);
}
return result;
}
protected WebElement getElement(String place) {
return getSeleniumHelper().getElement(place);
}
protected WebElement getElement(String place, String container) {
return doInContainer(container, () -> getElement(place));
}
/**
* @deprecated use #click(xpath=) instead.
*/
@WaitUntil
@Deprecated
public boolean clickByXPath(String xPath) {
WebElement element = findByXPath(xPath);
return clickElement(element);
}
/**
* @deprecated use #valueOf(xpath=) instead.
*/
@WaitUntil(TimeoutPolicy.RETURN_NULL)
@Deprecated
public String textByXPath(String xPath) {
return getTextByXPath(xPath);
}
protected String getTextByXPath(String xpathPattern, String... params) {
WebElement element = findByXPath(xpathPattern, params);
return getElementText(element);
}
/**
* @deprecated use #valueOf(css=.) instead.
*/
@WaitUntil(TimeoutPolicy.RETURN_NULL)
@Deprecated
public String textByClassName(String className) {
return getTextByClassName(className);
}
protected String getTextByClassName(String className) {
WebElement element = findByClassName(className);
return getElementText(element);
}
protected WebElement findByClassName(String className) {
By by = By.className(className);
return findElement(by);
}
protected WebElement findByXPath(String xpathPattern, String... params) {
return getSeleniumHelper().findByXPath(xpathPattern, params);
}
protected WebElement findByCss(String cssPattern, String... params) {
By by = getSeleniumHelper().byCss(cssPattern, params);
return findElement(by);
}
protected WebElement findByJavascript(String script, Object... parameters) {
By by = getSeleniumHelper().byJavascript(script, parameters);
return findElement(by);
}
protected List<WebElement> findAllByXPath(String xpathPattern, String... params) {
By by = getSeleniumHelper().byXpath(xpathPattern, params);
return findElements(by);
}
protected List<WebElement> findAllByCss(String cssPattern, String... params) {
By by = getSeleniumHelper().byCss(cssPattern, params);
return findElements(by);
}
protected List<WebElement> findAllByJavascript(String script, Object... parameters) {
By by = getSeleniumHelper().byJavascript(script, parameters);
return findElements(by);
}
protected List<WebElement> findElements(By by) {
return driver().findElements(by);
}
public void waitMilliSecondAfterScroll(int msToWait) {
waitAfterScroll = msToWait;
}
protected int getWaitAfterScroll() {
return waitAfterScroll;
}
protected String getElementText(WebElement element) {
String result = null;
if (element != null) {
scrollIfNotOnScreen(element);
result = getSeleniumHelper().getText(element);
}
return result;
}
/**
* Scrolls browser window so top of place becomes visible.
* @param place element to scroll to.
*/
@WaitUntil
public boolean scrollTo(String place) {
return scrollToIn(place, null);
}
/**
* Scrolls browser window so top of place becomes visible.
* @param place element to scroll to.
* @param container parent of place.
*/
@WaitUntil
public boolean scrollToIn(String place, String container) {
boolean result = false;
WebElement element = getElementToScrollTo(place, container);
if (element != null) {
scrollTo(element);
result = true;
}
return result;
}
protected WebElement getElementToScrollTo(String place, String container) {
return getElementToCheckVisibility(place, container);
}
/**
* Scrolls browser window so top of element becomes visible.
* @param element element to scroll to.
*/
protected void scrollTo(WebElement element) {
getSeleniumHelper().scrollTo(element);
waitAfterScroll(waitAfterScroll);
}
/**
* Wait after the scroll if needed
* @param msToWait amount of ms to wait after the scroll
*/
protected void waitAfterScroll(int msToWait) {
if (msToWait > 0) {
waitMilliseconds(msToWait);
}
}
/**
* Scrolls browser window if element is not currently visible so top of element becomes visible.
* @param element element to scroll to.
*/
protected void scrollIfNotOnScreen(WebElement element) {
if (!element.isDisplayed() || !isElementOnScreen(element)) {
scrollTo(element);
}
}
/**
* Determines whether element is enabled (i.e. can be clicked).
* @param place element to check.
* @return true if element is enabled.
*/
@WaitUntil(TimeoutPolicy.RETURN_FALSE)
public boolean isEnabled(String place) {
return isEnabledIn(place, null);
}
/**
* Determines whether element is enabled (i.e. can be clicked).
* @param place element to check.
* @param container parent of place.
* @return true if element is enabled.
*/
@WaitUntil(TimeoutPolicy.RETURN_FALSE)
public boolean isEnabledIn(String place, String container) {
boolean result = false;
WebElement element = getElementToCheckVisibility(place, container);
if (element != null) {
if ("label".equalsIgnoreCase(element.getTagName())) {
// for labels we want to know whether their target is enabled, not the label itself
WebElement labelTarget = getSeleniumHelper().getLabelledElement(element);
if (labelTarget != null) {
element = labelTarget;
}
}
result = element.isEnabled();
}
return result;
}
/**
* Determines whether element can be see in browser's window.
* @param place element to check.
* @return true if element is displayed and in viewport.
*/
@WaitUntil(TimeoutPolicy.RETURN_FALSE)
public boolean isVisible(String place) {
return isVisibleIn(place, null);
}
/**
* Determines whether element can be see in browser's window.
* @param place element to check.
* @param container parent of place.
* @return true if element is displayed and in viewport.
*/
@WaitUntil(TimeoutPolicy.RETURN_FALSE)
public boolean isVisibleIn(String place, String container) {
return isVisibleImpl(place, container, true);
}
/**
* Determines whether element is somewhere in browser's window.
* @param place element to check.
* @return true if element is displayed.
*/
@WaitUntil(TimeoutPolicy.RETURN_FALSE)
public boolean isVisibleOnPage(String place) {
return isVisibleOnPageIn(place, null);
}
/**
* Determines whether element is somewhere in browser's window.
* @param place element to check.
* @param container parent of place.
* @return true if element is displayed.
*/
@WaitUntil(TimeoutPolicy.RETURN_FALSE)
public boolean isVisibleOnPageIn(String place, String container) {
return isVisibleImpl(place, container, false);
}
protected boolean isVisibleImpl(String place, String container, boolean checkOnScreen) {
WebElement element = getElementToCheckVisibility(place, container);
return getSeleniumHelper().checkVisible(element, checkOnScreen);
}
public int numberOfTimesIsVisible(String text) {
return numberOfTimesIsVisibleInImpl(text, true);
}
public int numberOfTimesIsVisibleOnPage(String text) {
return numberOfTimesIsVisibleInImpl(text, false);
}
public int numberOfTimesIsVisibleIn(String text, String container) {
return doInContainer(container, () -> numberOfTimesIsVisible(text));
}
public int numberOfTimesIsVisibleOnPageIn(String text, String container) {
return doInContainer(container, () -> numberOfTimesIsVisibleOnPage(text));
}
protected int numberOfTimesIsVisibleInImpl(String text, boolean checkOnScreen) {
return getSeleniumHelper().countVisibleOccurrences(text, checkOnScreen);
}
protected WebElement getElementToCheckVisibility(String place) {
WebElement result = findElement(TextBy.partial(place));
if (result == null || !result.isDisplayed()) {
result = getElementToClick(place);
}
return result;
}
protected WebElement getElementToCheckVisibility(String place, String container) {
return doInContainer(container, () -> findByTechnicalSelectorOr(place, this::getElementToCheckVisibility));
}
/**
* Checks whether element is in browser's viewport.
* @param element element to check
* @return true if element is in browser's viewport.
*/
protected boolean isElementOnScreen(WebElement element) {
Boolean onScreen = getSeleniumHelper().isElementOnScreen(element);
return onScreen == null || onScreen.booleanValue();
}
@WaitUntil
public boolean hoverOver(String place) {
return hoverOverIn(place, null);
}
@WaitUntil
public boolean hoverOverIn(String place, String container) {
WebElement element = getElementToClick(place, container);
return hoverOver(element);
}
protected boolean hoverOver(WebElement element) {
boolean result = false;
if (element != null) {
scrollIfNotOnScreen(element);
if (element.isDisplayed()) {
getSeleniumHelper().hoverOver(element);
result = true;
}
}
return result;
}
/**
* @param timeout number of seconds before waitUntil() and waitForJavascriptCallback() throw TimeOutException.
*/
public void secondsBeforeTimeout(int timeout) {
secondsBeforeTimeout = timeout;
secondsBeforePageLoadTimeout(timeout);
int timeoutInMs = timeout * 1000;
getSeleniumHelper().setScriptWait(timeoutInMs);
}
/**
* @return number of seconds waitUntil() will wait at most.
*/
public int secondsBeforeTimeout() {
return secondsBeforeTimeout;
}
/**
* @param timeout number of seconds before waiting for a new page to load will throw a TimeOutException.
*/
public void secondsBeforePageLoadTimeout(int timeout) {
secondsBeforePageLoadTimeout = timeout;
int timeoutInMs = timeout * 1000;
getSeleniumHelper().setPageLoadWait(timeoutInMs);
}
/**
* @return number of seconds Selenium will wait at most for a request to load a page.
*/
public int secondsBeforePageLoadTimeout() {
return secondsBeforePageLoadTimeout;
}
/**
* Clears HTML5's localStorage (for the domain of the current open page in the browser).
*/
public void clearLocalStorage() {
getSeleniumHelper().executeJavascript("localStorage.clear();");
}
/**
* Deletes all cookies(for the domain of the current open page in the browser).
*/
public void deleteAllCookies() {
getSeleniumHelper().deleteAllCookies();
}
/**
* @param directory sets base directory where screenshots will be stored.
*/
public void screenshotBaseDirectory(String directory) {
if (directory.equals("")
|| directory.endsWith("/")
|| directory.endsWith("\\")) {
screenshotBase = directory;
} else {
screenshotBase = directory + "/";
}
}
/**
* @param height height to use to display screenshot images
*/
public void screenshotShowHeight(String height) {
screenshotHeight = height;
}
/**
* @return (escaped) HTML content of current page.
*/
public String pageSource() {
String result = null;
String html = getSeleniumHelper().getHtml();
if (html != null) {
result = "<pre>" + StringEscapeUtils.escapeHtml4(html) + "</pre>";
}
return result;
}
/**
* Saves current page's source to the wiki'f files section and returns a link to the
* created file.
* @return hyperlink to the file containing the page source.
*/
public String savePageSource() {
String fileName = getSeleniumHelper().getResourceNameFromLocation();
return savePageSource(fileName, fileName + ".html");
}
protected String savePageSource(String fileName, String linkText) {
PageSourceSaver saver = getSeleniumHelper().getPageSourceSaver(pageSourceBase);
// make href to file
String url = saver.savePageSource(fileName);
return String.format("<a href=\"%s\">%s</a>", url, linkText);
}
/**
* Takes screenshot from current page
* @param basename filename (below screenshot base directory).
* @return location of screenshot.
*/
public String takeScreenshot(String basename) {
try {
String screenshotFile = createScreenshot(basename);
if (screenshotFile == null) {
throw new SlimFixtureException(false, "Unable to take screenshot: does the webdriver support it?");
} else {
screenshotFile = getScreenshotLink(screenshotFile);
}
return screenshotFile;
} catch (UnhandledAlertException e) {
// standard behavior will stop test, this breaks storyboard that will attempt to take screenshot
// after triggering alert, but before the alert can be handled.
// so we output a message but no exception. We rely on a next line to actually handle alert
// (which may mean either really handle or stop test).
return String.format(
"<div><strong>Unable to take screenshot</strong>, alert is active. Alert text:<br/>" +
"'<span>%s</span>'</div>",
StringEscapeUtils.escapeHtml4(alertText()));
}
}
private String getScreenshotLink(String screenshotFile) {
String wikiUrl = getWikiUrl(screenshotFile);
if (wikiUrl != null) {
// make href to screenshot
if ("".equals(screenshotHeight)) {
wikiUrl = String.format("<a href=\"%s\">%s</a>",
wikiUrl, screenshotFile);
} else {
wikiUrl = String.format("<a href=\"%1$s\"><img src=\"%1$s\" title=\"%2$s\" height=\"%3$s\"/></a>",
wikiUrl, screenshotFile, screenshotHeight);
}
screenshotFile = wikiUrl;
}
return screenshotFile;
}
private String createScreenshot(String basename) {
String name = getScreenshotBasename(basename);
return getSeleniumHelper().takeScreenshot(name);
}
private String createScreenshot(String basename, Throwable t) {
String screenshotFile;
byte[] screenshotInException = getSeleniumHelper().findScreenshot(t);
if (screenshotInException == null || screenshotInException.length == 0) {
screenshotFile = createScreenshot(basename);
} else {
String name = getScreenshotBasename(basename);
screenshotFile = getSeleniumHelper().writeScreenshot(name, screenshotInException);
}
return screenshotFile;
}
private String getScreenshotBasename(String basename) {
return screenshotBase + basename;
}
/**
* Waits until the condition evaluates to a value that is neither null nor
* false. Because of this contract, the return type must not be Void.
* @param <T> the return type of the method, which must not be Void
* @param condition condition to evaluate to determine whether waiting can be stopped.
* @throws SlimFixtureException if condition was not met before secondsBeforeTimeout.
* @return result of condition.
*/
protected <T> T waitUntil(ExpectedCondition<T> condition) {
try {
return waitUntilImpl(condition);
} catch (TimeoutException e) {
String message = getTimeoutMessage(e);
return lastAttemptBeforeThrow(condition, new SlimFixtureException(false, message, e));
}
}
/**
* Waits until the condition evaluates to a value that is neither null nor
* false. If that does not occur the whole test is stopped.
* Because of this contract, the return type must not be Void.
* @param <T> the return type of the method, which must not be Void
* @param condition condition to evaluate to determine whether waiting can be stopped.
* @throws TimeoutStopTestException if condition was not met before secondsBeforeTimeout.
* @return result of condition.
*/
protected <T> T waitUntilOrStop(ExpectedCondition<T> condition) {
try {
return waitUntilImpl(condition);
} catch (TimeoutException e) {
try {
return handleTimeoutException(e);
} catch (TimeoutStopTestException tste) {
return lastAttemptBeforeThrow(condition, tste);
}
}
}
/**
* Tries the condition one last time before throwing an exception.
* This to prevent exception messages in the wiki that show no problem, which could happen if the browser's
* window content has changed between last (failing) try at condition and generation of the exception.
* @param <T> the return type of the method, which must not be Void
* @param condition condition that caused exception.
* @param e exception that will be thrown if condition does not return a result.
* @return last attempt results, if not null.
* @throws SlimFixtureException throws e if last attempt returns null.
*/
protected <T> T lastAttemptBeforeThrow(ExpectedCondition<T> condition, SlimFixtureException e) {
T lastAttemptResult = null;
try {
// last attempt to ensure condition has not been met
// this to prevent messages that show no problem
lastAttemptResult = condition.apply(getSeleniumHelper().driver());
} catch (Throwable t) {
// ignore
}
if (lastAttemptResult != null) {
return lastAttemptResult;
}
throw e;
}
/**
* Waits until the condition evaluates to a value that is neither null nor
* false. If that does not occur null is returned.
* Because of this contract, the return type must not be Void.
* @param <T> the return type of the method, which must not be Void
* @param condition condition to evaluate to determine whether waiting can be stopped.
* @return result of condition.
*/
protected <T> T waitUntilOrNull(ExpectedCondition<T> condition) {
try {
return waitUntilImpl(condition);
} catch (TimeoutException e) {
return null;
}
}
protected <T> T waitUntilImpl(ExpectedCondition<T> condition) {
return getSeleniumHelper().waitUntil(secondsBeforeTimeout(), condition);
}
protected <T> T handleTimeoutException(TimeoutException e) {
String message = getTimeoutMessage(e);
throw new TimeoutStopTestException(false, message, e);
}
private String getTimeoutMessage(TimeoutException e) {
String messageBase = String.format("Timed-out waiting (after %ss)", secondsBeforeTimeout());
return getSlimFixtureExceptionMessage("timeouts", "timeout", messageBase, e);
}
protected void handleRequiredElementNotFound(String toFind) {
handleRequiredElementNotFound(toFind, null);
}
protected void handleRequiredElementNotFound(String toFind, Throwable t) {
String messageBase = String.format("Unable to find: %s", toFind);
String message = getSlimFixtureExceptionMessage("notFound", toFind, messageBase, t);
throw new SlimFixtureException(false, message, t);
}
protected String getSlimFixtureExceptionMessage(String screenshotFolder, String screenshotFile, String messageBase, Throwable t) {
String screenshotBaseName = String.format("%s/%s/%s", screenshotFolder, getClass().getSimpleName(), screenshotFile);
return getSlimFixtureExceptionMessage(screenshotBaseName, messageBase, t);
}
protected String getSlimFixtureExceptionMessage(String screenshotBaseName, String messageBase, Throwable t) {
// take a screenshot of what was on screen
String screenShotFile = null;
try {
screenShotFile = createScreenshot(screenshotBaseName, t);
} catch (UnhandledAlertException e) {
System.err.println("Unable to take screenshot while alert is present for exception: " + messageBase);
} catch (Exception sse) {
System.err.println("Unable to take screenshot for exception: " + messageBase);
sse.printStackTrace();
}
String message = messageBase;
if (message == null) {
if (t == null) {
message = "";
} else {
message = ExceptionUtils.getStackTrace(t);
}
}
if (screenShotFile != null) {
String label = "Page content";
try {
String fileName;
if (t != null) {
fileName = t.getClass().getName();
} else if (screenshotBaseName != null) {
fileName = screenshotBaseName;
} else {
fileName = "exception";
}
label = savePageSource(fileName, label);
} catch (UnhandledAlertException e) {
System.err.println("Unable to capture page source while alert is present for exception: " + messageBase);
} catch (Exception e) {
System.err.println("Unable to capture page source for exception: " + messageBase);
e.printStackTrace();
}
String exceptionMsg = formatExceptionMsg(message);
message = String.format("<div><div>%s.</div><div>%s:%s</div></div>",
exceptionMsg, label, getScreenshotLink(screenShotFile));
}
return message;
}
protected String formatExceptionMsg(String value) {
return StringEscapeUtils.escapeHtml4(value);
}
private WebDriver driver() {
return getSeleniumHelper().driver();
}
private WebDriverWait waitDriver() {
return getSeleniumHelper().waitDriver();
}
/**
* @return helper to use.
*/
protected final SeleniumHelper getSeleniumHelper() {
return seleniumHelper;
}
/**
* Sets SeleniumHelper to use, for testing purposes.
* @param helper helper to use.
*/
protected void setSeleniumHelper(SeleniumHelper helper) {
seleniumHelper = helper;
}
public int currentBrowserWidth() {
return getWindowSize().getWidth();
}
public int currentBrowserHeight() {
return getWindowSize().getHeight();
}
public void setBrowserWidth(int newWidth) {
int currentHeight = currentBrowserHeight();
setBrowserSizeToBy(newWidth, currentHeight);
}
public void setBrowserHeight(int newHeight) {
int currentWidth = currentBrowserWidth();
setBrowserSizeToBy(currentWidth, newHeight);
}
public void setBrowserSizeToBy(int newWidth, int newHeight) {
getSeleniumHelper().setWindowSize(newWidth, newHeight);
Dimension actualSize = getWindowSize();
if (actualSize.getHeight() != newHeight || actualSize.getWidth() != newWidth) {
String message = String.format("Unable to change size to: %s x %s; size is: %s x %s",
newWidth, newHeight, actualSize.getWidth(), actualSize.getHeight());
throw new SlimFixtureException(false, message);
}
}
protected Dimension getWindowSize() {
return getSeleniumHelper().getWindowSize();
}
public void setBrowserSizeToMaximum() {
getSeleniumHelper().setWindowSizeToMaximum();
}
/**
* Downloads the target of the supplied link.
* @param place link to follow.
* @return downloaded file if any, null otherwise.
*/
@WaitUntil
public String download(String place) {
WebElement element = getSeleniumHelper().getLink(place);
return downloadLinkTarget(element);
}
/**
* Downloads the target of the supplied link.
* @param place link to follow.
* @param container part of screen containing link.
* @return downloaded file if any, null otherwise.
*/
@WaitUntil
public String downloadIn(String place, String container) {
return doInContainer(container, () -> download(place));
}
protected WebElement findElement(By selector) {
return getSeleniumHelper().findElement(selector);
}
public WebElement findByTechnicalSelectorOr(String place, Function<String, WebElement> supplierF) {
return getSeleniumHelper().findByTechnicalSelectorOr(place, () -> supplierF.apply(place));
}
/**
* Downloads the target of the supplied link.
* @param element link to follow.
* @return downloaded file if any, null otherwise.
*/
protected String downloadLinkTarget(WebElement element) {
String result;
String href = getLinkTarget(element);
if (href != null) {
result = downloadContentFrom(href);
} else {
throw new SlimFixtureException(false, "Could not determine url to download from");
}
return result;
}
/**
* Downloads binary content from specified url (using the browser's cookies).
* @param urlOrLink url to download from
* @return link to downloaded file
*/
public String downloadContentFrom(String urlOrLink) {
String result = null;
if (urlOrLink != null) {
String url = getUrl(urlOrLink);
BinaryHttpResponse resp = new BinaryHttpResponse();
getUrlContent(url, resp);
byte[] content = resp.getResponseContent();
if (content == null) {
result = resp.getResponse();
} else {
String fileName = resp.getFileName();
if (StringUtils.isEmpty(fileName)) {
fileName = "download";
}
String baseName = FilenameUtils.getBaseName(fileName);
String ext = FilenameUtils.getExtension(fileName);
String downloadedFile = FileUtil.saveToFile(getDownloadName(baseName), ext, content);
String wikiUrl = getWikiUrl(downloadedFile);
if (wikiUrl != null) {
// make href to file
result = String.format("<a href=\"%s\">%s</a>", wikiUrl, fileName);
} else {
result = downloadedFile;
}
}
}
return result;
}
/**
* Selects a file using the first file upload control.
* @param fileName file to upload
* @return true, if a file input was found and file existed.
*/
@WaitUntil
public boolean selectFile(String fileName) {
return selectFileFor(fileName, "css=input[type='file']");
}
/**
* Selects a file using a file upload control.
* @param fileName file to upload
* @param place file input to select the file for
* @return true, if place was a file input and file existed.
*/
@WaitUntil
public boolean selectFileFor(String fileName, String place) {
return selectFileForIn(fileName, place, null);
}
/**
* Selects a file using a file upload control.
* @param fileName file to upload
* @param place file input to select the file for
* @param container part of screen containing place
* @return true, if place was a file input and file existed.
*/
@WaitUntil
public boolean selectFileForIn(String fileName, String place, String container) {
boolean result = false;
if (fileName != null) {
String fullPath = getFilePathFromWikiUrl(fileName);
if (new File(fullPath).exists()) {
WebElement element = getElementToSelectFile(place, container);
if (element != null) {
element.sendKeys(fullPath);
result = true;
}
} else {
throw new SlimFixtureException(false, "Unable to find file: " + fullPath);
}
}
return result;
}
protected WebElement getElementToSelectFile(String place, String container) {
WebElement result = null;
WebElement element = getElement(place, container);
if (element != null
&& "input".equalsIgnoreCase(element.getTagName())
&& "file".equalsIgnoreCase(element.getAttribute("type"))) {
result = element;
}
return result;
}
private String getDownloadName(String baseName) {
return downloadBase + baseName;
}
/**
* GETs content of specified URL, using the browsers cookies.
* @param url url to retrieve content from
* @param resp response to store content in
*/
protected void getUrlContent(String url, HttpResponse resp) {
getEnvironment().addSeleniumCookies(resp);
getEnvironment().doGet(url, resp);
}
/**
* Gets the value of the cookie with the supplied name.
* @param cookieName name of cookie to get value from.
* @return cookie's value if any.
*/
public String cookieValue(String cookieName) {
String result = null;
Cookie cookie = getSeleniumHelper().getCookie(cookieName);
if (cookie != null) {
result = cookie.getValue();
}
return result;
}
public boolean refreshUntilValueOfIs(String place, String expectedValue) {
return repeatUntil(getRefreshUntilValueIs(place, expectedValue));
}
public boolean refreshUntilValueOfIsNot(String place, String expectedValue) {
return repeatUntilNot(getRefreshUntilValueIs(place, expectedValue));
}
protected RepeatUntilValueIsCompletion getRefreshUntilValueIs(String place, String expectedValue) {
return new RepeatUntilValueIsCompletion(place, expectedValue) {
@Override
public void repeat() {
refresh();
}
};
}
public boolean clickUntilValueOfIs(String clickPlace, String checkPlace, String expectedValue) {
return repeatUntil(getClickUntilValueIs(clickPlace, checkPlace, expectedValue));
}
public boolean clickUntilValueOfIsNot(String clickPlace, String checkPlace, String expectedValue) {
return repeatUntilNot(getClickUntilValueIs(clickPlace, checkPlace, expectedValue));
}
protected RepeatUntilValueIsCompletion getClickUntilValueIs(String clickPlace, String checkPlace, String expectedValue) {
String place = cleanupValue(clickPlace);
return getClickUntilCompletion(place, checkPlace, expectedValue);
}
protected RepeatUntilValueIsCompletion getClickUntilCompletion(String place, String checkPlace, String expectedValue) {
ExpectedCondition<Object> condition = wrapConditionForFramesIfNeeded(webDriver -> click(place));
return new RepeatUntilValueIsCompletion(checkPlace, expectedValue) {
@Override
public void repeat() {
waitUntil(condition);
}
};
}
protected <T> ExpectedCondition<T> wrapConditionForFramesIfNeeded(ExpectedCondition<T> condition) {
if (implicitFindInFrames) {
condition = getSeleniumHelper().conditionForAllFrames(condition);
}
return condition;
}
@Override
protected boolean repeatUntil(RepeatCompletion repeat) {
// During repeating we reduce the timeout used for finding elements,
// but the page load timeout is kept as-is (which takes extra work because secondsBeforeTimeout(int)
// also changes that.
int previousTimeout = secondsBeforeTimeout();
int pageLoadTimeout = secondsBeforePageLoadTimeout();
try {
int timeoutDuringRepeat = Math.max((Math.toIntExact(repeatInterval() / 1000)), 1);
secondsBeforeTimeout(timeoutDuringRepeat);
secondsBeforePageLoadTimeout(pageLoadTimeout);
return super.repeatUntil(repeat);
} finally {
secondsBeforeTimeout(previousTimeout);
secondsBeforePageLoadTimeout(pageLoadTimeout);
}
}
protected abstract class RepeatUntilValueIsCompletion implements RepeatCompletion {
private final String place;
private final String expectedValue;
protected RepeatUntilValueIsCompletion(String place, String expectedValue) {
this.place = place;
this.expectedValue = cleanExpectedValue(expectedValue);
}
@Override
public boolean isFinished() {
ExpectedCondition<Boolean> condition = wrapConditionForFramesIfNeeded(webDriver -> checkValueImpl());
Boolean valueFound = waitUntilOrNull(condition);
return valueFound != null && valueFound;
}
protected boolean checkValueImpl() {
boolean match;
String actual = valueOf(place);
if (expectedValue == null) {
match = actual == null;
} else {
match = expectedValue.equals(actual);
}
return match;
}
}
protected Object waitForJavascriptCallback(String statement, Object... parameters) {
try {
return getSeleniumHelper().waitForJavascriptCallback(statement, parameters);
} catch (TimeoutException e) {
return handleTimeoutException(e);
}
}
public NgBrowserTest getNgBrowserTest() {
return ngBrowserTest;
}
public void setNgBrowserTest(NgBrowserTest ngBrowserTest) {
this.ngBrowserTest = ngBrowserTest;
}
public boolean isImplicitWaitForAngularEnabled() {
return implicitWaitForAngular;
}
public void setImplicitWaitForAngularTo(boolean implicitWaitForAngular) {
this.implicitWaitForAngular = implicitWaitForAngular;
}
public void setImplicitFindInFramesTo(boolean implicitFindInFrames) {
this.implicitFindInFrames = implicitFindInFrames;
}
/**
* Executes javascript in the browser.
* @param script you want to execute
* @return result from script
*/
public Object executeScript(String script) {
String statement = cleanupValue(script);
return getSeleniumHelper().executeJavascript(statement);
}
}
|
package org.appwork.utils.swing.table;
import java.awt.Color;
import java.awt.Component;
import java.awt.Container;
import java.awt.Cursor;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JPopupMenu;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JViewport;
import javax.swing.KeyStroke;
import javax.swing.ScrollPaneConstants;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.event.TableColumnModelEvent;
import javax.swing.event.TableColumnModelListener;
import javax.swing.table.TableCellEditor;
import javax.swing.table.TableCellRenderer;
import javax.swing.table.TableColumn;
import javax.swing.table.TableColumnModel;
import org.appwork.app.gui.MigPanel;
import org.appwork.storage.JSonStorage;
import org.appwork.utils.Application;
import org.appwork.utils.BinaryLogic;
import org.appwork.utils.images.IconIO;
import org.appwork.utils.logging.Log;
import org.appwork.utils.swing.EDTHelper;
public class ExtTable<E> extends JTable {
private static final long serialVersionUID = 2822230056021924679L;
/**
* Column background color if column is NOT selected
*/
private final Color columnBackground;
/**
* Column background color if column is selected
*/
private final Color columnBackgroundSelected;
/**
* Column textcolor if column is NOT selected
*/
private final Color columnForeground;
/**
* Column textcolor if column is selected
*/
private final Color columnForegroundSelected;
/**
* The underlaying datamodel
*/
private final ExtTableModel<E> model;
/**
* TableID. Used to generate a key for saving internal data to database
*/
private final String tableID;
final private ArrayList<ExtRowHighlighter> rowHighlighters;
/**
* true if search is enabled
*/
private boolean searchEnabled = false;
private SearchDialog searchDialog;
private final ExtTableEventSender eventSender;
private JComponent columnButton = null;
private boolean columnButtonVisible = true;
private int verticalScrollPolicy;
/**
* @param downloadTableModel
*/
public ExtTable(final ExtTableModel<E> tableModel) {
this(tableModel, tableModel.getModelID() + "-Table");
}
/**
* Create an Extended Table instance
*
* @param model
* Databsemodel
* @param database
* Information storage interface.
* @param id
* Tableid used for storage
*/
public ExtTable(final ExtTableModel<E> model, final String id) {
super(model);
this.eventSender = new ExtTableEventSender();
this.tableID = id;
this.rowHighlighters = new ArrayList<ExtRowHighlighter>();
this.model = model;
// workaround
this.setColumnModel(new ExtColumnModel(this.getColumnModel()));
model.setTable(this);
this.createColumns();
// get defaultbackground and Foregroundcolors
Component c = super.getCellRenderer(0, 0).getTableCellRendererComponent(this, "", true, false, 0, 0);
this.columnBackgroundSelected = c.getBackground();
this.columnForegroundSelected = c.getForeground();
c = super.getCellRenderer(0, 0).getTableCellRendererComponent(this, "", false, false, 0, 0);
this.columnBackground = c.getBackground();
this.columnForeground = c.getForeground();
// Mouselistener for columnselection Menu and sort on click
this.getTableHeader().addMouseListener(new MouseAdapter() {
int columnPressed = 0;
@Override
public void mousePressed(final MouseEvent e) {
// only if we are not in resize mode
if (ExtTable.this.getTableHeader().getCursor().getType() == Cursor.getDefaultCursor().getType()) {
if (e.getButton() == MouseEvent.BUTTON1) {
this.columnPressed = ExtTable.this.columnAtPoint(e.getPoint());
} else if (e.getButton() == MouseEvent.BUTTON3) {
final JPopupMenu ccm = ExtTable.this.columnControlMenu(ExtTable.this.getExtColumnAtPoint(e.getPoint()));
ccm.show(ExtTable.this.getTableHeader(), e.getX(), e.getY());
if (ccm.getComponentCount() == 0) {
Toolkit.getDefaultToolkit().beep();
}
}
}
}
@Override
public void mouseReleased(final MouseEvent e) {
if (ExtTable.this.getTableHeader().getCursor().getType() == Cursor.getDefaultCursor().getType()) {
if (e.getButton() == MouseEvent.BUTTON1) {
if (this.columnPressed != ExtTable.this.columnAtPoint(e.getPoint())) { return; }
final int col = ExtTable.this.getExtColumnIndexByPoint(e.getPoint());
if (col == -1) { return; }
if (ExtTable.this.getExtTableModel().getExtColumn(col).isSortable(null)) {
ExtTable.this.getExtTableModel().getExtColumn(col).doSort(null);
}
}
}
}
});
// mouselistener to display column header tooltips
this.getTableHeader().addMouseMotionListener(new MouseAdapter() {
@Override
public void mouseMoved(final MouseEvent e) {
final int col = ExtTable.this.getExtColumnIndexByPoint(e.getPoint());
if (col >= 0) {
ExtTable.this.getTableHeader().setToolTipText(ExtTable.this.getExtTableModel().getExtColumn(col).getName());
}
}
});
this.getSelectionModel().addListSelectionListener(new ListSelectionListener() {
@SuppressWarnings("unchecked")
public void valueChanged(final ListSelectionEvent e) {
ArrayList<E> sel = ExtTable.this.getExtTableModel().getSelectedObjects();
if (sel != null && sel.size() == 0) {
sel = null;
}
ExtTable.this.onSelectionChanged(sel);
ExtTable.this.eventSender.fireEvent(new ExtTableEvent<ArrayList<E>>(ExtTable.this, ExtTableEvent.Types.SELECTION_CHANGED, sel));
}
});
this.getTableHeader().setReorderingAllowed(true);
this.getTableHeader().setResizingAllowed(true);
this.setAutoResizeMode(JTable.AUTO_RESIZE_SUBSEQUENT_COLUMNS);
this.setAutoscrolls(true);
this.getTableHeader().setPreferredSize(new Dimension(this.getColumnModel().getTotalColumnWidth(), 19));
// assures that the table is painted over the complete available high
// This method is 1.6 only
if (Application.getJavaVersion() >= 16000000) {
this.setFillsViewportHeight(true);
}
this.getColumnModel().addColumnModelListener(new TableColumnModelListener() {
public void columnAdded(final TableColumnModelEvent e) {
}
public void columnMarginChanged(final ChangeEvent e) {
}
public void columnMoved(final TableColumnModelEvent e) {
if (e == null) { return; }
if (e.getFromIndex() == e.getToIndex()) { return; }
final TableColumnModel tcm = ExtTable.this.getColumnModel();
for (int i = 0; i < tcm.getColumnCount(); i++) {
try {
JSonStorage.getStorage("ExtTable_" + ExtTable.this.tableID).put("POS_COL_" + i, ExtTable.this.getExtTableModel().getExtColumn(tcm.getColumn(i).getModelIndex()).getID());
} catch (final Exception e1) {
Log.exception(e1);
}
}
}
public void columnRemoved(final TableColumnModelEvent e) {
}
public void columnSelectionChanged(final ListSelectionEvent e) {
}
});
}
/**
* adds a row highlighter
*
* @param highlighter
*/
public void addRowHighlighter(final ExtRowHighlighter highlighter) {
this.removeRowHighlighter(highlighter);
this.rowHighlighters.add(highlighter);
}
/**
* create Columnselection popupmenu. It contains all available columns and
* let's the user select. The menu does not autoclose on click.
*
* @param extColumn
*
* @return
*/
protected JPopupMenu columnControlMenu(final ExtColumn<E> extColumn) {
JPopupMenu popup;
if (extColumn == null) {
// controlbutton
popup = new JPopupMenu();
for (int i = 0; i < this.getExtTableModel().getColumnCount(); i++) {
this.getExtTableModel().getExtColumn(i).extendControlButtonMenu(popup);
}
} else {
popup = extColumn.createHeaderPopup();
if (popup == null) {
popup = new JPopupMenu();
}
}
for (int i = 0; i < this.getExtTableModel().getColumnCount(); ++i) {
final int j = i;
if (this.getExtTableModel().isHidable(i)) {
final ExtCheckBoxMenuItem mi = new ExtCheckBoxMenuItem(this.getExtTableModel().getColumnName(i));
mi.setHideOnClick(false);
// mis[i] = mi;
mi.setSelected(this.getExtTableModel().isVisible(i));
mi.addActionListener(new ActionListener() {
public void actionPerformed(final ActionEvent e) {
ExtTable.this.getExtTableModel().setVisible(j, mi.isSelected());
ExtTable.this.createColumns();
ExtTable.this.revalidate();
ExtTable.this.repaint();
}
});
popup.add(mi);
}
}
return popup;
}
@Override
protected void configureEnclosingScrollPane() {
super.configureEnclosingScrollPane();
this.reconfigureColumnButton();
}
/**
* Creates the columns based on the model
*/
private void createColumns() {
final TableColumnModel tcm = this.getColumnModel();
while (tcm.getColumnCount() > 0) {
tcm.removeColumn(tcm.getColumn(0));
}
final LinkedHashMap<String, TableColumn> columns = new LinkedHashMap<String, TableColumn>();
for (int i = 0; i < this.getModel().getColumnCount(); ++i) {
final int j = i;
final TableColumn tableColumn = new TableColumn(i);
this.model.getExtColumn(j).setTableColumn(tableColumn);
tableColumn.setHeaderRenderer(this.model.getExtColumn(j).getHeaderRenderer(this.getTableHeader()) != null ? this.model.getExtColumn(j).getHeaderRenderer(this.getTableHeader()) : new ExtTableHeaderRenderer(this.model.getExtColumn(j), this.getTableHeader()));
// Save column width
tableColumn.addPropertyChangeListener(new PropertyChangeListener() {
public void propertyChange(final PropertyChangeEvent evt) {
if (evt.getPropertyName().equals("width")) {
try {
JSonStorage.getStorage("ExtTable_" + ExtTable.this.tableID).put("WIDTH_COL_" + ExtTable.this.model.getExtColumn(j).getID(), (Integer) evt.getNewValue());
} catch (final Exception e) {
Log.exception(e);
}
}
}
});
if (this.model.getExtColumn(j).getMaxWidth() >= 0) {
tableColumn.setMaxWidth(this.model.getExtColumn(j).getMaxWidth());
}
if (this.model.getExtColumn(j).getMinWidth() >= 0) {
tableColumn.setMinWidth(this.model.getExtColumn(j).getMinWidth());
}
// Set stored columnwidth
int w = this.model.getExtColumn(j).getDefaultWidth();
try {
w = JSonStorage.getStorage("ExtTable_" + this.tableID).get("WIDTH_COL_" + this.model.getExtColumn(j).getID(), w);
} catch (final Exception e) {
Log.exception(e);
} finally {
tableColumn.setPreferredWidth(w);
}
if (!this.model.isVisible(i)) {
continue;
}
columns.put(this.model.getExtColumn(j).getID(), tableColumn);
// addColumn(tableColumn);
}
// restore column position
int index = 0;
while (true) {
if (columns.isEmpty()) {
break;
}
if (index < this.getModel().getColumnCount()) {
String id;
try {
id = JSonStorage.getStorage("ExtTable_" + this.tableID).get("POS_COL_" + index, "");
index++;
if (id != null) {
final TableColumn item = columns.remove(id);
if (item != null) {
this.addColumn(item);
}
}
} catch (final Exception e) {
Log.exception(e);
}
} else {
for (final TableColumn ritem : columns.values()) {
this.addColumn(ritem);
}
break;
}
}
}
private JComponent createDefaultColumnButton() {
final MigPanel p = new MigPanel("ins 0 2 0 0", "[grow,fill]", "[grow,fill]");
final URL iconPath = ExtTable.class.getResource("columnButton.png");
final JButton button;
if (iconPath != null) {
button = new JButton(IconIO.getImageIcon(iconPath, 12));
} else {
button = new JButton("*");
}
button.setBorderPainted(false);
button.setContentAreaFilled(false);
p.setBackground(null);
p.setOpaque(false);
button.addActionListener(new ActionListener() {
public void actionPerformed(final ActionEvent event) {
final JButton source = (JButton) event.getSource();
final int x = source.getLocation().x;
final int y = source.getLocation().y;
final JPopupMenu ccm = ExtTable.this.columnControlMenu(null);
ccm.show(source, x, y);
if (ccm.getComponentCount() == 0) {
Toolkit.getDefaultToolkit().beep();
}
}
});
p.add(button, "width 12!,height 12!");
return p;
}
/* we do always create columsn ourself */
@Override
public boolean getAutoCreateColumnsFromModel() {
return false;
}
/**
* converts the colum index to model and returns the column's cell editor
*/
@Override
public TableCellEditor getCellEditor(final int row, final int column) {
return this.model.getCelleditorByColumn(this.convertColumnIndexToModel(column));
}
/**
* COnverts ther colum index to the current model and returns the column's
* cellrenderer
*/
@Override
public TableCellRenderer getCellRenderer(final int row, final int column) {
return this.model.getCellrendererByColumn(this.convertColumnIndexToModel(column));
}
/**
* @return the {@link ExtTable#columnBackground}
* @see ExtTable#columnBackground
*/
public Color getColumnBackground() {
return this.columnBackground;
}
/**
* @return the {@link ExtTable#columnBackgroundSelected}
* @see ExtTable#columnBackgroundSelected
*/
public Color getColumnBackgroundSelected() {
return this.columnBackgroundSelected;
}
public JComponent getColumnButton() {
if (this.columnButton == null) {
this.columnButton = this.createDefaultColumnButton();
}
return this.columnButton;
}
/**
* @return the {@link ExtTable#columnForeground}
* @see ExtTable#columnForeground
*/
public Color getColumnForeground() {
return this.columnForeground;
}
/**
* @return the {@link ExtTable#columnForegroundSelected}
* @see ExtTable#columnForegroundSelected
*/
public Color getColumnForegroundSelected() {
return this.columnForegroundSelected;
}
/**
* @return the eventSender
*/
public ExtTableEventSender getEventSender() {
return this.eventSender;
}
/**
* Returns the real column index at this point
*
* @param point
*/
public ExtColumn<E> getExtColumnAtPoint(final Point point) {
final int x = this.getExtColumnIndexByPoint(point);
return this.getExtTableModel().getExtColumn(x);
}
/**
* returns the real column at the given point. Method converts the column to
* the moduels colum
*
* @param point
* @return
*/
public int getExtColumnIndexByPoint(final Point point) {
final int x = this.columnAtPoint(point);
return this.convertColumnIndexToModel(x);
}
public ExtTableModel<E> getExtTableModel() {
return this.model;
}
/**
* Returns the original Celleditor given by the current LAF UI. Used to have
* an reference to the LAF's default editor
*
* @param row
* @param column
* @return
*/
public TableCellEditor getLafCellEditor(final int row, final int column) {
return super.getCellEditor(row, column);
}
/**
* Returns the original Cellrenderer given bei the current LAF UI Used to
* have an reference to the LAF's default renderer
*
* @param row
* @param column
* @return
*/
public TableCellRenderer getLafCellRenderer(final int row, final int column) {
return super.getCellRenderer(row, column);
}
public Point getPointinCell(final Point x) {
final int row = this.rowAtPoint(x);
if (row == -1) { return null; }
final Rectangle cellPosition = this.getCellRect(row, this.columnAtPoint(x), true);
final Point p = new Point();
p.setLocation(x.getX() - cellPosition.getX(), x.getY() - cellPosition.getY());
return p;
}
/**
* @return the rowHighlighters
*/
public ArrayList<ExtRowHighlighter> getRowHighlighters() {
return this.rowHighlighters;
}
/**
* @param point
* @return
*/
public int getRowIndexByPoint(final Point point) {
return this.rowAtPoint(point);
}
/**
* @return the tableID
*/
public String getTableID() {
return this.tableID;
}
public boolean isColumnButtonVisible() {
return this.columnButtonVisible;
}
/**
* @return the searchEnabled
*/
public boolean isSearchEnabled() {
return this.searchEnabled;
}
protected JPopupMenu onContextMenu(final JPopupMenu popup, final E contextObject, final ArrayList<E> selection) {
return null;
}
/**
* This method will be called when a doubleclick is performed on the object
* <code>obj</code>
*
* @param obj
*/
protected void onDoubleClick(final MouseEvent e, final E obj) {
}
protected void onSelectionChanged(final ArrayList<E> selected) {
}
/**
* @param selectedObjects
* @param evt
* @return
*/
protected boolean onShortcutCopy(final ArrayList<E> selectedObjects, final KeyEvent evt) {
return false;
}
/**
* @param selectedObjects
* @param evt
* @return
*/
protected boolean onShortcutCut(final ArrayList<E> selectedObjects, final KeyEvent evt) {
return false;
}
/**
* @param selectedObjects
* @param evt
* @param direct
* TODO
* @return
*/
protected boolean onShortcutDelete(final ArrayList<E> selectedObjects, final KeyEvent evt, final boolean direct) {
return false;
}
/**
* @param selectedObjects
* @param evt
* @return
*/
protected boolean onShortcutPaste(final ArrayList<E> selectedObjects, final KeyEvent evt) {
return false;
}
/**
* @param selectedObjects
* @param evt
* @return
*/
protected boolean onShortcutSearch(final ArrayList<E> selectedObjects, final KeyEvent evt) {
if (this.isSearchEnabled() && this.hasFocus()) {
this.startSearch();
return true;
}
return false;
}
/**
* @param e
* @param obj
*/
protected void onSingleClick(final MouseEvent e, final E obj) {
}
@Override
public void paintComponent(final Graphics g) {
super.paintComponent(g);
/*
* highlighter TODO: this might get slow for many rows TODO: change
* order? highlighting columns "overpaint" the text
*/
if (this.getRowCount() == 0) { return; }
final Rectangle visibleRect = this.getVisibleRect();
Rectangle first, last;
// get current width;
first = this.getCellRect(0, 0, true);
last = this.getCellRect(0, this.getColumnCount() - 1, true);
final int width = last.x + last.width - first.x;
for (final ExtRowHighlighter rh : this.rowHighlighters) {
for (int i = 0; i < this.getRowCount(); i++) {
first = this.getCellRect(i, 0, true);
// skip if the row is not in visible rec
if (first.y + first.height < visibleRect.y) {
continue;
}
if (first.y > visibleRect.y + visibleRect.height) {
continue;
}
if (rh.doHighlight(this, i)) {
rh.paint((Graphics2D) g, 0, first.y, width, first.height - 1);
}
}
}
}
/**
* Key selection
*/
@SuppressWarnings("unchecked")
@Override
protected boolean processKeyBinding(final KeyStroke stroke, final KeyEvent evt, final int condition, final boolean pressed) {
if (!pressed) { return super.processKeyBinding(stroke, evt, condition, pressed); }
switch (evt.getKeyCode()) {
case KeyEvent.VK_ESCAPE:
this.clearSelection();
return true;
case KeyEvent.VK_X:
if (evt.isControlDown() || evt.isMetaDown()) {
ExtTable.this.eventSender.fireEvent(new ExtTableEvent<ArrayList<E>>(ExtTable.this, ExtTableEvent.Types.SHORTCUT_CUT, this.getExtTableModel().getSelectedObjects()));
return this.onShortcutCut(this.getExtTableModel().getSelectedObjects(), evt);
}
break;
case KeyEvent.VK_V:
if (evt.isControlDown() || evt.isMetaDown()) {
ExtTable.this.eventSender.fireEvent(new ExtTableEvent<ArrayList<E>>(ExtTable.this, ExtTableEvent.Types.SHORTCUT_PASTE, this.getExtTableModel().getSelectedObjects()));
return this.onShortcutPaste(this.getExtTableModel().getSelectedObjects(), evt);
}
break;
case KeyEvent.VK_C:
if (evt.isControlDown() || evt.isMetaDown()) {
ExtTable.this.eventSender.fireEvent(new ExtTableEvent<ArrayList<E>>(ExtTable.this, ExtTableEvent.Types.SHORTCUT_COPY, this.getExtTableModel().getSelectedObjects()));
return this.onShortcutCopy(this.getExtTableModel().getSelectedObjects(), evt);
}
break;
case KeyEvent.VK_DELETE:
if (!evt.isAltDown()) {
/* no ctrl+alt+del */
ExtTable.this.eventSender.fireEvent(new ExtTableEvent<Object>(ExtTable.this, ExtTableEvent.Types.SHORTCUT_DELETE, this.getExtTableModel().getSelectedObjects(), BinaryLogic.containsSome(evt.getModifiers(), ActionEvent.SHIFT_MASK)));
return this.onShortcutDelete(this.getExtTableModel().getSelectedObjects(), evt, BinaryLogic.containsSome(evt.getModifiers(), ActionEvent.SHIFT_MASK));
}
break;
case KeyEvent.VK_BACK_SPACE:
if ((evt.isControlDown() || evt.isMetaDown()) && !evt.isAltDown()) {
/* no ctrl+alt+backspace = unix desktop restart */
ExtTable.this.eventSender.fireEvent(new ExtTableEvent<Object>(ExtTable.this, ExtTableEvent.Types.SHORTCUT_DELETE, this.getExtTableModel().getSelectedObjects(), false));
return this.onShortcutDelete(this.getExtTableModel().getSelectedObjects(), evt, false);
}
break;
case KeyEvent.VK_F:
if (evt.isControlDown() || evt.isMetaDown()) {
ExtTable.this.eventSender.fireEvent(new ExtTableEvent<ArrayList<E>>(ExtTable.this, ExtTableEvent.Types.SHORTCUT_SEARCH, this.getExtTableModel().getSelectedObjects()));
return this.onShortcutSearch(this.getExtTableModel().getSelectedObjects(), evt);
}
break;
case KeyEvent.VK_UP:
if (this.getSelectedRow() == 0 && !evt.isShiftDown()) {
if (this.getCellEditor() != null) {
this.getCellEditor().stopCellEditing();
}
this.changeSelection(this.getRowCount() - 1, 0, false, false);
return true;
}
break;
case KeyEvent.VK_DOWN:
if (this.getSelectedRow() == this.getRowCount() - 1 && !evt.isShiftDown()) {
if (this.getCellEditor() != null) {
this.getCellEditor().stopCellEditing();
}
this.changeSelection(0, 0, false, false);
return true;
}
break;
case KeyEvent.VK_A:
if (evt.isControlDown() || evt.isMetaDown()) {
if (this.getCellEditor() != null) {
this.getCellEditor().stopCellEditing();
}
this.getSelectionModel().setSelectionInterval(0, this.getRowCount() - 1);
return true;
}
break;
case KeyEvent.VK_HOME:
if (evt.isControlDown() || evt.isMetaDown() || evt.isShiftDown()) {
if (this.getCellEditor() != null) {
this.getCellEditor().stopCellEditing();
}
if (this.getSelectedRow() != -1 && this.getRowCount() != 0) {
this.getSelectionModel().setSelectionInterval(0, this.getSelectedRows()[this.getSelectedRows().length - 1]);
/* to avoid selection by super.processKeyBinding */
return true;
}
} else {
if (this.getCellEditor() != null) {
this.getCellEditor().stopCellEditing();
}
this.getSelectionModel().setSelectionInterval(0, 0);
}
break;
case KeyEvent.VK_END:
if (evt.isControlDown() || evt.isMetaDown() || evt.isShiftDown()) {
if (this.getCellEditor() != null) {
this.getCellEditor().stopCellEditing();
}
if (this.getSelectedRow() != -1 && this.getRowCount() != 0) {
this.getSelectionModel().setSelectionInterval(this.getSelectedRow(), this.getRowCount() - 1);
/* to avoid selection by super.processKeyBinding */
return true;
}
} else {
if (this.getCellEditor() != null) {
this.getCellEditor().stopCellEditing();
}
if (this.getRowCount() != 0) {
this.getSelectionModel().setSelectionInterval(this.getRowCount() - 1, this.getRowCount() - 1);
}
}
break;
}
return super.processKeyBinding(stroke, evt, condition, pressed);
}
@SuppressWarnings("unchecked")
@Override
protected void processMouseEvent(final MouseEvent e) {
super.processMouseEvent(e);
if (e.getID() == MouseEvent.MOUSE_RELEASED) {
if (e.isPopupTrigger() || e.getButton() == MouseEvent.BUTTON3) {
final int row = this.rowAtPoint(e.getPoint());
final E obj = this.getExtTableModel().getObjectbyRow(row);
// System.out.println(row);
if (obj == null || row == -1) {
/* no object under mouse, lets clear the selection */
this.clearSelection();
final JPopupMenu popup = this.onContextMenu(new JPopupMenu(), null, null);
this.eventSender.fireEvent(new ExtTableEvent<JPopupMenu>(this, ExtTableEvent.Types.CONTEXTMENU, popup));
if (popup != null && popup.getComponentCount() > 0) {
popup.show(ExtTable.this, e.getPoint().x, e.getPoint().y);
}
return;
} else {
/* check if we need to select object */
if (!this.isRowSelected(row)) {
this.clearSelection();
this.addRowSelectionInterval(row, row);
}
final ArrayList<E> selected = this.getExtTableModel().getSelectedObjects();
final JPopupMenu popup = this.onContextMenu(new JPopupMenu(), obj, selected);
if (popup != null && popup.getComponentCount() > 0) {
popup.show(ExtTable.this, e.getPoint().x, e.getPoint().y);
}
}
} else if (e.getButton() == MouseEvent.BUTTON1 && e.getClickCount() == 2) {
final int row = this.rowAtPoint(e.getPoint());
final E obj = this.getExtTableModel().getObjectbyRow(row);
// System.out.println(row);
if (obj != null) {
this.onDoubleClick(e, obj);
this.eventSender.fireEvent(new ExtTableEvent<E>(this, ExtTableEvent.Types.DOUBLECLICK, obj));
}
} else if (e.getButton() == MouseEvent.BUTTON1 && e.getClickCount() == 1) {
final int row = this.rowAtPoint(e.getPoint());
final E obj = this.getExtTableModel().getObjectbyRow(row);
// System.out.println(row);
if (obj != null) {
this.onSingleClick(e, obj);
}
}
} else if (e.getID() == MouseEvent.MOUSE_PRESSED) {
if (this.rowAtPoint(e.getPoint()) < 0) {
this.clearSelection();
}
}
}
protected void reconfigureColumnButton() {
final Container c1 = this.getParent();
if (c1 instanceof JViewport) {
final Container c2 = c1.getParent();
if (c2 instanceof JScrollPane) {
final JScrollPane scrollPane = (JScrollPane) c2;
final JViewport viewport = scrollPane.getViewport();
if (viewport == null || viewport.getView() != this) { return; }
if (this.isColumnButtonVisible()) {
this.verticalScrollPolicy = scrollPane.getVerticalScrollBarPolicy();
scrollPane.setCorner(ScrollPaneConstants.UPPER_TRAILING_CORNER, this.getColumnButton());
scrollPane.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
} else {
if (this.verticalScrollPolicy != 0) {
scrollPane.setVerticalScrollBarPolicy(this.verticalScrollPolicy);
}
try {
scrollPane.setCorner(ScrollPaneConstants.UPPER_TRAILING_CORNER, null);
} catch (final Throwable nothing) {
}
}
}
}
}
/**
* Removes a rowhilighter
*
* @param highlighter
*/
public void removeRowHighlighter(final ExtRowHighlighter highlighter) {
this.rowHighlighters.remove(highlighter);
}
public void scrollToRow(final int row) {
System.out.println("Scrol " + row);
if (row < 0) { return; }
new EDTHelper<Object>() {
@Override
public Object edtRun() {
final JViewport viewport = (JViewport) ExtTable.this.getParent();
if (viewport == null) { return null; }
final Rectangle rect = ExtTable.this.getCellRect(row, 0, true);
final Point pt = viewport.getViewPosition();
rect.setLocation(rect.x - pt.x, rect.y - pt.y);
viewport.scrollRectToVisible(rect);
System.out.println("Scrol " + rect);
return null;
}
}.start();
}
protected void scrollToSelection() {
new EDTHelper<Object>() {
@Override
public Object edtRun() {
final JViewport viewport = (JViewport) ExtTable.this.getParent();
if (viewport == null) { return null; }
final int[] sel = ExtTable.this.getSelectedRows();
if (sel == null || sel.length == 0) { return null; }
final Rectangle rect = ExtTable.this.getCellRect(sel[0], 0, true);
final Rectangle rect2 = ExtTable.this.getCellRect(sel[sel.length - 1], 0, true);
rect.height += rect2.y - rect.y;
final Point pt = viewport.getViewPosition();
rect.setLocation(rect.x - pt.x, rect.y - pt.y);
viewport.scrollRectToVisible(rect);
return null;
}
}.start();
}
public void setColumnBottonVisibility(final boolean visible) {
this.columnButtonVisible = visible;
this.reconfigureColumnButton();
}
public void setColumnButton(final JComponent c) {
this.columnButton = c;
this.reconfigureColumnButton();
}
/**
* @param searchEnabled
* the searchEnabled to set
*/
public void setSearchEnabled(final boolean searchEnabled) {
this.searchEnabled = searchEnabled;
}
private synchronized void startSearch() {
try {
if (this.searchDialog != null && this.searchDialog.isShowing()) {
this.searchDialog.requestFocus();
} else {
this.searchDialog = new SearchDialog(SearchDialog.NO_REGEX_FLAG, this) {
private static final long serialVersionUID = 2652101312418765845L;
@Override
public void actionPerformed(final ActionEvent e) {
final String ret = ExtTable.this.searchDialog.getReturnID();
if (ret != null) {
final int[] sel = ExtTable.this.getSelectedRows();
int startRow = -1;
if (sel != null & sel.length > 0) {
startRow = sel[sel.length - 1];
}
final E found = ExtTable.this.getExtTableModel().searchNextObject(startRow + 1, ret, ExtTable.this.searchDialog.isCaseSensitive(), ExtTable.this.searchDialog.isRegex());
ExtTable.this.getExtTableModel().setSelectedObject(found);
ExtTable.this.scrollToSelection();
}
}
};
}
} catch (final IOException e) {
Log.exception(e);
}
}
}
|
package net.hearthstats;
import java.awt.image.BufferedImage;
import java.util.Observable;
public class HearthstoneAnalyzer extends Observable {
private boolean _coin;
private BufferedImage _image;
private String _mode;
private String _opponentClass;
private String _result;
private String _screen;
private String _yourClass;
private int _deckSlot;
private boolean _isNewArena = false;
public HearthstoneAnalyzer() {
}
public void analyze(BufferedImage image) {
_image = image;
if(getScreen() != "Main Menu" && getScreen() != "Playing") {
_testForMainMenuScreen();
}
if(getScreen() != "Play") {
_testForPlayScreen();
}
if(getScreen() != "Arena") {
_testForArenaModeScreen();
}
if(getScreen() == "Play" || getScreen() == "Arena") {
_testForFindingOpponent();
if (getScreen() == "Play") {
if(getMode() != "Casual")
_testForCasualMode();
if(getMode() != "Ranked")
_testForRankedMode();
_testForDeckSlot();
}
}
if(getScreen() == "Finding Opponent") {
_testForMatchStartScreen();
}
if(getScreen() == "Match Start") {
if(getYourClass() == null)
_testForYourClass();
if(getOpponentClass() == null)
_testForOpponentClass();
if(!getCoin())
_testForCoin();
_testForPlayingScreen();
}
if(getScreen() == "Result") {
_testForArenaEnd();
}
if(getScreen() == "Playing") {
_testForVictory();
_testForDefeat();
}
if(getScreen() == "Arena" && !isNewArena()) {
_testForNewArenaRun();
}
_image.flush();
}
public boolean getCoin() {
return _coin;
}
public int getDeckSlot() {
return _deckSlot;
}
public String getMode() {
return _mode;
}
public String getOpponentClass() {
return _opponentClass;
}
public String getResult() {
return _result;
}
public String getScreen() {
return _screen;
}
public String getYourClass() {
return _yourClass;
}
public boolean isNewArena() {
return _isNewArena;
}
private void _notifyObserversOfChangeTo(String property) {
setChanged();
notifyObservers(property);
}
public void setIsNewArena(boolean isNew) {
_isNewArena = isNew;
_notifyObserversOfChangeTo("newArena");
}
private void _setDeckSlot(int deckSlot) {
_deckSlot = deckSlot;
_notifyObserversOfChangeTo("deckSlot");
}
private void _setCoin(boolean coin) {
_coin = coin;
_notifyObserversOfChangeTo("coin");
}
private void _setMode(String screen) {
_mode = screen;
_notifyObserversOfChangeTo("mode");
}
private void _setOpponentClass(String opponentClass) {
_opponentClass = opponentClass;
_notifyObserversOfChangeTo("opponentClass");
}
private void _setResult(String result) {
_result = result;
_notifyObserversOfChangeTo("result");
}
private void _setScreen(String screen) {
_screen = screen;
_notifyObserversOfChangeTo("screen");
}
private void _setYourClass(String yourClass) {
_yourClass = yourClass;
_notifyObserversOfChangeTo("yourClass");
}
private void _testForArenaEnd() {
int[][] tests = {
{ 315, 387, 239, 32, 39 },
{ 399, 404, 237, 41, 33 },
{ 448, 408, 223, 8, 16 }
};
if((new PixelGroupTest(_image, tests)).passed()) {
_screen = "Arena";
_notifyObserversOfChangeTo("arenaEnd");
}
}
private void _testForArenaModeScreen() {
int[][] tests = {
{ 807, 707, 95, 84, 111 },
{ 324, 665, 77, 114, 169 },
{ 120, 685, 255, 215, 115 },
{ 697, 504, 78, 62, 56 }
};
if((new PixelGroupTest(_image, tests)).passed()) {
_setScreen("Arena");
_setMode("Arena");
}
}
private void _testForCasualMode() {
int[][] tests = {
{ 833, 94, 100, 22, 16 }, // ranked off
{ 698, 128, 200, 255, 255 } // casual blue
};
if((new PixelGroupTest(_image, tests)).passed())
_setMode("Casual");
}
private void _testForCoin() {
int[][] tests = {
// fourth card right edge
{ 869, 389, 155, 250, 103 },
{ 864, 328, 130, 255, 85 },
{ 864, 379, 126, 255, 82 }
};
if((new PixelGroupTest(_image, tests)).passedOr())
_setCoin(true);
}
private void _testForDeckSlot() {
if(getDeckSlot() != 1) {
int[][] slotOnePixels = {
{ 163, 178, 33, 129, 242},
{ 183, 178, 33, 129, 242}
};
if((new PixelGroupTest(_image, slotOnePixels)).passedOr())
_setDeckSlot(1);
}
if(getDeckSlot() != 2) {
int[][] slotTwoPixels = {
{ 348, 178, 36, 144, 247 },
{ 368, 178, 36, 144, 247 }
};
if((new PixelGroupTest(_image, slotTwoPixels)).passedOr())
_setDeckSlot(2);
}
if(getDeckSlot() != 3) {
int[][] slotTwoPixels = {
{ 506, 178, 36, 144, 247 },
{ 526, 178, 36, 144, 247 }
};
if((new PixelGroupTest(_image, slotTwoPixels)).passedOr())
_setDeckSlot(3);
}
if(getDeckSlot() != 4) {
int[][] slotOnePixels = {
{ 163, 339, 33, 129, 242},
{ 183, 339, 33, 129, 242}
};
if((new PixelGroupTest(_image, slotOnePixels)).passedOr())
_setDeckSlot(4);
}
if(getDeckSlot() != 5) {
int[][] slotTwoPixels = {
{ 348, 339, 36, 144, 247 },
{ 368, 339, 36, 144, 247 }
};
if((new PixelGroupTest(_image, slotTwoPixels)).passedOr())
_setDeckSlot(5);
}
if(getDeckSlot() != 6) {
int[][] slotTwoPixels = {
{ 506, 339, 36, 144, 247 },
{ 526, 339, 36, 144, 247 }
};
if((new PixelGroupTest(_image, slotTwoPixels)).passedOr())
_setDeckSlot(6);
}
if(getDeckSlot() != 7) {
int[][] slotOnePixels = {
{ 163, 497, 33, 129, 242},
{ 183, 497, 33, 129, 242}
};
if((new PixelGroupTest(_image, slotOnePixels)).passedOr())
_setDeckSlot(7);
}
if(getDeckSlot() != 8) {
int[][] slotTwoPixels = {
{ 348, 497, 36, 144, 247 },
{ 368, 497, 36, 144, 247 }
};
if((new PixelGroupTest(_image, slotTwoPixels)).passedOr())
_setDeckSlot(8);
}
if(getDeckSlot() != 9) {
int[][] slotTwoPixels = {
{ 506, 497, 36, 144, 247 },
{ 526, 497, 36, 144, 247 }
};
if((new PixelGroupTest(_image, slotTwoPixels)).passedOr())
_setDeckSlot(9);
}
}
private void _testForDefeat() {
int[][] tests = {
{ 745, 219, 164, 162, 155 },
{ 344, 383, 134, 153, 239 },
{ 696, 357, 201, 197, 188 }
};
PixelGroupTest pxTest = new PixelGroupTest(_image, tests);
int[][] testsTwo = {
{ 347, 382, 129, 148, 236 },
{ 275, 345, 137, 138, 134 },
{ 537, 155, 235, 226, 67 }
};
PixelGroupTest pxTestTwo = new PixelGroupTest(_image, testsTwo);
int[][] testsThree = {
{ 347, 382, 129, 148, 236 },
{ 275, 345, 137, 138, 134 },
{ 537, 155, 235, 226, 67 }
};
PixelGroupTest pxTestThree = new PixelGroupTest(_image, testsThree);
if (pxTest.passed() || pxTestTwo.passed() || pxTestThree.passed()) {
_setScreen("Result");
_setResult("Defeat");
}
}
private void _testForClass(String className, int[][] pixelTests, boolean isYours) {
if((new PixelGroupTest(_image, pixelTests)).passed()) {
if(isYours)
_setYourClass(className);
else
_setOpponentClass(className);
}
}
private void _testForFindingOpponent() {
int[][] tests = {
{ 401, 143, 180, 122, 145 }, // title bar
{ 765, 583, 121, 72, 100 } // bottom bar
};
PixelGroupTest pxTest = new PixelGroupTest(_image, tests);
int[][] arenaTests = {
{ 393, 145, 205, 166, 135 }, // title bar
{ 819, 235, 109, 87, 79 },
{ 839, 585, 139, 113, 77 }
};
PixelGroupTest arenaPxTest = new PixelGroupTest(_image, arenaTests);
if (pxTest.passed() || arenaPxTest.passed()) {
_coin = false;
_yourClass = null;
_opponentClass = null;
_setScreen("Finding Opponent");
}
}
private void _testForMainMenuScreen() {
int[][] tests = {
{ 338, 453, 159, 96, 42 }, // box top
{ 211, 658, 228, 211, 116 }, // quest button exclamation mark
{ 513, 148, 36, 23, 24 } // dark vertical line in top center
};
if((new PixelGroupTest(_image, tests)).passed())
_setScreen("Main Menu");
}
private void _testForMatchStartScreen() {
int[][] tests = {
{ 403, 487, 201, 173, 94 }, // title bar
{ 946, 149, 203, 174, 96 } // bottom bar
};
if ((new PixelGroupTest(_image, tests)).passed()) {
_setScreen("Match Start");
}
}
private void _testForNewArenaRun() {
int[][] tests = {
{ 298, 170, 255, 239, 148 }, // key
//{ 492, 204, 128, 79, 47 }, // key stem
{ 382, 294, 255, 255, 255 }, // zero
{ 393, 281, 255, 255, 255 }, // zero
{ 321, 399, 209, 179, 127 }, // no red x
};
if ((new PixelGroupTest(_image, tests)).passed()) {
setIsNewArena(true);
}
}
private void _testForOpponentClass() {
// Druid Test
int[][] druidTests = {
{ 743, 118, 205, 255, 242 },
{ 882, 141, 231, 255, 252 },
{ 766, 215, 203, 160, 198 }
};
_testForClass("Druid", druidTests, false);
// Hunter Test
int[][] hunterTests = {
{ 825, 66, 173, 178, 183 },
{ 818, 175, 141, 37, 0 },
{ 739, 309, 216, 214, 211 }
};
_testForClass("Hunter", hunterTests, false);
// Mage Test
int[][] mageTests = {
{ 790, 68, 88, 23, 99 },
{ 788, 312, 215, 188, 177 },
{ 820, 247, 53, 64, 82 }
};
_testForClass("Mage", mageTests, false);
// Paladin Test
int[][] paladinTests = {
{ 895, 213, 255, 247, 147 },
{ 816, 301, 125, 237, 255 },
{ 767, 82, 133, 107, 168 }
};
_testForClass("Paladin", paladinTests, false);
// Priest Test
int[][] priestTests = {
{ 724, 189, 255, 236, 101 },
{ 796, 243, 58, 72, 138 },
{ 882, 148, 27, 20, 38 }
};
_testForClass("Priest", priestTests, false);
// Rogue Test
int[][] rogueTests = {
{ 889, 254, 132, 196, 72 },
{ 790, 273, 88, 21, 34 },
{ 841, 73, 100, 109, 183 }
};
_testForClass("Rogue", rogueTests, false);
// Shaman Test
int[][] shamanTests = {
{ 748, 94, 5, 50, 100 },
{ 887, 169, 234, 50, 32 },
{ 733, 206, 186, 255, 255 }
};
_testForClass("Shaman", shamanTests, false);
// Warlock Test
int[][] warlockTests = {
{ 711, 203, 127, 142, 36 },
{ 832, 264, 240, 244, 252 },
{ 832, 65, 98, 129, 0 }
};
_testForClass("Warlock", warlockTests, false);
// Warrior Test
int[][] warriorTests = {
{ 795, 64, 37, 4, 0 },
{ 780, 83, 167, 23, 4 },
{ 809, 92, 255, 247, 227 }
};
_testForClass("Warrior", warriorTests, false);
}
private void _testForPlayingScreen() {
// check for normal play boards
int[][] tests = {
{ 336, 203, 231, 198, 124 },
{ 763, 440, 234, 198, 124 }
};
PixelGroupTest normalPxTest = new PixelGroupTest(_image, tests);
// check for lighter orc board
int[][] orcBoardTests = {
{ 906, 283, 222, 158, 94 },
{ 120, 468, 195, 134, 78 }
};
PixelGroupTest orcPxTest = new PixelGroupTest(_image, orcBoardTests);
if (normalPxTest.passed() || orcPxTest.passed())
_setScreen("Playing");
}
private void _testForPlayScreen() {
int[][] tests = {
{ 543, 130, 121, 32, 22 }, // play mode red background
{ 254, 33, 197, 173, 132 }, // mode title light brown background
{ 956, 553, 24, 8, 8 },
{ 489, 688, 68, 65, 63 }
};
if((new PixelGroupTest(_image, tests)).passed())
_setScreen("Play");
}
private void _testForRankedMode() {
int[][] tests = {
{ 833, 88, 220, 255, 255 }, // ranked blue
{ 698, 120, 56, 16, 8 } // casual off
};
if((new PixelGroupTest(_image, tests)).passed())
_setMode("Ranked");
}
private void _testForVictory() {
int[][] tests = {
{ 334, 504, 88, 101, 192 },
{ 683, 510, 74, 88, 173 },
{ 549, 162, 255, 224, 119 }
};
PixelGroupTest pxTest = new PixelGroupTest(_image, tests);
int[][] testsTwo = {
{ 347, 469, 85, 102, 203 },
{ 737, 339, 63, 76, 148 },
{ 774, 214, 253, 243, 185 }
};
PixelGroupTest pxTestTwo = new PixelGroupTest(_image, testsTwo);
int[][] testsThree = {
{ 370, 528, 66, 81, 165 },
{ 690, 553, 63, 76, 162 },
{ 761, 228, 249, 234, 163 }
};
PixelGroupTest pxTestThree = new PixelGroupTest(_image, testsThree);
if(pxTest.passed() || pxTestTwo.passed() || pxTestThree.passed()) {
_setScreen("Result");
_setResult("Victory");
}
}
private void _testForYourClass() {
// Druid Test
int[][] druidTests = {
{ 225, 480, 210, 255, 246 },
{ 348, 510, 234, 255, 251 },
{ 237, 607, 193, 155, 195 }
};
_testForClass("Druid", druidTests, true);
// Hunter Test
int[][] hunterTests = {
{ 289, 438, 173, 161, 147 },
{ 366, 554, 250, 200, 81 },
{ 210, 675, 209, 209, 211 }
};
_testForClass("Hunter", hunterTests, true);
// Mage Test
int[][] mageTests = {
{ 259, 439, 96, 31, 102 },
{ 294, 677, 219, 210, 193 },
{ 216, 591, 0, 0, 56 }
};
_testForClass("Mage", mageTests, true);
// Paladin Test
int[][] paladinTests = {
{ 249, 447, 133, 105, 165 },
{ 304, 671, 74, 146, 234 },
{ 368, 581, 244, 238, 141 }
};
_testForClass("Paladin", paladinTests, true);
// Priest Test
int[][] priestTests = {
{ 229, 491, 180, 178, 166 },
{ 256, 602, 82, 104, 204 },
{ 350, 611, 22, 23, 27 }
};
_testForClass("Priest", priestTests, true);
// Rogue Test
int[][] rogueTests = {
{ 309, 446, 91, 107, 175 },
{ 291, 468, 187, 37, 25 },
{ 362, 623, 122, 186, 67 }
};
_testForClass("Rogue", rogueTests, true);
// Shaman Test
int[][] shamanTests = {
{ 223, 458, 4, 46, 93 },
{ 360, 533, 213, 32, 6 },
{ 207, 578, 177, 245, 249 }
};
_testForClass("Shaman", shamanTests, true);
// Warlock Test
int[][] warlockTests = {
{ 301, 435, 104, 138, 8 },
{ 265, 493, 221, 51, 32 },
{ 294, 680, 60, 75, 182 }
};
_testForClass("Warlock", warlockTests, true);
// Warrior Test
int[][] warriorTests = {
{ 252, 452, 163, 10, 0 },
{ 291, 579, 234, 192, 53 },
{ 280, 461, 255, 245, 225 }
};
_testForClass("Warior", warriorTests, true);
}
}
|
// PrairieReader.java
package loci.formats.in;
import java.io.*;
import java.text.*;
import java.util.*;
import loci.formats.*;
import loci.formats.meta.MetadataStore;
public class PrairieReader extends FormatReader {
// -- Constants --
// Private tags present in Prairie TIFF files
// IMPORTANT NOTE: these are the same as Metamorph's private tags - therefore,
// it is likely that Prairie TIFF files will be incorrectly
// identified unless the XML or CFG file is specified
private static final int PRAIRIE_TAG_1 = 33628;
private static final int PRAIRIE_TAG_2 = 33629;
private static final int PRAIRIE_TAG_3 = 33630;
// -- Fields --
/** List of files in the current dataset */
private String[] files;
/** Helper reader for opening images */
private TiffReader tiff;
/** Names of the associated XML files */
private String xmlFile, cfgFile;
private boolean readXML = false, readCFG = false;
// -- Constructor --
/** Constructs a new Prairie TIFF reader. */
public PrairieReader() {
super("Prairie (TIFF)", new String[] {"tif", "tiff", "cfg", "xml"});
}
// -- IFormatReader API methods --
/* @see loci.formats.IFormatReader#isThisType(byte[]) */
public boolean isThisType(byte[] block) {
// adapted from MetamorphReader.isThisType(byte[])
if (block.length < 3) return false;
if (block.length < 8) {
return true; // we have no way of verifying further
}
String s = new String(block);
if (s.indexOf("xml") != -1 && s.indexOf("PV") != -1) return true;
boolean little = (block[0] == 0x49 && block[1] == 0x49);
int ifdlocation = DataTools.bytesToInt(block, 4, little);
if (ifdlocation < 0) return false;
else if (ifdlocation + 1 > block.length) return true;
else {
int ifdnumber = DataTools.bytesToInt(block, ifdlocation, 2, little);
for (int i=0; i<ifdnumber; i++) {
if (ifdlocation + 3 + (i*12) > block.length) {
return false;
}
else {
int ifdtag = DataTools.bytesToInt(block,
ifdlocation + 2 + (i*12), 2, little);
if (ifdtag == PRAIRIE_TAG_1 || ifdtag == PRAIRIE_TAG_2 ||
ifdtag == PRAIRIE_TAG_3)
{
return true;
}
}
}
return false;
}
}
/* @see loci.formats.IFormatReader#fileGroupOption(String) */
public int fileGroupOption(String id) throws FormatException, IOException {
id = id.toLowerCase();
return (id.endsWith(".cfg") || id.endsWith(".xml")) ?
FormatTools.MUST_GROUP : FormatTools.CAN_GROUP;
}
/* @see loci.formats.IFormatReader#getUsedFiles() */
public String[] getUsedFiles() {
FormatTools.assertId(currentId, true, 1);
String[] s = new String[files.length + 2];
System.arraycopy(files, 0, s, 0, files.length);
s[files.length] = xmlFile;
s[files.length + 1] = cfgFile;
return s;
}
/* @see loci.formats.IFormatReader#openBytes(int, byte[]) */
public byte[] openBytes(int no, byte[] buf)
throws FormatException, IOException
{
FormatTools.assertId(currentId, true, 1);
FormatTools.checkPlaneNumber(this, no);
tiff.setId(files[no]);
return tiff.openBytes(0, buf);
}
/* @see loci.formats.IFormatReader#close(boolean) */
public void close(boolean fileOnly) throws IOException {
if (fileOnly && tiff != null) tiff.close(fileOnly);
else if (!fileOnly) close();
}
// -- IFormatHandler API methods --
/* @see loci.formats.IFormatHandler#isThisType(String, boolean) */
public boolean isThisType(String name, boolean open) {
if (!super.isThisType(name, open)) return false; // check extension
if (!isGroupFiles()) return false;
// check if there is an XML file in the same directory
Location f = new Location(name);
f = f.getAbsoluteFile();
Location parent = f.getParentFile();
String[] listing = parent.list();
if (listing == null) return false; // file doesn't exist, or other problem
int xmlCount = 0;
for (int i=0; i<listing.length; i++) {
if (listing[i].toLowerCase().endsWith(".xml")) {
try {
RandomAccessStream s = new RandomAccessStream(
parent.getAbsolutePath() + File.separator + listing[i]);
if (s.readString(512).indexOf("PV") != -1) xmlCount++;
}
catch (IOException e) { }
}
}
if (xmlCount == 0) {
listing = (String[]) Location.getIdMap().keySet().toArray(new String[0]);
for (int i=0; i<listing.length; i++) {
if (listing[i].toLowerCase().endsWith(".xml")) {
try {
RandomAccessStream s = new RandomAccessStream(listing[i]);
if (s.readString(512).indexOf("PV") != -1) xmlCount++;
}
catch (IOException e) { }
}
}
}
boolean xml = xmlCount > 0;
// just checking the filename isn't enough to differentiate between
// Prairie and regular TIFF; open the file and check more thoroughly
return open ? checkBytes(name, 524304) && xml : xml;
}
/* @see loci.formats.IFormatHandler#close() */
public void close() throws IOException {
if (tiff != null) tiff.close();
currentId = xmlFile = cfgFile = null;
tiff = null;
files = null;
readXML = false;
readCFG = false;
}
// -- Internal FormatReader API methods --
/* @see loci.formats.IFormatReader#initFile(String) */
protected void initFile(String id) throws FormatException, IOException {
if (debug) debug("PrairieReader.initFile(" + id + ")");
if (metadata == null) metadata = new Hashtable();
if (core == null) core = new CoreMetadata(1);
if (id.endsWith("xml") || id.endsWith("cfg")) {
// we have been given the XML file that lists TIFF files (best case)
status("Parsing XML");
if (id.endsWith("xml")) {
super.initFile(id);
tiff = new TiffReader();
xmlFile = id;
readXML = true;
}
else if (id.endsWith("cfg")) {
cfgFile = id;
readCFG = true;
}
RandomAccessStream is = new RandomAccessStream(id);
byte[] b = new byte[(int) is.length()];
is.read(b);
is.close();
String s = new String(b);
Vector elements = new Vector();
while (s.length() > 0) {
int ndx = s.indexOf("<");
int val1 = s.indexOf(">", ndx);
if (val1 != -1 && val1 > ndx) {
String sub = s.substring(ndx + 1, val1);
s = s.substring(val1 + 1);
elements.add(sub);
}
}
int zt = 0;
boolean isZ = false;
Vector f = new Vector();
int fileIndex = 1;
if (id.endsWith(".xml")) core.imageCount[0] = 0;
float pixelSizeX = 1f, pixelSizeY = 1f;
String date = null, laserPower = null;
Vector gains = new Vector(), offsets = new Vector();
String pastPrefix = "";
for (int i=1; i<elements.size(); i++) {
String el = (String) elements.get(i);
if (el.indexOf(" ") != -1) {
boolean closed = el.endsWith("/");
String prefix = el.substring(0, el.indexOf(" "));
if (prefix.equals("File")) core.imageCount[0]++;
if (prefix.equals("Frame")) {
zt++;
fileIndex = 1;
}
if (!prefix.equals("Key") && !prefix.equals("Frame")) {
el = el.substring(el.indexOf(" ") + 1);
while (el.indexOf("=") != -1) {
int eq = el.indexOf("=");
String key = el.substring(0, eq);
String value = el.substring(eq + 2, el.indexOf("\"", eq + 2));
if (prefix.equals("File")) {
addMeta(pastPrefix + " " + prefix + " " + fileIndex +
" " + key, value);
if (key.equals("filename")) fileIndex++;
}
else {
addMeta(pastPrefix + " " + prefix + " " + key, value);
if (pastPrefix.equals("PVScan") &&
prefix.equals("Sequence") && key.equals("type"))
{
isZ = value.equals("ZSeries");
}
if (prefix.equals("PVScan") && key.equals("date")) {
date = value;
}
}
el = el.substring(el.indexOf("\"", eq + 2) + 1).trim();
if (prefix.equals("File") && key.equals("filename")) {
File current = new File(id).getAbsoluteFile();
String dir = "";
if (current.exists()) {
dir = current.getPath();
dir = dir.substring(0, dir.lastIndexOf(File.separator) + 1);
}
f.add(dir + value);
}
}
}
else if (prefix.equals("Key")) {
int keyIndex = el.indexOf("key") + 5;
int valueIndex = el.indexOf("value") + 7;
String key = el.substring(keyIndex, el.indexOf("\"", keyIndex));
String value =
el.substring(valueIndex, el.indexOf("\"", valueIndex));
addMeta(key, value);
if (key.equals("pixelsPerLine")) {
core.sizeX[0] = Integer.parseInt(value);
}
else if (key.equals("linesPerFrame")) {
core.sizeY[0] = Integer.parseInt(value);
}
else if (key.equals("micronsPerPixel_XAxis")) {
pixelSizeX = Float.parseFloat(value);
}
else if (key.equals("micronsPerPixel_YAxis")) {
pixelSizeY = Float.parseFloat(value);
}
else if (key.startsWith("pmtGain_")) gains.add(value);
else if (key.startsWith("pmtOffset_")) offsets.add(value);
else if (key.equals(" PVScan date")) date = value;
else if (key.equals("laserPower_0")) laserPower = value;
}
if (!closed) {
pastPrefix = prefix;
if (prefix.equals("Frame")) {
int index = el.indexOf("index") + 7;
String idx = el.substring(index, el.indexOf("\"", index));
pastPrefix += " " + idx;
}
}
}
}
if (id.endsWith("xml")) {
files = new String[f.size()];
f.copyInto(files);
tiff.setId(files[0]);
status("Populating metadata");
if (zt == 0) zt = 1;
core.sizeZ[0] = isZ ? zt : 1;
core.sizeT[0] = isZ ? 1 : zt;
core.sizeC[0] = core.imageCount[0] / (core.sizeZ[0] * core.sizeT[0]);
core.currentOrder[0] = "XYC" + (isZ ? "ZT" : "TZ");
core.pixelType[0] = FormatTools.UINT16;
core.rgb[0] = false;
core.interleaved[0] = false;
core.littleEndian[0] = tiff.isLittleEndian();
core.indexed[0] = tiff.isIndexed();
core.falseColor[0] = false;
MetadataStore store = getMetadataStore();
store.setImageName("", 0);
MetadataTools.populatePixels(store, this);
store.setDimensionsPhysicalSizeX(new Float(pixelSizeX), 0, 0);
store.setDimensionsPhysicalSizeY(new Float(pixelSizeY), 0, 0);
for (int i=0; i<core.sizeC[0]; i++) {
String gain = (String) gains.get(i);
String offset = (String) offsets.get(i);
/*
if (offset != null) {
store.setDetectorSettingsOffset(new Float(offset), 0, i);
}
if (gain != null) {
store.setDetectorSettingsGain(new Float(gain), 0, i);
}
*/
}
if (date != null) {
SimpleDateFormat parse = new SimpleDateFormat("MM/dd/yyyy h:mm:ss a");
Date d = parse.parse(date, new ParsePosition(0));
SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
date = fmt.format(d);
}
store.setImageCreationDate(date, 0);
/*
if (laserPower != null) {
store.setLaserPower(new Float(laserPower), 0, 0);
}
*/
// CTR CHECK
/*
String zoom = (String) getMeta("opticalZoom");
if (zoom != null) {
store.setDisplayOptions(new Float(zoom),
new Boolean(core.sizeC[0] > 1), new Boolean(core.sizeC[0] > 1),
new Boolean(core.sizeC[0] > 2), Boolean.FALSE,
null, null, null, null, null, null, null, null, null, null, null);
}
*/
}
if (!readXML || !readCFG) {
File file = new File(id).getAbsoluteFile();
File parent = file.getParentFile();
String[] listing = file.exists() ? parent.list() :
(String[]) Location.getIdMap().keySet().toArray(new String[0]);
for (int i=0; i<listing.length; i++) {
String path = listing[i].toLowerCase();
if ((!readXML && path.endsWith(".xml")) ||
(readXML && path.endsWith(".cfg")))
{
String dir = "";
if (file.exists()) {
dir = parent.getPath();
if (!dir.endsWith(File.separator)) dir += File.separator;
}
initFile(dir + listing[i]);
}
}
}
}
else {
// we have been given a TIFF file - reinitialize with the proper XML file
status("Finding XML file");
Location f = new Location(id);
f = f.getAbsoluteFile();
Location parent = f.getParentFile();
String[] listing = parent.list();
for (int i=0; i<listing.length; i++) {
String path = listing[i].toLowerCase();
if (path.endsWith(".xml") || path.endsWith(".cfg")) {
initFile(new Location(path).getAbsolutePath());
}
}
}
if (currentId == null) currentId = id;
}
}
|
package nl.rutgerkok.blocklocker.impl.nms;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import org.bukkit.Bukkit;
import org.bukkit.World;
import org.bukkit.block.Sign;
import org.json.simple.JSONArray;
import org.json.simple.JSONValue;
import com.google.common.base.Optional;
/**
* Implementation of methods required by
* nl.rutgerkok.chestsignprotect.impl.NMSAccessor for Minecraft 1.7.8 and 1.7.9.
*
*/
public final class NMSAccessor implements ServerSpecific {
static Object call(Object on, Method method, Object... parameters) {
try {
return method.invoke(on, parameters);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
static Object enumField(Class<Enum<?>> enumClass, String name) {
try {
Method valueOf = getMethod(Enum.class, "valueOf", Class.class, String.class);
return invokeStatic(valueOf, enumClass, name);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
static Constructor<?> getConstructor(Class<?> clazz, Class<?>... paramTypes) {
try {
return clazz.getConstructor(paramTypes);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
static Field getField(Class<?> clazz, String name) {
try {
return clazz.getField(name);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
static Method getMethod(Class<?> clazz, String name, Class<?>... parameterTypes) {
try {
return clazz.getMethod(name, parameterTypes);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
/**
* Gets the Minecraft class version of the server, like "v1_8_R2".
*
* @return Minecraft class version.
*/
private static String getMinecraftClassVersion() {
String serverClassName = Bukkit.getServer().getClass().getName();
String version = serverClassName.split("\\.")[3];
if (!version.startsWith("v")) {
throw new AssertionError("Failed to detect Minecraft version, found " + version + " in " + serverClassName);
}
return version;
}
static Object invokeStatic(Method method, Object... parameters) {
return call(null, method, parameters);
}
static Object newInstance(Constructor<?> constructor, Object... params) {
try {
return constructor.newInstance(params);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
static Object retrieve(Object on, Field field) {
try {
return field.get(on);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
private final String nmsPrefix;
private final String obcPrefix;
final Class<?> BlockPosition;
final Constructor<?> BlockPosition_new;
final Class<?> ChatComponentText;
final Constructor<?> ChatComponentText_new;
final Class<?> ChatHoverable;
final Method ChatHoverable_getChatComponent;
final Constructor<?> ChatHoverable_new;
final Class<?> ChatModifier;
final Method ChatModifier_getGetHoverEvent;
final Constructor<?> ChatModifier_new;
final Class<?> CraftChatMessage;
final Method CraftChatMessage_fromComponent;
final Class<?> CraftWorld;
final Method CraftWorld_getHandle;
final Class<Enum<?>> EnumHoverAction;
final Object EnumHoverAction_SHOW_TEXT;
final Class<?> IChatBaseComponent;
final Method IChatBaseComponent_getChatModifier;
final Method ChatModifier_setChatHoverable;
final Class<?> TileEntitySign;
final Field TileEntitySign_lines;
final Class<?> WorldServer;
final Method WorldServer_getTileEntity;
public NMSAccessor() {
String version = getMinecraftClassVersion();
nmsPrefix = "net.minecraft.server." + version + ".";
obcPrefix = "org.bukkit.craftbukkit." + version + ".";
BlockPosition = getNMSClass("BlockPosition");
WorldServer = getNMSClass("WorldServer");
ChatModifier = getNMSClass("ChatModifier");
ChatHoverable = getNMSClass("ChatHoverable");
IChatBaseComponent = getNMSClass("IChatBaseComponent");
EnumHoverAction = getAnyNMSEnum("EnumHoverAction", "ChatHoverable$EnumHoverAction");
TileEntitySign = getNMSClass("TileEntitySign");
ChatComponentText = getNMSClass("ChatComponentText");
CraftWorld = getOBCClass("CraftWorld");
CraftChatMessage = getOBCClass("util.CraftChatMessage");
CraftWorld_getHandle = getMethod(CraftWorld, "getHandle");
CraftChatMessage_fromComponent = getMethod(CraftChatMessage, "fromComponent", IChatBaseComponent);
WorldServer_getTileEntity = getMethod(WorldServer, "getTileEntity", BlockPosition);
IChatBaseComponent_getChatModifier = getMethod(IChatBaseComponent, "getChatModifier");
ChatModifier_setChatHoverable = getMethod(ChatModifier, "setChatHoverable", ChatHoverable);
ChatModifier_getGetHoverEvent = getMethod(ChatModifier, "getHoverEvent");
ChatHoverable_getChatComponent = getMethod(ChatHoverable, "b");
ChatComponentText_new = getConstructor(ChatComponentText, String.class);
BlockPosition_new = getConstructor(BlockPosition, int.class, int.class, int.class);
ChatModifier_new = getConstructor(ChatModifier);
ChatHoverable_new = getConstructor(ChatHoverable, EnumHoverAction, IChatBaseComponent);
TileEntitySign_lines = getField(TileEntitySign, "lines");
EnumHoverAction_SHOW_TEXT = enumField(EnumHoverAction, "SHOW_TEXT");
}
private String chatComponentToString(Object chatComponent) {
return (String) invokeStatic(CraftChatMessage_fromComponent, chatComponent);
}
Class<Enum<?>> getAnyNMSEnum(String... possibleNames) {
Exception lastException = null;
for (String name : possibleNames) {
try {
return getNMSEnum(name);
} catch (Exception e) {
lastException = e;
}
}
throw new RuntimeException(lastException);
}
Object getBlockPosition(int x, int y, int z) {
return newInstance(BlockPosition_new, x, y, z);
}
@Override
public JsonSign getJsonData(World world, int x, int y, int z) {
// Find sign
Optional<?> nmsSign = toNmsSign(world, x, y, z);
if (!nmsSign.isPresent()) {
return JsonSign.EMPTY;
}
// Find strings stored in hovertext
Optional<String> secretData = getSecretData(nmsSign.get());
if (!secretData.isPresent()) {
return JsonSign.EMPTY;
}
// Find first line
Object firstLineObj = ((Object[]) retrieve(nmsSign.get(), TileEntitySign_lines))[0];
String firstLine = firstLineObj == null ? "" : chatComponentToString(firstLineObj);
// Parse and sanitize the sting
Object data = JSONValue.parse(secretData.get());
if (data instanceof JSONArray) {
return new JsonSign(firstLine, (JSONArray) data);
}
return JsonSign.EMPTY;
}
Class<?> getNMSClass(String name) {
try {
return Class.forName(nmsPrefix + name);
} catch (ClassNotFoundException e) {
throw new RuntimeException(e);
}
}
Class<Enum<?>> getNMSEnum(String name) {
Class<?> clazz = getNMSClass(name);
if (!clazz.isEnum()) {
throw new IllegalArgumentException(clazz + " is not an enum");
}
@SuppressWarnings("unchecked")
Class<Enum<?>> enumClazz = (Class<Enum<?>>) clazz;
return enumClazz;
}
Class<?> getOBCClass(String name) {
try {
return Class.forName(obcPrefix + name);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
private Optional<String> getSecretData(Object tileEntitySign) {
Object line = ((Object[]) retrieve(tileEntitySign, TileEntitySign_lines))[0];
if (line == null) {
return Optional.absent();
}
Object chatModifier = call(line, IChatBaseComponent_getChatModifier);
if (chatModifier == null) {
return Optional.absent();
}
Object chatHoverable = call(chatModifier, ChatModifier_getGetHoverEvent);
if (chatHoverable == null) {
return Optional.absent();
}
return Optional.of(chatComponentToString(call(chatHoverable, ChatHoverable_getChatComponent)));
}
@Override
public void setJsonData(Sign sign, JSONArray jsonArray) {
Optional<?> nmsSign = toNmsSign(sign.getWorld(), sign.getX(), sign.getY(), sign.getZ());
if (!nmsSign.isPresent()) {
throw new RuntimeException("No sign at " + sign.getLocation());
}
setSecretData(nmsSign.get(), jsonArray.toJSONString());
}
private void setSecretData(Object tileEntitySign, String data) {
Object line = ((Object[]) retrieve(tileEntitySign, TileEntitySign_lines))[0];
Object modifier = call(line, IChatBaseComponent_getChatModifier);
if (modifier == null) {
modifier = newInstance(ChatModifier_new);
}
Object chatComponentText = newInstance(ChatComponentText_new, data);
Object hoverable = newInstance(ChatHoverable_new, EnumHoverAction_SHOW_TEXT, chatComponentText);
call(modifier, ChatModifier_setChatHoverable, hoverable);
}
private Optional<?> toNmsSign(World world, int x, int y, int z) {
Object nmsWorld = call(world, CraftWorld_getHandle);
Object tileEntity = call(nmsWorld, WorldServer_getTileEntity, getBlockPosition(x, y, z));
if (!TileEntitySign.isInstance(tileEntity)) {
return Optional.absent();
}
return Optional.of(tileEntity);
}
}
|
package org.bdgp.OpenHiCAMM;
import java.util.List;
import java.util.ArrayList;
import org.micromanager.acquisition.MMAcquisition;
import org.micromanager.utils.MMScriptException;
public class MMAcquisitionCache {
private static List<MMCache> cache = new ArrayList<MMCache>();
private static final int MAX_CACHE = 2;
private MMAcquisitionCache() { }
public static synchronized MMAcquisition getAcquisition(
String name,
String dir,
boolean show,
boolean diskCached,
boolean existing)
{
MMCache mmCache = new MMCache(name, dir, show, diskCached, existing);
if (!cache.contains(mmCache)) {
if (cache.size() >= MAX_CACHE) cache.remove(0);
cache.add(mmCache);
}
return cache.get(cache.indexOf(mmCache)).getAcquisition();
}
public static class MMCache {
private String name;
private String dir;
private boolean show;
private boolean diskCached;
private boolean existing;
private MMAcquisition acquisition;
public MMCache(String name, String dir, boolean show, boolean diskCached, boolean existing) {
this.name = name;
this.dir = dir;
this.show = show;
this.diskCached = diskCached;
this.existing = existing;
}
public String getName() { return name; }
public String getDir() { return dir; }
public boolean isShow() { return show; }
public boolean isDiskCached() { return diskCached; }
public boolean isExisting() { return existing; }
public MMAcquisition getAcquisition() {
if (this.acquisition == null) {
try {
this.acquisition = new MMAcquisition(name, dir, show, diskCached, existing);
this.acquisition.initialize();
}
catch (MMScriptException e) {throw new RuntimeException(e);}
}
return this.acquisition;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((dir == null) ? 0 : dir.hashCode());
result = prime * result + (diskCached ? 1231 : 1237);
result = prime * result + (existing ? 1231 : 1237);
result = prime * result + ((name == null) ? 0 : name.hashCode());
result = prime * result + (show ? 1231 : 1237);
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
MMCache other = (MMCache) obj;
if (dir == null) {
if (other.dir != null)
return false;
} else if (!dir.equals(other.dir))
return false;
if (diskCached != other.diskCached)
return false;
if (existing != other.existing)
return false;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
if (show != other.show)
return false;
return true;
}
}
}
|
package net.hearthstats;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.Toolkit;
import java.awt.image.BufferedImage;
import java.awt.image.BufferedImageOp;
import java.awt.image.ColorConvertOp;
import java.awt.image.CropImageFilter;
import java.awt.image.DataBufferInt;
import java.awt.image.FilteredImageSource;
import java.awt.image.RescaleOp;
import java.io.File;
import java.io.IOException;
import java.util.Observable;
import javax.imageio.ImageIO;
import net.sourceforge.tess4j.Tesseract;
import net.sourceforge.tess4j.TesseractException;
public class HearthstoneAnalyzer extends Observable {
private boolean _coin;
private BufferedImage _image;
private String _mode;
private String _opponentClass;
private String _opponentName;
private String _result;
private String _screen;
private String _yourClass;
private int _deckSlot;
private boolean _isNewArena = false;
private float _ratio;
private int _xOffset;
private int _width;
private int _height;
private float _screenRatio;
public HearthstoneAnalyzer() {
}
public void analyze(BufferedImage image) {
_image = image;
_calculateResolutionRatios();
if(getScreen() != "Main Menu" && getScreen() != "Playing") {
_testForMainMenuScreen();
}
if(getScreen() != "Play") {
_testForPlayScreen();
}
if(getScreen() != "Arena") {
_testForArenaModeScreen();
}
if(getScreen() == "Play" || getScreen() == "Arena") {
_testForFindingOpponent();
if (getScreen() == "Play") {
if(getMode() != "Casual")
_testForCasualMode();
if(getMode() != "Ranked")
_testForRankedMode();
_testForDeckSlot();
}
}
if(getScreen() == "Match Start" || getScreen() == "Opponent Name") {
if(getYourClass() == null)
_testForYourClass();
if(getOpponentClass() == null)
_testForOpponentClass();
if(!getCoin())
_testForCoin();
if(getScreen() != "Opponent Name")
_testForOpponentName();
} else {
if(getScreen() != "Playing")
_testForMatchStartScreen();
}
if(getScreen() == "Result" || getScreen() == "Arena") {
_testForArenaEnd();
}
if(getScreen() == "Playing") {
_testForVictory();
_testForDefeat();
} else {
if(getScreen() != "Result")
_testForPlayingScreen();
}
if(getScreen() == "Arena" && !isNewArena()) {
_testForNewArenaRun();
}
_image.flush();
}
private void _calculateResolutionRatios() {
// handle 4:3 screen ratios
_ratio = _image.getHeight() / (float) 768;
_xOffset = 0;
_width = _image.getWidth();
_height = _image.getHeight();
_screenRatio = (float) _width / _height;
// handle widescreen x offsets
if(_screenRatio > 1.4) {
_xOffset = 107;
_xOffset = (int) (((float) _width - (_ratio * 1024)) / 2);
}
}
public boolean getCoin() {
return _coin;
}
public int getDeckSlot() {
return _deckSlot;
}
public String getMode() {
return _mode;
}
public String getOpponentClass() {
return _opponentClass;
}
public String getOpponentName() {
return _opponentName;
}
public String getResult() {
return _result;
}
public String getScreen() {
return _screen;
}
public String getYourClass() {
return _yourClass;
}
public boolean isNewArena() {
return _isNewArena;
}
private void _notifyObserversOfChangeTo(String property) {
setChanged();
notifyObservers(property);
}
public void setIsNewArena(boolean isNew) {
_isNewArena = isNew;
_notifyObserversOfChangeTo("newArena");
}
private void _setDeckSlot(int deckSlot) {
_deckSlot = deckSlot;
_notifyObserversOfChangeTo("deckSlot");
}
private void _setCoin(boolean coin) {
_coin = coin;
_notifyObserversOfChangeTo("coin");
}
private void _setMode(String screen) {
_mode = screen;
_notifyObserversOfChangeTo("mode");
}
private void _setOpponentClass(String opponentClass) {
_opponentClass = opponentClass;
_notifyObserversOfChangeTo("opponentClass");
}
private void _setOpponentName(String opponentName) {
_opponentName = opponentName;
_notifyObserversOfChangeTo("opponentName");
}
private void _setResult(String result) {
_result = result;
_notifyObserversOfChangeTo("result");
}
private void _setScreen(String screen) {
_screen = screen;
_notifyObserversOfChangeTo("screen");
}
private void _setYourClass(String yourClass) {
_yourClass = yourClass;
_notifyObserversOfChangeTo("yourClass");
}
private void _testForArenaEnd() {
int[][] tests = {
{ 315, 387, 239, 32, 39 },
{ 399, 404, 237, 41, 33 },
{ 448, 408, 223, 8, 16 }
};
if((new PixelGroupTest(_image, tests)).passed()) {
_screen = "Arena";
_notifyObserversOfChangeTo("arenaEnd");
}
}
private void _testForArenaModeScreen() {
int[][] tests = {
{ 807, 707, 95, 84, 111 },
{ 324, 665, 77, 114, 169 },
{ 120, 685, 255, 215, 115 },
{ 697, 504, 78, 62, 56 }
};
if((new PixelGroupTest(_image, tests)).passed()) {
_setScreen("Arena");
_setMode("Arena");
}
}
private void _testForCasualMode() {
int[][] tests = {
{ 833, 94, 100, 22, 16 }, // ranked off
{ 698, 128, 200, 255, 255 } // casual blue
};
PixelGroupTest testOne = new PixelGroupTest(_image, tests);
int[][] testsTwo = {
{ 812, 178, 255, 255, 255},
{ 758, 202, 215, 255, 255 }
};
PixelGroupTest testTwo = new PixelGroupTest(_image, testsTwo);
if(testOne.passed() || testTwo.passed())
_setMode("Casual");
}
private void _testForCoin() {
int[][] tests = {
// fourth card right edge
{ 869, 389, 155, 250, 103 },
{ 864, 328, 130, 255, 85 },
{ 870, 340, 127, 255, 83 },
{ 769, 280, 125, 255, 82 },
{ 864, 379, 126, 255, 82 }
};
if((new PixelGroupTest(_image, tests)).passedOr())
_setCoin(true);
}
private void _testForDeckSlot() {
if(getDeckSlot() != 1) {
int[][] slotOnePixels = {
{ 163, 178, 33, 129, 242},
{ 183, 178, 33, 129, 242}
};
if((new PixelGroupTest(_image, slotOnePixels)).passedOr())
_setDeckSlot(1);
}
if(getDeckSlot() != 2) {
int[][] slotTwoPixels = {
{ 348, 178, 36, 144, 247 },
{ 368, 178, 36, 144, 247 }
};
if((new PixelGroupTest(_image, slotTwoPixels)).passedOr())
_setDeckSlot(2);
}
if(getDeckSlot() != 3) {
int[][] slotTwoPixels = {
{ 506, 178, 36, 144, 247 },
{ 526, 178, 36, 144, 247 }
};
if((new PixelGroupTest(_image, slotTwoPixels)).passedOr())
_setDeckSlot(3);
}
if(getDeckSlot() != 4) {
int[][] slotOnePixels = {
{ 163, 339, 33, 129, 242},
{ 183, 339, 33, 129, 242}
};
if((new PixelGroupTest(_image, slotOnePixels)).passedOr())
_setDeckSlot(4);
}
if(getDeckSlot() != 5) {
int[][] slotTwoPixels = {
{ 348, 339, 36, 144, 247 },
{ 368, 339, 36, 144, 247 }
};
if((new PixelGroupTest(_image, slotTwoPixels)).passedOr())
_setDeckSlot(5);
}
if(getDeckSlot() != 6) {
int[][] slotTwoPixels = {
{ 506, 339, 36, 144, 247 },
{ 526, 339, 36, 144, 247 }
};
if((new PixelGroupTest(_image, slotTwoPixels)).passedOr())
_setDeckSlot(6);
}
if(getDeckSlot() != 7) {
int[][] slotOnePixels = {
{ 163, 497, 33, 129, 242},
{ 183, 497, 33, 129, 242}
};
if((new PixelGroupTest(_image, slotOnePixels)).passedOr())
_setDeckSlot(7);
}
if(getDeckSlot() != 8) {
int[][] slotTwoPixels = {
{ 348, 497, 36, 144, 247 },
{ 368, 497, 36, 144, 247 }
};
if((new PixelGroupTest(_image, slotTwoPixels)).passedOr())
_setDeckSlot(8);
}
if(getDeckSlot() != 9) {
int[][] slotTwoPixels = {
{ 506, 497, 36, 144, 247 },
{ 526, 497, 36, 144, 247 }
};
if((new PixelGroupTest(_image, slotTwoPixels)).passedOr())
_setDeckSlot(9);
}
}
private void _testForDefeat() {
int[][] tests = {
{ 745, 219, 164, 162, 155 },
{ 344, 383, 134, 153, 239 },
{ 696, 357, 201, 197, 188 }
};
PixelGroupTest pxTest = new PixelGroupTest(_image, tests);
int[][] testsTwo = {
{ 347, 382, 129, 148, 236 },
{ 275, 345, 137, 138, 134 },
{ 537, 155, 235, 226, 67 }
};
PixelGroupTest pxTestTwo = new PixelGroupTest(_image, testsTwo);
int[][] testsThree = {
{ 347, 382, 129, 148, 236 },
{ 275, 345, 137, 138, 134 },
{ 537, 155, 235, 226, 67 }
};
PixelGroupTest pxTestThree = new PixelGroupTest(_image, testsThree);
if (pxTest.passed() || pxTestTwo.passed() || pxTestThree.passed()) {
_setScreen("Result");
_setResult("Defeat");
}
}
private void _testForClass(String className, int[][] pixelTests, boolean isYours) {
if((new PixelGroupTest(_image, pixelTests)).passed()) {
if(isYours)
_setYourClass(className);
else
_setOpponentClass(className);
}
}
private void _testForFindingOpponent() {
int[][] tests = {
{ 401, 143, 180, 122, 145 }, // title bar
{ 765, 583, 121, 72, 100 } // bottom bar
};
PixelGroupTest pxTest = new PixelGroupTest(_image, tests);
int[][] arenaTests = {
{ 393, 145, 205, 166, 135 }, // title bar
{ 819, 235, 109, 87, 79 },
{ 839, 585, 139, 113, 77 }
};
PixelGroupTest arenaPxTest = new PixelGroupTest(_image, arenaTests);
if (pxTest.passed() || arenaPxTest.passed()) {
_coin = false;
_yourClass = null;
_opponentClass = null;
_opponentName = null;
_setScreen("Finding Opponent");
}
}
private void _testForOpponentName() {
int[][] tests = {
{ 383, 116, 187, 147, 79 }, // title banner left
{ 631, 107, 173, 130, 70 }, // title banner right
{ 505, 595, 129, 199, 255 } // confirm button
};
PixelGroupTest pxTest = new PixelGroupTest(_image, tests);
if(pxTest.passed()) {
_setScreen("Opponent Name");
_analyzeOpponnentName();
}
}
private void _analyzeOpponnentName() {
int x = (int) ((getMode() == "Ranked" ? 76 : 6) * _ratio);
int y = (int) (34 * _ratio); // with class name underneath
// int y = (int) (40 * ratio);
int imageWidth = (int) (150 * _ratio);
int imageHeight = (int) (19 * _ratio);
int bigWidth = imageWidth * 3;
int bigHeight = imageHeight * 3;
// get cropped image of name
BufferedImage opponentNameImg = _image.getSubimage(x, y, imageWidth, imageHeight);
// to gray scale
BufferedImage grayscale = new BufferedImage(opponentNameImg.getWidth(), opponentNameImg.getHeight(), BufferedImage.TYPE_INT_RGB);
BufferedImageOp grayscaleConv =
new ColorConvertOp(opponentNameImg.getColorModel().getColorSpace(),
grayscale.getColorModel().getColorSpace(), null);
grayscaleConv.filter(opponentNameImg, grayscale);
// blow it up for ocr
BufferedImage newImage = new BufferedImage(bigWidth, bigHeight, BufferedImage.TYPE_INT_RGB);
Graphics g = newImage.createGraphics();
g.drawImage(grayscale, 0, 0, bigWidth, bigHeight, null);
g.dispose();
// invert image
for (x = 0; x < newImage.getWidth(); x++) {
for (y = 0; y < newImage.getHeight(); y++) {
int rgba = newImage.getRGB(x, y);
Color col = new Color(rgba, true);
col = new Color(255 - col.getRed(),
255 - col.getGreen(),
255 - col.getBlue());
newImage.setRGB(x, y, col.getRGB());
}
}
// increase contrast
RescaleOp rescaleOp = new RescaleOp(1.8f, -30, null);
rescaleOp.filter(newImage, newImage); // Source and destination are the same.
// save it to a file
File outputfile = new File(Main.getExtractionFolder() + "/opponentname.jpg");
try {
ImageIO.write(newImage, "jpg", outputfile);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
_notifyObserversOfChangeTo("Exception: " + e.getMessage());
}
_setOpponentName(OCR.process(Main.getExtractionFolder() + "/opponentname.jpg"));
}
private void _testForMainMenuScreen() {
int[][] tests = {
{ 338, 453, 159, 96, 42 }, // box top
{ 211, 658, 228, 211, 116 }, // quest button exclamation mark
{ 513, 148, 36, 23, 24 } // dark vertical line in top center
};
if((new PixelGroupTest(_image, tests)).passed())
_setScreen("Main Menu");
}
private void _testForMatchStartScreen() {
int[][] tests = {
{ 403, 487, 201, 173, 94 }, // title bar
{ 946, 149, 203, 174, 96 } // bottom bar
};
if ((new PixelGroupTest(_image, tests)).passed()) {
_setScreen("Match Start");
}
}
private void _testForNewArenaRun() {
int[][] tests = {
{ 298, 170, 255, 239, 148 }, // key
//{ 492, 204, 128, 79, 47 }, // key stem
{ 382, 294, 255, 255, 255 }, // zero
{ 393, 281, 255, 255, 255 }, // zero
{ 321, 399, 209, 179, 127 }, // no red x
};
if ((new PixelGroupTest(_image, tests)).passed()) {
setIsNewArena(true);
}
}
private void _testForOpponentClass() {
// Druid Test
int[][] druidTests = {
{ 743, 118, 205, 255, 242 },
{ 882, 141, 231, 255, 252 },
{ 766, 215, 203, 160, 198 }
};
_testForClass("Druid", druidTests, false);
// Hunter Test
int[][] hunterTests = {
{ 825, 66, 173, 178, 183 },
{ 818, 175, 141, 37, 0 },
{ 739, 309, 216, 214, 211 }
};
_testForClass("Hunter", hunterTests, false);
// Mage Test
int[][] mageTests = {
{ 790, 68, 88, 23, 99 },
{ 788, 312, 215, 188, 177 },
{ 820, 247, 53, 64, 82 }
};
_testForClass("Mage", mageTests, false);
// Paladin Test
int[][] paladinTests = {
{ 895, 213, 255, 247, 147 },
{ 816, 301, 125, 237, 255 },
{ 767, 82, 133, 107, 168 }
};
_testForClass("Paladin", paladinTests, false);
// Priest Test
int[][] priestTests = {
{ 724, 189, 255, 236, 101 },
{ 796, 243, 58, 72, 138 },
{ 882, 148, 27, 20, 38 }
};
_testForClass("Priest", priestTests, false);
// Rogue Test
int[][] rogueTests = {
{ 889, 254, 132, 196, 72 },
{ 790, 273, 88, 21, 34 },
{ 841, 73, 100, 109, 183 }
};
_testForClass("Rogue", rogueTests, false);
// Shaman Test
int[][] shamanTests = {
{ 748, 94, 5, 50, 100 },
{ 887, 169, 234, 50, 32 },
{ 733, 206, 186, 255, 255 }
};
_testForClass("Shaman", shamanTests, false);
// Warlock Test
int[][] warlockTests = {
{ 711, 203, 127, 142, 36 },
{ 832, 264, 240, 244, 252 },
{ 832, 65, 98, 129, 0 }
};
_testForClass("Warlock", warlockTests, false);
// Warrior Test
int[][] warriorTests = {
{ 795, 64, 37, 4, 0 },
{ 780, 83, 167, 23, 4 },
{ 809, 92, 255, 247, 227 }
};
_testForClass("Warrior", warriorTests, false);
}
private void _testForPlayingScreen() {
// check for normal play boards
int[][] tests = {
{ 336, 203, 231, 198, 124 },
{ 763, 440, 234, 198, 124 }
};
PixelGroupTest normalPxTest = new PixelGroupTest(_image, tests);
// check for lighter orc board
int[][] orcBoardTests = {
{ 906, 283, 222, 158, 94 },
{ 120, 468, 195, 134, 78 }
};
PixelGroupTest orcPxTest = new PixelGroupTest(_image, orcBoardTests);
if (normalPxTest.passed() || orcPxTest.passed()) {
_setScreen("Playing");
// _analyzeOpponnentName();
}
}
private void _testForPlayScreen() {
int[][] tests = {
{ 543, 130, 121, 32, 22 }, // play mode red background
{ 254, 33, 197, 173, 132 }, // mode title light brown background
{ 956, 553, 24, 8, 8 },
{ 489, 688, 68, 65, 63 }
};
if((new PixelGroupTest(_image, tests)).passed())
_setScreen("Play");
}
private void _testForRankedMode() {
int[][] tests = {
{ 833, 88, 220, 255, 255 }, // ranked blue
{ 698, 120, 56, 16, 8 } // casual off
};
PixelGroupTest testOne = new PixelGroupTest(_image, tests);
int[][] testsTwo = {
{ 840, 184, 199, 255, 255 },
{ 948, 167, 192, 255, 255 }
};
PixelGroupTest testTwo = new PixelGroupTest(_image, testsTwo);
if(testOne.passed() || testTwo.passed())
_setMode("Ranked");
}
private void _testForVictory() {
int[][] tests = {
{ 334, 504, 88, 101, 192 },
{ 683, 510, 74, 88, 173 },
{ 549, 162, 255, 224, 119 }
};
PixelGroupTest pxTest = new PixelGroupTest(_image, tests);
int[][] testsTwo = {
{ 347, 469, 85, 102, 203 },
{ 737, 339, 63, 76, 148 },
{ 774, 214, 253, 243, 185 }
};
PixelGroupTest pxTestTwo = new PixelGroupTest(_image, testsTwo);
int[][] testsThree = {
{ 370, 528, 66, 81, 165 },
{ 690, 553, 63, 76, 162 },
{ 761, 228, 249, 234, 163 }
};
PixelGroupTest pxTestThree = new PixelGroupTest(_image, testsThree);
if(pxTest.passed() || pxTestTwo.passed() || pxTestThree.passed()) {
_setScreen("Result");
_setResult("Victory");
}
}
private void _testForYourClass() {
// Druid Test
int[][] druidTests = {
{ 225, 480, 210, 255, 246 },
{ 348, 510, 234, 255, 251 },
{ 237, 607, 193, 155, 195 }
};
_testForClass("Druid", druidTests, true);
// Hunter Test
int[][] hunterTests = {
{ 289, 438, 173, 161, 147 },
{ 366, 554, 250, 200, 81 },
{ 210, 675, 209, 209, 211 }
};
_testForClass("Hunter", hunterTests, true);
// Mage Test
int[][] mageTests = {
{ 259, 439, 96, 31, 102 },
{ 294, 677, 219, 210, 193 },
{ 216, 591, 0, 0, 56 }
};
_testForClass("Mage", mageTests, true);
// Paladin Test
int[][] paladinTests = {
{ 249, 447, 133, 105, 165 },
{ 304, 671, 74, 146, 234 },
{ 368, 581, 244, 238, 141 }
};
_testForClass("Paladin", paladinTests, true);
// Priest Test
int[][] priestTests = {
{ 229, 491, 180, 178, 166 },
{ 256, 602, 82, 104, 204 },
{ 350, 611, 22, 23, 27 }
};
_testForClass("Priest", priestTests, true);
// Rogue Test
int[][] rogueTests = {
{ 309, 446, 91, 107, 175 },
{ 291, 468, 187, 37, 25 },
{ 362, 623, 122, 186, 67 }
};
_testForClass("Rogue", rogueTests, true);
// Shaman Test
int[][] shamanTests = {
{ 223, 458, 4, 46, 93 },
{ 360, 533, 213, 32, 6 },
{ 207, 578, 177, 245, 249 }
};
_testForClass("Shaman", shamanTests, true);
// Warlock Test
int[][] warlockTests = {
{ 301, 435, 104, 138, 8 },
{ 265, 493, 221, 51, 32 },
{ 294, 680, 60, 75, 182 }
};
_testForClass("Warlock", warlockTests, true);
// Warrior Test
int[][] warriorTests = {
{ 252, 452, 163, 10, 0 },
{ 291, 579, 234, 192, 53 },
{ 280, 461, 255, 245, 225 }
};
_testForClass("Warior", warriorTests, true);
}
}
|
package nl.topicus.jdbc.transaction;
import java.sql.SQLException;
import java.sql.Savepoint;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
import com.google.cloud.Timestamp;
import com.google.cloud.spanner.DatabaseClient;
import com.google.cloud.spanner.Mutation;
import com.google.cloud.spanner.ResultSet;
import com.google.cloud.spanner.SpannerException;
import com.google.cloud.spanner.Statement;
import com.google.cloud.spanner.TransactionContext;
import com.google.cloud.spanner.TransactionRunner;
import com.google.cloud.spanner.TransactionRunner.TransactionCallable;
import com.google.common.base.Preconditions;
import com.google.rpc.Code;
import nl.topicus.jdbc.CloudSpannerDriver;
import nl.topicus.jdbc.Logger;
import nl.topicus.jdbc.exception.CloudSpannerSQLException;
class TransactionThread extends Thread {
public static class QueryException extends RuntimeException {
private static final long serialVersionUID = 1L;
private QueryException(String message, Throwable cause) {
super(message, cause);
}
}
private static class RollbackException extends RuntimeException {
private static final long serialVersionUID = 1L;
}
enum TransactionStatus {
NOT_STARTED, RUNNING, SUCCESS, FAIL;
}
private enum TransactionStopStatement {
COMMIT, ROLLBACK, PREPARE, COMMIT_PREPARED, ROLLBACK_PREPARED;
}
private final Logger logger;
private final StackTraceElement[] stackTraceElements;
private final Object monitor = new Object();
private DatabaseClient dbClient;
private boolean stop;
private boolean stopped;
private TransactionStatus status = TransactionStatus.NOT_STARTED;
private Timestamp commitTimestamp;
private Exception exception;
private TransactionStopStatement stopStatement = null;
/**
* The XA transaction id to be prepared/committed/rolled back
*/
private String xid;
private final Set<String> stopStatementStrings =
new HashSet<>(Arrays.asList(TransactionStopStatement.values()).stream().map(x -> x.name())
.collect(Collectors.toList()));
private List<Mutation> mutations = new ArrayList<>(40);
private Map<Savepoint, Integer> savepoints = new HashMap<>();
private BlockingQueue<Statement> statements = new LinkedBlockingQueue<>();
private BlockingQueue<ResultSet> resultSets = new LinkedBlockingQueue<>();
private static int threadInitNumber;
private static synchronized int nextThreadNum() {
return threadInitNumber++;
}
TransactionThread(DatabaseClient dbClient, Logger logger) {
super("Google Cloud Spanner JDBC Transaction Thread-" + nextThreadNum());
Preconditions.checkNotNull(dbClient, "dbClient may not be null");
Preconditions.checkNotNull(logger, "logger may not be null");
this.dbClient = dbClient;
this.logger = logger;
if (logger != null && logger.logDebug()) {
this.stackTraceElements = Thread.currentThread().getStackTrace();
} else {
this.stackTraceElements = null;
}
setDaemon(true);
}
@Override
public void run() {
TransactionRunner runner = dbClient.readWriteTransaction();
synchronized (monitor) {
try {
status = runner.run(new TransactionCallable<TransactionStatus>() {
@Override
public TransactionStatus run(TransactionContext transaction) throws Exception {
long startTime = System.currentTimeMillis();
long lastTriggerTime = startTime;
boolean transactionStartedLogged = false;
boolean stackTraceLoggedForKeepAlive = false;
boolean stackTraceLoggedForLongRunning = false;
status = TransactionStatus.RUNNING;
while (!stop) {
try {
Statement statement = statements.poll(5, TimeUnit.SECONDS);
if (statement != null) {
String sql = statement.getSql();
if (!stopStatementStrings.contains(sql)) {
resultSets.put(transaction.executeQuery(statement));
}
} else {
// keep alive
transactionStartedLogged =
logTransactionStarted(transactionStartedLogged, startTime);
logger.info(String.format("%s, %s", getName(),
"Transaction has been inactive for more than 5 seconds and will do a keep-alive query"));
if (!stackTraceLoggedForKeepAlive) {
logStartStackTrace();
stackTraceLoggedForKeepAlive = true;
}
try (ResultSet rs = transaction.executeQuery(Statement.of("SELECT 1"))) {
rs.next();
}
}
if (!stop && logger.logInfo()
&& (System.currentTimeMillis() - lastTriggerTime) > CloudSpannerDriver
.getLongTransactionTrigger()) {
transactionStartedLogged =
logTransactionStarted(transactionStartedLogged, startTime);
logger.info(String.format("%s, %s", getName(), "Transaction has been running for "
+ (System.currentTimeMillis() - startTime) + "ms"));
if (!stackTraceLoggedForLongRunning) {
logStartStackTrace();
stackTraceLoggedForLongRunning = true;
}
lastTriggerTime = System.currentTimeMillis();
}
} catch (InterruptedException e) {
logDebugIfTransactionStartedLogged(transactionStartedLogged,
"Transaction interrupted");
stopped = true;
exception = e;
throw e;
}
}
switch (stopStatement) {
case COMMIT:
logDebugIfTransactionStartedLogged(transactionStartedLogged,
"Transaction committed");
transaction.buffer(mutations);
break;
case ROLLBACK:
// throw an exception to force a rollback
logDebugIfTransactionStartedLogged(transactionStartedLogged,
"Transaction rolled back");
throw new RollbackException();
case PREPARE:
logDebugIfTransactionStartedLogged(transactionStartedLogged,
"Transaction prepare called");
XATransaction.prepareMutations(transaction, xid, mutations);
break;
case COMMIT_PREPARED:
logDebugIfTransactionStartedLogged(transactionStartedLogged,
"Transaction commit prepared called");
XATransaction.commitPrepared(transaction, xid);
break;
case ROLLBACK_PREPARED:
logDebugIfTransactionStartedLogged(transactionStartedLogged,
"Transaction rollback prepared called");
XATransaction.rollbackPrepared(transaction, xid);
break;
}
logDebugIfTransactionStartedLogged(transactionStartedLogged,
"Transaction successfully stopped");
return TransactionStatus.SUCCESS;
}
});
commitTimestamp = runner.getCommitTimestamp();
} catch (Exception e) {
if (e.getCause() instanceof RollbackException) {
status = TransactionStatus.SUCCESS;
} else {
// if statement prevents unnecessary String.format(...) call
if (logger.logDebug()) {
logger.debug(String.format("%s, %s", getName(),
"Transaction threw an exception: " + e.getMessage()));
}
status = TransactionStatus.FAIL;
exception = e;
}
} finally {
stopped = true;
monitor.notifyAll();
}
}
}
private void logDebugIfTransactionStartedLogged(boolean transactionStartedLogged, String log) {
if (transactionStartedLogged) {
logger.debug(String.format("%s, %s", getName(), log));
}
}
private boolean logTransactionStarted(boolean transactionStartedLogged, long startTime) {
if (!transactionStartedLogged) {
logger.debug(String.format("%s, %s", getName(),
"This transaction started at " + new java.sql.Timestamp(startTime).toString()));
}
return true;
}
private void logStartStackTrace() {
if (stackTraceElements != null) {
logger.debug(String.format("%s, %s", getName(), "Transaction was started by: "));
for (StackTraceElement ste : stackTraceElements) {
logger.debug("\t" + ste.toString());
}
}
}
ResultSet executeQuery(Statement statement) {
try {
statements.put(statement);
return resultSets.take();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new QueryException("Query execution interrupted", e);
}
}
boolean hasBufferedMutations() {
return !mutations.isEmpty();
}
int numberOfBufferedMutations() {
return mutations.size();
}
void buffer(Mutation mutation) {
if (mutation == null)
throw new NullPointerException("Mutation is null");
mutations.add(mutation);
}
void buffer(Iterable<Mutation> mutations) {
Iterator<Mutation> it = mutations.iterator();
while (it.hasNext())
buffer(it.next());
}
void setSavepoint(Savepoint savepoint) {
Preconditions.checkNotNull(savepoint);
savepoints.put(savepoint, mutations.size());
}
void rollbackSavepoint(Savepoint savepoint) throws CloudSpannerSQLException {
Preconditions.checkNotNull(savepoint);
Integer index = savepoints.get(savepoint);
if (index == null) {
throw new CloudSpannerSQLException("Unknown savepoint: " + savepoint.toString(),
Code.INVALID_ARGUMENT);
}
mutations.subList(index.intValue(), mutations.size()).clear();
removeSavepointsAfter(index.intValue());
}
void releaseSavepoint(Savepoint savepoint) throws CloudSpannerSQLException {
Preconditions.checkNotNull(savepoint);
Integer index = savepoints.get(savepoint);
if (index == null) {
throw new CloudSpannerSQLException("Unknown savepoint: " + savepoint.toString(),
Code.INVALID_ARGUMENT);
}
removeSavepointsAfter(index.intValue());
}
private void removeSavepointsAfter(int index) {
savepoints.entrySet().removeIf(e -> e.getValue() >= index);
}
Timestamp commit() throws SQLException {
stopTransaction(TransactionStopStatement.COMMIT);
return commitTimestamp;
}
void rollback() throws SQLException {
stopTransaction(TransactionStopStatement.ROLLBACK);
}
void prepareTransaction(String xid) throws SQLException {
this.xid = xid;
stopTransaction(TransactionStopStatement.PREPARE);
}
void commitPreparedTransaction(String xid) throws SQLException {
this.xid = xid;
stopTransaction(TransactionStopStatement.COMMIT_PREPARED);
}
void rollbackPreparedTransaction(String xid) throws SQLException {
this.xid = xid;
stopTransaction(TransactionStopStatement.ROLLBACK_PREPARED);
}
private void stopTransaction(TransactionStopStatement statement) throws SQLException {
if (status == TransactionStatus.FAIL || status == TransactionStatus.SUCCESS)
return;
while (status == TransactionStatus.NOT_STARTED) {
try {
Thread.sleep(1);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new CloudSpannerSQLException(getFailedMessage(statement, e), Code.ABORTED, e);
}
}
this.stopStatement = statement;
stop = true;
// Add a statement object in order to get the transaction thread to
// proceed
statements.add(Statement.of(statement.name()));
synchronized (monitor) {
while (!stopped || status == TransactionStatus.NOT_STARTED
|| status == TransactionStatus.RUNNING) {
try {
monitor.wait();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new CloudSpannerSQLException(getFailedMessage(statement, e), Code.ABORTED, e);
}
}
}
if (status == TransactionStatus.FAIL && exception != null) {
Code code = Code.UNKNOWN;
if (exception instanceof CloudSpannerSQLException)
code = ((CloudSpannerSQLException) exception).getCode();
if (exception instanceof SpannerException)
code = Code.forNumber(((SpannerException) exception).getCode());
throw new CloudSpannerSQLException(getFailedMessage(statement, exception), code, exception);
}
}
private String getFailedMessage(TransactionStopStatement statement, Exception e) {
return statement.toString() + " failed: " + e.getMessage();
}
TransactionStatus getTransactionStatus() {
return status;
}
}
|
package org.broad.igv.sam.reader;
import htsjdk.samtools.*;
import htsjdk.samtools.seekablestream.SeekableStream;
import htsjdk.samtools.util.CloseableIterator;
import org.apache.log4j.Logger;
import org.broad.igv.exceptions.DataLoadException;
import org.broad.igv.sam.PicardAlignment;
import org.broad.igv.util.FileUtils;
import org.broad.igv.util.HttpUtils;
import org.broad.igv.util.ResourceLocator;
import org.broad.igv.util.stream.IGVSeekableBufferedStream;
import org.broad.igv.util.stream.IGVSeekableStreamFactory;
import java.io.*;
import java.net.URL;
import java.util.ArrayList;
import java.util.Hashtable;
import java.util.List;
import java.util.Set;
public class BAMHttpReader implements AlignmentReader<PicardAlignment> {
static Logger log = Logger.getLogger(BAMHttpReader.class);
// Length of day in milliseconds
public static final long oneDay = 24 * 60 * 60 * 1000;
static Hashtable<String, File> indexFileCache = new Hashtable<String, File>();
private final ResourceLocator locator;
URL url;
SAMFileHeader header;
htsjdk.samtools.SamReader reader;
List<String> sequenceNames;
private boolean indexed = false; // False until proven otherwise
public BAMHttpReader(ResourceLocator locator, boolean requireIndex) throws IOException {
this.locator = locator;
this.url = new URL(locator.getPath());
reader = getSamReader(locator, requireIndex);
}
public SamReader getSamReader(ResourceLocator locator, boolean requireIndex) throws IOException {
if (requireIndex) {
final SamReaderFactory factory = SamReaderFactory.makeDefault().validationStringency(ValidationStringency.SILENT);
SeekableStream indexStream = getIndexStream(locator.getBamIndexPath());
this.indexed = true;
SeekableStream ss = new IGVSeekableBufferedStream(IGVSeekableStreamFactory.getInstance().getStreamFor(url), 128000);
SamInputResource resource = SamInputResource.of(ss).index(indexStream);
return factory.open(resource);
} else {
InputStream is = HttpUtils.getInstance().openConnectionStream(url);
return new SAMFileReader(new BufferedInputStream(is));
}
}
public void close() throws IOException {
if (reader != null) {
reader.close();
}
}
public SAMFileHeader getFileHeader() {
if (header == null) {
header = reader.getFileHeader();
}
return header;
}
public boolean hasIndex() {
return indexed;
}
public Set<String> getPlatforms() {
return AlignmentReaderFactory.getPlatforms(getFileHeader());
}
public List<String> getSequenceNames() {
if (sequenceNames == null) {
SAMFileHeader header = getFileHeader();
if (header == null) {
return null;
}
sequenceNames = new ArrayList();
List<SAMSequenceRecord> records = header.getSequenceDictionary().getSequences();
if (records.size() > 0) {
for (SAMSequenceRecord rec : header.getSequenceDictionary().getSequences()) {
String chr = rec.getSequenceName();
sequenceNames.add(chr);
}
}
}
return sequenceNames;
}
public CloseableIterator<PicardAlignment> iterator() {
try {
if (reader == null) {
InputStream is = HttpUtils.getInstance().openConnectionStream(url);
reader = new SAMFileReader(new BufferedInputStream(is));
}
return new WrappedIterator(reader.iterator());
} catch (IOException e) {
log.error("Error creating iterator", e);
throw new RuntimeException(e);
}
}
public CloseableIterator<PicardAlignment> query(String sequence, int start, int end, boolean contained) {
try {
if (reader == null) {
reader = getSamReader(locator, true);
}
CloseableIterator<SAMRecord> iter = reader.query(sequence, start + 1, end, contained);
return new WrappedIterator(iter);
} catch (IOException e) {
log.error("Error opening SAM reader", e);
throw new RuntimeException("Error opening SAM reader", e);
}
}
private SeekableStream getIndexStream(String indexPath) throws IOException {
List<String> pathsTried = new ArrayList<String>();
pathsTried.add(indexPath);
if (HttpUtils.getInstance().resourceAvailable(new URL(indexPath))) {
return IGVSeekableStreamFactory.getInstance().getStreamFor(new URL(indexPath));
} else {
if (indexPath.endsWith(".bam.bai")) {
indexPath = indexPath.substring(0, indexPath.length() - 8) + ".bai";
pathsTried.add(indexPath);
if (HttpUtils.getInstance().resourceAvailable(new URL(indexPath))) {
log.info("Index found: " + indexPath);
return IGVSeekableStreamFactory.getInstance().getStreamFor(new URL(indexPath));
}
} else if (indexPath.endsWith(".bai")) {
indexPath = indexPath.substring(0, indexPath.length() - 4) + ".bam.bai";
pathsTried.add(indexPath);
if (HttpUtils.getInstance().resourceAvailable(new URL(indexPath))){
log.info("Index found: " + indexPath);
return IGVSeekableStreamFactory.getInstance().getStreamFor(new URL(indexPath));
}
}
}
String msg = "Index file not found. Tried ";
for(String path : pathsTried) {
msg += "<br>" + indexPath;
}
throw new DataLoadException(msg, indexPath);
}
}
|
package net.maizegenetics.prefs;
import java.util.prefs.Preferences;
/**
*
* @author terryc
*/
public class TasselPrefs {
// Top level preferences
public static final String TASSEL_TOP = "/tassel";
public static final String TASSEL_SAVE_DIR = "saveDir";
public static final String TASSEL_SAVE_DIR_DEFAULT = "";
public static final String TASSEL_OPEN_DIR = "openDir";
public static final String TASSEL_OPEN_DIR_DEFAULT = "";
public static final String TASSEL_FONT_METRICS_CHAR_WIDTH = "fontMetricsCharWidth";
public static final int TASSEL_FONT_METRICS_CHAR_WIDTH_DEFAULT = 9;
public static final String TASSEL_IDENTIFIER_JOIN_STRICT = "idJoinStrict";
public static final boolean TASSEL_IDENTIFIER_JOIN_STRICT_DEFAULT = false;
private static boolean TASSEL_IDENTIFIER_JOIN_STRICT_VALUE = getBooleanPref(TASSEL_TOP, TASSEL_IDENTIFIER_JOIN_STRICT, TASSEL_IDENTIFIER_JOIN_STRICT_DEFAULT);
// FilterAlignmentPlugin preferences
public static final String FILTER_ALIGN_PLUGIN_TOP = "/tassel/plugins/filterAlign";
// Min. frequency for filtering sites.
public static final String FILTER_ALIGN_PLUGIN_MIN_FREQ = "minFreq";
public static final double FILTER_ALIGN_PLUGIN_MIN_FREQ_DEFAULT = 0.01;
// Max. frequency for filtering sites.
public static final String FILTER_ALIGN_PLUGIN_MAX_FREQ = "maxFreq";
public static final double FILTER_ALIGN_PLUGIN_MAX_FREQ_DEFAULT = 1.0;
// Min. frequency for filtering sites.
public static final String FILTER_ALIGN_PLUGIN_MIN_COUNT = "minCount";
public static final int FILTER_ALIGN_PLUGIN_MIN_COUNT_DEFAULT = 1;
// Alignment preferences
public static final String ALIGNMENT_TOP = "/tassel/alignment";
public static final String ALIGNMENT_MAX_ALLELES_TO_RETAIN = "maxAllelesToRetain";
public static final int ALIGNMENT_MAX_ALLELES_TO_RETAIN_DEFAULT = 2;
public static final String ALIGNMENT_RETAIN_RARE_ALLELES = "retainRareAlleles";
public static final boolean ALIGNMENT_RETAIN_RARE_ALLELES_DEFAULT = true;
/**
* Creates a new instance of TasselPrefs
*/
private TasselPrefs() {
}
public static String getPref(String path, String key, String def) {
Preferences node = Preferences.userRoot();
node = node.node(path);
return node.get(key, def);
}
public static void putPref(String path, String key, String value) {
Preferences node = Preferences.userRoot();
node = node.node(path);
node.put(key, value);
}
public static double getDoublePref(String path, String key, double def) {
Preferences node = Preferences.userRoot();
node = node.node(path);
return node.getDouble(key, def);
}
public static void putDoublePref(String path, String key, double value) {
Preferences node = Preferences.userRoot();
node = node.node(path);
node.putDouble(key, value);
}
public static int getIntPref(String path, String key, int def) {
Preferences node = Preferences.userRoot();
node = node.node(path);
return node.getInt(key, def);
}
public static void putIntPref(String path, String key, int value) {
Preferences node = Preferences.userRoot();
node = node.node(path);
node.putInt(key, value);
}
public static boolean getBooleanPref(String path, String key, boolean def) {
Preferences node = Preferences.userRoot();
node = node.node(path);
return node.getBoolean(key, def);
}
public static void putBooleanPref(String path, String key, boolean value) {
Preferences node = Preferences.userRoot();
node = node.node(path);
node.putBoolean(key, value);
}
// Top level preferences
public static String getSaveDir() {
return getPref(TASSEL_TOP, TASSEL_SAVE_DIR, TASSEL_SAVE_DIR_DEFAULT);
}
public static void putSaveDir(String value) {
putPref(TASSEL_TOP, TASSEL_SAVE_DIR, value);
}
public static String getOpenDir() {
return getPref(TASSEL_TOP, TASSEL_OPEN_DIR, TASSEL_OPEN_DIR_DEFAULT);
}
public static void putOpenDir(String value) {
putPref(TASSEL_TOP, TASSEL_OPEN_DIR, value);
}
public static int getFontMetricsCharWidth() {
return getIntPref(TASSEL_TOP, TASSEL_FONT_METRICS_CHAR_WIDTH, TASSEL_FONT_METRICS_CHAR_WIDTH_DEFAULT);
}
public static void putFontMetricsCharWidth(int value) {
putIntPref(TASSEL_TOP, TASSEL_FONT_METRICS_CHAR_WIDTH, value);
}
public static boolean getIDJoinStrict() {
// This can be called many times, so to improve performance
// this will return value without executing system call.
return TASSEL_IDENTIFIER_JOIN_STRICT_VALUE;
// return getBooleanPref(TASSEL_TOP, TASSEL_IDENTIFIER_JOIN_STRICT, TASSEL_IDENTIFIER_JOIN_STRICT_DEFAULT);
}
public static void putIDJoinStrict(boolean value) {
TASSEL_IDENTIFIER_JOIN_STRICT_VALUE = value;
putBooleanPref(TASSEL_TOP, TASSEL_IDENTIFIER_JOIN_STRICT, value);
}
// FilterAlignmentPlugin preferences
public static double getFilterAlignPluginMinFreq() {
return getDoublePref(FILTER_ALIGN_PLUGIN_TOP, FILTER_ALIGN_PLUGIN_MIN_FREQ, FILTER_ALIGN_PLUGIN_MIN_FREQ_DEFAULT);
}
public static void putFilterAlignPluginMinFreq(double value) {
putDoublePref(FILTER_ALIGN_PLUGIN_TOP, FILTER_ALIGN_PLUGIN_MIN_FREQ, value);
}
public static double getFilterAlignPluginMaxFreq() {
return getDoublePref(FILTER_ALIGN_PLUGIN_TOP, FILTER_ALIGN_PLUGIN_MAX_FREQ, FILTER_ALIGN_PLUGIN_MAX_FREQ_DEFAULT);
}
public static void putFilterAlignPluginMaxFreq(double value) {
putDoublePref(FILTER_ALIGN_PLUGIN_TOP, FILTER_ALIGN_PLUGIN_MAX_FREQ, value);
}
public static int getFilterAlignPluginMinCount() {
return getIntPref(FILTER_ALIGN_PLUGIN_TOP, FILTER_ALIGN_PLUGIN_MIN_COUNT, FILTER_ALIGN_PLUGIN_MIN_COUNT_DEFAULT);
}
public static void putFilterAlignPluginMinCount(int value) {
putIntPref(FILTER_ALIGN_PLUGIN_TOP, FILTER_ALIGN_PLUGIN_MIN_COUNT, value);
}
// Alignment preferences
public static int getAlignmentMaxAllelesToRetain() {
return getIntPref(ALIGNMENT_TOP, ALIGNMENT_MAX_ALLELES_TO_RETAIN, ALIGNMENT_MAX_ALLELES_TO_RETAIN_DEFAULT);
}
public static void putAlignmentMaxAllelesToRetain(int value) {
putIntPref(ALIGNMENT_TOP, ALIGNMENT_MAX_ALLELES_TO_RETAIN, value);
}
public static boolean getAlignmentRetainRareAlleles() {
return getBooleanPref(ALIGNMENT_TOP, ALIGNMENT_RETAIN_RARE_ALLELES, ALIGNMENT_RETAIN_RARE_ALLELES_DEFAULT);
}
public static void putAlignmentRetainRareAlleles(boolean value) {
putBooleanPref(ALIGNMENT_TOP, ALIGNMENT_RETAIN_RARE_ALLELES, value);
}
}
|
package org.drupal.project.computing;
import java.util.logging.Logger;
/**
* Connect to Drupal through direct database access. It uses JDBC and Apache Commons DBUtils, so it's independent of
* DBMS implementations. Currently we support MySQL and PostgreSQL.
*
* Due to security reasons, it is not recommended to use this class directly to access Drupal database unless necessary.
* Typical reasons to use this class: 1) performance, 2) prototyping. Other than those 2 cases, you should consider
* to use {computing_record} to pass data in/out of Drupal.
*
* This can be used as standalone class.
*/
public class DDatabase {
protected Logger logger = DUtils.getInstance().getPackageLogger();
}
|
package nl.mpi.arbil.templates;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Enumeration;
import java.util.Vector;
import nl.mpi.arbil.GuiHelper;
import nl.mpi.arbil.LinorgSessionStorage;
import nl.mpi.arbil.LinorgWindowManager;
import nl.mpi.arbil.data.ImdiTreeObject;
import org.apache.xmlbeans.SchemaProperty;
import org.apache.xmlbeans.SchemaType;
import org.apache.xmlbeans.SchemaTypeSystem;
import org.apache.xmlbeans.XmlBeans;
import org.apache.xmlbeans.XmlException;
import org.apache.xmlbeans.XmlObject;
import org.apache.xmlbeans.XmlOptions;
public class CmdiTemplate extends ArbilTemplate {
public void loadTemplate(String nameSpaceString) {
// testing only
//super.readTemplate(new File(""), "template_cmdi");
// construct the template from the XSD
try {
// create a temp file of the read template data so that it can be compared to a hand made version
File debugTempFile = File.createTempFile("templatetext", ".tmp");
debugTempFile.deleteOnExit();
BufferedWriter debugTemplateFileWriter = new BufferedWriter(new FileWriter(debugTempFile));
ArrayList<String[]> childNodePathsList = new ArrayList<String[]>();
URI xsdUri = new URI(nameSpaceString);
readSchema(xsdUri, childNodePathsList);
childNodePaths = childNodePathsList.toArray(new String[][]{});
for (String[] currentArray : childNodePaths) {
System.out.println("loadTemplate: " + currentArray[1] + ":" + currentArray[0]);
debugTemplateFileWriter.write("<ChildNodePath ChildPath=\"" + currentArray[0] + "\" SubNodeName=\"" + currentArray[1] + "\" />\r\n");
}
debugTemplateFileWriter.close();
// lanunch the hand made template and the generated template for viewing
// LinorgWindowManager.getSingleInstance().openUrlWindowOnce("templatetext", debugTempFile.toURL());
// LinorgWindowManager.getSingleInstance().openUrlWindowOnce("templatejar", CmdiTemplate.class.getResource("/nl/mpi/arbil/resources/templates/template_cmdi.xml"));
// LinorgWindowManager.getSingleInstance().openUrlWindowOnce("templatejar", CmdiTemplate.class.getResource("/nl/mpi/arbil/resources/templates/template.xml"));
} catch (URISyntaxException urise) {
GuiHelper.linorgBugCatcher.logError(urise);
} catch (IOException urise) {
GuiHelper.linorgBugCatcher.logError(urise);
}
// this should be adequate for cmdi templates
//templatesArray = childNodePaths;
// TODO: complete these
requiredFields = new String[]{};
fieldConstraints = new String[][]{};
preferredNameFields = new String[]{};
fieldUsageArray = new String[][]{};
fieldTriggersArray = new String[][]{};
autoFieldsArray = new String[][]{};
}
@Override
public Enumeration listTypesFor(Object targetNodeUserObject) {
// get the xpath of the target node
String targetNodeXpath = ((ImdiTreeObject) targetNodeUserObject).getURI().getFragment();
System.out.println("targetNodeXpath: " + targetNodeXpath);
if (targetNodeXpath != null) {
targetNodeXpath = targetNodeXpath.replaceAll("\\(\\d+\\)", "");
}
System.out.println("targetNodeXpath: " + targetNodeXpath);
Vector<String[]> childTypes = new Vector<String[]>();
if (targetNodeUserObject instanceof ImdiTreeObject) {
for (String[] childPathString : childNodePaths) {
boolean allowEntry = false;
if (targetNodeXpath == null) {
System.out.println("allowing: " + childPathString[0]);
allowEntry = true;
} else if (childPathString[0].startsWith(targetNodeXpath)) {
System.out.println("allowing: " + childPathString[0]);
allowEntry = true;
}
if (targetNodeXpath != null && childPathString[0].length() == targetNodeXpath.length()) {
System.out.println("disallowing: " + childPathString[0]);
allowEntry = false;
}
// remove types that require a container type that has not already been added to the target
for (String[] childPathTest : childNodePaths) {
// only if the test path is valid
if (targetNodeXpath == null || childPathTest[0].startsWith(targetNodeXpath)) {
if (childPathString[0].startsWith(childPathTest[0])) {
if (childPathTest[0].length() < childPathString[0].length()) {
System.out.println("removing: " + childPathString[0]);
System.out.println("based on: " + childPathTest[0]);
allowEntry = false;
}
}
}
}
// TODO: check that the sub node addables are being correctly listed in the context menu
// System.out.println("childPathString[0]: " + childPathString[0]);
// System.out.println("childPathString[1]: " + childPathString[1]);
if (allowEntry) {
childTypes.add(new String[]{childPathString[1], childPathString[0]});
}
}
Collections.sort(childTypes, new Comparator() {
public int compare(Object o1, Object o2) {
String value1 = ((String[]) o1)[0];
String value2 = ((String[]) o2)[0];
return value1.compareTo(value2);
}
});
}
return childTypes.elements();
}
private void readSchema(URI xsdFile, ArrayList<String[]> childNodePathsList) {
File schemaFile = LinorgSessionStorage.getSingleInstance().updateCache(xsdFile.toString(), 5);
templateFile = schemaFile; // store the template file for later use such as adding child nodes
try {
InputStream inputStream = new FileInputStream(schemaFile);
//Since we're dealing with xml schema files here the character encoding is assumed to be UTF-8
XmlOptions options = new XmlOptions();
options.setCharacterEncoding("UTF-8");
SchemaTypeSystem sts = XmlBeans.compileXsd(new XmlObject[]{XmlObject.Factory.parse(inputStream, options)}, XmlBeans.getBuiltinTypeSystem(), null);
for (SchemaType schemaType : sts.documentTypes()) {
System.out.println("T-documentTypes:");
constructXml(schemaType, childNodePathsList, "");
break; // there can only be a single root node and the IMDI schema specifies two (METATRANSCRIPT and VocabularyDef) so we must stop before that error creates another
}
} catch (IOException e) {
GuiHelper.linorgBugCatcher.logError(e);
} catch (XmlException e) {
GuiHelper.linorgBugCatcher.logError(e);
}
}
private void constructXml(SchemaType schemaType, ArrayList<String[]> childNodePathsList, String pathString) {
for (SchemaProperty schemaProperty : schemaType.getElementProperties()) {
String localName = schemaProperty.getName().getLocalPart();
String currentPathString = pathString + "." + localName;
boolean canHaveMultiple = true;
if (schemaProperty.getMaxOccurs() == null) {
// absence of the max occurs also means multiple
canHaveMultiple = true;
// todo: also check that min and max are the same because there may be cases of zero required but only one can be added
} else if (schemaProperty.getMaxOccurs().toString().equals("unbounded")) {
canHaveMultiple = true;
} else {
// todo: take into account max occurs in the add menu
canHaveMultiple = schemaProperty.getMaxOccurs().intValue() > 1;
}
boolean hasSubNodes = false;
System.out.println("Found template element: " + currentPathString);
SchemaType currentSchemaType = schemaProperty.getType();
constructXml(currentSchemaType, childNodePathsList, currentPathString);
hasSubNodes = true; // todo: complete or remove this hasSubNodes case
if (canHaveMultiple && hasSubNodes) {
childNodePathsList.add(new String[]{currentPathString, localName});
}
}
}
}
|
package org.exist.security.xacml;
import com.sun.xacml.attr.AnyURIAttribute;
import com.sun.xacml.attr.AttributeValue;
import com.sun.xacml.attr.StringAttribute;
import com.sun.xacml.ctx.Attribute;
import com.sun.xacml.ctx.RequestCtx;
import com.sun.xacml.ctx.Subject;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
import org.exist.dom.QName;
import org.exist.security.User;
import org.exist.xquery.ExternalModule;
import org.exist.xquery.Module;
import org.exist.xquery.XQueryContext;
/*
* Source.getKey().toString() needs to be unique:
* potential collision between FileSource and DBSource ??
*/
/**
* This class provides methods for creating an XACML request. The main methods
* are those that return a <code>RequestCtx</code>. Links are provided to the
* relevant constants in <code>XACMLConstants</code> to facilitate policy
* writing.
*
* @see XACMLConstants
*/
public class RequestHelper
{
public RequestCtx createQueryRequest(XQueryContext context, XACMLSource source)
{
Set subjects = createQuerySubjects(context.getUser(), null);
Set resourceAttributes = createQueryResource(source);
Set actionAttributes = createBasicAction(XACMLConstants.EXECUTE_QUERY_ACTION);
Set environmentAttributes = createEnvironment(context.getAccessContext());
return new RequestCtx(subjects, resourceAttributes, actionAttributes, environmentAttributes);
}
/**
* Creates a <code>RequestCtx</code> for a request concerning reflective
* access to Java code from an XQuery. This handles occurs when a method
* is being invoked on the class in question. This method creates a
* request with the following content:
* <ul>
*
* <li>Subjects for the contextModule and user are created with the
* createQuerySubjects method.</li>
*
* <li>Resource attributes are created with the
* <code>createReflectionResource</code> method.</li>
*
* <li>Action attributes are created with the
* <code>createBasicAction</code> method. The action-id is
* {@link XACMLConstants#INVOKE_METHOD_ACTION invoke method}.</li>
*
* <li>The {@link XACMLConstants#ACCESS_CONTEXT_ATTRIBUTE} access context
* attribute is generated for the environment section.</li>
*
* </ul>
*
* @param context The <code>XQueryContext</code> for the module making the
* request.
* @param contextModule The query containing the reflection.
* @param className The name of the class that is being accessed or loaded.
* @param methodName The name of the method that is being invoked
* @return A <code>RequestCtx</code> that represents the access in question.
*/
public RequestCtx createReflectionRequest(XQueryContext context, Module contextModule, String className, String methodName)
{
User user = context.getUser();
Set subjects = createQuerySubjects(user, contextModule);
Set resourceAttributes = createReflectionResource(className, methodName);
Set actionAttributes = createBasicAction(XACMLConstants.INVOKE_METHOD_ACTION);
Set environmentAttributes = createEnvironment(context.getAccessContext());
return new RequestCtx(subjects, resourceAttributes, actionAttributes, environmentAttributes);
}
/**
* Creates a <code>RequestCtx</code> for a request concerning access
* to a function in an XQuery library module. If the function is
* from a main module, this method returns null to indicate that.
* The client should interpret this to mean that the request is
* granted because access to a main module implies access to its
* functions.
*
* <p>
* This method creates a request with the following content:
* <ul>
*
* <li>Subjects for the contextModule and user (obtained from the
* XQueryContext) are created with the createQuerySubjects method.</li>
*
* <li>The specified functionModule parameter is used to generate the
* {@link XACMLConstants#SOURCE_KEY_ATTRIBUTE source-key},
* {@link XACMLConstants#SOURCE_TYPE_ATTRIBUTE source-type}, and
* {@link XACMLConstants#MODULE_CATEGORY_ATTRIBUTE module category}
* attributes. The functionName parameter is the value of the
* {@link XACMLConstants#RESOURCE_ID_ATTRIBUTE subject-id} attribute
* (the local part) and of the
* {@link XACMLConstants#MODULE_NS_ATTRIBUTE module namespace}
* attribute (the namespace URI part). The
* {@link XACMLConstants#RESOURCE_CATEGORY_ATTRIBUTE resource-category}
* attribute is {@link XACMLConstants#FUNCTION_RESOURCE function}.
*
* <li>Action attributes are created with the
* <code>createBasicAction</code> method. The action is
* {@link XACMLConstants#CALL_FUNCTION_ACTION call function}.
*
* <li>The {@link XACMLConstants#ACCESS_CONTEXT_ATTRIBUTE} access context
* attribute is generated for the environment section.</li>
*
* </ul>
*
* @param context The query context.
* @param contextModule The query making the access.
* @param functionName The <code>QName</code> of the function being called.
* @return A <code>RequestCtx</code> that represents the access in question
* or <code>null</code> if the function belongs to a main module and
* not a library module.
*/
public RequestCtx createFunctionRequest(XQueryContext context, Module contextModule, QName functionName)
{
String namespaceURI = functionName.getNamespaceURI();
Module functionModule = context.getModule(namespaceURI);
if(functionModule == null)
{
//main module, not a library module, so access to function is always allowed
return null;
}
User user = context.getUser();
Set subjects = createQuerySubjects(user, contextModule);
Set resourceAttributes = new HashSet(8);
addStringAttribute(resourceAttributes, XACMLConstants.MODULE_CATEGORY_ATTRIBUTE, getModuleCategory(functionModule));
XACMLSource moduleSrc = generateModuleSource(functionModule);
addSourceAttributes(resourceAttributes, moduleSrc);
addValidURIAttribute(resourceAttributes, XACMLConstants.MODULE_NS_ATTRIBUTE, namespaceURI);
addStringAttribute(resourceAttributes, XACMLConstants.RESOURCE_CATEGORY_ATTRIBUTE, XACMLConstants.FUNCTION_RESOURCE);
addStringAttribute(resourceAttributes, XACMLConstants.RESOURCE_ID_ATTRIBUTE, functionName.getLocalName());
Set actionAttributes = createBasicAction(XACMLConstants.CALL_FUNCTION_ACTION);
Set environmentAttributes = createEnvironment(context.getAccessContext());
return new RequestCtx(subjects, resourceAttributes, actionAttributes, environmentAttributes);
}
/**
* Creates a <code>Subject</code> for a <code>User</code>.
* The user's name is the value of the
* {@link XACMLConstants#SUBJECT_ID_ATTRIBUTE subject-id} attribute. The
* subject-category is {@link XACMLConstants#ACCESS_SUBJECT access-subject}.
* The {@link XACMLConstants#GROUP_ATTRIBUTE group} attribute is a bag
* containing the name of each group of which the user is a member.
*
* @param user The user making the request
* @return A <code>Subject</code> for use in a <code>RequestCtx</code>
*/
public Subject createUserSubject(User user)
{
AttributeValue value = new StringAttribute(user.getName());
Attribute attr = new Attribute(XACMLConstants.SUBJECT_ID_ATTRIBUTE, null, null, value);
return new Subject(XACMLConstants.ACCESS_SUBJECT, Collections.singleton(attr));
}
/**
* Creates the basic attributes needed to describe a simple action
* in a request. The <code>action</code> parameter is the value of
* the {@link XACMLConstants#ACTION_ID_ATTRIBUTE action-id} attribute and the
* {@link XACMLConstants#ACTION_NS_ATTRIBUTE namespace} attribute for the
* action-id is eXist's XACML
* {@link XACMLConstants#ACTION_NS action namespace}.
*
* @param action The {@link XACMLConstants#ACTION_ID_ATTRIBUTE action-id}
* of the action.
* @return A <code>Set</code> that contains attributes describing the
* action for use in a <code>RequestCtx</code>
*/
public Set createBasicAction(String action)
{
if(action == null)
return null;
Set attributes = new HashSet(4);
addStringAttribute(attributes, XACMLConstants.ACTION_ID_ATTRIBUTE, action);
addValidURIAttribute(attributes, XACMLConstants.ACTION_NS_ATTRIBUTE, XACMLConstants.ACTION_NS);
return attributes;
}
/**
* Creates a <code>Subject</code> for a <code>Module</code>.
* If the module is external, its <code>Source</code> is the value of the
* {@link XACMLConstants#SUBJECT_ID_ATTRIBUTE subject-id} attribute, otherwise,
* the name of the implementing class is used. The subject-category is
* {@link XACMLConstants#CODEBASE_SUBJECT codebase}. The value of the
* {@link XACMLConstants#SUBJECT_NS_ATTRIBUTE module namespace} attribute
* is the namespace URI of the module. The
* {@link XACMLConstants#MODULE_CATEGORY_ATTRIBUTE module category}
* attribute is the type of module, either
* {@link XACMLConstants#INTERNAL_LIBRARY_MODULE internal} or
* {@link XACMLConstants#EXTERNAL_LIBRARY_MODULE external}.
*
* @param module A query module involved in making the request
* @return A <code>Subject</code> for use in a <code>RequestCtx</code>
*/
public Subject createModuleSubject(Module module)
{
if(module == null)
return null;
Set attributes = new HashSet(8);
addValidURIAttribute(attributes, XACMLConstants.SUBJECT_NS_ATTRIBUTE, module.getNamespaceURI());
addStringAttribute(attributes, XACMLConstants.MODULE_CATEGORY_ATTRIBUTE, getModuleCategory(module));
XACMLSource moduleSrc = generateModuleSource(module);
addSourceAttributes(attributes, moduleSrc);
addStringAttribute(attributes, XACMLConstants.SUBJECT_ID_ATTRIBUTE, moduleSrc.createId());
return new Subject(XACMLConstants.CODEBASE_SUBJECT, attributes);
}
/**
* Creates a <code>Set</code> of <code>Attribute</code>s for a resource
* representing Java reflection in an XQuery.
* The {@link XACMLConstants#RESOURCE_CATEGORY_ATTRIBUTE resource-category}
* attribute is {@link XACMLConstants#METHOD_RESOURCE method}.
* The {@link XACMLConstants#SOURCE_TYPE_ATTRIBUTE source-type} attribute is
* {@link XACMLConstants#CLASS_SOURCE_TYPE class} and the
* {@link XACMLConstants#SOURCE_KEY_ATTRIBUTE source-key} attribute is the
* name of the class. The
* {@link XACMLConstants#RESOURCE_ID_ATTRIBUTE resource-id} attribute is the
* method name.
*
* @param className The name of the Java class
* @param methodName The name of the method being invoked
* @return A <code>Set</code> containing the <code>Attribute</code>s
* describing access to Java code by reflection.
*/
public Set createReflectionResource(String className, String methodName)
{
if(className == null)
throw new NullPointerException("Class name cannot be null");
if(methodName == null)
throw new NullPointerException("Method name cannot be null");
Set resourceAttributes = new HashSet(8);
addStringAttribute(resourceAttributes, XACMLConstants.RESOURCE_CATEGORY_ATTRIBUTE, XACMLConstants.METHOD_RESOURCE);
XACMLSource source = XACMLSource.getInstance(className);
addSourceAttributes(resourceAttributes, source);
addStringAttribute(resourceAttributes, XACMLConstants.RESOURCE_ID_ATTRIBUTE, methodName);
return resourceAttributes;
}
/**
* Creates the Resource section of a request for a main module.
*
* @param source The source of the query.
* @return A <code>Set</code> containing attributes for the specified
* query.
*/
public Set createQueryResource(XACMLSource source)
{
if(source == null)
throw new NullPointerException("Query source cannot be null");
Set resourceAttributes = new HashSet(4);
addSourceAttributes(resourceAttributes, source);
addStringAttribute(resourceAttributes, XACMLConstants.RESOURCE_ID_ATTRIBUTE, source.createId());
addStringAttribute(resourceAttributes, XACMLConstants.RESOURCE_CATEGORY_ATTRIBUTE, XACMLConstants.MAIN_MODULE_RESOURCE);
return resourceAttributes;
}
public Set createQuerySubjects(User user, Module contextModule)
{
if(user == null)
throw new NullPointerException("User cannot be null");
Set subjects = new HashSet(4);
Subject userSubject = createUserSubject(user);
subjects.add(userSubject);
if(contextModule != null)
{
Subject moduleSubject = createModuleSubject(contextModule);
subjects.add(moduleSubject);
}
return subjects;
}
/**
* Creates the environment section of a request for the given
* <code>AccessContext</code>.
*
* @param accessCtx The context
* @return A <code>Set</code> containing one attribute, the
* {@link XACMLConstants#ACCESS_CONTEXT_ATTRIBUTE access context}
* attribute with the value of the specified access context.
*/
public Set createEnvironment(AccessContext accessCtx)
{
if(accessCtx == null)
throw new NullAccessContextException();
Set environment = new HashSet(4);
addStringAttribute(environment, XACMLConstants.ACCESS_CONTEXT_ATTRIBUTE, accessCtx.toString());
return environment;
}
/**
* Generates an <code>XACMLSource</code> for a <code>Module</code>
* based on its implementing class name (if it is an
* <code>InternalModule</code>) or its <code>Source</code>
* (if it is an <code>ExternalModule</code>).
*
* @param module the module for which the source should be generated
* @return an <code>XACMLSource</code> that uniquely defines the source
* of the given module
*/
public static XACMLSource generateModuleSource(Module module)
{
if(module == null)
throw new NullPointerException("Module cannot be null");
if(module.isInternalModule())
return XACMLSource.getInstance(module.getClass());
return XACMLSource.getInstance(((ExternalModule)module).getSource());
}
/**
* Returns the module type for the given XQuery library module. This
* is either
* {@link XACMLConstants#INTERNAL_LIBRARY_MODULE internal} or
* {@link XACMLConstants#EXTERNAL_LIBRARY_MODULE external}
*
* @param module The XQuery library module. If it is null, this method
* returns null.
* @return null if module is null, the module's category (internal or external)
* otherwise
*/
public static String getModuleCategory(Module module)
{
if(module == null)
return null;
return module.isInternalModule() ? XACMLConstants.INTERNAL_LIBRARY_MODULE : XACMLConstants.EXTERNAL_LIBRARY_MODULE;
}
/**
* Adds new attributes to the specified <code>Set</code> of attributes
* that represent the specified source. The added attributes are the
* {@link XACMLConstants#SOURCE_KEY_ATTRIBUTE source's key} and the
* {@link XACMLConstants#SOURCE_TYPE_ATTRIBUTE source's type}.
*
* @param attributes The <code>Set</code> to which attributes will be
* added. If null, this method does nothing.
* @param source The source for which attributes will be added. It
* cannot be null.
*/
public static void addSourceAttributes(Set attributes, XACMLSource source)
{
if(source == null)
throw new NullPointerException("Source cannot be null");
addStringAttribute(attributes, XACMLConstants.SOURCE_KEY_ATTRIBUTE, source.getKey());
addStringAttribute(attributes, XACMLConstants.SOURCE_TYPE_ATTRIBUTE, source.getType());
}
/**
* Adds a new attribute of type string to the specified
* <code>Set</code> of attributes. The new attribute's value is
* constructed from the attrValue parameter and is given the id
* of the attrID parameter.
*
* @param attributes The <code>Set</code> to which the new attribute
* should be added. If it is null, this method does nothing.
* @param attrID The ID of the new attribute, cannot be null
* @param attrValue The value of the new attribute. It cannot be null.
*/
public static void addStringAttribute(Set attributes, URI attrID, String attrValue)
{
if(attributes == null)
return;
if(attrID == null)
throw new NullPointerException("Attribute ID cannot be null");
if(attrValue == null)
throw new NullPointerException("Attribute value cannot be null");
AttributeValue value = new StringAttribute(attrValue);
Attribute attr = new Attribute(attrID, null, null, value);
attributes.add(attr);
}
/**
* Adds a new attribute of type anyURI to the specified
* <code>Set</code> of attributes. The new attribute's value is
* constructed from the uriString parameter and is given the id
* of the attrID parameter.
*
* @param attributes The <code>Set</code> to which the new attribute
* should be added. If it is null, this method does nothing.
* @param attrID The ID of the new attribute, cannot be null
* @param uriString The value of the new attribute. It must parse into a
* valid URI and cannot be null.
* @throws URISyntaxException if the specified attribute value is not a
* valid URI.
*/
public static void addURIAttribute(Set attributes, URI attrID, String uriString) throws URISyntaxException
{
if(attributes == null)
return;
if(attrID == null)
throw new NullPointerException("Attribute ID cannot be null");
if(uriString == null)
throw new NullPointerException("Attribute value cannot be null");
URI uri = new URI(uriString);
AttributeValue value = new AnyURIAttribute(uri);
Attribute attr = new Attribute(attrID, null, null, value);
attributes.add(attr);
}
//wrapper for when the URI is known to be valid, such as when obtained from a source
//that validates the URI or from a constant
private static void addValidURIAttribute(Set attributes, URI attrID, String uriString)
{
try
{
addURIAttribute(attributes, attrID, uriString);
}
catch(URISyntaxException e)
{
throw new RuntimeException("URI should never be invalid", e);
}
}
RequestHelper() {}
}
|
package org.jpos.ee;
import java.util.Date;
import java.util.List;
import org.hibernate.Criteria;
import org.hibernate.HibernateException;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
@SuppressWarnings("unused")
public class RevisionManager {
DB db;
public RevisionManager (DB db) {
this.db = db;
}
@SuppressWarnings("unchecked")
public List<Revision> getRevisionsByRef (String ref)
throws HibernateException
{
Criteria crit = db.session().createCriteria (Revision.class)
.add (Restrictions.eq ("ref", ref))
.addOrder (Order.desc("id"));
return (List<Revision>) crit.list();
}
@SuppressWarnings("unchecked")
public List<Revision> getRevisionsByAuthor (User author)
throws HibernateException
{
Criteria crit = db.session().createCriteria (Revision.class)
.add (Restrictions.eq ("author", author))
.addOrder (Order.desc("id"));
return (List<Revision>) crit.list();
}
/**
* factory method used to create a Revision associated with this user.
*
* @param author the revision author
* @param ref associated with this revision
* @param info information
* @return a revision entry
*/
public Revision createRevision (User author, String ref, String info) {
Revision re = new Revision();
re.setDate (new Date());
re.setInfo (info);
re.setRef (ref);
re.setAuthor (author);
db.save (re);
return re;
}
}
|
package org.exist.xquery;
import org.exist.dom.DocumentSet;
import org.exist.xquery.util.ExpressionDumper;
import org.exist.xquery.value.Item;
import org.exist.xquery.value.Sequence;
import org.exist.xquery.value.Type;
/**
* XQuery if ... then ... else expression.
*
* @author wolf
*/
public class ConditionalExpression extends AbstractExpression implements RewritableExpression {
private Expression testExpr;
private Expression thenExpr;
private Expression elseExpr;
public ConditionalExpression(XQueryContext context, Expression testExpr,
Expression thenExpr, Expression elseExpr) {
super(context);
this.testExpr = testExpr.simplify();
this.thenExpr = thenExpr.simplify();
this.elseExpr = elseExpr.simplify();
}
/* (non-Javadoc)
* @see org.exist.xquery.AbstractExpression#getDependencies()
*/
public int getDependencies() {
return Dependency.CONTEXT_SET | Dependency.CONTEXT_ITEM;
}
public Expression getTestExpr() {
return testExpr;
}
public Expression getThenExpr() {
return thenExpr;
}
public Expression getElseExpr() {
return elseExpr;
}
/* (non-Javadoc)
* @see org.exist.xquery.AbstractExpression#getCardinality()
*/
public int getCardinality() {
return thenExpr.getCardinality() | elseExpr.getCardinality();
}
/* (non-Javadoc)
* @see org.exist.xquery.Expression#analyze(org.exist.xquery.Expression)
*/
public void analyze(AnalyzeContextInfo contextInfo) throws XPathException {
AnalyzeContextInfo myContextInfo = new AnalyzeContextInfo(contextInfo);
myContextInfo.setFlags(myContextInfo.getFlags() & (~IN_PREDICATE));
myContextInfo.setParent(this);
testExpr.analyze(myContextInfo);
myContextInfo.setParent(this);
thenExpr.analyze(myContextInfo);
myContextInfo.setParent(this);
elseExpr.analyze(myContextInfo);
}
/* (non-Javadoc)
* @see org.exist.xquery.Expression#eval(org.exist.dom.DocumentSet,
* org.exist.xquery.value.Sequence, org.exist.xquery.value.Item)
*/
public Sequence eval(Sequence contextSequence, Item contextItem) throws XPathException {
context.expressionStart(this);
final Sequence testSeq = testExpr.eval(contextSequence, contextItem);
try {
if (testSeq.effectiveBooleanValue()) {
return thenExpr.eval(contextSequence, contextItem);
} else {
return elseExpr.eval(contextSequence, contextItem);
}
} catch (final XPathException e) {
if (e.getLine() == 0)
{e.setLocation(line, column);}
throw e;
} finally {
context.expressionEnd(this);
}
}
/* (non-Javadoc)
* @see org.exist.xquery.Expression#preselect(org.exist.dom.DocumentSet)
*/
public DocumentSet preselect(DocumentSet in_docs) throws XPathException {
return in_docs;
}
/* (non-Javadoc)
* @see org.exist.xquery.Expression#dump(org.exist.xquery.util.ExpressionDumper)
*/
public void dump(ExpressionDumper dumper) {
dumper.display("if (");
dumper.startIndent();
testExpr.dump(dumper);
dumper.endIndent();
dumper.nl().display(") then");
dumper.startIndent();
thenExpr.dump(dumper);
dumper.endIndent();
dumper.nl().display("else");
dumper.startIndent();
elseExpr.dump(dumper);
dumper.endIndent();
}
public String toString() {
final StringBuilder result = new StringBuilder();
result.append("if ( ");
result.append(testExpr.toString());
result.append(" ) then ");
result.append(thenExpr.toString());
result.append(" else ");
result.append(elseExpr.toString());
return result.toString();
}
/* (non-Javadoc)
* @see org.exist.xquery.Expression#returnsType()
*/
public int returnsType() {
return Type.getCommonSuperType(thenExpr.returnsType(), elseExpr.returnsType());
}
/* (non-Javadoc)
* @see org.exist.xquery.AbstractExpression#resetState()
*/
public void resetState(boolean postOptimization) {
super.resetState(postOptimization);
testExpr.resetState(postOptimization);
thenExpr.resetState(postOptimization);
elseExpr.resetState(postOptimization);
}
public void accept(ExpressionVisitor visitor) {
visitor.visitConditional(this);
}
/* RewritableExpression API */
@Override
public void replace(Expression oldExpr, Expression newExpr) {
if (testExpr == oldExpr)
{testExpr = newExpr;}
else if (thenExpr == oldExpr)
{thenExpr = newExpr;}
else if (elseExpr == oldExpr)
{elseExpr = newExpr;}
}
@Override
public Expression getPrevious(Expression current) {
return null;
}
@Override
public Expression getFirst() {
return null;
}
@Override
public void remove(Expression oldExpr) throws XPathException {
//Nothing to do
}
/* END RewritableExpression API */
}
|
package org.esupportail.smsu.web;
import java.io.File;
import java.io.IOException;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.TreeMap;
import java.util.regex.MatchResult;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.inject.Inject;
import org.apache.commons.lang.StringUtils;
import org.codehaus.jackson.map.ObjectMapper;
import org.esupportail.smsu.utils.AggregateToFile;
import org.esupportail.smsu.utils.CachedDigest;
public class ServerSideDirectives {
private String scriptStart = "(<script [^>]*)";
private String scriptEnd = "([^>]*> *</script>)";
private String linkStart = "(<link [^>]*)";
private String linkEnd = "([^>]*>)";
private String stringValue = "\"([^\"]*)\"";
private String srcStringValue = "([^>]*src)=" + stringValue;
private String hrefStringValue = "([^>]*href)=" + stringValue;
@Inject private CachedDigest cachedDigest;
@Inject private AggregateToFile aggregateToFile;
public String instantiate(String template, Map<String,Object> env, ServletContextWrapper context) {
template = instantiate_vars(template, env);
// first remove what is unneeded
template = instantiate_serverSideIf(template, env);
// generate angular templates js
template = instantiate_serverSideAngularTemplates(template, env, context);
template = instantiate_serverSideConcat(template, context);
// must be done after Concat in case both are used
template = instantiate_serverSideCacheBuster(template, context);
// must be done after CacheBuster
template = instantiate_serverSidePrefix(template, env);
return template;
}
public String instantiate_vars(String template, final Map<String,Object> env) {
String regex = Pattern.quote("{{serverSide.") + "([^}]+)" + Pattern.quote("}}");
return ReplaceAllWithCallback.doIt(template, regex, new ReplaceAllWithCallback.Callback() {
public String replace(MatchResult m) {
return (String) env.get(m.group(1));
}
});
}
private String instantiate_serverSideCacheBuster(String template, ServletContextWrapper context) {
String ssp_src_regex = "\\bserver-side-cache-buster\\s+" + srcStringValue;
String ssp_href_regex = "\\bserver-side-cache-buster\\s+" + hrefStringValue;
template = instantiate_serverSideCacheBuster(template, scriptStart + ssp_src_regex + scriptEnd, context);
template = instantiate_serverSideCacheBuster(template, linkStart + ssp_href_regex + linkEnd, context);
if (template.matches("server-side-cache-buster")) throw new RuntimeException("syntax error for server-side-cache-buster in " + template);
return template;
}
private String instantiate_serverSidePrefix(String template, Map<String,Object> env) {
String ssp_src_regex = "\\bserver-side-prefix=" + stringValue + "\\s+" + srcStringValue;
String ssp_href_regex = "\\bserver-side-prefix=" + stringValue + "\\s+" + hrefStringValue;
template = instantiate_serverSidePrefix(template, scriptStart + ssp_src_regex + scriptEnd, env);
template = instantiate_serverSidePrefix(template, linkStart + ssp_href_regex + linkEnd, env);
if (template.matches("server-side-prefix")) throw new RuntimeException("syntax error for server-side-prefix in " + template);
return template;
}
private String instantiate_serverSideConcat(String template, final ServletContextWrapper context) {
String ssp_src_regex = "\\bserver-side-concat=" + stringValue + "\\s+" + srcStringValue;
String ssp_href_regex = "\\bserver-side-concat=" + stringValue + "\\s+" + hrefStringValue;
template = instantiate_serverSideConcat(template, scriptStart + ssp_src_regex + scriptEnd, context);
template = instantiate_serverSideConcat(template, linkStart + ssp_href_regex + linkEnd, context);
if (template.matches("server-side-concat")) throw new RuntimeException("syntax error for server-side-concat in " + template);
return template;
}
private String instantiate_serverSideAngularTemplates(String template, Map<String, Object> env, final ServletContextWrapper context) {
String ssp_src_regex = "\\bserver-side-angular-templates=" + stringValue + "\\s+" + srcStringValue;
template = instantiate_serverSideAngularTemplates(template, scriptStart + ssp_src_regex + scriptEnd, env, context);
if (template.matches("server-side-angular-templates")) throw new RuntimeException("syntax error for server-side-concat in " + template);
return template;
}
private String instantiate_serverSideIf(String template, Map<String, Object> env) {
String ssp_regex = "\\bserver-side-if=" + stringValue + "\\s*";
template = instantiate_serverSideIf(template, scriptStart + ssp_regex + scriptEnd, env);
template = instantiate_serverSideIf(template, linkStart + ssp_regex + linkEnd, env);
if (template.matches("server-side-if")) throw new RuntimeException("syntax error for server-side-if in " + template);
return template;
}
private String instantiate_serverSideCacheBuster(String template, String regex, final ServletContextWrapper context) {
return ReplaceAllWithCallback.doIt(template, regex, new ReplaceAllWithCallback.Callback() {
public String replace(MatchResult m) {
String openTag = m.group(1),
srcAttr = m.group(2),
srcVal = m.group(3),
endTag = m.group(4);
File src = src2file(context, srcVal);
String digest = cachedDigest.compute(src);
digest = digest.substring(0, 8); // not too long, otherwise it's really ugly and non necessary
return openTag + srcAttr + "=\"" + srcVal + "?d=" + digest + "\"" + endTag;
}
});
}
private String instantiate_serverSidePrefix(String template, String regex, final Map<String,Object> env) {
return ReplaceAllWithCallback.doIt(template, regex, new ReplaceAllWithCallback.Callback() {
public String replace(MatchResult m) {
String openTag = m.group(1),
prefixVar = m.group(2),
srcAttr = m.group(3),
srcVal = m.group(4),
endTag = m.group(5);
String prefix = (String) env.get(prefixVar);
if (prefix == null) throw new RuntimeException("invalid server-side-prefix " + prefixVar);
return openTag + srcAttr + "=\"" + prefix + "/" + srcVal + "\"" + endTag;
}
});
}
private String instantiate_serverSideConcat(String template, String regex, final ServletContextWrapper context) {
final Map<String,List<File>> destination2sources = new TreeMap<String, List<File>>();
String result = ReplaceAllWithCallback.doIt(template, regex, new ReplaceAllWithCallback.Callback() {
public String replace(MatchResult m) {
String openTag = m.group(1),
dest = m.group(2),
srcAttr = m.group(3),
srcVal = m.group(4),
endTag = m.group(5);
List<File> sources = destination2sources.get(dest);
boolean isFirst = sources == null;
if (isFirst) {
sources = new LinkedList<File>();
destination2sources.put(dest, sources);
}
sources.add(src2file(context, srcVal));
if (isFirst) {
return openTag + srcAttr + "=\"" + dest + "\"" + endTag;
} else {
return ""; // keep only the first, remove the others
}
}
});
try {
for (Entry<String,List<File>> e : destination2sources.entrySet()) {
aggregateToFile.concat(e.getValue(), src2file(context, e.getKey()));
}
} catch (IOException e) {
// failed to write concat, return input template unmodified
return template;
}
return result;
}
private String instantiate_serverSideAngularTemplates(String template, String regex, final Map<String, Object> env, final ServletContextWrapper context) {
return ReplaceAllWithCallback.doIt(template, regex, new ReplaceAllWithCallback.Callback() {
public String replace(MatchResult m) {
String openTag = m.group(1),
templates = m.group(2),
srcAttr = m.group(3),
dest = m.group(4),
closeTag = m.group(5);
String urlPrefix = getServerSidePrefix(m.group(), env);
final Map<File,String> htmlFileToURL = new TreeMap<File, String>();
for (String relative : templates.split("\\s+")) {
htmlFileToURL.put(src2file(context, relative), urlPrefix + "/" + relative);
}
try {
aggregateToFile.concat(htmlFileToURL.keySet(), src2file(context, dest), "", "", new AggregateToFile.Filter() {
public String filter(File file, String html) {
try {
String url = htmlFileToURL.get(file);
return prepareForClientSideInclude(prepareAngularTemplate(html, url));
} catch (IOException e) {
throw new RuntimeException(e);
}
}
});
return openTag + srcAttr + "=\"" + dest + "\"" + closeTag;
} catch (IOException e) {
return "";
}
}
});
}
private String instantiate_serverSideIf(String template, String regex, final Map<String,Object> env) {
String result = ReplaceAllWithCallback.doIt(template, regex, new ReplaceAllWithCallback.Callback() {
public String replace(MatchResult m) {
String openTag = m.group(1),
varName = m.group(2),
endTag = m.group(3);
Object val = env.get(varName);
if (val == null) throw new RuntimeException("invalid server-side-if " + varName);
return isFalse(val) ? "" : openTag + endTag;
}
});
return result;
}
// similar to perl/python falseness
private boolean isFalse(Object val) {
if (val == null) return true;
if (val instanceof Boolean) return !(Boolean) val;
if (val instanceof String) return StringUtils.isBlank((String) val);
if (val instanceof Number) return ((Number) val).doubleValue() == 0;
return false;
}
private File src2file(final ServletContextWrapper context, String src) {
File baseURL = new File(context.getRealPath("/"));
return new File(baseURL, src);
}
private String prepareAngularTemplate(String html, String url) {
return "<script type=\"text/ng-template\" id=\"" + url + "\">\n" + html + "\n</script>\n\n";
}
private String prepareForClientSideInclude(String script) throws IOException {
return "document.write(" + new ObjectMapper().writeValueAsString(script) + ");\n";
}
private String getServerSidePrefix(String scriptTag, final Map<String, Object> env) {
String urlPrefixVar = getFirstMatch("\\bserver-side-prefix=" + stringValue, scriptTag);
String urlPrefix = (String) env.get(urlPrefixVar);
if (urlPrefix == null) throw new RuntimeException("invalid server-side-prefix " + urlPrefixVar);
return urlPrefix;
}
private String getFirstMatch(String re, String s) {
Matcher m = Pattern.compile(re).matcher(s);
return m.find() ? m.group(1) : null;
}
static public class ReplaceAllWithCallback
{
static public interface Callback
{
public String replace(MatchResult matchResult);
}
static public String doIt(String subject, String regex, Callback callback)
{
return doIt(subject, Pattern.compile(regex), callback);
}
static public String doIt(String subject, Pattern pattern, Callback callback)
{
Matcher m = pattern.matcher(subject);
StringBuffer result = new StringBuffer();
while (m.find()) {
m.appendReplacement(result, ""); // add before match in result
result.append(callback.replace(m));
}
m.appendTail(result); // add after match in result
return result.toString();
}
}
}
|
//This code is developed as part of the Java CoG Kit project
//This message may not be removed or altered.
package org.griphyn.vdl.mapping.file;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.Array;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
public class SymLinker {
private static final String[] EMPTY_STRING_ARRAY = new String[0];
private static Object EMPTY_FILE_ATTR_ARRAY;
private static boolean canSymLink;
private static Class<?> clsPaths;
private static Class<?> clsFiles;
private static Method methodPathsGet;
private static Method methodFilesSymLink;
private static Method methodReadLink;
private static Method methodIsLink;
static {
if (init()) {
canSymLink = true;
canSymLink = symLinkTest();
}
else {
canSymLink = false;
}
}
private static synchronized boolean init() {
String spec = System.getProperty("java.specification.version");
// assume digit.digit
try {
if (spec.length() == 3) {
int major = Integer.parseInt(spec.substring(0, 1));
int minor = Integer.parseInt(spec.substring(2, 3));
boolean canSymLink = (major > 1) || (major == 1 && minor >= 7);
if (!canSymLink) {
return false;
}
}
}
catch (Exception e) {
return false;
}
try {
Class<?> clsFileAttribute = Class.forName("java.nio.file.attribute.FileAttribute");
Class<?> clsFileAttributeArray = Class.forName("[Ljava.nio.file.attribute.FileAttribute;");
EMPTY_FILE_ATTR_ARRAY = Array.newInstance(clsFileAttribute, 0);
Class<?> clsPath = Class.forName("java.nio.file.Path");
clsPaths = Class.forName("java.nio.file.Paths");
clsFiles = Class.forName("java.nio.file.Files");
methodPathsGet = clsPaths.getMethod("get", new Class[] {String.class, String[].class});
methodFilesSymLink = clsFiles.getMethod("createSymbolicLink", new Class[] {clsPath, clsPath, clsFileAttributeArray});
methodReadLink = clsFiles.getMethod("readSymbolicLink", new Class[] {clsPath});
methodIsLink = clsFiles.getMethod("isSymbolicLink", new Class[] {clsPath});
return true;
}
catch (Exception e) {
return false;
}
}
public static boolean canSymLink() {
return canSymLink;
}
private static boolean symLinkTest() {
try {
File f = File.createTempFile("symlinktest", "tmp");
try {
File g = File.createTempFile("symlinktest", "tmp");
try {
g.delete();
symLink(getPath(f.getAbsolutePath()), g.getAbsolutePath());
return true;
}
catch (Exception e) {
return false;
}
finally {
g.delete();
}
}
finally {
f.delete();
}
}
catch (Exception e) {
return false;
}
}
public static void symLink(Object target, String link) throws IOException {
Object filePath = target;
Object linkPath = getPath(link);
filePath = resolveLink(filePath);
createLink(filePath, linkPath);
}
/**
* Determines if a path is a symbolic link. If it is, it resolves it
* and returns the link target. If not, it returns <code>null</code>
*/
public static Object readLink(String file) throws IOException {
try {
Object filePath = getPath(file);
Object[] linkPathArg = new Object[] {filePath};
Boolean isLink = (Boolean) methodIsLink.invoke(null, linkPathArg);
if (isLink) {
return methodReadLink.invoke(null, linkPathArg);
}
else {
return null;
}
}
catch (IllegalArgumentException e) {
throw new UnsupportedOperationException(e);
}
catch (IllegalAccessException e) {
throw new UnsupportedOperationException(e);
}
catch (InvocationTargetException e) {
Throwable t = e.getTargetException();
if (t instanceof UnsupportedOperationException) {
throw (UnsupportedOperationException) t;
}
else if (t instanceof IOException) {
throw (IOException) t;
}
else if (t instanceof SecurityException) {
throw new UnsupportedOperationException(t);
}
else {
throw new UnsupportedOperationException(t);
}
}
}
private static Object resolveLink(Object linkPath) throws IOException {
try {
Object[] linkPathArg = new Object[] {linkPath};
Boolean isLink = (Boolean) methodIsLink.invoke(null, linkPathArg);
if (isLink) {
return methodReadLink.invoke(null, linkPathArg);
}
else {
return linkPath;
}
}
catch (IllegalArgumentException e) {
throw new UnsupportedOperationException(e);
}
catch (IllegalAccessException e) {
throw new UnsupportedOperationException(e);
}
catch (InvocationTargetException e) {
Throwable t = e.getTargetException();
if (t instanceof UnsupportedOperationException) {
throw (UnsupportedOperationException) t;
}
else if (t instanceof IOException) {
throw (IOException) t;
}
else if (t instanceof SecurityException) {
throw new UnsupportedOperationException(t);
}
else {
throw new UnsupportedOperationException(t);
}
}
}
private static void createLink(Object file, Object link) throws IOException {
try {
methodFilesSymLink.invoke(null, new Object[] {link, file, EMPTY_FILE_ATTR_ARRAY});
}
catch (IllegalArgumentException e) {
throw new UnsupportedOperationException(e);
}
catch (IllegalAccessException e) {
throw new UnsupportedOperationException(e);
}
catch (InvocationTargetException e) {
Throwable t = e.getTargetException();
if (t instanceof UnsupportedOperationException) {
throw (UnsupportedOperationException) t;
}
else if (t instanceof IOException) {
throw (IOException) t;
}
else if (t instanceof SecurityException) {
throw new UnsupportedOperationException(t);
}
else if (t instanceof RuntimeException) {
// expect FileAlreadyExistsException
throw new IOException(t);
}
else {
throw new UnsupportedOperationException(t);
}
}
}
public static Object getPath(String file) throws IOException {
if (!canSymLink) {
return null;
}
try {
return methodPathsGet.invoke(null, new Object[] {file, EMPTY_STRING_ARRAY});
}
catch (IllegalArgumentException e) {
throw new UnsupportedOperationException(e);
}
catch (IllegalAccessException e) {
throw new UnsupportedOperationException(e);
}
catch (InvocationTargetException e) {
Throwable t = e.getTargetException();
if (t instanceof RuntimeException) {
// expect InvalidPathException
throw new IOException(t);
}
else {
throw new UnsupportedOperationException(t);
}
}
}
}
|
package org.jabref.gui.importer.fetcher;
import javafx.geometry.Pos;
import javafx.scene.Node;
import javafx.scene.control.Button;
import javafx.scene.control.ComboBox;
import javafx.scene.control.TextField;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Priority;
import javafx.scene.layout.StackPane;
import javafx.scene.layout.VBox;
import org.jabref.gui.JabRefFrame;
import org.jabref.gui.SidePaneComponent;
import org.jabref.gui.SidePaneManager;
import org.jabref.gui.SidePaneType;
import org.jabref.gui.actions.Action;
import org.jabref.gui.actions.ActionFactory;
import org.jabref.gui.actions.StandardActions;
import org.jabref.gui.help.HelpAction;
import org.jabref.gui.icon.IconTheme;
import org.jabref.gui.search.SearchTextField;
import org.jabref.gui.util.ViewModelListCellFactory;
import org.jabref.logic.importer.SearchBasedFetcher;
import org.jabref.logic.l10n.Localization;
import org.jabref.preferences.JabRefPreferences;
import org.fxmisc.easybind.EasyBind;
public class WebSearchPane extends SidePaneComponent {
private final JabRefPreferences preferences;
private final WebSearchPaneViewModel viewModel;
public WebSearchPane(SidePaneManager sidePaneManager, JabRefPreferences preferences, JabRefFrame frame) {
super(sidePaneManager, IconTheme.JabRefIcons.WWW, Localization.lang("Web search"));
this.preferences = preferences;
this.viewModel = new WebSearchPaneViewModel(preferences.getImportFormatPreferences(), frame, preferences);
}
@Override
public Action getToggleAction() {
return StandardActions.TOGGLE_WEB_SEARCH;
}
@Override
protected Node createContentPane() {
// Setup combo box for fetchers
ComboBox<SearchBasedFetcher> fetchers = new ComboBox<>();
new ViewModelListCellFactory<SearchBasedFetcher>()
.withText(SearchBasedFetcher::getName)
.install(fetchers);
fetchers.itemsProperty().bind(viewModel.fetchersProperty());
fetchers.valueProperty().bindBidirectional(viewModel.selectedFetcherProperty());
fetchers.setMaxWidth(Double.POSITIVE_INFINITY);
// Create help button for currently selected fetcher
StackPane helpButtonContainer = new StackPane();
ActionFactory factory = new ActionFactory(preferences.getKeyBindingRepository());
EasyBind.subscribe(viewModel.selectedFetcherProperty(), fetcher -> {
if ((fetcher != null) && fetcher.getHelpPage().isPresent()) {
HelpAction helpCommand = new HelpAction(fetcher.getHelpPage().get());
Button helpButton = factory.createIconButton(StandardActions.HELP, helpCommand.getCommand());
helpButtonContainer.getChildren().setAll(helpButton);
} else {
helpButtonContainer.getChildren().clear();
}
});
HBox fetcherContainer = new HBox(fetchers, helpButtonContainer);
HBox.setHgrow(fetchers, Priority.ALWAYS);
// Create text field for query input
TextField query = SearchTextField.create();
query.setOnAction(event -> viewModel.search());
viewModel.queryProperty().bind(query.textProperty());
// Create button that triggers search
Button search = new Button(Localization.lang("Search"));
search.setDefaultButton(false);
search.setOnAction(event -> viewModel.search());
// Put everything together
VBox container = new VBox();
container.setAlignment(Pos.CENTER);
container.getChildren().addAll(fetcherContainer, query, search);
return container;
}
@Override
public SidePaneType getType() {
return SidePaneType.WEB_SEARCH;
}
@Override
public void beforeClosing() {
preferences.putBoolean(JabRefPreferences.WEB_SEARCH_VISIBLE, Boolean.FALSE);
}
@Override
public void afterOpening() {
preferences.putBoolean(JabRefPreferences.WEB_SEARCH_VISIBLE, Boolean.TRUE);
}
@Override
public Priority getResizePolicy() {
return Priority.NEVER;
}
}
|
// $Id: MergeData.java,v 1.3 2004/09/06 13:55:40 belaban Exp $
package org.jgroups.protocols.pbcast;
import org.jgroups.Address;
import org.jgroups.View;
import java.io.Externalizable;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
/**
* Encapsulates data sent with a MERGE_RSP (handleMergeResponse()) and INSTALL_MERGE_VIEW
* (handleMergeView()).
*
* @author Bela Ban Oct 22 2001
*/
public class MergeData implements Externalizable {
Address sender=null;
boolean merge_rejected=false;
View view=null;
Digest digest=null;
/**
* Empty constructor needed for externalization
*/
public MergeData() {
;
}
public MergeData(Address sender, View view, Digest digest) {
this.sender=sender;
this.view=view;
this.digest=digest;
}
public Address getSender() {
return sender;
}
public View getView() {
return view;
}
public Digest getDigest() {
return digest;
}
public void setView(View v) {
view=v;
}
public void setDigest(Digest d) {
digest=d;
}
public boolean equals(Object other) {
return sender != null && other != null && other instanceof MergeData &&
((MergeData)other).sender != null && ((MergeData)other).sender.equals(sender);
}
public void writeExternal(ObjectOutput out) throws IOException {
out.writeObject(sender);
out.writeBoolean(merge_rejected);
if(!merge_rejected) {
out.writeObject(view);
out.writeObject(digest);
}
}
public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {
sender=(Address)in.readObject();
merge_rejected=in.readBoolean();
if(!merge_rejected) {
view=(View)in.readObject();
digest=(Digest)in.readObject();
}
}
public String toString() {
StringBuffer sb=new StringBuffer();
sb.append("sender=" + sender);
if(merge_rejected)
sb.append(" (merge_rejected)");
else {
sb.append(", view=" + view + ", digest=" + digest);
}
return sb.toString();
}
}
|
package org.jenkinsci.remoting.protocol;
import hudson.remoting.Future;
import java.io.Closeable;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.ClosedChannelException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.RejectedExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
import java.util.logging.Level;
import java.util.logging.LogRecord;
import java.util.logging.Logger;
import javax.annotation.CheckForNull;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import javax.annotation.OverridingMethodsMustInvokeSuper;
import javax.annotation.concurrent.GuardedBy;
import javax.annotation.concurrent.NotThreadSafe;
import org.jenkinsci.remoting.util.ByteBufferPool;
/**
* A stack of {@link ProtocolLayer} that make a network protocol. The stack will start with a {@link NetworkLayer}
* instance,
* optionally followed by a series of {@link FilterLayer} instances and terminated by a {@link ApplicationLayer}
* instance.
*
* Instances are created using the {@link #on(NetworkLayer)} entry point, for example
*
* {@code ProtocolStack.on(netLayer).filter(filterLayer1).filter(filterLayer2).filter(filterLayer3).build(appLayer)}
*
* For this stack, the layers will be initialized and started in the following sequence:
*
* <ol>
* <li>{@link NetworkLayer#init(ProtocolStack.Ptr)} (<em>netLayer</em>)</li>
* <li>{@link FilterLayer#init(ProtocolStack.Ptr)} (<em>filterLayer1</em>)</li>
* <li>{@link FilterLayer#init(ProtocolStack.Ptr)} (<em>filterLayer2</em>)</li>
* <li>{@link FilterLayer#init(ProtocolStack.Ptr)} (<em>filterLayer3</em>)</li>
* <li>{@link ApplicationLayer#init(ProtocolStack.Ptr)} (<em>appLayer</em>)</li>
* <li>{@link NetworkLayer#start()} (<em>netLayer</em>)</li>
* <li>{@link FilterLayer#start()} (<em>filterLayer1</em>)</li>
* <li>{@link FilterLayer#start()} (<em>filterLayer2</em>)</li>
* <li>{@link FilterLayer#start()} (<em>filterLayer3</em>)</li>
* <li>{@link ApplicationLayer#start()} (<em>appLayer</em>)</li>
* </ol>
*
* If this stack is closed via the network layer - a network initiated close - then the close will be propagated in the
* following sequence:
*
* <ol>
* <li>{@link NetworkLayer} (<em>netLayer</em>) detects close</li>
* <li>{@link FilterLayer#onRecvClosed(IOException)} (<em>filterLayer1</em>)</li>
* <li>{@link FilterLayer#onRecvClosed(IOException)} (<em>filterLayer2</em>)</li>
* <li>{@link FilterLayer#onRecvClosed(IOException)} (<em>filterLayer3</em>)</li>
* <li>{@link FilterLayer#onRecvClosed(IOException)} (<em>appLayer</em>)</li>
* <li>{@link FilterLayer#doCloseSend()} (<em>filterLayer3</em>)</li>
* <li>{@link FilterLayer#doCloseSend()} (<em>filterLayer2</em>)</li>
* <li>{@link FilterLayer#doCloseSend()} (<em>filterLayer1</em>)</li>
* <li>{@link NetworkLayer#doCloseSend()} (<em>netLayer</em>)</li>
* </ol>
*
* If this stack is closed via a protocol layer - a mid-stack initiated close - then the close will be propagated in the
* following sequence:
*
* <ol>
* <li>{@link FilterLayer} (<em>filterLayer2</em>) initiates close</li>
* <li>{@link FilterLayer#onRecvClosed(IOException)} (<em>filterLayer3</em>)</li>
* <li>{@link FilterLayer#onRecvClosed(IOException)} (<em>appLayer</em>)</li>
* <li>{@link FilterLayer#doCloseSend()} (<em>filterLayer3</em>)</li>
* <li>{@link FilterLayer#doCloseSend()} (<em>filterLayer2</em>)</li>
* <li>{@link FilterLayer#doCloseSend()} (<em>filterLayer1</em>)</li>
* <li>{@link NetworkLayer#doCloseSend()} (<em>netLayer</em>)</li>
* <li>{@link FilterLayer#onRecvClosed(IOException)} (<em>filterLayer1</em>)</li>
* </ol>
*
* @param <T> the application specific API.
* @since 3.0
*/
public class ProtocolStack<T> implements Closeable, ByteBufferPool {
/**
* Our logger.
*/
private static final Logger LOGGER = Logger.getLogger(ProtocolStack.class.getName());
/**
* The lock that guards the {@link Ptr#nextSend} and {@link Ptr#nextRecv} pointers.
*/
private final ReadWriteLock stackLock = new ReentrantReadWriteLock();
/**
* Our network layer.
*/
private final NetworkLayer network;
/**
* Our application layer.
*/
private final ApplicationLayer<T> application;
/**
* The first layer for receiving data, should always point to {@link #network}.
*/
private final Ptr recvHead;
/**
* The name of this stack in to provide when logging.
*/
// TODO replace with org.slf4j.MDC once we switch to slf4j
private String name;
/**
* Our listeners.
*/
@GuardedBy("stackLock")
private final List<Listener> listeners = new ArrayList<Listener>();
private final long handshakingTimeout = 10L;
private final TimeUnit handshakingUnits = TimeUnit.SECONDS;
/**
* Private constructor used by {@link Builder#build(ApplicationLayer)}
*
* @param name the name of this stack to attach to logs.
* @param network the network transport.
* @param filters the filters.
* @param application the application layer.
*/
private ProtocolStack(String name, NetworkLayer network,
List<FilterLayer> filters,
ApplicationLayer<T> application,
List<Listener> listeners) {
this.name = name;
this.network = network;
this.application = application;
this.recvHead = new Ptr(network);
this.listeners.addAll(listeners);
Ptr sendHead = recvHead;
for (FilterLayer protocol : filters) {
sendHead = new Ptr(sendHead, protocol);
}
new Ptr(sendHead, application);
}
/**
* Create a {@link ProtocolStack} on the supplied {@link NetworkLayer}.
*
* @param network the {@link NetworkLayer} to build the stack on.
* @return the {@link ProtocolStack.Builder}.
*/
public static ProtocolStack.Builder on(NetworkLayer network) {
return new Builder(network);
}
/**
* Initialize the stack.
*
* @throws IOException if the stack could not be initialized.
*/
private void init() throws IOException {
if (LOGGER.isLoggable(Level.FINEST)) {
LOGGER.log(Level.FINEST, "[{0}] Initializing", name());
}
assert recvHead.layer == network;
for (Ptr p = recvHead; p != null; p = p.getNextRecv()) {
p.layer.init(p);
}
if (LOGGER.isLoggable(Level.FINEST)) {
LOGGER.log(Level.FINEST, "[{0}] Starting", name());
}
for (Ptr p = recvHead; p != null; p = p.getNextRecv()) {
try {
p.layer.start();
} catch (IOException e) {
if (LOGGER.isLoggable(Level.FINEST)) {
LogRecord record = new LogRecord(Level.FINEST, "[{0}] Start failure");
record.setParameters(new Object[]{name()});
record.setThrown(e);
LOGGER.log(record);
}
Ptr nextRecv = p.getNextRecv();
if (nextRecv != null) {
p.onRecvClosed(e);
}
throw e;
}
}
if (LOGGER.isLoggable(Level.FINEST)) {
LOGGER.log(Level.FINEST, "[{0}] Started", name());
}
}
/**
* Gets the application specific API.
*
* @return the application specific API.
* @see ApplicationLayer#get()
*/
public T get() {
return application.get();
}
/**
* The name of this stack to use in logging.
*
* @return the name of this stack to use in logging.
*/
public String name() {
return name;
}
/**
* Updates the name of this stack to use in logging.
*
* @param name the new name of this stack to use in logging.
*/
public void name(String name) {
if (!(this.name == null ? name == null : this.name.equals(name))) {
if (LOGGER.isLoggable(Level.FINER)) {
LOGGER.log(Level.FINER, "[{0}] is now known as [{1}]", new Object[]{this.name, name});
}
this.name = name != null && !name.isEmpty() ? name : this.name;
}
}
/**
* {@inheritDoc}
*/
@Override
public void close() throws IOException {
if (LOGGER.isLoggable(Level.FINEST)) {
LOGGER.log(Level.FINEST, "[{0}] Closing", name());
}
try {
application.doCloseWrite();
} catch (IOException e) {
if (LOGGER.isLoggable(Level.FINEST)) {
LogRecord record = new LogRecord(Level.FINEST, "[{0}] Abnormal close");
record.setParameters(new Object[]{name()});
record.setThrown(e);
LOGGER.log(record);
}
throw e;
} finally {
if (LOGGER.isLoggable(Level.FINEST)) {
LOGGER.log(Level.FINEST, "[{0}] Closed", name());
}
}
}
/**
* Adds a listener.
*
* @param listener the listener.
*/
public void addListener(Listener listener) {
stackLock.writeLock().lock();
try {
listeners.add(listener);
} finally {
stackLock.writeLock().unlock();
}
}
/**
* Removes a listener.
*
* @param listener the listener.
*/
public void removeListener(Listener listener) {
stackLock.writeLock().lock();
try {
listeners.remove(listener);
} finally {
stackLock.writeLock().unlock();
}
}
/**
* Request the {@link NetworkLayer} to stop receiving data.
*/
/*package*/ void doCloseRecv() {
network.doCloseRecv();
}
/**
* Check if the {@link NetworkLayer} is open to receive data.
*
* @return {@code true} if the {@link NetworkLayer} is receiving data.
*/
/*package*/ boolean isRecvOpen() {
return network.isRecvOpen();
}
/**
* {@inheritDoc}
*/
@Override
public int hashCode() {
return System.identityHashCode(this);
}
/**
* {@inheritDoc}
*/
@Override
public boolean equals(Object obj) {
return this == obj;
}
/**
* {@inheritDoc}
*/
@Override
public String toString() {
final StringBuilder sb = new StringBuilder("ProtocolStack{");
sb.append("name='").append(name).append('\'');
sb.append(",[");
assert recvHead.layer == network;
for (Ptr p = recvHead; p != null; p = p.getNextRecv()) {
if (p != recvHead) {
sb.append(',');
}
sb.append(p.layer);
}
sb.append("]}");
return sb.toString();
}
/**
* Callback notification that the protocol stack has been closed.
*
* @param cause the cause or {@code null} if the close was "normal".
*/
/*package*/ void onClosed(IOException cause) {
final List<Listener> listeners = new ArrayList<Listener>();
stackLock.readLock().lock();
try {
listeners.addAll(this.listeners);
} finally {
stackLock.readLock().unlock();
}
for (Listener listener : listeners) {
listener.onClosed(this, cause);
}
}
/**
* Executes the given command at some time in the future.
*
* @param task the runnable task
* @throws RejectedExecutionException if this task cannot be accepted for execution
* @throws NullPointerException if task is null
*/
@OverridingMethodsMustInvokeSuper
public void execute(Runnable task) {
network.getIoHub().execute(task);
}
/**
* Executes a task at a future point in time. This method should not be used for timing critical scheduling,
* rather it is intended to be used for things such as protocol timeouts.
*
* @param task the task.
* @param delay the delay.
* @param units the time units for the delay.
* @return a {@link Future} that completes when the task has run and can be used to cancel the execution.
* @throws RejectedExecutionException if this task cannot be accepted for execution
* @throws NullPointerException if task is null
*/
@OverridingMethodsMustInvokeSuper
public Future<?> executeLater(Runnable task, long delay, TimeUnit units) {
return network.getIoHub().executeLater(task, delay, units);
}
/**
* Gets this {@link ProtocolStack}'s handshaking timeout.
*
* @return this {@link ProtocolStack}'s handshaking timeout.
* @see #getHandshakingUnits()
*/
public long getHandshakingTimeout() {
return handshakingTimeout;
}
/**
* Gets the {@link TimeUnit} of {@link #getHandshakingTimeout()}.
*
* @return the {@link TimeUnit} of {@link #getHandshakingTimeout()}.
* @see #getHandshakingTimeout() ()
*/
public TimeUnit getHandshakingUnits() {
return handshakingUnits;
}
/**
* {@inheritDoc}
*/
@Override
public ByteBuffer acquire(int size) {
return network.getIoHub().acquire(size);
}
/**
* {@inheritDoc}
*/
@Override
public void release(ByteBuffer buffer) {
network.getIoHub().release(buffer);
}
/**
* Builder for {@link ProtocolStack} instances.
*/
@NotThreadSafe
public static class Builder {
/**
* Used tssign each stack a unique name unless a name has been specified.
*/
private static final AtomicInteger id = new AtomicInteger();
/**
* The network layer to build on.
*/
private final NetworkLayer network;
/**
* The filters to build with.
*/
private final List<FilterLayer> filters;
/**
* The initial listeners to register.
*/
private final List<Listener> listeners = new ArrayList<Listener>();
/**
* The name to give the protocol stack.
*/
@CheckForNull
private String name;
/**
* Flag to track that this builder has been used.
*/
private boolean built;
/**
* Creates a new {@link Builder}
*
* @param network the network stack.
*/
private Builder(NetworkLayer network) {
if (network.stack() != null) {
throw new IllegalArgumentException();
}
this.network = network;
this.filters = new ArrayList<FilterLayer>();
}
/**
* Adds the supplied filter into the {@link ProtocolStack}.
*
* @param filter the filter to add, if {@code null} then it will be ignored (useful for conditionally adding
* filters)
* @return {@code this}.
*/
public Builder filter(@CheckForNull FilterLayer filter) {
if (filter != null) {
if (filter.stack() != null) {
throw new IllegalArgumentException();
}
checkNotBuilt();
filters.add(filter);
}
return this;
}
/**
* Provide a custom name for the {@link ProtocolStack}.
*
* @param name the custom name.
* @return {@code this}
*/
public Builder named(String name) {
checkNotBuilt();
this.name = name;
return this;
}
/**
* Register a {@link Listener} for the {@link ProtocolStack}.
*
* @param listener the listener.
* @return {@code this}
*/
public Builder listener(Listener listener) {
checkNotBuilt();
this.listeners.add(listener);
return this;
}
/**
* Create the {@link ProtocolStack}.
*
* @param application the {@link ApplicationLayer} to use.
* @param <T> the application specific API.
* @return the {@link ProtocolStack}.
* @throws IOException if the {@link ProtocolStack} could not be started.
*/
public <T> ProtocolStack<T> build(ApplicationLayer<T> application) throws IOException {
if (application.stack() != null) {
throw new IllegalArgumentException();
}
checkNotBuilt();
built = true;
ProtocolStack<T> stack =
new ProtocolStack<T>(
name == null || name.isEmpty() ? String.format("Stack-%d", id.incrementAndGet()) : name,
network,
filters,
application,
listeners);
stack.init();
return stack;
}
/**
* Enforce the {@link Builder} as single use.
*/
private void checkNotBuilt() {
if (built) {
throw new IllegalStateException("Builder is single-shot as Network layers cannot be reused");
}
}
}
/**
* Tracks where a {@link ProtocolLayer} is in the {@link ProtocolStack}.
*/
public class Ptr {
/**
* Our layer.
*/
private final ProtocolLayer layer;
/**
* The next layer for sending.
*/
@GuardedBy("ProtocolStack.stackLock")
private Ptr nextSend;
/**
* The next layer for receiving.
*/
@GuardedBy("ProtocolStack.stackLock")
private Ptr nextRecv;
/**
* Flag to track calling {@link ProtocolLayer.Recv#onRecvClosed(IOException)}.
*/
@GuardedBy("ProtocolStack.stackLock")
private boolean recvOnClosed;
/**
* Flag to track calling {@link ProtocolLayer.Send#doCloseSend()}.
*/
@GuardedBy("ProtocolStack.stackLock")
private boolean sendDoClosed;
/**
* Flag to track this {@link ProtocolLayer} as removed from the stack.
*/
private boolean removed;
/**
* Creates the first {@link Ptr}.
*
* @param network the {@link NetworkLayer}.
*/
private Ptr(NetworkLayer network) {
stackLock.writeLock().lock();
try {
nextSend = null;
} finally {
stackLock.writeLock().unlock();
}
this.layer = network;
}
/**
* Creates a filter {@link Ptr}.
*
* @param nextSend the previous {@link Ptr}.
* @param filter the {@link FilterLayer}
*/
private Ptr(Ptr nextSend, FilterLayer filter) {
stackLock.writeLock().lock();
try {
this.nextSend = nextSend;
nextSend.nextRecv = this;
} finally {
stackLock.writeLock().unlock();
}
this.layer = filter;
}
/**
* Creates the last {@link Ptr}.
*
* @param nextSend the previous {@link Ptr}.
* @param application the {@link ApplicationLayer}
*/
private Ptr(Ptr nextSend, ApplicationLayer<?> application) {
stackLock.writeLock().lock();
try {
this.nextSend = nextSend;
nextSend.nextRecv = this;
} finally {
stackLock.writeLock().unlock();
}
this.layer = application;
}
/**
* Each {@link ProtocolLayer.Recv} should call this method to hand received data up the stack to the next
* {@link ProtocolLayer} (except for the {@link ApplicationLayer} which should eat the data).
*
* @param data the data to submit to the next layer up the stack.
* @throws IOException if the next layer could not process the data.
*/
public void onRecv(ByteBuffer data) throws IOException {
if (!data.hasRemaining()) {
return;
}
Ptr nextRecv = getNextRecv();
if (nextRecv == null) {
throw new UnsupportedOperationException("Application layer is not supposed to call onRecv");
}
ProtocolLayer.Recv recv = (ProtocolLayer.Recv) nextRecv.layer;
if (recv.isRecvOpen()) {
recv.onRecv(data);
} else {
throw new ClosedChannelException();
}
}
/**
* Each {@link ProtocolLayer.Send} should call this method to hand data for sending down the stack to the next
* {@link ProtocolLayer} (except for the {@link NetworkLayer} which should eat the data).
*
* @param data the data to submit to the next layer down the stack.
* @throws IOException if the next layer could not process the data.
*/
public void doSend(ByteBuffer data) throws IOException {
if (!data.hasRemaining()) {
return;
}
Ptr nextSend = getNextSend();
if (nextSend == null) {
throw new UnsupportedOperationException("Network layer is not supposed to call doSend");
}
ProtocolLayer.Send send = (ProtocolLayer.Send) nextSend.layer;
if (send.isSendOpen()) {
send.doSend(data);
} else {
throw new ClosedChannelException();
}
}
/**
* Checks if the next layer up the stack is open to receive data.
*
* @return {@code true} if the next layer up the stack is open to receive data.
*/
public boolean isRecvOpen() {
Ptr nextRecv;
stackLock.readLock().lock();
try {
nextRecv = getNextRecv();
if (nextRecv == null) {
throw new UnsupportedOperationException("Application layer is not supposed to call isRecvOpen");
}
if (recvOnClosed) {
return false;
}
} finally {
stackLock.readLock().unlock();
}
return ((ProtocolLayer.Recv) nextRecv.layer).isRecvOpen();
}
/**
* Checks if the next layer down the stack is open to send data.
*
* @return {@code true} if the next layer down the stack is open to send data.
*/
public boolean isSendOpen() {
Ptr nextSend;
stackLock.readLock().lock();
try {
nextSend = getNextSend();
if (nextSend == null) {
throw new UnsupportedOperationException("Network layer is not supposed to call isSendOpen");
}
if (sendDoClosed) {
return false;
}
} finally {
stackLock.readLock().unlock();
}
return ((ProtocolLayer.Send) nextSend.layer).isSendOpen();
}
/**
* Helper method to access the {@link ProtocolStack}.
*
* @return the {@link ProtocolStack}.
*/
public ProtocolStack<?> stack() {
return ProtocolStack.this;
}
/**
* Requests removal of this {@link ProtocolLayer} from the {@link ProtocolStack}
*/
public void remove() {
removed = true;
}
/**
* Requests the next layer down the stack to close output.
*
* @throws IOException if there was an error closing the output.
*/
public void doCloseSend() throws IOException {
if (getNextSend() == null) {
throw new UnsupportedOperationException("Network layer is not allowed to call doClose()");
}
stackLock.readLock().lock();
try {
if (sendDoClosed) {
return;
}
} finally {
stackLock.readLock().unlock();
}
stackLock.writeLock().lock();
try {
if (sendDoClosed) {
return;
}
sendDoClosed = true;
} finally {
stackLock.writeLock().unlock();
}
if (nextSend().isSendOpen()) {
nextSend().doCloseSend();
}
}
/**
* Notify the next layer up the stack that input has been closed.
*
* @param cause the cause of the lower layer being closed or {@code null}.
* @throws IOException if there was an error processing the close notification.
*/
public void onRecvClosed(IOException cause) throws IOException {
if (getNextRecv() == null) {
throw new UnsupportedOperationException("Application layer is not supposed to call onClose");
}
stackLock.readLock().lock();
try {
if (recvOnClosed) {
return;
}
} finally {
stackLock.readLock().unlock();
}
stackLock.writeLock().lock();
try {
if (recvOnClosed) {
return;
}
recvOnClosed = true;
} finally {
stackLock.writeLock().unlock();
}
if (nextRecv().isRecvOpen()) {
nextRecv().onRecvClosed(cause);
}
}
/**
* Helper to get the next layer down the stack as a {@link ProtocolLayer.Send}.
*
* @return the next layer down the stack.
* @throws NullPointerException if invoked from the {@link NetworkLayer}.
*/
@Nonnull
private ProtocolLayer.Send nextSend() {
return (ProtocolLayer.Send) getNextSend().layer;
}
/**
* Gets the {@link Ptr} for the next layer down the stack (processing the send half of any intermediary
* {@link #removed} flags if possible, if not possible it skips the removed {@link Ptr} instances anyway,
* leaving the update to a later call)
*
* @return the {@link Ptr} for the next layer down the stack
*/
@Nullable
private Ptr getNextSend() {
Ptr nextSend;
stackLock.readLock().lock();
try {
nextSend = this.nextSend;
while (nextSend != null && nextSend.removed && nextSend.nextSend != null) {
nextSend = nextSend.nextSend;
}
if (nextSend == this.nextSend) {
return nextSend;
}
} finally {
stackLock.readLock().unlock();
}
if (stackLock.writeLock().tryLock()) {
// we only need to unwind ourselves eventually, if we cannot do it now ok to do it later
try {
while (this.nextSend != nextSend && this.nextSend != null && this.nextSend.removed) {
assert this.nextSend.layer instanceof FilterLayer
: "this is the layer before and there is a layer after nextSend thus nextSend "
+ "*must* be a FilterLayer";
((FilterLayer) this.nextSend.layer).onSendRemoved();
// remove this.nextSend from the stack as it has set it's removed flag
Ptr tmp = this.nextSend.nextSend;
this.nextSend.nextSend = null;
this.nextSend = tmp;
}
} finally {
stackLock.writeLock().unlock();
}
}
return nextSend;
}
/**
* Helper to get the next layer up the stack as a {@link ProtocolLayer.Recv}.
*
* @return the next layer up the stack.
* @throws NullPointerException if invoked from the {@link ApplicationLayer}.
*/
@Nonnull
private ProtocolLayer.Recv nextRecv() {
return (ProtocolLayer.Recv) getNextRecv().layer;
}
/**
* Gets the {@link Ptr} for the next layer up the stack (processing the receive half of any intermediary
* {@link #removed} flags if possible, if not possible it skips the removed {@link Ptr} instances anyway,
* leaving the update to a later call)
*
* @return the {@link Ptr} for the next layer up the stack
*/
@Nullable
private Ptr getNextRecv() {
Ptr nextRecv;
stackLock.readLock().lock();
try {
nextRecv = this.nextRecv;
while (nextRecv != null && nextRecv.removed && nextRecv.nextRecv != null) {
nextRecv = nextRecv.nextRecv;
}
if (nextRecv == this.nextRecv) {
return this.nextRecv;
}
} finally {
stackLock.readLock().unlock();
}
if (stackLock.writeLock().tryLock()) {
// we only need to unwind ourselves eventually, if we cannot do it now ok to do it later
try {
while (this.nextRecv != nextRecv && this.nextRecv != null && this.nextRecv.removed) {
assert this.nextRecv.layer instanceof FilterLayer
: "this is the layer before and there is a layer after nextRecv thus nextRecv "
+ "*must* be a FilterLayer";
((FilterLayer) this.nextRecv.layer).onRecvRemoved();
// remove this.nextRecv from the stack as it has set it's removed flag
Ptr tmp = this.nextRecv.nextRecv;
this.nextRecv.nextRecv = null;
this.nextRecv = tmp;
}
} finally {
stackLock.writeLock().unlock();
}
}
return nextRecv;
}
}
/**
* Callback "interface" for changes in the state of {@link ProtocolStack}.
*/
public interface Listener {
/**
* When the stack was closed normally or abnormally due to an error.
*
* @param stack the stack that has closed.
* @param cause if the stack is closed abnormally, this parameter
* represents an exception that has triggered it.
* Otherwise {@code null}.
*/
void onClosed(ProtocolStack<?> stack, IOException cause);
}
}
|
package org.jitsi.jicofo;
import net.java.sip.communicator.impl.protocol.jabber.extensions.colibri.*;
import net.java.sip.communicator.impl.protocol.jabber.extensions.rayo.*;
import net.java.sip.communicator.service.protocol.*;
import net.java.sip.communicator.util.Logger;
import org.jitsi.impl.protocol.xmpp.extensions.*;
import org.jitsi.jicofo.log.*;
import org.jitsi.protocol.xmpp.*;
import org.jitsi.util.*;
import org.jitsi.videobridge.eventadmin.*;
import org.jivesoftware.smack.*;
import org.jivesoftware.smack.filter.*;
import org.jivesoftware.smack.packet.*;
import org.jivesoftware.smack.packet.Message; //disambiguation
import org.jivesoftware.smack.provider.*;
import org.jivesoftware.smackx.packet.*;
/**
* Class handles various Jitsi Meet extensions IQs like {@link MuteIq} and
* Colibri for recording.
*
* @author Pawel Domas
* @author Boris Grozev
*/
public class MeetExtensionsHandler
implements PacketFilter,
PacketListener
{
/**
* The logger
*/
private final static Logger logger
= Logger.getLogger(MeetExtensionsHandler.class);
/**
* <tt>FocusManager</tt> instance for accessing info about all active
* conferences.
*/
private final FocusManager focusManager;
/**
* Operation set that provider XMPP connection.
*/
private OperationSetDirectSmackXmpp smackXmpp;
/**
* Creates new instance of {@link MeetExtensionsHandler}.
* @param focusManager <tt>FocusManager</tt> that will be used by new
* instance to access active conferences and focus
* XMPP connection.
*/
public MeetExtensionsHandler(FocusManager focusManager)
{
this.focusManager = focusManager;
MuteIqProvider muteIqProvider = new MuteIqProvider();
muteIqProvider.registerMuteIqProvider(
ProviderManager.getInstance());
RayoIqProvider rayoIqProvider = new RayoIqProvider();
rayoIqProvider.registerRayoIQs(
ProviderManager.getInstance());
StartMutedProvider startMutedProvider = new StartMutedProvider();
startMutedProvider.registerStartMutedProvider(
ProviderManager.getInstance());
}
/**
* Initializes this instance and bind packet listeners.
*/
public void init()
{
this.smackXmpp
= focusManager.getOperationSet(
OperationSetDirectSmackXmpp.class);
smackXmpp.addPacketHandler(this, this);
}
/**
* Disposes this instance and stop listening for extensions packets.
*/
public void dispose()
{
if (smackXmpp != null)
{
smackXmpp.removePacketHandler(this);
smackXmpp = null;
}
}
@Override
public boolean accept(Packet packet)
{
return acceptMuteIq(packet)
|| acceptColibriIQ(packet)
|| acceptRayoIq(packet)
|| acceptMessage(packet)
|| acceptPresence(packet);
}
@Override
public void processPacket(Packet packet)
{
if (smackXmpp == null)
{
logger.error("Not initialized");
return;
}
if (packet instanceof ColibriConferenceIQ)
{
handleColibriIq((ColibriConferenceIQ) packet);
}
else if (packet instanceof MuteIq)
{
handleMuteIq((MuteIq) packet);
}
else if (packet instanceof RayoIqProvider.DialIq)
{
handleRayoIQ((RayoIqProvider.DialIq) packet);
}
else if (packet instanceof Message)
{
handleMessage((Message) packet);
}
else if (packet instanceof Presence)
{
handlePresence((Presence) packet);
}
else
{
logger.error("Unexpected packet: " + packet.toXML());
}
}
private boolean acceptColibriIQ(Packet packet)
{
return packet instanceof ColibriConferenceIQ
// And with recording element
&& ((ColibriConferenceIQ)packet).getRecording() != null;
}
private void handleColibriIq(ColibriConferenceIQ colibriIQ)
{
ColibriConferenceIQ.Recording recording = colibriIQ.getRecording();
String from = colibriIQ.getFrom();
JitsiMeetConference conference
= getConferenceForMucJid(colibriIQ.getFrom());
if (conference == null)
{
logger.debug("Room not found for JID: " + from);
return;
}
boolean recordingState =
conference.modifyRecordingState(
colibriIQ.getFrom(),
recording.getToken(),
recording.getState(),
recording.getDirectory());
ColibriConferenceIQ response = new ColibriConferenceIQ();
response.setType(IQ.Type.RESULT);
response.setPacketID(colibriIQ.getPacketID());
response.setTo(colibriIQ.getFrom());
response.setFrom(colibriIQ.getTo());
response.setRecording(
new ColibriConferenceIQ.Recording(recordingState));
smackXmpp.getXmppConnection().sendPacket(response);
}
private boolean acceptMuteIq(Packet packet)
{
return packet instanceof MuteIq;
}
private String getRoomNameFromMucJid(String mucJid)
{
int atIndex = mucJid.indexOf("@");
int slashIndex = mucJid.indexOf("/");
if (atIndex == -1 || slashIndex == -1)
return null;
return mucJid.substring(0, slashIndex);
}
private JitsiMeetConference getConferenceForMucJid(String mucJid)
{
String roomName = getRoomNameFromMucJid(mucJid);
if (roomName == null)
{
return null;
}
return focusManager.getConference(roomName);
}
private void handleMuteIq(MuteIq muteIq)
{
Boolean doMute = muteIq.getMute();
String jid = muteIq.getJid();
if (doMute == null || StringUtils.isNullOrEmpty(jid))
return;
String from = muteIq.getFrom();
JitsiMeetConference conference = getConferenceForMucJid(from);
if (conference == null)
{
logger.debug("Mute error: room not found for JID: " + from);
return;
}
IQ result;
if (conference.handleMuteRequest(muteIq.getFrom(), jid, doMute))
{
result = IQ.createResultIQ(muteIq);
if (!muteIq.getFrom().equals(jid))
{
MuteIq muteStatusUpdate = new MuteIq();
muteStatusUpdate.setType(IQ.Type.SET);
muteStatusUpdate.setTo(jid);
muteStatusUpdate.setMute(doMute);
smackXmpp.getXmppConnection().sendPacket(muteStatusUpdate);
}
}
else
{
result = IQ.createErrorResponse(
muteIq,
new XMPPError(XMPPError.Condition.interna_server_error));
}
smackXmpp.getXmppConnection().sendPacket(result);
}
private boolean acceptRayoIq(Packet p)
{
return p instanceof RayoIqProvider.DialIq;
}
private void handleRayoIQ(RayoIqProvider.DialIq dialIq)
{
String from = dialIq.getFrom();
JitsiMeetConference conference = getConferenceForMucJid(from);
if (conference == null)
{
logger.debug("Mute error: room not found for JID: " + from);
return;
}
ChatRoomMemberRole role = conference.getRoleForMucJid(from);
if (role == null)
{
// Only room members are allowed to send requests
IQ error = createErrorResponse(
dialIq, new XMPPError(XMPPError.Condition.forbidden));
smackXmpp.getXmppConnection().sendPacket(error);
return;
}
if (ChatRoomMemberRole.MODERATOR.compareTo(role) < 0)
{
IQ error = createErrorResponse(
dialIq, new XMPPError(XMPPError.Condition.not_allowed));
smackXmpp.getXmppConnection().sendPacket(error);
return;
}
// Check if Jigasi is available
String jigasiJid = conference.getServices().getSipGateway();
if (StringUtils.isNullOrEmpty(jigasiJid))
{
// Not available
IQ error = createErrorResponse(
dialIq, new XMPPError(XMPPError.Condition.service_unavailable));
smackXmpp.getXmppConnection().sendPacket(error);
return;
}
// Redirect original request to Jigasi component
String originalPacketId = dialIq.getPacketID();
dialIq.setFrom(null);
dialIq.setTo(jigasiJid);
dialIq.setPacketID(IQ.nextID());
IQ reply
= (IQ) smackXmpp.getXmppConnection().sendPacketAndGetReply(dialIq);
// Send Jigasi response back to the client
reply.setFrom(null);
reply.setTo(from);
reply.setPacketID(originalPacketId);
smackXmpp.getXmppConnection().sendPacket(reply);
}
private boolean acceptMessage(Packet packet)
{
if (packet != null && packet instanceof Message)
{
for (PacketExtension pe : packet.getExtensions())
if (pe instanceof LogPacketExtension)
return true;
}
return false;
}
/**
* Handles "message" stanzas.
*/
private void handleMessage(Message message)
{
for (PacketExtension ext : message.getExtensions())
if (ext instanceof LogPacketExtension)
handleLogRequest((LogPacketExtension) ext, message.getFrom());
}
/**
* Handles XEP-0337 "log" extensions.
*/
private void handleLogRequest(LogPacketExtension log, String jid)
{
JitsiMeetConference conference = getConferenceForMucJid(jid);
if (conference == null)
{
logger.debug("Room not found for JID: " + jid);
return;
}
Participant participant = conference.findParticipantForRoomJid(jid);
if (participant != null)
{
EventAdmin eventAdmin = FocusBundleActivator.getEventAdmin();
if (eventAdmin != null)
{
if (LogUtil.LOG_ID_PC_STATS.equals(log.getID()))
{
String content = LogUtil.getContent(log);
if (content != null)
{
Event event =
EventFactory.peerConnectionStats(
conference.getColibriConference().getConferenceId(),
participant.getEndpointId(),
content);
if (event != null)
eventAdmin.sendEvent(event);
}
}
else
{
if (logger.isInfoEnabled())
logger.info("Ignoring log request with an unknown ID:"
+ log.getID());
}
}
}
else
{
logger.info("Ignoring log request from an unknown JID: " + jid);
}
}
private boolean acceptPresence(Packet packet)
{
return packet instanceof Presence;
}
/**
* Handles presence stanzas
* @param presence
*/
private void handlePresence(Presence presence)
{
// unavailable is sent when user leaves the room
if (!presence.isAvailable())
{
return;
}
String from = presence.getFrom();
JitsiMeetConference conference = getConferenceForMucJid(from);
if (conference == null)
{
logger.debug("Room not found for JID: " + from);
return;
}
ChatRoomMemberRole role
= conference.getRoleForMucJid(presence.getFrom());
if(role != null &&
role.compareTo(ChatRoomMemberRole.MODERATOR) < 0)
{
StartMutedPacketExtension ext
= (StartMutedPacketExtension) presence.getExtension(
StartMutedPacketExtension.ELEMENT_NAME,
StartMutedPacketExtension.NAMESPACE);
if(ext != null)
{
boolean[] startMuted = new boolean[2];
startMuted[0] = ext.getAudioMuted();
startMuted[1] = ext.getVideoMuted();
conference.setStartMuted(startMuted);
}
}
Participant participant
= conference.findParticipantForRoomJid(presence.getFrom());
if (participant != null)
{
// Check if this conference is valid
String conferenceId
= conference.getColibriConference().getConferenceId();
if (StringUtils.isNullOrEmpty(conferenceId))
{
logger.error(
"Unable to send DisplayNameChanged event" +
" - no conference id");
return;
}
// Check for changes to the display name
String oldDisplayName = participant.getDisplayName();
String newDisplayName = null;
for (PacketExtension pe : presence.getExtensions())
{
if (pe instanceof Nick)
{
newDisplayName = ((Nick) pe).getName();
break;
}
}
if ((oldDisplayName == null && newDisplayName != null)
|| (oldDisplayName != null
&& !oldDisplayName.equals(newDisplayName)))
{
participant.setDisplayName(newDisplayName);
// Prevent NPE when adding to event hashtable
if (newDisplayName == null)
{
newDisplayName = "";
}
EventAdmin eventAdmin = FocusBundleActivator.getEventAdmin();
if (eventAdmin != null)
{
eventAdmin.sendEvent(
EventFactory.endpointDisplayNameChanged(
conferenceId,
participant.getEndpointId(),
newDisplayName));
}
}
}
}
/**
* FIXME: replace with IQ.createErrorResponse
* Prosody does not allow to include request body in error
* response. Replace this method with IQ.createErrorResponse once fixed.
*/
private IQ createErrorResponse(IQ request, XMPPError error)
{
if (!(request.getType() == IQ.Type.GET
|| request.getType() == IQ.Type.SET))
{
throw new IllegalArgumentException(
"IQ must be of type 'set' or 'get'. Original IQ: "
+ request.toXML());
}
final IQ result = new IQ()
{
public String getChildElementXML()
{
return "";
}
};
result.setType(IQ.Type.ERROR);
result.setPacketID(request.getPacketID());
result.setFrom(request.getTo());
result.setTo(request.getFrom());
result.setError(error);
return result;
}
}
|
package org.jinstagram.utils;
import java.nio.charset.Charset;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.lang.NullPointerException;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import org.apache.commons.codec.binary.Hex;
import org.jinstagram.exceptions.InstagramException;
@Deprecated
public class EnforceSignedHeaderUtils {
public static final String ENFORCE_SIGNED_HEADER = "X-Insta-Forwarded-For";
private static final String HMAC_SHA256 = "HmacSHA256";
@Deprecated
public static String signature(String clientSecret, String message) throws InstagramException {
try {
SecretKeySpec keySpec = new SecretKeySpec(clientSecret.getBytes(Charset.forName("UTF-8")), HMAC_SHA256);
Mac mac = Mac.getInstance(HMAC_SHA256);
mac.init(keySpec);
byte[] result = mac.doFinal(message.getBytes(Charset.forName("UTF-8")));
return Hex.encodeHexString(result);
} catch (NoSuchAlgorithmException e) {
throw new InstagramException("Invalid algorithm name!", e);
} catch (InvalidKeyException e) {
throw new InstagramException("Invalid key: " + clientSecret, e);
} catch (NullPointerException e) {
throw new InstagramException("Key is null!", e);
}
}
}
|
package org.objectweb.proactive.core.node;
import org.objectweb.proactive.ActiveObjectCreationException;
import org.objectweb.proactive.core.runtime.ProActiveRuntime;
/**
* <p>
* A <code>Node</code> offers a set of services needed by ProActive to work with
* remote JVM. Each JVM that is aimed to hold active objects should contains at least
* one instance of the node class. That instance, when created, will be registered
* to some registry where it is possible to perform a lookup (such as the RMI registry).
* </p><p>
* When ProActive needs to interact with a remote JVM, it will lookup for one node associated
* with that JVM (using typically the RMI Registry) and use this node to perform the interaction.
* </p><p>
* We expect several concrete implementations of the Node to be wrtten such as a RMI node, a JINI node ...
* </p>
*
* @author ProActive Team
* @version 1.1, 2002/08/28
* @since ProActive 0.9
*
*/
public interface Node
{
/**
* Returns the node information as one object. This method allows to
* retrieve all node information in one call to optimize performance.
* @return the node information as one object
*/
public NodeInformation getNodeInformation();
/**
* Returns a reference to the <code>ProActiveRuntime</code> where the node has been created
* @return ProActiveRuntime. The reference to the <code>ProActiveRuntime</code> where the node has been created
*/
public ProActiveRuntime getProActiveRuntime();
/**
* Returns all activeObjects deployed on this Node
* @return Object[] contains all activeObjects deployed on this Node
*/
public Object[] getActiveObjects() throws NodeException,ActiveObjectCreationException;
/**
* Returns all activeObjects with the given name deployed on this Node
* or null if such objects do not exist
* @param objectName the class of the Active Objects
* @return Object[].The set of activeObjects deployed on this node with the given name
*/
public Object[] getActiveObject(String objectName) throws NodeException,ActiveObjectCreationException;
}
|
package org.lightmare.deploy.management;
import java.io.File;
import java.io.IOException;
import java.io.Serializable;
import java.io.Writer;
import java.util.List;
import javax.servlet.Servlet;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.lightmare.deploy.fs.Watcher;
import org.lightmare.utils.CollectionUtils;
import org.lightmare.utils.IOUtils;
import org.lightmare.utils.ObjectUtils;
import org.lightmare.utils.StringUtils;
/**
* {@link Servlet} to manage deployed applications
*
* @author levan
*
*/
@WebServlet("/DeployManager")
public class DeployManager extends HttpServlet {
private static final long serialVersionUID = 1L;
public static final String DEPLOY_MANAGER_DEFAULT_NAME = CollectionUtils
.getFirst(DeployManager.class.getAnnotation(WebServlet.class)
.value());
// HTML tags
private static final String BEGIN_TAGS = "<tr><td><a name = \"";
private static final String NAME_OF_TAGS = "\" href=\"
private static final String END_NAME_TAGS = "</a></td>\n";
private static final String END_TAGS = "</td><td><a href = \"DeployManager\">reload</a></td></tr>";
private static final String REDEPLOY_START_TAG = "<td><a name = \"";
private static final String REDEPLOY_TYPE_TAG = "\" href=\"#\" onClick=\"sendRequest(this.name, '";
private static final String REDEPLOY_FILE_TYPE_TAG = "', '";
private static final String REDEPLOY_NAME_TAG = "')\">";
private static final String REDEPLOY_END_TAG = "</a></td>";
private static final String BEGIN_PAGE = StringUtils
.concat("<html>\n",
"\t<head><script type=\"text/javascript\">\n",
"/* <![CDATA[ */\n",
"\t\tfunction sendRequest(redeploy, type, fileType){\n ",
"\t\t\tvar xmlhttp = new XMLHttpRequest();\n ",
"\t\t\tvar reqUrl = \"DeployManager?file=\" + redeploy + \"&type=\" + type + \"&fileType=\" + fileType;\n",
"\t\t\txmlhttp.open(\"GET\", reqUrl, true);\n",
"\t\t\txmlhttp.send();\n", "}\n", "\n",
"</script>\n", "\t<title>Deployment management</title>",
"</head>\n", "\t<body>\n", "\t<table>\n");
private static final String TYPE_TAG = "\t\t<tr><td><br><b>";
private static final String END_TYPE_TAG = "</b></br></td></tr>\n";
private static final String END_PAGE = "</body></table>\n </html>";
private static final String LOGIN_PAGE = StringUtils
.concat("<html>\n",
"\t\t<head>\n",
"\t\t\t<title>Login</title>\n",
"\t\t</head>\n",
"\t\t<body>\n",
"\t\t\t\t\t\t<br><form name = \"ManagementLogin\" method=\"post\">",
"\t\t\t\t\t\t\t<br><input type=\"user\" name=\"user\"></br>",
"\t\t\t\t\t\t\t<br><input type=\"password\" name=\"password\"></br>",
"\t\t\t\t\t\t\t<br><input type=\"submit\" value=\"Submit\"></br>",
"\t\t\t\t\t\t</form></br>\n");
private static final String INCORRECT_MESSAGE = "<br><b>invalid user name / passowd</b></br>";
private static final String CONTROLL_NOT_ALLOWED_MESSAGE = "<br><b>server does not allows remote control</b></br>";
private static final String END_LOGIN_PAGE = "</html>";
private static final String DEPLOYMENTS = "deployments";
private static final String DATA_SOURCES = "datasources";
// HTTP parameters
private static final String REDEPLOY_PARAM_NAME = "file";
private static final String TYPE_PARAM_NAME = "type";
private static final String REDEPLOY_TYPE = "redeploy";
private static final String UNDEPLOY_TYPE = "undeploy";
protected static final String FILE_TYPE_PARAMETER_NAME = "fileType";
private static final String APP_DEPLOYMENT_TYPE = "application";
private static final String DTS_DEPLOYMENT_TYPE = "datasource";
private static final String USER_PARAMETER_NAME = "user";
private static final String PASS_PARAMETER_NAME = "password";
// Security for deploy management
private Security security;
/**
* Class to cache authenticated users for {@link DeployManager} java
* {@link javax.servlet.http.HttpServlet} page
*
* @author levan
*
*/
private static class DeployPass implements Serializable {
private static final long serialVersionUID = 1L;
private String userName;
}
private String getApplications() {
List<File> apps = Watcher.listDeployments();
List<File> dss = Watcher.listDataSources();
StringBuilder builder = new StringBuilder();
builder.append(BEGIN_PAGE);
builder.append(TYPE_TAG);
builder.append(DEPLOYMENTS);
builder.append(END_TYPE_TAG);
String tag;
if (CollectionUtils.valid(apps)) {
for (File app : apps) {
tag = getTag(app.getPath(), APP_DEPLOYMENT_TYPE);
builder.append(tag);
}
}
builder.append(BEGIN_PAGE);
builder.append(TYPE_TAG);
builder.append(DATA_SOURCES);
builder.append(END_TYPE_TAG);
if (CollectionUtils.valid(dss)) {
for (File ds : dss) {
tag = getTag(ds.getPath(), DTS_DEPLOYMENT_TYPE);
builder.append(tag);
}
}
builder.append(END_PAGE);
return builder.toString();
}
private void fillDeployType(StringBuilder builder, String app, String type,
String fileType) {
builder.append(REDEPLOY_START_TAG);
builder.append(app);
builder.append(REDEPLOY_TYPE_TAG);
builder.append(type);
builder.append(REDEPLOY_FILE_TYPE_TAG);
builder.append(fileType);
builder.append(REDEPLOY_NAME_TAG);
builder.append(type);
builder.append(REDEPLOY_END_TAG);
}
private String getTag(String app, String fileType) {
StringBuilder builder = new StringBuilder();
builder.append(BEGIN_TAGS);
builder.append(app);
builder.append(NAME_OF_TAGS);
builder.append(app);
builder.append(END_NAME_TAGS);
fillDeployType(builder, app, UNDEPLOY_TYPE, fileType);
fillDeployType(builder, app, REDEPLOY_TYPE, fileType);
builder.append(END_TAGS);
return builder.toString();
}
private String toLoginPage(boolean incorrect) {
StringBuilder builder = new StringBuilder();
builder.append(LOGIN_PAGE);
if (incorrect) {
builder.append(INCORRECT_MESSAGE);
}
builder.append(END_LOGIN_PAGE);
return builder.toString();
}
private boolean authenticate(String userName, String password,
HttpServletRequest request) {
boolean valid = security.controlAllowed(request)
&& security.authenticate(userName, password);
if (valid) {
DeployPass pass = new DeployPass();
pass.userName = userName;
HttpSession session = request.getSession(Boolean.FALSE);
session.setAttribute(Security.DEPLOY_PASS_KEY, pass);
}
return valid;
}
private boolean check(HttpSession session) {
boolean valid = ObjectUtils.notNull(session);
if (valid) {
Object pass = session.getAttribute(Security.DEPLOY_PASS_KEY);
valid = ObjectUtils.notNull(pass);
if (valid) {
valid = (pass instanceof DeployPass)
&& (StringUtils.valid(((DeployPass) pass).userName));
} else {
valid = security.check();
}
}
return valid;
}
@Override
public void init() throws ServletException {
try {
security = new Security();
} catch (IOException ex) {
}
super.init();
}
@Override
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
boolean controllAllowed = security.controlAllowed(request);
if (ObjectUtils.notTrue(controllAllowed)) {
response.sendError(HttpServletResponse.SC_FORBIDDEN,
CONTROLL_NOT_ALLOWED_MESSAGE);
} else {
boolean check = check(request.getSession(Boolean.FALSE));
String html;
if (check) {
String fileName = request.getParameter(REDEPLOY_PARAM_NAME);
String type = request.getParameter(TYPE_PARAM_NAME);
if (StringUtils.valid(fileName)) {
if (type == null || REDEPLOY_TYPE.equals(type)) {
Watcher.redeployFile(fileName);
} else if (UNDEPLOY_TYPE.equals(type)) {
Watcher.undeployFile(fileName);
}
}
html = getApplications();
} else {
html = toLoginPage(Boolean.FALSE);
}
Writer writer = response.getWriter();
try {
writer.write(html);
} finally {
IOUtils.close(writer);
}
}
}
@Override
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
boolean remoteAllowed = security.controlAllowed(request);
if (ObjectUtils.notTrue(remoteAllowed)) {
response.sendError(HttpServletResponse.SC_FORBIDDEN,
CONTROLL_NOT_ALLOWED_MESSAGE);
} else {
String userName = request.getParameter(USER_PARAMETER_NAME);
String password = request.getParameter(PASS_PARAMETER_NAME);
boolean valid = StringUtils.valid(userName)
&& StringUtils.valid(password);
if (valid) {
valid = authenticate(userName, password, request);
}
if (valid) {
response.sendRedirect(DEPLOY_MANAGER_DEFAULT_NAME);
} else {
String html = toLoginPage(Boolean.TRUE);
Writer writer = response.getWriter();
try {
writer.write(html);
} finally {
IOUtils.close(writer);
}
}
}
}
}
|
package web.component.impl.aws.model;
import java.util.HashSet;
import java.util.Set;
import org.junit.After;
import org.junit.AfterClass;
import static org.junit.Assert.*;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import web.component.api.model.VPC;
import web.component.impl.aws.AWS;
import web.component.impl.aws.ec2.AWSEC2;
/**
*
* @author ksc
*/
public class VPCImplTest {
static final String expectedCidrBlock = "10.1.0.0/16";
static final String expectedTenancy = "";
static final String expectedState = "";
static final String expectedDhcpOptionsId = "";
static VPCImpl testInstance;
static String expectedStringExpression;
static Set<VPC> testInstances = new HashSet<>();
public VPCImplTest() {
}
@BeforeClass
public static void setUpClass() {
testInstance = (VPCImpl) new VPCImpl.Builder().cidr(expectedCidrBlock).tenancy(expectedTenancy).create();
testInstances.add(testInstance);
while(!testInstance.getState().equals("available")){
System.out.println("wait for test vpc to be ready ...");
try {
Thread.sleep(10000);
} catch (InterruptedException ex) {
}
}
expectedStringExpression = "{VpcId: " + testInstance.getId() + ",CidrBlock: " + expectedCidrBlock + ",DhcpOptionsId: " + expectedDhcpOptionsId + ",Tags: [],InstanceTenancy: " + expectedTenancy + ",}";
System.out.println("Vpc for test is now available.");
}
@AfterClass
public static void tearDownClass() {
for(VPC toDelete : testInstances){
System.out.println("Delete test vpc [" + toDelete.toString() + "]");
toDelete.delete();
}
}
@Before
public void setUp() {
}
@After
public void tearDown() {
}
/**
* Test of asEc2Vpc method, of class VPCImpl.
*/
@Test
public void testAsEc2Vpc() {
System.out.println("asEc2Vpc");
AWSEC2 ec2 = (AWSEC2)AWS.get(AWS.BlockName.EC2);
com.amazonaws.services.ec2.model.Vpc source = ec2.getExistEc2Vpc(testInstance.getId());
com.amazonaws.services.ec2.model.Vpc viewAsEc2Vpc = testInstance.asEc2Vpc();
//two instances should be equal, but not the same.
assertEquals(source, viewAsEc2Vpc);
assertFalse(source == viewAsEc2Vpc);
}
/**
* Test of getCidrBlock method, of class VPCImpl.
*/
@Test
public void testGetCidrBlock() {
System.out.println("getCidrBlock");
assertEquals(expectedCidrBlock, testInstance.getCidrBlock());
}
/**
* Test of getDhcpOptionsId method, of class VPCImpl.
*/
@Test
public void testGetDhcpOptionsId() {
System.out.println("getDhcpOptionsId");
assertEquals(expectedDhcpOptionsId, testInstance.getDhcpOptionsId());
}
/**
* Test of getInstanceTenancy method, of class VPCImpl.
*/
@Test
public void testGetInstanceTenancy() {
System.out.println("getInstanceTenancy");
assertEquals(expectedTenancy, testInstance.getInstanceTenancy());
}
/**
* Test of getIsDefault method, of class VPCImpl.
*/
@Test
public void testGetIsDefault() {
System.out.println("getIsDefault");
assertEquals(true, testInstance.getIsDefault());
}
/**
* Test of getState method, of class VPCImpl.
*/
@Test
public void testGetState() {
System.out.println("getState");
assertEquals(expectedState, testInstance.getState());
}
/**
* Test of getId method, of class VPCImpl.
*/
@Test
public void testGetId() {
System.out.println("getId");
VPC existVpc = new VPCImpl.Builder().id(testInstance.getId()).get();
assertEquals(testInstance.getId(), existVpc.getId());
}
/**
* Test of delete method, of class VPCImpl.
*/
@Test
public void testDelete() {
System.out.println("delete");
VPC toBeDeleted = new VPCImpl.Builder().cidr(expectedCidrBlock).tenancy(expectedTenancy).create();
while(!toBeDeleted.getState().equals("available")){
try {
Thread.sleep(10000);
} catch (InterruptedException ex) {
}
}
testInstances.add(toBeDeleted);
String deletedId = toBeDeleted.getId();
toBeDeleted.delete();
//wait for deletion to be completed.
try {
Thread.sleep(3000);
} catch (InterruptedException ex) {
}
VPC shouldHaveBeenDeleted = new VPCImpl.Builder().id(deletedId).get();
assertEquals("Unknown state", shouldHaveBeenDeleted.getState());
}
/**
* Test of equals method, of class VPCImpl.
*/
@Test
public void testEquals() {
System.out.println("equals");
VPC equalInstance = new VPCImpl.Builder().id(testInstance.getId()).get();
VPC anotherInstance = new VPCImpl.Builder().cidr(expectedCidrBlock).tenancy(expectedTenancy).create();
testInstances.add(anotherInstance);
while(!anotherInstance.getState().equals("available")){
try {
Thread.sleep(10000);
} catch (InterruptedException ex) {
}
}
assertTrue(testInstance.equals(equalInstance));
assertFalse(testInstance.equals(anotherInstance));
}
/**
* Test of hashCode method, of class VPCImpl.
*/
@Test
public void testHashCode() {
System.out.println("hashCode");
VPC equalInstance = new VPCImpl.Builder().id(testInstance.getId()).get();
VPC anotherInstance = new VPCImpl.Builder().cidr(expectedCidrBlock).tenancy(expectedTenancy).create();
testInstances.add(anotherInstance);
while(!anotherInstance.getState().equals("available")){
try {
Thread.sleep(10000);
} catch (InterruptedException ex) {
}
}
assertTrue(testInstance.hashCode() == equalInstance.hashCode());
assertTrue(testInstance.hashCode() != anotherInstance.hashCode());
}
/**
* Test of toString method, of class VPCImpl.
*/
@Test
public void testToString() {
System.out.println("toString");
assertEquals(expectedStringExpression, testInstance.toString());
}
}
|
package org.onedatashare.server.module;
import com.google.api.services.drive.Drive;
import com.google.api.services.drive.model.File;
import com.google.api.services.drive.model.FileList;
import org.onedatashare.server.model.core.Stat;
import org.onedatashare.server.model.credential.EndpointCredential;
import org.onedatashare.server.model.credential.OAuthEndpointCredential;
import org.onedatashare.server.model.error.NotFoundException;
import org.onedatashare.server.model.filesystem.operations.DeleteOperation;
import org.onedatashare.server.model.filesystem.operations.DownloadOperation;
import org.onedatashare.server.model.filesystem.operations.ListOperation;
import org.onedatashare.server.model.filesystem.operations.MkdirOperation;
import org.onedatashare.server.model.request.TransferJobRequest;
import org.onedatashare.server.config.GDriveConfig;
import reactor.core.publisher.Mono;
import java.io.IOException;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
/**
* Resource class that provides services for Google Drive endpoint.
*/
public class GDriveResource extends Resource {
public static GDriveConfig gDriveConfig;
public static final String ROOT_DIR_ID = "root";
private static final String DOWNLOAD_URL = "https://drive.google.com/uc?id=%s&export=download";
private OAuthEndpointCredential credential;
private Drive service;
public GDriveResource(EndpointCredential credential) throws IOException {
this.credential = (OAuthEndpointCredential) credential;
gDriveConfig.initialize();
service = gDriveConfig.getDriveService(this.credential);
}
public Stat statHelper(String path, String id) throws IOException {
Drive.Files.List result;
Stat stat = new Stat()
.setName(path)
.setId(id);
if (path.equals("/")) {
stat.setDir(true);
result = this.service.files().list()
.setOrderBy("name")
.setQ("trashed=false and 'root' in parents")
.setFields("nextPageToken, files(id, name, kind, mimeType, size, modifiedTime)");
if (result == null) {
throw new NotFoundException();
}
FileList fileSet = null;
List<Stat> sub = new LinkedList<>();
do {
try {
fileSet = result.execute();
List<File> files = fileSet.getFiles();
for (File file : files) {
sub.add(mDataToStat(file));
}
stat.setFiles(sub);
result.setPageToken(fileSet.getNextPageToken());
} catch (NullPointerException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
fileSet.setNextPageToken(null);
}
}
while (result.getPageToken() != null);
} else {
File googleDriveFile = this.service.files().get(id)
.setFields("id, name, kind, mimeType, size, modifiedTime")
.execute();
if (googleDriveFile.getMimeType().equals("application/vnd.google-apps.folder")) {
stat.setDir(true);
String query = new StringBuilder().append("trashed=false and ")
.append("'" + id + "'").append(" in parents").toString();
result = this.service.files().list()
.setOrderBy("name").setQ(query)
.setFields("nextPageToken, files(id, name, kind, mimeType, size, modifiedTime)");
if (result == null)
throw new NotFoundException();
FileList fileSet = null;
List<Stat> sub = new LinkedList<>();
do {
try {
fileSet = result.execute();
List<File> files = fileSet.getFiles();
for (File file : files) {
sub.add(mDataToStat(file));
}
stat.setFiles(sub);
result.setPageToken(fileSet.getNextPageToken());
} catch (Exception e) {
fileSet.setNextPageToken(null);
}
}
while (result.getPageToken() != null);
} else {
stat.setFile(true);
stat.setTime(googleDriveFile.getModifiedTime().getValue() / 1000);
stat.setSize(googleDriveFile.getSize());
}
}
return stat;
}
private Stat mDataToStat(File file) {
Stat stat = new Stat(file.getName());
try {
stat.setFile(true);
stat.setId(file.getId());
stat.setTime(file.getModifiedTime().getValue()/1000);
if (file.getMimeType().equals("application/vnd.google-apps.folder")) {
stat.setDir(true);
stat.setFile(false);
}
else if(file.containsKey("size"))
stat.setSize(file.getSize());
}
catch (NullPointerException e) {
}catch (Exception e) {
e.printStackTrace();
}
return stat;
}
@Override
public Mono<Void> delete(DeleteOperation operation) {
return Mono.create(s -> {
try {
this.service.files().delete(operation.getId()).execute();
s.success();
} catch (IOException e) {
s.error(e);
}
});
}
@Override
public Mono<Stat> list(ListOperation operation) {
return Mono.create(s ->{
try {
Stat stat = statHelper(operation.getPath(), operation.getId());
s.success(stat);
} catch (IOException e) {
s.error(e);
}
});
}
@Override
public Mono<Void> mkdir(MkdirOperation operation) {
return Mono.create(s -> {
try {
String[] foldersToCreate = operation.getFolderToCreate().split("/");
String currId = operation.getId();
for(int i =0; i < foldersToCreate.length; i++){
if(foldersToCreate[i].equals("")){
continue;
}
File fileMetadata = new File();
fileMetadata.setName(foldersToCreate[i]);
fileMetadata.setMimeType("application/vnd.google-apps.folder");
fileMetadata.setParents(Collections.singletonList(currId));
File file = this.service.files().create(fileMetadata)
.setFields("id")
.execute();
currId = file.getId();
}
} catch (IOException e) {
s.error(e);
}
s.success();
});
}
@Override
public Mono download(DownloadOperation operation) {
return null;
}
public static Mono<? extends Resource> initialize(EndpointCredential credential){
return Mono.create(s -> {
try {
GDriveResource gDriveResource= new GDriveResource(credential);
s.success(gDriveResource);
} catch (Exception e) {
s.error(e);
}
});
}
}
|
package org.protorabbit.json;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.lang.reflect.Type;
import java.lang.reflect.ParameterizedType;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.logging.Logger;
import org.protorabbit.json.Serialize;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public class DefaultSerializer implements JSONSerializer {
private static Logger logger = null;
static Logger getLogger() {
if (logger == null) {
logger = Logger.getLogger("org.protrabbit");
}
return logger;
}
public Object serialize(Object o) {
// null is null
if (o == null) {
return JSONObject.NULL;
}
// collections
if (Collection.class.isAssignableFrom(o.getClass())) {
Iterator<?> it = ((Collection<?>)o).iterator();
JSONArray ja = new JSONArray();
while(it.hasNext()) {
Object i = serialize(it.next());
ja.put(i);
}
return ja;
}
// maps
if (Map.class.isAssignableFrom(o.getClass())) {
JSONObject jo = new JSONObject();
Map<?, ?> m = ((Map<?, ?>)o);
Iterator<?> ki = m.keySet().iterator();
while (ki.hasNext()) {
Object key = ki.next();
Object value = serialize(m.get(key));
try {
jo.put(key.toString(), value);
} catch (JSONException e) {
e.printStackTrace();
}
}
return jo;
}
// primitives
if (o instanceof Double ||
o instanceof Number ||
o instanceof Integer ||
o instanceof String ||
o instanceof Enum<?> ||
o instanceof Boolean) {
return o;
}
if (o instanceof Date) {
return ((Date)o).getTime();
}
// convert arrays to collections
boolean b = o.getClass().isArray();
if (b) {
try {
Object[] objs = (Object[])o;
List<Object> l = Arrays.asList(objs);
return serialize(l);
} catch (ClassCastException e) {
return JSONObject.NULL;
}
}
// serialize using bean like methods
return serializePOJO(o, true);
}
protected boolean skipSerialization ( Method m ) {
boolean skipIt = !( Modifier.isPublic(m.getModifiers()) &&
!"getHibernateLazyInitializer".equals(m.getName()) &&
!"getClass".equals(m.getName()) &&
!"getParent".equals(m.getName()) &&
!"getSystemClassLoader".equals(m.getName()) &&
!"getMethods".equals(m.getName()) &&
!"getDeclaredClasses".equals(m.getName()) &&
!"getConstructors".equals(m.getName()) &&
!"getDeclaringClass".equals(m.getName()) &&
!"getEnclosingClass".equals(m.getName()) &&
!"getClassLoader".equals(m.getName()) &&
(m.getName().startsWith("get") ||
m.getName().startsWith("is") ) &&
m.getName().length() > 2 &&
m.getParameterTypes().length == 0);
if( !skipIt &&
m.isAnnotationPresent(Serialize.class)) {
Serialize s = m.getAnnotation(Serialize.class);
if ("skip".equals(s.value())) {
skipIt = true;
}
}
return skipIt;
}
/*
* Look at all the public methods in the object
* find the ones that start with "get"
*
* create a property key for the methods and invoke the method using reflection
* to get value.
*/
public Object serializePOJO(Object pojo, boolean includeSuper) {
if ("java.lang.Class".equals(pojo.getClass().getName())) {
return null;
}
if (pojo.getClass().getClassLoader() == null) {
includeSuper = false;
}
Object[] args = {};
HashMap<String, Object> map = new HashMap<String, Object>();
Method[] methods = null;
if (includeSuper) {
methods =pojo.getClass().getMethods();
} else {
methods =pojo.getClass().getDeclaredMethods();
}
for (int i=0; i < methods.length;i++) {
Method m = methods[i];
try {
// skip if there is a skip annotation
if( !skipSerialization( m ) )
{
// change the case of the property from camelCase
String key = "";
if (m.getName().startsWith("is") &&
m.getName().length() > 3) {
key += m.getName().substring(2,3).toLowerCase();
// get the rest of the name;
key += m.getName().substring(3);
} else if (m.getName().startsWith("get") &&
m.getName().length() >= 4) {
key += m.getName().substring(3,4).toLowerCase();
// get the rest of the name;
key += m.getName().substring(4);
}
Object value = m.invoke(pojo, args);
map.put(key, value);
}
} catch (IllegalArgumentException e) {
getLogger().warning("Unable to serialize " + pojo + " : " + e);
} catch (IllegalAccessException e) {
getLogger().warning("Unable to serialize " + pojo + " : " + e);
} catch (InvocationTargetException e) {
getLogger().warning("Unable to serialize " + pojo + " : " + e);
}
}
// use the serializer itself to serialize a map of properties we created
if (map.keySet().size() > 0) {
return serialize(map);
}
return JSONObject.NULL;
}
/*
* Get a 1 argument method matching the name and assignable with a given property
*/
@SuppressWarnings("unchecked")
void invokeMethod(Method[] methods, String key, String name, JSONObject jo, Object targetObject) {
Object param = null;
Throwable ex = null;
for (int i=0;i < methods.length; i++) {
Method m = methods[i];
if (m.getName().equals(name)) {
Class<?>[] paramTypes = m.getParameterTypes();
if (paramTypes.length == 1 && jo.has(key)) {
Class<?> tparam = paramTypes[0];
boolean allowNull = false;
try {
if ( jo.isNull(key)) {
// do nothing because param is already null : lets us not null on other types
} else if (Long.class.isAssignableFrom(tparam) || tparam == long.class ) {
param = new Long(jo.getLong(key));
} else if (Double.class.isAssignableFrom(tparam) || tparam == double.class ) {
param = new Double(jo.getDouble(key));
} else if (Integer.class.isAssignableFrom(tparam) || tparam == int.class ) {
param = new Integer(jo.getInt(key));
} else if (String.class.isAssignableFrom(tparam)) {
param = jo.getString(key);
} else if (Enum.class.isAssignableFrom(tparam)) {
param = Enum.valueOf((Class<? extends Enum>)tparam, jo.getString(key));
} else if (Boolean.class.isAssignableFrom(tparam)) {
param = new Boolean(jo.getBoolean(key));
} else if (jo.isNull(key)) {
param = null;
allowNull = true;
} else if (Collection.class.isAssignableFrom( tparam ) ) {
if ( m.getGenericParameterTypes().length > 0) {
Type t = m.getGenericParameterTypes()[0];
if ( t instanceof ParameterizedType) {
ParameterizedType tv = (ParameterizedType)t;
if ( tv.getActualTypeArguments().length > 0 &&
tv.getActualTypeArguments()[0] == String.class ) {
List<String> ls = new ArrayList<String>();
JSONArray ja = jo.optJSONArray( key );
if ( ja != null) {
for (int j=0; j < ja.length(); j++) {
ls.add( ja.getString(j) );
}
}
param = ls;
} else {// TODO : Add general object processing
getLogger().warning("Don't know how to handle Collection of type : " + tv.getActualTypeArguments()[0] );
}
}
}
} else {
getLogger().warning("Unable to serialize " + key + " : Don't know how to handle " + tparam );
}
} catch (JSONException e) {
e.printStackTrace();
}
if (param != null || allowNull) {
try {
if (m != null) {
Object[] args = {param};
m.invoke(targetObject, args);
ex = null;
break;
}
} catch (SecurityException e) {
ex = e;
} catch (IllegalArgumentException e) {
ex = e;
} catch (IllegalAccessException e) {
ex = e;
} catch (InvocationTargetException e) {
ex = e;
}
}
}
}
}
if (ex != null) {
if (ex instanceof RuntimeException) {
throw (RuntimeException)ex;
} else {
throw new RuntimeException(ex);
}
}
}
public void deSerialize(String jsonText, Object targetObject) {
try {
JSONObject jo = new JSONObject(jsonText);
deSerialize(jo, targetObject);
} catch (JSONException e) {
e.printStackTrace();
}
}
@SuppressWarnings("unchecked")
public void deSerialize(Object jsonObject, Object targetObject) {
if (jsonObject != null) {
JSONObject jo = (JSONObject)jsonObject;
Method[] methods = targetObject.getClass().getMethods();
Iterator<String> it = jo.keys();
while (it.hasNext()) {
String key = it.next();
// jump out if the key length is too short
if (key.length() <= 1) continue;
String mName = "set" + key.substring(0,1).toUpperCase() + key.substring(1);
invokeMethod( methods,key, mName, jo, targetObject);
}
}
}
public Object genericDeserialize(String jsonText) {
// check for array
jsonText = jsonText.trim();
if (jsonText.startsWith("[")) {
try {
JSONArray ja = new JSONArray(jsonText);
return genericDeserialize(ja, null, null);
} catch (JSONException jex) {
throw new RuntimeException("Error Parsing JSON:" + jex);
}
// check for object
} else if (jsonText.startsWith("{")) {
try {
JSONObject jo = new JSONObject(jsonText);
return genericDeserialize(jo, null, null);
} catch (JSONException jex) {
throw new RuntimeException("Error Parsing JSON:" + jex);
}
} else {
throw new RuntimeException("Error : Can only deserialize JSON objects or JSON arrays");
}
}
@SuppressWarnings("unchecked")
private void addValue(Object targetObject, Object value, String key) {
if (targetObject == null) {
throw new RuntimeException("Error serializing: Can only deserialize JSON objects or JSON arrays");
} else if (targetObject instanceof ArrayList) {
List l = (List)targetObject;
l.add(value);
} else if (targetObject instanceof HashMap && key != null) {
Map m = (Map)targetObject;
m.put(key, value);
}
}
@SuppressWarnings("unchecked")
private Object genericDeserialize(Object o, Object targetObject, String key) throws JSONException {
if (o instanceof JSONObject) {
JSONObject jo = (JSONObject)o;
Map<String,Object> jaoo = new HashMap<String,Object>();
// only add if we are not top level
if (targetObject != null) {
addValue(targetObject, jaoo, key);
}
Iterator<String> it = jo.keys();
while (it.hasNext()) {
String k = it.next();
Object value = jo.get(k);
genericDeserialize(value, jaoo, k);
}
// if we are the top level object return self
if (targetObject == null) {
return jaoo;
}
} else if (o instanceof JSONArray) {
JSONArray ja = (JSONArray)o;
List<Object> jal = new ArrayList<Object>();
// only add if we are not top level
if (targetObject != null) {
addValue(targetObject, jal, key);
}
for (int i=0; i < ja.length(); i++) {
Object jao = ja.get(i);
genericDeserialize(jao, jal, null);
}
// if we are the top level object return self
if (targetObject == null) {
return jal;
}
// primitives
} else if (o instanceof Date) {
Object value = ((Date)o).getTime();
addValue(targetObject, value, key);
} else {
addValue(targetObject, o, key);
}
return null;
}
public Object deSerialize(String jsonText, Class<?> targetClass) {
// check for array
jsonText = jsonText.trim();
if (jsonText.startsWith("[")) {
try {
JSONArray ja = new JSONArray(jsonText);
List<Object> jal = new ArrayList<Object>();
for (int i=0; i < ja.length(); i++) {
try {
Object jao = ja.get(i);
Object targetObject = targetClass.newInstance();
deSerialize( jao, targetObject );
jal.add( targetObject );
} catch (InstantiationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return jal;
} catch (JSONException jex) {
throw new RuntimeException("Error Parsing JSON:" + jex);
}
// check for object
} else if (jsonText.startsWith("{")) {
try {
Object o = targetClass.newInstance();
deSerialize(jsonText, o);
return o;
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
} else {
throw new RuntimeException("Error : Can only deserialize JSON objects or JSON arrays");
}
return null;
}
public static void main(String[] args) {
/*
DefaultSerializer df = new DefaultSerializer();
TestObject to = new TestObject();
to.setFirstName("Greg");
to.setLastName("Murray");
to.setTimeout(55L);
to.setFoo( TestObject.Foo.One);
System.out.println("Original Object=" + to);
JSONObject json = (JSONObject) df.serialize(to);
System.out.println("JSON Object=" + json);
TestObject to2 = (TestObject) df.deSerialize(json.toString(), TestObject.class);
System.out.println("After=" + to2);
*/
}
}
|
package uk.co.uwcs.choob.modules;
import uk.co.uwcs.choob.*;
import java.sql.*;
import uk.co.uwcs.choob.support.*;
import uk.co.uwcs.choob.support.events.*;
import java.security.*;
import java.util.List;
import java.util.ArrayList;
/**
* Logs lines from IRC to the database.
* @author sadiq
*/
public final class HistoryModule
{
private DbConnectionBroker dbBroker;
/** Creates a new instance of LoggerModule */
HistoryModule(DbConnectionBroker dbBroker)
{
this.dbBroker = dbBroker;
}
/**
* Logs a line from IRC to the database.
* @param mes {@link Message} object representing the line from IRC.
* @throws Exception Thrown from the database access, potential SQL or IO exceptions.
*/
public void addLog( Message mes )
{
if (mes.getSynthLevel() > 0)
return;
AccessController.checkPermission(new ChoobPermission("history.add"));
Connection dbConnection = null;
PreparedStatement insertLine = null;
try
{
dbConnection=dbBroker.getConnection();
insertLine = dbConnection.prepareStatement("INSERT INTO History VALUES(NULL,?,?,?,?,?,?,?)");
insertLine.setString(1, mes.getClass().getName());
insertLine.setString(2, mes.getNick());
insertLine.setString(3, mes.getNick()+"@"+mes.getHostname());
String chan = null;
if (mes instanceof ChannelEvent)
{
chan = ((ChannelEvent)mes).getChannel();
}
insertLine.setString(4, chan);
insertLine.setString(5, mes.getMessage());
insertLine.setLong(6, mes.getMillis());
insertLine.setInt(7, mes.getRandom());
insertLine.executeUpdate();
}
catch( SQLException e )
{
System.err.println("Could not write history line to database: " + e);
// I think this exception doesn't need to be propogated... --bucko
}
finally
{
try
{
if (insertLine != null)
insertLine.close();
}
catch (SQLException e)
{
System.err.println("Could not close SQL connection: " + e);
}
finally
{
dbBroker.freeConnection( dbConnection );
}
}
}
/**
* Get the ID of a message object.
* @param mes The message object to find.
* @return Either a message ID, or -1 if the message didn't exist.
*/
public int getMessageID( Message mes )
{
Connection dbCon = null;
PreparedStatement stat = null;
try
{
dbCon=dbBroker.getConnection();
if (mes instanceof ChannelEvent)
{
stat = dbCon.prepareStatement("SELECT LineID FROM History WHERE Type = ? AND Nick = ? AND Hostmask = ? AND Time = ? AND Random = ? AND Channel = ?");
stat.setString(6, ((ChannelEvent)mes).getChannel());
}
else
stat = dbCon.prepareStatement("SELECT LineID FROM History WHERE Type = ? AND Nick = ? AND Hostmask = ? AND Time = ? AND Random = ?"); // Checking if the channel is null causes speshulness here. The check is irrelevant, though, because it will be, because of the Type.
stat.setString(1, mes.getClass().getName());
stat.setString(2, mes.getNick());
stat.setString(3, mes.getNick()+"@"+mes.getHostname());
stat.setLong(4, mes.getMillis());
stat.setInt(5, mes.getRandom());
ResultSet result = stat.executeQuery();
if ( result.first() )
return result.getInt(1);
else
return -1;
}
catch( SQLException e )
{
System.err.println("Could not read history line from database: " + e);
throw new ChoobError("SQL Error reading from database.");
}
finally
{
try
{
if (stat != null)
stat.close();
}
catch (SQLException e)
{
System.err.println("Could not read history line from database: " + e);
throw new ChoobError("SQL Error reading from database.");
}
finally
{
dbBroker.freeConnection( dbCon );
}
}
}
/**
* Get a historic message object.
* @param messageID The message ID, as returned from getMessageID.
* @return The message object or null if it didn't exist.
*/
public Message getMessage( int messageID )
{
System.out.println("getMessage");
Connection dbCon = null;
PreparedStatement stat = null;
try
{
dbCon=dbBroker.getConnection();
stat = dbCon.prepareStatement("SELECT * FROM History WHERE LineID = ?");
stat.setInt(1, messageID);
final ResultSet result = stat.executeQuery();
if ( result.first() )
{
System.out.println("resultfirst");
final String type = result.getString(2);
int pos = result.getString(4).indexOf('@');
final String login = result.getString(4).substring(0,pos);
final String host = result.getString(4).substring(pos+1);
final String channel = result.getString(5);
Message mes;
try
{
// Need privs to create events...
mes = AccessController.doPrivileged( new PrivilegedExceptionAction<Message>() {
public Message run() throws SQLException {
System.out.println("run");
if (type.equals(ChannelAction.class.getName()))
return new ChannelAction("onAction", result.getLong(7), result.getInt(8), result.getString(6), result.getString(3), login, host, channel, channel);
else if (type.equals(ChannelMessage.class.getName()))
return new ChannelMessage("onMessage", result.getLong(7), result.getInt(8), result.getString(6), result.getString(3), login, host, channel, channel);
else if (type.equals(PrivateMessage.class.getName()))
return new PrivateMessage("onPrivateMessage", result.getLong(7), result.getInt(8), result.getString(6), result.getString(3), login, host, channel);
else if (type.equals(PrivateAction.class.getName()))
return new PrivateAction("onPrivateAction", result.getLong(7), result.getInt(8), result.getString(6), result.getString(3), login, host, channel);
return null;
}
});
}
catch (PrivilegedActionException e)
{
throw (SQLException)e.getCause();
// Is an SQL exception...
}
if (mes == null)
System.err.println("Invalid event type: " + type);
return mes;
}
else
return null;
}
catch( SQLException e )
{
System.err.println("Could not read history line from database: " + e);
throw new ChoobError("SQL Error reading from database.");
}
finally
{
try
{
if (stat != null)
stat.close();
}
catch (SQLException e)
{
System.err.println("Could not read history line from database: " + e);
throw new ChoobError("SQL Error reading from database.");
}
finally
{
dbBroker.freeConnection( dbCon );
}
}
}
/**
* Get as the most recent Message from the history of the channel in which cause occurred.
* @param cause The "cause" - only messages that occurred before this are processed
* @return A list of message objects, the first being the most recent.
*/
public Message getLastMessage( Message cause )
{
if (cause instanceof ChannelEvent)
return getLastMessage(((ChannelEvent)cause).getChannel(), cause);
throw new IllegalArgumentException("Message passed to getLastMessage was not a ChannelEvent.");
}
/**
* Get as the most recent Message from the history of channel.
* @param channel The channel to read
* @return A list of message objects, the first being the most recent.
*/
public Message getLastMessage( String channel )
{
return getLastMessage(channel, null);
}
/**
* Get as the most recent Message from the history of channel.
* @param channel The channel to read
* @param cause The "cause" - only messages that occurred before this are processed
* @return A list of message objects, the first being the most recent.
*/
public Message getLastMessage( String channel, Message cause )
{
List<Message> ret = getLastMessages(channel, cause, 1);
if (ret.size() == 1)
return ret.get(0);
else
return null;
}
/**
* Get as many as possible up to count Messages from the history of the channel in which cause occurred.
* @param channel The channel to read
* @param count The maximal number of messages to return.
* @return A list of message objects, the first being the most recent.
*/
public List<Message> getLastMessages( String channel, int count )
{
return getLastMessages(channel, null, count);
}
/**
* Get as many as possible up to count Messages from the history of the channel in which cause occurred.
* @param cause The "cause" - only messages that occurred before this are processed
* @param count The maximal number of messages to return.
* @return A list of message objects, the first being the most recent.
*/
public List<Message> getLastMessages( Message cause, int count )
{
if (cause instanceof ChannelEvent)
return getLastMessages(((ChannelEvent)cause).getChannel(), cause, count);
throw new IllegalArgumentException("Message passed to getLastMessages was not a ChannelEvent.");
}
/**
* Get as many as possible up to count Messages from the history of channel.
* @param channel The channel to read
* @param cause The "cause" - only messages that occurred before this are processed
* @param count The maximal number of messages to return.
* @return A list of message objects, the first being the most recent.
*/
public List<Message> getLastMessages( final String channel, Message cause, int count )
{
Connection dbCon = null;
PreparedStatement stat = null;
try
{
dbCon = dbBroker.getConnection();
stat = dbCon.prepareStatement("SELECT * FROM History WHERE Channel = ? AND Time < ? AND Time > ? - 60*60*12*1000 ORDER BY Time DESC, LineID DESC LIMIT ?");
stat.setString(1, channel);
stat.setLong(2, cause == null ? System.currentTimeMillis() : cause.getMillis() );
stat.setLong(3, cause == null ? System.currentTimeMillis() : cause.getMillis() );
stat.setInt(4, count);
final ResultSet result = stat.executeQuery();
List<Message> results = new ArrayList<Message>(count);
if ( result.first() )
{
do
{
final String type = result.getString(2);
int pos = result.getString(4).indexOf('@');
final String login = result.getString(4).substring(0,pos);
final String host = result.getString(4).substring(pos+1);
Message mes;
try
{
// Need privs to create events...
mes = AccessController.doPrivileged( new PrivilegedExceptionAction<Message>() {
public Message run() throws SQLException {
if (type.equals(ChannelAction.class.getName()))
return new ChannelAction("onAction", result.getLong(7), result.getInt(8), result.getString(6), result.getString(3), login, host, channel, channel);
else if (type.equals(ChannelMessage.class.getName()))
return new ChannelMessage("onMessage", result.getLong(7), result.getInt(8), result.getString(6), result.getString(3), login, host, channel, channel);
return null;
}
});
}
catch (PrivilegedActionException e)
{
throw (SQLException)e.getCause();
// Is an SQL exception...
}
if (mes == null)
{
System.err.println("Invalid event type: " + type);
continue;
}
}//*/
|
package org.osiam.security.helper;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.osiam.auth.login.internal.InternalAuthentication;
import org.osiam.auth.login.ldap.OsiamLdapAuthentication;
import org.osiam.resources.scim.User;
import org.springframework.context.ApplicationListener;
import org.springframework.security.authentication.AuthenticationServiceException;
import org.springframework.security.authentication.LockedException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.authentication.event.AbstractAuthenticationEvent;
import org.springframework.security.authentication.event.AuthenticationFailureBadCredentialsEvent;
import org.springframework.security.authentication.event.AuthenticationSuccessEvent;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter;
import com.google.common.base.Strings;
public class LoginDecisionFilter extends AbstractAuthenticationProcessingFilter implements
ApplicationListener<AbstractAuthenticationEvent> {
private static final int MAX_LOGIN_FAILED = 3;
private boolean postOnly = true;
private final Map<String, Integer> accessCounter = Collections.synchronizedMap(new HashMap<String, Integer>());
public LoginDecisionFilter() {
super("/login/check");
}
@Override
public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) {
if (postOnly && !request.getMethod().equals("POST")) {
throw new AuthenticationServiceException("Authentication method not supported: " + request.getMethod());
}
UsernamePasswordAuthenticationToken authRequest = null;
String username = request.getParameter(getUsernameParameter());
String password = request.getParameter(getPasswordParameter());
if (username == null) {
username = "";
}
if (password == null) {
password = "";
}
username = username.trim();
checkUserLocking(username);
String provider = request.getParameter("provider");
if (!Strings.isNullOrEmpty(provider) && provider.equals("ldap")) {
authRequest = new OsiamLdapAuthentication(username, password);
} else {
authRequest = new InternalAuthentication(username, password, new ArrayList<GrantedAuthority>());
}
setDetails(request, authRequest);
return this.getAuthenticationManager().authenticate(authRequest);
}
private void checkUserLocking(String username) {
if (accessCounter.get(username) != null && accessCounter.get(username) >= MAX_LOGIN_FAILED) {
throw new LockedException("The user '" + username + "' is temporary locked.");
}
}
/**
* Provided so that subclasses may configure what is put into the authentication request's details property.
*
* @param request
* that an authentication request is being created for
* @param authRequest
* the authentication request object that should have its details set
*/
protected void setDetails(HttpServletRequest request, UsernamePasswordAuthenticationToken authRequest) {
authRequest.setDetails(authenticationDetailsSource.buildDetails(request));
}
/**
* Defines whether only HTTP POST requests will be allowed by this filter. If set to true, and an authentication
* request is received which is not a POST request, an exception will be raised immediately and authentication will
* not be attempted. The <tt>unsuccessfulAuthentication()</tt> method will be called as if handling a failed
* authentication.
* <p>
* Defaults to <tt>true</tt> but may be overridden by subclasses.
*/
public void setPostOnly(boolean postOnly) {
this.postOnly = postOnly;
}
public final String getUsernameParameter() {
return "username";
}
public final String getPasswordParameter() {
return "password";
}
@Override
public void onApplicationEvent(AbstractAuthenticationEvent appEvent) {
String currentUserName = extractUserName(appEvent);
if (currentUserName == null) {
return;
}
if (appEvent instanceof AuthenticationSuccessEvent) {
if (accessCounter.containsKey(currentUserName)) {
if (accessCounter.get(currentUserName) < MAX_LOGIN_FAILED) {
accessCounter.remove(currentUserName);
}
}
}
if (appEvent instanceof AuthenticationFailureBadCredentialsEvent) {
if (accessCounter.containsKey(currentUserName)) {
accessCounter.put(currentUserName, accessCounter.get(currentUserName) + 1);
} else {
accessCounter.put(currentUserName, 1);
}
}
}
private String extractUserName(AbstractAuthenticationEvent appEvent) {
if (appEvent.getSource() != null && appEvent.getSource() instanceof InternalAuthentication) {
InternalAuthentication internalAuth = (InternalAuthentication) appEvent.getSource();
if (internalAuth.getPrincipal() != null) {
if (internalAuth.getPrincipal() instanceof User) {
User user = (User) internalAuth.getPrincipal();
return user.getUserName();
}
if (internalAuth.getPrincipal() instanceof String) {
return (String) internalAuth.getPrincipal();
}
}
}
return null;
}
}
|
package org.sugarj.cleardep.build;
import java.io.File;
import java.io.IOException;
import java.io.Serializable;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.eclipse.core.runtime.FileLocator;
import org.sugarj.cleardep.BuildUnit;
import org.sugarj.cleardep.BuildUnit.InconsistenyReason;
import org.sugarj.cleardep.BuildUnit.State;
import org.sugarj.cleardep.build.BuildCycle.Result.UnitResultTuple;
import org.sugarj.cleardep.build.BuildCycleException.CycleState;
import org.sugarj.cleardep.dependency.BuildOutputRequirement;
import org.sugarj.cleardep.dependency.BuildRequirement;
import org.sugarj.cleardep.dependency.DuplicateBuildUnitPathException;
import org.sugarj.cleardep.dependency.DuplicateFileGenerationException;
import org.sugarj.cleardep.dependency.FileRequirement;
import org.sugarj.cleardep.dependency.Requirement;
import org.sugarj.cleardep.stamp.LastModifiedStamper;
import org.sugarj.cleardep.stamp.Stamp;
import org.sugarj.cleardep.xattr.Xattr;
import org.sugarj.common.FileCommands;
import org.sugarj.common.Log;
import org.sugarj.common.path.AbsolutePath;
import org.sugarj.common.path.Path;
import com.cedarsoftware.util.DeepEquals;
public class BuildManager extends BuildUnitProvider {
private final static Map<Thread, BuildManager> activeManagers = new HashMap<>();
public static <Out extends Serializable> Out build(BuildRequest<?, Out, ?, ?> buildReq) {
return build(buildReq, null);
}
public static <Out extends Serializable> Out build(BuildRequest<?, Out, ?, ?> buildReq, Map<? extends Path, Stamp> editedSourceFiles) {
Thread current = Thread.currentThread();
BuildManager manager = activeManagers.get(current);
boolean freshManager = manager == null;
if (freshManager) {
manager = new BuildManager(editedSourceFiles);
activeManagers.put(current, manager);
}
try {
return manager.requireInitially(buildReq).getBuildResult();
} catch (IOException e) {
e.printStackTrace();
return null;
} finally {
if (freshManager)
activeManagers.remove(current);
}
}
public static <Out extends Serializable> List<Out> buildAll(BuildRequest<?, Out, ?, ?>[] buildReqs) {
return buildAll(buildReqs, null);
}
public static <Out extends Serializable> List<Out> buildAll(BuildRequest<?, Out, ?, ?>[] buildReqs, Map<? extends Path, Stamp> editedSourceFiles) {
Thread current = Thread.currentThread();
BuildManager manager = activeManagers.get(current);
boolean freshManager = manager == null;
if (freshManager) {
manager = new BuildManager(editedSourceFiles);
activeManagers.put(current, manager);
}
try {
List<Out> out = new ArrayList<>();
for (BuildRequest<?, Out, ?, ?> buildReq : buildReqs)
if (buildReq != null)
try {
out.add(manager.requireInitially(buildReq).getBuildResult());
} catch (IOException e) {
e.printStackTrace();
out.add(null);
}
return out;
} finally {
if (freshManager)
activeManagers.remove(current);
}
}
private final Map<? extends Path, Stamp> editedSourceFiles;
private ExecutingStack executingStack;
private transient RequireStack requireStack;
private transient Map<Path, BuildUnit<?>> generatedFiles;
protected BuildManager(Map<? extends Path, Stamp> editedSourceFiles) {
this.editedSourceFiles = editedSourceFiles;
this.executingStack = new ExecutingStack();
// this.consistencyManager = new ConsistencyManager();
this.generatedFiles = new HashMap<Path, BuildUnit<?>>();
this.requireStack = new RequireStack();
}
// @formatter:off
private
<In extends Serializable,
Out extends Serializable>
// @formatter:on
void setUpMetaDependency(Builder<In, Out> builder, BuildUnit<Out> depResult) throws IOException {
if (depResult != null) {
// require the meta builder...
String className = builder.getClass().getName();
URL res = builder.getClass().getResource(className.substring(className.lastIndexOf(".")+1) + ".class");
URL resFile = FileLocator.resolve(res);
Path builderClass = new AbsolutePath(resFile.getFile());
Path depFile = Xattr.getDefault().getGenBy(builderClass);
if (!FileCommands.exists(depFile)) {
Log.log.logErr("Warning: Builder was not built using meta builder. Consistency for builder changes are not tracked...", Log.DETAIL);
} else {
BuildUnit<Serializable> metaBuilder = BuildUnit.read(depFile);
depResult.requires(metaBuilder);
depResult.requires(builderClass, LastModifiedStamper.instance.stampOf(builderClass));
// TODO: needed?
//for (Path p : metaBuilder.getExternalFileDependencies()) {
// depResult.requires(p, LastModifiedStamper.instance.stampOf(p));
}
}
}
// @formatter:off
protected
<In extends Serializable,
Out extends Serializable,
B extends Builder<In, Out>,
F extends BuilderFactory<In, Out, B>>
// @formatter:on
BuildUnit<Out> executeBuilder(Builder<In, Out> builder, Path dep, BuildRequest<In, Out, B, F> buildReq) throws IOException {
this.requireStack.beginRebuild(dep);
resetGenBy(dep, BuildUnit.read(dep));
BuildUnit<Out> depResult = BuildUnit.create(dep, buildReq);
// First step: cycle detection
BuildStackEntry<Out> entry = this.executingStack.push(depResult);
int inputHash = DeepEquals.deepHashCode(builder.input);
String taskDescription = builder.description();
if (taskDescription != null)
Log.log.beginTask(taskDescription, Log.CORE);
depResult.setState(BuildUnit.State.IN_PROGESS);
try {
try {
// setUpMetaDependency(builder, depResult);
// call the actual builder
Out out = builder.triggerBuild(depResult, this);
depResult.setBuildResult(out);
if (!depResult.isFinished())
depResult.setState(BuildUnit.State.SUCCESS);
} catch (BuildCycleException e) {
throw this.tryCompileCycle(e);
}
} catch (BuildCycleException e) {
stopBuilderInCycle(builder, dep, buildReq, depResult, e);
} catch (RequiredBuilderFailed e) {
if (taskDescription != null)
Log.log.logErr("Required builder failed", Log.CORE);
throw RequiredBuilderFailed.enqueueBuilder(e, depResult, builder);
} catch (Throwable e) {
depResult.setState(BuildUnit.State.FAILURE);
Log.log.logErr(e.getMessage(), Log.CORE);
throw RequiredBuilderFailed.init(builder, depResult, e);
} finally {
depResult.write();
if (taskDescription != null)
Log.log.endTask();
if (inputHash != DeepEquals.deepHashCode(builder.input))
throw new AssertionError("API Violation detected: Builder mutated its input.");
assertConsistency(depResult);
this.executingStack.pop(entry);
this.requireStack.finishRebuild(dep);
}
if (depResult.getState() == BuildUnit.State.FAILURE)
throw new RequiredBuilderFailed(builder, depResult, new IllegalStateException("Builder failed for unknown reason, please confer log."));
return depResult;
}
@Override
protected Throwable tryCompileCycle(BuildCycleException e) {
// Only try to compile a cycle which is unhandled
if (e.getCycleState() != CycleState.UNHANDLED) {
return e;
}
Log.log.log("Detected a dependency cycle with root " + e.getCycleComponents().get(0).unit.getPersistentPath(), Log.CORE);
e.setCycleState(CycleState.NOT_RESOLVED);
BuildCycle cycle = new BuildCycle(e.getCycleComponents());
CycleSupport cycleSupport = cycle.getCycleSupport();
if (cycleSupport == null) {
return e;
}
Log.log.beginTask("Compile cycle with: " + cycleSupport.getCycleDescription(cycle), Log.CORE);
try {
BuildCycle.Result result = cycleSupport.compileCycle(this, cycle);
e.setCycleResult(result);
e.setCycleState(CycleState.RESOLVED);
} catch (BuildCycleException cyclicEx) {
// Now cycle in cycle detected, use result from it
// But keep throw away the new exception but use
// the existing ones to kill all builders of this
// cycle
e.setCycleState(cyclicEx.getCycleState());
e.setCycleResult(cyclicEx.getCycleResult());
} catch (Throwable t) {
Log.log.endTask("Cyclic compilation failed: " + t.getMessage());
return t;
}
Log.log.endTask();
return e;
}
// @formatter:off
private
<In extends Serializable,
Out extends Serializable,
B extends Builder<In, Out>,
F extends BuilderFactory<In, Out, B>>
//@formatter:on
void stopBuilderInCycle(Builder<In, Out> builder, Path dep, BuildRequest<In, Out, B, F> buildReq, BuildUnit<Out> depResult, BuildCycleException e) {
// This is the exception which has been rethrown above, but we cannot
// handle it
// here because compiling the cycle needs to be in the major try block
// where normal
// units are compiled too
// Set the result to the unit
if (e.getCycleState() == CycleState.RESOLVED) {
if (e.getCycleResult() == null) {
Log.log.log("Error: Cyclic builder does not provide a cycleResult " + e.hashCode(), Log.CORE);
throw new AssertionError("Cyclic builder does not provide a cycleResult");
}
UnitResultTuple<Out> tuple = e.getCycleResult().getUnitResult(depResult);
if (tuple == null) {
throw new AssertionError("Cyclic builder does not provide a result for " + depResult.getPersistentPath());
}
tuple.setOutputToUnit();
} else {
depResult.setState(State.FAILURE);
}
Log.log.log("Stopped because of cycle", Log.CORE);
if (e.isUnitFirstInvokedOn(dep, buildReq.factory)) {
if (e.getCycleState() != CycleState.RESOLVED) {
Log.log.log("Unable to find builder which can compile the cycle", Log.CORE);
// Cycle cannot be handled
throw new RequiredBuilderFailed(builder, depResult, e);
} else {
if (this.executingStack.getNumContains(e.getCycleComponents().get(0).unit) == 1) {
Log.log.log("but cycle has been compiled", Log.CORE);
} else {
throw e;
}
}
} else {
// Kill depending builders
throw e;
}
}
//@formatter:off
protected
<In extends Serializable,
Out extends Serializable,
B extends Builder<In, Out>,
F extends BuilderFactory<In, Out, B>>
//@formatter:on
BuildUnit<Out> requireInitially(BuildRequest<In, Out, B, F> buildReq) throws IOException {
Log.log.beginTask("Incrementally rebuild inconsistent units", Log.CORE);
try {
return require(null, buildReq);
} finally {
Log.log.endTask();
}
}
@Override
//@formatter:off
public
<In extends Serializable,
Out extends Serializable,
B extends Builder<In, Out>,
F extends BuilderFactory<In, Out, B>>
//@formatter:on
BuildUnit<Out> require(BuildUnit<?> source, BuildRequest<In, Out, B, F> buildReq) throws IOException {
Builder<In, Out> builder = buildReq.createBuilder();
Path dep = builder.persistentPath();
BuildUnit<Out> depResult = BuildUnit.read(dep);
boolean localInconsistent =
(requireStack.isKnownInconsistent(dep)) ||
(depResult == null) ||
(!depResult.getGeneratedBy().deepEquals(buildReq)) ||
(!depResult.isConsistentNonrequirements());
if (localInconsistent) {
return executeBuilder(builder, dep, buildReq);
}
if (requireStack.isConsistent(dep))
return depResult;
// Dont execute require because it is cyclic, requireStack keeps track of
// this
if (source != null && requireStack.isAlreadyRequired(source.getPersistentPath(), dep)) {
return depResult;
}
requireStack.beginRequire(dep);
try {
for (Requirement req : depResult.getRequirements()) {
if (!req.isConsistentInBuild(depResult, this)) {
return executeBuilder(builder, dep, buildReq);
} else {
// Could get consistent because it was part of a cycle which is
// compiled now
// TODO better remove that for security purpose?
if (requireStack.isConsistent(dep))
return depResult;
}
}
requireStack.markConsistent(dep);
} finally {
if (source != null)
requireStack.finishRequire(source.getPersistentPath(), dep);
else
requireStack.finishRequire(null, dep);
}
return depResult;
}
private <Out extends Serializable> BuildUnit<Out> assertConsistency(BuildUnit<Out> depResult) {
BuildUnit<?> other = generatedFiles.put(depResult.getPersistentPath(), depResult);
if (other != null && other != depResult)
throw new DuplicateBuildUnitPathException("Build unit " + depResult + " has same persistent path as build unit " + other);
for (FileRequirement freq : depResult.getGeneratedFileRequirements()) {
other = generatedFiles.put(freq.path, depResult);
if (other != null && other != depResult)
throw new DuplicateFileGenerationException("Build unit " + depResult + " generates same file as build unit " + other);
}
InconsistenyReason reason = depResult.isConsistentShallowReason(null);
if (reason != InconsistenyReason.NO_REASON)
throw new AssertionError("Build manager does not guarantee soundness " + reason + " for " + FileCommands.tryGetRelativePath(depResult.getPersistentPath()));
return depResult;
}
private void resetGenBy(Path dep, BuildUnit<?> depResult) throws IOException {
if (depResult != null)
for (Path p : depResult.getGeneratedFiles())
BuildUnit.xattr.removeGenBy(p);
}
}
|
package org.osiam.storage.query;
import java.io.ObjectInputStream.GetField;
import java.util.Locale;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import org.osiam.resources.exceptions.OsiamException;
import org.osiam.storage.dao.ExtensionDao;
import org.osiam.storage.entities.ExtensionEntity;
import org.osiam.storage.entities.ExtensionFieldEntity;
import org.osiam.storage.entities.UserEntity;
import org.osiam.storage.helper.NumberPadder;
public class UserSimpleFilterChain implements FilterChain<UserEntity> {
private final ScimExpression scimExpression;
private final QueryField<UserEntity> userFilterField;
private ExtensionQueryField extensionFilterField;
private final ExtensionDao extensionDao;
private final CriteriaBuilder criteriaBuilder;
private final NumberPadder numberPadder;
public UserSimpleFilterChain(CriteriaBuilder criteriaBuilder, ExtensionDao extensionDao,
ScimExpression scimExpression,
NumberPadder numberPadder) {
this.criteriaBuilder = criteriaBuilder;
this.extensionDao = extensionDao;
this.numberPadder = numberPadder;
this.scimExpression = scimExpression;
String field = scimExpression.getField();
userFilterField = UserQueryField.fromString(field.toLowerCase(Locale.ENGLISH));
// It's not a known user field, so try to build a extension filter
if (userFilterField == null) {
extensionFilterField = getExtensionFilterField(field.toLowerCase(Locale.ENGLISH));
if(extensionFilterField == null) {
throw new IllegalArgumentException("Filtering not possible: '" + field + "' not available");
}
}
}
private ExtensionQueryField getExtensionFilterField(String fieldString) {
int lastIndexOf = fieldString.lastIndexOf('.');
if (lastIndexOf == -1) {
return null;
}
String urn = fieldString.substring(0, lastIndexOf);
String fieldName = fieldString.substring(lastIndexOf + 1);
final ExtensionEntity extension;
try {
extension = extensionDao.getExtensionByUrn(urn, true);
} catch (OsiamException ex) {
return null;
}
final ExtensionFieldEntity fieldEntity = extension.getFieldForName(fieldName, true);
return new ExtensionQueryField(urn, fieldEntity, numberPadder);
}
@Override
public Predicate createPredicateAndJoin(Root<UserEntity> root) {
if (userFilterField != null) {
return userFilterField.addFilter(root, scimExpression.getConstraint(), scimExpression.getValue(),
criteriaBuilder);
} else if (extensionFilterField != null) {
return extensionFilterField.addFilter(root, scimExpression.getConstraint(), scimExpression.getValue(),
criteriaBuilder);
} else {
throw new IllegalArgumentException("Filtering not possible. Field '" + scimExpression.getField()
+ "' not available.");
}
}
}
|
package pablosaraiva.gotobed;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class SimpleBedProvider extends BedProvider {
static {
try {
Class.forName("org.hsqldb.jdbc.JDBCDriver");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
@Override
public Connection getConnection() throws SQLException {
return DriverManager.getConnection("jdbc:hsqldb:mem:mymemdb", "SA", "");
}
}
|
package org.secureauth.sarestapi.resources;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.security.SecureRandom;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import javax.ws.rs.client.Entity;
import javax.ws.rs.core.MediaType;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.secureauth.sarestapi.data.*;
import org.secureauth.sarestapi.util.JSONUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
//Jersey 2 Libs
import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.WebTarget;
import org.glassfish.jersey.client.ClientConfig;
import javax.ws.rs.core.Response;
import javax.xml.bind.JAXBContext;
public class SAExecuter {
private ClientConfig config = null;
private Client client=null;
private static Logger logger=LoggerFactory.getLogger(SAExecuter.class);
//Set up our Connection
private void createConnection() throws Exception{
config = new ClientConfig();
TrustManager[] certs = new TrustManager[]{
new X509TrustManager(){
@Override
public X509Certificate[] getAcceptedIssuers(){
return null;
}
@Override
public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {}
@Override
public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException{}
}
};
SSLContext ctx = null;
try{
ctx = SSLContext.getInstance("TLS");
ctx.init(null, certs, new SecureRandom());
}catch(java.security.GeneralSecurityException ex){
logger.error(new StringBuilder().append("Exception occurred while attempting to setup SSL security. ").toString(), ex);
}
HttpsURLConnection.setDefaultSSLSocketFactory(ctx.getSocketFactory());
try{
client = ClientBuilder.newBuilder()
.sslContext(ctx)
.hostnameVerifier(
new HostnameVerifier(){
@Override
public boolean verify(String hostname, SSLSession session){return true;}
}
)
.build();
}catch(Exception e){
logger.error(new StringBuilder().append("Exception occurred while attempting to associating our SSL cert to the session.").toString(), e);
}
try{
client = ClientBuilder.newClient(config);
}catch(Exception e){
StringBuilder bud = new StringBuilder();
for(StackTraceElement st: e.getStackTrace()){
bud.append(st.toString()).append("\n");
}
throw new Exception(new StringBuilder().append("Exception occurred while attempting to create connection object. Exception: ")
.append(e.getMessage()).append("\nStackTraceElements:\n").append(bud.toString()).toString());
}
if(client == null) throw new Exception(new StringBuilder().append("Unable to create connection object, creation attempt returned NULL.").toString());
}
//Get Factors for the user requested
public <T> T executeGetRequest(String auth, String query,String ts, Class<T> valueType)throws Exception {
if(client == null) {
createConnection();
}
WebTarget target = null;
Response response = null;
T genericResponse =null;
try{
target = client.target(query);
response = target.request().
accept(MediaType.APPLICATION_JSON).
header("Authorization", auth).
header("X-SA-Date", ts).
get();
genericResponse = response.readEntity(valueType);
}catch(Exception e){
logger.error(new StringBuilder().append("Exception getting User Factors: \nQuery:\n\t")
.append(query).append("\nError:").append(e.getMessage()).append(".\nResponse code is ").append(response.getStatus()).toString(), e);
}
response.close();
return genericResponse;
}
//Validate User against Repository
public ResponseObject executeValidateUser(String header,String query, AuthRequest authRequest,String ts)throws Exception{
if(client == null) {
createConnection();
}
WebTarget target = null;
Response response = null;
ResponseObject responseObject =null;
try{
target = client.target(query);
response = target.request().
accept(MediaType.APPLICATION_JSON).
header("Authorization", header).
header("X-SA-Date", ts).
post(Entity.entity(JSONUtil.getJSONStringFromObject(authRequest),MediaType.APPLICATION_JSON));
responseObject = response.readEntity(ResponseObject.class);
}catch(Exception e){
logger.error(new StringBuilder().append("Exception Validating User: \nQuery:\n\t")
.append(query).append("\nError: \n\t").append((String) response.readEntity(String.class)).append(".\nResponse code is ").append(response.getStatus()).toString(), e);
}
response.close();
return responseObject;
}
//Validate Users Password
public ResponseObject executeValidateUserPassword(String auth,String query, AuthRequest authRequest,String ts)throws Exception{
if(client == null) {
createConnection();
}
WebTarget target = null;
Response response = null;
ResponseObject responseObject =null;
try{
target = client.target(query);
response = target.request().
accept(MediaType.APPLICATION_JSON).
header("Authorization", auth).
header("X-SA-Date", ts).
post(Entity.entity(JSONUtil.getJSONStringFromObject(authRequest), MediaType.APPLICATION_JSON));
responseObject=response.readEntity(ResponseObject.class);
}catch(Exception e){
logger.error(new StringBuilder().append("Exception Validating User Password: \nQuery:\n\t")
.append(query).append("\nError:").append(e.getMessage()).append(".\nResponse code is ").append(response.getStatus()).toString(), e);
}
response.close();
return responseObject;
}
//Validate Users Pin
public ResponseObject executeValidateUserPin(String auth,String query, AuthRequest authRequest,String ts)throws Exception{
if(client == null) {
createConnection();
}
WebTarget target = null;
Response response = null;
ResponseObject responseObject =null;
try{
target = client.target(query);
response = target.request().
accept(MediaType.APPLICATION_JSON).
header("Authorization", auth).
header("X-SA-Date", ts).
post(Entity.entity(JSONUtil.getJSONStringFromObject(authRequest), MediaType.APPLICATION_JSON));
responseObject=response.readEntity(ResponseObject.class);
}catch(Exception e){
logger.error(new StringBuilder().append("Exception Validating User Password: \nQuery:\n\t")
.append(query).append("\nError:").append(e.getMessage()).append(".\nResponse code is ").append(response.getStatus()).toString(), e);
}
response.close();
return responseObject;
}
//Validate Users KBA
public ResponseObject executeValidateKba(String auth,String query, AuthRequest authRequest, String ts)throws Exception{
if(client == null) {
createConnection();
}
WebTarget target = null;
Response response = null;
ResponseObject responseObject =null;
try{
target = client.target(query);
response = target.request().
accept(MediaType.APPLICATION_JSON).
header("Authorization", auth).
header("X-SA-Date", ts).
post(Entity.entity(JSONUtil.getJSONStringFromObject(authRequest), MediaType.APPLICATION_JSON));
responseObject=response.readEntity(ResponseObject.class);
}catch(Exception e){
logger.error(new StringBuilder().append("Exception Validating KBA: \nQuery:\n\t")
.append(query).append("\nError:").append(e.getMessage()).append(".\nResponse code is ").append(response.getStatus()).toString(), e);
}
response.close();
return responseObject;
}
//Validate User Oath Token
public ResponseObject executeValidateOath(String auth,String query, AuthRequest authRequest, String ts)throws Exception{
if(client == null) {
createConnection();
}
WebTarget target = null;
Response response = null;
ResponseObject responseObject =null;
try{
target = client.target(query);
response = target.request()
.accept(MediaType.APPLICATION_JSON).
header("Authorization", auth).
header("X-SA-Date", ts).
post(Entity.entity(JSONUtil.getJSONStringFromObject(authRequest), MediaType.APPLICATION_JSON));
responseObject=response.readEntity(ResponseObject.class);
}catch(Exception e){
logger.error(new StringBuilder().append("Exception Validating OATH: \nQuery:\n\t")
.append(query).append("\nError:").append(e.getMessage()).append(".\nResponse code is ").append(response.getStatus()).toString(), e);
}
response.close();
return responseObject;
}
//Validate OTP By Phone
public ResponseObject executeOTPByPhone(String auth,String query, AuthRequest authRequest, String ts)throws Exception{
if(client == null) {
createConnection();
}
WebTarget target = null;
Response response = null;
ResponseObject responseObject =null;
try{
target = client.target(query);
response = target.request().
accept(MediaType.APPLICATION_JSON).
//type(MediaType.APPLICATION_JSON).
header("Authorization", auth).
header("X-SA-Date", ts).
post(Entity.entity(JSONUtil.getJSONStringFromObject(authRequest), MediaType.APPLICATION_JSON));
responseObject=response.readEntity(ResponseObject.class);
}catch(Exception e){
logger.error(new StringBuilder().append("Exception Delivering OTP by Phone: \nQuery:\n\t")
.append(query).append("\nError:").append(e.getMessage()).append(".\nResponse code is ").append(response.getStatus()).toString(), e);
}
response.close();
return responseObject;
}
//Validate User OATH by SMS
public ResponseObject executeOTPBySMS(String auth,String query, AuthRequest authRequest,String ts)throws Exception{
if(client == null) {
createConnection();
}
WebTarget target = null;
Response response = null;
ResponseObject responseObject =null;
try{
target = client.target(query);
response = target.request()
.accept(MediaType.APPLICATION_JSON).
header("Authorization", auth).
header("X-SA-Date", ts).
post(Entity.entity(JSONUtil.getJSONStringFromObject(authRequest), MediaType.APPLICATION_JSON));
responseObject=response.readEntity(ResponseObject.class);
}catch(Exception e){
logger.error(new StringBuilder().append("Exception Delivering OTP by SMS: \nQuery:\n\t")
.append(query).append("\nError:").append(e.getMessage()).append(".\nResponse code is ").append(response.getStatus()).toString(), e);
}
response.close();
return responseObject;
}
//Validate User OTP by Email
public ResponseObject executeOTPByEmail(String auth,String query, AuthRequest authRequest,String ts)throws Exception{
if(client == null) {
createConnection();
}
WebTarget target = null;
Response response = null;
ResponseObject responseObject =null;
try{
target = client.target(query);
response = target.request().
accept(MediaType.APPLICATION_JSON).
header("Authorization", auth).
header("X-SA-Date", ts).
post(Entity.entity(JSONUtil.getJSONStringFromObject(authRequest), MediaType.APPLICATION_JSON));
responseObject=response.readEntity(ResponseObject.class);
}catch(Exception e){
logger.error(new StringBuilder().append("Exception Delivering OTP by Email: \nQuery:\n\t")
.append(query).append("\nError:").append(e.getMessage()).append(".\nResponse code is ").append(response.getStatus()).toString(), e);
}
response.close();
return responseObject;
}
// post request
public <T> T executePostRequest(String auth,String query, AuthRequest authRequest,String ts, Class<T> valueType)throws Exception{
if(client == null) {
createConnection();
}
WebTarget target = null;
Response response = null;
T responseObject =null;
try{
target = client.target(query);
response = target.request().
accept(MediaType.APPLICATION_JSON).
header("Authorization", auth).
header("X-SA-Date", ts).
post(Entity.entity(JSONUtil.getJSONStringFromObject(authRequest),MediaType.APPLICATION_JSON));
responseObject=response.readEntity(valueType);
}catch(Exception e){
logger.error(new StringBuilder().append("Exception Delivering OTP by Push: \nQuery:\n\t")
.append(query).append("\nError:").append(e.getMessage()).append(".\nResponse code is ").append(response.getStatus()).toString(), e);
}
response.close();
return responseObject;
}
//Validate User Token by Help Desk Call
public ResponseObject executeOTPByHelpDesk(String auth,String query, AuthRequest authRequest, String ts)throws Exception{
if(client == null) {
createConnection();
}
WebTarget target = null;
Response response = null;
ResponseObject responseObject =null;
try{
target = client.target(query);
response = target.request().
accept(MediaType.APPLICATION_JSON).
header("Authorization", auth).
header("X-SA-Date", ts).
post(Entity.entity(JSONUtil.getJSONStringFromObject(authRequest),MediaType.APPLICATION_JSON));
responseObject=response.readEntity(ResponseObject.class);
}catch(Exception e){
logger.error(new StringBuilder().append("Exception Delivering OTP by HelpDesk: \nQuery:\n\t")
.append(query).append("\nError:").append(e.getMessage()).append(".\nResponse code is ").append(response.getStatus()).toString(), e);
}
response.close();
return responseObject;
}
//Run IP Evaluation against user and IP Address
public IPEval executeIPEval(String auth,String query, IPEvalRequest ipEvalRequest, String ts)throws Exception{
if(client == null) {
createConnection();
}
WebTarget target = null;
Response response = null;
String responseStr=null;
IPEval ipEval =null;
try{
target = client.target(query);
response = target.request().
accept(MediaType.APPLICATION_JSON).
header("Authorization", auth).
header("X-SA-Date", ts).
post(Entity.entity(JSONUtil.getJSONStringFromObject(ipEvalRequest), MediaType.APPLICATION_JSON));
ipEval = response.readEntity(IPEval.class);
}catch(Exception e){
logger.error(new StringBuilder().append("Exception Running IP Evaluation: \nQuery:\n\t")
.append(query).append("\nError:").append(e.getMessage()).append(".\nResponse code is ").append(response.getStatus()).toString(), e);
}
response.close();
return ipEval;
}
//Run AccessHistories Post
public ResponseObject executeAccessHistory(String auth, String query, AccessHistoryRequest accessHistoryRequest, String ts)throws Exception{
if(client == null) {
createConnection();
}
WebTarget target = null;
Response response = null;
ResponseObject accessHistory =null;
try{
target = client.target(query);
response = target.request().
accept(MediaType.APPLICATION_JSON).
header("Authorization", auth).
header("X-SA-Date", ts).
post(Entity.entity(JSONUtil.getJSONStringFromObject(accessHistoryRequest),MediaType.APPLICATION_JSON));
accessHistory = response.readEntity(ResponseObject.class);
}catch(Exception e){
logger.error(new StringBuilder().append("Exception Running Access History POST: \nQuery:\n\t")
.append(query).append("\nError:").append(e.getMessage()).append(".\nResponse code is ").append(response.getStatus()).toString(), e);
}
response.close();
return accessHistory;
}
// Run DFP Validate
public DFPValidateResponse executeDFPValidate(String auth, String query, DFPValidateRequest dfpValidateRequest, String ts)throws Exception{
if(client == null) {
createConnection();
}
WebTarget target = null;
Response response = null;
DFPValidateResponse dfpValidateResponse =null;
try{
target = client.target(query);
response = target.request().
accept(MediaType.APPLICATION_JSON).
header("Authorization", auth).
header("X-SA-Date", ts).
post(Entity.entity(JSONUtil.getJSONStringFromObject(dfpValidateRequest),MediaType.APPLICATION_JSON));
dfpValidateResponse = response.readEntity(DFPValidateResponse.class);
}catch(Exception e){
logger.error(new StringBuilder().append("Exception Running Access History POST: \nQuery:\n\t")
.append(query).append("\nError:").append(e.getMessage()).append(".\nResponse code is ").append(response.getStatus()).toString(), e);
}
response.close();
return dfpValidateResponse;
}
// Run DFP Confirm
public DFPConfirmResponse executeDFPConfirm(String auth, String query, DFPConfirmRequest dfpConfirmRequest, String ts)throws Exception{
if(client == null) {
createConnection();
}
WebTarget target = null;
Response response = null;
String responseStr = null;
DFPConfirmResponse dfpConfirmResponse =null;
try{
target = client.target(query);
response = target.request().
accept(MediaType.APPLICATION_JSON).
header("Authorization", auth).
header("X-SA-Date", ts).
post(Entity.entity(JSONUtil.getJSONStringFromObject(dfpConfirmRequest),MediaType.APPLICATION_JSON));
dfpConfirmResponse = response.readEntity(DFPConfirmResponse.class);
}catch(Exception e){
logger.error(new StringBuilder().append("Exception Running DFP Confirm POST: \nQuery:\n\t")
.append(query).append("\nError:").append(e.getMessage()).append(".\nResponse code is ").append(response.getStatus()).toString(), e);
}
response.close();
return dfpConfirmResponse;
}
//Get Factors for the user requested
public <T> T executeGetJSObject(String auth, String query,String ts, Class<T> valueType)throws Exception {
if(client == null) {
createConnection();
}
WebTarget target = null;
Response response = null;
T jsObjectResponse =null;
try{
target = client.target(query);
response = target.request().
accept(MediaType.APPLICATION_JSON).
header("Authorization", auth).
header("X-SA-Date", ts).
get();
jsObjectResponse= response.readEntity(valueType);
}catch(Exception e){
logger.error(new StringBuilder().append("Exception getting JS Object SRC: \nQuery:\n\t")
.append(query).append("\nError:").append(e.getMessage()).append(".\nResponse code is ").append(response.getStatus()).toString(), e);
}
response.close();
return jsObjectResponse;
}
}
|
package org.spongepowered.api.entity.hanging.art;
/**
* A utility class for getting available {@link Art} pieces.
*/
public class Arts {
public static final Art KEBAB = null;
public static final Art AZTEC = null;
public static final Art ALBAN = null;
public static final Art AZTEC_2 = null;
public static final Art BOMB = null;
public static final Art PLANT = null;
public static final Art WASTELAND = null;
public static final Art WANDERER = null;
public static final Art GRAHAM = null;
public static final Art POOL = null;
public static final Art COURBET = null;
public static final Art SUNSET = null;
public static final Art SEA = null;
public static final Art CREEBET = null;
public static final Art MATCH = null;
public static final Art BUST = null;
public static final Art STAGE = null;
public static final Art VOID = null;
public static final Art SKULL_AND_ROSES = null;
public static final Art WITHER = null;
public static final Art FIGHTERS = null;
public static final Art SKELETON = null;
public static final Art DONKEY_KONG = null;
public static final Art POINTER = null;
public static final Art PIGSCENE = null;
public static final Art BURNING_SKULL = null;
private Arts() {
}
/**
* Checks if this is a flowerpot.
*
* @return Whether this is a flowerpot
*/
public static boolean isFlowerPot() {
return false;
}
}
|
package org.sports.websearch.contoller;
import org.sports.websearch.model.Article;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
@RequestMapping("/solr")
public class SolrController {
@RequestMapping(value = "/{query}", method = RequestMethod.GET)
public @ResponseBody ResponseEntity<Article> search(
@RequestParam(value = "query", required = true) String query) {
System.out.println(query);
return null;
}
}
|
package org.telegram.telegrambots.api.objects;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.jsontype.TypeSerializer;
import org.json.JSONObject;
import org.telegram.telegrambots.api.interfaces.IBotApiObject;
import java.io.IOException;
/**
* @author Ruben Bermudez
* @version 1.0
* @brief This object represents a sticker.
* @date 20 of June of 2015
*/
public class Sticker implements IBotApiObject {
private static final String FILEID_FIELD = "file_id";
private static final String WIDTH_FIELD = "width";
private static final String HEIGHT_FIELD = "height";
private static final String THUMB_FIELD = "thumb";
private static final String FILESIZE_FIELD = "file_size";
@JsonProperty(FILEID_FIELD)
private String fileId; ///< Unique identifier for this file
@JsonProperty(WIDTH_FIELD)
private Integer width; ///< Sticker width
@JsonProperty(HEIGHT_FIELD)
private Integer height; ///< Sticker height
@JsonProperty(THUMB_FIELD)
private PhotoSize thumb; ///< Optional. Sticker thumbnail in .webp or .jpg format
@JsonProperty(FILESIZE_FIELD)
private Integer fileSize; ///< Optional. File size
public Sticker() {
super();
}
public Sticker(JSONObject jsonObject) {
super();
this.fileId = jsonObject.getString(FILEID_FIELD);
this.width = jsonObject.getInt(WIDTH_FIELD);
this.height = jsonObject.getInt(HEIGHT_FIELD);
if (jsonObject.has(THUMB_FIELD)) {
this.thumb = new PhotoSize(jsonObject.getJSONObject(THUMB_FIELD));
}
if (jsonObject.has(FILESIZE_FIELD)) {
this.fileSize = jsonObject.getInt(FILESIZE_FIELD);
}
}
public String getFileId() {
return fileId;
}
public Integer getWidth() {
return width;
}
public Integer getHeight() {
return height;
}
public PhotoSize getThumb() {
return thumb;
}
public Integer getFileSize() {
return fileSize;
}
@Override
public void serialize(JsonGenerator gen, SerializerProvider serializers) throws IOException {
gen.writeStartObject();
gen.writeStringField(FILEID_FIELD, fileId);
gen.writeNumberField(WIDTH_FIELD, width);
gen.writeNumberField(HEIGHT_FIELD, height);
if (thumb != null) {
gen.writeObjectField(THUMB_FIELD, thumb);
}
if (fileSize != null) {
gen.writeNumberField(FILESIZE_FIELD, fileSize);
}
gen.writeEndObject();
gen.flush();
}
@Override
public void serializeWithType(JsonGenerator gen, SerializerProvider serializers, TypeSerializer typeSer) throws IOException {
serialize(gen, serializers);
}
@Override
public String toString() {
return "Sticker{" +
"fileId='" + fileId + '\'' +
", width=" + width +
", height=" + height +
", thumb=" + thumb +
", fileSize=" + fileSize +
'}';
}
}
|
package org.tournier.minecraftregionmanager;
import java.io.File;
public class ChunkMark
{
// A chunk mark is defined by 4 items:
private String worldName;
private int x, z;
private String chunkName;
// Constructor
public ChunkMark(String world, int cx, int cz, String name)
{
worldName = world;
x = cx;
z = cz;
chunkName = name;
}
public String getWorldName()
{
return worldName;
}
public int getX()
{
return x;
}
public int getZ()
{
return z;
}
public String getChunkName()
{
return chunkName;
}
public File getFileName()
{
int rx = (int) Math.floor((double) x / 32);
int rz = (int) Math.floor((double) z / 32);
File f = new File("./" + worldName + "/r." + rx + "." + rz + ".mca");
return f;
}
public String printMark()
{
String s = worldName + ":" + x + "," + z + ":" + chunkName + " (blocks " + (x*16) + "," + (z*16) + " to " + ((x*16)+15) + "," + ((z*16)+15) + ")";
return s;
}
}
|
package org.vaadin.hackathonofthings.io;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;
import org.vaadin.hackathonofthings.data.DataEvent;
import org.vaadin.hackathonofthings.data.DataSink;
import org.vaadin.hackathonofthings.data.Topic;
/**
* Data store saving incoming (sinked) events to the disk and retrieving them
* later for playback. Data retrieval is done based on the topic.
*/
public class FileDataStore extends AbstractFileDataSource implements DataSink {
private Topic topic;
private Writer writer;
public FileDataStore(Topic topic) {
super(topic);
this.topic = topic;
}
public void replay() throws IOException {
readFile(getFileName());
}
protected String getFileName() {
return topic.getId().replaceAll("[^a-zA-Z0-9_-]", "_");
}
public void consumeData(DataEvent event) {
if (event.getSender() == this) {
return;
}
try {
if (writer == null) {
writer = new FileWriter(getFileName());
}
// store an event
StringBuilder line = new StringBuilder();
line.append(event.getTimestamp()).append(";");
for (int i = 0; i < event.getData().length; ++i) {
line.append(event.getData()[i]);
if (i < event.getData().length - 1) {
line.append(";");
} else {
line.append("\n");
}
}
writer.write(line.toString());
writer.flush();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
@Override
protected DataEvent convertLine(String line) {
// convert read data back
String[] parts = line.split(";");
if (parts.length > 1) {
double[] data = new double[parts.length - 1];
long timestamp = Long.parseLong(parts[0]);
for (int i = 0; i < parts.length - 2; ++i) {
data[i] = Double.parseDouble(parts[i + 1]);
}
return new DataEvent(this, topic, timestamp, data);
}
return null;
}
public void close() throws IOException {
if (writer != null) {
writer.close();
}
}
}
|
package pixlepix.auracascade.gui;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.entity.player.InventoryPlayer;
import net.minecraft.inventory.Container;
import net.minecraft.inventory.InventoryBasic;
import net.minecraft.inventory.Slot;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import pixlepix.auracascade.block.tile.TileBookshelfCoordinator;
import pixlepix.auracascade.block.tile.TileStorageBookshelf;
import pixlepix.auracascade.data.StorageItemStack;
import java.util.ArrayList;
import java.util.Iterator;
public class ContainerCoordinator extends Container {
public float lastScroll;
protected TileBookshelfCoordinator tileEntity;
public ContainerCoordinator(InventoryPlayer inventoryPlayer, TileBookshelfCoordinator te) {
tileEntity = te;
for (int i = 0; i < 21; i++) {
int x = i % 7;
int y = i / 7;
addSlotToContainer(new SlotCoordinator(i, 8 + x * 20, 17 + y * 18, te, null));
}
bindPlayerInventory(inventoryPlayer);
scrollTo(0);
}
@Override
public boolean canInteractWith(EntityPlayer player) {
return tileEntity.isUseableByPlayer(player);
}
protected void bindPlayerInventory(InventoryPlayer inventoryPlayer) {
int ys = 84;
int xs = 8;
for (int x = 0; x < 3; ++x) {
for (int y = 0; y < 9; ++y) {
addSlotToContainer(new Slot(inventoryPlayer, y + x * 9 + 9, xs + y * 18, ys + x * 18));
}
}
for (int x = 0; x < 9; ++x) {
addSlotToContainer(new Slot(inventoryPlayer, x, xs + x * 18, ys + 58));
}
}
@Override
public ItemStack transferStackInSlot(EntityPlayer player, int slot) {
ItemStack stack = null;
Slot slotObject = (Slot) inventorySlots.get(slot);
//null checks and checks if the item can be stacked (maxStackSize > 1)
if (slotObject != null && slotObject.getHasStack()) {
stack = slotObject.getStack();
ItemStack stackLeftover;
//merges the item into player inventory since its in the tileEntity
if (slot < 21) {
StorageItemStack storageItemStack = ((SlotCoordinator) inventorySlots.get(slot)).storage;
storageItemStack.stackSize = 64;
stackLeftover = takeFromInventory(storageItemStack);
if (stackLeftover != null) {
this.mergeItemStack(stackLeftover, 21, 21 + 36, true);
}
update();
slotObject.onSlotChange(stack, slotObject.getStack());
return null;
}
//places it into the tileEntity is possible since its in the player inventory
else {
ItemStack stackToTransfer = slotObject.getStack();
stackLeftover = putIntoInventory(new StorageItemStack(stackToTransfer));
if (stackLeftover != null && stackLeftover.stackSize == stackToTransfer.stackSize) {
return null;
}
slotObject.putStack(stackLeftover);
slotObject.onSlotChange(stack, stackLeftover);
}
}
update();
return stack;
}
public void update() {
scrollTo(lastScroll);
}
public void scrollTo(float scroll) {
this.lastScroll = scroll;
ArrayList<StorageItemStack> stacks = tileEntity.getAbstractInventory();
int i = stacks.size() / 7 - 2;
int j = (int) ((double) (scroll * (float) i) + 0.5D);
if (j < 0) {
j = 0;
}
for (int k = 0; k < 3; ++k) {
for (int l = 0; l < 7; ++l) {
int i1 = l + (k + j) * 7;
if (i1 >= 0 && i1 < stacks.size()) {
((SlotCoordinator) this.getSlot(l + k * 7)).storage = stacks.get(i1);
} else {
((SlotCoordinator) this.getSlot(l + k * 7)).storage = null;
}
}
}
}
public ItemStack takeFromInventory(StorageItemStack lost) {
int amount = 0;
outer:
for (TileStorageBookshelf bookshelf : tileEntity.getBookshelves()) {
for (int i = 0; i < bookshelf.getSizeInventory(); i++) {
ItemStack stackInShelf = bookshelf.getStackInSlot(i);
if (stackInShelf != null && new StorageItemStack(stackInShelf).equalsType(lost)) {
int delta = Math.min(lost.stackSize - amount, stackInShelf.stackSize);
amount += delta;
stackInShelf.stackSize -= delta;
if (stackInShelf.stackSize == 0) {
bookshelf.setInventorySlotContents(i, null);
}
bookshelf.markDirty();
if (lost.stackSize <= 0) {
break outer;
}
}
}
}
lost.stackSize = amount;
return lost.stackSize != 0 ? lost.toItemStack() : null;
}
public ItemStack putIntoInventory(StorageItemStack gained) {
int amount = gained.stackSize;
if (amount != 0) {
outer:
for (TileStorageBookshelf bookshelf : tileEntity.getBookshelves()) {
for (int i = 0; i < bookshelf.getSizeInventory(); i++) {
ItemStack stackInShelf = bookshelf.getStackInSlot(i);
ItemStack testStack = null;
if (stackInShelf != null && new StorageItemStack(stackInShelf).equalsType(gained)) {
testStack = stackInShelf.copy();
}
if (stackInShelf == null) {
testStack = gained.toItemStack();
testStack.stackSize = 0;
}
if (testStack != null) {
ItemStack nextTestStack = testStack.copy();
nextTestStack.stackSize++;
while (amount > 0 && bookshelf.isItemValidForSlotSensitive(i, nextTestStack) && nextTestStack.stackSize < testStack.getMaxStackSize()) {
testStack = nextTestStack.copy();
nextTestStack.stackSize++;
amount
}
if (testStack.stackSize > 0) {
bookshelf.setInventorySlotContents(i, testStack);
}
if (gained.stackSize <= 0) {
break outer;
}
}
}
}
}
StorageItemStack result = gained.copy();
result.stackSize = amount;
return result.toItemStack();
}
@Override
public ItemStack slotClick(int slot, int clickedButton, int mode, EntityPlayer player) {
ItemStack itemstack = null;
if (player.inventory.getItemStack() != null && slot == -999 && (clickedButton == 0 || clickedButton == 1) && (mode == 0 || mode == 1)) {
if (clickedButton == 0) {
player.dropPlayerItemWithRandomChoice(player.inventory.getItemStack(), true);
player.inventory.setItemStack((ItemStack) null);
}
if (clickedButton == 1) {
player.dropPlayerItemWithRandomChoice(player.inventory.getItemStack().splitStack(1), true);
if (player.inventory.getItemStack().stackSize == 0) {
player.inventory.setItemStack((ItemStack) null);
}
}
} else if (slot >= 0 && inventorySlots.get(slot) instanceof SlotCoordinator && mode != 1) {
if ((clickedButton == 0 || clickedButton == 1) && mode == 0) {
StorageItemStack target = ((SlotCoordinator) inventorySlots.get(slot)).storage;
if (target != null && player.inventory.getItemStack() == null) {
target = target.copy();
target.stackSize = clickedButton == 0 ? 64 : 32;
ItemStack result = takeFromInventory(target);
player.inventory.setItemStack(result);
((SlotCoordinator) inventorySlots.get(slot)).onPickupFromSlot(player, result);
update();
} else if (player.inventory.getItemStack() != null) {
ItemStack placedStack = player.inventory.getItemStack().copy();
int reservedItems = 0;
if (clickedButton == 1) {
reservedItems = placedStack.stackSize - 1;
placedStack.stackSize = 1;
}
ItemStack leftovers = putIntoInventory(new StorageItemStack(placedStack));
if (leftovers != null) {
leftovers.stackSize += reservedItems;
} else if (reservedItems > 0) {
leftovers = placedStack.copy();
leftovers.stackSize = reservedItems;
}
player.inventory.setItemStack(leftovers);
update();
}
}
} else if (mode == 1) {
if (slot < 0) {
return null;
}
Slot slot2 = (Slot) this.inventorySlots.get(slot);
if (slot2 != null && slot2.canTakeStack(player)) {
ItemStack itemstack3 = this.transferStackInSlot(player, slot);
if (itemstack3 != null) {
Item item = itemstack3.getItem();
itemstack = itemstack3.copy();
if (slot2.getStack() != null && slot2.getStack().getItem() == item) {
this.retrySlotClick(slot, clickedButton, true, player);
}
}
}
} else {
if (slot < 0) {
return null;
}
Slot slot2 = (Slot) this.inventorySlots.get(slot);
if (slot2 != null) {
ItemStack stackInSlot = slot2.getStack();
ItemStack stackInPlayer = player.inventory.getItemStack();
ItemStack stackPickedUp = null;
int l1 = 0;
if (stackInSlot != null) {
itemstack = stackInSlot.copy();
}
if (stackInSlot == null) {
if (stackInPlayer != null && slot2.isItemValid(stackInPlayer)) {
l1 = clickedButton == 0 ? stackInPlayer.stackSize : 1;
if (l1 > slot2.getSlotStackLimit()) {
l1 = slot2.getSlotStackLimit();
}
if (stackInPlayer.stackSize >= l1) {
slot2.putStack(stackInPlayer.splitStack(l1));
}
if (stackInPlayer.stackSize == 0) {
player.inventory.setItemStack((ItemStack) null);
}
}
} else if (slot2.canTakeStack(player)) {
if (stackInPlayer == null) {
l1 = clickedButton == 0 ? stackInSlot.stackSize : (stackInSlot.stackSize + 1) / 2;
stackPickedUp = slot2.decrStackSize(l1);
player.inventory.setItemStack(stackPickedUp);
if (stackInSlot.stackSize == 0) {
slot2.putStack((ItemStack) null);
}
slot2.onPickupFromSlot(player, player.inventory.getItemStack());
} else if (slot2.isItemValid(stackInPlayer)) {
if (stackInSlot.getItem() == stackInPlayer.getItem() && stackInSlot.getItemDamage() == stackInPlayer.getItemDamage() && ItemStack.areItemStackTagsEqual(stackInPlayer, stackInSlot)) {
l1 = clickedButton == 0 ? stackInPlayer.stackSize : 1;
if (l1 > slot2.getSlotStackLimit() - stackInSlot.stackSize) {
l1 = slot2.getSlotStackLimit() - stackInSlot.stackSize;
}
if (l1 > stackInPlayer.getMaxStackSize() - stackInSlot.stackSize) {
l1 = stackInPlayer.getMaxStackSize() - stackInSlot.stackSize;
}
stackInPlayer.splitStack(l1);
if (stackInPlayer.stackSize == 0) {
player.inventory.setItemStack((ItemStack) null);
}
stackInSlot.stackSize += l1;
} else if (stackInPlayer.stackSize <= slot2.getSlotStackLimit()) {
slot2.putStack(stackInPlayer);
player.inventory.setItemStack(stackInSlot);
}
} else if (stackInSlot.getItem() == stackInPlayer.getItem() && stackInPlayer.getMaxStackSize() > 1 && (!stackInSlot.getHasSubtypes() || stackInSlot.getItemDamage() == stackInPlayer.getItemDamage()) && ItemStack.areItemStackTagsEqual(stackInSlot, stackInPlayer)) {
l1 = stackInSlot.stackSize;
if (l1 > 0 && l1 + stackInPlayer.stackSize <= stackInPlayer.getMaxStackSize()) {
stackInPlayer.stackSize += l1;
stackInSlot = slot2.decrStackSize(l1);
if (stackInSlot.stackSize == 0) {
slot2.putStack((ItemStack) null);
}
slot2.onPickupFromSlot(player, player.inventory.getItemStack());
}
}
}
slot2.onSlotChanged();
}
}
return itemstack;
}
}
|
package ptrman.visualizationTests;
import org.apache.commons.math3.linear.ArrayRealVector;
import org.eclipse.collections.api.tuple.primitive.IntIntPair;
import processing.core.PApplet;
import ptrman.Datastructures.Bb;
import ptrman.Datastructures.IMap2d;
import ptrman.Datastructures.Map2d;
import ptrman.bpsolver.Solver2;
import ptrman.levels.retina.*;
import ptrman.levels.retina.helper.ProcessConnector;
import ptrman.misc.Classifier;
import java.io.IOException;
import java.net.*;
import java.util.*;
/**
* encapsulates functionality to draw visualizations for showcase and debugging
*/
public class VisualizationDrawer {
public boolean drawVisualizationOfAltitude = true;
public boolean drawVisualizationOfEndoSceletons = false; // do we visualize all samples of endo/exo -sceleton
public boolean drawVisualizationOfLineDetectors = false;
public boolean drawVisualizationOfLineDetectorsEnableAct = true; // do we draw activation of line detectors?
public boolean drawVisualizationOfEdgeLineDetectors = false;
public boolean drawVisualizationOfTex = true; // draw visualization of texture
public void drawDetectors(Solver2 solver, PApplet applet) {
if(drawVisualizationOfAltitude) {
for (ProcessA.Sample iSample : solver.connectorSamplesForEndosceleton.out) {
float color = Math.min((float)iSample.altitude / 20.0f, 1.0f);
applet.stroke(color*255.0f);
applet.rect((float)iSample.position.getOne(), (float)iSample.position.getTwo(), 1, 1);
}
}
if(drawVisualizationOfEndoSceletons) {
applet.stroke(200.0f, 255.0f, 200.0f);
for (ProcessA.Sample s : solver.connectorSamplesForEndosceleton.out) {
if (s.type == ProcessA.Sample.EnumType.ENDOSCELETON) {
IntIntPair p = s.position;
applet.rect(p.getOne(), p.getTwo(), 1, 1);
}
}
}
if(drawVisualizationOfEdgeLineDetectors) { // draw visualization of line detectors
for (ProcessD iProcessDEdge : solver.processDEdge) {
for(LineDetectorWithMultiplePoints iLineDetector : iProcessDEdge.annealedCandidates) {
// iLineDetector.cachedSamplePositions
applet.stroke(128.0f, 128, 255);
for (RetinaPrimitive iLine : iProcessDEdge.splitDetectorIntoLines(iLineDetector)) {
double x0 = iLine.line.a.getDataRef()[0];
double y0 = iLine.line.a.getDataRef()[1];
double x1 = iLine.line.b.getDataRef()[0];
double y1 = iLine.line.b.getDataRef()[1];
applet.line((float)x0, (float)y0, (float)x1, (float)y1);
}
if (true) {
applet.stroke(255.0f, 0.0f, 0.0f);
for( ProcessA.Sample iSample : iLineDetector.samples) {
applet.rect((float)iSample.position.getOne(), (float)iSample.position.getTwo(), 1, 1);
}
}
}
}
int here = 5;
}
if(drawVisualizationOfLineDetectors) { // draw visualization of line detectors
for(LineDetectorWithMultiplePoints iLineDetector : solver.processD.annealedCandidates) {
// iLineDetector.cachedSamplePositions
float act = drawVisualizationOfLineDetectorsEnableAct ? (float)iLineDetector.calcActivation() : 1.0f;
applet.stroke(act*255.0f, act*255.0f, act*255.0f);
for (RetinaPrimitive iLine : solver.processD.splitDetectorIntoLines(iLineDetector)) {
double x0 = iLine.line.a.getDataRef()[0];
double y0 = iLine.line.a.getDataRef()[1];
double x1 = iLine.line.b.getDataRef()[0];
double y1 = iLine.line.b.getDataRef()[1];
applet.line((float)x0, (float)y0, (float)x1, (float)y1);
}
applet.stroke(255.0f, 0.0f, 0.0f);
for( ProcessA.Sample iSample : iLineDetector.samples) {
applet.rect((float)iSample.position.getOne(), (float)iSample.position.getTwo(), 1, 1);
}
}
int here = 5;
}
if (drawVisualizationOfTex) { // visualize texture points
for(TexPoint iTex : solver.processFi.outputSampleConnector.out) {
applet.stroke(255.0f, 0.0f, 255.0f);
applet.rect(iTex.x, iTex.y, 1, 1);
}
}
}
// used to transfer narsese relationships
public static List<String> relN = new ArrayList<>();
public void drawPrimitives(Solver2 solver, PApplet applet, Classifier classifier) {
// * draw primitives for edges
for (ProcessConnector<RetinaPrimitive> iCntr : solver.connectorDetectorsFromProcessHForEdge) {
for(RetinaPrimitive iLinePrimitive : iCntr.out) {
applet.stroke(0.0f, 255.0f, 0.0f);
double[] aa = iLinePrimitive.line.a.getDataRef();
double x0 = aa[0];
double y0 = aa[1];
double[] bb = iLinePrimitive.line.b.getDataRef();
double x1 = bb[0];
double y1 = bb[1];
applet.line((float)x0, (float)y0, (float)x1, (float)y1);
}
}
{ // iterate over line detectors of processD for edges
ArrayList<Bb> allBbs = new ArrayList<>(); // BB's of all edge filters
for (ProcessD iProcessDEdge : solver.processDEdge) {
for(LineDetectorWithMultiplePoints iLineDetector : iProcessDEdge.annealedCandidates) {
// iLineDetector.cachedSamplePositions
float act = drawVisualizationOfLineDetectorsEnableAct ? (float)iLineDetector.calcActivation() : 1.0f;
applet.stroke(act*255.0f, act*255.0f, act*255.0f);
for (RetinaPrimitive iLine : solver.processD.splitDetectorIntoLines(iLineDetector)) {
double x0 = iLine.line.a.getDataRef()[0];
double y0 = iLine.line.a.getDataRef()[1];
double x1 = iLine.line.b.getDataRef()[0];
double y1 = iLine.line.b.getDataRef()[1];
applet.line((float)x0, (float)y0, (float)x1, (float)y1);
}
applet.stroke(255.0f, 0.0f, 0.0f);
for( ProcessA.Sample iSample : iLineDetector.samples) {
applet.rect((float)iSample.position.getOne(), (float)iSample.position.getTwo(), 1, 1);
}
}
// bounding box logic
// we try to group points to bounding boxes for each edge detector direction
ArrayList<Bb> bbs = new ArrayList<>();
{
for(int idx=0;idx<solver.connectorSamplesFromProcessAForEdge.length;idx++) {
for(ProcessA.Sample iSample : solver.connectorSamplesFromProcessAForEdge[idx].out) {
boolean found = false; // found bb to add to?
for(Bb iBb : bbs) {
if (Bb.inRange(iBb, iSample.position.getOne(), iSample.position.getTwo(), 4.0)) { // in at boundary f bb or inside?
iBb.add(iSample.position.getOne(), iSample.position.getTwo());
found = true;
}
}
if (!found) {
Bb bb = new Bb();
bb.add(iSample.position.getOne(), iSample.position.getTwo());
bbs.add(bb);
}
}
}
}
// visualize BB's
if(false) {
applet.stroke(255.0f, 255.0f, 0.0f);
applet.fill(0, 1.0f);
for(Bb iBB : bbs) {
applet.rect((int)iBB.minx, (int) iBB.miny, (int)(iBB.maxx-iBB.minx), (int)(iBB.maxy-iBB.miny));
}
}
// transfer bbs to all
allBbs.addAll(bbs);
}
// merge BB's
for(int idx0=0; idx0 < allBbs.size();) {
for(int idx1=idx0+1; idx1 < allBbs.size(); idx1++) {
if (Bb.checkOverlap(allBbs.get(idx0), allBbs.get(idx1))) {
allBbs.set(idx0, Bb.merge(allBbs.get(idx0), allBbs.get(idx1)));
allBbs.remove(idx1);
// restart
idx0 = -1;
break;
}
}
idx0++;
}
// visualize merged BB's
applet.stroke(0.0f, 255.0f, 0.0f);
applet.fill(0, 1.0f);
for(Bb iBB : allBbs) {
applet.rect((int)iBB.minx, (int) iBB.miny, (int)(iBB.maxx-iBB.minx), (int)(iBB.maxy-iBB.miny));
}
List<Classification> classifications = new ArrayList<>();
if (classifier != null) { // is classification enabled?
// PREPARATION FOR CLASIFIERS
// prepare maps as targets to draw "quantized" line detectors
IMap2d<Boolean>[] edgeMaps = new IMap2d[solver.processDEdge.length];
for(int idx=0;idx<solver.processDEdge.length;idx++) {
edgeMaps[idx] = new Map2d<>(solver.mapBoolean.getWidth(), solver.mapBoolean.getLength());
for(int ix=0;ix<edgeMaps[idx].getWidth();ix++) {
for(int iy=0;iy<edgeMaps[idx].getLength();iy++) {
edgeMaps[idx].setAt(ix,iy,false);
}
}
}
// draw "quantized" line detectors as dots to get them back to a image representation
for(int idx=0;idx<solver.connectorSamplesFromProcessAForEdge.length;idx++) {
IMap2d<Boolean> selmap = edgeMaps[idx];
for(ProcessA.Sample iSample : solver.connectorSamplesFromProcessAForEdge[idx].out) {
int x = iSample.position.getOne();
int y = iSample.position.getTwo();
selmap.setAt(x, y, true);
selmap.setAt(x+1, y, true);
selmap.setAt(x, y+1, true);
selmap.setAt(x+1, y+1, true);
}
}
// ACTUAL CLASSIFICATION
boolean verbose = false;
if(verbose) System.out.println("FRAME");
for(Bb iBB : allBbs) {
float centerX = (float)(iBB.maxx+iBB.minx)/2.0f;
float centerY = (float)(iBB.maxy+iBB.miny)/2.0f;
// simulate convolution by finding best classification in proximity
ArrayRealVector stimulus = cropEdgeMapsAndConcatToVecAt(edgeMaps, (int)centerX, (int)centerY, 32, 32); // extract cropped image
classifier.classify(stimulus, false);
int bestCenterX = (int)centerX;
int bestCenterY = (int)centerY;
float bestSimilarity = classifier.bestCategorySimilarity;
int convRange = 3; // range of convolution - in + - dimension
for(int dx=-convRange;dx<convRange;dx++) {
for(int dy=-convRange;dy<convRange;dy++) {
int thisCenterX = (int)centerX+dx;
int thisCenterY = (int)centerY+dy;
ArrayRealVector stimulus2 = cropEdgeMapsAndConcatToVecAt(edgeMaps, (int)centerX, (int)centerY, 32, 32); // extract cropped image
classifier.classify(stimulus2, false);
float thisSim = classifier.bestCategorySimilarity;
if (thisSim > bestSimilarity) {
bestSimilarity = thisSim;
bestCenterX = thisCenterX;
bestCenterY = thisCenterY;
}
}
}
// * extract cropped image
// DEBUG CLASSIFICATION RECT
applet.stroke(255.0f, 255.0f, 255.0f);
applet.fill(0, 1.0f);
applet.rect( (int)bestCenterX-32/2, (int)bestCenterY-32/2, 32, 32);
// * classify
stimulus = cropEdgeMapsAndConcatToVecAt(edgeMaps, (int)bestCenterX, (int)bestCenterY, 32, 32); // extract cropped image
long categoryId = classifier.classify(stimulus, true);
float thisClassificationSim = classifier.bestCategorySimilarity;
classifications.add(new Classification(bestCenterX, bestCenterY, categoryId)); // store classification for later processing
// * draw classification (for debugging)
applet.fill(255);
applet.text("c="+categoryId, bestCenterX-32/2, bestCenterY-32/2);
}
if(verbose) System.out.println("FRAME END");
}
// TODO< group by class and send relations by element with lowest count of class! >
Map<Long, ArrayList<Classification>> classificationsByCategory = new HashMap<>();
for(Classification iClasfcn: classifications) {
if(classificationsByCategory.containsKey(iClasfcn.category)) {
classificationsByCategory.get(iClasfcn.category).add(iClasfcn);
}
else {
ArrayList<Classification> arr = new ArrayList<>();
arr.add(iClasfcn);
classificationsByCategory.put(iClasfcn.category, arr);
}
}
// find classification with lowest number of items
ArrayList<Classification> classificationCandidatesWithLowestMemberCount = null;
for(Map.Entry<Long, ArrayList<Classification>> i : classificationsByCategory.entrySet()) {
if (classificationCandidatesWithLowestMemberCount == null) { // is first one?
classificationCandidatesWithLowestMemberCount = i.getValue();
}
else if(i.getValue().size() < classificationCandidatesWithLowestMemberCount.size()) {
classificationCandidatesWithLowestMemberCount = i.getValue();
}
}
// send to NAR
//< it seems like NAR can get overwhelmed, so we don't send every time
if ((solver.t % 2) == 0) {
relN.clear();
HashMap<String, Boolean> relByNarsese = new HashMap<>(); // we want to reduce the amount of spam to NARS by omitting redudant events (all happens in the same frame anyways)
// build relations between classifications with low count with classifications of high count
if (classificationCandidatesWithLowestMemberCount != null) {
for(Classification iClassfcnWithLowestCount : classificationCandidatesWithLowestMemberCount) {
for(Classification iClasfcnOther: classifications) {
if (iClassfcnWithLowestCount != iClasfcnOther) { // must be different objects
if (iClassfcnWithLowestCount.category != iClasfcnOther.category) { // we are only interested in different classifications!
String relY;
String relX;
{ // compute relationship term
relY = "c";
relX = "c";
double diffX = iClassfcnWithLowestCount.posX-iClasfcnOther.posX;
double diffY = iClassfcnWithLowestCount.posY-iClasfcnOther.posY;
if (diffY < -15.0) {
relY = "b"; // below
}
if (diffY > 15.0) {
relY = "a"; // above
}
if (diffX < -15.0) {
relX = "b"; // below
}
if (diffX > 15.0) {
relX = "a"; // above
}
}
// scalable way// String n = "< ( {"+(relY)+"} * < ( {"+iClassfcnWithLowestCount.category+"} * {"+iClasfcnOther.category+"} ) --> h > ) --> relY >. :|:";
// not scalable way, will xplode for more complicated scenes
String n = "< ( {"+(relY)+"} * {"+iClassfcnWithLowestCount.category+"D"+iClasfcnOther.category+"} ) --> relY >. :|:";
relByNarsese.put(n, true); // store in set
n = "< ( {"+(relX)+"} * {"+iClassfcnWithLowestCount.category+"D"+iClasfcnOther.category+"} ) --> relX >. :|:";
relByNarsese.put(n, true); // store in set
}
}
}
}
}
for(String iN : relByNarsese.keySet()) {
relN.add(iN);
}
// HACK< sort BB's by x axis >
Collections.sort(allBbs, (a, b) -> (a.minx == b.minx) ? 0 : ((a.minx > b.minx) ? 1 : -1));
// HACK< we should send it normally over NarsBinding >
// build relations to center
if (allBbs.size() >= 2) {
Bb centerBb = allBbs.get(0);
for(int idx=1;idx<allBbs.size();idx++) {
Bb otherBb = allBbs.get(idx);
if (otherBb.minx < 20.0) {
continue; // HACK for pong, ignore it because we else get BS relations
}
String relY = "c";
double diffY = centerBb.miny-otherBb.miny;
double diffX = centerBb.minx-otherBb.minx;
if (diffY < -15.0) {
relY = "b"; // below
}
if (diffY > 15.0) {
relY = "a"; // above
}
break; // we only care about first relation
}
}
}
}
// * draw primitives for endoskeleton
for(RetinaPrimitive iLinePrimitive : solver.cntrFinalProcessing.out) {
applet.stroke(255.0f, 255.0f, 255.0f);
double x0 = iLinePrimitive.line.a.getDataRef()[0];
double y0 = iLinePrimitive.line.a.getDataRef()[1];
double x1 = iLinePrimitive.line.b.getDataRef()[0];
double y1 = iLinePrimitive.line.b.getDataRef()[1];
applet.line((float)x0, (float)y0, (float)x1, (float)y1);
// draw intersections as small triangles
applet.stroke(255.0f, 0.0f, 0.0f);
for (Intersection iIntersection : iLinePrimitive.line.intersections) {
int x = (int)iIntersection.intersectionPosition.getDataRef()[0];
int y = (int)iIntersection.intersectionPosition.getDataRef()[1];
applet.line(x,y-1,x-1,y+1);
applet.line(x,y-1,x+1,y+1);
applet.line(x-1,y+1,x+1,y+1);
}
}
}
// helper
// reads crops from edge maps and concatenate it all to a single vector for classification
static ArrayRealVector cropEdgeMapsAndConcatToVecAt(IMap2d<Boolean>[] edgeMaps, int centerX, int centerY, int width, int height) {
ArrayRealVector dest = new ArrayRealVector(edgeMaps.length*width*height);
int destIdx = 0; // index in dest
for(IMap2d<Boolean> iEdgeMap : edgeMaps) {
for(int ix=centerX-width/2;ix<centerX+width/2;ix++) {
for(int iy=centerY-height/2;iy<centerY+height/2;iy++) {
if (iEdgeMap.inBounds(ix, iy)) {
boolean v = iEdgeMap.readAt(ix, iy);
dest.setEntry(destIdx, v ? 1 : 0);
}
destIdx++;
}
}
}
return dest;
}
// helper
static class Classification {
public long category;
public int posX;
public int posY;
public Classification(int posX, int posY, long category) {
this.posX = posX;
this.posY = posY;
this.category = category;
}
}
}
|
package roycurtis.jdiscordirc.managers;
import net.dv8tion.jda.core.*;
import net.dv8tion.jda.core.entities.Game;
import net.dv8tion.jda.core.entities.Guild;
import net.dv8tion.jda.core.entities.Member;
import net.dv8tion.jda.core.entities.TextChannel;
import net.dv8tion.jda.core.events.DisconnectEvent;
import net.dv8tion.jda.core.events.ReadyEvent;
import net.dv8tion.jda.core.events.ReconnectedEvent;
import net.dv8tion.jda.core.events.ResumedEvent;
import net.dv8tion.jda.core.events.guild.member.GuildMemberJoinEvent;
import net.dv8tion.jda.core.events.guild.member.GuildMemberLeaveEvent;
import net.dv8tion.jda.core.events.guild.member.GuildMemberNickChangeEvent;
import net.dv8tion.jda.core.events.message.MessageReceivedEvent;
import net.dv8tion.jda.core.hooks.ListenerAdapter;
import net.dv8tion.jda.core.requests.CloseCode;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import static roycurtis.jdiscordirc.JDiscordIRC.BRIDGE;
import static roycurtis.jdiscordirc.JDiscordIRC.CONFIG;
public class DiscordManager extends ListenerAdapter
{
private static final Logger LOG = LoggerFactory.getLogger(DiscordManager.class);
private static final Pattern MENTION = Pattern.compile("\\B@([\\S]+)\\b");
private JDA bot;
private String token;
private String guildId;
private String channelId;
private String url;
//<editor-fold desc="Manager methods (main thread)">
public void init() throws Exception
{
LOG.info("Connecting for first time...");
token = CONFIG.get("discord.token");
guildId = CONFIG.get("discord.guild");
channelId = CONFIG.get("discord.channel");
url = CONFIG.get("discord.url");
bot = new JDABuilder(AccountType.BOT)
.setAudioEnabled(false)
.setToken(token)
.addEventListener(this)
.buildAsync();
}
public boolean isAvailable()
{
if (bot == null)
return false;
else return bot.getStatus() == JDA.Status.CONNECTED;
}
public void sendMessage(String msg, Object... parts)
{
if ( !isAvailable() )
{
LOG.debug("Rejecting message; Discord unavailable: {}", msg);
return;
}
String fullMsg = String.format(msg, parts);
LOG.info("Sent: {}", fullMsg);
bot.getTextChannelById(channelId)
.sendMessage(fullMsg)
.complete();
}
public void sendMessageWithMentions(String msg, Object... parts)
{
if ( !isAvailable() )
{
LOG.debug("Rejecting message; Discord unavailable: {}", msg);
return;
}
String fullMsg = String.format(msg, parts);
Matcher matcher = MENTION.matcher(fullMsg);
TextChannel channel = bot.getTextChannelById(channelId);
Guild guild = bot.getGuildById(guildId);
// Skip processing mentions if none seem to exist
if ( !matcher.find() )
{
LOG.info("Sent: {}", fullMsg);
channel.sendMessage(fullMsg).complete();
return;
}
// Have to reset from above one-time use of find
matcher.reset();
StringBuffer buffer = new StringBuffer();
// Iterate through any detected mentions and try to link to member
while ( matcher.find() )
{
String mention = matcher.group(1);
List<Member> matches = guild.getMembersByEffectiveName(mention, true);
// Skip if no matches, or ambiguous matches
if (matches.size() < 1 || matches.size() > 1)
continue;
Member member = matches.get(0);
// Skip if member is not actually in channel
if ( !member.hasPermission(channel, Permission.MESSAGE_READ) )
continue;
// Convert match into a real mention, add to string
matcher.appendReplacement( buffer, member.getAsMention() );
}
matcher.appendTail(buffer);
fullMsg = buffer.toString();
LOG.info("Sent: {}", fullMsg);
channel.sendMessage(fullMsg).complete();
}
public String getUrl()
{
return url;
}
public void setStatus(OnlineStatus status, String game, String url)
{
bot.getPresence().setStatus(status);
bot.getPresence().setGame( Game.of(game, url) );
}
//</editor-fold>
//<editor-fold desc="Bot event handlers (Discord thread)">
@Override
public void onReady(ReadyEvent event)
{
LOG.info("Connected successfully");
BRIDGE.onDiscordConnect();
}
@Override
public void onReconnect(ReconnectedEvent event)
{
LOG.info("Reconnected");
BRIDGE.onDiscordConnect();
}
@Override
public void onResume(ResumedEvent event)
{
LOG.info("Reconnected");
BRIDGE.onDiscordConnect();
}
@Override
public void onDisconnect(DisconnectEvent event)
{
// Thanks to Minn for the following, for better disconnect explaination.
// Cannot use event.getClientCloseFrame due to unknown issue with WebSocketFrame
String why;
CloseCode code = event.getCloseCode();
if (code != null)
why = String.format( "%s: %s", code.getCode(), code.getMeaning() );
else
why = event.isClosedByServer()
? "closed by server"
: "closed by client";
LOG.warn("Lost connection ({}); reconnecting...", why);
BRIDGE.onDiscordDisconnect();
}
@Override
public void onMessageReceived(MessageReceivedEvent event)
{
// Ignore own messages
if ( event.getAuthor().equals( bot.getSelfUser() ) )
return;
// Ignore messages from other channels
if ( !event.getChannel().getId().contentEquals(channelId) )
return;
LOG.trace( "Message from {} with {} attachment(s): {}",
event.getMember().getEffectiveName(),
event.getMessage().getAttachments().size(),
event.getMessage().getStrippedContent()
);
BRIDGE.onDiscordMessage(event);
}
@Override
public void onGuildMemberJoin(GuildMemberJoinEvent event)
{
// Ignore from other servers
if ( !event.getGuild().getId().contentEquals(guildId) )
return;
LOG.trace( "{} joined the server", event.getMember().getEffectiveName() );
BRIDGE.onDiscordUserJoin(event);
}
@Override
public void onGuildMemberLeave(GuildMemberLeaveEvent event)
{
// Ignore from other servers
if ( !event.getGuild().getId().contentEquals(guildId) )
return;
LOG.trace( "{} quit the server", event.getMember().getEffectiveName() );
BRIDGE.onDiscordUserLeave(event);
}
@Override
public void onGuildMemberNickChange(GuildMemberNickChangeEvent event)
{
// Ignore from other servers
if ( !event.getGuild().getId().contentEquals(guildId) )
return;
String oldNick = event.getPrevNick();
String newNick = event.getNewNick();
// Adding or removing a nickname means one or the other is null
if (oldNick == null) oldNick = event.getMember().getUser().getName();
if (newNick == null) newNick = event.getMember().getUser().getName();
LOG.trace("{} changed nick to {}", oldNick, newNick);
BRIDGE.onDiscordNickChange(oldNick, newNick);
}
//</editor-fold>
}
|
package gnu.xquery.testsuite;
import gnu.expr.*;
import kawa.*;
import gnu.mapping.*;
import gnu.xquery.lang.*;
import gnu.text.*;
public class TestMisc
{
static { XQuery.registerEnvironment(); }
static Interpreter interp = Interpreter.getInterpreter();
static Environment env = Environment.getCurrent();
static int expectedPasses = 0;
static int unexpectedPasses = 0;
static int expectedFailures = 0;
static int unexpectedFailures = 0;
static boolean verbose = false;
static String failureExpectedNext = null;
public static void main(String[] args)
{
// gnu.expr.ModuleExp.dumpZipPrefix = "kawa-zip-dump-";
// gnu.expr.ModuleExp.debugPrintExpr = true;
// Compilation.debugPrintFinalExpr = true;
evalTest("3.5+1", "4.5");
evalTest("3.5+1 ,4*2.5", "4.5 10.0");
evalTest("3<5", "true");
evalTest("let $x:=3+4 return $x", "7");
evalTest("let $x:=3+4 return <a>{$x}</a>", "<a>7</a>");
evalTest("for $y in (4,5,2+4) return <b>{10+$y}</b>",
"<b>14</b><b>15</b><b>16</b>");
evalTest("for $i in (1 to 10) where ($i mod 2)=1 return 20+$i",
"21 23 25 27 29");
evalTest("(3,4,5)[3]", "5");
evalTest("1,((2,3)[false()]),5", "1 5");
evalTest("1,((2 to 4)[true()]),5", "1 2 3 4 5");
evalTest("(for $y in (5,4) return <b>{10+$y}</b>)[2]", "<b>14</b>");
evalTest("document(\"tab.xml\")/result",
"<result>\n" +
"<row>\n" +
"<fld1>a1</fld1>\n" +
"<fld2 align=\"right\">12</fld2>\n" +
"</row>\n" +
"<row>\n" +
"<fld1 align=\"left\">b1</fld1>\n" +
"<fld2 align=\"right\">22</fld2>\n" +
"</row>\n" +
"<h:row>\n" +
"<j:fld1>c1</j:fld1>\n" +
"<h:fld2>33</h:fld2>\n" +
"<j:fld3>44</j:fld3>\n" +
"<k:fld1>c2</k:fld1>\n" +
"</h:row>\n" +
"</result>");
evalTest("document(\"tab.xml\")/result/row/fld2",
"<fld2 align=\"right\">12</fld2><fld2 align=\"right\">22</fld2>");
evalTest("document(\"tab.xml\")/result/row[fld2]",
"<row>\n" +
"<fld1>a1</fld1>\n" +
"<fld2 align=\"right\">12</fld2>\n" +
"</row><row>\n" +
"<fld1 align=\"left\">b1</fld1>\n" +
"<fld2 align=\"right\">22</fld2>\n" +
"</row>");
/** True if the two string match, ignoring unquoted white-space. */
/*
int ch;
for (;;)
{
ch = in.read();
if (ch < 0 || ch == '\r' || ch == '\n')
break;
if (ch != ' ' && ch != '\t')
{
in.unread();
break;
}
}
*/
ctx.runUntilDone();
}
return new String(out.toCharArray());
}
}
|
package org.voltdb;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.anyInt;
import static org.mockito.Matchers.anyLong;
import static org.mockito.Matchers.anyObject;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.reset;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import java.io.File;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.ArrayDeque;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Queue;
import java.util.Set;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.Executors;
import java.util.concurrent.LinkedTransferQueue;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import org.apache.zookeeper_voltpatches.CreateMode;
import org.apache.zookeeper_voltpatches.ZooDefs.Ids;
import org.apache.zookeeper_voltpatches.ZooKeeper;
import org.junit.After;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.mockito.ArgumentCaptor;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
import org.voltcore.messaging.HostMessenger;
import org.voltcore.messaging.LocalObjectMessage;
import org.voltcore.messaging.VoltMessage;
import org.voltcore.network.Connection;
import org.voltcore.network.VoltNetworkPool;
import org.voltcore.utils.DeferredSerialization;
import org.voltcore.utils.Pair;
import org.voltdb.ClientInterface.ClientInputHandler;
import org.voltdb.VoltDB.Configuration;
import org.voltdb.VoltTable.ColumnInfo;
import org.voltdb.catalog.Catalog;
import org.voltdb.client.ClientResponse;
import org.voltdb.client.ProcedureInvocationType;
import org.voltdb.common.Constants;
import org.voltdb.compiler.AdHocPlannedStatement;
import org.voltdb.compiler.AdHocPlannedStmtBatch;
import org.voltdb.compiler.AdHocPlannerWork;
import org.voltdb.compiler.CatalogChangeResult;
import org.voltdb.compiler.CatalogChangeWork;
import org.voltdb.compiler.VoltProjectBuilder;
import org.voltdb.iv2.Cartographer;
import org.voltdb.messaging.InitiateResponseMessage;
import org.voltdb.messaging.Iv2InitiateTaskMessage;
import org.voltdb.utils.CatalogUtil;
import org.voltdb.utils.Encoder;
import org.voltdb.utils.MiscUtils;
public class TestClientInterface {
// mocked objects that CI requires
private VoltDBInterface m_volt;
private Queue<DeferredSerialization> statsAnswers = new ArrayDeque<DeferredSerialization>();
private int drStatsInvoked = 0;
private StatsAgent m_statsAgent = new StatsAgent() {
@Override
public void performOpsAction(final Connection c, final long clientHandle, final OpsSelector selector,
final ParameterSet params) throws Exception {
final String stat = (String)params.toArray()[0];
if (stat.equals("TOPO") && !statsAnswers.isEmpty()) {
c.writeStream().enqueue(statsAnswers.poll());
} else if (stat.equals("DR")) {
drStatsInvoked++;
}
}
};
private SystemInformationAgent m_sysinfoAgent;
private HostMessenger m_messenger;
private ClientInputHandler m_handler;
private Cartographer m_cartographer;
private SimpleClientResponseAdapter m_cxn;
private ZooKeeper m_zk;
// real context
private static CatalogContext m_context = null;
// real CI, but spied on using mockito
private static ClientInterface m_ci = null;
// the mailbox in CI
//private static Mailbox m_mb = null;
private static int[] m_allPartitions = new int[] {0, 1, 2};
@BeforeClass
public static void setUpOnce() throws Exception {
buildCatalog();
}
BlockingQueue<ByteBuffer> responses = new LinkedTransferQueue<ByteBuffer>();
BlockingQueue<DeferredSerialization> responsesDS = new LinkedTransferQueue<DeferredSerialization>();
private static final ScheduledExecutorService ses = Executors.newScheduledThreadPool(1);
@Before
public void setUp() throws Exception {
// Set up CI with the mock objects.
m_volt = mock(VoltDBInterface.class);
m_sysinfoAgent = mock(SystemInformationAgent.class);
m_messenger = mock(HostMessenger.class);
m_handler = mock(ClientInputHandler.class);
m_cartographer = mock(Cartographer.class);
m_zk = mock(ZooKeeper.class);
responses = new LinkedTransferQueue<ByteBuffer>();
responsesDS = new LinkedTransferQueue<DeferredSerialization>();
//m_cxn = mock(SimpleClientResponseAdapter.class);
drStatsInvoked = 0;
m_cxn = new SimpleClientResponseAdapter(0, "foo") {
@Override
public void enqueue(ByteBuffer buf) {responses.offer(buf);}
@Override
public void enqueue(ByteBuffer bufs[]) {responses.offer(bufs[0]);}
@Override
public void enqueue(DeferredSerialization ds) {responsesDS.offer(ds);}
@Override
public void queueTask(Runnable r) {}
};
/*
* Setup the mock objects so that they return expected objects in CI
* construction
*/
VoltDB.replaceVoltDBInstanceForTest(m_volt);
doReturn(m_cxn.connectionId()).when(m_handler).connectionId();
doReturn(m_statsAgent).when(m_volt).getStatsAgent();
doReturn(m_statsAgent).when(m_volt).getOpsAgent(OpsSelector.STATISTICS);
doReturn(m_sysinfoAgent).when(m_volt).getOpsAgent(OpsSelector.SYSTEMINFORMATION);
doReturn(mock(SnapshotCompletionMonitor.class)).when(m_volt).getSnapshotCompletionMonitor();
doReturn(m_messenger).when(m_volt).getHostMessenger();
doReturn(mock(VoltNetworkPool.class)).when(m_messenger).getNetwork();
doReturn(m_zk).when(m_messenger).getZK();
doReturn(mock(Configuration.class)).when(m_volt).getConfig();
doReturn(32L).when(m_messenger).getHSIdForLocalSite(HostMessenger.ASYNC_COMPILER_SITE_ID);
doAnswer(new Answer<Object>() {
@Override
public Object answer(InvocationOnMock invocation)
{
Object args[] = invocation.getArguments();
return ses.scheduleAtFixedRate((Runnable) args[0], (long) args[1], (long) args[2], (TimeUnit) args[3]);
}
}).when(m_volt).scheduleWork(any(Runnable.class), anyLong(), anyLong(), (TimeUnit)anyObject());
m_ci = spy(new ClientInterface(null, VoltDB.DEFAULT_PORT, null, VoltDB.DEFAULT_ADMIN_PORT,
m_context, m_messenger, ReplicationRole.NONE,
m_cartographer, m_allPartitions));
m_ci.bindAdapter(m_cxn);
//m_mb = m_ci.m_mailbox;
}
private static void buildCatalog() throws IOException {
// build a real catalog
File cat = File.createTempFile("temp-log-reinitiator", "catalog");
cat.deleteOnExit();
VoltProjectBuilder builder = new VoltProjectBuilder();
String schema = "create table A (i integer not null, primary key (i));";
builder.addLiteralSchema(schema);
builder.addPartitionInfo("A", "i");
builder.addStmtProcedure("hello", "select * from A where i = ?", "A.i: 0");
if (!builder.compile(cat.getAbsolutePath())) {
throw new IOException();
}
byte[] bytes = MiscUtils.fileToBytes(cat);
String serializedCat = CatalogUtil.loadCatalogFromJar(bytes, null);
assertNotNull(serializedCat);
Catalog catalog = new Catalog();
catalog.execute(serializedCat);
String deploymentPath = builder.getPathToDeployment();
CatalogUtil.compileDeployment(catalog, deploymentPath, true, false);
m_context = new CatalogContext(0, 0, catalog, bytes, null, 0, 0);
TheHashinator.initialize(TheHashinator.getConfiguredHashinatorClass(), TheHashinator.getConfigureBytes(3));
}
@After
public void tearDown() {
reset(m_messenger);
reset(m_handler);
}
private static ByteBuffer createMsg(String name, final Object...params) throws IOException {
return createMsg(null, name, params);
}
/**
* Create a VoltMessage that can be fed into CI's handleRead() method.
* @param origTxnId The original txnId if it's a replicated transaction
* @param name The procedure name
* @param params Procedure parameters
* @return
* @throws IOException
*/
private static ByteBuffer createMsg(Long origTxnId, String name,
final Object...params) throws IOException
{
StoredProcedureInvocation proc = new StoredProcedureInvocation();
proc.setProcName(name);
if (origTxnId != null)
proc.setOriginalTxnId(origTxnId);
proc.setParams(params);
ByteBuffer buf = ByteBuffer.allocate(proc.getSerializedSize());
proc.flattenToBuffer(buf);
buf.flip();
return buf;
}
/**
* Pass the VoltMessage to CI's handleRead() and inspect if the expected
* parameters are passed to the initiator's createTranction() method. This
* is a convenient method if the caller expects the result of handling this
* message is to create a new transaction.
*
* @param msg
* @param procName
* @param partitionParam null if it's a multi-part txn
* @param isAdmin
* @param isReadonly
* @param isSinglePart
* @param isEverySite
* @return StoredProcedureInvocation object passed to createTransaction()
* @throws IOException
*/
private Iv2InitiateTaskMessage readAndCheck(ByteBuffer msg, String procName, Object partitionParam,
boolean isReadonly, boolean isSinglePart) throws Exception {
ClientResponseImpl resp = m_ci.handleRead(msg, m_handler, m_cxn);
assertNull(resp);
return checkInitMsgSent(procName, partitionParam, isReadonly, isSinglePart);
}
private Iv2InitiateTaskMessage checkInitMsgSent(String procName, Object partitionParam,
boolean isReadonly, boolean isSinglePart)
{
ArgumentCaptor<Long> destinationCaptor =
ArgumentCaptor.forClass(Long.class);
ArgumentCaptor<Iv2InitiateTaskMessage> messageCaptor =
ArgumentCaptor.forClass(Iv2InitiateTaskMessage.class);
verify(m_messenger).send(destinationCaptor.capture(), messageCaptor.capture());
Iv2InitiateTaskMessage message = messageCaptor.getValue();
assertEquals(isReadonly, message.isReadOnly()); // readonly
assertEquals(isSinglePart, message.isSinglePartition()); // single-part
assertEquals(procName, message.getStoredProcedureName());
if (isSinglePart) {
int expected = TheHashinator.getPartitionForParameter(VoltType.typeFromObject(partitionParam).getValue(),
partitionParam);
assertEquals(new Long(m_cartographer.getHSIdForMaster(expected)), destinationCaptor.getValue());
} else {
assertEquals(new Long(m_cartographer.getHSIdForMultiPartitionInitiator()), destinationCaptor.getValue());
}
return message;
}
@Test
public void testExplain() throws IOException {
ByteBuffer msg = createMsg("@Explain", "select * from a");
ClientResponseImpl resp = m_ci.handleRead(msg, m_handler, m_cxn);
assertNull(resp);
ArgumentCaptor<LocalObjectMessage> captor = ArgumentCaptor.forClass(LocalObjectMessage.class);
verify(m_messenger).send(eq(32L), captor.capture());
assertTrue(captor.getValue().payload instanceof AdHocPlannerWork );
System.out.println( captor.getValue().payload.toString() );
String payloadString = captor.getValue().payload.toString();
assertTrue(payloadString.contains("user partitioning: none"));
}
@Test
public void testAdHoc() throws IOException {
ByteBuffer msg = createMsg("@AdHoc", "select * from a");
ClientResponseImpl resp = m_ci.handleRead(msg, m_handler, m_cxn);
assertNull(resp);
ArgumentCaptor<LocalObjectMessage> captor = ArgumentCaptor.forClass(LocalObjectMessage.class);
verify(m_messenger).send(eq(32L), captor.capture());
assertTrue(captor.getValue().payload instanceof AdHocPlannerWork);
String payloadString = captor.getValue().payload.toString();
assertTrue(payloadString.contains("user partitioning: none"));
// single-part adhoc
reset(m_messenger);
msg = createMsg("@AdHocSpForTest", "select * from a where i = 3", 3);
resp = m_ci.handleRead(msg, m_handler, m_cxn);
assertNull(resp);
verify(m_messenger).send(eq(32L), captor.capture());
assertTrue(captor.getValue().payload instanceof AdHocPlannerWork);
payloadString = captor.getValue().payload.toString();
assertTrue(payloadString.contains("user params: empty"));
assertTrue(payloadString.contains("user partitioning: 3"));
}
@Test
public void testFinishedSPAdHocPlanning() throws Exception {
// Need a batch and a statement
String query = "select * from a where i = ?";
int partitionParamIndex = 0;
Object[] extractedValues = new Object[0];
VoltType[] paramTypes = new VoltType[]{VoltType.INTEGER};
AdHocPlannedStmtBatch plannedStmtBatch =
AdHocPlannedStmtBatch.mockStatementBatch(3, query, extractedValues, paramTypes,
new Object[]{3}, partitionParamIndex);
m_ci.processFinishedCompilerWork(plannedStmtBatch).run();
ArgumentCaptor<Long> destinationCaptor =
ArgumentCaptor.forClass(Long.class);
ArgumentCaptor<Iv2InitiateTaskMessage> messageCaptor =
ArgumentCaptor.forClass(Iv2InitiateTaskMessage.class);
verify(m_messenger).send(destinationCaptor.capture(), messageCaptor.capture());
Iv2InitiateTaskMessage message = messageCaptor.getValue();
assertTrue(message.isReadOnly()); // readonly
assertTrue(message.isSinglePartition()); // single-part
assertEquals("@AdHoc_RO_SP", message.getStoredProcedureName());
// SP AdHoc should have partitioning parameter serialized in the parameter set
Object partitionParam = message.getStoredProcedureInvocation().getParameterAtIndex(0);
assertTrue(partitionParam instanceof byte[]);
VoltType type = VoltType.get((Byte) message.getStoredProcedureInvocation().getParameterAtIndex(1));
assertTrue(type.isInteger());
byte[] serializedData = (byte[]) message.getStoredProcedureInvocation().getParameterAtIndex(2);
ByteBuffer buf = ByteBuffer.wrap(serializedData);
Object[] parameters = AdHocPlannedStmtBatch.userParamsFromBuffer(buf);
assertEquals(1, parameters.length);
assertEquals(3, parameters[0]);
AdHocPlannedStatement[] statements = AdHocPlannedStmtBatch.planArrayFromBuffer(buf);
assertTrue(Arrays.equals(TheHashinator.valueToBytes(3), (byte[]) partitionParam));
assertEquals(1, statements.length);
String sql = new String(statements[0].sql, Constants.UTF8ENCODING);
assertEquals(query, sql);
}
/**
* Fake an adhoc compiler result and return it to the CI, see if CI
* initiates the txn.
*/
@Test
public void testFinishedMPAdHocPlanning() throws Exception {
// Need a batch and a statement
String query = "select * from a";
Object[] extractedValues = new Object[0];
VoltType[] paramTypes = new VoltType[0];
AdHocPlannedStmtBatch plannedStmtBatch =
AdHocPlannedStmtBatch.mockStatementBatch(3, query, extractedValues, paramTypes, null, -1);
m_ci.processFinishedCompilerWork(plannedStmtBatch).run();
ArgumentCaptor<Long> destinationCaptor =
ArgumentCaptor.forClass(Long.class);
ArgumentCaptor<Iv2InitiateTaskMessage> messageCaptor =
ArgumentCaptor.forClass(Iv2InitiateTaskMessage.class);
verify(m_messenger).send(destinationCaptor.capture(), messageCaptor.capture());
Iv2InitiateTaskMessage message = messageCaptor.getValue();
//assertFalse(boolValues.get(0)); // is admin
assertTrue(message.isReadOnly()); // readonly
assertFalse(message.isSinglePartition()); // single-part
//assertFalse(boolValues.get(3)); // every site
assertEquals("@AdHoc_RO_MP", message.getStoredProcedureName());
byte[] serializedData = (byte[]) message.getStoredProcedureInvocation().getParameterAtIndex(0);
ByteBuffer buf = ByteBuffer.wrap(serializedData);
Object[] parameters = AdHocPlannedStmtBatch.userParamsFromBuffer(buf);
assertEquals(0, parameters.length);
AdHocPlannedStatement[] statements = AdHocPlannedStmtBatch.planArrayFromBuffer(buf);
assertEquals(1, statements.length);
String sql = new String(statements[0].sql, Constants.UTF8ENCODING);
assertEquals(query, sql);
}
@Test
public void testUpdateCatalog() throws IOException {
// only makes sense in pro (sysproc suite has a complementary test for community)
if (VoltDB.instance().getConfig().m_isEnterprise) {
String catalogHex = Encoder.hexEncode("blah");
ByteBuffer msg = createMsg("@UpdateApplicationCatalog", catalogHex, "blah");
ClientResponseImpl resp = m_ci.handleRead(msg, m_handler, m_cxn);
assertNull(resp);
ArgumentCaptor<LocalObjectMessage> captor = ArgumentCaptor.forClass(LocalObjectMessage.class);
verify(m_messenger).send(eq(32L), // A fixed number set in setUpOnce()
captor.capture());
assertTrue(captor.getValue().payload instanceof CatalogChangeWork);
}
}
@Test
public void testNegativeUpdateCatalog() throws IOException {
ByteBuffer msg = createMsg("@UpdateApplicationCatalog", new Integer(1), new Long(0));
ClientResponseImpl resp = m_ci.handleRead(msg, m_handler, m_cxn);
// expect an error response from handleRead.
assertNotNull(resp);
assertTrue(resp.getStatus() != 0);
}
/**
* Fake a catalog diff compiler result and send it back to the CI, see if CI
* initiates a new txn.
*/
@Test
public void testFinishedCatalogDiffing() {
CatalogChangeResult catalogResult = new CatalogChangeResult();
catalogResult.clientData = null;
catalogResult.clientHandle = 0;
catalogResult.connectionId = 0;
catalogResult.adminConnection = false;
// catalog change specific boiler plate
catalogResult.catalogHash = "blah".getBytes();
catalogResult.catalogBytes = "blah".getBytes();
catalogResult.deploymentString = "blah";
catalogResult.expectedCatalogVersion = 3;
catalogResult.encodedDiffCommands = "diff";
catalogResult.invocationType = ProcedureInvocationType.REPLICATED;
catalogResult.originalTxnId = 12345678l;
catalogResult.originalUniqueId = 87654321l;
m_ci.processFinishedCompilerWork(catalogResult).run();
ArgumentCaptor<Long> destinationCaptor =
ArgumentCaptor.forClass(Long.class);
ArgumentCaptor<Iv2InitiateTaskMessage> messageCaptor =
ArgumentCaptor.forClass(Iv2InitiateTaskMessage.class);
verify(m_messenger).send(destinationCaptor.capture(), messageCaptor.capture());
Iv2InitiateTaskMessage message = messageCaptor.getValue();
//assertFalse(boolValues.get(0)); // is admin
assertFalse(message.isReadOnly()); // readonly
assertFalse(message.isSinglePartition()); // single-part
//assertFalse(boolValues.get(3)); // every site
assertEquals("@UpdateApplicationCatalog", message.getStoredProcedureName());
assertEquals("diff", message.getStoredProcedureInvocation().getParameterAtIndex(0));
assertTrue(Arrays.equals("blah".getBytes(), (byte[]) message.getStoredProcedureInvocation().getParameterAtIndex(2)));
assertEquals(3, message.getStoredProcedureInvocation().getParameterAtIndex(3));
assertEquals("blah", message.getStoredProcedureInvocation().getParameterAtIndex(4));
assertEquals(ProcedureInvocationType.REPLICATED, message.getStoredProcedureInvocation().getType());
assertEquals(12345678l, message.getStoredProcedureInvocation().getOriginalTxnId());
assertEquals(87654321l, message.getStoredProcedureInvocation().getOriginalUniqueId());
}
@Test
public void testUserProc() throws Exception {
ByteBuffer msg = createMsg("hello", 1);
StoredProcedureInvocation invocation =
readAndCheck(msg, "hello", 1, true, true).getStoredProcedureInvocation();
assertEquals(1, invocation.getParameterAtIndex(0));
}
@Test
public void testGC() throws Exception {
ByteBuffer msg = createMsg("@GC");
ClientResponseImpl resp = m_ci.handleRead(msg, m_handler, m_cxn);
assertNull(resp);
ByteBuffer b = responses.take();
resp = new ClientResponseImpl();
b.position(4);
resp.initFromBuffer(b);
assertEquals(ClientResponse.SUCCESS, resp.getStatus());
VoltTable vt = resp.getResults()[0];
assertTrue(vt.advanceRow());
//System.gc() should take at least a little time
assertTrue(resp.getResults()[0].getLong(0) > 10000);
}
@Test
public void testSystemInformation() throws Exception {
ByteBuffer msg = createMsg("@SystemInformation");
ClientResponseImpl resp = m_ci.handleRead(msg, m_handler, m_cxn);
assertNull(resp);
verify(m_sysinfoAgent).performOpsAction(any(Connection.class), anyInt(), eq(OpsSelector.SYSTEMINFORMATION),
any(ParameterSet.class));
}
/**
* DR stats is not a txn, it goes to the stats agent directly.
* @throws Exception
*/
@Test
public void testDRStats() throws Exception {
ByteBuffer msg = createMsg("@Statistics", "DR", 0);
ClientResponseImpl resp = m_ci.handleRead(msg, m_handler, m_cxn);
assertNull(resp);
assertEquals(drStatsInvoked, 1);
}
@Test
public void testLoadSinglePartTable() throws Exception {
VoltTable table = new VoltTable(new ColumnInfo("i", VoltType.INTEGER));
table.addRow(1);
byte[] partitionParam = {0, 0, 0, 0, 0, 0, 0, 4};
ByteBuffer msg = createMsg("@LoadSinglepartitionTable", partitionParam, "a", table);
readAndCheck(msg, "@LoadSinglepartitionTable", partitionParam, false, true);
}
@Test
public void testPausedMode() throws IOException {
// pause the node
when(m_volt.getMode()).thenReturn(OperationMode.PAUSED);
ByteBuffer msg = createMsg("hello", 1);
ClientResponseImpl resp = m_ci.handleRead(msg, m_handler, m_cxn);
assertNotNull(resp);
assertEquals(ClientResponse.SERVER_UNAVAILABLE, resp.getStatus());
when(m_volt.getMode()).thenReturn(OperationMode.RUNNING);
}
@Test
public void testInvalidProcedure() throws IOException {
ByteBuffer msg = createMsg("hellooooo", 1);
ClientResponseImpl resp = m_ci.handleRead(msg, m_handler, m_cxn);
assertNotNull(resp);
assertEquals(ClientResponse.UNEXPECTED_FAILURE, resp.getStatus());
}
@Test
public void testAdminProcsOnNonAdminPort() throws IOException {
ByteBuffer msg = createMsg("@Pause");
ClientResponseImpl resp = m_ci.handleRead(msg, m_handler, m_cxn);
assertNotNull(resp);
assertEquals(ClientResponse.UNEXPECTED_FAILURE, resp.getStatus());
msg = createMsg("@Resume");
resp = m_ci.handleRead(msg, m_handler, m_cxn);
assertNotNull(resp);
assertEquals(ClientResponse.UNEXPECTED_FAILURE, resp.getStatus());
}
@Test
public void testRejectDupInvocation() throws IOException {
// by default, the mock initiator returns false for createTransaction()
ByteBuffer msg = createMsg(12345l, "hello", 1);
ClientResponseImpl resp = m_ci.handleRead(msg, m_handler, m_cxn);
assertNotNull(resp);
assertEquals(ClientResponse.UNEXPECTED_FAILURE, resp.getStatus());
}
@Test
public void testPolicyRejection() throws IOException {
// incorrect parameters to @AdHoc proc
ByteBuffer msg = createMsg("@AdHoc", 1, 3, 3);
ClientResponseImpl resp = m_ci.handleRead(msg, m_handler, m_cxn);
assertNotNull(resp);
assertEquals(ClientResponse.GRACEFUL_FAILURE, resp.getStatus());
}
@Test
public void testPromoteWithoutCommandLogging() throws Exception {
final ByteBuffer msg = createMsg("@Promote");
m_ci.handleRead(msg, m_handler, m_cxn);
// Verify that the truncation request node was not created.
verify(m_zk, never()).create(eq(VoltZK.request_truncation_snapshot), any(byte[].class),
eq(Ids.OPEN_ACL_UNSAFE), eq(CreateMode.PERSISTENT));
}
@Test
public void testPromoteWithCommandLogging() throws Exception {
org.voltdb.catalog.CommandLog logConfig = m_context.cluster.getLogconfig().get("log");
boolean wasEnabled = logConfig.getEnabled();
logConfig.setEnabled(true);
try {
final ByteBuffer msg = createMsg("@Promote");
m_ci.handleRead(msg, m_handler, m_cxn);
// Verify that the truncation request node was created.
verify(m_zk, never()).create(eq(VoltZK.request_truncation_snapshot), any(byte[].class),
eq(Ids.OPEN_ACL_UNSAFE), eq(CreateMode.PERSISTENT));
}
finally {
logConfig.setEnabled(wasEnabled);
}
}
@Test
public void testTransactionRestart() throws Exception {
initMsgAndSendRestartResp(true);
}
@Test
public void testTransactionRestartIgnored() throws Exception {
// fake operation mode as command log recovery so that it won't restart the txn
doReturn(OperationMode.INITIALIZING).when(m_volt).getMode();
initMsgAndSendRestartResp(false);
}
private void initMsgAndSendRestartResp(boolean shouldRestart) throws Exception
{
// restart will update the hashinator config, initialize it now
TheHashinator.constructHashinator(TheHashinator.getConfiguredHashinatorClass(),
TheHashinator.getConfigureBytes(3),
false);
Pair<Long, byte[]> hashinatorConfig = TheHashinator.getCurrentVersionedConfig();
long newHashinatorVersion = hashinatorConfig.getFirst() + 1;
ByteBuffer msg = createMsg("hello", 1);
Iv2InitiateTaskMessage initMsg = readAndCheck(msg, "hello", 1, true, true);
assertEquals(1, initMsg.getStoredProcedureInvocation().getParameterAtIndex(0));
// fake a restart response
InitiateResponseMessage respMsg = new InitiateResponseMessage(initMsg);
respMsg.setMispartitioned(true, initMsg.getStoredProcedureInvocation(),
Pair.of(newHashinatorVersion, hashinatorConfig.getSecond()));
// reset the message so that we can check for restart later
reset(m_messenger);
// Deliver a restart response
m_ci.m_mailbox.deliver(respMsg);
// Make sure that the txn is NOT restarted
DeferredSerialization resp = responsesDS.take();
if (shouldRestart) {
assertEquals(-1, resp.getSerializedSize());
checkInitMsgSent("hello", 1, true, true);
} else {
assertTrue(-1 != resp.getSerializedSize());
verify(m_messenger, never()).send(anyLong(), any(VoltMessage.class));
}
// the hashinator should've been updated in either case
assertEquals(newHashinatorVersion, TheHashinator.getCurrentVersionedConfig().getFirst().longValue());
}
@Test
public void testGetPartitionKeys() throws IOException {
//Unsupported type
ByteBuffer msg = createMsg("@GetPartitionKeys", "BIGINT");
ClientResponseImpl resp = m_ci.handleRead(msg, m_handler, m_cxn);
assertNotNull(resp);
assertEquals(ClientResponse.GRACEFUL_FAILURE, resp.getStatus());
//Null param
msg = createMsg("@GetPartitionKeys", new Object[] { null });
resp = m_ci.handleRead(msg, m_handler, m_cxn);
assertNotNull(resp);
assertEquals(ClientResponse.GRACEFUL_FAILURE, resp.getStatus());
//Empty string param
msg = createMsg("@GetPartitionKeys", "");
resp = m_ci.handleRead(msg, m_handler, m_cxn);
assertNotNull(resp);
assertEquals(ClientResponse.GRACEFUL_FAILURE, resp.getStatus());
//Junk string
msg = createMsg("@GetPartitionKeys", "ryanlikestheyankees");
resp = m_ci.handleRead(msg, m_handler, m_cxn);
assertNotNull(resp);
assertEquals(ClientResponse.GRACEFUL_FAILURE, resp.getStatus());
//No param
msg = createMsg("@GetPartitionKeys");
resp = m_ci.handleRead(msg, m_handler, m_cxn);
assertNotNull(resp);
assertEquals(ClientResponse.GRACEFUL_FAILURE, resp.getStatus());
//Extra param
msg = createMsg("@GetPartitionKeys", "INTEGER", 99);
resp = m_ci.handleRead(msg, m_handler, m_cxn);
assertNotNull(resp);
assertEquals(ClientResponse.GRACEFUL_FAILURE, resp.getStatus());
//Correct param with no case sensitivity
msg = createMsg("@GetPartitionKeys", "InTeGeR");
resp = m_ci.handleRead(msg, m_handler, m_cxn);
assertNotNull(resp);
assertEquals(ClientResponse.SUCCESS, resp.getStatus());
VoltTable vt = resp.getResults()[0];
assertEquals(3, vt.getRowCount());
assertEquals(VoltType.INTEGER, vt.getColumnType(1));
Set<Integer> partitions = new HashSet<Integer>(Arrays.asList( 0, 1, 2));
while (vt.advanceRow()) {
int partition = TheHashinator.getPartitionForParameter(VoltType.INTEGER.getValue(), vt.getLong(1));
assertTrue(partitions.remove(partition));
}
assertTrue(partitions.isEmpty());
}
@Test
public void testSubscribe() throws Exception {
RateLimitedClientNotifier.WARMUP_MS = 0;
ClientInterface.TOPOLOGY_CHANGE_CHECK_MS = 1;
try {
m_ci.startAcceptingConnections();
ByteBuffer msg = createMsg("@Subscribe", "TOPOLOGY");
ClientResponseImpl resp = m_ci.handleRead(msg, m_handler, m_cxn);
assertNotNull(resp);
assertEquals(ClientResponse.SUCCESS, resp.getStatus());
statsAnswers.offer(dsOf(getClientResponse("foo")));
m_ci.schedulePeriodicWorks();
//Shouldn't get anything
assertNull(responsesDS.poll(50, TimeUnit.MILLISECONDS));
//Change the bytes of the topology results and expect a topology update
//to make its way to the client
ByteBuffer expectedBuf = getClientResponse("bar");
statsAnswers.offer(dsOf(expectedBuf));
DeferredSerialization ds = responsesDS.take();
ByteBuffer actualBuf = ByteBuffer.allocate(ds.getSerializedSize());
ds.serialize(actualBuf);
assertEquals(expectedBuf, actualBuf);
} finally {
RateLimitedClientNotifier.WARMUP_MS = 1000;
ClientInterface.TOPOLOGY_CHANGE_CHECK_MS = 5000;
m_ci.shutdown();
}
}
private DeferredSerialization dsOf(final ByteBuffer buf) {
return new DeferredSerialization() {
@Override
public void serialize(final ByteBuffer outbuf) throws IOException {
outbuf.put(buf);
}
@Override
public void cancel() {}
@Override
public int getSerializedSize() {
return buf.remaining();
}
};
}
public ByteBuffer getClientResponse(String str) {
ClientResponseImpl response = new ClientResponseImpl(ClientResponse.SUCCESS,
new VoltTable[0], str, ClientInterface.ASYNC_TOPO_HANDLE);
ByteBuffer buf = ByteBuffer.allocate(response.getSerializedSize() + 4);
buf.putInt(buf.capacity() - 4);
response.flattenToBuffer(buf);
buf.flip();
return buf;
}
}
|
package org.voltdb.utils;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import junit.framework.TestCase;
import org.voltdb.ServerThread;
import org.voltdb.VoltDB;
import org.voltdb.VoltDB.Configuration;
import org.voltdb.VoltTable;
import org.voltdb.client.Client;
import org.voltdb.client.ClientFactory;
import org.voltdb.compiler.VoltProjectBuilder;
public class TestCSVLoader extends TestCase {
private String pathToCatalog;
private String pathToDeployment;
private ServerThread localServer;
private VoltDB.Configuration config;
private VoltProjectBuilder builder;
private Client client;
private String userHome = System.getProperty("user.home");
private String reportdir = userHome + "/";
String path_csv = userHome + "/" + "test.csv";
@Override
protected void setUp() throws Exception
{
super.setUp();
}
public void testCommon() throws Exception
{
String mySchema =
"create table BLAH (" +
"clm_integer integer default 0 not null, " + // column that is partitioned on
"clm_tinyint tinyint default 0, " +
"clm_smallint smallint default 0, " +
"clm_bigint bigint default 0, " +
"clm_string varchar(10) default null, " +
"clm_decimal decimal default null, " +
"clm_float float default null "+ // for later
//"clm_timestamp timestamp default null, " + // for later
//"clm_varinary varbinary default null" + // for later
"); ";
String []myOptions = {
"--file=" + userHome + "/test.csv",
//"--procedure=BLAH.insert",
"--reportdir=" + reportdir,
"--table=BLAH",
"--maxerrors=50",
"--user=",
"--password=",
"--port=",
"--strictquotes=true"
};
String []myData = { "1,1,1,11111111,first,1.10,1.11",
"2,2,2,222222,second,3.30,NULL",
"3,3,3,333333, third ,NULL, 3.33",
"4,4,4,444444, NULL ,4.40 ,4.44",
"5,5,5,5555555, fifth, 5.50, 5.55",
"6,6,NULL,666666, sixth, 6.60, 6.66",
"7,NULL,7,7777777, seventh, 7.70, 7.77 ",
"11, 1,1,\"1,000\",first,1.10,1.11",
//invalid lines below
"8, 8",
"",
"10,10,10,10 101 010,second,2.20,2.22",
"12,n ull,12,12121212,twelveth,12.12,12.12"
};
int invalidLineCnt = 4;
test_Interface( mySchema, myOptions, myData, invalidLineCnt );
test_Interface_lineByLine( mySchema, 7, myOptions, myData, invalidLineCnt );
}
/*
public void testNew() throws Exception
{
String mySchema =
"create table BLAH (" +
"clm_integer integer default 0 not null, " + // column that is partitioned on
// "clm_tinyint tinyint default 0, " +
// "clm_smallint smallint default 0, " +
// "clm_bigint bigint default 0, " +
//
// "clm_string varchar(10) default null, " +
// "clm_decimal decimal default null, " +
// "clm_float float default null "+ // for later
"clm_timestamp timestamp default null, " + // for later
//"clm_varinary varbinary default null" + // for later
"); ";
String []myOptions = {
"--inputfile=" + userHome + "/test.csv",
//"--procedurename=BLAH.insert",
"--reportdir=" + reportdir,
"--tablename=BLAH",
"--abortfailurecount=50",
};
String []myData = { "1,1111111111",
"2,12131231231"
};
int invalidLineCnt = 0;
test_Interface( mySchema, myOptions, myData, invalidLineCnt );
}
*/
//csvloader --inputfile=/tmp/ --tablename=VOTES --abortfailurecount=50
// public void testOptions() throws Exception
// String mySchema =
// "create table BLAH (" +
// "clm_integer integer default 0 not null, " + // column that is partitioned on
// "clm_tinyint tinyint default 0, " +
// String []myOptions = {
// "--inputfile=" + userHome + "/test.csv",
// //"--procedurename=BLAH.insert",
// "--reportdir=" + reportdir,
// "--tablename=BLAH",
// "--abortfailurecount=50",
// //"--separator=','"
// String []myData = { "1,1,1,11111111,first,1.10,1.11",
// "10,10,10,10 101 010,second,2.20,2.22",
// "2,2,2,222222,second,3.30,null",
// "3,3,3,333333, third ,NULL, 3.33",
// "4,4,4,444444, null ,4.40 ,4.44",
// "5,5,5,5555555, fifth, 5.50, 5.55",
// "6,6,null,666666, sixth, 6.60, 6.66",
// "7,null,7,7777777, seventh, 7.70, 7.77 ",
// "11, 1,1,\"1,000\",first,1.10,1.11",
// "8, 8",
// "12,n ull,12,12121212,twelveth,12.12,12.12"
// int invalidLineCnt = 3;
// test_Interface( mySchema, myOptions, myData, invalidLineCnt );
// public void testDelimeters () throws Exception
// simpleSchema =
// "create table BLAH (" +
// "clm_integer integer default 0 not null, " + // column that is partitioned on
// "clm_tinyint tinyint default 0, " +
// //"clm_smallint smallint default 0, " +
// //"clm_bigint bigint default 0, " +
// // "clm_string varchar(10) default null, " +
// //"clm_decimal decimal default null, " +
// //"clm_float float default 1.0, "+ // for later
// //"clm_timestamp timestamp default null, " + // for later
// //"clm_varinary varbinary default null" + // for later
// char str = '.';
// String []params = {
// //userHome + "/testdb.csv",
// "--inputfile=" + userHome + "/test.csv",
// //"--procedurename=BLAH.insert",
// "--reportdir=" + reportdir,
// "--tablename=BLAH",
// "--abortfailurecount=50",
// "--separator=",""
// String []myData = {"1, 1","","2, 2"};
// test_Interface( params, myData );
/*
public void testSimple() throws Exception {
simpleSchema =
"create table BLAH (" +
"clm_integer integer default 0 not null, " + // column that is partitioned on
"clm_tinyint tinyint default 0, " +
//"clm_smallint smallint default 0, " +
//"clm_bigint bigint default 0, " +
//"clm_string varchar(10) default null, " +
//"clm_decimal decimal default null, " +
//"clm_float float default 1.0, "+ // for later
//"clm_timestamp timestamp default null, " + // for later
//"clm_varinary varbinary default null" + // for later
"); ";
String []params_simple = {
//"--inputfile=" + userHome + "/testdb.csv",
//"--procedurename=BLAH.insert",
//"--reportdir=" + reportdir,
//"--tablename=BLAH",
//"--abortfailurecount=50",
"-help"
};
try {
CSVLoader.main(params_simple);
// do the test
VoltTable modCount;
modCount = client.callProcedure("@AdHoc", "SELECT * FROM BLAH;").getResults()[0];
System.out.println("data inserted to table BLAH:\n" + modCount);
int rowct = modCount.getRowCount();
BufferedReader csvreport = new BufferedReader(new FileReader(new String(reportdir + CSVLoader.reportfile)));
int lineCount = 0;
String line = "";
String promptMsg = "Number of acknowledged tuples:";
while ((line = csvreport.readLine()) != null) {
if (line.startsWith(promptMsg)) {
String num = line.substring(promptMsg.length());
lineCount = Integer.parseInt(num.replaceAll("\\s",""));
break;
}
}
System.out.println(String.format("The rows infected: (%d,%s)", lineCount, rowct));
assertEquals(lineCount, rowct);
CSVLoader.flush();
}
finally {
if (client != null) client.close();
client = null;
if (localServer != null) {
localServer.shutdown();
localServer.join();
}
localServer = null;
// no clue how helpful this is
System.gc();
}
}
*/
public void test_Interface( String my_schema, String[] my_options, String[] my_data, int invalidLineCnt ) throws Exception {
try{
BufferedWriter out_csv = new BufferedWriter( new FileWriter( path_csv ) );
for( int i = 0; i < my_data.length; i++ )
out_csv.write( my_data[ i ]+"\n" );
out_csv.flush();
out_csv.close();
}
catch( Exception e) {
System.err.print( e.getMessage() );
}
try{
pathToCatalog = Configuration.getPathToCatalogForTest("csv.jar");
pathToDeployment = Configuration.getPathToCatalogForTest("csv.xml");
builder = new VoltProjectBuilder();
//builder.addStmtProcedure("Insert", "insert into blah values (?, ?, ?);", null);
//builder.addStmtProcedure("InsertWithDate", "INSERT INTO BLAH VALUES (974599638818488300, 5, 'nullchar');");
builder.addLiteralSchema(my_schema);
builder.addPartitionInfo("BLAH", "clm_integer");
boolean success = builder.compile(pathToCatalog, 2, 1, 0);
assertTrue(success);
MiscUtils.copyFile(builder.getPathToDeployment(), pathToDeployment);
config = new VoltDB.Configuration();
config.m_pathToCatalog = pathToCatalog;
config.m_pathToDeployment = pathToDeployment;
localServer = new ServerThread(config);
client = null;
localServer.start();
localServer.waitForInitialization();
client = ClientFactory.createClient();
client.createConnection("localhost");
CSVLoader.main( my_options );
// do the test
VoltTable modCount;
modCount = client.callProcedure("@AdHoc", "SELECT * FROM BLAH;").getResults()[0];
System.out.println("data inserted to table BLAH:\n" + modCount);
int rowct = modCount.getRowCount();
BufferedReader csvreport = new BufferedReader(new FileReader(CSVLoader.path_reportfile));
int lineCount = 0;
String line = "";
String promptMsg = "Number of acknowledged tuples:";
String promptFailMsg = "Number of failed tuples:";
int invalidlinecnt = 0;
while ((line = csvreport.readLine()) != null) {
if (line.startsWith(promptMsg)) {
String num = line.substring(promptMsg.length());
lineCount = Integer.parseInt(num.replaceAll("\\s",""));
}
if( line.startsWith(promptFailMsg)){
String num = line.substring(promptFailMsg.length());
invalidlinecnt = Integer.parseInt(num.replaceAll("\\s",""));
}
}
System.out.println(String.format("The rows infected: (%d,%s)", lineCount, rowct));
//assertEquals(lineCount, rowct);
assertEquals(invalidLineCnt, invalidlinecnt);
}
finally {
if (client != null) client.close();
client = null;
if (localServer != null) {
localServer.shutdown();
localServer.join();
}
localServer = null;
// no clue how helpful this is
System.gc();
}
}
public void test_Interface_lineByLine( String my_schema, int columnCnt, String[] my_options, String[] my_data, int invalidLineCnt ) throws Exception {
try{
BufferedWriter out_csv = new BufferedWriter( new FileWriter( path_csv ) );
for( int i = 0; i < my_data.length; i++ )
out_csv.write( my_data[ i ]+"\n" );
out_csv.flush();
out_csv.close();
}
catch( Exception e) {
System.err.print( e.getMessage() );
}
try{
pathToCatalog = Configuration.getPathToCatalogForTest("csv.jar");
pathToDeployment = Configuration.getPathToCatalogForTest("csv.xml");
builder = new VoltProjectBuilder();
//builder.addStmtProcedure("Insert", "insert into blah values (?, ?, ?);", null);
//builder.addStmtProcedure("InsertWithDate", "INSERT INTO BLAH VALUES (974599638818488300, 5, 'nullchar');");
builder.addLiteralSchema(my_schema);
builder.addPartitionInfo("BLAH", "clm_integer");
boolean success = builder.compile(pathToCatalog, 2, 1, 0);
assertTrue(success);
MiscUtils.copyFile(builder.getPathToDeployment(), pathToDeployment);
config = new VoltDB.Configuration();
config.m_pathToCatalog = pathToCatalog;
config.m_pathToDeployment = pathToDeployment;
localServer = new ServerThread(config);
client = null;
localServer.start();
localServer.waitForInitialization();
client = ClientFactory.createClient();
client.createConnection("localhost");
new CSVLoader( my_options );
while( CSVLoader.readNext() )
{
String [] addStr= null;
CSVLoader.insertLine( addStr, columnCnt );
}
CSVLoader.drain();
CSVLoader.produceFiles();
CSVLoader.flush();
// do the test
VoltTable modCount;
modCount = client.callProcedure("@AdHoc", "SELECT * FROM BLAH;").getResults()[0];
System.out.println("data inserted to table BLAH:\n" + modCount);
int rowct = modCount.getRowCount();
BufferedReader csvreport = new BufferedReader(new FileReader(CSVLoader.path_reportfile));
int lineCount = 0;
String line = "";
String promptMsg = "Number of acknowledged tuples:";
String promptFailMsg = "Number of failed tuples:";
int invalidlinecnt = 0;
while ((line = csvreport.readLine()) != null) {
if (line.startsWith(promptMsg)) {
String num = line.substring(promptMsg.length());
lineCount = Integer.parseInt(num.replaceAll("\\s",""));
}
if( line.startsWith(promptFailMsg)){
String num = line.substring(promptFailMsg.length());
invalidlinecnt = Integer.parseInt(num.replaceAll("\\s",""));
}
}
System.out.println(String.format("The rows infected: (%d,%s)", lineCount, rowct));
assertEquals(invalidLineCnt,invalidlinecnt);
}
finally {
if (client != null) client.close();
client = null;
if (localServer != null) {
localServer.shutdown();
localServer.join();
}
localServer = null;
// no clue how helpful this is
System.gc();
}
}
}
|
package org.voltdb.utils;
import java.io.FileReader;
import org.voltdb.ServerThread;
import org.voltdb.VoltDB;
import org.voltdb.VoltTable;
import org.voltdb.VoltDB.Configuration;
import org.voltdb.VoltType;
import org.voltdb.client.Client;
import org.voltdb.client.ClientFactory;
import org.voltdb.compiler.VoltProjectBuilder;
import au.com.bytecode.opencsv_voltpatches.CSVReader;
import junit.framework.TestCase;
public class TestCSVLoader extends TestCase {
public void testSimple() throws Exception {
String simpleSchema =
"create table BLAH (" +
"clm_integer integer default 0 not null, " + // column that is partitioned on
"clm_tinyint tinyint default 0, " +
"clm_smallint smallint default 0, " +
"clm_bigint bigint default 0, " +
"clm_string varchar(10) default null, " +
"clm_decimal decimal default null, " +
//"clm_float float default 1.0, " + // for later
//"clm_timestamp timestamp default null, " + // for later
//"clm_varinary varbinary default null" + // for later
"); ";
String pathToCatalog = Configuration.getPathToCatalogForTest("csv.jar");
String pathToDeployment = Configuration.getPathToCatalogForTest("csv.xml");
VoltProjectBuilder builder = new VoltProjectBuilder();
builder.addLiteralSchema(simpleSchema);
builder.addPartitionInfo("BLAH", "clm_integer");
//builder.addStmtProcedure("Insert", "insert into blah values (?, ?, ?);", null);
//builder.addStmtProcedure("InsertWithDate", "INSERT INTO BLAH VALUES (974599638818488300, 5, 'nullchar');");
boolean success = builder.compile(pathToCatalog, 2, 1, 0);
assertTrue(success);
MiscUtils.copyFile(builder.getPathToDeployment(), pathToDeployment);
VoltDB.Configuration config = new VoltDB.Configuration();
config.m_pathToCatalog = pathToCatalog;
config.m_pathToDeployment = pathToDeployment;
ServerThread localServer = new ServerThread(config);
Client client = null;
try {
localServer.start();
localServer.waitForInitialization();
String []params = {"/Users/xinjia/testdb.csv","BLAH.insert"};
//String []params = {"/Users/xinjia/testdb.csv","Insert","--columns", "0,2,1"};
CSVLoader.main(params);
// do the test
client = ClientFactory.createClient();
client.createConnection("localhost");
final CSVReader reader = new CSVReader(new FileReader(params[0]));
int lineCount = 0;
while (reader.readNext() != null) {
lineCount++;
}
VoltTable modCount;
modCount = client.callProcedure("@AdHoc", "SELECT COUNT(*) FROM BLAH;").getResults()[0];
int rowct = 0;
while(modCount.advanceRow()) {
rowct = (Integer) modCount.get(0, VoltType.INTEGER);
}
System.out.println(String.format("The rows infected: (%d,%s)", lineCount, rowct));
assertEquals(lineCount, rowct);
modCount = client.callProcedure("@AdHoc", "SELECT * FROM BLAH;").getResults()[0];
System.out.println("data inserted to table BLAH:\n" + modCount);
}
finally {
if (client != null) client.close();
client = null;
if (localServer != null) {
localServer.shutdown();
localServer.join();
}
localServer = null;
// no clue how helpful this is
System.gc();
}
}
}
|
package net.maizegenetics.gbs.pipeline;
import java.awt.Frame;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import javax.swing.ImageIcon;
import net.maizegenetics.util.ArgsEngine;
import net.maizegenetics.pal.alignment.MutableNucleotideAlignment;
import net.maizegenetics.pal.alignment.Alignment;
import net.maizegenetics.pal.alignment.AlignmentUtils;
import net.maizegenetics.pal.alignment.ExportUtils;
import net.maizegenetics.pal.alignment.ImportUtils;
import net.maizegenetics.pal.alignment.MutableVCFAlignment;
import net.maizegenetics.pal.ids.IdGroup;
import net.maizegenetics.pal.ids.Identifier;
import net.maizegenetics.pal.ids.SimpleIdGroup;
import net.maizegenetics.plugindef.AbstractPlugin;
import net.maizegenetics.plugindef.DataSet;
import net.maizegenetics.util.VCFUtil;
import org.apache.log4j.Logger;
/**
* Basic filters needed for removing bad sites and taxa from GBS pipelines
* @author edbuckler
*/
public class MergeIdenticalTaxaPlugin extends AbstractPlugin {
int startChromosome = 1, endChromosome = 10;
private ArgsEngine myArgsEngine = null;
private static final Logger myLogger = Logger.getLogger(MergeIdenticalTaxaPlugin.class);
private String suppliedInputFileName, suppliedOutputFileName, infile, outfile;
private double majorityRule = 0.8;
private boolean makeHetCalls = true;
String[] lowCoverageTaxa = null;
private static enum INPUT_FORMAT {hapmap, vcf}; //input file format, acceptable values are "hapmap" "vcf"
private INPUT_FORMAT inputFormat = INPUT_FORMAT.hapmap;
private int myMaxNumAlleles;
public MergeIdenticalTaxaPlugin() {
super(null, false);
}
public MergeIdenticalTaxaPlugin(Frame parentFrame) {
super(parentFrame, false);
}
@Override
public DataSet performFunction(DataSet input) {
for (int chr = startChromosome; chr <= endChromosome; chr++) {
infile = suppliedInputFileName.replace("+", "" + chr);
outfile = suppliedOutputFileName.replace("+", "" + chr);
myLogger.info("Reading: " + infile);
Alignment a = null;
if (inputFormat == INPUT_FORMAT.hapmap)
{
try {
a = ImportUtils.readFromHapmap(infile, this);
} catch (Exception e) {
myLogger.info("Could not read input hapmap file for chr" + chr + ":\n\t" + infile + "\n\tSkipping...");
continue;
}
}
else if (inputFormat == INPUT_FORMAT.vcf)
{
try {
a = ImportUtils.readFromVCF(infile, this, myMaxNumAlleles);
} catch (Exception e) {
myLogger.info("Could not read input vcf file for chr" + chr + ":\n\t" + infile + "\n\tSkipping...");
continue;
}
}
else
{
throw new IllegalArgumentException("File format " + inputFormat + " is not recognized!");
}
myLogger.info("Original Alignment Taxa:" + a.getSequenceCount() + " Sites:" + a.getSiteCount());
AlignmentFilterByGBSUtils.getErrorRateForDuplicatedTaxa(a, true, false, true);
IdGroup idg = a.getIdGroup();
TreeMap<String, List<String>> sortedIds2 = new TreeMap<String, List<String>>();
int uniqueTaxa = 0;
for (int i = 0; i < idg.getIdCount(); i++) {
List<String> l = sortedIds2.get(idg.getIdentifier(i).getName());
if (l == null) {
sortedIds2.put(idg.getIdentifier(i).getName(), l = new ArrayList<String>());
uniqueTaxa++;
}
l.add(idg.getIdentifier(i).getFullName());
}
IdGroup newGroup = new SimpleIdGroup(uniqueTaxa);
int index = 0;
for (List<String> l : sortedIds2.values()) {
if (l.size() > 1) {
newGroup.setIdentifier(index, new Identifier(l.get(0).split(":")[0] + ":MERGE"));
System.out.println("To be merged: " + l.size() + ": " + l);
} else {
newGroup.setIdentifier(index, new Identifier(l.get(0)));
}
//System.out.println(newGroup.getIdentifier(index).getFullName());
index++;
}
System.out.println("Total taxa:" + idg.getIdCount());
System.out.println("Unique taxa:" + uniqueTaxa);
//MutableNucleotideAlignment theMSA = new MutableNucleotideAlignment(newGroup, a.getSiteCount(), a.getLoci());
MutableNucleotideAlignment theMSA = null;
if (inputFormat == INPUT_FORMAT.hapmap){
theMSA = MutableNucleotideAlignment.getInstance(newGroup, a.getSiteCount());
}
else if (inputFormat == INPUT_FORMAT.vcf){
theMSA = MutableVCFAlignment.getInstance(newGroup, a.getSiteCount(),newGroup.getIdCount(), a.getSiteCount(), myMaxNumAlleles);
}
for (int s = 0; s < a.getSiteCount(); s++) {
theMSA.setLocusOfSite(s, a.getLocus(s));
theMSA.setPositionOfSite(s, a.getPositionInLocus(s));
if (inputFormat == INPUT_FORMAT.vcf){
theMSA.setReferenceAllele(s, a.getReferenceAllele(s));
theMSA.setCommonAlleles(s, a.getAllelesByScope(Alignment.ALLELE_SCOPE_TYPE.Depth, s));
}
//theMSA.setSitePrefix(s, (byte) a.getSNPID(s).charAt(0));
//theMSA.setStrandOfSite(s, (byte) 1);
}
System.out.printf("MergeLine Number Scored PropScored HetSites PropHets%n");
int newTaxon = -1;
byte[] calls = null;
for (Map.Entry<String, List<String>> entry : sortedIds2.entrySet()) {
if (inputFormat == INPUT_FORMAT.hapmap)
{
if (entry.getValue().size() > 1) {
calls = consensusCalls(a, entry.getValue(), makeHetCalls, majorityRule);
newTaxon = theMSA.getIdGroup().whichIdNumber(entry.getValue().get(0).split(":")[0] + ":MERGE");
} else {
int oldTaxon = a.getIdGroup().whichIdNumber(entry.getValue().get(0));
calls = a.getBaseRange(oldTaxon, 0, a.getSiteCount() - 1);
newTaxon = theMSA.getIdGroup().whichIdNumber(entry.getValue().get(0));
}
for (int s = 0; s < a.getSiteCount(); s++) {
theMSA.setBase(newTaxon, s, calls[s]);
}
if (entry.getValue().size() > 1) {
int known = 0, hets = 0;
for (int s = 0; s < a.getSiteCount(); s++) {
byte cb = theMSA.getBase(newTaxon, s);
if (cb != Alignment.UNKNOWN_DIPLOID_ALLELE) {
known++;
}
if (AlignmentUtils.isHeterozygous(cb)) {
hets++;
}
}
double pctK = (double) known / (double) a.getSiteCount();
double pctH = (double) hets / (double) a.getSiteCount();
System.out.printf("%s %d %d %.3g %d %.3g %n", entry.getKey(), entry.getValue().size(), known, pctK, hets, pctH);
}
}
else if (inputFormat == INPUT_FORMAT.vcf){
if (entry.getValue().size() > 1){
newTaxon = theMSA.getIdGroup().whichIdNumber(entry.getValue().get(0).split(":")[0] + ":MERGE");
List<String> taxa = entry.getValue();
//the return result is a two day array result[x][y]
//y: site index
//x: x=0: genotype calling; x=1 to max: allele depth
byte[][] genotypeAndDepth = consensusCallsForVCF(a, taxa, myMaxNumAlleles);
for (int s = 0; s < a.getSiteCount(); s++) {
theMSA.setBase(newTaxon, s, genotypeAndDepth[0][s]);
byte[] mydepth = new byte[theMSA.getAllelesByScope(Alignment.ALLELE_SCOPE_TYPE.Depth, s).length];
for (int al=0; al<mydepth.length; al++)
{
mydepth[al] = genotypeAndDepth[al+1][s];
}
theMSA.setDepthForAlleles(newTaxon, s, mydepth);
}
}
else {
int oldTaxon = a.getIdGroup().whichIdNumber(entry.getValue().get(0));
calls = a.getBaseRange(oldTaxon, 0, a.getSiteCount());
newTaxon = theMSA.getIdGroup().whichIdNumber(entry.getValue().get(0));
for (int s = 0; s < a.getSiteCount(); s++) {
theMSA.setBase(newTaxon, s, calls[s]);
theMSA.setDepthForAlleles(newTaxon, s, a.getDepthForAlleles(oldTaxon, s));
}
}
}
}
if (inputFormat == INPUT_FORMAT.hapmap)
{
ExportUtils.writeToHapmap(theMSA, false, outfile, '\t', this);
}
else if (inputFormat == INPUT_FORMAT.vcf)
{
ExportUtils.writeToVCF(theMSA, outfile, '\t');
}
}
return null;
}
public static byte[] consensusCalls(Alignment a, List<String> taxa, boolean callhets, double majority) {
short[][] siteCnt = new short[2][a.getSiteCount()];
int[] taxaIndex = new int[taxa.size()];
for (int t = 0; t < taxaIndex.length; t++) {
taxaIndex[t] = a.getIdGroup().whichIdNumber(taxa.get(t));
}
byte[] calls = new byte[a.getSiteCount()];
Arrays.fill(calls, Alignment.UNKNOWN_DIPLOID_ALLELE);
for (int s = 0; s < a.getSiteCount(); s++) {
byte mjAllele = a.getMajorAllele(s);
byte mnAllele = a.getMinorAllele(s);
byte mj=AlignmentUtils.getDiploidValue(mjAllele,mjAllele);
byte mn=AlignmentUtils.getDiploidValue(mnAllele,mnAllele);
// byte[] snpValue = {mj, mn};
//byte het = IUPACNucleotides.getDegerateSNPByteFromTwoSNPs(snpValue);
byte het = AlignmentUtils.getUnphasedDiploidValue(mjAllele, mnAllele);
for (int t = 0; t < taxaIndex.length; t++) {
byte ob = a.getBase(taxaIndex[t], s);
if (ob == Alignment.UNKNOWN_DIPLOID_ALLELE) {
continue;
}
if (ob == mj) {
siteCnt[0][s]++;
} else if (ob == mn) {
siteCnt[1][s]++;
} else if (AlignmentUtils.isEqual(ob, het)) {
siteCnt[0][s]++;
siteCnt[1][s]++;
}
}
int totalCnt = siteCnt[0][s] + siteCnt[1][s];
if (totalCnt == 0) {
continue; //no data leave missing
}
if ((double) siteCnt[0][s] / (double) totalCnt > majority) {
calls[s] = mj;
} else if ((double) siteCnt[1][s] / (double) totalCnt > majority) {
calls[s] = mn;
} else if (callhets) {
calls[s] = het;
}
}
return calls;
}
public static byte[][] consensusCallsForVCF (Alignment a, List<String> taxa, int MaxNumAlleles)
{
//the return result is a two day array result[x][y]
//y: site index
//x: x=0: genotype calling; x=1 to max: allele depth
byte[][] result = new byte[MaxNumAlleles+1][a.getSiteCount()];
for (byte[] row: result)
{
Arrays.fill(row, (byte)0);
}
Arrays.fill(result[0], (byte)(-1));
int[] taxaIndex = new int[taxa.size()];
for (int t = 0; t < taxa.size(); t++) {
taxaIndex[t] = a.getIdGroup().whichIdNumber(taxa.get(t));
}
for (int s = 0; s < a.getSiteCount(); s++) {
byte[] alleles = a.getAllelesByScope(Alignment.ALLELE_SCOPE_TYPE.Depth, s);
int[] alleleDepth = new int[alleles.length];
Arrays.fill(alleleDepth, 0);
for (int t = 0; t < taxaIndex.length; t++) {
byte[] myAlleledepth = a.getDepthForAlleles(taxaIndex[t], s);
for (int al=0; al<myAlleledepth.length; al++)
{
alleleDepth[al] += (int)myAlleledepth[al];
}
}
result[0][s] = VCFUtil.resolveVCFGeno(alleles, alleleDepth);
for (int al=0; al<alleles.length; al++){
result[al+1][s] = (byte)(alleleDepth[al]>127?127:alleleDepth[al]);
}
}
return result;
}
private void printUsage() {
myLogger.info(
"Input format:\n"
+ "-hmp Input HapMap file; use a plus sign (+) as a wild card character to "
+ " specify multiple chromosome numbers.\n"
+ "-vcf Input VCF file. Use a plus sign (+) as a wild card character to specify multiple chromosome numbers. Options -hmp and -vcf are mutual exclusive.\n"
+ "-o Output HapMap file; use a plus sign (+) as a wild card character to "
+ " specify multiple chromosome numbers.\n"
+ "-xHet Exclude heterozygotes calls (default: " + makeHetCalls + ")"
+ "-hetFreq Cutoff frequency between het vs. homozygote calls (default: " + majorityRule + ")"
+ "-sC Start chromosome (default 1).\n"
+ "-eC End chromosome (default 10).\n"
+ "-maxAlleleVCF Maximum number of alleles allowed in vcf file.\n");
}
@Override
public void setParameters(String[] args) {
if (args.length == 0) {
printUsage();
throw new IllegalArgumentException("\n\nPlease use the above arguments/options.\n\n");
}
if (myArgsEngine == null) {
myArgsEngine = new ArgsEngine();
myArgsEngine.add("-hmp", "-hmpFile", true);
myArgsEngine.add("-vcf", "-vcfFile", true);
myArgsEngine.add("-o", "--outFile", true);
myArgsEngine.add("-xHets", "--excludeHets", false);
myArgsEngine.add("-hetFreq", "--heterozygoteFreqCutoff", true);
myArgsEngine.add("-sC", "--startChrom", true);
myArgsEngine.add("-eC", "--endChrom", true);
myArgsEngine.add("-maxAlleleVCF", "--maxAlleleVCF", true);
}
myArgsEngine.parse(args);
if (myArgsEngine.getBoolean("-sC")) {
startChromosome = Integer.parseInt(myArgsEngine.getString("-sC"));
} else {
printUsage();
throw new IllegalArgumentException("Please provide a start chromosome.\n");
}
if (myArgsEngine.getBoolean("-eC")) {
endChromosome = Integer.parseInt(myArgsEngine.getString("-eC"));
} else {
printUsage();
throw new IllegalArgumentException("Please provide an end chromosome.\n");
}
if (myArgsEngine.getBoolean("-hmp")) {
if (myArgsEngine.getBoolean("-vcf")){
throw new IllegalArgumentException("-hmp and -vcf options are mutual exclusive!\n");
}
suppliedInputFileName = myArgsEngine.getString("-hmp");
inputFormat = INPUT_FORMAT.hapmap;
} else if (myArgsEngine.getBoolean("-vcf")) {
suppliedInputFileName = myArgsEngine.getString("-vcf");
inputFormat = INPUT_FORMAT.vcf;
}
else {
printUsage();
throw new IllegalArgumentException("Please specify a HapMap file or VCF to merge taxa.\n");
}
if (myArgsEngine.getBoolean("-o")) {
suppliedOutputFileName = myArgsEngine.getString("-o");
} else {
printUsage();
throw new IllegalArgumentException("Please specify an output file name.\n");
}
if (myArgsEngine.getBoolean("-xHets")) {
makeHetCalls = false;
}
if (myArgsEngine.getBoolean("-hetFreq")) {
majorityRule = Double.parseDouble(myArgsEngine.getString("-hetFreq"));
}
if (myArgsEngine.getBoolean("-maxAlleleVCF")) {
if (! myArgsEngine.getBoolean("-vcf")){
throw new IllegalArgumentException("-maxAlleleVCF option only works with -vcf input.\n");
}
myMaxNumAlleles = Integer.parseInt(myArgsEngine.getString("-maxAlleleVCF"));
}
else
{
myMaxNumAlleles = VCFUtil.VCF_DEFAULT_MAX_NUM_ALLELES;
}
}
@Override
public ImageIcon getIcon() {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public String getButtonName() {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public String getToolTipText() {
throw new UnsupportedOperationException("Not supported yet.");
}
}
|
package net.miz_hi.smileessence.listener;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.ListView;
import net.miz_hi.smileessence.notification.Notificator;
import net.miz_hi.smileessence.util.CustomListAdapter;
public class TimelineScrollListener implements OnScrollListener
{
private CustomListAdapter<?> adapter;
public TimelineScrollListener(CustomListAdapter<?> adapter)
{
this.adapter = adapter;
}
@Override
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount)
{
}
@Override
public void onScrollStateChanged(AbsListView view, int scrollState)
{
adapter.setCanNotifyOnChange(false);
if (view.getFirstVisiblePosition() == 0 && view.getChildAt(0) != null && view.getChildAt(0).getTop() == 0)
{
if (scrollState == SCROLL_STATE_IDLE)
{
adapter.setCanNotifyOnChange(true);
int before = adapter.getCount();
adapter.notifyDataSetChanged();
int after = adapter.getCount();
int addCount = after - before;
((ListView) view).setSelectionFromTop(addCount, 0);
if (addCount > 0)
{
adapter.setCanNotifyOnChange(false);
Notificator.info(addCount + "");
}
}
}
}
}
|
package org.apache.cocoon.components.cron;
import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.XStreamException;
import com.thoughtworks.xstream.converters.Converter;
import com.thoughtworks.xstream.converters.MarshallingContext;
import com.thoughtworks.xstream.converters.UnmarshallingContext;
import com.thoughtworks.xstream.converters.extended.ISO8601DateConverter;
import com.thoughtworks.xstream.io.HierarchicalStreamReader;
import com.thoughtworks.xstream.io.HierarchicalStreamWriter;
import com.thoughtworks.xstream.io.xml.DomDriver;
import java.io.File;
import java.io.FileFilter;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.StringWriter;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Comparator;
import java.util.Date;
import java.util.Map;
import java.util.Properties;
import java.util.TimeZone;
import java.util.concurrent.CompletionService;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorCompletionService;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
import org.apache.avalon.framework.CascadingRuntimeException;
import org.apache.avalon.framework.configuration.Configurable;
import org.apache.avalon.framework.configuration.Configuration;
import org.apache.avalon.framework.configuration.ConfigurationException;
import org.apache.avalon.framework.parameters.Parameters;
import org.apache.avalon.framework.service.ServiceException;
import org.apache.cocoon.ProcessingException;
import org.apache.cocoon.components.cron.ConfigurableCronJob;
import org.apache.cocoon.components.cron.ServiceableCronJob;
import org.apache.cocoon.components.source.SourceUtil;
import org.apache.cocoon.environment.CocoonRunnable;
import org.apache.cocoon.xml.XMLUtils;
import org.apache.cocoon.xml.dom.DOMUtil;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.io.filefilter.WildcardFileFilter;
import org.apache.commons.lang.exception.ExceptionUtils;
import org.apache.excalibur.source.Source;
import org.apache.excalibur.source.SourceResolver;
import org.apache.xml.serialize.OutputFormat;
import org.joda.time.DateTime;
import org.w3c.dom.Attr;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.xml.sax.SAXException;
public class QueueProcessorCronJob extends ServiceableCronJob implements Configurable, ConfigurableCronJob {
private static final String PARAMETER_QUEUE_PATH = "queue-path";
private static final String PROCESSOR_STATUS_FILE = "processor-status.xml";
private static final long PROCESSOR_STATUS_FILE_STALE = 1200000;
private static final long TASK_TIMEOUT = 3000000; // 50 min.
private static final String inDirName = "in";
private static final String processingDirName = "in-progress";
private static final String outDirName = "out";
private static final String errorDirName = "error";
private File queuePath;
/**
* An enum denoting the status of a Processor this class).
*/
public enum ProcessorStatus {
ALIVE, DEAD, NONE
}
/**
* Copy job file to outDir, also, zip contents of processingDir into
* "{currentJob-name}.zip" into outDir.
* The zip contains a directory {currentJob-name}, all other files are in
* that directory.
*
* @param processingDir
* @param outDir
* @param currentJob
*/
private void finishUpJob(File processingDir, File outDir, File currentJob) throws IOException {
final String basename = FilenameUtils.getBaseName(currentJob.getName());
final String zipFileName = String.format("%s.zip", basename);
File zipFile = new File(outDir, zipFileName);
final String zipFolder = basename + "/";
if (this.getLogger().isDebugEnabled()) {
this.getLogger().debug("Finishing up job, creating Zip file.");
}
FileUtils.copyFileToDirectory(currentJob, outDir);
try {
// create byte buffer
byte[] buffer = new byte[1024];
FileOutputStream fos = new FileOutputStream(zipFile);
ZipOutputStream zos = new ZipOutputStream(fos);
// add a directory to the new ZIP first
zos.putNextEntry(new ZipEntry(zipFolder));
File[] files = processingDir.listFiles();
for (File file : files) {
FileInputStream fis = new FileInputStream(file);
// begin writing a new ZIP entry, positions the stream to the start of the entry data
zos.putNextEntry(new ZipEntry(zipFolder + file.getName()));
int length;
while ((length = fis.read(buffer)) > 0) {
zos.write(buffer, 0, length);
}
zos.closeEntry();
// close the InputStream
fis.close();
}
// close the ZipOutputStream
zos.close();
} catch (IOException ioe) {
this.getLogger().error("Error creating zip file" + ioe);
}
if (this.getLogger().isDebugEnabled()) {
this.getLogger().debug("Created Zip file.");
}
}
/**
* The object that runs a task.
*/
private class CocoonTaskRunner extends CocoonRunnable {
private final Task task;
private final SourceResolver resolver;
private final org.apache.avalon.framework.logger.Logger logger;
private final OutputStream os;
private final int sequenceNumber;
public CocoonTaskRunner(Task t, SourceResolver resolver, org.apache.avalon.framework.logger.Logger logger, OutputStream os, int sequenceNumber) {
this.task = t;
this.resolver = resolver;
this.logger = logger;
this.os = os;
this.sequenceNumber = sequenceNumber;
}
@Override
public void doRun() {
try {
Document doc = DOMUtil.createDocument();
Element taskNode = doc.createElement("task");
taskNode.setAttribute("id", sequenceNumber + "");
taskNode.setAttribute("uri", task.uri);
taskNode.setAttribute("startedAt", "" + new org.joda.time.DateTime());
Element taskResult = processPipeline(task.uri, resolver, logger, doc);
taskNode.setAttribute("finishedAt", "" + new org.joda.time.DateTime());
taskNode.appendChild(taskResult);
Properties properties = XMLUtils.createPropertiesForXML(true);
writeOutputStream(os, XMLUtils.serializeNode(taskNode, properties));
} catch (ProcessingException ex) {
Logger.getLogger(QueueProcessorCronJob.class.getName()).log(Level.SEVERE, null, ex);
String result = String.format("\n%s\n%s\n%s\n", "<error>", ex.getLocalizedMessage(), "</error>");
writeOutputStream(os, result);
}
}
}
/**
* Process a job: add all tasks to ExecutorService, invokeAll tasks and wait
* until all tasks have finished. While waiting, update
* processor-status.xml.
*
* @param inDir Where all output files are stored.
* @param currentJob The current job file.
*/
private void processCurrentJobConcurrently(File inDir, File currentJob) throws ServiceException, FileNotFoundException, IOException {
if (this.getLogger().isInfoEnabled()) {
this.getLogger().info("Processing job " + currentJob.getAbsoluteFile());
}
if (this.getLogger().isDebugEnabled()) {
this.getLogger().debug("Reading job file.");
}
JobConfig jobConfig = readJobConfig(currentJob);
if (this.getLogger().isDebugEnabled()) {
this.getLogger().debug("Job file read.");
}
int totalTasks = jobConfig.tasks.length;
int completedTasks = 0;
DateTime jobStartedAt = new DateTime();
writeProcessorStatus(jobConfig.name, jobStartedAt, totalTasks, completedTasks);
int availableProcessors = Runtime.getRuntime().availableProcessors();
int maxConcurrent = jobConfig.maxConcurrent;
int maxThreads = 1; // default nr of threads
if (maxConcurrent <= 0) {
// If negative, add to availableProcessors, but of course,
// use at least one thread.
maxThreads = availableProcessors + maxConcurrent;
if (maxThreads < 1) {
maxThreads = 1;
}
} else {
// Use specified maximum, but only if it is no more than what's
// available.
maxThreads = maxConcurrent;
if (maxConcurrent > availableProcessors) {
maxThreads = availableProcessors;
}
}
ExecutorService threadPool = Executors.newFixedThreadPool(maxThreads);
if (this.getLogger().isInfoEnabled()) {
this.getLogger().info("Using " + maxThreads + " threads to execute " + totalTasks + " tasks.");
}
CompletionService<CocoonTaskRunner> jobExecutor = new ExecutorCompletionService<CocoonTaskRunner>(threadPool);
SourceResolver resolver = (SourceResolver) this.manager.lookup(SourceResolver.ROLE);
File outputFile = new File(inDir, "task-results.xml");
OutputStream os = new FileOutputStream(outputFile);
writeOutputStream(os, String.format("<tasks job-id=\"%s\" job-name=\"%s\">", jobConfig.id, jobConfig.name));
int submittedTasks = 0;
for (Task t : jobConfig.tasks) {
CocoonTaskRunner taskRunner = new CocoonTaskRunner(t, resolver, this.getLogger(), os, ++submittedTasks);
jobExecutor.submit(taskRunner, taskRunner);
}
if (this.getLogger().isDebugEnabled()) {
this.getLogger().debug("Submitted " + submittedTasks + " tasks.");
}
boolean interrupted = false;
threadPool.shutdown(); // Means: process all tasks.
while (!threadPool.isTerminated() && !interrupted && completedTasks < totalTasks) {
Future<CocoonTaskRunner> f = null;
try {
if (this.getLogger().isDebugEnabled()) {
this.getLogger().debug("Retrieving next finished task.");
}
f = jobExecutor.poll(TASK_TIMEOUT, TimeUnit.MILLISECONDS);
if (null == f) {
this.getLogger().error("Failed getting next finished task (TASK_TIMEOUT (=" + TASK_TIMEOUT + ")), quitting.");
interrupted = true;
} else {
if (this.getLogger().isDebugEnabled()) {
this.getLogger().debug("Got finished task.");
}
Object o = f.get();
}
} catch (ExecutionException eex) {
this.getLogger().error("Received ExecutionException for task, ignoring, continuing with other tasks: ex = " + eex.getMessage());
} catch (InterruptedException iex) {
this.getLogger().error("Received InterruptedException, quitting executing tasks.");
interrupted = true;
break;
} catch (CascadingRuntimeException ex) {
this.getLogger().error("Received CascadingRuntimeException, ignoring, continuing with other tasks.");
}
completedTasks++;
if (this.getLogger().isInfoEnabled()) {
this.getLogger().info("Tasks completed: " + completedTasks + "/" + totalTasks);
}
writeProcessorStatus(jobConfig.name, jobStartedAt, totalTasks, completedTasks);
}
if (interrupted) {
threadPool.shutdownNow();
}
writeOutputStream(os, "</tasks>");
os.close();
this.manager.release(resolver);
}
/**
* Process the URL in one Task. All errors are caught, if one task goes bad
* continue processing the others.
*
* @param url URL to fetch
* @param manager Cocoon servicemanager (so cocoon: protocol is allowed.)
* @param logger For logging stuff
* @param os Where the output ends up.
* @return the output as a String object
*/
private Element processPipeline(String url,
SourceResolver resolver,
org.apache.avalon.framework.logger.Logger logger,
Document doc) {
Source src = null;
InputStream is = null;
Element node = null;
try {
if (logger.isDebugEnabled()) {
logger.debug("Going to resolve " + url);
}
src = resolver.resolveURI(url);
if (logger.isDebugEnabled()) {
logger.debug("Resolved " + url);
}
Document srcDoc = SourceUtil.toDOM(src);
Node srcNode = srcDoc.getFirstChild();
node = (Element)doc.importNode(srcNode, true);
} catch (Exception ex) {
node = doc.createElement("task-error");
node.appendChild(doc.createTextNode(ex.getLocalizedMessage()));
} finally {
try {
if (null != is) {
is.close();
}
} catch (IOException ex) {
Logger.getLogger(QueueProcessorCronJob.class.getName()).log(Level.SEVERE, null, ex);
} finally {
if (null != src) {
resolver.release(src);
src = null;
}
}
}
return node;
}
/**
* Check if there's a job in the processingDir. If yes then abstain if
* Processor = ALIVE, remove it otherwise. If No then move oldest job to
* processingDir, process that job.
*/
private void processQueue() throws IOException {
/*
Create subdirs if necessary.
*/
File queueDir = getOrCreateDirectory(this.queuePath, "");
File inDir = getOrCreateDirectory(queueDir, inDirName);
File processingDir = getOrCreateDirectory(queueDir, processingDirName);
File outDir = getOrCreateDirectory(queueDir, outDirName);
File errorDir = getOrCreateDirectory(queueDir, errorDirName);
// Get status of Processor
QueueProcessorCronJob.ProcessorStatus pStatus = processorStatus();
File currentJobFile = getOldestJobFile(processingDir);
if (this.getLogger().isDebugEnabled()) {
this.getLogger().debug(String.format("Processor: %s, queueDir=%s, current job: %s", pStatus, queueDir, currentJobFile));
}
// A job is already being processed
if (null != currentJobFile) {
/*
* A job is processed by a live Processor -> quit now.
*/
if (pStatus.equals(QueueProcessorCronJob.ProcessorStatus.ALIVE)) {
if (this.getLogger().isDebugEnabled()) {
this.getLogger().debug(String.format("Active job \"%s\" in queue \"%s\", stopping", currentJobFile, queueDir));
}
} else {
/*
* A job was processed, but the Processor is dead.
* Move job tot error-folder. Clean processing folder.
*/
this.getLogger().warn(String.format("Stale job \"%s\" in queue \"%s\", cancelling job and stopping", currentJobFile, queueDir));
moveFileTo(currentJobFile, new File(errorDir, currentJobFile.getName()));
FileUtils.cleanDirectory(processingDir);
}
} else {
// No job being processed.
File jobFile = getOldestJobFile(inDir);
if (jobFile != null) {
String jobFileName = jobFile.getName();
File currentJob = new File(processingDir, jobFileName);
try {
FileUtils.cleanDirectory(processingDir);
writeProcessorStatus(jobFileName, new DateTime(), 0, 0);
if (this.getLogger().isDebugEnabled()) {
this.getLogger().debug(String.format("Processing job \"%s\" in queue \"%s\"", jobFileName, queueDir));
}
moveFileTo(jobFile, currentJob);
if (this.getLogger().isDebugEnabled()) {
this.getLogger().debug(String.format("Moved job \"%s\" to \"%s\"", jobFile, currentJob));
}
processCurrentJobConcurrently(processingDir, currentJob);
finishUpJob(processingDir, outDir, currentJob);
} catch (Exception e) { // Catch IOException AND catch ClassCast exception etc.
this.getLogger().error("Error processing job \"" + jobFileName + "\"", e);
moveFileTo(currentJob, new File(errorDir, jobFileName));
String stackTrace = ExceptionUtils.getFullStackTrace(e);
FileUtils.writeStringToFile(new File(errorDir, FilenameUtils.removeExtension(jobFileName) + ".txt"), stackTrace, "UTF-8");
} finally {
FileUtils.cleanDirectory(processingDir);
deleteProcessorStatus();
}
} else {
if (this.getLogger().isDebugEnabled()) {
this.getLogger().debug("No job, stopping");
}
}
}
}
/**
* Main entrypoint for CronJob.
*
* @param name
*/
@Override
public void execute(String name) {
if (this.getLogger().isDebugEnabled()) {
this.getLogger().debug("CronJob " + name + " launched at " + new Date());
}
try {
processQueue();
} catch (IOException e) {
throw new CascadingRuntimeException("CronJob " + name + " raised an exception.", e);
}
}
@SuppressWarnings("rawtypes")
@Override
public void setup(Parameters params, Map objects) {
return;
}
/**
* Get path to queue folder.
*
* @param config
* @throws ConfigurationException
*/
@Override
public void configure(final Configuration config) throws ConfigurationException {
String actualQueuesDirName = config.getChild(PARAMETER_QUEUE_PATH).getValue();
queuePath = new File(actualQueuesDirName);
}
/**
* Read job description file into JobConfig object using XStream.
*
* @param currentJob
* @return JobConfig
*/
private JobConfig readJobConfig(File currentJob) throws XStreamException {
XStream xstream = getXStreamJobConfig();
JobConfig jobConfig = (JobConfig) xstream.fromXML(currentJob);
return jobConfig;
}
/**
* Return NONE (No processor), ALIVE (Processor still active) or DEAD
* (Processor hasn't updated status file for too long).
*
* @return ProcessorStatus: NONE, ALIVE or DEAD.
*/
private synchronized ProcessorStatus processorStatus() {
File statusFile = new File(this.queuePath, PROCESSOR_STATUS_FILE);
if (!statusFile.exists()) {
return QueueProcessorCronJob.ProcessorStatus.NONE;
} else {
long lastModified = statusFile.lastModified();
if (System.currentTimeMillis() - lastModified > PROCESSOR_STATUS_FILE_STALE) {
return QueueProcessorCronJob.ProcessorStatus.DEAD;
} else {
return QueueProcessorCronJob.ProcessorStatus.ALIVE;
}
}
}
/**
* We're done, delete status file.
*/
private synchronized void deleteProcessorStatus() {
File pStatusFile = new File(this.queuePath, PROCESSOR_STATUS_FILE);
pStatusFile.delete();
}
/**
* Update status file.
*
* @param jobName
* @param started
* @param totalTasks
* @param completedTasks
* @param currentTaskStartedAt
*/
private synchronized void writeProcessorStatus(String jobName, DateTime started, int totalTasks, int completedTasks) {
File pStatusFile = new File(this.queuePath, PROCESSOR_STATUS_FILE);
String status = String.format("<processor id=\"%s\" job-name=\"%s\" started=\"%s\" tasks=\"%d\" tasks-completed=\"%d\"/>",
Thread.currentThread().getId(),
jobName,
started.toString(),
totalTasks,
completedTasks);
try {
FileUtils.writeStringToFile(pStatusFile, status, "UTF-8");
} catch (IOException ex) {
Logger.getLogger(QueueProcessorCronJob.class.getName()).log(Level.SEVERE, null, ex);
}
}
/**
* Return File object for parent/path, creating it if necessary.
*
* @param parent
* @param path
* @return Resulting File object.
*/
private File getOrCreateDirectory(File parent, String path) {
File dir = new File(parent, path);
if (!dir.exists()) {
dir.mkdirs();
}
return dir;
}
/**
* Move file from one File object to another File object, deleting an
* already existing file if necessary.
*
* @param fromFile
* @param toFile
* @throws IOException
*/
private void moveFileTo(File fromFile, File toFile) throws IOException {
if (toFile.isFile()) {
FileUtils.forceDelete(toFile);
}
if (!fromFile.renameTo(toFile)) {
this.getLogger().error(String.format("Could not move file \"%s\" to \"%s\"", fromFile.getAbsolutePath(), toFile.getAbsoluteFile()));
}
}
/**
* Get oldest job (file named "job-*.xml") in dir, using lastModified
* timestamp and picking first File if there is more than one file with the
* same lastModified.
*
* @param dir
* @return
*/
protected File getOldestJobFile(File dir) {
if (dir == null || !dir.isDirectory()) {
return null;
}
File[] files = dir.listFiles((FileFilter) new WildcardFileFilter("job-*.xml"));
if (files.length == 0) {
return null;
}
Arrays.sort(files, new Comparator<File>() {
public int compare(File file1, File file2) {
return Long.valueOf(file1.lastModified()).compareTo(file2.lastModified());
}
});
return files[0];
}
private void writeOutputStream(OutputStream os, String msg) {
// synchronized (os) {
try {
os.write(msg.getBytes());
} catch (IOException ex) {
Logger.getLogger(QueueProcessorCronJob.class.getName()).log(Level.SEVERE, null, ex);
}
}
/**
* Classes used by XStream for loading the job-*.xml config files into.
*/
public static class Task {
public String id;
public String uri;
public Task() {
}
}
public static class JobConfig {
// <job id="id" name="job name" description="job description"
// created="datetime" max-concurrent="n">tasks...</job>
public String id;
public String name;
public String description;
public Date created;
public Integer maxConcurrent;
public Task[] tasks;
public JobConfig() {
}
}
/**
* Set some XStream options to configure serialization.
* @return The configured XStream object.
*/
public static XStream getXStreamJobConfig() {
// <job id="..." name="test-job" created="20140613T11:45:00" max-concurrent="3" description="...">
// <tasks>
// <task id="task-1">
// </task>
// </job>
XStream xstream = new XStream(new DomDriver());
// ISO8601DateConverter
xstream.registerConverter(new ISO8601DateConverter());
xstream.alias("job", JobConfig.class);
xstream.useAttributeFor(JobConfig.class, "id");
xstream.useAttributeFor(JobConfig.class, "name");
xstream.useAttributeFor(JobConfig.class, "description");
xstream.useAttributeFor(JobConfig.class, "created");
xstream.useAttributeFor(JobConfig.class, "maxConcurrent");
xstream.aliasField("max-concurrent", JobConfig.class, "maxConcurrent");
xstream.alias("task", Task.class);
xstream.useAttributeFor(Task.class, "id");
return xstream;
}
public static class JodaTimeConverter implements Converter {
@Override
@SuppressWarnings("unchecked")
public boolean canConvert(final Class type) {
return DateTime.class.isAssignableFrom(type);
}
@Override
public void marshal(Object source, HierarchicalStreamWriter writer, MarshallingContext context) {
writer.setValue(source.toString());
}
@Override
@SuppressWarnings("unchecked")
public Object unmarshal(HierarchicalStreamReader reader,
UnmarshallingContext context) {
return new DateTime(reader.getValue());
}
}
}
|
package org.jetbrains.plugins.scala.compiler;
import com.intellij.compiler.OutputParser;
import com.intellij.compiler.impl.javaCompiler.FileObject;
import com.intellij.openapi.compiler.CompilerMessageCategory;
import com.intellij.openapi.vfs.LocalFileSystem;
import com.intellij.openapi.vfs.VirtualFileManager;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import static org.jetbrains.plugins.scala.compiler.ScalacOutputParser.MESSAGE_TYPE.*;
import java.io.File;
import java.util.ArrayList;
import java.util.Set;
import java.util.HashSet;
import java.util.Arrays;
/**
* @author ilyas
*/
class ScalacOutputParser extends OutputParser {
@NonNls
private static final String ourErrorMarker = " error:";
@NonNls
private static final String ourWarningMarker = " warning:";
@NonNls
private static final String ourInfoMarkerStart = "[";
@NonNls
private static final String ourInfoMarkerEnd = "]";
@NonNls
private static final String ourWroteMarker = "wrote ";
@NonNls
private static final String ourColumnMarker = "^";
@NonNls
private static final String ourParsingMarker = "parsing ";
@NonNls
private static final String ourScalaInternalErrorMsg = "Scalac internal error";
// Phases
@NonNls
private static final String PHASE = "running phase ";
@NonNls
private static final String PARSER_ON = "parser on ";
@NonNls
private static Set<String> PHASES = new HashSet<String>();
static {
PHASES.addAll(Arrays.asList(
"parser", "namer", "typer", "superaccessors", "pickler", "refchecks", "liftcode",
"uncurry", "tailcalls", "explicitouter", "cleanup", "total", "inliner", "jvm",
"closelim", "inliner", "dce", "mixin", "flatten", "constructors", "erasure", "lazyvals",
"lambdalift"
));
}
private boolean mustProcessMsg = false;
private boolean fullCrash = false;
private boolean stopProcessing = false;
private int myMsgColumnMarker;
private MESSAGE_TYPE myMsgType = PLAIN;
private ArrayList<String> myWrittenList = new ArrayList<String>();
private final Object WRITTEN_LIST_LOCK = new Object();
static enum MESSAGE_TYPE {
ERROR, WARNING, PLAIN
}
private Integer myLineNumber;
private String myMessage;
private String myUrl;
@Override
public boolean processMessageLine(Callback callback) {
final String line = callback.getNextLine();
if (line == null) {
flushWrittenList(callback);
return false;
}
String text = line.trim();
if (fullCrash && text.length( ) > 0) {
callback.message(CompilerMessageCategory.ERROR, text, "", 0, 0);
return true;
}
if (text.endsWith("\r\n")) text = text.substring(0, text.length() - 2);
if (text.startsWith(ourScalaInternalErrorMsg)) {
callback.message(CompilerMessageCategory.ERROR, text, "", 0, 0);
fullCrash = true;
return true;
}
// Add error message to output
if (myMessage != null && stopMsgProcessing(text) && (mustProcessMsg || stopProcessing)) {
myMsgColumnMarker = myMsgColumnMarker > 0 ? myMsgColumnMarker : 1;
if (myMsgType == ERROR) {
callback.message(CompilerMessageCategory.ERROR, myMessage, myUrl, myLineNumber, myMsgColumnMarker);
} else if (myMsgType == WARNING) {
callback.message(CompilerMessageCategory.WARNING, myMessage, myUrl, myLineNumber, myMsgColumnMarker);
}
myMessage = null;
myMsgType = PLAIN;
mustProcessMsg = false;
stopProcessing = false;
}
if (text.indexOf(ourErrorMarker) > 0) { // new error occurred
processErrorMesssage(text, text.indexOf(ourErrorMarker), ERROR, callback);
} else if (text.indexOf(ourWarningMarker) > 0) {
processErrorMesssage(text, text.indexOf(ourWarningMarker), WARNING, callback);
} else if (!text.startsWith(ourInfoMarkerStart)) { // continuing process [error | warning] message
if (mustProcessMsg) {
if (ourColumnMarker.equals(text.trim())) {
myMsgColumnMarker = line.indexOf(ourColumnMarker) + 1;
stopProcessing = true;
} else if (myMessage != null) {
if (myMsgType != WARNING) {
myMessage += "\n" + text;
}
} else {
mustProcessMsg = false;
}
}
} else { //verbose compiler output
mustProcessMsg = false;
if (text.endsWith(ourInfoMarkerEnd)) {
String info = text.substring(ourInfoMarkerStart.length(), text.length() - ourInfoMarkerEnd.length());
if (info.startsWith(ourParsingMarker)) { //parsing
callback.setProgressText(info);
// Set file processed
callback.fileProcessed(info.substring(info.indexOf(ourParsingMarker) + ourParsingMarker.length()));
}
//add phases and their times to output
else if (getPhaseName(info) != null) {
callback.setProgressText("Phase " + getPhaseName(info) + " passed" + info.substring(getPhaseName(info).length()));
} else if (info.startsWith("loaded")) {
if (info.startsWith("loaded class file ")) { // Loaded file
final int end = info.indexOf(".class") + ".class".length();
final int begin = info.substring(0, end - 1).lastIndexOf("/") + 1;
callback.setProgressText("Loaded file " + info.substring(begin, end));
} else if (info.startsWith("loaded directory path ")) {
final int end = info.indexOf(".jar") + ".jar".length();
final int begin = info.substring(0, end - 1).lastIndexOf("/") + 1;
callback.setProgressText("Loaded directory path " + info.substring(begin, end));
}
// callback.setProgressText("Loading files...");
} else if (info.startsWith(ourWroteMarker)) {
callback.setProgressText(info);
String outputPath = info.substring(ourWroteMarker.length());
final String path = outputPath.replace(File.separatorChar, '/');
// callback.fileGenerated(path);
synchronized (WRITTEN_LIST_LOCK) {
myWrittenList.add(path);
}
}
}
}
return true;
}
private static String getPhaseName(@NotNull String st) {
for (String phase : PHASES) {
if (st.startsWith(phase + " ")) return phase;
}
return null;
}
public void flushWrittenList(Callback callback) {
synchronized (WRITTEN_LIST_LOCK) {
//ensure that all "written" files are really written
for (String s : myWrittenList) {
File out = new File(s);
callback.fileGenerated(new FileObject(out));
}
myWrittenList.clear();
}
}
private boolean stopMsgProcessing(String text) {
return text.startsWith(ourInfoMarkerStart) && !text.trim().equals(ourColumnMarker) ||
text.indexOf(ourErrorMarker) > 0 ||
text.indexOf(ourWarningMarker) > 0 ||
stopProcessing;
}
/*
Collect information about error occurrence
*/
private void processErrorMesssage(String text, int errIndex, MESSAGE_TYPE msgType, Callback callback) {
String errorPlace = text.substring(0, errIndex);
if (errorPlace.endsWith(":"))
errorPlace = errorPlace.substring(0, errorPlace.length() - 1); //hack over compiler output
int j = errorPlace.lastIndexOf(':');
if (j > 0) {
myUrl = VirtualFileManager.constructUrl(LocalFileSystem.PROTOCOL, errorPlace.substring(0, j).replace(File.separatorChar, '/'));
try {
myLineNumber = Integer.valueOf(errorPlace.substring(j + 1, errorPlace.length()));
myMessage = text.substring(errIndex + 1).trim();
mustProcessMsg = true;
myMsgType = msgType;
} catch (NumberFormatException e) {
callback.message(CompilerMessageCategory.INFORMATION, "", text, -1, -1);
myMessage = null;
mustProcessMsg = false;
myMsgType = PLAIN;
}
} else {
callback.message(CompilerMessageCategory.INFORMATION, "", text, -1, -1);
myMsgType = PLAIN;
}
}
public boolean isTrimLines() {
return false;
}
}
|
package main.java.elegit;
import org.eclipse.jgit.api.Git;
import org.eclipse.jgit.api.TransportCommand;
import org.eclipse.jgit.transport.UsernamePasswordCredentialsProvider;
import org.junit.After;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import java.io.File;
import java.io.FileWriter;
import java.io.PrintWriter;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.NoSuchElementException;
import java.util.Scanner;
import static org.junit.Assert.*;
public class AuthenticatedCloneTest {
private Path directoryPath;
private String testFileLocation;
@Before
public void setUp() throws Exception {
this.directoryPath = Files.createTempDirectory("unitTestRepos");
directoryPath.toFile().deleteOnExit();
testFileLocation = System.getProperty("user.home") + File.separator +
"elegitTests" + File.separator;
}
@After
public void tearDown() throws Exception {
}
@Test
public void testCloneHttpNoPassword() throws Exception {
Path repoPath = directoryPath.resolve("testrepo");
// Clone from dummy repo:
String remoteURL = "https://github.com/TheElegitTeam/TestRepository.git";
ClonedRepoHelper helper = new ClonedRepoHelper(repoPath, remoteURL);
assertNotNull(helper);
}
@Test
public void testLsHttpNoPassword() throws Exception {
TransportCommand command =
Git.lsRemoteRepository().setRemote("https://github.com/TheElegitTeam/TestRepository.git");
command.call();
}
/* The httpUsernamePassword should contain three lines, containing:
repo http(s) address
username
password
*/
@Test
public void testHttpUsernamePassword() throws Exception {
Path repoPath = directoryPath.resolve("testrepo");
File authData = new File(testFileLocation + "httpUsernamePassword.txt");
// If a developer does not have this file present, test should just pass.
if (!authData.exists())
return;
Scanner scanner = new Scanner(authData);
String remoteURL = scanner.next();
String username = scanner.next();
String password = scanner.next();
UsernamePasswordCredentialsProvider credentials = new UsernamePasswordCredentialsProvider(username, password);
ClonedRepoHelper helper = new ClonedRepoHelper(repoPath, remoteURL, credentials);
helper.fetch();
Path fileLocation = repoPath.resolve("README.md");
System.out.println(fileLocation);
FileWriter fw = new FileWriter(fileLocation.toString(), true);
fw.write("1");
fw.close();
helper.addFilePath(fileLocation);
helper.commit("Appended to file");
helper.pushAll();
helper.pushTags();
}
@Test
public void testLshHttpUsernamePasswordPublic() throws Exception {
testLsHttpUsernamePassword("httpUsernamePassword.txt");
}
@Test
public void testLshHttpUsernamePasswordPrivate() throws Exception {
testLsHttpUsernamePassword("httpUsernamePasswordPrivate.txt");
}
public void testLsHttpUsernamePassword(String filename) throws Exception {
File authData = new File(testFileLocation + filename);
// If a developer does not have this file present, test should just pass.
if (!authData.exists())
return;
Scanner scanner = new Scanner(authData);
String remoteURL = scanner.next();
String username = scanner.next();
String password = scanner.next();
UsernamePasswordCredentialsProvider credentials = new UsernamePasswordCredentialsProvider(username, password);
TransportCommand command = Git.lsRemoteRepository().setRemote(remoteURL);
RepoHelper.wrapAuthentication(command, credentials);
command.call();
}
/* The sshPassword should contain two lines:
repo ssh address
password
*/
@Test
public void testLsSshPassword() throws Exception {
Path repoPath = directoryPath.resolve("testrepo");
File authData = new File(testFileLocation + "sshPassword.txt");
// If a developer does not have this file present, test should just pass.
if (!authData.exists())
return;
Scanner scanner = new Scanner(authData);
String remoteURL = scanner.next();
String password = scanner.next();
TransportCommand command = Git.lsRemoteRepository().setRemote(remoteURL);
RepoHelper.wrapAuthentication(command, password);
command.call();
}
@Rule
public ExpectedException exception = ExpectedException.none();
@Test
public void testSshPassword() throws Exception {
Path repoPath = directoryPath.resolve("testrepo");
File authData = new File(testFileLocation + "sshPassword.txt");
// If a developer does not have this file present, test should just pass.
if (!authData.exists())
return;
Scanner scanner = new Scanner(authData);
String remoteURL = scanner.next();
String password = scanner.next();
ClonedRepoHelper helper = new ClonedRepoHelper(repoPath, remoteURL, password);
helper.fetch();
helper.pushAll();
helper.pushTags();
SessionModel sm = SessionModel.getSessionModel();
String pathname = repoPath.toString();
assertEquals(sm.getAuthPref(pathname), AuthMethod.SSHPASSWORD);
assertNotEquals(sm.getAuthPref(pathname), AuthMethod.HTTPS);
sm.removeAuthPref(pathname);
exception.expect(NoSuchElementException.class);
exception.expectMessage("AuthPref not present");
sm.getAuthPref(pathname);
}
}
|
package rapanui.core;
import java.util.Collection;
import java.util.List;
import java.util.function.IntFunction;
import java.util.function.BiConsumer;
class Patterns {
public static <T> boolean addToSet(Collection<T> set, T item) {
if (!set.contains(item)) {
set.add(item);
return true;
}
return false;
}
public static <T> boolean removeWithCheck(Collection<T> collection, T item) {
if (collection.contains(item)) {
collection.remove(item);
return true;
}
return false;
}
public static <T> boolean removeWithCheck(List<T> collection, int index) {
if (0 <= index && index < collection.size()) {
collection.remove(index);
return true;
}
return false;
}
public static <T> T[] listToArray(Collection<T> collection, IntFunction<T[]> constructor) {
return collection.toArray(constructor.apply(collection.size()));
}
public static <TObserver, TArgument> void notifyObservers(
Iterable<TObserver> observers,
BiConsumer<TObserver, TArgument> listeningMethod,
TArgument argument) {
assert observers != null;
assert listeningMethod != null;
for (TObserver observer : observers) {
if (observer != null)
listeningMethod.accept(observer, argument);
}
}
}
|
package grakn.core.server.rpc;
import brave.ScopedSpan;
import brave.Span;
import brave.propagation.TraceContext;
import com.google.common.util.concurrent.ThreadFactoryBuilder;
import grakn.benchmark.lib.instrumentation.ServerTracing;
import grakn.core.api.Transaction.Type;
import grakn.core.concept.Concept;
import grakn.core.concept.ConceptId;
import grakn.core.concept.Label;
import grakn.core.concept.thing.Attribute;
import grakn.core.concept.type.AttributeType;
import grakn.core.concept.type.EntityType;
import grakn.core.concept.type.RelationType;
import grakn.core.concept.type.Role;
import grakn.core.concept.type.Rule;
import grakn.core.protocol.SessionProto;
import grakn.core.protocol.SessionProto.Transaction;
import grakn.core.protocol.SessionServiceGrpc;
import grakn.core.server.deduplicator.AttributeDeduplicatorDaemon;
import grakn.core.server.exception.TransactionException;
import grakn.core.server.session.SessionImpl;
import grakn.core.server.session.TransactionOLTP;
import graql.lang.Graql;
import graql.lang.pattern.Pattern;
import graql.lang.query.GraqlQuery;
import io.grpc.Status;
import io.grpc.stub.StreamObserver;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.annotation.Nullable;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Stream;
/**
* Grakn RPC Session Service
*/
public class SessionService extends SessionServiceGrpc.SessionServiceImplBase {
private final OpenRequest requestOpener;
private final Map<String, SessionImpl> openSessions;
private AttributeDeduplicatorDaemon attributeDeduplicatorDaemon;
private Set<TransactionListener> transactionListenerSet;
public SessionService(OpenRequest requestOpener, AttributeDeduplicatorDaemon attributeDeduplicatorDaemon) {
this.requestOpener = requestOpener;
this.attributeDeduplicatorDaemon = attributeDeduplicatorDaemon;
this.openSessions = new HashMap<>();
this.transactionListenerSet = new HashSet<>();
}
/**
* Close all open transactions, sessions and connections with clients - this is invoked by JVM shutdown hook
*/
public void shutdown(){
transactionListenerSet.forEach(transactionListener -> transactionListener.close(null));
transactionListenerSet.clear();
openSessions.values().forEach(SessionImpl::close);
}
@Override
public StreamObserver<Transaction.Req> transaction(StreamObserver<Transaction.Res> responseSender) {
TransactionListener transactionListener = new TransactionListener(responseSender, attributeDeduplicatorDaemon, openSessions);
transactionListenerSet.add(transactionListener);
return transactionListener;
}
@Override
public void open(SessionProto.Session.Open.Req request, StreamObserver<SessionProto.Session.Open.Res> responseObserver) {
try {
String keyspace = request.getKeyspace();
SessionImpl session = requestOpener.open(request);
String sessionId = keyspace + UUID.randomUUID().toString();
openSessions.put(sessionId, session);
responseObserver.onNext(SessionProto.Session.Open.Res.newBuilder().setSessionId(sessionId).build());
responseObserver.onCompleted();
} catch (RuntimeException e) {
responseObserver.onError(ResponseBuilder.exception(e));
}
}
@Override
public void close(SessionProto.Session.Close.Req request, StreamObserver<SessionProto.Session.Close.Res> responseObserver) {
try {
SessionImpl session = openSessions.remove(request.getSessionId());
session.close();
responseObserver.onNext(SessionProto.Session.Close.Res.newBuilder().build());
responseObserver.onCompleted();
} catch (RuntimeException e) {
responseObserver.onError(ResponseBuilder.exception(e));
}
}
/**
* A StreamObserver that implements the transaction-handling behaviour for io.grpc.Server.
* Receives a stream of Transaction.Reqs and returning a stream of Transaction.Ress.
*/
class TransactionListener implements StreamObserver<Transaction.Req> {
final Logger LOG = LoggerFactory.getLogger(TransactionListener.class);
private final StreamObserver<Transaction.Res> responseSender;
private final AtomicBoolean terminated = new AtomicBoolean(false);
private final ExecutorService threadExecutor;
private AttributeDeduplicatorDaemon attributeDeduplicatorDaemon;
private final Map<String, SessionImpl> openSessions;
private final Iterators iterators = new Iterators();
@Nullable
private TransactionOLTP tx = null;
private String sessionId;
TransactionListener(StreamObserver<Transaction.Res> responseSender, AttributeDeduplicatorDaemon attributeDeduplicatorDaemon, Map<String, SessionImpl> openSessions) {
this.responseSender = responseSender;
ThreadFactory threadFactory = new ThreadFactoryBuilder().setNameFormat("transaction-listener-%s").build();
this.threadExecutor = Executors.newSingleThreadExecutor(threadFactory);
this.attributeDeduplicatorDaemon = attributeDeduplicatorDaemon;
this.openSessions = openSessions;
}
private <T> T nonNull(@Nullable T item) {
if (item == null) {
throw ResponseBuilder.exception(Status.FAILED_PRECONDITION);
} else {
return item;
}
}
@Override
public void onNext(Transaction.Req request) {
// !important: this is the gRPC thread
try {
if (ServerTracing.tracingEnabledFromMessage(request)) {
TraceContext receivedTraceContext = ServerTracing.extractTraceContext(request);
Span queueSpan = ServerTracing.createChildSpanWithParentContext("Server receive queue", receivedTraceContext);
queueSpan.start();
queueSpan.tag("childNumber", "0");
// hop context & active Span across thread boundaries
submit(() -> handleRequest(request, queueSpan, receivedTraceContext));
} else {
submit(() -> handleRequest(request));
}
} catch (RuntimeException e) {
close(e);
}
}
@Override
public void onError(Throwable t) {
transactionListenerSet.remove(this);
// This method is invoked when a client abruptly terminates a connection to the server
// so we want to make sure to also close and delete the session to which this transaction is associated to.
SessionImpl session = openSessions.remove(sessionId);
session.close();
close(t);
}
@Override
public void onCompleted() {
transactionListenerSet.remove(this);
close(null);
}
private void handleRequest(Transaction.Req request, Span queueSpan, TraceContext context) {
/* this method variant is only called if tracing is active */
// close the Span from gRPC thread
queueSpan.finish(); // time spent in queue
// create a new scoped span
ScopedSpan span = ServerTracing.startScopedChildSpanWithParentContext("Server handle request", context);
span.tag("childNumber", "1");
handleRequest(request);
}
private void handleRequest(Transaction.Req request) {
switch (request.getReqCase()) {
case OPEN_REQ:
open(request.getOpenReq());
break;
case COMMIT_REQ:
commit();
break;
case QUERY_REQ:
query(request.getQueryReq());
break;
case ITERATE_REQ:
next(request.getIterateReq());
break;
case GETSCHEMACONCEPT_REQ:
getSchemaConcept(request.getGetSchemaConceptReq());
break;
case GETCONCEPT_REQ:
getConcept(request.getGetConceptReq());
break;
case GETATTRIBUTES_REQ:
getAttributes(request.getGetAttributesReq());
break;
case PUTENTITYTYPE_REQ:
putEntityType(request.getPutEntityTypeReq());
break;
case PUTATTRIBUTETYPE_REQ:
putAttributeType(request.getPutAttributeTypeReq());
break;
case PUTRELATIONTYPE_REQ:
putRelationType(request.getPutRelationTypeReq());
break;
case PUTROLE_REQ:
putRole(request.getPutRoleReq());
break;
case PUTRULE_REQ:
putRule(request.getPutRuleReq());
break;
case CONCEPTMETHOD_REQ:
conceptMethod(request.getConceptMethodReq());
break;
default:
case REQ_NOT_SET:
throw ResponseBuilder.exception(Status.INVALID_ARGUMENT);
}
}
public void close(@Nullable Throwable error) {
submit(() -> {
if (tx != null) {
tx.close();
}
});
if (!terminated.getAndSet(true)) {
if (error != null) {
LOG.error("Runtime Exception in RPC TransactionListener: ", error);
responseSender.onError(ResponseBuilder.exception(error));
} else {
responseSender.onCompleted();
}
}
// just in case there's a trailing span, let's close it
if (ServerTracing.tracingActive()) {
ServerTracing.currentSpan().finish();
}
threadExecutor.shutdownNow();
try {
boolean terminated = threadExecutor.awaitTermination(30, TimeUnit.SECONDS);
if (!terminated) {
LOG.warn("Some tasks did not terminate within the timeout period.");
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
private void submit(Runnable runnable) {
try {
threadExecutor.submit(runnable).get();
} catch (ExecutionException e) {
Throwable cause = e.getCause();
assert cause instanceof RuntimeException : "No checked exceptions are thrown, because it's a `Runnable`";
throw (RuntimeException) cause;
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
private void open(Transaction.Open.Req request) {
if (tx != null) {
throw ResponseBuilder.exception(Status.FAILED_PRECONDITION);
}
sessionId = request.getSessionId();
SessionImpl session = openSessions.get(sessionId);
Type type = Type.of(request.getType().getNumber());
if (type != null && type.equals(Type.WRITE)) {
tx = session.transaction().write();
} else if (type != null && type.equals(Type.READ)) {
tx = session.transaction().read();
} else {
throw TransactionException.create("Invalid Transaction Type");
}
Transaction.Res response = ResponseBuilder.Transaction.open();
onNextResponse(response);
}
private void commit() {
/* permanent tracing hooks one method down */
tx().commitAndGetLogs().ifPresent(commitLog ->
commitLog.attributes().forEach((attributeIndex, conceptIds) ->
conceptIds.forEach(id -> attributeDeduplicatorDaemon.markForDeduplication(commitLog.keyspace(), attributeIndex, id))
));
onNextResponse(ResponseBuilder.Transaction.commit());
}
private void query(SessionProto.Transaction.Query.Req request) {
/* permanent tracing hooks, as performance here varies depending on query and what's in the graph */
int parseQuerySpanId = ServerTracing.startScopedChildSpan("Parsing Graql Query");
GraqlQuery query = Graql.parse(request.getQuery());
ServerTracing.closeScopedChildSpan(parseQuerySpanId);
int createStreamSpanId = ServerTracing.startScopedChildSpan("Creating query stream");
Stream<Transaction.Res> responseStream = tx().stream(query, request.getInfer().equals(Transaction.Query.INFER.TRUE)).map(ResponseBuilder.Transaction.Iter::query);
Transaction.Res response = ResponseBuilder.Transaction.queryIterator(iterators.add(responseStream.iterator()));
ServerTracing.closeScopedChildSpan(createStreamSpanId);
onNextResponse(response);
}
private void getSchemaConcept(Transaction.GetSchemaConcept.Req request) {
Concept concept = tx().getSchemaConcept(Label.of(request.getLabel()));
Transaction.Res response = ResponseBuilder.Transaction.getSchemaConcept(concept);
onNextResponse(response);
}
private void getConcept(Transaction.GetConcept.Req request) {
Concept concept = tx().getConcept(ConceptId.of(request.getId()));
Transaction.Res response = ResponseBuilder.Transaction.getConcept(concept);
onNextResponse(response);
}
private void getAttributes(Transaction.GetAttributes.Req request) {
Object value = request.getValue().getAllFields().values().iterator().next();
Collection<Attribute<Object>> attributes = tx().getAttributesByValue(value);
Iterator<Transaction.Res> iterator = attributes.stream().map(ResponseBuilder.Transaction.Iter::getAttributes).iterator();
int iteratorId = iterators.add(iterator);
Transaction.Res response = ResponseBuilder.Transaction.getAttributesIterator(iteratorId);
onNextResponse(response);
}
private void putEntityType(Transaction.PutEntityType.Req request) {
EntityType entityType = tx().putEntityType(Label.of(request.getLabel()));
Transaction.Res response = ResponseBuilder.Transaction.putEntityType(entityType);
onNextResponse(response);
}
private void putAttributeType(Transaction.PutAttributeType.Req request) {
Label label = Label.of(request.getLabel());
AttributeType.DataType<?> dataType = ResponseBuilder.Concept.DATA_TYPE(request.getDataType());
AttributeType<?> attributeType = tx().putAttributeType(label, dataType);
Transaction.Res response = ResponseBuilder.Transaction.putAttributeType(attributeType);
onNextResponse(response);
}
private void putRelationType(Transaction.PutRelationType.Req request) {
RelationType relationType = tx().putRelationType(Label.of(request.getLabel()));
Transaction.Res response = ResponseBuilder.Transaction.putRelationType(relationType);
onNextResponse(response);
}
private void putRole(Transaction.PutRole.Req request) {
Role role = tx().putRole(Label.of(request.getLabel()));
Transaction.Res response = ResponseBuilder.Transaction.putRole(role);
onNextResponse(response);
}
private void putRule(Transaction.PutRule.Req request) {
Label label = Label.of(request.getLabel());
Pattern when = Graql.parsePattern(request.getWhen());
Pattern then = Graql.parsePattern(request.getThen());
Rule rule = tx().putRule(label, when, then);
Transaction.Res response = ResponseBuilder.Transaction.putRule(rule);
onNextResponse(response);
}
private TransactionOLTP tx() {
return nonNull(tx);
}
private void conceptMethod(Transaction.ConceptMethod.Req request) {
Concept concept = nonNull(tx().getConcept(ConceptId.of(request.getId())));
Transaction.Res response = ConceptMethod.run(concept, request.getMethod(), iterators, tx());
onNextResponse(response);
}
private void next(Transaction.Iter.Req iterate) {
int iteratorId = iterate.getId();
Transaction.Res response = iterators.next(iteratorId);
if (response == null) throw ResponseBuilder.exception(Status.FAILED_PRECONDITION);
onNextResponse(response);
}
private void onNextResponse(Transaction.Res response) {
if (ServerTracing.tracingActive()) {
ServerTracing.currentSpan().finish();
}
responseSender.onNext(response);
}
}
/**
* Contains a mutable map of iterators of Transaction.Res for gRPC. These iterators are used for returning
* lazy, streaming responses such as for Graql query results.
*/
class Iterators {
private final AtomicInteger iteratorIdCounter = new AtomicInteger(1);
private final Map<Integer, Iterator<Transaction.Res>> iterators = new ConcurrentHashMap<>();
public int add(Iterator<Transaction.Res> iterator) {
int iteratorId = iteratorIdCounter.getAndIncrement();
iterators.put(iteratorId, iterator);
return iteratorId;
}
public Transaction.Res next(int iteratorId) {
Iterator<Transaction.Res> iterator = iterators.get(iteratorId);
if (iterator == null) return null;
Transaction.Res response;
if (iterator.hasNext()) {
response = iterator.next();
} else {
response = SessionProto.Transaction.Res.newBuilder()
.setIterateRes(SessionProto.Transaction.Iter.Res.newBuilder()
.setDone(true)).build();
stop(iteratorId);
}
return response;
}
public void stop(int iteratorId) {
iterators.remove(iteratorId);
}
}
}
|
package readinstruction;
import java.util.UUID;
public class ReadInstructionBuilder {
private UUID instructionId;
private int readAddress;
private int arrivalTime = 0;
private boolean hasDeadline = false;
public ReadInstructionBuilder withInstructionId(UUID id){
this.instructionId = instructionId;
return this;
}
public ReadInstructionBuilder withReadAddress(int readAddres){
this.readAddress = readAddres;
return this;
}
public ReadInstructionBuilder withArrivalTime(int arrivalTime){
this.arrivalTime = arrivalTime;
return this;
}
public ReadInstructionBuilder withDeadline(){
this.hasDeadline = true;
return this;
}
}
|
package test55;
import java.io.File;
import java.util.concurrent.Executors;
import com.embeddedunveiled.serial.SerialComManager;
import com.embeddedunveiled.serial.SerialComManager.BAUDRATE;
import com.embeddedunveiled.serial.SerialComManager.DATABITS;
import com.embeddedunveiled.serial.SerialComManager.FLOWCONTROL;
import com.embeddedunveiled.serial.SerialComManager.FTPPROTO;
import com.embeddedunveiled.serial.SerialComManager.FTPVAR;
import com.embeddedunveiled.serial.SerialComManager.PARITY;
import com.embeddedunveiled.serial.SerialComManager.STOPBITS;
import com.embeddedunveiled.serial.ftp.ISerialComXmodemProgress;
import com.embeddedunveiled.serial.ftp.SerialComFTPCMDAbort;
class AbortTest implements Runnable {
SerialComFTPCMDAbort abort = null;
public AbortTest(SerialComFTPCMDAbort bb) {
abort = bb;
}
@Override
public void run() {
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("=======ABORTING !======");
abort.abortTransfer();
}
}
// send file from one thread and receive from other using XMODEM checksum protocol
public class Test55 implements ISerialComXmodemProgress {
public static SerialComManager scm = null;
public static String PORT1 = null;
public static String PORT2 = null;
public static String sndtxt1 = null;
public static String sndtxt2 = null;
public static String rcvdiry1 = null;
public static String rcvdiry2 = null;
public static String rcvdiry3 = null;
public static String rcvdiry4 = null;
public static String sndjpg1 = null;
public static String sndjpg2 = null;
public static volatile boolean done = false;
public static Test55 test55 = new Test55();
public static void main(String[] args) {
try {
scm = new SerialComManager();
int osType = scm.getOSType();
if(osType == SerialComManager.OS_LINUX) {
PORT1 = "/dev/ttyUSB0";
PORT2 = "/dev/ttyUSB1";
sndtxt1 = "/home/r/ws-host-uart/ftptest/f1.txt";
rcvdiry1 = "/home/r/ws-host-uart/ftptest/xrf1.txt";
sndtxt2 = "/home/r/ws-host-uart/ftptest/xf2.txt";
rcvdiry2 = "/home/r/ws-host-uart/ftptest/xrf2.txt";
sndjpg1 = "/home/r/ws-host-uart/ftptest/f1.jpg";
rcvdiry3 = "/home/r/ws-host-uart/ftptest/xrf1.jpg";
sndjpg2 = "/home/r/ws-host-uart/ftptest/f2.jpg";
rcvdiry4 = "/home/r/ws-host-uart/ftptest/xrf2.jpg";
}else if(osType == SerialComManager.OS_WINDOWS) {
PORT1 = "COM51";
PORT2 = "COM52";
}else if(osType == SerialComManager.OS_MAC_OS_X) {
PORT1 = "/dev/cu.usbserial-A70362A3";
PORT2 = "/dev/cu.usbserial-A602RDCH";
}else if(osType == SerialComManager.OS_SOLARIS) {
PORT1 = null;
PORT2 = null;
}else{
}
PORT1 = "/dev/pts/4";
PORT2 = "/dev/pts/3";
Executors.newSingleThreadExecutor().execute(new Runnable() {
@Override
public void run() {
try {
long handle1 = scm.openComPort(PORT1, true, true, true);
scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B115200, 0);
scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false);
File[] f = new File[1];
f[0] = new File(sndtxt1);
Thread.sleep(1000);
boolean status1 = scm.sendFile(handle1, f, FTPPROTO.XMODEM, FTPVAR.CHKSUM, true, test55, null);
System.out.println("ASCII MODE sent txt status : " + status1);
done = true;
scm.closeComPort(handle1);
}catch (Exception e) {
e.printStackTrace();
}
}
});
long handle2 = scm.openComPort(PORT2, true, true, true);
scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B115200, 0);
scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false);
boolean status2 = scm.receiveFile(handle2, new File(rcvdiry1), FTPPROTO.XMODEM, FTPVAR.CHKSUM, true, test55, null);
System.out.println("ASCII MODE received status txt : " + status2);
scm.closeComPort(handle2);
while(done == false) {
Thread.sleep(10);
}
System.out.println("\n
done = false;
Executors.newSingleThreadExecutor().execute(new Runnable() {
@Override
public void run() {
try {
long handle3 = scm.openComPort(PORT1, true, true, true);
scm.configureComPortData(handle3, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B115200, 0);
scm.configureComPortControl(handle3, FLOWCONTROL.NONE, 'x', 'x', false, false);
File[] f = new File[1];
f[0] = new File(sndtxt2);
Thread.sleep(1000);
boolean status3 = scm.sendFile(handle3, f, FTPPROTO.XMODEM, FTPVAR.CHKSUM, false, test55, null);
System.out.println("BINARY MODE sent txt status : " + status3);
done = true;
scm.closeComPort(handle3);
}catch (Exception e) {
e.printStackTrace();
}
}
});
long handle4 = scm.openComPort(PORT2, true, true, true);
scm.configureComPortData(handle4, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B115200, 0);
scm.configureComPortControl(handle4, FLOWCONTROL.NONE, 'x', 'x', false, false);
boolean status4 = scm.receiveFile(handle4, new File(rcvdiry2), FTPPROTO.XMODEM, FTPVAR.CHKSUM, false, test55, null);
System.out.println("BINARY MODE received status txt : " + status4);
scm.closeComPort(handle4);
while(done == false) {
Thread.sleep(10);
}
System.out.println("\n
done = false;
Executors.newSingleThreadExecutor().execute(new Runnable() {
@Override
public void run() {
try {
long handle5 = scm.openComPort(PORT1, true, true, true);
scm.configureComPortData(handle5, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B115200, 0);
scm.configureComPortControl(handle5, FLOWCONTROL.NONE, 'x', 'x', false, false);
File[] f = new File[2];
f[0] = new File(sndjpg1);
Thread.sleep(1000);
boolean status5 = scm.sendFile(handle5, f, FTPPROTO.XMODEM, FTPVAR.CHKSUM, false, test55, null);
System.out.println("BINARY MODE sent jpg status : " + status5);
done = true;
scm.closeComPort(handle5);
}catch (Exception e) {
e.printStackTrace();
}
}
});
long handle6 = scm.openComPort(PORT2, true, true, true);
scm.configureComPortData(handle6, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B115200, 0);
scm.configureComPortControl(handle6, FLOWCONTROL.NONE, 'x', 'x', false, false);
boolean status6 = scm.receiveFile(handle6, new File(rcvdiry3), FTPPROTO.XMODEM, FTPVAR.CHKSUM, false, test55, null);
System.out.println("BINARY MODE received status jpg : " + status6);
scm.closeComPort(handle6);
while(done == false) {
Thread.sleep(10);
}
System.out.println("\n
done = false;
Executors.newSingleThreadExecutor().execute(new Runnable() {
@Override
public void run() {
try {
long handle5 = scm.openComPort(PORT1, true, true, true);
scm.configureComPortData(handle5, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B115200, 0);
scm.configureComPortControl(handle5, FLOWCONTROL.NONE, 'x', 'x', false, false);
File[] f = new File[2];
f[0] = new File(sndjpg2);
Thread.sleep(1000);
boolean status5 = scm.sendFile(handle5, f, FTPPROTO.XMODEM, FTPVAR.CHKSUM, false, test55, null);
System.out.println("BINARY MODE sent jpg status : " + status5);
done = true;
scm.closeComPort(handle5);
}catch (Exception e) {
e.printStackTrace();
}
}
});
long handle7 = scm.openComPort(PORT2, true, true, true);
scm.configureComPortData(handle7, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B115200, 0);
scm.configureComPortControl(handle7, FLOWCONTROL.NONE, 'x', 'x', false, false);
boolean status7 = scm.receiveFile(handle7, new File(rcvdiry4), FTPPROTO.XMODEM, FTPVAR.CHKSUM, false, test55, null);
System.out.println("BINARY MODE received status jpg : " + status7);
scm.closeComPort(handle7);
while(done == false) {
Thread.sleep(10);
}
System.out.println("\n
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
public void onXmodemReceiveProgressUpdate(long arg0) {
System.out.println("Receive numBlock : " + arg0);
}
@Override
public void onXmodemSentProgressUpdate(long arg0, int arg1) {
System.out.println("Sent numBlock : " + arg0 + " percentOfBlocksSent : " + arg1);
}
}
|
package protocolsupport.protocol.storage.netcache;
import protocolsupport.utils.Utils;
public class MovementCache {
protected double x;
protected double y;
protected double z;
protected int teleportConfirmId;
public int tryTeleportConfirm(double x, double y, double z) {
if (teleportConfirmId == -1) {
return -1;
}
if ((this.x == x) && (this.y == y) && (this.z == z)) {
int r = teleportConfirmId;
teleportConfirmId = -1;
return r;
}
return -1;
}
public void setTeleportLocation(double x, double y, double z, int teleportConfirmId) {
this.x = x;
this.y = y;
this.z = z;
this.teleportConfirmId = teleportConfirmId;
}
@Override
public String toString() {
return Utils.toStringAllFields(this);
}
}
|
// This program is free software; you can redistribute it and/or modify
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
// For more information contact:
// Tab Size = 8
package org.opennms.netmgt.capsd;
import java.lang.*;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.sql.SQLException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.Map;
import java.util.List;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.Date;
import org.apache.log4j.Category;
import org.opennms.core.utils.ThreadCategory;
import org.opennms.netmgt.EventConstants;
import org.opennms.netmgt.eventd.EventIpcManagerFactory;
import org.opennms.netmgt.capsd.snmp.*;
import org.opennms.protocols.snmp.*;
import org.opennms.netmgt.config.DatabaseConnectionFactory;
import org.opennms.netmgt.config.CapsdConfigFactory;
import org.opennms.netmgt.config.CollectdConfigFactory;
import org.opennms.netmgt.config.PollerConfigFactory;
import org.opennms.netmgt.utils.IPSorter;
// These generated by castor
import org.opennms.netmgt.xml.event.Event;
import org.opennms.netmgt.xml.event.Parm;
import org.opennms.netmgt.xml.event.Value;
import org.opennms.netmgt.xml.event.Parms;
// castor classes generated from the discovery-configuration.xsd
import org.opennms.netmgt.config.capsd.*;
final class SuspectEventProcessor
implements Runnable
{
/**
* SQL statement to retrieve the node identifier for a given IP address
*/
private static String SQL_RETRIEVE_INTERFACE_NODEID_PREFIX = "SELECT nodeId FROM ipinterface WHERE ";
/**
* SQL statement to retrieve the ipaddresses for a given node ID
*/
private final static String SQL_RETRIEVE_IPINTERFACES_ON_NODEID = "SELECT ipaddr FROM ipinterface WHERE nodeid = ?";
private final static String SELECT_METHOD_MIN = "min";
private final static String SELECT_METHOD_MAX = "max";
/**
* IP address of new suspect interface
*/
String m_suspectIf;
/**
* Constructor.
*
* @param ifAddress Suspect interface address.
*/
SuspectEventProcessor(String ifAddress)
{
// Check the arguments
if(ifAddress == null)
throw new IllegalArgumentException("The interface address cannot be null");
m_suspectIf = ifAddress;
}
/**
* This method is responsible for determining if a node already exists in the
* database for the current interface. If the IfCollector object contains a
* valid SNMP collection, an attempt will be made to look up in the database
* each interface contained in the SNMP collection's ifTable. If an interface
* is found to already exist in the database a DbNodeEntry object will be
* created from it and returned. If the IfCollector object does not contain
* a valid SNMP collection or if none of the interfaces exist in the database
* null is returned.
*
* @param dbc Connection to the database.
* @param collector Interface collector object
*
* @return dbNodeEntry Returns null if a node does not already exist in the database,
* otherwise returns the DbNodeEntry object for the node under which
* the current interface/IP address should be added.
*
* @throws SQLException Thrown if an error occurs retrieving the parent nodeid from
* the database.
*/
private DbNodeEntry getExistingNodeEntry(java.sql.Connection dbc, IfCollector collector ) throws SQLException
{
Category log = ThreadCategory.getInstance(getClass());
if (log.isDebugEnabled())
log.debug("getExistingNodeEntry: checking for current target: " + collector.getTarget());
// Do we have any additional interface information collected via SNMP?
// If not simply return, there is nothing to check
if(!collector.hasSnmpCollection() || collector.getSnmpCollector().failed())
return null;
// Next verify that ifTable and ipAddrTable entries were collected
IfSnmpCollector snmpc = collector.getSnmpCollector();
IfTable ifTable = null;
IpAddrTable ipAddrTable = null;
if(snmpc.hasIfTable())
ifTable = snmpc.getIfTable();
if (snmpc.hasIpAddrTable())
ipAddrTable = snmpc.getIpAddrTable();
if (ifTable == null || ipAddrTable == null)
return null;
// SQL statement prefix
StringBuffer sqlBuffer = new StringBuffer(SQL_RETRIEVE_INTERFACE_NODEID_PREFIX);
boolean firstAddress = true;
// Loop through the interface table entries and see if any already exist
// in the database.
Iterator iter = ifTable.getEntries().iterator();
List ipaddrsOfNewNode = new ArrayList();
List ipaddrsOfOldNode = new ArrayList();
while(iter.hasNext())
{
IfTableEntry ifEntry = (IfTableEntry)iter.next();
if (ifEntry.containsKey("ifIndex") != true) {
log.debug("getExistingNodeEntry: Breaking from loop");
break;
}
// Get ifIndex
int ifIndex = -1;
SnmpInt32 snmpIfIndex = (SnmpInt32)ifEntry.get(IfTableEntry.IF_INDEX);
if(snmpIfIndex != null)
ifIndex = snmpIfIndex.getValue();
// Get ALL IP Addresses for this ifIndex
List ipAddrs = IpAddrTable.getIpAddresses(ipAddrTable.getEntries(), ifIndex);
if (log.isDebugEnabled())
log.debug("getExistingNodeEntry: number of interfaces retrieved for ifIndex " + ifIndex + " is: " + ipAddrs.size());
// Get ifType for this interface
int ifType = -1;
SnmpInt32 snmpIfType = (SnmpInt32)ifEntry.get(IfTableEntry.IF_TYPE);
if(snmpIfType != null)
ifType = snmpIfType.getValue();
// Iterate over IP address list and add each to the sql buffer
Iterator aiter = ipAddrs.iterator();
while (aiter.hasNext())
{
InetAddress ipAddress = (InetAddress)aiter.next();
// Skip interface if no IP address or if IP address is "0.0.0.0"
// or if this interface is of type loopback
if (ipAddress == null ||
ipAddress.getHostAddress().equals("0.0.0.0") ||
ipAddress.getHostAddress().startsWith("127."))
continue;
if (firstAddress)
{
sqlBuffer.append("ipaddr='").append(ipAddress.getHostAddress()).append("'");
firstAddress = false;
}
else
sqlBuffer.append(" OR ipaddr='").append(ipAddress.getHostAddress()).append("'");
ipaddrsOfNewNode.add(ipAddress.getHostAddress());
}
} // end while
// Make sure we added at least one address to the SQL query
if (firstAddress)
return null;
// Prepare the db statement in advance
if (log.isDebugEnabled())
log.debug("getExistingNodeEntry: issuing SQL command: " + sqlBuffer.toString());
PreparedStatement stmt = dbc.prepareStatement(sqlBuffer.toString());
// Do any of the IP addrs already exist in the database under another node?
int nodeID = -1;
try
{
ResultSet rs = stmt.executeQuery();
if (rs.next())
{
nodeID = rs.getInt(1);
if (log.isDebugEnabled())
log.debug("getExistingNodeEntry: target " + collector.getTarget().getHostAddress() + nodeID);
rs = null;
}
}
catch(SQLException sqlE)
{
throw sqlE;
}
finally
{
try
{
stmt.close(); // automatically closes the result set as well
}
catch (Exception e)
{
// Ignore
}
}
if (nodeID == -1)
return null;
try
{
stmt = dbc.prepareStatement(SQL_RETRIEVE_IPINTERFACES_ON_NODEID);
stmt.setInt(1, nodeID);
ResultSet rs = stmt.executeQuery();
while (rs.next())
{
String ipaddr = rs.getString(1);
if (!ipaddr.equals("0.0.0.0"))
ipaddrsOfOldNode.add(ipaddr);
}
}
catch(SQLException sqlE)
{
throw sqlE;
}
finally
{
try
{
stmt.close(); // automatically closes the result set as well
}
catch (Exception e)
{
// Ignore
}
}
if (ipaddrsOfNewNode.containsAll(ipaddrsOfOldNode))
{
if (log.isDebugEnabled())
log.debug("getExistingNodeEntry: found one of the addrs under existing node: " + nodeID);
return DbNodeEntry.get(nodeID);
}
else
{
String dupIpaddr = getDuplicateIpaddress(ipaddrsOfOldNode, ipaddrsOfNewNode);
createAndSendDuplicateIpaddressEvent(nodeID, dupIpaddr);
return null;
}
}
/**
* This method is used to verify if there is a same ipaddress existing in two sets
* of ipaddresses, and return the first ipaddress that is the same in both sets as
* a string.
*
* @param ipListA a collection of ip addresses.
* @param ipListB a collection of ip addresses.
*
* @return the first ipaddress exists in both ipaddress lists.
*
*/
private String getDuplicateIpaddress(List ipListA, List ipListB)
{
Category log = ThreadCategory.getInstance(getClass());
if (ipListA == null || ipListB == null)
return null;
String ipaddr = null;
Iterator iter = ipListA.iterator();
while (iter.hasNext())
{
ipaddr = (String)iter.next();
if (ipListB.contains(ipaddr))
{
if (log.isDebugEnabled())
log.debug("getDuplicateIpaddress: get duplicate ip address: " + ipaddr);
break;
}
else
ipaddr = null;
}
return ipaddr;
}
/**
* This method is responsble for inserting a new node into the node table.
*
* @param dbc Database connection.
* @param ifaddr Suspect interface
* @param collector Interface collector containing SMB and SNMP info
* collected from the remote device.
*
* @return DbNodeEntry object associated with the newly inserted node
* table entry.
*
* @throws SQLException if an error occurs inserting the new node.
*/
private DbNodeEntry createNode(Connection dbc, InetAddress ifaddr, IfCollector collector)
throws SQLException
{
Category log = ThreadCategory.getInstance(getClass());
// Determine primary interface for the node. Primary interface
// is needed for determining the node label.
InetAddress primaryIf = determinePrimaryInterface(collector);
// Get Snmp and Smb collector objects
IfSnmpCollector snmpc = collector.getSnmpCollector();
IfSmbCollector smbc = collector.getSmbCollector();
// First create a node entry for the new interface
DbNodeEntry entryNode = DbNodeEntry.create();
// fill in the node information
Date now = new Date();
entryNode.setCreationTime(now);
entryNode.setLastPoll(now);
entryNode.setNodeType(DbNodeEntry.NODE_TYPE_ACTIVE);
entryNode.setLabel(primaryIf.getHostName());
if(entryNode.getLabel().equals(primaryIf.getHostAddress()))
entryNode.setLabelSource(DbNodeEntry.LABEL_SOURCE_ADDRESS);
else
entryNode.setLabelSource(DbNodeEntry.LABEL_SOURCE_HOSTNAME);
if(snmpc != null)
{
if(snmpc.hasSystemGroup())
{
SystemGroup sysgrp = snmpc.getSystemGroup();
// sysObjectId
entryNode.setSystemOID(sysgrp.get(SystemGroup.SYS_OBJECTID).toString());
// sysName
String str = SystemGroup.getPrintableString((SnmpOctetString)sysgrp.get(SystemGroup.SYS_NAME));
if (log.isDebugEnabled())
log.debug("SuspectEventProcessor: " + ifaddr.getHostAddress() + " has sysName: " + str);
if(str != null && str.length() > 0)
{
entryNode.setSystemName(str);
// Hostname takes precedence over sysName so only replace label if
// hostname was not available.
if(entryNode.getLabelSource() == DbNodeEntry.LABEL_SOURCE_ADDRESS)
{
entryNode.setLabel(str);
entryNode.setLabelSource(DbNodeEntry.LABEL_SOURCE_SYSNAME);
}
}
// sysDescription
str = SystemGroup.getPrintableString((SnmpOctetString) sysgrp.get(SystemGroup.SYS_DESCR));
if (log.isDebugEnabled())
log.debug("SuspectEventProcessor: " + ifaddr.getHostAddress() + " has sysDescription: " + str);
if (str!= null && str.length() > 0)
entryNode.setSystemDescription(str);
// sysLocation
str = SystemGroup.getPrintableString((SnmpOctetString) sysgrp.get(SystemGroup.SYS_LOCATION));
if (log.isDebugEnabled())
log.debug("SuspectEventProcessor: " + ifaddr.getHostAddress() + " has sysLocation: " + str);
if(str != null && str.length() > 0)
entryNode.setSystemLocation(str);
// sysContact
str = SystemGroup.getPrintableString((SnmpOctetString) sysgrp.get(SystemGroup.SYS_CONTACT));
if (log.isDebugEnabled())
log.debug("SuspectEventProcessor: " + ifaddr.getHostAddress() + " has sysContact: " + str);
if(str != null && str.length() > 0)
entryNode.setSystemContact(str);
}
}
// check for SMB information
if(smbc != null)
{
// Netbios Name and Domain
// Note: only override if the label source is not HOSTNAME
if(smbc.getNbtName() != null && entryNode.getLabelSource() != DbNodeEntry.LABEL_SOURCE_HOSTNAME)
{
entryNode.setLabel(smbc.getNbtName());
entryNode.setLabelSource(DbNodeEntry.LABEL_SOURCE_NETBIOS);
entryNode.setNetBIOSName(entryNode.getLabel());
if (smbc.getDomainName() != null)
{
entryNode.setDomainName(smbc.getDomainName());
}
}
// Operating System
if(smbc.getOS() != null)
{
entryNode.setOS(smbc.getOS());
}
}
entryNode.store(dbc);
return entryNode;
}
/**
* This method is responsble for inserting new entries into the ipInterface
* table for each interface found to be associated with the suspect interface
* during the capabilities scan.
*
* @param dbc Database connection.
* @param node DbNodeEntry object representing the suspect interface's
* parent node table entry
* @param useExistingNode False if a new node was created for the suspect interface.
* True if an existing node entry was found under which the
* the suspect interface is to be added.
* @param ifaddr Suspect interface
* @param collector Interface collector containing SMB and SNMP info
* collected from the remote device.
*
* @throws SQLException if an error occurs adding interfaces to the ipInterface
* table.
*/
private void addInterfaces(Connection dbc,
DbNodeEntry node,
boolean useExistingNode,
InetAddress ifaddr,
IfCollector collector)
throws SQLException
{
Category log = ThreadCategory.getInstance(getClass());
CapsdConfigFactory cFactory = CapsdConfigFactory.getInstance();
PollerConfigFactory pollerCfgFactory = PollerConfigFactory.getInstance();
Date now = new Date();
// if there is no snmp information then it's a
// simple addtion to the database
if(!collector.hasSnmpCollection() || collector.getSnmpCollector().failed())
{
DbIpInterfaceEntry ipIfEntry = DbIpInterfaceEntry.create(node.getNodeId(), ifaddr);
ipIfEntry.setLastPoll(now);
ipIfEntry.setHostname(ifaddr.getHostName());
// NOTE: (reference internal bug# 201)
// If the ip is 'managed', it might still be 'not polled' based
// on the poller configuration
// The package filter evaluation requires that the ip be in the
// database - at this point the ip is NOT in db, so insert as active
// and update afterward
// Try to avoid re-evaluating the ip against filters for
// each service, try to get the first package here and use
// that for service evaluation
boolean addrUnmanaged = cFactory.isAddressUnmanaged(ifaddr);
if(addrUnmanaged)
ipIfEntry.setManagedState(DbIpInterfaceEntry.STATE_UNMANAGED);
else
ipIfEntry.setManagedState(DbIpInterfaceEntry.STATE_MANAGED);
ipIfEntry.setPrimaryState(DbIpInterfaceEntry.SNMP_NOT_ELIGIBLE);
ipIfEntry.store(dbc);
// now update if necessary
org.opennms.netmgt.config.poller.Package ipPkg = null;
if (!addrUnmanaged)
{
boolean ipToBePolled = false;
ipPkg = pollerCfgFactory.getFirstPackageMatch(ifaddr.getHostAddress());
if (ipPkg != null)
ipToBePolled = true;
if (!ipToBePolled)
{
// update ismanaged to 'N' in ipinterface
ipIfEntry.setManagedState(DbIpInterfaceEntry.STATE_NOT_POLLED);
ipIfEntry.store(dbc);
}
}
// Add supported protocols
addSupportedProtocols(node,
ifaddr,
collector.getSupportedProtocols(),
addrUnmanaged,
-1,
ipPkg);
}
else
{
IfSnmpCollector snmpc = collector.getSnmpCollector();
// more complicate work needs to be done here. Information must
// be looked up in various entrys now!
DbIpInterfaceEntry ipIfEntry = DbIpInterfaceEntry.create(node.getNodeId(), ifaddr);
ipIfEntry.setLastPoll(now);
ipIfEntry.setHostname(ifaddr.getHostName());
// NOTE: (reference internal bug# 201)
// If the ip is 'managed', it might still be 'not polled' based
// on the poller configuration
// The package filter evaluation requires that the ip be in the
// database - at this point the ip is NOT in db, so insert as active
// and update afterward
// Try to avoid re-evaluating the ip against filters for
// each service, try to get the first package here and use
// that for service evaluation
boolean addrUnmanaged = cFactory.isAddressUnmanaged(ifaddr);
if(addrUnmanaged)
ipIfEntry.setManagedState(DbIpInterfaceEntry.STATE_UNMANAGED);
else
ipIfEntry.setManagedState(DbIpInterfaceEntry.STATE_MANAGED);
ipIfEntry.setPrimaryState(DbIpInterfaceEntry.SNMP_NOT_ELIGIBLE);
ipIfEntry.store(dbc);
// now update if necessary
org.opennms.netmgt.config.poller.Package ipPkg = null;
if (!addrUnmanaged)
{
boolean ipToBePolled = false;
ipPkg = pollerCfgFactory.getFirstPackageMatch(ifaddr.getHostAddress());
if (ipPkg != null)
ipToBePolled = true;
if (!ipToBePolled)
{
// update ismanaged to 'N' in ipinterface
ipIfEntry.setManagedState(DbIpInterfaceEntry.STATE_NOT_POLLED);
ipIfEntry.store(dbc);
}
}
int ifIndex = -1;
if((ifIndex = snmpc.getIfIndex(ifaddr)) != -1)
{
// Just set primary state to secondary for now. The primary SNMP interface
// won't be selected until after all interfaces have been inserted
// into the database. This is because the interface must already be in
// the database for filter rule evaluation to succeed.
ipIfEntry.setPrimaryState(DbIpInterfaceEntry.SNMP_SECONDARY);
ipIfEntry.setIfIndex(ifIndex);
int status = snmpc.getAdminStatus(ifIndex);
if(status != -1)
ipIfEntry.setStatus(status);
}
else
{
// Address does not have a valid ifIndex associated with it
// so set primary state to NOT_ELIGIBLE.
ipIfEntry.setPrimaryState(DbIpInterfaceEntry.SNMP_NOT_ELIGIBLE);
}
ipIfEntry.store(dbc);
// Add supported protocols
addSupportedProtocols(node,
ifaddr,
collector.getSupportedProtocols(),
addrUnmanaged,
ifIndex,
ipPkg);
// If the useExistingNode flag is true, then we're done. The interface
// is most likely an alias and the subinterfaces collected via SNMP should
// already be in the database.
if (useExistingNode == true)
return;
// Made it this far...lets add the sub interfaces
Map extraTargets = collector.getAdditionalTargets();
Iterator iter = extraTargets.keySet().iterator();
while(iter.hasNext())
{
InetAddress xifaddr = (InetAddress)iter.next();
if (log.isDebugEnabled())
log.debug("addInterfaces: adding interface " + xifaddr.getHostAddress());
DbIpInterfaceEntry xipIfEntry = DbIpInterfaceEntry.create(node.getNodeId(), xifaddr);
xipIfEntry.setLastPoll(now);
xipIfEntry.setHostname(xifaddr.getHostName());
// NOTE: (reference internal bug# 201)
// If the ip is 'managed', it might still be 'not polled' based
// on the poller configuration
// The package filter evaluation requires that the ip be in the
// database - at this point the ip is NOT in db, so insert as active
// and update afterward
// Try to avoid re-evaluating the ip against filters for
// each service, try to get the first package here and use
// that for service evaluation
boolean xaddrUnmanaged = cFactory.isAddressUnmanaged(xifaddr);
if(xaddrUnmanaged)
xipIfEntry.setManagedState(DbIpInterfaceEntry.STATE_UNMANAGED);
else
xipIfEntry.setManagedState(DbIpInterfaceEntry.STATE_MANAGED);
int xifIndex = -1;
if((xifIndex = snmpc.getIfIndex(xifaddr)) != -1)
{
xipIfEntry.setIfIndex(xifIndex);
int status = snmpc.getAdminStatus(xifIndex);
if(status != -1)
xipIfEntry.setStatus(status);
if (supportsSnmp((List)extraTargets.get(xifaddr)))
{
// Just set primary state to secondary for now. The primary SNMP interface
// won't be selected until after all interfaces have been inserted
// into the database. This is because the interface must already be in
// the database for filter rule evaluation to succeed.
xipIfEntry.setPrimaryState(DbIpInterfaceEntry.SNMP_SECONDARY);
}
else
{
xipIfEntry.setPrimaryState(DbIpInterfaceEntry.SNMP_NOT_ELIGIBLE);
}
}
else
{
// No ifIndex found so set primary state to NOT_ELIGIBLE
xipIfEntry.setPrimaryState(DbIpInterfaceEntry.SNMP_NOT_ELIGIBLE);
}
xipIfEntry.store(dbc);
// now update if necessary
org.opennms.netmgt.config.poller.Package xipPkg = null;
if (!xaddrUnmanaged)
{
boolean xipToBePolled = false;
xipPkg = pollerCfgFactory.getFirstPackageMatch(xifaddr.getHostAddress());
if (xipPkg != null)
xipToBePolled = true;
if (!xipToBePolled)
{
// update ismanaged to 'N' in ipinterface
xipIfEntry.setManagedState(DbIpInterfaceEntry.STATE_NOT_POLLED);
xipIfEntry.store(dbc);
}
}
// add the supported protocols
addSupportedProtocols(node,
xifaddr,
(List)extraTargets.get(xifaddr),
xaddrUnmanaged,
xifIndex,
xipPkg);
} // end while()
// Now add any non-IP interfaces
if (collector.hasNonIpInterfaces())
{
iter = ((List)collector.getNonIpInterfaces()).iterator();
while(iter.hasNext())
{
SnmpInt32 ifindex = (SnmpInt32)iter.next();
DbIpInterfaceEntry xipIfEntry = null;
try
{
xipIfEntry = DbIpInterfaceEntry.create(node.getNodeId(), InetAddress.getByName("0.0.0.0"));
}
catch(UnknownHostException e)
{
continue;
}
xipIfEntry.setLastPoll(now);
xipIfEntry.setManagedState(DbIpInterfaceEntry.STATE_UNMANAGED);
xipIfEntry.setIfIndex(ifindex.getValue());
int status = snmpc.getAdminStatus(ifIndex);
if(status != -1)
xipIfEntry.setStatus(status);
xipIfEntry.setPrimaryState(DbIpInterfaceEntry.SNMP_NOT_ELIGIBLE);
xipIfEntry.store(dbc);
}
}
// last thing to do is add all the snmp interface information
IfTable ift = snmpc.getIfTable();
Iterator ifiter = ift.getEntries().iterator();
while(ifiter.hasNext())
{
IfTableEntry ifte = (IfTableEntry)ifiter.next();
// index
int xifIndex = -1;
SnmpInt32 sint = (SnmpInt32)ifte.get(IfTableEntry.IF_INDEX);
if(sint != null)
xifIndex = sint.getValue();
else
continue;
// address
// WARNING: IfSnmpCollector.getIfAddressAndMask() ONLY returns
// the FIRST IP address and mask for a given interface as specified
// in the ipAddrTable.
InetAddress[] aaddrs = snmpc.getIfAddressAndMask(sint.getValue());
if(aaddrs == null)
{
// Must be non-IP interface, set ifAddress to '0.0.0.0' and
// Mask to null
aaddrs = new InetAddress[2];
try
{
aaddrs[0] = InetAddress.getByName("0.0.0.0");
}
catch (UnknownHostException e)
{
continue;
}
aaddrs[1] = null;
}
// Retrieve ifType so we can check for loopback
sint = (SnmpInt32)ifte.get(IfTableEntry.IF_TYPE);
int ifType = sint.getValue();
// Skip loopback interfaces
if (aaddrs[0].getHostAddress().startsWith("127."))
continue;
DbSnmpInterfaceEntry snmpEntry = DbSnmpInterfaceEntry.create(node.getNodeId(), xifIndex);
// IP address
snmpEntry.setIfAddress(aaddrs[0]);
// netmask
if (aaddrs[1] != null)
snmpEntry.setNetmask(aaddrs[1]);
// description
String str = SystemGroup.getPrintableString((SnmpOctetString)ifte.get(IfTableEntry.IF_DESCR));
if (log.isDebugEnabled())
log.debug("SuspectEventProcessor: " + aaddrs[0].getHostAddress() + " has ifDescription: " + str);
if(str != null && str.length() > 0)
snmpEntry.setDescription(str);
// physical address
StringBuffer sbuf = new StringBuffer();
SnmpOctetString ostr = (SnmpOctetString)ifte.get(IfTableEntry.IF_PHYS_ADDR);
byte[] bytes = ostr.getString();
for(int i = 0; i < bytes.length; i++)
{
sbuf.append(Integer.toHexString(((int)bytes[i] >> 4) & 0xf));
sbuf.append(Integer.toHexString((int)bytes[i] & 0xf));
}
String physAddr = sbuf.toString().trim();
if (log.isDebugEnabled())
log.debug("SuspectEventProcessor: " + aaddrs[0].getHostAddress() + " has physical address: -" + physAddr + "-");
if (physAddr.length() == 12)
{
snmpEntry.setPhysicalAddress(physAddr);
}
// type
snmpEntry.setType(ifType);
// speed
SnmpUInt32 uint = (SnmpUInt32)ifte.get(IfTableEntry.IF_SPEED);
if (uint == null)
{
snmpEntry.setSpeed(0);
}
else
{
snmpEntry.setSpeed((int)uint.getValue());
}
// admin status
sint = (SnmpInt32)ifte.get(IfTableEntry.IF_ADMIN_STATUS);
if (sint == null)
{
snmpEntry.setAdminStatus(0);
}
else
{
snmpEntry.setAdminStatus(sint.getValue());
}
// oper status
sint = (SnmpInt32)ifte.get(IfTableEntry.IF_OPER_STATUS);
if (sint == null)
{
snmpEntry.setOperationalStatus(0);
}
else
{
snmpEntry.setOperationalStatus(sint.getValue());
}
// name (from interface extensions table)
SnmpOctetString snmpIfName = snmpc.getIfName(xifIndex);
if (snmpIfName != null)
{
String ifName = SystemGroup.getPrintableString(snmpIfName);
if (ifName != null && ifName.length() > 0)
snmpEntry.setName(ifName);
}
snmpEntry.store(dbc);
}
}
}
/**
* Responsible for iterating inserting an entry into the ifServices
* table for each protocol supported by the interface.
*
* @param node Node entry
* @param ifaddr Interface address
* @param protocols List of supported protocols
* @param addrUnmanaged Boolean flag indicating if interface is managed or
* unmanaged according to the Capsd configuration.
* @param ifIndex Interface index or -1 if index is not known
* @param ipPkg Poller package to which the interface belongs
*
* @throws SQLException if an error occurs adding interfaces to the ipInterface
* table.
*/
private void addSupportedProtocols(DbNodeEntry node,
InetAddress ifaddr,
List protocols,
boolean addrUnmanaged,
int ifIndex,
org.opennms.netmgt.config.poller.Package ipPkg)
throws SQLException
{
// add the supported protocols
// NOTE!!!!!: (reference internal bug# 201)
// If the ip is 'managed', the service can still be 'not polled'
// based on the poller configuration - at this point the ip is already
// in the database, so package filter evaluation should go through OK
Iterator iproto = protocols.iterator();
while(iproto.hasNext())
{
IfCollector.SupportedProtocol p = (IfCollector.SupportedProtocol)iproto.next();
Number sid = (Number)CapsdConfigFactory.getInstance().getServiceIdentifier(p.getProtocolName());
DbIfServiceEntry ifSvcEntry = DbIfServiceEntry.create(node.getNodeId(), ifaddr, sid.intValue());
// now fill in the entry
if(addrUnmanaged)
ifSvcEntry.setStatus(DbIfServiceEntry.STATUS_UNMANAGED);
else
{
boolean svcToBePolled = false;
if (ipPkg != null)
{
svcToBePolled = PollerConfigFactory.getInstance().isPolled(p.getProtocolName(), ipPkg);
if (!svcToBePolled)
svcToBePolled = PollerConfigFactory.getInstance().isPolled(ifaddr.getHostAddress(), p.getProtocolName());
}
if (svcToBePolled)
ifSvcEntry.setStatus(DbIfServiceEntry.STATUS_ACTIVE);
else
ifSvcEntry.setStatus(DbIfServiceEntry.STATUS_NOT_POLLED);
}
// Set qualifier if available. Currently the qualifier field
// is used to store the port at which the protocol was found.
if (p.getQualifiers() != null && p.getQualifiers().get("port") != null)
{
try
{
Integer port = (Integer)p.getQualifiers().get("port");
ifSvcEntry.setQualifier(port.toString());
}
catch (ClassCastException ccE)
{
// Do nothing
}
}
ifSvcEntry.setSource(DbIfServiceEntry.SOURCE_PLUGIN);
ifSvcEntry.setNotify(DbIfServiceEntry.NOTIFY_ON);
if(ifIndex != -1)
ifSvcEntry.setIfIndex(ifIndex);
ifSvcEntry.store();
}
}
/**
* Utility method which checks the provided list of supported
* protocols to determine if the SNMP service is present.
*
* @param supportedProtocols List of supported protocol objects.
*
* @return TRUE if service "SNMP" is present in the list, FALSE otherwise
*/
static boolean supportsSnmp(List supportedProtocols)
{
Iterator iter = supportedProtocols.iterator();
while (iter.hasNext())
{
IfCollector.SupportedProtocol p = (IfCollector.SupportedProtocol)iter.next();
if (p.getProtocolName().equals("SNMP"))
return true;
}
return false;
}
/**
* Utility method which determines if the passed IfSnmpCollector object
* contains an ifIndex value for the passed IP address.
*
* @param ipaddr IP address
* @param snmpc SNMP collection
*
* @return TRUE if an ifIndex value was found in the SNMP collection for
* the provided IP address, FALSE otherwise.
*/
static boolean hasIfIndex(InetAddress ipaddr, IfSnmpCollector snmpc)
{
int ifIndex = snmpc.getIfIndex(ipaddr);
Category log = ThreadCategory.getInstance(Capsd.class);
if (log.isDebugEnabled())
log.debug("hasIfIndex: ipAddress: " + ipaddr.getHostAddress() + " has ifIndex: " + ifIndex);
if (ifIndex == -1)
return false;
else
return true;
}
/**
* Utility method which determines returns the ifType for
* the passed IP address.
*
* @param ipaddr IP address
* @param snmpc SNMP collection
*
* @return TRUE if an ifIndex value was found in the SNMP collection for
* the provided IP address, FALSE otherwise.
*/
static int getIfType(InetAddress ipaddr, IfSnmpCollector snmpc)
{
int ifIndex = snmpc.getIfIndex(ipaddr);
int ifType = snmpc.getIfType(ifIndex);
Category log = ThreadCategory.getInstance(Capsd.class);
if (log.isDebugEnabled())
log.debug("getIfType: ipAddress: " + ipaddr.getHostAddress() + " has ifIndex: " + ifIndex + " and ifType: " + ifType);
return ifType;
}
/**
* Utility method which compares two InetAddress objects based on the provided method (MIN/MAX)
* and returns the InetAddress which is to be considered the primary interface.
*
* NOTE: In order for an interface to be considered primary it must be
* managed. This method will return null if the 'oldPrimary' address is
* null and the 'currentIf' address is unmanaged.
*
* @param currentIf Interface with which to compare the 'oldPrimary' address.
* @param oldPrimary Primary interface to be compared against the 'currentIf' address.
* @param method Comparison method to be used (either "min" or "max")
*
* @return InetAddress object of the primary interface based on the provided method
* or null if neither address is eligible to be primary.
*/
static InetAddress compareAndSelectPrimary(InetAddress currentIf, InetAddress oldPrimary, String method)
{
InetAddress newPrimary = null;
if (oldPrimary == null)
{
if (!CapsdConfigFactory.getInstance().isAddressUnmanaged(currentIf))
return currentIf;
else
return oldPrimary;
}
long current = IPSorter.convertToLong(currentIf.getAddress());
long primary = IPSorter.convertToLong(oldPrimary.getAddress());
if (method.equals(SELECT_METHOD_MIN))
{
// Smallest address wins
if (current < primary)
{
// Replace the primary interface with the current
// interface only if the current interface is managed!
if(!CapsdConfigFactory.getInstance().isAddressUnmanaged(currentIf))
newPrimary = currentIf;
}
}
else
{
// Largest address wins
if (current > primary)
{
// Replace the primary interface with the current
// interface only if the current interface is managed!
if(!CapsdConfigFactory.getInstance().isAddressUnmanaged(currentIf))
newPrimary = currentIf;
}
}
if (newPrimary != null)
return newPrimary;
else
return oldPrimary;
}
/**
* Builds a list of InetAddress objects representing each of
* the interfaces from the IfCollector object which support SNMP
* and have a valid ifIndex and is a loopback interface.
*
* This is in order to allow a non-127.*.*.* loopback address to
* be chosen as the primary SNMP interface.
*
* @param collector IfCollector object containing SNMP and SMB info.
*
* @return List of InetAddress objects.
*/
private static List buildLBSnmpAddressList(IfCollector collector)
{
Category log = ThreadCategory.getInstance(SuspectEventProcessor.class);
List addresses = new ArrayList();
// Verify that SNMP info is available
if (collector.getSnmpCollector() == null)
{
if (log.isDebugEnabled())
log.debug("buildLBSnmpAddressList: no SNMP info for " + collector.getTarget());
return addresses;
}
// Verify that both the ifTable and ipAddrTable were
// successfully collected.
IfSnmpCollector snmpc = collector.getSnmpCollector();
if (!snmpc.hasIfTable() || !snmpc.hasIpAddrTable())
{
log.info("buildLBSnmpAddressList: missing SNMP info for " + collector.getTarget());
return addresses;
}
// To be eligible to be the primary SNMP interface for a node:
// 1. The interface must support SNMP
// 2. The interface must have a valid ifIndex
// Add eligible target.
InetAddress ipAddr = collector.getTarget();
if ( supportsSnmp(collector.getSupportedProtocols()) &&
hasIfIndex(ipAddr, snmpc) && getIfType(ipAddr, snmpc) == 24)
{
if (log.isDebugEnabled())
log.debug("buildLBSnmpAddressList: adding target interface " + ipAddr.getHostAddress() + " temporarily marked as primary!");
addresses.add(ipAddr);
}
// Add eligible subtargets.
if (collector.hasAdditionalTargets())
{
Map extraTargets = collector.getAdditionalTargets();
Iterator iter = extraTargets.keySet().iterator();
while(iter.hasNext())
{
InetAddress currIf = (InetAddress)iter.next();
// Test current subtarget.
if (supportsSnmp((List)extraTargets.get(currIf)) &&
getIfType(currIf, snmpc) == 24 )
{
if (log.isDebugEnabled())
log.debug("buildLBSnmpAddressList: adding subtarget interface " + currIf.getHostAddress() + " temporarily marked as primary!");
addresses.add(currIf);
}
} // end while()
} // end if()
return addresses;
}
/**
* Builds a list of InetAddress objects representing each of
* the interfaces from the IfCollector object which support SNMP
* and have a valid ifIndex.
*
* @param collector IfCollector object containing SNMP and SMB info.
*
* @return List of InetAddress objects.
*/
private static List buildSnmpAddressList(IfCollector collector)
{
Category log = ThreadCategory.getInstance(SuspectEventProcessor.class);
List addresses = new ArrayList();
// Verify that SNMP info is available
if (collector.getSnmpCollector() == null)
{
if (log.isDebugEnabled())
log.debug("buildSnmpAddressList: no SNMP info for " + collector.getTarget());
return addresses;
}
// Verify that both the ifTable and ipAddrTable were
// successfully collected.
IfSnmpCollector snmpc = collector.getSnmpCollector();
if (!snmpc.hasIfTable() || !snmpc.hasIpAddrTable())
{
log.info("buildSnmpAddressList: missing SNMP info for " + collector.getTarget());
return addresses;
}
// To be eligible to be the primary SNMP interface for a node:
// 1. The interface must support SNMP
// 2. The interface must have a valid ifIndex
// Add eligible target.
InetAddress ipAddr = collector.getTarget();
if ( supportsSnmp(collector.getSupportedProtocols()) &&
hasIfIndex(ipAddr, snmpc))
{
if (log.isDebugEnabled())
log.debug("buildSnmpAddressList: adding target interface " + ipAddr.getHostAddress() + " temporarily marked as primary!");
addresses.add(ipAddr);
}
// Add eligible subtargets.
if (collector.hasAdditionalTargets())
{
Map extraTargets = collector.getAdditionalTargets();
Iterator iter = extraTargets.keySet().iterator();
while(iter.hasNext())
{
InetAddress currIf = (InetAddress)iter.next();
// Test current subtarget.
if (supportsSnmp((List)extraTargets.get(currIf)) &&
hasIfIndex(currIf, snmpc) )
{
if (log.isDebugEnabled())
log.debug("buildSnmpAddressList: adding subtarget interface " + currIf.getHostAddress() + " temporarily marked as primary!");
addresses.add(currIf);
}
} // end while()
} // end if()
return addresses;
}
/**
* This method is responsbile for determining the node's primary IP interface
* from among all the node's IP interfaces.
*
* @param collector IfCollector object containing SNMP and SMB info.
*
* @return InetAddress object of the primary SNMP interface or null if none
* of the node's interfaces are eligible.
*/
private InetAddress determinePrimaryInterface(IfCollector collector)
{
Category log = ThreadCategory.getInstance(getClass());
InetAddress primaryIf = null;
// For now hard-coding primary interface address selection method to MIN
String method = SELECT_METHOD_MIN;
// Initially set the target interface as primary
primaryIf = collector.getTarget();
// Next the subtargets will be tested. If is managed and
// has a smaller numeric IP address then it will in turn be
// set as the primary interface.
if (collector.hasAdditionalTargets())
{
Map extraTargets = collector.getAdditionalTargets();
Iterator iter = extraTargets.keySet().iterator();
while(iter.hasNext())
{
InetAddress currIf = (InetAddress)iter.next();
primaryIf = compareAndSelectPrimary(currIf, primaryIf, method);
} // end while()
} // end if (Collector.hasAdditionalTargets())
if (log.isDebugEnabled())
if (primaryIf != null)
log.debug("determinePrimaryInterface: selected primary interface: " + primaryIf.getHostAddress());
else
log.debug("determinePrimaryInterface: no primary interface found");
return primaryIf;
}
/**
* This is where all the work of the class is done.
*/
public void run()
{
Category log = ThreadCategory.getInstance(getClass());
CapsdConfigFactory cFactory = CapsdConfigFactory.getInstance();
// Convert interface InetAddress object
InetAddress ifaddr = null;
try
{
ifaddr = InetAddress.getByName(m_suspectIf);
}
catch(UnknownHostException e)
{
log.warn("SuspectEventProcessor: Failed to convert interface address " + m_suspectIf + " to InetAddress", e);
return;
}
// collect the information
if(log.isDebugEnabled())
log.debug("SuspectEventProcessor: running collection for " + ifaddr.getHostAddress());
IfCollector collector = new IfCollector(ifaddr, true);
collector.run();
// Track changes to primary SNMP interface
InetAddress oldSnmpPrimaryIf = null;
InetAddress newSnmpPrimaryIf = null;
InetAddress newLBSnmpPrimaryIf = null;
// Update the database
boolean updateCompleted = false;
boolean useExistingNode = false;
DbNodeEntry entryNode = null;
try
{
// Synchronize on the Capsd sync lock so we can check if
// the interface is already in the database and perform
// the necessary inserts in one atomic operation
// The RescanProcessor class is also synchronizing on this
// lock prior to performing database inserts or updates.
Connection dbc = null;
synchronized(Capsd.getDbSyncLock())
{
// Get database connection
try
{
dbc = DatabaseConnectionFactory.getInstance().getConnection();
// Only add the node/interface to the database if
// it isn't already in the database
if (!cFactory.isInterfaceInDB(dbc, ifaddr))
{
// Using the interface collector object determine
// if this interface belongs under a node already
// in the database.
entryNode = getExistingNodeEntry(dbc, collector);
if (entryNode == null)
{
// Create a node entry for the new interface
entryNode = createNode(dbc,
ifaddr,
collector);
}
else
{
// Will use existing node entry
useExistingNode = true;
}
// Get old primary SNMP interface (if one exists)
oldSnmpPrimaryIf = getPrimarySnmpInterfaceFromDb(dbc, entryNode);
// Add interfaces
addInterfaces(dbc, entryNode, useExistingNode, ifaddr, collector);
// Now that all interfaces have been added to the database we
// can update the 'primarySnmpInterface' field of the ipInterface
// table. Necessary because the IP address must already be in
// the database to evaluate against a filter rule.
// First create a list of eligible loopback addresses, and
// choose one if valid.
List snmpLBAddresses = buildLBSnmpAddressList(collector);
newLBSnmpPrimaryIf = CollectdConfigFactory.getInstance().determinePrimarySnmpInterface(snmpLBAddresses);
if (newLBSnmpPrimaryIf == null)
{
List snmpAddresses = buildSnmpAddressList(collector);
newSnmpPrimaryIf = CollectdConfigFactory.getInstance().determinePrimarySnmpInterface(snmpAddresses);
setPrimarySnmpInterface(dbc, entryNode, newSnmpPrimaryIf, oldSnmpPrimaryIf);
}
else
{
if(log.isDebugEnabled())
log.debug("SuspectEventProcessor: Loopback Address set as primary: " + newLBSnmpPrimaryIf);
setPrimarySnmpInterface(dbc, entryNode, newLBSnmpPrimaryIf, oldSnmpPrimaryIf);
}
// Update
updateCompleted = true;
}
}
finally
{
if(dbc != null)
{
try
{
dbc.close();
}
catch(SQLException e)
{
if(log.isInfoEnabled())
log.info("run: an sql exception occured closing the database connection", e);
}
}
dbc = null;
}
}
} // end try
catch(Throwable t)
{
log.error("Error writing records", t);
}
// Send events
if (updateCompleted)
{
if (!useExistingNode)
createAndSendNodeAddedEvent(entryNode);
sendInterfaceEvents(entryNode, useExistingNode, ifaddr, collector);
if (useExistingNode)
{
generateSnmpDataCollectionEvents(entryNode, oldSnmpPrimaryIf, newSnmpPrimaryIf);
}
}
if (log.isDebugEnabled())
log.debug("SuspectEventProcessor for " + m_suspectIf + " completed.");
} // end run
/**
* Returns the InetAddress object of the primary SNMP interface (if one
* exists).
*
* @param dbc Database connection.
* @param node DbNodeEntry object representing the interface's
* parent node table entry
*
* @throws SQLException if an error occurs updating the ipInterface table
* @return Old SNMP primary interface address.
*/
static InetAddress getPrimarySnmpInterfaceFromDb(Connection dbc, DbNodeEntry node)
throws SQLException
{
Category log = ThreadCategory.getInstance(SuspectEventProcessor.class);
// Get old primary SNMP interface if one exists
log.debug("getPrimarySnmpInterfaceFromDb: retrieving old primary snmp interface...");
InetAddress oldPrimarySnmpIf = null;
// Prepare SQL statement
PreparedStatement stmt = dbc.prepareStatement("SELECT ipAddr FROM ipInterface WHERE nodeId=? AND isSnmpPrimary='P' AND isManaged!='D'");
stmt.setInt(1, node.getNodeId());
// Execute statement
ResultSet rs = null;
try
{
rs = stmt.executeQuery();
if (rs.next())
{
String oldPrimaryAddr = rs.getString("ipAddr");
if (oldPrimaryAddr != null)
{
try
{
oldPrimarySnmpIf = InetAddress.getByName(oldPrimaryAddr);
log.debug("getPrimarySnmpInterfaceFromDb: old primary Snmp interface is " + oldPrimarySnmpIf.getHostAddress());
}
catch (UnknownHostException e)
{
log.warn("Failed converting IP address " + oldPrimaryAddr);
}
}
}
}
catch(SQLException sqlE)
{
throw sqlE;
}
finally
{
try
{
stmt.close(); // automatically closes the result set as well
}
catch (Exception e)
{
// Ignore
}
}
return oldPrimarySnmpIf;
}
/**
* Responsible for setting the value of the 'isSnmpPrimary' field of the
* ipInterface table to 'P' (Primary) for the primary SNMP interface address.
*
* @param dbc Database connection.
* @param node DbNodeEntry object representing the suspect interface's
* parent node table entry
* @param newPrimarySnmpIf New primary SNMP interface.
* @param oldPrimarySnmpIf Old primary SNMP interface.
*
* @throws SQLException if an error occurs updating the ipInterface table
*
*/
static void setPrimarySnmpInterface(Connection dbc, DbNodeEntry node, InetAddress newPrimarySnmpIf, InetAddress oldPrimarySnmpIf)
throws SQLException
{
Category log = ThreadCategory.getInstance(SuspectEventProcessor.class);
if (newPrimarySnmpIf == null)
{
if (log.isDebugEnabled())
log.debug("setPrimarySnmpInterface: newSnmpPrimary is null, nothing to set, returning.");
return;
}
else
{
if (log.isDebugEnabled())
log.debug("setPrimarySnmpInterface: newSnmpPrimary=" + newPrimarySnmpIf);
}
// Verify that old and new primary interfaces are different
if (oldPrimarySnmpIf != null && oldPrimarySnmpIf.equals(newPrimarySnmpIf))
{
// Old and new primary interfaces are the same, just return
return;
}
// They are different so mark the old primary as a secondary interface
if (oldPrimarySnmpIf != null)
{
// Prepare SQL statement
PreparedStatement stmt = dbc.prepareStatement("UPDATE ipInterface SET isSnmpPrimary='S' WHERE nodeId=? AND ipAddr=? AND isManaged!='D'");
stmt.setInt(1, node.getNodeId());
stmt.setString(2, oldPrimarySnmpIf.getHostAddress());
// Execute statement
try
{
stmt.executeUpdate();
log.debug("setPrimarySnmpInterface: completed update of old primary interface to SECONDARY.");
}
catch(SQLException sqlE)
{
throw sqlE;
}
finally
{
try
{
stmt.close();
}
catch (Exception e)
{
// Ignore
}
}
}
// Set primary SNMP interface 'isSnmpPrimary' field to 'P' for primary
if (newPrimarySnmpIf != null)
{
if (log.isDebugEnabled())
log.debug("setPrimarySnmpInterface: primary SNMP interface=" + newPrimarySnmpIf.getHostAddress());
// Update the appropriate entry in the 'ipInterface' table
// Prepare SQL statement
PreparedStatement stmt = dbc.prepareStatement("UPDATE ipInterface SET isSnmpPrimary='P' WHERE nodeId=? AND ipaddr=? AND isManaged!='D'");
stmt.setInt(1, node.getNodeId());
stmt.setString(2, newPrimarySnmpIf.getHostAddress());
// Execute statement
try
{
stmt.executeUpdate();
if (log.isDebugEnabled())
log.debug("setPrimarySnmpInterface: completed update of new primary interface to PRIMARY.");
}
catch(SQLException sqlE)
{
throw sqlE;
}
finally
{
try
{
stmt.close();
}
catch (Exception e)
{
// Ignore
}
}
}
}
/**
* Determines if any SNMP data collection related events need to
* be generated based upon the results of the current rescan. If
* necessary will generate one of the following events:
* 'reinitializePrimarySnmpInterface'
* 'primarySnmpInterfaceChanged'
*
* @param nodeEntry DbNodeEntry object of the node being rescanned.
* @param oldPrimary Old primary SNMP interface
* @param newPrimary New primary SNMP interface
*/
private void generateSnmpDataCollectionEvents(DbNodeEntry nodeEntry, InetAddress oldPrimary, InetAddress newPrimary)
{
Category log = ThreadCategory.getInstance(getClass());
// Sanity check -- should not happen
if (oldPrimary == null && newPrimary == null)
{
log.warn("generateSnmpDataCollectionEvents: both old and new primary SNMP interface vars are null!");
}
// Sanity check -- should not happen
else if (oldPrimary != null && newPrimary == null)
{
log.warn("generateSnmpDataCollectionEvents: old primary (" + oldPrimary.getHostAddress() + ") is not null but new primary is null!");
}
// Just added the primary SNMP interface to the node, the nodeGainedService
// event already generated is sufficient to start SNMP data collection...no
// additional events are required.
else if (oldPrimary == null && newPrimary != null)
{
if (log.isDebugEnabled())
log.debug("generateSnmpDataCollectionEvents: identified " + newPrimary.getHostAddress() + " as the primary SNMP interface for node " + nodeEntry.getNodeId());
}
// A PrimarySnmpInterfaceChanged event is generated if the scan
// found a different primary SNMP interface than what is stored
// in the database.
else if (!oldPrimary.equals(newPrimary) )
{
if (log.isDebugEnabled())
{
log.debug("generateSnmpDataCollectionEvents: primary SNMP interface has changed. Was: " +
oldPrimary.getHostAddress() + " Is: " +
newPrimary.getHostAddress());
}
createAndSendPrimarySnmpInterfaceChangedEvent(nodeEntry.getNodeId(), newPrimary, oldPrimary);
}
// The primary SNMP interface did not change but the Capsd scan just added
// an interface to the node so we need to update the interface
// map which is maintained in memory for the purpose of doing
// SNMP data collection. Therefore we generate a
// reinitializePrimarySnmpInterface event so that this map
// can be refreshed based on the most up to date information
// in the database.
else
{
if (log.isDebugEnabled())
log.debug("generateSnmpDataCollectionEvents: Generating reinitializeSnmpInterface event for interface " + newPrimary.getHostAddress());
createAndSendReinitializePrimarySnmpInterfaceEvent(nodeEntry.getNodeId(), newPrimary);
}
}
/**
* This method is responsible for generating a primarySnmpInterfaceChanged event and
* sending it to eventd..
*
* @param nodeId Nodeid of node being rescanned.
* @param newPrimaryIf new primary SNMP interface address
* @param oldPrimaryIf old primary SNMP interface address
*/
private void createAndSendPrimarySnmpInterfaceChangedEvent(int nodeId,
InetAddress newPrimaryIf,
InetAddress oldPrimaryIf)
{
Category log = ThreadCategory.getInstance(getClass());
String oldPrimaryAddr = null;
if (oldPrimaryIf != null)
oldPrimaryAddr = oldPrimaryIf.getHostAddress();
String newPrimaryAddr = null;
if (newPrimaryIf != null)
newPrimaryAddr = newPrimaryIf.getHostAddress();
if (log.isDebugEnabled())
log.debug("createAndSendPrimarySnmpInterfaceChangedEvent: nodeId: " + nodeId +
" oldPrimarySnmpIf: '" + oldPrimaryAddr +
"' newPrimarySnmpIf: '" + newPrimaryAddr + "'");
Event newEvent = new Event();
newEvent.setUei(EventConstants.PRIMARY_SNMP_INTERFACE_CHANGED_EVENT_UEI);
newEvent.setSource("OpenNMS.Capsd");
newEvent.setNodeid(nodeId);
newEvent.setInterface(newPrimaryAddr);
newEvent.setHost(Capsd.getLocalHostAddress());
newEvent.setService("SNMP");
newEvent.setTime(EventConstants.formatToString(new java.util.Date()));
// Add appropriate parms
Parms eventParms = new Parms();
Parm eventParm = null;
Value parmValue = null;
if (oldPrimaryAddr != null)
{
// Add old node label
eventParm = new Parm();
eventParm.setParmName(EventConstants.PARM_OLD_PRIMARY_SNMP_ADDRESS);
parmValue = new Value();
parmValue.setContent(oldPrimaryAddr);
eventParm.setValue(parmValue);
eventParms.addParm(eventParm);
}
if (newPrimaryAddr != null)
{
// Add new node label
eventParm = new Parm();
eventParm.setParmName(EventConstants.PARM_NEW_PRIMARY_SNMP_ADDRESS);
parmValue = new Value();
parmValue.setContent(newPrimaryAddr);
eventParm.setValue(parmValue);
eventParms.addParm(eventParm);
}
// Add Parms to the event
newEvent.setParms(eventParms);
// Send event to Eventd
try
{
EventIpcManagerFactory.getInstance().getManager().sendNow(newEvent);
if (log.isDebugEnabled())
log.debug("createAndSendPrimarySnmpInterfaceChangedEvent: successfully sent primarySnmpInterfaceChanged event for nodeID: " + nodeId);
}
catch(Throwable t)
{
log.warn("run: unexpected throwable exception caught during send to middleware", t);
}
}
/**
* This method is responsible for generating a reinitializePrimarySnmpInterface
* event and sending it to eventd.
*
* @param nodeId Nodeid of node being rescanned.
* @param InetAddress Primary SNMP interface address.
*/
private void createAndSendReinitializePrimarySnmpInterfaceEvent(int nodeId, InetAddress primarySnmpIf)
{
Category log = ThreadCategory.getInstance(getClass());
if (log.isDebugEnabled())
log.debug("reinitializePrimarySnmpInterface: nodeId: " + nodeId +
" interface: " + primarySnmpIf.getHostAddress());
Event newEvent = new Event();
newEvent.setUei(EventConstants.REINITIALIZE_PRIMARY_SNMP_INTERFACE_EVENT_UEI);
newEvent.setSource("OpenNMS.Capsd");
newEvent.setNodeid(nodeId);
newEvent.setHost(Capsd.getLocalHostAddress());
newEvent.setInterface(primarySnmpIf.getHostAddress());
newEvent.setTime(EventConstants.formatToString(new java.util.Date()));
// Send event to Eventd
try
{
EventIpcManagerFactory.getInstance().getManager().sendNow(newEvent);
if (log.isDebugEnabled())
log.debug("createAndSendReinitializePrimarySnmpInterfaceEvent: successfully sent reinitializePrimarySnmpInterface event for nodeID: " + nodeId);
}
catch(Throwable t)
{
log.warn("run: unexpected throwable exception caught during send to middleware", t);
}
}
/**
* This method is responsible for creating all the necessary interface-level
* events for the node and sending them to Eventd.
*
* @param node DbNodeEntry object for the parent node.
* @param useExistingNode TRUE if existing node was used, FALSE if new
* node was created.
* @param ifaddr Target interface address
* @param collector Interface collector containing SNMP and SMB info.
*/
private void sendInterfaceEvents(DbNodeEntry node,
boolean useExistingNode,
InetAddress ifaddr,
IfCollector collector)
{
Category log = ThreadCategory.getInstance(getClass());
// Go ahead and send events for the target interface
// nodeGainedInterface
if (log.isDebugEnabled())
log.debug("sendInterfaceEvents: sending node gained interface event for " + ifaddr.getHostAddress());
createAndSendNodeGainedInterfaceEvent(node.getNodeId(), ifaddr);
// nodeGainedService
log.debug("sendInterfaceEvents: processing supported services for " + ifaddr.getHostAddress());
Iterator iproto = collector.getSupportedProtocols().iterator();
while(iproto.hasNext())
{
IfCollector.SupportedProtocol p = (IfCollector.SupportedProtocol)iproto.next();
if (log.isDebugEnabled())
log.debug("sendInterfaceEvents: sending event for service: " + p.getProtocolName());
createAndSendNodeGainedServiceEvent(node,
ifaddr,
p.getProtocolName(),
null);
}
// If the useExistingNode flag is set to TRUE we're done, none of the
// sub-targets should have been added.
if (useExistingNode)
return;
// If SNMP info available send events for sub-targets
if(collector.hasSnmpCollection() && !collector.getSnmpCollector().failed())
{
Map extraTargets = collector.getAdditionalTargets();
Iterator iter = extraTargets.keySet().iterator();
while(iter.hasNext())
{
InetAddress xifaddr = (InetAddress)iter.next();
// nodeGainedInterface
createAndSendNodeGainedInterfaceEvent(node.getNodeId(), xifaddr);
// nodeGainedService
List supportedProtocols = (List)extraTargets.get(xifaddr);
log.debug("interface " + xifaddr + " supports " + supportedProtocols.size() + " protocols.");
if (supportedProtocols != null)
{
iproto = supportedProtocols.iterator();
while(iproto.hasNext())
{
IfCollector.SupportedProtocol p = (IfCollector.SupportedProtocol)iproto.next();
createAndSendNodeGainedServiceEvent(node,
xifaddr,
p.getProtocolName(),
null);
}
}
}
}
}
/**
* This method is responsible for creating and sending a 'nodeAdded' event
* to Eventd
*
* @param nodeEntry DbNodeEntry object for the newly created node.
*/
private void createAndSendNodeAddedEvent(DbNodeEntry nodeEntry)
{
Category log = ThreadCategory.getInstance(getClass());
// create the event to be sent
Event newEvent = new Event();
newEvent.setUei(EventConstants.NODE_ADDED_EVENT_UEI);
newEvent.setSource("OpenNMS.Capsd");
newEvent.setNodeid(nodeEntry.getNodeId());
newEvent.setHost(Capsd.getLocalHostAddress());
newEvent.setTime(EventConstants.formatToString(new java.util.Date()));
// Add appropriate parms
Parms eventParms = new Parms();
Parm eventParm = null;
Value parmValue = null;
// Add node label
eventParm = new Parm();
eventParm.setParmName(EventConstants.PARM_NODE_LABEL);
parmValue = new Value();
parmValue.setContent(nodeEntry.getLabel());
eventParm.setValue(parmValue);
eventParms.addParm(eventParm);
// Add node label source
eventParm = new Parm();
eventParm.setParmName(EventConstants.PARM_NODE_LABEL_SOURCE);
parmValue = new Value();
char labelSource[] = new char[] {nodeEntry.getLabelSource()};
parmValue.setContent(new String(labelSource));
eventParm.setValue(parmValue);
eventParms.addParm(eventParm);
// Add discovery method
eventParm = new Parm();
eventParm.setParmName(EventConstants.PARM_METHOD);
parmValue = new Value();
parmValue.setContent("icmp");
eventParm.setValue(parmValue);
eventParms.addParm(eventParm);
// Add Parms to the event
newEvent.setParms(eventParms);
// Send event to Eventd
try
{
EventIpcManagerFactory.getInstance().getManager().sendNow(newEvent);
if (log.isDebugEnabled())
log.debug("createAndSendNodeAddedEvent: successfully sent NodeAdded event for nodeID: " + nodeEntry.getNodeId());
}
catch(Throwable t)
{
log.warn("run: unexpected throwable exception caught during send to middleware", t);
}
}
/**
* This method is responsible for creating and sending a 'duplicateIPAddress'
* event to Eventd
*
* @param nodeId Interface's parent node identifier.
* @param ipAddr Interface's IP address
*/
private void createAndSendDuplicateIpaddressEvent(int nodeId, String ipAddr)
{
Category log = ThreadCategory.getInstance(getClass());
// create the event to be sent
Event newEvent = new Event();
newEvent.setUei(EventConstants.DUPLICATE_IPINTERFACE_EVENT_UEI);
newEvent.setSource("OpenNMS.Capsd");
newEvent.setNodeid(nodeId);
newEvent.setHost(Capsd.getLocalHostAddress());
newEvent.setInterface(ipAddr);
newEvent.setTime(EventConstants.formatToString(new java.util.Date()));
// Send event to Eventd
try
{
EventIpcManagerFactory.getInstance().getManager().sendNow(newEvent);
if (log.isDebugEnabled())
log.debug("createAndSendDuplicateIpaddressEvent: successfully sent duplicateIPAddress event for interface: " + ipAddr);
}
catch(Throwable t)
{
log.warn("run: unexpected throwable exception caught during send to middleware", t);
}
}
/**
* This method is responsible for creating and sending a 'nodeGainedInterface'
* event to Eventd
*
* @param nodeId Interface's parent node identifier.
* @param ipAddr Interface's IP address
*/
private void createAndSendNodeGainedInterfaceEvent(int nodeId, InetAddress ipAddr)
{
Category log = ThreadCategory.getInstance(getClass());
// create the event to be sent
Event newEvent = new Event();
newEvent.setUei(EventConstants.NODE_GAINED_INTERFACE_EVENT_UEI);
newEvent.setSource("OpenNMS.Capsd");
newEvent.setNodeid(nodeId);
newEvent.setHost(Capsd.getLocalHostAddress());
newEvent.setInterface(ipAddr.getHostAddress());
newEvent.setTime(EventConstants.formatToString(new java.util.Date()));
// Add appropriate parms
Parms eventParms = new Parms();
Parm eventParm = null;
Value parmValue = null;
// Add IP host name
eventParm = new Parm();
eventParm.setParmName(EventConstants.PARM_IP_HOSTNAME);
parmValue = new Value();
parmValue.setContent(ipAddr.getHostName());
eventParm.setValue(parmValue);
eventParms.addParm(eventParm);
// Add discovery method
eventParm = new Parm();
eventParm.setParmName(EventConstants.PARM_METHOD);
parmValue = new Value();
parmValue.setContent("icmp");
eventParm.setValue(parmValue);
eventParms.addParm(eventParm);
// Add Parms to the event
newEvent.setParms(eventParms);
// Send event to Eventd
try
{
EventIpcManagerFactory.getInstance().getManager().sendNow(newEvent);
if (log.isDebugEnabled())
log.debug("createAndSendNodeGainedInterfaceEvent: successfully sent NodeGainedInterface event for interface: " + ipAddr.getHostAddress());
}
catch(Throwable t)
{
log.warn("run: unexpected throwable exception caught during send to middleware", t);
}
}
/**
* This method is responsible for creating and sending a 'nodeGainedService'
* event to Eventd
*
* @param nodeEntry Interface's parent node identifier.
* @param ipAddr Interface's IP address
* @param svcName Service name
* @param qualifier Service qualifier (typically the port on which the
* service was found)
*/
private void createAndSendNodeGainedServiceEvent(DbNodeEntry nodeEntry, InetAddress ipAddr, String svcName, String qualifier)
{
Category log = ThreadCategory.getInstance(getClass());
// create the event to be sent
Event newEvent = new Event();
newEvent.setUei(EventConstants.NODE_GAINED_SERVICE_EVENT_UEI);
newEvent.setSource("OpenNMS.Capsd");
newEvent.setNodeid(nodeEntry.getNodeId());
newEvent.setHost(Capsd.getLocalHostAddress());
newEvent.setInterface(ipAddr.getHostAddress());
newEvent.setService(svcName);
newEvent.setTime(EventConstants.formatToString(new java.util.Date()));
// Add appropriate parms
Parms eventParms = new Parms();
Parm eventParm = null;
Value parmValue = null;
// Add IP host name
eventParm = new Parm();
eventParm.setParmName(EventConstants.PARM_IP_HOSTNAME);
parmValue = new Value();
parmValue.setContent(ipAddr.getHostName());
eventParm.setValue(parmValue);
eventParms.addParm(eventParm);
// Add node label
eventParm = new Parm();
eventParm.setParmName(EventConstants.PARM_NODE_LABEL);
parmValue = new Value();
parmValue.setContent(nodeEntry.getLabel());
eventParm.setValue(parmValue);
eventParms.addParm(eventParm);
// Add node label source
eventParm = new Parm();
eventParm.setParmName(EventConstants.PARM_NODE_LABEL_SOURCE);
parmValue = new Value();
char labelSource[] = new char[] {nodeEntry.getLabelSource()};
parmValue.setContent(new String(labelSource));
eventParm.setValue(parmValue);
eventParms.addParm(eventParm);
// Add qualifier (if available)
if (qualifier != null && qualifier.length() > 0)
{
eventParm = new Parm();
eventParm.setParmName(EventConstants.PARM_QUALIFIER);
parmValue = new Value();
parmValue.setContent(qualifier);
eventParm.setValue(parmValue);
eventParms.addParm(eventParm);
}
// Add sysName (if available)
if (nodeEntry.getSystemName() != null)
{
eventParm = new Parm();
eventParm.setParmName(EventConstants.PARM_NODE_SYSNAME);
parmValue = new Value();
parmValue.setContent(nodeEntry.getSystemName());
eventParm.setValue(parmValue);
eventParms.addParm(eventParm);
}
// Add sysDescr (if available)
if (nodeEntry.getSystemDescription() != null)
{
eventParm = new Parm();
eventParm.setParmName(EventConstants.PARM_NODE_SYSDESCRIPTION);
parmValue = new Value();
parmValue.setContent(nodeEntry.getSystemDescription());
eventParm.setValue(parmValue);
eventParms.addParm(eventParm);
}
// Add Parms to the event
newEvent.setParms(eventParms);
// Send event to Eventd
try
{
EventIpcManagerFactory.getInstance().getManager().sendNow(newEvent);
if (log.isDebugEnabled())
log.debug("createAndSendNodeGainedServiceEvent: successfully sent NodeGainedService event for interface: " + ipAddr.getHostAddress() + " and service: " + svcName);
}
catch(Throwable t)
{
log.warn("run: unexpected throwable exception caught during send to middleware", t);
}
}
} // end class
|
package com.devicehive.websockets;
import com.devicehive.base.AbstractWebSocketTest;
import com.devicehive.base.fixture.JsonFixture;
import com.devicehive.base.fixture.WebSocketFixture;
import com.devicehive.base.websocket.WebSocketSynchronousConnection;
import com.devicehive.model.JsonStringWrapper;
import com.devicehive.model.wrappers.DeviceCommandWrapper;
import com.devicehive.model.wrappers.DeviceNotificationWrapper;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonPrimitive;
import org.junit.After;
import org.junit.Test;
import org.springframework.web.socket.TextMessage;
import java.util.HashMap;
import java.util.Optional;
import static com.devicehive.base.websocket.WebSocketSynchronousConnection.WAIT_TIMEOUT;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.CoreMatchers.notNullValue;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
public class CommandHandlersTest extends AbstractWebSocketTest {
@After
public void tearDown() throws Exception {
clearWSConnections();
}
@Test
public void should_insert_command_signed_in_as_admin() throws Exception {
WebSocketSynchronousConnection connection = syncConnection("/websocket/client");
WebSocketFixture.authenticateUser(ADMIN_LOGIN, ADMIN_PASS, connection);
DeviceCommandWrapper command = new DeviceCommandWrapper();
command.setCommand(Optional.of("test command"));
JsonObject commandInsert = JsonFixture.createWsCommand("command/insert", "1", new HashMap<String, JsonElement>() {{
put("deviceGuid", new JsonPrimitive(DEVICE_ID));
put("command", gson.toJsonTree(command));
}});
long time = System.currentTimeMillis();
TextMessage response = connection.sendMessage(new TextMessage(gson.toJson(commandInsert)), WAIT_TIMEOUT);
JsonObject jsonResp = gson.fromJson(response.getPayload(), JsonObject.class);
assertThat(jsonResp.get("action").getAsString(), is("command/insert"));
assertThat(jsonResp.get("requestId").getAsString(), is("1"));
assertThat(jsonResp.get("status").getAsString(), is("success"));
assertThat(jsonResp.get("command"), notNullValue());
InsertCommand commandResp = gson.fromJson(jsonResp.get("command"),InsertCommand.class);
assertThat(commandResp.getId(), notNullValue());
assertThat(commandResp.getTimestamp(), notNullValue());
assertTrue(commandResp.getTimestamp().getTime() > time);
}
@Test
public void should_insert_notification_signed_in_as_key() throws Exception {
WebSocketSynchronousConnection connection = syncConnection("/websocket/client");
WebSocketFixture.authenticateKey(ACCESS_KEY, connection);
DeviceNotificationWrapper notification = new DeviceNotificationWrapper();
notification.setNotification("hi there");
notification.setParameters(new JsonStringWrapper("{\"param\": \"param_1\"}"));
JsonObject notificationInsert = JsonFixture.createWsCommand("notification/insert", "1", new HashMap<String, JsonElement>() {{
put("deviceGuid", new JsonPrimitive(DEVICE_ID));
put("notification", gson.toJsonTree(notification));
}});
long time = System.currentTimeMillis();
TextMessage response = connection.sendMessage(new TextMessage(gson.toJson(notificationInsert)), WAIT_TIMEOUT);
JsonObject jsonResp = gson.fromJson(response.getPayload(), JsonObject.class);
assertThat(jsonResp.get("action").getAsString(), is("notification/insert"));
assertThat(jsonResp.get("requestId").getAsString(), is("1"));
assertThat(jsonResp.get("status").getAsString(), is("success"));
assertThat(jsonResp.get("notification"), notNullValue());
InsertNotification notificationResp = gson.fromJson(jsonResp.get("notification"),InsertNotification.class);
assertThat(notificationResp.getId(), notNullValue());
assertThat(notificationResp.getTimestamp(), notNullValue());
assertTrue(notificationResp.getTimestamp().getTime() > time);
}
}
|
package com.imsweb.seerapi.client.staging;
import java.io.IOException;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.hamcrest.CoreMatchers;
import org.hamcrest.MatcherAssert;
import org.junit.BeforeClass;
import org.junit.Test;
import com.imsweb.seerapi.client.SeerApi;
import com.imsweb.seerapi.client.disease.DateRange;
import com.imsweb.seerapi.client.disease.DateRangeString;
import com.imsweb.seerapi.client.disease.YearRange;
import com.imsweb.seerapi.client.disease.YearRangeInteger;
import com.imsweb.seerapi.client.disease.YearRangeString;
import com.imsweb.seerapi.client.glossary.Glossary.Category;
import com.imsweb.seerapi.client.shared.KeywordMatch;
import com.imsweb.seerapi.client.staging.cs.CsSchemaLookup;
import com.imsweb.seerapi.client.staging.cs.CsStagingData;
import com.imsweb.seerapi.client.staging.cs.CsStagingData.CsInput;
import com.imsweb.seerapi.client.staging.cs.CsStagingData.CsStagingInputBuilder;
import com.imsweb.seerapi.client.staging.eod.EodSchemaLookup;
import com.imsweb.seerapi.client.staging.eod.EodStagingData;
import com.imsweb.seerapi.client.staging.eod.EodStagingData.EodInput;
import com.imsweb.seerapi.client.staging.eod.EodStagingData.EodOutput;
import com.imsweb.seerapi.client.staging.eod.EodStagingData.EodStagingInputBuilder;
import com.imsweb.seerapi.client.staging.tnm.TnmSchemaLookup;
import com.imsweb.seerapi.client.staging.tnm.TnmStagingData;
import com.imsweb.seerapi.client.staging.tnm.TnmStagingData.TnmInput;
import com.imsweb.seerapi.client.staging.tnm.TnmStagingData.TnmOutput;
import com.imsweb.seerapi.client.staging.tnm.TnmStagingData.TnmStagingInputBuilder;
import static com.google.code.beanmatchers.BeanMatchers.hasValidBeanConstructor;
import static com.google.code.beanmatchers.BeanMatchers.hasValidBeanEquals;
import static com.google.code.beanmatchers.BeanMatchers.hasValidGettersAndSetters;
import static com.google.code.beanmatchers.BeanMatchers.hasValidGettersAndSettersExcluding;
import static com.imsweb.seerapi.client.staging.StagingData.HISTOLOGY_KEY;
import static com.imsweb.seerapi.client.staging.StagingData.PRIMARY_SITE_KEY;
import static com.imsweb.seerapi.client.staging.cs.CsStagingData.CsOutput.AJCC6_M;
import static com.imsweb.seerapi.client.staging.cs.CsStagingData.CsOutput.AJCC6_MDESCRIPTOR;
import static com.imsweb.seerapi.client.staging.cs.CsStagingData.CsOutput.AJCC6_N;
import static com.imsweb.seerapi.client.staging.cs.CsStagingData.CsOutput.AJCC6_NDESCRIPTOR;
import static com.imsweb.seerapi.client.staging.cs.CsStagingData.CsOutput.AJCC6_STAGE;
import static com.imsweb.seerapi.client.staging.cs.CsStagingData.CsOutput.AJCC6_T;
import static com.imsweb.seerapi.client.staging.cs.CsStagingData.CsOutput.AJCC6_TDESCRIPTOR;
import static com.imsweb.seerapi.client.staging.cs.CsStagingData.CsOutput.AJCC7_M;
import static com.imsweb.seerapi.client.staging.cs.CsStagingData.CsOutput.AJCC7_MDESCRIPTOR;
import static com.imsweb.seerapi.client.staging.cs.CsStagingData.CsOutput.AJCC7_N;
import static com.imsweb.seerapi.client.staging.cs.CsStagingData.CsOutput.AJCC7_NDESCRIPTOR;
import static com.imsweb.seerapi.client.staging.cs.CsStagingData.CsOutput.AJCC7_STAGE;
import static com.imsweb.seerapi.client.staging.cs.CsStagingData.CsOutput.AJCC7_T;
import static com.imsweb.seerapi.client.staging.cs.CsStagingData.CsOutput.AJCC7_TDESCRIPTOR;
import static com.imsweb.seerapi.client.staging.cs.CsStagingData.CsOutput.CSVER_DERIVED;
import static com.imsweb.seerapi.client.staging.cs.CsStagingData.CsOutput.SCHEMA_NUMBER;
import static com.imsweb.seerapi.client.staging.cs.CsStagingData.CsOutput.SS1977_M;
import static com.imsweb.seerapi.client.staging.cs.CsStagingData.CsOutput.SS1977_N;
import static com.imsweb.seerapi.client.staging.cs.CsStagingData.CsOutput.SS1977_STAGE;
import static com.imsweb.seerapi.client.staging.cs.CsStagingData.CsOutput.SS1977_T;
import static com.imsweb.seerapi.client.staging.cs.CsStagingData.CsOutput.SS2000_M;
import static com.imsweb.seerapi.client.staging.cs.CsStagingData.CsOutput.SS2000_N;
import static com.imsweb.seerapi.client.staging.cs.CsStagingData.CsOutput.SS2000_STAGE;
import static com.imsweb.seerapi.client.staging.cs.CsStagingData.CsOutput.SS2000_T;
import static com.imsweb.seerapi.client.staging.cs.CsStagingData.CsOutput.STOR_AJCC6_M;
import static com.imsweb.seerapi.client.staging.cs.CsStagingData.CsOutput.STOR_AJCC6_MDESCRIPTOR;
import static com.imsweb.seerapi.client.staging.cs.CsStagingData.CsOutput.STOR_AJCC6_N;
import static com.imsweb.seerapi.client.staging.cs.CsStagingData.CsOutput.STOR_AJCC6_NDESCRIPTOR;
import static com.imsweb.seerapi.client.staging.cs.CsStagingData.CsOutput.STOR_AJCC6_STAGE;
import static com.imsweb.seerapi.client.staging.cs.CsStagingData.CsOutput.STOR_AJCC6_T;
import static com.imsweb.seerapi.client.staging.cs.CsStagingData.CsOutput.STOR_AJCC6_TDESCRIPTOR;
import static com.imsweb.seerapi.client.staging.cs.CsStagingData.CsOutput.STOR_AJCC7_M;
import static com.imsweb.seerapi.client.staging.cs.CsStagingData.CsOutput.STOR_AJCC7_MDESCRIPTOR;
import static com.imsweb.seerapi.client.staging.cs.CsStagingData.CsOutput.STOR_AJCC7_N;
import static com.imsweb.seerapi.client.staging.cs.CsStagingData.CsOutput.STOR_AJCC7_NDESCRIPTOR;
import static com.imsweb.seerapi.client.staging.cs.CsStagingData.CsOutput.STOR_AJCC7_STAGE;
import static com.imsweb.seerapi.client.staging.cs.CsStagingData.CsOutput.STOR_AJCC7_T;
import static com.imsweb.seerapi.client.staging.cs.CsStagingData.CsOutput.STOR_AJCC7_TDESCRIPTOR;
import static com.imsweb.seerapi.client.staging.cs.CsStagingData.CsOutput.STOR_SS1977_STAGE;
import static com.imsweb.seerapi.client.staging.cs.CsStagingData.CsOutput.STOR_SS2000_STAGE;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
public class StagingTest {
private static final String _ALGORITHM = "cs";
private static final String _VERSION = "02.05.50";
private static StagingService _STAGING;
@BeforeClass
public static void setup() {
_STAGING = new SeerApi.Builder().connect().staging();
}
@Test
public void testGetAlgorithms() throws IOException {
List<StagingAlgorithm> algorithms = _STAGING.algorithms().execute().body();
assertThat(algorithms).isNotEmpty().extracting("algorithm").contains("cs", "tnm", "eod_public");
}
@Test
public void testGetAlgorithmVersions() throws IOException {
List<StagingVersion> versions = _STAGING.versions(_ALGORITHM).execute().body();
assertThat(versions).isNotEmpty();
}
@Test
public void testListSchemas() throws IOException {
List<StagingSchemaInfo> schemaInfos = _STAGING.schemas(_ALGORITHM, _VERSION).execute().body();
assertThat(schemaInfos).isNotEmpty();
schemaInfos = _STAGING.schemas(_ALGORITHM, _VERSION, "skin").execute().body();
assertThat(schemaInfos).isNotEmpty();
}
@Test
public void testSchemaLookup() throws IOException {
// first test simple lookup that returns a single schema with site/hist only
List<StagingSchemaInfo> schemas = _STAGING.schemaLookup(_ALGORITHM, _VERSION, new CsSchemaLookup("C509", "8000").getInputs()).execute().body();
assertThat(schemas).hasSize(1).extracting("id").contains("breast");
// now test just site
SchemaLookup data = new SchemaLookup();
data.setInput(PRIMARY_SITE_KEY, "C111");
assertThat(_STAGING.schemaLookup(_ALGORITHM, _VERSION, data.getInputs()).execute().body()).hasSize(7);
// add histology
data.setInput(StagingData.HISTOLOGY_KEY, "8000");
assertThat(_STAGING.schemaLookup(_ALGORITHM, _VERSION, data.getInputs()).execute().body()).hasSize(2);
// add discriminator
data.setInput("ssf25", "010");
schemas = _STAGING.schemaLookup(_ALGORITHM, _VERSION, data.getInputs()).execute().body();
assertThat(schemas).hasSize(1).extracting("id").contains("nasopharynx");
// test with the CS
schemas = _STAGING.schemaLookup(_ALGORITHM, _VERSION, new CsSchemaLookup("C111", "8000", "010").getInputs()).execute().body();
assertThat(schemas).hasSize(1).extracting("id").contains("nasopharynx");
// test with the TNM
schemas = _STAGING.schemaLookup(_ALGORITHM, _VERSION, new TnmSchemaLookup("C680", "8000").getInputs()).execute().body();
assertThat(schemas).hasSize(1).extracting("id").contains("urethra");
// test with the EOD
schemas = _STAGING.schemaLookup(_ALGORITHM, _VERSION, new EodSchemaLookup("C680", "8000").getInputs()).execute().body();
assertThat(schemas).hasSize(1).extracting("id").contains("urethra");
Map<String, String> values = new HashMap<>();
values.put(PRIMARY_SITE_KEY, "C680");
values.put(HISTOLOGY_KEY, "8000");
SchemaLookup schemaLookup = new SchemaLookup(values);
assertThat(schemaLookup.getInput(PRIMARY_SITE_KEY)).isEqualTo("C680");
assertThat(schemaLookup.getSite()).isEqualTo("C680");
assertThat(schemaLookup.getHistology()).isEqualTo("8000");
assertThat(schemaLookup.hasDiscriminator()).isFalse();
assertThat(schemaLookup).isEqualTo(new SchemaLookup("C680", "8000"));
// test invalid input
CsSchemaLookup csLookup = new CsSchemaLookup();
csLookup.setSite("C111");
csLookup.setHistology("8000");
csLookup.setInput(CsStagingData.SSF25_KEY, "010");
assertThatExceptionOfType(IllegalStateException.class)
.isThrownBy(() -> csLookup.setInput("bad_key", "1"))
.withMessageContaining("is not allowed for lookups");
assertThat(csLookup.hasDiscriminator()).isTrue();
// test clearning inpuyts
schemaLookup.clearInputs();
assertThat(schemaLookup.getInput(PRIMARY_SITE_KEY)).isNull();
}
@Test
public void testSchemaById() throws IOException {
StagingSchema schema = _STAGING.schemaById(_ALGORITHM, _VERSION, "brain").execute().body();
assertThat(schema).isNotNull();
assertThat(schema.getAlgorithm()).isEqualTo("cs");
assertThat(schema.getVersion()).isEqualTo("02.05.50");
assertThat(schema.getId()).isEqualTo("brain");
// verify the inputs
StagingSchemaInput input = schema.getInputs().stream().filter(i -> "site".equals(i.getKey())).findFirst().orElse(null);
assertThat(input).isNotNull();
assertThat(input.getName()).isEqualTo("Primary Site");
assertThat(input.getDescription()).isEqualTo("Code for the primary site of the tumor being reported using either ICD-O-2 or ICD-O-3.");
assertThat(input.getNaaccrItem()).isEqualTo(400);
assertThat(input.getNaaccrXmlId()).isEqualTo("primarySite");
assertThat(input.getUsedForStaging()).isTrue();
assertThat(input.getTable()).isEqualTo("primary_site");
// verify the outputs
StagingSchemaOutput output = schema.getOutputs().stream().filter(i -> "csver_derived".equals(i.getKey())).findFirst().orElse(null);
assertThat(output).isNotNull();
assertThat(output.getName()).isEqualTo("CS Version Derived");
assertThat(output.getDescription()).isEqualTo("Collaborative Staging (CS) version used to derive the CS output fields.");
assertThat(output.getNaaccrItem()).isEqualTo(2936);
assertThat(output.getNaaccrXmlId()).isEqualTo("csVersionDerived");
assertThat(output.getDefault()).isEqualTo("020550");
}
@Test
public void testSchemaInvolvedTables() throws IOException {
List<StagingTable> tables = _STAGING.involvedTables(_ALGORITHM, _VERSION, "brain").execute().body();
assertThat(tables).isNotEmpty();
}
@Test
public void testListTables() throws IOException {
List<StagingTable> tables = _STAGING.tables(_ALGORITHM, _VERSION, "ssf1").execute().body();
assertThat(tables).isNotEmpty();
tables = _STAGING.tables(_ALGORITHM, _VERSION, null, true).execute().body();
assertThat(tables).isEmpty();
tables = _STAGING.tables(_ALGORITHM, _VERSION, null, false).execute().body();
assertThat(tables).isNotEmpty();
}
@Test
public void testTableById() throws IOException {
StagingTable table = _STAGING.tableById(_ALGORITHM, _VERSION, "primary_site").execute().body();
assertThat(table).isNotNull();
assertThat(table.getAlgorithm()).isEqualTo("cs");
assertThat(table.getVersion()).isEqualTo("02.05.50");
assertThat(table.getId()).isEqualTo("primary_site");
}
@Test
public void testTableInvoledSchemas() throws IOException {
List<StagingSchema> schemas = _STAGING.involvedSchemas(_ALGORITHM, _VERSION, "extension_baa").execute().body();
assertThat(schemas).isNotEmpty();
}
@Test
public void testCsInputBuilder() {
CsStagingData data1 = new CsStagingData();
data1.setInput(CsInput.PRIMARY_SITE, "C680");
data1.setInput(CsInput.HISTOLOGY, "8000");
data1.setInput(CsInput.BEHAVIOR, "3");
data1.setInput(CsInput.GRADE, "9");
data1.setInput(CsInput.DX_YEAR, "2013");
data1.setInput(CsInput.CS_VERSION_ORIGINAL, "020550");
data1.setInput(CsInput.TUMOR_SIZE, "075");
data1.setInput(CsInput.EXTENSION, "100");
data1.setInput(CsInput.EXTENSION_EVAL, "9");
data1.setInput(CsInput.LYMPH_NODES, "100");
data1.setInput(CsInput.LYMPH_NODES_EVAL, "9");
data1.setInput(CsInput.REGIONAL_NODES_POSITIVE, "99");
data1.setInput(CsInput.REGIONAL_NODES_EXAMINED, "99");
data1.setInput(CsInput.METS_AT_DX, "10");
data1.setInput(CsInput.METS_EVAL, "9");
data1.setInput(CsInput.LVI, "9");
data1.setInput(CsInput.AGE_AT_DX, "060");
data1.setSsf(1, "020");
CsStagingData data2 = new CsStagingInputBuilder()
.withInput(CsStagingData.CsInput.PRIMARY_SITE, "C680")
.withInput(CsStagingData.CsInput.HISTOLOGY, "8000")
.withInput(CsStagingData.CsInput.BEHAVIOR, "3")
.withInput(CsStagingData.CsInput.GRADE, "9")
.withInput(CsStagingData.CsInput.DX_YEAR, "2013")
.withInput(CsStagingData.CsInput.CS_VERSION_ORIGINAL, "020550")
.withInput(CsStagingData.CsInput.TUMOR_SIZE, "075")
.withInput(CsStagingData.CsInput.EXTENSION, "100")
.withInput(CsStagingData.CsInput.EXTENSION_EVAL, "9")
.withInput(CsStagingData.CsInput.LYMPH_NODES, "100")
.withInput(CsStagingData.CsInput.LYMPH_NODES_EVAL, "9")
.withInput(CsStagingData.CsInput.REGIONAL_NODES_POSITIVE, "99")
.withInput(CsStagingData.CsInput.REGIONAL_NODES_EXAMINED, "99")
.withInput(CsStagingData.CsInput.METS_AT_DX, "10")
.withInput(CsStagingData.CsInput.METS_EVAL, "9")
.withInput(CsStagingData.CsInput.LVI, "9")
.withInput(CsStagingData.CsInput.AGE_AT_DX, "060")
.withSsf(1, "020")
.build();
assertThat(data1.getInput()).isEqualTo(data2.getInput());
}
@Test
public void testCsStaging() throws IOException {
CsStagingData data = new CsStagingInputBuilder()
.withInput(CsInput.PRIMARY_SITE, "C680")
.withInput(CsInput.HISTOLOGY, "8000")
.withInput(CsInput.BEHAVIOR, "3")
.withInput(CsInput.GRADE, "9")
.withInput(CsInput.DX_YEAR, "2013")
.withInput(CsInput.CS_VERSION_ORIGINAL, "020550")
.withInput(CsInput.TUMOR_SIZE, "075")
.withInput(CsInput.EXTENSION, "100")
.withInput(CsInput.EXTENSION_EVAL, "9")
.withInput(CsInput.LYMPH_NODES, "100")
.withInput(CsInput.LYMPH_NODES_EVAL, "9")
.withInput(CsInput.REGIONAL_NODES_POSITIVE, "99")
.withInput(CsInput.REGIONAL_NODES_EXAMINED, "99")
.withInput(CsInput.METS_AT_DX, "10")
.withInput(CsInput.METS_EVAL, "9")
.withInput(CsInput.LVI, "9")
.withInput(CsInput.AGE_AT_DX, "060")
.withSsf(1, "020")
.build();
// perform the staging
StagingData output = _STAGING.stage("cs", "02.05.50", data.getInput()).execute().body();
assertThat(output).isNotNull();
assertThat(output.getResult()).isEqualTo(StagingData.Result.STAGED);
assertThat(output.getErrors()).isEmpty();
assertThat(output.getPath()).hasSize(37);
// check output
assertThat(output.getOutput(SCHEMA_NUMBER.toString())).isEqualTo("129");
assertThat(output.getSchemaId()).isEqualTo("urethra");
assertThat(output.getOutput(CSVER_DERIVED.toString())).isEqualTo("020550");
// AJCC 6
assertThat(output.getOutput(AJCC6_T.toString())).isEqualTo("T1");
assertThat(output.getOutput(STOR_AJCC6_T.toString())).isEqualTo("10");
assertThat(output.getOutput(AJCC6_TDESCRIPTOR.toString())).isEqualTo("c");
assertThat(output.getOutput(STOR_AJCC6_TDESCRIPTOR.toString())).isEqualTo("c");
assertThat(output.getOutput(AJCC6_N.toString())).isEqualTo("N1");
assertThat(output.getOutput(STOR_AJCC6_N.toString())).isEqualTo("10");
assertThat(output.getOutput(AJCC6_NDESCRIPTOR.toString())).isEqualTo("c");
assertThat(output.getOutput(STOR_AJCC6_NDESCRIPTOR.toString())).isEqualTo("c");
assertThat(output.getOutput(AJCC6_M.toString())).isEqualTo("M1");
assertThat(output.getOutput(STOR_AJCC6_M.toString())).isEqualTo("10");
assertThat(output.getOutput(AJCC6_MDESCRIPTOR.toString())).isEqualTo("c");
assertThat(output.getOutput(STOR_AJCC6_MDESCRIPTOR.toString())).isEqualTo("c");
assertThat(output.getOutput(AJCC6_STAGE.toString())).isEqualTo("IV");
assertThat(output.getOutput(STOR_AJCC6_STAGE.toString())).isEqualTo("70");
// AJCC 7
assertThat(output.getOutput(AJCC7_T.toString())).isEqualTo("T1");
assertThat(output.getOutput(STOR_AJCC7_T.toString())).isEqualTo("100");
assertThat(output.getOutput(AJCC7_TDESCRIPTOR.toString())).isEqualTo("c");
assertThat(output.getOutput(STOR_AJCC7_TDESCRIPTOR.toString())).isEqualTo("c");
assertThat(output.getOutput(AJCC7_N.toString())).isEqualTo("N1");
assertThat(output.getOutput(STOR_AJCC7_N.toString())).isEqualTo("100");
assertThat(output.getOutput(AJCC7_NDESCRIPTOR.toString())).isEqualTo("c");
assertThat(output.getOutput(STOR_AJCC7_NDESCRIPTOR.toString())).isEqualTo("c");
assertThat(output.getOutput(AJCC7_M.toString())).isEqualTo("M1");
assertThat(output.getOutput(STOR_AJCC7_M.toString())).isEqualTo("100");
assertThat(output.getOutput(AJCC7_MDESCRIPTOR.toString())).isEqualTo("c");
assertThat(output.getOutput(STOR_AJCC7_MDESCRIPTOR.toString())).isEqualTo("c");
assertThat(output.getOutput(AJCC7_STAGE.toString())).isEqualTo("IV");
assertThat(output.getOutput(STOR_AJCC7_STAGE.toString())).isEqualTo("700");
// Summary Stage
assertThat(output.getOutput(SS1977_T.toString())).isEqualTo("L");
assertThat(output.getOutput(SS1977_N.toString())).isEqualTo("RN");
assertThat(output.getOutput(SS1977_M.toString())).isEqualTo("D");
assertThat(output.getOutput(SS1977_STAGE.toString())).isEqualTo("D");
assertThat(output.getOutput(STOR_SS1977_STAGE.toString())).isEqualTo("7");
assertThat(output.getOutput(SS2000_T.toString())).isEqualTo("L");
assertThat(output.getOutput(SS2000_N.toString())).isEqualTo("RN");
assertThat(output.getOutput(SS2000_M.toString())).isEqualTo("D");
assertThat(output.getOutput(SS2000_STAGE.toString())).isEqualTo("D");
assertThat(output.getOutput(STOR_SS2000_STAGE.toString())).isEqualTo("7");
}
@Test
public void testTnmInputBuilder() {
TnmStagingData data1 = new TnmStagingData();
data1.setInput(TnmInput.PRIMARY_SITE, "C680");
data1.setInput(TnmInput.HISTOLOGY, "8000");
data1.setInput(TnmInput.BEHAVIOR, "3");
data1.setInput(TnmInput.GRADE, "9");
data1.setInput(TnmInput.DX_YEAR, "2013");
data1.setInput(TnmInput.REGIONAL_NODES_POSITIVE, "99");
data1.setInput(TnmInput.AGE_AT_DX, "060");
data1.setInput(TnmInput.SEX, "1");
data1.setInput(TnmInput.RX_SUMM_SURGERY, "8");
data1.setInput(TnmInput.RX_SUMM_RADIATION, "9");
data1.setInput(TnmInput.CLIN_T, "1");
data1.setInput(TnmInput.CLIN_N, "2");
data1.setInput(TnmInput.CLIN_M, "3");
data1.setInput(TnmInput.PATH_T, "4");
data1.setInput(TnmInput.PATH_N, "5");
data1.setInput(TnmInput.PATH_M, "6");
data1.setSsf(1, "020");
TnmStagingData data2 = new TnmStagingData.TnmStagingInputBuilder()
.withInput(TnmInput.PRIMARY_SITE, "C680")
.withInput(TnmInput.HISTOLOGY, "8000")
.withInput(TnmInput.BEHAVIOR, "3")
.withInput(TnmInput.GRADE, "9")
.withInput(TnmInput.DX_YEAR, "2013")
.withInput(TnmInput.REGIONAL_NODES_POSITIVE, "99")
.withInput(TnmInput.AGE_AT_DX, "060")
.withInput(TnmInput.SEX, "1")
.withInput(TnmInput.RX_SUMM_SURGERY, "8")
.withInput(TnmInput.RX_SUMM_RADIATION, "9")
.withInput(TnmInput.CLIN_T, "1")
.withInput(TnmInput.CLIN_N, "2")
.withInput(TnmInput.CLIN_M, "3")
.withInput(TnmInput.PATH_T, "4")
.withInput(TnmInput.PATH_N, "5")
.withInput(TnmInput.PATH_M, "6")
.withSsf(1, "020").build();
assertThat(data1.getInput()).isEqualTo(data2.getInput());
}
@Test
public void testTnmStaging() throws IOException {
TnmStagingData data = new TnmStagingInputBuilder()
.withInput(TnmInput.PRIMARY_SITE, "C680")
.withInput(TnmInput.HISTOLOGY, "8000")
.withInput(TnmInput.BEHAVIOR, "3")
.withInput(TnmInput.DX_YEAR, "2016")
.withInput(TnmInput.RX_SUMM_SURGERY, "2")
.withInput(TnmInput.RX_SUMM_RADIATION, "4")
.withInput(TnmInput.REGIONAL_NODES_POSITIVE, "02")
.withInput(TnmInput.CLIN_T, "c0")
.withInput(TnmInput.CLIN_N, "c1")
.withInput(TnmInput.CLIN_M, "c0")
.withInput(TnmInput.PATH_T, "p0")
.withInput(TnmInput.PATH_N, "p1")
.withInput(TnmInput.PATH_M, "p1")
.build();
// perform the staging
StagingData output = _STAGING.stage("tnm", "1.9", data.getInput()).execute().body();
// check output
assertThat(output).isNotNull();
assertThat(output.getResult()).isEqualTo(StagingData.Result.STAGED);
assertThat(output.getSchemaId()).isEqualTo("urethra");
assertThat(output.getErrors()).isEmpty();
assertThat(output.getPath()).hasSize(25);
assertThat(output.getOutput()).hasSize(10);
// check outputs
assertThat(output.getOutput(TnmOutput.DERIVED_VERSION.toString())).isEqualTo("1.9");
assertThat(output.getOutput(TnmOutput.CLIN_STAGE_GROUP.toString())).isEqualTo("3");
assertThat(output.getOutput(TnmOutput.PATH_STAGE_GROUP.toString())).isEqualTo("4");
assertThat(output.getOutput(TnmOutput.COMBINED_STAGE_GROUP.toString())).isEqualTo("4");
assertThat(output.getOutput(TnmOutput.COMBINED_T.toString())).isEqualTo("c0");
assertThat(output.getOutput(TnmOutput.SOURCE_T.toString())).isEqualTo("1");
assertThat(output.getOutput(TnmOutput.COMBINED_N.toString())).isEqualTo("c1");
assertThat(output.getOutput(TnmOutput.SOURCE_N.toString())).isEqualTo("1");
assertThat(output.getOutput(TnmOutput.COMBINED_M.toString())).isEqualTo("p1");
assertThat(output.getOutput(TnmOutput.SOURCE_M.toString())).isEqualTo("2");
}
@Test
public void testEodInputBuilder() {
EodStagingData data1 = new EodStagingData();
data1.setInput(EodInput.PRIMARY_SITE, "C250");
data1.setInput(EodInput.HISTOLOGY, "8154");
data1.setInput(EodInput.DX_YEAR, "2018");
data1.setInput(EodInput.AGE_AT_DX, "060");
data1.setInput(EodInput.SEX, "1");
data1.setInput(EodInput.TUMOR_SIZE_SUMMARY, "004");
data1.setInput(EodInput.NODES_POS, "03");
data1.setInput(EodInput.EOD_PRIMARY_TUMOR, "500");
data1.setInput(EodInput.EOD_REGIONAL_NODES, "300");
data1.setInput(EodInput.EOD_METS, "10");
EodStagingData data2 = new EodStagingInputBuilder()
.withInput(EodInput.PRIMARY_SITE, "C250")
.withInput(EodInput.HISTOLOGY, "8154")
.withInput(EodInput.DX_YEAR, "2018")
.withInput(EodInput.AGE_AT_DX, "060")
.withInput(EodInput.SEX, "1")
.withInput(EodInput.TUMOR_SIZE_SUMMARY, "004")
.withInput(EodInput.NODES_POS, "03")
.withInput(EodInput.EOD_PRIMARY_TUMOR, "500")
.withInput(EodInput.EOD_REGIONAL_NODES, "300")
.withInput(EodInput.EOD_METS, "10").build();
assertThat(data1.getInput()).isEqualTo(data2.getInput());
}
@Test
public void testEodStaging() throws IOException {
EodStagingData data = new EodStagingInputBuilder()
.withInput(EodInput.PRIMARY_SITE, "C250")
.withInput(EodInput.HISTOLOGY, "8154")
.withInput(EodInput.DX_YEAR, "2018")
.withInput(EodInput.TUMOR_SIZE_SUMMARY, "004")
.withInput(EodInput.NODES_POS, "03")
.withInput(EodInput.EOD_PRIMARY_TUMOR, "500")
.withInput(EodInput.EOD_REGIONAL_NODES, "300")
.withInput(EodInput.EOD_METS, "10").build();
// perform the staging
StagingData output = _STAGING.stage("eod_public", "2.1", data.getInput()).execute().body();
assertThat(output).isNotNull();
assertThat(output.getResult()).isEqualTo(StagingData.Result.STAGED);
assertThat(output.getSchemaId()).isEqualTo("pancreas");
assertThat(output.getErrors()).isEmpty();
assertThat(output.getPath()).hasSize(12);
assertThat(output.getOutput()).hasSize(9);
// check outputs
assertThat(output.getOutput(EodOutput.DERIVED_VERSION.toString())).isEqualTo("2.1");
assertThat(output.getOutput(EodOutput.SS_2018_DERIVED.toString())).isEqualTo("7");
assertThat(output.getOutput(EodOutput.NAACCR_SCHEMA_ID.toString())).isEqualTo("00280");
assertThat(output.getOutput(EodOutput.EOD_2018_STAGE_GROUP.toString())).isEqualTo("4");
assertThat(output.getOutput(EodOutput.EOD_2018_T.toString())).isEqualTo("T1a");
assertThat(output.getOutput(EodOutput.EOD_2018_N.toString())).isEqualTo("N1");
assertThat(output.getOutput(EodOutput.EOD_2018_M.toString())).isEqualTo("M1");
assertThat(output.getOutput(EodOutput.AJCC_ID.toString())).isEqualTo("28");
}
@Test
public void testStagingWithErrors() throws IOException {
StagingData data = new StagingData();
data.setInput("site", "C181");
data.setInput("hist", "8093");
data.setInput("year_dx", "2015");
data.setInput("extension", "670");
// perform the staging
StagingData output = _STAGING.stage(_ALGORITHM, _VERSION, data.getInput()).execute().body();
assertThat(output).isNotNull();
assertThat(output.getResult()).isEqualTo(StagingData.Result.STAGED);
assertThat(output.getErrors()).hasSize(9);
}
@Test
public void testStagingGlossary() throws IOException {
Set<KeywordMatch> matches = _STAGING.schemaGlossary("eod_public", "2.0", "breast", null, true).execute().body();
assertThat(matches).hasSize(26);
matches = _STAGING.schemaGlossary("eod_public", "2.0", "breast", EnumSet.of(Category.STAGING), true).execute().body();
assertThat(matches).hasSize(1);
matches = _STAGING.tableGlossary("eod_public", "2.0", "cea_pretx_lab_value_33864", null, true).execute().body();
assertThat(matches).hasSize(24);
matches = _STAGING.tableGlossary("eod_public", "2.0", "cea_pretx_lab_value_33864", EnumSet.of(Category.STAGING), true).execute().body();
assertThat(matches).isEmpty();
}
@Test
public void testStagingMetadata() throws IOException {
StagingSchema schema = _STAGING.schemaById("eod_public", "2.0", "brain").execute().body();
assertThat(schema).isNotNull();
StagingSchemaInput mgmt = schema.getInputs().stream().filter(i -> i.getKey().equals("mgmt")).findFirst().orElse(null);
assertThat(mgmt).isNotNull();
assertThat(mgmt.getMetadata()).extracting("name").containsExactlyInAnyOrder("COC_REQUIRED", "SEER_REQUIRED", "SSDI");
}
@Test
public void testBeans() {
MatcherAssert.assertThat(StagingAlgorithm.class, CoreMatchers.allOf(hasValidBeanConstructor(), hasValidGettersAndSetters()));
MatcherAssert.assertThat(StagingMetadata.class, CoreMatchers.allOf(hasValidBeanConstructor(), hasValidGettersAndSetters(), hasValidBeanEquals()));
MatcherAssert.assertThat(StagingVersion.class, CoreMatchers.allOf(hasValidBeanConstructor(), hasValidGettersAndSettersExcluding("production", "beta", "development")));
MatcherAssert.assertThat(StagingSchema.class, CoreMatchers.allOf(hasValidBeanConstructor(), hasValidGettersAndSetters()));
MatcherAssert.assertThat(StagingSchemaInfo.class, CoreMatchers.allOf(hasValidBeanConstructor(), hasValidGettersAndSetters()));
MatcherAssert.assertThat(StagingSchemaInput.class, CoreMatchers.allOf(hasValidBeanConstructor(), hasValidGettersAndSetters()));
MatcherAssert.assertThat(StagingSchemaOutput.class, CoreMatchers.allOf(hasValidBeanConstructor(), hasValidGettersAndSetters()));
MatcherAssert.assertThat(StagingTable.class, CoreMatchers.allOf(hasValidBeanConstructor(), hasValidGettersAndSetters()));
MatcherAssert.assertThat(StagingTablePath.class, CoreMatchers.allOf(hasValidBeanConstructor(), hasValidGettersAndSetters()));
MatcherAssert.assertThat(StagingColumnDefinition.class, CoreMatchers.allOf(hasValidBeanConstructor(), hasValidGettersAndSetters()));
MatcherAssert.assertThat(StagingSchemaInput.class, CoreMatchers.allOf(hasValidBeanConstructor(), hasValidGettersAndSetters()));
MatcherAssert.assertThat(StagingSchemaOutput.class, CoreMatchers.allOf(hasValidBeanConstructor(), hasValidGettersAndSetters()));
MatcherAssert.assertThat(StagingMapping.class, CoreMatchers.allOf(hasValidBeanConstructor(), hasValidGettersAndSetters()));
MatcherAssert.assertThat(StagingKeyMapping.class, CoreMatchers.allOf(hasValidBeanConstructor(), hasValidGettersAndSetters()));
MatcherAssert.assertThat(StagingKeyValue.class, CoreMatchers.allOf(hasValidBeanConstructor(), hasValidGettersAndSetters()));
MatcherAssert.assertThat(StagingError.class, CoreMatchers.allOf(hasValidBeanConstructor(), hasValidGettersAndSetters()));
MatcherAssert.assertThat(YearRange.class, CoreMatchers.allOf(hasValidBeanConstructor(), hasValidGettersAndSetters()));
MatcherAssert.assertThat(YearRangeString.class, CoreMatchers.allOf(hasValidBeanConstructor(), hasValidGettersAndSetters()));
MatcherAssert.assertThat(YearRangeInteger.class, CoreMatchers.allOf(hasValidBeanConstructor(), hasValidGettersAndSetters()));
MatcherAssert.assertThat(DateRange.class, CoreMatchers.allOf(hasValidBeanConstructor(), hasValidGettersAndSetters()));
MatcherAssert.assertThat(DateRangeString.class, CoreMatchers.allOf(hasValidBeanConstructor(), hasValidGettersAndSetters()));
}
}
|
package com.milaboratory.core.mutations;
import com.milaboratory.core.alignment.Aligner;
import com.milaboratory.core.alignment.Alignment;
import com.milaboratory.core.alignment.LinearGapAlignmentScoring;
import com.milaboratory.core.sequence.NucleotideSequence;
import org.junit.Assert;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
/**
* @author Dmitry Bolotin
* @author Stanislav Poslavsky
*/
public class MutationsTest {
@Test
public void testCombine1() throws Exception {
NucleotideSequence seq1 = new NucleotideSequence("ATTAGACA"),
seq2 = new NucleotideSequence("CATTACCA"),
seq3 = new NucleotideSequence("CATAGCCA");
Mutations<NucleotideSequence> m1 = Aligner.alignGlobal(LinearGapAlignmentScoring.getNucleotideBLASTScoring(), seq1, seq2).getGlobalMutations(),
m2 = Aligner.alignGlobal(LinearGapAlignmentScoring.getNucleotideBLASTScoring(), seq2, seq3).getGlobalMutations();
checkMutations(m1);
checkMutations(m2);
Mutations<NucleotideSequence> m3 = m1.combineWith(m2);
assertTrue(MutationsUtil.check(m3));
Assert.assertEquals(seq3, m3.mutate(seq1));
}
@Test
public void testCombine2() throws Exception {
NucleotideSequence seq1 = new NucleotideSequence("ACGTGTTACCGGTGATT"),
seq2 = new NucleotideSequence("AGTTCTTGTTTTTTCCGTAC"),
seq3 = new NucleotideSequence("ATCCGTAAATTACGTGCTGT");
Mutations<NucleotideSequence> m1 = Aligner.alignGlobal(LinearGapAlignmentScoring.getNucleotideBLASTScoring(), seq1, seq2).getGlobalMutations(),
m2 = Aligner.alignGlobal(LinearGapAlignmentScoring.getNucleotideBLASTScoring(), seq2, seq3).getGlobalMutations();
Mutations<NucleotideSequence> m3 = m1.combineWith(m2);
assertTrue(MutationsUtil.check(m3));
checkMutations(m1);
checkMutations(m2);
checkMutations(m3);
Assert.assertEquals(seq3, m3.mutate(seq1));
}
@Test
public void testCombine3() throws Exception {
NucleotideSequence seq1 = new NucleotideSequence("AACTGCTAACTCGA"),
seq2 = new NucleotideSequence("CGAACGTTAAGCACAAA"),
seq3 = new NucleotideSequence("CAAATGTGAGATC");
Mutations<NucleotideSequence> m1 = Aligner.alignGlobal(LinearGapAlignmentScoring.getNucleotideBLASTScoring(), seq1, seq2).getGlobalMutations(),
m2 = Aligner.alignGlobal(LinearGapAlignmentScoring.getNucleotideBLASTScoring(), seq2, seq3).getGlobalMutations();
Mutations<NucleotideSequence> m3 = m1.combineWith(m2);
assertTrue(MutationsUtil.check(m3));
checkMutations(m1);
checkMutations(m2);
checkMutations(m3);
Assert.assertEquals(seq3, m3.mutate(seq1));
}
@Test
public void testBS() throws Exception {
NucleotideSequence
seq1 = new NucleotideSequence("TGACCCGTAACCCCCCGGT"),
seq2 = new NucleotideSequence("CGTAACTTCAGCCT");
Alignment<NucleotideSequence> alignment = Aligner.alignGlobal(LinearGapAlignmentScoring.getNucleotideBLASTScoring(),
seq1, seq2);
// AlignmentHelper helper = alignment.getAlignmentHelper();
// System.out.println(helper);
// int p;
// for (int i = helper.size() - 1; i >= 0; --i) {
// if ((p = helper.convertPositionToSeq1(i)) > 0)
// assertEquals(NucleotideSequence.ALPHABET.symbolFromCode(seq1.codeAt(p)),
// helper.getLine1().charAt(i));
// if ((p = helper.convertPositionToSeq2(i)) > 0)
// assertEquals(NucleotideSequence.ALPHABET.symbolFromCode(seq2.codeAt(p)),
// helper.getLine3().charAt(i));
Mutations<NucleotideSequence> mutations = alignment.getGlobalMutations();
checkMutations(mutations);
Assert.assertEquals(-1, mutations.firstMutationWithPosition(-1));
Assert.assertEquals(3, mutations.firstMutationWithPosition(3));
Assert.assertEquals(4, mutations.firstMutationWithPosition(4));
Assert.assertEquals(-6, mutations.firstMutationWithPosition(5));
Assert.assertEquals(5, mutations.firstMutationWithPosition(11));
Assert.assertEquals(7, mutations.firstMutationWithPosition(12));
Assert.assertEquals(8, mutations.firstMutationWithPosition(13));
}
public static void checkMutations(Mutations mutations) {
assertEquals("Encode/Decode", mutations, Mutations.decode(mutations.encode(), NucleotideSequence.ALPHABET));
}
@Test
public void test1() throws Exception {
MutationsBuilder<NucleotideSequence> builder = new MutationsBuilder<>(NucleotideSequence.ALPHABET);
builder.appendDeletion(1, 2);
builder.appendDeletion(2, 1);
builder.appendSubstitution(7, 3, 1);
builder.appendInsertion(9, 2);
builder.appendSubstitution(10, 3, 1);
Mutations<NucleotideSequence> mutations = builder.createAndDestroy();
assertEquals(1, mutations.getPositionByIndex(0));
assertEquals(1, mutations.getFromByIndex(1));
assertEquals(3, mutations.getFromByIndex(2));
assertEquals(1, mutations.getToByIndex(2));
assertEquals(9, mutations.getPositionByIndex(3));
assertEquals(2, mutations.getToByIndex(3));
assertEquals(1, mutations.getToByIndex(4));
assertEquals(10, mutations.getPositionByIndex(4));
}
@Test
public void test2() throws Exception {
MutationsBuilder<NucleotideSequence> builder = new MutationsBuilder<>(NucleotideSequence.ALPHABET);
builder.appendDeletion(1, 2);
builder.appendDeletion(2, 1);
builder.appendSubstitution(7, 3, 1);
builder.appendInsertion(9, 2);
builder.appendSubstitution(10, 3, 1);
Mutations<NucleotideSequence> mutations = builder.createAndDestroy();
assertEquals(1, mutations.firsMutationPosition());
assertEquals(10, mutations.lastMutationPosition());
}
}
|
package com.pm.server.repository;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import com.pm.server.TestTemplate;
import com.pm.server.datatype.Coordinate;
import com.pm.server.datatype.CoordinateImpl;
import com.pm.server.datatype.PlayerState;
import com.pm.server.player.Pacman;
import com.pm.server.player.PacmanImpl;
public class PacmanRepositoryTest extends TestTemplate {
private List<Pacman> pacmanList = new ArrayList<Pacman>();
private final static Integer numOfPacmans = 2;
private static final List<Integer> randomIdList = Arrays.asList(
95873,
30839,
34918
);
private static final List<Coordinate> randomCoordinateList = Arrays.asList(
new CoordinateImpl(45983.39872, 98347.39182),
new CoordinateImpl(39487.22889, 90893.32281),
new CoordinateImpl(49990.12929, 48982.39489)
);
@Autowired
private PacmanRepository pacmanRepository;
private static final Logger log =
LogManager.getLogger(PacmanRepositoryTest.class.getName());
@Before
public void setUp() {
for(Integer i = 0; i < numOfPacmans; i++) {
// Arbitrary decimal values
Coordinate coordinate = new CoordinateImpl(
(i+12345.6789) / 100,
(i-9876.54321) / 100
);
Pacman pacman = new PacmanImpl();
pacman.setId(i);
pacman.setLocation(coordinate);
pacmanList.add(pacman);
}
assert(pacmanList.size() == numOfPacmans);
}
@After
public void cleanUp() {
pacmanRepository.clearPlayers();
assert(pacmanRepository.getPlayer() == null);
pacmanList.clear();
assert(pacmanList.size() == 0);
}
@Test
public void unitTest_addPlayer() {
// Given
Pacman pacman = pacmanList.get(0);
// When
addPlayer_failUponException(pacman);
// Then
Pacman pacmanReturned = pacmanRepository.getPlayer();
assertEquals(pacman.getId(), pacmanReturned.getId());
assertEquals(pacman.getLocation(), pacmanReturned.getLocation());
}
@Test
public void unitTest_addPlayer_noId() {
// Given
Pacman pacman = pacmanList.get(0);
pacman.setId(null);
// When
addPlayer_failUponException(pacman);
// Then
Pacman pacman_returned = pacmanRepository.getPlayer();
assertEquals(pacman.getLocation(), pacman_returned.getLocation());
}
@Test
public void unitTest_addPlayer_noLocation() {
// Given
Pacman pacman = pacmanList.get(0);
pacman.setLocation(null);
// When
addPlayer_failUponException(pacman);
// Then
Pacman pacman_returned = pacmanRepository.getPlayer();
assertEquals(pacman.getId(), pacman_returned.getId());
}
@Test
public void unitTest_addPlayer_nullPlayer() {
// Given
// When
addPlayer_failUponException(null);
// Then
assertNull(pacmanRepository.getPlayer());
}
@Test(expected = IllegalStateException.class)
public void unitTest_addPlayer_pacmanAlreadyExists() throws Exception {
// Given
Pacman pacman1 = pacmanList.get(0);
Pacman pacman2 = pacmanList.get(1);
addPlayer_failUponException(pacman1);
// When
pacmanRepository.addPlayer(pacman2);
// Then
// Exception thrown above
}
@Test
public void unitTest_deletePlayerById() {
// Given
addPlayer_failUponException(pacmanList.get(0));
Integer randomId = randomIdList.get(0);
// When
try {
pacmanRepository.deletePlayerById(randomId);
}
catch(Exception e) {
log.error(e.getMessage());
fail();
}
// Then
assertNull(pacmanRepository.getPlayer());
}
@Test
public void unitTest_deletePlayerById_noId() {
// Given
addPlayer_failUponException(pacmanList.get(0));
// When
try {
pacmanRepository.deletePlayerById(null);
}
catch(Exception e) {
log.error(e.getMessage());
fail();
}
// Then
assertNull(pacmanRepository.getPlayer());
}
@Test(expected = IllegalStateException.class)
public void unitTest_deletePlayerById_noPlayer() throws Exception {
// Given
Integer randomId = randomIdList.get(0);
// When
pacmanRepository.deletePlayerById(randomId);
// Then
// Exception thrown above
}
@Test
public void unitTest_clearPlayers() {
// Given
addPlayer_failUponException(pacmanList.get(0));
// When
pacmanRepository.clearPlayers();
// Then
assertNull(pacmanRepository.getPlayer());
}
@Test
public void unitTest_getPlayerById() {
// Given
Pacman pacman = pacmanList.get(0);
addPlayer_failUponException(pacman);
Integer randomId = randomIdList.get(0);
// When
Pacman pacmanReturned = pacmanRepository.getPlayerById(randomId);
// Then
assertSame(pacman.getLocation(), pacmanReturned.getLocation());
}
@Test
public void unitTest_getPlayerById_nullAddedId() {
// Given
Pacman pacman = pacmanList.get(0);
pacman.setId(null);
addPlayer_failUponException(pacman);
Integer randomId = randomIdList.get(0);
// When
Pacman pacmanReturned = pacmanRepository.getPlayerById(randomId);
// Then
assertSame(pacman.getLocation(), pacmanReturned.getLocation());
}
@Test
public void unitTest_getPlayerById_nullRequestedId() {
// Given
Pacman pacman = pacmanList.get(0);
addPlayer_failUponException(pacman);
// When
Pacman pacmanReturned = pacmanRepository.getPlayerById(null);
// Then
assertSame(pacman.getLocation(), pacmanReturned.getLocation());
}
@Test
public void unitTest_getPlayerById_noPacman() {
// Given
Integer randomId = randomIdList.get(0);
// When
Pacman pacmanReturned = pacmanRepository.getPlayerById(randomId);
// Then
assertNull(pacmanReturned);
}
@Test
public void unitTest_getPlayer() {
// Given
Pacman pacman = pacmanList.get(0);
addPlayer_failUponException(pacman);
// When
Pacman pacmanReturned = pacmanRepository.getPlayer();
// Then
assertEquals(pacman, pacmanReturned);
}
@Test
public void unitTest_getPlayer_noPacman() {
// Given
// When
Pacman pacmanReturned = pacmanRepository.getPlayer();
// Then
assertNull(pacmanReturned);
}
@Test
public void unitTest_getAllPlayers() {
// Given
Pacman pacman = pacmanList.get(0);
addPlayer_failUponException(pacman);
// When
List<Pacman> pacmanReturnedList = pacmanRepository.getAllPlayers();
// Then
assertSame(pacman, pacmanReturnedList.get(0));
}
@Test
public void unitTest_getAllPlayers_noPacman() {
// Given
// When
List<Pacman> pacmanReturnedList = pacmanRepository.getAllPlayers();
// Then
assertTrue(pacmanReturnedList.isEmpty());
}
@Test
public void unitTest_setPlayerLocationById() {
// Given
Pacman pacman = pacmanList.get(0);
addPlayer_failUponException(pacman);
Coordinate newLocation = randomCoordinateList.get(0);
// When
pacmanRepository.setPlayerLocationById(pacman.getId(), newLocation);
// Then
Pacman pacmanReturned = pacmanRepository.getPlayer();
assertSame(newLocation, pacmanReturned.getLocation());
}
@Test
public void unitTest_setPlayerLocationById_randomId() {
// Given
Pacman pacman = pacmanList.get(0);
addPlayer_failUponException(pacman);
Integer randomId = randomIdList.get(0);
Coordinate newLocation = randomCoordinateList.get(0);
// When
pacmanRepository.setPlayerLocationById(randomId, newLocation);
// Then
Pacman pacmanReturned = pacmanRepository.getPlayer();
assertSame(newLocation, pacmanReturned.getLocation());
}
@Test
public void unitTest_setPlayerLocationById_nullId() {
// Given
Pacman pacman = pacmanList.get(0);
addPlayer_failUponException(pacman);
Coordinate newLocation = randomCoordinateList.get(0);
// When
pacmanRepository.setPlayerLocationById(null, newLocation);
// Then
Pacman pacmanReturned = pacmanRepository.getPlayer();
assertSame(newLocation, pacmanReturned.getLocation());
}
@Test(expected = NullPointerException.class)
public void unitTest_setPlayerLocationById_nullLocation() {
// Given
Integer randomId = randomIdList.get(0);
// When
pacmanRepository.setPlayerLocationById(randomId, null);
// Then
// Exception thrown above
}
@Test(expected = IllegalStateException.class)
public void unitTest_setPlayerLocationById_noPacman()
throws IllegalArgumentException {
// Given
Integer randomId = randomIdList.get(0);
Coordinate newLocation = randomCoordinateList.get(0);
// When
pacmanRepository.setPlayerLocationById(randomId, newLocation);
// Then
// Exception thrown above
}
@Test
public void unitTest_setPlayerLocation() {
// Given
Pacman pacman = pacmanList.get(0);
addPlayer_failUponException(pacman);
Coordinate newLocation = randomCoordinateList.get(0);
// When
pacmanRepository.setPlayerLocation(newLocation);
// Then
Pacman pacmanReturned = pacmanRepository.getPlayer();
assertSame(newLocation, pacmanReturned.getLocation());
}
@Test(expected = NullPointerException.class)
public void unitTest_setPlayerLocation_nullLocation() {
// Given
// When
pacmanRepository.setPlayerLocation(null);
// Then
// Exception thrown above
}
@Test(expected = IllegalStateException.class)
public void unitTest_setPlayerLocation_noPacman()
throws IllegalArgumentException {
// Given
Coordinate newLocation = randomCoordinateList.get(0);
// When
pacmanRepository.setPlayerLocation(newLocation);
// Then
// Exception thrown above
}
@Test
public void unitTest_setPlayerStateById() {
// Given
Pacman pacman = pacmanList.get(0);
addPlayer_failUponException(pacman);
PlayerState newState = PlayerState.ACTIVE;
// When
pacmanRepository.setPlayerStateById(pacman.getId(), newState);
// Then
Pacman pacmanResult = pacmanRepository.getPlayer();
assertEquals(newState, pacmanResult.getState());
}
@Test
public void unitTest_setPlayerStateById_sameState() {
// Given
Pacman pacman = pacmanList.get(0);
addPlayer_failUponException(pacman);
PlayerState newState = PlayerState.ACTIVE;
pacmanRepository.setPlayerState(newState);
// When
pacmanRepository.setPlayerStateById(pacman.getId(), newState);
// Then
Pacman pacmanResult = pacmanRepository.getPlayer();
assertEquals(newState, pacmanResult.getState());
}
@Test
public void unitTest_setPlayerStateById_nullId() {
// Given
Pacman pacman = pacmanList.get(0);
addPlayer_failUponException(pacman);
PlayerState newState = PlayerState.ACTIVE;
// When
pacmanRepository.setPlayerStateById(null, newState);
// Then
Pacman pacmanResult = pacmanRepository.getPlayer();
assertEquals(newState, pacmanResult.getState());
}
@Test(expected = NullPointerException.class)
public void unitTest_setPlayerStateById_nullState() {
// Given
Pacman pacman = pacmanList.get(0);
addPlayer_failUponException(pacman);
// When
pacmanRepository.setPlayerStateById(pacman.getId(), null);
// Then
// Exception thrown above
}
@Test
public void unitTest_setPlayerState() {
// Given
Pacman pacman = pacmanList.get(0);
addPlayer_failUponException(pacman);
PlayerState newState = PlayerState.ACTIVE;
// When
pacmanRepository.setPlayerState(newState);
// Then
Pacman pacmanResult = pacmanRepository.getPlayer();
assertEquals(newState, pacmanResult.getState());
}
@Test
public void unitTest_setPlayerState_sameState() {
// Given
Pacman pacman = pacmanList.get(0);
addPlayer_failUponException(pacman);
PlayerState newState = PlayerState.ACTIVE;
pacmanRepository.setPlayerState(newState);
// When
pacmanRepository.setPlayerState(newState);
// Then
Pacman pacmanResult = pacmanRepository.getPlayer();
assertEquals(newState, pacmanResult.getState());
}
@Test(expected = NullPointerException.class)
public void unitTest_setPlayerState_nullState() {
// Given
Pacman pacman = pacmanList.get(0);
addPlayer_failUponException(pacman);
// When
pacmanRepository.setPlayerState(null);
// Then
// Exception thrown above
}
@Test
public void unitTest_clearPlayers_noPlayer() {
// Given
// When
pacmanRepository.clearPlayers();
// Then
assertNull(pacmanRepository.getPlayer());
}
@Test
public void unitTest_numOfPlayers_0players() {
// Given
// When
Integer numOfPlayers = pacmanRepository.numOfPlayers();
// Then
assertEquals((Integer)0, numOfPlayers);
}
@Test
public void unitTest_numofPlayers_1player() {
// Given
addPlayer_failUponException(pacmanList.get(0));
// When
Integer numOfPlayers = pacmanRepository.numOfPlayers();
// Then
assertEquals((Integer)1, numOfPlayers);
}
private void addPlayer_failUponException(Pacman pacman) {
try {
pacmanRepository.addPlayer(pacman);
}
catch (Exception e) {
log.error(e.getMessage());
fail();
}
}
}
|
package oshi;
import junit.framework.TestCase;
import oshi.hardware.HardwareAbstractionLayer;
import oshi.hardware.Memory;
import oshi.hardware.Processor;
import oshi.software.os.OperatingSystem;
import oshi.software.os.OperatingSystemVersion;
import oshi.util.FormatUtil;
/**
* @author dblock[at]dblock[dot]org
*/
public class SystemInfoTests extends TestCase {
public static void main(String[] args) {
SystemInfo si = new SystemInfo();
// software
// software: operating system
OperatingSystem os = si.getOperatingSystem();
System.out.println(os);
// hardware
HardwareAbstractionLayer hal = si.getHardware();
// hardware: processors
System.out.println(hal.getProcessors().length + " CPU(s):");
for(Processor cpu : hal.getProcessors()) {
System.out.println(" " + cpu);
}
// hardware: memory
System.out.println("Memory: " +
FormatUtil.formatBytes(hal.getMemory().getAvailable()) + "/" +
FormatUtil.formatBytes(hal.getMemory().getTotal()));
}
public void testGetVersion() {
SystemInfo si = new SystemInfo();
OperatingSystem os = si.getOperatingSystem();
assertNotNull(os);
OperatingSystemVersion version = os.getVersion();
assertNotNull(version);
assertTrue(os.toString().length() > 0);
}
public void testGetProcessors() {
SystemInfo si = new SystemInfo();
HardwareAbstractionLayer hal = si.getHardware();
assertTrue(hal.getProcessors().length > 0);
}
public void testGetMemory() {
SystemInfo si = new SystemInfo();
HardwareAbstractionLayer hal = si.getHardware();
Memory memory = hal.getMemory();
assertNotNull(memory);
assertTrue(memory.getTotal() > 0);
assertTrue(memory.getAvailable() >= 0);
assertTrue(memory.getAvailable() <= memory.getTotal());
}
}
|
package com.poiji.deserialize;
import com.poiji.deserialize.model.EmployeeExtended;
import com.poiji.exception.PoijiException;
import com.poiji.internal.Poiji;
import com.poiji.option.PoijiOptions;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import java.io.File;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import static org.hamcrest.CoreMatchers.instanceOf;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.CoreMatchers.not;
import static org.hamcrest.CoreMatchers.notNullValue;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.fail;
@RunWith(Parameterized.class)
public class DerializersExtendedTest {
private String path;
private List<EmployeeExtended> expectedEmployess;
private Class<?> expectedException;
public DerializersExtendedTest(String path, List<EmployeeExtended> expectedEmployess, Class<?> expectedException) {
this.path = path;
this.expectedEmployess = expectedEmployess;
this.expectedException = expectedException;
}
@Parameterized.Parameters(name = "{index}: ({0})={1}")
public static Iterable<Object[]> queries() throws Exception {
return Arrays.asList(new Object[][]{
{"src/test/resources/employees_extended.xls", unmarshalling(), null},
{"src/test/resources/cloud.xls", unmarshalling(), PoijiException.class},
});
}
@Test
public void shouldMapExcelToJava() {
try {
PoijiOptions options = PoijiOptions.PoijiOptionsBuilder.settings().skip(1).datePattern("dd/mm/yyyy").build();
List<EmployeeExtended> actualEmployees = Poiji.fromExcel(new File(path), EmployeeExtended.class, options);
assertThat(actualEmployees, notNullValue());
assertThat(actualEmployees.size(), not(0));
assertThat(actualEmployees.size(), is(expectedEmployess.size()));
EmployeeExtended actualEmployee1 = actualEmployees.get(0);
EmployeeExtended actualEmployee2 = actualEmployees.get(1);
EmployeeExtended actualEmployee3 = actualEmployees.get(2);
EmployeeExtended expectedEmployee1 = expectedEmployess.get(0);
EmployeeExtended expectedEmployee2 = expectedEmployess.get(1);
EmployeeExtended expectedEmployee3 = expectedEmployess.get(2);
assertThat(actualEmployee1.toString(), is(expectedEmployee1.toString()));
assertThat(actualEmployee2.toString(), is(expectedEmployee2.toString()));
assertThat(actualEmployee3.toString(), is(expectedEmployee3.toString()));
} catch (Exception e) {
if (expectedException == null) {
fail(e.getMessage());
} else {
assertThat(e, instanceOf(expectedException));
}
}
}
private static List<EmployeeExtended> unmarshalling() throws ParseException {
List<EmployeeExtended> employees = new ArrayList<>(3);
SimpleDateFormat sdf = new SimpleDateFormat("dd/mm/yyyy");
EmployeeExtended employee1 = new EmployeeExtended();
employee1.setEmployeeId(123923L);
employee1.setName("Joe");
employee1.setSurname("Doe");
employee1.setSingle(true);
employee1.setAge(30);
employee1.setBirthday("4/9/1987");
employee1.setRate(4.9);
employee1.setDate(sdf.parse("05/01/2017 22:00:01.0"));
employees.add(employee1);
EmployeeExtended employee2 = new EmployeeExtended();
employee2.setEmployeeId(123123L);
employee2.setName("Sophie");
employee2.setSurname("Derue");
employee2.setSingle(false);
employee2.setAge(20);
employee2.setBirthday("5/3/1997");
employee2.setRate(5.3);
employee2.setDate((sdf).parse("05/01/2017 22:00:01.0"));
employees.add(employee2);
EmployeeExtended employee3 = new EmployeeExtended();
employee3.setEmployeeId(135923L);
employee3.setName("Paul");
employee3.setSurname("Raul");
employee3.setSingle(false);
employee3.setAge(31);
employee3.setBirthday("4/9/1986");
employee3.setRate(6.6);
employee3.setDate(sdf.parse("05/01/2017 22:00:01.0"));
employees.add(employee3);
return employees;
}
}
|
package com.richodemus.dropwizard.jwt;
import com.richodemus.dropwizard.jwt.helpers.TestApp;
import com.richodemus.dropwizard.jwt.helpers.TestConfiguration;
import com.richodemus.dropwizard.jwt.helpers.model.CreateUserRequest;
import com.richodemus.dropwizard.jwt.helpers.model.CreateUserResponse;
import com.richodemus.dropwizard.jwt.helpers.model.LoginRequest;
import com.richodemus.dropwizard.jwt.model.Role;
import io.dropwizard.testing.DropwizardTestSupport;
import io.dropwizard.testing.ResourceHelpers;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import javax.ws.rs.ForbiddenException;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.Entity;
import static org.assertj.core.api.Assertions.assertThat;
public class IntegrationTest
{
private static final String EXISTING_USER = "existing_user";
private static final String EXISTING_USER_PASSWORD = "existing_user_password";
private static final Role EXISTING_USER_ROLE = new Role("user");
public DropwizardTestSupport<TestConfiguration> target;
@Before
public void setUp() throws Exception
{
target = new DropwizardTestSupport<>(TestApp.class, ResourceHelpers.resourceFilePath("conf.yaml"));
target.before();
}
@After
public void tearDown() throws Exception
{
target.after();
}
@Test
public void shouldCreateUser() throws Exception
{
final CreateUserResponse result = ClientBuilder.newClient()
.target("http://localhost:" + target.getLocalPort())
.path("api/login/new")
.request()
.post(Entity.json(new CreateUserRequest(EXISTING_USER, EXISTING_USER_PASSWORD, EXISTING_USER_ROLE.stringValue())), CreateUserResponse.class);
assertThat(result.getResult()).isEqualTo(CreateUserResponse.Result.OK);
final Token result2 = ClientBuilder.newClient()
.target("http://localhost:" + target.getLocalPort())
.path("api/login")
.request()
.post(Entity.json(new LoginRequest(EXISTING_USER, EXISTING_USER_PASSWORD)), Token.class);
assertThat(result2.getUsername()).isEqualTo(EXISTING_USER);
assertThat(result2.getRole()).isEqualTo(EXISTING_USER_ROLE.stringValue());
}
@Test(expected = ForbiddenException.class)
public void shouldLoginUser() throws Exception
{
ClientBuilder.newClient()
.target("http://localhost:" + target.getLocalPort())
.path("api/login")
.request()
.post(Entity.json(new LoginRequest(EXISTING_USER, EXISTING_USER_PASSWORD)), Token.class);
}
}
|
package com.scienceminer.nerd.mention;
import com.scienceminer.nerd.disambiguation.NerdContext;
import com.scienceminer.nerd.service.NerdQuery;
import com.scienceminer.nerd.utilities.StringPos;
import com.scienceminer.nerd.utilities.Utilities;
import org.grobid.core.analyzers.GrobidAnalyzer;
import org.grobid.core.lang.Language;
import org.grobid.core.layout.LayoutToken;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
import java.util.*;
import java.util.prefs.PreferenceChangeEvent;
import java.util.stream.Collector;
import java.util.stream.Collectors;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.CoreMatchers.notNullValue;
import static org.hamcrest.Matchers.greaterThan;
import static org.hamcrest.Matchers.hasSize;
import static org.junit.Assert.*;
public class ProcessTextTest {
private ProcessText processText = null;
static final String testText = "Other factors were also at play, said Felix Boni, head of research at " +
"James Capel in Mexico City, such as positive technicals and economic uncertainty in Argentina, " +
"which has put it and neighbouring Brazil's markets at risk.";
@Before
public void setUp() throws Exception {
processText = new ProcessText(true);
}
@Test
public void testAcronymsStringAllLower() {
String input = "A graphical model or probabilistic graphical model (PGM) is a probabilistic model.";
Map<Mention, Mention> acronyms = processText.acronymCandidates(input, new Language("en", 1.0));
assertNotNull(acronyms);
for (Map.Entry<Mention, Mention> entry : acronyms.entrySet()) {
Mention base = entry.getValue();
Mention acronym = entry.getKey();
assertEquals(input.substring(acronym.getOffsetStart(), acronym.getOffsetEnd()).trim(), "PGM");
assertEquals(base.getRawName(), "probabilistic graphical model");
}
}
@Test
@Ignore("Not yet finished")
public void testAcronymCandidates() {
String input = "We are working with Pulse Calculation Tarmac (P.C.T.) during our discovery on science";
final Map<Mention, Mention> acronyms = processText.acronymCandidates(input, new Language("en"));
assertThat(acronyms.keySet(), hasSize(1));
}
@Test
public void testAcronymsTokensAllLower() {
String input = "A graphical model or probabilistic graphical model (PGM) is a probabilistic model.";
List<LayoutToken> tokens = GrobidAnalyzer.getInstance().tokenizeWithLayoutToken(input, new Language("en", 1.0));
Map<Mention, Mention> acronyms = processText.acronymCandidates(tokens);
assertThat(acronyms.entrySet(), hasSize(1));
final ArrayList<Mention> keys = new ArrayList<>(acronyms.keySet());
final Mention shortAcronym = keys.get(0);
final Mention extendedAcronym = acronyms.get(shortAcronym);
assertThat(extendedAcronym.getRawName(), is("probabilistic graphical model"));
assertThat(input.substring(shortAcronym.getOffsetStart(), shortAcronym.getOffsetEnd()), is("PGM"));
}
@Test
public void testAcronymsTokens() {
String input = "Figure 4. \n" +
"Canonical Correspondence Analysis (CCA) diagram showing the ordination of anopheline species along the\n" +
"first two axes and their correlation with environmental variables. The first axis is horizontal, second vertical. Direction\n" +
"and length of arrows shows the degree of correlation between mosquito larvae and the variables.";
List<LayoutToken> tokens = GrobidAnalyzer.getInstance().tokenizeWithLayoutToken(input, new Language("en", 1.0));
Map<Mention, Mention> acronyms = processText.acronymCandidates(tokens);
assertNotNull(acronyms);
for (Map.Entry<Mention, Mention> entry : acronyms.entrySet()) {
Mention base = entry.getValue();
Mention acronym = entry.getKey();
assertEquals(input.substring(acronym.getOffsetStart(), acronym.getOffsetEnd()).trim(), "CCA");
assertEquals(base.getRawName(), "Canonical Correspondence Analysis");
assertThat(acronym.getOffsetStart(), is(46));
assertThat(acronym.getOffsetEnd(), is(49));
}
}
@Test
@Ignore("Failing test")
public void testPropagateAcronyms_textSyncronisedWithLayoutTokens_shouldWork() {
String input = "The Pulse Covariant Transmission (PCT) is a great deal. We are going to make it great again.\n " +
"We propose a new methodology where the PCT results are improving in the gamma ray action matter.";
final Language language = new Language("en");
List<LayoutToken> tokens = GrobidAnalyzer.getInstance().tokenizeWithLayoutToken(input, language);
NerdQuery aQuery = new NerdQuery();
aQuery.setText(input);
aQuery.setTokens(tokens);
final HashMap<Mention, Mention> acronyms = new HashMap<>();
Mention base = new Mention("Pulse Covariant Transmission");
base.setOffsetStart(4);
base.setOffsetEnd(32);
final LayoutToken baseLayoutToken1 = new LayoutToken("Pulse");
baseLayoutToken1.setOffset(4);
final LayoutToken baseLayoutToken2 = new LayoutToken(" ");
baseLayoutToken2.setOffset(9);
final LayoutToken baseLayoutToken3 = new LayoutToken("Covariant");
baseLayoutToken3.setOffset(10);
final LayoutToken baseLayoutToken4 = new LayoutToken(" ");
baseLayoutToken4.setOffset(19);
final LayoutToken baseLayoutToken5 = new LayoutToken("Transmission");
baseLayoutToken5.setOffset(20);
final LayoutToken baseLayoutToken6 = new LayoutToken(" ");
baseLayoutToken6.setOffset(21);
Mention acronym = new Mention("PCT");
acronym.setNormalisedName("Pulse Covariant Transmission");
acronym.setOffsetStart(34);
acronym.setOffsetEnd(37);
acronym.setIsAcronym(true);
final LayoutToken acronymLayoutToken = new LayoutToken("PCT");
acronymLayoutToken.setOffset(34);
acronym.setLayoutTokens(Arrays.asList(acronymLayoutToken));
acronyms.put(acronym, base);
final NerdContext nerdContext = new NerdContext();
nerdContext.setAcronyms(acronyms);
aQuery.setContext(nerdContext);
final List<Mention> mentions = processText.propagateAcronyms(aQuery);
assertThat(mentions, hasSize(1));
assertThat(mentions.get(0).getRawName(), is("PCT"));
assertThat(mentions.get(0).getOffsetStart(), is(133));
assertThat(mentions.get(0).getOffsetEnd(), is(136));
assertThat(mentions.get(0).getLayoutTokens(), is(Arrays.asList(tokens.get(53))));
assertThat(mentions.get(0).getBoundingBoxes(), hasSize(greaterThan(0)));
}
@Test
@Ignore("Failing test")
public void testPropagateAcronyms_textNotSyncronisedWithLayoutTokens_shouldWork() {
String input = "The Pulse Covariant Transmission (PCT) is a great deal. We are going to make it great again.\n " +
"We propose a new methodology where the PCT results are improving in the gamma ray action matter.";
final Language language = new Language("en");
List<LayoutToken> tokens = GrobidAnalyzer.getInstance().tokenizeWithLayoutToken(input, language);
tokens = tokens.stream()
.map(layoutToken -> {
layoutToken.setOffset(layoutToken.getOffset() + 10);
return layoutToken;
}).collect(Collectors.toList());
NerdQuery aQuery = new NerdQuery();
aQuery.setText(input);
aQuery.setTokens(tokens);
processText.acronymCandidates(tokens);
final HashMap<Mention, Mention> acronyms = new HashMap<>();
Mention base = new Mention("Pulse Covariant Transmission");
base.setOffsetStart(14);
base.setOffsetEnd(42);
final LayoutToken baseLayoutToken1 = new LayoutToken("Pulse");
baseLayoutToken1.setOffset(4);
final LayoutToken baseLayoutToken2 = new LayoutToken(" ");
baseLayoutToken2.setOffset(9);
final LayoutToken baseLayoutToken3 = new LayoutToken("Covariant");
baseLayoutToken3.setOffset(10);
final LayoutToken baseLayoutToken4 = new LayoutToken(" ");
baseLayoutToken4.setOffset(19);
final LayoutToken baseLayoutToken5 = new LayoutToken("Transmission");
baseLayoutToken5.setOffset(20);
final LayoutToken baseLayoutToken6 = new LayoutToken(" ");
baseLayoutToken6.setOffset(21);
Mention acronym = new Mention("PCT");
acronym.setNormalisedName("Pulse Covariant Transmission");
acronym.setOffsetStart(44);
acronym.setOffsetEnd(47);
acronym.setIsAcronym(true);
final LayoutToken acronymLayoutToken = new LayoutToken("PCT");
acronymLayoutToken.setOffset(44);
acronym.setLayoutTokens(Arrays.asList(acronymLayoutToken));
acronyms.put(acronym, base);
final NerdContext nerdContext = new NerdContext();
nerdContext.setAcronyms(acronyms);
aQuery.setContext(nerdContext);
final List<Mention> mentions = processText.propagateAcronyms(aQuery);
assertThat(mentions, hasSize(1));
assertThat(mentions.get(0).getRawName(), is("PCT"));
assertThat(mentions.get(0).getOffsetStart(), is(143));
assertThat(mentions.get(0).getOffsetEnd(), is(146));
assertThat(mentions.get(0).getBoundingBoxes(), hasSize(greaterThan(0)));
assertThat(mentions.get(0).getLayoutTokens(), is(Arrays.asList(tokens.get(63))));
}
@Test
@Ignore("To be activated once propagateLayout has been patched")
public void testPropagateAcronyms_textNotSyncronisedWithLayoutTokens2_shouldWork() {
String input = "The Pulse Covariant Transmission (P.C.T.) is a great deal. We are going to make it great again.\n " +
"We propose a new methodology where the P.C.T. results are improving in the gamma ray action matter. " +
"P.C.T. is good for you";
final Language language = new Language("en");
List<LayoutToken> tokens = GrobidAnalyzer.getInstance().tokenizeWithLayoutToken(input, language);
tokens = tokens.stream()
.map(layoutToken -> {
layoutToken.setOffset(layoutToken.getOffset() + 10);
return layoutToken;
}).collect(Collectors.toList());
NerdQuery aQuery = new NerdQuery();
aQuery.setText(input);
aQuery.setTokens(tokens);
processText.acronymCandidates(tokens);
final HashMap<Mention, Mention> acronyms = new HashMap<>();
Mention base = new Mention("Pulse Covariant Transmission");
base.setOffsetStart(14);
base.setOffsetEnd(42);
final LayoutToken baseLayoutToken1 = new LayoutToken("Pulse");
baseLayoutToken1.setOffset(4);
final LayoutToken baseLayoutToken2 = new LayoutToken(" ");
baseLayoutToken2.setOffset(9);
final LayoutToken baseLayoutToken3 = new LayoutToken("Covariant");
baseLayoutToken3.setOffset(10);
final LayoutToken baseLayoutToken4 = new LayoutToken(" ");
baseLayoutToken4.setOffset(19);
final LayoutToken baseLayoutToken5 = new LayoutToken("Transmission");
baseLayoutToken5.setOffset(20);
final LayoutToken baseLayoutToken6 = new LayoutToken(" ");
baseLayoutToken6.setOffset(21);
Mention acronym = new Mention("P.C.T.");
acronym.setNormalisedName("Pulse Covariant Transmission");
acronym.setOffsetStart(44);
acronym.setOffsetEnd(47);
acronym.setIsAcronym(true);
final LayoutToken acronymLayoutToken1 = new LayoutToken("P");
acronymLayoutToken1.setOffset(44);
final LayoutToken acronymLayoutToken2 = new LayoutToken(".");
acronymLayoutToken2.setOffset(45);
final LayoutToken acronymLayoutToken3 = new LayoutToken("C");
acronymLayoutToken3.setOffset(46);
final LayoutToken acronymLayoutToken4 = new LayoutToken(".");
acronymLayoutToken4.setOffset(47);
final LayoutToken acronymLayoutToken5 = new LayoutToken("T");
acronymLayoutToken5.setOffset(48);
final LayoutToken acronymLayoutToken6 = new LayoutToken(".");
acronymLayoutToken6.setOffset(49);
acronym.setLayoutTokens(Arrays.asList(acronymLayoutToken1, acronymLayoutToken2,
acronymLayoutToken3, acronymLayoutToken4, acronymLayoutToken5, acronymLayoutToken6));
acronyms.put(acronym, base);
final NerdContext nerdContext = new NerdContext();
nerdContext.setAcronyms(acronyms);
aQuery.setContext(nerdContext);
final List<Mention> mentions = processText.propagateAcronyms(aQuery);
assertThat(mentions, hasSize(2));
assertThat(mentions.get(0).getRawName(), is("P.C.T."));
assertThat(mentions.get(0).getOffsetStart(), is(146));
assertThat(mentions.get(0).getOffsetEnd(), is(152));
assertThat(mentions.get(0).getBoundingBoxes(), hasSize(greaterThan(0)));
assertThat(mentions.get(0).getLayoutTokens(), hasSize(6));
assertThat(mentions.get(1).getRawName(), is("P.C.T."));
assertThat(mentions.get(1).getOffsetStart(), is(207));
assertThat(mentions.get(1).getOffsetEnd(), is(212));
assertThat(mentions.get(1).getBoundingBoxes(), hasSize(greaterThan(0)));
assertThat(mentions.get(1).getLayoutTokens(), hasSize(6));
}
@Test
public void testAcronymsStringMixedCase() {
String input = "Cigarette smoke (CS)-induced airway epithelial senescence has been implicated in " +
"the pathogenesis of chronic obstructive pulmonary disease (COPD).";
Map<Mention, Mention> acronyms = processText.acronymCandidates(input, new Language("en", 1.0));
assertNotNull(acronyms);
for (Map.Entry<Mention, Mention> entry : acronyms.entrySet()) {
Mention base = entry.getValue();
Mention acronym = entry.getKey();
//System.out.println("acronym: " + input.substring(acronym.start, acronym.end) + " / base: " + base.getRawName());
if (input.substring(acronym.getOffsetStart(), acronym.getOffsetEnd()).trim().equals("CS")) {
assertEquals(base.getRawName(), "Cigarette smoke");
} else {
assertEquals(input.substring(acronym.getOffsetStart(), acronym.getOffsetEnd()).trim(), "COPD");
assertEquals(base.getRawName(), "chronic obstructive pulmonary disease");
}
}
}
@Test
public void testAcronymsTokensMixedCase() {
String input = "Cigarette smoke (CS)-induced airway epithelial senescence has been implicated in " +
"the pathogenesis of chronic obstructive pulmonary disease (COPD).";
List<LayoutToken> tokens = GrobidAnalyzer.getInstance().tokenizeWithLayoutToken(input, new Language("en", 1.0));
Map<Mention, Mention> acronyms = processText.acronymCandidates(tokens);
assertNotNull(acronyms);
for (Map.Entry<Mention, Mention> entry : acronyms.entrySet()) {
Mention base = entry.getValue();
Mention acronym = entry.getKey();
//System.out.println("acronym: " + input.substring(acronym.start, acronym.end) + " / base: " + base.getRawName());
if (input.substring(acronym.getOffsetStart(), acronym.getOffsetEnd()).trim().equals("CS")) {
assertEquals(base.getRawName(), "Cigarette smoke");
} else {
assertEquals(input.substring(acronym.getOffsetStart(), acronym.getOffsetEnd()).trim(), "COPD");
assertEquals(base.getRawName(), "chronic obstructive pulmonary disease");
}
}
}
@Test
public void testDICECoefficient() throws Exception {
String mention = "Setophaga ruticilla";
Double dice = ProcessText.getDICECoefficient(mention, "en");
System.out.println(mention + ": " + dice);
mention = "Setophaga";
dice = ProcessText.getDICECoefficient(mention, "en");
System.out.println(mention + ": " + dice);
mention = "ruticilla";
dice = ProcessText.getDICECoefficient(mention, "en");
System.out.println(mention + ": " + dice);
mention = "bird";
dice = ProcessText.getDICECoefficient(mention, "en");
System.out.println(mention + ": " + dice);
mention = "washing machine";
dice = ProcessText.getDICECoefficient(mention, "en");
System.out.println(mention + ": " + dice);
mention = "washing";
dice = ProcessText.getDICECoefficient(mention, "en");
System.out.println(mention + ": " + dice);
mention = "machine";
dice = ProcessText.getDICECoefficient(mention, "en");
System.out.println(mention + ": " + dice);
}
/*@Test
public void testProcessSpecies() throws Exception {
List<Mention> entities = processText.processSpecies("The mouse is here with us, beware not to be too aggressive.",
new Language("en"));
assertThat(entities, hasSize(1));
}*/
/*@Test
public void testProcessSpecies2() {
if (processText == null) {
System.err.println("text processor was not properly initialised!");
}
try {
List<Mention> entities = processText.processSpecies("Morphological variation in hybrids between Salmo marmoratus and alien Salmo species in the Volarja stream, Soca River basin, Slovenia",
new Language("en"));
assertThat(entities, hasSize(1));
} catch(Exception e) {
e.printStackTrace();
}
}*/
@Test
public void testParagraphSegmentation() {
// create a dummy super long text to be segmented
List<LayoutToken> tokens = new ArrayList<>();
for (int i = 0; i < 1000; i++) {
if (i == 250) {
tokens.add(new LayoutToken("\n"));
}
if (i == 500) {
tokens.add(new LayoutToken("\n"));
tokens.add(new LayoutToken("\n"));
}
tokens.add(new LayoutToken("blabla"));
tokens.add(new LayoutToken(" "));
}
List<List<LayoutToken>> segments = ProcessText.segmentInParagraphs(tokens);
assertThat(segments, hasSize(5));
}
@Test
public void testParagraphSegmentationMonolithic() {
// create a dummy super long text to be segmented
List<LayoutToken> tokens = new ArrayList<>();
for (int i = 0; i < 1000; i++) {
tokens.add(new LayoutToken("blabla"));
tokens.add(new LayoutToken(" "));
}
List<List<LayoutToken>> segments = ProcessText.segmentInParagraphs(tokens);
assertThat(segments, hasSize(4));
}
@Test
@Ignore("This test is failing")
public void testNGram_old_oneGram_shouldWork() throws Exception {
final String input = "this is it.";
final List<StringPos> result = processText.ngrams(input, 1, new Language("en"));
System.out.println(result);
assertThat(result, hasSize(6));
assertThat(result.get(0), is(new StringPos("this", 0)));
assertThat(result.get(1), is(new StringPos(" ", 4)));
assertThat(result.get(2), is(new StringPos("is", 5)));
assertThat(result.get(3), is(new StringPos(" ", 7)));
}
@Test
@Ignore("This test is failing too")
public void testNGram_old_biGram_shouldWork() throws Exception {
final String input = "this is it.";
final List<StringPos> result = processText.ngrams(input, 2, new Language("en"));
// System.out.println(result);
assertThat(result, hasSize(15));
assertThat(result.get(0), is(new StringPos("this", 0)));
assertThat(result.get(1), is(new StringPos("this ", 0)));
assertThat(result.get(2), is(new StringPos("this is", 0)));
assertThat(result.get(3), is(new StringPos(" ", 4)));
}
@Test
public void testNGram_LayoutTokens_oneGram_shouldWork() throws Exception {
final String input = "this is it.";
final List<LayoutToken> inputLayoutTokens = GrobidAnalyzer.getInstance()
.tokenizeWithLayoutToken(input, new Language("en"));
final List<StringPos> result = processText.ngrams(inputLayoutTokens, 1);
System.out.println(result);
assertThat(result, hasSize(6));
assertThat(result.get(0), is(new StringPos("this", 0)));
assertThat(result.get(1), is(new StringPos(" ", 4)));
assertThat(result.get(2), is(new StringPos("is", 5)));
assertThat(result.get(3), is(new StringPos(" ", 7)));
}
@Test
@Ignore("This test is not testing anything")
public void testNGram_twoGram_shouldWork() throws Exception {
final String input = "this is it.";
final List<StringPos> old = processText.ngrams(input, 2, new Language("en"));
Collections.sort(old);
old.remove(4);
System.out.println(old);
final List<StringPos> newd = processText.ngrams(GrobidAnalyzer.getInstance().tokenizeWithLayoutToken(input), 2);
Collections.sort(newd);
System.out.println(newd);
}
@Test
@Ignore("This test is not testing anything")
public void extractMentionsWikipedia() throws Exception {
final String input = "this is it.";
final Language language = new Language("en");
final List<LayoutToken> inputLayoutTokens = GrobidAnalyzer.getInstance()
.tokenizeWithLayoutToken(input, language);
System.out.println(processText.extractMentionsWikipedia(inputLayoutTokens, language));
System.out.println(processText.extractMentionsWikipedia(input, language));
}
}
|
package org.apache.james.core;
import java.io.*;
import java.net.*;
import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;
import org.apache.mailet.*;
/**
* Wrap a MimeMessage adding routing informations (from SMTP) and same simple API.
* @author Federico Barbieri <scoobie@systemy.it>
* @author Serge Knystautas <sergek@lokitech.com>
* @version 0.9
*/
public class MailImpl implements Mail {
//We hardcode the serialVersionUID so that from James 1.2 on,
// MailImpl will be deserializable (so your mail doesn't get lost)
public static final long serialVersionUID = -4289663364703986260L;
private String errorMessage;
private String state;
private MimeMessage message;
private MailAddress sender;
private Collection recipients;
private String name;
private String remoteHost = "localhost";
private String remoteAddr = "127.0.0.1";
private Date lastUpdated = new Date();
public MailImpl() {
setState(Mail.DEFAULT);
}
public MailImpl(String name, MailAddress sender, Collection recipients) {
this();
this.name = name;
this.sender = sender;
this.recipients = recipients;
}
public MailImpl(String name, MailAddress sender, Collection recipients, InputStream messageIn)
throws MessagingException {
this(name, sender, recipients);
MimeMessageSource source = new MimeMessageInputStreamSource(name, messageIn);
MimeMessageWrapper wrapper = new MimeMessageWrapper(source);
this.setMessage(wrapper);
}
public MailImpl(String name, MailAddress sender, Collection recipients, MimeMessage message) {
this(name, sender, recipients);
this.setMessage(message);
}
public void clean() {
message = null;
}
public Mail duplicate() {
try {
return new MailImpl(name, sender, recipients, getMessage());
} catch (MessagingException me) {
}
return (Mail) null;
}
public Mail duplicate(String newName) {
try {
return new MailImpl(newName, sender, recipients, getMessage());
} catch (MessagingException me) {
}
return (Mail) null;
}
public String getErrorMessage() {
return errorMessage;
}
public MimeMessage getMessage() throws MessagingException {
return message;
}
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
public Collection getRecipients() {
return recipients;
}
public MailAddress getSender() {
return sender;
}
public String getState() {
return state;
}
public String getRemoteHost() {
return remoteHost;
}
public String getRemoteAddr() {
return remoteAddr;
}
public Date getLastUpdated() {
return lastUpdated;
}
/**
* <p>Return the size of the message including its headers.
* MimeMessage.getSize() method only returns the size of the
* message body.</p>
*
* <p>Note: this size is not guaranteed to be accurate - see Sun's
* documentation of MimeMessage.getSize().</p>
*
* @return approximate size of full message including headers.
*
* @author Stuart Roebuck <stuart.roebuck@adolos.co.uk>
*/
public int getSize() throws MessagingException {
//SK: Should probably eventually store this as a locally
// maintained value (so we don't have to load and reparse
// messages each time).
int size = message.getSize();
Enumeration e = message.getAllHeaderLines();
while (e.hasMoreElements()) {
size += ((String)e.nextElement()).length();
}
return size;
}
private void readObject(java.io.ObjectInputStream in) throws IOException, ClassNotFoundException {
try {
Object obj = in.readObject();
if (obj == null) {
sender = null;
} else if (obj instanceof String) {
sender = new MailAddress((String)obj);
} else if (obj instanceof MailAddress) {
sender = (MailAddress)obj;
}
} catch (ParseException pe) {
throw new IOException("Error parsing sender address: " + pe.getMessage());
}
recipients = (Collection) in.readObject();
state = (String) in.readObject();
errorMessage = (String) in.readObject();
name = (String) in.readObject();
remoteHost = (String) in.readObject();
remoteAddr = (String) in.readObject();
lastUpdated = (Date) in.readObject();
}
public void setErrorMessage(String msg) {
this.errorMessage = msg;
}
public void setMessage(MimeMessage message) {
this.message = message;
}
public void setRecipients(Collection recipients) {
this.recipients = recipients;
}
public void setSender(MailAddress sender) {
this.sender = sender;
}
public void setState(String state) {
this.state = state;
}
public void setRemoteHost(String remoteHost) {
this.remoteHost = remoteHost;
}
public void setRemoteAddr(String remoteAddr) {
this.remoteAddr = remoteAddr;
}
public void setLastUpdated(Date lastUpdated) {
this.lastUpdated = lastUpdated;
}
public void writeMessageTo(OutputStream out) throws IOException, MessagingException {
if (message != null) {
message.writeTo(out);
} else {
throw new MessagingException("No message set for this MailImpl.");
}
}
private void writeObject(java.io.ObjectOutputStream out) throws IOException {
//System.err.println("saving object");
lastUpdated = new Date();
out.writeObject(sender);
out.writeObject(recipients);
out.writeObject(state);
out.writeObject(errorMessage);
out.writeObject(name);
out.writeObject(remoteHost);
out.writeObject(remoteAddr);
out.writeObject(lastUpdated);
}
public Mail bounce(String message) throws MessagingException {
//This sends a message to the james component that is a bounce of the sent message
MimeMessage original = getMessage();
MimeMessage reply = (MimeMessage) original.reply(false);
reply.setSubject("Re: " + original.getSubject());
Collection recipients = new HashSet();
recipients.add(getSender());
InternetAddress addr[] = {new InternetAddress(getSender().toString())};
reply.setRecipients(Message.RecipientType.TO, addr);
reply.setFrom(new InternetAddress(getRecipients().iterator().next().toString()));
reply.setText(message);
reply.setHeader("Message-Id", "replyTo-" + getName());
return new MailImpl("replyTo-" + getName(), new MailAddress(getRecipients().iterator().next().toString()), recipients, reply);
}
public void writeContentTo(OutputStream out, int lines)
throws IOException, MessagingException {
String line;
BufferedReader br;
if(message != null) {
br = new BufferedReader(new InputStreamReader(message.getInputStream()));
while(lines
if((line = br.readLine()) == null) break;
line += "\r\n";
out.write(line.getBytes());
}
} else {
throw new MessagingException("No message set for this MailImpl.");
}
}
}
|
package edu.ucdenver.ccp.common.string;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static edu.ucdenver.ccp.common.string.StringUtil.*;
import java.nio.charset.MalformedInputException;
import java.util.List;
import org.junit.Test;
import edu.ucdenver.ccp.common.collections.CollectionsUtil;
import edu.ucdenver.ccp.common.file.CharacterEncoding;
import edu.ucdenver.ccp.common.string.StringUtil.RemoveFieldEnclosures;
import edu.ucdenver.ccp.common.test.DefaultTestCase;
public class StringUtilTest extends DefaultTestCase {
@Test
public void testIsInteger_validPositiveInput() {
assertTrue(StringUtil.isInteger("0"));
assertTrue(StringUtil.isInteger("00"));
assertTrue(StringUtil.isInteger("1"));
assertTrue(StringUtil.isInteger("10"));
assertTrue(StringUtil.isInteger("1234567890"));
assertFalse(StringUtil.isInteger("9876543211"));
}
@Test
public void testIsInteger_validNegativeInput() {
assertTrue(StringUtil.isInteger("-1"));
assertTrue(StringUtil.isInteger("-10"));
assertTrue(StringUtil.isInteger("-1234567890"));
assertFalse(StringUtil.isInteger("-9876543211"));
}
@Test
public void testIsInteger_invalidInput() {
assertTrue(StringUtil.isInteger("-0"));
assertTrue(StringUtil.isInteger("01"));
assertFalse(StringUtil.isInteger("this is not a number"));
assertFalse(StringUtil.isInteger("3.14159"));
assertFalse(StringUtil.isInteger("-09876543211"));
assertTrue(StringUtil.isInteger("-000005"));
assertFalse(StringUtil.isInteger(""));
assertFalse(StringUtil.isInteger(null));
}
@Test
public void testIsIntegerGreaterThanZero() {
assertTrue(StringUtil.isIntegerGreaterThanZero("1"));
assertTrue(StringUtil.isIntegerGreaterThanZero("10"));
assertTrue(StringUtil.isIntegerGreaterThanZero("1234567890"));
assertFalse(StringUtil.isIntegerGreaterThanZero("9876543211"));
assertFalse(StringUtil.isIntegerGreaterThanZero("0"));
assertFalse(StringUtil.isIntegerGreaterThanZero("-1"));
assertFalse(StringUtil.isIntegerGreaterThanZero("this is not a number"));
}
@Test
public void testIsNonNegativeInteger_validNonNegativeInput() {
assertTrue(StringUtil.isNonNegativeInteger("1"));
assertTrue(StringUtil.isNonNegativeInteger("10"));
assertTrue(StringUtil.isNonNegativeInteger("1234567890"));
assertFalse(StringUtil.isNonNegativeInteger("9876543211"));
}
@Test
public void testIsNonNegativeInteger_negativeInput() {
assertFalse(StringUtil.isNonNegativeInteger("-1"));
assertFalse(StringUtil.isNonNegativeInteger("-10"));
assertFalse(StringUtil.isNonNegativeInteger("-1234567890"));
assertFalse(StringUtil.isNonNegativeInteger("-9876543211"));
}
@Test
public void testIsNonNegativeInteger_invalidInput() {
assertTrue(StringUtil.isNonNegativeInteger("-0"));
assertTrue(StringUtil.isNonNegativeInteger("01"));
assertFalse(StringUtil.isNonNegativeInteger("this is not a number"));
assertFalse(StringUtil.isNonNegativeInteger("3.14159"));
assertFalse(StringUtil.isNonNegativeInteger("-09876543211"));
assertFalse(StringUtil.isNonNegativeInteger("-000005"));
assertFalse(StringUtil.isNonNegativeInteger(""));
assertFalse(StringUtil.isNonNegativeInteger(null));
}
@Test
public void testRemoveRegexSuffix_ValidInput() {
assertEquals("Suffix should be stripped.", "myFile", StringUtil
.removeSuffixRegex("myFile.txt.txt.txt.txt.txt", "(\\.txt)+"));
assertEquals("Suffix should be stripped.", "myFile", StringUtil
.removeSuffixRegex("myFile.tgz", "\\..gz"));
}
@Test
public void testRemoveRegexSuffix_EmptyInput() {
assertEquals("Suffix should be stripped.",
"myFile.txt.txt.txt.txt.txt", StringUtil.removeSuffixRegex(
"myFile.txt.txt.txt.txt.txt", ""));
assertEquals("Suffix should be stripped.", "myFile.tgz", StringUtil
.removeSuffixRegex("myFile.tgz", ""));
}
@Test
public void testRemoveRegexPrefix_ValidInput() {
assertEquals("Suffix should be stripped.", "e.txt.txt.txt.txt.txt",
StringUtil.removePrefixRegex("myFile.txt.txt.txt.txt.txt",
"(m?y?Fil)"));
assertEquals("Suffix should be stripped.", "gz", StringUtil
.removePrefixRegex("myFile.tgz", "my.*?t"));
}
/**
* Checks that StringUtil.removeSuffix() works correctly when valid input is
* used
*/
@Test
public void testRemoveSuffix_ValidInput() {
assertEquals("Suffix should be stripped.", "myFile.txt", StringUtil
.removeSuffix("myFile.txt.gz", ".gz"));
assertEquals("Suffix should be stripped.", "myFile", StringUtil
.removeSuffix("myFile.txt.gz.abc.123.xyz-654",
".txt.gz.abc.123.xyz-654"));
}
/**
* Checks for expected behavior of StringUtil.removeSuffix() if the suffix
* string is empty
*/
@Test
public void testRemoveSuffix_EmptyInput() {
assertEquals("Suffix should be stripped.", "myFile.txt", StringUtil
.removeSuffix("myFile.txt", ""));
assertEquals("Suffix should be stripped.", "", StringUtil.removeSuffix(
"", ""));
}
/**
* Checks for proper exception if the input string is null when calling
* StringUtil.removeSuffix()
*/
@Test(expected = IllegalArgumentException.class)
public void testRemoveSuffix_NullInputString() {
StringUtil.removeSuffix(null, ".gz");
}
/**
* Checks for proper exception if the suffix string is null when calling
* StringUtil.removeSuffix()
*/
@Test(expected = IllegalArgumentException.class)
public void testRemoveSuffix_NullSuffix() {
StringUtil.removeSuffix("File.txt", null);
}
/**
* Checks for proper exception if the input string does not end with the
* suffix requested to be removed when calling StringUtil.removeSuffix()
*/
@Test(expected = IllegalArgumentException.class)
public void testRemoveSuffix_InputStringDoesNotHaveSuffix() {
StringUtil.removeSuffix("File.txt.zip", ".gz");
}
@Test
public void testReplaceSuffix_ValidInput() {
assertEquals("Suffix should be replaced with .tar", "myTarball.tar",
StringUtil.replaceSuffix("myTarball.tgz", ".tgz", ".tar"));
}
@Test
public void testStartsWithRegex() {
assertTrue(StringUtil.startsWithRegex("2010-04-06", RegExPatterns
.getNDigitsPattern(4)));
assertTrue(StringUtil.startsWithRegex("2010-04-06", RegExPatterns
.getNDigitsPattern(3)));
assertTrue(StringUtil.startsWithRegex("2010-04-06", RegExPatterns
.getNDigitsPattern(2)));
assertTrue(StringUtil.startsWithRegex("2010-04-06", RegExPatterns
.getNDigitsPattern(1)));
assertTrue(StringUtil.startsWithRegex("2010-04-06", "^"
+ RegExPatterns.getNDigitsPattern(4)));
assertFalse(StringUtil.startsWithRegex("2010-04-06", RegExPatterns
.getNDigitsPattern(5)));
}
@Test
public void testContainsRegex() {
assertTrue(StringUtil.containsRegex("2010-04-06", RegExPatterns
.getNDigitsPattern(4)));
assertFalse(StringUtil.containsRegex("2010-04-06", RegExPatterns
.getNDigitsPattern(5)));
}
@Test
public void testCreateRepeatingString() {
String expectedStr = StringConstants.AMPERSAND
+ StringConstants.AMPERSAND + StringConstants.AMPERSAND;
assertEquals(String.format("String should contain 3 ampersands"),
expectedStr, StringUtil.createRepeatingString(
StringConstants.AMPERSAND, 3));
assertEquals(String.format("String should contain 6 ampersands"),
expectedStr + expectedStr, StringUtil.createRepeatingString(
StringConstants.AMPERSAND + StringConstants.AMPERSAND,
3));
}
@Test(expected = IllegalArgumentException.class)
public void testSplitWithFieldDelimiter_ZeroInDelimiter() {
StringUtil.splitWithFieldEnclosure("\"", String.format(".%s",
StringConstants.DIGIT_ZERO), StringConstants.QUOTATION_MARK);
}
@Test
public void testSplitWithFieldDelimiter() {
String inputStr = "J Clin Invest,0021-9738,1558-8238,1940,19,\"Index, vol.1-17\",1,10.1172/JCI101100,PMC548872,0,,live";
String[] expectedTokens = new String[] { "J Clin Invest", "0021-9738",
"1558-8238", "1940", "19", "\"Index, vol.1-17\"", "1",
"10.1172/JCI101100", "PMC548872", "0", "", "live" };
assertArrayEquals(String.format("One token should include a comma"),
expectedTokens, StringUtil.splitWithFieldEnclosure(inputStr,
StringConstants.COMMA, StringConstants.QUOTATION_MARK));
}
@Test
public void testSplitWithFieldDelimiter_EmptyColumnsAtEnd() {
String inputStr = "J Clin Invest,0021-9738,1558-8238,1940,19,\"Index, vol.1-17\",1,10.1172/JCI101100,PMC548872,0,,";
String[] expectedTokens = new String[] { "J Clin Invest", "0021-9738",
"1558-8238", "1940", "19", "\"Index, vol.1-17\"", "1",
"10.1172/JCI101100", "PMC548872", "0", "", "" };
assertArrayEquals(String.format("One token should include a comma"),
expectedTokens, StringUtil.splitWithFieldEnclosure(inputStr,
StringConstants.COMMA, StringConstants.QUOTATION_MARK));
}
@Test
public void testSplitWithFieldDelimiter_NoColumns() {
String inputStr = "J Clin Invest,0021-9738,1558-8238,1940,19,\"Index, vol.1-17\",1,10.1172/JCI101100,PMC548872,0,,live";
assertArrayEquals(String.format("One token should include a comma"),
new String[] { inputStr }, StringUtil.splitWithFieldEnclosure(
inputStr, StringConstants.SEMICOLON,
StringConstants.QUOTATION_MARK));
}
@Test
public void testSplitWithFieldDelimiter_FieldDelimiterNotPresentInText() {
String inputStr = "J Clin Invest,0021-9738,1558-8238,1940,19,\"Index, vol.1-17\",1,10.1172/JCI101100,PMC548872,0,,live";
String[] expectedTokens = new String[] { "J Clin Invest", "0021-9738",
"1558-8238", "1940", "19", "\"Index", " vol.1-17\"", "1",
"10.1172/JCI101100", "PMC548872", "0", "", "live" };
assertArrayEquals(String.format("One token should include a comma"),
expectedTokens, StringUtil.splitWithFieldEnclosure(inputStr,
StringConstants.COMMA, StringConstants.SEMICOLON));
}
@Test
public void testSplitWithFieldDelimiter_FieldDelimiterNull() {
String inputStr = "J Clin Invest,0021-9738,1558-8238,1940,19,\"Index, vol.1-17\",1,10.1172/JCI101100,PMC548872,0,,live";
String[] expectedTokens = new String[] { "J Clin Invest", "0021-9738",
"1558-8238", "1940", "19", "\"Index", " vol.1-17\"", "1",
"10.1172/JCI101100", "PMC548872", "0", "", "live" };
assertArrayEquals(String.format("One token should include a comma"),
expectedTokens, StringUtil.splitWithFieldEnclosure(inputStr,
StringConstants.COMMA, null));
}
@Test
public void testSplitWithFieldDelimiter_FieldDelimiterIsRegexSpecialCharacter() {
String inputStr = "J Clin Invest,0021-9738,1558-8238,1940,19,*Index, vol.1-17*,1,10.1172/JCI101100,PMC548872,0,,live";
String[] expectedTokens = new String[] { "J Clin Invest", "0021-9738",
"1558-8238", "1940", "19", "*Index, vol.1-17*", "1",
"10.1172/JCI101100", "PMC548872", "0", "", "live" };
assertArrayEquals(String.format("One token should include a comma"),
expectedTokens, StringUtil.splitWithFieldEnclosure(inputStr,
StringConstants.COMMA, "\\*"));
}
@Test
public void testStripNonAscii() {
try {
String none = "simple word";
// String one = "\u0031"; // 31
String o_umlaut = "\u00f6"; // c3-b6 o with diaeresis
String devanagari_one = "\u0967"; // e0-a5-0a7
String one3byte = devanagari_one;
String one3byteStripped = "?";
String two3byte = devanagari_one + devanagari_one;
String two3byteStripped = "??";
String one2byte = o_umlaut;
String one2byteStripped = "?";
String two2byte = o_umlaut + o_umlaut;
String two2byteStripped = "??";
String twoAnd3 = o_umlaut + devanagari_one;
String twoAnd3Stripped = "??";
String threeAnd2 = devanagari_one + o_umlaut;
String threeAnd2Stripped = "??";
String mixed = devanagari_one + "foo and " + o_umlaut + " bar"
+ devanagari_one;
String mixedStripped = "?foo and ? bar?";
String realData = "We thank Richelle Strom for generating the F2 intercross mice.";
String realDataStripped = "We thank Richelle Strom for generating the F2 intercross mice.";
// 01234567890123456789012345678901234567890123456789012345678901
assertTrue(StringUtil.stripNonAscii("").equals(""));
assertTrue(StringUtil.stripNonAscii(none).equals(none));
assertTrue(StringUtil.stripNonAscii(one2byte).equals(
one2byteStripped));
assertTrue(StringUtil.stripNonAscii(one3byte).equals(
one3byteStripped));
assertTrue(StringUtil.stripNonAscii(two3byte).equals(
two3byteStripped));
assertTrue(StringUtil.stripNonAscii(two2byte).equals(
two2byteStripped));
assertTrue(StringUtil.stripNonAscii(twoAnd3)
.equals(twoAnd3Stripped));
assertTrue(StringUtil.stripNonAscii(threeAnd2).equals(
threeAnd2Stripped));
assertTrue(StringUtil.stripNonAscii(mixed).equals(mixedStripped));
assertTrue(StringUtil.stripNonAscii(realData).equals(
realDataStripped));
} catch (java.io.UnsupportedEncodingException x) {
System.err.println("error:" + x);
x.printStackTrace();
}
}
@Test
public void testDelimitAndTrim_WithTrailingDelimiter() {
String inputStr = "\"D015430\",";
List<String> expectedTokens = CollectionsUtil.createList("\"D015430\"");
assertEquals(String.format("One token should be returned"),
expectedTokens, StringUtil.delimitAndTrim(inputStr,
StringConstants.COMMA, StringConstants.QUOTATION_MARK,
RemoveFieldEnclosures.FALSE));
}
@Test
public void testDelimitAndTrim_WithTrailingDelimiter_RemoveFieldEnclosures() {
String inputStr = "\"D015430\",";
List<String> expectedTokens = CollectionsUtil.createList("D015430");
assertEquals(String.format("One token should be returned"),
expectedTokens, StringUtil.delimitAndTrim(inputStr,
StringConstants.COMMA, StringConstants.QUOTATION_MARK,
RemoveFieldEnclosures.TRUE));
}
@Test
public void testByteArrayToString() throws Exception {
String asciiString = "naive";
String utf8String = "nai\u0308ve";
byte[] asciiByteArray = asciiString.getBytes();
assertEquals(
"ASCII bytes should be able to be read using ASCII encoding",
asciiString, decode(asciiByteArray, CharacterEncoding.US_ASCII));
assertEquals(
"ASCII bytes should be able to be read using UTF-8 encoding",
asciiString, decode(asciiByteArray, CharacterEncoding.UTF_8));
assertEquals(
"UTF-8 bytes should be able to be read using UTF-8 encoding",
utf8String, decode(utf8String.getBytes(CharacterEncoding.UTF_8
.getCharacterSetName()), CharacterEncoding.UTF_8));
}
@Test(expected = MalformedInputException.class)
public void testByteArrayToString_WithEncodingMismatch() throws Exception {
String utf8String = "nai\u0308ve";
StringUtil.decode(utf8String.getBytes(CharacterEncoding.UTF_8
.getCharacterSetName()), CharacterEncoding.US_ASCII);
}
}
|
package il.ac.bgu.cs.bp.bpjs.analysis;
import il.ac.bgu.cs.bp.bpjs.internal.ExecutorServiceMaker;
import il.ac.bgu.cs.bp.bpjs.model.*;
import org.junit.Test;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import static org.junit.Assert.*;
public class StateStoreTests {
@Test
public void ForgetfulStore() throws Exception {
BProgram program = new SingleResourceBProgram("SnapshotTests/ABCDTrace.js");
ExecutorService execSvc = ExecutorServiceMaker.makeWithName("StoreSvc");
DfsBProgramVerifier sut = new DfsBProgramVerifier();
VisitedStateStore forgetful = new ForgetfulVisitedStateStore();
Node initial = Node.getInitialNode(program, execSvc);
forgetful.store(initial);
assertFalse(forgetful.isVisited(initial));
Node next = sut.getUnvisitedNextNode(initial, execSvc);
assertFalse(forgetful.isVisited(next));
}
@Test
public void VisitedStateStoreNoHashBasic() throws Exception {
VisitedStateStore noHash = new BThreadSnapshotVisitedStateStore();
TestAAABTraceStore(noHash);
}
@Test
public void VisitedStateStoreHashBasic() throws Exception {
VisitedStateStore useHash = new HashVisitedStateStore();
TestAAABTraceStore(useHash);
}
private void TestAAABTraceStore(VisitedStateStore storeToUse) throws Exception {
BProgram program = new SingleResourceBProgram("SnapshotTests/ABCDTrace.js");
ExecutorService execSvc = ExecutorServiceMaker.makeWithName("StoreSvc");
DfsBProgramVerifier sut = new DfsBProgramVerifier();
Node initial = Node.getInitialNode(program, execSvc);
storeToUse.store(initial);
assertTrue(storeToUse.isVisited(initial));
Node next = sut.getUnvisitedNextNode(initial, execSvc);
assertFalse(storeToUse.isVisited(next));
storeToUse.store(next);
assertTrue(storeToUse.isVisited(next));
assertTrue(storeToUse.isVisited(initial));
storeToUse.clear();
assertFalse(storeToUse.isVisited(next));
assertFalse(storeToUse.isVisited(initial));
}
@Test
public void StateStoreNoHashTestDiffJSVar() throws Exception {
VisitedStateStore noHash = new BThreadSnapshotVisitedStateStore();
TestDiffJSVar(noHash);
}
@Test
public void StateStoreHashTestDiffJSVar() throws Exception {
VisitedStateStore hashStore = new HashVisitedStateStore();
TestDiffJSVar(hashStore);
}
private void TestDiffJSVar(VisitedStateStore storeToUse) throws Exception {
BProgram program = new StringBProgram("bp.registerBThread(function(){\n" +
" for ( var i=0; i<4; i++ ) {\n" +
" bp.sync({request:bp.Event(\"A\")});\n" +
" bp.sync({request:bp.Event(\"B\")});\n" +
" bp.sync({request:bp.Event(\"C\")});\n" +
" bp.sync({request:bp.Event(\"D\")});\n" +
" }\n" +
"});");
ExecutorService execSvc = ExecutorServiceMaker.makeWithName("StoreSvcDiiffJSVar");
DfsBProgramVerifier sut = new DfsBProgramVerifier();
List<Node> snapshots = new ArrayList<>();
Node initial = Node.getInitialNode(program, execSvc);
storeToUse.store(initial);
snapshots.add(initial);
assertTrue(storeToUse.isVisited(initial));
Node next = initial;
//Iteration 1,starts already at request state A
for (int i = 0; i < 4; i++) {
next = sut.getUnvisitedNextNode(next, execSvc);
storeToUse.store(next);
}
snapshots.add(next);
assertTrue(storeToUse.isVisited(next));
for (int i = 0; i < 4; i++) {
next = sut.getUnvisitedNextNode(next, execSvc);
storeToUse.store(next);
}
snapshots.add(next);
assertTrue(storeToUse.isVisited(next));
//now we want to compare specific states
BProgramSyncSnapshot state1 = snapshots.get(1).getSystemState();
BProgramSyncSnapshot state2 = snapshots.get(2).getSystemState();
assertNotEquals(state1, state2);
}
@Test
public void StateStoreNoHashTestEqualJSVar() throws Exception {
VisitedStateStore noHash = new BThreadSnapshotVisitedStateStore();
TestEqualJSVar(noHash);
}
@Test
public void StateStoreHashTestEqualJSVar() throws Exception {
VisitedStateStore hashStore = new HashVisitedStateStore();
TestEqualJSVar(hashStore);
}
private void TestEqualJSVar(VisitedStateStore storeToUse) throws Exception {
BProgram program = new StringBProgram("bp.registerBThread(function(){\n" +
" for ( var i=0; i<4; ) {\n" +
" bp.sync({request:bp.Event(\"A\")});\n" +
" bp.sync({request:bp.Event(\"B\")});\n" +
" bp.sync({request:bp.Event(\"C\")});\n" +
" bp.sync({request:bp.Event(\"D\")});\n" +
" }\n" +
"});");
ExecutorService execSvc = ExecutorServiceMaker.makeWithName("StoreSvcEqualJSVar");
DfsBProgramVerifier sut = new DfsBProgramVerifier();
List<Node> snapshots = new ArrayList<>();
Node initial = Node.getInitialNode(program, execSvc);
storeToUse.store(initial);
snapshots.add(initial);
assertTrue(storeToUse.isVisited(initial));
Node next = initial;
//Iteration 1,starts already at request state A
for (int i = 0; i < 4; i++) {
next = sut.getUnvisitedNextNode(next, execSvc);
storeToUse.store(next);
}
snapshots.add(next);
assertTrue(storeToUse.isVisited(next));
for (int i = 0; i < 4; i++) {
next = sut.getUnvisitedNextNode(next, execSvc);
assertTrue(storeToUse.isVisited(next));
storeToUse.store(next);
}
snapshots.add(next);
assertTrue(storeToUse.isVisited(next));
//now we want to compare specific
BProgramSyncSnapshot state1 = snapshots.get(1).getSystemState();
BProgramSyncSnapshot state2 = snapshots.get(2).getSystemState();
assertEquals(state1, state2);
}
/*
A bunch of tests from BProgramSyncSnapshot modified to check nodes.
*/
@Test
public void StateStoreNoHashTestIdenticalRuns() throws Exception {
VisitedStateStore noHash = new BThreadSnapshotVisitedStateStore();
testEqualRuns(noHash);
}
@Test
public void StateStoreHashTestIdenticalRuns() throws Exception {
VisitedStateStore hashStore = new HashVisitedStateStore();
testEqualRuns(hashStore);
}
/*
This test makes sure we compare nodes/states properly.
these two objects (by debugging) share program counter and frame index and should differ on variables only
*/
private void testEqualRuns(VisitedStateStore storeToUse) throws Exception {
BProgram bprog = new SingleResourceBProgram("SnapshotTests/ABCDTrace.js");
BProgram bprog2 = new SingleResourceBProgram("SnapshotTests/ABCDTrace.js");
ExecutorService execSvc = ExecutorServiceMaker.makeWithName("StoreSvcEqualJSVar");
DfsBProgramVerifier sut = new DfsBProgramVerifier();
Node initial1 = Node.getInitialNode(bprog, execSvc);
Node initial2 = Node.getInitialNode(bprog2, execSvc);
assertEquals(initial1,initial2);
Node next1 = initial1;
Node next2 = initial2;
storeToUse.store(next1);
assertTrue(storeToUse.isVisited(next2));
for (int i = 0; i < 4; i++) {
next1 = sut.getUnvisitedNextNode(next1, execSvc);
storeToUse.store(next1);
assertTrue(storeToUse.isVisited(next2));
}
}
}
|
package ru.salauyou.utils;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.NoSuchElementException;
public class KCombinationIterator<T> implements Iterator<Collection<T>> {
final private Collection<T> resultCollection;
final private List<T> source;
final int k, n;
final private int[] subset; // indexes of combination's elements in source list
private boolean started = false;
private boolean hasNext = false;
public KCombinationIterator(Collection<T> source, int k){
this(source, k, new ArrayList<T>());
}
public KCombinationIterator(Collection<T> source, int k, Collection<T> resultCollection) {
if (k < 1)
throw new IllegalArgumentException("k cannot be less than 1");
if (k > source.size())
throw new IllegalArgumentException("k cannot be greater than size of source collection");
this.source = new ArrayList<T>(source);
this.k = k;
this.n = source.size();
this.resultCollection = resultCollection;
subset = new int[k];
}
@Override
public boolean hasNext() {
if (n == 0)
return false;
if (!started){
// if not started, generate first subset
for (int i = 0; (subset[i] = i) < k - 1; i++);
started = true;
hasNext = true;
return true;
} else {
// check if more subsets can be generated
int i;
for (i = k - 1; i >= 0 && subset[i] == n - k + i; i
if (i < 0){
hasNext = false;
return false;
} else {
subset[i]++;
for (++i; i < k; i++)
subset[i] = subset[i - 1] + 1;
hasNext = true;
return true;
}
}
}
@SuppressWarnings("unchecked")
@Override
public Collection<T> next() {
if (!hasNext)
throw new NoSuchElementException("No more subsets can be generated");
Collection<T> result;
try {
result = resultCollection.getClass().newInstance();
} catch (Exception e) {
e.printStackTrace();
return null;
}
for (int i = 0; i < k; i++)
result.add(source.get(subset[i]));
return result;
}
/**
* Not supported
*
* @throws UnsupportedOperationException
*/
@Override
public void remove(){
throw new UnsupportedOperationException("remove() is not supported");
}
static public <T> Iterable<Collection<T>> decorateForEach(final Collection<T> source, final int k){
return new Iterable<Collection<T>>(){
@Override
public Iterator<Collection<T>> iterator() {
return new KCombinationIterator<T>(source, k);
}
};
}
}
|
package io.cozmic.usher.test.integration;
import io.cozmic.usher.Start;
import io.vertx.core.DeploymentOptions;
import io.vertx.core.Handler;
import io.vertx.core.Vertx;
import io.vertx.core.buffer.Buffer;
import io.vertx.core.json.JsonObject;
import io.vertx.core.net.NetClient;
import io.vertx.core.net.NetSocket;
import io.vertx.ext.unit.Async;
import io.vertx.ext.unit.TestContext;
import io.vertx.ext.unit.junit.VertxUnitRunner;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import java.util.Objects;
import java.util.concurrent.atomic.AtomicInteger;
import static org.junit.Assert.fail;
@RunWith(VertxUnitRunner.class)
public class RoutingTests {
Vertx vertx;
private FakeService fooService;
private FakeService barService;
@Before
public void before(TestContext context) {
vertx = Vertx.vertx();
fooService = new FakeService(Buffer.buffer("foo"), 9192);
barService = new FakeService(Buffer.buffer("bar"), 9193);
vertx.deployVerticle(fooService, context.asyncAssertSuccess(r -> vertx.deployVerticle(barService, context.asyncAssertSuccess())));
}
@After
public void after(TestContext context) {
vertx.close(context.asyncAssertSuccess());
}
/**
* Two different Inputs with different ports each route to a different backout Output
* @param context
*/
@Test
public void testMessageMatchRouting(TestContext context) {
final DeploymentOptions options = new DeploymentOptions();
final JsonObject config = new JsonObject();
config
.put("PayloadEncoder", new JsonObject())
.put("FooRouter", buildFooInput())
.put("BarRouter", buildBarInput())
.put("FooBackend", buildFooOutput(2500))
.put("BarBackend", buildBarOutput(2501));
options.setConfig(config);
vertx.deployVerticle(Start.class.getName(), options, context.asyncAssertSuccess(deploymentID -> {
final Async async = context.async();
final NetClient netClient = vertx.createNetClient();
netClient.connect(2500, "localhost", context.asyncAssertSuccess(fooSocket -> {
fooSocket.handler(fooBuffer -> {
context.assertEquals("foo", fooBuffer.toString());
netClient.connect(2501, "localhost", context.asyncAssertSuccess(barSocket -> {
barSocket.handler(barBuffer -> {
context.assertEquals("bar", barBuffer.toString());
async.complete();
});
barSocket.write("Hello Bar");
}));
});
fooSocket.write("Hello Foo");
}));
vertx.setTimer(5000, new Handler<Long>() {
@Override
public void handle(Long event) {
context.fail("timed out");
}
});
}));
}
/**
* One Input clones a message to two backends. Only the first backend will respond.
* @param context
*/
@Test
public void testMessageMatchCloning(TestContext context) {
final DeploymentOptions options = new DeploymentOptions();
final JsonObject config = new JsonObject();
config
.put("PayloadEncoder", new JsonObject())
.put("FooBarRouter", buildFooBarInput())
.put("FooBackend", buildFooOutput(2500))
.put("BarBackend", buildBarOutput(2500));
options.setConfig(config);
vertx.deployVerticle(Start.class.getName(), options, context.asyncAssertSuccess(deploymentID -> {
final Async async = context.async();
final NetClient netClient = vertx.createNetClient();
netClient.connect(2500, "localhost", context.asyncAssertSuccess(fooBarSocket -> {
final String payload = "Hello Foo and Bar";
AtomicInteger responseCount = new AtomicInteger();
fooBarSocket.handler(fooBuffer -> {
final String response = fooBuffer.toString();
int responses = 0;
if (Objects.equals(response, "foo")) {
context.assertEquals(payload, fooService.getLastBuffer().toString());
responses = responseCount.incrementAndGet();
}
if (Objects.equals(response, "bar")) {
context.assertEquals(payload, barService.getLastBuffer().toString());
responses = responseCount.incrementAndGet();
}
if (responses == 2) {
async.complete();
}
});
fooBarSocket.write(payload);
}));
vertx.setTimer(5000, event -> context.fail("timed out"));
}));
}
private JsonObject buildFooBarInput() {
return new JsonObject().put("type", "TcpInput").put("host", "localhost").put("port", 2500).put("encoder", "PayloadEncoder");
}
private JsonObject buildBarInput() {
return new JsonObject().put("type", "TcpInput").put("host", "localhost").put("port", 2501).put("encoder", "PayloadEncoder");
}
private JsonObject buildFooOutput(int inputFilterPort) {
return new JsonObject().put("type", "TcpOutput").put("host", "localhost").put("port", 9192).put("encoder", "PayloadEncoder").put("messageMatcher", String.format("#{msg.localPort == %s}", inputFilterPort));
}
private JsonObject buildBarOutput(int inputFilterPort) {
return new JsonObject().put("type", "TcpOutput").put("host", "localhost").put("port", 9193).put("encoder", "PayloadEncoder").put("messageMatcher", String.format("#{msg.localPort == %s}", inputFilterPort));
}
private JsonObject buildFooInput() {
return new JsonObject().put("type", "TcpInput").put("host", "localhost").put("port", 2500).put("encoder", "PayloadEncoder");
}
}
|
package io.github.benas.unixstream.components;
import io.github.benas.unixstream.UnixStream;
import org.junit.Test;
import java.io.IOException;
import java.nio.file.Path;
import java.util.List;
import java.util.stream.Collectors;
import static org.assertj.core.api.Assertions.assertThat;
public class PwdTest {
@Test
public void pwd() throws IOException {
UnixStream<Path> stream = UnixStream.pwd();
List<Path> paths = stream.collect(Collectors.toList());
assertThat(paths.get(0).toString()).contains("unix-stream");
}
}
|
package lpn.parser;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;
public class Transition {
private String name;
private boolean fail = false;
private boolean persistent = false;
private String enabling;
private ExprTree enablingTree;
private String delay;
private ExprTree delayTree;
private String priority;
private ExprTree priorityTree;
private ArrayList<Place> preset;
private ArrayList<Place> postset;
private HashMap<String, String> boolAssignments;
private HashMap<String, ExprTree> boolAssignTrees;
private HashMap<String, String> intAssignments;
private HashMap<String, ExprTree> intAssignTrees;
private HashMap<String, String> contAssignments;
private HashMap<String, ExprTree> contAssignTrees;
private HashMap<String, String> rateAssignments;
private HashMap<String, ExprTree> rateAssignTrees;
private LhpnFile lhpn;
private int index;
private boolean sticky;
private boolean local;
// TODO: Sort LPNs that share variables in the assignedVarSet of this transition.
private List<LhpnFile> dstLpnList = new ArrayList<LhpnFile>();
public Transition(String name, ArrayList<Variable> variables, LhpnFile lhpn) {
this.name = name;
this.lhpn = lhpn;
preset = new ArrayList<Place>();
postset = new ArrayList<Place>();
boolAssignments = new HashMap<String, String>();
boolAssignTrees = new HashMap<String, ExprTree>();
intAssignments = new HashMap<String, String>();
intAssignTrees = new HashMap<String, ExprTree>();
contAssignments = new HashMap<String, String>();
contAssignTrees = new HashMap<String, ExprTree>();
rateAssignments = new HashMap<String, String>();
rateAssignTrees = new HashMap<String, ExprTree>();
sticky = false;
}
public Transition(String name, int index, ArrayList<Variable> variables, LhpnFile lhpn, boolean local) {
this.name = name;
this.lhpn = lhpn;
this.index = index;
this.local = local;
preset = new ArrayList<Place>();
postset = new ArrayList<Place>();
boolAssignments = new HashMap<String, String>();
boolAssignTrees = new HashMap<String, ExprTree>();
intAssignments = new HashMap<String, String>();
intAssignTrees = new HashMap<String, ExprTree>();
contAssignments = new HashMap<String, String>();
contAssignTrees = new HashMap<String, ExprTree>();
rateAssignments = new HashMap<String, String>();
rateAssignTrees = new HashMap<String, ExprTree>();
sticky = false;
}
public Transition() {
}
public void addPostset(Place place) {
postset.add(place);
}
public void addPreset(Place place) {
preset.add(place);
}
public boolean addEnabling(String newEnab) {
boolean retVal = false;
if (newEnab == null) {
return false;
}
if (newEnab.equals("")) {
enabling = "";
enablingTree = new ExprTree();
retVal = true;
}
ExprTree expr = new ExprTree(lhpn);
if (newEnab != null && !newEnab.equals("")) {
expr.token = expr.intexpr_gettok(newEnab);
retVal = expr.intexpr_L(newEnab);
if (retVal) {
enablingTree = expr;
enabling = newEnab;
}
}
return retVal;
}
public boolean addIntAssign(String variable, String assignment) {
boolean retVal;
ExprTree expr = new ExprTree(lhpn);
expr.token = expr.intexpr_gettok(assignment);
retVal = expr.intexpr_L(assignment);
if (retVal) {
intAssignTrees.put(variable, expr);
intAssignments.put(variable, assignment);
}
return retVal;
}
public boolean addContAssign(String variable, String assignment) {
boolean retVal;
ExprTree expr = new ExprTree(lhpn);
expr.token = expr.intexpr_gettok(assignment);
retVal = expr.intexpr_L(assignment);
if (retVal) {
contAssignTrees.put(variable, expr);
contAssignments.put(variable, assignment);
}
return retVal;
}
public boolean addRateAssign(String variable, String assignment) {
boolean retVal;
ExprTree expr = new ExprTree(lhpn);
expr.token = expr.intexpr_gettok(assignment);
retVal = expr.intexpr_L(assignment);
if (retVal) {
rateAssignTrees.put(variable, expr);
rateAssignments.put(variable, assignment);
}
return retVal;
}
public boolean addDelay(String delay) {
if (delay.equals("")) {
this.delay = null;
delayTree = null;
return true;
}
boolean retVal;
if (delay.matches("\\d+?,\\d+?")) {
delay = "uniform(" + delay + ")";
}
ExprTree expr = new ExprTree(lhpn);
expr.token = expr.intexpr_gettok(delay);
retVal = expr.intexpr_L(delay);
if (retVal) {
delayTree = expr;
this.delay = delay;
}
return retVal;
}
public boolean addPriority(String priority) {
if (priority.equals("")) {
this.priority = null;
priorityTree = null;
return true;
}
boolean retVal;
ExprTree expr = new ExprTree(lhpn);
expr.token = expr.intexpr_gettok(priority);
retVal = expr.intexpr_L(priority);
if (retVal) {
priorityTree = expr;
this.priority = priority;
}
return retVal;
}
public boolean addBoolAssign(String variable, String assignment) {
boolean retVal;
ExprTree expr = new ExprTree(lhpn);
expr.token = expr.intexpr_gettok(assignment);
retVal = expr.intexpr_L(assignment);
if (retVal) {
boolAssignTrees.put(variable, expr);
boolAssignments.put(variable, assignment);
}
return retVal;
}
public void setName(String newName) {
this.name = newName;
}
public void setFail(boolean fail) {
this.fail = fail;
}
public void setIndex(int idx) {
this.index = idx;
}
public void setPersistent(boolean persistent) {
this.persistent = persistent;
}
public boolean isFail() {
return fail;
}
public boolean isPersistent() {
return persistent;
}
public boolean isConnected() {
return (preset.size() > 0 || postset.size() > 0);
}
public boolean isInteresting(ArrayList<Transition> visited) {
visited.add(this);
if (boolAssignments.size() > 0 || intAssignments.size() > 0
|| contAssignments.size() > 0 || rateAssignments.size() > 0
|| fail) {
return true;
}
for (Place p : postset) {
for (Transition t : p.getPostset()) {
if (visited.contains(t)) {
continue;
}
if (t.isInteresting(visited)) {
return true;
}
}
}
return false;
}
public boolean hasConflictSet() {
for (Place p : getPreset()) {
for (Transition t : p.getPostset()) {
if (!this.toString().equals(t.toString())) {
return true;
}
}
}
return false;
}
public int getIndex() {
return this.index;
}
public String getName() {
return name;
}
public String getDelay() {
return delay;
}
public String getPriority() {
return priority;
}
public ExprTree getDelayTree() {
return delayTree;
}
public ExprTree getPriorityTree() {
return priorityTree;
}
public String getTransitionRate() {
if (delayTree != null) {
if (delayTree.op.equals("exponential")) {
return delayTree.r1.toString();
}
}
return null;
}
public ExprTree getTransitionRateTree() {
if (delayTree.op.equals("exponential")) {
return delayTree.r1;
}
return null;
}
public Place[] getPreset() {
Place[] array = new Place[preset.size()];
int i = 0;
for (Place p : preset) {
array[i++] = p;
}
return array;
}
public Place[] getPostset() {
Place[] array = new Place[postset.size()];
int i = 0;
for (Place p : postset) {
array[i++] = p;
}
return array;
}
public Transition[] getConflictSet() {
ArrayList<Transition> conflictSet = new ArrayList<Transition>();
for (Place p : getPreset()) {
for (Transition t : p.getPostset()) {
if (!this.toString().equals(t.toString())) {
conflictSet.add(t);
}
}
}
Transition[] returnSet = new Transition[conflictSet.size()];
int i = 0;
for (Transition t : conflictSet) {
returnSet[i] = t;
i++;
}
return returnSet;
}
public Set<String> getConflictSetTransNames() {
Set<String> conflictSet = new HashSet<String>();
for (Place p : getPreset()) {
for (Transition t : p.getPostset()) {
if (!this.toString().equals(t.toString())) {
conflictSet.add(t.getName());
}
}
}
return conflictSet;
}
public Set<Integer> getConflictSetTransIndices() {
Set<Integer> conflictSet = new HashSet<Integer>();
for (Place p : getPreset()) {
for (Transition t : p.getPostset()) {
if (!this.toString().equals(t.toString())) {
conflictSet.add(t.getIndex());
}
}
}
return conflictSet;
}
public String getEnabling() {
return enabling;
}
public ExprTree getEnablingTree() {
return enablingTree;
}
public HashMap<String, String> getAssignments() {
HashMap<String, String> assignments = new HashMap<String, String>();
assignments.putAll(boolAssignments);
assignments.putAll(intAssignments);
assignments.putAll(contAssignments);
for (String var : rateAssignments.keySet()) {
if (assignments.containsKey(var)) {
assignments.put(var + "_rate", rateAssignments.get(var));
} else {
assignments.put(var, rateAssignments.get(var));
}
}
return assignments;
}
public HashMap<String, ExprTree> getAssignTrees() {
HashMap<String, ExprTree> assignments = new HashMap<String, ExprTree>();
assignments.putAll(boolAssignTrees);
assignments.putAll(intAssignTrees);
assignments.putAll(contAssignTrees);
for (String var : rateAssignments.keySet()) {
if (assignments.containsKey(var)) {
assignments.put(var + "_rate", rateAssignTrees.get(var));
} else {
assignments.put(var, rateAssignTrees.get(var));
}
}
return assignments;
}
public ExprTree getAssignTree(String var) {
if (boolAssignTrees.containsKey(var)) {
return getBoolAssignTree(var);
}
if (intAssignTrees.containsKey(var)) {
return getIntAssignTree(var);
}
if (contAssignTrees.containsKey(var)) {
return getContAssignTree(var);
}
if (rateAssignTrees.containsKey(var)) {
return getRateAssignTree(var);
}
if (var.split("\\s").length > 1) {
return getRateAssignTree(var.split("\\s")[0]);
}
return null;
}
public HashMap<String, String> getContAssignments() {
return contAssignments;
}
public HashMap<String, ExprTree> getContAssignTrees() {
return contAssignTrees;
}
public String getContAssignment(String variable) {
return contAssignments.get(variable);
}
public ExprTree getContAssignTree(String variable) {
return contAssignTrees.get(variable);
}
public HashMap<String, String> getIntAssignments() {
return intAssignments;
}
public HashMap<String, ExprTree> getIntAssignTrees() {
return intAssignTrees;
}
public String getIntAssignment(String variable) {
return intAssignments.get(variable);
}
public ExprTree getIntAssignTree(String variable) {
return intAssignTrees.get(variable);
}
public HashMap<String, String> getRateAssignments() {
return rateAssignments;
}
public HashMap<String, ExprTree> getRateAssignTrees() {
return rateAssignTrees;
}
public String getRateAssignment(String variable) {
return rateAssignments.get(variable);
}
public ExprTree getRateAssignTree(String variable) {
return rateAssignTrees.get(variable);
}
public HashMap<String, String> getBoolAssignments() {
return boolAssignments;
}
public HashMap<String, ExprTree> getBoolAssignTrees() {
return boolAssignTrees;
}
public String getBoolAssignment(String variable) {
return boolAssignments.get(variable);
}
public ExprTree getBoolAssignTree(String variable) {
return boolAssignTrees.get(variable);
}
public void renamePlace(Place oldPlace, Place newPlace) {
if (preset.contains(oldPlace)) {
preset.add(newPlace);
preset.remove(oldPlace);
}
if (postset.contains(oldPlace)) {
postset.add(newPlace);
postset.remove(oldPlace);
}
}
public void removeEnabling() {
enabling = null;
enablingTree = null;
}
public void removePreset(Place place) {
preset.remove(place);
}
public void removePostset(Place place) {
postset.remove(place);
}
public void removeAllAssign() {
boolAssignments.clear();
contAssignments.clear();
rateAssignments.clear();
intAssignments.clear();
}
public void removeAssignment(String variable) {
if (contAssignments.containsKey(variable)) {
removeContAssign(variable);
}
if (rateAssignments.containsKey(variable)) {
removeRateAssign(variable);
}
if (intAssignments.containsKey(variable)) {
removeIntAssign(variable);
}
if (boolAssignments.containsKey(variable)) {
removeBoolAssign(variable);
}
if (variable.split("\\s").length > 1) {
removeRateAssign(variable.split("\\s")[0]);
}
}
public void removeBoolAssign(String variable) {
boolAssignments.remove(variable);
boolAssignTrees.remove(variable);
}
public void removeContAssign(String variable) {
contAssignments.remove(variable);
contAssignTrees.remove(variable);
}
public void removeRateAssign(String variable) {
rateAssignments.remove(variable);
rateAssignTrees.remove(variable);
}
public void removeIntAssign(String variable) {
intAssignments.remove(variable);
intAssignTrees.remove(variable);
}
public boolean containsDelay() {
return ((delay != null) && !delay.equals(""));
}
public boolean containsEnabling() {
return ((enabling != null) && !enabling.equals(""));
}
public boolean containsPriority() {
return ((priority != null) && !priority.equals(""));
}
public boolean containsPreset(String name) {
return preset.contains(name);
}
public boolean containsPostset(String name) {
return postset.contains(name);
}
public boolean containsAssignment() {
return (boolAssignments.size() > 0 || intAssignments.size() > 0
|| contAssignments.size() > 0 || rateAssignments.size() > 0);
}
public boolean containsBooleanAssignment() {
return boolAssignments.size() > 0;
}
public boolean containsIntegerAssignment() {
return intAssignments.size() > 0;
}
public boolean containsContinuousAssignment() {
return contAssignments.size() > 0;
}
public boolean containsRateAssignment() {
return rateAssignments.size() > 0;
}
public boolean containsAssignment(String var) {
if (boolAssignments.containsKey(var)) {
return true;
}
if (intAssignments.containsKey(var)) {
return true;
}
if (contAssignments.containsKey(var)) {
return true;
}
if (rateAssignments.containsKey(var)) {
return true;
}
return false;
}
public boolean simplifyExpr(boolean change) {
if (enablingTree != null) {
if (!enabling.equals(enablingTree.toString("LHPN"))) {
change = true;
}
String newEnab = enablingTree.toString("LHPN");
addEnabling(newEnab);
}
if (delayTree != null) {
if (!delay.equals(delayTree.toString("LHPN"))) {
change = true;
}
String newDelay = delayTree.toString("LHPN");
addDelay(newDelay);
}
for (String var : boolAssignTrees.keySet()) {
if (!boolAssignments.get(var).equals(
boolAssignTrees.get(var).toString("boolean", "LHPN"))) {
change = true;
}
boolAssignments.put(var, boolAssignTrees.get(var).toString(
"boolean", "LHPN"));
}
for (String var : intAssignTrees.keySet()) {
if (!intAssignments.get(var).equals(
intAssignTrees.get(var).toString("integer", "LHPN"))) {
change = true;
}
intAssignments.put(var, intAssignTrees.get(var).toString("integer",
"LHPN"));
}
for (String var : contAssignTrees.keySet()) {
if (!contAssignments.get(var).equals(
contAssignTrees.get(var).toString("continuous", "LHPN"))) {
change = true;
}
contAssignments.put(var, contAssignTrees.get(var).toString(
"continuous", "LHPN"));
}
for (String var : rateAssignTrees.keySet()) {
if (!rateAssignments.get(var).equals(
rateAssignTrees.get(var).toString("continuous", "LHPN"))) {
change = true;
}
rateAssignments.put(var, rateAssignTrees.get(var).toString(
"continuous", "LHPN"));
}
return change;
}
public boolean minimizeUniforms(boolean change) {
if (enablingTree != null) {
if (!enabling.equals(enablingTree.minimizeUniforms().toString(
"LHPN"))) {
change = true;
}
enabling = enablingTree.minimizeUniforms().toString("LHPN");
}
if (delayTree != null) {
if (!delay.equals(delayTree.minimizeUniforms().toString("LHPN"))) {
change = true;
}
delay = delayTree.minimizeUniforms().toString("LHPN");
}
for (String var : boolAssignTrees.keySet()) {
if (!boolAssignments.get(var).equals(
boolAssignTrees.get(var).minimizeUniforms().toString(
"boolean", "LHPN"))) {
change = true;
}
boolAssignments.put(var, boolAssignTrees.get(var)
.minimizeUniforms().toString("boolean", "LHPN"));
}
for (String var : intAssignTrees.keySet()) {
if (!intAssignments.get(var).equals(
intAssignTrees.get(var).minimizeUniforms().toString(
"integer", "LHPN"))) {
change = true;
}
intAssignments.put(var, intAssignTrees.get(var).minimizeUniforms()
.toString("integer", "LHPN"));
}
for (String var : contAssignTrees.keySet()) {
if (!contAssignments.get(var).equals(
contAssignTrees.get(var).minimizeUniforms().toString(
"continuous", "LHPN"))) {
change = true;
}
contAssignments.put(var, contAssignTrees.get(var)
.minimizeUniforms().toString("continuous", "LHPN"));
}
for (String var : rateAssignTrees.keySet()) {
if (!rateAssignments.get(var).equals(
rateAssignTrees.get(var).minimizeUniforms().toString(
"continuous", "LHPN"))) {
change = true;
}
rateAssignments.put(var, rateAssignTrees.get(var)
.minimizeUniforms().toString("continuous", "LHPN"));
}
return change;
}
@Override
public String toString() {
return name;
}
public void changeName(String newName) {
name = newName;
}
/**
* @return LPN object containing this LPN transition.
*/
public LhpnFile getLpn() {
return lhpn;
}
/**
* @param lpn - Associated LPN containing this LPN transition.
*/
public void setLpn(LhpnFile lpn) {
this.lhpn = lpn;
}
public boolean local() {
// Returns true if LPNTran only modifies non-output variables.
boolean isLocal = true;
for (String assignVar : this.getAssignments().keySet()) {
if (!this.getLpn().getAllInternals().keySet().contains(assignVar)) {
isLocal = false;
break;
}
}
return isLocal;
}
public List<LhpnFile> getDstLpnList(){
return this.dstLpnList;
}
public void addDstLpn(LhpnFile lpn){
this.dstLpnList.add(lpn);
}
public String getFullLabel() {
return this.lhpn.getLabel() + ":" + this.name;
}
/**
* Check if firing 'fired_transition' causes a disabling error.
* @param current_enabled_transitions
* @param next_enabled_transitions
* @return
*/
public Transition disablingError(final LinkedList<Transition> current_enabled_transitions,
LinkedList<Transition> next_enabled_transitions) {
if (current_enabled_transitions == null || current_enabled_transitions.size()==0)
return null;
for(Transition curTran : current_enabled_transitions) {
if (curTran == this)
continue;
boolean disabled = true;
if (next_enabled_transitions != null && next_enabled_transitions.size()!=0) {
for(Transition nextTran : next_enabled_transitions) {
if(curTran == nextTran) {
disabled = false;
break;
}
}
}
if (disabled == true) {
Place[] preset1 = this.getPreset();
Place[] preset2 = curTran.getPreset();
Boolean share=false;
for (int i=0; i < preset1.length && !share; i++) {
for (int j=0; j < preset2.length && !share; j++) {
if (preset1[i].getName().equals(preset2[j].getName())) share=true;
}
}
if (!share) return curTran;
// if(this.sharePreSet(curTran) == false)
// return curTran;
/*
for (Iterator<String> confIter = this.getConflictSetTransNames().iterator(); confIter.hasNext();) {
String tran = confIter.next();
if (curTran.getConflictSetTransNames().contains(tran))
return curTran;
}
*/
}
}
return null;
}
public void setSticky(boolean sticky) {
this.sticky = sticky;
}
public boolean isSticky() {
return this.sticky;
}
public void setDstLpnList(LhpnFile curLPN) {
String[] allVars = curLPN.getVariables();
boolean foundLPN = false;
if (this.getAssignments() != null) {
Set<String> assignedVars = this.getAssignments().keySet();
for (Iterator<String> assignedVarsIter = assignedVars.iterator(); assignedVarsIter.hasNext();) {
String curVar = assignedVarsIter.next();
for (int i=0; i<allVars.length; i++) {
if (curVar.equals(allVars[i]) && !this.dstLpnList.contains(curLPN)) {
this.dstLpnList.add(curLPN);
foundLPN = true;
break;
}
}
if (foundLPN)
break;
}
}
}
/* Maybe copy method below is not needed.
public Transition copy(HashMap<String, VarNode> variables){
return new Transition(this.name, this.index, this.preset, this.postset, this.enablingGuard.copy(variables),
this.assignments.copy(variables), this.delayLB, this.delayUB, this.local);
}
*/
}
|
package stategraph;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.Stack;
import lhpn2sbml.parser.ExprTree;
import lhpn2sbml.parser.LHPNFile;
public class StateGraph {
private HashMap<String, LinkedList<Marking>> stateGraph;
private LHPNFile lhpn;
public StateGraph(LHPNFile lhpn) {
this.lhpn = lhpn;
stateGraph = new HashMap<String, LinkedList<Marking>>();
buildStateGraph();
}
private void buildStateGraph() {
ArrayList<String> variables = new ArrayList<String>();
for (String var : lhpn.getBooleanVars()) {
variables.add(var);
}
boolean[] variableVector = new boolean[variables.size()];
for (int i = 0; i < variableVector.length; i++) {
if (lhpn.getInitialVal(variables.get(i)).equals("true")) {
variableVector[i] = true;
}
else {
variableVector[i] = false;
}
}
ArrayList<String> markedPlaces = new ArrayList<String>();
HashMap<String, Boolean> places = lhpn.getPlaces();
for (String place : places.keySet()) {
if (places.get(place)) {
markedPlaces.add(place);
}
}
LinkedList<Marking> markings = new LinkedList<Marking>();
int counter = 0;
Marking state = new Marking(markedPlaces.toArray(new String[0]), new Marking[0], "S"
+ counter);
markings.add(state);
counter++;
stateGraph.put(vectorToString(variableVector), markings);
Stack<Transition> transitionsToFire = new Stack<Transition>();
for (String transition : lhpn.getTransitionList()) {
boolean addToStack = true;
for (String place : lhpn.getPreset(transition)) {
if (!markedPlaces.contains(place)) {
addToStack = false;
}
}
if (addToStack) {
transitionsToFire.push(new Transition(transition, copyArrayList(markedPlaces),
copyStateVector(variableVector), state));
}
}
while (transitionsToFire.size() != 0) {
Transition fire = transitionsToFire.pop();
markedPlaces = fire.getMarkedPlaces();
variableVector = fire.getVariableVector();
for (String place : lhpn.getPreset(fire.getTransition())) {
markedPlaces.remove(place);
}
for (String place : lhpn.getPostset(fire.getTransition())) {
markedPlaces.add(place);
}
for (int i = 0; i < variables.size(); i++) {
if (lhpn.getBoolAssignTree(fire.getTransition(), variables.get(i)) != null) {
if (evaluateExp(lhpn.getBoolAssignTree(fire.getTransition(), variables.get(i)))
.equals("true")) {
variableVector[i] = true;
}
else {
variableVector[i] = false;
}
}
}
if (!stateGraph.containsKey(vectorToString(variableVector))) {
markings = new LinkedList<Marking>();
state = new Marking(markedPlaces.toArray(new String[0]), new Marking[0], "S"
+ counter);
markings.add(state);
fire.getParent().addNextState(state);
counter++;
stateGraph.put(vectorToString(variableVector), markings);
for (String transition : lhpn.getTransitionList()) {
boolean addToStack = true;
for (String place : lhpn.getPreset(transition)) {
if (!markedPlaces.contains(place)) {
addToStack = false;
}
}
if (addToStack) {
transitionsToFire
.push(new Transition(transition, copyArrayList(markedPlaces),
copyStateVector(variableVector), state));
}
}
}
else {
markings = stateGraph.get(vectorToString(variableVector));
boolean add = true;
boolean same = true;
for (Marking mark : markings) {
for (String place : mark.getMarkings()) {
if (!markedPlaces.contains(place)) {
same = false;
}
}
for (String place : markedPlaces) {
boolean contains = false;
for (String place2 : mark.getMarkings()) {
if (place2.equals(place)) {
contains = true;
}
}
if (!contains) {
same = false;
}
}
if (same) {
add = false;
fire.getParent().addNextState(mark);
}
same = true;
}
if (add) {
state = new Marking(markedPlaces.toArray(new String[0]), new Marking[0], "S"
+ counter);
markings.add(state);
fire.getParent().addNextState(state);
counter++;
stateGraph.put(vectorToString(variableVector), markings);
for (String transition : lhpn.getTransitionList()) {
boolean addToStack = true;
for (String place : lhpn.getPreset(transition)) {
if (!markedPlaces.contains(place)) {
addToStack = false;
}
}
if (addToStack) {
transitionsToFire.push(new Transition(transition,
copyArrayList(markedPlaces), copyStateVector(variableVector),
state));
}
}
}
}
}
}
private String evaluateExp(ExprTree[] exprTrees) {
return "false";
}
private ArrayList<String> copyArrayList(ArrayList<String> original) {
ArrayList<String> copy = new ArrayList<String>();
for (String element : original) {
copy.add(element);
}
return copy;
}
private boolean[] copyStateVector(boolean[] original) {
boolean[] copy = new boolean[original.length];
for (int i = 0; i < original.length; i++) {
copy[i] = original[i];
}
return copy;
}
private String vectorToString(boolean[] vector) {
String string = "";
for (boolean b : vector) {
if (b) {
string += "1";
}
else {
string += "0";
}
}
return string;
}
public void outputStateGraph(String file) {
try {
BufferedWriter out = new BufferedWriter(new FileWriter(file));
out.write("digraph G {\n");
for (String state : stateGraph.keySet()) {
for (Marking m : stateGraph.get(state)) {
out.write(m.getID() + " [shape=\"ellipse\",label=\"" + state + "\"]\n");
for (Marking next : m.getNextStates()) {
out.write(m.getID() + " -> " + next.getID() + "\n");
}
}
}
out.write("}");
out.close();
}
catch (Exception e) {
System.err.println("Error outputting state graph as dot file.");
}
}
private class Transition {
private String transition;
private boolean[] variableVector;
private ArrayList<String> markedPlaces;
private Marking parent;
private Transition(String transition, ArrayList<String> markedPlaces,
boolean[] variableVector, Marking parent) {
this.transition = transition;
this.markedPlaces = markedPlaces;
this.variableVector = variableVector;
this.parent = parent;
}
private String getTransition() {
return transition;
}
private ArrayList<String> getMarkedPlaces() {
return markedPlaces;
}
private boolean[] getVariableVector() {
return variableVector;
}
private Marking getParent() {
return parent;
}
}
private class Marking {
private String[] markings;
private Marking[] nextStates;
private String id;
private Marking(String[] markings, Marking[] nextStates, String id) {
this.markings = markings;
this.nextStates = nextStates;
this.id = id;
}
private String getID() {
return id;
}
private String[] getMarkings() {
return markings;
}
private Marking[] getNextStates() {
return nextStates;
}
private void addNextState(Marking nextState) {
Marking[] newNextStates = new Marking[nextStates.length + 1];
for (int i = 0; i < nextStates.length; i++) {
newNextStates[i] = nextStates[i];
}
newNextStates[newNextStates.length - 1] = nextState;
nextStates = newNextStates;
}
}
}
|
package jp.sf.fess.suggest.service;
import jp.sf.fess.suggest.FessSuggestTestCase;
import jp.sf.fess.suggest.SpellChecker;
import jp.sf.fess.suggest.SuggestConstants;
import jp.sf.fess.suggest.Suggester;
import jp.sf.fess.suggest.entity.SuggestResponse;
import jp.sf.fess.suggest.server.SuggestSolrServer;
import org.apache.solr.client.solrj.impl.HttpSolrServer;
import org.apache.solr.common.SolrDocumentList;
import java.net.URLEncoder;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
public class SuggestServiceTest extends FessSuggestTestCase {
protected SuggestService service;
SuggestSolrServer suggestSolrServer;
public void setUp() throws Exception {
super.setUp();
startSolr();
Suggester suggester = new Suggester();
suggester.setConverter(createConverter());
suggester.setNormalizer(createNormalizer());
SpellChecker spellChecker = new SpellChecker();
spellChecker.setConverter(createConverter());
spellChecker.setNormalizer(createNormalizer());
suggestSolrServer = new SuggestSolrServer(new HttpSolrServer(SOLR_URL));
service = new SuggestService(suggester, spellChecker, suggestSolrServer);
suggestSolrServer.deleteByQuery("*:*");
}
@Override
public void tearDown() throws Exception {
super.tearDown();
stopSolr();
}
public void test_addSolrParams() throws Exception {
service.addSolrParams("q=content:hoge");
service.commit();
Thread.sleep(2 * 1000);
SolrDocumentList list = suggestSolrServer.select("*:*");
assertEquals(1, list.getNumFound());
}
public void test_addSolrParamsJapanese() throws Exception {
String query = "q=content:" + URLEncoder.encode("", SuggestConstants.UTF_8);
service.addSolrParams(query);
service.commit();
Thread.sleep(2 * 1000);
SolrDocumentList list = suggestSolrServer.select("*:*");
assertEquals(1, list.getNumFound());
SuggestResponse response = service.getSuggestResponse("", null, null, null, 20);
List sList = response.get("");
assertEquals("", sList.get(0));
}
public void test_addMultipleWords() throws Exception {
service.addSolrParams("q=content:hoge AND content:fuga");
service.addSolrParams("q=content:hoge AND content:zzz");
service.addSolrParams("q=content:hoge AND content:zzz");
service.commit();
Thread.sleep(2 * 1000);
assertEquals(2, service.getSearchLogDocumentNum());
assertEquals(0, service.getContentDocumentNum());
SuggestResponse response = service.getSuggestResponse("hoge", null, null, null, 20);
List sList = response.get("hoge");
assertEquals("hoge zzz", sList.get(0));
assertEquals("hoge fuga", sList.get(1));
response = service.getSuggestResponse("hoge f", null, null, null, 20);
sList = response.get("hoge f");
assertEquals(1, sList.size());
assertEquals("hoge fuga", sList.get(0));
}
public void test_addElevateWord() throws Exception {
service.addElevateWord("hoge", null, null, null, 0);
service.commit();
Thread.sleep(2 * 1000);
SuggestResponse response = service.getSuggestResponse("hoge", null, null, null, 20);
List sList = response.get("hoge");
assertEquals("hoge", sList.get(0));
}
public void test_updateBadWords() throws Exception {
Set<String> badWords = new HashSet<>();
badWords.add("hoge");
service.updateBadWords(badWords);
service.addSolrParams("q=content:hoge");
service.addSolrParams("q=content:hoge AND content:zzz");
service.commit();
Thread.sleep(2 * 1000);
SolrDocumentList list = suggestSolrServer.select("*:*");
assertEquals(0, list.getNumFound());
}
public void test_deleteBadWords() throws Exception {
service.addSolrParams("q=content:hoge");
service.addSolrParams("q=content:zzz");
service.addSolrParams("q=content:hoge AND content:zzz");
service.addSolrParams("q=content:fuga AND content:zzz");
service.commit();
Thread.sleep(2 * 1000);
SolrDocumentList list = suggestSolrServer.select("*:*");
assertEquals(4, list.getNumFound());
Set<String> badWords = new HashSet<>();
badWords.add("hoge");
service.updateBadWords(badWords);
service.deleteBadWords();
service.commit();
Thread.sleep(2 * 1000);
list = suggestSolrServer.select("*:*");
assertEquals(2, list.getNumFound());
badWords.add("zzz");
service.updateBadWords(badWords);
service.deleteBadWords();
service.commit();
Thread.sleep(2 * 1000);
list = suggestSolrServer.select("*:*");
assertEquals(0, list.getNumFound());
}
}
|
package kodkod.test.pardinus.temporal;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import java.util.Iterator;
import org.junit.Test;
import kodkod.ast.Expression;
import kodkod.ast.Formula;
import kodkod.ast.IntConstant;
import kodkod.ast.Relation;
import kodkod.engine.Evaluator;
import kodkod.engine.PardinusSolver;
import kodkod.engine.Solution;
import kodkod.engine.config.ExtendedOptions;
import kodkod.instance.PardinusBounds;
import kodkod.instance.TupleFactory;
import kodkod.instance.TupleSet;
import kodkod.instance.Universe;
/**
* Tests for mutable integer relations.
*
* @author Nuno Macedo // [HASLab] temporal model finding
*/
public class VarIntegerTests {
@Test
public void test0() {
Relation a = Relation.unary_variable("a");
Universe uni = new Universe("-2", "-1", "0", "1");
TupleFactory f = uni.factory();
TupleSet as = f.range(f.tuple("-2"), f.tuple("1"));
PardinusBounds bounds = new PardinusBounds(uni);
bounds.boundExactly(-2, f.range(f.tuple("-2"), f.tuple("-2")));
bounds.boundExactly(-1, f.range(f.tuple("-1"), f.tuple("-1")));
bounds.boundExactly(0, f.range(f.tuple("0"), f.tuple("0")));
bounds.boundExactly(1, f.range(f.tuple("1"), f.tuple("1")));
bounds.bound(a, as);
Formula formula = a.sum().eq(IntConstant.constant(1)).always();
ExtendedOptions opt = new ExtendedOptions();
// opt.setReporter(new SLF4JReporter());
opt.setBitwidth(2);
opt.setRunTemporal(true);
opt.setRunDecomposed(false);
opt.setMaxTraceLength(2);
opt.setNoOverflow(false);
PardinusSolver solver = new PardinusSolver(opt);
assertTrue("expected sat", solver.solve(formula, bounds).sat());
Iterator<Solution> sols = solver.solveAll(formula, bounds);
Solution sol = sols.next();
int c = 1;
while (sol.sat()) {
sol = sols.next();
c++;
if (sol.sat()) {
opt.reporter().debug(sol.instance().toString());
}
}
assertEquals(29, c);
solver.free();
}
@Test
public void test1() {
Relation a = Relation.unary_variable("a");
Universe uni = new Universe("-2", "-1", "0", "1");
TupleFactory f = uni.factory();
TupleSet as = f.range(f.tuple("-2"), f.tuple("1"));
PardinusBounds bounds = new PardinusBounds(uni);
bounds.boundExactly(-2, f.range(f.tuple("-2"), f.tuple("-2")));
bounds.boundExactly(-1, f.range(f.tuple("-1"), f.tuple("-1")));
bounds.boundExactly(0, f.range(f.tuple("0"), f.tuple("0")));
bounds.boundExactly(1, f.range(f.tuple("1"), f.tuple("1")));
bounds.bound(a, as);
Formula formula = (a.sum().eq(IntConstant.constant(1)).and(a.count().eq(IntConstant.constant(-2)))).always();
ExtendedOptions opt = new ExtendedOptions();
opt.setBitwidth(2);
opt.setRunTemporal(true);
opt.setRunDecomposed(false);
opt.setMaxTraceLength(2);
opt.setNoOverflow(false);
PardinusSolver solver = new PardinusSolver(opt);
assertTrue("expected sat", solver.solve(formula, bounds).sat());
Iterator<Solution> sols = solver.solveAll(formula, bounds);
Solution sol = sols.next();
int c = 1;
while (sol.sat()) {
sol = sols.next();
c++;
if (sol.sat()) {
opt.reporter().debug(sol.instance().toString());
}
}
assertEquals(7, c);
solver.free();
}
@Test
public void testU() {
Relation a = Relation.unary_variable("a");
Universe uni = new Universe("-2", "-1", "0", "1");
TupleFactory f = uni.factory();
TupleSet as = f.range(f.tuple("-2"), f.tuple("1"));
PardinusBounds bounds = new PardinusBounds(uni);
bounds.boundExactly(-2, f.range(f.tuple("-2"), f.tuple("-2")));
bounds.boundExactly(-1, f.range(f.tuple("-1"), f.tuple("-1")));
bounds.boundExactly(0, f.range(f.tuple("0"), f.tuple("0")));
bounds.boundExactly(1, f.range(f.tuple("1"), f.tuple("1")));
bounds.bound(a, as);
Formula formula = a.sum().eq(IntConstant.constant(2)).always();
ExtendedOptions opt = new ExtendedOptions();
opt.setBitwidth(2);
opt.setRunTemporal(true);
opt.setRunDecomposed(false);
opt.setMaxTraceLength(3);
opt.setNoOverflow(true);
// opt.setReporter(new ConsoleReporter());
PardinusSolver solver = new PardinusSolver(opt);
assertFalse("expected unsat", solver.solve(formula, bounds).sat());
}
@Test
public void testEnc() {
Relation a = Relation.unary_variable("a");
Universe uni = new Universe("-2", "-1", "0", "1");
TupleFactory f = uni.factory();
TupleSet as = f.range(f.tuple("-2"), f.tuple("1"));
PardinusBounds bounds = new PardinusBounds(uni);
bounds.boundExactly(-2, f.range(f.tuple("-2"), f.tuple("-2")));
bounds.boundExactly(-1, f.range(f.tuple("-1"), f.tuple("-1")));
bounds.boundExactly(0, f.range(f.tuple("0"), f.tuple("0")));
bounds.boundExactly(1, f.range(f.tuple("1"), f.tuple("1")));
bounds.bound(a, as);
Formula formula = a.sum().eq(IntConstant.constant(1)).always();
ExtendedOptions opt = new ExtendedOptions();
// opt.setReporter(new SLF4JReporter());
opt.setBitwidth(2);
opt.setRunTemporal(true);
opt.setRunDecomposed(false);
opt.setMaxTraceLength(2);
opt.setNoOverflow(false);
PardinusSolver solver = new PardinusSolver(opt);
assertTrue("expected sat", solver.solve(formula, bounds).sat());
Solution sol = solver.solveAll(formula, bounds).next();
assertEquals(4,sol.instance().ints().size());
Evaluator eval = new Evaluator(sol.instance());
assertEquals(4,eval.evaluate(Expression.INTS).size());
assertEquals(4,eval.evaluate(Expression.INTS,2).size());
assertEquals(2,eval.evaluate(a).size());
assertEquals(2,eval.evaluate(a,3).size());
solver.free();
}
}
|
package nl.yacht.lakesideresort.domain;
import org.junit.Assert;
import org.junit.Test;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
public class BoatRentalTest {
/**
* Testing a private method using reflection
*/
@Test
public void testGetNewTripNumber(){
BoatRental rental = new BoatRental();
List<Trip> tripsMock = new ArrayList<>();
Trip trip1 = new Trip(5);
Trip trip2 = new Trip(2);
Trip trip3 = new Trip(8);
Trip trip4 = new Trip(1);
try {
Field field = rental.getClass().getDeclaredField("trips");
field.setAccessible(true);
field.set(rental, tripsMock);
Method method = rental.getClass().getDeclaredMethod("getNewTripNumber", null);
method.setAccessible(true);
int tripNr = (int) method.invoke(rental);
Assert.assertTrue(tripNr == 9);
} catch (NoSuchFieldException e) {
e.printStackTrace();
} catch (IllegalAccessException e){
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
}
}
|
package org.jnosql.javaone.gameon.map;
import org.apache.tinkerpop.gremlin.structure.Edge;
import org.apache.tinkerpop.gremlin.structure.Graph;
import org.apache.tinkerpop.gremlin.structure.Vertex;
import org.jnosql.artemis.graph.EdgeEntity;
import org.jnosql.artemis.graph.GraphTemplate;
import org.jnosql.javaone.gameon.map.infrastructure.CDIExtension;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import javax.inject.Inject;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashSet;
import java.util.Optional;
import java.util.Set;
import static org.apache.tinkerpop.gremlin.structure.Direction.OUT;
import static org.jnosql.javaone.gameon.map.Site.builder;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
@ExtendWith(CDIExtension.class)
public class SiteServiceTest {
@Inject
private SiteService siteService;
@Inject
private Graph graph;
@Inject
private GraphTemplate template;
@BeforeEach
public void before() {
graph.traversal().V().toList().forEach(Vertex::remove);
graph.traversal().E().toList().forEach(Edge::remove);
}
@Test
public void shouldCreate() {
Site site = builder().withName("main").withFullName("Main room site").build();
siteService.create(site);
assertTrue(siteService.findByName(site.getName()).isPresent());
}
@Test
public void shouldReturnErrorWhenThereIsDoubleRoom() {
Site site = builder().withName("main").withFullName("Main room site").build();
siteService.create(site);
IllegalArgumentException exception = assertThrows(IllegalArgumentException.class, () -> siteService.create(site));
assertEquals("The site name already does exist: main", exception.getMessage());
}
@Test
public void shouldUpdateSite() {
String newFullName = "update Main room site";
Site site = builder().withName("main").withFullName("Main room site").build();
siteService.create(site);
siteService.update(builder().withName("main").withFullName(newFullName).build());
Site updatedSite = siteService.findByName("main").orElseThrow(() -> new NullPointerException("Cannot be null"));
assertEquals(newFullName, updatedSite.getFullName());
}
@Test
public void shouldCreateNewSite() {
assertNotNull(siteService.createSite());
}
@Test
public void shouldGoTo() {
String forward = "west gate description";
String backward = "back gate description";
Site main = builder().withName("main").withFullName("Main room site").withCoordinate(Coordinate.MAIN).build();
siteService.create(main);
Site site = builder().withName("second").withFullName("Main room site").build();
siteService.createSite().to(site).from("main").by(Direction.WEST);
Site eastSite = siteService.findByName("second").get();
main = siteService.findByName("main").get();
Site result = siteService.goTo(main, Direction.WEST).get();
Site resultB = siteService.goTo(eastSite, Direction.EAST).get();
assertEquals(eastSite.getId(), result.getId());
assertEquals(main.getId(), resultB.getId());
}
@Test
public void shouldReturnMainRoom() {
Site main = builder().withName("main").withFullName("Main room site").withCoordinate(Coordinate.MAIN).build();
siteService.create(main);
Optional<Site> recentRoom = siteService.getRecentRoom();
Assertions.assertEquals("main", recentRoom.map(Site::getName).orElse(""));
}
@Test
public void shouldCreateWhenSiteAreNull() {
Site main = builder().withName("main").withFullName("Main room site").build();
siteService.place(main);
main = siteService.findByName("main")
.orElseThrow(() -> new RuntimeException("Should return the main room"));
assertEquals("main", main.getName());
assertEquals("Main room site", main.getFullName());
assertEquals(Coordinate.MAIN, main.getCoordinate());
assertNotNull(main.getId());
}
@Test
public void shouldCreateNextRoom() {
Site main = builder().withName("main").withFullName("Main room site").withCoordinate(Coordinate.MAIN).build();
siteService.create(main);
main = siteService.findByName("main").get();
Site second = builder().withName("second").withFullName("second room").build();
siteService.place(second);
Site site = siteService.goTo(main, Direction.NORTH).get();
Assertions.assertEquals(site.getName(), second.getName());
}
@Test
public void shouldDoMap() {
Site main = builder().withName("main").withFullName("Main room site").withCoordinate(Coordinate.MAIN).build();
siteService.create(main);
Site second = builder().withName("second").withFullName("second room").build();
Site third = builder().withName("third").withFullName("third room").build();
Site fourth = builder().withName("fourth").withFullName("fourth room").build();
Site fifth = builder().withName("fifth").withFullName("fifth room").build();
Set<Site> sites = new HashSet<>(Arrays.asList(second, third, fourth, fifth));
siteService.place(second);
siteService.place(third);
siteService.place(fourth);
siteService.place(fifth);
main = siteService.findByName(main.getName()).get();
for (Direction direction : Direction.values()) {
Optional<Site> site = siteService.goTo(main, direction);
Assertions.assertTrue(site.isPresent());
sites.remove(site.get());
}
Assertions.assertTrue(sites.isEmpty());
}
@Test
public void shouldBecameUnavailable() {
Site main = builder().withName("main").withFullName("Main room site").withCoordinate(Coordinate.MAIN).build();
siteService.create(main);
Site second = builder().withName("second").withFullName("second room").build();
Site third = builder().withName("third").withFullName("third room").build();
Site fourth = builder().withName("fourth").withFullName("fourth room").build();
Site fifth = builder().withName("fifth").withFullName("fifth room").build();
siteService.place(second);
siteService.place(third);
siteService.place(fourth);
siteService.place(fifth);
main = siteService.findByName("main").get();
assertFalse(main.isDoorAvailable());
}
@Test
public void shouldGoLevelTwo() {
Site main = builder().withName("main").withFullName("Main room site").withCoordinate(Coordinate.MAIN).build();
siteService.create(main);
for (int index = 0; index < 12; index++) {
Site site = builder().withName("room_" + index).withFullName("room_" + index).build();
siteService.place(site);
site = siteService.findByName(site.getName()).get();
}
Coordinate[][] coordinates = new Coordinate[5][5];
Site[][] sites = new Site[5][5];
for (int x = -2; x <= 2; x++) {
for (int y = -2; y <= 2; y++) {
coordinates[x + 2][y + 2] = Coordinate.builder().withX(x).withY(y).build();
Optional<Site> siteXY = siteService.findByCoordinate(coordinates[x + 2][y + 2]);
if (siteXY.isPresent()) {
sites[x + 2][y + 2] = siteXY.get();
}
}
}
//y = -2
Assertions.assertNull(sites[0][0]);
Assertions.assertNull(sites[1][0]);
Assertions.assertNotNull(sites[2][0]);
Assertions.assertNull(sites[3][0]);
Assertions.assertNull(sites[4][0]);
//y = -1
Assertions.assertNull(sites[0][1]);
Assertions.assertNotNull(sites[1][1]);
Assertions.assertNotNull(sites[2][1]);
Assertions.assertNotNull(sites[3][1]);
Assertions.assertNull(sites[4][1]);
//y = -0
Assertions.assertNotNull(sites[0][2]);
Assertions.assertNotNull(sites[1][2]);
Assertions.assertNotNull(sites[2][2]);
Assertions.assertNotNull(sites[3][2]);
Assertions.assertNotNull(sites[4][2]);
//y = 1
Assertions.assertNull(sites[0][3]);
Assertions.assertNotNull(sites[1][3]);
Assertions.assertNotNull(sites[2][3]);
Assertions.assertNotNull(sites[3][3]);
Assertions.assertNull(sites[4][3]);
//y = 2
Assertions.assertNull(sites[0][4]);
Assertions.assertNull(sites[1][4]);
Assertions.assertNotNull(sites[2][4]);
Assertions.assertNull(sites[3][4]);
Assertions.assertNull(sites[4][4]);
//x = 0, y = 1
{
Site zp1 = sites[2][3];
Collection<EdgeEntity> edges_zp1 = template.getEdges(zp1, OUT);
Assertions.assertEquals(4, edges_zp1.size());
Assertions.assertEquals(sites[1][3], siteService.goTo(zp1, Direction.WEST).get());
Assertions.assertEquals(sites[3][3], siteService.goTo(zp1, Direction.EAST).get());
Assertions.assertEquals(sites[2][4], siteService.goTo(zp1, Direction.NORTH).get());
Assertions.assertEquals(sites[2][2], siteService.goTo(zp1, Direction.SOUTH).get());
}
//x = 0, y = 2
{
Site zp2 = sites[2][4];
Collection<EdgeEntity> edges_zp2 = template.getEdges(zp2, OUT);
Assertions.assertEquals(1, edges_zp2.size());
Assertions.assertEquals(sites[2][3], siteService.goTo(zp2, Direction.SOUTH).get());
assertFalse(siteService.goTo(zp2, Direction.NORTH).isPresent());
assertFalse(siteService.goTo(zp2, Direction.EAST).isPresent());
assertFalse(siteService.goTo(zp2, Direction.WEST).isPresent());
}
//x = -1, y = -1
{
Site m1m1 = sites[1][1];
Collection<EdgeEntity> edges_m1m1 = template.getEdges(m1m1, OUT);
Assertions.assertEquals(2, edges_m1m1.size());
Assertions.assertEquals(sites[1][2], siteService.goTo(m1m1, Direction.NORTH).get());
Assertions.assertEquals(sites[2][1], siteService.goTo(m1m1, Direction.EAST).get());
assertFalse(siteService.goTo(m1m1, Direction.WEST).isPresent());
assertFalse(siteService.goTo(m1m1, Direction.SOUTH).isPresent());
}
}
@Test
public void shouldDelete() {
Site main = builder().withName("main").withFullName("Main room site").withCoordinate(Coordinate.MAIN).build();
siteService.create(main);
siteService.deleteByName("main");
assertFalse(siteService.findByName("main").isPresent());
Optional<Site> site = siteService.findByName("0:0");
Assertions.assertTrue(site.isPresent());
Assertions.assertTrue(site.map(Site::isEmpty).orElse(false));
}
}
|
package biomodel.gui.sbmlcore;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.net.URI;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.ListSelectionModel;
import main.Gui;
import main.util.Utility;
import org.sbml.jsbml.ASTNode;
import org.sbml.jsbml.Compartment;
import org.sbml.jsbml.InitialAssignment;
import org.sbml.jsbml.KineticLaw;
import org.sbml.jsbml.ListOf;
import org.sbml.jsbml.LocalParameter;
import org.sbml.jsbml.Model;
import org.sbml.jsbml.ModifierSpeciesReference;
import org.sbml.jsbml.Parameter;
import org.sbml.jsbml.Reaction;
import org.sbml.jsbml.SBMLDocument;
import org.sbml.jsbml.SBase;
import org.sbml.jsbml.SimpleSpeciesReference;
import org.sbml.jsbml.Species;
import org.sbml.jsbml.SpeciesReference;
import org.sbml.jsbml.UnitDefinition;
import org.sbml.jsbml.ext.arrays.ArraysSBasePlugin;
import org.sbml.jsbml.ext.arrays.Index;
import org.sbml.jsbml.ext.comp.Port;
import org.sbml.jsbml.ext.fbc.FluxBound;
import biomodel.annotation.AnnotationUtility;
import biomodel.annotation.SBOLAnnotation;
import biomodel.gui.sbol.SBOLField;
import biomodel.gui.schematic.ModelEditor;
import biomodel.parser.BioModel;
import biomodel.util.GlobalConstants;
import biomodel.util.SBMLutilities;
/**
* This is a class for creating SBML parameters
*
* @author Chris Myers
*
*/
public class Reactions extends JPanel implements ActionListener, MouseListener {
private static final long serialVersionUID = 1L;
private JComboBox stoiciLabel;
private JComboBox reactionComp; // compartment combo box
private JList reactions; // JList of reactions
private String[] reacts; // array of reactions
/*
* reactions buttons
*/
private JButton addReac, removeReac, editReac;
private JList reacParameters; // JList of reaction parameters
private String[] reacParams; // array of reaction parameters
/*
* reaction parameters buttons
*/
private JButton reacAddParam, reacRemoveParam, reacEditParam;
private ArrayList<LocalParameter> changedParameters; // ArrayList of parameters
/*
* reaction parameters text fields
*/
private JTextField reacParamID, reacParamValue, reacParamName;
private JComboBox reacParamUnits;
private JTextField reacID, reacName; // reaction name and id text
private JCheckBox onPort, paramOnPort;
// fields
private JComboBox reacReverse, reacFast; // reaction reversible, fast combo
// boxes
/*
* reactant buttons
*/
private JButton addReactant, removeReactant, editReactant;
private JList reactants; // JList for reactants
private String[] reacta; // array for reactants
private JComboBox reactantConstant;
/*
* ArrayList of reactants
*/
private ArrayList<SpeciesReference> changedReactants;
/*
* product buttons
*/
private JButton addProduct, removeProduct, editProduct;
private JList products; // JList for products
private String[] proda; // array for products
private JComboBox productConstant;
/*
* ArrayList of products
*/
private ArrayList<SpeciesReference> changedProducts;
/*
* modifier buttons
*/
private JButton addModifier, removeModifier, editModifier;
private JList modifiers; // JList for modifiers
private String[] modifierArray; // array for modifiers
/*
* ArrayList of modifiers
*/
private ArrayList<ModifierSpeciesReference> changedModifiers;
private JComboBox productSpecies; // ComboBox for product editing
private JComboBox modifierSpecies; // ComboBox for modifier editing
private JTextField productId;
private JTextField productName;
private JTextField modifierName;
private JTextField productStoichiometry; // text field for editing products
private JComboBox reactantSpecies; // ComboBox for reactant editing
private JTextField RiIndex;
private JTextField PiIndex;
private JTextField MiIndex, modifierId;
private JTextField CiIndex;
/*
* text field for editing reactants
*/
private JTextField reactantId;
private JTextField reactantName;
private SBOLField sbolField;
private JTextField reactantStoichiometry;
private JTextArea kineticLaw; // text area for editing kinetic law
private ArrayList<String> thisReactionParams;
private JButton useMassAction, clearKineticLaw;
private BioModel bioModel;
private Boolean paramsOnly;
private String file;
private ArrayList<String> parameterChanges;
private InitialAssignments initialsPanel;
private Rules rulesPanel;
private String selectedReaction;
private ModelEditor modelEditor;
private Reaction complex = null;
private Reaction production = null;
private JComboBox SBOTerms = null;
private JTextField repCooperativity, actCooperativity, repBinding, actBinding;
public Reactions(BioModel gcm, Boolean paramsOnly, ArrayList<String> getParams, String file, ArrayList<String> parameterChanges,
ModelEditor gcmEditor) {
super(new BorderLayout());
this.bioModel = gcm;
this.paramsOnly = paramsOnly;
this.file = file;
this.parameterChanges = parameterChanges;
this.modelEditor = gcmEditor;
Model model = gcm.getSBMLDocument().getModel();
JPanel addReacs = new JPanel();
addReac = new JButton("Add Reaction");
removeReac = new JButton("Remove Reaction");
editReac = new JButton("Edit Reaction");
addReacs.add(addReac);
addReacs.add(removeReac);
addReacs.add(editReac);
addReac.addActionListener(this);
removeReac.addActionListener(this);
editReac.addActionListener(this);
if (paramsOnly) {
addReac.setEnabled(false);
removeReac.setEnabled(false);
}
JLabel reactionsLabel = new JLabel("List of Reactions:");
reactions = new JList();
reactions.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
JScrollPane scroll2 = new JScrollPane();
scroll2.setViewportView(reactions);
ListOf<Reaction> listOfReactions = model.getListOfReactions();
reacts = new String[model.getReactionCount()];
for (int i = 0; i < model.getReactionCount(); i++) {
Reaction reaction = listOfReactions.get(i);
reacts[i] = reaction.getId();
if (paramsOnly && reaction.getKineticLaw()!=null) {
ListOf<LocalParameter> params = reaction.getKineticLaw().getListOfLocalParameters();
for (int j = 0; j < reaction.getKineticLaw().getLocalParameterCount(); j++) {
LocalParameter paramet = (params.get(j));
for (int k = 0; k < getParams.size(); k++) {
if (getParams.get(k).split(" ")[0].equals(reaction.getId() + "/" + paramet.getId())) {
parameterChanges.add(getParams.get(k));
String[] splits = getParams.get(k).split(" ");
if (splits[splits.length - 2].equals("Modified") || splits[splits.length - 2].equals("Custom")) {
String value = splits[splits.length - 1];
paramet.setValue(Double.parseDouble(value));
}
else if (splits[splits.length - 2].equals("Sweep")) {
String value = splits[splits.length - 1];
paramet.setValue(Double.parseDouble(value.split(",")[0].substring(1).trim()));
}
if (!reacts[i].contains("Modified")) {
reacts[i] += " Modified";
}
}
}
}
}
}
Utility.sort(reacts);
reactions.setListData(reacts);
reactions.setSelectedIndex(0);
reactions.addMouseListener(this);
this.add(reactionsLabel, "North");
this.add(scroll2, "Center");
this.add(addReacs, "South");
}
/**
* Creates a frame used to edit reactions or create new ones.
*/
public void reactionsEditor(BioModel bioModel, String option, String reactionId, boolean inSchematic) {
/*
* if (option.equals("OK") && reactions.getSelectedIndex() == -1) {
* JOptionPane.showMessageDialog(Gui.frame, "No reaction selected.",
* "Must Select A Reaction", JOptionPane.ERROR_MESSAGE); return; }
*/
selectedReaction = reactionId;
JLabel id = new JLabel("ID:");
reacID = new JTextField(15);
JLabel name = new JLabel("Name:");
if (bioModel.getSBMLDocument().getLevel() < 3) {
reacName = new JTextField(50);
}
else {
reacName = new JTextField(30);
}
JLabel onPortLabel = new JLabel("Is Mapped to a Port:");
onPort = new JCheckBox();
JLabel reactionCompLabel = new JLabel("Compartment:");
ListOf<Compartment> listOfCompartments = bioModel.getSBMLDocument().getModel().getListOfCompartments();
String[] addC = new String[bioModel.getSBMLDocument().getModel().getCompartmentCount()];
for (int i = 0; i < bioModel.getSBMLDocument().getModel().getCompartmentCount(); i++) {
addC[i] = listOfCompartments.get(i).getId();
}
reactionComp = new JComboBox(addC);
reactionComp.addActionListener(this);
JLabel reverse = new JLabel("Reversible:");
String[] options = { "true", "false" };
reacReverse = new JComboBox(options);
reacReverse.setSelectedItem("false");
JLabel fast = new JLabel("Fast:");
reacFast = new JComboBox(options);
reacFast.setSelectedItem("false");
String selectedID = "";
Reaction copyReact = null;
JPanel param = new JPanel(new BorderLayout());
JPanel addParams = new JPanel();
reacAddParam = new JButton("Add Parameter");
reacRemoveParam = new JButton("Remove Parameter");
reacEditParam = new JButton("Edit Parameter");
addParams.add(reacAddParam);
addParams.add(reacRemoveParam);
addParams.add(reacEditParam);
reacAddParam.addActionListener(this);
reacRemoveParam.addActionListener(this);
reacEditParam.addActionListener(this);
JLabel parametersLabel = new JLabel("List Of Local Parameters:");
reacParameters = new JList();
reacParameters.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
JScrollPane scroll = new JScrollPane();
scroll.setMinimumSize(new Dimension(260, 220));
scroll.setPreferredSize(new Dimension(276, 152));
scroll.setViewportView(reacParameters);
reacParams = new String[0];
changedParameters = new ArrayList<LocalParameter>();
thisReactionParams = new ArrayList<String>();
if (option.equals("OK")) {
Reaction reac = bioModel.getSBMLDocument().getModel().getReaction(reactionId);
if (reac.getKineticLaw()!=null) {
//reac.createKineticLaw();
ListOf<LocalParameter> listOfParameters = reac.getKineticLaw().getListOfLocalParameters();
reacParams = new String[reac.getKineticLaw().getLocalParameterCount()];
for (int i = 0; i < reac.getKineticLaw().getLocalParameterCount(); i++) {
/*
* This code is a hack to get around a local parameter
* conversion bug in libsbml
*/
LocalParameter pp = listOfParameters.get(i);
LocalParameter parameter = new LocalParameter(bioModel.getSBMLDocument().getLevel(), bioModel.getSBMLDocument().getVersion());
parameter.setId(pp.getId());
SBMLutilities.setMetaId(parameter, pp.getMetaId());
parameter.setName(pp.getName());
parameter.setValue(pp.getValue());
parameter.setUnits(pp.getUnits());
changedParameters.add(parameter);
thisReactionParams.add(parameter.getId());
String p;
if (parameter.isSetUnits()) {
p = parameter.getId() + " " + parameter.getValue() + " " + parameter.getUnits();
}
else {
p = parameter.getId() + " " + parameter.getValue();
}
if (paramsOnly) {
for (int j = 0; j < parameterChanges.size(); j++) {
if (parameterChanges.get(j).split(" ")[0].equals(selectedReaction + "/" + parameter.getId())) {
p = parameterChanges.get(j).split("/")[1];
}
}
}
reacParams[i] = p;
}
}
}
else {
// Parameter p = new Parameter(BioSim.SBML_LEVEL,
// BioSim.SBML_VERSION);
LocalParameter p = new LocalParameter(bioModel.getSBMLDocument().getLevel(), bioModel.getSBMLDocument().getVersion());
p.setId("kf");
p.setValue(0.1);
changedParameters.add(p);
// p = new Parameter(BioSim.SBML_LEVEL, BioSim.SBML_VERSION);
p = new LocalParameter(bioModel.getSBMLDocument().getLevel(), bioModel.getSBMLDocument().getVersion());
p.setId("kr");
p.setValue(1.0);
changedParameters.add(p);
reacParams = new String[2];
reacParams[0] = "kf 0.1";
reacParams[1] = "kr 1.0";
thisReactionParams.add("kf");
thisReactionParams.add("kr");
}
Utility.sort(reacParams);
reacParameters.setListData(reacParams);
reacParameters.setSelectedIndex(0);
reacParameters.addMouseListener(this);
param.add(parametersLabel, "North");
param.add(scroll, "Center");
param.add(addParams, "South");
JPanel reactantsPanel = new JPanel(new BorderLayout());
JPanel addReactants = new JPanel();
addReactant = new JButton("Add Reactant");
removeReactant = new JButton("Remove Reactant");
editReactant = new JButton("Edit Reactant");
addReactants.add(addReactant);
addReactants.add(removeReactant);
addReactants.add(editReactant);
addReactant.addActionListener(this);
removeReactant.addActionListener(this);
editReactant.addActionListener(this);
JLabel reactantsLabel = new JLabel("List Of Reactants:");
reactants = new JList();
reactants.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
JScrollPane scroll2 = new JScrollPane();
scroll2.setMinimumSize(new Dimension(260, 220));
scroll2.setPreferredSize(new Dimension(276, 152));
scroll2.setViewportView(reactants);
reacta = new String[0];
changedReactants = new ArrayList<SpeciesReference>();
if (option.equals("OK")) {
Reaction reac = bioModel.getSBMLDocument().getModel().getReaction(reactionId);
ListOf<SpeciesReference> listOfReactants = reac.getListOfReactants();
reacta = new String[reac.getReactantCount()];
for (int i = 0; i < reac.getReactantCount(); i++) {
SpeciesReference reactant = listOfReactants.get(i);
changedReactants.add(reactant);
reacta[i] = reactant.getSpecies() + " " + reactant.getStoichiometry();
}
}
Utility.sort(reacta);
reactants.setListData(reacta);
reactants.setSelectedIndex(0);
reactants.addMouseListener(this);
reactantsPanel.add(reactantsLabel, "North");
reactantsPanel.add(scroll2, "Center");
reactantsPanel.add(addReactants, "South");
JPanel productsPanel = new JPanel(new BorderLayout());
JPanel addProducts = new JPanel();
addProduct = new JButton("Add Product");
removeProduct = new JButton("Remove Product");
editProduct = new JButton("Edit Product");
addProducts.add(addProduct);
addProducts.add(removeProduct);
addProducts.add(editProduct);
addProduct.addActionListener(this);
removeProduct.addActionListener(this);
editProduct.addActionListener(this);
JLabel productsLabel = new JLabel("List Of Products:");
products = new JList();
products.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
JScrollPane scroll3 = new JScrollPane();
scroll3.setMinimumSize(new Dimension(260, 220));
scroll3.setPreferredSize(new Dimension(276, 152));
scroll3.setViewportView(products);
proda = new String[0];
changedProducts = new ArrayList<SpeciesReference>();
if (option.equals("OK")) {
Reaction reac = bioModel.getSBMLDocument().getModel().getReaction(reactionId);
ListOf<SpeciesReference> listOfProducts = reac.getListOfProducts();
proda = new String[reac.getProductCount()];
for (int i = 0; i < reac.getProductCount(); i++) {
SpeciesReference product = listOfProducts.get(i);
changedProducts.add(product);
this.proda[i] = product.getSpecies() + " " + product.getStoichiometry();
}
}
Utility.sort(proda);
products.setListData(proda);
products.setSelectedIndex(0);
products.addMouseListener(this);
productsPanel.add(productsLabel, "North");
productsPanel.add(scroll3, "Center");
productsPanel.add(addProducts, "South");
JPanel modifierPanel = new JPanel(new BorderLayout());
JPanel addModifiers = new JPanel();
addModifier = new JButton("Add Modifier");
removeModifier = new JButton("Remove Modifier");
editModifier = new JButton("Edit Modifier");
addModifiers.add(addModifier);
addModifiers.add(removeModifier);
addModifiers.add(editModifier);
addModifier.addActionListener(this);
removeModifier.addActionListener(this);
editModifier.addActionListener(this);
JLabel modifiersLabel = new JLabel("List Of Modifiers:");
modifiers = new JList();
modifiers.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
JScrollPane scroll5 = new JScrollPane();
scroll5.setMinimumSize(new Dimension(260, 220));
scroll5.setPreferredSize(new Dimension(276, 152));
scroll5.setViewportView(modifiers);
modifierArray = new String[0];
changedModifiers = new ArrayList<ModifierSpeciesReference>();
if (option.equals("OK")) {
Reaction reac = bioModel.getSBMLDocument().getModel().getReaction(reactionId);
ListOf<ModifierSpeciesReference> listOfModifiers = reac.getListOfModifiers();
modifierArray = new String[reac.getModifierCount()];
for (int i = 0; i < reac.getModifierCount(); i++) {
ModifierSpeciesReference modifier = listOfModifiers.get(i);
changedModifiers.add(modifier);
this.modifierArray[i] = modifier.getSpecies();
}
}
Utility.sort(modifierArray);
modifiers.setListData(modifierArray);
modifiers.setSelectedIndex(0);
modifiers.addMouseListener(this);
modifierPanel.add(modifiersLabel, "North");
modifierPanel.add(scroll5, "Center");
modifierPanel.add(addModifiers, "South");
JComboBox kineticFluxLabel = new JComboBox(new String[] {"Kinetic Law:","Flux Bounds:"});
kineticLaw = new JTextArea();
kineticLaw.setLineWrap(true);
kineticLaw.setWrapStyleWord(true);
useMassAction = new JButton("Use Mass Action");
clearKineticLaw = new JButton("Clear");
useMassAction.addActionListener(this);
clearKineticLaw.addActionListener(this);
JPanel kineticButtons = new JPanel();
kineticButtons.add(useMassAction);
kineticButtons.add(clearKineticLaw);
JScrollPane scroll4 = new JScrollPane();
scroll4.setMinimumSize(new Dimension(100, 100));
scroll4.setPreferredSize(new Dimension(100, 100));
scroll4.setViewportView(kineticLaw);
if (option.equals("OK")) {
if (bioModel.getSBMLDocument().getModel().getReaction(reactionId).getKineticLaw()!=null) {
kineticFluxLabel.setSelectedIndex(0);
kineticLaw.setText(bioModel.removeBooleans(bioModel.getSBMLDocument().getModel().getReaction(reactionId).getKineticLaw().getMath()));
} else {
kineticFluxLabel.setSelectedIndex(1);
String fluxbounds = "";
for(int i = 0; i < bioModel.getSBMLFBC().getListOfFluxBounds().size(); i++){
if(bioModel.getSBMLFBC().getListOfFluxBounds().get(i).getReaction().equals(reactionId)){
if(bioModel.getSBMLFBC().getListOfFluxBounds().get(i).getOperation().toString().equals("greaterEqual")){
fluxbounds = bioModel.getSBMLFBC().getListOfFluxBounds().get(i).getValue() + "<=" + fluxbounds;
if(!fluxbounds.contains(reactionId)){
fluxbounds += reactionId;
}
}
if(bioModel.getSBMLFBC().getListOfFluxBounds().get(i).getOperation().toString().equals("lessEqual")){
fluxbounds += "<=" + bioModel.getSBMLFBC().getListOfFluxBounds().get(i).getValue();
if(!fluxbounds.contains(reactionId)){
fluxbounds = reactionId + fluxbounds;
}
}
if(bioModel.getSBMLFBC().getListOfFluxBounds().get(i).getOperation().toString().equals("equal")){
double value = bioModel.getSBMLFBC().getListOfFluxBounds().get(i).getValue();
fluxbounds = value + "<=" + reactionId + "<=" + value;
}
}
}
kineticLaw.setText(fluxbounds);
}
}
JPanel kineticPanel = new JPanel(new BorderLayout());
kineticPanel.add(kineticFluxLabel, "North");
kineticPanel.add(scroll4, "Center");
kineticPanel.add(kineticButtons, "South");
JPanel reactionPanel = new JPanel(new BorderLayout());
JPanel reactionPanelNorth = new JPanel();
reactionPanelNorth.setLayout(new GridLayout(3, 1));
JPanel reactionPanelNorth1 = new JPanel();
JPanel reactionPanelNorth3 = new JPanel();
JPanel reactionPanelNorth4 = new JPanel();
CiIndex = new JTextField(20);
reactionPanelNorth1.add(id);
reactionPanelNorth1.add(reacID);
reactionPanelNorth1.add(name);
reactionPanelNorth1.add(reacName);
reactionPanelNorth1.add(onPortLabel);
reactionPanelNorth1.add(onPort);
reactionPanelNorth3.add(reactionCompLabel);
reactionPanelNorth3.add(reactionComp);
reactionPanelNorth3.add(new JLabel("Compartment Indices:"));
reactionPanelNorth3.add(CiIndex);
reactionPanelNorth4.add(reverse);
reactionPanelNorth4.add(reacReverse);
reactionPanelNorth4.add(fast);
reactionPanelNorth4.add(reacFast);
// Parse out SBOL annotations and add to SBOL field
if (!paramsOnly) {
// Field for annotating reaction with SBOL DNA components
List<URI> sbolURIs = new LinkedList<URI>();
String sbolStrand = "";
if (option.equals("OK")) {
Reaction reac = bioModel.getSBMLDocument().getModel().getReaction(reactionId);
sbolStrand = AnnotationUtility.parseSBOLAnnotation(reac, sbolURIs);
}
sbolField = new SBOLField(sbolURIs, sbolStrand, GlobalConstants.SBOL_DNA_COMPONENT, modelEditor, 2, false);
reactionPanelNorth4.add(sbolField);
}
reactionPanelNorth.add(reactionPanelNorth1);
reactionPanelNorth.add(reactionPanelNorth3);
reactionPanelNorth.add(reactionPanelNorth4);
if (inSchematic) {
reactionPanel.add(reactionPanelNorth, "North");
reactionPanel.add(param, "Center");
reactionPanel.add(kineticPanel, "South");
}
else {
JPanel reactionPanelCentral = new JPanel(new GridLayout(1, 3));
JPanel reactionPanelSouth = new JPanel(new GridLayout(1, 2));
reactionPanelCentral.add(reactantsPanel);
reactionPanelCentral.add(productsPanel);
reactionPanelCentral.add(modifierPanel);
reactionPanelSouth.add(param);
reactionPanelSouth.add(kineticPanel);
reactionPanel.add(reactionPanelNorth, "North");
reactionPanel.add(reactionPanelCentral, "Center");
reactionPanel.add(reactionPanelSouth, "South");
}
if (option.equals("OK")) {
Reaction reac = bioModel.getSBMLDocument().getModel().getReaction(reactionId);
copyReact = reac.clone();
ArraysSBasePlugin sBasePlugin = SBMLutilities.getArraysSBasePlugin(reac);
String dimInID = "";
for(int i = sBasePlugin.getDimensionCount()-1; i>=0; i
org.sbml.jsbml.ext.arrays.Dimension dimX = sBasePlugin.getDimensionByArrayDimension(i);
dimInID += "[" + dimX.getSize() + "]";
}
String freshIndex = "";
for(int i = sBasePlugin.getIndexCount()-1; i>=0; i
Index indie = sBasePlugin.getIndex(i);
freshIndex += "[" + SBMLutilities.myFormulaToString(indie.getMath()) + "]";
}
CiIndex.setText(freshIndex);
reacID.setText(reac.getId()+dimInID);
selectedID = reac.getId();
reacName.setText(reac.getName());
if (bioModel.getPortByIdRef(reac.getId())!=null) {
onPort.setSelected(true);
} else {
onPort.setSelected(false);
}
if (reac.getReversible()) {
reacReverse.setSelectedItem("true");
}
else {
reacReverse.setSelectedItem("false");
}
if (reac.getFast()) {
reacFast.setSelectedItem("true");
}
else {
reacFast.setSelectedItem("false");
}
if (bioModel.getSBMLDocument().getLevel() > 2) {
reactionComp.setSelectedItem(reac.getCompartment());
}
complex = null;
production = null;
if (reac.isSetSBOTerm()) {
if (BioModel.isComplexReaction(reac)) {
complex = reac;
reacID.setEnabled(false);
reacName.setEnabled(false);
onPort.setEnabled(false);
reacReverse.setEnabled(false);
reacFast.setEnabled(false);
reactionComp.setEnabled(false);
reacAddParam.setEnabled(false);
reacRemoveParam.setEnabled(false);
reacEditParam.setEnabled(false);
addProduct.setEnabled(false);
removeProduct.setEnabled(false);
editProduct.setEnabled(false);
products.removeMouseListener(this);
addModifier.setEnabled(false);
removeModifier.setEnabled(false);
editModifier.setEnabled(false);
modifiers.removeMouseListener(this);
kineticLaw.setEditable(false);
clearKineticLaw.setEnabled(false);
reacParameters.setEnabled(false);
useMassAction.setEnabled(false);
} else if (BioModel.isConstitutiveReaction(reac) || BioModel.isDegradationReaction(reac) ||
BioModel.isDiffusionReaction(reac)) {
reacID.setEnabled(false);
reacName.setEnabled(false);
onPort.setEnabled(false);
reacReverse.setEnabled(false);
reacFast.setEnabled(false);
reactionComp.setEnabled(false);
reacAddParam.setEnabled(false);
reacRemoveParam.setEnabled(false);
reacEditParam.setEnabled(false);
addReactant.setEnabled(false);
removeReactant.setEnabled(false);
editReactant.setEnabled(false);
reactants.removeMouseListener(this);
addProduct.setEnabled(false);
removeProduct.setEnabled(false);
editProduct.setEnabled(false);
products.removeMouseListener(this);
addModifier.setEnabled(false);
removeModifier.setEnabled(false);
editModifier.setEnabled(false);
modifiers.removeMouseListener(this);
kineticLaw.setEditable(false);
useMassAction.setEnabled(false);
clearKineticLaw.setEnabled(false);
reacParameters.setEnabled(false);
} else if (BioModel.isProductionReaction(reac)) {
production = reac;
reacID.setEnabled(false);
reacName.setEnabled(false);
onPort.setEnabled(false);
reacReverse.setEnabled(false);
reacFast.setEnabled(false);
reactionComp.setEnabled(false);
reacAddParam.setEnabled(false);
reacRemoveParam.setEnabled(false);
reacEditParam.setEnabled(false);
addReactant.setEnabled(false);
removeReactant.setEnabled(false);
editReactant.setEnabled(false);
reactants.removeMouseListener(this);
kineticLaw.setEditable(false);
clearKineticLaw.setEnabled(false);
reacParameters.setEnabled(false);
useMassAction.setEnabled(false);
}
}
}
else {
String NEWreactionId = "r0";
int i = 0;
while (bioModel.isSIdInUse(NEWreactionId)) {
i++;
NEWreactionId = "r" + i;
}
Reaction reac = bioModel.getSBMLDocument().getModel().getReaction(reactionId);
ArraysSBasePlugin sBasePlugin = SBMLutilities.getArraysSBasePlugin(reac);
String dimInID = "";
for(int i1 = 0; i1<sBasePlugin.getDimensionCount(); i1++){
org.sbml.jsbml.ext.arrays.Dimension dimX = sBasePlugin.getDimensionByArrayDimension(i1);
dimInID += "[" + dimX.getSize() + "]";
}
reacID.setText(NEWreactionId+dimInID);
}
if (paramsOnly) {
reacID.setEditable(false);
reacName.setEditable(false);
reacReverse.setEnabled(false);
reacFast.setEnabled(false);
reacAddParam.setEnabled(false);
reacRemoveParam.setEnabled(false);
addReactant.setEnabled(false);
removeReactant.setEnabled(false);
editReactant.setEnabled(false);
addProduct.setEnabled(false);
removeProduct.setEnabled(false);
editProduct.setEnabled(false);
addModifier.setEnabled(false);
removeModifier.setEnabled(false);
editModifier.setEnabled(false);
kineticLaw.setEditable(false);
useMassAction.setEnabled(false);
clearKineticLaw.setEnabled(false);
reactionComp.setEnabled(false);
onPort.setEnabled(false);
}
Object[] options1 = { option, "Cancel" };
int value = JOptionPane.showOptionDialog(Gui.frame, reactionPanel, "Reaction Editor", JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE,
null, options1, options1[0]);
String[] dimID = new String[]{""};
String[] dex = new String[]{""};
String[] dimensionIds = new String[]{""};
boolean error = true;
while (error && value == JOptionPane.YES_OPTION) {
error = false;
dimID = SBMLutilities.checkSizeParameters(bioModel.getSBMLDocument(), reacID.getText(), false);
if(dimID!=null){
dimensionIds = SBMLutilities.getDimensionIds("",dimID.length-1);
error = SBMLutilities.checkID(bioModel.getSBMLDocument(), dimID[0].trim(), reactionId.trim(), false);
}
else{
error = true;
}
if(reactionComp.isEnabled() && !error){
SBase variable = SBMLutilities.getElementBySId(bioModel.getSBMLDocument(), (String)reactionComp.getSelectedItem());
dex = SBMLutilities.checkIndices(CiIndex.getText().trim(), variable, bioModel.getSBMLDocument(), dimensionIds, "compartment", dimID);
error = (dex==null);
}
if (!error) {
if (complex==null && production==null && kineticLaw.getText().trim().equals("")) {
JOptionPane.showMessageDialog(Gui.frame, "A reaction must have a kinetic law.", "Enter A Kinetic Law", JOptionPane.ERROR_MESSAGE);
error = true;
}
else if ((changedReactants.size() == 0) && (changedProducts.size() == 0)) {
JOptionPane.showMessageDialog(Gui.frame, "A reaction must have at least one reactant or product.", "No Reactants or Products",
JOptionPane.ERROR_MESSAGE);
error = true;
}
else if(kineticFluxLabel.getSelectedItem().equals("Kinetic Law:")){
if (complex==null && production==null && SBMLutilities.myParseFormula(kineticLaw.getText().trim()) == null) {
JOptionPane.showMessageDialog(Gui.frame, "Unable to parse kinetic law.", "Kinetic Law Error", JOptionPane.ERROR_MESSAGE);
error = true;
}
else if (complex==null && production==null){
ArrayList<String> invalidKineticVars = getInvalidVariablesInReaction(kineticLaw.getText().trim(), dimensionIds, true, "", false);
if (invalidKineticVars.size() > 0) {
String invalid = "";
for (int i = 0; i < invalidKineticVars.size(); i++) {
if (i == invalidKineticVars.size() - 1) {
invalid += invalidKineticVars.get(i);
}
else {
invalid += invalidKineticVars.get(i) + "\n";
}
}
String message;
message = "Kinetic law contains unknown variables.\n\n" + "Unknown variables:\n" + invalid;
JTextArea messageArea = new JTextArea(message);
messageArea.setLineWrap(true);
messageArea.setWrapStyleWord(true);
messageArea.setEditable(false);
JScrollPane scrolls = new JScrollPane();
scrolls.setMinimumSize(new Dimension(300, 300));
scrolls.setPreferredSize(new Dimension(300, 300));
scrolls.setViewportView(messageArea);
JOptionPane.showMessageDialog(Gui.frame, scrolls, "Kinetic Law Error", JOptionPane.ERROR_MESSAGE);
error = true;
}
if (!error) {
error = SBMLutilities.checkNumFunctionArguments(bioModel.getSBMLDocument(), SBMLutilities.myParseFormula(kineticLaw.getText().trim()));
}
}
else {
error = !fluxBoundisGood(kineticLaw.getText().replaceAll("\\s",""), reactionId);
}
}
}
if(kineticFluxLabel.getSelectedItem().equals("Kinetic Law:")){
if (!error && complex==null && production==null) {
if (SBMLutilities.returnsBoolean(bioModel.addBooleans(kineticLaw.getText().trim()), bioModel.getSBMLDocument().getModel())) {
JOptionPane.showMessageDialog(Gui.frame, "Kinetic law must evaluate to a number.", "Number Expected", JOptionPane.ERROR_MESSAGE);
error = true;
}
}
}
if (!error) {
if (option.equals("OK")) {
int index = reactions.getSelectedIndex();
String val = reactionId;
Reaction react = bioModel.getSBMLDocument().getModel().getReaction(val);
ListOf remove;
long size;
if (react.getKineticLaw()==null) {
react.createKineticLaw();
}
remove = react.getKineticLaw().getListOfLocalParameters();
size = react.getKineticLaw().getLocalParameterCount();
for (int i = 0; i < size; i++) {
remove.remove(0);
}
for (int i = 0; i < changedParameters.size(); i++) {
react.getKineticLaw().addLocalParameter(changedParameters.get(i));
}
remove = react.getListOfProducts();
size = react.getProductCount();
for (int i = 0; i < size; i++) {
remove.remove(0);
}
for (int i = 0; i < changedProducts.size(); i++) {
react.addProduct(changedProducts.get(i));
}
remove = react.getListOfModifiers();
size = react.getModifierCount();
for (int i = 0; i < size; i++) {
remove.remove(0);
}
for (int i = 0; i < changedModifiers.size(); i++) {
react.addModifier(changedModifiers.get(i));
}
remove = react.getListOfReactants();
size = react.getReactantCount();
for (int i = 0; i < size; i++) {
remove.remove(0);
}
for (int i = 0; i < changedReactants.size(); i++) {
react.addReactant(changedReactants.get(i));
}
if (reacReverse.getSelectedItem().equals("true")) {
react.setReversible(true);
}
else {
react.setReversible(false);
}
if (bioModel.getSBMLDocument().getLevel() > 2) {
react.setCompartment((String) reactionComp.getSelectedItem());
}
if (reacFast.getSelectedItem().equals("true")) {
react.setFast(true);
}
else {
react.setFast(false);
}
react.setId(dimID[0].trim());
react.setName(reacName.getText().trim());
Port port = bioModel.getPortByIdRef(val);
if (port!=null) {
if (onPort.isSelected()) {
port.setId(GlobalConstants.SBMLREACTION+"__"+react.getId());
port.setIdRef(react.getId());
} else {
bioModel.getSBMLCompModel().removePort(port);
}
} else {
if (onPort.isSelected()) {
port = bioModel.getSBMLCompModel().createPort();
port.setId(GlobalConstants.SBMLREACTION+"__"+react.getId());
port.setIdRef(react.getId());
}
}
if(kineticFluxLabel.getSelectedItem().equals("Kinetic Law:")){
if (complex==null && production==null) {
react.getKineticLaw().setMath(bioModel.addBooleans(kineticLaw.getText().trim()));
} else if (complex!=null) {
react.getKineticLaw().setMath(SBMLutilities.myParseFormula(BioModel.createComplexKineticLaw(complex)));
} else {
react.getKineticLaw().setMath(SBMLutilities.myParseFormula(BioModel.createProductionKineticLaw(production)));
}
error = checkKineticLawUnits(react.getKineticLaw());
int i = 0;
while (i < bioModel.getSBMLFBC().getListOfFluxBounds().size()) {
if(bioModel.getSBMLFBC().getListOfFluxBounds().get(i).getReaction().equals(reactionId)){
bioModel.getSBMLFBC().removeFluxBound(i);
} else {
i++;
}
}
}
else{
react.unsetKineticLaw();
int i = 0;
while(i < bioModel.getSBMLFBC().getListOfFluxBounds().size()){
if(bioModel.getSBMLFBC().getListOfFluxBounds().get(i).getReaction().equals(reactionId)){
bioModel.getSBMLFBC().removeFluxBound(i);
} else {
i++;
}
}
if(kineticLaw.getText().contains("<=")){
String[] userInput = kineticLaw.getText().replaceAll("\\s","").split("<=");
if (userInput.length==3) {
double greaterValue = Double.parseDouble(userInput[0]);
FluxBound fxGreater = bioModel.getSBMLFBC().createFluxBound();
fxGreater.setOperation(FluxBound.Operation.GREATER_EQUAL);
fxGreater.setValue(greaterValue);
fxGreater.setReaction(reactionId);
double lessValue = Double.parseDouble(userInput[2]);
FluxBound fxLess = bioModel.getSBMLFBC().createFluxBound();
fxLess.setOperation(FluxBound.Operation.LESS_EQUAL);
fxLess.setValue(lessValue);
fxLess.setReaction(reactionId);
}
else {
try{
double lessValue = Double.parseDouble(userInput[1]);
FluxBound fxLess = bioModel.getSBMLFBC().createFluxBound();
fxLess.setOperation(FluxBound.Operation.LESS_EQUAL);
fxLess.setValue(lessValue);
fxLess.setReaction(reactionId);
}
catch(Exception e){
double greaterValue = Double.parseDouble(userInput[0]);
FluxBound fxGreater = bioModel.getSBMLFBC().createFluxBound();
fxGreater.setOperation(FluxBound.Operation.GREATER_EQUAL);
fxGreater.setValue(greaterValue);
fxGreater.setReaction(reactionId);
}
}
}
else if(kineticLaw.getText().contains(">=")){
String[] userInput = kineticLaw.getText().replaceAll("\\s","").split(">=");
if (userInput.length==3) {
double greaterValue = Double.parseDouble(userInput[2]);
FluxBound fxGreater = bioModel.getSBMLFBC().createFluxBound();
fxGreater.setOperation(FluxBound.Operation.GREATER_EQUAL);
fxGreater.setValue(greaterValue);
fxGreater.setReaction(reactionId);
double lessValue = Double.parseDouble(userInput[0]);
FluxBound fxLess = bioModel.getSBMLFBC().createFluxBound();
fxLess.setOperation(FluxBound.Operation.LESS_EQUAL);
fxLess.setValue(lessValue);
fxLess.setReaction(reactionId);
} else {
try{
double greaterValue = Double.parseDouble(userInput[1]);
FluxBound fxGreater = bioModel.getSBMLFBC().createFluxBound();
fxGreater.setOperation(FluxBound.Operation.GREATER_EQUAL);
fxGreater.setValue(greaterValue);
fxGreater.setReaction(reactionId);
}
catch(Exception e){
double lessValue = Double.parseDouble(userInput[0]);
FluxBound fxLess = bioModel.getSBMLFBC().createFluxBound();
fxLess.setOperation(FluxBound.Operation.LESS_EQUAL);
fxLess.setValue(lessValue);
fxLess.setReaction(reactionId);
}
}
}
else{
String[] userInput = kineticLaw.getText().replaceAll("\\s","").split("=");
FluxBound fxEqual = bioModel.getSBMLFBC().createFluxBound();
fxEqual.setOperation(FluxBound.Operation.EQUAL);
fxEqual.setReaction(reactionId);
if(userInput[0].equals(reactionId)){
fxEqual.setValue(Double.parseDouble(userInput[1]));
}
else{
fxEqual.setValue(Double.parseDouble(userInput[0]));
}
}
}
if (!error) {
error = SBMLutilities.checkCycles(bioModel.getSBMLDocument());
if (error) {
JOptionPane.showMessageDialog(Gui.frame, "Cycle detected within initial assignments, assignment rules, and rate laws.",
"Cycle Detected", JOptionPane.ERROR_MESSAGE);
}
}
if (!error) {
if (index >= 0) {
if (!paramsOnly) {
reacts[index] = dimID[0];
}
reactions.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
reacts = Utility.getList(reacts, reactions);
reactions.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
Utility.sort(reacts);
reactions.setListData(reacts);
reactions.setSelectedIndex(index);
}
}
else {
changedParameters = new ArrayList<LocalParameter>();
ListOf<LocalParameter> listOfParameters = react.getKineticLaw().getListOfLocalParameters();
for (int i = 0; i < react.getKineticLaw().getLocalParameterCount(); i++) {
LocalParameter parameter = listOfParameters.get(i);
changedParameters.add(new LocalParameter(parameter));
}
changedProducts = new ArrayList<SpeciesReference>();
ListOf<SpeciesReference> listOfProducts = react.getListOfProducts();
for (int i = 0; i < react.getProductCount(); i++) {
SpeciesReference product = listOfProducts.get(i);
changedProducts.add(product);
}
changedReactants = new ArrayList<SpeciesReference>();
ListOf<SpeciesReference> listOfReactants = react.getListOfReactants();
for (int i = 0; i < react.getReactantCount(); i++) {
SpeciesReference reactant = listOfReactants.get(i);
changedReactants.add(reactant);
}
changedModifiers = new ArrayList<ModifierSpeciesReference>();
ListOf<ModifierSpeciesReference> listOfModifiers = react.getListOfModifiers();
for (int i = 0; i < react.getModifierCount(); i++) {
ModifierSpeciesReference modifier = listOfModifiers.get(i);
changedModifiers.add(modifier);
}
}
// Handle SBOL data
if (!error && inSchematic && !paramsOnly) {
if (!error) {
// Add SBOL annotation to reaction
if (sbolField.getSBOLURIs().size() > 0) {
SBOLAnnotation sbolAnnot = new SBOLAnnotation(react.getMetaId(), sbolField.getSBOLURIs(),
sbolField.getSBOLStrand());
AnnotationUtility.setSBOLAnnotation(react, sbolAnnot);
} else
AnnotationUtility.removeSBOLAnnotation(react);
}
}
// TODO: Scott - change for Plugin writing
if(!error){
ArraysSBasePlugin sBasePlugin = SBMLutilities.getArraysSBasePlugin(react);
sBasePlugin.unsetListOfDimensions();
for(int i = 0; i<dimID.length-1; i++){
org.sbml.jsbml.ext.arrays.Dimension dimX = sBasePlugin.createDimension(dimensionIds[i]);
dimX.setSize(dimID[i+1]);
dimX.setArrayDimension(i);
}
// Add the indices
sBasePlugin.unsetListOfIndices();
for(int i = 0; i<dex.length-1; i++){
Index indexRule = new Index();
indexRule.setArrayDimension(i);
indexRule.setReferencedAttribute("variable");
ASTNode indexMath = SBMLutilities.myParseFormula(dex[i+1]);
indexRule.setMath(indexMath);
sBasePlugin.addIndex(indexRule);
}
}
}
else {
Reaction react = bioModel.getSBMLDocument().getModel().createReaction();
int index = reactions.getSelectedIndex();
if(kineticFluxLabel.getSelectedItem().equals("Kinetic Law:")){
react.createKineticLaw();
for (int i = 0; i < changedParameters.size(); i++) {
react.getKineticLaw().addLocalParameter(changedParameters.get(i));
}
}
for (int i = 0; i < changedProducts.size(); i++) {
react.addProduct(changedProducts.get(i));
}
for (int i = 0; i < changedModifiers.size(); i++) {
react.addModifier(changedModifiers.get(i));
}
for (int i = 0; i < changedReactants.size(); i++) {
react.addReactant(changedReactants.get(i));
}
if (reacReverse.getSelectedItem().equals("true")) {
react.setReversible(true);
}
else {
react.setReversible(false);
}
if (reacFast.getSelectedItem().equals("true")) {
react.setFast(true);
}
else {
react.setFast(false);
}
if (bioModel.getSBMLDocument().getLevel() > 2) {
react.setCompartment((String) reactionComp.getSelectedItem());
}
react.setId(dimID[0]);
react.setName(reacName.getText().trim());
if (onPort.isSelected()) {
Port port = bioModel.getSBMLCompModel().createPort();
port.setId(GlobalConstants.SBMLREACTION+"__"+react.getId());
port.setIdRef(react.getId());
}
if(kineticFluxLabel.getSelectedItem().equals("Kinetic Law:")){
if (complex==null && production==null) {
react.getKineticLaw().setMath(bioModel.addBooleans(kineticLaw.getText().trim()));
} else if (complex!=null) {
react.getKineticLaw().setMath(SBMLutilities.myParseFormula(BioModel.createComplexKineticLaw(complex)));
} else {
react.getKineticLaw().setMath(SBMLutilities.myParseFormula(BioModel.createProductionKineticLaw(production)));
}
error = checkKineticLawUnits(react.getKineticLaw());
}
else{
error = !fluxBoundisGood(kineticLaw.getText().replaceAll("\\s",""), reactionId);
}
if (!error) {
error = SBMLutilities.checkCycles(bioModel.getSBMLDocument());
if (error) {
JOptionPane.showMessageDialog(Gui.frame, "Cycle detected within initial assignments, assignment rules, and rate laws.",
"Cycle Detected", JOptionPane.ERROR_MESSAGE);
}
}
if (!error) {
JList add = new JList();
Object[] adding = { dimID[0] };
add.setListData(adding);
add.setSelectedIndex(0);
reactions.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
adding = Utility.add(reacts, reactions, add);
reacts = new String[adding.length];
for (int i = 0; i < adding.length; i++) {
reacts[i] = (String) adding[i];
}
Utility.sort(reacts);
reactions.setListData(reacts);
reactions.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
if (bioModel.getSBMLDocument().getModel().getReactionCount() == 1) {
reactions.setSelectedIndex(0);
}
else {
reactions.setSelectedIndex(index);
}
}
else {
removeTheReaction(bioModel, dimID[0]);
}
// TODO: Scott - change for Plugin writing
if(!error){
ArraysSBasePlugin sBasePlugin = SBMLutilities.getArraysSBasePlugin(react);
sBasePlugin.unsetListOfDimensions();
for(int i = 0; i<dimID.length-1; i++){
org.sbml.jsbml.ext.arrays.Dimension dimX = sBasePlugin.createDimension(dimensionIds[i]);
dimX.setSize(dimID[i+1]);
dimX.setArrayDimension(i);
}
// Add the indices
sBasePlugin.unsetListOfIndices();
for(int i = 0; i<dex.length-1; i++){
Index indexRule = new Index();
indexRule.setArrayDimension(i);
indexRule.setReferencedAttribute("variable");
ASTNode indexMath = SBMLutilities.myParseFormula(dex[i+1]);
indexRule.setMath(indexMath);
sBasePlugin.addIndex(indexRule);
}
}
}
modelEditor.setDirty(true);
bioModel.makeUndoPoint();
}
if (error) {
value = JOptionPane.showOptionDialog(Gui.frame, reactionPanel, "Reaction Editor", JOptionPane.YES_NO_OPTION,
JOptionPane.PLAIN_MESSAGE, null, options1, options1[0]);
}
}
if (value == JOptionPane.NO_OPTION) {
if (option.equals("OK")) {
String reactId = reactionId;
removeTheReaction(bioModel, reactId);
bioModel.getSBMLDocument().getModel().addReaction(copyReact);
}
return;
}
}
/**
* Find invalid reaction variables in a formula
*/
private ArrayList<String> getInvalidVariablesInReaction(String formula, String[] dimensionIds, boolean isReaction, String arguments, boolean isFunction) {
ArrayList<String> validVars = new ArrayList<String>();
ArrayList<String> invalidVars = new ArrayList<String>();
Model model = bioModel.getSBMLDocument().getModel();
for (int i = 0; i < bioModel.getSBMLDocument().getModel().getFunctionDefinitionCount(); i++) {
validVars.add(model.getFunctionDefinition(i).getId());
}
if (isReaction) {
for (int i = 0; i < changedParameters.size(); i++) {
validVars.add(changedParameters.get(i).getId());
}
for (int i = 0; i < changedReactants.size(); i++) {
validVars.add(changedReactants.get(i).getSpecies());
validVars.add(changedReactants.get(i).getId());
}
for (int i = 0; i < changedProducts.size(); i++) {
validVars.add(changedProducts.get(i).getSpecies());
validVars.add(changedProducts.get(i).getId());
}
for (int i = 0; i < changedModifiers.size(); i++) {
validVars.add(changedModifiers.get(i).getSpecies());
}
if (dimensionIds != null) {
for (int i = 0; i < dimensionIds.length; i++) {
validVars.add(dimensionIds[i]);
}
}
}
else if (!isFunction) {
for (int i = 0; i < bioModel.getSBMLDocument().getModel().getSpeciesCount(); i++) {
validVars.add(model.getSpecies(i).getId());
}
}
if (isFunction) {
String[] args = arguments.split(" |\\,");
for (int i = 0; i < args.length; i++) {
validVars.add(args[i]);
}
}
else {
for (int i = 0; i < bioModel.getSBMLDocument().getModel().getCompartmentCount(); i++) {
if (bioModel.getSBMLDocument().getLevel() > 2 || (model.getCompartment(i).getSpatialDimensions() != 0)) {
validVars.add(model.getCompartment(i).getId());
}
}
for (int i = 0; i < bioModel.getSBMLDocument().getModel().getParameterCount(); i++) {
validVars.add(model.getParameter(i).getId());
}
for (int i = 0; i < bioModel.getSBMLDocument().getModel().getReactionCount(); i++) {
Reaction reaction = model.getReaction(i);
validVars.add(reaction.getId());
for (int j = 0; j < reaction.getReactantCount(); j++) {
SpeciesReference reactant = reaction.getReactant(j);
if ((reactant.isSetId()) && (!reactant.getId().equals(""))) {
validVars.add(reactant.getId());
}
}
for (int j = 0; j < reaction.getProductCount(); j++) {
SpeciesReference product = reaction.getProduct(j);
if ((product.isSetId()) && (!product.getId().equals(""))) {
validVars.add(product.getId());
}
}
}
String[] kindsL3V1 = { "ampere", "avogadro", "becquerel", "candela", "celsius", "coulomb", "dimensionless", "farad", "gram", "gray", "henry",
"hertz", "item", "joule", "katal", "kelvin", "kilogram", "litre", "lumen", "lux", "metre", "mole", "newton", "ohm", "pascal",
"radian", "second", "siemens", "sievert", "steradian", "tesla", "volt", "watt", "weber" };
for (int i = 0; i < kindsL3V1.length; i++) {
validVars.add(kindsL3V1[i]);
}
for (int i = 0; i < model.getUnitDefinitionCount(); i++) {
validVars.add(model.getUnitDefinition(i).getId());
}
}
String[] splitLaw = formula.split(" |\\(|\\)|\\,|\\*|\\+|\\/|\\-|>|=|<|\\^|%|&|\\||!|\\[|\\]|\\{|\\}");
for (int i = 0; i < splitLaw.length; i++) {
if (splitLaw[i].equals("abs") || splitLaw[i].equals("arccos") || splitLaw[i].equals("arccosh") || splitLaw[i].equals("arcsin")
|| splitLaw[i].equals("arcsinh") || splitLaw[i].equals("arctan") || splitLaw[i].equals("arctanh") || splitLaw[i].equals("arccot")
|| splitLaw[i].equals("arccoth") || splitLaw[i].equals("arccsc") || splitLaw[i].equals("arccsch") || splitLaw[i].equals("arcsec")
|| splitLaw[i].equals("arcsech") || splitLaw[i].equals("acos") || splitLaw[i].equals("acosh") || splitLaw[i].equals("asin")
|| splitLaw[i].equals("asinh") || splitLaw[i].equals("atan") || splitLaw[i].equals("atanh") || splitLaw[i].equals("acot")
|| splitLaw[i].equals("acoth") || splitLaw[i].equals("acsc") || splitLaw[i].equals("acsch") || splitLaw[i].equals("asec")
|| splitLaw[i].equals("asech") || splitLaw[i].equals("cos") || splitLaw[i].equals("cosh") || splitLaw[i].equals("cot")
|| splitLaw[i].equals("coth") || splitLaw[i].equals("csc") || splitLaw[i].equals("csch") || splitLaw[i].equals("ceil")
|| splitLaw[i].equals("factorial") || splitLaw[i].equals("exp") || splitLaw[i].equals("floor") || splitLaw[i].equals("ln")
|| splitLaw[i].equals("log") || splitLaw[i].equals("sqr") || splitLaw[i].equals("log10") || splitLaw[i].equals("pow")
|| splitLaw[i].equals("sqrt") || splitLaw[i].equals("root") || splitLaw[i].equals("piecewise") || splitLaw[i].equals("sec")
|| splitLaw[i].equals("sech") || splitLaw[i].equals("sin") || splitLaw[i].equals("sinh") || splitLaw[i].equals("tan")
|| splitLaw[i].equals("tanh") || splitLaw[i].equals("") || splitLaw[i].equals("and") || splitLaw[i].equals("or")
|| splitLaw[i].equals("xor") || splitLaw[i].equals("not") || splitLaw[i].equals("eq") || splitLaw[i].equals("geq")
|| splitLaw[i].equals("leq") || splitLaw[i].equals("gt") || splitLaw[i].equals("neq") || splitLaw[i].equals("lt")
|| splitLaw[i].equals("delay") || splitLaw[i].equals("t") || splitLaw[i].equals("time") || splitLaw[i].equals("true")
|| splitLaw[i].equals("false") || splitLaw[i].equals("pi") || splitLaw[i].equals("exponentiale")
|| ((bioModel.getSBMLDocument().getLevel() > 2) && (splitLaw[i].equals("avogadro")))) {
}
else {
String temp = splitLaw[i];
if (splitLaw[i].substring(splitLaw[i].length() - 1, splitLaw[i].length()).equals("e")) {
temp = splitLaw[i].substring(0, splitLaw[i].length() - 1);
}
try {
Double.parseDouble(temp);
}
catch (Exception e1) {
if (!validVars.contains(splitLaw[i])) {
invalidVars.add(splitLaw[i]);
}
}
}
}
return invalidVars;
}
/**
* Creates a frame used to edit reactions parameters or create new ones.
*/
private void reacParametersEditor(BioModel bioModel,String option) {
if (option.equals("OK") && reacParameters.getSelectedIndex() == -1) {
JOptionPane.showMessageDialog(Gui.frame, "No parameter selected.", "Must Select A Parameter", JOptionPane.ERROR_MESSAGE);
return;
}
JPanel parametersPanel;
if (paramsOnly) {
parametersPanel = new JPanel(new GridLayout(7, 2));
}
else {
parametersPanel = new JPanel(new GridLayout(5, 2));
}
JLabel idLabel = new JLabel("ID:");
JLabel nameLabel = new JLabel("Name:");
JLabel valueLabel = new JLabel("Value:");
JLabel unitsLabel = new JLabel("Units:");
JLabel onPortLabel = new JLabel("Is Mapped to a Port:");
paramOnPort = new JCheckBox();
reacParamID = new JTextField();
reacParamName = new JTextField();
reacParamValue = new JTextField();
reacParamUnits = new JComboBox();
reacParamUnits.addItem("( none )");
Model model = bioModel.getSBMLDocument().getModel();
ListOf<UnitDefinition> listOfUnits = model.getListOfUnitDefinitions();
String[] units = new String[model.getUnitDefinitionCount()];
for (int i = 0; i < model.getUnitDefinitionCount(); i++) {
UnitDefinition unit = listOfUnits.get(i);
units[i] = unit.getId();
// GET OTHER THINGS
}
for (int i = 0; i < units.length; i++) {
if (bioModel.getSBMLDocument().getLevel() > 2
|| (!units[i].equals("substance") && !units[i].equals("volume") && !units[i].equals("area") && !units[i].equals("length") && !units[i]
.equals("time"))) {
reacParamUnits.addItem(units[i]);
}
}
String[] unitIdsL2V4 = { "substance", "volume", "area", "length", "time", "ampere", "becquerel", "candela", "celsius", "coulomb",
"dimensionless", "farad", "gram", "gray", "henry", "hertz", "item", "joule", "katal", "kelvin", "kilogram", "litre", "lumen", "lux",
"metre", "mole", "newton", "ohm", "pascal", "radian", "second", "siemens", "sievert", "steradian", "tesla", "volt", "watt", "weber" };
String[] unitIdsL3V1 = { "ampere", "avogadro", "becquerel", "candela", "celsius", "coulomb", "dimensionless", "farad", "gram", "gray",
"henry", "hertz", "item", "joule", "katal", "kelvin", "kilogram", "litre", "lumen", "lux", "metre", "mole", "newton", "ohm",
"pascal", "radian", "second", "siemens", "sievert", "steradian", "tesla", "volt", "watt", "weber" };
String[] unitIds;
if (bioModel.getSBMLDocument().getLevel() < 3) {
unitIds = unitIdsL2V4;
}
else {
unitIds = unitIdsL3V1;
}
for (int i = 0; i < unitIds.length; i++) {
reacParamUnits.addItem(unitIds[i]);
}
String[] list = { "Original", "Modified" };
String[] list1 = { "1", "2" };
final JComboBox type = new JComboBox(list);
final JTextField start = new JTextField();
final JTextField stop = new JTextField();
final JTextField step = new JTextField();
final JComboBox level = new JComboBox(list1);
final JButton sweep = new JButton("Sweep");
sweep.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
Object[] options = { "Ok", "Close" };
JPanel p = new JPanel(new GridLayout(4, 2));
JLabel startLabel = new JLabel("Start:");
JLabel stopLabel = new JLabel("Stop:");
JLabel stepLabel = new JLabel("Step:");
JLabel levelLabel = new JLabel("Level:");
p.add(startLabel);
p.add(start);
p.add(stopLabel);
p.add(stop);
p.add(stepLabel);
p.add(step);
p.add(levelLabel);
p.add(level);
int i = JOptionPane.showOptionDialog(Gui.frame, p, "Sweep", JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE, null, options,
options[0]);
if (i == JOptionPane.YES_OPTION) {
double startVal = 0.0;
double stopVal = 0.0;
double stepVal = 0.0;
try {
startVal = Double.parseDouble(start.getText().trim());
stopVal = Double.parseDouble(stop.getText().trim());
stepVal = Double.parseDouble(step.getText().trim());
}
catch (Exception e1) {
}
reacParamValue.setText("(" + startVal + "," + stopVal + "," + stepVal + "," + level.getSelectedItem() + ")");
}
}
});
if (paramsOnly) {
reacParamID.setEditable(false);
reacParamName.setEditable(false);
reacParamValue.setEnabled(false);
reacParamUnits.setEnabled(false);
sweep.setEnabled(false);
paramOnPort.setEnabled(false);
}
String selectedID = "";
if (option.equals("OK")) {
String v = ((String) reacParameters.getSelectedValue()).split(" ")[0];
LocalParameter paramet = null;
for (LocalParameter p : changedParameters) {
if (p.getId().equals(v)) {
paramet = p;
}
}
if (paramet==null) return;
reacParamID.setText(paramet.getId());
selectedID = paramet.getId();
reacParamName.setText(paramet.getName());
reacParamValue.setText("" + paramet.getValue());
if (paramet.isSetUnits()) {
reacParamUnits.setSelectedItem(paramet.getUnits());
}
if (bioModel.getPortByMetaIdRef(paramet.getMetaId())!=null) {
paramOnPort.setSelected(true);
} else {
paramOnPort.setSelected(false);
}
if (paramsOnly && (((String) reacParameters.getSelectedValue()).contains("Modified"))
|| (((String) reacParameters.getSelectedValue()).contains("Custom"))
|| (((String) reacParameters.getSelectedValue()).contains("Sweep"))) {
type.setSelectedItem("Modified");
sweep.setEnabled(true);
reacParamValue.setText(((String) reacParameters.getSelectedValue()).split(" ")[((String) reacParameters.getSelectedValue())
.split(" ").length - 1]);
reacParamValue.setEnabled(true);
reacParamUnits.setEnabled(false);
if (reacParamValue.getText().trim().startsWith("(")) {
try {
start.setText((reacParamValue.getText().trim()).split(",")[0].substring(1).trim());
stop.setText((reacParamValue.getText().trim()).split(",")[1].trim());
step.setText((reacParamValue.getText().trim()).split(",")[2].trim());
int lev = Integer.parseInt((reacParamValue.getText().trim()).split(",")[3].replace(")", "").trim());
if (lev == 1) {
level.setSelectedIndex(0);
}
else {
level.setSelectedIndex(1);
}
}
catch (Exception e1) {
}
}
}
}
parametersPanel.add(idLabel);
parametersPanel.add(reacParamID);
parametersPanel.add(nameLabel);
parametersPanel.add(reacParamName);
if (paramsOnly) {
JLabel typeLabel = new JLabel("Value Type:");
type.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if (!((String) type.getSelectedItem()).equals("Original")) {
sweep.setEnabled(true);
reacParamValue.setEnabled(true);
reacParamUnits.setEnabled(false);
}
else {
sweep.setEnabled(false);
reacParamValue.setEnabled(false);
reacParamUnits.setEnabled(false);
SBMLDocument d = SBMLutilities.readSBML(file);
KineticLaw KL = d.getModel().getReaction(selectedReaction).getKineticLaw();
ListOf<LocalParameter> list = KL.getListOfLocalParameters();
int number = -1;
for (int i = 0; i < KL.getLocalParameterCount(); i++) {
if (list.get(i).getId().equals(((String) reacParameters.getSelectedValue()).split(" ")[0])) {
number = i;
}
}
reacParamValue.setText(d.getModel().getReaction(selectedReaction).getKineticLaw()
.getLocalParameter(number).getValue()
+ "");
if (d.getModel().getReaction(selectedReaction).getKineticLaw().getLocalParameter(number)
.isSetUnits()) {
reacParamUnits.setSelectedItem(d.getModel().getReaction(selectedReaction)
.getKineticLaw().getLocalParameter(number).getUnits());
}
reacParamValue.setText(d.getModel().getReaction(selectedReaction).getKineticLaw().getLocalParameter(number).getValue() + "");
}
}
});
parametersPanel.add(typeLabel);
parametersPanel.add(type);
}
parametersPanel.add(valueLabel);
parametersPanel.add(reacParamValue);
if (paramsOnly) {
parametersPanel.add(new JLabel());
parametersPanel.add(sweep);
}
parametersPanel.add(unitsLabel);
parametersPanel.add(reacParamUnits);
parametersPanel.add(onPortLabel);
parametersPanel.add(paramOnPort);
Object[] options = { option, "Cancel" };
int value = JOptionPane.showOptionDialog(Gui.frame, parametersPanel, "Parameter Editor", JOptionPane.YES_NO_OPTION,
JOptionPane.PLAIN_MESSAGE, null, options, options[0]);
boolean error = true;
while (error && value == JOptionPane.YES_OPTION) {
error = SBMLutilities.checkID(bioModel.getSBMLDocument(), reacParamID.getText().trim(), selectedID, true);
if (!error) {
if (thisReactionParams.contains(reacParamID.getText().trim()) && (!reacParamID.getText().trim().equals(selectedID))) {
JOptionPane.showMessageDialog(Gui.frame, "ID is not unique.", "ID Not Unique", JOptionPane.ERROR_MESSAGE);
error = true;
}
}
if (!error) {
double val = 0;
if (reacParamValue.getText().trim().startsWith("(") && reacParamValue.getText().trim().endsWith(")")) {
try {
Double.parseDouble((reacParamValue.getText().trim()).split(",")[0].substring(1).trim());
Double.parseDouble((reacParamValue.getText().trim()).split(",")[1].trim());
Double.parseDouble((reacParamValue.getText().trim()).split(",")[2].trim());
int lev = Integer.parseInt((reacParamValue.getText().trim()).split(",")[3].replace(")", "").trim());
if (lev != 1 && lev != 2) {
error = true;
JOptionPane.showMessageDialog(Gui.frame, "The level can only be 1 or 2.", "Error", JOptionPane.ERROR_MESSAGE);
}
}
catch (Exception e1) {
error = true;
JOptionPane.showMessageDialog(Gui.frame, "Invalid sweeping parameters.", "Error", JOptionPane.ERROR_MESSAGE);
}
}
else {
try {
val = Double.parseDouble(reacParamValue.getText().trim());
}
catch (Exception e1) {
JOptionPane
.showMessageDialog(Gui.frame, "The value must be a real number.", "Enter A Valid Value", JOptionPane.ERROR_MESSAGE);
error = true;
}
}
if (!error) {
String unit = (String) reacParamUnits.getSelectedItem();
String param = "";
if (paramsOnly && !((String) type.getSelectedItem()).equals("Original")) {
int index = reacParameters.getSelectedIndex();
String[] splits = reacParams[index].split(" ");
for (int i = 0; i < splits.length - 2; i++) {
param += splits[i] + " ";
}
if (!splits[splits.length - 2].equals("Modified") && !splits[splits.length - 2].equals("Custom")
&& !splits[splits.length - 2].equals("Sweep")) {
param += splits[splits.length - 2] + " " + splits[splits.length - 1] + " ";
}
if (reacParamValue.getText().trim().startsWith("(") && reacParamValue.getText().trim().endsWith(")")) {
double startVal = Double.parseDouble((reacParamValue.getText().trim()).split(",")[0].substring(1).trim());
double stopVal = Double.parseDouble((reacParamValue.getText().trim()).split(",")[1].trim());
double stepVal = Double.parseDouble((reacParamValue.getText().trim()).split(",")[2].trim());
int lev = Integer.parseInt((reacParamValue.getText().trim()).split(",")[3].replace(")", "").trim());
param += "Sweep (" + startVal + "," + stopVal + "," + stepVal + "," + lev + ")";
}
else {
param += "Modified " + val;
}
}
else {
if (unit.equals("( none )")) {
param = reacParamID.getText().trim() + " " + val;
}
else {
param = reacParamID.getText().trim() + " " + val + " " + unit;
}
}
if (option.equals("OK")) {
int index = reacParameters.getSelectedIndex();
String v = ((String) reacParameters.getSelectedValue()).split(" ")[0];
LocalParameter paramet = null;
for (LocalParameter p : changedParameters) {
if (p.getId().equals(v)) {
paramet = p;
}
}
if (paramet==null) return;
reacParameters.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
reacParams = Utility.getList(reacParams, reacParameters);
reacParameters.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
paramet.setId(reacParamID.getText().trim());
paramet.setName(reacParamName.getText().trim());
SBMLutilities.setMetaId(paramet, reacID.getText()+"___"+reacParamID.getText().trim());
for (int i = 0; i < thisReactionParams.size(); i++) {
if (thisReactionParams.get(i).equals(v)) {
thisReactionParams.set(i, reacParamID.getText().trim());
}
}
paramet.setValue(val);
if (unit.equals("( none )")) {
paramet.unsetUnits();
}
else {
paramet.setUnits(unit);
}
reacParams[index] = param;
Utility.sort(reacParams);
reacParameters.setListData(reacParams);
reacParameters.setSelectedIndex(index);
if (paramsOnly) {
int remove = -1;
for (int i = 0; i < parameterChanges.size(); i++) {
if (parameterChanges.get(i).split(" ")[0].equals(selectedReaction + "/" + reacParamID.getText().trim())) {
remove = i;
}
}
String reacValue = selectedReaction;
int index1 = reactions.getSelectedIndex();
if (remove != -1) {
parameterChanges.remove(remove);
reactions.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
reacts = Utility.getList(reacts, reactions);
reactions.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
reacts[index1] = reacValue.split(" ")[0];
Utility.sort(reacts);
reactions.setListData(reacts);
reactions.setSelectedIndex(index1);
}
if (!((String) type.getSelectedItem()).equals("Original")) {
parameterChanges.add(reacValue + "/" + param);
reactions.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
reacts = Utility.getList(reacts, reactions);
reactions.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
reacts[index1] = reacValue + " Modified";
Utility.sort(reacts);
reactions.setListData(reacts);
reactions.setSelectedIndex(index1);
}
}
else {
kineticLaw.setText(SBMLutilities.updateFormulaVar(kineticLaw.getText().trim(), v, reacParamID.getText().trim()));
}
Port port = bioModel.getPortByMetaIdRef(paramet.getMetaId());
if (port!=null) {
if (paramOnPort.isSelected()) {
port.setId(GlobalConstants.LOCALPARAMETER+"__"+paramet.getMetaId());
port.setMetaIdRef(paramet.getMetaId());
} else {
bioModel.getSBMLCompModel().removePort(port);
}
} else {
if (paramOnPort.isSelected()) {
port = bioModel.getSBMLCompModel().createPort();
port.setId(GlobalConstants.LOCALPARAMETER+"__"+paramet.getMetaId());
port.setMetaIdRef(paramet.getMetaId());
}
}
}
else {
int index = reacParameters.getSelectedIndex();
// Parameter paramet = new Parameter(BioSim.SBML_LEVEL,
// BioSim.SBML_VERSION);
LocalParameter paramet = new LocalParameter(bioModel.getSBMLDocument().getLevel(), bioModel.getSBMLDocument().getVersion());
changedParameters.add(paramet);
paramet.setId(reacParamID.getText().trim());
paramet.setName(reacParamName.getText().trim());
SBMLutilities.setMetaId(paramet, reacID.getText()+"___"+reacParamID.getText().trim());
thisReactionParams.add(reacParamID.getText().trim());
paramet.setValue(val);
if (!unit.equals("( none )")) {
paramet.setUnits(unit);
}
if (paramOnPort.isSelected()) {
Port port = bioModel.getSBMLCompModel().createPort();
port.setId(GlobalConstants.LOCALPARAMETER+"__"+paramet.getMetaId());
port.setMetaIdRef(paramet.getMetaId());
}
JList add = new JList();
Object[] adding = { param };
add.setListData(adding);
add.setSelectedIndex(0);
reacParameters.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
adding = Utility.add(reacParams, reacParameters, add);
reacParams = new String[adding.length];
for (int i = 0; i < adding.length; i++) {
reacParams[i] = (String) adding[i];
}
Utility.sort(reacParams);
reacParameters.setListData(reacParams);
reacParameters.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
try {
if (bioModel.getSBMLDocument().getModel().getReaction(selectedReaction).getKineticLaw()
.getLocalParameterCount() == 1) {
reacParameters.setSelectedIndex(0);
}
else {
reacParameters.setSelectedIndex(index);
}
}
catch (Exception e2) {
reacParameters.setSelectedIndex(0);
}
}
modelEditor.setDirty(true);
bioModel.makeUndoPoint();
}
}
if (error) {
value = JOptionPane.showOptionDialog(Gui.frame, parametersPanel, "Parameter Editor", JOptionPane.YES_NO_OPTION,
JOptionPane.PLAIN_MESSAGE, null, options, options[0]);
}
}
if (value == JOptionPane.NO_OPTION) {
return;
}
}
private void addLocalParameter(String id,double val) {
LocalParameter paramet = new LocalParameter(bioModel.getSBMLDocument().getLevel(), bioModel.getSBMLDocument().getVersion());
changedParameters.add(paramet);
paramet.setId(id);
paramet.setName(id);
SBMLutilities.setMetaId(paramet, reacID.getText()+"___"+id);
thisReactionParams.add(id);
paramet.setValue(val);
JList add = new JList();
String param = id + " " + val;
Object[] adding = { param };
add.setListData(adding);
add.setSelectedIndex(0);
reacParameters.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
adding = Utility.add(reacParams, reacParameters, add);
reacParams = new String[adding.length];
for (int i = 0; i < adding.length; i++) {
reacParams[i] = (String) adding[i];
}
Utility.sort(reacParams);
reacParameters.setListData(reacParams);
reacParameters.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
reacParameters.setSelectedIndex(0);
modelEditor.setDirty(true);
bioModel.makeUndoPoint();
}
/**
* Creates a frame used to edit products or create new ones.
*/
public void productsEditor(BioModel bioModel, String option, String selectedProductId, SpeciesReference product,
boolean inSchematic) {
JPanel productsPanel;
if (bioModel.getSBMLDocument().getLevel() < 3) {
productsPanel = new JPanel(new GridLayout(5, 2));
}
else {
productsPanel = new JPanel(new GridLayout(6, 2));
}
JLabel productIdLabel = new JLabel("Id:");
JLabel productNameLabel = new JLabel("Name:");
JLabel speciesLabel = new JLabel("Species:");
Object[] stoiciOptions = { "Stoichiometry", "Stoichiometry Math" };
stoiciLabel = new JComboBox(stoiciOptions);
JLabel stoichiometryLabel = new JLabel("Stoichiometry:");
JLabel constantLabel = new JLabel("Constant:");
Object[] productConstantOptions = { "true", "false" };
productConstant = new JComboBox(productConstantOptions);
ListOf<Species> listOfSpecies = bioModel.getSBMLDocument().getModel().getListOfSpecies();
String[] speciesList = new String[bioModel.getSBMLDocument().getModel().getSpeciesCount()];
for (int i = 0; i < bioModel.getSBMLDocument().getModel().getSpeciesCount(); i++) {
speciesList[i] = listOfSpecies.get(i).getId();
}
Utility.sort(speciesList);
productSpecies = new JComboBox();
PiIndex = new JTextField(10);
PiIndex.setEnabled(true);
productSpecies.addActionListener(this);
if (inSchematic) {
productSpecies.setEnabled(false);
} else {
productSpecies.setEnabled(true);
}
for (int i = 0; i < speciesList.length; i++) {
Species species = bioModel.getSBMLDocument().getModel().getSpecies(speciesList[i]);
if (species.getBoundaryCondition() || (!species.getConstant() && Rules.keepVarRateRule(bioModel, "", speciesList[i]))) {
productSpecies.addItem(speciesList[i]);
}
}
productId = new JTextField("");
/*
* int j = 0; while (usedIDs.contains("product"+j)) { j++; }
* productId.setText("product"+j);
*/
productName = new JTextField("");
productStoichiometry = new JTextField("1");
String selectedID = "";
if (option.equals("OK")) {
String v = selectedProductId;
if (product == null || !inSchematic) {
for (SpeciesReference p : changedProducts) {
if (p.getSpecies().equals(v)) {
product = p;
}
}
}
if (product==null) return;
if (product.isSetName()) {
productName.setText(product.getName());
}
productSpecies.setSelectedItem(product.getSpecies());
productStoichiometry.setText("" + product.getStoichiometry());
if (product.isSetId()) {
selectedID = product.getId();
productId.setText(product.getId());
InitialAssignment init = bioModel.getSBMLDocument().getModel().getInitialAssignment(selectedID);
if (init!=null) {
productStoichiometry.setText("" + bioModel.removeBooleans(init.getMath()));
}
}
if (!product.getConstant()) {
productConstant.setSelectedItem("false");
}
ArraysSBasePlugin sBasePlugin = SBMLutilities.getArraysSBasePlugin(product);
//TODO: Make sure it reads correctly
String dimInID = "";
for(int i = sBasePlugin.getDimensionCount()-1; i>=0; i
org.sbml.jsbml.ext.arrays.Dimension dimX = sBasePlugin.getDimensionByArrayDimension(i);
dimInID += "[" + dimX.getSize() + "]";
}
productId.setText(productId.getText()+dimInID);
// TODO: Scott - change for Plugin reading
String freshIndex = "";
for(int i = sBasePlugin.getIndexCount()-1; i>=0; i
Index indie = sBasePlugin.getIndex(i);
freshIndex += "[" + SBMLutilities.myFormulaToString(indie.getMath()) + "]";
}
PiIndex.setText(freshIndex);
}
if (production!=null) {
double np = bioModel.getSBMLDocument().getModel().getParameter(GlobalConstants.STOICHIOMETRY_STRING).getValue();
if (production.getKineticLaw().getLocalParameter(GlobalConstants.STOICHIOMETRY_STRING)!=null) {
np = production.getKineticLaw().getLocalParameter(GlobalConstants.STOICHIOMETRY_STRING).getValue();
}
productStoichiometry.setText(""+np);
productStoichiometry.setEnabled(false);
}
productsPanel.add(productIdLabel);
productsPanel.add(productId);
productsPanel.add(productNameLabel);
productsPanel.add(productName);
productsPanel.add(speciesLabel);
productsPanel.add(productSpecies);
productsPanel.add(new JLabel("Indices:"));
productsPanel.add(PiIndex);
if (bioModel.getSBMLDocument().getLevel() < 3) {
productsPanel.add(stoiciLabel);
}
else {
productsPanel.add(stoichiometryLabel);
}
productsPanel.add(productStoichiometry);
if (bioModel.getSBMLDocument().getLevel() > 2) {
productsPanel.add(constantLabel);
productsPanel.add(productConstant);
}
if (speciesList.length == 0) {
JOptionPane.showMessageDialog(Gui.frame, "There are no species availiable to be products." + "\nAdd species to this sbml file first.",
"No Species", JOptionPane.ERROR_MESSAGE);
return;
}
Object[] options = { option, "Cancel" };
int value = JOptionPane.showOptionDialog(Gui.frame, productsPanel, "Products Editor", JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE,
null, options, options[0]);
String[] dimID = new String[]{""};
String[] dex = new String[]{""};
String[] dimensionIds = new String[]{""};
boolean error = true;
while (error && value == JOptionPane.YES_OPTION) {
error = false;
String prod = "";
double val = 1.0;
dimID = SBMLutilities.checkSizeParameters(bioModel.getSBMLDocument(), productId.getText(), true);
if(dimID!=null){
dimensionIds = SBMLutilities.getDimensionIds("p",dimID.length-1);
if (dimID[0].equals("")) {
error = SBMLutilities.variableInUse(bioModel.getSBMLDocument(), selectedID, false, true, true);
}
else {
error = SBMLutilities.checkID(bioModel.getSBMLDocument(), dimID[0], selectedID, false);
}
}
else{
error = true;
}
if(!error){
SBase variable = SBMLutilities.getElementBySId(bioModel.getSBMLDocument(), (String)productSpecies.getSelectedItem());
dex = SBMLutilities.checkIndices(PiIndex.getText(), variable, bioModel.getSBMLDocument(), dimensionIds, "variable", dimID);
error = (dex==null);
}
if (!error) {
if (stoiciLabel.getSelectedItem().equals("Stoichiometry")) {
InitialAssignments.removeInitialAssignment(bioModel, selectedID);
try {
val = Double.parseDouble(productStoichiometry.getText().trim());
}
catch (Exception e1) {
if (productId.getText().equals("")) {
JOptionPane.showMessageDialog(Gui.frame, "The stoichiometry must be a real number if no id is provided.", "Enter A Valid Value",
JOptionPane.ERROR_MESSAGE);
error = true;
} else {
// TODO: this needs to send product dimension when it exists
error = InitialAssignments.addInitialAssignment(bioModel, dimID[0],
productStoichiometry.getText().trim(),dimID);
val = 1.0;
}
}
if (val <= 0) {
JOptionPane.showMessageDialog(Gui.frame, "The stoichiometry value must be greater than 0.", "Enter A Valid Value",
JOptionPane.ERROR_MESSAGE);
error = true;
}
prod = productSpecies.getSelectedItem() + " " + val;
}
else {
prod = productSpecies.getSelectedItem() + " " + productStoichiometry.getText().trim();
}
}
int index = -1;
if (!error) {
if (product == null || !inSchematic) {
if (option.equals("OK")) {
index = products.getSelectedIndex();
}
products.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
proda = Utility.getList(proda, products);
products.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
if (index >= 0) {
products.setSelectedIndex(index);
}
for (int i = 0; i < proda.length; i++) {
if (i != index) {
if (proda[i].split(" ")[0].equals(productSpecies.getSelectedItem())) {
error = true;
JOptionPane.showMessageDialog(Gui.frame, "Unable to add species as a product.\n"
+ "Each species can only be used as a product once.", "Species Can Only Be Used Once",
JOptionPane.ERROR_MESSAGE);
}
}
}
}
}
if (!error) {
if (stoiciLabel.getSelectedItem().equals("Stoichiometry Math")) {
if (productStoichiometry.getText().trim().equals("")) {
JOptionPane.showMessageDialog(Gui.frame, "Stoichiometry math must have formula.", "Enter Stoichiometry Formula",
JOptionPane.ERROR_MESSAGE);
error = true;
}
else if (SBMLutilities.myParseFormula(productStoichiometry.getText().trim()) == null) {
JOptionPane.showMessageDialog(Gui.frame, "Stoichiometry formula is not valid.", "Enter Valid Formula",
JOptionPane.ERROR_MESSAGE);
error = true;
}
else {
ArrayList<String> invalidVars = getInvalidVariablesInReaction(productStoichiometry.getText().trim(), dimensionIds, true, "", false);
if (invalidVars.size() > 0) {
String invalid = "";
for (int i = 0; i < invalidVars.size(); i++) {
if (i == invalidVars.size() - 1) {
invalid += invalidVars.get(i);
}
else {
invalid += invalidVars.get(i) + "\n";
}
}
String message;
message = "Stoiciometry math contains unknown variables.\n\n" + "Unknown variables:\n" + invalid;
JTextArea messageArea = new JTextArea(message);
messageArea.setLineWrap(true);
messageArea.setWrapStyleWord(true);
messageArea.setEditable(false);
JScrollPane scrolls = new JScrollPane();
scrolls.setMinimumSize(new Dimension(300, 300));
scrolls.setPreferredSize(new Dimension(300, 300));
scrolls.setViewportView(messageArea);
JOptionPane.showMessageDialog(Gui.frame, scrolls, "Stoiciometry Math Error", JOptionPane.ERROR_MESSAGE);
error = true;
}
if (!error) {
error = SBMLutilities.checkNumFunctionArguments(bioModel.getSBMLDocument(),
SBMLutilities.myParseFormula(productStoichiometry.getText().trim()));
}
if (!error) {
if (SBMLutilities.returnsBoolean(SBMLutilities.myParseFormula(productStoichiometry.getText().trim()), bioModel.getSBMLDocument().getModel())) {
JOptionPane.showMessageDialog(Gui.frame, "Stoichiometry math must evaluate to a number.", "Number Expected",
JOptionPane.ERROR_MESSAGE);
error = true;
}
}
}
}
}
if (!error && option.equals("OK") && productConstant.getSelectedItem().equals("true")) {
String id = selectedID;
error = SBMLutilities.checkConstant(bioModel.getSBMLDocument(), "Product stoiciometry", id);
}
if (!error) {
if (option.equals("OK")) {
String v = selectedProductId;
SpeciesReference produ = product;
if (product == null || !inSchematic) {
for (SpeciesReference p : changedProducts) {
if (p.getSpecies().equals(v)) {
produ = p;
}
}
products.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
proda = Utility.getList(proda, products);
products.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
}
if (produ==null) return;
produ.setId(dimID[0]);
produ.setName(productName.getText().trim());
produ.setSpecies((String) productSpecies.getSelectedItem());
produ.setStoichiometry(val);
if (productConstant.getSelectedItem().equals("true")) {
produ.setConstant(true);
}
else {
produ.setConstant(false);
}
// TODO: Scott - change for Plugin writing
if(!error){
ArraysSBasePlugin sBasePlugin = SBMLutilities.getArraysSBasePlugin(produ);
sBasePlugin.unsetListOfDimensions();
for(int i = 0; i<dimID.length-1; i++){
org.sbml.jsbml.ext.arrays.Dimension dimX = sBasePlugin.createDimension(dimensionIds[i]);
dimX.setSize(dimID[i+1]);
dimX.setArrayDimension(i);
}
// Add the indices
sBasePlugin.unsetListOfIndices();
for(int i = 0; i<dex.length-1; i++){
Index indexRule = new Index();
indexRule.setArrayDimension(i);
indexRule.setReferencedAttribute("variable");
ASTNode indexMath = SBMLutilities.myParseFormula(dex[i+1]);
indexRule.setMath(indexMath);
sBasePlugin.addIndex(indexRule);
}
}
if (product == null || !inSchematic) {
proda[index] = prod;
Utility.sort(proda);
products.setListData(proda);
products.setSelectedIndex(index);
}
SBMLutilities.updateVarId(bioModel.getSBMLDocument(), false, selectedID, dimID[0]);
if (product == null || !inSchematic) {
kineticLaw.setText(SBMLutilities.updateFormulaVar(kineticLaw.getText().trim(), selectedID, dimID[0]));
}
}
else {
// SpeciesReference produ = new
// SpeciesReference(BioSim.SBML_LEVEL, BioSim.SBML_VERSION);
SpeciesReference produ = new SpeciesReference(bioModel.getSBMLDocument().getLevel(), bioModel.getSBMLDocument().getVersion());
produ.setId(dimID[0]);
produ.setName(productName.getText().trim());
changedProducts.add(produ);
produ.setSpecies((String) productSpecies.getSelectedItem());
produ.setStoichiometry(val);
if (productConstant.getSelectedItem().equals("true")) {
produ.setConstant(true);
}
else {
produ.setConstant(false);
}
if(!error){
ArraysSBasePlugin sBasePlugin = SBMLutilities.getArraysSBasePlugin(produ);
for(int i = 0; i<dimID.length-1; i++){
org.sbml.jsbml.ext.arrays.Dimension dimX = sBasePlugin.createDimension(dimensionIds[i]);
dimX.setSize(dimID[i+1]);
dimX.setArrayDimension(i);
}
// Add the indices
for(int i = 0; i<dex.length-1; i++){
Index indexRule = new Index();
indexRule.setArrayDimension(i);
indexRule.setReferencedAttribute("variable");
ASTNode indexMath = SBMLutilities.myParseFormula(dex[i+1]);
indexRule.setMath(indexMath);
sBasePlugin.addIndex(indexRule);
}
}
JList add = new JList();
Object[] adding = { prod };
add.setListData(adding);
add.setSelectedIndex(0);
products.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
adding = Utility.add(proda, products, add);
proda = new String[adding.length];
for (int i = 0; i < adding.length; i++) {
proda[i] = (String) adding[i];
}
Utility.sort(proda);
products.setListData(proda);
products.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
products.setSelectedIndex(0);
}
modelEditor.setDirty(true);
bioModel.makeUndoPoint();
}
if (error) {
value = JOptionPane.showOptionDialog(Gui.frame, productsPanel, "Products Editor", JOptionPane.YES_NO_OPTION,
JOptionPane.PLAIN_MESSAGE, null, options, options[0]);
}
}
if (value == JOptionPane.NO_OPTION) {
return;
}
}
private LocalParameter getChangedParameter(String paramStr) {
for (LocalParameter r : changedParameters) {
if (r.getId().equals(paramStr)) {
return r;
}
}
return null;
}
/**
* Creates a frame used to edit modifiers or create new ones.
*/
public void modifiersEditor(BioModel bioModel,String option,String selectedModifierId, ModifierSpeciesReference modifier,
boolean inSchematic) {
JPanel modifiersPanel;
MiIndex = new JTextField(10);
modifierId = new JTextField(10);
modifierName = new JTextField(10);
JLabel speciesLabel = new JLabel("Species:");
ListOf<Species> listOfSpecies = bioModel.getSBMLDocument().getModel().getListOfSpecies();
String[] speciesList = new String[bioModel.getSBMLDocument().getModel().getSpeciesCount()];
for (int i = 0; i < bioModel.getSBMLDocument().getModel().getSpeciesCount(); i++) {
speciesList[i] = listOfSpecies.get(i).getId();
}
Utility.sort(speciesList);
Object[] choices = speciesList;
modifierSpecies = new JComboBox(choices);
modifierSpecies.addActionListener(this);
if (inSchematic) {
modifierSpecies.setEnabled(false);
} else {
modifierSpecies.setEnabled(true);
}
JLabel SBOTermsLabel = new JLabel("Type");
JLabel RepStoichiometryLabel = new JLabel("Stoichiometry of repression (nc)");
JLabel RepBindingLabel = new JLabel("Repression binding equilibrium (Kr)");
JLabel ActStoichiometryLabel = new JLabel("Stoichiometry of activation (nc)");
JLabel ActBindingLabel = new JLabel("Activation binding equilibrium (Ka)");
String selectedID = "";
if (option.equals("OK")) {
String v = selectedModifierId;
if (modifier == null || !inSchematic) {
for (ModifierSpeciesReference p : changedModifiers) {
if (p.getSpecies().equals(v)) {
modifier = p;
}
}
}
if (modifier==null) return;
if (modifier.isSetName()) {
modifierName.setText(modifier.getName());
}
if (modifier.isSetId()) {
selectedID = modifier.getId();
modifierId.setText(modifier.getId());
}
// TODO: Scott - change for Plugin reading
ArraysSBasePlugin sBasePlugin = SBMLutilities.getArraysSBasePlugin(modifier);
String dimInID = "";
for(int i = sBasePlugin.getDimensionCount()-1; i>=0; i
org.sbml.jsbml.ext.arrays.Dimension dimX = sBasePlugin.getDimensionByArrayDimension(i);
dimInID += "[" + dimX.getSize() + "]";
}
modifierId.setText(modifierId.getText()+dimInID);
String freshIndex = "";
for(int i = sBasePlugin.getIndexCount()-1; i>=0; i
Index indie = sBasePlugin.getIndex(i);
freshIndex += "[" + SBMLutilities.myFormulaToString(indie.getMath()) + "]";
}
MiIndex.setText(freshIndex);
modifierSpecies.setSelectedItem(modifier.getSpecies());
if (production!=null) {
if (BioModel.isPromoter(modifier)) {
String [] sboTerms = new String[1];
sboTerms[0] = "Promoter";
SBOTerms = new JComboBox(sboTerms);
SBOTerms.setSelectedItem("Promoter");
} else {
String [] sboTerms = new String[4];
sboTerms[0] = "Repression";
sboTerms[1] = "Activation";
sboTerms[2] = "Dual activity";
sboTerms[3] = "No influence";
SBOTerms = new JComboBox(sboTerms);
if (BioModel.isRepressor(modifier)) {
SBOTerms.setSelectedItem("Repression");
} else if (BioModel.isActivator(modifier)) {
SBOTerms.setSelectedItem("Activation");
} else if (BioModel.isRegulator(modifier)) {
SBOTerms.setSelectedItem("Dual activity");
} else if (BioModel.isNeutral(modifier)) {
SBOTerms.setSelectedItem("No influence");
}
}
}
} else {
String [] sboTerms = new String[4];
sboTerms[0] = "Repression";
sboTerms[1] = "Activation";
sboTerms[2] = "Dual activity";
sboTerms[3] = "No influence";
SBOTerms = new JComboBox(sboTerms);
}
if (production==null) {
modifiersPanel = new JPanel(new GridLayout(4, 2));
} else {
if (SBOTerms.getSelectedItem().equals("Promoter")) {
modifiersPanel = new JPanel(new GridLayout(5, 2));
} else {
modifiersPanel = new JPanel(new GridLayout(9, 2));
}
}
modifiersPanel.add(new JLabel("Id:"));
modifiersPanel.add(modifierId);
modifiersPanel.add(new JLabel("Name:"));
modifiersPanel.add(modifierName);
modifiersPanel.add(speciesLabel);
modifiersPanel.add(modifierSpecies);
modifiersPanel.add(new JLabel("Indices:"));
modifiersPanel.add(MiIndex);
if (production!=null) {
modifiersPanel.add(SBOTermsLabel);
modifiersPanel.add(SBOTerms);
if (SBOTerms.getSelectedItem().equals("Promoter")) {
modifierSpecies.setEnabled(false);
SBOTerms.setEnabled(false);
} else {
String selectedSpecies = (String)modifierSpecies.getSelectedItem();
modifiersPanel.add(RepStoichiometryLabel);
repCooperativity = new JTextField();
double nc = bioModel.getSBMLDocument().getModel().getParameter(GlobalConstants.COOPERATIVITY_STRING).getValue();
repCooperativity.setText(""+nc);
LocalParameter p = getChangedParameter(GlobalConstants.COOPERATIVITY_STRING+"_"+selectedSpecies+"_r");
if (p!=null) {
repCooperativity.setText(""+p.getValue());
}
modifiersPanel.add(repCooperativity);
modifiersPanel.add(RepBindingLabel);
repBinding = new JTextField(bioModel.getParameter(GlobalConstants.FORWARD_KREP_STRING) + "/" +
bioModel.getParameter(GlobalConstants.REVERSE_KREP_STRING));
LocalParameter kr_f = getChangedParameter(GlobalConstants.FORWARD_KREP_STRING.replace("_","_" + selectedSpecies + "_"));
LocalParameter kr_r = getChangedParameter(GlobalConstants.REVERSE_KREP_STRING.replace("_","_" + selectedSpecies + "_"));
if (kr_f!=null && kr_r!=null) {
repBinding.setText(""+kr_f.getValue()+"/"+kr_r.getValue());
}
modifiersPanel.add(repBinding);
modifiersPanel.add(ActStoichiometryLabel);
actCooperativity = new JTextField();
nc = bioModel.getSBMLDocument().getModel().getParameter(GlobalConstants.COOPERATIVITY_STRING).getValue();
actCooperativity.setText(""+nc);
p = getChangedParameter(GlobalConstants.COOPERATIVITY_STRING+"_"+selectedSpecies+"_a");
if (p!=null) {
actCooperativity.setText(""+p.getValue());
}
modifiersPanel.add(actCooperativity);
modifiersPanel.add(ActBindingLabel);
actBinding = new JTextField(bioModel.getParameter(GlobalConstants.FORWARD_KACT_STRING) + "/" +
bioModel.getParameter(GlobalConstants.REVERSE_KACT_STRING));
LocalParameter ka_f = getChangedParameter(GlobalConstants.FORWARD_KACT_STRING.replace("_","_" + selectedSpecies + "_"));
LocalParameter ka_r = getChangedParameter(GlobalConstants.REVERSE_KACT_STRING.replace("_","_" + selectedSpecies + "_"));
if (ka_f!=null && ka_r!=null) {
actBinding.setText(""+ka_f.getValue()+"/"+ka_r.getValue());
}
modifiersPanel.add(actBinding);
}
}
if (choices.length == 0) {
JOptionPane.showMessageDialog(Gui.frame, "There are no species availiable to be modifiers." + "\nAdd species to this sbml file first.",
"No Species", JOptionPane.ERROR_MESSAGE);
return;
}
Object[] options = { option, "Cancel" };
int value = JOptionPane.showOptionDialog(Gui.frame, modifiersPanel, "Modifiers Editor", JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE,
null, options, options[0]);
String[] dex = new String[]{""};
String[] dimensionIds = new String[]{""};
String[] dimID = new String[]{""};
boolean error = true;
while (error && value == JOptionPane.YES_OPTION) {
error = false;
int index = -1;
dimID = SBMLutilities.checkSizeParameters(bioModel.getSBMLDocument(), modifierId.getText(), true);
if(dimID!=null){
dimensionIds = SBMLutilities.getDimensionIds("m",dimID.length-1);
if (dimID[0].trim().equals("")) {
error = SBMLutilities.variableInUse(bioModel.getSBMLDocument(), selectedID, false, true, true);
}
else {
error = SBMLutilities.checkID(bioModel.getSBMLDocument(), dimID[0].trim(), selectedID, false);
}
}
else{
error = true;
}
if(!error){
SBase variable = SBMLutilities.getElementBySId(bioModel.getSBMLDocument(), (String)modifierSpecies.getSelectedItem());
dex = SBMLutilities.checkIndices(MiIndex.getText(), variable, bioModel.getSBMLDocument(), dimensionIds, "variable", dimID);
error = (dex==null);
}
if (modifier == null || !inSchematic) {
if (option.equals("OK")) {
index = modifiers.getSelectedIndex();
}
modifiers.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
modifierArray = Utility.getList(modifierArray, modifiers);
modifiers.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
if (index >= 0) {
modifiers.setSelectedIndex(index);
}
for (int i = 0; i < modifierArray.length; i++) {
if (i != index) {
if (modifierArray[i].split(" ")[0].equals(modifierSpecies.getSelectedItem())) {
error = true;
JOptionPane.showMessageDialog(Gui.frame, "Unable to add species as a modifier.\n"
+ "Each species can only be used as a modifier once.", "Species Can Only Be Used Once",
JOptionPane.ERROR_MESSAGE);
}
}
}
}
String mod = (String) modifierSpecies.getSelectedItem();
double repCoop = 0.0;
double actCoop = 0.0;
double repBindf = 0.0;
double repBindr = 1.0;
double actBindf = 0.0;
double actBindr = 1.0;
if (production!=null) {
try {
repCoop = Double.parseDouble(repCooperativity.getText().trim());
}
catch (Exception e1) {
JOptionPane.showMessageDialog(Gui.frame, "The repression cooperativity must be a real number.", "Enter A Valid Value",
JOptionPane.ERROR_MESSAGE);
error = true;
}
try {
repBindf = Double.parseDouble(repBinding.getText().trim().split("/")[0]);
repBindr = Double.parseDouble(repBinding.getText().trim().split("/")[1]);
}
catch (Exception e1) {
JOptionPane.showMessageDialog(Gui.frame, "The repression binding must be a forward rate / reverse rate.", "Enter A Valid Value",
JOptionPane.ERROR_MESSAGE);
error = true;
}
try {
actCoop = Double.parseDouble(actCooperativity.getText().trim());
}
catch (Exception e1) {
JOptionPane.showMessageDialog(Gui.frame, "The activation cooperativity must be a real number.", "Enter A Valid Value",
JOptionPane.ERROR_MESSAGE);
error = true;
}
try {
actBindf = Double.parseDouble(actBinding.getText().trim().split("/")[0]);
actBindr = Double.parseDouble(actBinding.getText().trim().split("/")[1]);
}
catch (Exception e1) {
JOptionPane.showMessageDialog(Gui.frame, "The activation binding must be a forward rate / reverse rate.", "Enter A Valid Value",
JOptionPane.ERROR_MESSAGE);
error = true;
}
}
if (!error) {
if (option.equals("OK")) {
String v = selectedModifierId;
ModifierSpeciesReference modi = modifier;
modi.setId(dimID[0]);
modi.setName(modifierName.getText());
if (modifier == null || !inSchematic) {
for (ModifierSpeciesReference p : changedModifiers) {
if (p.getSpecies().equals(mod)) {
modi = p;
}
}
modifiers.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
modifierArray = Utility.getList(modifierArray, modifiers);
modifiers.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
//modifiers.setSelectedIndex(index);
}
modi.setSpecies((String) modifierSpecies.getSelectedItem());
if (production!=null) {
if (SBOTerms.getSelectedItem().equals("Repression")) {
modi.setSBOTerm(GlobalConstants.SBO_REPRESSION);
} else if (SBOTerms.getSelectedItem().equals("Activation")) {
modi.setSBOTerm(GlobalConstants.SBO_ACTIVATION);
} else if (SBOTerms.getSelectedItem().equals("Dual activity")) {
modi.setSBOTerm(GlobalConstants.SBO_DUAL_ACTIVITY);
} else if (SBOTerms.getSelectedItem().equals("No influence")) {
modi.setSBOTerm(GlobalConstants.SBO_NEUTRAL);
} else if (SBOTerms.getSelectedItem().equals("Promoter")) {
modi.setSBOTerm(GlobalConstants.SBO_PROMOTER_MODIFIER);
}
}
if (production!=null) {
double nc = bioModel.getSBMLDocument().getModel().getParameter(GlobalConstants.COOPERATIVITY_STRING).getValue();
String ncStr = GlobalConstants.COOPERATIVITY_STRING+"_"+mod+"_r";
LocalParameter paramet = getChangedParameter(ncStr);
if (paramet != null) {
removeLocalParameter(ncStr);
}
if (nc!=repCoop) {
addLocalParameter(ncStr,repCoop);
}
ncStr = GlobalConstants.COOPERATIVITY_STRING+"_"+mod+"_a";
paramet = getChangedParameter(ncStr);
if (paramet != null) {
removeLocalParameter(ncStr);
}
if (nc!=actCoop) {
addLocalParameter(ncStr,actCoop);
}
double bindf = bioModel.getSBMLDocument().getModel().getParameter(GlobalConstants.FORWARD_KREP_STRING).getValue();
double bindr = bioModel.getSBMLDocument().getModel().getParameter(GlobalConstants.REVERSE_KREP_STRING).getValue();
LocalParameter kr_f = getChangedParameter(GlobalConstants.FORWARD_KREP_STRING.replace("_","_" + mod + "_"));
LocalParameter kr_r = getChangedParameter(GlobalConstants.REVERSE_KREP_STRING.replace("_","_" + mod + "_"));
if (kr_f != null) {
removeLocalParameter(GlobalConstants.FORWARD_KREP_STRING.replace("_","_" + mod + "_"));
}
if (kr_r != null) {
removeLocalParameter(GlobalConstants.REVERSE_KREP_STRING.replace("_","_" + mod + "_"));
}
if (repBindf!=bindf || repBindr!=bindr) {
addLocalParameter(GlobalConstants.FORWARD_KREP_STRING.replace("_","_" + mod + "_"),repBindf);
addLocalParameter(GlobalConstants.REVERSE_KREP_STRING.replace("_","_" + mod + "_"),repBindr);
}
bindf = bioModel.getSBMLDocument().getModel().getParameter(GlobalConstants.FORWARD_KACT_STRING).getValue();
bindr = bioModel.getSBMLDocument().getModel().getParameter(GlobalConstants.REVERSE_KACT_STRING).getValue();
LocalParameter ka_f = getChangedParameter(GlobalConstants.FORWARD_KACT_STRING.replace("_","_" + mod + "_"));
LocalParameter ka_r = getChangedParameter(GlobalConstants.REVERSE_KACT_STRING.replace("_","_" + mod + "_"));
if (ka_f != null) {
removeLocalParameter(GlobalConstants.FORWARD_KACT_STRING.replace("_","_" + mod + "_"));
}
if (ka_r != null) {
removeLocalParameter(GlobalConstants.REVERSE_KACT_STRING.replace("_","_" + mod + "_"));
}
if (actBindf!=bindf || actBindr!=bindr) {
addLocalParameter(GlobalConstants.FORWARD_KACT_STRING.replace("_","_" + mod + "_"),actBindf);
addLocalParameter(GlobalConstants.REVERSE_KACT_STRING.replace("_","_" + mod + "_"),actBindr);
}
}
if (modifier == null || !inSchematic) {
modifierArray[index] = mod;
Utility.sort(modifierArray);
modifiers.setListData(modifierArray);
modifiers.setSelectedIndex(index);
}
// TODO: Scott - change for Plugin writing
ArraysSBasePlugin sBasePlugin = SBMLutilities.getArraysSBasePlugin(modifier);
sBasePlugin.unsetListOfDimensions();
for(int i = 0; i<dimID.length-1; i++){
org.sbml.jsbml.ext.arrays.Dimension dimX = sBasePlugin.createDimension(dimensionIds[i]);
dimX.setSize(dimID[i+1]);
dimX.setArrayDimension(i);
}
sBasePlugin.unsetListOfIndices();
for(int i = 0; i<dex.length-1; i++){
Index indexRule = new Index();
indexRule.setArrayDimension(i);
indexRule.setReferencedAttribute("variable");
ASTNode indexMath = SBMLutilities.myParseFormula(dex[i+1]);
indexRule.setMath(indexMath);
sBasePlugin.addIndex(indexRule);
}
}
else {
modifiers.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
modifierArray = Utility.getList(modifierArray, modifiers);
modifiers.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
modifiers.setSelectedIndex(index);
ModifierSpeciesReference modi = new ModifierSpeciesReference(bioModel.getSBMLDocument().getLevel(), bioModel.getSBMLDocument().getVersion());
modi.setId(dimID[0]);
modi.setName(modifierName.getText());
changedModifiers.add(modi);
modi.setSpecies(mod);
if (production!=null) {
if (SBOTerms.getSelectedItem().equals("Repression")) {
modi.setSBOTerm(GlobalConstants.SBO_REPRESSION);
} else if (SBOTerms.getSelectedItem().equals("Activation")) {
modi.setSBOTerm(GlobalConstants.SBO_ACTIVATION);
} else if (SBOTerms.getSelectedItem().equals("Dual activity")) {
modi.setSBOTerm(GlobalConstants.SBO_DUAL_ACTIVITY);
} else if (SBOTerms.getSelectedItem().equals("No influence")) {
modi.setSBOTerm(GlobalConstants.SBO_NEUTRAL);
} else if (SBOTerms.getSelectedItem().equals("Promoter")) {
modi.setSBOTerm(GlobalConstants.SBO_PROMOTER_MODIFIER);
}
}
if (production!=null) {
double nc = bioModel.getSBMLDocument().getModel().getParameter(GlobalConstants.COOPERATIVITY_STRING).getValue();
String ncStr = GlobalConstants.COOPERATIVITY_STRING+"_"+mod+"_r";
LocalParameter paramet = getChangedParameter(ncStr);
if (paramet != null) {
removeLocalParameter(ncStr);
}
if (nc!=repCoop) {
addLocalParameter(ncStr,repCoop);
}
ncStr = GlobalConstants.COOPERATIVITY_STRING+"_"+mod+"_a";
paramet = getChangedParameter(ncStr);
if (paramet != null) {
removeLocalParameter(ncStr);
}
if (nc!=actCoop) {
addLocalParameter(ncStr,actCoop);
}
double bindf = bioModel.getSBMLDocument().getModel().getParameter(GlobalConstants.FORWARD_KREP_STRING).getValue();
double bindr = bioModel.getSBMLDocument().getModel().getParameter(GlobalConstants.REVERSE_KREP_STRING).getValue();
LocalParameter kr_f = getChangedParameter(GlobalConstants.FORWARD_KREP_STRING.replace("_","_" + mod + "_"));
LocalParameter kr_r = getChangedParameter(GlobalConstants.REVERSE_KREP_STRING.replace("_","_" + mod + "_"));
if (kr_f != null) {
removeLocalParameter(GlobalConstants.FORWARD_KREP_STRING.replace("_","_" + mod + "_"));
}
if (kr_r != null) {
removeLocalParameter(GlobalConstants.REVERSE_KREP_STRING.replace("_","_" + mod + "_"));
}
if (repBindf!=bindf || repBindr!=bindr) {
addLocalParameter(GlobalConstants.FORWARD_KREP_STRING.replace("_","_" + mod + "_"),repBindf);
addLocalParameter(GlobalConstants.REVERSE_KREP_STRING.replace("_","_" + mod + "_"),repBindr);
}
bindf = bioModel.getSBMLDocument().getModel().getParameter(GlobalConstants.FORWARD_KACT_STRING).getValue();
bindr = bioModel.getSBMLDocument().getModel().getParameter(GlobalConstants.REVERSE_KACT_STRING).getValue();
LocalParameter ka_f = getChangedParameter(GlobalConstants.FORWARD_KACT_STRING.replace("_","_" + mod + "_"));
LocalParameter ka_r = getChangedParameter(GlobalConstants.REVERSE_KACT_STRING.replace("_","_" + mod + "_"));
if (ka_f != null) {
removeLocalParameter(GlobalConstants.FORWARD_KACT_STRING.replace("_","_" + mod + "_"));
}
if (ka_r != null) {
removeLocalParameter(GlobalConstants.REVERSE_KACT_STRING.replace("_","_" + mod + "_"));
}
if (actBindf!=bindf || actBindr!=bindr) {
addLocalParameter(GlobalConstants.FORWARD_KACT_STRING.replace("_","_" + mod + "_"),actBindf);
addLocalParameter(GlobalConstants.REVERSE_KACT_STRING.replace("_","_" + mod + "_"),actBindr);
}
}
JList add = new JList();
Object[] adding = { mod };
add.setListData(adding);
add.setSelectedIndex(0);
modifiers.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
adding = Utility.add(modifierArray, modifiers, add);
modifierArray = new String[adding.length];
for (int i = 0; i < adding.length; i++) {
modifierArray[i] = (String) adding[i];
}
Utility.sort(modifierArray);
modifiers.setListData(modifierArray);
modifiers.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
try {
if (bioModel.getSBMLDocument().getModel().getReaction(selectedReaction).getModifierCount() == 1) {
modifiers.setSelectedIndex(0);
}
else {
modifiers.setSelectedIndex(index);
}
}
catch (Exception e2) {
modifiers.setSelectedIndex(0);
}
ArraysSBasePlugin sBasePlugin = SBMLutilities.getArraysSBasePlugin(modifier);
for(int i = 0; i<dimID.length-1; i++){
org.sbml.jsbml.ext.arrays.Dimension dimX = sBasePlugin.createDimension(dimensionIds[i]);
dimX.setSize(dimID[i]);
dimX.setArrayDimension(i);
}
for(int i = 0; i<dex.length-1; i++){
Index indexRule = new Index();
indexRule.setArrayDimension(i);
indexRule.setReferencedAttribute("variable");
ASTNode indexMath = SBMLutilities.myParseFormula(dex[i+1]);
indexRule.setMath(indexMath);
sBasePlugin.addIndex(indexRule);
}
}
}
modelEditor.setDirty(true);
bioModel.makeUndoPoint();
if (error) {
value = JOptionPane.showOptionDialog(Gui.frame, modifiersPanel, "Modifiers Editor", JOptionPane.YES_NO_OPTION,
JOptionPane.PLAIN_MESSAGE, null, options, options[0]);
}
}
if (value == JOptionPane.NO_OPTION) {
return;
}
}
/**
* Creates a frame used to edit reactants or create new ones.
*/
public void reactantsEditor(BioModel gcm, String option, String selectedReactantId, SpeciesReference reactant,
boolean inSchematic, Reaction reaction) {
JPanel reactantsPanel;
if (gcm.getSBMLDocument().getLevel() < 3) {
reactantsPanel = new JPanel(new GridLayout(5, 2));
}
else {
reactantsPanel = new JPanel(new GridLayout(6, 2));
}
JLabel reactantIdLabel = new JLabel("Id:");
JLabel reactantNameLabel = new JLabel("Name:");
JLabel speciesLabel = new JLabel("Species:");
Object[] stoiciOptions = { "Stoichiometry", "Stoichiometry Math" };
stoiciLabel = new JComboBox(stoiciOptions);
JLabel stoichiometryLabel = new JLabel("Stoichiometry:");
JLabel constantLabel = new JLabel("Constant:");
Object[] reactantConstantOptions = { "true", "false" };
reactantConstant = new JComboBox(reactantConstantOptions);
ListOf<Species> listOfSpecies = gcm.getSBMLDocument().getModel().getListOfSpecies();
String[] speciesList = new String[gcm.getSBMLDocument().getModel().getSpeciesCount()];
for (int i = 0; i < gcm.getSBMLDocument().getModel().getSpeciesCount(); i++) {
speciesList[i] = listOfSpecies.get(i).getId();
}
Utility.sort(speciesList);
RiIndex = new JTextField(10);
RiIndex.setEnabled(true);
reactantSpecies = new JComboBox();
reactantSpecies.addActionListener(this);
if (inSchematic) {
reactantSpecies.setEnabled(false);
} else {
reactantSpecies.setEnabled(true);
}
// TODO: Scott: if (inSchematic) extract dimensions from reaction else from reaction id field
for (int i = 0; i < speciesList.length; i++) {
Species species = gcm.getSBMLDocument().getModel().getSpecies(speciesList[i]);
if (species.getBoundaryCondition() || (!species.getConstant() && Rules.keepVarRateRule(gcm, "", speciesList[i]))) {
reactantSpecies.addItem(speciesList[i]);
}
}
reactantId = new JTextField("");
reactantName = new JTextField("");
reactantStoichiometry = new JTextField("1");
String selectedID = "";
if (complex!=null) {
double nc = bioModel.getSBMLDocument().getModel().getParameter(GlobalConstants.COOPERATIVITY_STRING).getValue();
reactantStoichiometry.setText(""+nc);
}
if (option.equals("OK")) {
String v = selectedReactantId;
if (reactant == null) {
for (SpeciesReference r : changedReactants) {
if (r.getSpecies().equals(v)) {
reactant = r;
}
}
}
reactantSpecies.setSelectedItem(reactant.getSpecies());
if (reactant.isSetName()) {
reactantName.setText(reactant.getName());
}
reactantStoichiometry.setText("" + reactant.getStoichiometry());
if (reactant.isSetId()) {
selectedID = reactant.getId();
reactantId.setText(reactant.getId());
InitialAssignment init = bioModel.getSBMLDocument().getModel().getInitialAssignment(selectedID);
if (init!=null) {
reactantStoichiometry.setText("" + bioModel.removeBooleans(init.getMath()));
}
}
if (!reactant.getConstant()) {
reactantConstant.setSelectedItem("false");
}
// TODO: Scott - change for Plugin reading
ArraysSBasePlugin sBasePlugin = SBMLutilities.getArraysSBasePlugin(reactant);
String dimInID = "";
for(int i = sBasePlugin.getDimensionCount()-1; i>=0; i
org.sbml.jsbml.ext.arrays.Dimension dimX = sBasePlugin.getDimensionByArrayDimension(i);
dimInID += "[" + dimX.getSize() + "]";
}
reactantId.setText(reactantId.getText()+dimInID);
String freshIndex = "";
for(int i = sBasePlugin.getIndexCount()-1; i>=0; i
Index indie = sBasePlugin.getIndex(i);
freshIndex += "[" + SBMLutilities.myFormulaToString(indie.getMath()) + "]";
}
RiIndex.setText(freshIndex);
if (complex!=null) {
if (complex.getKineticLaw().getLocalParameter(GlobalConstants.COOPERATIVITY_STRING+"_"+selectedID)!=null) {
double nc = complex.getKineticLaw().getLocalParameter(GlobalConstants.COOPERATIVITY_STRING+"_"+selectedID).getValue();
reactantStoichiometry.setText(""+nc);
}
}
}
reactantsPanel.add(reactantIdLabel);
reactantsPanel.add(reactantId);
reactantsPanel.add(reactantNameLabel);
reactantsPanel.add(reactantName);
reactantsPanel.add(speciesLabel);
reactantsPanel.add(reactantSpecies);
reactantsPanel.add(new JLabel("Indices:"));
reactantsPanel.add(RiIndex);
if (gcm.getSBMLDocument().getLevel() < 3) {
reactantsPanel.add(stoiciLabel);
}
else {
reactantsPanel.add(stoichiometryLabel);
}
reactantsPanel.add(reactantStoichiometry);
if (gcm.getSBMLDocument().getLevel() > 2) {
reactantsPanel.add(constantLabel);
reactantsPanel.add(reactantConstant);
}
if (speciesList.length == 0) {
JOptionPane.showMessageDialog(Gui.frame, "There are no species availiable to be reactants." + "\nAdd species to this sbml file first.",
"No Species", JOptionPane.ERROR_MESSAGE);
return;
}
Object[] options = { option, "Cancel" };
int value = JOptionPane.showOptionDialog(Gui.frame, reactantsPanel, "Reactants Editor", JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE,
null, options, options[0]);
String[] dimID = new String[]{""};
String[] dex = new String[]{""};
String[] dimensionIds = new String[]{""};
boolean error = true;
while (error && value == JOptionPane.YES_OPTION) {
error = false;
String react = "";
double val = 1.0;
dimID = SBMLutilities.checkSizeParameters(bioModel.getSBMLDocument(), reactantId.getText(), true);
if(dimID!=null){
dimensionIds = SBMLutilities.getDimensionIds("r",dimID.length-1);
if (dimID[0].trim().equals("")) {
error = SBMLutilities.variableInUse(gcm.getSBMLDocument(), selectedID, false, true, true);
}
else {
error = SBMLutilities.checkID(gcm.getSBMLDocument(), dimID[0].trim(), selectedID, false);
}
}
else{
error = true;
}
if(!error){
SBase variable = SBMLutilities.getElementBySId(bioModel.getSBMLDocument(), (String)reactantSpecies.getSelectedItem());
String test = RiIndex.getText();
dex = SBMLutilities.checkIndices(RiIndex.getText(), variable, bioModel.getSBMLDocument(), dimensionIds, "variable", dimID);
error = (dex==null);
}
if (!error) {
if (stoiciLabel.getSelectedItem().equals("Stoichiometry")) {
InitialAssignments.removeInitialAssignment(bioModel, selectedID);
try {
val = Double.parseDouble(reactantStoichiometry.getText().trim());
}
catch (Exception e1) {
if (reactantId.getText().equals("")) {
JOptionPane.showMessageDialog(Gui.frame, "The stoichiometry must be a real number if no id is provided.", "Enter A Valid Value",
JOptionPane.ERROR_MESSAGE);
error = true;
} else {
// TODO: need sot use reactant dimension when it exists
error = InitialAssignments.addInitialAssignment(bioModel, dimID[0].trim(),
reactantStoichiometry.getText().trim(), dimID);
val = 1.0;
}
}
if (val <= 0) {
JOptionPane.showMessageDialog(Gui.frame, "The stoichiometry value must be greater than 0.", "Enter A Valid Value",
JOptionPane.ERROR_MESSAGE);
error = true;
}
react = reactantSpecies.getSelectedItem() + " " + val;
}
else {
react = reactantSpecies.getSelectedItem() + " " + reactantStoichiometry.getText().trim();
}
}
int index = -1;
if (!error) {
if (reactant == null || !inSchematic) {
if (option.equals("OK")) {
index = reactants.getSelectedIndex();
}
reactants.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
reacta = Utility.getList(reacta, reactants);
reactants.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
if (index >= 0) {
reactants.setSelectedIndex(index);
}
for (int i = 0; i < reacta.length; i++) {
if (i != index) {
if (reacta[i].split(" ")[0].equals(reactantSpecies.getSelectedItem())) {
error = true;
JOptionPane.showMessageDialog(Gui.frame, "Unable to add species as a reactant.\n"
+ "Each species can only be used as a reactant once.", "Species Can Only Be Used Once",
JOptionPane.ERROR_MESSAGE);
}
}
}
}
}
if (!error) {
if (stoiciLabel.getSelectedItem().equals("Stoichiometry Math")) {
if (reactantStoichiometry.getText().trim().equals("")) {
JOptionPane.showMessageDialog(Gui.frame, "Stoichiometry math must have formula.", "Enter Stoichiometry Formula",
JOptionPane.ERROR_MESSAGE);
error = true;
}
else if (SBMLutilities.myParseFormula(reactantStoichiometry.getText().trim()) == null) {
JOptionPane.showMessageDialog(Gui.frame, "Stoichiometry formula is not valid.", "Enter Valid Formula",
JOptionPane.ERROR_MESSAGE);
error = true;
}
else {
ArrayList<String> invalidVars = getInvalidVariablesInReaction(reactantStoichiometry.getText().trim(), dimensionIds, true, "", false);
if (invalidVars.size() > 0) {
String invalid = "";
for (int i = 0; i < invalidVars.size(); i++) {
if (i == invalidVars.size() - 1) {
invalid += invalidVars.get(i);
}
else {
invalid += invalidVars.get(i) + "\n";
}
}
String message;
message = "Stoiciometry math contains unknown variables.\n\n" + "Unknown variables:\n" + invalid;
JTextArea messageArea = new JTextArea(message);
messageArea.setLineWrap(true);
messageArea.setWrapStyleWord(true);
messageArea.setEditable(false);
JScrollPane scrolls = new JScrollPane();
scrolls.setMinimumSize(new Dimension(300, 300));
scrolls.setPreferredSize(new Dimension(300, 300));
scrolls.setViewportView(messageArea);
JOptionPane.showMessageDialog(Gui.frame, scrolls, "Stoiciometry Math Error", JOptionPane.ERROR_MESSAGE);
error = true;
}
if (!error) {
error = SBMLutilities.checkNumFunctionArguments(gcm.getSBMLDocument(),
SBMLutilities.myParseFormula(reactantStoichiometry.getText().trim()));
}
if (!error) {
if (SBMLutilities.returnsBoolean(SBMLutilities.myParseFormula(reactantStoichiometry.getText().trim()), bioModel.getSBMLDocument().getModel())) {
JOptionPane.showMessageDialog(Gui.frame, "Stoichiometry math must evaluate to a number.", "Number Expected",
JOptionPane.ERROR_MESSAGE);
error = true;
}
}
}
}
}
if (!error && option.equals("OK") && reactantConstant.getSelectedItem().equals("true")) {
String id = selectedID;
error = SBMLutilities.checkConstant(gcm.getSBMLDocument(), "Reactant stoiciometry", id);
}
if (!error) {
if (option.equals("OK")) {
String v = selectedReactantId;
SpeciesReference reactan = reactant;
if (reactant == null || !inSchematic) {
for (SpeciesReference r : changedReactants) {
if (r.getSpecies().equals(v)) {
reactan = r;
}
}
reactants.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
reacta = Utility.getList(reacta, reactants);
reactants.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
}
if (reactan==null) return;
reactan.setId(dimID[0].trim());
reactan.setName(reactantName.getText().trim());
reactan.setSpecies((String) reactantSpecies.getSelectedItem());
reactan.setStoichiometry(val);
if (complex!=null) {
double nc = bioModel.getSBMLDocument().getModel().getParameter(GlobalConstants.COOPERATIVITY_STRING).getValue();
String ncStr = GlobalConstants.COOPERATIVITY_STRING+"_"+reactan.getSpecies();
LocalParameter paramet = null;
for (LocalParameter p : changedParameters) {
if (p.getId().equals(ncStr)) {
paramet = p;
}
}
if (nc==val) {
if (paramet != null) {
removeLocalParameter(ncStr);
}
} else {
if (paramet != null) {
removeLocalParameter(ncStr);
addLocalParameter(GlobalConstants.COOPERATIVITY_STRING+"_"+reactan.getSpecies(),val);
} else {
addLocalParameter(GlobalConstants.COOPERATIVITY_STRING+"_"+reactan.getSpecies(),val);
}
}
}
if (reactantConstant.getSelectedItem().equals("true")) {
reactan.setConstant(true);
}
else {
reactan.setConstant(false);
}
// TODO: Scott - change for Plugin writing
if(!error){
ArraysSBasePlugin sBasePlugin = SBMLutilities.getArraysSBasePlugin(reactan);
sBasePlugin.unsetListOfDimensions();
for(int i = 0; i<dimID.length-1; i++){
org.sbml.jsbml.ext.arrays.Dimension dimX = sBasePlugin.createDimension(dimensionIds[i]);
dimX.setSize(dimID[i+1]);
dimX.setArrayDimension(i);
}
// Add the indices
sBasePlugin.unsetListOfIndices();
for(int i = 0; i<dex.length-1; i++){
Index indexRule = new Index();
indexRule.setArrayDimension(i);
indexRule.setReferencedAttribute("variable");
ASTNode indexMath = SBMLutilities.myParseFormula(dex[i+1]);
indexRule.setMath(indexMath);
sBasePlugin.addIndex(indexRule);
}
}
if (reactant == null || !inSchematic) {
reacta[index] = react;
Utility.sort(reacta);
reactants.setListData(reacta);
reactants.setSelectedIndex(index);
}
SBMLutilities.updateVarId(gcm.getSBMLDocument(), false, selectedID, dimID[0].trim());
if (reactant == null || !inSchematic) {
kineticLaw.setText(SBMLutilities.updateFormulaVar(kineticLaw.getText().trim(), selectedID, dimID[0].trim()));
}
}
else {
// SpeciesReference reactan = new
// SpeciesReference(BioSim.SBML_LEVEL, BioSim.SBML_VERSION);
SpeciesReference reactan = new SpeciesReference(gcm.getSBMLDocument().getLevel(), gcm.getSBMLDocument().getVersion());
reactan.setId(dimID[0].trim());
reactan.setName(reactantName.getText().trim());
reactan.setConstant(true);
changedReactants.add(reactan);
reactan.setSpecies((String) reactantSpecies.getSelectedItem());
reactan.setStoichiometry(val);
if (complex!=null) {
double nc = bioModel.getSBMLDocument().getModel().getParameter(GlobalConstants.COOPERATIVITY_STRING).getValue();
String ncStr = GlobalConstants.COOPERATIVITY_STRING+"_"+reactan.getSpecies();
LocalParameter paramet = null;
for (LocalParameter p : changedParameters) {
if (p.getId().equals(ncStr)) {
paramet = p;
}
}
if (nc==val) {
if (paramet != null) {
removeLocalParameter(ncStr);
}
} else {
if (paramet != null) {
removeLocalParameter(ncStr);
addLocalParameter(GlobalConstants.COOPERATIVITY_STRING+"_"+reactan.getSpecies(),val);
} else {
addLocalParameter(GlobalConstants.COOPERATIVITY_STRING+"_"+reactan.getSpecies(),val);
}
}
}
if (reactantConstant.getSelectedItem().equals("true")) {
reactan.setConstant(true);
}
else {
reactan.setConstant(false);
}
// TODO: Scott - change for Plugin writing
if(!error){
ArraysSBasePlugin sBasePlugin = SBMLutilities.getArraysSBasePlugin(reactan);
for(int i = 0; i<dimID.length-1; i++){
org.sbml.jsbml.ext.arrays.Dimension dimX = sBasePlugin.createDimension(dimensionIds[i]);
dimX.setSize(dimID[i+1]);
dimX.setArrayDimension(i);
}
// Add the indices
for(int i = 0; i<dex.length-1; i++){
Index indexRule = new Index();
indexRule.setArrayDimension(i);
indexRule.setReferencedAttribute("variable");
ASTNode indexMath = SBMLutilities.myParseFormula(dex[i+1]);
indexRule.setMath(indexMath);
sBasePlugin.addIndex(indexRule);
}
}
JList add = new JList();
Object[] adding = { react };
add.setListData(adding);
add.setSelectedIndex(0);
reactants.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
adding = Utility.add(reacta, reactants, add);
reacta = new String[adding.length];
for (int i = 0; i < adding.length; i++) {
reacta[i] = (String) adding[i];
}
Utility.sort(reacta);
reactants.setListData(reacta);
reactants.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
reactants.setSelectedIndex(0);
}
modelEditor.setDirty(true);
gcm.makeUndoPoint();
}
if (error) {
value = JOptionPane.showOptionDialog(Gui.frame, reactantsPanel, "Reactants Editor", JOptionPane.YES_NO_OPTION,
JOptionPane.PLAIN_MESSAGE, null, options, options[0]);
}
}
if (value == JOptionPane.NO_OPTION) {
return;
}
}
/**
* Remove a reaction
*/
private void removeReaction() {
int index = reactions.getSelectedIndex();
if (index != -1) {
String selected = ((String) reactions.getSelectedValue()).split(" ")[0];
Reaction reaction = bioModel.getSBMLDocument().getModel().getReaction(selected);
if (BioModel.isProductionReaction(reaction)) {
bioModel.removePromoter(selected.replace("Production_", ""));
} else {
bioModel.removeReaction(selected);
reactions.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
reacts = (String[]) Utility.remove(reactions, reacts);
reactions.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
if (index < reactions.getModel().getSize()) {
reactions.setSelectedIndex(index);
}
else {
reactions.setSelectedIndex(index - 1);
}
}
modelEditor.setDirty(true);
bioModel.makeUndoPoint();
}
}
/**
* Remove the reaction
*/
public static void removeTheReaction(BioModel gcm, String selected) {
Reaction tempReaction = gcm.getSBMLDocument().getModel().getReaction(selected);
ListOf<Reaction> r = gcm.getSBMLDocument().getModel().getListOfReactions();
for (int i = 0; i < gcm.getSBMLDocument().getModel().getReactionCount(); i++) {
if (r.get(i).getId().equals(tempReaction.getId())) {
r.remove(i);
}
}
}
/**
* Remove a reactant from a reaction
*/
private void removeReactant() {
int index = reactants.getSelectedIndex();
if (index != -1) {
String v = ((String) reactants.getSelectedValue()).split(" ")[0];
for (int i = 0; i < changedReactants.size(); i++) {
if (changedReactants.get(i).getSpecies().equals(v) &&
!SBMLutilities.variableInUse(bioModel.getSBMLDocument(), changedReactants.get(i).getId(), false, true,true)) {
changedReactants.remove(i);
reactants.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
reacta = (String[]) Utility.remove(reactants, reacta);
reactants.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
if (index < reactants.getModel().getSize()) {
reactants.setSelectedIndex(index);
}
else {
reactants.setSelectedIndex(index - 1);
}
modelEditor.setDirty(true);
bioModel.makeUndoPoint();
}
}
}
}
/**
* Remove a product from a reaction
*/
private void removeProduct() {
int index = products.getSelectedIndex();
if (index != -1) {
String v = ((String) products.getSelectedValue()).split(" ")[0];
for (int i = 0; i < changedProducts.size(); i++) {
if (changedProducts.get(i).getSpecies().equals(v) &&
!SBMLutilities.variableInUse(bioModel.getSBMLDocument(), changedProducts.get(i).getId(), false, true, true)) {
changedProducts.remove(i);
products.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
proda = (String[]) Utility.remove(products, proda);
products.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
if (index < products.getModel().getSize()) {
products.setSelectedIndex(index);
}
else {
products.setSelectedIndex(index - 1);
}
modelEditor.setDirty(true);
bioModel.makeUndoPoint();
}
}
}
}
/**
* Remove a modifier from a reaction
*/
private void removeModifier() {
int index = modifiers.getSelectedIndex();
if (index != -1) {
String v = ((String) modifiers.getSelectedValue()).split(" ")[0];
for (int i = 0; i < changedModifiers.size(); i++) {
if (changedModifiers.get(i).getSpecies().equals(v)) {
if (!changedModifiers.get(i).isSetSBOTerm() ||
changedModifiers.get(i).getSBOTerm()!=GlobalConstants.SBO_PROMOTER_MODIFIER) {
changedModifiers.remove(i);
} else {
return;
}
}
}
modifiers.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
modifierArray = (String[]) Utility.remove(modifiers, modifierArray);
modifiers.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
if (index < modifiers.getModel().getSize()) {
modifiers.setSelectedIndex(index);
}
else {
modifiers.setSelectedIndex(index - 1);
}
modelEditor.setDirty(true);
bioModel.makeUndoPoint();
}
}
private static String indexedSpeciesRef(SimpleSpeciesReference reference) {
String result = reference.getSpecies();
ArraysSBasePlugin sBasePlugin = SBMLutilities.getArraysSBasePlugin(reference);
for(int i = sBasePlugin.getIndexCount()-1; i>=0; i
Index index = sBasePlugin.getIndex(i);
result += "[" + SBMLutilities.myFormulaToString(index.getMath()) + "]";
}
return result;
}
private static String indexedSpeciesRefId(SimpleSpeciesReference reference) {
String result = reference.getId();
ArraysSBasePlugin sBasePlugin = SBMLutilities.getArraysSBasePlugin(reference);
for(int i = sBasePlugin.getIndexCount()-1; i>=0; i
Index index = sBasePlugin.getIndex(i);
result += "[" + SBMLutilities.myFormulaToString(index.getMath()) + "]";
}
return result;
}
/**
* Remove a function if not in use
*/
private void useMassAction() {
String kf;
String kr;
if (changedParameters.size() == 0) {
JOptionPane.showMessageDialog(Gui.frame, "Unable to create mass action kinetic law.\n"
+ "Requires at least one local parameter.", "Unable to Create Kinetic Law",
JOptionPane.ERROR_MESSAGE);
return;
}
else if (changedParameters.size() == 1) {
kf = changedParameters.get(0).getId();
kr = changedParameters.get(0).getId();
}
else {
kf = changedParameters.get(0).getId();
kr = changedParameters.get(1).getId();
}
String kinetic = kf;
boolean addEquil = false;
String equilExpr = "";
for (SpeciesReference s : changedReactants) {
if (SBMLutilities.getArraysSBasePlugin(s).getDimensionCount()>0) {
JOptionPane.showMessageDialog(Gui.frame, "Unable to create mass action kinetic law.\n"
+ "Dimensions on species references not currently supported for use mass action button.", "Unable to Create Kinetic Law",
JOptionPane.ERROR_MESSAGE);
return;
}
if (s.isSetId()) {
addEquil = true;
equilExpr += indexedSpeciesRefId(s);
}
else {
equilExpr += s.getStoichiometry();
}
}
if (addEquil) {
kinetic += " * pow(" + kf + "/" + kr + "," + equilExpr + "-2)";
}
for (SpeciesReference s : changedReactants) {
if (s.isSetId()) {
kinetic += " * pow(" + indexedSpeciesRef(s) + ", " + indexedSpeciesRefId(s) + ")";
}
else {
if (s.getStoichiometry() == 1) {
kinetic += " * " + indexedSpeciesRef(s);
}
else {
kinetic += " * pow(" + indexedSpeciesRef(s) + ", " + s.getStoichiometry() + ")";
}
}
}
for (ModifierSpeciesReference s : changedModifiers) {
if (SBMLutilities.getArraysSBasePlugin(s).getDimensionCount()>0) {
JOptionPane.showMessageDialog(Gui.frame, "Unable to create mass action kinetic law.\n"
+ "Dimensions on species references not currently supported for use mass action button.", "Unable to Create Kinetic Law",
JOptionPane.ERROR_MESSAGE);
return;
}
kinetic += " * " + indexedSpeciesRef(s);
}
if (reacReverse.getSelectedItem().equals("true")) {
kinetic += " - " + kr;
addEquil = false;
equilExpr = "";
for (SpeciesReference s : changedProducts) {
if (SBMLutilities.getArraysSBasePlugin(s).getDimensionCount()>0) {
JOptionPane.showMessageDialog(Gui.frame, "Unable to create mass action kinetic law.\n"
+ "Dimensions on species references not currently supported for use mass action button.", "Unable to Create Kinetic Law",
JOptionPane.ERROR_MESSAGE);
return;
}
if (s.isSetId()) {
addEquil = true;
equilExpr += indexedSpeciesRefId(s);
}
else {
equilExpr += s.getStoichiometry();
}
}
if (addEquil) {
kinetic += " * pow(" + kf + "/" + kr + "," + equilExpr + "-1)";
}
for (SpeciesReference s : changedProducts) {
if (s.isSetId()) {
kinetic += " * pow(" + indexedSpeciesRef(s) + ", " + indexedSpeciesRefId(s) + ")";
}
else {
if (s.getStoichiometry() == 1) {
kinetic += " * " + indexedSpeciesRef(s);
}
else {
kinetic += " * pow(" + indexedSpeciesRef(s) + ", " + s.getStoichiometry() + ")";
}
}
}
for (ModifierSpeciesReference s : changedModifiers) {
kinetic += " * " + indexedSpeciesRef(s);
}
}
kineticLaw.setText(kinetic);
modelEditor.setDirty(true);
bioModel.makeUndoPoint();
}
/**
* Remove a reaction parameter, if allowed
*/
private void reacRemoveParam() {
int index = reacParameters.getSelectedIndex();
if (index != -1) {
String v = ((String) reacParameters.getSelectedValue()).split(" ")[0];
if (reactions.getSelectedIndex() != -1) {
String kinetic = kineticLaw.getText().trim();
String[] vars = new String[0];
if (!kinetic.equals("")) {
vars = SBMLutilities.myFormulaToString(SBMLutilities.myParseFormula(kineticLaw.getText().trim())).split(" |\\(|\\)|\\,");
}
for (int j = 0; j < vars.length; j++) {
if (vars[j].equals(v)) {
JOptionPane.showMessageDialog(Gui.frame, "Cannot remove reaction parameter because it is used in the kinetic law.",
"Cannot Remove Parameter", JOptionPane.ERROR_MESSAGE);
return;
}
}
}
for (int i = 0; i < changedParameters.size(); i++) {
if (changedParameters.get(i).getId().equals(v)) {
changedParameters.remove(i);
}
}
thisReactionParams.remove(v);
reacParameters.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
reacParams = (String[]) Utility.remove(reacParameters, reacParams);
reacParameters.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
if (index < reacParameters.getModel().getSize()) {
reacParameters.setSelectedIndex(index);
}
else {
reacParameters.setSelectedIndex(index - 1);
}
modelEditor.setDirty(true);
bioModel.makeUndoPoint();
}
}
private void removeLocalParameter(String v) {
for (int i = 0; i < reacParameters.getModel().getSize(); i++) {
if (((String)reacParameters.getModel().getElementAt(i)).split(" ")[0].equals(v)) {
reacParameters.setSelectedIndex(i);
break;
}
}
for (int i = 0; i < changedParameters.size(); i++) {
if (changedParameters.get(i).getId().equals(v)) {
changedParameters.remove(i);
}
}
thisReactionParams.remove(v);
reacParameters.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
reacParams = (String[]) Utility.remove(reacParameters, reacParams);
reacParameters.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
reacParameters.setSelectedIndex(0);
modelEditor.setDirty(true);
bioModel.makeUndoPoint();
}
/**
* Check the units of a kinetic law
*/
public boolean checkKineticLawUnits(KineticLaw law) {
if (law.containsUndeclaredUnits()) {
if (Gui.getCheckUndeclared()) {
JOptionPane.showMessageDialog(Gui.frame, "Kinetic law contains literals numbers or parameters with undeclared units.\n"
+ "Therefore, it is not possible to completely verify the consistency of the units.", "Contains Undeclared Units",
JOptionPane.WARNING_MESSAGE);
}
return false;
}
else if (Gui.getCheckUnits()) {
if (SBMLutilities.checkUnitsInKineticLaw(bioModel.getSBMLDocument(), law)) {
JOptionPane.showMessageDialog(Gui.frame, "Kinetic law units should be substance / time.", "Units Do Not Match",
JOptionPane.ERROR_MESSAGE);
return true;
}
}
return false;
}
/**
* Checks the string to see if there are any errors. Retruns true if there are no errors, else returns false.
*/
public boolean fluxBoundisGood(String s, String reactionId){
if(s.contains("<=")){
String [] correctnessTest = s.split("<=");
if(correctnessTest.length == 3){
try{
Double.parseDouble(correctnessTest[0]);
}
catch(NumberFormatException e){
JOptionPane.showMessageDialog(Gui.frame, correctnessTest[0]+ " has to be a double.",
"Incorrect Element", JOptionPane.ERROR_MESSAGE);
return false;
}
try{
Double.parseDouble(correctnessTest[2]);
}
catch(NumberFormatException e){
JOptionPane.showMessageDialog(Gui.frame, correctnessTest[2] + " has to be a double.",
"Incorrect Element", JOptionPane.ERROR_MESSAGE);
return false;
}
if(Double.parseDouble(correctnessTest[0]) > Double.parseDouble(correctnessTest[2])){
JOptionPane.showMessageDialog(Gui.frame, correctnessTest[0] + " must be less than " + correctnessTest[2],
"Imbalance with Bounds", JOptionPane.ERROR_MESSAGE);
return false;
}
return true;
}
else if(correctnessTest.length == 2){
if(!correctnessTest[0].equals(reactionId) && !correctnessTest[1].equals(reactionId)){
JOptionPane.showMessageDialog(Gui.frame, "Must have "+ reactionId + " in the equation.", "No Reaction",
JOptionPane.ERROR_MESSAGE);
return false;
}
if(correctnessTest[0].equals(reactionId)){
try{
Double.parseDouble(correctnessTest[1]);
}
catch(Exception e){
if(e.equals(new NumberFormatException())){
JOptionPane.showMessageDialog(Gui.frame, correctnessTest[1] + " has to be a double.", "Incorrect Element",
JOptionPane.ERROR_MESSAGE);
return false;
}
}
}
else{
try{
Double.parseDouble(correctnessTest[0]);
}
catch(Exception e){
if(e.equals(new NumberFormatException())){
JOptionPane.showMessageDialog(Gui.frame, correctnessTest[0] + " has to be a double.", "Incorrect Element",
JOptionPane.ERROR_MESSAGE);
return false;
}
}
}
return true;
} else{
JOptionPane.showMessageDialog(Gui.frame, "Wrong number of elements.", "Bad Format",
JOptionPane.ERROR_MESSAGE);
return false;
}
}
else if(s.contains(">=")){
String [] correctnessTest = s.split(">=");
if(correctnessTest.length == 3){
try{
Double.parseDouble(correctnessTest[0]);
}
catch(NumberFormatException e){
JOptionPane.showMessageDialog(Gui.frame, correctnessTest[0]+ " has to be a double.",
"Incorrect Element", JOptionPane.ERROR_MESSAGE);
return false;
}
try{
Double.parseDouble(correctnessTest[2]);
}
catch(NumberFormatException e){
JOptionPane.showMessageDialog(Gui.frame, correctnessTest[2] + " has to be a double.",
"Incorrect Element", JOptionPane.ERROR_MESSAGE);
return false;
}
if(Double.parseDouble(correctnessTest[0]) < Double.parseDouble(correctnessTest[2])){
JOptionPane.showMessageDialog(Gui.frame, correctnessTest[0] + " must be greater than " + correctnessTest[2],
"Imbalance with Bounds", JOptionPane.ERROR_MESSAGE);
return false;
}
return true;
}
else if(correctnessTest.length == 2){
if(!correctnessTest[0].equals(reactionId) && !correctnessTest[1].equals(reactionId)){
JOptionPane.showMessageDialog(Gui.frame, "Must have "+ reactionId + " in the equation.", "No Reaction",
JOptionPane.ERROR_MESSAGE);
return false;
}
if(correctnessTest[0].equals(reactionId)){
try{
Double.parseDouble(correctnessTest[1]);
}
catch(Exception e){
if(e.equals(new NumberFormatException())){
JOptionPane.showMessageDialog(Gui.frame, correctnessTest[1] + " has to be a double.", "Incorrect Element",
JOptionPane.ERROR_MESSAGE);
return false;
}
}
}
else{
try{
Double.parseDouble(correctnessTest[0]);
}
catch(Exception e){
if(e.equals(new NumberFormatException())){
JOptionPane.showMessageDialog(Gui.frame, correctnessTest[0] + " has to be a double.", "Incorrect Element",
JOptionPane.ERROR_MESSAGE);
return false;
}
}
}
return true;
} else{
JOptionPane.showMessageDialog(Gui.frame, "Wrong number of elements.", "Bad Format",
JOptionPane.ERROR_MESSAGE);
return false;
}
}
else if(s.contains("=")){
String [] correctnessTest = s.split("=");
if(correctnessTest.length == 2){
if(!correctnessTest[0].equals(reactionId) && !correctnessTest[1].equals(reactionId)){
JOptionPane.showMessageDialog(Gui.frame, "Must have "+ reactionId + " in the equation.", "No Reaction",
JOptionPane.ERROR_MESSAGE);
return false;
}
if(correctnessTest[0].equals(reactionId)){
try{
Double.parseDouble(correctnessTest[1]);
}
catch(Exception e){
if(e.equals(new NumberFormatException())){
JOptionPane.showMessageDialog(Gui.frame, correctnessTest[1] + " has to be a double.", "Incorrect Element",
JOptionPane.ERROR_MESSAGE);
return false;
}
}
}
else{
try{
Double.parseDouble(correctnessTest[0]);
}
catch(Exception e){
if(e.equals(new NumberFormatException())){
JOptionPane.showMessageDialog(Gui.frame, correctnessTest[0] + " has to be a double.", "Incorrect Element",
JOptionPane.ERROR_MESSAGE);
return false;
}
}
}
return true;
} else{
JOptionPane.showMessageDialog(Gui.frame, "Wrong number of elements.", "Bad Format",
JOptionPane.ERROR_MESSAGE);
return false;
}
}
else{
JOptionPane.showMessageDialog(Gui.frame, "Need Operations.", "Bad Format",
JOptionPane.ERROR_MESSAGE);
return false;
}
}
public void setPanels(InitialAssignments initialsPanel, Rules rulesPanel) {
this.initialsPanel = initialsPanel;
this.rulesPanel = rulesPanel;
}
@Override
public void actionPerformed(ActionEvent e) {
// if the add compartment type button is clicked
// if the add species type button is clicked
// if the add compartment button is clicked
// if the add parameters button is clicked
// if the add reactions button is clicked
if (e.getSource() == addReac) {
reactionsEditor(bioModel, "Add", "", false);
}
// if the edit reactions button is clicked
else if (e.getSource() == editReac) {
if (reactions.getSelectedIndex() == -1) {
JOptionPane.showMessageDialog(Gui.frame, "No reaction selected.", "Must Select A Reaction", JOptionPane.ERROR_MESSAGE);
return;
}
reactionsEditor(bioModel, "OK", ((String) reactions.getSelectedValue()).split(" ")[0], false);
initialsPanel.refreshInitialAssignmentPanel(bioModel);
rulesPanel.refreshRulesPanel();
}
// if the remove reactions button is clicked
else if (e.getSource() == removeReac) {
removeReaction();
}
// if the add reactions parameters button is clicked
else if (e.getSource() == reacAddParam) {
reacParametersEditor(bioModel,"Add");
}
// if the edit reactions parameters button is clicked
else if (e.getSource() == reacEditParam) {
reacParametersEditor(bioModel,"OK");
}
// if the remove reactions parameters button is clicked
else if (e.getSource() == reacRemoveParam) {
reacRemoveParam();
}
// if the add reactants button is clicked
else if (e.getSource() == addReactant) {
reactantsEditor(bioModel, "Add", "", null, false, null);
}
// if the edit reactants button is clicked
else if (e.getSource() == editReactant) {
if (reactants.getSelectedIndex() == -1) {
JOptionPane.showMessageDialog(Gui.frame, "No reactant selected.", "Must Select A Reactant", JOptionPane.ERROR_MESSAGE);
return;
}
reactantsEditor(bioModel, "OK", ((String) reactants.getSelectedValue()).split(" ")[0], null, false, null);
initialsPanel.refreshInitialAssignmentPanel(bioModel);
rulesPanel.refreshRulesPanel();
}
// if the remove reactants button is clicked
else if (e.getSource() == removeReactant) {
removeReactant();
}
// if the add products button is clicked
else if (e.getSource() == addProduct) {
productsEditor(bioModel, "Add", "", null, false);
}
// if the edit products button is clicked
else if (e.getSource() == editProduct) {
if (products.getSelectedIndex() == -1) {
JOptionPane.showMessageDialog(Gui.frame, "No product selected.", "Must Select A Product", JOptionPane.ERROR_MESSAGE);
return;
}
productsEditor(bioModel, "OK", ((String) products.getSelectedValue()).split(" ")[0], null, false);
initialsPanel.refreshInitialAssignmentPanel(bioModel);
rulesPanel.refreshRulesPanel();
}
// if the remove products button is clicked
else if (e.getSource() == removeProduct) {
removeProduct();
}
// if the add modifiers button is clicked
else if (e.getSource() == addModifier) {
modifiersEditor(bioModel, "Add", "", null, false);
}
// if the edit modifiers button is clicked
else if (e.getSource() == editModifier) {
if (modifiers.getSelectedIndex() == -1) {
JOptionPane.showMessageDialog(Gui.frame, "No modifier selected.", "Must Select A Modifier", JOptionPane.ERROR_MESSAGE);
return;
}
modifiersEditor(bioModel,"OK", ((String) modifiers.getSelectedValue()).split(" ")[0], null, false);
}
// if the remove modifiers button is clicked
else if (e.getSource() == removeModifier) {
removeModifier();
}
// if the clear button is clicked
else if (e.getSource() == clearKineticLaw) {
kineticLaw.setText("");
modelEditor.setDirty(true);
bioModel.makeUndoPoint();
}
// if the use mass action button is clicked
else if (e.getSource() == useMassAction) {
useMassAction();
}
}
@Override
public void mouseClicked(MouseEvent e) {
if (e.getClickCount() == 2) {
if (e.getSource() == reactions) {
if (reactions.getSelectedIndex() == -1) {
JOptionPane.showMessageDialog(Gui.frame, "No reaction selected.", "Must Select A Reaction", JOptionPane.ERROR_MESSAGE);
return;
}
reactionsEditor(bioModel, "OK", ((String) reactions.getSelectedValue()).split(" ")[0], false);
initialsPanel.refreshInitialAssignmentPanel(bioModel);
rulesPanel.refreshRulesPanel();
}
else if (e.getSource() == reacParameters) {
reacParametersEditor(bioModel,"OK");
}
else if (e.getSource() == reactants) {
if (!paramsOnly) {
if (reactants.getSelectedIndex() == -1) {
JOptionPane.showMessageDialog(Gui.frame, "No reactant selected.", "Must Select A Reactant", JOptionPane.ERROR_MESSAGE);
return;
}
reactantsEditor(bioModel, "OK", ((String) reactants.getSelectedValue()).split(" ")[0], null, false, null);
initialsPanel.refreshInitialAssignmentPanel(bioModel);
rulesPanel.refreshRulesPanel();
}
}
else if (e.getSource() == products) {
if (!paramsOnly) {
if (products.getSelectedIndex() == -1) {
JOptionPane.showMessageDialog(Gui.frame, "No product selected.", "Must Select A Product", JOptionPane.ERROR_MESSAGE);
return;
}
productsEditor(bioModel, "OK", ((String) products.getSelectedValue()).split(" ")[0], null, false);
initialsPanel.refreshInitialAssignmentPanel(bioModel);
rulesPanel.refreshRulesPanel();
}
}
else if (e.getSource() == modifiers) {
if (!paramsOnly) {
if (modifiers.getSelectedIndex() == -1) {
JOptionPane.showMessageDialog(Gui.frame, "No modifier selected.", "Must Select A Modifier", JOptionPane.ERROR_MESSAGE);
return;
}
modifiersEditor(bioModel,"OK", ((String) modifiers.getSelectedValue()).split(" ")[0], null, false);
}
}
}
}
/**
* Refresh reaction panel
*/
public void refreshReactionPanel(BioModel gcm) {
String selectedReactionId = "";
if (!reactions.isSelectionEmpty()) {
selectedReactionId = ((String) reactions.getSelectedValue()).split(" ")[0];
}
this.bioModel = gcm;
Model model = gcm.getSBMLDocument().getModel();
ListOf<Reaction> listOfReactions = model.getListOfReactions();
reacts = new String[model.getReactionCount()];
for (int i = 0; i < model.getReactionCount(); i++) {
Reaction reaction = listOfReactions.get(i);
reacts[i] = reaction.getId();
if (paramsOnly) {
if (!reaction.isSetKineticLaw()) continue;
ListOf<LocalParameter> params = reaction.getKineticLaw().getListOfLocalParameters();
for (int j = 0; j < reaction.getKineticLaw().getLocalParameterCount(); j++) {
LocalParameter paramet = (params.get(j));
for (int k = 0; k < parameterChanges.size(); k++) {
if (parameterChanges.get(k).split(" ")[0].equals(reaction.getId() + "/" + paramet.getId())) {
String[] splits = parameterChanges.get(k).split(" ");
if (splits[splits.length - 2].equals("Modified") || splits[splits.length - 2].equals("Custom")) {
String value = splits[splits.length - 1];
paramet.setValue(Double.parseDouble(value));
}
else if (splits[splits.length - 2].equals("Sweep")) {
String value = splits[splits.length - 1];
paramet.setValue(Double.parseDouble(value.split(",")[0].substring(1).trim()));
}
if (!reacts[i].contains("Modified")) {
reacts[i] += " Modified";
}
}
}
}
}
}
Utility.sort(reacts);
int selected = 0;
for (int i = 0; i < reacts.length; i++) {
if (reacts[i].split(" ")[0].equals(selectedReactionId)) {
selected = i;
}
}
reactions.setListData(reacts);
reactions.setSelectedIndex(selected);
}
/**
* This method currently does nothing.
*/
@Override
public void mouseEntered(MouseEvent e) {
}
/**
* This method currently does nothing.
*/
@Override
public void mouseExited(MouseEvent e) {
}
/**
* This method currently does nothing.
*/
@Override
public void mousePressed(MouseEvent e) {
}
/**
* This method currently does nothing.
*/
@Override
public void mouseReleased(MouseEvent e) {
}
}
|
package org.nextrtc.signalingserver.domain;
import static org.apache.commons.lang3.StringUtils.EMPTY;
import static org.hamcrest.Matchers.is;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import static org.nextrtc.signalingserver.api.annotation.NextRTCEvents.CONVERSATION_CREATED;
import static org.nextrtc.signalingserver.api.annotation.NextRTCEvents.MEMBER_LOCAL_STREAM_CREATED;
import static org.nextrtc.signalingserver.api.annotation.NextRTCEvents.SESSION_STARTED;
import java.util.List;
import javax.websocket.CloseReason;
import javax.websocket.Session;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.nextrtc.signalingserver.BaseTest;
import org.nextrtc.signalingserver.EventChecker;
import org.nextrtc.signalingserver.MessageMatcher;
import org.nextrtc.signalingserver.api.NextRTCEvent;
import org.nextrtc.signalingserver.api.annotation.NextRTCEventListener;
import org.nextrtc.signalingserver.domain.ServerTest.LocalStreamCreated;
import org.nextrtc.signalingserver.domain.ServerTest.ServerEventCheck;
import org.nextrtc.signalingserver.exception.Exceptions;
import org.nextrtc.signalingserver.exception.SignalingException;
import org.nextrtc.signalingserver.repository.Members;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
@ContextConfiguration(classes = { ServerEventCheck.class, LocalStreamCreated.class })
public class ServerTest extends BaseTest {
@NextRTCEventListener({ SESSION_STARTED, CONVERSATION_CREATED })
public static class ServerEventCheck extends EventChecker {
}
@Rule
public ExpectedException expect = ExpectedException.none();
@Autowired
private Server server;
@Autowired
private Members members;
@Autowired
private ServerEventCheck eventCheckerCall;
@Test
public void shouldThrowExceptionWhenMemberDoesntExists() throws Exception {
// given
Session session = mock(Session.class);
when(session.getId()).thenReturn("s1");
// then
expect.expect(SignalingException.class);
expect.expectMessage(Exceptions.MEMBER_NOT_FOUND.name());
// when
server.handle(mock(Message.class), session);
}
@Test
public void shouldRegisterUserOnWebSocketConnection() throws Exception {
// given
Session session = mock(Session.class);
when(session.getId()).thenReturn("s1");
// when
server.register(session);
// then
assertTrue(members.findBy("s1").isPresent());
}
@Test
public void shouldCreateConversationOnCreateSignal() throws Exception {
// given
Session session = mockSession("s1");
server.register(session);
// when
server.handle(Message.create()
.signal("create")
.build(), session);
// then
List<NextRTCEvent> events = eventCheckerCall.getEvents();
assertThat(events.size(), is(2));
}
@Test
public void shouldCreateConversation() throws Exception {
// given
MessageMatcher s1Matcher = new MessageMatcher();
MessageMatcher s2Matcher = new MessageMatcher();
Session s1 = mockSession("s1", s1Matcher);
Session s2 = mockSession("s2", s2Matcher);
server.register(s1);
server.register(s2);
// when
server.handle(Message.create()
.signal("create")
.build(), s1);
// then
assertThat(s1Matcher.getMessages().size(), is(1));
assertThat(s1Matcher.getMessage().getSignal(), is("created"));
assertThat(s2Matcher.getMessages().size(), is(0));
}
@Test
public void shouldCreateConversationThenJoinAndSendOfferRequest() throws Exception {
// given
MessageMatcher s1Matcher = new MessageMatcher();
MessageMatcher s2Matcher = new MessageMatcher();
Session s1 = mockSession("s1", s1Matcher);
Session s2 = mockSession("s2", s2Matcher);
server.register(s1);
server.register(s2);
// when
server.handle(Message.create()
.signal("create")
.build(), s1);
String conversationKey = s1Matcher.getMessage().getContent();
// s1Matcher.reset();
server.handle(Message.create()
.signal("join")
.content(conversationKey)
.build(), s2);
// then
assertThat(s1Matcher.getMessages().size(), is(3));
assertMessage(s1Matcher, 0, EMPTY, "s1", "created", conversationKey);
assertMessage(s1Matcher, 1, "s2", "s1", "joined", EMPTY);
assertMessage(s1Matcher, 2, "s2", "s1", "offerRequest", EMPTY);
assertThat(s2Matcher.getMessages().size(), is(1));
assertMessage(s2Matcher, 0, EMPTY, "s2", "joined", conversationKey);
}
@NextRTCEventListener({ MEMBER_LOCAL_STREAM_CREATED })
public static class LocalStreamCreated extends EventChecker {
}
@Autowired
private LocalStreamCreated eventLocalStream;
@Test
public void shouldCreateConversationJoinMemberAndPassOfferResponseToRestMembers() throws Exception {
// given
MessageMatcher s1Matcher = new MessageMatcher();
MessageMatcher s2Matcher = new MessageMatcher();
Session s1 = mockSession("s1", s1Matcher);
Session s2 = mockSession("s2", s2Matcher);
server.register(s1);
server.register(s2);
server.handle(Message.create()
.signal("create")
.build(), s1);
String conversationKey = s1Matcher.getMessage().getContent();
server.handle(Message.create()
.signal("join")
.content(conversationKey)
.build(), s2);
s1Matcher.reset();
s2Matcher.reset();
// when
// s2 has to create local stream
server.handle(Message.create()
.to("s2")
.signal("offerResponse")
.content("s2 spd")
.build(), s1);
// then
assertThat(s1Matcher.getMessages().size(), is(1));
assertMessage(s1Matcher, 0, "s2", "s1", "answerRequest", "s2 spd");
assertThat(s2Matcher.getMessages().size(), is(0));
}
@Test
public void shouldCreateConversationJoinMemberAndPassOfferResponseToRestTwoMembers() throws Exception {
// given
MessageMatcher s1Matcher = new MessageMatcher();
MessageMatcher s2Matcher = new MessageMatcher();
MessageMatcher s3Matcher = new MessageMatcher();
Session s1 = mockSession("s1", s1Matcher);
Session s2 = mockSession("s2", s2Matcher);
Session s3 = mockSession("s3", s3Matcher);
server.register(s1);
server.register(s2);
server.register(s3);
server.handle(Message.create()
.signal("create")
.build(), s1);
String conversationKey = s1Matcher.getMessage().getContent();
server.handle(Message.create()
.signal("join")
.content(conversationKey)
.build(), s2);
server.handle(Message.create()
.signal("join")
.content(conversationKey)
.build(), s3);
s1Matcher.reset();
s2Matcher.reset();
s3Matcher.reset();
// when
// s2 has to create local stream
server.handle(Message.create()
.to("s1")
.signal("offerResponse")
.content("s2 spd")
.build(), s2);
// s3 has to create local stream
server.handle(Message.create()
.to("s1")
.signal("offerResponse")
.content("s3 spd")
.build(), s3);
// then
assertThat(s1Matcher.getMessages().size(), is(2));
assertMessage(s1Matcher, 0, "s2", "s1", "answerRequest", "s2 spd");
assertMessage(s1Matcher, 1, "s3", "s1", "answerRequest", "s3 spd");
assertThat(s2Matcher.getMessages().size(), is(0));
assertThat(s3Matcher.getMessages().size(), is(0));
}
@Test
public void shouldExchangeSpds() throws Exception {
// given
MessageMatcher s1Matcher = new MessageMatcher();
MessageMatcher s2Matcher = new MessageMatcher();
Session s1 = mockSession("s1", s1Matcher);
Session s2 = mockSession("s2", s2Matcher);
server.register(s1);
server.register(s2);
server.handle(Message.create()
.signal("create")
.build(), s1);
// -> created
String conversationKey = s1Matcher.getMessage().getContent();
server.handle(Message.create()
.signal("join")
.content(conversationKey)
.build(), s2);
// -> joined
// -> offerRequest
server.handle(Message.create()
.to("s1")
.signal("offerResponse")
.content("s2 spd")
.build(), s2);
// -> answerRequest
s1Matcher.reset();
s2Matcher.reset();
// when
server.handle(Message.create()
.to("s2")
.signal("answerResponse")
.content("s1 spd")
.build(), s1);
// then
assertThat(s2Matcher.getMessages().size(), is(1));
assertMessage(s2Matcher, 0, "s1", "s2", "finalize", "s1 spd");
assertThat(s1Matcher.getMessages().size(), is(0));
}
@Test
public void shouldExchangeCandidates() throws Exception {
// given
MessageMatcher s1Matcher = new MessageMatcher();
MessageMatcher s2Matcher = new MessageMatcher();
Session s1 = mockSession("s1", s1Matcher);
Session s2 = mockSession("s2", s2Matcher);
server.register(s1);
server.register(s2);
server.handle(Message.create()
.signal("create")
.build(), s1);
// -> created
String conversationKey = s1Matcher.getMessage().getContent();
server.handle(Message.create()
.signal("join")
.content(conversationKey)
.build(), s2);
// -> joined
// -> offerRequest
server.handle(Message.create()
.to("s1")
.signal("offerResponse")
.content("s2 spd")
.build(), s2);
// -> answerRequest
server.handle(Message.create()
.to("s2")
.signal("answerResponse")
.content("s1 spd")
.build(), s1);
// -> finalize
s1Matcher.reset();
s2Matcher.reset();
server.handle(Message.create()
.to("s1")
.signal("candidate")
.content("candidate s2")
.build(), s2);
server.handle(Message.create()
.to("s2")
.signal("candidate")
.content("candidate s1")
.build(), s1);
// when
// then
assertThat(s1Matcher.getMessages().size(), is(1));
assertMessage(s1Matcher, 0, "s2", "s1", "candidate", "candidate s2");
assertThat(s2Matcher.getMessages().size(), is(1));
assertMessage(s2Matcher, 0, "s1", "s2", "candidate", "candidate s1");
}
@Test
public void shouldUnregisterSession() throws Exception {
// given
MessageMatcher s1Matcher = new MessageMatcher();
MessageMatcher s2Matcher = new MessageMatcher();
Session s1 = mockSession("s1", s1Matcher);
Session s2 = mockSession("s2", s2Matcher);
server.register(s1);
server.register(s2);
server.handle(Message.create()
.signal("create")
.build(), s1);
// -> created
String conversationKey = s1Matcher.getMessage().getContent();
server.handle(Message.create()
.signal("join")
.content(conversationKey)
.build(), s2);
s1Matcher.reset();
s2Matcher.reset();
server.unregister(s1, mock(CloseReason.class));
// when
// then
assertThat(s1Matcher.getMessages().size(), is(0));
assertThat(s2Matcher.getMessages().size(), is(1));
assertMessage(s2Matcher, 0, "s1", "s2", "left", EMPTY);
}
private void assertMessage(MessageMatcher matcher, int number, String from, String to, String signal, String content) {
assertThat(matcher.getMessage(number).getFrom(), is(from));
assertThat(matcher.getMessage(number).getTo(), is(to));
assertThat(matcher.getMessage(number).getSignal(), is(signal));
assertThat(matcher.getMessage(number).getContent(), is(content));
}
@Before
public void resetObjects() {
eventCheckerCall.reset();
eventLocalStream.reset();
members.unregister("s1");
members.unregister("s2");
members.unregister("s3");
}
}
|
package org.sdnplatform.sync.internal;
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.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map.Entry;
import org.junit.After;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import org.sdnplatform.sync.IClosableIterator;
import org.sdnplatform.sync.IInconsistencyResolver;
import org.sdnplatform.sync.IStoreClient;
import org.sdnplatform.sync.IStoreListener;
import org.sdnplatform.sync.IStoreListener.UpdateType;
import org.sdnplatform.sync.ISyncService;
import org.sdnplatform.sync.ISyncService.Scope;
import org.sdnplatform.sync.Versioned;
import org.sdnplatform.sync.error.ObsoleteVersionException;
import org.sdnplatform.sync.internal.config.Node;
import org.sdnplatform.sync.internal.config.PropertyCCProvider;
import org.sdnplatform.sync.internal.store.Key;
import org.sdnplatform.sync.internal.store.TBean;
import org.sdnplatform.sync.internal.util.CryptoUtil;
import org.sdnplatform.sync.internal.version.VectorClock;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import net.floodlightcontroller.core.module.FloodlightModuleContext;
import net.floodlightcontroller.debugcounter.IDebugCounterService;
import net.floodlightcontroller.debugcounter.MockDebugCounterService;
import net.floodlightcontroller.threadpool.IThreadPoolService;
import net.floodlightcontroller.threadpool.ThreadPool;
public class SyncManagerTest {
protected static Logger logger =
LoggerFactory.getLogger(SyncManagerTest.class);
protected FloodlightModuleContext[] moduleContexts;
protected SyncManager[] syncManagers;
protected final static ObjectMapper mapper = new ObjectMapper();
protected String nodeString;
ArrayList<Node> nodes;
ThreadPool tp;
@Rule
public TemporaryFolder keyStoreFolder = new TemporaryFolder();
protected File keyStoreFile;
protected String keyStorePassword = "verysecurepassword";
protected void setupSyncManager(FloodlightModuleContext fmc,
SyncManager syncManager, Node thisNode)
throws Exception {
fmc.addService(IThreadPoolService.class, tp);
fmc.addService(IDebugCounterService.class, new MockDebugCounterService());
fmc.addConfigParam(syncManager, "configProviders",
PropertyCCProvider.class.getName());
fmc.addConfigParam(syncManager, "nodes", nodeString);
fmc.addConfigParam(syncManager, "thisNodeId", ""+thisNode.getNodeId());
fmc.addConfigParam(syncManager, "persistenceEnabled", "false");
fmc.addConfigParam(syncManager, "authScheme", "CHALLENGE_RESPONSE");
fmc.addConfigParam(syncManager, "keyStorePath",
keyStoreFile.getAbsolutePath());
fmc.addConfigParam(syncManager, "keyStorePassword", keyStorePassword);
tp.init(fmc);
syncManager.init(fmc);
tp.startUp(fmc);
syncManager.startUp(fmc);
syncManager.registerStore("global", Scope.GLOBAL);
syncManager.registerStore("local", Scope.LOCAL);
}
@Before
public void setUp() throws Exception {
keyStoreFile = new File(keyStoreFolder.getRoot(),
"keystore.jceks");
CryptoUtil.writeSharedSecret(keyStoreFile.getAbsolutePath(),
keyStorePassword,
CryptoUtil.secureRandom(16));
tp = new ThreadPool();
syncManagers = new SyncManager[4];
moduleContexts = new FloodlightModuleContext[4];
nodes = new ArrayList<>();
nodes.add(new Node("localhost", 40101, (short)1, (short)1));
nodes.add(new Node("localhost", 40102, (short)2, (short)2));
nodes.add(new Node("localhost", 40103, (short)3, (short)1));
nodes.add(new Node("localhost", 40104, (short)4, (short)2));
nodeString = mapper.writeValueAsString(nodes);
for(int i = 0; i < 4; i++) {
moduleContexts[i] = new FloodlightModuleContext();
syncManagers[i] = new SyncManager();
setupSyncManager(moduleContexts[i], syncManagers[i], nodes.get(i));
}
}
@After
public void tearDown() {
tp.getScheduledExecutor().shutdownNow();
tp = null;
if (syncManagers != null) {
for(int i = 0; i < syncManagers.length; i++) {
if (null != syncManagers[i])
syncManagers[i].shutdown();
}
}
syncManagers = null;
}
@Test
public void testBasicOneNode() throws Exception {
AbstractSyncManager sync = syncManagers[0];
IStoreClient<Key, TBean> testClient =
sync.getStoreClient("global", Key.class, TBean.class);
Key k = new Key("com.bigswitch.bigsync.internal", "test");
TBean tb = new TBean("hello", 42);
TBean tb2 = new TBean("hello", 84);
TBean tb3 = new TBean("hello", 126);
assertNotNull(testClient.get(k));
assertNull(testClient.get(k).getValue());
testClient.put(k, tb);
Versioned<TBean> result = testClient.get(k);
assertEquals(result.getValue(), tb);
result.setValue(tb2);
testClient.put(k, result);
try {
result.setValue(tb3);
testClient.put(k, result);
fail("Should get ObsoleteVersionException");
} catch (ObsoleteVersionException e) {
// happy town
}
result = testClient.get(k);
assertEquals(tb2, result.getValue());
}
@Test
public void testIterator() throws Exception {
AbstractSyncManager sync = syncManagers[0];
IStoreClient<Key, TBean> testClient =
sync.getStoreClient("local", Key.class, TBean.class);
HashMap<Key, TBean> testMap = new HashMap<>();
for (int i = 0; i < 100; i++) {
Key k = new Key("com.bigswitch.bigsync.internal", "test" + i);
TBean tb = new TBean("value", i);
testMap.put(k, tb);
testClient.put(k, tb);
}
IClosableIterator<Entry<Key, Versioned<TBean>>> iter =
testClient.entries();
int size = 0;
try {
while (iter.hasNext()) {
Entry<Key, Versioned<TBean>> e = iter.next();
assertEquals(testMap.get(e.getKey()), e.getValue().getValue());
size += 1;
}
} finally {
iter.close();
}
assertEquals(testMap.size(), size);
}
protected static <K, V> Versioned<V> waitForValue(IStoreClient<K, V> client,
K key, V value,
int maxTime,
String clientName)
throws Exception {
Versioned<V> v = null;
long then = System.currentTimeMillis();
while (true) {
v = client.get(key);
if (value != null) {
if (v.getValue() != null && v.getValue().equals(value)) break;
} else {
if (v.getValue() != null) break;
}
if (v.getValue() != null)
logger.info("{}: Value for key {} not yet right: " +
"expected: {}; actual: {}",
new Object[]{clientName, key, value, v.getValue()});
else
logger.info("{}: Value for key {} is null: expected {}",
new Object[]{clientName, key, value});
Thread.sleep(100);
assertTrue(then + maxTime > System.currentTimeMillis());
}
return v;
}
private void waitForFullMesh(int maxTime) throws Exception {
waitForFullMesh(syncManagers, maxTime);
}
protected static void waitForFullMesh(SyncManager[] syncManagers,
int maxTime) throws Exception {
long then = System.currentTimeMillis();
while (true) {
boolean full = true;
for(int i = 0; i < syncManagers.length; i++) {
if (!syncManagers[i].rpcService.isFullyConnected())
full = false;
}
if (full) break;
Thread.sleep(100);
assertTrue(then + maxTime > System.currentTimeMillis());
}
}
private void waitForConnection(SyncManager sm,
short nodeId,
boolean connected,
int maxTime) throws Exception {
long then = System.currentTimeMillis();
while (true) {
if (connected == sm.rpcService.isConnected(nodeId)) break;
Thread.sleep(100);
assertTrue(then + maxTime > System.currentTimeMillis());
}
}
@Test
public void testBasicGlobalSync() throws Exception {
waitForFullMesh(2000);
ArrayList<IStoreClient<String, String>> clients =
new ArrayList<>(syncManagers.length);
// write one value to each node's local interface
for (int i = 0; i < syncManagers.length; i++) {
IStoreClient<String, String> client =
syncManagers[i].getStoreClient("global",
String.class, String.class);
clients.add(client);
client.put("key" + i, ""+i);
}
// verify that we see all the values everywhere
for (int j = 0; j < clients.size(); j++) {
for (int i = 0; i < syncManagers.length; i++) {
waitForValue(clients.get(j), "key" + i, ""+i, 2000, "client"+j);
}
}
}
@Test
public void testBasicLocalSync() throws Exception {
waitForFullMesh(2000);
ArrayList<IStoreClient<String, String>> clients =
new ArrayList<>(syncManagers.length);
// write one value to each node's local interface
for (int i = 0; i < syncManagers.length; i++) {
IStoreClient<String, String> client =
syncManagers[i].getStoreClient("local",
String.class, String.class);
clients.add(client);
client.put("key" + i, ""+i);
}
// verify that we see all the values from each local group at all the
// nodes of that local group
for (int j = 0; j < clients.size(); j++) {
IStoreClient<String, String> client = clients.get(j);
for (int i = 0; i < syncManagers.length; i++) {
if (i % 2 == j % 2)
waitForValue(client, "key" + i, ""+i, 2000, "client"+j);
else {
Versioned<String> v = client.get("key" + i);
if (v.getValue() != null) {
fail("Node " + j + " reading key" + i +
": " + v.getValue());
}
}
}
}
}
@Test
public void testConcurrentWrite() throws Exception {
waitForFullMesh(2000);
// Here we generate concurrent writes and then resolve them using
// a custom inconsistency resolver
IInconsistencyResolver<Versioned<List<String>>> ir =
new IInconsistencyResolver<Versioned<List<String>>>() {
@Override
public List<Versioned<List<String>>>
resolveConflicts(List<Versioned<List<String>>> items) {
VectorClock vc = null;
List<String> strings = new ArrayList<>();
for (Versioned<List<String>> item : items) {
if (vc == null)
vc = (VectorClock)item.getVersion();
else
vc = vc.merge((VectorClock)item.getVersion());
strings.addAll(item.getValue());
}
Versioned<List<String>> v =
new Versioned<>(strings, vc);
return Collections.singletonList(v);
}
};
TypeReference<List<String>> tr = new TypeReference<List<String>>() {};
TypeReference<String> ktr = new TypeReference<String>() {};
IStoreClient<String, List<String>> client0 =
syncManagers[0].getStoreClient("local", ktr, tr, ir);
IStoreClient<String, List<String>> client2 =
syncManagers[2].getStoreClient("local", ktr, tr, ir);
client0.put("key", Collections.singletonList("value"));
Versioned<List<String>> v = client0.get("key");
assertNotNull(v);
// now we generate two writes that are concurrent to each other
// but are both locally after the first write. The result should be
// two non-obsolete lists each containing a single element.
// The inconsistency resolver above will resolve these by merging
// the lists
List<String> comp = new ArrayList<>();
v.setValue(Collections.singletonList("newvalue0"));
comp.add("newvalue0");
client0.put("key", v);
v.setValue(Collections.singletonList("newvalue1"));
comp.add("newvalue1");
client2.put("key", v);
v = waitForValue(client0, "key", comp, 1000, "client0");
// add one more value to the array. Now there will be exactly one
// non-obsolete value
List<String> newlist = new ArrayList<>(v.getValue());
assertEquals(2, newlist.size());
newlist.add("finalvalue");
v.setValue(newlist);
client0.put("key", v);
v = waitForValue(client2, "key", newlist, 2000, "client2");
assertEquals(3, newlist.size());
}
@Ignore("fails in OSS Floodlight; since Sync isn't a focus, disabling for now.")
@Test
public void testReconnect() throws Exception {
IStoreClient<String, String> client0 =
syncManagers[0].getStoreClient("global",
String.class,
String.class);
IStoreClient<String, String> client1 =
syncManagers[1].getStoreClient("global",
String.class, String.class);
IStoreClient<String, String> client2 =
syncManagers[2].getStoreClient("global",
String.class, String.class);
client0.put("key0", "value0");
waitForValue(client2, "key0", "value0", 1000, "client0");
logger.info("Shutting down server ID 1");
syncManagers[0].shutdown();
client1.put("newkey1", "newvalue1");
client2.put("newkey2", "newvalue2");
client1.put("key0", "newvalue0");
client2.put("key2", "newvalue2");
for (int i = 0; i < 500; i++) {
client2.put("largetest" + i, "largetestvalue");
}
logger.info("Initializing server ID 1");
syncManagers[0] = new SyncManager();
setupSyncManager(moduleContexts[0], syncManagers[0], nodes.get(0));
waitForFullMesh(2000);
client0 = syncManagers[0].getStoreClient("global",
String.class, String.class);
waitForValue(client0, "newkey1", "newvalue1", 1000, "client0");
waitForValue(client0, "newkey2", "newvalue2", 1000, "client0");
waitForValue(client0, "key0", "newvalue0", 1000, "client0");
waitForValue(client0, "key2", "newvalue2", 1000, "client0");
for (int i = 0; i < 500; i++) {
waitForValue(client0, "largetest" + i,
"largetestvalue", 1000, "client0");
}
}
protected class Update {
String key;
UpdateType type;
public Update(String key, UpdateType type) {
super();
this.key = key;
this.type = type;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + getOuterType().hashCode();
result = prime * result + ((key == null) ? 0 : key.hashCode());
result = prime * result + ((type == null) ? 0 : type.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;
Update other = (Update) obj;
if (!getOuterType().equals(other.getOuterType())) return false;
if (key == null) {
if (other.key != null) return false;
} else if (!key.equals(other.key)) return false;
if (type != other.type) return false;
return true;
}
private SyncManagerTest getOuterType() {
return SyncManagerTest.this;
}
}
protected class TestListener implements IStoreListener<String> {
HashSet<Update> notified = new HashSet<>();
@Override
public void keysModified(Iterator<String> keys,
UpdateType type) {
while (keys.hasNext())
notified.add(new Update(keys.next(), type));
}
}
@SuppressWarnings("rawtypes")
private void waitForNotify(TestListener tl,
HashSet comp,
int maxTime) throws Exception {
long then = System.currentTimeMillis();
while (true) {
if (tl.notified.containsAll(comp)) break;
Thread.sleep(100);
assertTrue(then + maxTime > System.currentTimeMillis());
}
}
@Test
public void testNotify() throws Exception {
IStoreClient<String, String> client0 =
syncManagers[0].getStoreClient("local",
String.class, String.class);
IStoreClient<String, String> client2 =
syncManagers[2].getStoreClient("local",
new TypeReference<String>() {},
new TypeReference<String>() {});
TestListener t0 = new TestListener();
TestListener t2 = new TestListener();
client0.addStoreListener(t0);
client2.addStoreListener(t2);
client0.put("test0", "value");
client2.put("test2", "value");
HashSet<Update> c0 = new HashSet<>();
c0.add(new Update("test0", UpdateType.LOCAL));
c0.add(new Update("test2", UpdateType.REMOTE));
HashSet<Update> c2 = new HashSet<>();
c2.add(new Update("test0", UpdateType.REMOTE));
c2.add(new Update("test2", UpdateType.LOCAL));
waitForNotify(t0, c0, 2000);
waitForNotify(t2, c2, 2000);
assertEquals(2, t0.notified.size());
assertEquals(2, t2.notified.size());
t0.notified.clear();
t2.notified.clear();
Versioned<String> v0 = client0.get("test0");
v0.setValue("newvalue");
client0.put("test0", v0);
Versioned<String> v2 = client0.get("test2");
v2.setValue("newvalue");
client2.put("test2", v2);
waitForNotify(t0, c0, 2000);
waitForNotify(t2, c2, 2000);
assertEquals(2, t0.notified.size());
assertEquals(2, t2.notified.size());
t0.notified.clear();
t2.notified.clear();
client0.delete("test0");
client2.delete("test2");
waitForNotify(t0, c0, 2000);
waitForNotify(t2, c2, 2000);
assertEquals(2, t0.notified.size());
assertEquals(2, t2.notified.size());
}
@Test
public void testAddNode() throws Exception {
waitForFullMesh(2000);
IStoreClient<String, String> client0 =
syncManagers[0].getStoreClient("global",
String.class, String.class);
IStoreClient<String, String> client1 =
syncManagers[1].getStoreClient("global",
String.class, String.class);
client0.put("key", "value");
waitForValue(client1, "key", "value", 2000, "client1");
nodes.add(new Node("localhost", 40105, (short)5, (short)5));
SyncManager[] sms = Arrays.copyOf(syncManagers,
syncManagers.length + 1);
FloodlightModuleContext[] fmcs =
Arrays.copyOf(moduleContexts,
moduleContexts.length + 1);
sms[syncManagers.length] = new SyncManager();
fmcs[moduleContexts.length] = new FloodlightModuleContext();
nodeString = mapper.writeValueAsString(nodes);
setupSyncManager(fmcs[moduleContexts.length],
sms[syncManagers.length],
nodes.get(syncManagers.length));
syncManagers = sms;
moduleContexts = fmcs;
for(int i = 0; i < 4; i++) {
moduleContexts[i].addConfigParam(syncManagers[i],
"nodes", nodeString);
syncManagers[i].doUpdateConfiguration();
}
waitForFullMesh(2000);
IStoreClient<String, String> client4 =
syncManagers[4].getStoreClient("global",
String.class, String.class);
client4.put("newkey", "newvalue");
waitForValue(client4, "key", "value", 2000, "client4");
waitForValue(client0, "newkey", "newvalue", 2000, "client0");
}
@Test
public void testRemoveNode() throws Exception {
waitForFullMesh(2000);
IStoreClient<String, String> client0 =
syncManagers[0].getStoreClient("global",
String.class, String.class);
IStoreClient<String, String> client1 =
syncManagers[1].getStoreClient("global",
String.class, String.class);
IStoreClient<String, String> client2 =
syncManagers[2].getStoreClient("global",
String.class, String.class);
client0.put("key", "value");
waitForValue(client1, "key", "value", 2000, "client1");
nodes.remove(0);
nodeString = mapper.writeValueAsString(nodes);
SyncManager oldNode = syncManagers[0];
syncManagers = Arrays.copyOfRange(syncManagers, 1, 4);
moduleContexts = Arrays.copyOfRange(moduleContexts, 1, 4);
try {
for(int i = 0; i < syncManagers.length; i++) {
moduleContexts[i].addConfigParam(syncManagers[i],
"nodes", nodeString);
syncManagers[i].doUpdateConfiguration();
waitForConnection(syncManagers[i], (short)1, false, 2000);
}
} finally {
oldNode.shutdown();
}
waitForFullMesh(2000);
client1.put("newkey", "newvalue");
waitForValue(client2, "key", "value", 2000, "client4");
waitForValue(client2, "newkey", "newvalue", 2000, "client0");
}
@Test
public void testChangeNode() throws Exception {
waitForFullMesh(2000);
IStoreClient<String, String> client0 =
syncManagers[0].getStoreClient("global",
String.class, String.class);
IStoreClient<String, String> client2 =
syncManagers[2].getStoreClient("global",
String.class, String.class);
client0.put("key", "value");
waitForValue(client2, "key", "value", 2000, "client2");
nodes.set(2, new Node("localhost", 50103, (short)3, (short)1));
nodeString = mapper.writeValueAsString(nodes);
for(int i = 0; i < syncManagers.length; i++) {
moduleContexts[i].addConfigParam(syncManagers[i],
"nodes", nodeString);
syncManagers[i].doUpdateConfiguration();
}
waitForFullMesh(2000);
waitForValue(client2, "key", "value", 2000, "client2");
client2 = syncManagers[2].getStoreClient("global",
String.class, String.class);
client0.put("key", "newvalue");
waitForValue(client2, "key", "newvalue", 2000, "client2");
}
/**
* Do a brain-dead performance test with one thread writing and waiting
* for the values on the other node. The result get printed to the log
*/
public void testSimpleWritePerformance(String store) throws Exception {
waitForFullMesh(5000);
final int count = 1000000;
IStoreClient<String, String> client0 =
syncManagers[0].getStoreClient(store,
String.class, String.class);
IStoreClient<String, String> client2 =
syncManagers[2].getStoreClient(store,
String.class, String.class);
long then = System.currentTimeMillis();
for (int i = 1; i <= count; i++) {
client0.put(""+i, ""+i);
}
long donewriting = System.currentTimeMillis();
waitForValue(client2, ""+count, null, count, "client2");
long now = System.currentTimeMillis();
logger.info("Simple write ({}): {} values in {}+/-100 " +
"millis ({} synced writes/s) ({} local writes/s)",
new Object[]{store, count, (now-then),
1000.0*count/(now-then),
1000.0*count/(donewriting-then)});
}
@Test
@Ignore // ignored just to speed up routine tests
public void testPerfSimpleWriteLocal() throws Exception {
testSimpleWritePerformance("local");
}
@Test
@Ignore // ignored just to speed up routine tests
public void testPerfSimpleWriteGlobal() throws Exception {
testSimpleWritePerformance("global");
}
@Test
@Ignore
public void testPerfOneNode() throws Exception {
tearDown();
tp = new ThreadPool();
tp.init(null);
tp.startUp(null);
nodes = new ArrayList<>();
nodes.add(new Node("localhost", 40101, (short)1, (short)1));
nodeString = mapper.writeValueAsString(nodes);
SyncManager sm = new SyncManager();
FloodlightModuleContext fmc = new FloodlightModuleContext();
setupSyncManager(fmc, sm, nodes.get(0));
fmc.addService(ISyncService.class, sm);
SyncTorture st = new SyncTorture();
//fmc.addConfigParam(st, "iterations", "1");
st.init(fmc);
st.startUp(fmc);
Thread.sleep(10000);
}
}
|
package gui;
import com.alexmerz.graphviz.ParseException;
import com.alexmerz.graphviz.TokenMgrError;
import gui.basics.NumberSpinner;
import gui.partialdeployment.PartialDeploymentController;
import io.InvalidTagException;
import io.NetworkParser;
import io.reporters.HTMLReporter;
import io.reporters.Reporter;
import javafx.event.ActionEvent;
import javafx.fxml.Initializable;
import javafx.scene.control.*;
import javafx.scene.layout.GridPane;
import javafx.stage.FileChooser;
import network.exceptions.NodeExistsException;
import network.exceptions.NodeNotFoundException;
import simulators.*;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.List;
import java.util.ResourceBundle;
import java.util.stream.Collectors;
import static policies.shortestpath.ShortestPathPolicy.isShortestPath;
public class Controller implements Initializable {
public GridPane pane;
public TextField networkTextField;
public Button startButton;
public Spinner<Integer> destinationIdSpinner;
public Spinner<Integer> repetitionsSpinner;
public Spinner<Integer> minDelaySpinner;
public Spinner<Integer> maxDelaySpinner;
public PartialDeploymentController partialDeploymentFormController;
public CheckBox debugCheckBox;
private FileChooser fileChooser = new FileChooser();
@Override
public void initialize(URL location, ResourceBundle resources) {
// ensure the start button is disabled when the text field is empty
networkTextField.textProperty().addListener((observable, oldText, newText) -> {
startButton.setDisable(newText.isEmpty());
});
NumberSpinner.setupNumberSpinner(destinationIdSpinner, 0, Integer.MAX_VALUE, 0);
NumberSpinner.setupNumberSpinner(repetitionsSpinner, 1, Integer.MAX_VALUE, 1);
NumberSpinner.setupNumberSpinner(minDelaySpinner, 0, Integer.MAX_VALUE, 0);
NumberSpinner.setupNumberSpinner(maxDelaySpinner, 0, Integer.MAX_VALUE, 10);
// enforces the minimum delay is never higher than the maximum delay
minDelaySpinner.valueProperty().addListener((observable, oldValue, newValue) -> {
if (newValue > maxDelaySpinner.getValue()) {
maxDelaySpinner.getValueFactory().setValue(newValue);
}
});
// enforces the maximum delay is never lower than the minimum delay
maxDelaySpinner.valueProperty().addListener((observable, oldValue, newValue) -> {
if (newValue < minDelaySpinner.getValue()) {
minDelaySpinner.getValueFactory().setValue(newValue);
}
});
// accept only *.gv file in the file chooser
fileChooser.getExtensionFilters().add(new FileChooser.ExtensionFilter("Network files (*.gv)", "*.gv"));
}
/**
* Handles browsing for network files. Opens up a file chooser for the user to select the network files to
* simulate.
*/
public void handleClickedBrowseButton(ActionEvent actionEvent) {
List<File> files = fileChooser.showOpenMultipleDialog(pane.getScene().getWindow());
if (files != null) {
List<String> filePaths = files.stream()
.filter(File::exists)
.map(File::getAbsolutePath)
.collect(Collectors.toList());
networkTextField.setText(String.join(" ; ", filePaths));
}
}
public void handleClickedStartButton(ActionEvent actionEvent) {
for (String networkFilePath : networkTextField.getText().split(" ; ")) {
simulate(new File(networkFilePath));
}
}
/**
* Simulates each network file.
*
* @param networkFile network file to be simulated.
*/
private void simulate(File networkFile) {
int destinationId = destinationIdSpinner.getValue();
int repetitionCount = repetitionsSpinner.getValue();
int minDelay = minDelaySpinner.getValue();
int maxDelay = maxDelaySpinner.getValue();
try {
NetworkParser parser = new NetworkParser();
parser.parse(networkFile);
// simulator that will be used to simulate
Simulator simulator;
if (!partialDeploymentFormController.activateToggle.isSelected()) {
if (isShortestPath(parser.getNetwork().getPolicy())) {
simulator = new SPPolicyStandardSimulator(parser.getNetwork(), destinationId, minDelay, maxDelay);
} else {
simulator = new StandardSimulator(parser.getNetwork(), destinationId, minDelay, maxDelay);
}
} else {
int timeToChange = partialDeploymentFormController.detectingTimeSpinner.getValue();
if (isShortestPath(parser.getNetwork().getPolicy())) {
simulator = new SPPolicyFullDeploymentSimulator(parser.getNetwork(), destinationId,
minDelay, maxDelay, timeToChange);
} else {
simulator = new FullDeploymentSimulator(parser.getNetwork(), destinationId,
minDelay, maxDelay, timeToChange);
}
}
String debugFilePath = networkFile.getPath().replaceFirst("\\.gv", ".debug");
simulator.enableDebugReport(debugCheckBox.isSelected(), new File(debugFilePath));
for (int i = 0; i < repetitionCount; i++) {
simulator.simulate();
}
try {
// store the report file in the same directory as the network file and with the same name bu with
// different extension
String reportFileName = networkFile.getName().replaceFirst("\\.gv", ".html");
// FIXME add a reporter implementation
Reporter reporter = new HTMLReporter(new File(networkFile.getParent(), reportFileName));
simulator.report(reporter);
} catch (IOException e) {
Alert alert = new Alert(Alert.AlertType.ERROR, "could not generate report", ButtonType.OK);
alert.setHeaderText("Report File Error");
alert.showAndWait();
}
} catch (IOException e) {
Alert alert = new Alert(Alert.AlertType.ERROR, "can't open the file", ButtonType.OK);
alert.setHeaderText("Network File Error");
alert.showAndWait();
} catch (TokenMgrError | ParseException | NodeExistsException | NodeNotFoundException | InvalidTagException e) {
Alert alert = new Alert(Alert.AlertType.ERROR, "network file is corrupted", ButtonType.OK);
alert.setHeaderText("Invalid File Error");
alert.showAndWait();
}
}
}
|
package hex;
import water.*;
import water.exceptions.H2OIllegalArgumentException;
import water.exceptions.H2OModelBuilderIllegalArgumentException;
import water.fvec.*;
import water.rapids.ASTKFold;
import water.util.ArrayUtils;
import water.util.Log;
import water.util.MRUtils;
import water.util.VecUtils;
import java.util.*;
/**
* Model builder parent class. Contains the common interfaces and fields across all model builders.
*/
abstract public class ModelBuilder<M extends Model<M,P,O>, P extends Model.Parameters, O extends Model.Output> extends Iced {
public Job _job; // Job controlling this build
/** Block till completion, and return the built model from the DKV. Note the
* funny assert: the Job does NOT have to be controlling this model build,
* but might, e.g. be controlling a Grid search for which this is just one
* of many results. Calling 'get' means that we are blocking on the Job
* which is controlling ONLY this ModelBuilder, and when the Job completes
* we can return built Model. */
public final M get() { assert _job._result == _result; return (M)_job.get(); }
public final boolean isStopped() { return _job.isStopped(); }
// Key of the model being built; note that this is DIFFERENT from
// _job._result if the Job is being shared by many sub-models
// e.g. cross-validation.
protected Key<M> _result; // Built Model key
public final Key<M> dest() { return _result; }
/** Default model-builder key */
public static Key<? extends Model> defaultKey(String algoName) {
return Key.make(H2O.calcNextUniqueModelId(algoName));
}
/** Default easy constructor: Unique new job and unique new result key */
protected ModelBuilder(P parms) {
String algoName = parms.algoName();
_job = new Job<>(_result = (Key<M>)defaultKey(algoName), parms.javaName(), algoName);
_parms = parms;
}
/** Unique new job and named result key */
protected ModelBuilder(P parms, Key<M> key) {
_job = new Job<>(_result = key, parms.javaName(), parms.algoName());
_parms = parms;
}
/** Shared pre-existing Job and unique new result key */
protected ModelBuilder(P parms, Job job) {
_job = job;
_result = (Key<M>)defaultKey(parms.algoName());
_parms = parms;
}
/** List of known ModelBuilders with all default args; endlessly cloned by
* the GUI for new private instances, then the GUI overrides some of the
* defaults with user args. */
private static String[] ALGOBASES = new String[0];
public static String[] algos() { return ALGOBASES; }
private static ModelBuilder[] BUILDERS = new ModelBuilder[0];
/** One-time start-up only ModelBuilder, endlessly cloned by the GUI for the
* default settings. */
protected ModelBuilder(P parms, boolean startup_once) {
assert startup_once;
_job = null;
_result = null;
_parms = parms;
init(false); // Default cheap init
String base = getClass().getSimpleName().toLowerCase();
if( ArrayUtils.find(ALGOBASES,base) != -1 )
throw H2O.fail("Only called once at startup per ModelBuilder, and "+base+" has already been called");
ALGOBASES = Arrays.copyOf(ALGOBASES,ALGOBASES.length+1);
BUILDERS = Arrays.copyOf(BUILDERS ,BUILDERS .length+1);
ALGOBASES[ALGOBASES.length-1] = base;
BUILDERS [BUILDERS .length-1] = this;
}
/** gbm -> GBM, deeplearning -> DeepLearning */
public static String algoName(String urlName) { return BUILDERS[ArrayUtils.find(ALGOBASES,urlName)]._parms.algoName(); }
/** gbm -> hex.tree.gbm.GBM, deeplearning -> hex.deeplearning.DeepLearning */
public static String javaName(String urlName) { return BUILDERS[ArrayUtils.find(ALGOBASES,urlName)]._parms.javaName(); }
/** gbm -> GBMParameters */
public static String paramName(String urlName) { return algoName(urlName)+"Parameters"; }
/** Factory method to create a ModelBuilder instance for given the algo name.
* Shallow clone of both the default ModelBuilder instance and a Parameter. */
public static <B extends ModelBuilder> B make(String algo, Job job, Key<Model> result) {
int idx = ArrayUtils.find(ALGOBASES,algo.toLowerCase());
assert idx != -1 : "Unregistered algorithm "+algo;
B mb = (B)BUILDERS[idx].clone();
mb._job = job;
mb._result = result;
mb._parms = BUILDERS[idx]._parms.clone();
return mb;
}
/** All the parameters required to build the model. */
public P _parms; // Not final, so CV can set-after-clone
/** Training frame: derived from the parameter's training frame, excluding
* all ignored columns, all constant and bad columns, perhaps flipping the
* response column to an Categorical, etc. */
public final Frame train() { return _train; }
protected transient Frame _train;
/** Validation frame: derived from the parameter's validation frame, excluding
* all ignored columns, all constant and bad columns, perhaps flipping the
* response column to a Categorical, etc. Is null if no validation key is set. */
protected final Frame valid() { return _valid; }
protected transient Frame _valid;
// TODO: tighten up the type
// Map the algo name (e.g., "deeplearning") to the builder class (e.g., DeepLearning.class) :
private static final Map<String, Class<? extends ModelBuilder>> _builders = new HashMap<>();
// Map the Model class (e.g., DeepLearningModel.class) to the algo name (e.g., "deeplearning"):
private static final Map<Class<? extends Model>, String> _model_class_to_algo = new HashMap<>();
// Map the simple algo name (e.g., deeplearning) to the full algo name (e.g., "Deep Learning"):
private static final Map<String, String> _algo_to_algo_full_name = new HashMap<>();
// Map the algo name (e.g., "deeplearning") to the Model class (e.g., DeepLearningModel.class):
private static final Map<String, Class<? extends Model>> _algo_to_model_class = new HashMap<>();
/** Train response vector. */
public Vec response(){return _response;}
/** Validation response vector. */
public Vec vresponse(){return _vresponse == null ? _response : _vresponse;}
abstract protected class Driver extends H2O.H2OCountedCompleter<Driver> {
protected Driver() { super(true); } // bump priority of model drivers
protected Driver(H2O.H2OCountedCompleter completer){ super(completer,true); }
}
/** Method to launch training of a Model, based on its parameters. */
final public Job<M> trainModel() {
if (error_count() > 0)
throw H2OModelBuilderIllegalArgumentException.makeFromBuilder(this);
if( !nFoldCV() )
return _job.start(trainModelImpl(), progressUnits());
// cross-validation needs to be forked off to allow continuous (non-blocking) progress bar
return _job.start(new H2O.H2OCountedCompleter() {
@Override
public void compute2() {
computeCrossValidation();
tryComplete();
}
}, (1/*for all pre-fold work*/+nFoldWork()+1/*for all the post-fold work*/) * progressUnits());
}
/** Train a model as part of a larger Job; the Job already exists and has started. */
final public M trainModelNested() {
if (error_count() > 0)
throw H2OModelBuilderIllegalArgumentException.makeFromBuilder(this);
if( !nFoldCV() ) trainModelImpl().compute2();
else computeCrossValidation();
return _result.get();
}
/** Model-specific implementation of model training
* @return A F/J Job, which, when executed, does the build. F/J is NOT started. */
abstract protected Driver trainModelImpl();
abstract protected long progressUnits();
// Work for each requested fold
private int nFoldWork() {
if( _parms._fold_column == null ) return _parms._nfolds;
Vec f = train().vec(_parms._fold_column);
Vec fc = VecUtils.toCategoricalVec(f);
int N = fc.domain().length;
fc.remove();
return N;
}
// Temp zero'd vector, same size as train()
private Vec zTmp() { return train().anyVec().makeZero(); }
/**
* Default naive (serial) implementation of N-fold cross-validation
* @return Cross-validation Job
* (builds N+1 models, all have train+validation metrics, the main model has N-fold cross-validated validation metrics)
*/
public void computeCrossValidation() {
assert _job.isRunning(); // main Job is still running
final Integer N = nFoldWork();
init(false);
try {
Scope.enter();
// Step 1: Assign each row to a fold
final Vec foldAssignment = cv_AssignFold(N);
// Step 2: Make 2*N binary weight vectors
final Vec[] weights = cv_makeWeights(N,foldAssignment);
_job.update(1); // Did the major pre-fold work
// Step 3: Build N train & validation frames; build N ModelBuilders; error check them all
ModelBuilder<M, P, O> cvModelBuilders[] = cv_makeFramesAndBuilders(N,weights);
// Step 4: Run all the CV models and launch the main model
H2O.H2OCountedCompleter mainMB = cv_runCVBuilds(N, cvModelBuilders);
// Step 5: Score the CV models
ModelMetrics.MetricBuilder mbs[] = cv_scoreCVModels(N, weights, cvModelBuilders);
// wait for completion of the main model
mainMB.join();
// Step 6: Combine cross-validation scores; compute main model x-val
// scores; compute gains/lifts
cv_mainModelScores(N, mbs, cvModelBuilders);
} finally {
Scope.exit();
}
}
// Step 1: Assign each row to a fold
// TODO: Implement better splitting algo (with Strata if response is
public Vec cv_AssignFold(int N) {
Vec fold = train().vec(_parms._fold_column);
if( fold != null ) {
if( !fold.isInt() ||
(!(fold.min() == 0 && fold.max() == N-1) &&
!(fold.min() == 1 && fold.max() == N ) )) // Allow 0 to N-1, or 1 to N
throw new H2OIllegalArgumentException("Fold column must be integers from 0 to number of folds, and all folds must be non-empty");
return fold;
}
final long seed = _parms.nFoldSeed();
Log.info("Creating " + N + " cross-validation splits with random number seed: " + seed);
switch( _parms._fold_assignment ) {
case AUTO:
case Random: return ASTKFold. kfoldColumn( zTmp(),N,seed);
case Modulo: return ASTKFold. moduloKfoldColumn( zTmp(),N );
case Stratified: return ASTKFold.stratifiedKFoldColumn(response(),N,seed);
default: throw H2O.unimpl();
}
}
// Step 2: Make 2*N binary weight vectors
public Vec[] cv_makeWeights( final int N, Vec foldAssignment ) {
String origWeightsName = _parms._weights_column;
Vec origWeight = origWeightsName != null ? train().vec(origWeightsName) : train().anyVec().makeCon(1.0);
Frame folds_and_weights = new Frame(new Vec[]{foldAssignment, origWeight});
Vec[] weights = new MRTask() {
@Override public void map(Chunk chks[], NewChunk nchks[]) {
Chunk fold = chks[0], orig = chks[1];
for( int row=0; row< orig._len; row++ ) {
int foldAssignment = (int)fold.at8(row) % N;
double w = orig.atd(row);
for( int f = 0; f < N; f++ ) {
boolean holdout = foldAssignment == f;
nchks[2*f+0].addNum(holdout ? 0 : w);
nchks[2*f+1].addNum(holdout ? w : 0);
}
}
}
}.doAll(2*N,Vec.T_NUM,folds_and_weights).outputFrame().vecs();
if( _parms._fold_column == null ) foldAssignment.remove();
if( origWeightsName == null ) origWeight.remove(); // Cleanup temp
for( Vec weight : weights )
if( weight.isConst() )
throw new H2OIllegalArgumentException("Not enough data to create " + N + " random cross-validation splits. Either reduce nfolds, specify a larger dataset (or specify another random number seed, if applicable).");
return weights;
}
// Step 3: Build N train & validation frames; build N ModelBuilders; error check them all
public ModelBuilder<M, P, O>[] cv_makeFramesAndBuilders( int N, Vec[] weights ) {
final long old_cs = _parms.checksum();
final String origDest = _job._result.toString();
final String weightName = "__internal_cv_weights__";
if (train().find(weightName) != -1) throw new H2OIllegalArgumentException("Frame cannot contain a Vec called '" + weightName + "'.");
Frame cv_fr = new Frame(train().names(),train().vecs());
if( _parms._weights_column!=null ) cv_fr.remove( _parms._weights_column ); // The CV frames will have their own private weight column
ModelBuilder<M, P, O>[] cvModelBuilders = new ModelBuilder[N];
for( int i=0; i<N; i++ ) {
String identifier = origDest + "_cv_" + (i+1);
// Training/Validation share the same data, but will have exclusive weights
Frame cvTrain = new Frame(Key.make(identifier+"_train"),cv_fr.names(),cv_fr.vecs());
cvTrain.add(weightName, weights[2*i]);
DKV.put(cvTrain);
Frame cvValid = new Frame(Key.make(identifier+"_valid"),cv_fr.names(),cv_fr.vecs());
cvValid.add(weightName, weights[2*i+1]);
DKV.put(cvValid);
// Shallow clone - not everything is a private copy!!!
ModelBuilder<M, P, O> cv_mb = (ModelBuilder)this.clone();
cv_mb._result = Key.make(identifier); // Each submodel gets its own key
cv_mb._parms = (P) _parms.clone();
// Fix up some parameters of the clone
cv_mb._parms._weights_column = weightName;// All submodels have a weight column, which the main model does not
cv_mb._parms._train = cvTrain._key; // All submodels have a weight column, which the main model does not
cv_mb._parms._valid = cvValid._key;
cv_mb._parms._fold_assignment = Model.Parameters.FoldAssignmentScheme.AUTO;
cv_mb._parms._nfolds = 0; // Each submodel is not itself folded
cv_mb.init(false); // Arg check submodels
// Error-check all the cross-validation Builders before launching any
if( cv_mb.error_count() > 0 ) // Gather all submodel error messages
for( ValidationMessage vm : cv_mb._messages )
message(vm._log_level, vm._field_name, vm._message);
cvModelBuilders[i] = cv_mb;
}
if( error_count() > 0 ) // Error in any submodel
throw H2OModelBuilderIllegalArgumentException.makeFromBuilder(this);
// check that this Job's original _params haven't changed
assert old_cs == _parms.checksum();
return cvModelBuilders;
}
// Step 4: Run all the CV models and launch the main model
public H2O.H2OCountedCompleter cv_runCVBuilds( int N, ModelBuilder<M, P, O>[] cvModelBuilders ) {
final boolean async = true; // Set to TRUE for parallel building
H2O.H2OCountedCompleter submodel_tasks[] = new H2O.H2OCountedCompleter[N];
for( int i=0; i<N; ++i ) {
if( _job.stop_requested() ) break; // Stop launching but still must block for all async jobs
Log.info("Building cross-validation model " + (i + 1) + " / " + N + ".");
submodel_tasks[i] = H2O.submitTask(cvModelBuilders[i].trainModelImpl());
if( !async ) submodel_tasks[i].join();
}
if( async ) // Block for the parallel builds to complete
for( int i=0; i<N; ++i ) // (block, even if cancelled)
submodel_tasks[i].join();
// Now do the main model
if( _job.stop_requested() ) return null;
assert _job.isRunning();
Log.info("Building main model.");
modifyParmsForCrossValidationMainModel(cvModelBuilders); //tell the main model that it shouldn't stop early either
H2O.H2OCountedCompleter mainMB = H2O.submitTask(trainModelImpl()); //non-blocking
if( !async ) mainMB.join();
return mainMB;
}
// Step 5: Score the CV models
public ModelMetrics.MetricBuilder[] cv_scoreCVModels(int N, Vec[] weights, ModelBuilder<M, P, O>[] cvModelBuilders) {
if( _job.stop_requested() ) return null;
ModelMetrics.MetricBuilder[] mbs = new ModelMetrics.MetricBuilder[N];
Futures fs = new Futures();
for (int i=0; i<N; ++i) {
if( _job.stop_requested() ) return null; //don't waste time scoring if the CV run is stopped
Frame cvValid = cvModelBuilders[i].valid();
Frame adaptFr = new Frame(cvValid);
M cvModel = cvModelBuilders[i].dest().get();
cvModel.adaptTestForTrain(adaptFr, true, !isSupervised());
mbs[i] = cvModel.scoreMetrics(adaptFr);
if (nclasses() == 2 /* need holdout predictions for gains/lift table */ || _parms._keep_cross_validation_predictions) {
String predName = "prediction_" + cvModelBuilders[i]._result.toString();
cvModel.predictScoreImpl(cvValid, adaptFr, predName);
}
// free resources as early as possible
if (adaptFr != null) {
Model.cleanup_adapt(adaptFr, cvValid);
DKV.remove(adaptFr._key,fs);
}
DKV.remove(cvModelBuilders[i]._parms._train,fs);
DKV.remove(cvModelBuilders[i]._parms._valid,fs);
weights[2*i ].remove(fs);
weights[2*i+1].remove(fs);
}
fs.blockForPending();
return mbs;
}
// Step 6: Combine cross-validation scores; compute main model x-val scores; compute gains/lifts
public void cv_mainModelScores(int N, ModelMetrics.MetricBuilder mbs[], ModelBuilder<M, P, O> cvModelBuilders[]) {
if( _job.stop_requested() ) return;
assert _job.isRunning();
M mainModel = _result.get();
// Compute and put the cross-validation metrics into the main model
Log.info("Computing " + N + "-fold cross-validation metrics.");
mainModel._output._cross_validation_models = new Key[N];
Key<Frame>[] predKeys = new Key[N];
mainModel._output._cross_validation_predictions = _parms._keep_cross_validation_predictions ? predKeys : null;
for (int i = 0; i < N; ++i) {
if (i > 0) mbs[0].reduce(mbs[i]);
Key<M> cvModelKey = cvModelBuilders[i]._result;
mainModel._output._cross_validation_models[i] = cvModelKey;
predKeys[i] = Key.make("prediction_" + cvModelKey.toString());
}
Frame preds = null;
//stitch together holdout predictions into one Vec, to compute the Gains/Lift table
if (nclasses() == 2) {
Vec[] p1s = new Vec[N];
for (int i=0;i<N;++i) {
p1s[i] = ((Frame)DKV.getGet(predKeys[i])).lastVec();
}
Frame p1combined = new HoldoutPredictionCombiner().doAll(1,Vec.T_NUM,new Frame(p1s)).outputFrame(new String[]{"p1"},null);
Vec p1 = p1combined.anyVec();
preds = new Frame(new Vec[]{p1, p1, p1}); //pretend to have labels,p0,p1, but will only need p1 anyway
}
// Keep or toss predictions
for (Key<Frame> k : predKeys) {
Frame fr = DKV.getGet(k);
if( _parms._keep_cross_validation_predictions ) Scope.untrack(fr.keys());
else fr.remove();
}
mainModel._output._cross_validation_metrics = mbs[0].makeModelMetrics(mainModel, _parms.train(), null, preds);
if (preds!=null) preds.remove();
mainModel._output._cross_validation_metrics._description = N + "-fold cross-validation on training data";
Log.info(mainModel._output._cross_validation_metrics.toString());
// Now, the main model is complete (has cv metrics)
DKV.put(mainModel);
}
// helper to combine multiple holdout prediction Vecs (each only has 1/N-th filled with non-zeros) into 1 Vec
private static class HoldoutPredictionCombiner extends MRTask<HoldoutPredictionCombiner> {
@Override
public void map(Chunk[] cs, NewChunk[] nc) {
double [] vals = new double[cs[0].len()];
for (int i=0;i<cs.length;++i)
for (int row = 0; row < cs[0].len(); ++row)
vals[row] += cs[i].atd(row);
nc[0].setDoubles(vals);
}
}
/** Override for model-specific checks / modifications to _parms for the main model during N-fold cross-validation.
* For example, the model might need to be told to not do early stopping.
*/
public void modifyParmsForCrossValidationMainModel(ModelBuilder<M, P, O>[] cvModelBuilders) { }
/** @return Whether n-fold cross-validation is done */
public boolean nFoldCV() {
return _parms._fold_column != null || _parms._nfolds != 0;
}
/** List containing the categories of models that this builder can
* build. Each ModelBuilder must have one of these. */
abstract public ModelCategory[] can_build();
/** Visibility for this algo: is it always visible, is it beta (always
* visible but with a note in the UI) or is it experimental (hidden by
* default, visible in the UI if the user gives an "experimental" flag at
* startup); test-only builders are "experimental" */
public enum BuilderVisibility { Experimental, Beta, Stable }
public BuilderVisibility builderVisibility() { return BuilderVisibility.Stable; }
/** Clear whatever was done by init() so it can be run again. */
public void clearInitState() {
clearValidationErrors();
}
protected boolean logMe() { return true; }
public boolean isSupervised(){return false;}
protected transient Vec _response; // Handy response column
protected transient Vec _vresponse; // Handy response column
protected transient Vec _offset; // Handy offset column
protected transient Vec _weights; // observation weight column
protected transient Vec _fold; // fold id column
public boolean hasOffsetCol(){ return _parms._offset_column != null;} // don't look at transient Vec
public boolean hasWeightCol(){return _parms._weights_column != null;} // don't look at transient Vec
public boolean hasFoldCol(){return _parms._fold_column != null;} // don't look at transient Vec
public int numSpecialCols() { return (hasOffsetCol() ? 1 : 0) + (hasWeightCol() ? 1 : 0) + (hasFoldCol() ? 1 : 0); }
// no hasResponse, call isSupervised instead (response is mandatory if isSupervised is true)
protected int _nclass; // Number of classes; 1 for regression; 2+ for classification
public int nclasses(){return _nclass;}
public final boolean isClassifier() { return nclasses() > 1; }
/**
* Find and set response/weights/offset/fold and put them all in the end,
* @return number of non-feature vecs
*/
protected int separateFeatureVecs() {
int res = 0;
if(_parms._weights_column != null) {
Vec w = _train.remove(_parms._weights_column);
if(w == null)
error("_weights_column","Weights column '" + _parms._weights_column + "' not found in the training frame");
else {
if(!w.isNumeric())
error("_weights_column","Invalid weights column '" + _parms._weights_column + "', weights must be numeric");
_weights = w;
if(w.naCnt() > 0)
error("_weights_columns","Weights cannot have missing values.");
if(w.min() < 0)
error("_weights_columns","Weights must be >= 0");
if(w.max() == 0)
error("_weights_columns","Max. weight must be > 0");
_train.add(_parms._weights_column, w);
++res;
}
} else {
_weights = null;
assert(!hasWeightCol());
}
if(_parms._offset_column != null) {
Vec o = _train.remove(_parms._offset_column);
if(o == null)
error("_offset_column","Offset column '" + _parms._offset_column + "' not found in the training frame");
else {
if(!o.isNumeric())
error("_offset_column","Invalid offset column '" + _parms._offset_column + "', offset must be numeric");
_offset = o;
if(o.naCnt() > 0)
error("_offset_column","Offset cannot have missing values.");
if(_weights == _offset)
error("_offset_column", "Offset must be different from weights");
_train.add(_parms._offset_column, o);
++res;
}
} else {
_offset = null;
assert(!hasOffsetCol());
}
if(_parms._fold_column != null) {
Vec f = _train.remove(_parms._fold_column);
if(f == null)
error("_fold_column","Fold column '" + _parms._fold_column + "' not found in the training frame");
else {
if(!f.isInt() && !f.isCategorical())
error("_fold_column","Invalid fold column '" + _parms._fold_column + "', fold must be integer or categorical");
if(f.min() < 0)
error("_fold_column","Invalid fold column '" + _parms._fold_column + "', fold must be non-negative");
if(f.isConst())
error("_fold_column","Invalid fold column '" + _parms._fold_column + "', fold cannot be constant");
_fold = f;
if(f.naCnt() > 0)
error("_fold_column","Fold cannot have missing values.");
if(_fold == _weights)
error("_fold_column", "Fold must be different from weights");
if(_fold == _offset)
error("_fold_column", "Fold must be different from offset");
_train.add(_parms._fold_column, f);
++res;
}
} else {
_fold = null;
assert(!hasFoldCol());
}
if(isSupervised() && _parms._response_column != null) {
_response = _train.remove(_parms._response_column);
if (_response == null) {
if (isSupervised())
error("_response_column", "Response column '" + _parms._response_column + "' not found in the training frame");
} else {
if(_response == _offset)
error("_response", "Response must be different from offset_column");
if(_response == _weights)
error("_response", "Response must be different from weights_column");
if(_response == _fold)
error("_response", "Response must be different from fold_column");
_train.add(_parms._response_column, _response);
++res;
}
} else {
_response = null;
}
return res;
}
protected boolean ignoreStringColumns(){return true;}
protected boolean ignoreConstColumns(){return _parms._ignore_const_cols;}
/**
* Ignore constant columns, columns with all NAs and strings.
* @param npredictors
* @param expensive
*/
protected void ignoreBadColumns(int npredictors, boolean expensive){
// Drop all-constant and all-bad columns.
if(_parms._ignore_const_cols)
new FilterCols(npredictors) {
@Override protected boolean filter(Vec v) {
return (ignoreConstColumns() && v.isConst()) || v.isBad() || (ignoreStringColumns() && v.isString()); }
}.doIt(_train,"Dropping constant columns: ",expensive);
}
/**
* Override this method to call error() if the model is expected to not fit in memory, and say why
*/
protected void checkMemoryFootPrint() {}
transient double [] _distribution;
transient double [] _priorClassDist;
protected boolean computePriorClassDistribution(){
return isClassifier();
}
/** A list of field validation issues. */
public ValidationMessage[] _messages = new ValidationMessage[0];
private int _error_count = -1; // -1 ==> init not run yet, for those Jobs that have an init, like ModelBuilder. Note, this counts ONLY errors, not WARNs and etc.
public int error_count() { assert _error_count >= 0 : "init() not run yet"; return _error_count; }
public void hide (String field_name, String message) { message(Log.TRACE, field_name, message); }
public void info (String field_name, String message) { message(Log.INFO , field_name, message); }
public void warn (String field_name, String message) { message(Log.WARN , field_name, message); }
public void error(String field_name, String message) { message(Log.ERRR , field_name, message); _error_count++; }
public void clearValidationErrors() {
_messages = new ValidationMessage[0];
_error_count = 0;
}
public void message(byte log_level, String field_name, String message) {
_messages = Arrays.copyOf(_messages, _messages.length + 1);
_messages[_messages.length - 1] = new ValidationMessage(log_level, field_name, message);
}
/** Get a string representation of only the ERROR ValidationMessages (e.g., to use in an exception throw). */
public String validationErrors() {
StringBuilder sb = new StringBuilder();
for( ValidationMessage vm : _messages )
if( vm._log_level == Log.ERRR )
sb.append(vm.toString()).append("\n");
return sb.toString();
}
/** Can be an ERROR, meaning the parameters can't be used as-is,
* a TRACE, which means the specified field should be hidden given
* the values of other fields, or a WARN or INFO for informative
* messages to the user. */
public static final class ValidationMessage extends Iced {
final byte _log_level; // See util/Log.java for levels
final String _field_name;
final String _message;
public ValidationMessage(byte log_level, String field_name, String message) {
_log_level = log_level;
_field_name = field_name;
_message = message;
Log.log(log_level,field_name + ": " + message);
}
public int log_level() { return _log_level; }
@Override public String toString() { return Log.LVLS[_log_level] + " on field: " + _field_name + ": " + _message; }
}
/** Initialize the ModelBuilder, validating all arguments and preparing the
* training frame. This call is expected to be overridden in the subclasses
* and each subclass will start with "super.init();". This call is made by
* the front-end whenever the GUI is clicked, and needs to be fast whenever
* {@code expensive} is false; it will be called once again at the start of
* model building {@see #trainModel()} with expensive set to true.
*<p>
* The incoming training frame (and validation frame) will have ignored
* columns dropped out, plus whatever work the parent init did.
*<p>
* NOTE: The front end initially calls this through the parameters validation
* endpoint with no training_frame, so each subclass's {@code init()} method
* has to work correctly with the training_frame missing.
*<p>
*/
public void init(boolean expensive) {
// Log parameters
if( expensive && logMe() ) {
Log.info("Building H2O " + this.getClass().getSimpleName().toString() + " model with these parameters:");
Log.info(new String(_parms.writeJSON(new AutoBuffer()).buf()));
}
// NOTE: allow re-init:
clearInitState();
assert _parms != null; // Parms must already be set in
if( _parms._train == null ) {
if (expensive)
error("_train","Missing training frame");
return;
}
Frame tr = _parms.train();
if( tr == null ) { error("_train","Missing training frame: "+_parms._train); return; }
_train = new Frame(null /* not putting this into KV */, tr._names.clone(), tr.vecs().clone());
if (_parms._nfolds < 0 || _parms._nfolds == 1) {
error("_nfolds", "nfolds must be either 0 or >1.");
}
if (_parms._nfolds > 1 && _parms._nfolds > train().numRows()) {
error("_nfolds", "nfolds cannot be larger than the number of rows (" + train().numRows() + ").");
}
if (_parms._fold_column != null) {
hide("_fold_assignment", "Fold assignment is ignored when a fold column is specified.");
if (_parms._nfolds > 1) {
error("_nfolds", "nfolds cannot be specified at the same time as a fold column.");
} else {
hide("_nfolds", "nfolds is ignored when a fold column is specified.");
}
if (_parms._fold_assignment != Model.Parameters.FoldAssignmentScheme.AUTO) {
error("_fold_assignment", "Fold assignment is not allowed in conjunction with a fold column.");
}
}
if (_parms._nfolds > 1) {
hide("_fold_column", "Fold column is ignored when nfolds > 1.");
}
// hide cross-validation parameters unless cross-val is enabled
if (!nFoldCV()) {
hide("_keep_cross_validation_predictions", "Only for cross-validation.");
hide("_fold_assignment", "Only for cross-validation.");
if (_parms._fold_assignment != Model.Parameters.FoldAssignmentScheme.AUTO) {
error("_fold_assignment", "Fold assignment is only allowed for cross-validation.");
}
}
if (_parms._distribution != Distribution.Family.tweedie) {
hide("_tweedie_power", "Only for Tweedie Distribution.");
}
if (_parms._tweedie_power <= 1 || _parms._tweedie_power >= 2) {
error("_tweedie_power", "Tweedie power must be between 1 and 2 (exclusive).");
}
// Drop explicitly dropped columns
if( _parms._ignored_columns != null ) {
_train.remove(_parms._ignored_columns);
if( expensive ) Log.info("Dropping ignored columns: "+Arrays.toString(_parms._ignored_columns));
}
// Rebalance train and valid datasets
if (expensive && error_count() == 0) {
_train = rebalance(_train, false, _result + ".temporary.train");
_valid = rebalance(_valid, false, _result + ".temporary.valid");
}
// Drop all non-numeric columns (e.g., String and UUID). No current algo
// can use them, and otherwise all algos will then be forced to remove
// them. Text algos (grep, word2vec) take raw text columns - which are
// numeric (arrays of bytes).
ignoreBadColumns(separateFeatureVecs(), expensive);
// Check that at least some columns are not-constant and not-all-NAs
if( _train.numCols() == 0 )
error("_train","There are no usable columns to generate model");
if(isSupervised()) {
if(_response != null) {
if (expensive) checkDistributions();
_nclass = _response.isCategorical() ? _response.cardinality() : 1;
if (_response.isConst())
error("_response","Response cannot be constant.");
}
if (! _parms._balance_classes)
hide("_max_after_balance_size", "Balance classes is false, hide max_after_balance_size");
else if (_parms._weights_column != null && _weights != null && !_weights.isBinary())
error("_balance_classes", "Balance classes and observation weights are not currently supported together.");
if( _parms._max_after_balance_size <= 0.0 )
error("_max_after_balance_size","Max size after balancing needs to be positive, suggest 1.0f");
if( _train != null ) {
if (_train.numCols() <= 1)
error("_train", "Training data must have at least 2 features (incl. response).");
if( null == _parms._response_column) {
error("_response_column", "Response column parameter not set.");
return;
}
if(_response != null && computePriorClassDistribution()) {
if (isClassifier() && isSupervised()) {
MRUtils.ClassDist cdmt =
_weights != null ? new MRUtils.ClassDist(nclasses()).doAll(_response, _weights) : new MRUtils.ClassDist(nclasses()).doAll(_response);
_distribution = cdmt.dist();
_priorClassDist = cdmt.rel_dist();
} else { // Regression; only 1 "class"
_distribution = new double[]{ (_weights != null ? _weights.mean() : 1.0) * train().numRows() };
_priorClassDist = new double[]{1.0f};
}
}
}
if( !isClassifier() ) {
hide("_balance_classes", "Balance classes is only applicable to classification problems.");
hide("_class_sampling_factors", "Class sampling factors is only applicable to classification problems.");
hide("_max_after_balance_size", "Max after balance size is only applicable to classification problems.");
hide("_max_confusion_matrix_size", "Max confusion matrix size is only applicable to classification problems.");
}
if (_nclass <= 2) {
hide("_max_hit_ratio_k", "Max K-value for hit ratio is only applicable to multi-class classification problems.");
hide("_max_confusion_matrix_size", "Only for multi-class classification problems.");
}
if( !_parms._balance_classes ) {
hide("_max_after_balance_size", "Only used with balanced classes");
hide("_class_sampling_factors", "Class sampling factors is only applicable if balancing classes.");
}
}
else {
hide("_response_column", "Ignored for unsupervised methods.");
hide("_balance_classes", "Ignored for unsupervised methods.");
hide("_class_sampling_factors", "Ignored for unsupervised methods.");
hide("_max_after_balance_size", "Ignored for unsupervised methods.");
hide("_max_confusion_matrix_size", "Ignored for unsupervised methods.");
_response = null;
_vresponse = null;
_nclass = 1;
}
if( _nclass > Model.Parameters.MAX_SUPPORTED_LEVELS ) {
error("_nclass", "Too many levels in response column: " + _nclass + ", maximum supported number of classes is " + Model.Parameters.MAX_SUPPORTED_LEVELS + ".");
}
// Build the validation set to be compatible with the training set.
// Toss out extra columns, complain about missing ones, remap categoricals
Frame va = _parms.valid(); // User-given validation set
if (va != null) {
_valid = new Frame(null /* not putting this into KV */, va._names.clone(), va.vecs().clone());
try {
String[] msgs = Model.adaptTestForTrain(_train._names, _parms._weights_column, _parms._offset_column, _parms._fold_column, null, _train.domains(), _valid, _parms.missingColumnsType(), expensive, true);
_vresponse = _valid.vec(_parms._response_column);
if (_vresponse == null && _parms._response_column != null)
error("_validation_frame", "Validation frame must have a response column '" + _parms._response_column + "'.");
if (expensive) {
for (String s : msgs) {
Log.info(s);
warn("_valid", s);
}
}
assert !expensive || (_valid == null || Arrays.equals(_train._names, _valid._names));
} catch (IllegalArgumentException iae) {
error("_valid", iae.getMessage());
}
} else {
_valid = null;
_vresponse = null;
}
if (_parms._checkpoint != null && DKV.get(_parms._checkpoint) == null) {
error("_checkpoint", "Checkpoint has to point to existing model!");
}
if (_parms._stopping_tolerance < 0) {
error("_stopping_tolerance", "Stopping tolerance must be >= 0.");
}
if (_parms._stopping_tolerance >= 1) {
error("_stopping_tolerance", "Stopping tolerance must be < 1.");
}
if (_parms._stopping_rounds == 0) {
if (_parms._stopping_metric != ScoreKeeper.StoppingMetric.AUTO)
warn("_stopping_metric", "Stopping metric is ignored for _stopping_rounds=0.");
if (_parms._stopping_tolerance != _parms.defaultStoppingTolerance())
warn("_stopping_tolerance", "Stopping tolerance is ignored for _stopping_rounds=0.");
} else if (_parms._stopping_rounds < 0) {
error("_stopping_rounds", "Stopping rounds must be >= 0.");
} else {
if (isClassifier()) {
if (_parms._stopping_metric == ScoreKeeper.StoppingMetric.deviance) {
error("_stopping_metric", "Stopping metric cannot be deviance for classification.");
}
if (nclasses()!=2 && _parms._stopping_metric == ScoreKeeper.StoppingMetric.AUC) {
error("_stopping_metric", "Stopping metric cannot be AUC for multinomial classification.");
}
} else {
if (_parms._stopping_metric == ScoreKeeper.StoppingMetric.misclassification ||
_parms._stopping_metric == ScoreKeeper.StoppingMetric.AUC ||
_parms._stopping_metric == ScoreKeeper.StoppingMetric.logloss)
{
error("_stopping_metric", "Stopping metric cannot be " + _parms._stopping_metric.toString() + " for regression.");
}
}
}
}
/**
* Rebalance a frame for load balancing
* @param original_fr Input frame
* @param local Whether to only create enough chunks to max out all cores on one node only
* @param name Name of rebalanced frame
* @return Frame that has potentially more chunks
*/
protected Frame rebalance(final Frame original_fr, boolean local, final String name) {
if (original_fr == null) return null;
int chunks = desiredChunks(original_fr, local);
if (original_fr.anyVec().nChunks() >= chunks) {
if (chunks>1)
Log.info(name.substring(name.length()-5)+ " dataset already contains " + original_fr.anyVec().nChunks() +
" chunks. No need to rebalance.");
return original_fr;
}
Log.info("Rebalancing " + name.substring(name.length()-5) + " dataset into " + chunks + " chunks.");
Key newKey = Key.make(name + ".chunks" + chunks);
RebalanceDataSet rb = new RebalanceDataSet(original_fr, newKey, chunks);
H2O.submitTask(rb).join();
Frame rebalanced_fr = DKV.get(newKey).get();
Scope.track(rebalanced_fr);
return rebalanced_fr;
}
/**
* Find desired number of chunks. If fewer, dataset will be rebalanced.
* @return Lower bound on number of chunks after rebalancing.
*/
protected int desiredChunks(final Frame original_fr, boolean local) {
return Math.min((int) Math.ceil(original_fr.numRows() / 1e3), H2O.NUMCPUS);
}
public void checkDistributions() {
if (_parms._distribution == Distribution.Family.poisson) {
if (_response.min() < 0)
error("_response", "Response must be non-negative for Poisson distribution.");
} else if (_parms._distribution == Distribution.Family.gamma) {
if (_response.min() < 0)
error("_response", "Response must be non-negative for Gamma distribution.");
} else if (_parms._distribution == Distribution.Family.tweedie) {
if (_parms._tweedie_power >= 2 || _parms._tweedie_power <= 1)
error("_tweedie_power", "Tweedie power must be between 1 and 2.");
if (_response.min() < 0)
error("_response", "Response must be non-negative for Tweedie distribution.");
}
}
protected transient HashSet<String> _removedCols = new HashSet<String>();
abstract class FilterCols {
final int _specialVecs; // special vecs to skip at the end
public FilterCols(int n) {_specialVecs = n;}
abstract protected boolean filter(Vec v);
void doIt( Frame f, String msg, boolean expensive ) {
boolean any=false;
for( int i = 0; i < f.vecs().length - _specialVecs; i++ ) {
if( filter(f.vecs()[i]) ) {
if( any ) msg += ", "; // Log dropped cols
any = true;
msg += f._names[i];
_removedCols.add(f._names[i]);
f.remove(i);
i--; // Re-run at same iteration after dropping a col
}
}
if( any ) {
warn("_train", msg);
if (expensive) Log.info(msg);
}
}
}
}
|
package example;
//-*- mode:java; encoding:utf-8 -*-
// vim:set fileencoding=utf-8:
//@homepage@
import java.awt.*;
import java.awt.event.*;
import java.util.Objects;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.table.*;
public final class MainPanel extends JPanel {
private MainPanel() {
super(new BorderLayout());
DefaultListModel<String> listModel = new DefaultListModel<>();
TestModel model = new TestModel(listModel);
model.addTest(new Test("Name 1", "comment"));
model.addTest(new Test("Name 2", "test"));
model.addTest(new Test("Name d", "ee"));
model.addTest(new Test("Name c", "test cc"));
model.addTest(new Test("Name b", "test bb"));
model.addTest(new Test("Name a", "ff"));
model.addTest(new Test("Name 0", "test aa"));
model.addTest(new Test("Name 0", "gg"));
JTable table = new JTable(model);
table.setCellSelectionEnabled(true);
JTableHeader header = table.getTableHeader();
header.addMouseListener(new MouseAdapter() {
@Override public void mousePressed(MouseEvent e) {
if (table.isEditing()) {
table.getCellEditor().stopCellEditing();
}
int col = header.columnAtPoint(e.getPoint());
table.changeSelection(0, col, false, false);
table.changeSelection(table.getRowCount() - 1, col, false, true);
}
});
RowHeaderList<String> rowHeader = new RowHeaderList<>(listModel, table);
rowHeader.setFixedCellWidth(50);
JScrollPane scroll = new JScrollPane(table);
scroll.setRowHeaderView(rowHeader);
scroll.getRowHeader().addChangeListener(e -> {
JViewport viewport = (JViewport) e.getSource();
scroll.getVerticalScrollBar().setValue(viewport.getViewPosition().y);
});
scroll.setComponentPopupMenu(new TablePopupMenu());
table.setInheritsPopupMenu(true);
rowHeader.setBackground(Color.BLUE);
scroll.setBackground(Color.RED);
scroll.getViewport().setBackground(Color.GREEN);
add(scroll);
setPreferredSize(new Dimension(320, 240));
}
public static void main(String... args) {
EventQueue.invokeLater(new Runnable() {
@Override public void run() {
createAndShowGUI();
}
});
}
public static void createAndShowGUI() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException
| IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
JFrame frame = new JFrame("@title@");
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.getContentPane().add(new MainPanel());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}
class RowHeaderList<E> extends JList<E> {
protected final JTable table;
protected final ListSelectionModel tableSelection;
protected final ListSelectionModel rListSelection;
protected int rollOverRowIndex = -1;
protected int pressedRowIndex = -1;
protected RowHeaderList(ListModel<E> model, JTable table) {
super(model);
this.table = table;
setFixedCellHeight(table.getRowHeight());
setCellRenderer(new RowHeaderRenderer<>(table.getTableHeader()));
//setSelectionModel(table.getSelectionModel());
RollOverListener rol = new RollOverListener();
addMouseListener(rol);
addMouseMotionListener(rol);
//setBorder(BorderFactory.createMatteBorder(1, 0, 0, 0, Color.GRAY.brighter()));
tableSelection = table.getSelectionModel();
rListSelection = getSelectionModel();
}
class RowHeaderRenderer<E2> extends JLabel implements ListCellRenderer<E2> {
private final JTableHeader header; // = table.getTableHeader();
protected RowHeaderRenderer(JTableHeader header) {
super();
this.header = header;
this.setOpaque(true);
//this.setBorder(UIManager.getBorder("TableHeader.cellBorder"));
this.setBorder(BorderFactory.createMatteBorder(0, 0, 1, 2, Color.GRAY.brighter()));
this.setHorizontalAlignment(CENTER);
this.setForeground(header.getForeground());
this.setBackground(header.getBackground());
this.setFont(header.getFont());
}
@Override public Component getListCellRendererComponent(JList<? extends E2> list, E2 value, int index, boolean isSelected, boolean cellHasFocus) {
if (index == pressedRowIndex) {
setBackground(Color.GRAY);
} else if (index == rollOverRowIndex) {
setBackground(Color.WHITE);
} else if (isSelected) {
setBackground(Color.GRAY.brighter());
} else {
setForeground(header.getForeground());
setBackground(header.getBackground());
}
setText(Objects.toString(value, ""));
return this;
}
}
class RollOverListener extends MouseAdapter {
@Override public void mouseExited(MouseEvent e) {
if (pressedRowIndex < 0) {
//pressedRowIndex = -1;
rollOverRowIndex = -1;
repaint();
}
}
@Override public void mouseMoved(MouseEvent e) {
int row = locationToIndex(e.getPoint());
if (row != rollOverRowIndex) {
rollOverRowIndex = row;
repaint();
}
}
@Override public void mouseDragged(MouseEvent e) {
if (pressedRowIndex >= 0) {
int row = locationToIndex(e.getPoint());
int start = Math.min(row, pressedRowIndex);
int end = Math.max(row, pressedRowIndex);
tableSelection.clearSelection();
rListSelection.clearSelection();
tableSelection.addSelectionInterval(start, end);
rListSelection.addSelectionInterval(start, end);
repaint();
}
}
@Override public void mousePressed(MouseEvent e) {
int row = locationToIndex(e.getPoint());
if (row == pressedRowIndex) {
return;
}
rListSelection.clearSelection();
table.changeSelection(row, 0, false, false);
table.changeSelection(row, table.getColumnModel().getColumnCount() - 1, false, true);
pressedRowIndex = row;
// table.setRowSelectionInterval(row, row);
// table.getSelectionModel().setSelectionInterval(row, row);
// tableSelection.clearSelection();
// table.getSelectionModel().setAnchorSelectionIndex(row);
// table.getSelectionModel().setLeadSelectionIndex(row);
// tableSelection.addSelectionInterval(row, row);
// rListSelection.addSelectionInterval(row, row);
// table.getColumnModel().getSelectionModel().setAnchorSelectionIndex(0);
// table.getColumnModel().getSelectionModel().setLeadSelectionIndex(0);
// table.changeSelection(pressedRowIndex, table.getColumnModel().getColumnCount() - 1, false, true);
}
@Override public void mouseReleased(MouseEvent e) {
rListSelection.clearSelection();
pressedRowIndex = -1;
rollOverRowIndex = -1;
repaint();
}
}
}
class TestModel extends DefaultTableModel {
private static final ColumnContext[] COLUMN_ARRAY = {
//new ColumnContext("No.", Integer.class, false),
new ColumnContext("Name", String.class, false),
new ColumnContext("Comment", String.class, false)
};
private int number;
private final DefaultListModel<String> rowListModel;
protected TestModel(DefaultListModel<String> lm) {
super();
rowListModel = lm;
}
public void addTest(Test t) {
Object[] obj = {t.getName(), t.getComment()};
super.addRow(obj);
rowListModel.addElement("row" + number);
number++;
}
@Override public void removeRow(int index) {
super.removeRow(index);
rowListModel.remove(index);
}
@Override public boolean isCellEditable(int row, int col) {
return COLUMN_ARRAY[col].isEditable;
}
@Override public Class<?> getColumnClass(int column) {
return COLUMN_ARRAY[column].columnClass;
}
@Override public int getColumnCount() {
return COLUMN_ARRAY.length;
}
@Override public String getColumnName(int column) {
return COLUMN_ARRAY[column].columnName;
}
private static class ColumnContext {
public final String columnName;
public final Class columnClass;
public final boolean isEditable;
protected ColumnContext(String columnName, Class columnClass, boolean isEditable) {
this.columnName = columnName;
this.columnClass = columnClass;
this.isEditable = isEditable;
}
}
}
class Test {
private String name;
private String comment;
protected Test(String name, String comment) {
this.name = name;
this.comment = comment;
}
public void setName(String str) {
name = str;
}
public void setComment(String str) {
comment = str;
}
public String getName() {
return name;
}
public String getComment() {
return comment;
}
}
class TablePopupMenu extends JPopupMenu {
private final Action addAction = new AbstractAction("add") {
@Override public void actionPerformed(ActionEvent e) {
JTable table = (JTable) getInvoker();
TestModel model = (TestModel) table.getModel();
model.addTest(new Test("add row", ""));
Rectangle rect = table.getCellRect(model.getRowCount() - 1, 0, true);
table.scrollRectToVisible(rect);
}
};
private final Action deleteAction = new AbstractAction("delete") {
@Override public void actionPerformed(ActionEvent e) {
JTable table = (JTable) getInvoker();
DefaultTableModel model = (DefaultTableModel) table.getModel();
int[] selection = table.getSelectedRows();
for (int i = selection.length - 1; i >= 0; i
model.removeRow(table.convertRowIndexToModel(selection[i]));
}
}
};
protected TablePopupMenu() {
super();
add(addAction);
addSeparator();
add(deleteAction);
}
@Override public void show(Component c, int x, int y) {
if (c instanceof JTable) {
deleteAction.setEnabled(((JTable) c).getSelectedRowCount() > 0);
super.show(c, x, y);
}
}
}
|
package bat_nav;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import javax.swing.AbstractAction;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.JButton;
public class Joueur {
//Contient le score, historique, les bateaux qu'il reste
Joueur(int score)
{
}
}
class CreationJoueur extends JFrame{ // A voir ou mettre
private JLabel label;
private JTextField t;
private JPanel buildContentPane(){ // Creation TextBox
JPanel panel = new JPanel();
panel.setLayout(new FlowLayout());
t = new JTextField();
panel.add(t);
label = new JLabel("Rien pour le moment");
panel.add(label);
JButton bouton = new JButton(new GetAction(this, "Ok"));
panel.add(bouton);
return panel;
}
public JTextField getTextField(){
return t;
}
public JLabel getLabel(){
return label;
}
}
class GetAction extends AbstractAction { //Recuperation name
private CreationJoueur fenetre;
private String name;
public GetAction(CreationJoueur fenetre, String texte){
super(texte);
this.fenetre = fenetre;
}
public void actionPerformed(ActionEvent e) {
name = fenetre.getTextField().getText();
fenetre.getLabel().setText(name);
}
}
|
package battle;
public class Fighter {
public boolean removeStatus(Status status) {
throw new UnsupportedOperationException("Not supported yet.");
}
}
|
package battle;
import java.util.ArrayList;
import java.util.List;
public class Fighter implements Actor {
/**
* @see FighterBuilder#setName
*/
private final String name;
/**
* @see FighterBuilder#setCloseRange
*/
private final int closeRange;
/**
* @see FighterBuilder#addSkill
*/
private final List<Skill> skillList;
/**
* @see Fighter#applyStatus
*/
private final List<Status> statusList;
/**
* Initializes the object so that all internal field variables that can be
* explicitly set are done so through the given parameters. See the {@link
* FighterBuilder} class which allows you to create Fighter objects using a
* builder pattern.
* @param name {@see FighterBuilder#setName}
* @param closeRange {@see FighterBuilder#setCloseRange}
* @param skillList {@see FighterBuilder#addSkill}
*/
public Fighter(String name, int closeRange, List<Skill> skillList) {
this.name = name;
this.closeRange = closeRange;
this.skillList = skillList;
this.statusList = new ArrayList<>();
}
/**
* Attempts to apply the given Status object to the fighter. Returns {@code
* true} if the predicate for its application returned {@code true}.
* @param status status to be applied.
* @return {@code true} if the status was applied.
*/
public boolean applyStatus(Status status) {
throw new UnsupportedOperationException("Not supported yet.");
}
/**
* Attempts to remove the given Status object from the fighter. Returns {@code
* true} if the object was both found and if the predicate for its removal
* returned {@code true}. This method will only remove the Status object
* given.
* @param status the status to be removed.
* @return {@code true} if the status was removed.
* @see #removeStatus(String name)
*/
public boolean removeStatus(Status status) {
throw new UnsupportedOperationException("Not supported yet.");
}
/**
* Attempts to remove any Status object matching the given name from the
* fighter. Returns {@code true} if a match was both found and if the
* predicate for its removal returned {@code true}.
* @param name name of the status to be removed.
* @return {@code true} if the status was removed.
*/
public boolean removeStatus(String name) {
throw new UnsupportedOperationException("Not supported yet.");
}
/**
* Tells the fighter to attempt to execute the given skill. Returns true if
* the skill or any sub-skill was successfully executed. The order in which
* the given skill is executed is as such:<br><ol>
* <li>The battlefield is checked for any valid targets that meet the skill's
* requirements. Valid targets must match the target criteria of the skill.
* The targets must also have all of the matching Status objects found in
* the Skill object's list of requirements. If no valid targets are found,
* then execution fails and this method returns false.</li>
* <li>All Skill objects found in the list of sub-skills is executed
* recursively using this method. If all calls return false, then the Skill
* fails and this method returns false. If there are no sub-skills, the
* passed skill succeeds and applies its actions to valid targets. Up to
* the skill's maximum targets property can be affected by the skill,
* starting with those closest to the fighter.</li>
* <li>If any but not all sub-skill executions return true, this Skill fails
* to apply its actions but returns true. If all sub-skill executions
* return true, this Skill succeeds and applies its actions to valid
* targets. Up to the skill's maximum targets property can be affected by
* the skill, starting with those closest to the fighter. This method would
* then return true. </li></ol>
* Note that valid targets that meet the requirements are checked both before
* and after sub-skills are executed. It is possible to create a skill that
* can never apply its actions. This will be so if your sub-skills applis a
* status that in turn removes a status that the primary skill requires, or if
* it applies a status that defeats would-be targets.
* @param skill the skill attempting to be executed.
* @return {@code true} if the skill or any sub-Skill successfully executed.
*/
public boolean executeSkill(Skill skill) {
throw new UnsupportedOperationException("Not supported yet.");
}
/**
* @return close range property of the fighter.
* @see FighterBuilder#setCloseRange
*/
public int getCloseRange() {
throw new UnsupportedOperationException("Not supported yet.");
}
/**
* Returns {@code true} if this fighter is an ally of the given fighter.
* @param fighter fighter to test allied relationship with.
* @return {@code true} if given fighter is an ally.
*/
boolean isAlly(Fighter fighter) {
throw new UnsupportedOperationException("Not supported yet.");
}
/**
* Returns {@code true} if this fighter is an enemy of the given fighter.
* @param fighter fighter to test enemy relationship with.
* @return {@code true} if given fighter is an enemy.
*/
boolean isEnemy(Fighter fighter) {
throw new UnsupportedOperationException("Not supported yet.");
}
/**
* Returns {@code true} if the fighter has a status applied to it that stuns
* it.
* @return {@code true} if stunned.
*/
public boolean isStunned() {
throw new UnsupportedOperationException("Not supported yet.");
}
/**
* Returns {@code true} if the fighter has a status applied to it that defeats
* it.
* @return {@code true} if defeated.
*/
public boolean isDefeated() {
throw new UnsupportedOperationException("Not supported yet.");
}
}
|
package hash;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.channels.FileChannel.MapMode;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.logging.Logger;
/**
* Generates a SHA-2 Hash for binary data, and formats the value into
* a Hex representation.
*/
public class HashMaker {
private static Logger logger = Logger.getLogger(HashMaker.class.getName());
MessageDigest md = null;
String key;
byte[] rawHash;
/**
* Generate a Hash value for binary data.
* @param data Binary data
* @return hash Hash as a hex value
*/
public String hash(byte[] data){
if(md == null){
try {
md = MessageDigest.getInstance("SHA-256");
} catch (NoSuchAlgorithmException e1) {
logger.severe(e1.getMessage());
return null;
}
}
if(data == null){
logger.severe("No data");
return null;
}
md.reset();
rawHash = md.digest(data);
key = toHex(rawHash);
return key;
}
public String hashFile(File file) {
if (md == null) {
try {
md = MessageDigest.getInstance("SHA-256");
} catch (NoSuchAlgorithmException e1) {
logger.severe(e1.getMessage());
return null;
}
}
if(file == null){
return null;
}
key = null;
FileInputStream stream;
stream = null;
try {
final FileChannel channel;
final MappedByteBuffer buffer;
final int fileSize;
stream = new FileInputStream(file);
channel = stream.getChannel();
buffer = channel.map(MapMode.READ_ONLY, 0, file.length());
fileSize = (int) file.length();
for (int i = 0; i < fileSize; i++) {
md.update(buffer.get());
}
rawHash = md.digest();
key = toHex(rawHash);
} catch (final IOException ex) {
ex.printStackTrace();
} finally {
if (stream != null) {
try {
stream.close();
} catch (final IOException ex) {
ex.printStackTrace();
}
}
}
return key;
}
/**
* Converts binary values to Hex.
* @param conv binary value to convert to a string.
* @return string representation of binary value
*/
private String toHex (byte[] conv){
String str ="";
String chk = "";
int tmp = 0;
for (byte b : conv){
tmp = b;
if (tmp <0)
tmp += 256;
chk = Integer.toHexString(tmp).toUpperCase();
if (chk.length() != 2)
chk = "0"+chk;
str += chk;
}
return str;
}
}
|
package ccw.launching;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.Path;
import org.eclipse.debug.core.ILaunch;
import org.eclipse.debug.core.ILaunchConfiguration;
import org.eclipse.debug.core.ILaunchConfigurationWorkingCopy;
import org.eclipse.jdt.core.IJavaProject;
import org.eclipse.jdt.core.IPackageFragment;
import org.eclipse.jdt.core.IPackageFragmentRoot;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.launching.IJavaLaunchConfigurationConstants;
import ccw.CCWPlugin;
import ccw.ClojureCore;
import ccw.util.IOUtils;
import ccw.util.StringUtils;
public final class LaunchUtils implements IJavaLaunchConfigurationConstants {
private LaunchUtils(){}
static public final String LAUNCH_ID = "ccw.launching.clojure";
static public final String MAIN_CLASSNAME = "clojure.main";
static public final String MAIN_CLASSNAME_FOR_REPL = "clojure.contrib.repl_ln";
static public final int DEFAULT_SERVER_PORT = -1;
/** Launch attribute that will be of type String, the files will be listed separated by newlines */
static public final String ATTR_FILES_LAUNCHED_AT_STARTUP = "CCW_ATTR_FILES_LAUNCHED_AT_STARTUP";
public static final String ATTR_CLOJURE_SERVER_LISTEN = "CCW_ATTR_CLOJURE_SERVER_LISTEN";
public static final String ATTR_CLOJURE_SERVER_FILE_PORT = "ccw.debug.serverrepl.file.port";
public static final String SERVER_FILE_PORT_PREFIX = "ccw.debug.serverrepl.port-";
public static final String SERVER_FILE_PORT_SUFFFIX = ".port";
public static final String ATTR_CLOJURE_INSTALL_REPL = "CCW_ATTR_CLOJURE_INSTALL_REPL";
/**
* @param files
* @param lastFileAsScript if true, does not install the last arg as a resource to load, but as
* a script to launch
* @return
*/
static public String getProgramArguments(IProject project, IFile[] files, boolean lastFileAsScript) {
StringBuilder args = new StringBuilder();
int lastIndex = lastFileAsScript ? files.length - 1 : files.length;
for (int i = 0; i < lastIndex; i++) {
String fileArg = fileArg(project, files[i]);
if (!StringUtils.isEmpty(fileArg)) {
args.append(" -i" + fileArg);
}
}
if (lastFileAsScript) {
args.append(fileArg(project, files[lastIndex]));
}
return args.toString();
}
public static IProject getProject(ILaunchConfiguration configuration) throws CoreException {
String projectName = configuration.getAttribute(LaunchUtils.ATTR_PROJECT_NAME, (String) null);
if (projectName == null) {
return null;
} else {
return ResourcesPlugin.getWorkspace().getRoot().getProject(projectName);
}
}
private static String fileArg(IProject project, IFile file) {
String FILE_ARG_ERROR_PREFIX = "When trying to create clojure.main "
+ "file arg to launch, was " + "unable to ";
IPath filePath = file.getLocation();
IJavaProject javaProject = ClojureCore.getJavaProject(project);
try {
IPackageFragmentRoot filePFR = findPackageFragmentRoot(javaProject, filePath);
if (filePFR != null) {
IPath pfrPath = filePFR.getResource().getLocation();// getResource();
String classpathRelativeArg = filePath.makeRelativeTo(pfrPath).toString();
return " \"@/" + classpathRelativeArg + "\"";
} else {
CCWPlugin.logError(FILE_ARG_ERROR_PREFIX +
" find package fragment root for file "
+ file + " in project " + project);
return "";
}
} catch (JavaModelException jme) {
CCWPlugin.logError(FILE_ARG_ERROR_PREFIX +
" complete due to a JavaModelException finding package fragment root for file "
+ file + " in project " + project, jme);
return "";
}
}
private static IPackageFragmentRoot findPackageFragmentRoot(IJavaProject javaProject, IPath filePath) throws JavaModelException {
if (filePath.isEmpty() || filePath.isRoot()) {
return null;
} else {
IResource possibleFragmentResource = ResourcesPlugin.getWorkspace().getRoot().getFileForLocation(filePath);
if (possibleFragmentResource != null) {
filePath = possibleFragmentResource.getFullPath();
}
IPackageFragmentRoot fragment = javaProject.findPackageFragmentRoot(filePath);
if (fragment != null) {
return fragment;
} else {
return findPackageFragmentRoot(javaProject, filePath.removeLastSegments(1));
}
}
}
static public String getProgramArguments(IProject project, List<IFile> files, boolean lastFileAsScript) {
return getProgramArguments(project, files.toArray(new IFile[]{}), lastFileAsScript);
}
static public List<IFile> getFilesToLaunchList(ILaunchConfiguration config) throws CoreException {
List<IFile> selectedFiles = new ArrayList<IFile>();
for (String path : config.getAttribute(LaunchUtils.ATTR_FILES_LAUNCHED_AT_STARTUP, "").split("\n")) {
IResource rc = ResourcesPlugin.getWorkspace().getRoot().findMember(new Path(path));
if (rc instanceof IFile) {
selectedFiles.add((IFile) rc);
}
}
return selectedFiles;
}
static public String getFilesToLaunchAsCommandLineList(ILaunchConfiguration config, boolean lastFileAsScript) throws CoreException {
List<IFile> filesToLaunch = LaunchUtils.getFilesToLaunchList(config);
return LaunchUtils.getProgramArguments(getProject(config), filesToLaunch, lastFileAsScript);
}
static public void setFilesToLaunchString(ILaunchConfigurationWorkingCopy config, List<IFile> selectedFiles) {
StringBuilder filesAsString = new StringBuilder();
if (selectedFiles != null) {
for (int i = 0; i < selectedFiles.size(); i++) {
if (i != 0) {
filesAsString.append('\n');
}
filesAsString.append(selectedFiles.get(i).getFullPath());
}
}
config.setAttribute(LaunchUtils.ATTR_FILES_LAUNCHED_AT_STARTUP, filesAsString.toString());
}
static public int getLaunchServerReplPort(ILaunch launch) {
String portAttr = launch.getAttribute(LaunchUtils.ATTR_CLOJURE_SERVER_LISTEN);
int port;
if (portAttr == null || (port = Integer.valueOf(portAttr)) == -1) {
port = tryFindPort(launch);
if (port != -1) {
launch.setAttribute(LaunchUtils.ATTR_CLOJURE_SERVER_LISTEN, Integer.toString(port));
}
}
return port;
}
static private int tryFindPort(ILaunch launch) {
FileReader fr = null;
BufferedReader br = null;
try {
String filename = launch.getAttribute(LaunchUtils.ATTR_CLOJURE_SERVER_FILE_PORT);
if (filename != null) {
File f = new File(filename);
fr = new FileReader(f);
br = new BufferedReader(fr);
return Integer.valueOf(br.readLine());
}
} catch (IOException e) {
// maybe do not catch exception to not pollute log with false positives?
} catch (NumberFormatException e) {
// maybe do not catch exception to not pollute log with false positives?
} finally {
IOUtils.safeClose(br);
IOUtils.safeClose(fr);
}
return -1;
}
}
|
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package org.broad.igv.sam;
import com.google.common.base.Predicate;
import org.apache.log4j.Logger;
import org.broad.igv.data.Interval;
import org.broad.igv.feature.FeatureUtils;
import org.broad.igv.feature.Locus;
import org.broad.igv.feature.SpliceJunctionFeature;
import org.broad.igv.feature.Strand;
import org.broad.igv.feature.genome.Genome;
import org.broad.igv.feature.genome.GenomeManager;
import org.broad.igv.ui.panel.ReferenceFrame;
import org.broad.tribble.Feature;
import java.util.*;
import static org.broad.igv.util.collections.CollUtils.filter;
/**
* @author jrobinso
*/
public class AlignmentInterval extends Locus implements Interval {
private static Logger log = Logger.getLogger(AlignmentInterval.class);
Genome genome;
private int maxCount = 0;
private AlignmentCounts counts;
private LinkedHashMap<String, List<Row>> groupedAlignmentRows; // The alignments
private List<SpliceJunctionFeature> spliceJunctions;
private List<DownsampledInterval> downsampledIntervals;
private AlignmentTrack.RenderOptions renderOptions;
public AlignmentInterval(String chr, int start, int end,
LinkedHashMap<String, List<Row>> groupedAlignmentRows,
AlignmentCounts counts,
List<SpliceJunctionFeature> spliceJunctions,
List<DownsampledInterval> downsampledIntervals,
AlignmentTrack.RenderOptions renderOptions) {
super(chr, start, end);
this.groupedAlignmentRows = groupedAlignmentRows;
genome = GenomeManager.getInstance().getCurrentGenome();
//reference = genome.getSequence(chr, start, end);
this.counts = counts;
this.maxCount = counts.getMaxCount();
this.spliceJunctions = spliceJunctions;
this.downsampledIntervals = downsampledIntervals;
this.renderOptions = renderOptions;
}
static AlignmentInterval emptyAlignmentInterval(String chr, int start, int end) {
return new AlignmentInterval(chr, start, end, null, null, null, null, null);
}
static Alignment getFeatureContaining(List<Alignment> features, int right) {
int leftBounds = 0;
int rightBounds = features.size() - 1;
int idx = features.size() / 2;
int lastIdx = -1;
while (idx != lastIdx) {
lastIdx = idx;
Alignment f = features.get(idx);
if (f.contains(right)) {
return f;
}
if (f.getStart() > right) {
rightBounds = idx;
idx = (leftBounds + idx) / 2;
} else {
leftBounds = idx;
idx = (rightBounds + idx) / 2;
}
}
// Check the extremes
if (features.get(0).contains(right)) {
return features.get(0);
}
if (features.get(rightBounds).contains(right)) {
return features.get(rightBounds);
}
return null;
}
/**
* The "packed" alignments in this interval
*/
public LinkedHashMap<String, List<Row>> getGroupedAlignments() {
return groupedAlignmentRows;
}
public int getGroupCount() {
return groupedAlignmentRows == null ? 0 : groupedAlignmentRows.size();
}
public void setAlignmentRows(LinkedHashMap<String, List<Row>> alignmentRows, AlignmentTrack.RenderOptions renderOptions) {
this.groupedAlignmentRows = alignmentRows;
this.renderOptions = renderOptions;
}
public void sortRows(AlignmentTrack.SortOption option, ReferenceFrame referenceFrame, String tag) {
double center = referenceFrame.getCenter();
sortRows(option, center, tag);
}
/**
* Sort rows group by group
*
* @param option
* @param location
*/
public void sortRows(AlignmentTrack.SortOption option, double location, String tag) {
if (groupedAlignmentRows == null) {
return;
}
for (List<AlignmentInterval.Row> alignmentRows : groupedAlignmentRows.values()) {
for (AlignmentInterval.Row row : alignmentRows) {
row.updateScore(option, location, this, tag);
}
Collections.sort(alignmentRows);
}
}
public byte getReference(int pos) {
if (genome == null) {
return 0;
}
return genome.getReference(getChr(), pos);
}
public AlignmentCounts getCounts() {
return counts;
}
/**
* Return the count of the specified nucleotide
*
* @param pos genomic position
* @param b nucleotide
* @return
*/
public int getCount(int pos, byte b) {
AlignmentCounts c = counts;
if (pos >= c.getStart() && pos < c.getEnd()) {
return c.getCount(pos, b);
}
return 0;
}
public int getMaxCount() {
return maxCount;
}
public AlignmentCounts getAlignmentCounts(int pos) {
AlignmentCounts c = counts;
if (pos >= c.getStart() && pos < c.getEnd()) {
return c;
}
return null;
}
public int getTotalCount(int pos) {
AlignmentCounts c = counts;
if (pos >= c.getStart() && pos < c.getEnd()) {
return c.getTotalCount(pos);
}
return 0;
}
public int getNegCount(int pos, byte b) {
AlignmentCounts c = counts;
if (pos >= c.getStart() && pos < c.getEnd()) {
return c.getNegCount(pos, b);
}
return 0;
}
public int getPosCount(int pos, byte b) {
AlignmentCounts c = counts;
if (pos >= c.getStart() && pos < c.getEnd()) {
return c.getPosCount(pos, b);
}
return 0;
}
public int getDelCount(int pos) {
AlignmentCounts c = counts;
if (pos >= c.getStart() && pos < c.getEnd()) {
return c.getDelCount(pos);
}
return 0;
}
public int getInsCount(int pos) {
AlignmentCounts c = counts;
if (pos >= c.getStart() && pos < c.getEnd()) {
return c.getInsCount(pos);
}
return 0;
}
public Iterator<Alignment> getAlignmentIterator() {
return new AlignmentIterator();
}
public List<SpliceJunctionFeature> getSpliceJunctions() {
return spliceJunctions;
}
public List<DownsampledInterval> getDownsampledIntervals() {
return downsampledIntervals;
}
@Override
public boolean contains(String chr, int start, int end, int zoom) {
return super.contains(chr, start, end);
}
@Override
public boolean overlaps(String chr, int start, int end, int zoom) {
return super.overlaps(chr, start, end);
}
@Override
public boolean canMerge(Interval i) {
if (!super.overlaps(i.getChr(), i.getStart(), i.getEnd())
|| !(i instanceof AlignmentInterval)) {
return false;
}
return getCounts().getClass().equals(((AlignmentInterval) i).getCounts().getClass());
}
@Override
public boolean merge(Interval i) {
boolean canMerge = this.canMerge(i);
if (!canMerge) return false;
AlignmentInterval other = (AlignmentInterval) i;
List<Alignment> allAlignments = (List<Alignment>) FeatureUtils.combineSortedFeatureListsNoDups(
getAlignmentIterator(), other.getAlignmentIterator(), start, end);
this.counts = counts.merge(other.getCounts(), renderOptions.bisulfiteContext);
this.spliceJunctions = FeatureUtils.combineSortedFeatureListsNoDups(this.spliceJunctions, other.getSpliceJunctions(), start, end);
this.downsampledIntervals = FeatureUtils.combineSortedFeatureListsNoDups(this.downsampledIntervals, other.getDownsampledIntervals(), start, end);
//This must be done AFTER calling combineSortedFeatureListsNoDups for the last time,
//because we rely on the original start/end
this.start = Math.min(getStart(), i.getStart());
this.end = Math.max(getEnd(), i.getEnd());
this.maxCount = Math.max(this.getMaxCount(), other.getMaxCount());
AlignmentPacker packer = new AlignmentPacker();
this.groupedAlignmentRows = packer.packAlignments(allAlignments.iterator(), this.end, renderOptions);
return true;
}
/**
* Remove data outside the specified interval.
* This interval must contain the specified interval.
*
* @param chr
* @param start
* @param end
* @param zoom
* @return true if any trimming was performed, false if not
*/
public boolean trimTo(final String chr, final int start, final int end, int zoom) {
boolean toRet = false;
if (!this.contains(chr, start, end, zoom)) {
return false;
}
for (String groupKey : groupedAlignmentRows.keySet()) {
for (AlignmentInterval.Row row : groupedAlignmentRows.get(groupKey)) {
Iterator<Alignment> alIter = row.alignments.iterator();
Alignment al;
while (alIter.hasNext()) {
al = alIter.next();
if (al.getEnd() < start || al.getStart() > end) {
alIter.remove();
toRet |= true;
}
}
}
}
Predicate<Feature> overlapPredicate = FeatureUtils.getOverlapPredicate(chr, start, end);
//getCounts().trimTo(chr, start, end);
filter(this.getDownsampledIntervals(), overlapPredicate);
filter(this.getSpliceJunctions(), overlapPredicate);
this.start = Math.max(this.start, start);
this.end = Math.min(this.end, end);
return toRet;
}
private List addToListNoDups(List self, List other) {
if (self == null) self = new ArrayList();
if (other != null) {
Set selfSet = new HashSet(self);
selfSet.addAll(other);
self = new ArrayList(selfSet);
FeatureUtils.sortFeatureList(self);
}
return self;
}
/**
* AlignmentInterval data is independent of zoom
*
* @return
*/
@Override
public int getZoom() {
return -1;
}
public static class Row implements Comparable<Row> {
int nextIdx;
private double score = 0;
List<Alignment> alignments;
private int start;
private int lastEnd;
public Row() {
nextIdx = 0;
this.alignments = new ArrayList(100);
}
public void addAlignment(Alignment alignment) {
if (alignments.isEmpty()) {
this.start = alignment.getStart();
}
alignments.add(alignment);
lastEnd = alignment.getEnd();
}
public void updateScore(AlignmentTrack.SortOption option, Locus locus, AlignmentInterval interval, String tag) {
double mean = 0;
//double sd = 0;
int number = 0;
for (int center = locus.getStart(); center < locus.getEnd(); center++) {
double value = calculateScore(option, center, interval, tag);
mean = number * (mean / (number + 1)) + (value / (number + 1));
number++;
}
setScore(mean);
}
public void updateScore(AlignmentTrack.SortOption option, double center, AlignmentInterval interval, String tag) {
setScore(calculateScore(option, center, interval, tag));
}
public double calculateScore(AlignmentTrack.SortOption option, double center, AlignmentInterval interval, String tag) {
int adjustedCenter = (int) center;
Alignment centerAlignment = getFeatureContaining(alignments, adjustedCenter);
if (centerAlignment == null) {
return Integer.MAX_VALUE;
} else {
switch (option) {
case START:
return centerAlignment.getStart();
case STRAND:
return centerAlignment.isNegativeStrand() ? -1 : 1;
case FIRST_OF_PAIR_STRAND:
Strand strand = centerAlignment.getFirstOfPairStrand();
int score = 2;
if (strand != Strand.NONE) {
score = strand == Strand.NEGATIVE ? 1 : -1;
}
return score;
case NUCELOTIDE:
byte base = centerAlignment.getBase(adjustedCenter);
byte ref = interval.getReference(adjustedCenter);
if (base == 'N' || base == 'n') {
return 2; // Base is "n"
} else if (base == ref) {
return 3; // Base is reference
} else {
//If base is 0, base not covered (splice junction) or is deletion
if (base == 0) {
int delCount = interval.getDelCount(adjustedCenter);
if (delCount > 0) {
return -delCount;
} else {
//Base not covered, NOT a deletion
return 1;
}
} else {
int count = interval.getCount(adjustedCenter, base);
byte phred = centerAlignment.getPhred(adjustedCenter);
return -(count + (phred / 100.0f));
}
}
case QUALITY:
return -centerAlignment.getMappingQuality();
case SAMPLE:
String sample = centerAlignment.getSample();
score = sample == null ? 0 : sample.hashCode();
return score;
case READ_GROUP:
String readGroup = centerAlignment.getReadGroup();
score = readGroup == null ? 0 : readGroup.hashCode();
return score;
case INSERT_SIZE:
return -Math.abs(centerAlignment.getInferredInsertSize());
case MATE_CHR:
ReadMate mate = centerAlignment.getMate();
if (mate == null) {
return Integer.MAX_VALUE;
} else {
if (mate.getChr().equals(centerAlignment.getChr())) {
return Integer.MAX_VALUE - 1;
} else {
return mate.getChr().hashCode();
}
}
case TAG:
Object tagValue = centerAlignment.getAttribute(tag);
score = tagValue == null ? 0 : tagValue.hashCode();
return score;
default:
return Integer.MAX_VALUE;
}
}
}
// Used for iterating over all alignments, e.g. for packing
public Alignment nextAlignment() {
if (nextIdx < alignments.size()) {
Alignment tmp = alignments.get(nextIdx);
nextIdx++;
return tmp;
} else {
return null;
}
}
public int getNextStartPos() {
if (nextIdx < alignments.size()) {
return alignments.get(nextIdx).getStart();
} else {
return Integer.MAX_VALUE;
}
}
public boolean hasNext() {
return nextIdx < alignments.size();
}
public void resetIdx() {
nextIdx = 0;
}
/**
* @return the score
*/
public double getScore() {
return score;
}
/**
* @param score the score to set
*/
public void setScore(double score) {
this.score = score;
}
public int getStart() {
return start;
}
public int getLastEnd() {
return lastEnd;
}
@Override
public int compareTo(Row o) {
return (int) Math.signum(getScore() - o.getScore());
}
// @Override
// public boolean equals(Object object){
// if(!(object instanceof Row)){
// return false;
// Row other = (Row) object;
// boolean equals = this.getStart() == other.getStart();
// equals &= this.getLastEnd() == other.getLastEnd();
// equals &= this.getScore() == other.getScore();
// return equals;
// @Override
// public int hashCode(){
// int score = (int) getScore();
// score = score != 0 ? score : 1;
// return (getStart() * getLastEnd() * score);
} // end class row
/**
* An alignment iterator that iterates over packed rows. Used for
* "repacking". Using the iterator avoids the need to copy alignments
* from the rows
*/
class AlignmentIterator implements Iterator<Alignment> {
PriorityQueue<AlignmentInterval.Row> rows;
Alignment nextAlignment;
AlignmentIterator() {
rows = new PriorityQueue(5, new Comparator<AlignmentInterval.Row>() {
public int compare(AlignmentInterval.Row o1, AlignmentInterval.Row o2) {
return o1.getNextStartPos() - o2.getNextStartPos();
}
});
for (List<AlignmentInterval.Row> alignmentRows : groupedAlignmentRows.values()) {
for (AlignmentInterval.Row r : alignmentRows) {
r.resetIdx();
rows.add(r);
}
}
advance();
}
public boolean hasNext() {
return nextAlignment != null;
}
public Alignment next() {
Alignment tmp = nextAlignment;
if (tmp != null) {
advance();
}
return tmp;
}
private void advance() {
nextAlignment = null;
AlignmentInterval.Row nextRow = null;
while (nextAlignment == null && !rows.isEmpty()) {
while ((nextRow = rows.poll()) != null) {
if (nextRow.hasNext()) {
nextAlignment = nextRow.nextAlignment();
break;
}
}
}
if (nextRow != null && nextAlignment != null) {
rows.add(nextRow);
}
}
public void remove() {
// ignore
}
}
}
|
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package org.broad.igv.tools;
import net.sf.samtools.util.CloseableIterator;
import org.broad.igv.feature.*;
import org.broad.igv.feature.genome.Genome;
import org.broad.igv.sam.Alignment;
import org.broad.igv.sam.AlignmentBlock;
import org.broad.igv.sam.ReadMate;
import org.broad.igv.sam.reader.AlignmentQueryReader;
import org.broad.igv.sam.reader.MergedAlignmentReader;
import org.broad.igv.sam.reader.MergedAlignmentReader2;
import org.broad.igv.sam.reader.SamQueryReaderFactory;
import org.broad.igv.tools.parsers.DataConsumer;
import org.broad.igv.ui.filefilters.AlignmentFileFilter;
import org.broad.igv.util.FileUtils;
import org.broad.igv.util.stats.Distribution;
import org.broad.tribble.Feature;
import org.broad.tribble.util.HttpUtils;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.*;
import java.util.List;
/**
* TODO -- normalize option
*
-n Normalize the count by the total number of reads. This option
multiplies each count by (1,000,000 / total # of reads). It
is useful when comparing multiple chip-seq experiments when
the absolute coverage depth is not important.
*/
public class CoverageCounter {
private int upperExpectedInsertSize = 600;
private int lowerExpectedInsertSize = 200;
enum Event {
mismatch, indel, largeISize, smallISize, inversion, duplication, inter, unmappedMate
}
private String alignmentFile;
private File tdfFile;
private DataConsumer consumer;
private float[] buffer;
private int windowSize = 1;
// TODO -- make mapping qulaity a parameter
private int minMappingQuality = 0;
private int strandOption = -1;
private int extFactor;
private int totalCount = 0;
private File wigFile = null;
private WigWriter wigWriter = null;
private boolean keepZeroes = false;
private Genome genome;
private String readGroup; // The read group to count
Map<Event, WigWriter> writers = new HashMap();
private boolean computeTDF = true;
private Distribution coverageHistogram;
private static final double LOG_1__1 = 0.09531018;
private String interval = null;
// TODO Sigma hack
List<Feature> genes;
public CoverageCounter(String alignmentFile,
DataConsumer consumer,
int windowSize,
int extFactor,
File tdfFile, // For reference
File wigFile,
Genome genome,
int strandOption,
String options) {
this.alignmentFile = alignmentFile;
this.tdfFile = tdfFile;
this.consumer = consumer;
this.windowSize = windowSize;
this.extFactor = extFactor;
this.wigFile = wigFile;
this.genome = genome;
this.strandOption = strandOption;
buffer = strandOption < 0 ? new float[1] : new float[2];
if (options != null) {
parseOptions(options);
}
// TODO Sigma hack
genes = GeneManager.getGeneManager(genome.getId()).getGenesForChromosome("chr1");
}
private void parseOptions(String options) {
try {
String[] opts = options.split(",");
for (String opt : opts) {
if (opt.startsWith("l:")) {
String[] tmp = opt.split(":");
readGroup = tmp[1];
} else if (opt.startsWith("q")) {
String[] tmp = opt.split("@");
interval = tmp[1];
} else if (opt.startsWith("i")) {
writers.put(Event.largeISize, new WigWriter(new File(getFilenameBase() + ".large_isize.wig"), windowSize));
writers.put(Event.smallISize, new WigWriter(new File(getFilenameBase() + ".small_isize.wig"), windowSize));
// Optionally specify mean and std dev (todo -- just specify min and max)
String[] tokens = opt.split(":");
if (tokens.length > 2) {
//float median = Float.parseFloat(tokens[1]);
//float mad = Float.parseFloat(tokens[2]);
//upperExpectedInsertSize = (int) (median + 3 * mad);
//lowerExpectedInsertSize = Math.max(50, (int) (median - 3 * mad));
int min = Integer.parseInt(tokens[1]);
int max = Integer.parseInt(tokens[2]);
upperExpectedInsertSize = min;
lowerExpectedInsertSize = max;
} else {
PairedEndStats stats = PairedEndStats.compute(alignmentFile);
if (stats == null) {
System.out.println("Warning: error computing stats. Using default insert size settings");
} else {
//double median = stats.getMedianInsertSize();
//double mad = stats.getMadInsertSize();
//upperExpectedInsertSize = (int) (median + 3 * mad);
//lowerExpectedInsertSize = Math.max(50, (int) (median - 3 * mad));
upperExpectedInsertSize = (int) stats.getMaxPercentileInsertSize();
lowerExpectedInsertSize = (int) stats.getMinPercentileInsertSize();
System.out.println(alignmentFile + " min = " + lowerExpectedInsertSize + " max = " + upperExpectedInsertSize);
}
}
} else if (opt.equals("o")) {
writers.put(Event.inversion, new WigWriter(new File(getFilenameBase() + ".inversion.wig"), windowSize));
writers.put(Event.duplication, new WigWriter(new File(getFilenameBase() + ".duplication.wig"), windowSize));
} else if (opt.equals("m")) {
writers.put(Event.mismatch, new WigWriter(new File(getFilenameBase() + ".mismatch.wig"), windowSize));
} else if (opt.equals("d")) {
writers.put(Event.indel, new WigWriter(new File(getFilenameBase() + ".indel.wig"), windowSize));
} else if (opt.equals("u")) {
writers.put(Event.unmappedMate, new WigWriter(new File(getFilenameBase() + ".nomate.wig"), windowSize));
} else if (opt.equals("r")) {
writers.put(Event.inter, new WigWriter(new File(getFilenameBase() + ".inter.wig"), windowSize));
} else if (opt.equals("h")) {
coverageHistogram = new Distribution(200);
} else if (opt.equals("a")) {
keepZeroes = true;
} else {
System.out.println("Unknown coverage option: " + opt);
}
}
} catch (IOException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
}
private String getFilenameBase() {
String tmp = tdfFile.getAbsolutePath();
tmp = tmp.substring(0, tmp.length() - 4);
if (readGroup != null) {
tmp += "." + readGroup;
}
return tmp;
}
// TODO -- options to ovveride all of these checks
private boolean passFilter(Alignment alignment) {
return (readGroup == null || readGroup.equals(alignment.getReadGroup())) &&
alignment.isMapped() &&
!alignment.isDuplicate() &&
alignment.getMappingQuality() >= minMappingQuality &&
!alignment.isVendorFailedRead();
}
public void parse() {
int tolerance = (int) (windowSize * (Math.floor(extFactor / windowSize) + 2));
consumer.setSortTolerance(tolerance);
AlignmentQueryReader reader = null;
CloseableIterator<Alignment> iter = null;
String lastChr = "";
ReadCounter counter = null;
try {
if (wigFile != null) {
wigWriter = new WigWriter(wigFile, windowSize);
}
reader = getReader(alignmentFile, false);
if (interval == null) {
iter = reader.iterator();
} else {
Locus locus = new Locus(interval);
iter = reader.query(locus.getChr(), locus.getStart(), locus.getEnd(), false);
}
while (iter != null && iter.hasNext()) {
Alignment alignment = iter.next();
if (passFilter(alignment)) {
totalCount++;
String alignmentChr = alignment.getChr();
// Close all counters with position < alignment.getStart()
if (alignmentChr.equals(lastChr)) {
if (counter != null) {
counter.closeBucketsBefore(alignment.getAlignmentStart() - tolerance);
}
} else {
if (counter != null) {
counter.closeBucketsBefore(Integer.MAX_VALUE);
}
counter = new ReadCounter(alignmentChr);
lastChr = alignmentChr;
}
if (alignment.getMappingQuality() == 0) {
// TODO -- mq zero event
} else if (alignment.isPaired()) {
final int start = alignment.getStart();
final int end = alignment.getEnd();
counter.incrementPairedCount(start, end);
ReadMate mate = alignment.getMate();
boolean mateMapped = mate != null && mate.isMapped();
boolean sameChromosome = mateMapped && mate.getChr().equals(alignment.getChr());
if (mateMapped) {
if (sameChromosome) {
// Pair orientation
String oStr = alignment.getPairOrientation();
if (oStr.equals("R1F2") || oStr.equals("R2F1")) {
counter.incrementPairedEvent(start, end, Event.duplication);
} else if (oStr.equals("F1F2") || oStr.equals("F2F1") ||
oStr.equals("R1R2") || oStr.equals("R2R1")) {
counter.incrementPairedEvent(start, end, Event.inversion);
}
// Insert size
int isize = Math.abs(alignment.getInferredInsertSize());
if (isize > upperExpectedInsertSize) {
counter.incrementPairedEvent(start, end, Event.largeISize);
}
if (isize < lowerExpectedInsertSize) {
counter.incrementPairedEvent(start, end, Event.smallISize);
}
} else {
counter.incrementPairedEvent(start, end, Event.inter);
}
} else { // unmapped mate
counter.incrementPairedEvent(start, end, Event.unmappedMate);
}
}
AlignmentBlock[] blocks = alignment.getAlignmentBlocks();
if (blocks != null) {
int lastBlockEnd = -1;
for (AlignmentBlock block : blocks) {
if (!block.isSoftClipped()) {
if (lastBlockEnd >= 0) {
String c = alignment.getCigarString();
int s = block.getStart();
if (s > lastBlockEnd) {
counter.incrementEvent(lastBlockEnd, Event.indel);
}
}
byte[] bases = block.getBases();
int blockStart = block.getStart();
int adjustedStart = block.getStart();
int adjustedEnd = block.getEnd();
if (alignment.isNegativeStrand()) {
adjustedStart = Math.max(0, adjustedStart - extFactor);
} else {
adjustedEnd += extFactor;
}
for (int pos = adjustedStart; pos < adjustedEnd; pos++) {
byte base = 0;
int baseIdx = pos - blockStart;
if (bases != null && baseIdx >= 0 && baseIdx < bases.length) {
base = bases[baseIdx];
}
int idx = pos - blockStart;
byte quality = (idx >= 0 && idx < block.qualities.length) ?
block.qualities[pos - blockStart] : (byte) 0;
counter.incrementCount(pos, base, quality);
}
lastBlockEnd = block.getEnd();
}
}
} else {
int adjustedStart = alignment.getAlignmentStart();
int adjustedEnd = alignment.getAlignmentEnd();
if (alignment.isNegativeStrand()) {
adjustedStart = Math.max(0, adjustedStart - extFactor);
} else {
adjustedEnd += extFactor;
}
for (int pos = adjustedStart; pos < adjustedEnd; pos++) {
counter.incrementCount(pos, (byte) 0, (byte) 0);
}
}
if (writers.containsKey(Event.indel)) {
for (AlignmentBlock block : alignment.getInsertions()) {
counter.incrementEvent(block.getStart(), Event.indel);
}
}
}
}
}
catch (Exception e) {
e.printStackTrace();
}
finally {
if (counter != null) {
counter.closeBucketsBefore(Integer.MAX_VALUE);
}
consumer.setAttribute("totalCount", String.valueOf(totalCount));
consumer.parsingComplete();
if (iter != null) {
iter.close();
}
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
}
if (wigWriter != null) {
wigWriter.close();
}
for (WigWriter writer : writers.values()) {
writer.close();
}
if (coverageHistogram != null) {
try {
PrintWriter pw = new PrintWriter(new FileWriter(getFilenameBase() + ".hist.txt"));
coverageHistogram.print(pw);
pw.close();
} catch (IOException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
}
}
}
private AlignmentQueryReader getReader(String alignmentFile, boolean b) throws IOException {
boolean isList = alignmentFile.indexOf(",") > 0;
if (isList) {
String[] tokens = alignmentFile.split(",");
List<AlignmentQueryReader> readers = new ArrayList(tokens.length);
for (String f : tokens) {
readers.add(SamQueryReaderFactory.getReader(f, b));
}
return new MergedAlignmentReader(readers);
} else {
if (!FileUtils.isRemote(alignmentFile)) {
File f = new File(alignmentFile);
if (f.isDirectory()) {
List<AlignmentQueryReader> readers = new ArrayList();
for (File file : f.listFiles(new AlignmentFileFilter())) {
readers.add(SamQueryReaderFactory.getReader(file.getAbsolutePath(), b));
}
return new MergedAlignmentReader(readers);
}
}
return SamQueryReaderFactory.getReader(alignmentFile, b);
}
}
class ReadCounter {
String chr;
TreeMap<Integer, Counter> counts = new TreeMap();
ReadCounter(String chr) {
this.chr = chr;
}
void incrementCount(int position, byte base, byte quality) {
final Counter counter = getCounterForPosition(position);
counter.increment(position, base, quality);
}
void incrementEvent(int position, Event type) {
final Counter counter = getCounterForPosition(position);
counter.incrementEvent(type, 1);
}
void incrementPairedCount(int start, int end) {
int startIdx = start / windowSize;
int endIdx = end / windowSize;
for (int idx = startIdx; idx <= endIdx; idx++) {
Counter counter = getCounter(idx);
counter.incrementPairedCount(fractionOverlap(counter, start, end));
}
}
// frac should be between 0 and 1
void incrementPairedEvent(int start, int end, Event type) {
int startIdx = start / windowSize;
int endIdx = end / windowSize;
for (int idx = startIdx; idx <= endIdx; idx++) {
Counter counter = getCounter(idx);
counter.incrementEvent(type, fractionOverlap(counter, start, end));
}
}
// todo -- move to counter class?
float fractionOverlap(Counter counter, int start, int end) {
float counterLength = counter.end - counter.start;
float overlapLength = Math.min(end, counter.end) - Math.max(start, counter.start);
return overlapLength / counterLength;
}
//public void incrementISize(Alignment alignment) {
// int startBucket = alignment.getStart() / windowSize;
// int endBucket = alignment.getAlignmentEnd() / windowSize;
// for (int bucket = startBucket; bucket <= endBucket; bucket++) {
// int bucketStartPosition = bucket * windowSize;
// int bucketEndPosition = bucketStartPosition + windowSize;
// if (!counts.containsKey(bucket)) {
// counts.put(bucket, new Counter(chr, bucketStartPosition, bucketEndPosition));
// final Counter counter = counts.get(bucket);
// counter.incrementISize(alignment.getInferredInsertSize());
private Counter getCounterForPosition(int position) {
int idx = position / windowSize;
return getCounter(idx);
}
private Counter getCounter(int idx) {
if (!counts.containsKey(idx)) {
int counterStartPosition = idx * windowSize;
int counterEndPosition = counterStartPosition + windowSize;
counts.put(idx, new Counter(chr, counterStartPosition, counterEndPosition));
}
final Counter counter = counts.get(idx);
return counter;
}
//void incrementNegCount(int position) {
// Integer bucket = position / windowSize;
// if (!counts.containsKey(bucket)) {
// counts.put(bucket, new Counter());
// counts.get(bucket).incrementNeg();
void closeBucketsBefore(int position) {
List<Integer> bucketsToClose = new ArrayList();
Integer bucket = position / windowSize;
for (Map.Entry<Integer, Counter> entry : counts.entrySet()) {
if (entry.getKey() < bucket) {
// Divide total count by window size. This is the average count per
// base over the window, so 30x coverage remains 30x irrespective of window size.
int bucketStartPosition = entry.getKey() * windowSize;
int bucketEndPosition = bucketStartPosition + windowSize;
if (genome != null) {
Chromosome chromosome = genome.getChromosome(chr);
if (chromosome != null) {
bucketEndPosition = Math.min(bucketEndPosition, chromosome.getLength());
}
}
int bucketSize = bucketEndPosition - bucketStartPosition;
final Counter counter = entry.getValue();
buffer[0] = ((float) counter.getCount()) / bucketSize;
if (strandOption > 0) {
buffer[1] = ((float) counter.getCount()) / bucketSize;
}
consumer.addData(chr, bucketStartPosition, bucketEndPosition, buffer, null);
for (Map.Entry<Event, WigWriter> entries : writers.entrySet()) {
Event evt = entries.getKey();
WigWriter writer = entries.getValue();
float score = counter.getEventScore(evt);
writer.addData(chr, bucketStartPosition, bucketEndPosition, score);
}
if (wigWriter != null) {
wigWriter.addData(chr, bucketStartPosition, bucketEndPosition, buffer[0]);
}
if (coverageHistogram != null) {
List<Feature> transcripts = FeatureUtils.getAllFeaturesAt(bucketStartPosition, 10000, 5, genes, false);
if (transcripts != null && !transcripts.isEmpty()) {
boolean isCoding = false;
for (Feature t : transcripts) {
Exon exon = ((IGVFeature) t).getExonAt(bucketStartPosition);
if (exon != null && !exon.isUTR(bucketStartPosition)) {
isCoding = true;
break;
}
}
if (isCoding) {
int[] baseCounts = counter.getBaseCount();
for (int i = 0; i < baseCounts.length; i++) {
coverageHistogram.addDataPoint(baseCounts[i]);
}
}
}
}
bucketsToClose.add(entry.getKey());
}
}
for (Integer key : bucketsToClose) {
counts.remove(key);
}
}
}
/**
* Events
* base mismatch
* translocation
* insertion (small)
* insertion (large, rearrangment)
* deletion (small)
* deletion (large, rearrangment)
*/
class Counter {
int count = 0;
int negCount = 0;
int qualityCount = 0;
float pairedCount = 0;
float mismatchCount = 0;
float indelCount = 0;
float largeISizeCount = 0;
float smallISizeCount = 0;
float inversionCount = 0;
float duplicationCount = 0;
float unmappedMate = 0;
float interChrCount = 0;
float totalISizeCount = 0;
String chr;
int start;
int end;
byte[] ref;
int[] baseCount;
//int isizeCount = 0;
//float isizeZScore = 0;
//float totalIsize = 0;
Counter(String chr, int start, int end) {
this.chr = chr;
this.start = start;
this.end = end;
baseCount = new int[end - start];
ref = SequenceManager.readSequence(genome.getId(), chr, start, end);
}
int getCount() {
return count;
}
int getNegCount() {
return negCount;
}
void incrementNeg() {
negCount++;
}
// frac should be between 0 znd 1
void incrementPairedCount(float frac) {
pairedCount += frac;
}
public int[] getBaseCount() {
return baseCount;
}
void increment(int position, byte base, byte quality) {
// Qualities of 2 or less => no idea what this base is
//if (quality <= 2) {
// return;
int offset = position - start;
baseCount[offset]++;
if (ref != null) {
byte refBase = ref[offset];
if (refBase != base) {
mismatchCount += quality;
}
}
count++;
qualityCount += quality;
}
// frac should be between 0 and 1
void incrementEvent(Event evt, float frac) {
switch (evt) {
case indel:
indelCount += frac;
break;
case largeISize:
largeISizeCount += frac;
break;
case smallISize:
smallISizeCount += frac;
break;
case inversion:
inversionCount += frac;
break;
case duplication:
duplicationCount += frac;
break;
case inter:
interChrCount += frac;
break;
case unmappedMate:
unmappedMate += frac;
break;
}
}
public float getEventScore(Event evt) {
switch (evt) {
case mismatch:
return qualityCount < 25 ? 0 : mismatchCount / qualityCount;
case indel:
return count < 5 ? 0 : indelCount / count;
case largeISize:
return pairedCount < 5 ? 0 : largeISizeCount / pairedCount;
case smallISize:
return pairedCount < 5 ? 0 : smallISizeCount / pairedCount;
case inversion:
return pairedCount < 5 ? 0 : inversionCount / pairedCount;
case duplication:
return pairedCount < 5 ? 0 : duplicationCount / pairedCount;
case inter:
return (pairedCount < 5 ? 0 : interChrCount / pairedCount);
case unmappedMate:
return (pairedCount < 5 ? 0 : unmappedMate / pairedCount);
}
throw new RuntimeException("Unknown event type: " + evt);
}
public void incrementISize(int inferredInsertSize) {
totalISizeCount++;
if (inferredInsertSize > 600) {
largeISizeCount++;
} else if (inferredInsertSize < 200) {
smallISizeCount++;
}
//float zs = Math.min(6, (Math.abs(inferredInsertSize) - meanInsertSize) / stdDevInsertSize);
//isizeZScore += zs;
//ppCount++;
//if (Math.abs(Math.abs(inferredInsertSize) - meanInsertSize) > 2 * stdDevInsertSize) {
// isizeCount++;
//otalIsize += Math.abs(inferredInsertSize);
}
//float getISizeFraction() {
// if (pairedCount < 3) {
// return 0;
// float frac = ((float) isizeCount) / pairedCount;
// return frac;
//float avg = isizeZScore / ppCount;
//return avg;
//float getAvgIsize() {
// return pairedCount == 0 ? 0 : totalIsize / pairedCount;
}
/**
* Creates a vary step wig file
*/
class WigWriter {
Event event = null;
String lastChr = null;
int lastPosition = 0;
int step;
int span;
PrintWriter pw;
WigWriter(File file, int step) throws IOException {
this.step = step;
this.span = step;
pw = new PrintWriter(new FileWriter(file));
}
WigWriter(File file, int step, Event event) throws IOException {
this.step = step;
this.span = step;
pw = new PrintWriter(new FileWriter(file));
this.event = event;
}
public void addData(String chr, int start, int end, float data) {
if (Float.isNaN(data)) {
return;
}
if (genome.getChromosome(chr) == null) {
return;
}
if ((!keepZeroes && data == 0) || end <= start) {
return;
}
int dataSpan = end - start;
if (chr == null || !chr.equals(lastChr) || dataSpan != span) {
span = dataSpan;
outputStepLine(chr, start + 1);
}
pw.println((start + 1) + "\t" + data);
lastPosition = start;
lastChr = chr;
}
private void close() {
pw.close();
}
private void outputStepLine(String chr, int start) {
pw.println("variableStep chrom=" + chr + " span=" + span);
}
}
}
|
package org.java_websocket;
import org.java_websocket.Framedata.Opcode;
import org.java_websocket.exeptions.InvalidDataException;
public abstract class WebSocketAdapter implements WebSocketListener {
/**
* This default implementation does not do anything. Go ahead and overwrite it.
*
* @see org.java_websocket.WebSocketListener#onWebsocketHandshakeRecievedAsServer(org.java_websocket.WebSocket, org.java_websocket.Draft, org.java_websocket.Handshakedata)
*/
@Override
public HandshakeBuilder onWebsocketHandshakeRecievedAsServer( WebSocket conn, Draft draft, Handshakedata request ) throws InvalidDataException {
return new HandshakedataImpl1();
}
/**
* This default implementation does not do anything which will cause connections to be accepted. Go ahead and overwrite it.
*
* @see org.java_websocket.WebSocketListener#onWebsocketHandshakeRecievedAsClient(org.java_websocket.WebSocket, org.java_websocket.Handshakedata, org.java_websocket.Handshakedata)
*/
@Override
public void onWebsocketHandshakeRecievedAsClient( WebSocket conn, Handshakedata request, Handshakedata response ) throws InvalidDataException {
}
/**
* This default implementation does not do anything. Go ahead and overwrite it.
*
* @see org.java_websocket.WebSocketListener#onWebsocketMessage(org.java_websocket.WebSocket, java.lang.String)
*/
@Override
public void onWebsocketMessage( WebSocket conn, String message ) {
}
/**
* This default implementation does not do anything. Go ahead and overwrite it.
*
* @see org.java_websocket.WebSocketListener#onWebsocketOpen(org.java_websocket.WebSocket, org.java_websocket.Handshakedata)
*/
@Override
public void onWebsocketOpen( WebSocket conn, Handshakedata handshake ) {
}
/**
* This default implementation does not do anything. Go ahead and overwrite it.
*
* @see org.java_websocket.WebSocketListener#onWebsocketClose(org.java_websocket.WebSocket, int, java.lang.String, boolean)
*/
@Override
public void onWebsocketClose( WebSocket conn, int code, String reason, boolean remote ) {
}
/**
* This default implementation does not do anything. Go ahead and overwrite it.
*
* @see org.java_websocket.WebSocketListener#onWebsocketMessage(org.java_websocket.WebSocket, byte[])
*/
@Override
public void onWebsocketMessage( WebSocket conn, byte[] blob ) {
}
/**
* This default implementation will send a pong in response to the received ping.
* The pong frame will have the same payload as the ping frame.
*
* @see org.java_websocket.WebSocketListener#onWebsocketPing(org.java_websocket.WebSocket, org.java_websocket.Framedata)
*/
@Override
public void onWebsocketPing( WebSocket conn, Framedata f ) {
FramedataImpl1 resp = new FramedataImpl1 ( f );
resp.setOptcode( Opcode.PONG );
try {
conn.sendFrame ( resp );
} catch ( InterruptedException e ) {
e.printStackTrace();
}
}
/**
* This default implementation does not do anything. Go ahead and overwrite it.
*
* @see org.java_websocket.WebSocketListener#onWebsocketPong(org.java_websocket.WebSocket, org.java_websocket.Framedata)
*/
@Override
public void onWebsocketPong( WebSocket conn, Framedata f ) {
}
@Override
public String getFlashPolicy( WebSocket conn ) {
return "<cross-domain-policy><allow-access-from domain=\"*\" to-ports=\"" + conn.getLocalSocketAddress().getPort() + "\" /></cross-domain-policy>\0";
}
/**
* This default implementation does not do anything. Go ahead and overwrite it.
* @see org.java_websocket.WebSocketListener#onWebsocketError(org.java_websocket.WebSocket, java.lang.Exception)
*/
@Override
public void onWebsocketError( WebSocket conn, Exception ex ) {
}
}
|
package org.jgroups.protocols.pbcast;
import org.jgroups.Address;
import org.jgroups.Event;
import org.jgroups.Message;
import org.jgroups.View;
import org.jgroups.annotations.*;
import org.jgroups.conf.PropertyConverters;
import org.jgroups.stack.*;
import org.jgroups.util.*;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
/**
* Negative AcKnowledgement layer (NAKs). Messages are assigned a monotonically increasing sequence number (seqno).
* Receivers deliver messages ordered according to seqno and request retransmission of missing messages.<br/>
* Retransmit requests are usually sent to the original sender of a message, but this can be changed by
* xmit_from_random_member (send to random member) or use_mcast_xmit_req (send to everyone). Responses can also be sent
* to everyone instead of the requester by setting use_mcast_xmit to true.
*
* @author Bela Ban
* @version $Id: NAKACK.java,v 1.192 2008/06/12 15:18:25 belaban Exp $
*/
@MBean(description="Reliable transmission multipoint FIFO protocol")
@DeprecatedProperty(names={"max_xmit_size"})
public class NAKACK extends Protocol implements Retransmitter.RetransmitCommand, NakReceiverWindow.Listener {
@Property(name="retransmit_timeout",converter=PropertyConverters.LongArray.class)
private long[] retransmit_timeouts={600, 1200, 2400, 4800}; // time(s) to wait before requesting retransmission
@Property
boolean enable_xmit_time_stats = false;
private boolean is_server=false;
private Address local_addr=null;
private final List<Address> members=new CopyOnWriteArrayList<Address>();
private View view;
@GuardedBy("seqno_lock")
private long seqno=0; // current message sequence number (starts with 1)
private final Lock seqno_lock=new ReentrantLock();
@ManagedAttribute(description = "Garbage collection lag", writable = true)
@Property
private int gc_lag=20; // number of msgs garbage collection lags behind
private Map<Thread,ReentrantLock> locks;
private static final long INITIAL_SEQNO=0;
/**
* Retransmit messages using multicast rather than unicast. This has the advantage that, if many receivers lost a
* message, the sender only retransmits once.
*/
@Property
@ManagedAttribute(description = "Retransmit messages using multicast rather than unicast", writable = true)
private boolean use_mcast_xmit=true;
/** Use a multicast to request retransmission of missing messages. This may be costly as every member in the cluster
* will send a response
*/
@Property
private boolean use_mcast_xmit_req=false;
/**
* Ask a random member for retransmission of a missing message. If set to true, discard_delivered_msgs will be
* set to false
*/
@Property
@ManagedAttribute(description = "Ask a random member for retransmission of a missing message",writable = true)
private boolean xmit_from_random_member=false;
/** The first value (in milliseconds) to use in the exponential backoff retransmission mechanism. Only enabled
* if the value is > 0
*/
@Property
private long exponential_backoff=0;
/** If enabled, we use statistics gathered from actual retransmission times to compute the new retransmission times */
@Property
private boolean use_stats_for_retransmission=false;
/**
* Messages that have been received in order are sent up the stack (= delivered to the application). Delivered
* messages are removed from NakReceiverWindow.xmit_table and moved to NakReceiverWindow.delivered_msgs, where
* they are later garbage collected (by STABLE). Since we do retransmits only from sent messages, never
* received or delivered messages, we can turn the moving to delivered_msgs off, so we don't keep the message
* around, and don't need to wait for garbage collection to remove them.
*/
@Property
@ManagedAttribute(description = "Discard delivered messages",writable = true)
private boolean discard_delivered_msgs=false;
@Property
private boolean eager_lock_release=true;
/** If value is > 0, the retransmit buffer is bounded: only the max_xmit_buf_size latest messages are kept,
* older ones are discarded when the buffer size is exceeded. A value <= 0 means unbounded buffers
*/
@Property
@ManagedAttribute(description = "If value is > 0, the retransmit buffer is bounded. If value <= 0 unbounded buffers are used", writable = true)
private int max_xmit_buf_size=0;
/** Map to store sent and received messages (keyed by sender) */
private final ConcurrentMap<Address,NakReceiverWindow> xmit_table=new ConcurrentHashMap<Address,NakReceiverWindow>(11);
/** Map which keeps track of threads removing messages from NakReceiverWindows, so we don't wait while a thread
* is removing messages */
// private final ConcurrentMap<Address,AtomicBoolean> in_progress=new ConcurrentHashMap<Address,AtomicBoolean>();
private boolean leaving=false;
private boolean started=false;
private TimeScheduler timer=null;
private static final String name="NAKACK";
@ManagedAttribute(description = "Number of retransmit requests received")
private long xmit_reqs_received;
@ManagedAttribute(description = "Number of retransmit requests sent")
private long xmit_reqs_sent;
@ManagedAttribute(description = "Number of retransmit responses received" )
private long xmit_rsps_received;
@ManagedAttribute(description = "Number of retransmit responses sent" )
private long xmit_rsps_sent;
@ManagedAttribute(description = "Number of missing messages received")
private long missing_msgs_received;
/** Captures stats on XMIT_REQS, XMIT_RSPS per sender */
private HashMap<Address,StatsEntry> sent=new HashMap<Address,StatsEntry>();
/** Captures stats on XMIT_REQS, XMIT_RSPS per receiver */
private HashMap<Address,StatsEntry> received=new HashMap<Address,StatsEntry>();
@Property
private int stats_list_size=20;
/** BoundedList<MissingMessage>. Keeps track of the last stats_list_size XMIT requests */
private BoundedList<MissingMessage> receive_history;
/** BoundedList<XmitRequest>. Keeps track of the last stats_list_size missing messages received */
private BoundedList<XmitRequest> send_history;
/** Per-sender map of seqnos and timestamps, to keep track of avg times for retransmission of messages */
private final ConcurrentMap<Address,ConcurrentMap<Long,Long>> xmit_stats=new ConcurrentHashMap<Address,ConcurrentMap<Long,Long>>();
@Property
private int xmit_history_max_size=50;
/** Maintains a list of the last N retransmission times (duration it took to retransmit a message) for all members */
private final ConcurrentMap<Address,BoundedList<Long>> xmit_times_history=new ConcurrentHashMap<Address,BoundedList<Long>>();
/** Maintains a smoothed average of the retransmission times per sender, these are the actual values that are used for
* new retransmission requests */
private final Map<Address,Double> smoothed_avg_xmit_times=new HashMap<Address,Double>();
/** the weight with which we take the previous smoothed average into account, WEIGHT should be >0 and <= 1 */
private static final double WEIGHT=0.9;
private static final double INITIAL_SMOOTHED_AVG=30.0;
// private final ConcurrentMap<Address,LossRate> loss_rates=new ConcurrentHashMap<Address,LossRate>();
/**
* Maintains retransmission related data across a time. Only used if enable_xmit_time_stats is set to true.
* At program termination, accumulated data is dumped to a file named by the address of the member. Careful,
* don't enable this in production as the data in this hashmap are never reaped ! Really only meant for
* diagnostics !
*/
private ConcurrentMap<Long,XmitTimeStat> xmit_time_stats=null;
private long xmit_time_stats_start;
/** Keeps track of OOB messages sent by myself, needed by {@link #handleMessage(org.jgroups.Message, NakAckHeader)} */
private final Set<Long> oob_loopback_msgs=Collections.synchronizedSet(new HashSet<Long>());
private final Lock rebroadcast_lock=new ReentrantLock();
private final Condition rebroadcast_done=rebroadcast_lock.newCondition();
// set during processing of a rebroadcast event
private volatile boolean rebroadcasting=false;
private final Lock rebroadcast_digest_lock=new ReentrantLock();
@GuardedBy("rebroadcast_digest_lock")
private Digest rebroadcast_digest=null;
@Property
private long max_rebroadcast_timeout=2000;
private static final int NUM_REBROADCAST_MSGS=3;
/** BoundedList<Digest>, keeps the last 10 stability messages */
private final BoundedList<Digest> stability_msgs=new BoundedList<Digest>(10);
/** When not finding a message on an XMIT request, include the last N stability messages in the error message */
@Property
protected boolean print_stability_history_on_failed_xmit=false;
/** If true, logs messages discarded because received from other members */
@ManagedAttribute(description="If true, logs messages discarded because received from other members",writable=true)
private boolean log_discard_msgs=true;
/** <em>Regular</em> messages which have been added, but not removed */
private final AtomicInteger undelivered_msgs=new AtomicInteger(0);
@ManagedAttribute
public int getUndeliveredMessages() {
return undelivered_msgs.get();
}
public NAKACK() {
}
public String getName() {
return name;
}
public long getXmitRequestsReceived() {return xmit_reqs_received;}
public long getXmitRequestsSent() {return xmit_reqs_sent;}
public long getXmitResponsesReceived() {return xmit_rsps_received;}
public long getXmitResponsesSent() {return xmit_rsps_sent;}
public long getMissingMessagesReceived() {return missing_msgs_received;}
@ManagedAttribute
public int getPendingRetransmissionRequests() {
int num=0;
for(NakReceiverWindow win: xmit_table.values()) {
num+=win.getPendingXmits();
}
return num;
}
@ManagedAttribute
public int getXmitTableSize() {
int num=0;
for(NakReceiverWindow win: xmit_table.values()) {
num+=win.size();
}
return num;
}
public int getReceivedTableSize() {
return getPendingRetransmissionRequests();
}
public void resetStats() {
xmit_reqs_received=xmit_reqs_sent=xmit_rsps_received=xmit_rsps_sent=missing_msgs_received=0;
sent.clear();
received.clear();
if(receive_history !=null)
receive_history.clear();
if(send_history != null)
send_history.clear();
}
public void init() throws Exception {
if(enable_xmit_time_stats) {
if(log.isWarnEnabled())
log.warn("enable_xmit_time_stats is experimental, and may be removed in any release");
xmit_time_stats=new ConcurrentHashMap<Long,XmitTimeStat>();
xmit_time_stats_start=System.currentTimeMillis();
}
if(xmit_from_random_member) {
if(discard_delivered_msgs) {
discard_delivered_msgs=false;
log.warn("xmit_from_random_member set to true: changed discard_delivered_msgs to false");
}
}
if(stats) {
send_history=new BoundedList<XmitRequest>(stats_list_size);
receive_history=new BoundedList<MissingMessage>(stats_list_size);
}
}
public int getGcLag() {
return gc_lag;
}
public void setGcLag(int gc_lag) {
this.gc_lag=gc_lag;
}
public boolean isUseMcastXmit() {
return use_mcast_xmit;
}
public void setUseMcastXmit(boolean use_mcast_xmit) {
this.use_mcast_xmit=use_mcast_xmit;
}
public boolean isXmitFromRandomMember() {
return xmit_from_random_member;
}
public void setXmitFromRandomMember(boolean xmit_from_random_member) {
this.xmit_from_random_member=xmit_from_random_member;
}
public boolean isDiscardDeliveredMsgs() {
return discard_delivered_msgs;
}
public void setDiscardDeliveredMsgs(boolean discard_delivered_msgs) {
boolean old=this.discard_delivered_msgs;
this.discard_delivered_msgs=discard_delivered_msgs;
if(old != this.discard_delivered_msgs) {
for(NakReceiverWindow win: xmit_table.values()) {
win.setDiscardDeliveredMessages(this.discard_delivered_msgs);
}
}
}
public int getMaxXmitBufSize() {
return max_xmit_buf_size;
}
public void setMaxXmitBufSize(int max_xmit_buf_size) {
this.max_xmit_buf_size=max_xmit_buf_size;
}
/**
*
* @return
* @deprecated removed in 2.6
*/
public long getMaxXmitSize() {
return -1;
}
/**
*
* @param max_xmit_size
* @deprecated removed in 2.6
*/
public void setMaxXmitSize(long max_xmit_size) {
}
public void setLogDiscardMessages(boolean flag) {
log_discard_msgs=flag;
}
public boolean getLogDiscardMessages() {
return log_discard_msgs;
}
public Map<String,Object> dumpStats() {
Map<String,Object> retval=super.dumpStats();
if(retval == null)
retval=new HashMap<String,Object>();
retval.put("xmit_reqs_received", new Long(xmit_reqs_received));
retval.put("xmit_reqs_sent", new Long(xmit_reqs_sent));
retval.put("xmit_rsps_received", new Long(xmit_rsps_received));
retval.put("xmit_rsps_sent", new Long(xmit_rsps_sent));
retval.put("missing_msgs_received", new Long(missing_msgs_received));
retval.put("msgs", printMessages());
return retval;
}
public String printStats() {
Map.Entry entry;
Object key, val;
StringBuilder sb=new StringBuilder();
sb.append("sent:\n");
for(Iterator it=sent.entrySet().iterator(); it.hasNext();) {
entry=(Map.Entry)it.next();
key=entry.getKey();
if(key == null) key="<mcast dest>";
val=entry.getValue();
sb.append(key).append(": ").append(val).append("\n");
}
sb.append("\nreceived:\n");
for(Iterator it=received.entrySet().iterator(); it.hasNext();) {
entry=(Map.Entry)it.next();
key=entry.getKey();
val=entry.getValue();
sb.append(key).append(": ").append(val).append("\n");
}
sb.append("\nXMIT_REQS sent:\n");
for(XmitRequest tmp: send_history) {
sb.append(tmp).append("\n");
}
sb.append("\nMissing messages received\n");
for(MissingMessage missing: receive_history) {
sb.append(missing).append("\n");
}
sb.append("\nStability messages received\n");
sb.append(printStabilityMessages()).append("\n");
return sb.toString();
}
@ManagedOperation(description="TODO")
public String printStabilityMessages() {
StringBuilder sb=new StringBuilder();
sb.append(Util.printListWithDelimiter(stability_msgs, "\n"));
return sb.toString();
}
public String printStabilityHistory() {
StringBuilder sb=new StringBuilder();
int i=1;
for(Digest digest: stability_msgs) {
sb.append(i++).append(": ").append(digest).append("\n");
}
return sb.toString();
}
@ManagedOperation(description="TODO")
public String printLossRates() {
StringBuilder sb=new StringBuilder();
NakReceiverWindow win;
for(Map.Entry<Address,NakReceiverWindow> entry: xmit_table.entrySet()) {
win=entry.getValue();
sb.append(entry.getKey()).append(": ").append(win.printLossRate()).append("\n");
}
return sb.toString();
}
@ManagedAttribute
public double getAverageLossRate() {
double retval=0.0;
int count=0;
if(xmit_table.isEmpty())
return 0.0;
for(NakReceiverWindow win: xmit_table.values()) {
retval+=win.getLossRate();
count++;
}
return retval / (double)count;
}
@ManagedAttribute
public double getAverageSmoothedLossRate() {
double retval=0.0;
int count=0;
if(xmit_table.isEmpty())
return 0.0;
for(NakReceiverWindow win: xmit_table.values()) {
retval+=win.getSmoothedLossRate();
count++;
}
return retval / (double)count;
}
public Vector<Integer> providedUpServices() {
Vector<Integer> retval=new Vector<Integer>(5);
retval.addElement(new Integer(Event.GET_DIGEST));
retval.addElement(new Integer(Event.SET_DIGEST));
retval.addElement(new Integer(Event.MERGE_DIGEST));
return retval;
}
public void start() throws Exception {
timer=getTransport().getTimer();
if(timer == null)
throw new Exception("timer is null");
locks=stack.getLocks();
started=true;
if(xmit_time_stats != null) {
Runtime.getRuntime().addShutdownHook(new Thread() {
public void run() {
String filename="xmit-stats-" + local_addr + ".log";
System.out.println("-- dumping runtime xmit stats to " + filename);
try {
dumpXmitStats(filename);
}
catch(IOException e) {
e.printStackTrace();
}
}
});
}
}
public void stop() {
started=false;
reset(); // clears sent_msgs and destroys all NakReceiverWindows
oob_loopback_msgs.clear();
}
/**
* <b>Callback</b>. Called by superclass when event may be handled.<p> <b>Do not use <code>down_prot.down()</code> in this
* method as the event is passed down by default by the superclass after this method returns !</b>
*/
public Object down(Event evt) {
switch(evt.getType()) {
case Event.MSG:
Message msg=(Message)evt.getArg();
Address dest=msg.getDest();
if(dest != null && !dest.isMulticastAddress()) {
break; // unicast address: not null and not mcast, pass down unchanged
}
send(evt, msg);
return null; // don't pass down the stack
case Event.STABLE: // generated by STABLE layer. Delete stable messages passed in arg
stable((Digest)evt.getArg());
return null; // do not pass down further (Bela Aug 7 2001)
case Event.GET_DIGEST:
return getDigest();
case Event.SET_DIGEST:
setDigest((Digest)evt.getArg());
return null;
case Event.MERGE_DIGEST:
mergeDigest((Digest)evt.getArg());
return null;
case Event.TMP_VIEW:
View tmp_view=(View)evt.getArg();
Vector<Address> mbrs=tmp_view.getMembers();
members.clear();
members.addAll(mbrs);
// adjustReceivers(false);
break;
case Event.VIEW_CHANGE:
tmp_view=(View)evt.getArg();
mbrs=tmp_view.getMembers();
members.clear();
members.addAll(mbrs);
adjustReceivers(members);
is_server=true; // check vids from now on
Set<Address> tmp=new LinkedHashSet<Address>(members);
tmp.add(null); // for null destination (= mcast)
sent.keySet().retainAll(tmp);
received.keySet().retainAll(tmp);
view=tmp_view;
xmit_stats.keySet().retainAll(tmp);
// in_progress.keySet().retainAll(mbrs); // remove elements which are not in the membership
break;
case Event.BECOME_SERVER:
is_server=true;
break;
case Event.DISCONNECT:
leaving=true;
reset();
break;
case Event.REBROADCAST:
rebroadcasting=true;
rebroadcast_digest=(Digest)evt.getArg();
try {
rebroadcastMessages();
}
finally {
rebroadcasting=false;
rebroadcast_digest_lock.lock();
try {
rebroadcast_digest=null;
}
finally {
rebroadcast_digest_lock.unlock();
}
}
return null;
}
return down_prot.down(evt);
}
/**
* <b>Callback</b>. Called by superclass when event may be handled.<p> <b>Do not use <code>PassUp</code> in this
* method as the event is passed up by default by the superclass after this method returns !</b>
*/
public Object up(Event evt) {
switch(evt.getType()) {
case Event.MSG:
Message msg=(Message)evt.getArg();
NakAckHeader hdr=(NakAckHeader)msg.getHeader(name);
if(hdr == null)
break; // pass up (e.g. unicast msg)
// discard messages while not yet server (i.e., until JOIN has returned)
if(!is_server) {
if(log.isTraceEnabled())
log.trace("message was discarded (not yet server)");
return null;
}
// Changed by bela Jan 29 2003: we must not remove the header, otherwise
// further xmit requests will fail !
//hdr=(NakAckHeader)msg.removeHeader(getName());
switch(hdr.type) {
case NakAckHeader.MSG:
handleMessage(msg, hdr);
return null; // transmitter passes message up for us !
case NakAckHeader.XMIT_REQ:
if(hdr.range == null) {
if(log.isErrorEnabled()) {
log.error("XMIT_REQ: range of xmit msg is null; discarding request from " + msg.getSrc());
}
return null;
}
handleXmitReq(msg.getSrc(), hdr.range.low, hdr.range.high, hdr.sender);
return null;
case NakAckHeader.XMIT_RSP:
if(log.isTraceEnabled())
log.trace("received missing message " + msg.getSrc() + ":" + hdr.seqno);
handleXmitRsp(msg);
return null;
default:
if(log.isErrorEnabled()) {
log.error("NakAck header type " + hdr.type + " not known !");
}
return null;
}
case Event.STABLE: // generated by STABLE layer. Delete stable messages passed in arg
stable((Digest)evt.getArg());
return null; // do not pass up further (Bela Aug 7 2001)
case Event.SET_LOCAL_ADDRESS:
local_addr=(Address)evt.getArg();
break;
case Event.SUSPECT:
// release the promise if rebroadcasting is in progress... otherwise we wait forever. there will be a new
// flush round anyway
if(rebroadcasting) {
cancelRebroadcasting();
}
break;
}
return up_prot.up(evt);
}
private void send(Event evt, Message msg) {
if(msg == null)
throw new NullPointerException("msg is null; event is " + evt);
if(!started) {
if(log.isTraceEnabled())
log.trace("[" + local_addr + "] discarded message as start() has not been called, message: " + msg);
return;
}
long msg_id;
NakReceiverWindow win=xmit_table.get(local_addr);
msg.setSrc(local_addr); // this needs to be done so we can check whether the message sender is the local_addr
seqno_lock.lock();
try {
try { // incrementing seqno and adding the msg to sent_msgs needs to be atomic
msg_id=seqno +1;
msg.putHeader(name, new NakAckHeader(NakAckHeader.MSG, msg_id));
win.add(msg_id, msg);
seqno=msg_id;
}
catch(Throwable t) {
throw new RuntimeException("failure adding msg " + msg + " to the retransmit table for " + local_addr, t);
}
}
finally {
seqno_lock.unlock();
}
try {
if(msg.isFlagSet(Message.OOB))
oob_loopback_msgs.add(msg_id);
if(log.isTraceEnabled())
log.trace("sending " + local_addr + "#" + msg_id);
down_prot.down(evt); // if this fails, since msg is in sent_msgs, it can be retransmitted
}
catch(Throwable t) { // eat the exception, don't pass it up the stack
if(log.isWarnEnabled()) {
log.warn("failure passing message down", t);
}
}
}
/**
* Finds the corresponding NakReceiverWindow and adds the message to it (according to seqno). Then removes as many
* messages as possible from the NRW and passes them up the stack. Discards messages from non-members.
*/
private void handleMessage(Message msg, NakAckHeader hdr) {
Address sender=msg.getSrc();
if(sender == null) {
if(log.isErrorEnabled())
log.error("sender of message is null");
return;
}
if(log.isTraceEnabled())
log.trace(new StringBuilder().append('[').append(local_addr).append(": received ").append(sender).append('#').append(hdr.seqno));
NakReceiverWindow win=xmit_table.get(sender);
if(win == null) { // discard message if there is no entry for sender
if(leaving)
return;
if(log.isWarnEnabled() && log_discard_msgs)
log.warn(local_addr + "] discarded message from non-member " + sender + ", my view is " + view);
return;
}
boolean loopback=local_addr.equals(sender);
boolean added=loopback || win.add(hdr.seqno, msg);
boolean regular_msg_added=added && !msg.isFlagSet(Message.OOB);
// message is passed up if OOB. Later, when remove() is called, we discard it. This affects ordering !
if(added && msg.isFlagSet(Message.OOB)) {
if(!loopback || oob_loopback_msgs.remove(hdr.seqno)) {
up_prot.up(new Event(Event.MSG, msg));
win.removeOOBMessage();
if(!(win.hasMessagesToRemove() && undelivered_msgs.get() > 0))
return;
}
}
// where lots of threads can come up to this point concurrently, but only 1 is allowed to pass at a time
// We *can* deliver messages from *different* senders concurrently, e.g. reception of P1, Q1, P2, Q2 can result in
// delivery of P1, Q1, Q2, P2: FIFO (implemented by NAKACK) says messages need to be delivered in the
// order in which they were sent by the sender
Message msg_to_deliver;
ReentrantLock lock=win.getLock();
lock.lock();
try {
if(eager_lock_release)
locks.put(Thread.currentThread(), lock);
short removed_regular_msgs=0;
while((msg_to_deliver=win.remove()) != null) {
if(msg_to_deliver.isFlagSet(Message.OOB)) {
continue;
}
removed_regular_msgs++;
// Changed by bela Jan 29 2003: not needed (see above)
//msg_to_deliver.removeHeader(getName());
up_prot.up(new Event(Event.MSG, msg_to_deliver));
}
// We keep track of regular messages that we added, but couldn't remove (because of ordering).
// When we have such messages pending, then even OOB threads will remove and process them
if(regular_msg_added && removed_regular_msgs == 0) {
undelivered_msgs.incrementAndGet();
}
if(removed_regular_msgs > 0) { // regardless of whether a message was added or not !
int num_msgs_added=regular_msg_added? 1 : 0;
undelivered_msgs.addAndGet(-(removed_regular_msgs -num_msgs_added));
}
}
finally {
if(eager_lock_release)
locks.remove(Thread.currentThread());
if(lock.isHeldByCurrentThread())
lock.unlock();
}
}
/**
* Retransmits messsages first_seqno to last_seqno from original_sender from xmit_table to xmit_requester,
* called when XMIT_REQ is received.
* @param xmit_requester The sender of the XMIT_REQ, we have to send the requested copy of the message to this address
* @param first_seqno The first sequence number to be retransmitted (<= last_seqno)
* @param last_seqno The last sequence number to be retransmitted (>= first_seqno)
* @param original_sender The member who originally sent the messsage. Guaranteed to be non-null
*/
private void handleXmitReq(Address xmit_requester, long first_seqno, long last_seqno, Address original_sender) {
Message msg;
if(log.isTraceEnabled()) {
StringBuilder sb=new StringBuilder();
sb.append(local_addr).append(": received xmit request from ").append(xmit_requester).append(" for ");
sb.append(original_sender).append(" [").append(first_seqno).append(" - ").append(last_seqno).append("]");
log.trace(sb.toString());
}
if(first_seqno > last_seqno) {
if(log.isErrorEnabled())
log.error("first_seqno (" + first_seqno + ") > last_seqno (" + last_seqno + "): not able to retransmit");
return;
}
if(stats) {
xmit_reqs_received+=last_seqno - first_seqno +1;
updateStats(received, xmit_requester, 1, 0, 0);
}
if(xmit_time_stats != null) {
long key=(System.currentTimeMillis() - xmit_time_stats_start) / 1000;
XmitTimeStat stat=xmit_time_stats.get(key);
if(stat == null) {
stat=new XmitTimeStat();
XmitTimeStat stat2=xmit_time_stats.putIfAbsent(key, stat);
if(stat2 != null)
stat=stat2;
}
stat.xmit_reqs_received.addAndGet((int)(last_seqno - first_seqno +1));
stat.xmit_rsps_sent.addAndGet((int)(last_seqno - first_seqno +1));
}
NakReceiverWindow win=xmit_table.get(original_sender);
if(win == null) {
if(log.isErrorEnabled()) {
StringBuilder sb=new StringBuilder();
sb.append("(requester=").append(xmit_requester).append(", local_addr=").append(this.local_addr);
sb.append(") ").append(original_sender).append(" not found in retransmission table:\n").append(printMessages());
if(print_stability_history_on_failed_xmit) {
sb.append(" (stability history:\n").append(printStabilityHistory());
}
log.error(sb);
}
return;
}
for(long i=first_seqno; i <= last_seqno; i++) {
msg=win.get(i);
if(msg == null || msg == NakReceiverWindow.NULL_MSG) {
if(log.isWarnEnabled() && !local_addr.equals(xmit_requester)) {
StringBuilder sb=new StringBuilder();
sb.append("(requester=").append(xmit_requester).append(", local_addr=").append(this.local_addr);
sb.append(") message ").append(original_sender).append("::").append(i);
sb.append(" not found in retransmission table of ").append(original_sender).append(":\n").append(win);
if(print_stability_history_on_failed_xmit) {
sb.append(" (stability history:\n").append(printStabilityHistory());
}
log.warn(sb);
}
continue;
}
sendXmitRsp(xmit_requester, msg, i);
}
}
private void cancelRebroadcasting() {
rebroadcast_lock.lock();
try {
rebroadcasting=false;
rebroadcast_done.signalAll();
}
finally {
rebroadcast_lock.unlock();
}
}
private static void updateStats(HashMap<Address,StatsEntry> map, Address key, int req, int rsp, int missing) {
StatsEntry entry=map.get(key);
if(entry == null) {
entry=new StatsEntry();
map.put(key, entry);
}
entry.xmit_reqs+=req;
entry.xmit_rsps+=rsp;
entry.missing_msgs_rcvd+=missing;
}
/**
* Sends a message msg to the requester. We have to wrap the original message into a retransmit message, as we need
* to preserve the original message's properties, such as src, headers etc.
* @param dest
* @param msg
* @param seqno
*/
private void sendXmitRsp(Address dest, Message msg, long seqno) {
Buffer buf;
if(msg == null) {
if(log.isErrorEnabled())
log.error("message is null, cannot send retransmission");
return;
}
if(use_mcast_xmit)
dest=null;
if(stats) {
xmit_rsps_sent++;
updateStats(sent, dest, 0, 1, 0);
}
if(msg.getSrc() == null)
msg.setSrc(local_addr);
try {
buf=Util.messageToByteBuffer(msg);
Message xmit_msg=new Message(dest, null, buf.getBuf(), buf.getOffset(), buf.getLength());
// changed Bela Jan 4 2007: we should not use OOB for retransmitted messages, otherwise we tax the OOB thread pool
// too much
// msg.setFlag(Message.OOB);
xmit_msg.putHeader(name, new NakAckHeader(NakAckHeader.XMIT_RSP, seqno));
down_prot.down(new Event(Event.MSG, xmit_msg));
}
catch(IOException ex) {
log.error("failed marshalling xmit list", ex);
}
}
private void handleXmitRsp(Message msg) {
if(msg == null) {
if(log.isWarnEnabled())
log.warn("message is null");
return;
}
try {
Message wrapped_msg=Util.byteBufferToMessage(msg.getRawBuffer(), msg.getOffset(), msg.getLength());
if(xmit_time_stats != null) {
long key=(System.currentTimeMillis() - xmit_time_stats_start) / 1000;
XmitTimeStat stat=xmit_time_stats.get(key);
if(stat == null) {
stat=new XmitTimeStat();
XmitTimeStat stat2=xmit_time_stats.putIfAbsent(key, stat);
if(stat2 != null)
stat=stat2;
}
stat.xmit_rsps_received.incrementAndGet();
}
if(stats) {
xmit_rsps_received++;
updateStats(received, msg.getSrc(), 0, 1, 0);
}
up(new Event(Event.MSG, wrapped_msg));
if(rebroadcasting) {
Digest tmp=getDigest();
boolean cancel_rebroadcasting;
rebroadcast_digest_lock.lock();
try {
cancel_rebroadcasting=tmp.isGreaterThanOrEqual(rebroadcast_digest);
}
finally {
rebroadcast_digest_lock.unlock();
}
if(cancel_rebroadcasting) {
cancelRebroadcasting();
}
}
}
catch(Exception ex) {
if(log.isErrorEnabled()) {
log.error("failed reading retransmitted message", ex);
}
}
}
/**
* Takes the argument highest_seqnos and compares it to the current digest. If the current digest has fewer messages,
* then send retransmit messages for the missing messages. Return when all missing messages have been received. If
* we're waiting for a missing message from P, and P crashes while waiting, we need to exclude P from the wait set.
*/
private void rebroadcastMessages() {
Digest my_digest;
Map<Address,Digest.Entry> their_digest;
Address sender;
Digest.Entry their_entry, my_entry;
long their_high, my_high;
long sleep=max_rebroadcast_timeout / NUM_REBROADCAST_MSGS;
long wait_time=max_rebroadcast_timeout, start=System.currentTimeMillis();
while(wait_time > 0) {
rebroadcast_digest_lock.lock();
try {
if(rebroadcast_digest == null)
break;
their_digest=rebroadcast_digest.getSenders();
}
finally {
rebroadcast_digest_lock.unlock();
}
my_digest=getDigest();
boolean xmitted=false;
for(Map.Entry<Address,Digest.Entry> entry: their_digest.entrySet()) {
sender=entry.getKey();
their_entry=entry.getValue();
my_entry=my_digest.get(sender);
if(my_entry == null)
continue;
their_high=their_entry.getHighest();
my_high=my_entry.getHighest();
if(their_high > my_high) {
if(log.isTraceEnabled())
log.trace("sending XMIT request to " + sender + " for messages " + my_high + " - " + their_high);
retransmit(my_high, their_high, sender, true); // use multicast to send retransmit request
xmitted=true;
}
}
if(!xmitted)
return; // we're done; no retransmissions are needed anymore. our digest is >= rebroadcast_digest
rebroadcast_lock.lock();
try {
try {
my_digest=getDigest();
rebroadcast_digest_lock.lock();
try {
if(!rebroadcasting || my_digest.isGreaterThanOrEqual(rebroadcast_digest))
return;
}
finally {
rebroadcast_digest_lock.unlock();
}
rebroadcast_done.await(sleep, TimeUnit.MILLISECONDS);
wait_time-=(System.currentTimeMillis() - start);
}
catch(InterruptedException e) {
}
}
finally {
rebroadcast_lock.unlock();
}
}
}
/**
* Remove old members from NakReceiverWindows and add new members (starting seqno=0). Essentially removes all
* entries from xmit_table that are not in <code>members</code>. This method is not called concurrently
* multiple times
*/
private void adjustReceivers(List<Address> new_members) {
NakReceiverWindow win;
// 1. Remove all senders in xmit_table that are not members anymore
for(Iterator<Address> it=xmit_table.keySet().iterator(); it.hasNext();) {
Address sender=it.next();
if(!new_members.contains(sender)) {
if(local_addr != null && local_addr.equals(sender)) {
if(log.isErrorEnabled())
log.error("will not remove myself (" + sender + ") from xmit_table, received incorrect new membership of " + new_members);
continue;
}
win=xmit_table.get(sender);
win.reset();
if(log.isDebugEnabled()) {
log.debug("removing " + sender + " from xmit_table (not member anymore)");
}
it.remove();
}
}
// 2. Add newly joined members to xmit_table (starting seqno=0)
for(Address sender: new_members) {
if(!xmit_table.containsKey(sender)) {
win=createNakReceiverWindow(sender, INITIAL_SEQNO, 0);
xmit_table.put(sender, win);
}
}
}
/**
* Returns a message digest: for each member P the lowest, highest delivered and highest received seqno is added
*/
private Digest getDigest() {
Digest.Entry entry;
Map<Address,Digest.Entry> map=new HashMap<Address,Digest.Entry>(members.size());
for(Address sender: members) {
entry=getEntry(sender);
if(entry == null) {
if(log.isErrorEnabled()) {
log.error("range is null");
}
continue;
}
map.put(sender, entry);
}
return new Digest(map);
}
/**
* Creates a NakReceiverWindow for each sender in the digest according to the sender's seqno. If NRW already exists,
* reset it.
*/
private void setDigest(Digest digest) {
if(digest == null) {
if(log.isErrorEnabled()) {
log.error("digest or digest.senders is null");
}
return;
}
if(local_addr != null && digest.contains(local_addr)) {
clear();
}
else {
// remove all but local_addr (if not null)
for(Iterator<Address> it=xmit_table.keySet().iterator(); it.hasNext();) {
Address key=it.next();
if(local_addr != null && local_addr.equals(key)) {
;
}
else {
it.remove();
}
}
}
Address sender;
Digest.Entry val;
long initial_seqno;
NakReceiverWindow win;
for(Map.Entry<Address, Digest.Entry> entry: digest.getSenders().entrySet()) {
sender=entry.getKey();
val=entry.getValue();
if(sender == null || val == null) {
if(log.isWarnEnabled()) {
log.warn("sender or value is null");
}
continue;
}
initial_seqno=val.getHighestDeliveredSeqno();
win=createNakReceiverWindow(sender, initial_seqno, val.getLow());
xmit_table.put(sender, win);
}
if(!xmit_table.containsKey(local_addr)) {
if(log.isWarnEnabled()) {
log.warn("digest does not contain local address (local_addr=" + local_addr + ", digest=" + digest);
}
}
}
private void mergeDigest(Digest digest) {
if(digest == null) {
if(log.isErrorEnabled()) {
log.error("digest or digest.senders is null");
}
return;
}
StringBuilder sb=null;
if(log.isDebugEnabled()) {
sb=new StringBuilder();
sb.append("existing digest: " + getDigest()).append("\nnew digest: " + digest);
}
Address sender;
Digest.Entry val;
NakReceiverWindow win;
long highest_delivered_seqno, low_seqno;
for(Map.Entry<Address, Digest.Entry> entry: digest.getSenders().entrySet()) {
sender=entry.getKey();
val=entry.getValue();
if(sender == null || val == null) {
if(log.isWarnEnabled()) {
log.warn("sender or value is null");
}
continue;
}
highest_delivered_seqno=val.getHighestDeliveredSeqno();
low_seqno=val.getLow();
// except for myself
win=xmit_table.get(sender);
if(win != null) {
if(local_addr != null && local_addr.equals(sender)) {
continue;
}
else {
win.reset(); // stops retransmission
xmit_table.remove(sender);
}
}
win=createNakReceiverWindow(sender, highest_delivered_seqno, low_seqno);
xmit_table.put(sender, win);
}
if(log.isDebugEnabled() && sb != null) {
sb.append("\n").append("resulting digest: " + getDigest());
log.debug(sb);
}
if(!xmit_table.containsKey(local_addr)) {
if(log.isWarnEnabled()) {
log.warn("digest does not contain local address (local_addr=" + local_addr + ", digest=" + digest);
}
}
}
private NakReceiverWindow createNakReceiverWindow(Address sender, long initial_seqno, long lowest_seqno) {
NakReceiverWindow win=new NakReceiverWindow(local_addr, sender, this, initial_seqno, lowest_seqno, timer);
if(use_stats_for_retransmission) {
win.setRetransmitTimeouts(new ActualInterval(sender));
}
else if(exponential_backoff > 0) {
win.setRetransmitTimeouts(new ExponentialInterval(exponential_backoff));
}
else {
win.setRetransmitTimeouts(new StaticInterval(retransmit_timeouts));
}
win.setDiscardDeliveredMessages(discard_delivered_msgs);
win.setMaxXmitBufSize(this.max_xmit_buf_size);
if(stats)
win.setListener(this);
return win;
}
private void dumpXmitStats(String filename) throws IOException {
Writer out=new FileWriter(filename);
try {
TreeMap<Long,XmitTimeStat> map=new TreeMap<Long,XmitTimeStat>(xmit_time_stats);
StringBuilder sb;
XmitTimeStat stat;
out.write("time (secs) gaps-detected xmit-reqs-sent xmit-reqs-received xmit-rsps-sent xmit-rsps-received missing-msgs-received\n\n");
for(Map.Entry<Long,XmitTimeStat> entry: map.entrySet()) {
sb=new StringBuilder();
stat=entry.getValue();
sb.append(entry.getKey()).append(" ");
sb.append(stat.gaps_detected).append(" ");
sb.append(stat.xmit_reqs_sent).append(" ");
sb.append(stat.xmit_reqs_received).append(" ");
sb.append(stat.xmit_rsps_sent).append(" ");
sb.append(stat.xmit_rsps_received).append(" ");
sb.append(stat.missing_msgs_received).append("\n");
out.write(sb.toString());
}
}
finally {
out.close();
}
}
private Digest.Entry getEntry(Address sender) {
if(sender == null) {
if(log.isErrorEnabled()) {
log.error("sender is null");
}
return null;
}
NakReceiverWindow win=xmit_table.get(sender);
if(win == null) {
if(log.isErrorEnabled()) {
log.error("sender " + sender + " not found in xmit_table");
}
return null;
}
long low=win.getLowestSeen(),
highest_delivered=win.getHighestDelivered(),
highest_received=win.getHighestReceived();
return new Digest.Entry(low, highest_delivered, highest_received);
}
/**
* Garbage collect messages that have been seen by all members. Update sent_msgs: for the sender P in the digest
* which is equal to the local address, garbage collect all messages <= seqno at digest[P]. Update xmit_table:
* for each sender P in the digest and its highest seqno seen SEQ, garbage collect all delivered_msgs in the
* NakReceiverWindow corresponding to P which are <= seqno at digest[P].
*/
private void stable(Digest digest) {
NakReceiverWindow recv_win;
long my_highest_rcvd; // highest seqno received in my digest for a sender P
long stability_highest_rcvd; // highest seqno received in the stability vector for a sender P
if(members == null || local_addr == null || digest == null) {
if(log.isWarnEnabled())
log.warn("members, local_addr or digest are null !");
return;
}
if(log.isTraceEnabled()) {
log.trace("received stable digest " + digest);
}
stability_msgs.add(digest);
Address sender;
Digest.Entry val;
long high_seqno_delivered, high_seqno_received;
for(Map.Entry<Address, Digest.Entry> entry: digest.getSenders().entrySet()) {
sender=entry.getKey();
if(sender == null)
continue;
val=entry.getValue();
high_seqno_delivered=val.getHighestDeliveredSeqno();
high_seqno_received=val.getHighestReceivedSeqno();
// check whether the last seqno received for a sender P in the stability vector is > last seqno
// received for P in my digest. if yes, request retransmission (see "Last Message Dropped" topic
// in DESIGN)
recv_win=xmit_table.get(sender);
if(recv_win != null) {
my_highest_rcvd=recv_win.getHighestReceived();
stability_highest_rcvd=high_seqno_received;
if(stability_highest_rcvd >= 0 && stability_highest_rcvd > my_highest_rcvd) {
if(log.isTraceEnabled()) {
log.trace("my_highest_rcvd (" + my_highest_rcvd + ") < stability_highest_rcvd (" +
stability_highest_rcvd + "): requesting retransmission of " +
sender + '#' + stability_highest_rcvd);
}
retransmit(stability_highest_rcvd, stability_highest_rcvd, sender);
}
}
high_seqno_delivered-=gc_lag;
if(high_seqno_delivered < 0) {
continue;
}
if(log.isTraceEnabled())
log.trace("deleting msgs <= " + high_seqno_delivered + " from " + sender);
// delete *delivered* msgs that are stable
if(recv_win != null) {
recv_win.stable(high_seqno_delivered); // delete all messages with seqnos <= seqno
}
}
}
/**
* Implementation of Retransmitter.RetransmitCommand. Called by retransmission thread when gap is detected.
*/
public void retransmit(long first_seqno, long last_seqno, Address sender) {
retransmit(first_seqno, last_seqno, sender, false);
}
protected void retransmit(long first_seqno, long last_seqno, Address sender, boolean multicast_xmit_request) {
NakAckHeader hdr;
Message retransmit_msg;
Address dest=sender; // to whom do we send the XMIT request ?
if(multicast_xmit_request || this.use_mcast_xmit_req) {
dest=null;
}
else {
if(xmit_from_random_member && !local_addr.equals(sender)) {
Address random_member=(Address)Util.pickRandomElement(members);
if(random_member != null && !local_addr.equals(random_member)) {
dest=random_member;
if(log.isTraceEnabled())
log.trace("picked random member " + dest + " to send XMIT request to");
}
}
}
hdr=new NakAckHeader(NakAckHeader.XMIT_REQ, first_seqno, last_seqno, sender);
retransmit_msg=new Message(dest, null, null);
retransmit_msg.setFlag(Message.OOB);
if(log.isTraceEnabled())
log.trace(local_addr + ": sending XMIT_REQ ([" + first_seqno + ", " + last_seqno + "]) to " + dest);
retransmit_msg.putHeader(name, hdr);
ConcurrentMap<Long,Long> tmp=xmit_stats.get(sender);
if(tmp == null) {
tmp=new ConcurrentHashMap<Long,Long>();
ConcurrentMap<Long,Long> tmp2=xmit_stats.putIfAbsent(sender, tmp);
if(tmp2 != null)
tmp=tmp2;
}
for(long seq=first_seqno; seq < last_seqno; seq++) {
tmp.putIfAbsent(seq, System.currentTimeMillis());
}
if(xmit_time_stats != null) {
long key=(System.currentTimeMillis() - xmit_time_stats_start) / 1000;
XmitTimeStat stat=xmit_time_stats.get(key);
if(stat == null) {
stat=new XmitTimeStat();
XmitTimeStat stat2=xmit_time_stats.putIfAbsent(key, stat);
if(stat2 != null)
stat=stat2;
}
stat.xmit_reqs_sent.addAndGet((int)(last_seqno - first_seqno +1));
}
down_prot.down(new Event(Event.MSG, retransmit_msg));
if(stats) {
xmit_reqs_sent+=last_seqno - first_seqno +1;
updateStats(sent, dest, 1, 0, 0);
XmitRequest req=new XmitRequest(sender, first_seqno, last_seqno, dest);
send_history.add(req);
}
}
public void missingMessageReceived(long seqno, Address original_sender) {
ConcurrentMap<Long,Long> tmp=xmit_stats.get(original_sender);
if(tmp != null) {
Long timestamp=tmp.remove(seqno);
if(timestamp != null) {
long diff=System.currentTimeMillis() - timestamp;
BoundedList<Long> list=xmit_times_history.get(original_sender);
if(list == null) {
list=new BoundedList<Long>(xmit_history_max_size);
BoundedList<Long> list2=xmit_times_history.putIfAbsent(original_sender, list);
if(list2 != null)
list=list2;
}
list.add(diff);
// compute the smoothed average for retransmission times for original_sender
synchronized(smoothed_avg_xmit_times) {
Double smoothed_avg=smoothed_avg_xmit_times.get(original_sender);
if(smoothed_avg == null)
smoothed_avg=INITIAL_SMOOTHED_AVG;
// the smoothed avg takes 90% of the previous value, 100% of the new value and averages them
// then, we add 10% to be on the safe side (an xmit value should rather err on the higher than lower side)
smoothed_avg=((smoothed_avg * WEIGHT) + diff) / 2;
smoothed_avg=smoothed_avg * (2 - WEIGHT);
smoothed_avg_xmit_times.put(original_sender, smoothed_avg);
}
}
}
if(xmit_time_stats != null) {
long key=(System.currentTimeMillis() - xmit_time_stats_start) / 1000;
XmitTimeStat stat=xmit_time_stats.get(key);
if(stat == null) {
stat=new XmitTimeStat();
XmitTimeStat stat2=xmit_time_stats.putIfAbsent(key, stat);
if(stat2 != null)
stat=stat2;
}
stat.missing_msgs_received.incrementAndGet();
}
if(stats) {
missing_msgs_received++;
updateStats(received, original_sender, 0, 0, 1);
MissingMessage missing=new MissingMessage(original_sender, seqno);
receive_history.add(missing);
}
}
/** Called when a message gap is detected */
public void messageGapDetected(long from, long to, Address src) {
if(xmit_time_stats != null) {
long key=(System.currentTimeMillis() - xmit_time_stats_start) / 1000;
XmitTimeStat stat=xmit_time_stats.get(key);
if(stat == null) {
stat=new XmitTimeStat();
XmitTimeStat stat2=xmit_time_stats.putIfAbsent(key, stat);
if(stat2 != null)
stat=stat2;
}
stat.gaps_detected.addAndGet((int)(to - from +1));
}
}
private void clear() {
// changed April 21 2004 (bela): SourceForge bug# 938584. We cannot delete our own messages sent between
// a join() and a getState(). Otherwise retransmission requests from members who missed those msgs might
// fail. Not to worry though: those msgs will be cleared by STABLE (message garbage collection)
// sent_msgs.clear();
for(NakReceiverWindow win: xmit_table.values()) {
win.reset();
}
xmit_table.clear();
undelivered_msgs.set(0);
}
private void reset() {
seqno_lock.lock();
try {
seqno=0;
}
finally {
seqno_lock.unlock();
}
for(NakReceiverWindow win: xmit_table.values()) {
win.destroy();
}
xmit_table.clear();
undelivered_msgs.set(0);
}
@ManagedOperation(description="TODO")
public String printMessages() {
StringBuilder ret=new StringBuilder();
Map.Entry<Address,NakReceiverWindow> entry;
Address addr;
Object w;
for(Iterator<Map.Entry<Address,NakReceiverWindow>> it=xmit_table.entrySet().iterator(); it.hasNext();) {
entry=it.next();
addr=entry.getKey();
w=entry.getValue();
ret.append(addr).append(": ").append(w.toString()).append('\n');
}
return ret.toString();
}
@ManagedOperation(description="TODO")
public String printRetransmissionAvgs() {
StringBuilder sb=new StringBuilder();
for(Map.Entry<Address,BoundedList<Long>> entry: xmit_times_history.entrySet()) {
Address sender=entry.getKey();
BoundedList<Long> list=entry.getValue();
long tmp=0;
int i=0;
for(Long val: list) {
tmp+=val;
i++;
}
double avg=i > 0? tmp / i: -1;
sb.append(sender).append(": ").append(avg).append("\n");
}
return sb.toString();
}
@ManagedOperation(description="TODO")
public String printSmoothedRetransmissionAvgs() {
StringBuilder sb=new StringBuilder();
for(Map.Entry<Address,Double> entry: smoothed_avg_xmit_times.entrySet()) {
sb.append(entry.getKey()).append(": ").append(entry.getValue()).append("\n");
}
return sb.toString();
}
@ManagedOperation(description="TODO")
public String printRetransmissionTimes() {
StringBuilder sb=new StringBuilder();
for(Map.Entry<Address,BoundedList<Long>> entry: xmit_times_history.entrySet()) {
Address sender=entry.getKey();
BoundedList<Long> list=entry.getValue();
sb.append(sender).append(": ").append(list).append("\n");
}
return sb.toString();
}
@ManagedAttribute
public double getTotalAverageRetransmissionTime() {
long total=0;
int i=0;
for(BoundedList<Long> list: xmit_times_history.values()) {
for(Long val: list) {
total+=val;
i++;
}
}
return i > 0? total / i: -1;
}
@ManagedAttribute
public double getTotalAverageSmoothedRetransmissionTime() {
double total=0.0;
int cnt=0;
synchronized(smoothed_avg_xmit_times) {
for(Double val: smoothed_avg_xmit_times.values()) {
if(val != null) {
total+=val;
cnt++;
}
}
}
return cnt > 0? total / cnt : -1;
}
/** Returns the smoothed average retransmission time for a given sender */
public double getSmoothedAverageRetransmissionTime(Address sender) {
synchronized(smoothed_avg_xmit_times) {
Double retval=smoothed_avg_xmit_times.get(sender);
if(retval == null) {
retval=INITIAL_SMOOTHED_AVG;
smoothed_avg_xmit_times.put(sender, retval);
}
return retval;
}
}
// public static final class LossRate {
// private final Set<Long> received=new HashSet<Long>();
// private final Set<Long> missing=new HashSet<Long>();
// private double smoothed_loss_rate=0.0;
// public synchronized void addReceived(long seqno) {
// received.add(seqno);
// missing.remove(seqno);
// setSmoothedLossRate();
// public synchronized void addReceived(Long ... seqnos) {
// for(int i=0; i < seqnos.length; i++) {
// Long seqno=seqnos[i];
// received.add(seqno);
// missing.remove(seqno);
// setSmoothedLossRate();
// public synchronized void addMissing(long from, long to) {
// for(long i=from; i <= to; i++) {
// if(!received.contains(i))
// missing.add(i);
// setSmoothedLossRate();
// public synchronized double computeLossRate() {
// int num_missing=missing.size();
// if(num_missing == 0)
// return 0.0;
// int num_received=received.size();
// int total=num_missing + num_received;
// return num_missing / (double)total;
// public synchronized double getSmoothedLossRate() {
// return smoothed_loss_rate;
// public synchronized String toString() {
// StringBuilder sb=new StringBuilder();
// int num_missing=missing.size();
// int num_received=received.size();
// int total=num_missing + num_received;
// sb.append("total=").append(total).append(" (received=").append(received.size()).append(", missing=")
// .append(missing.size()).append(", loss rate=").append(computeLossRate())
// .append(", smoothed loss rate=").append(smoothed_loss_rate).append(")");
// return sb.toString();
// /** Set the new smoothed_loss_rate value to 70% of the new value and 30% of the old value */
// private void setSmoothedLossRate() {
// double new_loss_rate=computeLossRate();
// if(smoothed_loss_rate == 0) {
// smoothed_loss_rate=new_loss_rate;
// else {
// smoothed_loss_rate=smoothed_loss_rate * .3 + new_loss_rate * .7;
private static class XmitTimeStat {
final AtomicInteger gaps_detected=new AtomicInteger(0);
final AtomicInteger xmit_reqs_sent=new AtomicInteger(0);
final AtomicInteger xmit_reqs_received=new AtomicInteger(0);
final AtomicInteger xmit_rsps_sent=new AtomicInteger(0);
final AtomicInteger xmit_rsps_received=new AtomicInteger(0);
final AtomicInteger missing_msgs_received=new AtomicInteger(0);
}
private class ActualInterval implements Interval {
private final Address sender;
public ActualInterval(Address sender) {
this.sender=sender;
}
public long next() {
return (long)getSmoothedAverageRetransmissionTime(sender);
}
public Interval copy() {
return this;
}
}
static class StatsEntry {
long xmit_reqs, xmit_rsps, missing_msgs_rcvd;
public String toString() {
StringBuilder sb=new StringBuilder();
sb.append(xmit_reqs).append(" xmit_reqs").append(", ").append(xmit_rsps).append(" xmit_rsps");
sb.append(", ").append(missing_msgs_rcvd).append(" missing msgs");
return sb.toString();
}
}
static class XmitRequest {
Address original_sender; // original sender of message
long low, high, timestamp=System.currentTimeMillis();
Address xmit_dest; // destination to which XMIT_REQ is sent, usually the original sender
XmitRequest(Address original_sender, long low, long high, Address xmit_dest) {
this.original_sender=original_sender;
this.xmit_dest=xmit_dest;
this.low=low;
this.high=high;
}
public String toString() {
StringBuilder sb=new StringBuilder();
sb.append(new Date(timestamp)).append(": ").append(original_sender).append(" #[").append(low);
sb.append("-").append(high).append("]");
sb.append(" (XMIT_REQ sent to ").append(xmit_dest).append(")");
return sb.toString();
}
}
static class MissingMessage {
Address original_sender;
long seq, timestamp=System.currentTimeMillis();
MissingMessage(Address original_sender, long seqno) {
this.original_sender=original_sender;
this.seq=seqno;
}
public String toString() {
StringBuilder sb=new StringBuilder();
sb.append(new Date(timestamp)).append(": ").append(original_sender).append(" #").append(seq);
return sb.toString();
}
}
}
|
package org.jgroups.protocols.pbcast;
import org.jgroups.*;
import org.jgroups.annotations.*;
import org.jgroups.conf.PropertyConverters;
import org.jgroups.stack.*;
import org.jgroups.util.*;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
/**
* Negative AcKnowledgement layer (NAKs). Messages are assigned a monotonically
* increasing sequence number (seqno). Receivers deliver messages ordered
* according to seqno and request retransmission of missing messages.<br/>
* Retransmit requests are usually sent to the original sender of a message, but
* this can be changed by xmit_from_random_member (send to random member) or
* use_mcast_xmit_req (send to everyone). Responses can also be sent to everyone
* instead of the requester by setting use_mcast_xmit to true.
*
* @author Bela Ban
* @version $Id: NAKACK.java,v 1.205 2008/10/08 15:05:29 belaban Exp $
*/
@MBean(description="Reliable transmission multipoint FIFO protocol")
@DeprecatedProperty(names={"max_xmit_size"})
public class NAKACK extends Protocol implements Retransmitter.RetransmitCommand, NakReceiverWindow.Listener {
private static final long INITIAL_SEQNO=0;
private static final String name="NAKACK";
/**
* the weight with which we take the previous smoothed average into account,
* WEIGHT should be >0 and <= 1
*/
private static final double WEIGHT=0.9;
private static final double INITIAL_SMOOTHED_AVG=30.0;
private static final int NUM_REBROADCAST_MSGS=3;
@Property(name="retransmit_timeout", converter=PropertyConverters.LongArray.class, description="Timeout before requesting retransmissions")
private long[] retransmit_timeouts= { 600, 1200, 2400, 4800 }; // time(s) to wait before requesting retransmission
@Property(description="If true, retransmissions stats will be captured. Default is false")
boolean enable_xmit_time_stats=false;
@ManagedAttribute(description="Garbage collection lag", writable=true)
@Property
private int gc_lag=20; // number of msgs garbage collection lags behind
/**
* Retransmit messages using multicast rather than unicast. This has the
* advantage that, if many receivers lost a message, the sender only
* retransmits once.
*/
@Property(description="Retransmit messages using multicast rather than unicast. Default is true")
@ManagedAttribute(description="Retransmit messages using multicast rather than unicast", writable=true)
private boolean use_mcast_xmit=true;
/**
* Use a multicast to request retransmission of missing messages. This may
* be costly as every member in the cluster will send a response
*/
@Property(description="Use a multicast to request retransmission of missing messages. Default is false")
private boolean use_mcast_xmit_req=false;
/**
* Ask a random member for retransmission of a missing message. If set to
* true, discard_delivered_msgs will be set to false
*/
@Property(description="Ask a random member for retransmission of a missing message. Default is false")
@ManagedAttribute(description="Ask a random member for retransmission of a missing message", writable=true)
private boolean xmit_from_random_member=false;
/**
* The first value (in milliseconds) to use in the exponential backoff
* retransmission mechanism. Only enabled if the value is > 0
*/
@Property(description="The first value (in milliseconds) to use in the exponential backoff. Enabled if freater than 0. Default is 0")
private long exponential_backoff=0;
/**
* If enabled, we use statistics gathered from actual retransmission times
* to compute the new retransmission times
*/
@Property(description="Use statistics gathered from actual retransmission times to compute new retransmission times. Default is false")
private boolean use_stats_for_retransmission=false;
/**
* Messages that have been received in order are sent up the stack (=
* delivered to the application). Delivered messages are removed from
* NakReceiverWindow.xmit_table and moved to
* NakReceiverWindow.delivered_msgs, where they are later garbage collected
* (by STABLE). Since we do retransmits only from sent messages, never
* received or delivered messages, we can turn the moving to delivered_msgs
* off, so we don't keep the message around, and don't need to wait for
* garbage collection to remove them.
*/
@Property(description="Should messages delivere to application be discarded. Default is false")
@ManagedAttribute(description="Discard delivered messages", writable=true)
private boolean discard_delivered_msgs=false;
@Property(description="See http://jira.jboss.com/jira/browse/JGRP-656. Default is true")
private boolean eager_lock_release=true;
/**
* If value is > 0, the retransmit buffer is bounded: only the
* max_xmit_buf_size latest messages are kept, older ones are discarded when
* the buffer size is exceeded. A value <= 0 means unbounded buffers
*/
@Property(description="If value is > 0, the retransmit buffer is bounded. If value <= 0 unbounded buffers are used. Default is 0")
@ManagedAttribute(description="If value is > 0, the retransmit buffer is bounded. If value <= 0 unbounded buffers are used", writable=true)
private int max_xmit_buf_size=0;
@Property(description="Size of retransmission history. Default is 50 entries")
private int xmit_history_max_size=50;
@Property
private long max_rebroadcast_timeout=2000;
/**
* When not finding a message on an XMIT request, include the last N
* stability messages in the error message
*/
@Property(description="Should stability history be printed if we fail in retransmission. Default is false")
protected boolean print_stability_history_on_failed_xmit=false;
@Property(description="Size of send and receive history. Default is 20 entries")
private int stats_list_size=20;
@ManagedAttribute(description="Number of retransmit requests received")
private long xmit_reqs_received;
@ManagedAttribute(description="Number of retransmit requests sent")
private long xmit_reqs_sent;
@ManagedAttribute(description="Number of retransmit responses received")
private long xmit_rsps_received;
@ManagedAttribute(description="Number of retransmit responses sent")
private long xmit_rsps_sent;
@ManagedAttribute(description="Number of missing messages received")
private long missing_msgs_received;
/**
* Maintains retransmission related data across a time. Only used if enable_xmit_time_stats is set to true.
* At program termination, accumulated data is dumped to a file named by the address of the member.
* Careful, don't enable this in production as the data in this hashmap are
* never reaped ! Really only meant for diagnostics !
*/
private ConcurrentMap<Long,XmitTimeStat> xmit_time_stats=null;
private long xmit_time_stats_start;
/**
* BoundedList<MissingMessage>. Keeps track of the last stats_list_size
* XMIT requests
*/
private BoundedList<MissingMessage> receive_history;
/**
* BoundedList<XmitRequest>. Keeps track of the last stats_list_size
* missing messages received
*/
private BoundedList<XmitRequest> send_history;
/** Captures stats on XMIT_REQS, XMIT_RSPS per sender */
private ConcurrentMap<Address,StatsEntry> sent=new ConcurrentHashMap<Address,StatsEntry>();
/** Captures stats on XMIT_REQS, XMIT_RSPS per receiver */
private ConcurrentMap<Address,StatsEntry> received=new ConcurrentHashMap<Address,StatsEntry>();
/**
* Per-sender map of seqnos and timestamps, to keep track of avg times for retransmission of messages
*/
private final ConcurrentMap<Address,ConcurrentMap<Long,Long>> xmit_stats=new ConcurrentHashMap<Address,ConcurrentMap<Long,Long>>();
/**
* Maintains a list of the last N retransmission times (duration it took to
* retransmit a message) for all members
*/
private final ConcurrentMap<Address,BoundedList<Long>> xmit_times_history=new ConcurrentHashMap<Address,BoundedList<Long>>();
/**
* Maintains a smoothed average of the retransmission times per sender,
* these are the actual values that are used for new retransmission requests
*/
private final Map<Address,Double> smoothed_avg_xmit_times=new HashMap<Address,Double>();
private Map<Thread,ReentrantLock> locks;
private boolean is_server=false;
private Address local_addr=null;
private final List<Address> members=new CopyOnWriteArrayList<Address>();
private View view;
@GuardedBy("seqno_lock")
private long seqno=0; // current message sequence number (starts with 1)
private final Lock seqno_lock=new ReentrantLock();
/** Map to store sent and received messages (keyed by sender) */
private final ConcurrentMap<Address,NakReceiverWindow> xmit_table=new ConcurrentHashMap<Address,NakReceiverWindow>(11);
private volatile boolean leaving=false;
private volatile boolean started=false;
private TimeScheduler timer=null;
/**
* Keeps track of OOB messages sent by myself, needed by
* {@link #handleMessage(org.jgroups.Message, NakAckHeader)}
*/
private final Set<Long> oob_loopback_msgs=Collections.synchronizedSet(new HashSet<Long>());
private final Lock rebroadcast_lock=new ReentrantLock();
private final Condition rebroadcast_done=rebroadcast_lock.newCondition();
// set during processing of a rebroadcast event
private volatile boolean rebroadcasting=false;
private final Lock rebroadcast_digest_lock=new ReentrantLock();
@GuardedBy("rebroadcast_digest_lock")
private Digest rebroadcast_digest=null;
/** BoundedList<Digest>, keeps the last 10 stability messages */
private final BoundedList<Digest> stability_msgs=new BoundedList<Digest>(10);
/** If true, logs messages discarded because received from other members */
@ManagedAttribute(description="If true, logs messages discarded because received from other members", writable=true)
private boolean log_discard_msgs=true;
/** <em>Regular</em> messages which have been added, but not removed */
private final AtomicInteger undelivered_msgs=new AtomicInteger(0);
public NAKACK() {
}
public String getName() {
return name;
}
@ManagedAttribute
public int getUndeliveredMessages() {
return undelivered_msgs.get();
}
public long getXmitRequestsReceived() {return xmit_reqs_received;}
public long getXmitRequestsSent() {return xmit_reqs_sent;}
public long getXmitResponsesReceived() {return xmit_rsps_received;}
public long getXmitResponsesSent() {return xmit_rsps_sent;}
public long getMissingMessagesReceived() {return missing_msgs_received;}
@ManagedAttribute
public int getPendingRetransmissionRequests() {
int num=0;
for(NakReceiverWindow win: xmit_table.values()) {
num+=win.getPendingXmits();
}
return num;
}
@ManagedAttribute
public int getXmitTableSize() {
int num=0;
for(NakReceiverWindow win: xmit_table.values()) {
num+=win.size();
}
return num;
}
public int getReceivedTableSize() {
return getPendingRetransmissionRequests();
}
public void resetStats() {
xmit_reqs_received=xmit_reqs_sent=xmit_rsps_received=xmit_rsps_sent=missing_msgs_received=0;
sent.clear();
received.clear();
if(receive_history !=null)
receive_history.clear();
if(send_history != null)
send_history.clear();
}
public void init() throws Exception {
if(enable_xmit_time_stats) {
if(log.isWarnEnabled())
log.warn("enable_xmit_time_stats is experimental, and may be removed in any release");
xmit_time_stats=new ConcurrentHashMap<Long,XmitTimeStat>();
xmit_time_stats_start=System.currentTimeMillis();
}
if(xmit_from_random_member) {
if(discard_delivered_msgs) {
discard_delivered_msgs=false;
log.warn("xmit_from_random_member set to true: changed discard_delivered_msgs to false");
}
}
if(stats) {
send_history=new BoundedList<XmitRequest>(stats_list_size);
receive_history=new BoundedList<MissingMessage>(stats_list_size);
}
}
public int getGcLag() {
return gc_lag;
}
public void setGcLag(int gc_lag) {
this.gc_lag=gc_lag;
}
public boolean isUseMcastXmit() {
return use_mcast_xmit;
}
public void setUseMcastXmit(boolean use_mcast_xmit) {
this.use_mcast_xmit=use_mcast_xmit;
}
public boolean isXmitFromRandomMember() {
return xmit_from_random_member;
}
public void setXmitFromRandomMember(boolean xmit_from_random_member) {
this.xmit_from_random_member=xmit_from_random_member;
}
public boolean isDiscardDeliveredMsgs() {
return discard_delivered_msgs;
}
public void setDiscardDeliveredMsgs(boolean discard_delivered_msgs) {
boolean old=this.discard_delivered_msgs;
this.discard_delivered_msgs=discard_delivered_msgs;
if(old != this.discard_delivered_msgs) {
for(NakReceiverWindow win: xmit_table.values()) {
win.setDiscardDeliveredMessages(this.discard_delivered_msgs);
}
}
}
public int getMaxXmitBufSize() {
return max_xmit_buf_size;
}
public void setMaxXmitBufSize(int max_xmit_buf_size) {
this.max_xmit_buf_size=max_xmit_buf_size;
}
/**
*
* @return
* @deprecated removed in 2.6
*/
public long getMaxXmitSize() {
return -1;
}
/**
*
* @param max_xmit_size
* @deprecated removed in 2.6
*/
public void setMaxXmitSize(long max_xmit_size) {
}
public void setLogDiscardMessages(boolean flag) {
log_discard_msgs=flag;
}
public boolean getLogDiscardMessages() {
return log_discard_msgs;
}
public Map<String,Object> dumpStats() {
Map<String,Object> retval=super.dumpStats();
if(retval == null)
retval=new HashMap<String,Object>();
retval.put("xmit_reqs_received", new Long(xmit_reqs_received));
retval.put("xmit_reqs_sent", new Long(xmit_reqs_sent));
retval.put("xmit_rsps_received", new Long(xmit_rsps_received));
retval.put("xmit_rsps_sent", new Long(xmit_rsps_sent));
retval.put("missing_msgs_received", new Long(missing_msgs_received));
retval.put("msgs", printMessages());
return retval;
}
public String printStats() {
Map.Entry entry;
Object key, val;
StringBuilder sb=new StringBuilder();
sb.append("sent:\n");
for(Iterator it=sent.entrySet().iterator(); it.hasNext();) {
entry=(Map.Entry)it.next();
key=entry.getKey();
if(key == null || key == Global.NULL) key="<mcast dest>";
val=entry.getValue();
sb.append(key).append(": ").append(val).append("\n");
}
sb.append("\nreceived:\n");
for(Iterator it=received.entrySet().iterator(); it.hasNext();) {
entry=(Map.Entry)it.next();
key=entry.getKey();
if(key == null || key == Global.NULL) key="<mcast dest>";
val=entry.getValue();
sb.append(key).append(": ").append(val).append("\n");
}
sb.append("\nXMIT_REQS sent:\n");
for(XmitRequest tmp: send_history) {
sb.append(tmp).append("\n");
}
sb.append("\nMissing messages received\n");
for(MissingMessage missing: receive_history) {
sb.append(missing).append("\n");
}
sb.append("\nStability messages received\n");
sb.append(printStabilityMessages()).append("\n");
return sb.toString();
}
@ManagedOperation(description="TODO")
public String printStabilityMessages() {
StringBuilder sb=new StringBuilder();
sb.append(Util.printListWithDelimiter(stability_msgs, "\n"));
return sb.toString();
}
public String printStabilityHistory() {
StringBuilder sb=new StringBuilder();
int i=1;
for(Digest digest: stability_msgs) {
sb.append(i++).append(": ").append(digest).append("\n");
}
return sb.toString();
}
@ManagedOperation(description="TODO")
public String printLossRates() {
StringBuilder sb=new StringBuilder();
NakReceiverWindow win;
for(Map.Entry<Address,NakReceiverWindow> entry: xmit_table.entrySet()) {
win=entry.getValue();
sb.append(entry.getKey()).append(": ").append(win.printLossRate()).append("\n");
}
return sb.toString();
}
@ManagedAttribute
public double getAverageLossRate() {
double retval=0.0;
int count=0;
if(xmit_table.isEmpty())
return 0.0;
for(NakReceiverWindow win: xmit_table.values()) {
retval+=win.getLossRate();
count++;
}
return retval / (double)count;
}
@ManagedAttribute
public double getAverageSmoothedLossRate() {
double retval=0.0;
int count=0;
if(xmit_table.isEmpty())
return 0.0;
for(NakReceiverWindow win: xmit_table.values()) {
retval+=win.getSmoothedLossRate();
count++;
}
return retval / (double)count;
}
public Vector<Integer> providedUpServices() {
Vector<Integer> retval=new Vector<Integer>(5);
retval.addElement(new Integer(Event.GET_DIGEST));
retval.addElement(new Integer(Event.SET_DIGEST));
retval.addElement(new Integer(Event.MERGE_DIGEST));
return retval;
}
public void start() throws Exception {
timer=getTransport().getTimer();
if(timer == null)
throw new Exception("timer is null");
locks=stack.getLocks();
started=true;
leaving=false;
if(xmit_time_stats != null) {
Runtime.getRuntime().addShutdownHook(new Thread() {
public void run() {
String filename="xmit-stats-" + local_addr + ".log";
System.out.println("-- dumping runtime xmit stats to " + filename);
try {
dumpXmitStats(filename);
}
catch(IOException e) {
e.printStackTrace();
}
}
});
}
}
public void stop() {
started=false;
reset(); // clears sent_msgs and destroys all NakReceiverWindows
oob_loopback_msgs.clear();
}
/**
* <b>Callback</b>. Called by superclass when event may be handled.<p> <b>Do not use <code>down_prot.down()</code> in this
* method as the event is passed down by default by the superclass after this method returns !</b>
*/
public Object down(Event evt) {
switch(evt.getType()) {
case Event.MSG:
Message msg=(Message)evt.getArg();
Address dest=msg.getDest();
if(dest != null && !dest.isMulticastAddress()) {
break; // unicast address: not null and not mcast, pass down unchanged
}
send(evt, msg);
return null; // don't pass down the stack
case Event.STABLE: // generated by STABLE layer. Delete stable messages passed in arg
stable((Digest)evt.getArg());
return null; // do not pass down further (Bela Aug 7 2001)
case Event.GET_DIGEST:
return getDigest();
case Event.SET_DIGEST:
setDigest((Digest)evt.getArg());
return null;
case Event.MERGE_DIGEST:
mergeDigest((Digest)evt.getArg());
return null;
case Event.TMP_VIEW:
View tmp_view=(View)evt.getArg();
Vector<Address> mbrs=tmp_view.getMembers();
members.clear();
members.addAll(mbrs);
// adjustReceivers(false);
break;
case Event.VIEW_CHANGE:
tmp_view=(View)evt.getArg();
mbrs=tmp_view.getMembers();
members.clear();
members.addAll(mbrs);
view=tmp_view;
adjustReceivers(members);
is_server=true; // check vids from now on
Set<Address> tmp=new LinkedHashSet<Address>(members);
tmp.add(null); // for null destination (= mcast)
sent.keySet().retainAll(tmp);
received.keySet().retainAll(tmp);
xmit_stats.keySet().retainAll(tmp);
// in_progress.keySet().retainAll(mbrs); // remove elements which are not in the membership
break;
case Event.BECOME_SERVER:
is_server=true;
break;
case Event.DISCONNECT:
leaving=true;
reset();
break;
case Event.REBROADCAST:
rebroadcasting=true;
rebroadcast_digest=(Digest)evt.getArg();
try {
rebroadcastMessages();
}
finally {
rebroadcasting=false;
rebroadcast_digest_lock.lock();
try {
rebroadcast_digest=null;
}
finally {
rebroadcast_digest_lock.unlock();
}
}
return null;
}
return down_prot.down(evt);
}
/**
* <b>Callback</b>. Called by superclass when event may be handled.<p> <b>Do not use <code>PassUp</code> in this
* method as the event is passed up by default by the superclass after this method returns !</b>
*/
public Object up(Event evt) {
switch(evt.getType()) {
case Event.MSG:
Message msg=(Message)evt.getArg();
NakAckHeader hdr=(NakAckHeader)msg.getHeader(name);
if(hdr == null)
break; // pass up (e.g. unicast msg)
// discard messages while not yet server (i.e., until JOIN has returned)
if(!is_server) {
if(log.isTraceEnabled())
log.trace("message was discarded (not yet server)");
return null;
}
// Changed by bela Jan 29 2003: we must not remove the header, otherwise
// further xmit requests will fail !
//hdr=(NakAckHeader)msg.removeHeader(getName());
switch(hdr.type) {
case NakAckHeader.MSG:
handleMessage(msg, hdr);
return null; // transmitter passes message up for us !
case NakAckHeader.XMIT_REQ:
if(hdr.range == null) {
if(log.isErrorEnabled()) {
log.error("XMIT_REQ: range of xmit msg is null; discarding request from " + msg.getSrc());
}
return null;
}
handleXmitReq(msg.getSrc(), hdr.range.low, hdr.range.high, hdr.sender);
return null;
case NakAckHeader.XMIT_RSP:
if(log.isTraceEnabled())
log.trace("received missing message " + msg.getSrc() + ":" + hdr.seqno);
handleXmitRsp(msg);
return null;
default:
if(log.isErrorEnabled()) {
log.error("NakAck header type " + hdr.type + " not known !");
}
return null;
}
case Event.STABLE: // generated by STABLE layer. Delete stable messages passed in arg
stable((Digest)evt.getArg());
return null; // do not pass up further (Bela Aug 7 2001)
case Event.SET_LOCAL_ADDRESS:
local_addr=(Address)evt.getArg();
break;
case Event.SUSPECT:
// release the promise if rebroadcasting is in progress... otherwise we wait forever. there will be a new
// flush round anyway
if(rebroadcasting) {
cancelRebroadcasting();
}
break;
}
return up_prot.up(evt);
}
private void send(Event evt, Message msg) {
if(msg == null)
throw new NullPointerException("msg is null; event is " + evt);
if(!started) {
if(log.isTraceEnabled())
log.trace("[" + local_addr + "] discarded message as start() has not been called, message: " + msg);
return;
}
long msg_id;
NakReceiverWindow win=xmit_table.get(local_addr);
msg.setSrc(local_addr); // this needs to be done so we can check whether the message sender is the local_addr
seqno_lock.lock();
try {
try { // incrementing seqno and adding the msg to sent_msgs needs to be atomic
msg_id=seqno +1;
msg.putHeader(name, new NakAckHeader(NakAckHeader.MSG, msg_id));
win.add(msg_id, msg);
seqno=msg_id;
}
catch(Throwable t) {
throw new RuntimeException("failure adding msg " + msg + " to the retransmit table for " + local_addr, t);
}
}
finally {
seqno_lock.unlock();
}
try {
if(msg.isFlagSet(Message.OOB))
oob_loopback_msgs.add(msg_id);
if(log.isTraceEnabled())
log.trace("sending " + local_addr + "#" + msg_id);
down_prot.down(evt); // if this fails, since msg is in sent_msgs, it can be retransmitted
}
catch(Throwable t) { // eat the exception, don't pass it up the stack
if(log.isWarnEnabled()) {
log.warn("failure passing message down", t);
}
}
}
/**
* Finds the corresponding NakReceiverWindow and adds the message to it (according to seqno). Then removes as many
* messages as possible from the NRW and passes them up the stack. Discards messages from non-members.
*/
private void handleMessage(Message msg, NakAckHeader hdr) {
Address sender=msg.getSrc();
if(sender == null) {
if(log.isErrorEnabled())
log.error("sender of message is null");
return;
}
if(log.isTraceEnabled())
log.trace(new StringBuilder().append('[').append(local_addr).append(": received ").append(sender).append('#').append(hdr.seqno));
NakReceiverWindow win=xmit_table.get(sender);
if(win == null) { // discard message if there is no entry for sender
if(leaving)
return;
if(log.isWarnEnabled() && log_discard_msgs)
log.warn(local_addr + "] discarded message from non-member " + sender + ", my view is " + view);
return;
}
boolean loopback=local_addr.equals(sender);
boolean added=loopback || win.add(hdr.seqno, msg);
boolean regular_msg_added=added && !msg.isFlagSet(Message.OOB);
// message is passed up if OOB. Later, when remove() is called, we discard it. This affects ordering !
if(added && msg.isFlagSet(Message.OOB)) {
if(!loopback || oob_loopback_msgs.remove(hdr.seqno)) {
up_prot.up(new Event(Event.MSG, msg));
win.removeOOBMessage();
if(!(win.hasMessagesToRemove() && undelivered_msgs.get() > 0))
return;
}
}
// Efficient way of checking whether another thread is already processing messages from 'sender'.
// If that's the case, we return immediately and let the exiting thread process our message
// can be returned to the thread pool
final AtomicBoolean processing=win.getProcessing();
if(!processing.compareAndSet(false, true)) {
return;
}
// where lots of threads can come up to this point concurrently, but only 1 is allowed to pass at a time
// We *can* deliver messages from *different* senders concurrently, e.g. reception of P1, Q1, P2, Q2 can result in
// delivery of P1, Q1, Q2, P2: FIFO (implemented by NAKACK) says messages need to be delivered in the
// order in which they were sent by the sender
short removed_regular_msgs=0;
// 2nd line of defense: in case of an exception, remove() might not be called, therefore processing would never
// be set back to false. If we get an exception and released_processing is not true, then we set
// processing to false in the finally clause
boolean released_processing=false;
final ReentrantLock lock=win.getLock();
try {
lock.lock();
if(eager_lock_release)
locks.put(Thread.currentThread(), lock);
while(true) {
Message msg_to_deliver=win.remove(processing);
if(msg_to_deliver == null) {
released_processing=true;
return; // processing will be set to false now
}
if(msg_to_deliver.isFlagSet(Message.OOB)) {
continue;
}
removed_regular_msgs++;
// Changed by bela Jan 29 2003: not needed (see above)
//msg_to_deliver.removeHeader(getName());
up_prot.up(new Event(Event.MSG, msg_to_deliver));
}
}
finally {
if(!released_processing)
processing.set(false);
if(eager_lock_release)
locks.remove(Thread.currentThread());
if(lock.isHeldByCurrentThread())
lock.unlock();
// We keep track of regular messages that we added, but couldn't remove (because of ordering).
// When we have such messages pending, then even OOB threads will remove and process them
if(regular_msg_added && removed_regular_msgs == 0) {
undelivered_msgs.incrementAndGet();
}
if(removed_regular_msgs > 0) { // regardless of whether a message was added or not !
int num_msgs_added=regular_msg_added? 1 : 0;
undelivered_msgs.addAndGet(-(removed_regular_msgs -num_msgs_added));
}
}
}
/**
* Retransmits messsages first_seqno to last_seqno from original_sender from xmit_table to xmit_requester,
* called when XMIT_REQ is received.
* @param xmit_requester The sender of the XMIT_REQ, we have to send the requested copy of the message to this address
* @param first_seqno The first sequence number to be retransmitted (<= last_seqno)
* @param last_seqno The last sequence number to be retransmitted (>= first_seqno)
* @param original_sender The member who originally sent the messsage. Guaranteed to be non-null
*/
private void handleXmitReq(Address xmit_requester, long first_seqno, long last_seqno, Address original_sender) {
Message msg;
if(log.isTraceEnabled()) {
StringBuilder sb=new StringBuilder();
sb.append(local_addr).append(": received xmit request from ").append(xmit_requester).append(" for ");
sb.append(original_sender).append(" [").append(first_seqno).append(" - ").append(last_seqno).append("]");
log.trace(sb.toString());
}
if(first_seqno > last_seqno) {
if(log.isErrorEnabled())
log.error("first_seqno (" + first_seqno + ") > last_seqno (" + last_seqno + "): not able to retransmit");
return;
}
if(stats) {
xmit_reqs_received+=last_seqno - first_seqno +1;
updateStats(received, xmit_requester, 1, 0, 0);
}
if(xmit_time_stats != null) {
long key=(System.currentTimeMillis() - xmit_time_stats_start) / 1000;
XmitTimeStat stat=xmit_time_stats.get(key);
if(stat == null) {
stat=new XmitTimeStat();
XmitTimeStat stat2=xmit_time_stats.putIfAbsent(key, stat);
if(stat2 != null)
stat=stat2;
}
stat.xmit_reqs_received.addAndGet((int)(last_seqno - first_seqno +1));
stat.xmit_rsps_sent.addAndGet((int)(last_seqno - first_seqno +1));
}
NakReceiverWindow win=xmit_table.get(original_sender);
if(win == null) {
if(log.isErrorEnabled()) {
StringBuilder sb=new StringBuilder();
sb.append("(requester=").append(xmit_requester).append(", local_addr=").append(this.local_addr);
sb.append(") ").append(original_sender).append(" not found in retransmission table:\n").append(printMessages());
if(print_stability_history_on_failed_xmit) {
sb.append(" (stability history:\n").append(printStabilityHistory());
}
log.error(sb);
}
return;
}
for(long i=first_seqno; i <= last_seqno; i++) {
msg=win.get(i);
if(msg == null) {
if(log.isWarnEnabled() && !local_addr.equals(xmit_requester)) {
StringBuilder sb=new StringBuilder();
sb.append("(requester=").append(xmit_requester).append(", local_addr=").append(this.local_addr);
sb.append(") message ").append(original_sender).append("::").append(i);
sb.append(" not found in retransmission table of ").append(original_sender).append(":\n").append(win);
if(print_stability_history_on_failed_xmit) {
sb.append(" (stability history:\n").append(printStabilityHistory());
}
log.warn(sb);
}
continue;
}
sendXmitRsp(xmit_requester, msg, i);
}
}
private void cancelRebroadcasting() {
rebroadcast_lock.lock();
try {
rebroadcasting=false;
rebroadcast_done.signalAll();
}
finally {
rebroadcast_lock.unlock();
}
}
private static void updateStats(ConcurrentMap<Address,StatsEntry> map, Address key, int req, int rsp, int missing) {
StatsEntry entry=map.get(key);
if(entry == null) {
entry=new StatsEntry();
StatsEntry tmp=map.putIfAbsent(key, entry);
if(tmp != null)
entry=tmp;
}
entry.xmit_reqs+=req;
entry.xmit_rsps+=rsp;
entry.missing_msgs_rcvd+=missing;
}
/**
* Sends a message msg to the requester. We have to wrap the original message into a retransmit message, as we need
* to preserve the original message's properties, such as src, headers etc.
* @param dest
* @param msg
* @param seqno
*/
private void sendXmitRsp(Address dest, Message msg, long seqno) {
Buffer buf;
if(msg == null) {
if(log.isErrorEnabled())
log.error("message is null, cannot send retransmission");
return;
}
if(stats) {
xmit_rsps_sent++;
updateStats(sent, dest, 0, 1, 0);
}
if(use_mcast_xmit)
dest=null;
if(msg.getSrc() == null)
msg.setSrc(local_addr);
try {
buf=Util.messageToByteBuffer(msg);
Message xmit_msg=new Message(dest, null, buf.getBuf(), buf.getOffset(), buf.getLength());
// changed Bela Jan 4 2007: we should not use OOB for retransmitted messages, otherwise we tax the OOB thread pool
// too much
// msg.setFlag(Message.OOB);
xmit_msg.putHeader(name, new NakAckHeader(NakAckHeader.XMIT_RSP, seqno));
down_prot.down(new Event(Event.MSG, xmit_msg));
}
catch(IOException ex) {
log.error("failed marshalling xmit list", ex);
}
}
private void handleXmitRsp(Message msg) {
if(msg == null) {
if(log.isWarnEnabled())
log.warn("message is null");
return;
}
try {
Message wrapped_msg=Util.byteBufferToMessage(msg.getRawBuffer(), msg.getOffset(), msg.getLength());
if(xmit_time_stats != null) {
long key=(System.currentTimeMillis() - xmit_time_stats_start) / 1000;
XmitTimeStat stat=xmit_time_stats.get(key);
if(stat == null) {
stat=new XmitTimeStat();
XmitTimeStat stat2=xmit_time_stats.putIfAbsent(key, stat);
if(stat2 != null)
stat=stat2;
}
stat.xmit_rsps_received.incrementAndGet();
}
if(stats) {
xmit_rsps_received++;
updateStats(received, msg.getSrc(), 0, 1, 0);
}
up(new Event(Event.MSG, wrapped_msg));
if(rebroadcasting) {
Digest tmp=getDigest();
boolean cancel_rebroadcasting;
rebroadcast_digest_lock.lock();
try {
cancel_rebroadcasting=tmp.isGreaterThanOrEqual(rebroadcast_digest);
}
finally {
rebroadcast_digest_lock.unlock();
}
if(cancel_rebroadcasting) {
cancelRebroadcasting();
}
}
}
catch(Exception ex) {
if(log.isErrorEnabled()) {
log.error("failed reading retransmitted message", ex);
}
}
}
/**
* Takes the argument highest_seqnos and compares it to the current digest. If the current digest has fewer messages,
* then send retransmit messages for the missing messages. Return when all missing messages have been received. If
* we're waiting for a missing message from P, and P crashes while waiting, we need to exclude P from the wait set.
*/
private void rebroadcastMessages() {
Digest my_digest;
Map<Address,Digest.Entry> their_digest;
Address sender;
Digest.Entry their_entry, my_entry;
long their_high, my_high;
long sleep=max_rebroadcast_timeout / NUM_REBROADCAST_MSGS;
long wait_time=max_rebroadcast_timeout, start=System.currentTimeMillis();
while(wait_time > 0) {
rebroadcast_digest_lock.lock();
try {
if(rebroadcast_digest == null)
break;
their_digest=rebroadcast_digest.getSenders();
}
finally {
rebroadcast_digest_lock.unlock();
}
my_digest=getDigest();
boolean xmitted=false;
for(Map.Entry<Address,Digest.Entry> entry: their_digest.entrySet()) {
sender=entry.getKey();
their_entry=entry.getValue();
my_entry=my_digest.get(sender);
if(my_entry == null)
continue;
their_high=their_entry.getHighest();
my_high=my_entry.getHighest();
if(their_high > my_high) {
if(log.isTraceEnabled())
log.trace("sending XMIT request to " + sender + " for messages " + my_high + " - " + their_high);
retransmit(my_high, their_high, sender, true); // use multicast to send retransmit request
xmitted=true;
}
}
if(!xmitted)
return; // we're done; no retransmissions are needed anymore. our digest is >= rebroadcast_digest
rebroadcast_lock.lock();
try {
try {
my_digest=getDigest();
rebroadcast_digest_lock.lock();
try {
if(!rebroadcasting || my_digest.isGreaterThanOrEqual(rebroadcast_digest))
return;
}
finally {
rebroadcast_digest_lock.unlock();
}
rebroadcast_done.await(sleep, TimeUnit.MILLISECONDS);
wait_time-=(System.currentTimeMillis() - start);
}
catch(InterruptedException e) {
}
}
finally {
rebroadcast_lock.unlock();
}
}
}
/**
* Remove old members from NakReceiverWindows and add new members (starting seqno=0). Essentially removes all
* entries from xmit_table that are not in <code>members</code>. This method is not called concurrently
* multiple times
*/
private void adjustReceivers(List<Address> new_members) {
NakReceiverWindow win;
// 1. Remove all senders in xmit_table that are not members anymore
for(Iterator<Address> it=xmit_table.keySet().iterator(); it.hasNext();) {
Address sender=it.next();
if(!new_members.contains(sender)) {
if(local_addr != null && local_addr.equals(sender)) {
if(log.isErrorEnabled())
log.error("will not remove myself (" + sender + ") from xmit_table, received incorrect new membership of " + new_members);
continue;
}
win=xmit_table.get(sender);
win.reset();
if(log.isDebugEnabled()) {
log.debug("removing " + sender + " from xmit_table (not member anymore)");
}
it.remove();
}
}
// 2. Add newly joined members to xmit_table (starting seqno=0)
for(Address sender: new_members) {
if(!xmit_table.containsKey(sender)) {
win=createNakReceiverWindow(sender, INITIAL_SEQNO, 0);
xmit_table.put(sender, win);
}
}
}
/**
* Returns a message digest: for each member P the lowest, highest delivered and highest received seqno is added
*/
private Digest getDigest() {
Digest.Entry entry;
Map<Address,Digest.Entry> map=new HashMap<Address,Digest.Entry>(members.size());
for(Address sender: members) {
entry=getEntry(sender);
if(entry == null) {
if(log.isErrorEnabled()) {
log.error("range is null");
}
continue;
}
map.put(sender, entry);
}
return new Digest(map);
}
/**
* Creates a NakReceiverWindow for each sender in the digest according to the sender's seqno. If NRW already exists,
* reset it.
*/
private void setDigest(Digest digest) {
if(digest == null) {
if(log.isErrorEnabled()) {
log.error("digest or digest.senders is null");
}
return;
}
if(local_addr != null && digest.contains(local_addr)) {
clear();
}
else {
// remove all but local_addr (if not null)
for(Iterator<Address> it=xmit_table.keySet().iterator(); it.hasNext();) {
Address key=it.next();
if(local_addr != null && local_addr.equals(key)) {
;
}
else {
it.remove();
}
}
}
Address sender;
Digest.Entry val;
long initial_seqno;
NakReceiverWindow win;
for(Map.Entry<Address, Digest.Entry> entry: digest.getSenders().entrySet()) {
sender=entry.getKey();
val=entry.getValue();
if(sender == null || val == null) {
if(log.isWarnEnabled()) {
log.warn("sender or value is null");
}
continue;
}
initial_seqno=val.getHighestDeliveredSeqno();
win=createNakReceiverWindow(sender, initial_seqno, val.getLow());
xmit_table.put(sender, win);
}
if(!xmit_table.containsKey(local_addr)) {
if(log.isWarnEnabled()) {
log.warn("digest does not contain local address (local_addr=" + local_addr + ", digest=" + digest);
}
}
}
private void mergeDigest(Digest digest) {
if(digest == null) {
if(log.isErrorEnabled()) {
log.error("digest or digest.senders is null");
}
return;
}
StringBuilder sb=null;
if(log.isDebugEnabled()) {
sb=new StringBuilder();
sb.append("existing digest: " + getDigest()).append("\nnew digest: " + digest);
}
Address sender;
Digest.Entry val;
NakReceiverWindow win;
long highest_delivered_seqno, low_seqno;
for(Map.Entry<Address, Digest.Entry> entry: digest.getSenders().entrySet()) {
sender=entry.getKey();
val=entry.getValue();
if(sender == null || val == null) {
if(log.isWarnEnabled()) {
log.warn("sender or value is null");
}
continue;
}
highest_delivered_seqno=val.getHighestDeliveredSeqno();
low_seqno=val.getLow();
// except for myself
win=xmit_table.get(sender);
if(win != null) {
if(local_addr != null && local_addr.equals(sender)) {
continue;
}
else {
win.reset(); // stops retransmission
xmit_table.remove(sender);
}
}
win=createNakReceiverWindow(sender, highest_delivered_seqno, low_seqno);
xmit_table.put(sender, win);
}
if(log.isDebugEnabled() && sb != null) {
sb.append("\n").append("resulting digest: " + getDigest());
log.debug(sb);
}
if(!xmit_table.containsKey(local_addr)) {
if(log.isWarnEnabled()) {
log.warn("digest does not contain local address (local_addr=" + local_addr + ", digest=" + digest);
}
}
}
private NakReceiverWindow createNakReceiverWindow(Address sender, long initial_seqno, long lowest_seqno) {
NakReceiverWindow win=new NakReceiverWindow(local_addr, sender, this, initial_seqno, lowest_seqno, timer);
if(use_stats_for_retransmission) {
win.setRetransmitTimeouts(new ActualInterval(sender));
}
else if(exponential_backoff > 0) {
win.setRetransmitTimeouts(new ExponentialInterval(exponential_backoff));
}
else {
win.setRetransmitTimeouts(new StaticInterval(retransmit_timeouts));
}
win.setDiscardDeliveredMessages(discard_delivered_msgs);
win.setMaxXmitBufSize(this.max_xmit_buf_size);
if(stats)
win.setListener(this);
return win;
}
private void dumpXmitStats(String filename) throws IOException {
Writer out=new FileWriter(filename);
try {
TreeMap<Long,XmitTimeStat> map=new TreeMap<Long,XmitTimeStat>(xmit_time_stats);
StringBuilder sb;
XmitTimeStat stat;
out.write("time (secs) gaps-detected xmit-reqs-sent xmit-reqs-received xmit-rsps-sent xmit-rsps-received missing-msgs-received\n\n");
for(Map.Entry<Long,XmitTimeStat> entry: map.entrySet()) {
sb=new StringBuilder();
stat=entry.getValue();
sb.append(entry.getKey()).append(" ");
sb.append(stat.gaps_detected).append(" ");
sb.append(stat.xmit_reqs_sent).append(" ");
sb.append(stat.xmit_reqs_received).append(" ");
sb.append(stat.xmit_rsps_sent).append(" ");
sb.append(stat.xmit_rsps_received).append(" ");
sb.append(stat.missing_msgs_received).append("\n");
out.write(sb.toString());
}
}
finally {
out.close();
}
}
private Digest.Entry getEntry(Address sender) {
if(sender == null) {
if(log.isErrorEnabled()) {
log.error("sender is null");
}
return null;
}
NakReceiverWindow win=xmit_table.get(sender);
if(win == null) {
if(log.isErrorEnabled()) {
log.error("sender " + sender + " not found in xmit_table");
}
return null;
}
long low=win.getLowestSeen(),
highest_delivered=win.getHighestDelivered(),
highest_received=win.getHighestReceived();
return new Digest.Entry(low, highest_delivered, highest_received);
}
/**
* Garbage collect messages that have been seen by all members. Update sent_msgs: for the sender P in the digest
* which is equal to the local address, garbage collect all messages <= seqno at digest[P]. Update xmit_table:
* for each sender P in the digest and its highest seqno seen SEQ, garbage collect all delivered_msgs in the
* NakReceiverWindow corresponding to P which are <= seqno at digest[P].
*/
private void stable(Digest digest) {
NakReceiverWindow recv_win;
long my_highest_rcvd; // highest seqno received in my digest for a sender P
long stability_highest_rcvd; // highest seqno received in the stability vector for a sender P
if(members == null || local_addr == null || digest == null) {
if(log.isWarnEnabled())
log.warn("members, local_addr or digest are null !");
return;
}
if(log.isTraceEnabled()) {
log.trace("received stable digest " + digest);
}
stability_msgs.add(digest);
Address sender;
Digest.Entry val;
long high_seqno_delivered, high_seqno_received;
for(Map.Entry<Address, Digest.Entry> entry: digest.getSenders().entrySet()) {
sender=entry.getKey();
if(sender == null)
continue;
val=entry.getValue();
high_seqno_delivered=val.getHighestDeliveredSeqno();
high_seqno_received=val.getHighestReceivedSeqno();
// check whether the last seqno received for a sender P in the stability vector is > last seqno
// received for P in my digest. if yes, request retransmission (see "Last Message Dropped" topic
// in DESIGN)
recv_win=xmit_table.get(sender);
if(recv_win != null) {
my_highest_rcvd=recv_win.getHighestReceived();
stability_highest_rcvd=high_seqno_received;
if(stability_highest_rcvd >= 0 && stability_highest_rcvd > my_highest_rcvd) {
if(log.isTraceEnabled()) {
log.trace("my_highest_rcvd (" + my_highest_rcvd + ") < stability_highest_rcvd (" +
stability_highest_rcvd + "): requesting retransmission of " +
sender + '#' + stability_highest_rcvd);
}
retransmit(stability_highest_rcvd, stability_highest_rcvd, sender);
}
}
high_seqno_delivered-=gc_lag;
if(high_seqno_delivered < 0) {
continue;
}
if(log.isTraceEnabled())
log.trace("deleting msgs <= " + high_seqno_delivered + " from " + sender);
// delete *delivered* msgs that are stable
if(recv_win != null) {
recv_win.stable(high_seqno_delivered); // delete all messages with seqnos <= seqno
}
}
}
/**
* Implementation of Retransmitter.RetransmitCommand. Called by retransmission thread when gap is detected.
*/
public void retransmit(long first_seqno, long last_seqno, Address sender) {
retransmit(first_seqno, last_seqno, sender, false);
}
protected void retransmit(long first_seqno, long last_seqno, final Address sender, boolean multicast_xmit_request) {
NakAckHeader hdr;
Message retransmit_msg;
Address dest=sender; // to whom do we send the XMIT request ?
if(multicast_xmit_request || this.use_mcast_xmit_req) {
dest=null;
}
else {
if(xmit_from_random_member && !local_addr.equals(sender)) {
Address random_member=(Address)Util.pickRandomElement(members);
if(random_member != null && !local_addr.equals(random_member)) {
dest=random_member;
if(log.isTraceEnabled())
log.trace("picked random member " + dest + " to send XMIT request to");
}
}
}
hdr=new NakAckHeader(NakAckHeader.XMIT_REQ, first_seqno, last_seqno, sender);
retransmit_msg=new Message(dest, null, null);
retransmit_msg.setFlag(Message.OOB);
if(log.isTraceEnabled())
log.trace(local_addr + ": sending XMIT_REQ ([" + first_seqno + ", " + last_seqno + "]) to " + dest);
retransmit_msg.putHeader(name, hdr);
ConcurrentMap<Long,Long> tmp=xmit_stats.get(sender);
if(tmp == null) {
tmp=new ConcurrentHashMap<Long,Long>();
ConcurrentMap<Long,Long> tmp2=xmit_stats.putIfAbsent(sender, tmp);
if(tmp2 != null)
tmp=tmp2;
}
for(long seq=first_seqno; seq < last_seqno; seq++) {
tmp.putIfAbsent(seq, System.currentTimeMillis());
}
if(xmit_time_stats != null) {
long key=(System.currentTimeMillis() - xmit_time_stats_start) / 1000;
XmitTimeStat stat=xmit_time_stats.get(key);
if(stat == null) {
stat=new XmitTimeStat();
XmitTimeStat stat2=xmit_time_stats.putIfAbsent(key, stat);
if(stat2 != null)
stat=stat2;
}
stat.xmit_reqs_sent.addAndGet((int)(last_seqno - first_seqno +1));
}
down_prot.down(new Event(Event.MSG, retransmit_msg));
if(stats) {
xmit_reqs_sent+=last_seqno - first_seqno +1;
updateStats(sent, sender, 1, 0, 0);
XmitRequest req=new XmitRequest(sender, first_seqno, last_seqno, sender);
send_history.add(req);
}
}
public void missingMessageReceived(long seqno, final Address original_sender) {
ConcurrentMap<Long,Long> tmp=xmit_stats.get(original_sender);
if(tmp != null) {
Long timestamp=tmp.remove(seqno);
if(timestamp != null) {
long diff=System.currentTimeMillis() - timestamp;
BoundedList<Long> list=xmit_times_history.get(original_sender);
if(list == null) {
list=new BoundedList<Long>(xmit_history_max_size);
BoundedList<Long> list2=xmit_times_history.putIfAbsent(original_sender, list);
if(list2 != null)
list=list2;
}
list.add(diff);
// compute the smoothed average for retransmission times for original_sender
// needs to be synchronized because we rely on the previous value for computation of the next value
synchronized(smoothed_avg_xmit_times) {
Double smoothed_avg=smoothed_avg_xmit_times.get(original_sender);
if(smoothed_avg == null)
smoothed_avg=INITIAL_SMOOTHED_AVG;
// the smoothed avg takes 90% of the previous value, 100% of the new value and averages them
// then, we add 10% to be on the safe side (an xmit value should rather err on the higher than lower side)
smoothed_avg=((smoothed_avg * WEIGHT) + diff) / 2;
smoothed_avg=smoothed_avg * (2 - WEIGHT);
smoothed_avg_xmit_times.put(original_sender, smoothed_avg);
}
}
}
if(xmit_time_stats != null) {
long key=(System.currentTimeMillis() - xmit_time_stats_start) / 1000;
XmitTimeStat stat=xmit_time_stats.get(key);
if(stat == null) {
stat=new XmitTimeStat();
XmitTimeStat stat2=xmit_time_stats.putIfAbsent(key, stat);
if(stat2 != null)
stat=stat2;
}
stat.missing_msgs_received.incrementAndGet();
}
if(stats) {
missing_msgs_received++;
updateStats(received, original_sender, 0, 0, 1);
MissingMessage missing=new MissingMessage(original_sender, seqno);
receive_history.add(missing);
}
}
/** Called when a message gap is detected */
public void messageGapDetected(long from, long to, Address src) {
if(xmit_time_stats != null) {
long key=(System.currentTimeMillis() - xmit_time_stats_start) / 1000;
XmitTimeStat stat=xmit_time_stats.get(key);
if(stat == null) {
stat=new XmitTimeStat();
XmitTimeStat stat2=xmit_time_stats.putIfAbsent(key, stat);
if(stat2 != null)
stat=stat2;
}
stat.gaps_detected.addAndGet((int)(to - from +1));
}
}
private void clear() {
// changed April 21 2004 (bela): SourceForge bug# 938584. We cannot delete our own messages sent between
// a join() and a getState(). Otherwise retransmission requests from members who missed those msgs might
// fail. Not to worry though: those msgs will be cleared by STABLE (message garbage collection)
// sent_msgs.clear();
for(NakReceiverWindow win: xmit_table.values()) {
win.reset();
}
xmit_table.clear();
undelivered_msgs.set(0);
}
private void reset() {
seqno_lock.lock();
try {
seqno=0;
}
finally {
seqno_lock.unlock();
}
for(NakReceiverWindow win: xmit_table.values()) {
win.destroy();
}
xmit_table.clear();
undelivered_msgs.set(0);
}
@ManagedOperation(description="TODO")
public String printMessages() {
StringBuilder ret=new StringBuilder();
Map.Entry<Address,NakReceiverWindow> entry;
Address addr;
Object w;
for(Iterator<Map.Entry<Address,NakReceiverWindow>> it=xmit_table.entrySet().iterator(); it.hasNext();) {
entry=it.next();
addr=entry.getKey();
w=entry.getValue();
ret.append(addr).append(": ").append(w.toString()).append('\n');
}
return ret.toString();
}
@ManagedOperation(description="TODO")
public String printRetransmissionAvgs() {
StringBuilder sb=new StringBuilder();
for(Map.Entry<Address,BoundedList<Long>> entry: xmit_times_history.entrySet()) {
Address sender=entry.getKey();
BoundedList<Long> list=entry.getValue();
long tmp=0;
int i=0;
for(Long val: list) {
tmp+=val;
i++;
}
double avg=i > 0? tmp / i: -1;
sb.append(sender).append(": ").append(avg).append("\n");
}
return sb.toString();
}
@ManagedOperation(description="TODO")
public String printSmoothedRetransmissionAvgs() {
StringBuilder sb=new StringBuilder();
for(Map.Entry<Address,Double> entry: smoothed_avg_xmit_times.entrySet()) {
sb.append(entry.getKey()).append(": ").append(entry.getValue()).append("\n");
}
return sb.toString();
}
@ManagedOperation(description="TODO")
public String printRetransmissionTimes() {
StringBuilder sb=new StringBuilder();
for(Map.Entry<Address,BoundedList<Long>> entry: xmit_times_history.entrySet()) {
Address sender=entry.getKey();
BoundedList<Long> list=entry.getValue();
sb.append(sender).append(": ").append(list).append("\n");
}
return sb.toString();
}
@ManagedAttribute
public double getTotalAverageRetransmissionTime() {
long total=0;
int i=0;
for(BoundedList<Long> list: xmit_times_history.values()) {
for(Long val: list) {
total+=val;
i++;
}
}
return i > 0? total / i: -1;
}
@ManagedAttribute
public double getTotalAverageSmoothedRetransmissionTime() {
double total=0.0;
int cnt=0;
synchronized(smoothed_avg_xmit_times) {
for(Double val: smoothed_avg_xmit_times.values()) {
if(val != null) {
total+=val;
cnt++;
}
}
}
return cnt > 0? total / cnt : -1;
}
/** Returns the smoothed average retransmission time for a given sender */
public double getSmoothedAverageRetransmissionTime(Address sender) {
synchronized(smoothed_avg_xmit_times) {
Double retval=smoothed_avg_xmit_times.get(sender);
if(retval == null) {
retval=INITIAL_SMOOTHED_AVG;
smoothed_avg_xmit_times.put(sender, retval);
}
return retval;
}
}
// public static final class LossRate {
// private final Set<Long> received=new HashSet<Long>();
// private final Set<Long> missing=new HashSet<Long>();
// private double smoothed_loss_rate=0.0;
// public synchronized void addReceived(long seqno) {
// received.add(seqno);
// missing.remove(seqno);
// setSmoothedLossRate();
// public synchronized void addReceived(Long ... seqnos) {
// for(int i=0; i < seqnos.length; i++) {
// Long seqno=seqnos[i];
// received.add(seqno);
// missing.remove(seqno);
// setSmoothedLossRate();
// public synchronized void addMissing(long from, long to) {
// for(long i=from; i <= to; i++) {
// if(!received.contains(i))
// missing.add(i);
// setSmoothedLossRate();
// public synchronized double computeLossRate() {
// int num_missing=missing.size();
// if(num_missing == 0)
// return 0.0;
// int num_received=received.size();
// int total=num_missing + num_received;
// return num_missing / (double)total;
// public synchronized double getSmoothedLossRate() {
// return smoothed_loss_rate;
// public synchronized String toString() {
// StringBuilder sb=new StringBuilder();
// int num_missing=missing.size();
// int num_received=received.size();
// int total=num_missing + num_received;
// sb.append("total=").append(total).append(" (received=").append(received.size()).append(", missing=")
// .append(missing.size()).append(", loss rate=").append(computeLossRate())
// .append(", smoothed loss rate=").append(smoothed_loss_rate).append(")");
// return sb.toString();
// /** Set the new smoothed_loss_rate value to 70% of the new value and 30% of the old value */
// private void setSmoothedLossRate() {
// double new_loss_rate=computeLossRate();
// if(smoothed_loss_rate == 0) {
// smoothed_loss_rate=new_loss_rate;
// else {
// smoothed_loss_rate=smoothed_loss_rate * .3 + new_loss_rate * .7;
private static class XmitTimeStat {
final AtomicInteger gaps_detected=new AtomicInteger(0);
final AtomicInteger xmit_reqs_sent=new AtomicInteger(0);
final AtomicInteger xmit_reqs_received=new AtomicInteger(0);
final AtomicInteger xmit_rsps_sent=new AtomicInteger(0);
final AtomicInteger xmit_rsps_received=new AtomicInteger(0);
final AtomicInteger missing_msgs_received=new AtomicInteger(0);
}
private class ActualInterval implements Interval {
private final Address sender;
public ActualInterval(Address sender) {
this.sender=sender;
}
public long next() {
return (long)getSmoothedAverageRetransmissionTime(sender);
}
public Interval copy() {
return this;
}
}
static class StatsEntry {
long xmit_reqs, xmit_rsps, missing_msgs_rcvd;
public String toString() {
StringBuilder sb=new StringBuilder();
sb.append(xmit_reqs).append(" xmit_reqs").append(", ").append(xmit_rsps).append(" xmit_rsps");
sb.append(", ").append(missing_msgs_rcvd).append(" missing msgs");
return sb.toString();
}
}
static class XmitRequest {
final Address original_sender; // original sender of message
final long low, high, timestamp=System.currentTimeMillis();
final Address xmit_dest; // destination to which XMIT_REQ is sent, usually the original sender
XmitRequest(Address original_sender, long low, long high, Address xmit_dest) {
this.original_sender=original_sender;
this.xmit_dest=xmit_dest;
this.low=low;
this.high=high;
}
public String toString() {
StringBuilder sb=new StringBuilder();
sb.append(new Date(timestamp)).append(": ").append(original_sender).append(" #[").append(low);
sb.append("-").append(high).append("]");
sb.append(" (XMIT_REQ sent to ").append(xmit_dest).append(")");
return sb.toString();
}
}
static class MissingMessage {
final Address original_sender;
final long seq, timestamp=System.currentTimeMillis();
MissingMessage(Address original_sender, long seqno) {
this.original_sender=original_sender;
this.seq=seqno;
}
public String toString() {
StringBuilder sb=new StringBuilder();
sb.append(new Date(timestamp)).append(": ").append(original_sender).append(" #").append(seq);
return sb.toString();
}
}
}
|
/* Open Source Software - may be modified and shared by FRC teams. The code */
/* the project. */
// FILE NAME: Kilroy.java (Team 339 - Kilroy)
// ABSTRACT:
// This file is where almost all code for Kilroy will be
// written. All of these functions are functions that should
// override methods in the base class (IterativeRobot). The
// functions are as follows:
// autonomousInit() - Initialization code for autonomous mode
// should go here. Will be called each time the robot enters
// autonomous mode.
// disabledInit() - Initialization code for disabled mode should
// go here. This function will be called one time when the
// robot first enters disabled mode.
// robotInit() - Robot-wide initialization code should go here.
// It will be called exactly 1 time.
// teleopInit() - Initialization code for teleop mode should go here.
// Will be called each time the robot enters teleop mode.
// autonomousPeriodic() - Periodic code for autonomous mode should
// go here. Will be called periodically at a regular rate while
// the robot is in autonomous mode.
// disabledPeriodic() - Periodic code for disabled mode should go here.
// Will be called periodically at a regular rate while the robot
// is in disabled mode.
// teleopPeriodic() - Periodic code for teleop mode should go here.
// Will be called periodically at a regular rate while the robot
// is in teleop mode.
// autonomousContinuous() - Continuous code for autonomous mode should
// go here. Will be called repeatedly as frequently as possible
// while the robot is in autonomous mode.
// disabledContinuous() - Continuous code for disabled mode should go
// here. Will be called repeatedly as frequently as possible while
// the robot is in disabled mode.
// teleopContinuous() - Continuous code for teleop mode should go here.
// Will be called repeatedly as frequently as possible while the
// robot is in teleop mode.
// Other functions not normally used
// startCompetition() - This function is a replacement for the WPI
// supplied 'main loop'. This should not normally be written or
// used.
// Team 339.
package org.usfirst.frc.team339.robot;
import org.usfirst.frc.team339.Hardware.Hardware;
import edu.wpi.first.wpilibj.DoubleSolenoid;
import edu.wpi.first.wpilibj.IterativeRobot;
import edu.wpi.first.wpilibj.MotorSafetyHelper;
import edu.wpi.first.wpilibj.Relay.Direction;
/**
* The VM is configured to automatically run this class, and to call the
* functions corresponding to each mode, as described in the IterativeRobot
* documentation. If you change the name of this class or the package after
* creating this project, you must also update the manifest file in the resource
* directory.
*/
public class Robot extends IterativeRobot
{
// private data for the class
// new watchdog object
MotorSafetyHelper watchdog;
@Override
public void autonomousInit ()
{
// start setup - tell the user we are beginning
// setup
System.out.println("Started AutonousInit().");
// Dims the brightness level so that we can take a better picture
// of the retroreflective tape.
// of the retroreflective tape.
Hardware.axisCamera.writeBrightness(5);
// Call the Autonomous class's Init function,
// which contains the user code.
Autonomous.init();
// done setup - tell the user we are complete
// setup
System.out.println("Completed AutonousInit().");
} // end autonomousInit
@Override
public void autonomousPeriodic ()
{
// Call the Autonomous class's Periodic function,
// which contains the user code.
Autonomous.periodic();
} // end autonomousPeriodic
@Override
public void disabledInit ()
{
// start setup - tell the user we are beginning
// setup
System.out.println("Started DisabledInit().");
// User code goes below here
Hardware.leftRearMotorSafety.setSafetyEnabled(false);
Hardware.rightRearMotorSafety.setSafetyEnabled(false);
Hardware.leftFrontMotorSafety.setSafetyEnabled(false);
Hardware.rightFrontMotorSafety.setSafetyEnabled(false);
// User code goes above here
// done setup - tell the user we are complete
// setup
System.out.println("Completed DisabledInit().");
} // end disabledInit
@Override
public void disabledPeriodic ()
{
// Watch dog code used to go here.
// User code goes below here
// User code goes above here
} // end disabledPeriodic
@Override
public void robotInit ()
{
// Watch dog code used to go here.
// User code goes below here
// Encoder Initialization
Hardware.leftRearEncoder.setDistancePerPulse(0.019706);
Hardware.leftRearEncoder.reset();
Hardware.rightRearEncoder.setDistancePerPulse(0.019706);
Hardware.rightRearEncoder.reset();
Hardware.transmission.initEncoders(Hardware.rightRearEncoder,
Hardware.leftRearEncoder);
Hardware.leftRearEncoder
.setDistancePerPulse(distancePerTickForMotorEncoders);
Hardware.leftRearEncoder.reset();
Hardware.rightRearEncoder
.setDistancePerPulse(distancePerTickForMotorEncoders);
Hardware.rightRearEncoder.reset();
Hardware.transmission.setMaxGear(2);
Hardware.transmission.initEncoders(Hardware.rightRearEncoder,
Hardware.leftRearEncoder);
// USB camera initialization
Hardware.transmission.initEncoders(Hardware.rightRearEncoder,
Hardware.leftRearEncoder);
// USB camera initialization
// Settings for the USB Camera
Hardware.cam0.setBrightness(50);
Hardware.cam0.setExposureAuto();
Hardware.cam0.setSize(160, 120);
Hardware.cam0.setFPS(20);
Hardware.cam0.setWhiteBalanceAuto();
Hardware.cam0.setWhiteBalanceHoldCurrent();
Hardware.cam0.updateSettings();
// Starts streaming video
Hardware.cameraServer.startAutomaticCapture(Hardware.cam0);
// Sets FPS and Resolution of camera
Hardware.axisCamera.writeMaxFPS(Hardware.AXIS_FPS);
Hardware.axisCamera.writeResolution(Hardware.AXIS_RESOLUTION);
Hardware.axisCamera
.writeBrightness(Hardware.NORMAL_AXIS_CAMERA_BRIGHTNESS);
// Hardware.axisCamera
// .writeWhiteBalance(AxisCamera.WhiteBalance.kHold);
// Tells the relay which way is on (kBackward is unable to be used)
Hardware.ringLightRelay.setDirection(Direction.kForward);
// motor initialization
Hardware.leftRearMotorSafety.setSafetyEnabled(true);
Hardware.rightRearMotorSafety.setSafetyEnabled(true);
Hardware.leftFrontMotorSafety.setSafetyEnabled(true);
Hardware.rightFrontMotorSafety.setSafetyEnabled(true);
Hardware.rightRearMotor.setInverted(true);
// Compressor Initialization
Hardware.compressor.setClosedLoopControl(true);
// Encoder Initialization
Hardware.leftRearEncoder.reset();
Hardware.leftRearEncoder
.setDistancePerPulse(distancePerTickForMotorEncoders);
Hardware.rightRearEncoder.reset();
Hardware.rightRearEncoder
.setDistancePerPulse(distancePerTickForMotorEncoders);
// Solenoid Initialization
// initializes the solenoids...duh duh duh...
Hardware.cameraSolenoid.set(DoubleSolenoid.Value.kForward);
Hardware.catapultSolenoid0.set(false);
Hardware.catapultSolenoid1.set(false);
Hardware.catapultSolenoid2.set(false);
Hardware.rightRearEncoder.setReverseDirection(true);
// User code goes above here
// done setup - tell the user we are complete
// setup
System.out.println(
"Kilroy XVII is started. All hardware items created.");
System.out.println();
System.out.println();
} // end robotInit
@Override
public void teleopInit ()
{
// start setup - tell the user we are beginning
// setup
System.out.println("Started teleopInit().");
// Call the Teleop class's Init function,
// which contains the user code.
Teleop.init();
// done setup - tell the user we are complete
// setup
System.out.println("Completed TeleopInit().");
} // end teleopInit
@Override
public void teleopPeriodic ()
{
// Watch dog code used to go here.
// Call the Teleop class's Periodic function,
// which contains the user code.
Teleop.periodic();
} // end teleopPeriodic
@Override
public void testInit ()
{
// User code goes below here
// User code goes above here
} // end testInit
@Override
public void testPeriodic ()
{
// User code goes below here
// User code goes above here
} // end testPeriodic
// TUNEABLES
private final double distancePerTickForMotorEncoders = 0.019706;
} // end class
|
package org.usfirst.frc.team997.robot;
import org.usfirst.frc.team997.robot.commands.AutoCheval;
import org.usfirst.frc.team997.robot.commands.AutoDriveBackwards;
import org.usfirst.frc.team997.robot.commands.AutoDriveForward;
import org.usfirst.frc.team997.robot.commands.DriveToSetpoint;
import org.usfirst.frc.team997.robot.commands.NullCommand;
import org.usfirst.frc.team997.robot.subsystems.DriveTrain;
import org.usfirst.frc.team997.robot.subsystems.Gatherer;
import org.usfirst.frc.team997.robot.subsystems.GathererArm;
//import org.usfirst.frc.team997.robot.subsystems.GathererArmNoSP;
import org.usfirst.frc.team997.robot.subsystems.Shooter;
import org.usfirst.frc.team997.robot.subsystems.ShooterPivot;
import edu.wpi.first.wpilibj.ADXRS450_Gyro;
import edu.wpi.first.wpilibj.CameraServer;
import edu.wpi.first.wpilibj.IterativeRobot;
import edu.wpi.first.wpilibj.PowerDistributionPanel;
import edu.wpi.first.wpilibj.Relay;
import edu.wpi.first.wpilibj.command.Command;
import edu.wpi.first.wpilibj.command.Scheduler;
import edu.wpi.first.wpilibj.livewindow.LiveWindow;
import edu.wpi.first.wpilibj.smartdashboard.SendableChooser;
import edu.wpi.first.wpilibj.smartdashboard.SmartDashboard;
/**
* The VM is configured to automatically run this class, and to call the
* functions corresponding to each mode, as described in the IterativeRobot
* documentation. If you change the name of this class or the package after
* creating this project, you must also update the manifest file in the resource
* directory.
*/
public class Robot extends IterativeRobot {
public static Relay clight;
private CameraServer camera;
public static final Shooter shooter = new Shooter(
RobotMap.shooterBallSensor, RobotMap.shooterMotorPort,
RobotMap.servoMotorFirstPort, RobotMap.servoMotorSecondPort);
public static final ShooterPivot shooterPivot = new ShooterPivot(
RobotMap.aimingMotorPort, RobotMap.shooterPivotAnglePort);
public static final DriveTrain driveTrain =
new DriveTrain(RobotMap.leftMotorPort, RobotMap.rightMotorPort,
RobotMap.leftEncoderFirstPort, RobotMap.leftEncoderSecondPort,
RobotMap.rightEncoderFirstPort, RobotMap.rightEncoderSecondPort);
public static final Gatherer gatherer = new Gatherer(RobotMap.rollerMotorPort);
public static final GathererArm gathererArm =
new GathererArm(RobotMap.gatherArmMotorPort, RobotMap.gathererArmAnglePort);
//public static final GathererArmNoSP gathererArm = new GathererArmNoSP(RobotMap.gatherArmMotorPort);
public static ADXRS450_Gyro gyro;
public static OI oi;
private Command autonomousCommand;
private SendableChooser chooser;
//public static Compressor compressor;
public static PowerDistributionPanel pdp;
public void robotInit() {
oi = new OI();
chooser = new SendableChooser();
chooser.addDefault("Forward", new AutoDriveForward());
chooser.addObject("Backward", new AutoDriveBackwards()); //use this for low bar
chooser.addObject("Cheval", new AutoCheval());
chooser.addObject("Nothing", new NullCommand());
SmartDashboard.putData("Auto mode", chooser);
gyro = new ADXRS450_Gyro();
gyro.calibrate();
pdp = new PowerDistributionPanel();
camera = CameraServer.getInstance();
camera.setQuality(42);
camera.startAutomaticCapture("cam1");
//clight = new Relay(RobotMap.circleLightPort);
// Need to reset the servo's position to be ready to capture a ball. Retracts kicker servos.
Robot.shooter.retractKicker();
autonomousCommand = new AutoCheval();
}
public void disabledInit() {
}
public void disabledPeriodic() {
Scheduler.getInstance().run();
}
public void autonomousInit() {
gyro.reset();
//autonomousCommand = (Command) chooser.getSelected();
// schedule the autonomous command (example)
// if (autonomousCommand != null) autonomousCommand.start();
getSelected().start();
}
// private Command getSelected() { return autonomousCommand; }
private Command getSelected() { return (Command) chooser.getSelected(); }
public void autonomousPeriodic() {
Scheduler.getInstance().run();
smartDashboard();
}
public void teleopInit() {
Robot.gathererArm.lockArmPosition();
}
public void teleopPeriodic() {
Scheduler.getInstance().run();
smartDashboard();
}
public void testPeriodic() {
LiveWindow.run();
}
public void smartDashboard(){
Robot.driveTrain.smartDashboard();
Robot.shooter.smartDashboard();
Robot.gathererArm.smartDashboard();
Robot.shooterPivot.smartDashboard();
//imu info put on the smartdashboard
SmartDashboard.putNumber("Gyro Angle", Robot.gyro.getAngle());
SmartDashboard.putNumber("Gyro Rate", Robot.gyro.getRate());
}
}
|
package cn.cerc.core;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
*
*
* @author
*/
public class TDate extends TDateTime {
private static final long serialVersionUID = 1L;
public TDate(Date date) {
this.setData(date);
}
public TDate(String date) {
TDateTime val = TDateTime.fromDate(date);
if (val == null) {
throw new RuntimeException(String.format("%s ", date));
}
this.setData(val.getData());
}
@Deprecated
public static TDate Today() {
return today();
}
public static TDate today() {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Date date = new Date();
String str = sdf.format(date);
try {
date = sdf.parse(str);
} catch (ParseException e) {
e.printStackTrace();
throw new RuntimeException("");
}
return new TDate(date);
}
public static void main(String[] args) {
TDate val;
val = new TDate(TDateTime.now().incMonth(-13).getData());
System.out.println(val.getShortValue());
val = TDate.Today();
System.out.println(val.getShortValue());
}
@Override
public String toString() {
return this.getDate();
}
public String getShortValue() {
String year = this.getYearMonth().substring(2, 4);
int month = this.getMonth();
int day = this.getDay();
if (TDateTime.now().compareYear(this) != 0) {
return String.format("%s%d", year, month);
} else {
return String.format("%d%d", month, day);
}
}
}
|
package org.jetel.graph;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.NoSuchElementException;
import java.util.TreeMap;
import java.util.concurrent.CyclicBarrier;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.log4j.MDC;
import org.jetel.data.DataRecord;
import org.jetel.enums.EnabledEnum;
import org.jetel.exception.ComponentNotReadyException;
import org.jetel.exception.ConfigurationProblem;
import org.jetel.exception.ConfigurationStatus;
import org.jetel.exception.ConfigurationStatus.Priority;
import org.jetel.exception.ConfigurationStatus.Severity;
import org.jetel.exception.TransformException;
import org.jetel.exception.XMLConfigurationException;
import org.jetel.graph.distribution.NodeAllocation;
import org.jetel.graph.runtime.CloverPost;
import org.jetel.graph.runtime.CloverWorkerListener;
import org.jetel.graph.runtime.ErrorMsgBody;
import org.jetel.graph.runtime.Message;
import org.jetel.metadata.DataRecordMetadata;
import org.jetel.util.string.StringUtils;
import org.w3c.dom.Element;
/**
* A class that represents atomic transformation task. It is a base class for
* all kinds of transformation components.
*
*@author D.Pavlis
*@created January 31, 2003
*@since April 2, 2002
*@see org.jetel.component
*@revision $Revision$
*/
public abstract class Node extends GraphElement implements Runnable, CloverWorkerListener {
private static final Log logger = LogFactory.getLog(Node.class);
protected Thread nodeThread;
/**
* List of all threads under this component.
* For instance parallel reader uses threads for parallel reading.
* It is component's responsibility to register all inner threads via addChildThread() method.
*/
protected List<Thread> childThreads;
protected EnabledEnum enabled;
protected int passThroughInputPort;
protected int passThroughOutputPort;
protected TreeMap<Integer, OutputPort> outPorts;
protected TreeMap<Integer, InputPort> inPorts;
protected volatile boolean runIt = true;
protected volatile Result runResult;
protected Throwable resultException;
protected String resultMessage;
protected Phase phase;
/**
* Distribution of this node processing at cluster environment.
*/
protected NodeAllocation allocation;
// buffered values
protected OutputPort[] outPortsArray;
protected int outPortsSize;
//synchronization barrier for all components in a phase
//all components have to finish pre-execution before execution method
private CyclicBarrier executeBarrier;
//synchronization barrier for all components in a phase
//watchdog needs to have all components with thread assignment before can continue to watch the phase
private CyclicBarrier preExecuteBarrier;
/**
* Various PORT kinds identifiers
*
*@since August 13, 2002
*/
public final static char OUTPUT_PORT = 'O';
/** Description of the Field */
public final static char INPUT_PORT = 'I';
/**
* XML attributes of every cloverETL component
*/
public final static String XML_NAME_ATTRIBUTE = "guiName";
public final static String XML_TYPE_ATTRIBUTE="type";
public final static String XML_ENABLED_ATTRIBUTE="enabled";
public final static String XML_ALLOCATION_ATTRIBUTE = "allocation";
/**
* Standard constructor.
*
*@param id Unique ID of the Node
*@since April 4, 2002
*/
public Node(String id){
this(id,null);
}
/**
* Standard constructor.
*
*@param id Unique ID of the Node
*@since April 4, 2002
*/
public Node(String id, TransformationGraph graph) {
super(id,graph);
outPorts = new TreeMap<Integer, OutputPort>();
inPorts = new TreeMap<Integer, InputPort>();
phase = null;
runResult=Result.N_A; // result is not known yet
childThreads = new ArrayList<Thread>();
allocation = NodeAllocation.createBasedOnNeighbours();
}
/**
* Sets the EOF for particular output port. EOF indicates that no more data
* will be sent throught the output port.
*
*@param portNum The new EOF value
* @throws IOException
* @throws IOException
*@since April 18, 2002
*/
public void setEOF(int portNum) throws InterruptedException, IOException {
try {
((OutputPort) outPorts.get(Integer.valueOf(portNum))).eof();
} catch (IndexOutOfBoundsException ex) {
ex.printStackTrace();
}
}
/**
* Returns the type of this Node (subclasses/Components should override
* this method to return appropriate type).
*
*@return The Type value
*@since April 4, 2002
*/
public abstract String getType();
/**
* Returns True if this Node is Leaf Node - i.e. only consumes data (has only
* input ports connected to it)
*
*@return True if Node is a Leaf
*@since April 4, 2002
*/
public boolean isLeaf() {
if (outPorts.size() == 0) {
return true;
} else {
return false;
}
}
/**
* Returns True if this Node is Phase Leaf Node - i.e. only consumes data within
* phase it belongs to (has only input ports connected or any connected output ports
* connects this Node with Node in different phase)
*
* @return True if this Node is Phase Leaf
*/
public boolean isPhaseLeaf() {
for (OutputPort outputPort : getOutPorts()) {
if (phase != outputPort.getReader().getPhase()) {
return true;
}
}
return false;
}
/**
* Returns True if this node is Root Node - i.e. it produces data (has only output ports
* connected to id).
*
*@return True if Node is a Root
*@since April 4, 2002
*/
public boolean isRoot() {
if (inPorts.size() == 0) {
return true;
} else {
return false;
}
}
/**
* Sets the processing phase of the Node object.<br>
* Default is 0 (ZERO).
*
*@param phase The new phase number
*/
public void setPhase(Phase phase) {
this.phase = phase;
}
/**
* Gets the processing phase of the Node object
*
*@return The phase value
*/
public Phase getPhase() {
return phase;
}
/**
* @return phase number
*/
public int getPhaseNum(){
return phase.getPhaseNum();
}
/**
* Gets the OutPorts attribute of the Node object
*
*@return Collection of OutPorts
*@since April 18, 2002
*/
public Collection<OutputPort> getOutPorts() {
return outPorts.values();
}
/**
* Gets the InPorts attribute of the Node object
*
*@return Collection of InPorts
*@since April 18, 2002
*/
public Collection<InputPort> getInPorts() {
return inPorts.values();
}
/**
* Gets the metadata on output ports of the Node object
*
*@return Collection of output ports metadata
*/
public List<DataRecordMetadata> getOutMetadata() {
List<DataRecordMetadata> ret = new ArrayList<DataRecordMetadata>(outPorts.size());
for(Iterator<OutputPort> it = getOutPorts().iterator(); it.hasNext();) {
ret.add(it.next().getMetadata());
}
return ret;
}
/**
* Gets the metadata on input ports of the Node object
*
*@return Collection of input ports metadata
*/
public List<DataRecordMetadata> getInMetadata() {
List<DataRecordMetadata> ret = new ArrayList<DataRecordMetadata>(inPorts.size());
for(Iterator<InputPort> it = getInPorts().iterator(); it.hasNext();) {
ret.add(it.next().getMetadata());
}
return ret;
}
/**
* Gets the number of records passed through specified port type and number
*
*@param portType Port type (IN, OUT, LOG)
*@param portNum port number (0...)
*@return The RecordCount value
*@since May 17, 2002
*@deprecated
*/
public int getRecordCount(char portType, int portNum) {
int count;
// Integer used as key to TreeMap containing ports
Integer port = Integer.valueOf(portNum);
try {
switch (portType) {
case OUTPUT_PORT:
count = ((OutputPort) outPorts.get(port)).getOutputRecordCounter();
break;
case INPUT_PORT:
count = ((InputPort) inPorts.get(port)).getInputRecordCounter();
break;
default:
count = -1;
}
} catch (Exception ex) {
count = -1;
}
return count;
}
/**
* Gets the result code of finished Node.<br>
*
*@return The Result value
*@since July 29, 2002
*@see org.jetel.graph.Node.Result
*/
public Result getResultCode() {
return runResult;
}
/**
* Sets the result code of component.
* @param result
*/
public void setResultCode(Result result) {
this.runResult = result;
}
/**
* Gets the ResultMsg of finished Node.<br>
* This message briefly describes what caused and error (if there was any).
*
*@return The ResultMsg value
*@since July 29, 2002
*/
public String getResultMsg() {
return runResult!=null ? runResult.message() : null;
}
/**
* Gets exception which caused Node to fail execution - if
* there was such failure.
*
* @return
* @since 13.12.2006
*/
public Throwable getResultException(){
return resultException;
}
// Operations
/* (non-Javadoc)
* @see org.jetel.graph.GraphElement#init()
*/
@Override
public void init() throws ComponentNotReadyException {
super.init();
runResult = Result.READY;
refreshBufferedValues();
}
/* (non-Javadoc)
* @see org.jetel.graph.GraphElement#preExecute()
*/
public void preExecute() throws ComponentNotReadyException {
super.preExecute();
runResult = Result.RUNNING;
}
/**
* main execution method of Node (calls in turn execute())
*
*@since April 2, 2002
*/
public void run() {
runResult = Result.RUNNING; // set running result, so we know run() method was started
//store the current thread like a node executor
setNodeThread(Thread.currentThread());
try {
//we need a synchronization point for all components in a phase
//watchdog starts all components in phase and wait on this barrier for real startup
preExecuteBarrier.await();
//preExecute() invocation
try {
preExecute();
} catch (ComponentNotReadyException e) {
throw new ComponentNotReadyException(this, "Component pre-execute initialization failed. " + e.getMessage(), e);
}
//waiting for other nodes in the current phase - first all pre-execution has to be done at all nodes
executeBarrier.await();
//execute() invocation
if((runResult = execute()) == Result.ERROR) {
Message<ErrorMsgBody> msg = Message.createErrorMessage(this,
new ErrorMsgBody(runResult.code(),
resultMessage != null ? resultMessage : runResult.message(), null));
getCloverPost().sendMessage(msg);
}
if (runResult == Result.FINISHED_OK) {
if (runIt = false) { //component returns ok tag, but the component was actually aborted
runResult = Result.ABORTED;
} else {
//check whether all input ports are already closed
for (InputPort inputPort : getInPorts()) {
if (!inputPort.isEOF()) {
runResult = Result.ERROR;
Message<ErrorMsgBody> msg = Message.createErrorMessage(this,
new ErrorMsgBody(runResult.code(), "Component has finished and input port " + inputPort.getInputPortNumber() + " still contains some unread records.", null));
getCloverPost().sendMessage(msg);
return;
}
}
}
//broadcast all output ports with EOF information
broadcastEOF();
}
} catch (InterruptedException ex) {
runResult=Result.ABORTED;
return;
} catch (IOException ex) { // may be handled differently later
runResult=Result.ERROR;
resultException = ex;
Message<ErrorMsgBody> msg = Message.createErrorMessage(this,
new ErrorMsgBody(runResult.code(), runResult.message(), ex));
getCloverPost().sendMessage(msg);
return;
} catch (TransformException ex){
runResult=Result.ERROR;
resultException = ex;
Message<ErrorMsgBody> msg = Message.createErrorMessage(this,
new ErrorMsgBody(runResult.code(), "Error occurred in nested transformation: " + runResult.message(), ex));
getCloverPost().sendMessage(msg);
return;
} catch (SQLException ex){
runResult=Result.ERROR;
resultException = ex;
Message<ErrorMsgBody> msg = Message.createErrorMessage(this,
new ErrorMsgBody(runResult.code(), runResult.message(), ex));
getCloverPost().sendMessage(msg);
return;
} catch (Exception ex) { // may be handled differently later
runResult=Result.ERROR;
resultException = ex;
Message<ErrorMsgBody> msg = Message.createErrorMessage(this,
new ErrorMsgBody(runResult.code(), runResult.message(), ex));
getCloverPost().sendMessage(msg);
return;
} catch (Throwable ex) {
logger.fatal(ex);
runResult=Result.ERROR;
resultException = ex;
Message<ErrorMsgBody> msg = Message.createErrorMessage(this,
new ErrorMsgBody(runResult.code(), runResult.message(), ex));
getCloverPost().sendMessage(msg);
return;
} finally {
sendFinishMessage();
setNodeThread(null);
}
}
public abstract Result execute() throws Exception;
/**
* This method should be called every time when node finishes its work.
*/
private void sendFinishMessage() {
//sends notification - node has finished
Message<Object> msg = Message.createNodeFinishedMessage(this);
if (getCloverPost() != null) //that condition should be removed - graph aborting is not well synchronized now
getCloverPost().sendMessage(msg);
}
/**
* Abort execution of Node - only inform node, that should finish processing.
*
*@since April 4, 2002
*/
public void abort() {
abort(null);
}
synchronized public void abort(Throwable cause ) {
int attempts = 30;
runIt = false;
while (runResult == Result.RUNNING && attempts
if (logger.isTraceEnabled())
logger.trace("try to interrupt thread "+getNodeThread());
getNodeThread().interrupt();
try {
Thread.sleep(10);
} catch (InterruptedException e) {
}
}
if (cause != null) {
runResult=Result.ERROR;
resultException = cause;
Message<ErrorMsgBody> msg = Message.createErrorMessage(this,
new ErrorMsgBody(runResult.code(), runResult.message(), cause));
getCloverPost().sendMessage(msg);
sendFinishMessage();
} else if (runResult == Result.RUNNING) {
logger.debug("Node '" + getId() + "' was not interrupted in legal way.");
runResult = Result.ABORTED;
sendFinishMessage();
}
}
/**
* @return thread of running node; <b>null</b> if node does not running
*/
public synchronized Thread getNodeThread() {
return nodeThread;
}
/**
* Sets actual thread in which this node current running.
* @param nodeThread
*/
private synchronized void setNodeThread(Thread nodeThread) {
if(nodeThread != null) {
this.nodeThread = nodeThread;
//thread context classloader is preset to a reasonable classloader
//this is just for sure, threads are recycled and no body can guarantee which context classloader remains preset
nodeThread.setContextClassLoader(this.getClass().getClassLoader());
String oldName = nodeThread.getName();
ContextProvider.registerNode(this);
long runId = getGraph().getRuntimeContext().getRunId();
nodeThread.setName(getId()+"_"+runId);
MDC.put("runId", getGraph().getRuntimeContext().getRunId());
if (logger.isTraceEnabled()) {
logger.trace("set thread name; old:"+oldName+" new:"+ nodeThread.getName());
logger.trace("set thread runId; runId:"+runId+" thread name:"+Thread.currentThread().getName());
}
} else {
ContextProvider.unregister();
MDC.remove("runId");
long runId = getGraph().getRuntimeContext().getRunId();
if (logger.isTraceEnabled())
logger.trace("reset thread runId; runId:"+runId+" thread name:"+Thread.currentThread().getName());
this.nodeThread.setName("<unnamed>");
this.nodeThread = null;
}
}
/**
* End execution of Node - let Node finish gracefully
*
*@since April 4, 2002
*/
public void end() {
runIt = false;
}
/**
* Provides CloverRuntime - object providing
* various run-time services
*
* @return
* @since 13.12.2006
*/
public CloverPost getCloverPost(){
return getGraph().getPost();
}
/**
* An operation that adds port to list of all InputPorts
*
*@param port Port (Input connection) to be added
*@since April 2, 2002
*@deprecated Use the other method which takes 2 arguments (portNum, port)
*/
public void addInputPort(InputPort port) {
Integer portNum;
int keyVal;
try {
portNum = (Integer) inPorts.lastKey();
keyVal = portNum.intValue() + 1;
} catch (NoSuchElementException ex) {
keyVal = 0;
}
inPorts.put(Integer.valueOf(keyVal), port);
port.connectReader(this, keyVal);
}
/**
* An operation that adds port to list of all InputPorts
*
*@param portNum Number to be associated with this port
*@param port Port (Input connection) to be added
*@since April 2, 2002
*/
public void addInputPort(int portNum, InputPort port) {
inPorts.put(Integer.valueOf(portNum), port);
port.connectReader(this, portNum);
}
/**
* An operation that adds port to list of all OutputPorts
*
*@param port Port (Output connection) to be added
*@since April 4, 2002
*@deprecated Use the other method which takes 2 arguments (portNum, port)
*/
public void addOutputPort(OutputPort port) {
Integer portNum;
int keyVal;
try {
portNum = (Integer) inPorts.lastKey();
keyVal = portNum.intValue() + 1;
} catch (NoSuchElementException ex) {
keyVal = 0;
}
outPorts.put(Integer.valueOf(keyVal), port);
port.connectWriter(this, keyVal);
resetBufferedValues();
}
/**
* An operation that adds port to list of all OutputPorts
*
*@param portNum Number to be associated with this port
*@param port The feature to be added to the OutputPort attribute
*@since April 4, 2002
*/
public void addOutputPort(int portNum, OutputPort port) {
outPorts.put(Integer.valueOf(portNum), port);
port.connectWriter(this, portNum);
resetBufferedValues();
}
/**
* Gets the port which has associated the num specified
*
*@param portNum number associated with the port
*@return The outputPort
*/
public OutputPort getOutputPort(int portNum) {
Object outPort=outPorts.get(Integer.valueOf(portNum));
if (outPort instanceof OutputPort) {
return (OutputPort)outPort ;
}else if (outPort==null) {
return null;
}
throw new RuntimeException("Port number \""+portNum+"\" does not implement OutputPort interface "+outPort.getClass().getName());
}
/**
* Gets the port which has associated the num specified
*
*@param portNum number associated with the port
*@return The outputPort
*/
public OutputPortDirect getOutputPortDirect(int portNum) {
Object outPort=outPorts.get(Integer.valueOf(portNum));
if (outPort instanceof OutputPortDirect) {
return (OutputPortDirect)outPort ;
}else if (outPort==null) {
return null;
}
throw new RuntimeException("Port number \""+portNum+"\" does not implement OutputPortDirect interface");
}
/**
* Gets the port which has associated the num specified
*
*@param portNum portNum number associated with the port
*@return The inputPort
*/
public InputPort getInputPort(int portNum) {
Object inPort=inPorts.get(Integer.valueOf(portNum));
if (inPort instanceof InputPort) {
return (InputPort)inPort ;
}else if (inPort==null){
return null;
}
throw new RuntimeException("Port number \""+portNum+"\" does not implement InputPort interface");
}
/**
* Gets the port which has associated the num specified
*
*@param portNum portNum number associated with the port
*@return The inputPort
*/
public InputPortDirect getInputPortDirect(int portNum) {
Object inPort=inPorts.get(Integer.valueOf(portNum));
if (inPort instanceof InputPortDirect) {
return (InputPortDirect)inPort ;
}else if (inPort==null){
return null;
}
throw new RuntimeException("Port number \""+portNum+"\" does not implement InputPortDirect interface");
}
/**
* Removes input port.
* @param inputPort
*/
public void removeInputPort(InputPort inputPort) {
inPorts.remove(Integer.valueOf(inputPort.getInputPortNumber()));
}
/**
* Removes output port.
* @param outputPort
*/
public void removeOutputPort(OutputPort outputPort) {
outPorts.remove(Integer.valueOf(outputPort.getOutputPortNumber()));
resetBufferedValues();
}
/**
* An operation that does removes/unregisteres por<br>
* Not yet implemented.
*
*@param _portNum Description of Parameter
*@param _portType Description of Parameter
*@since April 2, 2002
*/
public void deletePort(int _portNum, char _portType) {
throw new UnsupportedOperationException("Deleting port is not supported !");
}
/**
* An operation that writes one record through specified output port.<br>
* As this operation gets the Port object from TreeMap, don't use it in loops
* or when time is critical. Instead obtain the Port object directly and
* use it's writeRecord() method.
*
*@param _portNum Description of Parameter
*@param _record Description of Parameter
*@exception IOException Description of Exception
*@exception InterruptedException Description of Exception
*@since April 2, 2002
*/
public void writeRecord(int _portNum, DataRecord _record) throws IOException, InterruptedException {
((OutputPort) outPorts.get(Integer.valueOf(_portNum))).writeRecord(_record);
}
/**
* An operation that reads one record through specified input port.<br>
* As this operation gets the Port object from TreeMap, don't use it in loops
* or when time is critical. Instead obtain the Port object directly and
* use it's readRecord() method.
*
*@param _portNum Description of Parameter
*@param record Description of Parameter
*@return Description of the Returned Value
*@exception IOException Description of Exception
*@exception InterruptedException Description of Exception
*@since April 2, 2002
*/
public DataRecord readRecord(int _portNum, DataRecord record) throws IOException, InterruptedException {
return ((InputPort) inPorts.get(Integer.valueOf(_portNum))).readRecord(record);
}
/**
* An operation that does ...
*
*@param record Description of Parameter
*@exception IOException Description of Exception
*@exception InterruptedException Description of Exception
*@since April 2, 2002
*/
public void writeRecordBroadcast(DataRecord record) throws IOException, InterruptedException {
for(int i=0;i<outPortsSize;i++){
outPortsArray[i].writeRecord(record);
}
}
/**
* Description of the Method
*
*@param recordBuffer Description of Parameter
*@exception IOException Description of Exception
*@exception InterruptedException Description of Exception
*@since August 13, 2002
*/
public void writeRecordBroadcastDirect(ByteBuffer recordBuffer) throws IOException, InterruptedException {
for(int i=0;i<outPortsSize;i++){
((OutputPortDirect) outPortsArray[i]).writeRecordDirect(recordBuffer);
recordBuffer.rewind();
}
}
/**
* Closes all output ports - sends EOF signal to them.
* @throws IOException
*
*@since April 11, 2002
*/
public void closeAllOutputPorts() throws InterruptedException, IOException {
for (OutputPort outputPort : getOutPorts()) {
outputPort.eof();
}
}
/**
* Send EOF (no more data) to all connected output ports
* @throws IOException
*
*@since April 18, 2002
*/
public void broadcastEOF() throws InterruptedException, IOException{
closeAllOutputPorts();
}
/**
* Closes specified output port - sends EOF signal.
*
*@param portNum Which port to close
* @throws IOException
*@since April 11, 2002
*/
public void closeOutputPort(int portNum) throws InterruptedException, IOException {
OutputPort port = (OutputPort) outPorts.get(Integer.valueOf(portNum));
if (port == null) {
throw new RuntimeException(this.getId()+" - can't close output port \"" + portNum
+ "\" - does not exists!");
}
port.eof();
}
/**
* Compares this Node to specified Object
*
* @param obj
* Node to compare with
* @return True if obj represents node with the same ID
* @since April 18, 2002
*/
@Override
public boolean equals(Object obj) {
if (obj == null || !(obj instanceof Node)) {
return false;
}
final Node other = (Node) obj;
return getId().equals(other.getId());
}
@Override
public int hashCode(){
return getId().hashCode();
}
/**
* Description of the Method
*
*@return Description of the Returned Value
*@since May 21, 2002
*/
public void toXML(Element xmlElement) {
// set basic XML attributes of all graph components
xmlElement.setAttribute(XML_ID_ATTRIBUTE, getId());
xmlElement.setAttribute(XML_TYPE_ATTRIBUTE, getType());
}
/**
* Description of the Method
*
*@param nodeXML Description of Parameter
*@return Description of the Returned Value
*@since May 21, 2002
*/
public static Node fromXML(TransformationGraph graph, Element xmlElement)throws XMLConfigurationException {
throw new UnsupportedOperationException("not implemented in org.jetel.graph.Node");
}
/**
* @return <b>true</b> if node is enabled; <b>false</b> else
*/
public EnabledEnum getEnabled() {
return enabled;
}
/**
* @param enabled whether node is enabled
*/
public void setEnabled(String enabledStr) {
enabled = EnabledEnum.fromString(enabledStr, EnabledEnum.ENABLED);
}
/**
* @return index of "pass through" input port
*/
public int getPassThroughInputPort() {
return passThroughInputPort;
}
/**
* Sets "pass through" input port.
* @param passThroughInputPort
*/
public void setPassThroughInputPort(int passThroughInputPort) {
this.passThroughInputPort = passThroughInputPort;
}
/**
* @return index of "pass through" output port
*/
public int getPassThroughOutputPort() {
return passThroughOutputPort;
}
/**
* Sets "pass through" output port
* @param passThroughOutputPort
*/
public void setPassThroughOutputPort(int passThroughOutputPort) {
this.passThroughOutputPort = passThroughOutputPort;
}
/**
* @return node allocation in parallel processing (cluster environment)
*/
public NodeAllocation getAllocation() {
return allocation;
}
/**
* @param required node allocation in parallel processing (cluster environment)
*/
public void setAllocation(NodeAllocation alloc) {
this.allocation = alloc;
}
protected void resetBufferedValues(){
outPortsArray=null;
outPortsSize=0;
}
protected void refreshBufferedValues(){
Collection<OutputPort> op = getOutPorts();
outPortsArray = (OutputPort[]) op.toArray(new OutputPort[op.size()]);
outPortsSize = outPortsArray.length;
}
/**
* Checks number of input ports, whether is in the given interval.
* @param status
* @param min
* @param max
* @param checkNonAssignedPorts should be checked non-assigned ports (for example first port without edge and second port with edge)
* @return true if the number of input ports is in the given interval; else false
*/
protected boolean checkInputPorts(ConfigurationStatus status, int min, int max, boolean checkNonAssignedPorts) {
boolean retValue = true;
Collection<InputPort> inPorts = getInPorts();
if(inPorts.size() < min) {
status.add(new ConfigurationProblem("At least " + min + " input port must be defined!", Severity.ERROR, this, Priority.NORMAL));
retValue = false;
}
if(inPorts.size() > max) {
status.add(new ConfigurationProblem("At most " + max + " input ports can be defined!", Severity.ERROR, this, Priority.NORMAL));
retValue = false;
}
int index = 0;
for (InputPort inputPort : inPorts) {
if (inputPort.getMetadata() == null){ //TODO interface for matadata
status.add(new ConfigurationProblem("Metadata on input port " + inputPort.getInputPortNumber() +
" are not defined!", Severity.WARNING, this, Priority.NORMAL));
retValue = false;
}
if (checkNonAssignedPorts && inputPort.getInputPortNumber() != index){
status.add(new ConfigurationProblem("Input port " + index + " is not defined!", Severity.ERROR, this, Priority.NORMAL));
retValue = false;
}
index++;
}
return retValue;
}
protected boolean checkInputPorts(ConfigurationStatus status, int min, int max) {
return checkInputPorts(status, min, max, true);
}
/**
* Checks number of output ports, whether is in the given interval.
* @param status
* @param min
* @param max
* @param checkNonAssignedPorts should be checked non-assigned ports (for example first port without edge and second port with edge)
* @return true if the number of output ports is in the given interval; else false
*/
protected boolean checkOutputPorts(ConfigurationStatus status, int min, int max, boolean checkNonAssignedPorts) {
Collection<OutputPort> outPorts = getOutPorts();
if(outPorts.size() < min) {
status.add(new ConfigurationProblem("At least " + min + " output port must be defined!", Severity.ERROR, this, Priority.NORMAL));
return false;
}
if(outPorts.size() > max) {
status.add(new ConfigurationProblem("At most " + max + " output ports can be defined!", Severity.ERROR, this, Priority.NORMAL));
return false;
}
int index = 0;
for (OutputPort outputPort : outPorts) {
if (outputPort.getMetadata() == null){
status.add(new ConfigurationProblem("Metadata on output port " + outputPort.getOutputPortNumber() +
" are not defined!", Severity.WARNING, this, Priority.NORMAL));
return false;
}
if (checkNonAssignedPorts && outputPort.getOutputPortNumber() != index){
status.add(new ConfigurationProblem("Output port " + index + " is not defined!", Severity.ERROR, this, Priority.NORMAL));
return false;
}
index++;
}
return true;
}
protected boolean checkOutputPorts(ConfigurationStatus status, int min, int max) {
return checkOutputPorts(status, min, max, true);
}
/**
* Checks if metadatas in given list are all equal
*
* @param status
* @param metadata list of metadata to check
* @return
*/
protected ConfigurationStatus checkMetadata(ConfigurationStatus status, Collection<DataRecordMetadata> metadata){
return checkMetadata(status, metadata, (Collection<DataRecordMetadata>)null);
}
/**
* Checks if all metadata (in inMetadata list as well as in outMetadata list) are equal
*
* @param status
* @param inMetadata
* @param outMetadata
* @return
*/
protected ConfigurationStatus checkMetadata(ConfigurationStatus status, Collection<DataRecordMetadata> inMetadata,
Collection<DataRecordMetadata> outMetadata){
return checkMetadata(status, inMetadata, outMetadata, true);
}
/**
* Checks if all metadata (in inMetadata list as well as in outMetadata list) are equal
* If checkFixDelType is true then checks fixed/delimited state.
*
* @param status
* @param inMetadata
* @param outMetadata
* @param checkFixDelType
* @return
*/
protected ConfigurationStatus checkMetadata(ConfigurationStatus status, Collection<DataRecordMetadata> inMetadata,
Collection<DataRecordMetadata> outMetadata, boolean checkFixDelType){
Iterator<DataRecordMetadata> iterator = inMetadata.iterator();
DataRecordMetadata metadata = null, nextMetadata;
if (iterator.hasNext()) {
metadata = iterator.next();
}
//check input metadata
while (iterator.hasNext()) {
nextMetadata = iterator.next();
if (metadata == null || !metadata.equals(nextMetadata)) {
status.add(new ConfigurationProblem("Metadata " +
StringUtils.quote(metadata == null ? "null" : metadata.getName()) +
" does not equal to metadata " +
StringUtils.quote(nextMetadata == null ? "null" : nextMetadata.getName()),
metadata == null || nextMetadata == null ? Severity.WARNING : Severity.ERROR,
this, Priority.NORMAL));
}
metadata = nextMetadata;
}
if (outMetadata == null) {
return status;
}
//check if input metadata equals output metadata
iterator = outMetadata.iterator();
if (iterator.hasNext()) {
nextMetadata = iterator.next();
if (metadata == null || !metadata.equals(nextMetadata, checkFixDelType)) {
status.add(new ConfigurationProblem("Metadata " +
StringUtils.quote(metadata == null ? "null" : metadata.getName()) +
" does not equal to metadata " +
StringUtils.quote(nextMetadata == null ? "null" : nextMetadata.getName()),
metadata == null || nextMetadata == null ? Severity.WARNING : Severity.ERROR,
this, Priority.NORMAL));
}
metadata = nextMetadata;
}
//check output metadata
while (iterator.hasNext()) {
nextMetadata = iterator.next();
if (metadata == null || !metadata.equals(nextMetadata)) {
status.add(new ConfigurationProblem("Metadata " +
StringUtils.quote(metadata == null ? "null" : metadata.getName()) +
" does not equal to metadata " +
StringUtils.quote(nextMetadata == null ? "null" : nextMetadata.getName()),
metadata == null || nextMetadata == null ? Severity.WARNING : Severity.ERROR,
this, Priority.NORMAL));
}
metadata = nextMetadata;
}
return status;
}
protected ConfigurationStatus checkMetadata(ConfigurationStatus status, DataRecordMetadata inMetadata,
Collection<DataRecordMetadata> outMetadata){
Collection<DataRecordMetadata> inputMetadata = new ArrayList<DataRecordMetadata>(1);
inputMetadata.add(inMetadata);
return checkMetadata(status, inputMetadata, outMetadata);
}
protected ConfigurationStatus checkMetadata(ConfigurationStatus status, Collection<DataRecordMetadata> inMetadata,
DataRecordMetadata outMetadata){
Collection<DataRecordMetadata> outputMetadata = new ArrayList<DataRecordMetadata>(1);
outputMetadata.add(outMetadata);
return checkMetadata(status, inMetadata, outputMetadata);
}
protected ConfigurationStatus checkMetadata(ConfigurationStatus status, DataRecordMetadata inMetadata,
DataRecordMetadata outMetadata) {
Collection<DataRecordMetadata> inputMetadata = new ArrayList<DataRecordMetadata>(1);
inputMetadata.add(inMetadata);
Collection<DataRecordMetadata> outputMetadata = new ArrayList<DataRecordMetadata>(1);
outputMetadata.add(outMetadata);
return checkMetadata(status, inputMetadata, outputMetadata);
}
/**
* The given thread is registered as a child thread of this component.
* The child threads are exploited for grabing of tracking information - CPU usage of this component
* is sum of all threads.
* @param childThread
*/
public void registerChildThread(Thread childThread) {
childThreads.add(childThread);
}
/**
* The given threads are registered as child threads of this component.
* The child threads are exploited for grabing of tracking information - for instance
* CPU usage of this component is sum of all threads.
* @param childThreads
*/
protected void registerChildThreads(List<Thread> childThreads) {
childThreads.addAll(childThreads);
}
/**
* @return list of all child threads - threads running under this component
*/
public List<Thread> getChildThreads() {
return childThreads;
}
/* (non-Javadoc)
* @see org.jetel.graph.GraphElement#reset()
* @deprecated see {@link org.jetel.graph.IGraphElement#preExecute()} and {@link org.jetel.graph.IGraphElement#postExecute()} methods
*/
@Deprecated
synchronized public void reset() throws ComponentNotReadyException {
super.reset();
runIt = true;
runResult=Result.READY;
resultMessage = null;
resultException = null;
childThreads.clear();
}
@Override
public synchronized void free() {
super.free();
childThreads.clear();
}
/**
* This method is intended to be overridden.
* @return URLs which this component is using
*/
public String[] getUsedUrls() {
return new String[0];
}
public void setPreExecuteBarrier(CyclicBarrier preExecuteBarrier) {
this.preExecuteBarrier = preExecuteBarrier;
}
public void setExecuteBarrier(CyclicBarrier executeBarrier) {
this.executeBarrier = executeBarrier;
}
/**
* That is not nice solution to make public this variable. Unfortunately this is necessary
* for new ComponentAlgorithm interface. Whenever this class will be removed also this
* getter can be removed.
* @return current status of runIt variable
*/
public boolean runIt() {
return runIt;
}
@Override
public void workerFinished(Event e) {
// ignore by default
}
@Override
public void workerCrashed(Event e) {
//e.getException().printStackTrace();
resultException = e.getException();
abort(e.getException());
}
}
|
package com.github.sormuras.listing;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInput;
import java.io.ObjectInputStream;
import java.io.ObjectOutput;
import java.io.ObjectOutputStream;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Proxy;
import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import org.junit.jupiter.api.Assertions;
public interface Tests {
static void assertEquals(Class<?> testClass, String testName, Listable listable) {
assertEquals(testClass, testName, new Listing().add(listable));
}
static void assertEquals(Class<?> testClass, String testName, Listing listing) {
try {
Assertions.assertEquals(load(testClass, testName), listing.toString());
} catch (Exception e) {
Assertions.fail(e.toString());
}
}
static void assertSerializable(Listable listable) {
try {
String expected = listable.list();
Assertions.assertEquals(expected, listable.list());
byte[] bytes = convertToBytes(listable);
Object converted = convertFromBytes(bytes);
String actual = ((Listable) converted).list();
Assertions.assertEquals(expected, actual);
} catch (Exception e) {
Assertions.fail(e.toString());
}
}
static Object convertFromBytes(byte[] bytes) throws Exception {
try (ByteArrayInputStream bis = new ByteArrayInputStream(bytes);
ObjectInput in = new ObjectInputStream(bis)) {
return in.readObject();
}
}
static byte[] convertToBytes(Object object) throws Exception {
try (ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutput out = new ObjectOutputStream(bos)) {
out.writeObject(object);
return bos.toByteArray();
}
}
static String load(Class<?> testClass, String testName) {
String fileName = testClass.getName().replace('.', '/') + "." + testName + ".txt";
try {
Path path = Paths.get(testClass.getClassLoader().getResource(fileName).toURI());
return new String(Files.readAllBytes(path), StandardCharsets.UTF_8);
} catch (Exception e) {
throw new AssertionError("Loading `" + fileName + "` failed!", e);
}
}
static <T> T proxy(Class<T> type, InvocationHandler handler) {
ClassLoader loader = type.getClassLoader();
Class<?>[] interfaces = {type};
return type.cast(Proxy.newProxyInstance(loader, interfaces, handler));
}
/** Same as: <code>toString(bytes, 16, 16)</code>. */
static String toString(byte[] bytes) {
return toString(bytes, 16, 16);
}
/** Same as: <code>toString(ByteBuffer.wrap(bytes), bytesPerLine, maxLines)</code>. */
static String toString(byte[] bytes, int bytesPerLine, int maxLines) {
return toString(ByteBuffer.wrap(bytes), bytesPerLine, maxLines);
}
/** Same as: <code>toString(buffer, 16, 16)</code>. */
static String toString(ByteBuffer buffer) {
return toString(buffer, 16, 16);
}
static String toString(ByteBuffer buffer, int bytesPerLine, int maxLines) {
return toString(new StringBuilder(), buffer, bytesPerLine, maxLines);
}
static String toString(StringBuilder builder, ByteBuffer buffer) {
return toString(builder, buffer, 16, 16);
}
static String toString(StringBuilder builder, ByteBuffer buffer, int bytesPerLine, int maxLines) {
final boolean INCLUDE_SEGMENT_NUMBERS = true;
final boolean INCLUDE_VIEW_HEX = true;
final boolean INCLUDE_VIEW_ASCII = true;
final int BLOCK_LENGTH = 4;
final char BLOCK_SEPARATOR = ' ';
int i, j, n, k, line;
builder.append(buffer).append(" {\n");
line = 0;
for (n = 0; n < buffer.remaining(); n += bytesPerLine, line++) {
// builder.append(" ");
if (line >= maxLines) {
int omitted = buffer.remaining() - n;
builder.append("...(");
builder.append(omitted);
builder.append(" byte");
builder.append(omitted != 1 ? "s" : "");
builder.append(" omitted)\n");
break;
}
if (INCLUDE_SEGMENT_NUMBERS) {
String segment = Integer.toHexString(n).toUpperCase();
for (j = 0, k = 4 - segment.length(); j < k; j++) {
builder.append('0');
}
builder.append(segment).append(" | ");
}
if (INCLUDE_VIEW_HEX) {
for (i = n; i < n + bytesPerLine && i < buffer.remaining(); i++) {
String s = Integer.toHexString(buffer.get(i) & 255).toUpperCase();
if (s.length() == 1) {
builder.append('0');
}
builder.append(s).append(' ');
if (i % bytesPerLine % BLOCK_LENGTH == BLOCK_LENGTH - 1 && i < n + bytesPerLine - 1) {
builder.append(BLOCK_SEPARATOR);
}
}
while (i < n + bytesPerLine) {
builder.append(" ");
if (i % bytesPerLine % BLOCK_LENGTH == BLOCK_LENGTH - 1 && i < n + bytesPerLine - 1) {
builder.append(BLOCK_SEPARATOR);
}
i++;
}
builder.append('|').append(' ');
}
if (INCLUDE_VIEW_ASCII) {
for (i = n; i < n + bytesPerLine && i < buffer.remaining(); i++) {
int v = buffer.get(i) & 255;
if (v > 127 || Character.isISOControl((char) v)) {
builder.append('.');
} else {
builder.append((char) v);
}
if (i % bytesPerLine % BLOCK_LENGTH == BLOCK_LENGTH - 1 && i < n + bytesPerLine - 1) {
builder.append(BLOCK_SEPARATOR);
}
}
while (i < n + bytesPerLine) {
builder.append(' ');
if (i % bytesPerLine % BLOCK_LENGTH == BLOCK_LENGTH - 1 && i < n + bytesPerLine - 1) {
builder.append(BLOCK_SEPARATOR);
}
i++;
}
}
builder.append('\n');
}
builder.append("}");
return builder.toString();
}
}
|
package org.mini2Dx.ui.element;
import java.util.LinkedList;
import java.util.Queue;
import org.mini2Dx.core.graphics.TextureRegion;
import org.mini2Dx.core.serialization.annotation.ConstructorArg;
import org.mini2Dx.core.serialization.annotation.Field;
import org.mini2Dx.ui.render.ImageRenderNode;
import org.mini2Dx.ui.render.ParentRenderNode;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.assets.AssetManager;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.TextureAtlas;
import com.badlogic.gdx.graphics.g2d.TextureAtlas.AtlasRegion;
/**
* Wraps a {@link Texture} or {@link TextureRegion} as a {@link UiElement}
*/
public class Image extends UiElement {
private static final String LOGGING_TAG = Image.class.getSimpleName();
protected ImageRenderNode renderNode;
private TextureRegion textureRegion;
@Field
private String texturePath;
@Field(optional = true)
private String atlas;
@Field(optional = true)
private boolean responsive = false;
@Field(optional=true)
private boolean flipX = false;
@Field(optional=true)
private boolean flipY = false;
/**
* Constructor. Generates a unique ID for this {@link Image}
*/
public Image() {
super(null);
}
/**
* Constructor
*
* @param id
* The unique ID for this {@link Image}
*/
public Image(@ConstructorArg(clazz = String.class, name = "id") String id) {
super(id);
}
/**
* Constructor
*
* @param id
* The unique ID for this {@link Image}
* @param texturePath
* The path for the {@link Texture} to be loaded by the
* {@link AssetManager}
*/
public Image(String id, String texturePath) {
super(id);
setTexturePath(texturePath);
}
/**
* Constructor. Generates a unique ID for this {@link Image}
*
* @param texture
* The {@link Texture} to use
*/
public Image(Texture texture) {
this(null, texture);
}
/**
* Constructor. Generates a unique ID for this {@link Image}
*
* @param textureRegion
* The {@link TextureRegion} to use
*/
public Image(TextureRegion textureRegion) {
this(null, textureRegion);
}
/**
* Constructor
*
* @param id
* The unique ID for this {@link Image}
* @param texture
* The {@link Texture} to use
*/
public Image(String id, Texture texture) {
super(id);
this.textureRegion = new TextureRegion(texture);
}
/**
* Constructor
*
* @param id
* The unique ID for this {@link Image}
* @param textureRegion
* The {@link TextureRegion} to use
*/
public Image(String id, TextureRegion textureRegion) {
super(id);
this.textureRegion = textureRegion;
}
@Override
public void attach(ParentRenderNode<?, ?> parentRenderNode) {
if (renderNode != null) {
return;
}
renderNode = new ImageRenderNode(parentRenderNode, this);
parentRenderNode.addChild(renderNode);
}
@Override
public void detach(ParentRenderNode<?, ?> parentRenderNode) {
if (renderNode == null) {
return;
}
parentRenderNode.removeChild(renderNode);
renderNode = null;
}
/**
* Returns the current {@link TextureRegion} for this {@link Image}
*
* @param assetManager
* The game's {@link AssetManager}
* @return Null if no {@link TextureRegion} has been set
*/
public TextureRegion getTextureRegion(AssetManager assetManager) {
if (atlas != null) {
if (texturePath != null) {
TextureAtlas textureAtlas = assetManager.get(atlas, TextureAtlas.class);
if(textureAtlas == null) {
Gdx.app.error(LOGGING_TAG, "Could not find texture atlas " + atlas);
return null;
}
AtlasRegion atlasRegion = textureAtlas.findRegion(texturePath);
if(atlasRegion == null) {
Gdx.app.error(LOGGING_TAG, "Could not find " + texturePath + " in texture atlas " + atlas);
return null;
}
textureRegion = new TextureRegion();
texturePath = null;
}
} else if (texturePath != null) {
textureRegion = new TextureRegion(assetManager.get(texturePath, Texture.class));
texturePath = null;
}
return textureRegion;
}
/**
* Sets the current {@link TextureRegion} used by this {@link Image}
*
* @param textureRegion
* The {@link TextureRegion} to use
*/
public void setTextureRegion(TextureRegion textureRegion) {
this.textureRegion = textureRegion;
if (renderNode == null) {
return;
}
renderNode.setDirty(true);
}
/**
* Sets the current {@link Texture} used by this {@link Image}
*
* @param texture
* The {@link Texture} to use
*/
public void setTexture(Texture texture) {
if (texture == null) {
setTextureRegion(null);
} else {
setTextureRegion(new TextureRegion(texture));
}
}
/**
* Returns the current texture path
*
* @return Null if no path is used
*/
public String getTexturePath() {
return texturePath;
}
/**
* Sets the current texture path. This will set the current
* {@link TextureRegion} by loading it via the {@link AssetManager}
*
* @param texturePath
* The path to the texture
*/
public void setTexturePath(String texturePath) {
this.texturePath = texturePath;
if (renderNode == null) {
return;
}
renderNode.setDirty(true);
}
/**
* Returns the atlas (if any) to look up the texture in
* @return Null by default
*/
public String getAtlas() {
return atlas;
}
/**
* Sets the atlas to look up the texture in
* @param atlas Null if the texture should not be looked up via an atlas
*/
public void setAtlas(String atlas) {
this.atlas = atlas;
if (renderNode == null) {
return;
}
renderNode.setDirty(true);
}
/**
* Returns if this {@link Image} should scale to the size of its parent
*
* @return False by default
*/
public boolean isResponsive() {
return responsive;
}
/**
* Sets if this {@link Image} should scale to the size of its parent
* @param responsive
*/
public void setResponsive(boolean responsive) {
this.responsive = responsive;
if (renderNode == null) {
return;
}
renderNode.setDirty(true);
}
@Override
public void setVisibility(Visibility visibility) {
if (visibility == null) {
return;
}
if (this.visibility == visibility) {
return;
}
this.visibility = visibility;
if (renderNode == null) {
return;
}
renderNode.setDirty(true);
}
@Override
public void defer(Runnable runnable) {
deferredQueue.offer(runnable);
}
@Override
public void syncWithRenderNode() {
while (!effects.isEmpty()) {
renderNode.applyEffect(effects.poll());
}
while (!deferredQueue.isEmpty()) {
deferredQueue.poll().run();
}
}
@Override
public void setStyleId(String styleId) {
if (styleId == null) {
return;
}
if (this.styleId.equals(styleId)) {
return;
}
this.styleId = styleId;
if (renderNode == null) {
return;
}
renderNode.setDirty(true);
}
@Override
public void setZIndex(int zIndex) {
this.zIndex = zIndex;
if (renderNode == null) {
return;
}
renderNode.setDirty(true);
}
/**
* Returns if the texture should be flipped horizontally during rendering
* @return
*/
public boolean isFlipX() {
return flipX;
}
/**
* Sets if the texture should be flipped horizontally during rendering
* @param flipX True if the texture should be flipped
*/
public void setFlipX(boolean flipX) {
this.flipX = flipX;
}
/**
* Returns if the texture should be flipped vertically during rendering
* @return
*/
public boolean isFlipY() {
return flipY;
}
/**
* Sets if the texture should be flipped vertically during rendering
* @param flipY True if the texture should be flipped
*/
public void setFlipY(boolean flipY) {
this.flipY = flipY;
}
}
|
package org.yamcs;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.yamcs.api.EventProducer;
import org.yamcs.api.EventProducerFactory;
import org.yamcs.protobuf.Pvalue.MonitoringResult;
import org.yamcs.protobuf.Yamcs.NamedObjectId;
import org.yamcs.utils.StringConvertors;
import org.yamcs.xtce.AlarmReportType;
import org.yamcs.xtce.AlarmType;
import org.yamcs.xtce.Parameter;
import org.yamcs.xtce.ParameterType;
import org.yamcs.xtce.XtceDb;
import org.yamcs.xtceproc.XtceDbFactory;
import com.google.common.util.concurrent.AbstractService;
/**
* Generates realtime alarm events automatically, by subscribing to all relevant
* parameters.
* <p>
* <b>Must be declared after {@link YarchChannel}</b>
*/
public class AlarmReporter extends AbstractService implements ParameterConsumer {
private EventProducer eventProducer;
private Map<Parameter, ActiveAlarm> activeAlarms=new HashMap<Parameter, ActiveAlarm>();
// Last value of each param (for detecting changes in value)
private Map<Parameter, ParameterValue> lastValuePerParameter=new HashMap<Parameter, ParameterValue>();
final String yamcsInstance;
final String channelName;
public AlarmReporter(String yamcsInstance) {
this(yamcsInstance, "realtime");
}
public AlarmReporter(String yamcsInstance, String channelName) {
this.yamcsInstance = yamcsInstance;
this.channelName = channelName;
eventProducer=EventProducerFactory.getEventProducer(yamcsInstance);
eventProducer.setSource("AlarmChecker");
}
@Override
public void doStart() {
Channel channel = Channel.getInstance(yamcsInstance, channelName);
if(channel==null) {
ConfigurationException e = new ConfigurationException("Cannot find a channel '"+channelName+"' in instance '"+yamcsInstance+"'");
notifyFailed(e);
return;
}
ParameterRequestManager prm = channel.getParameterRequestManager();
prm.getAlarmChecker().enableReporting(this);
// Auto-subscribe to parameters with alarms
Set<Parameter> requiredParameters=new HashSet<Parameter>();
try {
XtceDb xtcedb=XtceDbFactory.getInstance(yamcsInstance);
for (Parameter parameter:xtcedb.getParameters()) {
ParameterType ptype=parameter.getParameterType();
if(ptype!=null && ptype.hasAlarm()) {
requiredParameters.add(parameter);
Set<Parameter> dependentParameters = ptype.getDependentParameters();
if(dependentParameters!=null) {
requiredParameters.addAll(dependentParameters);
}
}
}
} catch(ConfigurationException e) {
throw new RuntimeException(e);
}
if(!requiredParameters.isEmpty()) {
List<NamedObjectId> paramNames=new ArrayList<NamedObjectId>(); // Now that we have uniques..
for(Parameter p:requiredParameters) {
paramNames.add(NamedObjectId.newBuilder().setName(p.getQualifiedName()).build());
}
try {
prm.addRequest(paramNames, this);
} catch(InvalidIdentification e) {
throw new RuntimeException("Could not register dependencies for alarms", e);
}
}
notifyStarted();
}
@Override
public void doStop() {
notifyStopped();
}
@Override
public void updateItems(int subscriptionId, ArrayList<ParameterValueWithId> items) {
// Nothing. The real business of sending events, happens while checking the alarms
// because that's where we have easy access to the XTCE definition of the active
// alarm. The PRM is only used to signal the parameter subscriptions.
}
/**
* Sends an event if an alarm condition for the active context has been
* triggered <tt>minViolations</tt> times. This configuration does not
* affect events for parameters that go back to normal, or that change
* severity levels while the alarm is already active.
*/
public void reportNumericParameterEvent(ParameterValue pv, AlarmType alarmType, int minViolations) {
boolean sendUpdateEvent=false;
if(alarmType.getAlarmReportType()==AlarmReportType.ON_VALUE_CHANGE) {
ParameterValue oldPv=lastValuePerParameter.get(pv.def);
if(oldPv!=null && hasChanged(oldPv, pv)) {
sendUpdateEvent=true;
}
lastValuePerParameter.put(pv.def, pv);
}
if(pv.getMonitoringResult()==MonitoringResult.IN_LIMITS) {
if(activeAlarms.containsKey(pv.getParameter())) {
eventProducer.sendInfo("NORMAL", "Parameter "+pv.getParameter().getQualifiedName()+" is back to normal");
activeAlarms.remove(pv.getParameter());
}
} else { // out of limits
MonitoringResult previousMonitoringResult=null;
ActiveAlarm activeAlarm=activeAlarms.get(pv.getParameter());
if(activeAlarm==null || activeAlarm.alarmType!=alarmType) {
activeAlarm=new ActiveAlarm(alarmType, pv.getMonitoringResult());
} else {
previousMonitoringResult=activeAlarm.monitoringResult;
activeAlarm.monitoringResult=pv.getMonitoringResult();
activeAlarm.violations++;
}
if(activeAlarm.violations==minViolations || (activeAlarm.violations>minViolations && previousMonitoringResult!=activeAlarm.monitoringResult)) {
sendUpdateEvent=true;
}
activeAlarms.put(pv.getParameter(), activeAlarm);
}
if(sendUpdateEvent) {
sendValueChangeEvent(pv);
}
}
public void reportEnumeratedParameterEvent(ParameterValue pv, AlarmType alarmType, int minViolations) {
boolean sendUpdateEvent=false;
if(alarmType.getAlarmReportType()==AlarmReportType.ON_VALUE_CHANGE) {
ParameterValue oldPv=lastValuePerParameter.get(pv.def);
if(oldPv!=null && hasChanged(oldPv, pv)) {
sendUpdateEvent=true;
}
lastValuePerParameter.put(pv.def, pv);
}
if(pv.getMonitoringResult()==MonitoringResult.IN_LIMITS) {
if(activeAlarms.containsKey(pv.getParameter())) {
eventProducer.sendInfo("NORMAL", "Parameter "+pv.getParameter().getQualifiedName()+" is back to a normal state ("+pv.getEngValue().getStringValue()+")");
activeAlarms.remove(pv.getParameter());
}
} else { // out of limits
MonitoringResult previousMonitoringResult=null;
ActiveAlarm activeAlarm=activeAlarms.get(pv.getParameter());
if(activeAlarm==null || activeAlarm.alarmType!=alarmType) {
activeAlarm=new ActiveAlarm(alarmType, pv.getMonitoringResult());
} else {
previousMonitoringResult=activeAlarm.monitoringResult;
activeAlarm.monitoringResult=pv.getMonitoringResult();
activeAlarm.violations++;
}
if(activeAlarm.violations==minViolations || (activeAlarm.violations>minViolations&& previousMonitoringResult!=activeAlarm.monitoringResult)) {
sendUpdateEvent=true;
}
activeAlarms.put(pv.getParameter(), activeAlarm);
}
if(sendUpdateEvent) {
sendStateChangeEvent(pv);
}
}
private void sendValueChangeEvent(ParameterValue pv) {
switch(pv.getMonitoringResult()) {
case WATCH_LOW:
case WARNING_LOW:
eventProducer.sendWarning(pv.getMonitoringResult().toString(), "Parameter "+pv.getParameter().getQualifiedName()+" is too low");
break;
case WATCH_HIGH:
case WARNING_HIGH:
eventProducer.sendWarning(pv.getMonitoringResult().toString(), "Parameter "+pv.getParameter().getQualifiedName()+" is too high");
break;
case DISTRESS_LOW:
case CRITICAL_LOW:
case SEVERE_LOW:
eventProducer.sendError(pv.getMonitoringResult().toString(), "Parameter "+pv.getParameter().getQualifiedName()+" is too low");
break;
case DISTRESS_HIGH:
case CRITICAL_HIGH:
case SEVERE_HIGH:
eventProducer.sendError(pv.getMonitoringResult().toString(), "Parameter "+pv.getParameter().getQualifiedName()+" is too high");
break;
case IN_LIMITS:
eventProducer.sendInfo(pv.getMonitoringResult().toString(), "Parameter "+pv.getParameter().getQualifiedName()+" has changed to value "+StringConvertors.toString(pv.getEngValue(), false));
break;
default:
throw new IllegalStateException("Unexpected monitoring result: "+pv.getMonitoringResult());
}
}
private void sendStateChangeEvent(ParameterValue pv) {
switch(pv.getMonitoringResult()) {
case WATCH:
case WARNING:
eventProducer.sendWarning(pv.getMonitoringResult().toString(), "Parameter "+pv.getParameter().getQualifiedName()+" transitioned to state "+pv.getEngValue().getStringValue());
break;
case DISTRESS:
case CRITICAL:
case SEVERE:
eventProducer.sendError(pv.getMonitoringResult().toString(), "Parameter "+pv.getParameter().getQualifiedName()+" transitioned to state "+pv.getEngValue().getStringValue());
break;
case IN_LIMITS:
eventProducer.sendInfo(pv.getMonitoringResult().toString(), "Parameter "+pv.getParameter().getQualifiedName()+" transitioned to state "+pv.getEngValue().getStringValue());
break;
default:
throw new IllegalStateException("Unexpected monitoring result: "+pv.getMonitoringResult());
}
}
private boolean hasChanged(ParameterValue pvOld, ParameterValue pvNew) {
// Crude string value comparison.
return !StringConvertors.toString(pvOld.getEngValue(), false)
.equals(StringConvertors.toString(pvNew.getEngValue(), false));
}
private static class ActiveAlarm {
MonitoringResult monitoringResult;
AlarmType alarmType;
int violations=1;
ParameterValue lastValue;
ActiveAlarm(AlarmType alarmType, MonitoringResult monitoringResult) {
this.alarmType=alarmType;
this.monitoringResult=monitoringResult;
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.