answer
stringlengths 17
10.2M
|
|---|
package org.pocketcampus.core.plugin;
import java.io.IOException;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.nio.charset.Charset;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.pocketcampus.core.debug.Reporter;
import org.pocketcampus.core.exception.ServerException;
import org.pocketcampus.shared.utils.StringUtils;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
/**
* Server core. Singleton
* @author Jonas
* @author Florian
* @status working, incomplete
*/
public class Router extends HttpServlet {
/** Serialization crap */
private static final long serialVersionUID = 2912684020711306666L;
private Core core_;
/** Gson instance to serialize resulting objects */
private static Gson gson_;
/** Displays nice HTML pages */
private static Reporter reporter_;
@Override
public void init() throws ServletException {
super.init();
core_ = Core.getInstance();
reporter_ = new Reporter();
// .setPrettyPrinting()
gson_ = new GsonBuilder().setDateFormat("yyyy-MM-dd'T'HH:mm:ss Z").setPrettyPrinting().create();
String[] plugins = new String[] {
"org.pocketcampus.plugin.food.Food",
"org.pocketcampus.plugin.map.Map",
"org.pocketcampus.plugin.transport.Transport",
"org.pocketcampus.plugin.test.Test",
"org.pocketcampus.plugin.bikes.Bikes"
};
// XXX
for(String s : plugins) {
try {
initClass(s);
} catch (ServerException e) {
e.printStackTrace();
}
}
}
/**
* Handle the GET request
* Final because the children do not have to handle the request by themselves
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("Request: " + request.getRequestURL());
Enumeration<String> ps = request.getParameterNames();
while(ps.hasMoreElements()) {
String s = ps.nextElement();
System.out.println("Parameter: " + s + " -> " + request.getParameter(s));
}
// URL used to access the servlet
//String path = request.getPathInfo();
String path = request.getServletPath();
if(path != null && path.endsWith(".do")) {
path = path.substring(0, path.length() - 3);
}
// Request without any command
if(path == null || path.equals("/")) {
reporter_.statusReport(response, core_.getPluginList(), core_.getMethodList());
return;
}
// Get the object and the method connected to the command
try {
IPlugin obj = getObject(path);
Method m = getMethod(obj, path);
invoke(request, response, obj, m);
} catch (ServerException e) {
reporter_.errorReport(response, e);
}
}
/**
* Creates an instance of the plugin from its path.
* @param plugin path
* @return instance of the plugin
* @throws ServerException
*/
private IPlugin getObject(String path) throws ServerException {
String className = getClassNameFromPath(path);
if(className==null || className.equals("")) {
throw new ServerException("No method provided.");
}
IPlugin obj = initClass(className);
if(obj == null) {
throw new ServerException("Object initialization failed.");
}
return obj;
}
/**
* Extracts the class name of a class path.
* @param class path of a plugin
* @return class name
*/
private String getClassNameFromPath(String path) {
String split[] = path.split("/");
if(split.length > 1) {
return "org.pocketcampus.plugin." + split[1].toLowerCase() + "." + StringUtils.capitalize(split[1]);
}
return null;
}
/**
* Invokes the plugin.
* @param request
* @param response
* @param obj
* @param m
* @throws IOException
*/
private void invoke(HttpServletRequest request, HttpServletResponse response, IPlugin obj, Method m) throws IOException {
// Create the arguments to pass to the method
Object arglist[] = new Object[1];
//request.setCharacterEncoding("iso-8859-15");
request.setCharacterEncoding("UTF-8");
Charset charset = Charset.forName("UTF-8");
arglist[0] = request;
try {
// Sets the content type
final String encoding = "text/html; charset=UTF-8";
response.setContentType(encoding);
// Invokes the method
Object ret = m.invoke(obj, arglist);
String json = gson_.toJson(ret);
// Fixes the damn encoding
//json = charset.encode(json).toString();
// Puts the method content into the response
response.getWriter().println(json);
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvocationTargetException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**
* Get the name of the method that has to be invoked using the URL
* @param path path from the request
* @return the name of the request if exist, or the name of the default method
*/
private String getMethodNameFromPath(String path) {
String split[] = path.split("/");
if(split.length < 3 || split[2] == null) {
return null;
} else {
return split[2];
}
}
private Method getMethod(IPlugin obj, String path) throws ServerException {
String className = getClassNameFromPath(path);
String methodName = getMethodNameFromPath(path);
if(methodName == null || !core_.getMethodList().get(className).containsKey(methodName)) {
throw new ServerException("Method <b>"+ methodName +"</b> not found in package <b>"+ className +"</b>. Mispelled?");
}
Method m = core_.getMethodList().get(className).get(methodName);
return m;
}
private IPlugin initClass(String className) throws ServerException {
// Checks if the class already exists
IPlugin clazz = core_.getPluginList().get(className);
if(clazz != null) {
return clazz;
}
IPlugin obj = null;
try {
Class<?> c = Class.forName(className);
Constructor<?> ct = c.getConstructor();
// Check that the class implements the correct interface
Class<?>[] interfaces = c.getInterfaces();
boolean ok = false;
for(Class<?> i : interfaces) {
ok = ok || i.equals(IPlugin.class);
}
if(!ok) {
return null;
}
obj = (IPlugin) ct.newInstance(new Object[0]);
core_.getPluginList().put(className, obj);
// Get the methods from the class
Method methlist[] = c.getDeclaredMethods();
HashMap<String, Method> classMethods = new HashMap<String, Method>();
for(Method m : methlist) {
// Check if the programmer wants to put the method public
if(m.isAnnotationPresent(PublicMethod.class)) {
classMethods.put(m.getName(), m);
}
}
core_.getMethodList().put(className, classMethods);
} catch (ClassNotFoundException e) {
throw new ServerException("The class <b>" + className + "</b> was not found. Mispelled?");
} catch (IllegalArgumentException e) {
throw new ServerException("IllegalArgumentException : " + className);
} catch (InstantiationException e) {
throw new ServerException("InstantiationException : " + className);
} catch (IllegalAccessException e) {
throw new ServerException("IllegalAccessException : " + className);
} catch (InvocationTargetException e) {
throw new ServerException("InvocationTargetException : " + className);
} catch (SecurityException e) {
throw new ServerException("SecurityException : " + className);
} catch (NoSuchMethodException e) {
throw new ServerException("NoSuchMethodException : " + className);
}
return obj;
}
}
|
package com.kcthota.query;
import static com.kcthota.JSONQuery.expressions.Expr.appendTo;
import static com.kcthota.JSONQuery.expressions.Expr.prependTo;
import static com.kcthota.JSONQuery.expressions.Expr.eq;
import static com.kcthota.JSONQuery.expressions.Expr.val;
import static com.kcthota.JSONQuery.expressions.Expr.trim;
import static com.kcthota.JSONQuery.expressions.Expr.upper;
import static com.kcthota.JSONQuery.expressions.Expr.lower;
import static com.kcthota.JSONQuery.expressions.Expr.replace;
import static com.kcthota.JSONQuery.expressions.Expr.substring;
import static com.kcthota.JSONQuery.expressions.Expr.length;
import static com.kcthota.JSONQuery.expressions.Expr.indexof;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.fail;
import org.junit.Test;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.kcthota.JSONQuery.Query;
import com.kcthota.JSONQuery.exceptions.UnsupportedExprException;
import com.kcthota.JSONQuery.expressions.Expr;
/**
* @author Krishna Chaitanya Thota
* Apr 26, 2015 1:40:47 AM
*/
public class ValueTest {
@Test
public void testValue1(){
ObjectNode node = new ObjectMapper().createObjectNode();
node.putObject("name").put("firstName", "Krishna").put("lastName", "Thota");
node.put("city", "Santa Clara");
node.putArray("interests").add("hiking").add("biking");
Query q=new Query(node);
assertThat(q.value("city").textValue()).isEqualTo("Santa Clara");
assertThat(q.value("name/firstName").textValue()).isEqualTo("Krishna");
assertThat(q.value(val("name/lastName")).textValue()).isEqualTo("Thota");
assertThat(q.value(val("interests/0")).textValue()).isEqualTo("hiking");
assertThat(q.value("interests/1").textValue()).isEqualTo("biking");
assertThat(q.value(val(val("name"), "firstName")).textValue()).isEqualTo("Krishna");
}
@Test
public void testAppendTo(){
ObjectNode node = new ObjectMapper().createObjectNode();
node.putObject("name").put("firstName", "Krishna").put("lastName", "Thota");
node.put("age", 25);
node.put("city", "Santa Clara");
node.putArray("interests").add("hiking").add("biking");
Query q=new Query(node);
assertThat(q.value(appendTo("name/firstName", "1")).textValue()).isEqualTo("Krishna1");
assertThat(q.value(appendTo("city", ", CA")).textValue()).isEqualTo("Santa Clara, CA");
assertThat(q.value(appendTo(val("name/firstName"), null, " C" )).textValue()).isEqualTo("Krishna C");
assertThat(q.value(appendTo(val("name/firstName"), " C")).textValue()).isEqualTo("Krishna C");
assertThat(q.is(eq(appendTo("name/lastName", "1"), "Thota1"))).isTrue();
assertThat(q.value(appendTo("interests/0", " hills")).textValue()).isEqualTo("hiking hills");
try {
q.value(appendTo("age", "1"));
fail("UnsupportedExprException expected when appending to non-string values");
} catch(UnsupportedExprException e) {
assertThat(e.getMessage()).isEqualTo("Property value is not a string");
}
}
@Test
public void testPrependTo(){
ObjectNode node = new ObjectMapper().createObjectNode();
node.putObject("name").put("firstName", "Krishna").put("lastName", "Thota");
node.put("age", 25);
node.put("city", "Santa Clara");
node.putArray("interests").add("hiking").add("biking");
Query q=new Query(node);
assertThat(q.value(prependTo("name/firstName", "Mr. ")).textValue()).isEqualTo("Mr. Krishna");
assertThat(q.value(prependTo(val("name/firstName"), "Mr. ")).textValue()).isEqualTo("Mr. Krishna");
assertThat(q.is(eq(prependTo("name/lastName", "1"), "1Thota"))).isTrue();
assertThat(q.value(prependTo("interests/0", "hill ")).textValue()).isEqualTo("hill hiking");
try {
q.value(prependTo("age", "1"));
fail("UnsupportedExprException expected when appending to non-string values");
} catch(UnsupportedExprException e) {
assertThat(e.getMessage()).isEqualTo("Property value is not a string");
}
}
@Test
public void testTrim(){
ObjectNode node = new ObjectMapper().createObjectNode();
node.putObject("name").put("firstName", " Krishna ").put("lastName", " Thota ");
node.put("age", 25);
node.put("city", "Santa Clara, ");
node.putArray("interests").add(" hiking ").add(" biking ");
Query q=new Query(node);
assertThat(q.value(trim("name/firstName")).textValue()).isEqualTo("Krishna");
assertThat(q.is(eq(trim("name/lastName"), "Thota"))).isTrue();
assertThat(q.value(appendTo(trim("interests/0"), " hills")).textValue()).isEqualTo("hiking hills");
try {
q.value(trim("age"));
fail("UnsupportedExprException expected when appending to non-string values");
} catch(UnsupportedExprException e) {
assertThat(e.getMessage()).isEqualTo("Property value is not a string");
}
}
@Test
public void testUpper(){
ObjectNode node = new ObjectMapper().createObjectNode();
node.putObject("name").put("firstName", "Krishna").put("lastName", "Thota");
node.put("age", 25);
node.put("city", "Santa Clara,");
node.putArray("interests").add("hiking").add("biking");
Query q=new Query(node);
assertThat(q.value(upper("name/firstName")).textValue()).isEqualTo("KRISHNA");
assertThat(q.is(eq(upper("name/lastName"), "THOTA"))).isTrue();
assertThat(q.value(upper(appendTo("interests/0", " hills"))).textValue()).isEqualTo("HIKING HILLS");
try {
q.value(trim("age"));
fail("UnsupportedExprException expected when appending to non-string values");
} catch(UnsupportedExprException e) {
assertThat(e.getMessage()).isEqualTo("Property value is not a string");
}
}
@Test
public void testLower(){
ObjectNode node = new ObjectMapper().createObjectNode();
node.putObject("name").put("firstName", "Krishna").put("lastName", "Thota");
node.put("age", 25);
node.put("city", "Santa Clara,");
node.putArray("interests").add("HIKING").add("biking");
Query q=new Query(node);
assertThat(q.value(lower("name/firstName")).textValue()).isEqualTo("krishna");
assertThat(q.is(eq(lower("name/lastName"), "thota"))).isTrue();
assertThat(q.value(lower(appendTo("interests/0", " hills"))).textValue()).isEqualTo("hiking hills");
try {
q.value(trim("age"));
fail("UnsupportedExprException expected when appending to non-string values");
} catch(UnsupportedExprException e) {
assertThat(e.getMessage()).isEqualTo("Property value is not a string");
}
}
@Test
public void testReplace(){
ObjectNode node = new ObjectMapper().createObjectNode();
node.putObject("name").put("firstName", "Krishna").put("lastName", "Thota");
node.put("age", 25);
node.put("city", "Santa Clara");
node.putArray("interests").add("hiking").add("biking");
Query q=new Query(node);
assertThat(q.value(replace("name/firstName", "Krish", "Chris")).textValue()).isEqualTo("Chrisna");
assertThat(q.is(eq(replace("name/lastName", "Thota", "KC"), "KC"))).isTrue();
assertThat(q.is(eq(replace("city", " ", ""), "SantaClara"))).isTrue();
assertThat(q.value(lower(replace("interests/0", "hiking", "hike"))).textValue()).isEqualTo("hike");
assertThat(q.is(eq(replace("city", "something", "somethingelse"), "Santa Clara"))).isTrue();
try {
q.value(trim("age"));
fail("UnsupportedExprException expected when appending to non-string values");
} catch(UnsupportedExprException e) {
assertThat(e.getMessage()).isEqualTo("Property value is not a string");
}
}
@Test
public void testSubstring(){
ObjectNode node = new ObjectMapper().createObjectNode();
node.putObject("name").put("firstName", "Krishna").put("lastName", "Thota");
node.put("age", 25);
node.put("city", "Santa Clara");
node.putArray("interests").add("hiking").add("biking");
Query q=new Query(node);
assertThat(q.value(substring("name/firstName", 1)).textValue()).isEqualTo("rishna");
assertThat(q.is(eq(substring("name/lastName", 0, 2), "Th"))).isTrue();
assertThat(q.is(eq(substring("city", 6, 20), "Clara"))).isTrue();
assertThat(q.value(lower(substring("interests/0", 3))).textValue()).isEqualTo("ing");
try {
q.value(trim("age"));
fail("UnsupportedExprException expected when appending to non-string values");
} catch(UnsupportedExprException e) {
assertThat(e.getMessage()).isEqualTo("Property value is not a string");
}
}
@Test
public void testLengthExpression() {
ObjectNode node = new ObjectMapper().createObjectNode();
node.putObject("name").put("firstName", "Krishna").put("lastName", "Thota");
node.put("age", 25);
node.put("city", "Santa Clara");
node.putArray("interests").add("hiking").add("biking");
Query q = Query.q(node);
assertThat(q.value(length("city"))).isEqualTo(11);
assertThat(q.value(length(val("name"), "firstName"))).isEqualTo(7);
assertThat(q.value(length("interests"))).isEqualTo(2);
assertThat(q.value(length(null))).isEqualTo(4);
assertThat(q.value(length("age"))).isEqualTo(0);
}
@Test
public void testIndexofExpression() {
ObjectNode node = new ObjectMapper().createObjectNode();
node.putObject("name").put("firstName", "Krishna").put("lastName", "Thota");
node.put("age", 25);
node.put("city", "Santa Clara");
node.putArray("interests").add("hiking").add("biking");
Query q = Query.q(node);
assertThat(q.value(indexof("city", "San"))).isEqualTo(0);
assertThat(q.value(indexof("city", " "))).isEqualTo(5);
assertThat(q.value(indexof("city", null))).isEqualTo(-1); //string value is null
assertThat(q.value(indexof("name/firstName", "s"))).isEqualTo(3);
assertThat(q.value(indexof("interests/1","ing"))).isEqualTo(3);
assertThat(q.value(indexof("age", "25"))).isEqualTo(-1); //not a string value
assertThat(q.value(indexof("name", "Krishna"))).isEqualTo(-1); //not a string value
}
}
|
package integration;
import com.automation.remarks.junit5.VideoExtension;
import com.codeborne.selenide.Configuration;
import com.codeborne.selenide.Selenide;
import com.codeborne.selenide.junit5.ScreenShooterExtension;
import com.codeborne.selenide.junit5.TextReportExtension;
import integration.server.LocalHttpServer;
import org.assertj.core.api.WithAssertions;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.extension.ExtendWith;
import java.io.File;
import java.util.Locale;
import java.util.logging.Logger;
import static com.automation.remarks.video.enums.RecordingMode.ANNOTATED;
import static com.codeborne.selenide.Configuration.FileDownloadMode.HTTPGET;
import static com.codeborne.selenide.Configuration.FileDownloadMode.PROXY;
import static com.codeborne.selenide.Configuration.browser;
import static com.codeborne.selenide.Configuration.browserSize;
import static com.codeborne.selenide.Configuration.clickViaJs;
import static com.codeborne.selenide.Configuration.collectionsTimeout;
import static com.codeborne.selenide.Configuration.fastSetValue;
import static com.codeborne.selenide.Configuration.timeout;
import static com.codeborne.selenide.Configuration.versatileSetValue;
import static com.codeborne.selenide.Selenide.executeJavaScript;
import static com.codeborne.selenide.Selenide.open;
import static com.codeborne.selenide.WebDriverRunner.closeWebDriver;
import static com.codeborne.selenide.WebDriverRunner.isHeadless;
import static com.codeborne.selenide.WebDriverRunner.isIE;
import static com.codeborne.selenide.WebDriverRunner.isPhantomjs;
import static com.codeborne.selenide.WebDriverRunner.isSafari;
import static org.junit.jupiter.api.Assumptions.assumeFalse;
import static org.openqa.selenium.net.PortProber.findFreePort;
@ExtendWith({ScreenShooterExtension.class, TextReportExtension.class, VideoExtension.class})
public abstract class IntegrationTest implements WithAssertions {
private static final Logger log = Logger.getLogger(IntegrationTest.class.getName());
// http or https
private static final boolean SSL = false;
protected static LocalHttpServer server;
static long averageSeleniumCommandDuration = 100;
private static String protocol;
private static int port;
private long defaultTimeout;
private long defaultCollectionsTimeout;
@BeforeAll
static void setUpAll() throws Exception {
System.setProperty("java.util.logging.SimpleFormatter.format", "%1$tT %4$s %5$s%6$s%n"); // add %2$s for source
Locale.setDefault(Locale.ENGLISH);
runLocalHttpServer();
setUpVideoRecorder();
}
private static void runLocalHttpServer() throws Exception {
if (server == null) {
synchronized (IntegrationTest.class) {
port = findFreePort();
log.info("START " + browser + " TESTS");
server = new LocalHttpServer(port, SSL).start();
protocol = SSL ? "https:
}
}
}
private static void setUpVideoRecorder() {
File videoFolder = new File("build/reports/tests/" + Configuration.browser);
videoFolder.mkdirs();
System.setProperty("video.folder", videoFolder.getAbsolutePath());
System.setProperty("video.enabled", String.valueOf(!isHeadless()));
System.setProperty("video.mode", String.valueOf(ANNOTATED));
}
@AfterAll
public static void restartUnstableWebdriver() {
if (isIE() || isPhantomjs()) {
closeWebDriver();
}
}
@BeforeEach
void setUpEach() {
resetSettings();
restartReallyUnstableBrowsers();
rememberTimeout();
}
private void resetSettings() {
Configuration.baseUrl = protocol + "127.0.0.1:" + port;
Configuration.reportsFolder = "build/reports/tests/" + Configuration.browser;
fastSetValue = false;
versatileSetValue = false;
browserSize = "1200x960";
server.reset();
Configuration.proxyPort = 0;
Configuration.proxyHost = "";
toggleProxy(true);
}
private void restartReallyUnstableBrowsers() {
if (isSafari()) {
closeWebDriver();
}
}
private void rememberTimeout() {
defaultTimeout = timeout;
defaultCollectionsTimeout = collectionsTimeout;
}
protected void openFile(String fileName) {
open("/" + fileName + "?browser=" + Configuration.browser +
"&timeout=" + Configuration.timeout);
}
<T> T openFile(String fileName, Class<T> pageObjectClass) {
return open("/" + fileName + "?browser=" + Configuration.browser +
"&timeout=" + Configuration.timeout, pageObjectClass);
}
protected void toggleProxy(boolean proxyEnabled) {
if (proxyEnabled) {
assumeFalse(isPhantomjs()); // I don't know why, but PhantomJS seems to ignore proxy
}
if (Configuration.proxyEnabled != proxyEnabled) {
Selenide.close();
}
Configuration.proxyEnabled = proxyEnabled;
Configuration.fileDownload = proxyEnabled ? PROXY : HTTPGET;
}
protected void givenHtml(String... html) {
open("/empty.html");
executeJavaScript(
"document.querySelector('body').innerHTML = arguments[0];",
String.join(" ", html)
);
}
@AfterEach
public void restoreDefaultProperties() {
timeout = defaultTimeout;
collectionsTimeout = defaultCollectionsTimeout;
clickViaJs = false;
}
}
|
package mho.qbar;
import mho.haskellesque.iterables.ExhaustiveProvider;
import mho.haskellesque.iterables.IterableProvider;
import mho.haskellesque.iterables.RandomProvider;
import mho.haskellesque.math.BasicMath;
import mho.haskellesque.ordering.Ordering;
import mho.haskellesque.structures.Pair;
import mho.haskellesque.structures.Triple;
import org.jetbrains.annotations.NotNull;
import org.junit.Test;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.math.RoundingMode;
import java.util.Arrays;
import java.util.Random;
import static mho.haskellesque.iterables.IterableUtils.*;
import static mho.haskellesque.ordering.Ordering.*;
import static mho.qbar.Rational.*;
import static mho.qbar.Rational.of;
import static org.junit.Assert.*;
import static org.junit.Assert.assertEquals;
public class RationalProperties {
private static boolean USE_RANDOM = true;
private static final String NECESSARY_CHARS = "-/0123456789";
private static final int LIMIT = 10000;
private static IterableProvider P;
private static Iterable<Rational> T_RATIONALS;
private static void initialize() {
if (USE_RANDOM) {
RandomProvider randomProvider = new RandomProvider(new Random(7706916639046193098L));
P = randomProvider;
T_RATIONALS = randomRationals(randomProvider);
} else {
P = new ExhaustiveProvider();
T_RATIONALS = RATIONALS;
}
}
@Test
public void testAllProperties() {
for (boolean useRandom : Arrays.asList(false, true)) {
System.out.println("Testing " + (useRandom ? "randomly" : "exhaustively"));
USE_RANDOM = useRandom;
properties_Of_BigInteger_BigInteger();
propertiesOf_int_int();
propertiesOf_BigInteger();
propertiesOf_int();
propertiesOf_float();
propertiesOf_double();
propertiesOf_BigDecimal();
propertiesNegate();
propertiesInvert();
propertiesAbs();
propertiesSignum();
propertiesAdd();
propertiesSubtract();
propertiesMultiply_Rational_Rational();
propertiesMultiply_BigInteger();
propertiesMultiply_int();
propertiesDivide_Rational_Rational();
propertiesDivide_BigInteger();
propertiesDivide_int();
propertiesPow();
propertiesFloor();
propertiesCeiling();
propertiesFractionalPart();
propertiesRound();
// roundToDenominatorProperties();
// shiftLeftProperties();
// shiftRightProperties();
// binaryExponentProperties();
// toFloatProperties();
// toFloatRoundingModeProperties();
System.out.println();
}
System.out.println("Done");
}
public static void properties_Of_BigInteger_BigInteger() {
initialize();
System.out.println("testing of(BigInteger, BigInteger) properties...");
Iterable<Pair<BigInteger, BigInteger>> ps = filter(
p -> {
assert p.b != null;
return !p.b.equals(BigInteger.ZERO);
},
P.pairs(P.bigIntegers())
);
for (Pair<BigInteger, BigInteger> p : take(LIMIT, ps)) {
assert p.a != null;
assert p.b != null;
Rational r = of(p.a, p.b);
validate(r);
assertEquals(p.toString(), of(p.a).divide(p.b), r);
}
}
public static void propertiesOf_int_int() {
initialize();
System.out.println("testing of(int, int) properties...");
BigInteger minInt = BigInteger.valueOf(Integer.MIN_VALUE);
BigInteger maxInt = BigInteger.valueOf(Integer.MAX_VALUE);
Iterable<Pair<Integer, Integer>> ps = filter(p -> p.b != 0, P.pairs(P.integers()));
for (Pair<Integer, Integer> p : take(LIMIT, ps)) {
assert p.a != null;
assert p.b != null;
Rational r = of(p.a, p.b);
validate(r);
assertEquals(p.toString(), of(p.a).divide(p.b), r);
assertTrue(p.toString(), ge(r.getNumerator(), minInt));
assertTrue(p.toString(), le(r.getNumerator(), maxInt));
assertTrue(p.toString(), ge(r.getDenominator(), minInt));
assertTrue(p.toString(), le(r.getDenominator(), maxInt));
}
}
public static void propertiesOf_BigInteger() {
initialize();
System.out.println("testing of(BigInteger) properties...");
for (BigInteger i : take(LIMIT, P.bigIntegers())) {
Rational r = of(i);
validate(r);
assertEquals(i.toString(), r.getDenominator(), BigInteger.ONE);
}
}
public static void propertiesOf_int() {
initialize();
System.out.println("testing of(int) properties...");
BigInteger minInt = BigInteger.valueOf(Integer.MIN_VALUE);
BigInteger maxInt = BigInteger.valueOf(Integer.MAX_VALUE);
for (int i : take(LIMIT, P.integers())) {
Rational r = of(i);
validate(r);
assertEquals(Integer.toString(i), r.getDenominator(), BigInteger.ONE);
assertTrue(Integer.toString(i), ge(r.getNumerator(), minInt));
assertTrue(Integer.toString(i), le(r.getNumerator(), maxInt));
}
}
public static void propertiesOf_float() {
initialize();
System.out.println("testing of(float) properties...");
BigInteger denominatorLimit = BigInteger.ONE.shiftLeft(149);
BigInteger numeratorLimit = BigInteger.ONE.shiftLeft(128).subtract(BigInteger.ONE.shiftLeft(104));
Iterable<Float> fs = filter(f -> Float.isFinite(f) && !Float.isNaN(f), P.floats());
for (float f : take(LIMIT, fs)) {
Rational r = of(f);
assert r != null;
validate(r);
if (f != -0.0f) {
fae(Float.toString(f), f, r.toFloat());
}
assertTrue(Float.toString(f), BasicMath.isAPowerOfTwo(r.getDenominator()));
assertTrue(Float.toString(f), le(r.getDenominator(), denominatorLimit));
assertTrue(Float.toString(f), le(r.getNumerator(), numeratorLimit));
}
for (float f : take(LIMIT, P.ordinaryFloats())) {
Rational r = of(f);
assert r != null;
fae(Float.toString(f), f, r.toFloat());
}
}
public static void propertiesOf_double() {
initialize();
System.out.println("testing of(double) properties...");
BigInteger denominatorLimit = BigInteger.ONE.shiftLeft(1074);
BigInteger numeratorLimit = BigInteger.ONE.shiftLeft(1024).subtract(BigInteger.ONE.shiftLeft(971));
Iterable<Double> ds = filter(d -> Double.isFinite(d) && !Double.isNaN(d), P.doubles());
for (double d : take(LIMIT, ds)) {
Rational r = of(d);
assert r != null;
validate(r);
if (d != -0.0) {
dae(Double.toString(d), d, r.toDouble());
}
assertTrue(Double.toString(d), BasicMath.isAPowerOfTwo(r.getDenominator()));
assertTrue(Double.toString(d), le(r.getDenominator(), denominatorLimit));
assertTrue(Double.toString(d), le(r.getNumerator(), numeratorLimit));
}
for (double d : take(LIMIT, P.ordinaryDoubles())) {
Rational r = of(d);
assert r != null;
dae(Double.toString(d), d, r.toDouble());
}
}
public static void propertiesOf_BigDecimal() {
initialize();
System.out.println("testing of(BigDecimal) properties...");
for (BigDecimal bd : take(LIMIT, P.bigDecimals())) {
Rational r = of(bd);
validate(r);
assertEquals(bd.toString(), bd.stripTrailingZeros(), r.toBigDecimal().stripTrailingZeros());
assertTrue(bd.toString(), r.hasTerminatingDecimalExpansion());
}
}
public static void propertiesNegate() {
initialize();
System.out.println("testing negate() properties...");
for (Rational r : take(LIMIT, T_RATIONALS)) {
Rational negativeR = r.negate();
validate(negativeR);
assertEquals(r.toString(), r, negativeR.negate());
assertTrue(add(r, negativeR) == ZERO);
}
Iterable<Rational> rs = filter(r -> r != ZERO, T_RATIONALS);
for (Rational r : take(LIMIT, rs)) {
Rational negativeR = r.negate();
assertTrue(r.toString(), !r.equals(negativeR));
}
}
public static void propertiesInvert() {
initialize();
System.out.println("testing invert() properties...");
Iterable<Rational> rs = filter(r -> r != ZERO, T_RATIONALS);
for (Rational r : take(LIMIT, rs)) {
Rational inverseR = r.invert();
validate(inverseR);
assertEquals(r.toString(), r, inverseR.invert());
assertTrue(multiply(r, inverseR) == ONE);
assertTrue(inverseR != ZERO);
}
rs = filter(r -> r != ZERO && r.abs() != ONE, T_RATIONALS);
for (Rational r : take(LIMIT, rs)) {
Rational inverseR = r.invert();
assertTrue(r.toString(), !r.equals(inverseR));
}
}
public static void propertiesAbs() {
initialize();
System.out.println("testing abs() properties...");
for (Rational r : take(LIMIT, T_RATIONALS)) {
Rational absR = r.abs();
validate(absR);
assertEquals(r.toString(), absR, absR.abs());
assertTrue(r.toString(), ge(absR, ZERO));
}
}
public static void propertiesSignum() {
initialize();
System.out.println("testing signum() properties...");
for (Rational r : take(LIMIT, T_RATIONALS)) {
int signumR = r.signum();
assertEquals(r.toString(), signumR, Ordering.compare(r, ZERO).toInt());
assertTrue(r.toString(), signumR == -1 || signumR == 0 || signumR == 1);
}
}
public static void propertiesAdd() {
initialize();
System.out.println("testing add(Rational, Rational) properties...");
for (Pair<Rational, Rational> p : take(LIMIT, P.pairs(T_RATIONALS))) {
assert p.a != null;
assert p.b != null;
Rational sum = add(p.a, p.b);
validate(sum);
assertEquals(p.toString(), sum, add(p.b, p.a));
}
for (Rational r : take(LIMIT, T_RATIONALS)) {
assertEquals(r.toString(), add(ZERO, r), r);
assertEquals(r.toString(), add(r, ZERO), r);
assertTrue(r.toString(), add(r, r.negate()) == ZERO);
}
for (Triple<Rational, Rational, Rational> t : take(LIMIT, P.triples(T_RATIONALS))) {
assert t.a != null;
assert t.b != null;
assert t.c != null;
Rational sum1 = add(add(t.a, t.b), t.c);
Rational sum2 = add(t.a, add(t.b, t.c));
assertEquals(t.toString(), sum1, sum2);
}
}
public static void propertiesSubtract() {
initialize();
System.out.println("testing subtract(Rational, Rational) properties...");
for (Pair<Rational, Rational> p : take(LIMIT, P.pairs(T_RATIONALS))) {
assert p.a != null;
assert p.b != null;
Rational difference = subtract(p.a, p.b);
validate(difference);
assertEquals(p.toString(), difference, subtract(p.b, p.a).negate());
assertEquals(p.toString(), p.a, add(difference, p.b));
}
for (Rational r : take(LIMIT, T_RATIONALS)) {
assertEquals(r.toString(), subtract(ZERO, r), r.negate());
assertEquals(r.toString(), subtract(r, ZERO), r);
assertTrue(r.toString(), subtract(r, r) == ZERO);
}
}
public static void propertiesMultiply_Rational_Rational() {
initialize();
System.out.println("testing multiply(Rational, Rational) properties...");
for (Pair<Rational, Rational> p : take(LIMIT, P.pairs(T_RATIONALS))) {
assert p.a != null;
assert p.b != null;
Rational product = multiply(p.a, p.b);
validate(product);
assertEquals(p.toString(), product, multiply(p.b, p.a));
}
for (Rational r : take(LIMIT, T_RATIONALS)) {
assertEquals(r.toString(), multiply(ONE, r), r);
assertEquals(r.toString(), multiply(r, ONE), r);
assertTrue(r.toString(), multiply(ZERO, r) == ZERO);
assertTrue(r.toString(), multiply(r, ZERO) == ZERO);
}
Iterable<Rational> rs = filter(r -> r != ZERO, T_RATIONALS);
for (Rational r : take(LIMIT, rs)) {
assertTrue(r.toString(), multiply(r, r.invert()) == ONE);
}
for (Triple<Rational, Rational, Rational> t : take(LIMIT, P.triples(T_RATIONALS))) {
assert t.a != null;
assert t.b != null;
assert t.c != null;
Rational product1 = multiply(multiply(t.a, t.b), t.c);
Rational product2 = multiply(t.a, multiply(t.b, t.c));
assertEquals(t.toString(), product1, product2);
}
for (Triple<Rational, Rational, Rational> t : take(LIMIT, P.triples(T_RATIONALS))) {
assert t.a != null;
assert t.b != null;
assert t.c != null;
Rational expression1 = multiply(add(t.a, t.b), t.c);
Rational expression2 = add(multiply(t.a, t.c), multiply(t.b, t.c));
assertEquals(t.toString(), expression1, expression2);
}
}
public static void propertiesMultiply_BigInteger() {
initialize();
System.out.println("testing multiply(BigInteger) properties...");
Iterable<Pair<Rational, BigInteger>> ps = P.pairs(T_RATIONALS, P.bigIntegers());
for (Pair<Rational, BigInteger> p : take(LIMIT, ps)) {
assert p.a != null;
assert p.b != null;
Rational product = p.a.multiply(p.b);
validate(product);
assertEquals(p.toString(), product, multiply(p.a, of(p.b)));
assertEquals(p.toString(), product, multiply(of(p.b), p.a));
}
for (BigInteger i : take(LIMIT, P.bigIntegers())) {
assertEquals(i.toString(), ONE.multiply(i), of(i));
assertTrue(i.toString(), ZERO.multiply(i) == ZERO);
}
for (Rational r : take(LIMIT, T_RATIONALS)) {
assertEquals(r.toString(), r.multiply(BigInteger.ONE), r);
assertTrue(r.toString(), r.multiply(BigInteger.ZERO) == ZERO);
}
Iterable<BigInteger> bis = filter(i -> !i.equals(BigInteger.ZERO), P.bigIntegers());
for (BigInteger i : take(LIMIT, bis)) {
assertTrue(i.toString(), of(i).invert().multiply(i) == ONE);
}
Iterable<Rational> rs = T_RATIONALS;
for (Triple<Rational, Rational, BigInteger> t : take(LIMIT, P.triples(rs, rs, P.bigIntegers()))) {
assert t.a != null;
assert t.b != null;
assert t.c != null;
Rational expression1 = add(t.a, t.b).multiply(t.c);
Rational expression2 = add(t.a.multiply(t.c), t.b.multiply(t.c));
assertEquals(t.toString(), expression1, expression2);
}
}
public static void propertiesMultiply_int() {
initialize();
System.out.println("testing multiply(int) properties...");
for (Pair<Rational, Integer> p :take(LIMIT, P.pairs(T_RATIONALS, P.integers()))) {
assert p.a != null;
assert p.b != null;
Rational product = p.a.multiply(p.b);
validate(product);
assertEquals(p.toString(), product, multiply(p.a, of(p.b)));
assertEquals(p.toString(), product, multiply(of(p.b), p.a));
}
for (int i : take(LIMIT, P.integers())) {
assertEquals(Integer.toString(i), ONE.multiply(i), of(i));
assertTrue(Integer.toString(i), ZERO.multiply(i) == ZERO);
}
for (Rational r : take(LIMIT, T_RATIONALS)) {
assertEquals(r.toString(), r.multiply(1), r);
assertTrue(r.toString(), r.multiply(0) == ZERO);
}
Iterable<Integer> is = filter(i -> i != 0, P.integers());
for (int i : take(LIMIT, is)) {
assertTrue(Integer.toString(i), of(i).invert().multiply(i) == ONE);
}
Iterable<Rational> rs = T_RATIONALS;
for (Triple<Rational, Rational, Integer> t : take(LIMIT, P.triples(rs, rs, P.integers()))) {
assert t.a != null;
assert t.b != null;
assert t.c != null;
Rational expression1 = add(t.a, t.b).multiply(t.c);
Rational expression2 = add(t.a.multiply(t.c), t.b.multiply(t.c));
assertEquals(t.toString(), expression1, expression2);
}
}
public static void propertiesDivide_Rational_Rational() {
initialize();
System.out.println("testing divide(Rational, Rational) properties...");
Iterable<Pair<Rational, Rational>> ps = filter(p -> p.b != ZERO, P.pairs(T_RATIONALS));
for (Pair<Rational, Rational> p : take(LIMIT, ps)) {
assert p.a != null;
assert p.b != null;
Rational quotient = divide(p.a, p.b);
validate(quotient);
assertEquals(p.toString(), p.a, multiply(quotient, p.b));
}
ps = filter(p -> p.a != ZERO && p.b != ZERO, P.pairs(T_RATIONALS));
for (Pair<Rational, Rational> p : take(LIMIT, ps)) {
assert p.a != null;
assert p.b != null;
assertEquals(p.toString(), divide(p.a, p.b), divide(p.b, p.a).invert());
}
for (Rational r : take(LIMIT, T_RATIONALS)) {
assertEquals(r.toString(), divide(r, ONE), r);
}
Iterable<Rational> rs = filter(r -> r != ZERO, T_RATIONALS);
for (Rational r : take(LIMIT, rs)) {
assertEquals(r.toString(), divide(ONE, r), r.invert());
assertTrue(r.toString(), divide(r, r) == ONE);
}
}
public static void propertiesDivide_BigInteger() {
initialize();
System.out.println("testing divide(BigInteger) properties...");
Iterable<Pair<Rational, BigInteger>> ps = P.pairs(
T_RATIONALS,
filter(i -> !i.equals(BigInteger.ZERO), P.bigIntegers())
);
for (Pair<Rational, BigInteger> p : take(LIMIT, ps)) {
assert p.a != null;
assert p.b != null;
Rational quotient = p.a.divide(p.b);
validate(quotient);
assertEquals(p.toString(), p.a, quotient.multiply(p.b));
}
ps = P.pairs(
(Iterable<Rational>) filter(r -> r != ZERO, T_RATIONALS),
filter(i -> !i.equals(BigInteger.ZERO), P.bigIntegers())
);
for (Pair<Rational, BigInteger> p : take(LIMIT, ps)) {
assert p.a != null;
assert p.b != null;
assertEquals(p.toString(), p.a.divide(p.b), divide(of(p.b), p.a).invert());
}
Iterable<BigInteger> bis = filter(i -> !i.equals(BigInteger.ZERO), P.bigIntegers());
for (BigInteger i : take(LIMIT, bis)) {
assertEquals(i.toString(), ONE.divide(i), of(i).invert());
assertEquals(i.toString(), of(i).divide(i), ONE);
}
for (Rational r : take(LIMIT, RATIONALS)) {
assertEquals(r.toString(), r.divide(BigInteger.ONE), r);
}
}
public static void propertiesDivide_int() {
initialize();
System.out.println("testing divide(int) properties...");
Iterable<Pair<Rational, Integer>> ps = P.pairs(T_RATIONALS, filter(i -> i != 0, P.integers()));
for (Pair<Rational, Integer> p : take(LIMIT, ps)) {
assert p.a != null;
assert p.b != null;
Rational quotient = p.a.divide(p.b);
validate(quotient);
assertEquals(p.toString(), p.a, quotient.multiply(p.b));
}
ps = P.pairs((Iterable<Rational>) filter(r -> r != ZERO, T_RATIONALS), filter(i -> i != 0, P.integers()));
for (Pair<Rational, Integer> p : take(LIMIT, ps)) {
assert p.a != null;
assert p.b != null;
assertEquals(p.toString(), p.a.divide(p.b), divide(of(p.b), p.a).invert());
}
Iterable<Integer> is = filter(i -> i != 0, P.integers());
for (int i : take(LIMIT, is)) {
assertEquals(Integer.toString(i), ONE.divide(i), of(i).invert());
assertEquals(Integer.toString(i), of(i).divide(i), ONE);
}
for (Rational r : take(LIMIT, RATIONALS)) {
assertEquals(r.toString(), r.divide(1), r);
}
}
public static void propertiesPow() {
initialize();
System.out.println("testing pow(int) properties...");
Iterable<Integer> exps;
if (P instanceof ExhaustiveProvider) {
exps = P.integers();
} else {
exps = ((RandomProvider) P).integersGeometric(20);
}
Iterable<Pair<Rational, Integer>> ps = filter(p -> p.b >= 0 || p.a != ZERO, P.pairs(T_RATIONALS, exps));
for (Pair<Rational, Integer> p : take(LIMIT, ps)) {
assert p.a != null;
assert p.b != null;
Rational r = p.a.pow(p.b);
validate(r);
}
ps = P.pairs(filter(r -> r != ZERO, T_RATIONALS), exps);
for (Pair<Rational, Integer> p : take(LIMIT, ps)) {
assert p.a != null;
assert p.b != null;
Rational r = p.a.pow(p.b);
assertEquals(p.toString(), r, p.a.pow(-p.b).invert());
assertEquals(p.toString(), r, p.a.invert().pow(-p.b));
}
Iterable<Integer> pexps;
if (P instanceof ExhaustiveProvider) {
pexps = P.positiveIntegers();
} else {
pexps = ((RandomProvider) P).positiveIntegersGeometric(20);
}
for (int i : take(LIMIT, pexps)) {
assertTrue(Integer.toString(i), ZERO.pow(i) == ZERO);
}
for (Rational r : take(LIMIT, T_RATIONALS)) {
assertTrue(r.toString(), r.pow(0) == ONE);
assertEquals(r.toString(), r.pow(1), r);
assertEquals(r.toString(), r.pow(2), multiply(r, r));
}
Iterable<Rational> rs = filter(r -> r != ZERO, T_RATIONALS);
for (Rational r : take(LIMIT, rs)) {
assertEquals(r.toString(), r.pow(-1), r.invert());
}
Iterable<Triple<Rational, Integer, Integer>> ts1 = filter(
p -> p.b >= 0 && p.c >= 0 || p.a != ZERO,
P.triples(T_RATIONALS, exps, exps)
);
for (Triple<Rational, Integer, Integer> t : take(LIMIT, ts1)) {
assert t.a != null;
assert t.b != null;
assert t.c != null;
Rational expression1 = multiply(t.a.pow(t.b), t.a.pow(t.c));
Rational expression2 = t.a.pow(t.b + t.c);
assertEquals(t.toString(), expression1, expression2);
}
ts1 = filter(
t -> t.a != ZERO || t.c == 0 && t.b >= 0,
P.triples(T_RATIONALS, exps, exps)
);
for (Triple<Rational, Integer, Integer> t : take(LIMIT, ts1)) {
assert t.a != null;
assert t.b != null;
assert t.c != null;
Rational expression1 = divide(t.a.pow(t.b), t.a.pow(t.c));
Rational expression2 = t.a.pow(t.b - t.c);
assertEquals(t.toString(), expression1, expression2);
}
ts1 = filter(
t -> t.a != ZERO || t.b >= 0 && t.c >= 0,
P.triples(T_RATIONALS, exps, exps)
);
for (Triple<Rational, Integer, Integer> t : take(LIMIT, ts1)) {
assert t.a != null;
assert t.b != null;
assert t.c != null;
Rational expression5 = t.a.pow(t.b).pow(t.c);
Rational expression6 = t.a.pow(t.b * t.c);
assertEquals(t.toString(), expression5, expression6);
}
Iterable<Triple<Rational, Rational, Integer>> ts2 = filter(
t -> t.a != ZERO && t.b != ZERO || t.c >= 0,
P.triples(T_RATIONALS, T_RATIONALS, exps)
);
for (Triple<Rational, Rational, Integer> t : take(LIMIT, ts2)) {
assert t.a != null;
assert t.b != null;
assert t.c != null;
Rational expression1 = multiply(t.a, t.b).pow(t.c);
Rational expression2 = multiply(t.a.pow(t.c), t.b.pow(t.c));
assertEquals(t.toString(), expression1, expression2);
}
ts2 = filter(
t -> t.a != ZERO || t.c >= 0,
P.triples(T_RATIONALS, filter(r -> r != ZERO, T_RATIONALS), exps)
);
for (Triple<Rational, Rational, Integer> t : take(LIMIT, ts2)) {
assert t.a != null;
assert t.b != null;
assert t.c != null;
Rational expression1 = divide(t.a, t.b).pow(t.c);
Rational expression2 = divide(t.a.pow(t.c), t.b.pow(t.c));
assertEquals(t.toString(), expression1, expression2);
}
}
public static void propertiesFloor() {
initialize();
System.out.println("testing floor() properties...");
for (Rational r : take(LIMIT, T_RATIONALS)) {
BigInteger floor = r.floor();
assertTrue(r.toString(), le(of(floor), r));
assertTrue(r.toString(), le(subtract(r, of(floor)), ONE));
}
for (BigInteger i : take(LIMIT, P.bigIntegers())) {
assertEquals(i.toString(), of(i).floor(), i);
}
}
public static void propertiesCeiling() {
initialize();
System.out.println("testing ceiling() properties...");
for (Rational r : take(LIMIT, T_RATIONALS)) {
BigInteger ceiling = r.ceiling();
assertTrue(r.toString(), ge(of(ceiling), r));
assertTrue(r.toString(), le(subtract(of(ceiling), r), ONE));
}
for (BigInteger i : take(LIMIT, P.bigIntegers())) {
assertEquals(i.toString(), of(i).ceiling(), i);
}
}
public static void propertiesFractionalPart() {
initialize();
System.out.println("testing fractionalPart() properties...");
for (Rational r : take(LIMIT, T_RATIONALS)) {
Rational fractionalPart = r.fractionalPart();
validate(fractionalPart);
assertTrue(r.toString(), ge(fractionalPart, ZERO));
assertTrue(r.toString(), lt(fractionalPart, ONE));
assertEquals(r.toString(), add(of(r.floor()), fractionalPart), r);
}
for (BigInteger i : take(LIMIT, P.bigIntegers())) {
assertEquals(i.toString(), of(i).fractionalPart(), ZERO);
}
}
public static void propertiesRound() {
initialize();
System.out.println("testing round(RoundingMode) properties...");
Iterable<Pair<Rational, RoundingMode>> ps = filter(
p -> {
assert p.a != null;
return p.b != RoundingMode.UNNECESSARY || p.a.getDenominator().equals(BigInteger.ONE);
},
P.pairs(T_RATIONALS, P.roundingModes())
);
for (Pair<Rational, RoundingMode> p : take(LIMIT, ps)) {
assert p.a != null;
assert p.b != null;
BigInteger rounded = p.a.round(p.b);
assertTrue(p.toString(), rounded.equals(BigInteger.ZERO) || rounded.signum() == p.a.signum());
assertTrue(p.toString(), lt(subtract(p.a, of(rounded)).abs(), ONE));
}
for (BigInteger i : take(LIMIT, P.bigIntegers())) {
assertEquals(i.toString(), of(i).round(RoundingMode.UNNECESSARY), i);
}
for (Rational r : take(LIMIT, T_RATIONALS)) {
assertEquals(r.toString(), r.round(RoundingMode.FLOOR), r.floor());
assertEquals(r.toString(), r.round(RoundingMode.CEILING), r.ceiling());
assertTrue(r.toString(), le(of(r.round(RoundingMode.DOWN)).abs(), r.abs()));
assertTrue(r.toString(), ge(of(r.round(RoundingMode.UP)).abs(), r.abs()));
assertTrue(r.toString(), le(subtract(r, of(r.round(RoundingMode.HALF_DOWN))).abs(), of(1, 2)));
assertTrue(r.toString(), le(subtract(r, of(r.round(RoundingMode.HALF_UP))).abs(), of(1, 2)));
assertTrue(r.toString(), le(subtract(r, of(r.round(RoundingMode.HALF_EVEN))).abs(), of(1, 2)));
}
Iterable<Rational> rs = filter(r -> lt(r.abs().fractionalPart(), of(1, 2)), T_RATIONALS);
for (Rational r : take(LIMIT, rs)) {
assertEquals(r.toString(), r.round(RoundingMode.HALF_DOWN), r.round(RoundingMode.DOWN));
assertEquals(r.toString(), r.round(RoundingMode.HALF_UP), r.round(RoundingMode.DOWN));
assertEquals(r.toString(), r.round(RoundingMode.HALF_EVEN), r.round(RoundingMode.DOWN));
}
rs = filter(r -> gt(r.abs().fractionalPart(), of(1, 2)), T_RATIONALS);
for (Rational r : take(LIMIT, rs)) {
assertEquals(r.toString(), r.round(RoundingMode.HALF_DOWN), r.round(RoundingMode.UP));
assertEquals(r.toString(), r.round(RoundingMode.HALF_UP), r.round(RoundingMode.UP));
assertEquals(r.toString(), r.round(RoundingMode.HALF_EVEN), r.round(RoundingMode.UP));
}
//odd multiples of 1/2
rs = map(i -> of(i.shiftLeft(1).add(BigInteger.ONE), BigInteger.valueOf(2)), P.bigIntegers());
for (Rational r : take(LIMIT, rs)) {
assertEquals(r.toString(), r.round(RoundingMode.HALF_DOWN), r.round(RoundingMode.DOWN));
assertEquals(r.toString(), r.round(RoundingMode.HALF_UP), r.round(RoundingMode.UP));
assertFalse(r.toString(), r.round(RoundingMode.HALF_EVEN).testBit(0));
}
}
public static void propertiesRoundToDenominator() {
initialize();
System.out.println("testing roundToDenominator(BigInteger, RoundingMode) properties...");
Iterable<Triple<Rational, BigInteger, RoundingMode>> ts = filter(
p -> {
assert p.a != null;
assert p.b != null;
return p.c != RoundingMode.UNNECESSARY || p.b.mod(p.a.getDenominator()).equals(BigInteger.ZERO);
},
P.triples(T_RATIONALS, P.positiveBigIntegers(), P.roundingModes())
);
for (Triple<Rational, BigInteger, RoundingMode> t : take(LIMIT, ts)) {
assert t.a != null;
assert t.b != null;
assert t.c != null;
Rational rounded = t.a.roundToDenominator(t.b, t.c);
validate(rounded);
assertEquals(t.toString(), t.b.mod(rounded.getDenominator()), BigInteger.ZERO);
assertTrue(t.toString(), rounded == ZERO || rounded.signum() == t.a.signum());
assertTrue(t.toString(), lt(subtract(t.a, rounded).abs(), of(BigInteger.ONE, t.b)));
if (t.c == RoundingMode.HALF_DOWN || t.c == RoundingMode.HALF_UP || t.c == RoundingMode.HALF_EVEN) {
Rational fractionalPart = t.a.abs().multiply(t.b).fractionalPart();
if (fractionalPart.compareTo(of(1, 2)) < 0) {
assertEquals(t.toString(), rounded, t.a.roundToDenominator(t.b, RoundingMode.DOWN));
} else if (fractionalPart.compareTo(of(1, 2)) > 0) {
assertEquals(t.toString(), rounded, t.a.roundToDenominator(t.b, RoundingMode.UP));
} else {
if (t.c == RoundingMode.HALF_DOWN) {
assertEquals(t.toString(), rounded, t.a.roundToDenominator(t.b, RoundingMode.DOWN));
}
if (t.c == RoundingMode.HALF_UP) {
assertEquals(t.toString(), rounded, t.a.roundToDenominator(t.b, RoundingMode.UP));
}
if (t.c == RoundingMode.HALF_EVEN) {
assertEquals(t.toString(), rounded.multiply(t.b).getNumerator().testBit(0), false);
}
}
}
}
Iterable<Pair<Rational, RoundingMode>> ps1 = filter(
p -> {
assert p.a != null;
return p.b != RoundingMode.UNNECESSARY || p.a.getDenominator().equals(BigInteger.ONE);
},
P.pairs(T_RATIONALS, P.roundingModes())
);
for (Pair<Rational, RoundingMode> p : take(LIMIT, ps1)) {
assert p.a != null;
assert p.b != null;
Rational rounded = p.a.roundToDenominator(BigInteger.ONE, p.b);
assertEquals(p.toString(), rounded.getNumerator(), p.a.round(p.b));
assertEquals(p.toString(), rounded.getDenominator(), BigInteger.ONE);
}
Iterable<Pair<Rational, BigInteger>> ps2 = filter(
p -> {
assert p.a != null;
assert p.b != null;
return p.b.mod(p.a.getDenominator()).equals(BigInteger.ZERO);
},
P.pairs(T_RATIONALS, P.positiveBigIntegers())
);
for (Pair<Rational, BigInteger> p : take(LIMIT, ps2)) {
assert p.a != null;
assert p.b != null;
assertTrue(p.toString(), p.a.roundToDenominator(p.b, RoundingMode.UNNECESSARY).equals(p.a));
}
ps2 = P.pairs(T_RATIONALS, P.positiveBigIntegers());
for (Pair<Rational, BigInteger> p : take(LIMIT, ps2)) {
assert p.a != null;
assert p.b != null;
assertTrue(p.toString(), le(p.a.roundToDenominator(p.b, RoundingMode.FLOOR), p.a));
assertTrue(p.toString(), ge(p.a.roundToDenominator(p.b, RoundingMode.CEILING), p.a));
assertTrue(p.toString(), le(p.a.roundToDenominator(p.b, RoundingMode.DOWN).abs(), p.a.abs()));
assertTrue(p.toString(), ge(p.a.roundToDenominator(p.b, RoundingMode.UP).abs(), p.a.abs()));
assertTrue(
p.toString(),
le(
subtract(p.a, p.a.roundToDenominator(p.b, RoundingMode.HALF_DOWN)).abs(),
of(p.b).shiftLeft(1).invert()
)
);
assertTrue(
p.toString(),
le(
subtract(p.a, p.a.roundToDenominator(p.b, RoundingMode.HALF_UP)).abs(),
of(p.b).shiftLeft(1).invert()
)
);
assertTrue(
p.toString(),
le(
subtract(p.a, p.a.roundToDenominator(p.b, RoundingMode.HALF_EVEN)).abs(),
of(p.b).shiftLeft(1).invert()
)
);
}
ps2 = filter(
p -> {
assert p.a != null;
assert p.b != null;
return lt((Rational) p.a.abs().multiply(p.b).fractionalPart(), of(1, 2));
},
P.pairs(T_RATIONALS, P.positiveBigIntegers())
);
for (Pair<Rational, BigInteger> p : take(LIMIT, ps2)) {
assert p.a != null;
assert p.b != null;
assertEquals(
p.toString(),
p.a.roundToDenominator(p.b, RoundingMode.HALF_DOWN),
p.a.roundToDenominator(p.b, RoundingMode.DOWN)
);
assertEquals(
p.toString(),
p.a.roundToDenominator(p.b, RoundingMode.HALF_UP),
p.a.roundToDenominator(p.b, RoundingMode.DOWN)
);
assertEquals(
p.toString(),
p.a.roundToDenominator(p.b, RoundingMode.HALF_EVEN),
p.a.roundToDenominator(p.b, RoundingMode.DOWN)
);
}
ps2 = filter(
p -> {
assert p.a != null;
assert p.b != null;
return gt((Rational) p.a.abs().multiply(p.b).fractionalPart(), of(1, 2));
},
P.pairs(T_RATIONALS, P.positiveBigIntegers())
);
for (Pair<Rational, BigInteger> p : take(LIMIT, ps2)) {
assert p.a != null;
assert p.b != null;
assertEquals(
p.toString(),
p.a.roundToDenominator(p.b, RoundingMode.HALF_DOWN),
p.a.roundToDenominator(p.b, RoundingMode.UP)
);
assertEquals(
p.toString(),
p.a.roundToDenominator(p.b, RoundingMode.HALF_UP),
p.a.roundToDenominator(p.b, RoundingMode.UP)
);
assertEquals(
p.toString(),
p.a.roundToDenominator(p.b, RoundingMode.HALF_EVEN),
p.a.roundToDenominator(p.b, RoundingMode.UP)
);
}
// ps2 = filter(
}
// public static void shiftLeftProperties() {
// Iterable<Pair<Rational, Integer>> g = P.pairs(T_RATIONALS, P.integers());
// for (Pair<Rational, Integer> p : g.iterate(limit)) {
// Rational shifted = p.a.shiftLeft(p.b);
// validate(shifted);
// assertEquals(p.toString(), p.a.negate().shiftLeft(p.b), shifted.negate());
// assertEquals(p.toString(), shifted, p.a.shiftRight(-p.b));
// if (p.b >= 0) {
// assertEquals(p.toString(), shifted, p.a.multiply(BigInteger.ONE.shiftLeft(p.b)));
// public static void shiftRightProperties() {
// Iterable<Pair<Rational, Integer>> g = P.pairs(T_RATIONALS, P.integers());
// for (Pair<Rational, Integer> p : g.iterate(limit)) {
// Rational shifted = p.a.shiftRight(p.b);
// validate(shifted);
// assertEquals(p.toString(), p.a.negate().shiftRight(p.b), shifted.negate());
// assertEquals(p.toString(), shifted, p.a.shiftLeft(-p.b));
// if (p.b >= 0) {
// assertEquals(p.toString(), shifted, p.a.divide(BigInteger.ONE.shiftLeft(p.b)));
// public static void binaryExponentProperties() {
// for (Rational r : positiveRationals().iterate(limit)) {
// int exponent = r.binaryExponent();
// Rational power = ONE.shiftLeft(exponent);
// assertTrue(r.toString(), power.compareTo(r) <= 0);
// assertTrue(r.toString(), r.compareTo(power.shiftLeft(1)) < 0);
// public static void toFloatProperties() {
// for (Rational r : T_RATIONALS.iterate(limit)) {
// float f = r.toFloat();
// assertEquals(r.toString(), f, r.toFloat(RoundingMode.HALF_EVEN));
// public static void toFloatRoundingModeProperties() {
// Iterable<Pair<Rational, RoundingMode>> g = new FilteredIterable<Pair<Rational, RoundingMode>>(
// P.pairs(T_RATIONALS, Iterables.roundingModes()),
// p -> p.b != RoundingMode.UNNECESSARY
// || of(p.a.toFloat(RoundingMode.FLOOR)).equals(p.a));
// for (Pair<Rational, RoundingMode> p : g.iterate(limit)) {
// float rounded = p.a.toFloat(p.b);
// assertTrue(p.toString(), !Float.isNaN(rounded));
// assertTrue(p.toString(), rounded == 0.0 || Math.signum(rounded) == p.a.signum());
// float successor = MathUtils.successor(rounded);
// float predecessor = MathUtils.predecessor(rounded);
// float up = p.a.signum() == -1 ? predecessor : successor;
// float down = p.a.signum() == -1 ? successor : predecessor;
// if (p.b == RoundingMode.UNNECESSARY) {
// assertEquals(p.toString(), p.a, of(rounded));
// assertTrue(p.toString(), Float.isFinite(rounded));
// assertTrue(p.toString(), !new Float(rounded).equals(-0.0f));
// if (p.b == RoundingMode.FLOOR) {
// assertTrue(p.toString(), of(rounded).compareTo(p.a) <= 0);
// assertTrue(p.toString(), of(successor).compareTo(p.a) > 0);
// if (p.a.compareTo(ZERO) >= 0 && p.a.compareTo(SMALLEST_FLOAT) < 0) {
// assertEquals(p.toString(), rounded, 0.0f);
// if (p.a.compareTo(LARGEST_FLOAT.negate()) < 0) {
// assertTrue(p.toString(), rounded < 0 && Float.isInfinite(rounded));
// if (p.a.compareTo(LARGEST_FLOAT) >= 0) {
// assertEquals(p.toString(), rounded, Float.MAX_VALUE);
// assertTrue(p.toString(), rounded < 0 || Float.isFinite(rounded));
// assertTrue(p.toString(), !new Float(rounded).equals(-0.0f));
// if (p.b == RoundingMode.CEILING) {
// assertTrue(p.toString(), of(rounded).compareTo(p.a) >= 0);
// assertTrue(p.toString(), of(predecessor).compareTo(p.a) < 0);
// if (p.a == ZERO) {
// assertEquals(p.toString(), rounded, 0.0f);
// if (p.a.compareTo(ZERO) < 0 && p.a.compareTo(SMALLEST_FLOAT.negate()) > 0) {
// assertEquals(p.toString(), rounded, -0.0f);
// if (p.a.compareTo(LARGEST_FLOAT) > 0) {
// assertTrue(p.toString(), rounded > 0 && Float.isInfinite(rounded));
// if (p.a.compareTo(LARGEST_FLOAT.negate()) <= 0) {
// assertEquals(p.toString(), rounded, -Float.MAX_VALUE);
// assertTrue(p.toString(), rounded > 0 || Float.isFinite(rounded));
// if (p.b == RoundingMode.DOWN) {
// assertTrue(p.toString(), of(rounded).abs().compareTo(p.a.abs()) <= 0);
// assertTrue(p.toString(), of(up).abs().compareTo(p.a.abs()) > 0);
// if (p.a.compareTo(ZERO) >= 0 && p.a.compareTo(SMALLEST_FLOAT) < 0) {
// assertEquals(p.toString(), rounded, 0.0f);
// if (p.a.compareTo(ZERO) < 0 && p.a.compareTo(SMALLEST_FLOAT.negate()) > 0) {
// assertEquals(p.toString(), rounded, -0.0f);
// if (p.a.compareTo(LARGEST_FLOAT) >= 0) {
// assertEquals(p.toString(), rounded, Float.MAX_VALUE);
// if (p.a.compareTo(LARGEST_FLOAT.negate()) <= 0) {
// assertEquals(p.toString(), rounded, -Float.MAX_VALUE);
// assertTrue(p.toString(), Float.isFinite(rounded));
// if (p.b == RoundingMode.UP) {
// assertTrue(p.toString(), of(rounded).abs().compareTo(p.a.abs()) >= 0);
// if (p.a != ZERO) {
// assertTrue(p.toString(), of(down).abs().compareTo(p.a.abs()) < 0);
// if (p.a == ZERO) {
// assertEquals(p.toString(), rounded, 0.0f);
// if (p.a.compareTo(LARGEST_FLOAT) > 0) {
// assertTrue(p.toString(), rounded > 0 && Float.isInfinite(rounded));
// if (p.a.compareTo(LARGEST_FLOAT.negate()) < 0) {
// assertTrue(p.toString(), rounded < 0 && Float.isInfinite(rounded));
// assertTrue(p.toString(), !new Float(rounded).equals(-0.0f));
// if (p.b == RoundingMode.HALF_DOWN || p.b == RoundingMode.HALF_UP || p.b == RoundingMode.HALF_EVEN) {
// boolean equidistant = false;
// if (Float.isFinite(rounded) && rounded != Float.MAX_VALUE && rounded != -Float.MAX_VALUE) {
// Rational distance = subtract(of(rounded), p.a).abs();
// Rational predDistance = subtract(of(predecessor), p.a).abs();
// Rational succDistance = subtract(of(successor), p.a).abs();
// assertEquals(p.toString(), min(distance, predDistance, succDistance), distance);
// if (distance.equals(predDistance) || distance.equals(succDistance)) {
// equidistant = true;
// //TODO
// if (p.b == RoundingMode.HALF_DOWN) {
// if (equidistant) {
// assertEquals(p.toString(), rounded, p.a.toFloat(RoundingMode.DOWN));
// } else if (p.b == RoundingMode.HALF_UP) {
// if (equidistant) {
// assertEquals(p.toString(), rounded, p.a.toFloat(RoundingMode.UP));
private static void validate(@NotNull Rational r) {
assertEquals(r.toString(), r.getNumerator().gcd(r.getDenominator()), BigInteger.ONE);
assertEquals(r.toString(), r.getDenominator().signum(), 1);
if (r.equals(ZERO)) assertTrue(r.toString(), r == ZERO);
if (r.equals(ONE)) assertTrue(r.toString(), r == ONE);
}
private static void fae(String message, float f1, float f2) {
assertEquals(message, Float.toString(f1), Float.toString(f2));
}
private static void dae(String message, double d1, double d2) {
assertEquals(message, Double.toString(d1), Double.toString(d2));
}
}
|
package mil.nga.sf.wkb.test;
import java.io.IOException;
import java.nio.ByteOrder;
import junit.framework.TestCase;
import mil.nga.sf.CompoundCurve;
import mil.nga.sf.Curve;
import mil.nga.sf.Geometry;
import mil.nga.sf.GeometryCollection;
import mil.nga.sf.GeometryEnvelope;
import mil.nga.sf.GeometryType;
import mil.nga.sf.LineString;
import mil.nga.sf.MultiLineString;
import mil.nga.sf.MultiPoint;
import mil.nga.sf.MultiPolygon;
import mil.nga.sf.Point;
import mil.nga.sf.Polygon;
import mil.nga.sf.Surface;
import mil.nga.sf.extended.ExtendedGeometryCollection;
import mil.nga.sf.util.GeometryEnvelopeBuilder;
import mil.nga.sf.wkb.GeometryCodes;
import org.junit.Test;
/**
* Test Well Known Binary Geometries
*
* @author osbornb
*/
public class WKBTest {
/**
* Number of random geometries to create for each test
*/
private static final int GEOMETRIES_PER_TEST = 10;
/**
* Constructor
*/
public WKBTest() {
}
@Test
public void testPoint() throws IOException {
for (int i = 0; i < GEOMETRIES_PER_TEST; i++) {
// Create and test a point
Point point = WKBTestUtils.createPoint(WKBTestUtils.coinFlip(),
WKBTestUtils.coinFlip());
geometryTester(point);
}
}
@Test
public void testLineString() throws IOException {
for (int i = 0; i < GEOMETRIES_PER_TEST; i++) {
// Create and test a line string
LineString lineString = WKBTestUtils.createLineString(
WKBTestUtils.coinFlip(), WKBTestUtils.coinFlip());
geometryTester(lineString);
}
}
@Test
public void testPolygon() throws IOException {
for (int i = 0; i < GEOMETRIES_PER_TEST; i++) {
// Create and test a polygon
Polygon polygon = WKBTestUtils.createPolygon(
WKBTestUtils.coinFlip(), WKBTestUtils.coinFlip());
geometryTester(polygon);
}
}
@Test
public void testMultiPoint() throws IOException {
for (int i = 0; i < GEOMETRIES_PER_TEST; i++) {
// Create and test a multi point
MultiPoint multiPoint = WKBTestUtils.createMultiPoint(
WKBTestUtils.coinFlip(), WKBTestUtils.coinFlip());
geometryTester(multiPoint);
}
}
@Test
public void testMultiLineString() throws IOException {
for (int i = 0; i < GEOMETRIES_PER_TEST; i++) {
// Create and test a multi line string
MultiLineString multiLineString = WKBTestUtils
.createMultiLineString(WKBTestUtils.coinFlip(),
WKBTestUtils.coinFlip());
geometryTester(multiLineString);
}
}
@Test
public void testMultiCurveWithLineStrings() throws IOException {
// Test a pre-created WKB saved as the abstract MultiCurve type with
// LineStrings
byte[] bytes = new byte[] { 0, 0, 0, 0, 11, 0, 0, 0, 2, 0, 0, 0, 0, 2,
0, 0, 0, 3, 64, 50, -29, -55, -6, 126, -15, 120, -64, 65, -124,
-86, -46, -62, -60, 94, -64, 66, -31, -40, 124, -2, -47, -5,
-64, 82, -13, -22, 8, -38, 6, 111, 64, 81, 58, 88, 78, -15, 82,
111, -64, 86, 20, -18, -37, 3, -99, -86, 0, 0, 0, 0, 2, 0, 0,
0, 10, 64, 98, 48, -84, 37, -62, 34, 98, -64, 68, -12, -81,
104, 13, -109, 6, -64, 101, -82, 76, -68, 34, 117, -110, 64,
39, -125, 83, 1, 50, 86, 8, -64, 83, 127, -93, 42, -89, 54,
-56, -64, 67, -58, -13, -104, 1, -17, -10, 64, 97, 18, -82,
-112, 100, -128, 16, 64, 68, -13, -86, -112, 112, 59, -3, 64,
67, -4, -71, -91, -16, -15, 85, -64, 49, 110, -16, 94, -71, 24,
-13, -64, 94, 84, 94, -4, -78, -101, -75, -64, 80, 74, -39, 90,
38, 107, 104, 64, 72, -16, -43, 82, -112, -39, 77, 64, 28, 30,
97, -26, 64, 102, -110, 64, 92, 63, -14, -103, 99, -67, 63,
-64, 65, -48, 84, -37, -111, -55, -25, -64, 101, -10, -62,
-115, 104, -125, 28, -64, 66, 5, 108, -56, -59, 69, -36, -64,
83, 33, -36, -86, 106, -84, -16, 64, 70, 30, -104, -50, -57,
15, -7 };
TestCase.assertEquals(GeometryCodes.getCode(GeometryType.MULTICURVE),
bytes[4]);
Geometry geometry = WKBTestUtils.readGeometry(bytes);
TestCase.assertTrue(geometry instanceof GeometryCollection);
TestCase.assertEquals(geometry.getGeometryType(),
GeometryType.GEOMETRYCOLLECTION);
@SuppressWarnings("unchecked")
GeometryCollection<Curve> multiCurve = (GeometryCollection<Curve>) geometry;
TestCase.assertEquals(2, multiCurve.numGeometries());
Geometry geometry1 = multiCurve.getGeometries().get(0);
Geometry geometry2 = multiCurve.getGeometries().get(1);
TestCase.assertTrue(geometry1 instanceof LineString);
TestCase.assertTrue(geometry2 instanceof LineString);
LineString lineString1 = (LineString) geometry1;
LineString lineString2 = (LineString) geometry2;
TestCase.assertEquals(3, lineString1.numPoints());
TestCase.assertEquals(10, lineString2.numPoints());
Point point1 = lineString1.startPoint();
Point point2 = lineString2.endPoint();
TestCase.assertEquals(18.889800697319032, point1.getX());
TestCase.assertEquals(-35.036463112927535, point1.getY());
TestCase.assertEquals(-76.52909336488278, point2.getX());
TestCase.assertEquals(44.2390383216843, point2.getY());
ExtendedGeometryCollection<Curve> extendedMultiCurve = new ExtendedGeometryCollection<>(
multiCurve);
TestCase.assertEquals(GeometryType.MULTICURVE,
extendedMultiCurve.getGeometryType());
geometryTester(extendedMultiCurve, multiCurve);
byte[] bytes2 = WKBTestUtils.writeBytes(extendedMultiCurve);
TestCase.assertEquals(GeometryCodes.getCode(GeometryType.MULTICURVE),
bytes2[4]);
WKBTestUtils.compareByteArrays(bytes, bytes2);
}
@Test
public void testMultiCurveWithCompoundCurve() throws IOException {
// Test a pre-created WKB saved as the abstract MultiCurve type with a
// CompoundCurve
byte[] bytes = new byte[] { 0, 0, 0, 0, 11, 0, 0, 0, 1, 0, 0, 0, 0, 9,
0, 0, 0, 2, 0, 0, 0, 0, 2, 0, 0, 0, 3, 65, 74, 85, 13, 0, -60,
-101, -90, 65, 84, -23, 84, 60, -35, 47, 27, 65, 74, 85, 12,
-28, -68, 106, 127, 65, 84, -23, 84, 123, 83, -9, -49, 65, 74,
85, 8, -1, 92, 40, -10, 65, 84, -23, 83, -81, -99, -78, 45, 0,
0, 0, 0, 2, 0, 0, 0, 2, 65, 74, 85, 8, -1, 92, 40, -10, 65, 84,
-23, 83, -81, -99, -78, 45, 65, 74, 85, 13, 0, -60, -101, -90,
65, 84, -23, 84, 60, -35, 47, 27 };
TestCase.assertEquals(GeometryCodes.getCode(GeometryType.MULTICURVE),
bytes[4]);
Geometry geometry = WKBTestUtils.readGeometry(bytes);
TestCase.assertTrue(geometry instanceof GeometryCollection);
TestCase.assertEquals(geometry.getGeometryType(),
GeometryType.GEOMETRYCOLLECTION);
@SuppressWarnings("unchecked")
GeometryCollection<Curve> multiCurve = (GeometryCollection<Curve>) geometry;
TestCase.assertEquals(1, multiCurve.numGeometries());
Geometry geometry1 = multiCurve.getGeometries().get(0);
TestCase.assertTrue(geometry1 instanceof CompoundCurve);
CompoundCurve compoundCurve1 = (CompoundCurve) geometry1;
TestCase.assertEquals(2, compoundCurve1.numLineStrings());
LineString lineString1 = compoundCurve1.getLineStrings().get(0);
LineString lineString2 = compoundCurve1.getLineStrings().get(1);
TestCase.assertEquals(3, lineString1.numPoints());
TestCase.assertEquals(2, lineString2.numPoints());
TestCase.assertEquals(new Point(3451418.006, 5481808.951),
lineString1.getPoint(0));
TestCase.assertEquals(new Point(3451417.787, 5481809.927),
lineString1.getPoint(1));
TestCase.assertEquals(new Point(3451409.995, 5481806.744),
lineString1.getPoint(2));
TestCase.assertEquals(new Point(3451409.995, 5481806.744),
lineString2.getPoint(0));
TestCase.assertEquals(new Point(3451418.006, 5481808.951),
lineString2.getPoint(1));
ExtendedGeometryCollection<Curve> extendedMultiCurve = new ExtendedGeometryCollection<>(
multiCurve);
TestCase.assertEquals(GeometryType.MULTICURVE,
extendedMultiCurve.getGeometryType());
geometryTester(extendedMultiCurve, multiCurve);
byte[] bytes2 = WKBTestUtils.writeBytes(extendedMultiCurve);
TestCase.assertEquals(GeometryCodes.getCode(GeometryType.MULTICURVE),
bytes2[4]);
WKBTestUtils.compareByteArrays(bytes, bytes2);
}
@Test
public void testMultiCurve() throws IOException {
// Test the abstract MultiCurve type
GeometryCollection<Curve> multiCurve = WKBTestUtils.createMultiCurve();
byte[] bytes = WKBTestUtils.writeBytes(multiCurve);
ExtendedGeometryCollection<Curve> extendedMultiCurve = new ExtendedGeometryCollection<>(
multiCurve);
TestCase.assertEquals(GeometryType.MULTICURVE,
extendedMultiCurve.getGeometryType());
byte[] extendedBytes = WKBTestUtils.writeBytes(extendedMultiCurve);
TestCase.assertEquals(
GeometryCodes.getCode(GeometryType.GEOMETRYCOLLECTION),
bytes[4]);
TestCase.assertEquals(GeometryCodes.getCode(GeometryType.MULTICURVE),
extendedBytes[4]);
Geometry geometry1 = WKBTestUtils.readGeometry(bytes);
Geometry geometry2 = WKBTestUtils.readGeometry(extendedBytes);
TestCase.assertTrue(geometry1 instanceof GeometryCollection);
TestCase.assertTrue(geometry2 instanceof GeometryCollection);
TestCase.assertEquals(GeometryType.GEOMETRYCOLLECTION,
geometry1.getGeometryType());
TestCase.assertEquals(GeometryType.GEOMETRYCOLLECTION,
geometry2.getGeometryType());
TestCase.assertEquals(multiCurve, geometry1);
TestCase.assertEquals(geometry1, geometry2);
@SuppressWarnings("unchecked")
GeometryCollection<Geometry> geometryCollection1 = (GeometryCollection<Geometry>) geometry1;
@SuppressWarnings("unchecked")
GeometryCollection<Geometry> geometryCollection2 = (GeometryCollection<Geometry>) geometry2;
TestCase.assertTrue(geometryCollection1.isMultiCurve());
TestCase.assertTrue(geometryCollection2.isMultiCurve());
geometryTester(multiCurve);
geometryTester(extendedMultiCurve, multiCurve);
}
@Test
public void testMultiSurface() throws IOException {
// Test the abstract MultiSurface type
GeometryCollection<Surface> multiSurface = WKBTestUtils
.createMultiSurface();
byte[] bytes = WKBTestUtils.writeBytes(multiSurface);
ExtendedGeometryCollection<Surface> extendedMultiSurface = new ExtendedGeometryCollection<>(
multiSurface);
TestCase.assertEquals(GeometryType.MULTISURFACE,
extendedMultiSurface.getGeometryType());
byte[] extendedBytes = WKBTestUtils.writeBytes(extendedMultiSurface);
TestCase.assertEquals(
GeometryCodes.getCode(GeometryType.GEOMETRYCOLLECTION),
bytes[4]);
TestCase.assertEquals(GeometryCodes.getCode(GeometryType.MULTISURFACE),
extendedBytes[4]);
Geometry geometry1 = WKBTestUtils.readGeometry(bytes);
Geometry geometry2 = WKBTestUtils.readGeometry(extendedBytes);
TestCase.assertTrue(geometry1 instanceof GeometryCollection);
TestCase.assertTrue(geometry2 instanceof GeometryCollection);
TestCase.assertEquals(GeometryType.GEOMETRYCOLLECTION,
geometry1.getGeometryType());
TestCase.assertEquals(GeometryType.GEOMETRYCOLLECTION,
geometry2.getGeometryType());
TestCase.assertEquals(multiSurface, geometry1);
TestCase.assertEquals(geometry1, geometry2);
@SuppressWarnings("unchecked")
GeometryCollection<Geometry> geometryCollection1 = (GeometryCollection<Geometry>) geometry1;
@SuppressWarnings("unchecked")
GeometryCollection<Geometry> geometryCollection2 = (GeometryCollection<Geometry>) geometry2;
TestCase.assertTrue(geometryCollection1.isMultiSurface());
TestCase.assertTrue(geometryCollection2.isMultiSurface());
geometryTester(multiSurface);
geometryTester(extendedMultiSurface, multiSurface);
}
@Test
public void testMultiPolygon() throws IOException {
for (int i = 0; i < GEOMETRIES_PER_TEST; i++) {
// Create and test a multi polygon
MultiPolygon multiPolygon = WKBTestUtils.createMultiPolygon(
WKBTestUtils.coinFlip(), WKBTestUtils.coinFlip());
geometryTester(multiPolygon);
}
}
@Test
public void testGeometryCollection() throws IOException {
for (int i = 0; i < GEOMETRIES_PER_TEST; i++) {
// Create and test a geometry collection
GeometryCollection<Geometry> geometryCollection = WKBTestUtils
.createGeometryCollection(WKBTestUtils.coinFlip(),
WKBTestUtils.coinFlip());
geometryTester(geometryCollection);
}
}
@Test
public void testMultiPolygon25() throws IOException {
// Test a pre-created WKB hex saved as a 2.5D MultiPolygon
byte[] bytes = hexStringToByteArray("0106000080010000000103000080010000000F0000007835454789C456C0DFDB63124D3F2C4000000000000000004CE4512E89C456C060BF20D13F3F2C400000000000000000A42EC6388CC456C0E0A50400423F2C400000000000000000B4E3B1608CC456C060034E67433F2C400000000000000000F82138508DC456C09FD015C5473F2C400000000000000000ECD6591B8CC456C000C305BC5B3F2C4000000000000000001002AD0F8CC456C060DB367D5C3F2C40000000000000000010996DEF8AC456C0BF01756A6C3F2C4000000000000000007054A08B8AC456C0806A0C1F733F2C4000000000000000009422D81D8AC456C041CA3C5B8A3F2C4000000000000000003CCB05C489C456C03FC4FC52AA3F2C400000000000000000740315A689C456C0BFC8635EB33F2C400000000000000000E4A5630B89C456C0DFE726D6B33F2C400000000000000000F45A4F3389C456C000B07950703F2C4000000000000000007835454789C456C0DFDB63124D3F2C400000000000000000");
TestCase.assertEquals(1, bytes[0]); // little endian
TestCase.assertEquals(GeometryCodes.getCode(GeometryType.MULTIPOLYGON),
bytes[1]);
TestCase.assertEquals(0, bytes[2]);
TestCase.assertEquals(0, bytes[3]);
TestCase.assertEquals(-128, bytes[4]);
Geometry geometry = WKBTestUtils.readGeometry(bytes);
TestCase.assertTrue(geometry instanceof MultiPolygon);
TestCase.assertEquals(geometry.getGeometryType(),
GeometryType.MULTIPOLYGON);
MultiPolygon multiPolygon = (MultiPolygon) geometry;
TestCase.assertTrue(multiPolygon.hasZ());
TestCase.assertFalse(multiPolygon.hasM());
TestCase.assertEquals(1, multiPolygon.numGeometries());
Polygon polygon = multiPolygon.getPolygon(0);
TestCase.assertTrue(polygon.hasZ());
TestCase.assertFalse(polygon.hasM());
TestCase.assertEquals(1, polygon.numRings());
LineString ring = polygon.getRing(0);
TestCase.assertTrue(ring.hasZ());
TestCase.assertFalse(ring.hasM());
TestCase.assertEquals(15, ring.numPoints());
for (Point point : ring.getPoints()) {
TestCase.assertTrue(point.hasZ());
TestCase.assertFalse(point.hasM());
TestCase.assertNotNull(point.getZ());
TestCase.assertNull(point.getM());
}
byte[] multiPolygonBytes = WKBTestUtils.writeBytes(multiPolygon,
ByteOrder.LITTLE_ENDIAN);
Geometry geometry2 = WKBTestUtils.readGeometry(multiPolygonBytes);
geometryTester(geometry, geometry2);
TestCase.assertEquals(bytes.length, multiPolygonBytes.length);
int equalBytes = 0;
for (int i = 0; i < bytes.length; i++) {
if (bytes[i] == multiPolygonBytes[i]) {
equalBytes++;
}
}
TestCase.assertEquals(bytes.length - 6, equalBytes);
}
/**
* Test the geometry writing to and reading from bytes
*
* @param geometry
* geometry
* @throws IOException
*/
private void geometryTester(Geometry geometry) throws IOException {
geometryTester(geometry, geometry);
}
/**
* Test the geometry writing to and reading from bytes, compare with the
* provided geometry
*
* @param geometry
* geometry
* @param compareGeometry
* compare geometry
* @throws IOException
*/
private void geometryTester(Geometry geometry, Geometry compareGeometry)
throws IOException {
// Write the geometries to bytes
byte[] bytes1 = WKBTestUtils.writeBytes(geometry, ByteOrder.BIG_ENDIAN);
byte[] bytes2 = WKBTestUtils.writeBytes(geometry,
ByteOrder.LITTLE_ENDIAN);
TestCase.assertFalse(WKBTestUtils.equalByteArrays(bytes1, bytes2));
// Test that the bytes are read using their written byte order, not
// the specified
Geometry geometry1opposite = WKBTestUtils.readGeometry(bytes1,
ByteOrder.LITTLE_ENDIAN);
Geometry geometry2opposite = WKBTestUtils.readGeometry(bytes2,
ByteOrder.BIG_ENDIAN);
WKBTestUtils.compareByteArrays(
WKBTestUtils.writeBytes(compareGeometry),
WKBTestUtils.writeBytes(geometry1opposite));
WKBTestUtils.compareByteArrays(
WKBTestUtils.writeBytes(compareGeometry),
WKBTestUtils.writeBytes(geometry2opposite));
Geometry geometry1 = WKBTestUtils.readGeometry(bytes1,
ByteOrder.BIG_ENDIAN);
Geometry geometry2 = WKBTestUtils.readGeometry(bytes2,
ByteOrder.LITTLE_ENDIAN);
WKBTestUtils.compareGeometries(compareGeometry, geometry1);
WKBTestUtils.compareGeometries(compareGeometry, geometry2);
WKBTestUtils.compareGeometries(geometry1, geometry2);
GeometryEnvelope envelope = GeometryEnvelopeBuilder
.buildEnvelope(compareGeometry);
GeometryEnvelope envelope1 = GeometryEnvelopeBuilder
.buildEnvelope(geometry1);
GeometryEnvelope envelope2 = GeometryEnvelopeBuilder
.buildEnvelope(geometry2);
WKBTestUtils.compareEnvelopes(envelope, envelope1);
WKBTestUtils.compareEnvelopes(envelope1, envelope2);
}
/**
* Convert the hex string to a byte array
*
* @param hex
* hex string
* @return byte array
*/
private static byte[] hexStringToByteArray(String hex) {
int len = hex.length();
byte[] bytes = new byte[len / 2];
for (int i = 0; i < len; i += 2) {
bytes[i / 2] = (byte) ((Character.digit(hex.charAt(i), 16) << 4) + Character
.digit(hex.charAt(i + 1), 16));
}
return bytes;
}
}
|
package org.c4sg;
import static org.hamcrest.CoreMatchers.is;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions;
import static org.mockito.Mockito.when;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import java.util.Arrays;
import java.util.List;
import org.c4sg.controller.UserController;
import org.c4sg.dto.UserDTO;
import org.c4sg.service.UserService;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.MediaType;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import com.fasterxml.jackson.databind.ObjectMapper;
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = {C4SgApplication.class}, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class UserControllerTest {
private MockMvc mockMvc;
@Mock
private UserService userServiceMock;
//private UserDAO userDao;
@InjectMocks
private UserController userController;
@Before
public void setup() {
this.mockMvc = MockMvcBuilders.standaloneSetup(userController).build();
}
@Test
public void testGetUsers() throws Exception
{
/*
//Mock user data
List<UserDTO> mockUsers = getMockUsers("All");
when(userServiceMock.findAll()).thenReturn(mockUsers);
this.mockMvc.perform(get("/api/users")
.accept(MediaType.parseMediaType("application/json;charset=UTF-8")))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8))
.andExpect(jsonPath("$", hasSize(4)))
.andExpect(jsonPath("$[0].id",is(1)))
.andExpect(jsonPath("$[0].github",is(1)))
.andExpect(jsonPath("$[0].userName",is("test1UserName")))
.andExpect(jsonPath("$[0].firstName",is("test1FirstName")))
.andExpect(jsonPath("$[0].lastName",is("test1LastName")))
.andExpect(jsonPath("$[0].email",is("test1Email@gmail.com")))
.andExpect(jsonPath("$[0].phone",is("9542234567")))
.andExpect(jsonPath("$[0].status",is("A")))
.andExpect(jsonPath("$[0].role",is("V")))
.andExpect(jsonPath("$[0].state",is("CA")))
.andExpect(jsonPath("$[0].country",is("USA")))
.andExpect(jsonPath("$[1].id",is(2)))
.andExpect(jsonPath("$[1].github",is(2)))
.andExpect(jsonPath("$[1].userName",is("test2UserName")))
.andExpect(jsonPath("$[1].firstName",is("test2FirstName")))
.andExpect(jsonPath("$[1].lastName",is("test2LastName")))
.andExpect(jsonPath("$[1].email",is("test2Email@gmail.com")))
.andExpect(jsonPath("$[1].phone",is("9542234567")))
.andExpect(jsonPath("$[1].status",is("P")))
.andExpect(jsonPath("$[1].role",is("V")))
.andExpect(jsonPath("$[1].state",is("CA")))
.andExpect(jsonPath("$[1].country",is("USA")))
.andExpect(jsonPath("$[2].id",is(3)))
.andExpect(jsonPath("$[2].github",is(3)))
.andExpect(jsonPath("$[2].userName",is("dev3UserName")))
.andExpect(jsonPath("$[2].firstName",is("dev3FirstName")))
.andExpect(jsonPath("$[2].lastName",is("dev3LastName")))
.andExpect(jsonPath("$[2].email",is("dev3Email@gmail.com")))
.andExpect(jsonPath("$[2].phone",is("9542234567")))
.andExpect(jsonPath("$[2].status",is("A")))
.andExpect(jsonPath("$[2].role",is("D")))
.andExpect(jsonPath("$[2].state",is("CA")))
.andExpect(jsonPath("$[2].country",is("USA")))
.andExpect(jsonPath("$[3].id",is(4)))
.andExpect(jsonPath("$[3].github",is(4)))
.andExpect(jsonPath("$[3].userName",is("vol4UserName")))
.andExpect(jsonPath("$[3].firstName",is("vol4FirstName")))
.andExpect(jsonPath("$[3].lastName",is("vol4LastName")))
.andExpect(jsonPath("$[3].email",is("vol4Email@gmail.com")))
.andExpect(jsonPath("$[3].phone",is("9542234567")))
.andExpect(jsonPath("$[3].status",is("D")))
.andExpect(jsonPath("$[3].role",is("V")))
.andExpect(jsonPath("$[3].state",is("CA")))
.andExpect(jsonPath("$[3].country",is("USA")))
;
verify(userServiceMock, times(1)).findAll();
verifyNoMoreInteractions(userServiceMock);
*/
}
/*
//Testing POST
@Test
public void testCreateUser() throws Exception {
UserDTO user = new UserDTO();
user.setEmail("test1Email@gmail.com");
when(userServiceMock.saveUser(user)).thenReturn(user);
this.mockMvc.perform(post("/api/users")
.contentType(MediaType.APPLICATION_JSON)
.content(asJsonString(user)))
.andExpect(status().isCreated())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8))
.andExpect(jsonPath("$.email",is("test1Email@gmail.com")))
;
verify(userServiceMock, times(1)).saveUser(user);
verifyNoMoreInteractions(userServiceMock);
}
@Test
public void testGetActiveUsers() throws Exception {
List<UserDTO> activeUsers = getMockUsers("Active");
when(userServiceMock.findActiveUsers()).thenReturn(activeUsers);
this.mockMvc.perform(get("/api/users/active")
.accept(MediaType.parseMediaType("application/json;charset=UTF-8")))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8))
.andExpect(jsonPath("$", hasSize(2)))
.andExpect(jsonPath("$[0].id",is(1)))
.andExpect(jsonPath("$[0].github",is(1)))
.andExpect(jsonPath("$[0].userName",is("test1UserName")))
.andExpect(jsonPath("$[0].firstName",is("test1FirstName")))
.andExpect(jsonPath("$[0].lastName",is("test1LastName")))
.andExpect(jsonPath("$[0].email",is("test1Email@gmail.com")))
.andExpect(jsonPath("$[0].phone",is("9542234567")))
.andExpect(jsonPath("$[0].status",is("A")))
.andExpect(jsonPath("$[0].role",is("V")))
.andExpect(jsonPath("$[0].state",is("CA")))
.andExpect(jsonPath("$[0].country",is("USA")))
.andExpect(jsonPath("$[1].id",is(3)))
.andExpect(jsonPath("$[1].github",is(3)))
.andExpect(jsonPath("$[1].userName",is("dev3UserName")))
.andExpect(jsonPath("$[1].firstName",is("dev3FirstName")))
.andExpect(jsonPath("$[1].lastName",is("dev3LastName")))
.andExpect(jsonPath("$[1].email",is("dev3Email@gmail.com")))
.andExpect(jsonPath("$[1].phone",is("9542234567")))
.andExpect(jsonPath("$[1].status",is("A")))
.andExpect(jsonPath("$[1].role",is("D")))
.andExpect(jsonPath("$[1].state",is("CA")))
.andExpect(jsonPath("$[1].country",is("USA")));
verify(userServiceMock, times(1)).findActiveUsers();
verifyNoMoreInteractions(userServiceMock);
}
@Test
public void testGetUserById() throws Exception {
//Mock user data - user with id = 1
UserDTO userById = getMockUsers("ById").get(0);
when(userServiceMock.findById(1)).thenReturn(userById);
this.mockMvc.perform(get("/api/users/{id}",1)
.accept(MediaType.parseMediaType("application/json;charset=UTF-8")))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8))
.andExpect(jsonPath("$.id",is(1)))
.andExpect(jsonPath("$.github",is(1)))
.andExpect(jsonPath("$.userName",is("test1UserName")))
.andExpect(jsonPath("$.firstName",is("test1FirstName")))
.andExpect(jsonPath("$.lastName",is("test1LastName")))
.andExpect(jsonPath("$.email",is("test1Email@gmail.com")))
.andExpect(jsonPath("$.phone",is("9542234567")))
.andExpect(jsonPath("$.status",is("A")))
.andExpect(jsonPath("$.role",is("V")))
.andExpect(jsonPath("$.state",is("CA")))
.andExpect(jsonPath("$.country",is("USA")));
verify(userServiceMock, times(1)).findById(1);
verifyNoMoreInteractions(userServiceMock);
}
@Test
public void testGetDevelopers()
{
//code is commented because findDevelopers() method in UserService returns User instead of UserDTO
//get mock users
List<UserDTO> developers = getMockUsers("Developers");
when(userServiceMock.findDevelopers()).thenReturn(developers);
this.mockMvc.perform(get("/api/users/developers")
.accept(MediaType.parseMediaType("application/json;charset=UTF-8")))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8))
.andExpect(jsonPath("$",hasSize(1)))
.andExpect(jsonPath("$[0].github",is(3)))
.andExpect(jsonPath("$[0].userName",is("dev3UserName")))
.andExpect(jsonPath("$[0].firstName",is("dev3FirstName")))
.andExpect(jsonPath("$[0].lastName",is("dev3LastName")))
.andExpect(jsonPath("$[0].email",is("dev3Email@gmail.com")))
.andExpect(jsonPath("$[0].phone",is("9542234567")))
.andExpect(jsonPath("$[0].status",is("A")))
.andExpect(jsonPath("$[0].role",is("D")))
.andExpect(jsonPath("$[0].state",is("CA")))
.andExpect(jsonPath("$[0].country",is("USA")));
verify(userServiceMock, times(1)).findDevelopers();
verifyNoMoreInteractions(userServiceMock);
}
//Testing PUT
@Test
public void testUpdateUser() throws Exception {
//get mock data
UserDTO user = getMockUsers("Update").get(0);
when(userServiceMock.saveUser(user)).thenReturn(user);
this.mockMvc.perform(put("/api/users")
.contentType(MediaType.APPLICATION_JSON)
.content(asJsonString(user)))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8))
.andExpect(jsonPath("$.id",is(1)))
.andExpect(jsonPath("$.github",is(1)))
.andExpect(jsonPath("$.userName",is("test1UserName")))
.andExpect(jsonPath("$.firstName",is("test1FirstName")))
.andExpect(jsonPath("$.lastName",is("test1LastName")))
.andExpect(jsonPath("$.email",is("test1Email@gmail.com")))
.andExpect(jsonPath("$.phone",is("9542234567")))
.andExpect(jsonPath("$.status",is("A")))
.andExpect(jsonPath("$.role",is("V")))
.andExpect(jsonPath("$.state",is("CA")))
.andExpect(jsonPath("$.country",is("USA")));
verify(userServiceMock, times(1)).saveUser(user);
verifyNoMoreInteractions(userServiceMock);
}
//Testing DELETE
@Test
public void testDeleteUser() throws Exception
{
//get mock data
UserDTO user = getMockUsers("Delete").get(0);
doNothing().when(userServiceMock).deleteUser(user.getId());
this.mockMvc.perform(delete("/api/users/{id}",user.getId())
.accept(MediaType.parseMediaType("application/json;charset=UTF-8")))
.andExpect(status().isOk());
verify(userServiceMock, times(1)).deleteUser(user.getId());
verifyNoMoreInteractions(userServiceMock);
}
*/
//Private methods
List<UserDTO> getMockUsers(String condition)
{
//creating mock data
//Role - Volunteer and Status - Active
//Role - Volunteer and Status - pending
//Role - Developer and Status - Active
//Role - Volunteer and Status - Deleted
if(condition == "Active")
{
return Arrays.asList(userDto, userDto3);
}
else if(condition == "Developers")
{
return Arrays.asList(userDto3);
}
else if(condition == "ById")
{
return Arrays.asList(userDto);
}
else if(condition == "Create")
{
return Arrays.asList(userDto);
}
else if(condition == "Update")
{
return Arrays.asList(userDto);
}
else if(condition == "Delete")
{
return Arrays.asList(userDto);
}
else
{
//returns all users
return Arrays.asList(userDto, userDto2, userDto3, userDto4);
}
}
static String asJsonString(final Object obj) {
try {
return new ObjectMapper().writeValueAsString(obj);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
|
package org.recap.camel;
import org.apache.camel.ProducerTemplate;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.component.file.FileEndpoint;
import org.apache.camel.component.file.GenericFile;
import org.apache.camel.component.file.GenericFileFilter;
import org.apache.commons.io.FilenameUtils;
import org.junit.Test;
import org.recap.BaseTestCase;
import org.recap.ReCAPConstants;
import org.recap.camel.activemq.JmxHelper;
import org.recap.camel.datadump.DataExportHeaderUtil;
import org.recap.model.export.DataDumpRequest;
import org.recap.model.search.SearchRecordsRequest;
import org.recap.repository.BibliographicDetailsRepository;
import org.recap.repository.XmlRecordRepository;
import org.recap.service.DataDumpSolrService;
import org.recap.service.formatter.datadump.MarcXmlFormatterService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.*;
public class CamelJdbcUT extends BaseTestCase {
@Value("${etl.split.xml.tag.name}")
String xmlTagName;
@Value("${etl.pool.size}")
Integer etlPoolSize;
@Value("${etl.pool.size}")
Integer etlMaxPoolSize;
@Value("${etl.max.pool.size}")
String inputDirectoryPath;
@Value("${activemq.broker.url}")
String brokerUrl;
@Autowired
JmxHelper jmxHelper;
@Autowired
DataExportHeaderUtil dataExportHeaderUtil;
@Autowired
XmlRecordRepository xmlRecordRepository;
@Autowired
BibliographicDetailsRepository bibliographicDetailsRepository;
@Autowired
DataDumpSolrService dataDumpSolrService;
@Autowired
MarcXmlFormatterService marcXmlFormatterService;
@Autowired
private ProducerTemplate producer;
@Value("${datadump.batch.size}")
String dataDumpBatchSize;
@Test
public void parseXmlAndInsertIntoDb() throws Exception {
camelContext.addRoutes(new RouteBuilder() {
@Override
public void configure() throws Exception {
FileEndpoint fileEndpoint = endpoint("file:" + inputDirectoryPath, FileEndpoint.class);
fileEndpoint.setFilter(new XmlFileFilter());
from(fileEndpoint)
.split()
.tokenizeXML(xmlTagName)
.streaming()
.threads(etlPoolSize, etlMaxPoolSize, "xmlProcessingThread")
.process(new XmlProcessor(xmlRecordRepository))
.to("jdbc:dataSource");
}
});
java.lang.Thread.sleep(10000);
}
class XmlFileFilter implements GenericFileFilter {
@Override
public boolean accept(GenericFile file) {
return FilenameUtils.getExtension(file.getAbsoluteFilePath()).equalsIgnoreCase("xml");
}
}
@Test
public void exportDataDumpForMarcXML() throws Exception {
SearchRecordsRequest searchRecordsRequest = new SearchRecordsRequest();
searchRecordsRequest.setOwningInstitutions(Arrays.asList("CUL"));
searchRecordsRequest.setCollectionGroupDesignations(Arrays.asList("Shared"));
searchRecordsRequest.setPageSize(Integer.valueOf(dataDumpBatchSize));
long startTime = System.currentTimeMillis();
Map results = dataDumpSolrService.getResults(searchRecordsRequest);
DataDumpRequest dataDumpRequest = new DataDumpRequest();
dataDumpRequest.setToEmailAddress("premlovesindia@gmail.com");
String dateTimeString = getDateTimeString();
dataDumpRequest.setDateTimeString(dateTimeString);
dataDumpRequest.setTransmissionType(ReCAPConstants.DATADUMP_TRANSMISSION_TYPE_FTP);
dataDumpRequest.setInstitutionCodes(Arrays.asList("NYPL", "CUL"));
dataDumpRequest.setOutputFileFormat(ReCAPConstants.DATADUMP_XML_FORMAT_MARC);
long endTime = System.currentTimeMillis();
System.out.println("Time taken to fetch 10K results for page 1 is : " + (endTime - startTime) / 1000 + " seconds ");
String fileName = "PUL" + File.separator + dateTimeString + File.separator + ReCAPConstants.DATA_DUMP_FILE_NAME + "PUL" + 0;
String folderName = "PUL" + File.separator + dateTimeString;
Integer totalPageCount = (Integer) results.get("totalPageCount");
String headerString = dataExportHeaderUtil.getBatchHeaderString(totalPageCount, 1, folderName, fileName, dataDumpRequest);
producer.sendBodyAndHeader(ReCAPConstants.SOLR_INPUT_FOR_DATA_EXPORT_Q, results, "batchHeaders", headerString.toString());
for (int pageNum = 1; pageNum < totalPageCount; pageNum++) {
searchRecordsRequest.setPageNumber(pageNum);
startTime = System.currentTimeMillis();
Map results1 = dataDumpSolrService.getResults(searchRecordsRequest);
endTime = System.currentTimeMillis();
System.out.println("Time taken to fetch 10K results for page : " + pageNum + " is " + (endTime - startTime) / 1000 + " seconds ");
fileName = "PUL" + File.separator + dateTimeString + File.separator + ReCAPConstants.DATA_DUMP_FILE_NAME + "PUL" + pageNum + 1;
headerString = dataExportHeaderUtil.getBatchHeaderString(totalPageCount, pageNum + 1, folderName, fileName, dataDumpRequest);
producer.sendBodyAndHeader(ReCAPConstants.SOLR_INPUT_FOR_DATA_EXPORT_Q, results1, "batchHeaders", headerString.toString());
}
while (true) {
}
}
@Test
public void exportDataDumpForSCSBXML() throws Exception {
SearchRecordsRequest searchRecordsRequest = new SearchRecordsRequest();
searchRecordsRequest.setOwningInstitutions(Arrays.asList("PUL"));
searchRecordsRequest.setCollectionGroupDesignations(Arrays.asList("Shared"));
searchRecordsRequest.setPageSize(Integer.valueOf(2));
long startTime = System.currentTimeMillis();
Map results = dataDumpSolrService.getResults(searchRecordsRequest);
DataDumpRequest dataDumpRequest = new DataDumpRequest();
dataDumpRequest.setToEmailAddress("peri.subrahmanya@gmail.com");
String dateTimeString = getDateTimeString();
dataDumpRequest.setDateTimeString(dateTimeString);
dataDumpRequest.setTransmissionType(ReCAPConstants.DATADUMP_TRANSMISSION_TYPE_FTP);
dataDumpRequest.setInstitutionCodes(Arrays.asList("NYPL", "CUL"));
dataDumpRequest.setOutputFileFormat(ReCAPConstants.DATADUMP_XML_FORMAT_SCSB);
long endTime = System.currentTimeMillis();
System.out.println("Time taken to fetch 10K results for page 1 is : " + (endTime - startTime) / 1000 + " seconds ");
String fileName = "PUL" + File.separator + dateTimeString + File.separator + ReCAPConstants.DATA_DUMP_FILE_NAME + "PUL" + 0;
String folderName = "PUL" + File.separator + dateTimeString;
// Integer totalPageCount = (Integer) results.get("totalPageCount");
Integer totalPageCount = 3;
String headerString = dataExportHeaderUtil.getBatchHeaderString(totalPageCount, 1, folderName, fileName, dataDumpRequest);
producer.sendBodyAndHeader(ReCAPConstants.SOLR_INPUT_FOR_DATA_EXPORT_Q, results, "batchHeaders", headerString.toString());
for (int pageNum = 1; pageNum < totalPageCount; pageNum++) {
searchRecordsRequest.setPageNumber(pageNum);
startTime = System.currentTimeMillis();
Map results1 = dataDumpSolrService.getResults(searchRecordsRequest);
endTime = System.currentTimeMillis();
System.out.println("Time taken to fetch 10K results for page : " + pageNum + " is " + (endTime - startTime) / 1000 + " seconds ");
fileName = "PUL" + File.separator + dateTimeString + File.separator + ReCAPConstants.DATA_DUMP_FILE_NAME + "PUL" + pageNum + 1;
headerString = dataExportHeaderUtil.getBatchHeaderString(totalPageCount, pageNum + 1, folderName, fileName, dataDumpRequest);
producer.sendBodyAndHeader(ReCAPConstants.SOLR_INPUT_FOR_DATA_EXPORT_Q, results1, "batchHeaders", headerString.toString());
}
while (true) {
}
}
@Test
public void exportDataDumpForDeletedJson() throws Exception {
SearchRecordsRequest searchRecordsRequest = new SearchRecordsRequest();
searchRecordsRequest.setOwningInstitutions(Arrays.asList("PUL"));
searchRecordsRequest.setCollectionGroupDesignations(Arrays.asList("Shared"));
searchRecordsRequest.setDeleted(true);
searchRecordsRequest.setPageSize(Integer.valueOf(dataDumpBatchSize));
long startTime = System.currentTimeMillis();
Map results = dataDumpSolrService.getResults(searchRecordsRequest);
DataDumpRequest dataDumpRequest = new DataDumpRequest();
dataDumpRequest.setToEmailAddress("peri.subrahmanya@gmail.com");
String dateTimeString = getDateTimeString();
dataDumpRequest.setDateTimeString(dateTimeString);
dataDumpRequest.setTransmissionType(ReCAPConstants.DATADUMP_TRANSMISSION_TYPE_FTP);
dataDumpRequest.setInstitutionCodes(Arrays.asList("NYPL", "CUL"));
dataDumpRequest.setOutputFileFormat(ReCAPConstants.DATADUMP_DELETED_JSON_FORMAT);
long endTime = System.currentTimeMillis();
System.out.println("Time taken to fetch 10K results for page 1 is : " + (endTime - startTime) / 1000 + " seconds ");
String fileName = "PUL" + File.separator + dateTimeString + File.separator + ReCAPConstants.DATA_DUMP_FILE_NAME + "PUL" + 0;
String folderName = "PUL" + File.separator + dateTimeString;
Integer totalPageCount = (Integer) results.get("totalPageCount");
String headerString = dataExportHeaderUtil.getBatchHeaderString(totalPageCount, 1, folderName, fileName, dataDumpRequest);
producer.sendBodyAndHeader(ReCAPConstants.SOLR_INPUT_FOR_DATA_EXPORT_Q, results, "batchHeaders", headerString);
for (int pageNum = 1; pageNum < totalPageCount; pageNum++) {
searchRecordsRequest.setPageNumber(pageNum);
startTime = System.currentTimeMillis();
Map results1 = dataDumpSolrService.getResults(searchRecordsRequest);
endTime = System.currentTimeMillis();
System.out.println("Time taken to fetch 10K results for page : " + pageNum + " is " + (endTime - startTime) / 1000 + " seconds ");
fileName = "PUL" + File.separator + dateTimeString + File.separator + ReCAPConstants.DATA_DUMP_FILE_NAME + "PUL" + pageNum + 1;
headerString = dataExportHeaderUtil.getBatchHeaderString(totalPageCount, pageNum + 1, folderName, fileName, dataDumpRequest);
producer.sendBodyAndHeader(ReCAPConstants.SOLR_INPUT_FOR_DATA_EXPORT_Q, results1, "batchHeaders", headerString.toString());
}
while (true) {
}
}
private String getInstitutionCodes(DataDumpRequest dataDumpRequest) {
List<String> institutionCodes = dataDumpRequest.getInstitutionCodes();
StringBuilder stringBuilder = new StringBuilder();
for (Iterator<String> iterator = institutionCodes.iterator(); iterator.hasNext(); ) {
String code = iterator.next();
stringBuilder.append(code);
if(iterator.hasNext()){
stringBuilder.append("*");
}
}
return stringBuilder.toString();
}
private String getDateTimeString() {
Date date = new Date();
SimpleDateFormat sdf = new SimpleDateFormat(ReCAPConstants.DATE_FORMAT_MMDDYYY);
return sdf.format(date);
}
}
|
package eg.projects.settingswin;
import javax.swing.JButton;
import javax.swing.JPanel;
import javax.swing.JTextField;
import java.io.File;
//--Eadgyth--/
import eg.FileChooser;
/**
* Defines a button which is pressed to open a file chooser and set
* the name of the chosen file or directory in a text field
*/
public class BrowserButton {
private final FileChooser fc;
private final JTextField tf;
private final JButton bt = new JButton("...");
/**
* @param fc the file chooser to select a file or directory
* @param tf the text field that displays the name of the
* selected file or directory
*/
public BrowserButton(FileChooser fc, JTextField tf) {
this.fc = fc;
this.tf = tf;
bt.addActionListener(e -> setText());
bt.setFocusable(false);
}
/**
* Adds this <code>JButton</code> to the specified
* <code>JPanel</code>
*
* @param pnl the JPanel
*/
public void addButton(JPanel pnl) {
pnl.add(bt);
}
//--private--/
private void setText() {
File file = fc.selectedFileOrDirectory();
if (file != null) {
String text = file.getName();
tf.setText(text);
tf.requestFocusInWindow();
}
}
}
|
package moonlightowl.openblocks;
import javafx.application.Application;
import javafx.application.Platform;
import javafx.fxml.FXMLLoader;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.input.MouseButton;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.AnchorPane;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Priority;
import javafx.stage.FileChooser;
import javafx.stage.Stage;
import javafx.stage.WindowEvent;
import moonlightowl.openblocks.io.JSON;
import moonlightowl.openblocks.io.lua.Lua;
import moonlightowl.openblocks.structure.Block;
import moonlightowl.openblocks.structure.Joint;
import moonlightowl.openblocks.structure.Wire;
import moonlightowl.openblocks.ui.About;
import moonlightowl.openblocks.ui.ToolButton;
import moonlightowl.openblocks.ui.ToolPane;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import java.io.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Optional;
public class OpenBlocks extends Application {
private Stage parentStage;
// FXML links
public AnchorPane rootPane;
public MenuBar menuBar;
public HBox toolBar;
public ScrollPane scroller;
// Custom elements
private ToolPane[] tools;
private About about;
private Workspace workspace;
private boolean selectedTrash = false;
private Blocks.Id selected;
private ImageView selectedIcon;
private ArrayList<Wire> wires;
private boolean addWires = false;
private File projectFile;
private boolean changed = false;
@Override
public void start(Stage primaryStage) throws Exception {
parentStage = primaryStage;
FXMLLoader loader = new FXMLLoader(getClass().getResource("/main.fxml"));
loader.setController(this);
loader.load();
// Resources
Assets.load();
Log.init();
// Generate GUI
initUI();
// Create IDE window
setTitle(Settings.UNTITLED);
primaryStage.setScene(new Scene(rootPane, Settings.WIDTH, Settings.HEIGHT));
primaryStage.setMinWidth(500);
primaryStage.setMinHeight(400);
primaryStage.show();
// Handle exit
primaryStage.setOnCloseRequest(event -> {
if(changed) {
// Ask a question
Alert alert = new Alert(Alert.AlertType.CONFIRMATION);
alert.setTitle("Завершение работы");
alert.setHeaderText("Сохранение изменений");
alert.setContentText("В проект были внесены изменения. Сохранить?");
ButtonType buttonSave = new ButtonType("Сохранить");
ButtonType buttonDiscard = new ButtonType("Не сохранять");
ButtonType buttonCancel = new ButtonType("Отмена", ButtonBar.ButtonData.CANCEL_CLOSE);
alert.getButtonTypes().setAll(buttonSave, buttonDiscard, buttonCancel);
// Get an answer
Optional<ButtonType> result = alert.showAndWait();
if (result.get() == buttonSave){
saveProject();
} else if (result.get() == buttonCancel) {
event.consume();
}
}
// Finalize resources
if(!event.isConsumed()){
Log.out("Shutdown.");
Log.close();
}
});
Log.out("Let's go!");
}
public static void main(String[] args) {
launch(args);
}
public void setTitle(String title){
if(title != null)
parentStage.setTitle(title + " - " + Settings.TITLE + " " + Settings.VERSION);
else
parentStage.setTitle(Settings.TITLE + " " + Settings.VERSION);
changed = false;
}
public void projectChanged() {
if(!changed){
parentStage.setTitle("*"+parentStage.getTitle());
changed = true;
}
}
public void initUI(){
about = new About(parentStage);
workspace = new Workspace(scroller);
selectedIcon = new ImageView();
selectedIcon.setScaleX(0.3);
selectedIcon.setScaleY(0.3);
rootPane.getChildren().add(selectedIcon);
initToolsPanels();
initToolBar();
wires = new ArrayList<>();
/** Event listenters */
// Wire operations
Joint.setOnClickListenter(event ->{
Joint joint = (Joint)event.getSource();
if(event.getButton() == MouseButton.PRIMARY) {
// Replace existing one
if(joint.isAttached()){
Wire[] old = new Wire[]{};
if(!joint.isMultiwired() || wires.isEmpty()){
old = joint.getWires();
joint.detachAllWires();
}
if(!addWires) {
wires.forEach(joint::attachWire);
wires.clear();
}
wires.addAll(Arrays.asList(old));
}
// Or create / attach new wire
else {
if (wires.isEmpty()) {
Wire wire = new Wire();
joint.attachWire(wire);
wire.reposition(joint.getAbsX(), joint.getAbsY());
workspace.addWire(wire);
wires.add(wire);
} else {
wires.forEach(joint::attachWire);
wires.clear();
}
}
projectChanged();
}
});
// Block removement
Block.setOnClickListenter(event -> {
if (selectedTrash && event.getButton() == MouseButton.PRIMARY) {
Block block = (Block)event.getSource();
workspace.removeBlock(block);
projectChanged();
}
});
// Wire removement
Wire.setOnClickListenter(event -> {
if (selectedTrash && event.getButton() == MouseButton.PRIMARY) {
Wire wire = (Wire)event.getSource();
workspace.removeWire(wire);
projectChanged();
}
});
// Add new objects to workspace
rootPane.setOnMouseClicked(event -> {
if(hasOpenedPanes())
closeAllToolPanes();
else
if(event.getButton() == MouseButton.PRIMARY) {
if(selected != null) {
Block block = selected.getInstance()
.setPosition(workspace.projectX(event.getX()),
workspace.projectY(event.getY()));
workspace.addBlock(block);
projectChanged();
}
} else if(event.getButton() == MouseButton.SECONDARY) {
// Deselect current block type
deselect();
// Remove current uncomplete wire
if(!wires.isEmpty()){
wires.forEach(workspace::removeWire);
wires.clear();
}
}
});
// Move mouse tool icon & current wire loose end (if any)
rootPane.setOnMouseMoved(event -> {
selectedIcon.setTranslateX(event.getSceneX());
selectedIcon.setTranslateY(event.getSceneY());
if(!wires.isEmpty())
for(Wire wire: wires)
wire.reposition(workspace.projectX(event.getX()),
workspace.projectY(event.getY()));
});
rootPane.addEventFilter(MouseEvent.MOUSE_DRAGGED, rootPane.getOnMouseMoved());
// Keyboard tool selector
rootPane.setOnKeyPressed(event -> {
switch(event.getCode()){
case DIGIT1: toggleToolPane(0); break;
case DIGIT2: toggleToolPane(1); break;
case DIGIT3: toggleToolPane(2); break;
case DIGIT4: toggleToolPane(3); break;
case S: workspace.drag(0, -Settings.DRAG_SPEED); break;
case W: workspace.drag(0, Settings.DRAG_SPEED); break;
case D: workspace.drag(-Settings.DRAG_SPEED, 0); break;
case A: workspace.drag(Settings.DRAG_SPEED, 0); break;
case SHIFT: addWires = true; break;
case DELETE: selectTrashTool(); break;
case ESCAPE: deselect(); break;
}
});
rootPane.setOnKeyReleased(event -> {
switch (event.getCode()) {
case SHIFT: addWires = false;
}
});
}
/** UI generation */
private void initToolsPanels(){
tools = new ToolPane[] {
new ToolPane("Точки входа"),
new ToolPane("Действия"),
new ToolPane("Циклы"),
new ToolPane("Логика")
};
for(Blocks.Id id: Blocks.Id.values()){
ToolButton tool = new ToolButton(id.name, Assets.toolIcons[id.id]);
tool.setOnMouseClicked(event -> { select(id); closeAllToolPanes(); });
tools[id.category.ordinal()].add(tool);
}
for(ToolPane pane: tools) rootPane.getChildren().add(pane);
}
private void initToolBar(){
for(int c = 0; c < 4; c++) {
Button button = newToolBarButton(Assets.toolBarIcon[c+1]);
int id = c; button.setOnAction(event -> toggleToolPane(id));
toolBar.getChildren().add(button);
}
Button trash = newToolBarButton(Assets.toolBarIcon[5]);
trash.setOnAction(event -> selectTrashTool());
toolBar.getChildren().add(trash);
}
private Button newToolBarButton(Image image){
Button button = new Button();
button.setId("tool");
button.setGraphic(new ImageView(image));
return button;
}
/** Tool actions */
public void selectTrashTool(){
deselect();
selectedTrash = true;
selectedIcon.setImage(Assets.toolBarIcon[5]);
}
public void select(Blocks.Id id){
deselect();
selected = id;
selectedIcon.setImage(Assets.toolIcons[id.id]);
}
public void deselect(){
selected = null;
selectedTrash = false;
selectedIcon.setImage(null);
}
/** Block panel actions */
public void closeAllToolPanes(){ toggleToolPane(-1); }
public void toggleToolPane(int id){
for(int c = 0; c < tools.length; c++)
if(c == id) tools[c].toggle();
else tools[c].close();
}
public boolean hasOpenedPanes(){ for(ToolPane pane: tools) if(pane.isOpen()) return true; return false; }
/** Project file management */
private void save() {
String data = JSON.generate(workspace).toJSONString();
if(projectFile != null) {
try (FileWriter writer = new FileWriter(projectFile)) {
writer.write(data);
Log.out("Successfully saved JSON Object to file...");
} catch (IOException e) {
Log.error("Project saving error", e);
error("Ошибка записи проекта",
"В силу неведомых причин, сериализация проекта в JSON прошла неудачно.\n" +
"Проверьте, есть ли свободное место на диске, и имеет ли программа права на запись" +
"в выбранном каталоге.", e);
}
} else {
error("Ошибка записи проекта", "Не удалось выбрать имя файла", null);
}
}
private void load() {
JSONParser parser = new JSONParser();
try (FileReader reader = new FileReader(projectFile)) {
JSONObject data = (JSONObject) parser.parse(reader);
JSON.recreate(workspace, data);
} catch (Exception e) {
Log.error("Error loading project", e);
error("Ошибка открытия проекта",
"Вероятнее всего, файл, который вы пытаетесь открыть - поврежден.", e);
}
}
/** Menu actions */
public void newProject() {
workspace.clear();
projectFile = null;
setTitle(Settings.UNTITLED);
deselect(); // Drop all previously selected tools
}
public void openProject(){
FileChooser fileChooser = new FileChooser();
fileChooser.setTitle("Открыть...");
fileChooser.setInitialDirectory(new File(System.getProperty("user.dir")));
fileChooser.setSelectedExtensionFilter(
new FileChooser.ExtensionFilter("Проект "+Settings.TITLE, "*."+Settings.EXTENSION));
projectFile = fileChooser.showOpenDialog(parentStage);
if(projectFile != null) {
workspace.clear();
load();
setTitle(projectFile.getName());
deselect(); // Drop all previously selected tools
}
}
public void saveProject() {
if(projectFile == null) saveProjectAs();
else{ save(); setTitle(projectFile.getName()); }
}
public void saveProjectAs() {
FileChooser fileChooser = new FileChooser();
fileChooser.setTitle("Сохранить как...");
fileChooser.setInitialDirectory(new File(System.getProperty("user.dir")));
fileChooser.setInitialFileName(projectFile == null ?
Settings.UNTITLED + "." + Settings.EXTENSION : projectFile.getName());
fileChooser.setSelectedExtensionFilter(
new FileChooser.ExtensionFilter("Проект "+Settings.TITLE, "*."+Settings.EXTENSION));
projectFile = fileChooser.showSaveDialog(parentStage);
if(projectFile != null) {
save();
setTitle(projectFile.getName());
}
}
public void exportProject() {
FileChooser fileChooser = new FileChooser();
fileChooser.setTitle("Экспортировать в...");
fileChooser.setInitialDirectory(new File(System.getProperty("user.dir")));
fileChooser.setInitialFileName((projectFile == null ?
Settings.UNTITLED : projectFile.getName().split("\\.")[0]) + ".lua");
fileChooser.setSelectedExtensionFilter(
new FileChooser.ExtensionFilter("Программа OpenComputers", "*.lua"));
File file = fileChooser.showSaveDialog(parentStage);
try (FileOutputStream stream = new FileOutputStream(file)) {
if(!Lua.export(workspace, stream))
error("Ошибка экспорта",
"Внезапно, структура проекта не поддается экпорту! \nОтправьте проект автору IDE, пусть тоже удивится.", null);
else
Log.out("Successfully exported project to Lua");
} catch (IOException e) {
Log.error("Cannot export project properly! Some errors occured.", e);
error("Ошибка записи проекта",
"В силу неизвестных причин, произошла ошибка записи экспортированного листинга в файл.", e);
}
}
public void clearProject(){
workspace.clear();
projectChanged();
deselect(); // Drop all previously selected tools
}
public void showAboutWindow() {
about.show();
}
public void exit() {
parentStage.fireEvent(new WindowEvent(parentStage, WindowEvent.WINDOW_CLOSE_REQUEST));
}
/** Messages */
public void error(String title, String message, Exception e) {
Alert alert = new Alert(Alert.AlertType.ERROR);
alert.setTitle(title);
alert.setHeaderText("Упс! Что-то пошло не так...");
Label l = new Label(message);
alert.getDialogPane().setContent(l);
if(e != null) {
// Create expandable Exception.
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
e.printStackTrace(pw);
String exceptionText = sw.toString();
Label label = new Label("Стектрейс:");
TextArea textArea = new TextArea(exceptionText);
textArea.setEditable(false);
textArea.setWrapText(true);
textArea.setMaxWidth(Double.MAX_VALUE);
textArea.setMaxHeight(Double.MAX_VALUE);
GridPane.setVgrow(textArea, Priority.ALWAYS);
GridPane.setHgrow(textArea, Priority.ALWAYS);
GridPane expContent = new GridPane();
expContent.setMaxWidth(Double.MAX_VALUE);
expContent.add(label, 0, 0);
expContent.add(textArea, 0, 1);
alert.getDialogPane().setExpandableContent(expContent);
// Dirty hack for proper resizing
alert.getDialogPane().expandedProperty().addListener((event) -> {
Platform.runLater(() -> {
alert.getDialogPane().requestLayout();
Stage stage = (Stage)alert.getDialogPane().getScene().getWindow();
stage.sizeToScene();
});
});
}
alert.showAndWait();
}
}
|
package net.foxopen.jira.changelog;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.Collections;
import java.util.Comparator;
import java.util.LinkedList;
import org.joda.time.DateTime;
import com.atlassian.jira.rest.client.JiraRestClient;
import com.atlassian.jira.rest.client.JiraRestClientFactory;
import com.atlassian.jira.rest.client.ProjectRestClient;
import com.atlassian.jira.rest.client.RestClientException;
import com.atlassian.jira.rest.client.domain.BasicIssue;
import com.atlassian.jira.rest.client.domain.Issue;
import com.atlassian.jira.rest.client.domain.Project;
import com.atlassian.jira.rest.client.domain.SearchResult;
import com.atlassian.jira.rest.client.domain.Version;
import com.atlassian.jira.rest.client.internal.async.AsynchronousJiraRestClientFactory;
import com.atlassian.util.concurrent.Promise;
/**
* JiraAPI acts as a single point to communicate with JIRA and extract the
* version information for use with the ChangelogBuilder.
*
* @author mleonard87
*
*/
public class JiraAPI {
private final String username_, password_;
private final URI jiraServerURI_;
private String jql_;
private String descriptionField;
private LinkedList<VersionInfo> versionList_;
private VersionInfoCache cache_;
/**
* JiraAPI Constructor that accepts the basic information require to
* communicate with a JIRA instance.
*
* @param username The username used to authenticate with JIRA.
* @param password The password used to authenticate with JIRA.
* @param URL The URL pointing to the JIRA instance.
* @param descriptionField The name of the field in JIRA to use as the
* changelog description.
*/
public JiraAPI(String username, String password, String URL, String jql, String descriptionField) {
username_ = username;
password_ = password;
if (jql.equals("")) {
jql_ = "";
} else {
jql_ = " and (" + jql + ")";
}
this.descriptionField = descriptionField;
URI tempURI = null;
try {
tempURI = new URI(URL);
} catch (URISyntaxException e) {
Logger.err("The JIRA URL supplied - \"" + URL + "\" is not a valid URI.");
} finally {
jiraServerURI_ = tempURI;
}
}
/**
* Sets the version info cache
*
* @param cache The version info cache.
*/
public void setVersionInfoCache(VersionInfoCache cache) {
cache_ = cache;
}
/**
* Communicate with JIRA to find all versions prior to the version you are
* currently building for each version found get a list of issues fixed in
* that version from the serialized java object cache on disk, or pull the
* list of issues from JIRA. Finally add all these versions to a LinkedList
* and sort by date descending.
*
* @param projectKey The key used for the project in JIRA.
* @param versionLabel The version label from JIRA (belonging to the project
* specified with projectKey that you are currently building).
*/
public void fetchVersionDetails(String projectKey, String versionLabel) {
try {
// Create the initial JIRA connection.
Logger.log("Establishing JIRA API connection for generating changelog to " + jiraServerURI_ + ".");
JiraRestClientFactory factory = new AsynchronousJiraRestClientFactory();
final JiraRestClient restClient = factory.createWithBasicHttpAuthentication(jiraServerURI_, username_, password_);
// Get an instance of the JIRA Project
Logger.log("Obtaining project information via JIRA API.");
ProjectRestClient projectClient = restClient.getProjectClient();
Promise<Project> promise = projectClient.getProject(projectKey);
Project proj = promise.claim();
// Get a list of versions for this project and identify the one were
// currently trying to build.
Logger.log("Determining if the version '" + versionLabel + "' exists in JIRA.");
Version buildVersion = null;
for (Version v : proj.getVersions()) {
if (v.getName().equals(versionLabel)) {
buildVersion = v;
}
}
if (buildVersion == null) {
Logger.err("Could not find a version in JIRA matching the version label argument: \"" + versionLabel + "\".");
System.exit(1);
}
Logger.log("Version '" + versionLabel + "' found in JIRA.");
versionList_ = new LinkedList<VersionInfo>();
// For each version determine if it was released prior to the current
// build. If so get a list of issues fixed in it and
// and add it to a LinkedList. If the version has been previously cached
// the data will be pulled from the cache.
// the version being currently built will never be pulled from the cache.
for (Version v : proj.getVersions()) {
if ((v.getReleaseDate() != null && v.isReleased()) || v.getName().equals(versionLabel)) {
DateTime versionReleaseDate = v.getReleaseDate();
if (versionReleaseDate == null) {
versionReleaseDate = new DateTime();
}
if (v.getName().equals(versionLabel) || versionReleaseDate.isBefore(buildVersion.getReleaseDate()) || versionReleaseDate.isEqual(buildVersion.getReleaseDate())) {
Logger.log("Version '" + v.getName() + "' was released before '" + versionLabel + "' - generating changelog.");
// Attempt to get the changelog from the cache. If it can't be found
// or were trying
// to generate a changelog for the current version then
// build/rebuild and cache.
VersionInfo vi = null;
if (cache_ != null && !v.getName().equals(versionLabel)) {
vi = cache_.getCached(v.getName());
}
if (vi == null) {
LinkedList<Change> issueList = new LinkedList<Change>();
Logger.log("Obtaining issues related to '" + v.getName() + "' via JIRA API.");
SearchResult sr = null;
try {
Promise<SearchResult> searchJql = restClient.getSearchClient().searchJql("project = '" + projectKey + "' and fixVersion = '" + v.getName() + "'" + jql_);
sr = searchJql.claim();
for (BasicIssue bi : sr.getIssues()) {
Logger.log("Obtaining further issue details for issue '" + bi.getKey() + "' via JIRA API.");
Promise<Issue> issue = restClient.getIssueClient().getIssue(bi.getKey());
Issue i = issue.claim();
// Add this issue
String changelogDescription;
String type = null;
try {
changelogDescription = i.getFieldByName(descriptionField).getValue().toString();
} catch (NullPointerException npe) {
// Changelog Description doesn't exist as a field for this
// issue so just default to the summary.
changelogDescription = i.getSummary();
}
type = i.getIssueType().getName();
issueList.add(new Change(i.getKey(), changelogDescription, type));
}
} catch (RestClientException jqlErr) {
Logger.log("The additional JQL string supplied was either invalid or returned no results. Ignoring additional JQL.");
Promise<SearchResult> searchJql = restClient.getSearchClient().searchJql("project = '" + projectKey + "' and fixVersion = '" + v.getName() + "'" + jql_);
sr = searchJql.claim();
for (BasicIssue bi : sr.getIssues()) {
Logger.log("Obtaining further issue details for issue '" + bi.getKey() + "' via JIRA API.");
Promise<Issue> issue = restClient.getIssueClient().getIssue(bi.getKey());
Issue i = issue.claim();
// Add this issue
String changelogDescription = null;
String type = null;
try {
changelogDescription = i.getFieldByName(descriptionField).getValue().toString();
} catch (NullPointerException npe) {
// Changelog Description doesn't exist as a field for this
// issue so just default to the summary.
changelogDescription = i.getSummary();
}
type = i.getIssueType().getName();
issueList.add(new Change(i.getKey(), changelogDescription, type));
}
}
vi = new VersionInfo(v.getName(), v.getDescription(), versionReleaseDate.toDate(), issueList);
if (cache_ != null) {
cache_.cache(vi);
}
}
versionList_.add(vi);
}
}
}
// Sort the version by release date descending.
Logger.log("Sorting versions by release date descending.");
Collections.sort(versionList_, new DateComparator());
} catch (RestClientException uh) {
// Awful error handling block becase all errors seem to be of exception
// type RestClientException.
if (uh.getMessage().startsWith("No project could be found with key")) {
Logger.err("A project with the key \"" + projectKey + "\" could not be found in the JIRA instance at \"" + jiraServerURI_ + "\".");
}
if (uh.getMessage().startsWith("com.sun.jersey.api.client.ClientHandlerException: java.net.UnknownHostException:")) {
Logger.err("A JIRA instance could not be reached at \"" + jiraServerURI_ + "\".");
}
uh.printStackTrace();
System.exit(1);
}
}
/**
* Gets the list of JIRA versions to be included in the changelog, as well as
* their issues.
*
* @return LinkedList of VersionInfo instances giving details about each JIRA
* version to be included in the change log and their issues. Ordered
* descending by release date.
*/
public LinkedList<VersionInfo> getVersionInfoList() {
return versionList_;
}
}
/**
* Simple comparator that can be used to order by Date objects descending.
*
* @author leonmi
*
*/
class DateComparator implements Comparator<VersionInfo> {
/**
* Compare the value of two dates. Used to sort issues and versions by date
*
* @param a A date to compare with
* @param b Another date to compare
* @return -1 if <param>a</param> > <param>b</param>, 1 if <param>a</param>
* < <param>b</param>, otherwise 0
*/
public int compare(VersionInfo a, VersionInfo b) {
if (a.getReleaseDate().after(b.getReleaseDate())) {
return -1;
} else if (a.getReleaseDate().before(b.getReleaseDate())) {
return 1;
} else {
return -(a.getName().compareTo(b.getName()));
}
}
}
|
package modules.test;
import org.junit.Assert;
import org.junit.Test;
import org.skyve.domain.HierarchicalBean;
import org.skyve.domain.PersistentBean;
import org.skyve.domain.PolymorphicPersistentBean;
import modules.test.MappedExtensionJoinedStrategy.MappedExtensionJoinedStrategyExtension;
import modules.test.MappedExtensionSingleStrategy.MappedExtensionSingleStrategyExtension;
import modules.test.domain.AllAttributesPersistent;
import modules.test.domain.Hierarchical;
import modules.test.domain.MappedBase;
import modules.test.domain.MappedExtensionJoinedStrategy;
import modules.test.domain.MappedExtensionSingleStrategy;
import modules.test.domain.MappedSubclassedJoinedStrategy;
import modules.test.domain.MappedSubclassedSingleStrategy;
public class GenerationTests extends AbstractSkyveTest {
@Test
@SuppressWarnings({ "cast", "static-method" })
public void testGenerateExtensionHierarchy() {
MappedBase mb = new MappedBase();
MappedExtensionSingleStrategy mess = MappedExtensionSingleStrategy.newInstance();
MappedExtensionJoinedStrategy mejs = MappedExtensionJoinedStrategy.newInstance();
MappedSubclassedSingleStrategy msss = new MappedSubclassedSingleStrategy();
MappedSubclassedJoinedStrategy msjs = new MappedSubclassedJoinedStrategy();
Assert.assertTrue(new AllAttributesPersistent() instanceof PersistentBean);
Assert.assertTrue(new Hierarchical() instanceof HierarchicalBean<?>);
Assert.assertTrue(mb instanceof PersistentBean);
Assert.assertFalse(MappedBase.class.isAnnotationPresent(PolymorphicPersistentBean.class)); // mapped bean
Assert.assertTrue(mejs instanceof MappedBase);
Assert.assertTrue(MappedExtensionJoinedStrategy.class.isAnnotationPresent(PolymorphicPersistentBean.class)); // joined strategy
Assert.assertTrue(mess instanceof MappedBase);
Assert.assertTrue(MappedExtensionSingleStrategy.class.isAnnotationPresent(PolymorphicPersistentBean.class)); // single strategy
Assert.assertTrue(msjs instanceof MappedExtensionJoinedStrategyExtension);
Assert.assertFalse(MappedExtensionJoinedStrategyExtension.class.isAnnotationPresent(PolymorphicPersistentBean.class)); // no subclasses
Assert.assertTrue(msss instanceof MappedExtensionSingleStrategyExtension);
Assert.assertFalse(MappedExtensionSingleStrategyExtension.class.isAnnotationPresent(PolymorphicPersistentBean.class)); // no subclasses
}
}
|
package virtualgameshelf.gui;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import com.opencsv.CSVReader;
import javafx.application.*;
import javafx.beans.value.*;
import javafx.geometry.*;
import javafx.scene.*;
import javafx.scene.control.*;
import javafx.scene.control.Alert.AlertType;
import javafx.scene.control.ButtonBar.ButtonData;
import javafx.scene.image.*;
import javafx.scene.layout.*;
import javafx.stage.*;
import virtualgameshelf.backend.domain.Game;
import virtualgameshelf.backend.domain.GameList;
public class VirtualGameShelf extends Application {
/** User's complete list of games. Static to allow for global access */
public static GameList gameList = new GameList();
/** Used to look up full names of consoles. ("PS4" -> "PlayStation 4") */
protected static Map<String, String> systemNameMap;
/** Visual display of gameList */
private static VBox gameListVBox;
public static void main(String[] args) {
// Bugfix: Prevents JavaFX ComboBox freezing on Windows 10
System.setProperty("glass.accessible.force", "false");
launch(args);
}
@Override
public void start(Stage mainStage) throws Exception {
mainStage.setTitle("Virtual Game Shelf");
// add application icon
// mainStage.getIcons().add(new Image("icons/"));
BorderPane root = new BorderPane();
Scene mainScene = new Scene(root, 400, 600);
mainStage.setScene(mainScene);
// used to add a scroll bar to the page
ScrollPane scroll = new ScrollPane();
scroll.setFitToWidth(true);
root.setCenter(scroll);
// add stylesheet
mainScene.getStylesheets().add("stylesheet.css");
// top menu bar
MainMenuBar menuBar = new MainMenuBar(mainStage);
root.setTop(menuBar);
initializeSystemNameMap();
// used to display games in library
gameListVBox = new VBox();
gameListVBox.setPadding( new Insets(16) );
gameListVBox.setSpacing(16);
gameListVBox.setAlignment( Pos.CENTER );
scroll.setContent(gameListVBox);
// used to add games to the library
MenuButton addGameButton = createAddGameButton();
root.setMargin(addGameButton, new Insets(16));
root.setBottom(addGameButton);
root.setAlignment(addGameButton, Pos.CENTER_RIGHT);
mainStage.show();
}
public MenuButton createAddGameButton() {
MenuButton addGameButton = new MenuButton(null, new ImageView("icons/add.png"));
addGameButton.setPopupSide(Side.TOP);
MenuItem manualAdd = new MenuItem("Manually Add New Game");
manualAdd.setOnAction(e -> {
NewGameWindow newGameWindow = new NewGameWindow();
Game newGame = newGameWindow.showAndAddGame();
if (newGame != null) {
// Add title to game list
gameList.addGame(newGame);
displayGameConsoles();
}
});
MenuItem autoAdd = new MenuItem("Add New Game Via Steam");
autoAdd.setOnAction(e -> System.out.println("This feature is not yet available."));
addGameButton.getItems().addAll(manualAdd, autoAdd);
// rotates the image 45 degrees when the menu button is "active"
addGameButton.showingProperty().addListener((ChangeListener<Boolean>) (observable, oldValue, newValue) -> {
if (newValue) {
addGameButton.setRotate(45.0);
} else {
addGameButton.setRotate(0.0);
}
});
return addGameButton;
}
/** Used to display the list of games */
public static void displayGameConsoles() {
TreeItem<String> rootNode = new TreeItem<>("Consoles", new ImageView("icons/gamepad.png"));
rootNode.setExpanded(true);
for (Game g : gameList.getGameList()) {
TreeItem<String> gameLeaf = new TreeItem<>(g.getName() + "\n" + g.getSystem() +
"\n" + g.getCompletion() + "\n" + g.getHours() + " hours played \n" + g.getRating() + " star(s)");
boolean found = false;
String displayName = getSystemDisplayName(g.getSystem());
for (TreeItem<String> depNode : rootNode.getChildren()) {
if (depNode.getValue().contentEquals(displayName)) {
depNode.getChildren().add(gameLeaf);
found = true;
break;
}
}
if (!found) {
TreeItem<String> depNode = new TreeItem<>(displayName, new ImageView("icons/vintage.png"));
rootNode.getChildren().add(depNode);
depNode.getChildren().add(gameLeaf);
}
}
TreeView<String> treeView = new TreeView<>(rootNode);
treeView.getSelectionModel().selectedItemProperty().addListener((ChangeListener<TreeItem<String>>) (observable, oldValue, newValue) -> {
TreeItem<String> selectedItem = newValue;
// Ensures 'edit game' prompt only shows for games
if (selectedItem.isLeaf() && selectedItem.getParent() != null) {
displayEditGameAlert(selectedItem);
}
});
// Clear and redraw game list
gameListVBox.getChildren().clear();
gameListVBox.getChildren().add(treeView);
}
/** Initialize hashmap to lookup console names. (e.g.: "PS4" -> "PlayStation 4") */
private void initializeSystemNameMap() {
systemNameMap = new LinkedHashMap<>();
List<String[]> systemList = null;
// Read in systemList from file
try {
CSVReader reader = new CSVReader(new FileReader("resources/system_list.csv"));
systemList = reader.readAll();
reader.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
// Populate systemName hash map
if (systemList != null) {
for (String[] s : systemList) {
String name = s[0];
String displayName = s[1];
if (name != null && !name.equals("name")
&& displayName != null && !displayName.equals("displayName")) {
systemNameMap.put(name, displayName);
}
}
}
}
/**
* Returns game system's full display name
* @param system Abbreviated system name. [ie: PS4]
* @return Full system display name. [ie: PlayStation 4].
*/
public static String getSystemDisplayName(String system) {
if (systemNameMap.containsKey(system)) {
return systemNameMap.get(system);
} else {
return system;
}
}
/** Display option to edit or delete a game */
public static void displayEditGameAlert(TreeItem<String> selectedItem) {
int index = -1;
Alert alert = new Alert(AlertType.CONFIRMATION);
alert.setHeaderText(null); // TODO: Use game title for header
alert.setContentText("Would you like to:");
ButtonType deleteGame = new ButtonType("Delete Game");
ButtonType editGame = new ButtonType("Edit Game");
ButtonType buttonTypeCancel = new ButtonType("Cancel", ButtonData.CANCEL_CLOSE);
alert.getButtonTypes().setAll(deleteGame, editGame, buttonTypeCancel);
Optional<ButtonType> result = alert.showAndWait();
if (result.get() == deleteGame){
index = getGameIndex(selectedItem);
gameList.getGameList().remove(index);
displayGameConsoles();
}
else if (result.get() == editGame) {
index = getGameIndex(selectedItem);
ArrayList<Game> tempGameList = (ArrayList<Game>) gameList.getGameList().clone();
NewGameWindow newGameWindow = new NewGameWindow(tempGameList.get(index) );
Game newGame = newGameWindow.showAndAddGame();
if (newGame != null) {
// Add title to game list
gameList.getGameList().remove(index);
gameList.addGame(newGame);
displayGameConsoles();
}
}
else {
// ... user chose CANCEL or closed the dialog
}
}
/** Takes TreeItem and returns its location in GameList as an int */
public static int getGameIndex(TreeItem<String> selectedItem) {
int index = -1;
for (Game g : gameList.getGameList()) {
if (selectedItem.getValue().equals(g.gameString())) {
for (int i = 0; i < gameList.getGameList().size(); i++) {
if (g.gameString().equals(gameList.getGameList().get(i).gameString())) {
index = i;
}
}
}
}
return index;
}
}
|
package cn.ymex.cute.kits;
import android.app.Activity;
import android.content.Context;
import android.support.annotation.IdRes;
import android.support.annotation.LayoutRes;
import android.support.annotation.NonNull;
import android.support.v7.widget.Toolbar;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.TextView;
import java.util.ArrayList;
public class UiKit {
private static boolean sInitialed;
private static Context mContext;
public static int SCREEN_WIDTH_PX;
public static int SCREEN_HEIGHT_PX;
public static float SCREEN_DENSITY;
public static int SCREEN_WIDTH_DP;
public static int SCREEN_HEIGHT_DP;
public static void init(Context context) {
if (sInitialed || context == null) {
throw new IllegalArgumentException("context not allow null");
}
mContext = context;
sInitialed = true;
DisplayMetrics dm = new DisplayMetrics();
WindowManager wm = (WindowManager) context
.getSystemService(Context.WINDOW_SERVICE);
wm.getDefaultDisplay().getMetrics(dm);
UiKit.SCREEN_WIDTH_PX = dm.widthPixels;
UiKit.SCREEN_HEIGHT_PX = dm.heightPixels;
UiKit.SCREEN_DENSITY = dm.density;
UiKit.SCREEN_WIDTH_DP = (int) (UiKit.SCREEN_WIDTH_PX / dm.density);
UiKit.SCREEN_HEIGHT_DP = (int) (UiKit.SCREEN_HEIGHT_PX / dm.density);
}
/**
* @param dp to px
* @return
*/
public static int dp2px(float dp) {
final float scale = SCREEN_DENSITY;
return (int) (dp * scale + 0.5f);
}
public static int designedDP2px(float designedDp) {
// density = 160 w=320 * h 480 1dp = 1px
if (SCREEN_WIDTH_DP != 320) {
designedDp = designedDp * SCREEN_WIDTH_DP / 320f;
}
return dp2px(designedDp);
}
public static float px2dp(int px) {
final float scale = SCREEN_DENSITY;
return (px / scale + 0.5f);
}
public static void setPadding(final View view, float left, float top,
float right, float bottom) {
view.setPadding(designedDP2px(left), dp2px(top), designedDP2px(right),
dp2px(bottom));
}
/**
* find view by id from view
* @param view
* @param id
* @return
* @return: T
*/
public static <T extends View> T find(@NonNull View view,@IdRes int id) {
return (T) view.findViewById(id);
}
/**
* find view by id from activity
* @param act
* @param id
* @return
* @return: T
*/
public static <T extends View> T find(@NonNull Activity act,@IdRes int id) {
return (T) act.findViewById(id);
}
/**
* inflate xml layout
* @param context
* @param resource
* @return
*/
public static <T extends View>View inflate(@NonNull Context context, @LayoutRes int resource) {
return (T) LayoutInflater.from(context).inflate(resource, null);
}
/**
* inflate xml layout
* @param context
* @param resource
* @param viewGroup
* @return
*/
public static <T extends View>View inflate(@NonNull Context context, @NonNull int resource, ViewGroup viewGroup) {
return (T) LayoutInflater.from(context).inflate(resource, viewGroup);
}
/**
* set actionbar title in center
* @param toolbar
*/
public static void setToolbarTitleInCenter(@NonNull final Toolbar toolbar) {
CharSequence title = toolbar.getTitle();
ArrayList<View> outViews = new ArrayList<>(1);
toolbar.findViewsWithText(outViews, title, View.FIND_VIEWS_WITH_TEXT);
if (!outViews.isEmpty()) {
final TextView titleView = (TextView) outViews.get(0);
Toolbar.LayoutParams params = new Toolbar.LayoutParams(
Toolbar.LayoutParams.WRAP_CONTENT, Toolbar.LayoutParams.WRAP_CONTENT);
params.gravity = Gravity.CENTER;
titleView.setGravity(Gravity.CENTER);
titleView.setLayoutParams(params);
toolbar.requestLayout();
}
}
}
|
package net.oesterholt.taskgnome;
import java.awt.Dimension;
import java.awt.Image;
import java.awt.Point;
import java.awt.Window;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.net.URL;
import java.util.Vector;
import java.util.prefs.Preferences;
import javax.swing.AbstractAction;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JMenuItem;
import javax.swing.SwingUtilities;
import net.oesterholt.taskgnome.sync.Synchronizer;
import net.oesterholt.taskgnome.utils.TgLogger;
import org.apache.log4j.Appender;
import org.apache.log4j.BasicConfigurator;
import org.apache.log4j.ConsoleAppender;
import org.apache.log4j.FileAppender;
import org.apache.log4j.Level;
import org.apache.log4j.Logger;
import org.apache.log4j.PatternLayout;
public class TaskGnome {
static Logger logger=TgLogger.getLogger(TaskGnome.class);
public static void setIconImage(Window w) {
URL url=TaskGnome.class.getResource("/net/oesterholt/taskgnome/resources/icon.png");
ImageIcon icon = new ImageIcon(url);
w.setIconImage(icon.getImage());
}
public static ImageIcon toolBarIcon(String name) {
URL url=TaskGnome.class.getResource(
String.format("/net/oesterholt/taskgnome/resources/%s.png",name)
);
return new ImageIcon(
new ImageIcon(url).getImage().getScaledInstance(48, 48, Image.SCALE_SMOOTH)
);
}
@SuppressWarnings("serial")
public static JButton toolBarAction(final String action,final ActionListener l) {
JButton b=new JButton(new AbstractAction(action,TaskGnome.toolBarIcon(action)) {
public void actionPerformed(ActionEvent e) {
ActionEvent E=new ActionEvent(e.getSource(), e.getID(), action);
l.actionPerformed(E);
}
});
b.setFocusable(false);
b.setHideActionText(true);
return b;
}
public static JMenuItem menu(final String action, final String txt,ActionListener l) {
JMenuItem mnu=new JMenuItem(txt);
mnu.addActionListener(l);
mnu.setActionCommand(action);
return mnu;
}
public static void setWindowPosition(Point where,Dimension size) {
Preferences prefs=Preferences.userNodeForPackage(TaskGnome.class);
prefs.putInt("wx", where.x);
prefs.putInt("wy", where.y);
prefs.putInt("width", size.width);
prefs.putInt("height", size.height);
}
public static Point getPrevWindowLocation() {
Preferences prefs=Preferences.userNodeForPackage(TaskGnome.class);
int x=prefs.getInt("wx", -1);
int y=prefs.getInt("wy", -1);
if (x<0 || y<0) {
return null;
} else {
return new Point(x,y);
}
}
public static Dimension getPrevWindowSize() {
Preferences prefs=Preferences.userNodeForPackage(TaskGnome.class);
int w=prefs.getInt("width", -1);
int h=prefs.getInt("height", -1);
if (w<0 || h<0) {
return null;
} else {
return new Dimension(w,h);
}
}
public static void setLastPath(String f) {
Preferences prefs=Preferences.userNodeForPackage(TaskGnome.class);
prefs.put("lastpath",f);
}
public static Vector<String> getRecentlyUsed() {
Preferences prefs=Preferences.userNodeForPackage(TaskGnome.class);
Integer i;
Vector<String> r=new Vector<String>();
for(i=0;i<5;i++) {
String key="recently_"+i;
String f=prefs.get(key, null);
if (f!=null) {
r.add(f);
}
}
return r;
}
public static void main(String argv[]) {
File td = new File(System.getProperty("user.home"), ".taskgnome");
if (!td.exists()) {
td.mkdirs();
}
BasicConfigurator.configure();
Logger.getRootLogger().getLoggerRepository().resetConfiguration();
File logfile = new File(td.getAbsolutePath(), "taskgnome.log");
logfile.delete();
FileAppender fa = new FileAppender();
fa.setName("TaskGnomeLogger");
fa.setFile(logfile.getAbsolutePath());
fa.setLayout(new PatternLayout("%d %-5p [%c{1}] %m%n"));
fa.setThreshold(Level.DEBUG);
fa.setAppend(true);
fa.activateOptions();
Logger.getRootLogger().addAppender(fa);
logger.debug("TaskGnome started");
TaskWindow u;
try {
u = new TaskWindow(td.getAbsolutePath());
SwingUtilities.invokeLater(u);
} catch (Exception e) {
e.printStackTrace();
System.exit(1);
}
}
}
|
package gnu.expr;
import gnu.bytecode.*;
import gnu.mapping.*;
public class ProcInitializer extends Initializer
{
LambdaExp proc;
public ProcInitializer(LambdaExp lexp, Compilation comp, Field field) {
this.field = field;
proc = lexp;
LambdaExp heapLambda = field.getStaticFlag() ? comp.getModule()
: lexp.getOwningLambda() ;
if (heapLambda instanceof ModuleExp && comp.isStatic()) {
next = comp.clinitChain;
comp.clinitChain = this;
} else {
next = heapLambda.initChain;
heapLambda.initChain = this;
}
}
/** Create and load a ModuleMethod for the given procedure. */
public static void emitLoadModuleMethod(LambdaExp proc, Compilation comp) {
Declaration pdecl = proc.nameDecl;
Object pname = pdecl == null ? proc.getName() : pdecl.getSymbol();
ModuleMethod oldproc = null;
if (comp.immediate && pname != null
&& pdecl != null && pdecl.context instanceof ModuleExp) {
// In interactive mode allow dynamic rebinding of procedures.
// If there is an existing ModuleMethod binding, re-use it.
Environment env = Environment.getCurrent();
Symbol sym = pname instanceof Symbol ? (Symbol) pname
: Symbol.make("", pname.toString().intern());
Object property = comp.getLanguage().getEnvPropertyFor(proc.nameDecl);
Object old = env.get(sym, property, null);
if (old instanceof ModuleMethod) {
String moduleName =
((ModuleMethod) old).module.getClass().getName();
if (moduleName.startsWith(ModuleManager.interactiveClassPrefix)
|| moduleName.equals(comp.moduleClass.getName()))
oldproc = (ModuleMethod) old;
}
}
CodeAttr code = comp.getCode();
ClassType procClass = proc.usingCallContext()
? Compilation.typeModuleMethodWithContext
: Compilation.typeModuleMethod;
Method initModuleMethod;
if (oldproc == null) {
code.emitNew(procClass);
code.emitDup(1);
initModuleMethod = procClass.getDeclaredMethod("<init>", 4);
} else {
comp.compileConstant(oldproc, Target.pushValue(procClass));
initModuleMethod = Compilation.typeModuleMethod.getDeclaredMethod("init", 4);
}
LambdaExp owning = proc.getNeedsClosureEnv() ? proc.getOwningLambda()
: comp.getModule();
if (owning instanceof ClassExp && owning.staticLinkField != null)
code.emitLoad(code.getCurrentScope().getVariable(1));
else if (! (owning instanceof ModuleExp))
owning.loadHeapFrame(comp);
else if (comp.moduleClass == comp.mainClass
&& ! comp.method.getStaticFlag())
code.emitPushThis();
else {
if (comp.moduleInstanceVar == null
|| comp.moduleInstanceVar.dead()) {
comp.moduleInstanceVar
= code.locals.current_scope.addVariable(code,
comp.moduleClass,
"$instance");
if (comp.moduleClass != comp.mainClass && ! comp.isStatic()) {
code.emitNew(comp.moduleClass);
code.emitDup(comp.moduleClass);
code.emitInvokeSpecial(comp.moduleClass.constructor);
if (comp.moduleInstanceMainField == null)
comp.moduleInstanceMainField =
comp.moduleClass.addField("$main", comp.mainClass, 0);
code.emitDup(comp.moduleClass);
code.emitPushThis();
code.emitPutField(comp.moduleInstanceMainField);
} else
code.emitGetStatic(comp.moduleInstanceMainField);
code.emitStore(comp.moduleInstanceVar);
}
code.emitLoad(comp.moduleInstanceVar);
}
code.emitPushInt(proc.getSelectorValue(comp));
comp.compileConstant(pname, Target.pushObject);
// If there are keyword arguments, we treat that as "unlimited" maxArgs,
// so that ModuleBody.matchX methods call matchN. A kludge, I guess.
code.emitPushInt(proc.min_args
| ((proc.keywords == null ? proc.max_args : -1) << 12));
code.emitInvoke(initModuleMethod);
if (proc.properties != null) {
int len = proc.properties.length;
for (int i = 0; i < len; i += 2) {
Object key = proc.properties[i];
// Skip "name" property since we've taken care of that specially.
if (key != null && key != PropertySet.nameKey) {
Object val = proc.properties[i+1];
code.emitDup(1);
Field pfld = null;
if (key == Procedure.validateApplyKey)
pfld = Compilation.typeProcedure
.getDeclaredField("validateApplyKey");
else if (key == Procedure.validateXApplyKey)
pfld = Compilation.typeProcedure
.getDeclaredField("validateXApplyKey");
else if (key == Procedure.compilerXKey)
pfld = Compilation.typeProcedure
.getDeclaredField("compilerXKey");
if (pfld != null)
code.emitGetStatic(pfld);
else
comp.compileConstant(key);
Target target = Target.pushObject;
if (val instanceof Expression)
((Expression) val).compile(comp, target);
else
comp.compileConstant(val, target);
Method m = (ClassType.make("gnu.mapping.PropertySet")
.getDeclaredMethod("setProperty", 2));
code.emitInvokeVirtual(m);
}
}
}
}
public void emit(Compilation comp) {
CodeAttr code = comp.getCode();
if (! field.getStaticFlag())
code.emitPushThis();
emitLoadModuleMethod(proc, comp);
if (field.getStaticFlag())
code.emitPutStatic(field);
else
code.emitPutField(field);
}
public void reportError(String message, Compilation comp) {
String saveFile = comp.getFileName();
int saveLine = comp.getLineNumber();
int saveColumn = comp.getColumnNumber();
comp.setLocation(proc);
String name = proc.getName();
StringBuffer sbuf = new StringBuffer(message);
if (name == null)
sbuf.append("unnamed procedure");
else {
sbuf.append("procedure ");
sbuf.append(name);
}
comp.error('e', sbuf.toString());
comp.setLine(saveFile, saveLine, saveColumn);
}
}
|
package eu.e43.impeller.activity;
import org.htmlcleaner.CompactHtmlSerializer;
import org.htmlcleaner.ContentNode;
import org.htmlcleaner.HtmlCleaner;
import org.htmlcleaner.TagNode;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.accounts.Account;
import android.app.ProgressDialog;
import android.content.ContentValues;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.AssetFileDescriptor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Point;
import android.location.Address;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.v4.app.NavUtils;
import android.text.Html;
import android.text.Spanned;
import android.util.Log;
import android.view.Display;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.Toast;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.Iterator;
import eu.e43.impeller.Constants;
import eu.e43.impeller.LocationServices;
import eu.e43.impeller.PostTask;
import eu.e43.impeller.content.PumpContentProvider;
import eu.e43.impeller.ogp.MetaElement;
import eu.e43.impeller.ogp.OpenGraph;
import eu.e43.impeller.uikit.LocationAdapter;
import eu.e43.impeller.uikit.PumpHtml;
import eu.e43.impeller.R;
import eu.e43.impeller.Utils;
import eu.e43.impeller.account.OAuth;
import oauth.signpost.OAuthConsumer;
public class PostActivity extends ActivityWithAccount {
public static final String ACTION_REPLY = "eu.e43.impeller.action.REPLY";
private static final String TAG = "PostActivity";
// EXTRA_HTML_TEXT is a 4.2 feature
private static final String EXTRA_HTML_TEXT = "android.intent.extra.HTML_TEXT";
private static final int TYPE_NOTE = 0;
private static final int TYPE_COMMENT = 1;
private static final int TYPE_IMAGE = 2;
private static final int TYPE_VIDEO = 3;
// UI widgets
EditText m_title;
ImageView m_postType;
ImageView m_imageView;
EditText m_content;
Spinner m_location;
CheckBox m_isPublic;
ProgressDialog m_progress;
LocationAdapter m_locations;
// Object properties
int m_type; // objectType
Uri m_imageUri; // Image URI
JSONObject m_inReplyTo = null; // inReplyTo
String m_embedCode; // embedCode
JSONObject m_videoLink = null; // Video medialink
// Object properties which the UI may change:
String m_proposedTitle;
String m_proposedText;
String m_proposedHTML;
String m_sourceLink;
protected void onCreateEx(Bundle _) {
setContentView(R.layout.activity_post);
}
@Override
protected void gotAccount(Account a_, Bundle _) {
Intent intent = getIntent();
String type = intent.getType();
Log.v(TAG, "MIME Type is " + type);
if(type == null || type.startsWith("text/")) {
if(ACTION_REPLY.equals(intent.getAction())) {
m_type = TYPE_COMMENT;
} else {
m_type = TYPE_NOTE;
}
} else if(type.startsWith("image/")) {
m_type = TYPE_IMAGE;
m_imageUri = (Uri) intent.getParcelableExtra(Intent.EXTRA_STREAM);
if(m_imageUri == null) {
Log.e(TAG, "No image URI?");
setResult(RESULT_CANCELED);
finish();
}
} else {
setResult(RESULT_CANCELED);
finish();
}
if(intent.hasExtra(Intent.EXTRA_SUBJECT)) {
m_proposedTitle = intent.getStringExtra(Intent.EXTRA_SUBJECT);
}
if(intent.hasExtra(EXTRA_HTML_TEXT)) {
m_proposedHTML = intent.getStringExtra(EXTRA_HTML_TEXT);
}
if(intent.hasExtra(Intent.EXTRA_TEXT)) {
m_proposedText = intent.getStringExtra(Intent.EXTRA_TEXT);
}
if(m_proposedText != null) {
Log.v(TAG, "Has proposed text... " + m_proposedText);
try {
URI uri = new URI(m_proposedText.trim());
Log.v(TAG, "Proposed text is an URL " + uri);
if("http".equals(uri.getScheme()) || "https".equals(uri.getScheme())) {
Log.v(TAG, "Performing discovery on URL " + uri);
new DiscoveryTask().execute(uri);
return;
}
} catch(URISyntaxException ex) {
// Pass
}
}
// else
prepareUi();
}
private void prepareUi() {
// Prepare after doing full discovery
m_title = (EditText) findViewById(R.id.title);
m_imageView = (ImageView) findViewById(R.id.image);
m_location = (Spinner) findViewById(R.id.location);
m_content = (EditText) findViewById(R.id.content);
m_isPublic = (CheckBox) findViewById(R.id.isPublic);
m_postType = (ImageView) findViewById(R.id.postType);
switch(m_type) {
case TYPE_NOTE:
case TYPE_COMMENT:
m_postType.setImageResource(R.drawable.ic_note_dark);
break;
case TYPE_IMAGE:
m_postType.setImageResource(R.drawable.ic_picture_dark);
break;
case TYPE_VIDEO:
m_postType.setImageResource(R.drawable.ic_video_dark);
break;
}
if(m_imageUri != null) {
m_imageView.setVisibility(View.VISIBLE);
if(isImageLink()) {
getImageLoader().setImage(m_imageView, m_imageUri.toString());
} else {
SetupImageTask t = new SetupImageTask();
t.execute();
}
}
if(m_proposedTitle != null) {
m_title.setText(m_proposedTitle);
}
if(m_proposedHTML != null) {
PumpHtml.setFromHtml(this, m_content, m_proposedHTML);
} else if(m_proposedText != null) {
m_content.setText(m_proposedText);
}
if(ACTION_REPLY.equals(getIntent().getAction())) {
setTitle(R.string.title_activity_post_reply);
m_title.setVisibility(View.GONE);
m_title.setText("");
try {
m_inReplyTo = new JSONObject(getIntent().getStringExtra("inReplyTo"));
} catch (JSONException e) {
Log.e(TAG, "Error parsing inReplyTo", e);
setResult(RESULT_CANCELED);
finish();
}
}
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
if(Integer.parseInt(prefs.getString(Constants.PREF_MY_LOCATION, "0"))
>= Constants.MY_LOCATION_FETCH) {
m_locations = new LocationAdapter(this, m_location);
m_location.setAdapter(m_locations);
} else {
findViewById(R.id.location_container).setVisibility(View.GONE);
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.post, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch(item.getItemId()) {
case android.R.id.home:
NavUtils.navigateUpFromSameTask(this);
return true;
case R.id.action_post:
onPost();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
@Override
protected void gotAccount(Account a) {
m_account = a;
}
private void dismissProgress() {
if(m_progress != null) {
m_progress.dismiss();
m_progress = null;
}
}
@Override
protected void onDestroy() {
dismissProgress();
super.onDestroy();
}
private boolean isImageLink() {
return m_imageUri.getScheme().equals("http") || m_imageUri.getScheme().equals("https");
}
private class DiscoveryTask extends AsyncTask<URI, Void, Void> {
ProgressDialog m_discoveryProgress;
@Override
protected void onPreExecute() {
m_discoveryProgress = ProgressDialog.show(PostActivity.this,
getString(R.string.just_a_moment),
getString(R.string.getting_information), true);
}
@Override
protected Void doInBackground(URI... params) {
try {
OpenGraph og = new OpenGraph(params[0].toString(), true);
for(MetaElement elem : og.getProperties()) {
Log.d(TAG, elem.getNamespace().getPrefix() + ":" + elem.getProperty() + "=" + elem.getContent());
}
String image = og.getContent("image");
if(m_imageUri == null && image != null) {
if(og.getContent("image:secure_url") != null) {
m_imageUri = Uri.parse(og.getContent("image:secure_url"));
Log.i(TAG, "Has og:image:secure_url " + m_imageUri);
} else {
m_imageUri = Uri.parse(image);
Log.i(TAG, "Has og:image " + m_imageUri);
}
} else Log.i(TAG, "No og:image");
if(og.getContent("url") != null) {
m_sourceLink = og.getContent("url");
Log.i(TAG, "og:url " + m_sourceLink);
} else {
m_sourceLink = params[0].toString();
}
if(og.getContent("title") != null)
m_proposedTitle = og.getContent("title");
if(m_proposedText == null && og.getContent("description") != null)
m_proposedText = og.getContent("description");
String ogType = og.getContent("type");
if(ogType != null && ogType.equals("video")) {
String videoUrl = og.getContent("video");
if(videoUrl != null) {
if(og.getContent("video:secure_url") != null)
videoUrl = og.getContent("video:secure_url");
String videoType = og.getContent("video:type");
if(videoUrl == null) {
// pass
} else {
m_type = TYPE_VIDEO;
HtmlCleaner cleaner = new HtmlCleaner();
TagNode embedCode;
Integer width = null;
Integer height = null;
if(og.getContent("video:width") != null)
width = Integer.parseInt(og.getContent("video:width"));
if(og.getContent("video:height") != null)
height = Integer.parseInt(og.getContent("video:height"));
if(videoType != null && !videoType.startsWith("video/")) {
embedCode = new TagNode("object");
embedCode.addAttribute("data", videoUrl);
embedCode.addAttribute("type", videoType);
// For Flash on downlevel browsers
TagNode movieParam = new TagNode("param");
movieParam.addAttribute("movie", videoUrl);
embedCode.addChild(movieParam);
|
package org.basex.api.xqj;
import static org.basex.Text.*;
import static org.basex.util.Token.*;
import java.io.IOException;
import javax.xml.stream.XMLStreamConstants;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamReader;
import org.basex.BaseX;
import org.basex.build.Builder;
import org.basex.build.Parser;
import org.basex.core.ProgressException;
import org.basex.core.Prop;
import org.basex.io.IO;
import org.basex.util.Atts;
import org.basex.util.TokenBuilder;
final class XMLStreamWrapper extends Parser {
/** Element counter. */
int nodes;
/** XML stream reader. */
XMLStreamReader reader;
/**
* Constructor.
* @param sr stream reader
* @param pr database properties
*/
XMLStreamWrapper(final XMLStreamReader sr, final Prop pr) {
super(IO.DUMMY, pr);
reader = sr;
}
@Override
public void parse(final Builder builder) throws IOException {
try {
builder.startDoc(token(io.name()));
while(reader.hasNext()) {
final int kind = reader.next();
switch(kind) {
case XMLStreamConstants.START_ELEMENT:
final int as = reader.getAttributeCount();
final Atts att = new Atts();
for(int a = 0; a < as; a++) {
att.add(token(reader.getAttributeLocalName(a)),
token(reader.getAttributeValue(a)));
}
builder.startElem(token(reader.getLocalName()), att);
nodes++;
break;
case XMLStreamConstants.END_ELEMENT:
builder.endElem(token(reader.getLocalName()));
break;
case XMLStreamConstants.CHARACTERS:
builder.text(new TokenBuilder(reader.getText()), false);
nodes++;
break;
case XMLStreamConstants.PROCESSING_INSTRUCTION:
builder.pi(new TokenBuilder(reader.getPITarget() + ' ' +
reader.getPIData()));
nodes++;
break;
case XMLStreamConstants.COMMENT:
builder.comment(new TokenBuilder(reader.getText()));
nodes++;
break;
case XMLStreamConstants.END_DOCUMENT:
break;
default:
throw new IOException("Unknown node kind " + kind);
}
}
builder.endDoc();
} catch(final ProgressException ex) {
throw ex;
} catch(final IOException ex) {
ex.printStackTrace();
throw ex;
} catch(final XMLStreamException ex) {
final IOException ioe = new IOException(ex.getMessage());
ioe.setStackTrace(ex.getStackTrace());
throw ioe;
}
}
@Override
public String tit() {
return PROGCREATE;
}
@Override
public String det() {
return BaseX.info(NODESPARSED, io.name(), nodes);
}
@Override
public double prog() {
return nodes / 1000000d % 1;
}
}
|
package org.broad.igv.track;
import org.apache.commons.math.stat.StatUtils;
import org.apache.log4j.Logger;
import org.broad.igv.PreferenceManager;
import org.broad.igv.feature.Exon;
import org.broad.igv.feature.IGVFeature;
import org.broad.igv.feature.genome.Genome;
import org.broad.igv.ui.*;
import org.broad.igv.ui.panel.FrameManager;
import org.broad.igv.ui.panel.IGVPopupMenu;
import org.broad.igv.ui.panel.ReferenceFrame;
import org.broad.igv.util.stats.KMPlotFrame;
import org.broad.tribble.Feature;
import org.broad.igv.renderer.*;
import org.broad.igv.ui.util.MessageUtils;
import org.broad.igv.ui.util.UIUtilities;
import javax.swing.*;
import javax.swing.event.PopupMenuEvent;
import javax.swing.event.PopupMenuListener;
import java.awt.*;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.StringSelection;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.Set;
/**
* @author jrobinso
*/
public class TrackMenuUtils {
static Logger log = Logger.getLogger(TrackMenuUtils.class);
final static String LEADING_HEADING_SPACER = " ";
private static final WindowFunction[] ORDERED_WINDOW_FUNCTIONS = new WindowFunction[]{
WindowFunction.min,
WindowFunction.percentile2,
WindowFunction.percentile10,
WindowFunction.median,
WindowFunction.mean,
WindowFunction.percentile90,
WindowFunction.percentile98,
WindowFunction.max,
WindowFunction.none
};
/**
* Return a popup menu with items applicable to the collection of tracks.
*
* @param tracks
* @return
*/
public static IGVPopupMenu getPopupMenu(final Collection<Track> tracks, String title, TrackClickEvent te) {
if (log.isDebugEnabled()) {
log.debug("enter getPopupMenu");
}
//JidePopupMenu menu = new JidePopupMenu();
IGVPopupMenu menu = new IGVPopupMenu();
JLabel popupTitle = new JLabel(LEADING_HEADING_SPACER + title, JLabel.CENTER);
popupTitle.setFont(UIConstants.boldFont);
if (popupTitle != null) {
menu.add(popupTitle);
menu.addSeparator();
}
addStandardItems(menu, tracks, te);
menu.addPopupMenuListener(new PopupMenuListener() {
public void popupMenuWillBecomeVisible(PopupMenuEvent popupMenuEvent) {
}
public void popupMenuWillBecomeInvisible(PopupMenuEvent popupMenuEvent) {
close();
}
public void popupMenuCanceled(PopupMenuEvent popupMenuEvent) {
close();
}
private void close() {
IGV.getInstance().getTrackManager().clearSelections();
IGV.getInstance().repaint();
}
});
return menu;
}
public static void addStandardItems(JPopupMenu menu, Collection<Track> tracks, TrackClickEvent te) {
boolean hasDataTracks = false;
boolean hasFeatureTracks = false;
boolean hasOtherTracks = false;
for (Track track : tracks) {
// TODO -- this is ugly, refactor to remove instanceof
if (track instanceof DataTrack) {
hasDataTracks = true;
} else if (track instanceof FeatureTrack) {
hasFeatureTracks = true;
} else {
hasOtherTracks = true;
}
if (hasDataTracks && hasFeatureTracks && hasOtherTracks) {
break;
}
}
boolean featureTracksOnly = hasFeatureTracks && !hasDataTracks && !hasOtherTracks;
boolean dataTracksOnly = !hasFeatureTracks && hasDataTracks && !hasOtherTracks;
addSharedItems(menu, tracks, hasFeatureTracks);
menu.addSeparator();
if (dataTracksOnly) {
addDataItems(menu, tracks);
} else if (featureTracksOnly) {
addFeatureItems(menu, tracks, te);
}
menu.addSeparator();
menu.add(getRemoveMenuItem(tracks));
}
public static void addZoomItems(JPopupMenu menu, final ReferenceFrame frame) {
if (FrameManager.isGeneListMode()) {
JMenuItem item = new JMenuItem("Reset panel to '" + frame.getName() + "'");
item.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
frame.reset();
// TODO -- paint only panels for this frame
}
});
menu.add(item);
}
JMenuItem zoomOutItem = new JMenuItem("Zoom out");
zoomOutItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
frame.incrementZoom(-1);
}
});
menu.add(zoomOutItem);
JMenuItem zoomInItem = new JMenuItem("Zoom in");
zoomInItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
frame.incrementZoom(1);
}
});
menu.add(zoomInItem);
}
/**
* Return popup menu with items applicable to data tracks
*
* @return
*/
private static void addDataItems(JPopupMenu menu, final Collection<Track> tracks) {
if (log.isDebugEnabled()) {
log.debug("enter getDataPopupMenu");
}
final String[] labels = {"Heatmap", "Bar Chart", "Scatterplot", "Line Plot"};
final Class[] renderers = {HeatmapRenderer.class, BarChartRenderer.class,
ScatterplotRenderer.class, LineplotRenderer.class
};
//JLabel popupTitle = new JLabel(LEADING_HEADING_SPACER + title, JLabel.CENTER);
JLabel rendererHeading = new JLabel(LEADING_HEADING_SPACER + "Type of Graph", JLabel.LEFT);
rendererHeading.setFont(UIConstants.boldFont);
menu.add(rendererHeading);
// Get existing selections
Set<Class> currentRenderers = new HashSet<Class>();
for (Track track : tracks) {
if (track.getRenderer() != null) {
currentRenderers.add(track.getRenderer().getClass());
}
}
// Create and renderer menu items
for (int i = 0; i < labels.length; i++) {
JCheckBoxMenuItem item = new JCheckBoxMenuItem(labels[i]);
final Class rendererClass = renderers[i];
if (currentRenderers.contains(rendererClass)) {
item.setSelected(true);
}
item.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
changeRenderer(tracks, rendererClass);
}
});
menu.add(item);
}
menu.addSeparator();
// Get union of all valid window functions for selected tracks
Set<WindowFunction> avaibleWindowFunctions = new HashSet();
for (Track track : tracks) {
avaibleWindowFunctions.addAll(track.getAvailableWindowFunctions());
}
avaibleWindowFunctions.add(WindowFunction.none);
// dataPopupMenu.addSeparator();
// Collection all window functions for selected tracks
Set<WindowFunction> currentWindowFunctions = new HashSet<WindowFunction>();
for (Track track : tracks) {
if (track.getWindowFunction() != null) {
currentWindowFunctions.add(track.getWindowFunction());
}
}
if (!avaibleWindowFunctions.isEmpty() || !currentWindowFunctions.isEmpty()) {
JLabel statisticsHeading = new JLabel(LEADING_HEADING_SPACER + "Windowing Function", JLabel.LEFT);
statisticsHeading.setFont(UIConstants.boldFont);
menu.add(statisticsHeading);
for (final WindowFunction wf : ORDERED_WINDOW_FUNCTIONS) {
JCheckBoxMenuItem item = new JCheckBoxMenuItem(wf.getDisplayName());
if (avaibleWindowFunctions.contains(wf) || currentWindowFunctions.contains(wf)) {
if (currentWindowFunctions.contains(wf)) {
item.setSelected(true);
}
item.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
changeStatType(wf.toString(), tracks);
}
});
menu.add(item);
}
}
menu.addSeparator();
}
menu.add(getDataRangeItem(tracks));
menu.add(getHeatmapScaleItem(tracks));
if (tracks.size() > 0) {
menu.add(getLogScaleItem(tracks));
}
menu.add(getAutoscaleItem(tracks));
menu.add(getShowDataRangeItem(tracks));
menu.add(getChangeKMPlotItem(tracks));
}
/**
* Return popup menu with items applicable to feature tracks
*
* @return
*/
private static void addFeatureItems(JPopupMenu featurePopupMenu, final Collection<Track> tracks, TrackClickEvent te) {
addDisplayModeItems(tracks, featurePopupMenu);
if (tracks.size() == 1) {
Track t = tracks.iterator().next();
Feature f = t.getFeatureAtMousePosition(te);
if (f != null) {
featurePopupMenu.addSeparator();
// If we are over an exon, copy its sequence instead of the entire feature.
if (f instanceof IGVFeature) {
double position = te.getChromosomePosition();
Collection<Exon> exons = ((IGVFeature) f).getExons();
if (exons != null) {
for (Exon exon : exons) {
if (position > exon.getStart() && position < exon.getEnd()) {
f = exon;
break;
}
}
}
}
featurePopupMenu.add(getCopyDetailsItem(f, te));
featurePopupMenu.add(getCopySequenceItem(f));
}
}
featurePopupMenu.addSeparator();
featurePopupMenu.add(getChangeFeatureWindow(tracks));
}
/**
* Popup menu with items applicable to both feature and data tracks
*
* @return
*/
private static void addSharedItems(JPopupMenu menu, final Collection<Track> tracks, boolean hasFeatureTracks) {
//JLabel trackSettingsHeading = new JLabel(LEADING_HEADING_SPACER + "Track Settings", JLabel.LEFT);
//trackSettingsHeading.setFont(boldFont);
//menu.add(trackSettingsHeading);
menu.add(getTrackRenameItem(tracks));
String colorLabel = hasFeatureTracks
? "Change Track Color..." : "Change Track Color (Positive Values)...";
JMenuItem item = new JMenuItem(colorLabel);
item.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
changeTrackColor(tracks);
}
});
menu.add(item);
if (!hasFeatureTracks) {
// Change track color by attribute
item = new JMenuItem("Change Track Color (Negative Values)...");
item.setToolTipText(
"Change the alternate track color. This color is used when graphing negative values");
item.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
changeAltTrackColor(tracks);
}
});
menu.add(item);
}
menu.add(getChangeTrackHeightItem(tracks));
menu.add(getChangeFontSizeItem(tracks));
}
private static void changeStatType(String statType, Collection<Track> selectedTracks) {
for (Track track : selectedTracks) {
track.setWindowFunction(WindowFunction.valueOf(statType));
}
refresh();
}
public static JMenuItem getTrackRenameItem(final Collection<Track> selectedTracks) {
// Change track height by attribute
JMenuItem item = new JMenuItem("Rename Track...");
item.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
UIUtilities.invokeOnEventThread(new Runnable() {
public void run() {
renameTrack(selectedTracks);
}
});
}
});
if (selectedTracks.size() > 1) {
item.setEnabled(false);
}
return item;
}
private static JMenuItem getHeatmapScaleItem(final Collection<Track> selectedTracks) {
JMenuItem item = new JMenuItem("Set Heatmap Scale...");
item.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
if (selectedTracks.size() > 0) {
ContinuousColorScale colorScale = selectedTracks.iterator().next().getColorScale();
HeatmapScaleDialog dlg = new HeatmapScaleDialog(IGV.getMainFrame(), colorScale);
dlg.setVisible(true);
if (!dlg.isCanceled()) {
colorScale = dlg.getColorScale();
// dlg.isFlipAxis());
for (Track track : selectedTracks) {
track.setColorScale(colorScale);
}
IGV.getInstance().repaint();
}
}
}
});
return item;
}
public static JMenuItem getDataRangeItem(final Collection<Track> selectedTracks) {
JMenuItem item = new JMenuItem("Set Data Range...");
item.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
if (selectedTracks.size() > 0) {
// Create a datarange that spans the extent of prev tracks range
float mid = 0;
float min = Float.MAX_VALUE;
float max = Float.MIN_VALUE;
boolean drawBaseline = false;
for (Track t : selectedTracks) {
DataRange dr = t.getDataRange();
min = Math.min(min, dr.getMinimum());
max = Math.max(max, dr.getMaximum());
mid += dr.getBaseline();
}
mid /= selectedTracks.size();
if (mid < min) {
mid = min;
} else if (mid > max) {
min = max;
}
DataRange prevAxisDefinition = new DataRange(min, mid, max, drawBaseline);
DataRangeDialog dlg = new DataRangeDialog(IGV.getMainFrame(), prevAxisDefinition);
dlg.setVisible(true);
if (!dlg.isCanceled()) {
min = Math.min(dlg.getMax(), dlg.getMin());
max = Math.max(dlg.getMin(), dlg.getMax());
mid = dlg.getBase();
mid = Math.max(min, Math.min(mid, max));
DataRange axisDefinition = new DataRange(dlg.getMin(), dlg.getBase(), dlg.getMax());
for (Track track : selectedTracks) {
track.setDataRange(axisDefinition);
if (track instanceof DataTrack) {
((DataTrack) track).setAutoscale(false);
}
}
IGV.getInstance().repaint();
}
}
}
});
return item;
}
private static JMenuItem getDrawBorderItem() {
// Change track height by attribute
final JCheckBoxMenuItem drawBorderItem = new JCheckBoxMenuItem("Draw borders");
drawBorderItem.setSelected(FeatureTrack.isDrawBorder());
drawBorderItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
FeatureTrack.setDrawBorder(drawBorderItem.isSelected());
IGV.getInstance().repaintDataPanels();
}
});
return drawBorderItem;
}
private static JMenuItem getLogScaleItem(final Collection<Track> selectedTracks) {
// Change track height by attribute
final JCheckBoxMenuItem logScaleItem = new JCheckBoxMenuItem("Log scale");
final boolean logScale = selectedTracks.iterator().next().getDataRange().isLog();
logScaleItem.setSelected(logScale);
logScaleItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
DataRange.Type scaleType = logScaleItem.isSelected() ?
DataRange.Type.LOG :
DataRange.Type.LINEAR;
for (Track t : selectedTracks) {
t.getDataRange().setType(scaleType);
}
IGV.getInstance().repaintDataPanels();
}
});
return logScaleItem;
}
private static JMenuItem getAutoscaleItem(final Collection<Track> selectedTracks) {
final JCheckBoxMenuItem autoscaleItem = new JCheckBoxMenuItem("Autoscale");
if (selectedTracks.size() == 0) {
autoscaleItem.setEnabled(false);
} else {
boolean autoScale = false;
for (Track t : selectedTracks) {
if (t instanceof DataTrack && ((DataTrack) t).isAutoscale()) {
autoScale = true;
break;
}
}
autoscaleItem.setSelected(autoScale);
autoscaleItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
boolean autoScale = autoscaleItem.isSelected();
for (Track t : selectedTracks) {
if (t instanceof DataTrack) {
((DataTrack) t).setAutoscale(autoScale);
}
}
IGV.getInstance().repaintDataPanels();
}
});
}
return autoscaleItem;
}
private static JMenuItem getShowDataRangeItem(final Collection<Track> selectedTracks) {
final JCheckBoxMenuItem item = new JCheckBoxMenuItem("Show Data Range");
if (selectedTracks.size() == 0) {
item.setEnabled(false);
} else {
boolean showDataRange = true;
for (Track t : selectedTracks) {
if (!t.isShowDataRange()) {
showDataRange = false;
break;
}
}
item.setSelected(showDataRange);
item.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
boolean showDataRange = item.isSelected();
for (Track t : selectedTracks) {
if (t instanceof DataTrack) {
((DataTrack) t).setShowDataRange(showDataRange);
}
}
IGV.getInstance().repaintDataPanels();
}
});
}
return item;
}
public static void addDisplayModeItems(final Collection<Track> tracks, JPopupMenu menu) {
// Find "most representative" state from track collection
int expCount = 0;
int sqCount = 0;
int collCount = 0;
for (Track track : tracks) {
switch (track.getDisplayMode()) {
case EXPANDED:
expCount++;
break;
case SQUISHED:
sqCount++;
break;
case COLLAPSED:
collCount++;
break;
}
}
Track.DisplayMode currentMode = null;
if (expCount > sqCount && expCount > collCount) {
currentMode = Track.DisplayMode.EXPANDED;
} else if (sqCount > expCount && sqCount > collCount) {
currentMode = Track.DisplayMode.SQUISHED;
} else {
currentMode = Track.DisplayMode.COLLAPSED;
}
ButtonGroup group = new ButtonGroup();
JRadioButtonMenuItem m1 = new JRadioButtonMenuItem("Expanded");
m1.setSelected(currentMode == Track.DisplayMode.EXPANDED);
m1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
setTrackDisplayMode(tracks, Track.DisplayMode.EXPANDED);
refresh();
}
});
JRadioButtonMenuItem m2 = new JRadioButtonMenuItem("Squished");
m2.setSelected(currentMode == Track.DisplayMode.SQUISHED);
m2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
setTrackDisplayMode(tracks, Track.DisplayMode.SQUISHED);
refresh();
}
});
JRadioButtonMenuItem m3 = new JRadioButtonMenuItem("Collapsed");
m3.setSelected(currentMode == Track.DisplayMode.COLLAPSED);
m3.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
setTrackDisplayMode(tracks, Track.DisplayMode.COLLAPSED);
refresh();
}
});
group.add(m1);
group.add(m2);
group.add(m3);
menu.add(m3);
menu.add(m2);
menu.add(m1);
}
private static void setTrackDisplayMode(Collection<Track> tracks, Track.DisplayMode mode) {
for (Track t : tracks) {
t.setDisplayMode(mode);
}
}
public static JMenuItem getRemoveMenuItem(final Collection<Track> selectedTracks) {
boolean multiple = selectedTracks.size() > 1;
JMenuItem item = new JMenuItem("Remove Track" + (multiple ? "s" : ""));
item.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
if (selectedTracks.isEmpty()) {
return;
}
StringBuffer buffer = new StringBuffer();
for (Track track : selectedTracks) {
buffer.append("\n\t");
buffer.append(track.getName());
}
String deleteItems = buffer.toString();
JTextArea textArea = new JTextArea();
textArea.setEditable(false);
JScrollPane scrollPane = new JScrollPane(textArea);
textArea.setText(deleteItems);
JOptionPane optionPane = new JOptionPane(scrollPane,
JOptionPane.PLAIN_MESSAGE,
JOptionPane.YES_NO_OPTION);
optionPane.setPreferredSize(new Dimension(550, 500));
JDialog dialog = optionPane.createDialog(IGV.getMainFrame(), "Remove The Following Tracks");
dialog.setVisible(true);
Object choice = optionPane.getValue();
if ((choice == null) || (JOptionPane.YES_OPTION != ((Integer) choice).intValue())) {
return;
}
IGV.getInstance().getTrackManager().removeTracks(selectedTracks);
IGV.getInstance().doRefresh();
}
});
return item;
}
public static void changeRenderer(final Collection<Track> selectedTracks, Class rendererClass) {
for (Track track : selectedTracks) {
// TODO -- a temporary hack to facilitate RNAi development
if (track.getTrackType() == TrackType.RNAI) {
if (rendererClass == BarChartRenderer.class) {
rendererClass = RNAiBarChartRenderer.class;
}
}
track.setRendererClass(rendererClass);
}
refresh();
}
public static void renameTrack(final Collection<Track> selectedTracks) {
if (selectedTracks.isEmpty()) {
return;
}
Track t = selectedTracks.iterator().next();
String newName = JOptionPane.showInputDialog(IGV.getMainFrame(), "Enter new name: ", t.getName());
if (newName == null || newName.trim() == "") {
return;
}
t.setName(newName);
refresh();
}
public static void changeTrackHeight(final Collection<Track> selectedTracks) {
if (selectedTracks.isEmpty()) {
return;
}
final String parameter = "Track height";
int value = getIntValue(parameter, getRepresentativeTrackHeight(selectedTracks));
if (value == Integer.MIN_VALUE) {
return;
}
value = Math.max(0, value);
for (Track track : selectedTracks) {
track.setHeight(value);
}
refresh();
}
public static void changeFeatureVisibilityWindow(final Collection<Track> selectedTracks) {
Collection<Track> featureTracks = new ArrayList(selectedTracks.size());
for (Track t : selectedTracks) {
if (t instanceof FeatureTrack) {
featureTracks.add(t);
}
}
if (featureTracks.isEmpty()) {
return;
}
int origValue = featureTracks.iterator().next().getVisibilityWindow();
int origValueKB = Math.max(1, origValue / 1000);
int value = getIntValue("Visibility window (kb)", origValueKB);
if (value == Integer.MIN_VALUE) {
return;
}
for (Track track : featureTracks) {
track.setVisibilityWindow((int) (value * 1000));
}
refresh();
}
public static void changeFontSize(final Collection<Track> selectedTracks) {
if (selectedTracks.isEmpty()) {
return;
}
final String parameter = "Font size";
int defaultValue = selectedTracks.iterator().next().getFontSize();
int value = getIntValue(parameter, defaultValue);
if (value == Integer.MIN_VALUE) {
return;
}
for (Track track : selectedTracks) {
track.setFontSize(value);
}
refresh();
}
public static int getIntValue(String parameter, int value) {
while (true) {
String height = JOptionPane.showInputDialog(
IGV.getMainFrame(), parameter + ": ",
String.valueOf(value));
if ((height == null) || height.trim().equals("")) {
return Integer.MIN_VALUE; // <= the logical "null" value
}
try {
value = Integer.parseInt(height);
return value;
} catch (NumberFormatException numberFormatException) {
JOptionPane.showMessageDialog(IGV.getMainFrame(),
parameter + " must be an integer number.");
}
}
}
public static void changeTrackColor(final Collection<Track> selectedTracks) {
if (selectedTracks.isEmpty()) {
return;
}
Color currentSelection = selectedTracks.iterator().next().getColor();
Color color = UIUtilities.showColorChooserDialog(
"Select Track Color (Positive Values)",
currentSelection);
if (color != null) {
for (Track track : selectedTracks) {
track.setColor(color);
}
refresh();
}
}
public static void changeAltTrackColor(final Collection<Track> selectedTracks) {
if (selectedTracks.isEmpty()) {
return;
}
Color currentSelection = selectedTracks.iterator().next().getColor();
Color color = UIUtilities.showColorChooserDialog(
"Select Track Color (Negative Values)",
currentSelection);
if (color == null) {
return;
}
for (Track track : selectedTracks) {
track.setAltColor(color);
}
refresh();
}
public static JMenuItem getCopyDetailsItem(final Feature f, final TrackClickEvent evt) {
JMenuItem item = new JMenuItem("Copy Details to Clipboard");
item.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
ReferenceFrame frame = evt.getFrame();
int mouseX = evt.getMouseEvent().getX();
double location = frame.getChromosomePosition(mouseX);
if (f instanceof IGVFeature) {
String details = ((IGVFeature) f).getValueString(location, null);
if (details != null) {
details = details.replace("<br>", System.getProperty("line.separator"));
details += System.getProperty("line.separator") +
f.getChr() + ":" + (f.getStart() + 1) + "-" + f.getEnd();
StringSelection stringSelection = new StringSelection(details);
Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
clipboard.setContents(stringSelection, null);
}
}
}
});
return item;
}
public static JMenuItem getCopySequenceItem(final Feature f) {
JMenuItem item = new JMenuItem("Copy Sequence");
item.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
Genome genome = IGV.getInstance().getGenomeManager().getCurrentGenome();
String chr = f.getChr();
int start = f.getStart();
int end = f.getEnd();
byte[] seqBytes = genome.getSequence(chr, start, end);
if (seqBytes == null) {
MessageUtils.showMessage("Sequence not available");
} else {
String sequence = new String(seqBytes);
StringSelection stringSelection = new StringSelection(sequence);
Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
clipboard.setContents(stringSelection, null);
}
}
});
return item;
}
/**
* Return a representative track height to use as the default. For now
* using the median track height.
*
* @return
*/
public static int getRepresentativeTrackHeight(Collection<Track> tracks) {
double[] heights = new double[tracks.size()];
int i = 0;
for (Track track : tracks) {
heights[i] = track.getHeight();
i++;
}
int medianTrackHeight = (int) Math.round(StatUtils.percentile(heights, 50));
if (medianTrackHeight > 0) {
return medianTrackHeight;
}
return PreferenceManager.getInstance().getAsInt(PreferenceManager.INITIAL_TRACK_HEIGHT);
}
public static void refresh() {
IGV.getInstance().showLoadedTrackCount();
IGV.getInstance().doRefresh();
}
public static JMenuItem getChangeTrackHeightItem(final Collection<Track> selectedTracks) {
// Change track height by attribute
JMenuItem item = new JMenuItem("Change Track Height...");
item.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
changeTrackHeight(selectedTracks);
}
});
return item;
}
public static JMenuItem getChangeKMPlotItem(final Collection<Track> selectedTracks) {
// Change track height by attribute
JMenuItem item = new JMenuItem("Kaplan-Meier Plot...");
item.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
KMPlotFrame frame = new KMPlotFrame(selectedTracks);
frame.setVisible(true);
}
});
return item;
}
public static JMenuItem getChangeFeatureWindow(final Collection<Track> selectedTracks) {
// Change track height by attribute
JMenuItem item = new JMenuItem("Set Feature Visibility Window...");
item.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
changeFeatureVisibilityWindow(selectedTracks);
}
});
return item;
}
public static JMenuItem getChangeFontSizeItem(final Collection<Track> selectedTracks) {
// Change track height by attribute
JMenuItem item = new JMenuItem("Change Font Size...");
item.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
changeFontSize(selectedTracks);
}
});
return item;
}
}
|
package org.ensembl.healthcheck;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.logging.Logger;
import org.ensembl.healthcheck.testcase.EnsTestCase;
import org.ensembl.healthcheck.testcase.MultiDatabaseTestCase;
import org.ensembl.healthcheck.testcase.OrderedDatabaseTestCase;
import org.ensembl.healthcheck.testcase.Repair;
import org.ensembl.healthcheck.testcase.SingleDatabaseTestCase;
/**
* <p>
* TestRunner is a base class that provides utilities for running tests -
* logging, the ability to find and run tests from certain locations, etc.
* </p>
*/
public class TestRunner {
/** List that holds an instance of each test. */
protected List allTests;
/** The List of group names (as Strings) that will be run. */
protected List<String> groupsToRun;
/** The logger to use for this class */
protected static Logger logger = Logger.getLogger("HealthCheckLogger");
/** Output level used by ReportManager */
protected int outputLevel = ReportLine.PROBLEM;
// EG change to public to allow Database runner to modify this
/** The name of the file where configuration is stored */
// public static String propertiesFile = "";
private static String propertiesFile = "database.properties";
public static String getPropertiesFile() {
return propertiesFile;
}
public static void setPropertiesFile(String propertiesFile) {
TestRunner.propertiesFile = propertiesFile;
}
/** Flag to determine whether repairs will be shown if appropriate */
protected boolean showRepair = false;
/** Flag to determine whether repairs will be carried out if appropriate */
protected boolean doRepair = false;
/** Creates a new instance of TestRunner */
public TestRunner() {
groupsToRun = new ArrayList<String>();
} // TestRunner
/**
* Run appropriate tests against databases. Also run show/repair methods if
* the test implements the Repair interface and the appropriate flags are
* set.
*
* @param databaseRegistry
* The DatabaseRegistry to use.
* @param testRegistry
* The TestRegistry to use.
* @param skipSlow
* If true, skip long-running tests.
*/
protected void runAllTests(DatabaseRegistry databaseRegistry,
TestRegistry testRegistry, boolean skipSlow) {
int numberOfTestsRun = 0;
// Single-database tests
// run the appropriate tests on each of them
for (DatabaseRegistryEntry database : databaseRegistry.getAll()) {
// If a healthcheck database is being used and nothing has been propagated for the database being tested, skip
if (ReportManager.usingDatabase()) {
boolean propagated = ReportManager.hasPropagated(database);
if (!propagated) {
continue;
}
}
for (SingleDatabaseTestCase testCase : testRegistry.getAllSingle(
groupsToRun, database.getType())) {
if (!testCase.isLongRunning()
|| (testCase.isLongRunning() && !skipSlow)) {
try {
ReportManager.startTestCase(testCase, database);
logger.info("Running " + testCase.getName() + " ["
+ database.getName() + "]");
testCase.types();
boolean result = testCase.run(database);
ReportManager
.finishTestCase(testCase, result, database);
logger.info(testCase.getName() + " ["
+ database.getName() + "]"
+ (result ? "PASSED" : "FAILED"));
checkRepair(testCase, database);
numberOfTestsRun++;
} catch (Throwable e) {
logger.warning("Could not execute test "
+ testCase.getName() + " on "
+ database.getName() + ": " + e.getMessage());
}
} else {
logger.info("Skipping long-running test "
+ testCase.getName());
}
} // foreach test
} // foreach DB
// Multi-database tests
// here we just pass the whole DatabaseRegistry to each test
// and let the test decide what to do
for (MultiDatabaseTestCase testCase : testRegistry
.getAllMulti(groupsToRun)) {
if (!testCase.isLongRunning()
|| (testCase.isLongRunning() && !skipSlow)) {
try {
ReportManager.startTestCase(testCase, null);
logger.info("Starting test " + testCase.getName() + " ");
testCase.types();
boolean result = testCase.run(databaseRegistry);
ReportManager.finishTestCase(testCase, result, null);
logger.info(testCase.getName() + " "
+ (result ? "PASSED" : "FAILED"));
numberOfTestsRun++;
} catch (Throwable e) {
//TODO If we had a throwable then we should mark the test as failed
// catch and log unexpected exceptions
logger.warning("Could not execute test "
+ testCase.getName() + ": " + e.getMessage());
}
} else {
logger.info("Skipping long-running test " + testCase.getName());
}
} // foreach test
// Ordered database tests
// getAll() should give back databases in the order they were specified
// on the command line
DatabaseRegistryEntry[] orderedDatabases = databaseRegistry.getAll();
for (OrderedDatabaseTestCase testCase : testRegistry
.getAllOrdered(groupsToRun)) {
ReportManager.startTestCase(testCase, null);
try {
boolean result = testCase.run(orderedDatabases);
ReportManager.finishTestCase(testCase, result, null);
logger.info(testCase.getName() + " "
+ (result ? "PASSED" : "FAILED"));
} catch (Throwable e) {
//TODO If we had a throwable then we should mark the test as failed
// catch and log unexpected exceptions
logger.warning("Could not execute test " + testCase.getName()
+ ": " + e.getMessage());
}
numberOfTestsRun++;
} // foreach test
if (numberOfTestsRun == 0) {
logger.warning("Warning: no tests were run.");
}
} // runAllTests
/**
* Check if the given testcase can repair errors on the given database.
*/
private void checkRepair(EnsTestCase testCase,
DatabaseRegistryEntry database) {
// check for show/do repair
if (testCase.canRepair()) {
if (showRepair) {
((Repair) testCase).show(database);
}
if (doRepair) {
((Repair) testCase).repair(database);
}
}
} // checkRepair
/**
* Get the union of all the test groups.
*
* @param tests
* The tests to check.
* @return An array containing the names of all the groups that any member
* of tests is a member of.
*/
public String[] listAllGroups(List<EnsTestCase> tests) {
ArrayList<String> g = new ArrayList<String>();
Iterator<EnsTestCase> it = tests.iterator();
while (it.hasNext()) {
List<String> thisTestsGroups = it.next().getGroups();
Iterator<String> it2 = thisTestsGroups.iterator();
while (it2.hasNext()) {
String group = it2.next();
if (!g.contains(group)) {
g.add(group);
}
}
}
return (String[]) g.toArray(new String[g.size()]);
} // listAllGroups
/**
* List all the tests in a particular group.
*
* @param tests
* The tests to check.
* @param group
* The group name to check.
* @return An array containing the names whatever tests are a member of
* group.
*/
public String[] listTestsInGroup(List tests, String group) {
ArrayList g = new ArrayList();
Iterator it = tests.iterator();
while (it.hasNext()) {
EnsTestCase test = (EnsTestCase) it.next();
if (test.inGroup(group)) {
g.add(test.getShortTestName());
}
}
return (String[]) g.toArray(new String[g.size()]);
} // listTestsInGroup
/**
* Print (to stdout) out a list of test reports, keyed by the test type.
*
* @param level
* The lowest report level (see ReportLine) to print. Reports
* with a level lower than this are not printed.
* @param printFailureText
* If true, print result of getFailureText() for each test.
*/
public void printReportsByTest(int level, boolean printFailureText) {
System.out.println("\n
Map map = ReportManager.getAllReportsByTestCase(level);
Set keys = map.keySet();
Iterator it = keys.iterator();
while (it.hasNext()) {
String test = (String) it.next();
List lines = (List) map.get(test);
if (lines.size() > 0) {
System.out.print("\n" + test);
// print failure text if appropriate
String failureText = "";
try {
EnsTestCase testObj = (EnsTestCase) (Class.forName(test)
.newInstance());
String teamResponsible = testObj
.getPrintableTeamResponsibleString();
if (teamResponsible == null) {
teamResponsible = "Not set";
}
System.out.println(" [Team responsible: " + teamResponsible
+ "]");
failureText = testObj.getFailureText();
if (testObj.getEffect() != null) {
failureText += testObj.getEffect() + "\n";
}
if (testObj.getFix() != null) {
failureText += testObj.getFix() + "\n";
}
} catch (Exception e) {
System.err.println("Error, can't instantiate object ");
e.printStackTrace();
}
if (printFailureText && failureText.length() > 0) {
System.out.println("Note: " + failureText);
}
Iterator it2 = lines.iterator();
while (it2.hasNext()) {
ReportLine reportLine = (ReportLine) it2.next();
if (reportLine.getLevel() >= level) {
String dbName = reportLine.getDatabaseName();
if (dbName.equals("no_database")) {
dbName = "";
} else {
dbName = reportLine.getDatabaseName() + ": ";
}
System.out.println(" " + dbName
+ reportLine.getMessage());
} // if level
} // while it2
} // if lines
} // while it
} // printReportsByTest
/**
* Print (to stdout) a list of test results, ordered by database.
*
* @param level
* The minimum level of report to print - see ReportLine. Reports
* below this level are not printed.
*/
public void printReportsByDatabase(int level) {
System.out.println("\n
Map map = ReportManager.getAllReportsByDatabase(level);
Set keys = map.keySet();
Iterator it = keys.iterator();
while (it.hasNext()) {
String key = (String) it.next();
System.out.print("\n" + key + ": ");
List lines = (List) map.get(key);
int nProblems = lines.size();
if (nProblems == 0) {
System.out.println("No problems found");
} else {
String s = (nProblems == 1) ? "" : "s";
System.out.println(nProblems + " problem" + s + " found");
Iterator it2 = lines.iterator();
while (it2.hasNext()) {
ReportLine reportLine = (ReportLine) it2.next();
if (reportLine.getLevel() >= level) {
System.out.println(" "
+ reportLine.getShortTestCaseName() + ": "
+ reportLine.getMessage());
} // if level
} // while it2
} // if nProblems
} // while it
} // printReportsByDatabase
/**
* Set the outputLevel variable based on an input string (probably from the
* command line)
*
* @param str
* The output level to use.
*/
protected void setOutputLevel(String str) {
String lstr = str.toLowerCase();
if (lstr.equals("all")) {
outputLevel = ReportLine.ALL;
} else if (lstr.equals("none")) {
outputLevel = ReportLine.NONE;
} else if (lstr.equals("problem")) {
outputLevel = ReportLine.PROBLEM;
} else if (lstr.equals("correct")) {
outputLevel = ReportLine.CORRECT;
} else if (lstr.equals("warning")) {
outputLevel = ReportLine.WARNING;
} else if (lstr.equals("info")) {
outputLevel = ReportLine.INFO;
} else {
logger.warning("Output level " + str
+ " not recognised; using 'all'");
}
} // setOutputLevel
/**
* Set the output level.
*
* @param l
* The new output level.
*/
public void setOutputLevel(int l) {
outputLevel = l;
logger.finest("Set outputLevel to " + outputLevel);
} // setOutputLevel
/**
* Get the current output level.
*
* @return The current output level. See ReportLine.
*/
public int getOutputLevel() {
return outputLevel;
} // getOutputLevel
} // TestRunner
|
package org.exist.storage;
//import java.io.EOFException;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import org.apache.log4j.Logger;
import org.exist.EXistException;
import org.exist.collections.Collection;
import org.exist.dom.AttrImpl;
import org.exist.dom.DocumentImpl;
import org.exist.dom.DocumentSet;
import org.exist.dom.ElementImpl;
import org.exist.dom.ExtArrayNodeSet;
import org.exist.dom.NodeProxy;
import org.exist.dom.NodeSet;
import org.exist.dom.TextImpl;
import org.exist.dom.QName;
import org.exist.dom.SymbolTable;
import org.exist.numbering.NodeId;
import org.exist.storage.btree.BTreeCallback;
import org.exist.storage.btree.BTreeException;
import org.exist.storage.btree.DBException;
import org.exist.storage.btree.IndexQuery;
import org.exist.storage.btree.Value;
import org.exist.storage.index.BFile;
import org.exist.storage.io.VariableByteArrayInput;
import org.exist.storage.io.VariableByteInput;
import org.exist.storage.io.VariableByteOutputStream;
import org.exist.storage.lock.Lock;
import org.exist.util.ByteConversion;
import org.exist.util.Configuration;
import org.exist.util.FastQSort;
import org.exist.util.LockException;
import org.exist.util.ReadOnlyException;
import org.exist.util.UTF8;
import org.exist.util.ValueOccurrences;
import org.exist.util.XMLString;
import org.exist.xquery.Constants;
import org.exist.xquery.TerminatedException;
import org.exist.xquery.XPathException;
import org.exist.xquery.value.AtomicValue;
import org.exist.xquery.value.Item;
import org.exist.xquery.value.StringValue;
import org.exist.xquery.value.Type;
/**
* Maintains an index on typed node values.
*
* TODO: Check correct types during validation.
*
* In the BTree single BFile, the keys are :
* (collectionId, indexType, indexData)
* and the values are : gid1, gid2-gid1, ...
* <b></b>
* <p>Algorithm:</p>
* When a node is stored, an entry is added or updated in the {@link #pending} map,
* with given String content and basic type as key.
* This way, the index entries are easily put in the persistent BFile storage by
* {@link #flush()} .
*
* @author wolf
*/
public class NativeValueIndex implements ContentLoadingObserver {
private final static Logger LOG = Logger.getLogger(NativeValueIndex.class);
public static final String FILE_NAME = "values.dbx";
public static final String FILE_KEY_IN_CONFIG = "db-connection.values";
//TODO : find the real semantics
public static final int WITH_PATH = 1;
public static final int WITHOUT_PATH = 2;
public static final double DEFAULT_VALUE_CACHE_GROWTH = 1.25;
public static final double DEFAULT_VALUE_KEY_THRESHOLD = 0.01;
public static final double DEFAULT_VALUE_VALUE_THRESHOLD = 0.04;
public static int OFFSET_COLLECTION_ID = 0;
public static int OFFSET_VALUE_TYPE = OFFSET_COLLECTION_ID + Collection.LENGTH_COLLECTION_ID;
public static int LENGTH_VALUE_TYPE = 1; //sizeof byte
public static int OFFSET_DATA = OFFSET_VALUE_TYPE + NativeValueIndex.LENGTH_VALUE_TYPE;
public static int LENGTH_NODE_IDS = 4; //sizeof int
public final static byte IDX_GENERIC = 0;
public final static byte IDX_QNAME = 1;
/** The broker that is using this value index */
DBBroker broker;
/** The datastore for this value index */
protected BFile dbValues;
protected Configuration config;
/** A collection of key-value pairs that pending modifications for this value index.
* The keys are {@link org.exist.xquery.value.AtomicValue atomic values}
* that implement {@link Indexable Indexable}.
* The values are {@link org.exist.util.LongLinkedList lists} containing
* the nodes GIDs (global identifiers.
*/
protected Map[] pending = new Map[2];
/** The current document */
private DocumentImpl doc;
/** Work output Stream taht should be cleared before every use */
private VariableByteOutputStream os = new VariableByteOutputStream();
//TODO : reconsider this. Case sensitivity have nothing to do with atomic values -pb
protected boolean caseSensitive = true;
public static String PROPERTY_INDEX_CASE_SENSITIVE = "indexer.case-sensitive";
public NativeValueIndex(DBBroker broker, byte id, String dataDir, Configuration config) throws DBException {
this.broker = broker;
this.config = config;
this.pending[IDX_GENERIC] = new TreeMap();
this.pending[IDX_QNAME] = new TreeMap();
//use inheritance if necessary !
//TODO : read from configuration (key ?)
double cacheGrowth = NativeValueIndex.DEFAULT_VALUE_CACHE_GROWTH;
double cacheKeyThresdhold = NativeValueIndex.DEFAULT_VALUE_KEY_THRESHOLD;
double cacheValueThresHold = NativeValueIndex.DEFAULT_VALUE_VALUE_THRESHOLD;
BFile nativeFile = (BFile) config.getProperty(getConfigKeyForFile());
if (nativeFile == null) {
//use inheritance
File file = new File(dataDir + File.separatorChar + getFileName());
LOG.debug("Creating '" + file.getName() + "'...");
nativeFile = new BFile(broker.getBrokerPool(), id, false,
file, broker.getBrokerPool().getCacheManager(), cacheGrowth, cacheKeyThresdhold, cacheValueThresHold);
config.setProperty(getConfigKeyForFile(), nativeFile);
}
dbValues = nativeFile;
//TODO : reconsider this. Case sensitivity have nothing to do with atomic values -pb
Boolean caseOpt = (Boolean) config.getProperty(NativeValueIndex.PROPERTY_INDEX_CASE_SENSITIVE);
if (caseOpt != null)
caseSensitive = caseOpt.booleanValue();
broker.addContentLoadingObserver(getInstance());
}
public String getFileName() {
return FILE_NAME;
}
public String getConfigKeyForFile() {
return FILE_KEY_IN_CONFIG;
}
public NativeValueIndex getInstance() {
return this;
}
/* (non-Javadoc)
* @see org.exist.storage.ContentLoadingObserver#setDocument(org.exist.dom.DocumentImpl)
*/
public void setDocument(DocumentImpl document) {
this.doc = document;
}
/** Store the given element's value in the value index.
* @param xpathType The value type
* @param node The element
* @param content The string representation of the value
*/
public void storeElement(ElementImpl node, String content, int xpathType, byte indexType) {
if (doc.getDocId() != node.getDocId()) {
throw new IllegalArgumentException("Document id ('" + doc.getDocId() + "') and proxy id ('" +
node.getDocId() + "') differ !");
}
AtomicValue atomic = convertToAtomic(xpathType, content);
//Ignore if the value can't be successfully atomized
//(this is logged elsewhere)
if (atomic == null)
return;
Object key;
if (indexType == IDX_QNAME) {
key = new QNameKey(node.getQName(), atomic);
} else
key = atomic;
ArrayList buf;
//Is this indexable value already pending ?
if (pending[indexType].containsKey(key))
buf = (ArrayList) pending[indexType].get(key);
else {
//Create a NodeId list
buf = new ArrayList(8);
pending[indexType].put(key, buf);
}
//Add node's NodeId to the list
buf.add(node.getNodeId());
}
/** Store the given attribute's value in the value index.
* @param spec The index specification
* @param node The attribute
*/
public void storeAttribute(AttrImpl node, NodePath currentPath, int indexingHint, RangeIndexSpec spec) {
//Return early
if (indexingHint != WITHOUT_PATH)
return;
if (doc != null && doc.getDocId() != node.getDocId()) {
throw new IllegalArgumentException("Document id ('" + doc.getDocId() + "') and proxy id ('" +
node.getDocId() + "') differ !");
}
AtomicValue atomic = convertToAtomic(spec.getType(), node.getValue());
//Ignore if the value can't be successfully atomized
//(this is logged elsewhere)
if(atomic == null)
return;
int indexType = spec.getQName() == null ? IDX_GENERIC : IDX_QNAME;
Object key;
if (indexType == IDX_QNAME) {
key = new QNameKey(node.getQName(), atomic);
} else
key = atomic;
ArrayList buf;
//Is this indexable value already pending ?
if (pending[indexType].containsKey(key))
//Reuse the existing NodeId list
buf = (ArrayList) pending[indexType].get(key);
else {
//Create a NodeId list
buf = new ArrayList(8);
pending[indexType].put(key, buf);
}
//Add node's GID to the list
buf.add(node.getNodeId());
}
public void storeText(TextImpl node, NodePath currentPath, int indexingHint) {
// TODO Auto-generated method stub
}
public void startElement(ElementImpl node, NodePath currentPath, boolean index) {
// TODO Auto-generated method stub
}
public void endElement(int xpathType, ElementImpl node, String content) {
// TODO Auto-generated method stub
}
public void removeElement(ElementImpl node, NodePath currentPath, String content) {
// TODO Auto-generated method stub
}
/* (non-Javadoc)
* @see org.exist.storage.IndexGenerator#sync()
*/
public void sync() {
final Lock lock = dbValues.getLock();
try {
lock.acquire(Lock.WRITE_LOCK);
dbValues.flush();
} catch (LockException e) {
LOG.warn("Failed to acquire lock for '" + dbValues.getFile().getName() + "'", e);
//TODO : throw an exception ? -pb
} catch (DBException e) {
LOG.error(e.getMessage(), e);
//TODO : throw an exception ? -pb
} finally {
lock.release(Lock.WRITE_LOCK);
}
}
/* (non-Javadoc)
* @see org.exist.storage.IndexGenerator#flush()
*/
public void flush() {
//TODO : return if doc == null? -pb
int keyCount = pending[IDX_GENERIC].size() + pending[IDX_QNAME].size();
if (keyCount == 0)
return;
final short collectionId = this.doc.getCollection().getId();
final Lock lock = dbValues.getLock();
for (byte section = 0; section <= IDX_QNAME; section++) {
for (Iterator i = pending[section].entrySet().iterator(); i.hasNext();) {
Map.Entry entry = (Map.Entry) i.next();
Object key = entry.getKey();
//TODO : NativeElementIndex uses ArrayLists -pb
ArrayList gids = (ArrayList) entry.getValue();
int gidsCount = gids.size();
//Don't forget this one
FastQSort.sort(gids, 0, gidsCount - 1);
os.clear();
os.writeInt(this.doc.getDocId());
os.writeInt(gidsCount);
//Mark position
int nodeIDsLength = os.position();
//Dummy value : actual one will be written below
os.writeFixedInt(0);
//Compute the GID list
for (int j = 0; j < gidsCount; j++) {
NodeId nodeId = (NodeId) gids.get(j);
try {
nodeId.write(os);
} catch (IOException e) {
LOG.warn("IO error while writing range index: " + e.getMessage(), e);
//TODO : throw exception?
}
}
//Write (variable) length of node IDs
os.writeFixedInt(nodeIDsLength, os.position() - nodeIDsLength - LENGTH_NODE_IDS);
try {
lock.acquire(Lock.WRITE_LOCK);
Value v;
if (section == IDX_GENERIC)
v = new SimpleValue(collectionId, (Indexable) key);
else {
QNameKey qnk = (QNameKey) key;
v = new QNameValue(collectionId, qnk.qname, qnk.value, broker.getSymbols());
}
if (dbValues.append(v, os.data()) == BFile.UNKNOWN_ADDRESS) {
LOG.error("Could not append index data for key '" + key + "'");
//TODO : throw exception ?
}
} catch (EXistException e) {
LOG.error(e.getMessage(), e);
} catch (LockException e) {
LOG.warn("Failed to acquire lock for '" + dbValues.getFile().getName() + "'", e);
//TODO : return ?
} catch (IOException e) {
LOG.error(e.getMessage(), e);
//TODO : return ?
} catch (ReadOnlyException e) {
LOG.warn(e.getMessage(), e);
//Return without clearing the pending entries
return;
} finally {
lock.release(Lock.WRITE_LOCK);
os.clear();
}
}
pending[section].clear();
}
}
/* (non-Javadoc)
* @see org.exist.storage.IndexGenerator#remove()
*/
public void remove() {
//TODO : return if doc == null? -pb
int keyCount = pending[IDX_GENERIC].size() + pending[IDX_QNAME].size();
if (keyCount == 0)
return;
final short collectionId = this.doc.getCollection().getId();
final Lock lock = dbValues.getLock();
for (byte section = 0; section <= IDX_QNAME; section++) {
for (Iterator i = pending[section].entrySet().iterator(); i.hasNext();) {
Map.Entry entry = (Map.Entry) i.next();
Object key = entry.getKey();
ArrayList storedGIDList = (ArrayList) entry.getValue();
ArrayList newGIDList = new ArrayList();
os.clear();
try {
lock.acquire(Lock.WRITE_LOCK);
//Compute a key for the value
Value searchKey;
if (section == IDX_GENERIC)
searchKey = new SimpleValue(collectionId, (Indexable) key);
else {
QNameKey qnk = (QNameKey) key;
searchKey = new QNameValue(collectionId, qnk.qname, qnk.value, broker.getSymbols());
}
Value value = dbValues.get(searchKey);
//Does the value already has data in the index ?
if (value != null) {
//Add its data to the new list
VariableByteArrayInput is = new VariableByteArrayInput(value.getData());
while (is.available() > 0) {
int storedDocId = is.readInt();
int gidsCount = is.readInt();
int size = is.readFixedInt();
if (storedDocId != this.doc.getDocId()) {
// data are related to another document:
// append them to any existing data
os.writeInt(storedDocId);
os.writeInt(gidsCount);
os.writeFixedInt(size);
is.copyRaw(os, size);
} else {
// data are related to our document:
// feed the new list with the GIDs
for (int j = 0; j < gidsCount; j++) {
NodeId nodeId = broker.getBrokerPool().getNodeFactory().createFromStream(is);
// add the node to the new list if it is not
// in the list of removed nodes
if (!containsNode(storedGIDList, nodeId)) {
newGIDList.add(nodeId);
}
}
}
}
//append the data from the new list
if (newGIDList.size() > 0) {
int gidsCount = newGIDList.size();
//Don't forget this one
FastQSort.sort(newGIDList, 0, gidsCount - 1);
os.writeInt(this.doc.getDocId());
os.writeInt(gidsCount);
//Mark position
int nodeIDsLength = os.position();
//Dummy value : actual one will be written below
os.writeFixedInt(0);
for (int j = 0; j < gidsCount; j++) {
NodeId nodeId = (NodeId) newGIDList.get(j);
try {
nodeId.write(os);
} catch (IOException e) {
LOG.warn("IO error while writing range index: " + e.getMessage(), e);
//TODO : throw exception ?
}
}
//Write (variable) length of node IDs
os.writeFixedInt(nodeIDsLength, os.position() - nodeIDsLength - LENGTH_NODE_IDS);
}
if (dbValues.update(value.getAddress(), searchKey, os.data()) == BFile.UNKNOWN_ADDRESS) {
LOG.error("Could not update index data for value '" + searchKey + "'");
//TODO: throw exception ?
}
} else {
if (dbValues.put(searchKey, os.data()) == BFile.UNKNOWN_ADDRESS) {
LOG.error("Could not put index data for value '" + searchKey + "'");
//TODO : throw exception ?
}
}
} catch (EXistException e) {
LOG.error(e.getMessage(), e);
} catch (LockException e) {
LOG.warn("Failed to acquire lock for '" + dbValues.getFile().getName() + "'", e);
//TODO : return ?
} catch (ReadOnlyException e) {
LOG.warn("Read-only error on '" + dbValues.getFile().getName() + "'", e);
} catch (IOException e) {
LOG.error(e.getMessage(), e);
} finally {
lock.release(Lock.WRITE_LOCK);
os.clear();
}
}
pending[section].clear();
}
}
private static boolean containsNode(List list, NodeId nodeId) {
for (int i = 0; i < list.size(); i++) {
if (((NodeId) list.get(i)).equals(nodeId))
return true;
}
return false;
}
/* Drop all index entries for the given collection.
* @see org.exist.storage.IndexGenerator#dropIndex(org.exist.collections.Collection)
*/
public void dropIndex(Collection collection) {
final Lock lock = dbValues.getLock();
try {
lock.acquire(Lock.WRITE_LOCK);
//TODO : flush ? -pb
// remove generic index
Value ref = new SimpleValue(collection.getId());
dbValues.removeAll(null, new IndexQuery(IndexQuery.TRUNC_RIGHT, ref));
// remove QName index
ref = new QNameValue(collection.getId());
dbValues.removeAll(null, new IndexQuery(IndexQuery.TRUNC_RIGHT, ref));
} catch (LockException e) {
LOG.warn("Failed to acquire lock for '" + dbValues.getFile().getName() + "'", e);
} catch (BTreeException e) {
LOG.error(e.getMessage(), e);
} catch (IOException e) {
LOG.error(e.getMessage(), e);
} finally {
lock.release(Lock.WRITE_LOCK);
}
}
/* Drop all index entries for the given document.
* @see org.exist.storage.IndexGenerator#dropIndex(org.exist.dom.DocumentImpl)
*/
//TODO : note that this is *not* this.doc -pb
public void dropIndex(DocumentImpl document) throws ReadOnlyException {
final short collectionId = document.getCollection().getId();
final Lock lock = dbValues.getLock();
try {
lock.acquire(Lock.WRITE_LOCK);
for (int section = 0; section <= IDX_QNAME; section++) {
for (Iterator i = pending[section].entrySet().iterator(); i.hasNext();) {
Map.Entry entry = (Map.Entry) i.next();
Object key = entry.getKey();
//Compute a key for the indexed value in the collection
Value v;
if (section == IDX_GENERIC)
v = new SimpleValue(collectionId, (Indexable) key);
else {
QNameKey qnk = (QNameKey) key;
v = new QNameValue(collectionId, qnk.qname, qnk.value, broker.getSymbols());
}
Value value = dbValues.get(v);
if (value == null)
continue;
VariableByteArrayInput is = new VariableByteArrayInput(value.getData());
boolean changed = false;
os.clear();
while (is.available() > 0) {
int storedDocId = is.readInt();
int gidsCount = is.readInt();
int size = is.readFixedInt();
if (storedDocId != document.getDocId()) {
// data are related to another document:
// copy them (keep them)
os.writeInt(storedDocId);
os.writeInt(gidsCount);
os.writeFixedInt(size);
is.copyRaw(os, size);
} else {
// data are related to our document:
// skip them (remove them)
is.skipBytes(size);
changed = true;
}
}
//Store new data, if relevant
if (changed) {
if (os.data().size() == 0) {
// nothing to store:
// remove the existing key/value pair
dbValues.remove(v);
} else {
// still something to store:
// modify the existing value for the key
if (dbValues.put(v, os.data()) == BFile.UNKNOWN_ADDRESS) {
LOG.error("Could not put index data for key '" + v + "'");
//TODO : throw exception ?
}
}
}
}
pending[section].clear();
}
} catch (LockException e) {
LOG.warn("Failed to acquire lock for '" + dbValues.getFile().getName() + "'", e);
} catch (IOException e) {
LOG.error(e.getMessage(), e);
} catch (EXistException e) {
LOG.warn("Exception while removing range index: " + e.getMessage(), e);
} finally {
os.clear();
lock.release(Lock.WRITE_LOCK);
}
}
/** find
* @param relation binary operator used for the comparison
* @param value right hand comparison value */
public NodeSet find(int relation, DocumentSet docs, NodeSet contextSet, int axis, QName qname, Indexable value)
throws TerminatedException {
final NodeSet result = new ExtArrayNodeSet();
final SearchCallback cb = new SearchCallback(docs, contextSet, result, axis == NodeSet.ANCESTOR);
final Lock lock = dbValues.getLock();
for (Iterator iter = docs.getCollectionIterator(); iter.hasNext();) {
try {
lock.acquire(Lock.READ_LOCK);
final short collectionId = ((Collection) iter.next()).getId();
//Compute a key for the value in the collection
final Value searchKey, prefixKey;
if (qname == null) {
searchKey = new SimpleValue(collectionId, value);
prefixKey = new SimplePrefixValue(collectionId, value.getType());
} else {
searchKey = new QNameValue(collectionId, qname, value, broker.getSymbols());
prefixKey = new QNamePrefixValue(collectionId, qname, value.getType(), broker.getSymbols());
}
final int idxOp = checkRelationOp(relation);
final IndexQuery query = new IndexQuery(idxOp, searchKey);
if (idxOp == IndexQuery.EQ)
dbValues.query(query, cb);
else
dbValues.query(query, prefixKey, cb);
} catch (EXistException e) {
LOG.error(e.getMessage(), e);
} catch (LockException e) {
LOG.warn("Failed to acquire lock for '" + dbValues.getFile().getName() + "'", e);
} catch (IOException e) {
LOG.error(e.getMessage(), e);
} catch (BTreeException e) {
LOG.error(e.getMessage(), e);
} finally {
lock.release(Lock.READ_LOCK);
}
}
return result;
}
public NodeSet match(DocumentSet docs, NodeSet contextSet, int axis, String expr, QName qname, int type)
throws TerminatedException, EXistException {
return match(docs, contextSet, axis, expr, qname, type, 0, true);
}
/** Regular expression search
* @param type like type argument for {@link org.exist.storage.RegexMatcher} constructor
* @param flags like flags argument for {@link org.exist.storage.RegexMatcher} constructor
* */
public NodeSet match(DocumentSet docs, NodeSet contextSet, int axis, String expr, QName qname, int type, int flags, boolean caseSensitiveQuery)
throws TerminatedException, EXistException {
// if the regexp starts with a char sequence, we restrict the index scan to entries starting with
// the same sequence. Otherwise, we have to scan the whole index.
StringValue startTerm = null;
if (expr.startsWith("^") && caseSensitiveQuery == caseSensitive) {
StringBuffer term = new StringBuffer();
for (int j = 1; j < expr.length(); j++)
if (Character.isLetterOrDigit(expr.charAt(j)))
term.append(expr.charAt(j));
else
break;
if(term.length() > 0) {
startTerm = new StringValue(term.toString());
LOG.debug("Match will begin index scan at '" + startTerm + "'");
}
}
final TermMatcher comparator = new RegexMatcher(expr, type, flags);
final NodeSet result = new ExtArrayNodeSet();
final RegexCallback cb = new RegexCallback(docs, contextSet, result, comparator, axis == NodeSet.ANCESTOR);
final Lock lock = dbValues.getLock();
for (Iterator iter = docs.getCollectionIterator(); iter.hasNext();) {
try {
lock.acquire(Lock.READ_LOCK);
final short collectionId = ((Collection) iter.next()).getId();
Value searchKey;
if (qname == null) {
if (startTerm != null) {
//Compute a key for the start term in the collection
searchKey = new SimpleValue(collectionId, startTerm);
} else {
//Compute a key for an arbitrary string in the collection
searchKey = new SimplePrefixValue(collectionId, Type.STRING);
}
} else {
if (startTerm != null) {
searchKey = new QNameValue(collectionId, qname, startTerm, broker.getSymbols());
} else {
LOG.debug("Searching with QName prefix");
searchKey = new QNamePrefixValue(collectionId, qname, Type.STRING, broker.getSymbols());
}
}
final IndexQuery query = new IndexQuery(IndexQuery.TRUNC_RIGHT, searchKey);
dbValues.query(query, cb);
} catch (LockException e) {
LOG.warn("Failed to acquire lock for '" + dbValues.getFile().getName() + "'", e);
} catch (IOException e) {
LOG.error(e.getMessage(), e);
} catch (BTreeException e) {
LOG.error(e.getMessage(), e);
} finally {
lock.release(Lock.READ_LOCK);
}
}
return result;
}
public ValueOccurrences[] scanIndexKeys(DocumentSet docs, NodeSet contextSet, Indexable start) {
final int type = start.getType();
final boolean stringType = Type.subTypeOf(type, Type.STRING);
final IndexScanCallback cb = new IndexScanCallback(docs, contextSet, type);
final Lock lock = dbValues.getLock();
for (Iterator i = docs.getCollectionIterator(); i.hasNext();) {
try {
lock.acquire(Lock.READ_LOCK);
final short collectionId = ((Collection) i.next()).getId();
//Compute a key for the start value in the collection
if (stringType) {
final Value startKey = new SimpleValue(collectionId, start);
IndexQuery query = new IndexQuery(IndexQuery.TRUNC_RIGHT, startKey);
dbValues.query(query, cb);
} else {
final Value startKey = new SimpleValue(collectionId, start);
final Value prefixKey = new SimplePrefixValue(collectionId, start.getType());
final IndexQuery query = new IndexQuery(IndexQuery.GEQ, startKey);
dbValues.query(query, prefixKey, cb);
}
} catch (EXistException e) {
LOG.error(e.getMessage(), e);
} catch (LockException e) {
LOG.warn("Failed to acquire lock for '" + dbValues.getFile().getName() + "'", e);
} catch (IOException e) {
LOG.error(e.getMessage(), e);
} catch (BTreeException e) {
LOG.error(e.getMessage(), e);
} catch (TerminatedException e) {
LOG.warn(e.getMessage(), e);
} finally {
lock.release(Lock.READ_LOCK);
}
}
Map map = cb.map;
ValueOccurrences[] result = new ValueOccurrences[map.size()];
return (ValueOccurrences[]) map.values().toArray(result);
}
protected int checkRelationOp(int relation) {
int indexOp;
switch(relation) {
case Constants.LT:
indexOp = IndexQuery.LT;
break;
case Constants.LTEQ:
indexOp = IndexQuery.LEQ;
break;
case Constants.GT:
indexOp = IndexQuery.GT;
break;
case Constants.GTEQ:
indexOp = IndexQuery.GEQ;
break;
case Constants.NEQ:
indexOp = IndexQuery.NEQ;
break;
case Constants.EQ:
default:
indexOp = IndexQuery.EQ;
break;
}
return indexOp;
}
/**
* @param xpathType
* @param value
* @return <code>null</null> if atomization fails or if the atomic value is not indexable.
* Should we throw an exception instead ? -pb
*/
private AtomicValue convertToAtomic(int xpathType, String value) {
AtomicValue atomic;
if (Type.subTypeOf(xpathType, Type.STRING)) {
atomic = new StringValue(value);
} else {
try {
atomic = new StringValue(value).convertTo(xpathType);
} catch (XPathException e) {
LOG.warn("Node value '" + value + "' cannot be converted to " +
Type.getTypeName(xpathType));
return null;
}
}
if (atomic == null) {
LOG.warn("Node value '" + Type.getTypeName(xpathType) + "(" + value + ")'" +
" cannot be used as index key. It is null.");
return null;
}
if (!(atomic instanceof Indexable)) {
LOG.warn("Node value '" + Type.getTypeName(xpathType) + "(" + value + ")'" +
" cannot be used as index key. It does not implement " + Indexable.class.getName());
return null;
}
return atomic;
}
public void closeAndRemove() {
//Use inheritance if necessary ;-)
config.setProperty(getConfigKeyForFile(), null);
dbValues.closeAndRemove();
}
public boolean close() throws DBException {
//Use inheritance if necessary ;-)
config.setProperty(getConfigKeyForFile(), null);
return dbValues.close();
}
public void printStatistics() {
dbValues.printStatistics();
}
public String toString() {
return this.getClass().getName() + " at "+ dbValues.getFile().getName() +
" owned by " + broker.toString() + " (case sensitive = " + caseSensitive + ")";
}
/** TODO document */
class SearchCallback implements BTreeCallback {
DocumentSet docs;
NodeSet contextSet;
NodeSet result;
boolean returnAncestor;
public SearchCallback(DocumentSet docs, NodeSet contextSet, NodeSet result, boolean returnAncestor) {
this.docs = docs;
this.contextSet = contextSet;
this.result = result;
this.returnAncestor = returnAncestor;
}
/* (non-Javadoc)
* @see org.dbxml.core.filer.BTreeCallback#indexInfo(org.dbxml.core.data.Value, long)
*/
public boolean indexInfo(Value value, long pointer) throws TerminatedException {
VariableByteInput is;
try {
is = dbValues.getAsStream(pointer);
} catch (IOException e) {
LOG.error(e.getMessage(), e);
return true;
}
try {
while (is.available() > 0) {
int storedDocId = is.readInt();
int gidsCount = is.readInt();
int size = is.readFixedInt();
DocumentImpl storedDocument = docs.getDoc(storedDocId);
//Exit if the document is not concerned
if (storedDocument == null) {
is.skipBytes(size);
continue;
}
//Process the nodes
for (int j = 0; j < gidsCount; j++) {
NodeId nodeId = broker.getBrokerPool().getNodeFactory().createFromStream(is);
NodeProxy storedNode = new NodeProxy(storedDocument, nodeId);
// if a context set is specified, we can directly check if the
// matching node is a descendant of one of the nodes
// in the context set.
if (contextSet != null) {
int sizeHint = contextSet.getSizeHint(storedDocument);
if (returnAncestor) {
NodeProxy parentNode = contextSet.parentWithChild(storedNode, false, true, NodeProxy.UNKNOWN_NODE_LEVEL);
if (parentNode != null)
result.add(parentNode, sizeHint);
} else
result.add(storedNode, sizeHint);
// otherwise, we add all nodes without check
} else {
result.add(storedNode, Constants.NO_SIZE_HINT);
}
}
}
} catch (IOException e) {
LOG.error(e.getMessage(), e);
}
return false;
}
}
/** TODO document */
private class RegexCallback extends SearchCallback {
private TermMatcher matcher;
private XMLString key = new XMLString(128);
public RegexCallback(DocumentSet docs, NodeSet contextSet, NodeSet result, TermMatcher matcher, boolean returnAncestor) {
super(docs, contextSet, result, returnAncestor);
this.matcher = matcher;
}
public boolean indexInfo(Value value, long pointer) throws TerminatedException {
int offset;
if (value.data()[value.start()] == IDX_GENERIC)
offset = SimpleValue.OFFSET_VALUE + NativeValueIndex.LENGTH_VALUE_TYPE;
else
offset = QNameValue.OFFSET_VALUE + NativeValueIndex.LENGTH_VALUE_TYPE;
key.reuse();
UTF8.decode(value.data(), value.start() + offset,
value.getLength() - offset, key);
if(matcher.matches(key)) {
super.indexInfo(value, pointer);
}
return true;
}
}
private final class IndexScanCallback implements BTreeCallback{
private DocumentSet docs;
private NodeSet contextSet;
private Map map = new TreeMap();
private int type;
IndexScanCallback(DocumentSet docs, NodeSet contextSet, int type) {
this.docs = docs;
this.contextSet = contextSet;
this.type = type;
}
/* (non-Javadoc)
* @see org.dbxml.core.filer.BTreeCallback#indexInfo(org.dbxml.core.data.Value, long)
*/
public boolean indexInfo(Value key, long pointer) throws TerminatedException {
AtomicValue atomic;
try {
atomic = (AtomicValue) SimpleValue.deserialize(key.data(), key.start(), key.getLength());
if (atomic.getType() != type)
return false;
} catch (EXistException e) {
LOG.error(e.getMessage(), e);
return true;
}
VariableByteInput is;
try {
is = dbValues.getAsStream(pointer);
} catch (IOException e) {
LOG.error(e.getMessage(), e);
return true;
}
ValueOccurrences oc = (ValueOccurrences) map.get(atomic);
try {
while (is.available() > 0) {
boolean docAdded = false;
int storedDocId = is.readInt();
int gidsCount = is.readInt();
int size = is.readFixedInt();
DocumentImpl storedDocument = docs.getDoc(storedDocId);
//Exit if the document is not concerned
if (storedDocument == null) {
is.skipBytes(size);
continue;
}
NodeId lastParentId = null;
for (int j = 0; j < gidsCount; j++) {
NodeId nodeId = broker.getBrokerPool().getNodeFactory().createFromStream(is);
if (contextSet != null) {
NodeProxy parentNode = contextSet.parentWithChild(storedDocument, nodeId, false, true);
if (parentNode != null) {
if (oc == null) {
oc = new ValueOccurrences(atomic);
map.put(atomic, oc);
}
//Handle this very special case : /item[foo = "bar"] vs. /item[@foo = "bar"]
//Same value, same parent but different nodes !
//Not sure if we should track the contextSet's parentId... (just like we do)
//... or the way the contextSet is created (thus keeping track of the NodeTest)
if (lastParentId == null || !lastParentId.equals(parentNode.getNodeId()))
oc.addOccurrences(1);
if (!docAdded) {
oc.addDocument(storedDocument);
docAdded = true;
}
lastParentId = parentNode.getNodeId();
}
}
//TODO : what if contextSet == null ? -pb
//See above where we have this behaviour :
//otherwise, we add all nodes without check
}
}
} catch(IOException e) {
LOG.error(e.getMessage(), e);
}
return true;
}
}
private static class QNameKey implements Comparable {
private QName qname;
private AtomicValue value;
public QNameKey(QName qname, AtomicValue atomic) {
this.qname = qname;
this.value = atomic;
}
public int compareTo(Object o) {
QNameKey other = (QNameKey) o;
int cmp = qname.compareTo(other.qname);
if (cmp == 0)
return value.compareTo(other.value);
else
return cmp;
}
}
private static class SimpleValue extends Value {
public static int OFFSET_IDX_TYPE = 0;
public static int LENGTH_IDX_TYPE = 1; //sizeof byte
public static int OFFSET_COLLECTION_ID = OFFSET_IDX_TYPE + LENGTH_IDX_TYPE;
public static int OFFSET_VALUE = OFFSET_COLLECTION_ID + Collection.LENGTH_COLLECTION_ID;
public SimpleValue(short collectionId) {
len = LENGTH_IDX_TYPE + Collection.LENGTH_COLLECTION_ID;
data = new byte[len];
data[OFFSET_IDX_TYPE] = IDX_GENERIC;
ByteConversion.shortToByte(collectionId, data, OFFSET_COLLECTION_ID);
pos = OFFSET_IDX_TYPE;
}
public SimpleValue(short collectionId, Indexable atomic) throws EXistException {
data = atomic.serializeValue(OFFSET_VALUE);
len = data.length;
pos = OFFSET_IDX_TYPE;
data[OFFSET_IDX_TYPE] = IDX_GENERIC;
ByteConversion.shortToByte(collectionId, data, OFFSET_COLLECTION_ID);
}
public static Indexable deserialize(byte[] data, int start, int len) throws EXistException {
return ValueIndexFactory.deserialize(data, start + OFFSET_VALUE, len - OFFSET_VALUE);
}
}
private static class SimplePrefixValue extends Value {
public static int LENGTH_VALUE_TYPE = 1; //sizeof byte
public SimplePrefixValue(short collectionId, int type) {
len = SimpleValue.LENGTH_IDX_TYPE + Collection.LENGTH_COLLECTION_ID + LENGTH_VALUE_TYPE;
data = new byte[len];
data[SimpleValue.OFFSET_IDX_TYPE] = IDX_GENERIC;
ByteConversion.shortToByte(collectionId, data, SimpleValue.OFFSET_COLLECTION_ID);
data[SimpleValue.OFFSET_VALUE] = (byte) type;
pos = SimpleValue.OFFSET_IDX_TYPE;
}
}
private static class QNameValue extends Value {
public static int OFFSET_IDX_TYPE = 0;
public static int LENGTH_IDX_TYPE = 1; //sizeof byte
public static int OFFSET_COLLECTION_ID = OFFSET_IDX_TYPE + LENGTH_IDX_TYPE;
public static int OFFSET_QNAME = OFFSET_COLLECTION_ID + Collection.LENGTH_COLLECTION_ID;
public static int LENGTH_QNAME_TYPE = 1; //sizeof byte
public static int OFFSET_NS_URI = OFFSET_QNAME + LENGTH_QNAME_TYPE;
public static int OFFSET_LOCAL_NAME = OFFSET_NS_URI + SymbolTable.LENGTH_NS_URI;
public static int OFFSET_VALUE = OFFSET_LOCAL_NAME + SymbolTable.LENGTH_LOCAL_NAME;
public QNameValue(short collectionId) {
len = LENGTH_IDX_TYPE + Collection.LENGTH_COLLECTION_ID;
data = new byte[len];
data[OFFSET_IDX_TYPE] = IDX_QNAME;
ByteConversion.shortToByte(collectionId, data, OFFSET_COLLECTION_ID);
pos = OFFSET_IDX_TYPE;
}
public QNameValue(short collectionId, QName qname, Indexable atomic, SymbolTable symbols) throws EXistException {
data = atomic.serializeValue(OFFSET_VALUE);
len = data.length;
pos = OFFSET_IDX_TYPE;
final short namespaceId = symbols.getNSSymbol(qname.getNamespaceURI());
final short localNameId = symbols.getSymbol(qname.getLocalName());
data[OFFSET_IDX_TYPE] = IDX_QNAME;
ByteConversion.shortToByte(collectionId, data, OFFSET_COLLECTION_ID);
data[OFFSET_QNAME] = qname.getNameType();
ByteConversion.shortToByte(namespaceId, data, OFFSET_NS_URI);
ByteConversion.shortToByte(localNameId, data, OFFSET_LOCAL_NAME);
}
}
private static class QNamePrefixValue extends Value {
public static int LENGTH_VALUE_TYPE = 1; //sizeof byte
public QNamePrefixValue(short collectionId, QName qname, int type, SymbolTable symbols) {
len = QNameValue.OFFSET_VALUE + LENGTH_VALUE_TYPE;
data = new byte[len];
data[QNameValue.OFFSET_IDX_TYPE] = IDX_QNAME;
ByteConversion.shortToByte(collectionId, data, QNameValue.OFFSET_COLLECTION_ID);
final short namespaceId = symbols.getNSSymbol(qname.getNamespaceURI());
final short localNameId = symbols.getSymbol(qname.getLocalName());
data[QNameValue.OFFSET_QNAME] = qname.getNameType();
ByteConversion.shortToByte(namespaceId, data, QNameValue.OFFSET_NS_URI);
ByteConversion.shortToByte(localNameId, data, QNameValue.OFFSET_LOCAL_NAME);
data[QNameValue.OFFSET_VALUE] = (byte) type;
pos = QNameValue.OFFSET_IDX_TYPE;
}
}
}
|
package org.exist.xquery.value;
import com.ibm.icu.text.Collator;
import org.exist.util.FastStringBuffer;
import org.exist.util.FloatingPointConverter;
import org.exist.xquery.Constants;
import org.exist.xquery.ErrorCodes;
import org.exist.xquery.XPathException;
import java.math.BigDecimal;
public class DoubleValue extends NumericValue {
// and e is an integer between -1075 and 970, inclusive.
// In addition also -INF, +INF and NaN.
public static final DoubleValue ZERO = new DoubleValue(0.0E0);
public static final DoubleValue POSITIVE_INFINITY = new DoubleValue(Double.POSITIVE_INFINITY);
public static final DoubleValue NEGATIVE_INFINITY = new DoubleValue(Double.NEGATIVE_INFINITY);
public static final DoubleValue NaN = new DoubleValue(Double.NaN);
private final double value;
public DoubleValue(final double value) {
this.value = value;
}
public DoubleValue(final AtomicValue otherValue) throws XPathException {
this(otherValue.getStringValue());
}
public DoubleValue(final String stringValue) throws XPathException {
try {
if ("INF".equals(stringValue)) {
value = Double.POSITIVE_INFINITY;
} else if ("-INF".equals(stringValue)) {
value = Double.NEGATIVE_INFINITY;
} else if ("NaN".equals(stringValue)) {
value = Double.NaN;
} else {
value = Double.parseDouble(stringValue);
}
} catch (final NumberFormatException e) {
throw new XPathException(ErrorCodes.FORG0001, "cannot construct " + Type.getTypeName(this.getItemType()) +
" from '" + stringValue + "'");
}
}
@Override
public int getType() {
return Type.DOUBLE;
}
@Override
public String getStringValue() {
final FastStringBuffer sb = new FastStringBuffer(20);
//0 is a dummy parameter
FloatingPointConverter.appendDouble(sb, value).getNormalizedString(0);
return sb.toString();
}
public double getValue() {
return value;
}
@Override
public boolean hasFractionalPart() {
if (isNaN()) {
return false;
}
if (isInfinite()) {
return false;
}
return new DecimalValue(new BigDecimal(value)).hasFractionalPart();
}
@Override
public Item itemAt(final int pos) {
return pos == 0 ? this : null;
}
@Override
public boolean isNaN() {
return Double.isNaN(value);
}
@Override
public boolean isInfinite() {
return Double.isInfinite(value);
}
@Override
public boolean isZero() {
return Double.compare(Math.abs(value), 0.0) == Constants.EQUAL;
}
@Override
public boolean isNegative() {
return (Double.compare(value, 0.0) < Constants.EQUAL);
}
@Override
public boolean isPositive() {
return (Double.compare(value, 0.0) > Constants.EQUAL);
}
@Override
public AtomicValue convertTo(final int requiredType) throws XPathException {
switch (requiredType) {
case Type.ATOMIC:
case Type.ITEM:
case Type.NUMBER:
case Type.DOUBLE:
return this;
case Type.FLOAT:
//if (Float.compare(value, 0.0f) && (value < Float.MIN_VALUE || value > Float.MAX_VALUE)
// throw new XPathException("Value is out of range for type xs:float");
//return new FloatValue((float) value);
return new FloatValue((float) value);
case Type.UNTYPED_ATOMIC:
return new UntypedAtomicValue(getStringValue());
case Type.STRING:
return new StringValue(getStringValue());
case Type.DECIMAL:
if (isNaN()) {
throw new XPathException(ErrorCodes.FORG0001, "can not convert "
+ Type.getTypeName(getType())
+ "('"
+ getStringValue()
+ "') to "
+ Type.getTypeName(requiredType));
}
if (isInfinite()) {
throw new XPathException(ErrorCodes.FORG0001, "can not convert "
+ Type.getTypeName(getType())
+ "('" + getStringValue()
+ "') to "
+ Type.getTypeName(requiredType));
}
return new DecimalValue(new BigDecimal(value));
case Type.INTEGER:
case Type.NON_POSITIVE_INTEGER:
case Type.NEGATIVE_INTEGER:
case Type.LONG:
case Type.INT:
case Type.SHORT:
case Type.BYTE:
case Type.NON_NEGATIVE_INTEGER:
case Type.UNSIGNED_LONG:
case Type.UNSIGNED_INT:
case Type.UNSIGNED_SHORT:
case Type.UNSIGNED_BYTE:
case Type.POSITIVE_INTEGER:
if (isNaN()) {
throw new XPathException(ErrorCodes.FORG0001, "can not convert "
+ Type.getTypeName(getType())
+ "('" + getStringValue()
+ "') to "
+ Type.getTypeName(requiredType));
}
if (Double.isInfinite(value)) {
throw new XPathException(ErrorCodes.FORG0001, "can not convert "
+ Type.getTypeName(getType())
+ "('"
+ getStringValue()
+ "') to "
+ Type.getTypeName(requiredType));
}
if (requiredType != Type.INTEGER && value > Integer.MAX_VALUE) {
throw new XPathException(ErrorCodes.FOCA0003, "Value is out of range for type " + Type.getTypeName(requiredType));
}
return new IntegerValue(Double.valueOf(value).longValue(), requiredType);
case Type.BOOLEAN:
return new BooleanValue(this.effectiveBooleanValue());
default:
throw new XPathException(ErrorCodes.FORG0001, "cannot cast '"
+ Type.getTypeName(this.getItemType())
+ "(\""
+ getStringValue()
+ "\")' to "
+ Type.getTypeName(requiredType));
}
}
@Override
public double getDouble() {
return value;
}
@Override
public int getInt() {
return Long.valueOf(Math.round(value)).intValue();
}
@Override
public long getLong() {
return Math.round(value);
}
@Override
public NumericValue ceiling() {
return new DoubleValue(Math.ceil(value));
}
@Override
public NumericValue floor() {
return new DoubleValue(Math.floor(value));
}
@Override
public NumericValue round() {
if (Double.isNaN(value) || Double.isInfinite(value) || value == 0.0) {
return this;
}
if (value >= -0.5 && value < 0.0) {
return new DoubleValue(-0.0);
}
if (value > Long.MIN_VALUE && value < Long.MAX_VALUE) {
return new DoubleValue(Math.round(value));
}
//too big return original value unchanged
return this;
}
@Override
public NumericValue round(final IntegerValue precision) throws XPathException {
if (precision == null) {
return round();
}
if (Double.isNaN(value) || Double.isInfinite(value) || value == 0.0) {
return this;
}
/* use the decimal rounding method */
return (DoubleValue) ((DecimalValue) convertTo(Type.DECIMAL)).round(precision).convertTo(Type.DOUBLE);
}
@Override
public ComputableValue minus(final ComputableValue other) throws XPathException {
if (Type.subTypeOf(other.getType(), Type.DOUBLE)) {
return new DoubleValue(value - ((DoubleValue) other).value);
} else {
return minus((ComputableValue) other.convertTo(getType()));
}
}
@Override
public ComputableValue plus(final ComputableValue other) throws XPathException {
if (Type.subTypeOf(other.getType(), Type.DOUBLE)) {
return new DoubleValue(value + ((DoubleValue) other).value);
} else {
return plus((ComputableValue) other.convertTo(getType()));
}
}
@Override
public ComputableValue mult(final ComputableValue other) throws XPathException {
switch (other.getType()) {
case Type.DOUBLE:
return new DoubleValue(value * ((DoubleValue) other).value);
case Type.DAY_TIME_DURATION:
case Type.YEAR_MONTH_DURATION:
return other.mult(this);
default:
return mult((ComputableValue) other.convertTo(getType()));
}
}
@Override
public ComputableValue div(final ComputableValue other) throws XPathException {
if (Type.subTypeOf(other.getType(), Type.NUMBER)) {
//Positive or negative zero divided by positive or negative zero returns NaN.
if (this.isZero() && ((NumericValue) other).isZero()) {
return NaN;
}
//A negative number divided by positive zero returns -INF.
if (this.isNegative() &&
((NumericValue) other).isZero() && ((NumericValue) other).isPositive()) {
return NEGATIVE_INFINITY;
}
//A negative number divided by positive zero returns -INF.
if (this.isNegative() &&
((NumericValue) other).isZero() && ((NumericValue) other).isNegative()) {
return POSITIVE_INFINITY;
}
//Division of Positive by negative zero returns -INF and INF, respectively.
if (this.isPositive() &&
((NumericValue) other).isZero() && ((NumericValue) other).isNegative()) {
return NEGATIVE_INFINITY;
}
if (this.isPositive() &&
((NumericValue) other).isZero() && ((NumericValue) other).isPositive()) {
return POSITIVE_INFINITY;
}
//Also, INF or -INF divided by INF or -INF returns NaN.
if (this.isInfinite() && ((NumericValue) other).isInfinite()) {
return NaN;
}
}
if (Type.subTypeOf(other.getType(), Type.DOUBLE)) {
return new DoubleValue(value / ((DoubleValue) other).value);
} else {
return div((ComputableValue) other.convertTo(getType()));
}
}
@Override
public IntegerValue idiv(final NumericValue other) throws XPathException {
final ComputableValue result = div(other);
return new IntegerValue(((IntegerValue) result.convertTo(Type.INTEGER)).getLong());
}
@Override
public NumericValue mod(final NumericValue other) throws XPathException {
if (Type.subTypeOf(other.getType(), Type.DOUBLE)) {
return new DoubleValue(value % ((DoubleValue) other).value);
} else {
return mod((NumericValue) other.convertTo(getType()));
}
}
@Override
public NumericValue negate() {
return new DoubleValue(-value);
}
@Override
public NumericValue abs() {
return new DoubleValue(Math.abs(value));
}
@Override
public AtomicValue max(final Collator collator, final AtomicValue other) throws XPathException {
if (Type.subTypeOf(other.getType(), Type.DOUBLE)) {
return new DoubleValue(Math.max(value, ((DoubleValue) other).value));
} else {
return new DoubleValue(
Math.max(value, ((DoubleValue) other.convertTo(Type.DOUBLE)).value));
}
}
@Override
public AtomicValue min(final Collator collator, final AtomicValue other) throws XPathException {
if (Type.subTypeOf(other.getType(), Type.DOUBLE)) {
return new DoubleValue(Math.min(value, ((DoubleValue) other).value));
} else {
return new DoubleValue(
Math.min(value, ((DoubleValue) other.convertTo(Type.DOUBLE)).value));
}
}
@Override
public int conversionPreference(final Class<?> javaClass) {
if (javaClass.isAssignableFrom(DoubleValue.class)) {
return 0;
}
if (javaClass == Long.class || javaClass == long.class) {
return 3;
}
if (javaClass == Integer.class || javaClass == int.class) {
return 4;
}
if (javaClass == Short.class || javaClass == short.class) {
return 5;
}
if (javaClass == Byte.class || javaClass == byte.class) {
return 6;
}
if (javaClass == Double.class || javaClass == double.class) {
return 1;
}
if (javaClass == Float.class || javaClass == float.class) {
return 2;
}
if (javaClass == String.class) {
return 7;
}
if (javaClass == Boolean.class || javaClass == boolean.class) {
return 8;
}
if (javaClass == Object.class) {
return 20;
}
return Integer.MAX_VALUE;
}
@Override
@SuppressWarnings("unchecked")
public <T> T toJavaObject(final Class<T> target) throws XPathException {
if (target.isAssignableFrom(DoubleValue.class)) {
return (T) this;
} else if (target == Double.class || target == double.class) {
return (T) Double.valueOf(value);
} else if (target == Float.class || target == float.class) {
return (T) new Float(value);
} else if (target == Long.class || target == long.class) {
return (T) Long.valueOf(((IntegerValue) convertTo(Type.LONG)).getValue());
} else if (target == Integer.class || target == int.class) {
final IntegerValue v = (IntegerValue) convertTo(Type.INT);
return (T) Integer.valueOf((int) v.getValue());
} else if (target == Short.class || target == short.class) {
final IntegerValue v = (IntegerValue) convertTo(Type.SHORT);
return (T) Short.valueOf((short) v.getValue());
} else if (target == Byte.class || target == byte.class) {
final IntegerValue v = (IntegerValue) convertTo(Type.BYTE);
return (T) Byte.valueOf((byte) v.getValue());
} else if (target == String.class) {
return (T) getStringValue();
} else if (target == Boolean.class) {
return (T) Boolean.valueOf(effectiveBooleanValue());
}
throw new XPathException(
"cannot convert value of type "
+ Type.getTypeName(getType())
+ " to Java object of type "
+ target.getName());
}
/**
* size writen by {link #serialize(short, boolean)}
*/
public int getSerializedSize() {
return 1 + 8;
}
@Override
public int compareTo(final Object o) {
final AtomicValue other = (AtomicValue) o;
if (Type.subTypeOf(other.getType(), Type.DOUBLE)) {
return Double.compare(value, ((DoubleValue) other).value);
} else {
return getType() < other.getType() ? Constants.INFERIOR : Constants.SUPERIOR;
}
}
@Override
public int hashCode() {
return Double.valueOf(value).hashCode();
}
}
|
package org.httpkit.server;
import java.util.Map;
@SuppressWarnings({"rawtypes", "unchecked"})
public class RackHttpHandler implements Runnable {
final HttpRequest req;
final RespCallback cb;
final Object handler;
public RackHttpHandler(HttpRequest req, RespCallback cb, Object handler) {
this.req = req;
this.cb = cb;
this.handler = handler;
}
public void run() {
}
}
|
package org.jcodings.transcode;
import org.jcodings.Ptr;
import org.jcodings.exception.TranscoderException;
import static org.jcodings.transcode.Transcoding.Body.*;
public class Transcoding implements TranscodingInstruction {
public Transcoding(Transcoder transcoder) {
this.transcoder = transcoder;
this.readBuf = new byte[transcoder.maxInput];
this.writeBuf = new byte[transcoder.maxOutput];
}
public final Transcoder transcoder;
int flags;
Body resumePosition;
int nextTable;
int nextInfo;
byte nextByte;
int outputIndex;
int recognizedLength, readAgainLength;
final byte[] readBuf;
int writeBuffOff, writeBuffLen;
final byte[] writeBuf;
byte[] state;
void close() {
transcoder.stateFinish();
}
private int charStart;
private byte[] charStartBytes;
@Override
public String toString() {
return "Transcoding for transcoder " + transcoder.toString();
}
/* transcode_char_start */
int charStart() {
if (recognizedLength > inCharStart - inPos.p) {
System.arraycopy(inBytes, inCharStart, readBuf, recognizedLength, inP - inCharStart);
charStart = 0;
charStartBytes = readBuf;
} else {
charStart = inCharStart - recognizedLength;
charStartBytes = inBytes;
}
return recognizedLength + (inP - inCharStart);
}
/* rb_transcoding_convert */
EConvResult convert(byte[] in, Ptr inPtr, int inStop, byte[] out, Ptr outPtr, int outStop, int flags) {
return transcodeRestartable(in, inPtr, inStop, out, outPtr, outStop, flags);
}
private EConvResult transcodeRestartable(byte[] in, Ptr inStart, int inStop, byte[] out, Ptr outStart, int outStop, int opt) {
if (readAgainLength != 0) {
byte[] readAgainBuf = new byte[readAgainLength];
Ptr readAgainPos = new Ptr(0);
int readAgainStop = readAgainLength;
System.arraycopy(readBuf, recognizedLength, readAgainBuf, readAgainPos.p, readAgainLength);
readAgainLength = 0;
EConvResult res = transcodeRestartable0(readAgainBuf, readAgainPos, readAgainStop, out, outStart, outStop, opt | EConv.PARTIAL_INPUT);
if (!res.isSourceBufferEmpty()) {
System.arraycopy(readAgainBuf, readAgainPos.p, readBuf, recognizedLength + readAgainLength, readAgainStop - readAgainPos.p);
readAgainLength += readAgainStop - readAgainPos.p;
}
}
return transcodeRestartable0(in, inStart, inStop, out, outStart, outStop, opt);
}
int inCharStart;
byte[] inBytes;
int inP;
Ptr inPos;
private static int STR1_LENGTH(int byteaddr) {
return byteaddr + 4;
}
private static int STR1_BYTEINDEX(int byteaddr) {
return byteaddr >> 6;
}
private EConvResult transcodeRestartable0(Pointer<BytePointer> in_pos, Pointer<BytePointer> out_pos, BytePointer in_stop, BytePointer out_stop, Transcoding tc, int opt) {
Transcoder tr = tc.transcoder;
int unitlen = tr.inputUnitLength;
int readagain_len = 0;
BytePointer inchar_start;
BytePointer in_p = inchar_start = in_pos.deref();
BytePointer out_p = out_pos.deref();
Body IP = tc.resumePosition;
try {
while (true) {
switch (IP) {
case B00:
inchar_start = in_p;
tc.recognizedLength = 0;
tc.nextTable = tr.treeStart;
IP = SUSPEND_AFTER_OUTPUT(tc, opt, in_p, inchar_start, in_pos, out_pos, out_p, readagain_len, B01);
continue;
case B01:
if (in_stop.le(in_p)) {
if ((opt & EConvFlags.PARTIAL_INPUT) == 0) {
IP = B02;
continue;
}
SUSPEND(tc, in_p, inchar_start, in_pos, out_pos, out_p, readagain_len, EConvResult.SourceBufferEmpty, B00);
IP = B00;
continue;
}
IP = B04;
continue;
case B04:
tc.nextByte = in_p.deref_inc();
IP = B05;
continue;
case B05: // follow_byte:
if (tc.nextByte < BL_MIN_BYTE(tc) || BL_MAX_BYTE(tc) < tc.nextByte) {
tc.nextInfo = INVALID;
} else {
tc.nextInfo = BL_ACTION(tc, tc.nextByte);
}
IP = B06;
continue;
case B06: // follow_info:
switch (tc.nextInfo & 0x1F) {
case NOMAP:
BytePointer p = inchar_start;
tc.writeBuffOff = 0;
while (p.offset < in_p.offset) {
TRANSCODING_WRITEBUF(tc)[tc.writeBuffOff] = p.deref_inc();
}
tc.writeBuffLen = tc.writeBuffOff;
tc.writeBuffOff = 0;
while (tc.writeBuffOff < tc.writeBuffLen) {
SUSPEND_OBUF(tc, out_stop, in_p, inchar_start, in_pos, out_pos, out_p, readagain_len, B07);
out_p.set_inc(TRANSCODING_WRITEBUF(tc)[tc.writeBuffOff++]);
}
IP = B00;
continue;
case 0x00:
case 0x04:
case 0x08:
case 0x0C:
case 0x10:
case 0x14:
case 0x18:
case 0x1C:
SUSPEND_AFTER_OUTPUT(tc, opt, in_p, inchar_start, in_pos, out_pos, out_p, readagain_len, B09);
IP = B09;
continue;
case ZERObt: // drop input
IP = B00;
continue;
case ONEbt:
SUSPEND_OBUF(tc, out_stop, in_p, inchar_start, in_pos, out_pos, out_p, readagain_len, B11);
IP = B11;
continue;
case TWObt:
SUSPEND_OBUF(tc, out_stop, in_p, inchar_start, in_pos, out_pos, out_p, readagain_len, B12);
IP = B12;
continue;
case THREEbt:
SUSPEND_OBUF(tc, out_stop, in_p, inchar_start, in_pos, out_pos, out_p, readagain_len, B14);
IP = B14;
case FOURbt:
SUSPEND_OBUF(tc, out_stop, in_p, inchar_start, in_pos, out_pos, out_p, readagain_len, B17);
IP = B17;
continue;
case GB4bt:
SUSPEND_OBUF(tc, out_stop, in_p, inchar_start, in_pos, out_pos, out_p, readagain_len, B18);
IP = B18;
continue;
case STR1:
tc.outputIndex = 0;
IP = B22;
continue;
case FUNii:
tc.nextInfo = tr.func_ii.call(tc, tc.nextInfo);
IP = B06;
continue;
case FUNsi:
{
int char_start;
int[] char_len = {0};
char_start = tc.transcode_char_start(in_pos, inchar_start, in_p, char_len);
tc.nextInfo = tr.func_si.call(tc, char_start, char_len[0]);
IP = B06;
continue;
}
case FUNio:
IP = B24;
continue;
case FUNso:
SUSPEND_OBUF(tc, out_stop, in_p, inchar_start, in_pos, out_pos, out_p, readagain_len, B27);
IP = B27;
continue;
case FUNsio:
SUSPEND_OBUF(tc, out_stop, in_p, inchar_start, in_pos, out_pos, out_p, readagain_len, B28);
IP = B28;
continue;
case INVALID:
if (tc.recognizedLength + (in_p.offset - inchar_start.offset) <= unitlen) {
if (tc.recognizedLength + (in_p.offset - inchar_start.offset) < unitlen) {
SUSPEND_AFTER_OUTPUT(tc, opt, in_p, inchar_start, in_pos, out_pos, out_p, readagain_len, B29);
}
IP = B29;
continue;
} else {
int invalid_len;
int discard_len;
invalid_len = tc.recognizedLength + (in_p.offset - inchar_start.offset);
discard_len = ((invalid_len - 1) / unitlen) * unitlen;
readagain_len = invalid_len - discard_len;
IP = B31;
continue;
}
IP = B31;
continue;
case UNDEF:
IP = B32;
continue;
default:
throw new RuntimeException("unknown transcoding instruction");
}
IP = B00;
continue;
case B29:
while ((opt & EConvFlags.PARTIAL_INPUT) != 0 && tc.recognizedLength + (in_stop.offset - inchar_start.offset) < unitlen) {
in_p.offset = in_stop.offset;
SUSPEND(tc, in_p, inchar_start, in_pos, out_pos, out_p, readagain_len, EConvResult.SourceBufferEmpty, B29);
}
IP = B30;
continue;
case B30:
if (tc.recognizedLength + (in_stop.offset - inchar_start.offset) <= unitlen) {
in_p.offset = in_stop.offset;
} else {
in_p.offset = inchar_start.offset + (unitlen - tc.recognizedLength);
}
IP = B31;
continue;
case B28:
{
int char_start;
int[] char_len = {0};
if (tr.maxOutput <= out_stop.offset - out_p.offset) {
char_start = transcode_char_start(tc, in_pos.deref(), inchar_start, in_p, char_len);
out_p.offset += tr.func_sio(TRANSCODING_STATE(tc), char_start, char_len[0], out_p, out_stop.offset - out_p.offset);
IP = B00;
continue;
} else {
char_start = transcode_char_start(tc, in_pos.deref(), inchar_start, in_p, char_len);
tc.writeBuffLen = tr.func_sio(TRANSCODING_STATE(tc), char_start, char_len[0], TRANSCODING_WRITEBUF(tc), TRANSCODING_WRITEBUF_SIZE(tc));
tc.writeBuffOff = 0;
IP = B25;
continue;
}
}
case B27:
{
int char_start;
int[] char_len = {0};
if (tr.maxOutput <= out_stop.offset - out_p.offset) {
char_start = transcode_char_start(tc, in_pos.deref(), inchar_start, in_p, char_len);
out_p.offset += tr.func_so(TRANSCODING_STATE(tc), char_start, char_len[0], out_p, out_stop.offset - out_p.offset);
IP = B00;
continue;
} else {
char_start = transcode_char_start(tc, in_pos.deref(), inchar_start, in_p, char_len);
tc.writeBuffLen = tr.func_so(TRANSCODING_STATE(tc), char_start, char_len[0], TRANSCODING_WRITEBUF(tc), TRANSCODING_WRITEBUF_SIZE(tc));
tc.writeBuffOff = 0;
IP = B25;
continue;
}
}
case B24:
if (tr.maxOutput <= out_stop.offset - out_p.offset) {
out_p.offset += tr.func_io.call(tc, tc.nextInfo, out_p, out_stop.offset - out_p.offset);
IP = B00;
continue;
} else {
tc.writeBuffLen = tr.func_io.call(tc, tc.nextInfo, TRANSCODING_WRITEBUF(tc), TRANSCODING_WRITEBUF_SIZE(tc));
tc.writeBuffOff = 0;
IP = B25;
continue;
}
case B25:
while (tc.writeBuffOff < tc.writeBuffLen) {
SUSPEND_OBUF(tc, out_stop, in_p, inchar_start, in_pos, out_pos, out_p, readagain_len, B26);
out_p.set_inc(TRANSCODING_WRITEBUF(tc)[tc.writeBuffOff++]);
}
IP = B00;
continue;
case B26:
out_p.set_inc(TRANSCODING_WRITEBUF(tc)[tc.writeBuffOff++]);
IP = B25;
continue;
case B11: // byte 1
out_p.set_inc(getBT1(tc.nextInfo));
IP = B00;
continue;
case B12: // bytes 1, 2
out_p.set_inc(getBT1(tc.nextInfo));
SUSPEND_OBUF(tc, out_stop, in_p, inchar_start, in_pos, out_pos, out_p, readagain_len, B13);
case B13: // byte 2
out_p.set_inc(getBT2(tc.nextInfo));
IP = B00; // continue
continue;
case B17: // bytes 0, 1, 2, 3
out_p.set_inc(getBT0(tc.nextInfo));
SUSPEND_OBUF(tc, out_stop, in_p, inchar_start, in_pos, out_pos, out_p, readagain_len, B14);
case B14: // bytes 1, 2, 3
out_p.set_inc(getBT1(tc.nextInfo));
SUSPEND_OBUF(tc, out_stop, in_p, inchar_start, in_pos, out_pos, out_p, readagain_len, B15);
case B15: // bytes 2, 3
out_p.set_inc(getBT2(tc.nextInfo));
SUSPEND_OBUF(tc, out_stop, in_p, inchar_start, in_pos, out_pos, out_p, readagain_len, B16);
case B16: // byte 3
out_p.set_inc(getBT3(tc.nextInfo));
IP = B00;
continue;
case B18: // GB4 bytes 0, 1, 2, 3
out_p.set_inc(getGB4bt0(tc.nextInfo));
SUSPEND_OBUF(tc, out_stop, in_p, inchar_start, in_pos, out_pos, out_p, readagain_len, B19);
case B19: // GB4 bytes 1, 2, 3
out_p.set_inc(getGB4bt1(tc.nextInfo));
SUSPEND_OBUF(tc, out_stop, in_p, inchar_start, in_pos, out_pos, out_p, readagain_len, B20);
case B20: // GB4 bytes 2, 3
out_p.set_inc(getGB4bt2(tc.nextInfo));
SUSPEND_OBUF(tc, out_stop, in_p, inchar_start, in_pos, out_pos, out_p, readagain_len, B21);
case B21: // GB4 bytes 3
out_p.set_inc(getGB4bt3(tc.nextInfo));
IP = B00;
continue;
case B22:
while (tc.outputIndex < STR1_LENGTH(BYTE_ADDR(tc, STR1_BYTEINDEX(tc.nextInfo)).deref())) {
SUSPEND_OBUF(tc, out_stop, in_p, inchar_start, in_pos, out_pos, out_p, readagain_len, B23);
out_p.set_inc(BYTE_ADDR(tc, STR1_BYTEINDEX(tc.nextInfo)).deref());
tc.outputIndex++;
}
IP = B00;
continue;
case B23:
out_p.set_inc(BYTE_ADDR(tc, STR1_BYTEINDEX(tc.nextInfo)).deref());
tc.outputIndex++;
IP = B22;
continue;
case B07:
out_p.set_inc(TRANSCODING_WRITEBUF(tc)[tc.writeBuffOff++]);
while (tc.writeBuffOff < tc.writeBuffLen) {
SUSPEND_OBUF(tc, out_stop, in_p, inchar_start, in_pos, out_pos, out_p, readagain_len, B07);
out_p.set_inc(TRANSCODING_WRITEBUF(tc)[tc.writeBuffOff++]);
}
IP = B00;
continue;
case B09:
while (in_p.offset >= in_stop.offset) {
if ((opt & EConvFlags.PARTIAL_INPUT) != 0) {
IP = B10; // incomplete
continue;
}
SUSPEND(tc, in_p, inchar_start, in_pos, out_pos, out_p, readagain_len, EConvResult.SourceBufferEmpty, B09);
}
tc.nextByte = in_p.deref_inc();
tc.nextTable = tc.nextInfo;
IP = B05;
continue;
case B31: // invalid:
SUSPEND(tc, in_p, inchar_start, in_pos, out_pos, out_p, readagain_len, EConvResult.InvalidByteSequence, B00);
IP = B00;
continue;
case B10: // incomplete:
SUSPEND(tc, in_p, inchar_start, in_pos, out_pos, out_p, readagain_len, EConvResult.IncompleteInput, B00);
IP = B00;
continue;
case B32: // undef:
SUSPEND(tc, in_p, inchar_start, in_pos, out_pos, out_p, readagain_len, EConvResult.UndefinedConversion, B00);
IP = B00;
continue;
case B02:
/* TODO: cleanup */
}
}
} catch (TranscodingSuspend ts) {
return ts.result;
}
}
private static void SUSPEND(Transcoding tc, BytePointer in_p, BytePointer inchar_start, Pointer<BytePointer> in_pos, Pointer<BytePointer> out_pos, BytePointer out_p, int readagain_len, EConvResult ret, Body num) {
tc.resumePosition = num;
if (in_p.offset - inchar_start.offset > 0) System.arraycopy(inchar_start.bytes, inchar_start.offset, tc.readBuf, tc.recognizedLength, in_p.offset - inchar_start.offset);
in_pos.set(in_p);
out_pos.set(out_p);
tc.recognizedLength += in_p.offset - inchar_start.offset;
if (readagain_len != 0) {
tc.recognizedLength -= readagain_len;
tc.readAgainLength = readagain_len;
}
throw new TranscodingSuspend(ret);
}
private static Body SUSPEND_OBUF(Transcoding tc, BytePointer out_stop, BytePointer in_p, BytePointer inchar_start, Pointer<BytePointer> in_pos, Pointer<BytePointer> out_pos, BytePointer out_p, int readagain_len, Body num) {
while (out_stop.offset - out_p.offset < 1) {
SUSPEND(tc, in_p, inchar_start, in_pos, out_pos, out_p, readagain_len, EConvResult.DestinationBufferFull, num);
}
return num;
}
private static Body SUSPEND_AFTER_OUTPUT(Transcoding tc, int opt, BytePointer in_p, BytePointer inchar_start, Pointer<BytePointer> in_pos, Pointer<BytePointer> out_pos, BytePointer out_p, int readagain_len, Body num) {
if ((opt & EConvFlags.AFTER_OUTPUT) != 0 && out_pos.deref() != out_p) {
SUSPEND(tc, in_p, inchar_start, in_pos, out_pos, out_p, readagain_len, EConvResult.AfterOutput, num);
}
return num;
}
enum Body {
B00,
B01,
B04,
B05,
B06,
B29,
B30,
B28,
B27,
B24,
B25,
B26,
B11,
B12,
B13,
B14,
B15,
B16,
B17,
B18,
B19,
B20,
B21,
B22,
B23,
B07,
B09,
B31,
B10,
B32,
B02;
}
private static byte[] TRANSCODING_WRITEBUF(Transcoding tc) {
return tc.writeBuf;
}
private static int TRANSCODING_WRITEBUF_SIZE(Transcoding tc) {
return tc.writeBuffLen;
}
private static byte[] TRANSCODING_STATE(Transcoding tc) {
return tc.state;
}
private static class BytePointer {
BytePointer(byte[] bytes, int offset) {
this.bytes = bytes;
this.offset = offset;
}
byte deref() {
return deref(0);
}
byte deref_inc() {
byte result = deref(0);
offset++;
return result;
}
byte deref(int index) {
return this.bytes[offset + index];
}
boolean lt(BytePointer other) {
return this.offset < other.offset;
}
boolean le(BytePointer other) {
return this.offset <= other.offset;
}
void set_inc(byte value) {
this.bytes[this.offset++] = value;
}
final byte[] bytes;
int offset;
}
private static class IntPointer {
IntPointer(int[] ints, int offset) {
this.ints = ints;
this.offset = offset;
}
int deref(int index) {
return this.ints[offset + index];
}
final int[] ints;
int offset;
}
private static class Pointer<T> {
Pointer(T[] objects, int offset) {
this.objects = objects;
this.offset = offset;
}
T deref() {
return deref(0);
}
T deref(int index) {
return this.objects[offset + index];
}
void set(T t) {
objects[offset] = t;
}
final T[] objects;
int offset;
}
private static final int WORDINDEX_SHIFT_BITS = 2;
private static int WORDINDEX2INFO(int widx) {
return widx << WORDINDEX_SHIFT_BITS;
}
private static int INFO2WORDINDEX(int info) {
return info >>> WORDINDEX_SHIFT_BITS;
}
private static BytePointer BYTE_ADDR(Transcoding tc, int index) {
return new BytePointer(tc.transcoder.byteArray, index);
}
private static IntPointer WORD_ADDR(Transcoding tc, int index) {
return new IntPointer(tc.transcoder.intArray, INFO2WORDINDEX(index));
}
private static BytePointer BL_BASE(Transcoding tc) {
return Transcoding.BYTE_ADDR(tc, BYTE_LOOKUP_BASE(Transcoding.WORD_ADDR(tc, tc.nextTable)));
}
private static IntPointer BL_INFO(Transcoding tc) {
return Transcoding.WORD_ADDR(tc, BYTE_LOOKUP_INFO(Transcoding.WORD_ADDR(tc, tc.nextTable)));
}
private static int BYTE_LOOKUP_BASE(IntPointer bl) {
return bl.deref(0);
}
private static int BYTE_LOOKUP_INFO(IntPointer bl) {
return bl.deref(1);
}
private static int BL_MIN_BYTE(Transcoding tc) {
return Transcoding.BL_BASE(tc).deref(0);
}
private static int BL_MAX_BYTE(Transcoding tc) {
return Transcoding.BL_BASE(tc).deref(1);
}
private static int BL_OFFSET(Transcoding tc, byte b) {
return Transcoding.BL_BASE(tc).deref(2 + b - Transcoding.BL_MIN_BYTE(tc));
}
private static int BL_ACTION(Transcoding tc, byte b) {
return Transcoding.BL_INFO(tc).deref(Transcoding.BL_OFFSET(tc, b));
}
private static class TranscodingSuspend extends RuntimeException {
EConvResult result;
TranscodingSuspend(EConvResult result) {
this.result = result;
}
@Override
public Throwable fillInStackTrace() {
return this;
}
}
public static byte getGB4bt0(int a) {
return (byte)(a >>> 8);
}
public static byte getGB4bt1(int a) {
return (byte)(((a >>> 24) & 0xf) | 0x30);
}
public static byte getGB4bt2(int a) {
return (byte)(a >>> 160);
}
public static byte getGB4bt3(int a) {
return (byte)(((a >>> 28) & 0x0f) | 0x30);
}
public static byte getBT1(int a) {
return (byte)(a >>> 8);
}
public static byte getBT2(int a) {
return (byte)(a >>> 16);
}
public static byte getBT3(int a) {
return (byte)(a >>> 24);
}
public static byte getBT0(int a) {
return (byte)(((a >>> 5) & 0x0F) | 0x30);
}
}
|
package org.jcodings.transcode;
import org.jcodings.Ptr;
public class Transcoding implements TranscodingInstruction {
public Transcoding(Transcoder transcoder, int flags) {
this.transcoder = transcoder;
this.flags = flags;
this.resumePosition = START;
this.recognizedLength = 0;
this.readAgainLength = 0;
this.writeBuffLen = 0;
this.writeBuffOff = 0;
this.readBuf = new byte[transcoder.maxInput];
this.writeBuf = new byte[transcoder.maxOutput];
this.state = new byte[transcoder.stateSize];
transcoder.stateInit(state);
}
public final Transcoder transcoder;
int flags;
int resumePosition;
int nextTable;
int nextInfo;
byte nextByte;
int outputIndex;
int recognizedLength, readAgainLength;
final byte[] readBuf;
int writeBuffOff, writeBuffLen;
final byte[] writeBuf;
final byte[] state;
EConvResult suspendResult;
void close() {
transcoder.stateFinish(state);
}
private int charStart;
private byte[] charStartBytes;
@Override
public String toString() {
return "Transcoding for transcoder " + transcoder.toString();
}
/* transcode_char_start */
int charStart() {
if (recognizedLength > inCharStart - inPos.p) {
System.arraycopy(inBytes, inCharStart, readBuf, recognizedLength, inP - inCharStart);
charStart = 0;
charStartBytes = readBuf;
} else {
charStart = inCharStart - recognizedLength;
charStartBytes = inBytes;
}
return recognizedLength + (inP - inCharStart);
}
/* rb_transcoding_convert */
EConvResult convert(byte[] in, Ptr inPtr, int inStop, byte[] out, Ptr outPtr, int outStop, int flags) {
return transcodeRestartable(in, inPtr, inStop, out, outPtr, outStop, flags);
}
private EConvResult transcodeRestartable(byte[] in, Ptr inStart, int inStop, byte[] out, Ptr outStart, int outStop, int opt) {
if (readAgainLength != 0) {
byte[] readAgainBuf = new byte[readAgainLength];
Ptr readAgainPos = new Ptr(0);
int readAgainStop = readAgainLength;
System.arraycopy(readBuf, recognizedLength, readAgainBuf, readAgainPos.p, readAgainLength);
readAgainLength = 0;
System.arraycopy(readAgainBuf, 0, TRANSCODING_READBUF(this), recognizedLength, readAgainLength);
readAgainLength = 0;
EConvResult res = transcodeRestartable0(readAgainBuf, readAgainPos, out, outStart, readAgainStop, outStop, opt | EConv.PARTIAL_INPUT);
if (!res.isSourceBufferEmpty()) {
System.arraycopy(readAgainBuf, readAgainPos.p, readBuf, recognizedLength + readAgainLength, readAgainStop - readAgainPos.p);
readAgainLength += readAgainStop - readAgainPos.p;
}
}
return transcodeRestartable0(in, inStart, out, outStart, inStop, outStop, opt);
}
int inCharStart;
byte[] inBytes;
int inP;
Ptr inPos;
private static int STR1_LENGTH(byte[] bytes, int byteaddr) {
return bytes[byteaddr] + 4;
}
private static int STR1_BYTEINDEX(int w) {
return w >>> 6;
}
private EConvResult transcodeRestartable0(final byte[] in_bytes, Ptr in_pos, final byte[] out_bytes, Ptr out_pos, int in_stop, int out_stop, int opt) {
Transcoder tr = transcoder;
int unitlen = tr.inputUnitLength;
int readagain_len = 0;
int inchar_start = in_pos.p;
int in_p = inchar_start;
int out_p = out_pos.p;
int[] char_len = null;
int ip = resumePosition;
MACHINE: while (true) {
switch (ip) {
case START:
inchar_start = in_p;
recognizedLength = 0;
nextTable = tr.treeStart;
if (0 == SUSPEND_AFTER_OUTPUT(this, opt, in_bytes, in_p, inchar_start, in_pos, out_pos, out_p, readagain_len, RESUME_AFTER_OUTPUT)) return suspendResult;
// fall through
case RESUME_AFTER_OUTPUT:
if (in_stop <= in_p) {
if ((opt & EConvFlags.PARTIAL_INPUT) == 0) {
ip = CLEANUP;
continue;
}
SUSPEND(this, in_bytes, in_p, inchar_start, in_pos, out_pos, out_p, readagain_len, EConvResult.SourceBufferEmpty, START);
return suspendResult;
}
// fall through
case NEXTBYTE:
nextByte = in_bytes[in_p++];
// fall through
case FOLLOW_BYTE: // follow_byte:
if ((nextByte & 0xFF) < BL_MIN_BYTE(this) || BL_MAX_BYTE(this) < (nextByte & 0xFF)) {
nextInfo = INVALID;
} else {
nextInfo = BL_ACTION(this, nextByte);
}
// fall through
case FOLLOW_INFO: // follow_info:
switch (nextInfo & 0x1F) {
case NOMAP:
int p = inchar_start;
writeBuffOff = 0;
while (p < in_p) {
writeBuf[writeBuffOff++] = in_bytes[p++];
}
writeBuffLen = writeBuffOff;
writeBuffOff = 0;
while (writeBuffOff < writeBuffLen) {
if (0 == SUSPEND_OBUF(this, out_stop, in_bytes, in_p, inchar_start, in_pos, out_pos, out_p, readagain_len, RESUME_NOMAP)) return suspendResult;
out_bytes[out_p++] = writeBuf[writeBuffOff++];
}
ip = START;
continue;
case 0x00:
case 0x04:
case 0x08:
case 0x0C:
case 0x10:
case 0x14:
case 0x18:
case 0x1C:
if (0 == SUSPEND_AFTER_OUTPUT(this, opt, in_bytes, in_p, inchar_start, in_pos, out_pos, out_p, readagain_len, SELECT_TABLE)) return suspendResult;
ip = SELECT_TABLE;
continue;
case ZERObt: // drop input
ip = START;
continue;
case ONEbt:
if (0 == SUSPEND_OBUF(this, out_stop, in_bytes, in_p, inchar_start, in_pos, out_pos, out_p, readagain_len, RESUME_ONE_BYTE_1)) return suspendResult;
ip = ONE_BYTE_1;
continue;
case TWObt:
if (0 == SUSPEND_OBUF(this, out_stop, in_bytes, in_p, inchar_start, in_pos, out_pos, out_p, readagain_len, RESUME_TWO_BYTE_1)) return suspendResult;
ip = TWO_BYTE_1;
continue;
case THREEbt:
if (0 == SUSPEND_OBUF(this, out_stop, in_bytes, in_p, inchar_start, in_pos, out_pos, out_p, readagain_len, RESUME_FOUR_BYTE_1)) return suspendResult;
ip = FOUR_BYTE_1;
continue;
case FOURbt:
if (0 == SUSPEND_OBUF(this, out_stop, in_bytes, in_p, inchar_start, in_pos, out_pos, out_p, readagain_len, RESUME_FOUR_BYTE_0)) return suspendResult;
ip = FOUR_BYTE_0;
continue;
case GB4bt:
if (0 == SUSPEND_OBUF(this, out_stop, in_bytes, in_p, inchar_start, in_pos, out_pos, out_p, readagain_len, RESUME_GB_FOUR_BYTE_0)) return suspendResult;
ip = GB_FOUR_BYTE_0;
continue;
case STR1:
outputIndex = 0;
ip = STRING;
continue;
case FUNii:
nextInfo = tr.infoToInfo(state, nextInfo);
ip = FOLLOW_INFO;
continue;
case FUNsi:
{
int char_start;
char_len = PREPARE_CHAR_LEN(char_len);
char_start = transcode_char_start(in_bytes, in_pos.p, inchar_start, in_p, char_len);
nextInfo = tr.startToInfo(state, in_bytes, char_start, char_len[0]);
ip = FOLLOW_INFO;
continue;
}
case FUNio:
ip = CALL_FUN_IO;
continue;
case FUNso:
if (0 == SUSPEND_OBUF(this, out_stop, in_bytes, in_p, inchar_start, in_pos, out_pos, out_p, readagain_len, RESUME_CALL_FUN_SO)) return suspendResult;
ip = CALL_FUN_SO;
continue;
case FUNsio:
if (0 == SUSPEND_OBUF(this, out_stop, in_bytes, in_p, inchar_start, in_pos, out_pos, out_p, readagain_len, RESUME_CALL_FUN_SIO)) return suspendResult;
ip = CALL_FUN_SIO;
continue;
case INVALID:
if (recognizedLength + (in_p - inchar_start) <= unitlen) {
if (recognizedLength + (in_p - inchar_start) < unitlen) {
if (0 == SUSPEND_AFTER_OUTPUT(this, opt, in_bytes, in_p, inchar_start, in_pos, out_pos, out_p, readagain_len, READ_MORE)) return suspendResult;
}
ip = READ_MORE;
continue;
} else {
int invalid_len;
int discard_len;
invalid_len = recognizedLength + (in_p - inchar_start);
discard_len = ((invalid_len - 1) / unitlen) * unitlen;
readagain_len = invalid_len - discard_len;
ip = REPORT_INVALID;
continue;
}
case UNDEF:
ip = REPORT_UNDEF;
continue;
default:
throw new RuntimeException("unknown transcoding instruction");
}
case READ_MORE:
while ((opt & EConvFlags.PARTIAL_INPUT) != 0 && recognizedLength + (in_stop - inchar_start) < unitlen) {
in_p = in_stop;
SUSPEND(this, in_bytes, in_p, inchar_start, in_pos, out_pos, out_p, readagain_len, EConvResult.SourceBufferEmpty, READ_MORE);
return suspendResult;
}
if (recognizedLength + (in_stop - inchar_start) <= unitlen) {
in_p = in_stop;
} else {
in_p = inchar_start + (unitlen - recognizedLength);
}
ip = REPORT_INVALID;
continue;
// func_sio logic
case RESUME_CALL_FUN_SIO:
// continue loop from SUSPEND_OBUF
while (out_stop - out_p < 1) {
SUSPEND(this, in_bytes, in_p, inchar_start, in_pos, out_pos, out_p, readagain_len, EConvResult.DestinationBufferFull, RESUME_CALL_FUN_SIO);
return suspendResult;
}
// fall through
case CALL_FUN_SIO:
{
int char_start;
char_len = PREPARE_CHAR_LEN(char_len);
if (tr.maxOutput <= out_stop - out_p) {
char_start = transcode_char_start(in_bytes, in_pos.p, inchar_start, in_p, char_len);
out_p += tr.startToIOutput(state, in_bytes, char_start, char_len[0], nextInfo, out_bytes, out_p, out_stop - out_p);
ip = START;
continue;
} else {
char_start = transcode_char_start(in_bytes, in_pos.p, inchar_start, in_p, char_len);
writeBuffLen = tr.startToIOutput(state, in_bytes, char_start, char_len[0], nextInfo, writeBuf, 0, writeBuffLen);
writeBuffOff = 0;
ip = TRANSFER_WRITEBUF;
continue;
}
}
// func_so logic
case RESUME_CALL_FUN_SO:
// continue loop from SUSPEND_OBUF
while (out_stop - out_p < 1) {
SUSPEND(this, in_bytes, in_p, inchar_start, in_pos, out_pos, out_p, readagain_len, EConvResult.DestinationBufferFull, RESUME_CALL_FUN_SO);
return suspendResult;
}
// fall through
case CALL_FUN_SO:
{
int char_start;
char_len = PREPARE_CHAR_LEN(char_len);
if (tr.maxOutput <= out_stop - out_p) {
char_start = transcode_char_start(in_bytes, in_pos.p, inchar_start, in_p, char_len);
out_p += tr.startToOutput(state, in_bytes, char_start, char_len[0], out_bytes, out_p, out_stop - out_p);
ip = START;
continue;
} else {
char_start = transcode_char_start(in_bytes, in_pos.p, inchar_start, in_p, char_len);
writeBuffLen = tr.startToOutput(state, in_bytes, char_start, char_len[0], writeBuf, 0, writeBuffLen);
writeBuffOff = 0;
ip = TRANSFER_WRITEBUF;
continue;
}
}
// func_io logic
case CALL_FUN_IO:
if (tr.maxOutput <= out_stop - out_p) {
out_p += tr.infoToOutput(state, nextInfo, out_bytes, out_p, out_stop - out_p);
ip = START;
continue;
} else {
writeBuffLen = tr.infoToOutput(state, nextInfo, writeBuf, 0, writeBuffLen);
writeBuffOff = 0;
// fall through
}
// write buffer transfer logic
case RESUME_TRANSFER_WRITEBUF:
// continue loop from SUSPEND_OBUF
while (out_stop - out_p < 1) {
SUSPEND(this, in_bytes, in_p, inchar_start, in_pos, out_pos, out_p, readagain_len, EConvResult.DestinationBufferFull, RESUME_TRANSFER_WRITEBUF);
return suspendResult;
}
out_bytes[out_p++] = writeBuf[writeBuffOff++];
// fall through
case TRANSFER_WRITEBUF:
while (writeBuffOff < writeBuffLen) {
if (0 == SUSPEND_OBUF(this, out_stop, in_bytes, in_p, inchar_start, in_pos, out_pos, out_p, readagain_len, RESUME_TRANSFER_WRITEBUF)) return suspendResult;
out_bytes[out_p++] = writeBuf[writeBuffOff++];
}
ip = START;
continue;
// bytes from info logic
case RESUME_ONE_BYTE_1: // byte 1
// continue loop from SUSPEND_OBUF
while (out_stop - out_p < 1) {
SUSPEND(this, in_bytes, in_p, inchar_start, in_pos, out_pos, out_p, readagain_len, EConvResult.DestinationBufferFull, RESUME_ONE_BYTE_1);
return suspendResult;
}
// fall through
case ONE_BYTE_1: // byte 1
out_bytes[out_p++] = getBT1(nextInfo);
ip = START;
continue;
case TWO_BYTE_1: // bytes 1, 2
out_bytes[out_p++] = getBT1(nextInfo);
if (0 == SUSPEND_OBUF(this, out_stop, in_bytes, in_p, inchar_start, in_pos, out_pos, out_p, readagain_len, RESUME_TWO_BYTE_1)) return suspendResult;
// fall through
case TWO_BYTE_2: // byte 2
out_bytes[out_p++] = getBT2(nextInfo);
ip = START; // continue
continue;
case RESUME_TWO_BYTE_1:
// continue loop from SUSPEND_OBUF
while (out_stop - out_p < 1) {
SUSPEND(this, in_bytes, in_p, inchar_start, in_pos, out_pos, out_p, readagain_len, EConvResult.DestinationBufferFull, RESUME_TWO_BYTE_1);
return suspendResult;
}
ip = TWO_BYTE_1;
continue;
case FOUR_BYTE_0: // bytes 0, 1, 2, 3
out_bytes[out_p++] = getBT0(nextInfo);
if (0 == SUSPEND_OBUF(this, out_stop, in_bytes, in_p, inchar_start, in_pos, out_pos, out_p, readagain_len, RESUME_FOUR_BYTE_1)) return suspendResult;
// fall through
case FOUR_BYTE_1: // bytes 1, 2, 3
out_bytes[out_p++] = getBT1(nextInfo);
if (0 == SUSPEND_OBUF(this, out_stop, in_bytes, in_p, inchar_start, in_pos, out_pos, out_p, readagain_len, RESUME_FOUR_BYTE_2)) return suspendResult;
// fall through
case FOUR_BYTE_2: // bytes 2, 3
out_bytes[out_p++] = getBT2(nextInfo);
if (0 == SUSPEND_OBUF(this, out_stop, in_bytes, in_p, inchar_start, in_pos, out_pos, out_p, readagain_len, RESUME_FOUR_BYTE_3)) return suspendResult;
// fall through
case FOUR_BYTE_3: // byte 3
out_bytes[out_p++] = getBT3(nextInfo);
ip = START;
continue;
case RESUME_FOUR_BYTE_0: // bytes 0, 1, 2, 3
// continue loop from SUSPEND_OBUF
if (out_stop - out_p < 1) {
SUSPEND(this, in_bytes, in_p, inchar_start, in_pos, out_pos, out_p, readagain_len, EConvResult.DestinationBufferFull, RESUME_FOUR_BYTE_0);
return suspendResult;
}
ip = FOUR_BYTE_0;
continue;
case RESUME_FOUR_BYTE_1: // bytes 1, 2, 3
// continue loop from SUSPEND_OBUF
if (out_stop - out_p < 1) {
SUSPEND(this, in_bytes, in_p, inchar_start, in_pos, out_pos, out_p, readagain_len, EConvResult.DestinationBufferFull, RESUME_FOUR_BYTE_1);
return suspendResult;
}
ip = FOUR_BYTE_1;
continue;
case RESUME_FOUR_BYTE_2: // bytes 2, 3
// continue loop from SUSPEND_OBUF
if (out_stop - out_p < 1) {
SUSPEND(this, in_bytes, in_p, inchar_start, in_pos, out_pos, out_p, readagain_len, EConvResult.DestinationBufferFull, RESUME_FOUR_BYTE_2);
return suspendResult;
}
ip = FOUR_BYTE_2;
continue;
case RESUME_FOUR_BYTE_3: // byte 3
// continue loop from SUSPEND_OBUF
if (out_stop - out_p < 1) {
SUSPEND(this, in_bytes, in_p, inchar_start, in_pos, out_pos, out_p, readagain_len, EConvResult.DestinationBufferFull, RESUME_FOUR_BYTE_3);
return suspendResult;
}
ip = FOUR_BYTE_3;
continue;
case GB_FOUR_BYTE_0: // GB4 bytes 0, 1, 2, 3
out_bytes[out_p++] = getGB4bt0(nextInfo);
if (0 == SUSPEND_OBUF(this, out_stop, in_bytes, in_p, inchar_start, in_pos, out_pos, out_p, readagain_len, RESUME_GB_FOUR_BYTE_0)) return suspendResult;
// fall through
case GB_FOUR_BYTE_1: // GB4 bytes 1, 2, 3
out_bytes[out_p++] = getGB4bt1(nextInfo);
if (0 == SUSPEND_OBUF(this, out_stop, in_bytes, in_p, inchar_start, in_pos, out_pos, out_p, readagain_len, RESUME_GB_FOUR_BYTE_1)) return suspendResult;
// fall through
case GB_FOUR_BYTE_2: // GB4 bytes 2, 3
out_bytes[out_p++] = getGB4bt2(nextInfo);
if (0 == SUSPEND_OBUF(this, out_stop, in_bytes, in_p, inchar_start, in_pos, out_pos, out_p, readagain_len, RESUME_GB_FOUR_BYTE_2)) return suspendResult;
// fall through
case GB_FOUR_BYTE_3: // GB4 bytes 3
out_bytes[out_p++] = getGB4bt3(nextInfo);
ip = START;
continue;
case RESUME_GB_FOUR_BYTE_0: // GB4 bytes 0, 1, 2, 3
// continue loop from SUSPEND_OBUF
if (out_stop - out_p < 1) {
SUSPEND(this, in_bytes, in_p, inchar_start, in_pos, out_pos, out_p, readagain_len, EConvResult.DestinationBufferFull, RESUME_GB_FOUR_BYTE_0);
return suspendResult;
}
ip = GB_FOUR_BYTE_0;
continue;
case RESUME_GB_FOUR_BYTE_1: // GB4 bytes 1, 2, 3
// continue loop from SUSPEND_OBUF
if (out_stop - out_p < 1) {
SUSPEND(this, in_bytes, in_p, inchar_start, in_pos, out_pos, out_p, readagain_len, EConvResult.DestinationBufferFull, RESUME_GB_FOUR_BYTE_1);
return suspendResult;
}
ip = GB_FOUR_BYTE_1;
continue;
case RESUME_GB_FOUR_BYTE_2: // GB4 bytes 2, 3
// continue loop from SUSPEND_OBUF
if (out_stop - out_p < 1) {
SUSPEND(this, in_bytes, in_p, inchar_start, in_pos, out_pos, out_p, readagain_len, EConvResult.DestinationBufferFull, RESUME_GB_FOUR_BYTE_2);
return suspendResult;
}
ip = GB_FOUR_BYTE_2;
continue;
case RESUME_STRING:
// continue loop from SUSPEND_OBUF
while (out_stop - out_p < 1) {
SUSPEND(this, in_bytes, in_p, inchar_start, in_pos, out_pos, out_p, readagain_len, EConvResult.DestinationBufferFull, RESUME_STRING);
return suspendResult;
}
out_bytes[out_p++] = transcoder.byteArray[BYTE_ADDR(STR1_BYTEINDEX(nextInfo)) + 1 + outputIndex];
outputIndex++;
// fall through
case STRING:
while (outputIndex < STR1_LENGTH(transcoder.byteArray, BYTE_ADDR(STR1_BYTEINDEX(nextInfo)))) {
if (0 == SUSPEND_OBUF(this, out_stop, in_bytes, in_p, inchar_start, in_pos, out_pos, out_p, readagain_len, RESUME_STRING)) return suspendResult;
out_bytes[out_p++] = transcoder.byteArray[BYTE_ADDR(STR1_BYTEINDEX(nextInfo)) + 1 + outputIndex];
outputIndex++;
}
ip = START;
continue;
case RESUME_NOMAP:
// continue loop from SUSPEND_OBUF
while (out_stop - out_p < 1) {
SUSPEND(this, in_bytes, in_p, inchar_start, in_pos, out_pos, out_p, readagain_len, EConvResult.DestinationBufferFull, RESUME_NOMAP);
return suspendResult;
}
out_bytes[out_p++] = writeBuf[writeBuffOff++];
while (writeBuffOff < writeBuffLen) {
if (0 == SUSPEND_OBUF(this, out_stop, in_bytes, in_p, inchar_start, in_pos, out_pos, out_p, readagain_len, RESUME_NOMAP)) return suspendResult;
out_bytes[out_p++] = writeBuf[writeBuffOff++];
}
ip = START;
continue;
case SELECT_TABLE:
while (in_p >= in_stop) {
if ((opt & EConvFlags.PARTIAL_INPUT) == 0) {
ip = REPORT_INCOMPLETE; // incomplete
continue MACHINE;
}
SUSPEND(this, in_bytes, in_p, inchar_start, in_pos, out_pos, out_p, readagain_len, EConvResult.SourceBufferEmpty, SELECT_TABLE);
return suspendResult;
}
nextByte = in_bytes[in_p++];
nextTable = nextInfo;
ip = FOLLOW_BYTE;
continue;
case REPORT_INVALID: // invalid:
SUSPEND(this, in_bytes, in_p, inchar_start, in_pos, out_pos, out_p, readagain_len, EConvResult.InvalidByteSequence, START);
return suspendResult;
case REPORT_INCOMPLETE: // incomplete:
SUSPEND(this, in_bytes, in_p, inchar_start, in_pos, out_pos, out_p, readagain_len, EConvResult.IncompleteInput, START);
return suspendResult;
case REPORT_UNDEF: // undef:
SUSPEND(this, in_bytes, in_p, inchar_start, in_pos, out_pos, out_p, readagain_len, EConvResult.UndefinedConversion, START);
return suspendResult;
case RESUME_CLEANUP:
// continue loop from SUSPEND_OBUF
while (out_stop - out_p < 1) {
SUSPEND(this, in_bytes, in_p, inchar_start, in_pos, out_pos, out_p, readagain_len, EConvResult.DestinationBufferFull, RESUME_CLEANUP);
return suspendResult;
}
ip = FINISHED;
continue;
case RESUME_FINISH_WRITEBUF:
// continue loop from SUSPEND_OBUF
if (SUSPEND == SUSPEND_OBUF(this, out_stop, in_bytes, in_p, inchar_start, in_pos, out_pos, out_p, readagain_len, RESUME_FINISH_WRITEBUF)) return suspendResult;
out_bytes[out_p++] = writeBuf[writeBuffOff++];
while (writeBuffOff <= writeBuffLen) {
if (SUSPEND == SUSPEND_OBUF(this, out_stop, in_bytes, in_p, inchar_start, in_pos, out_pos, out_p, readagain_len, RESUME_FINISH_WRITEBUF)) return suspendResult;
out_bytes[out_p++] = writeBuf[writeBuffOff++];
}
ip = FINISHED;
continue;
case FINISH_FUNC:
if (tr.maxOutput <= out_stop - out_p) {
out_p += tr.finish(state, out_bytes, out_p, out_stop - out_p);
} else {
writeBuffLen = tr.finish(state, writeBuf, 0, writeBuffLen);
writeBuffOff = 0;
while (writeBuffOff <= writeBuffLen) {
if (SUSPEND == SUSPEND_OBUF(this, out_stop, in_bytes, in_p, inchar_start, in_pos, out_pos, out_p, readagain_len, RESUME_FINISH_WRITEBUF)) return suspendResult;
out_bytes[out_p++] = writeBuf[writeBuffOff++];
}
}
ip = FINISHED;
continue;
case CLEANUP:
if (tr.hasFinish()) {
if (SUSPEND == SUSPEND_OBUF(this, out_stop, in_bytes, in_p, inchar_start, in_pos, out_pos, out_p, readagain_len, RESUME_CLEANUP)) return suspendResult;
ip = FINISH_FUNC;
continue;
}
// fall through
case FINISHED:
SUSPEND(this, in_bytes, in_p, inchar_start, in_pos, out_pos, out_p, readagain_len, EConvResult.Finished, FINISHED);
return suspendResult;
}
}
}
private int[] PREPARE_CHAR_LEN(int[] char_len) {
if (char_len == null) {
char_len = new int[]{0};
} else {
char_len[0] = 0;
}
return char_len;
}
private int transcode_char_start(byte[] in_bytes, int in_start, int inchar_start, int in_p, int[] char_len_ptr) {
int ptr;
if (inchar_start - in_start < recognizedLength) {
System.arraycopy(TRANSCODING_READBUF(this), recognizedLength, in_bytes, inchar_start, in_p - inchar_start);
ptr = 0;
}
else {
ptr = inchar_start - recognizedLength;
}
char_len_ptr[0] = recognizedLength + (in_p - inchar_start);
return ptr;
}
private static int SUSPEND(Transcoding tc, byte[] in_bytes, int in_p, int inchar_start, Ptr in_pos, Ptr out_pos, int out_p, int readagain_len, EConvResult ret, int ip) {
prepareToSuspend(tc, in_bytes, in_p, inchar_start, in_pos, out_pos, out_p, readagain_len, ip);
tc.suspendResult = ret;
return SUSPEND;
}
private static void prepareToSuspend(Transcoding tc, byte[] in_bytes, int in_p, int inchar_start, Ptr in_pos, Ptr out_pos, int out_p, int readagain_len, int ip) {
tc.resumePosition = ip;
int recognizedLength = tc.recognizedLength;
if (in_p - inchar_start > 0) System.arraycopy(in_bytes, inchar_start, tc.readBuf, recognizedLength, in_p - inchar_start);
in_pos.p = in_p;
out_pos.p = out_p;
recognizedLength += in_p - inchar_start;
if (readagain_len != 0) {
recognizedLength -= readagain_len;
tc.readAgainLength = readagain_len;
}
tc.recognizedLength = recognizedLength;
}
private static int SUSPEND_OBUF(Transcoding tc, int out_stop, byte[] in_bytes, int in_p, int inchar_start, Ptr in_pos, Ptr out_pos, int out_p, int readagain_len, int ip) {
while (out_stop - out_p < 1) {
return SUSPEND(tc, in_bytes, in_p, inchar_start, in_pos, out_pos, out_p, readagain_len, EConvResult.DestinationBufferFull, ip);
}
return ip;
}
private static int SUSPEND_AFTER_OUTPUT(Transcoding tc, int opt, byte[] in_bytes, int in_p_offset, int inchar_start_offset, Ptr in_pos, Ptr out_pos, int out_p_offset, int readagain_len, int ip) {
if (checkAfterOutput(opt, out_pos, out_p_offset)) {
return SUSPEND(tc, in_bytes, in_p_offset, inchar_start_offset, in_pos, out_pos, out_p_offset, readagain_len, EConvResult.AfterOutput, ip);
}
return ip;
}
private static boolean checkAfterOutput(int opt, Ptr out_pos, int out_p_offset) {
return (opt & EConvFlags.AFTER_OUTPUT) != 0 && out_pos.p != out_p_offset;
}
private static final int SUSPEND = 0;
private static final int START = 1;
private static final int RESUME_AFTER_OUTPUT = 2;
private static final int NEXTBYTE = 3;
private static final int FOLLOW_BYTE = 4;
private static final int FOLLOW_INFO = 5;
private static final int READ_MORE = 6;
private static final int RESUME_READ_MORE = 7;
private static final int CALL_FUN_SIO = 8;
private static final int RESUME_CALL_FUN_SIO = 44;
private static final int CALL_FUN_SO = 9;
private static final int RESUME_CALL_FUN_SO = 43;
private static final int CALL_FUN_IO = 10;
private static final int TRANSFER_WRITEBUF = 11;
private static final int RESUME_TRANSFER_WRITEBUF = 12;
private static final int ONE_BYTE_1 = 13;
private static final int RESUME_ONE_BYTE_1 = 46;
private static final int TWO_BYTE_1 = 14;
private static final int RESUME_TWO_BYTE_1 = 36;
private static final int TWO_BYTE_2 = 15;
private static final int FOUR_BYTE_1 = 16;
private static final int RESUME_FOUR_BYTE_1 = 37;
private static final int FOUR_BYTE_2 = 17;
private static final int RESUME_FOUR_BYTE_2 = 38;
private static final int FOUR_BYTE_3 = 18;
private static final int RESUME_FOUR_BYTE_3 = 39;
private static final int FOUR_BYTE_0 = 19;
private static final int RESUME_FOUR_BYTE_0 = 45;
private static final int GB_FOUR_BYTE_0 = 20;
private static final int RESUME_GB_FOUR_BYTE_0 = 40;
private static final int GB_FOUR_BYTE_1 = 21;
private static final int RESUME_GB_FOUR_BYTE_1 = 41;
private static final int GB_FOUR_BYTE_2 = 22;
private static final int RESUME_GB_FOUR_BYTE_2 = 42;
private static final int GB_FOUR_BYTE_3 = 23;
private static final int STRING = 24;
private static final int RESUME_STRING = 25;
private static final int RESUME_NOMAP = 26;
private static final int SELECT_TABLE = 27;
private static final int REPORT_INVALID = 28;
private static final int REPORT_INCOMPLETE = 29;
private static final int REPORT_UNDEF = 30;
private static final int FINISH_FUNC = 31;
private static final int RESUME_FINISH_WRITEBUF = 32;
private static final int FINISHED = 33;
private static final int CLEANUP = 34;
private static final int RESUME_CLEANUP = 35;
private static byte[] TRANSCODING_READBUF(Transcoding tc) {
return tc.readBuf;
}
private static final int WORDINDEX_SHIFT_BITS = 2;
public static int WORDINDEX2INFO(int widx) {
return widx << WORDINDEX_SHIFT_BITS;
}
private static int INFO2WORDINDEX(int info) {
return info >>> WORDINDEX_SHIFT_BITS;
}
private static int BYTE_ADDR(int index) {
return index;
}
private static int WORD_ADDR(int index) {
return INFO2WORDINDEX(index);
}
private static int BL_BASE(Transcoding tc) {
return BYTE_ADDR(BYTE_LOOKUP_BASE(tc, WORD_ADDR(tc.nextTable)));
}
private static int BL_INFO(Transcoding tc) {
return WORD_ADDR(BYTE_LOOKUP_INFO(tc, WORD_ADDR(tc.nextTable)));
}
private static int BYTE_LOOKUP_BASE(Transcoding tc, int bl) {
return tc.transcoder.intArray[bl];
}
private static int BYTE_LOOKUP_INFO(Transcoding tc, int bl) {
return tc.transcoder.intArray[bl + 1];
}
public static int BL_MIN_BYTE(Transcoding tc) {
return tc.transcoder.byteArray[BL_BASE(tc)] & 0xFF;
}
public static int BL_MAX_BYTE(Transcoding tc) {
return tc.transcoder.byteArray[BL_BASE(tc) + 1] & 0xFF;
}
public static int BL_OFFSET(Transcoding tc, int b) {
return tc.transcoder.byteArray[BL_BASE(tc) + 2 + b - BL_MIN_BYTE(tc)] & 0xFF;
}
public static int BL_ACTION(Transcoding tc, byte b) {
return tc.transcoder.intArray[BL_INFO(tc) + BL_OFFSET(tc, b & 0xFF)];
}
public static byte getGB4bt0(int a) {
return (byte)(a >>> 8);
}
public static byte getGB4bt1(int a) {
return (byte)(((a >>> 24) & 0xf) | 0x30);
}
public static byte getGB4bt2(int a) {
return (byte)(a >>> 160);
}
public static byte getGB4bt3(int a) {
return (byte)(((a >>> 28) & 0x0f) | 0x30);
}
public static byte getBT1(int a) {
return (byte)(a >>> 8);
}
public static byte getBT2(int a) {
return (byte)(a >>> 16);
}
public static byte getBT3(int a) {
return (byte)(a >>> 24);
}
public static byte getBT0(int a) {
return (byte)(((a >>> 5) & 0x0F) | 0x30);
}
}
|
package org.myrobotlab.service;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.myrobotlab.framework.Service;
import org.myrobotlab.framework.ServiceType;
import org.myrobotlab.logging.Level;
import org.myrobotlab.logging.LoggerFactory;
import org.myrobotlab.logging.Logging;
import org.myrobotlab.logging.LoggingFactory;
import org.myrobotlab.service.interfaces.DeviceController;
import org.myrobotlab.service.interfaces.I2CControl;
import org.myrobotlab.service.interfaces.I2CController;
import org.myrobotlab.service.interfaces.ServiceInterface;
import java.awt.image.BufferedImage;
import java.awt.image.DataBufferByte;
import static org.myrobotlab.service.data.OledSsd1306Data.SSD1306_128_64Data;
import static org.myrobotlab.service.data.OledSsd1306Data.SSD1306_128_32Data;
import static org.myrobotlab.service.data.OledSsd1306Data.SSD1306_96_16Data;
import static org.myrobotlab.service.data.OledSsd1306Data.FONT;
import org.slf4j.Logger;
public class OledSsd1306 extends Service implements I2CControl {
private static final long serialVersionUID = 1L;
public final static Logger log = LoggerFactory.getLogger(OledSsd1306.class.getCanonicalName());
public static final int HIGH = 0x1;
public static final int LOW = 0x0;
public static final int INPUT = 0x0;
public static final int OUTPUT = 0x1;
public List<String> controllers = new ArrayList<String>();
public String controllerName;
transient public I2CController controller; // Remove
// this
// when
// PinArrayControl
// has
// been
// implementer
// Raspi
public boolean isControllerSet = false;
public List<String> deviceAddressList = Arrays.asList("0x3C", "0x3D");
public String deviceAddress = "0x3C";
public List<String> deviceBusList = Arrays.asList("0", "1", "2", "3", "4", "5", "6", "7");
public String deviceBus = "1";
// private boolean isAttached = false;
// Constants for the SSD1306
public static short SSD1306_SETCONTRAST = 0x81;
public static short SSD1306_DISPLAYALLON_RESUME = 0xA4;
public static short SSD1306_DISPLAYALLON = 0xA5;
public static short SSD1306_NORMALDISPLAY = 0xA6;
public static short SSD1306_INVERTDISPLAY = 0xA7;
public static short SSD1306_DISPLAYOFF = 0xAE;
public static short SSD1306_DISPLAYON = 0xAF;
public static short SSD1306_SETDISPLAYOFFSET = 0xD3;
public static short SSD1306_SETCOMPINS = 0xDA;
public static short SSD1306_SETVCOMDETECT = 0xDB;
public static short SSD1306_SETDISPLAYCLOCKDIV = 0xD5;
public static short SSD1306_SETPRECHARGE = 0xD9;
public static short SSD1306_SETMULTIPLEX = 0xA8;
public static short SSD1306_SETLOWCOLUMN = 0x00;
public static short SSD1306_SETHIGHCOLUMN = 0x10;
public static short SSD1306_SETSTARTLINE = 0x40;
public static short SSD1306_MEMORYMODE = 0x20;
public static short SSD1306_COLUMNADDR = 0x21;
public static short SSD1306_PAGEADDR = 0x22;
public static short SSD1306_COMSCANINC = 0xC0;
public static short SSD1306_COMSCANDEC = 0xC8;
public static short SSD1306_SEGREMAP = 0xA0;
public static short SSD1306_CHARGEPUMP = 0x8D;
public static short SSD1306_EXTERNALVCC = 0x1;
public static short SSD1306_SWITCHCAPVCC = 0x2;
// The different types of OLED's supported
public static int SSD1306_128_64 = 0;
public static int SSD1306_128_32 = 1;
public static int SSD1306_96_16 = 2;
public int oledType = SSD1306_128_64; // Set
// default
// oledType
// 128*64
public static final int BLACK = 0;
public static final int WHITE = 1;
public static final int INVERSE = 2;
// Scrolling #defines
public static int SSD1306_ACTIVATE_SCROLL = 0x2F;
public static int SSD1306_DEACTIVATE_SCROLL = 0x2E;
public static int SSD1306_SET_VERTICAL_SCROLL_AREA = 0xA3;
public static int SSD1306_RIGHT_HORIZONTAL_SCROLL = 0x26;
public static int SSD1306_LEFT_HORIZONTAL_SCROLL = 0x27;
public static int SSD1306_VERTICAL_AND_RIGHT_HORIZONTAL_SCROLL = 0x29;
public static int SSD1306_VERTICAL_AND_LEFT_HORIZONTAL_SCROLL = 0x2A;
// Buffer for the OLED
public int SSD1306_LCDWIDTH = 128;
public int SSD1306_LCDHEIGHT = 64;
public int[] buffer;
// pin
private int vccstate; // vccstate
// vccstate
private int rotation;
static int premask[] = { 0x00, 0x80, 0xC0, 0xE0, 0xF0, 0xF8, 0xFC, 0xFE };
static int postmask[] = { 0x00, 0x01, 0x03, 0x07, 0x0F, 0x1F, 0x3F, 0x7F };
public static void main(String[] args) {
LoggingFactory.getInstance().configure();
LoggingFactory.getInstance().setLevel(Level.DEBUG);
try {
OledSsd1306 oledSsd1306 = (OledSsd1306) Runtime.start("OledSsd1306", "OledSsd1306");
Runtime.start("gui", "GUIService");
} catch (Exception e) {
Logging.logError(e);
}
}
public OledSsd1306(String n) {
super(n);
refreshControllers();
subscribe(Runtime.getInstance().getName(), "registered", this.getName(), "onRegistered");
setDisplayType(SSD1306_128_64);
}
public void onRegistered(ServiceInterface s) {
refreshControllers();
broadcastState();
}
public void refreshControllers() {
controllers = Runtime.getServiceNamesFromInterface(I2CController.class);
controllers.remove(this.getName());
broadcastState();
}
public void setDeviceBus(String deviceBus) {
this.deviceBus = deviceBus;
broadcastState();
}
public void setDeviceAddress(String deviceAddress) {
this.deviceAddress = deviceAddress;
broadcastState();
}
/**
* This methods sets the i2c Controller that will be used to communicate with
* the i2c device
*/
// @Override
public boolean setController(String controllerName, String deviceBus, String deviceAddress) {
this.controllerName = controllerName;
return setController((I2CController) Runtime.getService(controllerName), deviceBus, deviceAddress);
}
public boolean setController(String controllerName) {
this.controllerName = controllerName;
return setController((I2CController) Runtime.getService(controllerName), this.deviceBus, this.deviceAddress);
}
public boolean setController(I2CController controller) {
return setController(controller, this.deviceBus, this.deviceAddress);
}
/**
* This methods sets the i2c Controller that will be used to communicate with
* the i2c device
*/
public boolean setController(I2CController controller, String deviceBus, String deviceAddress) {
if (controller == null) {
error("setting null as controller");
return false;
}
log.info(String.format("%s setController %s", getName(), controllerName));
controllerName = controller.getName();
this.controller = controller;
this.deviceBus = deviceBus;
this.deviceAddress = deviceAddress;
createDevice();
isControllerSet = true;
broadcastState();
return true;
}
/**
* This method creates the i2c device
*/
boolean createDevice() {
if (controller != null) {
controller.createI2cDevice(this, Integer.parseInt(deviceBus), Integer.decode(deviceAddress));
}
log.info(String.format("Creating device on bus: %s address %s", deviceBus, deviceAddress));
return true;
}
public void unsetController() {
/*
* controller = null; controllerName = null; this.deviceBus = null;
* this.deviceAddress = null;
*/
isControllerSet = false;
broadcastState();
}
public I2CController getController() {
return controller;
}
public String getControllerName() {
String controlerName = null;
if (controller != null) {
controlerName = controller.getName();
}
return controlerName;
}
/*
* public boolean isAttached() { return isAttached; }
*/
/**
* Initiate the buffer with data for the size of the OLED screen
*
* @param displayType
*/
public void setDisplayType(int displayType) {
if (displayType == SSD1306_128_64) {
SSD1306_LCDWIDTH = 128;
SSD1306_LCDHEIGHT = 64;
buffer = new int[SSD1306_LCDHEIGHT * SSD1306_LCDWIDTH / 8];
buffer = SSD1306_128_64Data.clone();
} else if (displayType == SSD1306_128_32) {
SSD1306_LCDWIDTH = 128;
SSD1306_LCDHEIGHT = 32;
buffer = new int[SSD1306_LCDHEIGHT * SSD1306_LCDWIDTH / 8];
buffer = SSD1306_128_32Data.clone();
} else if (displayType == SSD1306_96_16) {
SSD1306_LCDWIDTH = 96;
SSD1306_LCDHEIGHT = 16;
buffer = new int[SSD1306_LCDHEIGHT * SSD1306_LCDWIDTH / 8];
buffer = SSD1306_96_16Data.clone();
} else {
log.error(String.format("DisplayType %s not implemented.", displayType));
}
}
int getWidth() {
return SSD1306_LCDWIDTH;
}
int getHeight() {
return SSD1306_LCDHEIGHT;
}
public synchronized void setPixel(int x, int y, boolean on) {
final int pos = x + (y / 8) * SSD1306_LCDWIDTH;
if (on) {
this.buffer[pos] |= (1 << (y & 0x07));
} else {
this.buffer[pos] &= ~(1 << (y & 0x07));
}
}
void drawBitmap(int x, int y, int[] bitmap, int w, int h, boolean on) {
int i, j, byteWidth = (w + 7) / 8;
int aByte = 0;
for (j = 0; j < h; j++) {
for (i = 0; i < w; i++) {
if ((i & 7)>0) {
aByte <<= 1;
} else {
aByte = bitmap[j * byteWidth + i / 8];
}
if ((aByte & 0x80)>0) {
setPixel(x + i, y + j, on);
}
else {
setPixel(x + i, y + j, !on);
}
}
}
}
public synchronized void drawString(String string, int x, int y, boolean on) {
int posX = x;
int posY = y;
for (char c : string.toCharArray()) {
if (c == '\n') {
posY += 8;
posX = x;
}
if (posX >= 0 && posX + 5 < this.getWidth() && posY >= 0 && posY + 7 < this.getHeight()) {
drawChar(c, posX, posY, on);
}
posX += 6;
}
}
public synchronized void drawStringCentered(String string, int y, boolean on) {
final int strSizeX = string.length() * 5 + string.length() - 1;
final int x = (this.getWidth() - strSizeX) / 2;
drawString(string, x, y, on);
}
public synchronized void clearRect(int x, int y, int width, int height, boolean on) {
for (int posX = x; posX < x + width; ++posX) {
for (int posY = y; posY < y + height; ++posY) {
setPixel(posX, posY, on);
}
}
}
public synchronized void drawChar(char c, int x, int y, boolean on) {
if (c > 255) {
c = '?';
}
for (int i = 0; i < 5; ++i) {
int line = FONT[(c * 5) + i];
for (int j = 0; j < 8; ++j) {
if ((line & 0x01) > 0) {
setPixel(x + i, y + j, on);
}
line >>= 1;
}
}
}
/**
* draws the given image over the current image buffer. The image is
* automatically converted to a binary image (if it not already is).
* <p/>
* Note that the current buffer is not cleared before, so if you want the
* image to completely overwrite the current display content you need to call
* clear() before.
*
* @param image
* @param x
* @param y
*/
public synchronized void drawImage(BufferedImage image, int x, int y) {
BufferedImage tmpImage = new BufferedImage(this.getWidth(), this.getHeight(), BufferedImage.TYPE_BYTE_BINARY);
tmpImage.getGraphics().drawImage(image, x, y, null);
int index = 0;
int pixelval;
final byte[] pixels = ((DataBufferByte) tmpImage.getRaster().getDataBuffer()).getData();
for (int posY = 0; posY < SSD1306_LCDHEIGHT; posY++) {
for (int posX = 0; posX < SSD1306_LCDWIDTH / 8; posX++) {
for (int bit = 0; bit < 8; bit++) {
pixelval = (byte) ((pixels[index / 8] >> (8 - bit)) & 0x01);
setPixel(posX * 8 + bit, posY, pixelval > 0);
index++;
}
}
}
}
void begin(int vccstate) {
this.vccstate = vccstate;
// Init sequence
ssd1306_command(SSD1306_DISPLAYOFF); // 0xAE
ssd1306_command(SSD1306_SETDISPLAYCLOCKDIV); // 0xD5
ssd1306_command(0x80); // the suggested ratio 0x80
ssd1306_command(SSD1306_SETMULTIPLEX); // 0xA8
ssd1306_command(SSD1306_LCDHEIGHT - 1);
ssd1306_command(SSD1306_SETDISPLAYOFFSET); // 0xD3
ssd1306_command(0x0); // no offset
ssd1306_command(SSD1306_SETSTARTLINE | 0x0); // line
ssd1306_command(SSD1306_CHARGEPUMP); // 0x8D
if (vccstate == SSD1306_EXTERNALVCC) {
ssd1306_command(0x10);
} else {
ssd1306_command(0x14);
}
ssd1306_command(SSD1306_MEMORYMODE); // 0x20
ssd1306_command(0x00); // 0x0 act like ks0108
ssd1306_command(SSD1306_SEGREMAP | 0x1);
ssd1306_command(SSD1306_COMSCANDEC);
if (oledType == SSD1306_128_32) {
ssd1306_command(SSD1306_SETCOMPINS); // 0xDA
ssd1306_command(0x02);
ssd1306_command(SSD1306_SETCONTRAST); // 0x81
ssd1306_command(0x8F);
} else if (oledType == SSD1306_128_64) {
ssd1306_command(SSD1306_SETCOMPINS); // 0xDA
ssd1306_command(0x12);
ssd1306_command(SSD1306_SETCONTRAST); // 0x81
if (vccstate == SSD1306_EXTERNALVCC) {
ssd1306_command(0x9F);
} else {
ssd1306_command(0xCF);
}
} else if (oledType == SSD1306_96_16) {
ssd1306_command(SSD1306_SETCOMPINS); // 0xDA
ssd1306_command(0x2); // ada x12
ssd1306_command(SSD1306_SETCONTRAST); // 0x81
if (vccstate == SSD1306_EXTERNALVCC) {
ssd1306_command(0x10);
} else {
ssd1306_command(0xAF);
}
}
ssd1306_command(SSD1306_SETPRECHARGE); // 0xd9
if (vccstate == SSD1306_EXTERNALVCC) {
ssd1306_command(0x22);
} else {
ssd1306_command(0xF1);
}
ssd1306_command(SSD1306_SETVCOMDETECT); // 0xDB
ssd1306_command(0x40);
ssd1306_command(SSD1306_DISPLAYALLON_RESUME); // 0xA4
ssd1306_command(SSD1306_NORMALDISPLAY); // 0xA6
ssd1306_command(SSD1306_DEACTIVATE_SCROLL);
ssd1306_command(SSD1306_DISPLAYON);// --turn on oled panel
}
void invertDisplay(boolean i) {
if (i) {
ssd1306_command(SSD1306_INVERTDISPLAY);
} else {
ssd1306_command(SSD1306_NORMALDISPLAY);
}
}
void ssd1306_command(int c) {
// I2C
byte control = 0x00; // Co = 0, D/C = 0
byte buffer[] = { control, (byte) c };
controller.i2cWrite((I2CControl) this, Integer.parseInt(deviceBus), Integer.decode(deviceAddress), buffer, buffer.length);
}
// startscrollright
// Activate a right handed scroll for rows start through stop
// Hint, the display is 16 rows tall. To scroll the whole display, run:
// display.scrollright(0x00, 0x0F)
void startscrollright(int start, int stop) {
ssd1306_command(SSD1306_RIGHT_HORIZONTAL_SCROLL);
ssd1306_command(0X00);
ssd1306_command(start);
ssd1306_command(0X00);
ssd1306_command(stop);
ssd1306_command(0X00);
ssd1306_command(0XFF);
ssd1306_command(SSD1306_ACTIVATE_SCROLL);
}
// startscrollleft
// Activate a right handed scroll for rows start through stop
// Hint, the display is 16 rows tall. To scroll the whole display, run:
// display.scrollright(0x00, 0x0F)
void startscrollleft(int start, int stop) {
ssd1306_command(SSD1306_LEFT_HORIZONTAL_SCROLL);
ssd1306_command(0X00);
ssd1306_command(start);
ssd1306_command(0X00);
ssd1306_command(stop);
ssd1306_command(0X00);
ssd1306_command(0XFF);
ssd1306_command(SSD1306_ACTIVATE_SCROLL);
}
// startscrolldiagright
// Activate a diagonal scroll for rows start through stop
// Hint, the display is 16 rows tall. To scroll the whole display, run:
// display.scrollright(0x00, 0x0F)
void startscrolldiagright(int start, int stop) {
ssd1306_command(SSD1306_SET_VERTICAL_SCROLL_AREA);
ssd1306_command(0X00);
ssd1306_command(SSD1306_LCDHEIGHT);
ssd1306_command(SSD1306_VERTICAL_AND_RIGHT_HORIZONTAL_SCROLL);
ssd1306_command(0X00);
ssd1306_command(start);
ssd1306_command(0X00);
ssd1306_command(stop);
ssd1306_command(0X01);
ssd1306_command(SSD1306_ACTIVATE_SCROLL);
}
// startscrolldiagleft
// Activate a diagonal scroll for rows start through stop
// Hint, the display is 16 rows tall. To scroll the whole display, run:
// display.scrollright(0x00, 0x0F)
void startscrolldiagleft(int start, int stop) {
ssd1306_command(SSD1306_SET_VERTICAL_SCROLL_AREA);
ssd1306_command(0X00);
ssd1306_command(SSD1306_LCDHEIGHT);
ssd1306_command(SSD1306_VERTICAL_AND_LEFT_HORIZONTAL_SCROLL);
ssd1306_command(0X00);
ssd1306_command(start);
ssd1306_command(0X00);
ssd1306_command(stop);
ssd1306_command(0X01);
ssd1306_command(SSD1306_ACTIVATE_SCROLL);
}
void stopscroll() {
ssd1306_command(SSD1306_DEACTIVATE_SCROLL);
}
// Dim the display
// dim = true: display is dimmed
// dim = false: display is normal
void dim(boolean dim) {
int contrast;
if (dim) {
contrast = 0; // Dimmed display
} else {
if (vccstate == SSD1306_EXTERNALVCC) {
contrast = 0x9F;
} else {
contrast = 0xCF;
}
}
// the range of contrast to too small to be really useful
// it is useful to dim the display
ssd1306_command(SSD1306_SETCONTRAST);
ssd1306_command(contrast);
}
public void display(int[] image) {
buffer = image.clone();
display();
}
public void display() {
ssd1306_command(SSD1306_COLUMNADDR);
ssd1306_command(0); // Column start address (0 = reset)
ssd1306_command(SSD1306_LCDWIDTH - 1); // Column end address (127 = reset)
ssd1306_command(SSD1306_PAGEADDR);
ssd1306_command(0); // Page start address (0 = reset)
if (SSD1306_LCDHEIGHT == 64) {
ssd1306_command(7); // Page end address
}
if (SSD1306_LCDHEIGHT == 32) {
ssd1306_command(3); // Page end address
}
if (SSD1306_LCDHEIGHT == 16) {
ssd1306_command(1); // Page end address
}
// I2C
for (int i = 0; i < (SSD1306_LCDWIDTH * SSD1306_LCDHEIGHT / 8) - 1; i++) {
// send a bunch of data in one xmission
// Wire.beginTransmission(_i2caddr);
byte writeBuffer[] = new byte[17];
int writeBufferIx = 0;
writeBuffer[writeBufferIx] = 0x40;
for (int x = 0; x < 16; x++) {
writeBufferIx++;
writeBuffer[writeBufferIx] = (byte) buffer[i];
// WIRE_WRITE(buffer[i]);
i++;
}
i
// Wire.endTransmission();
controller.i2cWrite((I2CControl) this, Integer.parseInt(deviceBus), Integer.decode(deviceAddress), writeBuffer, writeBuffer.length);
}
}
// clear everything
void clearDisplay() {
for (int i = 0; i < buffer.length; i++) {
buffer[i] = 0;
}
}
// fill everything
void fillDisplay() {
for (int i = 0; i < buffer.length; i++) {
buffer[i] = 0xff;
}
}
void drawFastHLine(int x, int y, int w, int color) {
boolean bSwap = false;
int tmpx;
switch (rotation) {
case 0:
// 0 degree rotation, do nothing
break;
case 1:
// 90 degree rotation, swap x & y for rotation, then invert x
bSwap = true;
tmpx = x;
x = y;
y = tmpx;
x = SSD1306_LCDWIDTH - x - 1;
break;
case 2:
// 180 degree rotation, invert x and y - then shift y around for height.
x = SSD1306_LCDWIDTH - x - 1;
y = SSD1306_LCDHEIGHT - y - 1;
x -= (w - 1);
break;
case 3:
// 270 degree rotation, swap x & y for rotation, then invert y and adjust
// y for w (not to become h)
bSwap = true;
tmpx = x;
x = y;
y = tmpx;
y = SSD1306_LCDHEIGHT - y - 1;
y -= (w - 1);
break;
}
if (bSwap) {
drawFastVLineInternal(x, y, w, color);
} else {
drawFastHLineInternal(x, y, w, color);
}
}
void drawFastHLineInternal(int x, int y, int w, int color) {
// Do bounds/limit checks
if (y < 0 || y >= SSD1306_LCDHEIGHT) {
return;
}
// make sure we don't try to draw below 0
if (x < 0) {
w += x;
x = 0;
}
// make sure we don't go off the edge of the display
if ((x + w) > SSD1306_LCDWIDTH) {
w = (SSD1306_LCDWIDTH - x);
}
// if our width is now negative, punt
if (w <= 0) {
return;
}
// set up the pointer for movement through the buffer
// int *pBuf = buffer;
int pBuf = 0;
// adjust the buffer pointer for the current row
pBuf += ((y / 8) * SSD1306_LCDWIDTH);
// and offset x columns in
pBuf += x;
int mask = 1 << (y & 7);
switch (color) {
case WHITE:
while (w > 0) {
buffer[pBuf] = buffer[pBuf] | mask;
pBuf++;
w
}
;
break;
case BLACK:
mask = ~mask;
while (w > 0) {
buffer[pBuf] = buffer[pBuf] & mask;
pBuf++;
w
}
;
break;
case INVERSE:
while (w > 0) {
buffer[pBuf] = buffer[pBuf] ^ mask;
pBuf++;
w
}
;
break;
}
}
void drawFastVLine(int x, int y, int h, int color) {
boolean bSwap = false;
int tmpx;
switch (rotation) {
case 0:
break;
case 1:
// 90 degree rotation, swap x & y for rotation, then invert x and adjust x
// for h (now to become w)
bSwap = true;
tmpx = x;
x = y;
y = tmpx;
x = SSD1306_LCDWIDTH - x - 1;
x -= (h - 1);
break;
case 2:
// 180 degree rotation, invert x and y - then shift y around for height.
x = SSD1306_LCDWIDTH - x - 1;
y = SSD1306_LCDHEIGHT - y - 1;
y -= (h - 1);
break;
case 3:
// 270 degree rotation, swap x & y for rotation, then invert y
bSwap = true;
tmpx = x;
x = y;
y = tmpx;
y = SSD1306_LCDHEIGHT - y - 1;
break;
}
if (bSwap) {
drawFastHLineInternal(x, y, h, color);
} else {
drawFastVLineInternal(x, y, h, color);
}
}
void drawFastVLineInternal(int x, int __y, int __h, int color) {
// do nothing if we're off the left or right side of the screen
if (x < 0 || x >= SSD1306_LCDWIDTH) {
return;
}
// make sure we don't try to draw below 0
if (__y < 0) {
// __y is negative, this will subtract enough from __h to account for __y
// being 0
__h += __y;
__y = 0;
}
// make sure we don't go past the height of the display
if ((__y + __h) > SSD1306_LCDHEIGHT) {
__h = (SSD1306_LCDHEIGHT - __y);
}
// if our height is now negative, punt
if (__h <= 0) {
return;
}
// this display doesn't need ints for coordinates, use local byte registers
// for faster juggling
int y = __y;
int h = __h;
int mod = y & 7;
// set up the pointer for fast movement through the buffer
int pBuf = 0;
// adjust the buffer pointer for the current row
pBuf += ((y / 8) * SSD1306_LCDWIDTH);
// and offset x columns in
pBuf += x;
// do the first partial byte, if necessary - this requires some masking
if (mod > 0) {
// mask off the high n bits we want to set
mod = 8 - mod;
// note - lookup table results in a nearly 10% performance improvement in
// fill* functions
// register int mask = ~(0xFF >> (mod));
int mask = premask[mod];
// adjust the mask if we're not going to reach the end of this byte
if (h < mod) {
mask &= (0XFF >> (mod - h));
}
switch (color) {
case WHITE:
buffer[pBuf] = buffer[pBuf] | mask;
break;
case BLACK:
buffer[pBuf] = buffer[pBuf] & ~mask;
break;
case INVERSE:
buffer[pBuf] = buffer[pBuf] ^ mask;
break;
}
// fast exit if we're done here!
if (h < mod) {
return;
}
h -= mod;
pBuf = pBuf + SSD1306_LCDWIDTH;
}
// write solid bytes while we can - effectively doing 8 rows at a time
if (h >= 8) {
if (color == INVERSE) { // separate copy of the code so we don't impact
// performance of the black/white write version
// with an extra comparison per loop
do {
buffer[pBuf] = ~(buffer[pBuf]);
// adjust the buffer forward 8 rows worth of data
pBuf += SSD1306_LCDWIDTH;
// adjust h & y (there's got to be a faster way for me to do this, but
// this should still help a fair bit for now)
h -= 8;
} while (h >= 8);
} else {
// store a local value to work with
int val = (color == WHITE) ? 255 : 0;
do {
// write our value in
buffer[pBuf] = val;
// adjust the buffer forward 8 rows worth of data
pBuf += SSD1306_LCDWIDTH;
// adjust h & y (there's got to be a faster way for me to do this, but
// this should still help a fair bit for now)
h -= 8;
} while (h >= 8);
}
}
// now do the final partial byte, if necessary
if (h > 0) {
mod = h & 7;
// this time we want to mask the low bits of the byte, vs the high bits we
// did above
// register int mask = (1 << mod) - 1;
// note - lookup table results in a nearly 10% performance improvement in
// fill* functions
int mask = postmask[mod];
switch (color) {
case WHITE:
buffer[pBuf] = buffer[pBuf] | mask;
break;
case BLACK:
buffer[pBuf] = buffer[pBuf] & ~mask;
break;
case INVERSE:
buffer[pBuf] = buffer[pBuf] ^ mask;
break;
}
}
}
/**
* This static method returns all the details of the class without it having
* to be constructed. It has description, categories, dependencies, and peer
* definitions.
*
* @return ServiceType - returns all the data
*
*/
static public ServiceType getMetaData() {
ServiceType meta = new ServiceType(OledSsd1306.class.getCanonicalName());
meta.addDescription("OLED driver using SSD1306 driver and the i2c protocol");
meta.addCategory("i2c", "control");
meta.setAvailable(true);
meta.setSponsor("Mats");
return meta;
}
@Override
public void setController(DeviceController controller) {
setController(controller);
}
@Override
public boolean isAttached() {
return isControllerSet;
}
}
|
package org.sunflow.core.light;
import org.sunflow.SunflowAPI;
import org.sunflow.core.IntersectionState;
import org.sunflow.core.LightSample;
import org.sunflow.core.LightSource;
import org.sunflow.core.ParameterList;
import org.sunflow.core.PrimitiveList;
import org.sunflow.core.Ray;
import org.sunflow.core.Shader;
import org.sunflow.core.ShadingState;
import org.sunflow.image.ChromaticitySpectrum;
import org.sunflow.image.Color;
import org.sunflow.image.ConstantSpectralCurve;
import org.sunflow.image.IrregularSpectralCurve;
import org.sunflow.image.RGBSpace;
import org.sunflow.image.RegularSpectralCurve;
import org.sunflow.image.SpectralCurve;
import org.sunflow.image.XYZColor;
import org.sunflow.math.BoundingBox;
import org.sunflow.math.MathUtils;
import org.sunflow.math.Matrix4;
import org.sunflow.math.OrthoNormalBasis;
import org.sunflow.math.Point3;
import org.sunflow.math.Vector3;
public class SunSkyLight implements LightSource, PrimitiveList, Shader {
// sunflow parameters
private int numSkySamples;
private OrthoNormalBasis basis;
// parameters to the model
private Vector3 sunDirWorld;
private float turbidity;
// derived quantities
private Vector3 sunDir;
private SpectralCurve sunSpectralRadiance;
private Color sunColor;
private float sunTheta;
private double zenithY, zenithx, zenithy;
private final double[] perezY = new double[5];
private final double[] perezx = new double[5];
private final double[] perezy = new double[5];
private float jacobian;
private float[] colHistogram;
private float[][] imageHistogram;
// constant data
private static final float[] solAmplitudes = { 165.5f, 162.3f, 211.2f,
258.8f, 258.2f, 242.3f, 267.6f, 296.6f, 305.4f, 300.6f, 306.6f,
288.3f, 287.1f, 278.2f, 271.0f, 272.3f, 263.6f, 255.0f, 250.6f,
253.1f, 253.5f, 251.3f, 246.3f, 241.7f, 236.8f, 232.1f, 228.2f,
223.4f, 219.7f, 215.3f, 211.0f, 207.3f, 202.4f, 198.7f, 194.3f,
190.7f, 186.3f, 182.6f };
private static final RegularSpectralCurve solCurve = new RegularSpectralCurve(solAmplitudes, 380, 750);
private static final float[] k_oWavelengths = { 300, 305, 310, 315, 320,
325, 330, 335, 340, 345, 350, 355, 445, 450, 455, 460, 465, 470,
475, 480, 485, 490, 495, 500, 505, 510, 515, 520, 525, 530, 535,
540, 545, 550, 555, 560, 565, 570, 575, 580, 585, 590, 595, 600,
605, 610, 620, 630, 640, 650, 660, 670, 680, 690, 700, 710, 720,
730, 740, 750, 760, 770, 780, 790, };
private static final float[] k_oAmplitudes = { 10.0f, 4.8f, 2.7f, 1.35f,
.8f, .380f, .160f, .075f, .04f, .019f, .007f, .0f, .003f, .003f,
.004f, .006f, .008f, .009f, .012f, .014f, .017f, .021f, .025f,
.03f, .035f, .04f, .045f, .048f, .057f, .063f, .07f, .075f, .08f,
.085f, .095f, .103f, .110f, .12f, .122f, .12f, .118f, .115f, .12f,
.125f, .130f, .12f, .105f, .09f, .079f, .067f, .057f, .048f, .036f,
.028f, .023f, .018f, .014f, .011f, .010f, .009f, .007f, .004f, .0f,
.0f };
private static final float[] k_gWavelengths = { 759, 760, 770, 771 };
private static final float[] k_gAmplitudes = { 0, 3.0f, 0.210f, 0 };
private static final float[] k_waWavelengths = { 689, 690, 700, 710, 720,
730, 740, 750, 760, 770, 780, 790, 800 };
private static final float[] k_waAmplitudes = { 0f, 0.160e-1f, 0.240e-1f,
0.125e-1f, 0.100e+1f, 0.870f, 0.610e-1f, 0.100e-2f, 0.100e-4f,
0.100e-4f, 0.600e-3f, 0.175e-1f, 0.360e-1f };
private static final IrregularSpectralCurve k_oCurve = new IrregularSpectralCurve(k_oWavelengths, k_oAmplitudes);
private static final IrregularSpectralCurve k_gCurve = new IrregularSpectralCurve(k_gWavelengths, k_gAmplitudes);
private static final IrregularSpectralCurve k_waCurve = new IrregularSpectralCurve(k_waWavelengths, k_waAmplitudes);
public SunSkyLight() {
numSkySamples = 64;
sunDirWorld = new Vector3(1, 1, 1);
turbidity = 6;
basis = OrthoNormalBasis.makeFromWV(new Vector3(0, 0, 1), new Vector3(0, 1, 0));
initSunSky();
}
private SpectralCurve computeAttenuatedSunlight(float theta, float turbidity) {
float[] data = new float[91]; // holds the sunsky curve data
final double alpha = 1.3;
final double lozone = 0.35;
final double w = 2.0;
double beta = 0.04608365822050 * turbidity - 0.04586025928522;
// Relative optical mass
double m = 1.0 / (Math.cos(theta) + 0.000940 * Math.pow(1.6386 - theta, -1.253));
for (int i = 0, lambda = 350; lambda <= 800; i++, lambda += 5) {
// Rayleigh scattering
double tauR = Math.exp(-m * 0.008735 * Math.pow((double) lambda / 1000.0, -4.08));
// Aerosol (water + dust) attenuation
double tauA = Math.exp(-m * beta * Math.pow((double) lambda / 1000.0, -alpha));
// Attenuation due to ozone absorption
double tauO = Math.exp(-m * k_oCurve.sample(lambda) * lozone);
// Attenuation due to mixed gases absorption
double tauG = Math.exp(-1.41 * k_gCurve.sample(lambda) * m / Math.pow(1.0 + 118.93 * k_gCurve.sample(lambda) * m, 0.45));
// Attenuation due to water vapor absorption
double tauWA = Math.exp(-0.2385 * k_waCurve.sample(lambda) * w * m / Math.pow(1.0 + 20.07 * k_waCurve.sample(lambda) * w * m, 0.45));
// 100.0 comes from solAmplitudes begin in wrong units.
double amp = /*100.0 * */solCurve.sample(lambda) * tauR * tauA * tauO * tauG * tauWA;
data[i] = (float) amp;
}
return new RegularSpectralCurve(data, 350, 800);
}
private double perezFunction(final double[] lam, double theta, double gamma, double lvz) {
double den = ((1.0 + lam[0] * Math.exp(lam[1])) * (1.0 + lam[2] * Math.exp(lam[3] * sunTheta) + lam[4] * Math.cos(sunTheta) * Math.cos(sunTheta)));
double num = ((1.0 + lam[0] * Math.exp(lam[1] / Math.cos(theta))) * (1.0 + lam[2] * Math.exp(lam[3] * gamma) + lam[4] * Math.cos(gamma) * Math.cos(gamma)));
return lvz * num / den;
}
private void initSunSky() {
// perform all the required initialization of constants
sunDirWorld.normalize();
sunDir = basis.untransform(sunDirWorld, new Vector3());
sunDir.normalize();
sunTheta = (float) Math.acos(MathUtils.clamp(sunDir.z, -1, 1));
if (sunDir.z > 0) {
sunSpectralRadiance = computeAttenuatedSunlight(sunTheta, turbidity);
// produce color suitable for rendering
sunColor = RGBSpace.SRGB.convertXYZtoRGB(sunSpectralRadiance.toXYZ().mul(1e-4f)).constrainRGB();
} else {
sunSpectralRadiance = new ConstantSpectralCurve(0);
}
// sunSolidAngle = (float) (0.25 * Math.PI * 1.39 * 1.39 / (150 * 150));
float theta2 = sunTheta * sunTheta;
float theta3 = sunTheta * theta2;
float T = turbidity;
float T2 = turbidity * turbidity;
double chi = (4.0 / 9.0 - T / 120.0) * (Math.PI - 2.0 * sunTheta);
zenithY = (4.0453 * T - 4.9710) * Math.tan(chi) - 0.2155 * T + 2.4192;
zenithY *= 1000; /* conversion from kcd/m^2 to cd/m^2 */
zenithx = (0.00165 * theta3 - 0.00374 * theta2 + 0.00208 * sunTheta + 0) * T2 + (-0.02902 * theta3 + 0.06377 * theta2 - 0.03202 * sunTheta + 0.00394) * T + (0.11693 * theta3 - 0.21196 * theta2 + 0.06052 * sunTheta + 0.25885);
zenithy = (0.00275 * theta3 - 0.00610 * theta2 + 0.00316 * sunTheta + 0) * T2 + (-0.04212 * theta3 + 0.08970 * theta2 - 0.04153 * sunTheta + 0.00515) * T + (0.15346 * theta3 - 0.26756 * theta2 + 0.06669 * sunTheta + 0.26688);
perezY[0] = 0.17872 * T - 1.46303;
perezY[1] = -0.35540 * T + 0.42749;
perezY[2] = -0.02266 * T + 5.32505;
perezY[3] = 0.12064 * T - 2.57705;
perezY[4] = -0.06696 * T + 0.37027;
perezx[0] = -0.01925 * T - 0.25922;
perezx[1] = -0.06651 * T + 0.00081;
perezx[2] = -0.00041 * T + 0.21247;
perezx[3] = -0.06409 * T - 0.89887;
perezx[4] = -0.00325 * T + 0.04517;
perezy[0] = -0.01669 * T - 0.26078;
perezy[1] = -0.09495 * T + 0.00921;
perezy[2] = -0.00792 * T + 0.21023;
perezy[3] = -0.04405 * T - 1.65369;
perezy[4] = -0.01092 * T + 0.05291;
final int w = 32, h = 32;
imageHistogram = new float[w][h];
colHistogram = new float[w];
float du = 1.0f / w;
float dv = 1.0f / h;
for (int x = 0; x < w; x++) {
for (int y = 0; y < h; y++) {
float u = (x + 0.5f) * du;
float v = (y + 0.5f) * dv;
Color c = getSkyRGB(getDirection(u, v));
imageHistogram[x][y] = c.getLuminance() * (float) Math.sin(Math.PI * v);
if (y > 0)
imageHistogram[x][y] += imageHistogram[x][y - 1];
}
colHistogram[x] = imageHistogram[x][h - 1];
if (x > 0)
colHistogram[x] += colHistogram[x - 1];
for (int y = 0; y < h; y++)
imageHistogram[x][y] /= imageHistogram[x][h - 1];
}
for (int x = 0; x < w; x++)
colHistogram[x] /= colHistogram[w - 1];
jacobian = (float) (2 * Math.PI * Math.PI) / (w * h);
}
public boolean update(ParameterList pl, SunflowAPI api) {
Vector3 up = pl.getVector("up", null);
Vector3 east = pl.getVector("east", null);
if (up != null && east != null)
basis = OrthoNormalBasis.makeFromWV(up, east);
else if (up != null)
basis = OrthoNormalBasis.makeFromW(up);
numSkySamples = pl.getInt("samples", numSkySamples);
sunDirWorld = pl.getVector("sundir", sunDirWorld);
turbidity = pl.getFloat("turbidity", turbidity);
// recompute model
initSunSky();
return true;
}
public void init(String name, SunflowAPI api) {
// register this object with the api properly
api.geometry(name, this);
api.shader(name + ".shader", this);
api.parameter("shaders", name + ".shader");
api.instance(name + ".instance", name);
api.light(name + ".light", this);
}
private Color getSkyRGB(Vector3 dir) {
if (dir.z < 0)
return Color.BLACK;
if (dir.z < 0.001f)
dir.z = 0.001f;
dir.normalize();
double theta = Math.acos(MathUtils.clamp(dir.z, -1, 1));
double gamma = Math.acos(MathUtils.clamp(Vector3.dot(dir, sunDir), -1, 1));
double x = perezFunction(perezx, theta, gamma, zenithx);
double y = perezFunction(perezy, theta, gamma, zenithy);
double Y = perezFunction(perezY, theta, gamma, zenithY) * 1e-4;
XYZColor c = ChromaticitySpectrum.get((float) x, (float) y);
// XYZColor c = new ChromaticitySpectrum((float) x, (float) y).toXYZ();
float X = (float) (c.getX() * Y / c.getY());
float Z = (float) (c.getZ() * Y / c.getY());
return RGBSpace.SRGB.convertXYZtoRGB(X, (float) Y, Z);
}
public int getNumSamples() {
return 1 + numSkySamples;
}
public int getLowSamples() {
return 2;
}
public void getPhoton(double randX1, double randY1, double randX2, double randY2, Point3 p, Vector3 dir, Color power) {
// FIXME: not implemented
}
public float getPower() {
return 0;
}
public void getSample(int i, int n, ShadingState state, LightSample dest) {
if (i == 0) {
if (Vector3.dot(sunDirWorld, state.getGeoNormal()) > 0 && Vector3.dot(sunDirWorld, state.getNormal()) > 0) {
dest.setShadowRay(new Ray(state.getPoint(), sunDirWorld));
dest.getShadowRay().setMax(Float.MAX_VALUE);
dest.setRadiance(sunColor, sunColor);
dest.getDiffuseRadiance().mul(n);
dest.getSpecularRadiance().mul(n);
dest.traceShadow(state);
}
} else {
// random offset on unit square, we use the infinite version of
// getRandom because the light sampling is adaptive
double randX = state.getRandom(i - 1, 0);
double randY = state.getRandom(i - 1, 1);
int x = 0;
while (randX >= colHistogram[x] && x < colHistogram.length - 1)
x++;
float[] rowHistogram = imageHistogram[x];
int y = 0;
while (randY >= rowHistogram[y] && y < rowHistogram.length - 1)
y++;
// sample from (x, y)
float u = (float) ((x == 0) ? (randX / colHistogram[0]) : ((randX - colHistogram[x - 1]) / (colHistogram[x] - colHistogram[x - 1])));
float v = (float) ((y == 0) ? (randY / rowHistogram[0]) : ((randY - rowHistogram[y - 1]) / (rowHistogram[y] - rowHistogram[y - 1])));
float px = ((x == 0) ? colHistogram[0] : (colHistogram[x] - colHistogram[x - 1]));
float py = ((y == 0) ? rowHistogram[0] : (rowHistogram[y] - rowHistogram[y - 1]));
float su = (x + u) / colHistogram.length;
float sv = (y + v) / rowHistogram.length;
float invP = (float) Math.sin(sv * Math.PI) * jacobian / (px * py);
Vector3 dir = getDirection(su, sv);
basis.transform(dir);
if (Vector3.dot(dir, state.getGeoNormal()) > 0 && Vector3.dot(dir, state.getNormal()) > 0) {
dest.setShadowRay(new Ray(state.getPoint(), dir));
dest.getShadowRay().setMax(Float.MAX_VALUE);
Color radiance = getSkyRGB(basis.untransform(dir));
dest.setRadiance(radiance, radiance);
invP *= (float) n / (float) (n - 1);
dest.getDiffuseRadiance().mul(invP);
dest.getSpecularRadiance().mul(invP);
dest.traceShadow(state);
}
}
}
public boolean isVisible(ShadingState state) {
return true;
}
public PrimitiveList getBakingPrimitives() {
return null;
}
public int getNumPrimitives() {
return 1;
}
public float getPrimitiveBound(int primID, int i) {
return 0;
}
public BoundingBox getWorldBounds(Matrix4 o2w) {
return null;
}
public void intersectPrimitive(Ray r, int primID, IntersectionState state) {
if (r.getMax() == Float.POSITIVE_INFINITY)
state.setIntersection(0, 0, 0);
}
public void prepareShadingState(ShadingState state) {
if (state.includeLights())
state.setShader(this);
}
public Color getRadiance(ShadingState state) {
return getSkyRGB(basis.untransform(state.getRay().getDirection())).constrainRGB();
}
public void scatterPhoton(ShadingState state, Color power) {
// let photon escape
}
private Vector3 getDirection(float u, float v) {
Vector3 dest = new Vector3();
double phi = 0, theta = 0;
theta = u * 2 * Math.PI;
phi = v * Math.PI;
double sin_phi = Math.sin(phi);
dest.x = (float) (-sin_phi * Math.cos(theta));
dest.y = (float) Math.cos(phi);
dest.z = (float) (sin_phi * Math.sin(theta));
return dest;
}
}
|
package org.team2168.commands;
/**
* Turn the flashlight on.
*
* This command doesn't complete. If it is going to be used in a sequence,
* specify a timeout!
*/
public class FlashlightOn extends CommandBase {
public FlashlightOn() {
requires(flashlight);
}
/**
* Called just before this Command runs the first time
*/
protected void initialize() {
}
/**
* Called repeatedly when this Command is scheduled to run
*/
protected void execute() {
flashlight.turnOn();
}
/**
* This command will never complete (we're running it as a default command)
* It will repeatedly set the state of the spike relay output.
*/
protected boolean isFinished() {
return false;
}
/**
* Called once after isFinished returns true
*/
protected void end() {
}
/**
* Called when another command which requires one or more of the same
* subsystems is scheduled to run.
*/
protected void interrupted() {
}
}
|
package org.yi.happy.archive;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintStream;
import java.io.Reader;
import java.io.Writer;
import org.yi.happy.annotate.EntryPoint;
import org.yi.happy.archive.block.EncodedBlock;
import org.yi.happy.archive.block.parser.EncodedBlockParse;
import org.yi.happy.archive.file_system.FileSystem;
import org.yi.happy.archive.file_system.RealFileSystem;
/**
* load a list of files from a volume into a store.
*/
public class VolumeGetMain {
private final FileSystem fs;
private final Reader in;
private final Writer out;
private final PrintStream err;
/**
* create with context.
*
* @param fs
* the file system.
* @param in
* the standard input.
* @param out
* the standard output.
* @param err
* the standard error.
*/
public VolumeGetMain(FileSystem fs, Reader in, Writer out, PrintStream err) {
this.fs = fs;
this.in = in;
this.out = out;
this.err = err;
}
/**
* run the body.
*
* @param args
* the command line.
* @throws IOException
*/
public void run(String... args) throws IOException {
if (args.length != 2) {
out.write("use: store base < list\n");
return;
}
FileBlockStore s = new FileBlockStore(fs, args[0]);
LineCursor in = new LineCursor(this.in);
while (in.next()) {
try {
byte[] data = fs.load(fs.join(args[1], in.get()),
Blocks.MAX_SIZE);
EncodedBlock b = EncodedBlockParse.parse(data);
s.put(b);
} catch (Exception e) {
e.printStackTrace(err);
}
}
}
/**
* Invoke from the command line.
*
* @param args
* the arguments.
* @throws IOException
*/
@EntryPoint
public static void main(String[] args) throws IOException {
FileSystem fs = new RealFileSystem();
Reader in = new InputStreamReader(System.in, "UTF-8");
Writer out = new OutputStreamWriter(System.out, "UTF-8");
PrintStream err = System.err;
new VolumeGetMain(fs, in, out, err).run(args);
out.flush();
}
}
|
package org.jasig.portal;
import java.io.IOException;
import java.net.URL;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSessionBindingEvent;
import org.jasig.portal.jndi.JNDIManager;
import org.jasig.portal.layout.TransientUserLayoutManagerWrapper;
import org.jasig.portal.layout.IUserLayoutChannelDescription;
import org.jasig.portal.layout.IUserLayoutManager;
import org.jasig.portal.layout.UserLayoutManagerFactory;
import org.jasig.portal.security.IPerson;
import org.jasig.portal.services.LogService;
import org.jasig.portal.utils.PropsMatcher;
/**
* UserPreferencesManager is responsible for keeping: user id, user layout, user preferences
* and stylesheet descriptions.
* For method descriptions please see {@link IUserPreferencesManager}.
* @author Peter Kharchenko <a href="mailto:">pkharchenko@interactivebusiness.com</a>
* @version $Revision$
*/
public class UserPreferencesManager implements IUserPreferencesManager {
// user agent mapper for guessing the profile
static PropsMatcher uaMatcher;
private IUserLayoutManager ulm;
private UserPreferences complete_up;
// caching of stylesheet descriptions is recommended
// if they'll take up too much space, we can take them
// out, but cache stylesheet URIs, mime type and serializer name.
// Those are used in every rendering cycle.
private ThemeStylesheetDescription tsd;
private StructureStylesheetDescription ssd;
private boolean unmapped_user_agent = false;
IPerson m_person;
IUserLayoutStore ulsdb = null;
private static final boolean saveUserPreferencesAtLogout = PropertiesManager.getPropertyAsBoolean(UserPreferencesManager.class.getName() + ".save_UserPreferences_at_logout");
/**
* Constructor does the following
* 1. Read layout.properties
* 2. read userLayout from the database
* @param the servlet request object
* @param person object
*/
public UserPreferencesManager (HttpServletRequest req, IPerson person) throws PortalException {
ulm=null;
try {
m_person = person;
// load user preferences
// Should obtain implementation in a different way!!
ulsdb = UserLayoutStoreFactory.getUserLayoutStoreImpl();
// determine user profile
String userAgent = req.getHeader("User-Agent");
UserProfile upl = ulsdb.getUserProfile(m_person, userAgent);
if (upl == null) {
upl = ulsdb.getSystemProfile(userAgent);
}
if(upl==null) {
// try guessing the profile through pattern matching
if(uaMatcher==null) {
// init user agent matcher
URL url = null;
try {
url = this.getClass().getResource("/properties/browser.mappings");
if (url != null) {
uaMatcher = new PropsMatcher(url.openStream());
}
} catch (IOException ioe) {
LogService.log(LogService.ERROR, "UserPreferencesManager::UserPreferencesManager() : Exception occurred while loading browser mapping file: " + url + ". " + ioe);
}
}
if(uaMatcher!=null) {
// try matching
String profileId=uaMatcher.match(userAgent);
if(profileId!=null) {
// user agent has been matched
upl=ulsdb.getSystemProfileById(Integer.parseInt(profileId));
}
}
}
if (upl != null) {
ulm=UserLayoutManagerFactory.getUserLayoutManager(m_person,upl);
try {
complete_up=ulsdb.getUserPreferences(m_person, upl);
} catch (Exception e) {
LogService.log(LogService.ERROR, "UserPreferencesManager(): caught an exception trying to retreive user preferences for user=\"" + m_person.getID() + "\", profile=\"" + upl.getProfileName() + "\".", e);
complete_up=new UserPreferences(upl);
}
try {
// Initialize the JNDI context for this user
JNDIManager.initializeSessionContext(req.getSession(),Integer.toString(m_person.getID()),Integer.toString(upl.getLayoutId()),ulm.getUserLayoutDOM());
} catch(PortalException ipe) {
LogService.log(LogService.ERROR, "UserPreferencesManager(): Could not properly initialize user context", ipe);
}
} else {
// there is no user-defined mapping for this particular browser.
// user should be redirected to a browser-registration page.
unmapped_user_agent = true;
LogService.log(LogService.DEBUG, "UserPreferencesManager::UserPreferencesManager() : unable to find a profile for user \"" + m_person.getID()+"\" and userAgent=\""+ userAgent + "\".");
}
} catch (PortalException pe) {
throw pe;
} catch (Exception e) {
LogService.log(LogService.ERROR, e);
}
}
/**
* A simpler constructor, that only initialises the person object.
* Needed for ancestors.
* @param person an <code>IPerson</code> object.
*/
public UserPreferencesManager(IPerson person) {
m_person=person;
}
/* This function processes request parameters related to
* setting Structure/Theme stylesheet parameters and attributes.
* (uP_sparam, uP_tparam, uP_sfattr, uP_scattr
* uP_tcattr)
* It also processes layout root requests (uP_root) and
* (up_fname)
* @param req current <code>HttpServletRequest</code>
*/
public void processUserPreferencesParameters(HttpServletRequest req) {
// save processing
String saveWhat=req.getParameter("uP_save");
if(saveWhat!=null) {
try {
if(saveWhat.equals("preferences")) {
ulsdb.putUserPreferences(m_person, complete_up);
} else if(saveWhat.equals("layout")) {
ulm.saveUserLayout();
} else if(saveWhat.equals("all")) {
ulsdb.putUserPreferences(m_person, complete_up);
ulm.saveUserLayout();
}
LogService.log(LogService.ERROR, "UserPreferencesManager::processUserPreferencesParameters() : persisted "+saveWhat+" changes.");
} catch (Exception e) {
LogService.log(LogService.ERROR, "UserPreferencesManager::processUserPreferencesParameters() : unable to persist "+saveWhat+" changes. "+e);
}
}
// layout root setting
String root;
if ((root = req.getParameter("uP_root")) != null) {
// If a channel specifies "me" as its root, set the root
// to the channel's subscribe Id
if (root.equals("me")) {
// get uPFile spec and search for "channel" clause
UPFileSpec upfs=new UPFileSpec(req);
root=upfs.getTargetNodeId();
}
if(root!=null) {
complete_up.getStructureStylesheetUserPreferences().putParameterValue("userLayoutRoot", root);
} else {
LogService.log(LogService.ERROR, "UserPreferencesManager::processUserPreferencesParameters() : unable to extract channel ID. servletPath=\""+req.getServletPath()+"\".");
}
}
// fname and root are mutually exclusive and
// should not be used in the same request,
// as an fname is treated as the root target.
String fname = req.getParameter("uP_fname");
if (fname != null) {
// get a subscribe id for the fname
String subId = ulm.getSubscribeId(fname);
if ( ulm instanceof TransientUserLayoutManagerWrapper ){
// get wrapper implementation for focusing
TransientUserLayoutManagerWrapper iulm =
(TransientUserLayoutManagerWrapper) ulm;
// .. and now set it as the focused id
iulm.setFocusedId(subId);
}
complete_up.getStructureStylesheetUserPreferences().putParameterValue("userLayoutRoot",
subId);
LogService.log(LogService.DEBUG,
"UserPreferencesManager::processUserPreferencesParameters() : " +
"setting sfname \" userLayoutRoot" + "\"=\"" + subId + "\".");
}
// other params
String[] sparams = req.getParameterValues("uP_sparam");
if (sparams != null) {
for (int i = 0; i < sparams.length; i++) {
String pValue = req.getParameter(sparams[i]);
complete_up.getStructureStylesheetUserPreferences().putParameterValue(sparams[i], pValue);
LogService.log(LogService.DEBUG, "UserPreferencesManager::processUserPreferencesParameters() : setting sparam \"" + sparams[i] + "\"=\"" + pValue + "\".");
}
}
String[] tparams = req.getParameterValues("uP_tparam");
if (tparams != null) {
for (int i = 0; i < tparams.length; i++) {
String pValue = req.getParameter(tparams[i]);
complete_up.getThemeStylesheetUserPreferences().putParameterValue(tparams[i], pValue);
LogService.log(LogService.DEBUG, "UserPreferencesManager::processUserPreferencesParameters() : setting tparam \"" + tparams[i]+ "\"=\"" + pValue + "\".");
}
}
// attribute processing
// structure transformation
String[] sfattrs = req.getParameterValues("uP_sfattr");
if (sfattrs != null) {
for (int i = 0; i < sfattrs.length; i++) {
String aName = sfattrs[i];
String[] aNode = req.getParameterValues(aName + "_folderId");
if (aNode != null && aNode.length > 0) {
for (int j = 0; j < aNode.length; j++) {
String aValue = req.getParameter(aName + "_" + aNode[j] + "_value");
complete_up.getStructureStylesheetUserPreferences().setFolderAttributeValue(aNode[j], aName, aValue);
LogService.log(LogService.DEBUG, "UserPreferencesManager::processUserPreferencesParameters() : setting sfattr \"" + aName + "\" of \"" + aNode[j] + "\" to \"" + aValue + "\".");
}
}
}
}
String[] scattrs = req.getParameterValues("uP_scattr");
if (scattrs != null) {
for (int i = 0; i < scattrs.length; i++) {
String aName = scattrs[i];
String[] aNode = req.getParameterValues(aName + "_channelId");
if (aNode != null && aNode.length > 0) {
for (int j = 0; j < aNode.length; j++) {
String aValue = req.getParameter(aName + "_" + aNode[j] + "_value");
complete_up.getStructureStylesheetUserPreferences().setChannelAttributeValue(aNode[j], aName, aValue);
LogService.log(LogService.DEBUG, "UserPreferencesManager::processUserPreferencesParameters() : setting scattr \"" + aName + "\" of \"" + aNode[j] + "\" to \"" + aValue + "\".");
}
}
}
}
// theme stylesheet attributes
String[] tcattrs = req.getParameterValues("uP_tcattr");
if (tcattrs != null) {
for (int i = 0; i < tcattrs.length; i++) {
String aName = tcattrs[i];
String[] aNode = req.getParameterValues(aName + "_channelId");
if (aNode != null && aNode.length > 0) {
for (int j = 0; j < aNode.length; j++) {
String aValue = req.getParameter(aName + "_" + aNode[j] + "_value");
complete_up.getThemeStylesheetUserPreferences().setChannelAttributeValue(aNode[j], aName, aValue);
LogService.log(LogService.DEBUG, "UserPreferencesManager::processUserPreferencesParameters() : setting tcattr \"" + aName + "\" of \"" + aNode[j] + "\" to \"" + aValue + "\".");
}
}
}
}
}
/**
* Returns current person object
* @return current <code>IPerson</code>
*/
public IPerson getPerson () {
return (m_person);
}
/**
* Returns a global channel Id given a channel instance Id
* @param channelSubscribeId subscribe id of a channel
* @return channel global id
*/
protected String getChannelPublishId(String channelSubscribeId) throws PortalException {
// Get the channel node from the user's layout
IUserLayoutChannelDescription channel=(IUserLayoutChannelDescription) getUserLayoutManager().getNode(channelSubscribeId);
if(channel!=null) {
return channel.getChannelPublishId();
} else {
return null;
}
}
public boolean isUserAgentUnmapped() {
return unmapped_user_agent;
}
/*
* Resets both user layout and user preferences.
* Note that if any of the two are "null", old values will be used.
*/
public void setNewUserLayoutAndUserPreferences(IUserLayoutManager newUlm, UserPreferences newPreferences) throws PortalException {
try {
if (newPreferences != null) {
// see if the profile has changed
if(complete_up.getProfile().getProfileId()!=newPreferences.getProfile().getProfileId() || complete_up.getProfile().isSystemProfile()!=newPreferences.getProfile().isSystemProfile()) {
// see if a layout was passed
if(newUlm !=null && newUlm.getLayoutId()==newPreferences.getProfile().getLayoutId()) {
// just use a new layout
this.ulm=newUlm;
} else {
// construct a new user layout manager, for a new profile
ulm=UserLayoutManagerFactory.getUserLayoutManager(m_person,newPreferences.getProfile());
}
}
ulsdb.putUserPreferences(m_person, newPreferences);
complete_up=newPreferences;
}
} catch (Exception e) {
LogService.log(LogService.ERROR, e);
throw new GeneralRenderingException(e.getMessage());
}
}
public IUserLayoutManager getUserLayoutManager() {
return ulm;
}
public void finishedSession(HttpSessionBindingEvent bindingEvent) {
// persist the layout and user preferences
try {
if(saveUserPreferencesAtLogout) {
ulsdb.putUserPreferences(m_person, complete_up);
}
ulm.saveUserLayout();
} catch (Exception e) {
LogService.log(LogService.ERROR,"UserPreferencesManager::finishedSession() : unable to persist layout upon session termination !", e);
}
}
public UserPreferences getUserPreferencesCopy() {
return new UserPreferences(this.getUserPreferences());
}
public UserProfile getCurrentProfile() {
return this.getUserPreferences().getProfile();
}
public ThemeStylesheetDescription getThemeStylesheetDescription() throws Exception {
if (this.tsd == null) {
tsd = ulsdb.getThemeStylesheetDescription(this.getCurrentProfile().getThemeStylesheetId());
}
return tsd;
}
public StructureStylesheetDescription getStructureStylesheetDescription() throws Exception {
if (this.ssd == null) {
ssd = ulsdb.getStructureStylesheetDescription(this.getCurrentProfile().getStructureStylesheetId());
}
return ssd;
}
public UserPreferences getUserPreferences() {
return complete_up;
}
}
|
package org.jfree.data.general;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.jfree.chart.util.ParamChecks;
import org.jfree.data.DomainInfo;
import org.jfree.data.DomainOrder;
import org.jfree.data.KeyToGroupMap;
import org.jfree.data.KeyedValues;
import org.jfree.data.Range;
import org.jfree.data.RangeInfo;
import org.jfree.data.category.CategoryDataset;
import org.jfree.data.category.CategoryRangeInfo;
import org.jfree.data.category.DefaultCategoryDataset;
import org.jfree.data.category.IntervalCategoryDataset;
import org.jfree.data.function.Function2D;
import org.jfree.data.statistics.BoxAndWhiskerCategoryDataset;
import org.jfree.data.statistics.BoxAndWhiskerXYDataset;
import org.jfree.data.statistics.MultiValueCategoryDataset;
import org.jfree.data.statistics.StatisticalCategoryDataset;
import org.jfree.data.xy.IntervalXYDataset;
import org.jfree.data.xy.OHLCDataset;
import org.jfree.data.xy.TableXYDataset;
import org.jfree.data.xy.XYDataset;
import org.jfree.data.xy.XYDomainInfo;
import org.jfree.data.xy.XYRangeInfo;
import org.jfree.data.xy.XYSeries;
import org.jfree.data.xy.XYSeriesCollection;
import org.jfree.data.xy.XYZDataset;
import org.jfree.util.ArrayUtilities;
/**
* A collection of useful static methods relating to datasets.
*/
public final class DatasetUtilities {
/**
* Private constructor for non-instanceability.
*/
private DatasetUtilities() {
// now try to instantiate this ;-)
}
/**
* Calculates the total of all the values in a {@link PieDataset}. If
* the dataset contains negative or <code>null</code> values, they are
* ignored.
*
* @param dataset the dataset (<code>null</code> not permitted).
*
* @return The total.
*/
public static double calculatePieDatasetTotal(PieDataset dataset) {
ParamChecks.nullNotPermitted(dataset, "dataset");
List keys = dataset.getKeys();
double totalValue = 0;
Iterator iterator = keys.iterator();
while (iterator.hasNext()) {
Comparable current = (Comparable) iterator.next();
if (current != null) {
Number value = dataset.getValue(current);
double v = 0.0;
if (value != null) {
v = value.doubleValue();
}
if (v > 0) {
totalValue = totalValue + v;
}
}
}
return totalValue;
}
/**
* Creates a pie dataset from a table dataset by taking all the values
* for a single row.
*
* @param dataset the dataset (<code>null</code> not permitted).
* @param rowKey the row key.
*
* @return A pie dataset.
*/
public static PieDataset createPieDatasetForRow(CategoryDataset dataset,
Comparable rowKey) {
int row = dataset.getRowIndex(rowKey);
return createPieDatasetForRow(dataset, row);
}
/**
* Creates a pie dataset from a table dataset by taking all the values
* for a single row.
*
* @param dataset the dataset (<code>null</code> not permitted).
* @param row the row (zero-based index).
*
* @return A pie dataset.
*/
public static PieDataset createPieDatasetForRow(CategoryDataset dataset,
int row) {
DefaultPieDataset result = new DefaultPieDataset();
int columnCount = dataset.getColumnCount();
for (int current = 0; current < columnCount; current++) {
Comparable columnKey = dataset.getColumnKey(current);
result.setValue(columnKey, dataset.getValue(row, current));
}
return result;
}
/**
* Creates a pie dataset from a table dataset by taking all the values
* for a single column.
*
* @param dataset the dataset (<code>null</code> not permitted).
* @param columnKey the column key.
*
* @return A pie dataset.
*/
public static PieDataset createPieDatasetForColumn(CategoryDataset dataset,
Comparable columnKey) {
int column = dataset.getColumnIndex(columnKey);
return createPieDatasetForColumn(dataset, column);
}
/**
* Creates a pie dataset from a {@link CategoryDataset} by taking all the
* values for a single column.
*
* @param dataset the dataset (<code>null</code> not permitted).
* @param column the column (zero-based index).
*
* @return A pie dataset.
*/
public static PieDataset createPieDatasetForColumn(CategoryDataset dataset,
int column) {
DefaultPieDataset result = new DefaultPieDataset();
int rowCount = dataset.getRowCount();
for (int i = 0; i < rowCount; i++) {
Comparable rowKey = dataset.getRowKey(i);
result.setValue(rowKey, dataset.getValue(i, column));
}
return result;
}
/**
* Creates a new pie dataset based on the supplied dataset, but modified
* by aggregating all the low value items (those whose value is lower
* than the <code>percentThreshold</code>) into a single item with the
* key "Other".
*
* @param source the source dataset (<code>null</code> not permitted).
* @param key a new key for the aggregated items (<code>null</code> not
* permitted).
* @param minimumPercent the percent threshold.
*
* @return The pie dataset with (possibly) aggregated items.
*/
public static PieDataset createConsolidatedPieDataset(PieDataset source,
Comparable key, double minimumPercent) {
return DatasetUtilities.createConsolidatedPieDataset(source, key,
minimumPercent, 2);
}
/**
* Creates a new pie dataset based on the supplied dataset, but modified
* by aggregating all the low value items (those whose value is lower
* than the <code>percentThreshold</code>) into a single item. The
* aggregated items are assigned the specified key. Aggregation only
* occurs if there are at least <code>minItems</code> items to aggregate.
*
* @param source the source dataset (<code>null</code> not permitted).
* @param key the key to represent the aggregated items.
* @param minimumPercent the percent threshold (ten percent is 0.10).
* @param minItems only aggregate low values if there are at least this
* many.
*
* @return The pie dataset with (possibly) aggregated items.
*/
public static PieDataset createConsolidatedPieDataset(PieDataset source,
Comparable key, double minimumPercent, int minItems) {
DefaultPieDataset result = new DefaultPieDataset();
double total = DatasetUtilities.calculatePieDatasetTotal(source);
// Iterate and find all keys below threshold percentThreshold
List keys = source.getKeys();
ArrayList otherKeys = new ArrayList();
Iterator iterator = keys.iterator();
while (iterator.hasNext()) {
Comparable currentKey = (Comparable) iterator.next();
Number dataValue = source.getValue(currentKey);
if (dataValue != null) {
double value = dataValue.doubleValue();
if (value / total < minimumPercent) {
otherKeys.add(currentKey);
}
}
}
// Create new dataset with keys above threshold percentThreshold
iterator = keys.iterator();
double otherValue = 0;
while (iterator.hasNext()) {
Comparable currentKey = (Comparable) iterator.next();
Number dataValue = source.getValue(currentKey);
if (dataValue != null) {
if (otherKeys.contains(currentKey)
&& otherKeys.size() >= minItems) {
// Do not add key to dataset
otherValue += dataValue.doubleValue();
}
else {
// Add key to dataset
result.setValue(currentKey, dataValue);
}
}
}
// Add other category if applicable
if (otherKeys.size() >= minItems) {
result.setValue(key, otherValue);
}
return result;
}
public static CategoryDataset createCategoryDataset(String rowKeyPrefix,
String columnKeyPrefix, double[][] data) {
DefaultCategoryDataset result = new DefaultCategoryDataset();
for (int r = 0; r < data.length; r++) {
String rowKey = rowKeyPrefix + (r + 1);
for (int c = 0; c < data[r].length; c++) {
String columnKey = columnKeyPrefix + (c + 1);
result.addValue(new Double(data[r][c]), rowKey, columnKey);
}
}
return result;
}
public static CategoryDataset createCategoryDataset(String rowKeyPrefix,
String columnKeyPrefix, Number[][] data) {
DefaultCategoryDataset result = new DefaultCategoryDataset();
for (int r = 0; r < data.length; r++) {
String rowKey = rowKeyPrefix + (r + 1);
for (int c = 0; c < data[r].length; c++) {
String columnKey = columnKeyPrefix + (c + 1);
result.addValue(data[r][c], rowKey, columnKey);
}
}
return result;
}
/**
* Creates a {@link CategoryDataset} that contains a copy of the data in
* an array (instances of <code>Double</code> are created to represent the
* data items).
* <p>
* Row and column keys are taken from the supplied arrays.
*
* @param rowKeys the row keys (<code>null</code> not permitted).
* @param columnKeys the column keys (<code>null</code> not permitted).
* @param data the data.
*
* @return The dataset.
*/
public static CategoryDataset createCategoryDataset(Comparable[] rowKeys,
Comparable[] columnKeys, double[][] data) {
ParamChecks.nullNotPermitted(rowKeys, "rowKeys");
ParamChecks.nullNotPermitted(columnKeys, "columnKeys");
if (ArrayUtilities.hasDuplicateItems(rowKeys)) {
throw new IllegalArgumentException("Duplicate items in 'rowKeys'.");
}
if (ArrayUtilities.hasDuplicateItems(columnKeys)) {
throw new IllegalArgumentException(
"Duplicate items in 'columnKeys'.");
}
if (rowKeys.length != data.length) {
throw new IllegalArgumentException(
"The number of row keys does not match the number of rows in "
+ "the data array.");
}
int columnCount = 0;
for (int r = 0; r < data.length; r++) {
columnCount = Math.max(columnCount, data[r].length);
}
if (columnKeys.length != columnCount) {
throw new IllegalArgumentException(
"The number of column keys does not match the number of "
+ "columns in the data array.");
}
// now do the work...
DefaultCategoryDataset result = new DefaultCategoryDataset();
for (int r = 0; r < data.length; r++) {
Comparable rowKey = rowKeys[r];
for (int c = 0; c < data[r].length; c++) {
Comparable columnKey = columnKeys[c];
result.addValue(new Double(data[r][c]), rowKey, columnKey);
}
}
return result;
}
/**
* Creates a {@link CategoryDataset} by copying the data from the supplied
* {@link KeyedValues} instance.
*
* @param rowKey the row key (<code>null</code> not permitted).
* @param rowData the row data (<code>null</code> not permitted).
*
* @return A dataset.
*/
public static CategoryDataset createCategoryDataset(Comparable rowKey,
KeyedValues rowData) {
ParamChecks.nullNotPermitted(rowKey, "rowKey");
ParamChecks.nullNotPermitted(rowData, "rowData");
DefaultCategoryDataset result = new DefaultCategoryDataset();
for (int i = 0; i < rowData.getItemCount(); i++) {
result.addValue(rowData.getValue(i), rowKey, rowData.getKey(i));
}
return result;
}
/**
* Creates an {@link XYDataset} by sampling the specified function over a
* fixed range.
*
* @param f the function (<code>null</code> not permitted).
* @param start the start value for the range.
* @param end the end value for the range.
* @param samples the number of sample points (must be > 1).
* @param seriesKey the key to give the resulting series
* (<code>null</code> not permitted).
*
* @return A dataset.
*/
public static XYDataset sampleFunction2D(Function2D f, double start,
double end, int samples, Comparable seriesKey) {
// defer argument checking
XYSeries series = sampleFunction2DToSeries(f, start, end, samples,
seriesKey);
XYSeriesCollection collection = new XYSeriesCollection(series);
return collection;
}
/**
* Creates an {@link XYSeries} by sampling the specified function over a
* fixed range.
*
* @param f the function (<code>null</code> not permitted).
* @param start the start value for the range.
* @param end the end value for the range.
* @param samples the number of sample points (must be > 1).
* @param seriesKey the key to give the resulting series
* (<code>null</code> not permitted).
*
* @return A series.
*
* @since 1.0.13
*/
public static XYSeries sampleFunction2DToSeries(Function2D f,
double start, double end, int samples, Comparable seriesKey) {
ParamChecks.nullNotPermitted(f, "f");
ParamChecks.nullNotPermitted(seriesKey, "seriesKey");
if (start >= end) {
throw new IllegalArgumentException("Requires 'start' < 'end'.");
}
if (samples < 2) {
throw new IllegalArgumentException("Requires 'samples' > 1");
}
XYSeries series = new XYSeries(seriesKey);
double step = (end - start) / (samples - 1);
for (int i = 0; i < samples; i++) {
double x = start + (step * i);
series.add(x, f.getValue(x));
}
return series;
}
/**
* Returns <code>true</code> if the dataset is empty (or <code>null</code>),
* and <code>false</code> otherwise.
*
* @param dataset the dataset (<code>null</code> permitted).
*
* @return A boolean.
*/
public static boolean isEmptyOrNull(PieDataset dataset) {
if (dataset == null) {
return true;
}
int itemCount = dataset.getItemCount();
if (itemCount == 0) {
return true;
}
for (int item = 0; item < itemCount; item++) {
Number y = dataset.getValue(item);
if (y != null) {
double yy = y.doubleValue();
if (yy > 0.0) {
return false;
}
}
}
return true;
}
/**
* Returns <code>true</code> if the dataset is empty (or <code>null</code>),
* and <code>false</code> otherwise.
*
* @param dataset the dataset (<code>null</code> permitted).
*
* @return A boolean.
*/
public static boolean isEmptyOrNull(CategoryDataset dataset) {
if (dataset == null) {
return true;
}
int rowCount = dataset.getRowCount();
int columnCount = dataset.getColumnCount();
if (rowCount == 0 || columnCount == 0) {
return true;
}
for (int r = 0; r < rowCount; r++) {
for (int c = 0; c < columnCount; c++) {
if (dataset.getValue(r, c) != null) {
return false;
}
}
}
return true;
}
/**
* Returns <code>true</code> if the dataset is empty (or <code>null</code>),
* and <code>false</code> otherwise.
*
* @param dataset the dataset (<code>null</code> permitted).
*
* @return A boolean.
*/
public static boolean isEmptyOrNull(XYDataset dataset) {
if (dataset != null) {
for (int s = 0; s < dataset.getSeriesCount(); s++) {
if (dataset.getItemCount(s) > 0) {
return false;
}
}
}
return true;
}
/**
* Returns the range of values in the domain (x-values) of a dataset.
*
* @param dataset the dataset (<code>null</code> not permitted).
*
* @return The range of values (possibly <code>null</code>).
*/
public static Range findDomainBounds(XYDataset dataset) {
return findDomainBounds(dataset, true);
}
/**
* Returns the range of values in the domain (x-values) of a dataset.
*
* @param dataset the dataset (<code>null</code> not permitted).
* @param includeInterval determines whether or not the x-interval is taken
* into account (only applies if the dataset is an
* {@link IntervalXYDataset}).
*
* @return The range of values (possibly <code>null</code>).
*/
public static Range findDomainBounds(XYDataset dataset,
boolean includeInterval) {
ParamChecks.nullNotPermitted(dataset, "dataset");
Range result;
// if the dataset implements DomainInfo, life is easier
if (dataset instanceof DomainInfo) {
DomainInfo info = (DomainInfo) dataset;
result = info.getDomainBounds(includeInterval);
}
else {
result = iterateDomainBounds(dataset, includeInterval);
}
return result;
}
/**
* Returns the bounds of the x-values in the specified <code>dataset</code>
* taking into account only the visible series and including any x-interval
* if requested.
*
* @param dataset the dataset (<code>null</code> not permitted).
* @param visibleSeriesKeys the visible series keys (<code>null</code>
* not permitted).
* @param includeInterval include the x-interval (if any)?
*
* @return The bounds (or <code>null</code> if the dataset contains no
* values.
*
* @since 1.0.13
*/
public static Range findDomainBounds(XYDataset dataset,
List visibleSeriesKeys, boolean includeInterval) {
ParamChecks.nullNotPermitted(dataset, "dataset");
Range result;
if (dataset instanceof XYDomainInfo) {
XYDomainInfo info = (XYDomainInfo) dataset;
result = info.getDomainBounds(visibleSeriesKeys, includeInterval);
}
else {
result = iterateToFindDomainBounds(dataset, visibleSeriesKeys,
includeInterval);
}
return result;
}
/**
* Iterates over the items in an {@link XYDataset} to find
* the range of x-values. If the dataset is an instance of
* {@link IntervalXYDataset}, the starting and ending x-values
* will be used for the bounds calculation.
*
* @param dataset the dataset (<code>null</code> not permitted).
*
* @return The range (possibly <code>null</code>).
*/
public static Range iterateDomainBounds(XYDataset dataset) {
return iterateDomainBounds(dataset, true);
}
/**
* Iterates over the items in an {@link XYDataset} to find
* the range of x-values.
*
* @param dataset the dataset (<code>null</code> not permitted).
* @param includeInterval a flag that determines, for an
* {@link IntervalXYDataset}, whether the x-interval or just the
* x-value is used to determine the overall range.
*
* @return The range (possibly <code>null</code>).
*/
public static Range iterateDomainBounds(XYDataset dataset,
boolean includeInterval) {
ParamChecks.nullNotPermitted(dataset, "dataset");
double minimum = Double.POSITIVE_INFINITY;
double maximum = Double.NEGATIVE_INFINITY;
int seriesCount = dataset.getSeriesCount();
double lvalue, uvalue;
if (includeInterval && dataset instanceof IntervalXYDataset) {
IntervalXYDataset intervalXYData = (IntervalXYDataset) dataset;
for (int series = 0; series < seriesCount; series++) {
int itemCount = dataset.getItemCount(series);
for (int item = 0; item < itemCount; item++) {
double value = intervalXYData.getXValue(series, item);
lvalue = intervalXYData.getStartXValue(series, item);
uvalue = intervalXYData.getEndXValue(series, item);
if (!Double.isNaN(value)) {
minimum = Math.min(minimum, value);
maximum = Math.max(maximum, value);
}
if (!Double.isNaN(lvalue)) {
minimum = Math.min(minimum, lvalue);
maximum = Math.max(maximum, lvalue);
}
if (!Double.isNaN(uvalue)) {
minimum = Math.min(minimum, uvalue);
maximum = Math.max(maximum, uvalue);
}
}
}
}
else {
for (int series = 0; series < seriesCount; series++) {
int itemCount = dataset.getItemCount(series);
for (int item = 0; item < itemCount; item++) {
lvalue = dataset.getXValue(series, item);
uvalue = lvalue;
if (!Double.isNaN(lvalue)) {
minimum = Math.min(minimum, lvalue);
maximum = Math.max(maximum, uvalue);
}
}
}
}
if (minimum > maximum) {
return null;
}
else {
return new Range(minimum, maximum);
}
}
/**
* Returns the range of values in the range for the dataset.
*
* @param dataset the dataset (<code>null</code> not permitted).
*
* @return The range (possibly <code>null</code>).
*/
public static Range findRangeBounds(CategoryDataset dataset) {
return findRangeBounds(dataset, true);
}
/**
* Returns the range of values in the range for the dataset.
*
* @param dataset the dataset (<code>null</code> not permitted).
* @param includeInterval a flag that determines whether or not the
* y-interval is taken into account.
*
* @return The range (possibly <code>null</code>).
*/
public static Range findRangeBounds(CategoryDataset dataset,
boolean includeInterval) {
ParamChecks.nullNotPermitted(dataset, "dataset");
Range result;
if (dataset instanceof RangeInfo) {
RangeInfo info = (RangeInfo) dataset;
result = info.getRangeBounds(includeInterval);
}
else {
result = iterateRangeBounds(dataset, includeInterval);
}
return result;
}
/**
* Finds the bounds of the y-values in the specified dataset, including
* only those series that are listed in visibleSeriesKeys.
*
* @param dataset the dataset (<code>null</code> not permitted).
* @param visibleSeriesKeys the keys for the visible series
* (<code>null</code> not permitted).
* @param includeInterval include the y-interval (if the dataset has a
* y-interval).
*
* @return The data bounds.
*
* @since 1.0.13
*/
public static Range findRangeBounds(CategoryDataset dataset,
List visibleSeriesKeys, boolean includeInterval) {
ParamChecks.nullNotPermitted(dataset, "dataset");
Range result;
if (dataset instanceof CategoryRangeInfo) {
CategoryRangeInfo info = (CategoryRangeInfo) dataset;
result = info.getRangeBounds(visibleSeriesKeys, includeInterval);
}
else {
result = iterateToFindRangeBounds(dataset, visibleSeriesKeys,
includeInterval);
}
return result;
}
/**
* Returns the range of values in the range for the dataset. This method
* is the partner for the {@link #findDomainBounds(XYDataset)} method.
*
* @param dataset the dataset (<code>null</code> not permitted).
*
* @return The range (possibly <code>null</code>).
*/
public static Range findRangeBounds(XYDataset dataset) {
return findRangeBounds(dataset, true);
}
/**
* Returns the range of values in the range for the dataset. This method
* is the partner for the {@link #findDomainBounds(XYDataset, boolean)}
* method.
*
* @param dataset the dataset (<code>null</code> not permitted).
* @param includeInterval a flag that determines whether or not the
* y-interval is taken into account.
*
* @return The range (possibly <code>null</code>).
*/
public static Range findRangeBounds(XYDataset dataset,
boolean includeInterval) {
ParamChecks.nullNotPermitted(dataset, "dataset");
Range result;
if (dataset instanceof RangeInfo) {
RangeInfo info = (RangeInfo) dataset;
result = info.getRangeBounds(includeInterval);
}
else {
result = iterateRangeBounds(dataset, includeInterval);
}
return result;
}
/**
* Finds the bounds of the y-values in the specified dataset, including
* only those series that are listed in visibleSeriesKeys, and those items
* whose x-values fall within the specified range.
*
* @param dataset the dataset (<code>null</code> not permitted).
* @param visibleSeriesKeys the keys for the visible series
* (<code>null</code> not permitted).
* @param xRange the x-range (<code>null</code> not permitted).
* @param includeInterval include the y-interval (if the dataset has a
* y-interval).
*
* @return The data bounds.
*
* @since 1.0.13
*/
public static Range findRangeBounds(XYDataset dataset,
List visibleSeriesKeys, Range xRange, boolean includeInterval) {
ParamChecks.nullNotPermitted(dataset, "dataset");
Range result;
if (dataset instanceof XYRangeInfo) {
XYRangeInfo info = (XYRangeInfo) dataset;
result = info.getRangeBounds(visibleSeriesKeys, xRange,
includeInterval);
}
else {
result = iterateToFindRangeBounds(dataset, visibleSeriesKeys,
xRange, includeInterval);
}
return result;
}
/**
* Iterates over the data item of the category dataset to find
* the range bounds.
*
* @param dataset the dataset (<code>null</code> not permitted).
* @param includeInterval a flag that determines whether or not the
* y-interval is taken into account.
*
* @return The range (possibly <code>null</code>).
*
* @deprecated As of 1.0.10, use
* {@link #iterateRangeBounds(CategoryDataset, boolean)}.
*/
public static Range iterateCategoryRangeBounds(CategoryDataset dataset,
boolean includeInterval) {
return iterateRangeBounds(dataset, includeInterval);
}
/**
* Iterates over the data item of the category dataset to find
* the range bounds.
*
* @param dataset the dataset (<code>null</code> not permitted).
*
* @return The range (possibly <code>null</code>).
*
* @since 1.0.10
*/
public static Range iterateRangeBounds(CategoryDataset dataset) {
return iterateRangeBounds(dataset, true);
}
/**
* Iterates over the data item of the category dataset to find
* the range bounds.
*
* @param dataset the dataset (<code>null</code> not permitted).
* @param includeInterval a flag that determines whether or not the
* y-interval is taken into account.
*
* @return The range (possibly <code>null</code>).
*
* @since 1.0.10
*/
public static Range iterateRangeBounds(CategoryDataset dataset,
boolean includeInterval) {
double minimum = Double.POSITIVE_INFINITY;
double maximum = Double.NEGATIVE_INFINITY;
int rowCount = dataset.getRowCount();
int columnCount = dataset.getColumnCount();
if (includeInterval && dataset instanceof IntervalCategoryDataset) {
// handle the special case where the dataset has y-intervals that
// we want to measure
IntervalCategoryDataset icd = (IntervalCategoryDataset) dataset;
Number value, lvalue, uvalue;
for (int row = 0; row < rowCount; row++) {
for (int column = 0; column < columnCount; column++) {
value = icd.getValue(row, column);
double v;
if ((value != null)
&& !Double.isNaN(v = value.doubleValue())) {
minimum = Math.min(v, minimum);
maximum = Math.max(v, maximum);
}
lvalue = icd.getStartValue(row, column);
if (lvalue != null
&& !Double.isNaN(v = lvalue.doubleValue())) {
minimum = Math.min(v, minimum);
maximum = Math.max(v, maximum);
}
uvalue = icd.getEndValue(row, column);
if (uvalue != null
&& !Double.isNaN(v = uvalue.doubleValue())) {
minimum = Math.min(v, minimum);
maximum = Math.max(v, maximum);
}
}
}
}
else {
// handle the standard case (plain CategoryDataset)
for (int row = 0; row < rowCount; row++) {
for (int column = 0; column < columnCount; column++) {
Number value = dataset.getValue(row, column);
if (value != null) {
double v = value.doubleValue();
if (!Double.isNaN(v)) {
minimum = Math.min(minimum, v);
maximum = Math.max(maximum, v);
}
}
}
}
}
if (minimum == Double.POSITIVE_INFINITY) {
return null;
}
else {
return new Range(minimum, maximum);
}
}
/**
* Iterates over the data item of the category dataset to find
* the range bounds.
*
* @param dataset the dataset (<code>null</code> not permitted).
* @param includeInterval a flag that determines whether or not the
* y-interval is taken into account.
* @param visibleSeriesKeys the visible series keys.
*
* @return The range (possibly <code>null</code>).
*
* @since 1.0.13
*/
public static Range iterateToFindRangeBounds(CategoryDataset dataset,
List visibleSeriesKeys, boolean includeInterval) {
ParamChecks.nullNotPermitted(dataset, "dataset");
ParamChecks.nullNotPermitted(visibleSeriesKeys, "visibleSeriesKeys");
double minimum = Double.POSITIVE_INFINITY;
double maximum = Double.NEGATIVE_INFINITY;
int columnCount = dataset.getColumnCount();
if (includeInterval
&& dataset instanceof BoxAndWhiskerCategoryDataset) {
// handle special case of BoxAndWhiskerDataset
BoxAndWhiskerCategoryDataset bx
= (BoxAndWhiskerCategoryDataset) dataset;
Iterator iterator = visibleSeriesKeys.iterator();
while (iterator.hasNext()) {
Comparable seriesKey = (Comparable) iterator.next();
int series = dataset.getRowIndex(seriesKey);
int itemCount = dataset.getColumnCount();
for (int item = 0; item < itemCount; item++) {
Number lvalue = bx.getMinRegularValue(series, item);
if (lvalue == null) {
lvalue = bx.getValue(series, item);
}
Number uvalue = bx.getMaxRegularValue(series, item);
if (uvalue == null) {
uvalue = bx.getValue(series, item);
}
if (lvalue != null) {
minimum = Math.min(minimum, lvalue.doubleValue());
}
if (uvalue != null) {
maximum = Math.max(maximum, uvalue.doubleValue());
}
}
}
}
else if (includeInterval
&& dataset instanceof IntervalCategoryDataset) {
// handle the special case where the dataset has y-intervals that
// we want to measure
IntervalCategoryDataset icd = (IntervalCategoryDataset) dataset;
Number lvalue, uvalue;
Iterator iterator = visibleSeriesKeys.iterator();
while (iterator.hasNext()) {
Comparable seriesKey = (Comparable) iterator.next();
int series = dataset.getRowIndex(seriesKey);
for (int column = 0; column < columnCount; column++) {
lvalue = icd.getStartValue(series, column);
uvalue = icd.getEndValue(series, column);
if (lvalue != null && !Double.isNaN(lvalue.doubleValue())) {
minimum = Math.min(minimum, lvalue.doubleValue());
}
if (uvalue != null && !Double.isNaN(uvalue.doubleValue())) {
maximum = Math.max(maximum, uvalue.doubleValue());
}
}
}
}
else if (includeInterval
&& dataset instanceof MultiValueCategoryDataset) {
// handle the special case where the dataset has y-intervals that
// we want to measure
MultiValueCategoryDataset mvcd
= (MultiValueCategoryDataset) dataset;
Iterator iterator = visibleSeriesKeys.iterator();
while (iterator.hasNext()) {
Comparable seriesKey = (Comparable) iterator.next();
int series = dataset.getRowIndex(seriesKey);
for (int column = 0; column < columnCount; column++) {
List values = mvcd.getValues(series, column);
Iterator valueIterator = values.iterator();
while (valueIterator.hasNext()) {
Object o = valueIterator.next();
if (o instanceof Number){
double v = ((Number) o).doubleValue();
if (!Double.isNaN(v)){
minimum = Math.min(minimum, v);
maximum = Math.max(maximum, v);
}
}
}
}
}
}
else if (includeInterval
&& dataset instanceof StatisticalCategoryDataset) {
// handle the special case where the dataset has y-intervals that
// we want to measure
StatisticalCategoryDataset scd
= (StatisticalCategoryDataset) dataset;
Iterator iterator = visibleSeriesKeys.iterator();
while (iterator.hasNext()) {
Comparable seriesKey = (Comparable) iterator.next();
int series = dataset.getRowIndex(seriesKey);
for (int column = 0; column < columnCount; column++) {
Number meanN = scd.getMeanValue(series, column);
if (meanN != null) {
double std = 0.0;
Number stdN = scd.getStdDevValue(series, column);
if (stdN != null) {
std = stdN.doubleValue();
if (Double.isNaN(std)) {
std = 0.0;
}
}
double mean = meanN.doubleValue();
if (!Double.isNaN(mean)) {
minimum = Math.min(minimum, mean - std);
maximum = Math.max(maximum, mean + std);
}
}
}
}
}
else {
// handle the standard case (plain CategoryDataset)
Iterator iterator = visibleSeriesKeys.iterator();
while (iterator.hasNext()) {
Comparable seriesKey = (Comparable) iterator.next();
int series = dataset.getRowIndex(seriesKey);
for (int column = 0; column < columnCount; column++) {
Number value = dataset.getValue(series, column);
if (value != null) {
double v = value.doubleValue();
if (!Double.isNaN(v)) {
minimum = Math.min(minimum, v);
maximum = Math.max(maximum, v);
}
}
}
}
}
if (minimum == Double.POSITIVE_INFINITY) {
return null;
}
else {
return new Range(minimum, maximum);
}
}
/**
* Iterates over the data item of the xy dataset to find
* the range bounds.
*
* @param dataset the dataset (<code>null</code> not permitted).
*
* @return The range (possibly <code>null</code>).
*
* @deprecated As of 1.0.10, use {@link #iterateRangeBounds(XYDataset)}.
*/
public static Range iterateXYRangeBounds(XYDataset dataset) {
return iterateRangeBounds(dataset);
}
/**
* Iterates over the data item of the xy dataset to find
* the range bounds.
*
* @param dataset the dataset (<code>null</code> not permitted).
*
* @return The range (possibly <code>null</code>).
*
* @since 1.0.10
*/
public static Range iterateRangeBounds(XYDataset dataset) {
return iterateRangeBounds(dataset, true);
}
/**
* Iterates over the data items of the xy dataset to find
* the range bounds.
*
* @param dataset the dataset (<code>null</code> not permitted).
* @param includeInterval a flag that determines, for an
* {@link IntervalXYDataset}, whether the y-interval or just the
* y-value is used to determine the overall range.
*
* @return The range (possibly <code>null</code>).
*
* @since 1.0.10
*/
public static Range iterateRangeBounds(XYDataset dataset,
boolean includeInterval) {
double minimum = Double.POSITIVE_INFINITY;
double maximum = Double.NEGATIVE_INFINITY;
int seriesCount = dataset.getSeriesCount();
// handle three cases by dataset type
if (includeInterval && dataset instanceof IntervalXYDataset) {
// handle special case of IntervalXYDataset
IntervalXYDataset ixyd = (IntervalXYDataset) dataset;
for (int series = 0; series < seriesCount; series++) {
int itemCount = dataset.getItemCount(series);
for (int item = 0; item < itemCount; item++) {
double value = ixyd.getYValue(series, item);
double lvalue = ixyd.getStartYValue(series, item);
double uvalue = ixyd.getEndYValue(series, item);
if (!Double.isNaN(value)) {
minimum = Math.min(minimum, value);
maximum = Math.max(maximum, value);
}
if (!Double.isNaN(lvalue)) {
minimum = Math.min(minimum, lvalue);
maximum = Math.max(maximum, lvalue);
}
if (!Double.isNaN(uvalue)) {
minimum = Math.min(minimum, uvalue);
maximum = Math.max(maximum, uvalue);
}
}
}
}
else if (includeInterval && dataset instanceof OHLCDataset) {
// handle special case of OHLCDataset
OHLCDataset ohlc = (OHLCDataset) dataset;
for (int series = 0; series < seriesCount; series++) {
int itemCount = dataset.getItemCount(series);
for (int item = 0; item < itemCount; item++) {
double lvalue = ohlc.getLowValue(series, item);
double uvalue = ohlc.getHighValue(series, item);
if (!Double.isNaN(lvalue)) {
minimum = Math.min(minimum, lvalue);
}
if (!Double.isNaN(uvalue)) {
maximum = Math.max(maximum, uvalue);
}
}
}
}
else {
// standard case - plain XYDataset
for (int series = 0; series < seriesCount; series++) {
int itemCount = dataset.getItemCount(series);
for (int item = 0; item < itemCount; item++) {
double value = dataset.getYValue(series, item);
if (!Double.isNaN(value)) {
minimum = Math.min(minimum, value);
maximum = Math.max(maximum, value);
}
}
}
}
if (minimum == Double.POSITIVE_INFINITY) {
return null;
}
else {
return new Range(minimum, maximum);
}
}
/**
* Returns the range of values in the z-dimension for the dataset. This
* method is the partner for the {@link #findRangeBounds(XYDataset)}
* and {@link #findDomainBounds(XYDataset)} methods.
*
* @param dataset the dataset (<code>null</code> not permitted).
*
* @return The range (possibly <code>null</code>).
*/
public static Range findZBounds(XYZDataset dataset) {
return findZBounds(dataset, true);
}
/**
* Returns the range of values in the z-dimension for the dataset. This
* method is the partner for the
* {@link #findRangeBounds(XYDataset, boolean)} and
* {@link #findDomainBounds(XYDataset, boolean)} methods.
*
* @param dataset the dataset (<code>null</code> not permitted).
* @param includeInterval a flag that determines whether or not the
* z-interval is taken into account.
*
* @return The range (possibly <code>null</code>).
*/
public static Range findZBounds(XYZDataset dataset,
boolean includeInterval) {
ParamChecks.nullNotPermitted(dataset, "dataset");
Range result = iterateZBounds(dataset, includeInterval);
return result;
}
/**
* Finds the bounds of the z-values in the specified dataset, including
* only those series that are listed in visibleSeriesKeys, and those items
* whose x-values fall within the specified range.
*
* @param dataset the dataset (<code>null</code> not permitted).
* @param visibleSeriesKeys the keys for the visible series
* (<code>null</code> not permitted).
* @param xRange the x-range (<code>null</code> not permitted).
* @param includeInterval include the z-interval (if the dataset has a
* z-interval).
*
* @return The data bounds.
*/
public static Range findZBounds(XYZDataset dataset,
List visibleSeriesKeys, Range xRange, boolean includeInterval) {
ParamChecks.nullNotPermitted(dataset, "dataset");
Range result = iterateToFindZBounds(dataset, visibleSeriesKeys,
xRange, includeInterval);
return result;
}
/**
* Iterates over the data item of the xyz dataset to find
* the z-dimension bounds.
*
* @param dataset the dataset (<code>null</code> not permitted).
*
* @return The range (possibly <code>null</code>).
*/
public static Range iterateZBounds(XYZDataset dataset) {
return iterateZBounds(dataset, true);
}
/**
* Iterates over the data items of the xyz dataset to find
* the z-dimension bounds.
*
* @param dataset the dataset (<code>null</code> not permitted).
* @param includeInterval include the z-interval (if the dataset has a
* z-interval.
*
* @return The range (possibly <code>null</code>).
*/
public static Range iterateZBounds(XYZDataset dataset,
boolean includeInterval) {
double minimum = Double.POSITIVE_INFINITY;
double maximum = Double.NEGATIVE_INFINITY;
int seriesCount = dataset.getSeriesCount();
for (int series = 0; series < seriesCount; series++) {
int itemCount = dataset.getItemCount(series);
for (int item = 0; item < itemCount; item++) {
double value = dataset.getZValue(series, item);
if (!Double.isNaN(value)) {
minimum = Math.min(minimum, value);
maximum = Math.max(maximum, value);
}
}
}
if (minimum == Double.POSITIVE_INFINITY) {
return null;
}
else {
return new Range(minimum, maximum);
}
}
/**
* Returns the range of x-values in the specified dataset for the
* data items belonging to the visible series.
*
* @param dataset the dataset (<code>null</code> not permitted).
* @param visibleSeriesKeys the visible series keys (<code>null</code> not
* permitted).
* @param includeInterval a flag that determines whether or not the
* y-interval for the dataset is included (this only applies if the
* dataset is an instance of IntervalXYDataset).
*
* @return The x-range (possibly <code>null</code>).
*
* @since 1.0.13
*/
public static Range iterateToFindDomainBounds(XYDataset dataset,
List visibleSeriesKeys, boolean includeInterval) {
ParamChecks.nullNotPermitted(dataset, "dataset");
ParamChecks.nullNotPermitted(visibleSeriesKeys, "visibleSeriesKeys");
double minimum = Double.POSITIVE_INFINITY;
double maximum = Double.NEGATIVE_INFINITY;
if (includeInterval && dataset instanceof IntervalXYDataset) {
// handle special case of IntervalXYDataset
IntervalXYDataset ixyd = (IntervalXYDataset) dataset;
Iterator iterator = visibleSeriesKeys.iterator();
while (iterator.hasNext()) {
Comparable seriesKey = (Comparable) iterator.next();
int series = dataset.indexOf(seriesKey);
int itemCount = dataset.getItemCount(series);
for (int item = 0; item < itemCount; item++) {
double lvalue = ixyd.getStartXValue(series, item);
double uvalue = ixyd.getEndXValue(series, item);
if (!Double.isNaN(lvalue)) {
minimum = Math.min(minimum, lvalue);
}
if (!Double.isNaN(uvalue)) {
maximum = Math.max(maximum, uvalue);
}
}
}
}
else {
// standard case - plain XYDataset
Iterator iterator = visibleSeriesKeys.iterator();
while (iterator.hasNext()) {
Comparable seriesKey = (Comparable) iterator.next();
int series = dataset.indexOf(seriesKey);
int itemCount = dataset.getItemCount(series);
for (int item = 0; item < itemCount; item++) {
double x = dataset.getXValue(series, item);
if (!Double.isNaN(x)) {
minimum = Math.min(minimum, x);
maximum = Math.max(maximum, x);
}
}
}
}
if (minimum == Double.POSITIVE_INFINITY) {
return null;
}
else {
return new Range(minimum, maximum);
}
}
/**
* Returns the range of y-values in the specified dataset for the
* data items belonging to the visible series and with x-values in the
* given range.
*
* @param dataset the dataset (<code>null</code> not permitted).
* @param visibleSeriesKeys the visible series keys (<code>null</code> not
* permitted).
* @param xRange the x-range (<code>null</code> not permitted).
* @param includeInterval a flag that determines whether or not the
* y-interval for the dataset is included (this only applies if the
* dataset is an instance of IntervalXYDataset).
*
* @return The y-range (possibly <code>null</code>).
*
* @since 1.0.13
*/
public static Range iterateToFindRangeBounds(XYDataset dataset,
List visibleSeriesKeys, Range xRange, boolean includeInterval) {
ParamChecks.nullNotPermitted(dataset, "dataset");
ParamChecks.nullNotPermitted(visibleSeriesKeys, "visibleSeriesKeys");
ParamChecks.nullNotPermitted(xRange, "xRange");
double minimum = Double.POSITIVE_INFINITY;
double maximum = Double.NEGATIVE_INFINITY;
// handle three cases by dataset type
if (includeInterval && dataset instanceof OHLCDataset) {
// handle special case of OHLCDataset
OHLCDataset ohlc = (OHLCDataset) dataset;
Iterator iterator = visibleSeriesKeys.iterator();
while (iterator.hasNext()) {
Comparable seriesKey = (Comparable) iterator.next();
int series = dataset.indexOf(seriesKey);
int itemCount = dataset.getItemCount(series);
for (int item = 0; item < itemCount; item++) {
double x = ohlc.getXValue(series, item);
if (xRange.contains(x)) {
double lvalue = ohlc.getLowValue(series, item);
double uvalue = ohlc.getHighValue(series, item);
if (!Double.isNaN(lvalue)) {
minimum = Math.min(minimum, lvalue);
}
if (!Double.isNaN(uvalue)) {
maximum = Math.max(maximum, uvalue);
}
}
}
}
}
else if (includeInterval && dataset instanceof BoxAndWhiskerXYDataset) {
// handle special case of BoxAndWhiskerXYDataset
BoxAndWhiskerXYDataset bx = (BoxAndWhiskerXYDataset) dataset;
Iterator iterator = visibleSeriesKeys.iterator();
while (iterator.hasNext()) {
Comparable seriesKey = (Comparable) iterator.next();
int series = dataset.indexOf(seriesKey);
int itemCount = dataset.getItemCount(series);
for (int item = 0; item < itemCount; item++) {
double x = bx.getXValue(series, item);
if (xRange.contains(x)) {
Number lvalue = bx.getMinRegularValue(series, item);
Number uvalue = bx.getMaxRegularValue(series, item);
if (lvalue != null) {
minimum = Math.min(minimum, lvalue.doubleValue());
}
if (uvalue != null) {
maximum = Math.max(maximum, uvalue.doubleValue());
}
}
}
}
}
else if (includeInterval && dataset instanceof IntervalXYDataset) {
// handle special case of IntervalXYDataset
IntervalXYDataset ixyd = (IntervalXYDataset) dataset;
Iterator iterator = visibleSeriesKeys.iterator();
while (iterator.hasNext()) {
Comparable seriesKey = (Comparable) iterator.next();
int series = dataset.indexOf(seriesKey);
int itemCount = dataset.getItemCount(series);
for (int item = 0; item < itemCount; item++) {
double x = ixyd.getXValue(series, item);
if (xRange.contains(x)) {
double lvalue = ixyd.getStartYValue(series, item);
double uvalue = ixyd.getEndYValue(series, item);
if (!Double.isNaN(lvalue)) {
minimum = Math.min(minimum, lvalue);
}
if (!Double.isNaN(uvalue)) {
maximum = Math.max(maximum, uvalue);
}
}
}
}
}
else {
// standard case - plain XYDataset
Iterator iterator = visibleSeriesKeys.iterator();
while (iterator.hasNext()) {
Comparable seriesKey = (Comparable) iterator.next();
int series = dataset.indexOf(seriesKey);
int itemCount = dataset.getItemCount(series);
for (int item = 0; item < itemCount; item++) {
double x = dataset.getXValue(series, item);
double y = dataset.getYValue(series, item);
if (xRange.contains(x)) {
if (!Double.isNaN(y)) {
minimum = Math.min(minimum, y);
maximum = Math.max(maximum, y);
}
}
}
}
}
if (minimum == Double.POSITIVE_INFINITY) {
return null;
}
else {
return new Range(minimum, maximum);
}
}
/**
* Returns the range of z-values in the specified dataset for the
* data items belonging to the visible series and with x-values in the
* given range.
*
* @param dataset the dataset (<code>null</code> not permitted).
* @param visibleSeriesKeys the visible series keys (<code>null</code> not
* permitted).
* @param xRange the x-range (<code>null</code> not permitted).
* @param includeInterval a flag that determines whether or not the
* z-interval for the dataset is included (this only applies if the
* dataset has an interval, which is currently not supported).
*
* @return The y-range (possibly <code>null</code>).
*/
public static Range iterateToFindZBounds(XYZDataset dataset,
List visibleSeriesKeys, Range xRange, boolean includeInterval) {
ParamChecks.nullNotPermitted(dataset, "dataset");
ParamChecks.nullNotPermitted(visibleSeriesKeys, "visibleSeriesKeys");
ParamChecks.nullNotPermitted(xRange, "xRange");
double minimum = Double.POSITIVE_INFINITY;
double maximum = Double.NEGATIVE_INFINITY;
Iterator iterator = visibleSeriesKeys.iterator();
while (iterator.hasNext()) {
Comparable seriesKey = (Comparable) iterator.next();
int series = dataset.indexOf(seriesKey);
int itemCount = dataset.getItemCount(series);
for (int item = 0; item < itemCount; item++) {
double x = dataset.getXValue(series, item);
double z = dataset.getZValue(series, item);
if (xRange.contains(x)) {
if (!Double.isNaN(z)) {
minimum = Math.min(minimum, z);
maximum = Math.max(maximum, z);
}
}
}
}
if (minimum == Double.POSITIVE_INFINITY) {
return null;
}
else {
return new Range(minimum, maximum);
}
}
/**
* Finds the minimum domain (or X) value for the specified dataset. This
* is easy if the dataset implements the {@link DomainInfo} interface (a
* good idea if there is an efficient way to determine the minimum value).
* Otherwise, it involves iterating over the entire data-set.
* <p>
* Returns <code>null</code> if all the data values in the dataset are
* <code>null</code>.
*
* @param dataset the dataset (<code>null</code> not permitted).
*
* @return The minimum value (possibly <code>null</code>).
*/
public static Number findMinimumDomainValue(XYDataset dataset) {
ParamChecks.nullNotPermitted(dataset, "dataset");
Number result;
// if the dataset implements DomainInfo, life is easy
if (dataset instanceof DomainInfo) {
DomainInfo info = (DomainInfo) dataset;
return new Double(info.getDomainLowerBound(true));
}
else {
double minimum = Double.POSITIVE_INFINITY;
int seriesCount = dataset.getSeriesCount();
for (int series = 0; series < seriesCount; series++) {
int itemCount = dataset.getItemCount(series);
for (int item = 0; item < itemCount; item++) {
double value;
if (dataset instanceof IntervalXYDataset) {
IntervalXYDataset intervalXYData
= (IntervalXYDataset) dataset;
value = intervalXYData.getStartXValue(series, item);
}
else {
value = dataset.getXValue(series, item);
}
if (!Double.isNaN(value)) {
minimum = Math.min(minimum, value);
}
}
}
if (minimum == Double.POSITIVE_INFINITY) {
result = null;
}
else {
result = new Double(minimum);
}
}
return result;
}
/**
* Returns the maximum domain value for the specified dataset. This is
* easy if the dataset implements the {@link DomainInfo} interface (a good
* idea if there is an efficient way to determine the maximum value).
* Otherwise, it involves iterating over the entire data-set. Returns
* <code>null</code> if all the data values in the dataset are
* <code>null</code>.
*
* @param dataset the dataset (<code>null</code> not permitted).
*
* @return The maximum value (possibly <code>null</code>).
*/
public static Number findMaximumDomainValue(XYDataset dataset) {
ParamChecks.nullNotPermitted(dataset, "dataset");
Number result;
// if the dataset implements DomainInfo, life is easy
if (dataset instanceof DomainInfo) {
DomainInfo info = (DomainInfo) dataset;
return new Double(info.getDomainUpperBound(true));
}
// hasn't implemented DomainInfo, so iterate...
else {
double maximum = Double.NEGATIVE_INFINITY;
int seriesCount = dataset.getSeriesCount();
for (int series = 0; series < seriesCount; series++) {
int itemCount = dataset.getItemCount(series);
for (int item = 0; item < itemCount; item++) {
double value;
if (dataset instanceof IntervalXYDataset) {
IntervalXYDataset intervalXYData
= (IntervalXYDataset) dataset;
value = intervalXYData.getEndXValue(series, item);
}
else {
value = dataset.getXValue(series, item);
}
if (!Double.isNaN(value)) {
maximum = Math.max(maximum, value);
}
}
}
if (maximum == Double.NEGATIVE_INFINITY) {
result = null;
}
else {
result = new Double(maximum);
}
}
return result;
}
/**
* Returns the minimum range value for the specified dataset. This is
* easy if the dataset implements the {@link RangeInfo} interface (a good
* idea if there is an efficient way to determine the minimum value).
* Otherwise, it involves iterating over the entire data-set. Returns
* <code>null</code> if all the data values in the dataset are
* <code>null</code>.
*
* @param dataset the dataset (<code>null</code> not permitted).
*
* @return The minimum value (possibly <code>null</code>).
*/
public static Number findMinimumRangeValue(CategoryDataset dataset) {
ParamChecks.nullNotPermitted(dataset, "dataset");
if (dataset instanceof RangeInfo) {
RangeInfo info = (RangeInfo) dataset;
return new Double(info.getRangeLowerBound(true));
}
// hasn't implemented RangeInfo, so we'll have to iterate...
else {
double minimum = Double.POSITIVE_INFINITY;
int seriesCount = dataset.getRowCount();
int itemCount = dataset.getColumnCount();
for (int series = 0; series < seriesCount; series++) {
for (int item = 0; item < itemCount; item++) {
Number value;
if (dataset instanceof IntervalCategoryDataset) {
IntervalCategoryDataset icd
= (IntervalCategoryDataset) dataset;
value = icd.getStartValue(series, item);
}
else {
value = dataset.getValue(series, item);
}
if (value != null) {
minimum = Math.min(minimum, value.doubleValue());
}
}
}
if (minimum == Double.POSITIVE_INFINITY) {
return null;
}
else {
return new Double(minimum);
}
}
}
/**
* Returns the minimum range value for the specified dataset. This is
* easy if the dataset implements the {@link RangeInfo} interface (a good
* idea if there is an efficient way to determine the minimum value).
* Otherwise, it involves iterating over the entire data-set. Returns
* <code>null</code> if all the data values in the dataset are
* <code>null</code>.
*
* @param dataset the dataset (<code>null</code> not permitted).
*
* @return The minimum value (possibly <code>null</code>).
*/
public static Number findMinimumRangeValue(XYDataset dataset) {
ParamChecks.nullNotPermitted(dataset, "dataset");
// work out the minimum value...
if (dataset instanceof RangeInfo) {
RangeInfo info = (RangeInfo) dataset;
return new Double(info.getRangeLowerBound(true));
}
// hasn't implemented RangeInfo, so we'll have to iterate...
else {
double minimum = Double.POSITIVE_INFINITY;
int seriesCount = dataset.getSeriesCount();
for (int series = 0; series < seriesCount; series++) {
int itemCount = dataset.getItemCount(series);
for (int item = 0; item < itemCount; item++) {
double value;
if (dataset instanceof IntervalXYDataset) {
IntervalXYDataset intervalXYData
= (IntervalXYDataset) dataset;
value = intervalXYData.getStartYValue(series, item);
}
else if (dataset instanceof OHLCDataset) {
OHLCDataset highLowData = (OHLCDataset) dataset;
value = highLowData.getLowValue(series, item);
}
else {
value = dataset.getYValue(series, item);
}
if (!Double.isNaN(value)) {
minimum = Math.min(minimum, value);
}
}
}
if (minimum == Double.POSITIVE_INFINITY) {
return null;
}
else {
return new Double(minimum);
}
}
}
/**
* Returns the maximum range value for the specified dataset. This is easy
* if the dataset implements the {@link RangeInfo} interface (a good idea
* if there is an efficient way to determine the maximum value).
* Otherwise, it involves iterating over the entire data-set. Returns
* <code>null</code> if all the data values are <code>null</code>.
*
* @param dataset the dataset (<code>null</code> not permitted).
*
* @return The maximum value (possibly <code>null</code>).
*/
public static Number findMaximumRangeValue(CategoryDataset dataset) {
ParamChecks.nullNotPermitted(dataset, "dataset");
// work out the minimum value...
if (dataset instanceof RangeInfo) {
RangeInfo info = (RangeInfo) dataset;
return new Double(info.getRangeUpperBound(true));
}
// hasn't implemented RangeInfo, so we'll have to iterate...
else {
double maximum = Double.NEGATIVE_INFINITY;
int seriesCount = dataset.getRowCount();
int itemCount = dataset.getColumnCount();
for (int series = 0; series < seriesCount; series++) {
for (int item = 0; item < itemCount; item++) {
Number value;
if (dataset instanceof IntervalCategoryDataset) {
IntervalCategoryDataset icd
= (IntervalCategoryDataset) dataset;
value = icd.getEndValue(series, item);
}
else {
value = dataset.getValue(series, item);
}
if (value != null) {
maximum = Math.max(maximum, value.doubleValue());
}
}
}
if (maximum == Double.NEGATIVE_INFINITY) {
return null;
}
else {
return new Double(maximum);
}
}
}
/**
* Returns the maximum range value for the specified dataset. This is
* easy if the dataset implements the {@link RangeInfo} interface (a good
* idea if there is an efficient way to determine the maximum value).
* Otherwise, it involves iterating over the entire data-set. Returns
* <code>null</code> if all the data values are <code>null</code>.
*
* @param dataset the dataset (<code>null</code> not permitted).
*
* @return The maximum value (possibly <code>null</code>).
*/
public static Number findMaximumRangeValue(XYDataset dataset) {
ParamChecks.nullNotPermitted(dataset, "dataset");
// work out the minimum value...
if (dataset instanceof RangeInfo) {
RangeInfo info = (RangeInfo) dataset;
return new Double(info.getRangeUpperBound(true));
}
// hasn't implemented RangeInfo, so we'll have to iterate...
else {
double maximum = Double.NEGATIVE_INFINITY;
int seriesCount = dataset.getSeriesCount();
for (int series = 0; series < seriesCount; series++) {
int itemCount = dataset.getItemCount(series);
for (int item = 0; item < itemCount; item++) {
double value;
if (dataset instanceof IntervalXYDataset) {
IntervalXYDataset intervalXYData
= (IntervalXYDataset) dataset;
value = intervalXYData.getEndYValue(series, item);
}
else if (dataset instanceof OHLCDataset) {
OHLCDataset highLowData = (OHLCDataset) dataset;
value = highLowData.getHighValue(series, item);
}
else {
value = dataset.getYValue(series, item);
}
if (!Double.isNaN(value)) {
maximum = Math.max(maximum, value);
}
}
}
if (maximum == Double.NEGATIVE_INFINITY) {
return null;
}
else {
return new Double(maximum);
}
}
}
/**
* Returns the minimum and maximum values for the dataset's range
* (y-values), assuming that the series in one category are stacked.
*
* @param dataset the dataset (<code>null</code> not permitted).
*
* @return The range (<code>null</code> if the dataset contains no values).
*/
public static Range findStackedRangeBounds(CategoryDataset dataset) {
return findStackedRangeBounds(dataset, 0.0);
}
/**
* Returns the minimum and maximum values for the dataset's range
* (y-values), assuming that the series in one category are stacked.
*
* @param dataset the dataset (<code>null</code> not permitted).
* @param base the base value for the bars.
*
* @return The range (<code>null</code> if the dataset contains no values).
*/
public static Range findStackedRangeBounds(CategoryDataset dataset,
double base) {
ParamChecks.nullNotPermitted(dataset, "dataset");
Range result = null;
double minimum = Double.POSITIVE_INFINITY;
double maximum = Double.NEGATIVE_INFINITY;
int categoryCount = dataset.getColumnCount();
for (int item = 0; item < categoryCount; item++) {
double positive = base;
double negative = base;
int seriesCount = dataset.getRowCount();
for (int series = 0; series < seriesCount; series++) {
Number number = dataset.getValue(series, item);
if (number != null) {
double value = number.doubleValue();
if (value > 0.0) {
positive = positive + value;
}
if (value < 0.0) {
negative = negative + value;
// '+', remember value is negative
}
}
}
minimum = Math.min(minimum, negative);
maximum = Math.max(maximum, positive);
}
if (minimum <= maximum) {
result = new Range(minimum, maximum);
}
return result;
}
/**
* Returns the minimum and maximum values for the dataset's range
* (y-values), assuming that the series in one category are stacked.
*
* @param dataset the dataset.
* @param map a structure that maps series to groups.
*
* @return The value range (<code>null</code> if the dataset contains no
* values).
*/
public static Range findStackedRangeBounds(CategoryDataset dataset,
KeyToGroupMap map) {
ParamChecks.nullNotPermitted(dataset, "dataset");
boolean hasValidData = false;
Range result = null;
// create an array holding the group indices for each series...
int[] groupIndex = new int[dataset.getRowCount()];
for (int i = 0; i < dataset.getRowCount(); i++) {
groupIndex[i] = map.getGroupIndex(map.getGroup(
dataset.getRowKey(i)));
}
// minimum and maximum for each group...
int groupCount = map.getGroupCount();
double[] minimum = new double[groupCount];
double[] maximum = new double[groupCount];
int categoryCount = dataset.getColumnCount();
for (int item = 0; item < categoryCount; item++) {
double[] positive = new double[groupCount];
double[] negative = new double[groupCount];
int seriesCount = dataset.getRowCount();
for (int series = 0; series < seriesCount; series++) {
Number number = dataset.getValue(series, item);
if (number != null) {
hasValidData = true;
double value = number.doubleValue();
if (value > 0.0) {
positive[groupIndex[series]]
= positive[groupIndex[series]] + value;
}
if (value < 0.0) {
negative[groupIndex[series]]
= negative[groupIndex[series]] + value;
// '+', remember value is negative
}
}
}
for (int g = 0; g < groupCount; g++) {
minimum[g] = Math.min(minimum[g], negative[g]);
maximum[g] = Math.max(maximum[g], positive[g]);
}
}
if (hasValidData) {
for (int j = 0; j < groupCount; j++) {
result = Range.combine(result, new Range(minimum[j],
maximum[j]));
}
}
return result;
}
/**
* Returns the minimum value in the dataset range, assuming that values in
* each category are "stacked".
*
* @param dataset the dataset (<code>null</code> not permitted).
*
* @return The minimum value.
*
* @see #findMaximumStackedRangeValue(CategoryDataset)
*/
public static Number findMinimumStackedRangeValue(CategoryDataset dataset) {
ParamChecks.nullNotPermitted(dataset, "dataset");
Number result = null;
boolean hasValidData = false;
double minimum = 0.0;
int categoryCount = dataset.getColumnCount();
for (int item = 0; item < categoryCount; item++) {
double total = 0.0;
int seriesCount = dataset.getRowCount();
for (int series = 0; series < seriesCount; series++) {
Number number = dataset.getValue(series, item);
if (number != null) {
hasValidData = true;
double value = number.doubleValue();
if (value < 0.0) {
total = total + value;
// '+', remember value is negative
}
}
}
minimum = Math.min(minimum, total);
}
if (hasValidData) {
result = new Double(minimum);
}
return result;
}
/**
* Returns the maximum value in the dataset range, assuming that values in
* each category are "stacked".
*
* @param dataset the dataset (<code>null</code> not permitted).
*
* @return The maximum value (possibly <code>null</code>).
*
* @see #findMinimumStackedRangeValue(CategoryDataset)
*/
public static Number findMaximumStackedRangeValue(CategoryDataset dataset) {
ParamChecks.nullNotPermitted(dataset, "dataset");
Number result = null;
boolean hasValidData = false;
double maximum = 0.0;
int categoryCount = dataset.getColumnCount();
for (int item = 0; item < categoryCount; item++) {
double total = 0.0;
int seriesCount = dataset.getRowCount();
for (int series = 0; series < seriesCount; series++) {
Number number = dataset.getValue(series, item);
if (number != null) {
hasValidData = true;
double value = number.doubleValue();
if (value > 0.0) {
total = total + value;
}
}
}
maximum = Math.max(maximum, total);
}
if (hasValidData) {
result = new Double(maximum);
}
return result;
}
/**
* Returns the minimum and maximum values for the dataset's range,
* assuming that the series are stacked.
*
* @param dataset the dataset (<code>null</code> not permitted).
*
* @return The range ([0.0, 0.0] if the dataset contains no values).
*/
public static Range findStackedRangeBounds(TableXYDataset dataset) {
return findStackedRangeBounds(dataset, 0.0);
}
/**
* Returns the minimum and maximum values for the dataset's range,
* assuming that the series are stacked, using the specified base value.
*
* @param dataset the dataset (<code>null</code> not permitted).
* @param base the base value.
*
* @return The range (<code>null</code> if the dataset contains no values).
*/
public static Range findStackedRangeBounds(TableXYDataset dataset,
double base) {
ParamChecks.nullNotPermitted(dataset, "dataset");
double minimum = base;
double maximum = base;
for (int itemNo = 0; itemNo < dataset.getItemCount(); itemNo++) {
double positive = base;
double negative = base;
int seriesCount = dataset.getSeriesCount();
for (int seriesNo = 0; seriesNo < seriesCount; seriesNo++) {
double y = dataset.getYValue(seriesNo, itemNo);
if (!Double.isNaN(y)) {
if (y > 0.0) {
positive += y;
}
else {
negative += y;
}
}
}
if (positive > maximum) {
maximum = positive;
}
if (negative < minimum) {
minimum = negative;
}
}
if (minimum <= maximum) {
return new Range(minimum, maximum);
}
else {
return null;
}
}
/**
* Calculates the total for the y-values in all series for a given item
* index.
*
* @param dataset the dataset.
* @param item the item index.
*
* @return The total.
*
* @since 1.0.5
*/
public static double calculateStackTotal(TableXYDataset dataset, int item) {
double total = 0.0;
int seriesCount = dataset.getSeriesCount();
for (int s = 0; s < seriesCount; s++) {
double value = dataset.getYValue(s, item);
if (!Double.isNaN(value)) {
total = total + value;
}
}
return total;
}
/**
* Calculates the range of values for a dataset where each item is the
* running total of the items for the current series.
*
* @param dataset the dataset (<code>null</code> not permitted).
*
* @return The range.
*
* @see #findRangeBounds(CategoryDataset)
*/
public static Range findCumulativeRangeBounds(CategoryDataset dataset) {
ParamChecks.nullNotPermitted(dataset, "dataset");
boolean allItemsNull = true; // we'll set this to false if there is at
// least one non-null data item...
double minimum = 0.0;
double maximum = 0.0;
for (int row = 0; row < dataset.getRowCount(); row++) {
double runningTotal = 0.0;
for (int column = 0; column <= dataset.getColumnCount() - 1;
column++) {
Number n = dataset.getValue(row, column);
if (n != null) {
allItemsNull = false;
double value = n.doubleValue();
if (!Double.isNaN(value)) {
runningTotal = runningTotal + value;
minimum = Math.min(minimum, runningTotal);
maximum = Math.max(maximum, runningTotal);
}
}
}
}
if (!allItemsNull) {
return new Range(minimum, maximum);
}
else {
return null;
}
}
/**
* Returns the interpolated value of y that corresponds to the specified
* x-value in the given series. If the x-value falls outside the range of
* x-values for the dataset, this method returns <code>Double.NaN</code>.
*
* @param dataset the dataset (<code>null</code> not permitted).
* @param series the series index.
* @param x the x-value.
*
* @return The y value.
*
* @since 1.0.16
*/
public static double findYValue(XYDataset dataset, int series, double x) {
// delegate null check on dataset
int[] indices = findItemIndicesForX(dataset, series, x);
if (indices[0] == -1) {
return Double.NaN;
}
if (indices[0] == indices[1]) {
return dataset.getYValue(series, indices[0]);
}
double x0 = dataset.getXValue(series, indices[0]);
double x1 = dataset.getXValue(series, indices[1]);
double y0 = dataset.getYValue(series, indices[0]);
double y1 = dataset.getYValue(series, indices[1]);
return y0 + (y1 - y0) * (x - x0) / (x1 - x0);
}
/**
* Finds the indices of the the items in the dataset that span the
* specified x-value. There are three cases for the return value:
* <ul>
* <li>there is an exact match for the x-value at index i
* (returns <code>int[] {i, i}</code>);</li>
* <li>the x-value falls between two (adjacent) items at index i and i+1
* (returns <code>int[] {i, i+1}</code>);</li>
* <li>the x-value falls outside the domain bounds, in which case the
* method returns <code>int[] {-1, -1}</code>.</li>
* </ul>
* @param dataset the dataset (<code>null</code> not permitted).
* @param series the series index.
* @param x the x-value.
*
* @return The indices of the two items that span the x-value.
*
* @since 1.0.16
*
* @see #findYValue(org.jfree.data.xy.XYDataset, int, double)
*/
public static int[] findItemIndicesForX(XYDataset dataset, int series,
double x) {
ParamChecks.nullNotPermitted(dataset, "dataset");
int itemCount = dataset.getItemCount(series);
if (itemCount == 0) {
return new int[] {-1, -1};
}
if (itemCount == 1) {
if (x == dataset.getXValue(series, 0)) {
return new int[] {0, 0};
} else {
return new int[] {-1, -1};
}
}
if (dataset.getDomainOrder() == DomainOrder.ASCENDING) {
int low = 0;
int high = itemCount - 1;
double lowValue = dataset.getXValue(series, low);
if (lowValue > x) {
return new int[] {-1, -1};
}
if (lowValue == x) {
return new int[] {low, low};
}
double highValue = dataset.getXValue(series, high);
if (highValue < x) {
return new int[] {-1, -1};
}
if (highValue == x) {
return new int[] {high, high};
}
int mid = (low + high) / 2;
while (high - low > 1) {
double midV = dataset.getXValue(series, mid);
if (x == midV) {
return new int[] {mid, mid};
}
if (midV < x) {
low = mid;
}
else {
high = mid;
}
mid = (low + high) / 2;
}
return new int[] {low, high};
}
else if (dataset.getDomainOrder() == DomainOrder.DESCENDING) {
int high = 0;
int low = itemCount - 1;
double lowValue = dataset.getXValue(series, low);
if (lowValue > x) {
return new int[] {-1, -1};
}
double highValue = dataset.getXValue(series, high);
if (highValue < x) {
return new int[] {-1, -1};
}
int mid = (low + high) / 2;
while (high - low > 1) {
double midV = dataset.getXValue(series, mid);
if (x == midV) {
return new int[] {mid, mid};
}
if (midV < x) {
low = mid;
}
else {
high = mid;
}
mid = (low + high) / 2;
}
return new int[] {low, high};
}
else {
// we don't know anything about the ordering of the x-values,
// so we iterate until we find the first crossing of x (if any)
// we know there are at least 2 items in the series at this point
double prev = dataset.getXValue(series, 0);
if (x == prev) {
return new int[] {0, 0}; // exact match on first item
}
for (int i = 1; i < itemCount; i++) {
double next = dataset.getXValue(series, i);
if (x == next) {
return new int[] {i, i}; // exact match
}
if ((x > prev && x < next) || (x < prev && x > next)) {
return new int[] {i - 1, i}; // spanning match
}
}
return new int[] {-1, -1}; // no crossing of x
}
}
}
|
package net.hexid.hexbot.bot;
import java.io.File;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map.Entry;
import java.util.TreeMap;
import net.hexid.Utils;
public class Bots {
private static TreeMap<String, HashMap<String, String>> bots = new TreeMap<>();
/**
* Add a new bot to the list of usable bots
* @param id
* @param name
* @param cliClassPath
* @param guiClassPath
* @param fileName
*/
public static void addBot(String id, String name, String cli, String gui, String file) {
HashMap<String, String> bot = new HashMap<>();
bot.put("botName", name);
bot.put("cliClassPath", cli);
bot.put("guiClassPath", gui);
bot.put("fileName", file);
bots.put(id.toLowerCase(), bot);
}
/**
* Remove all bots whose file does not exist
*/
public static void removeInvalidBots() {
Iterator<Entry<String, HashMap<String, String>>> iter = bots.entrySet().iterator();
while(iter.hasNext()) {
if(!(new File(getBotFile(iter.next().getKey()))).exists())
iter.remove();
}
}
/**
* @return TreeMap of botNames linked with HashMaps of botData
*/
public static TreeMap<String, HashMap<String, String>> getBots() {
return bots;
}
public static String getBotEnvPath(String oldEnvPath) {
String dir = Utils.getPWD().getPath();
String sysSpecific = System.getProperty("os.name").toLowerCase();
String casperBin = "bin";
if(sysSpecific.contains("win")) {
sysSpecific = "windows";
casperBin = "batchbin";
} else if(sysSpecific.contains("mac")) {
sysSpecific = "macosx";
} else {
sysSpecific += ("-" + System.getProperty("os.arch"));
}
String phantom = Utils.joinFile(dir, "libs", "phantomjs");
String phantomBin = Utils.joinFile(phantom, "bin");
String phantomOS = Utils.joinFile(phantomBin, sysSpecific);
String casper = Utils.joinFile(dir, "libs", "casperjs", casperBin);
return Utils.join(File.pathSeparator, oldEnvPath, phantomOS, phantomBin, phantom, casper);
}
/**
* @return Array of all bot IDs (keys to map)
*/
public static String[] botIDs() {
return bots.keySet().toArray(new String[0]);
}
/**
* @return String representation of the array of bot IDs
*/
public static String botIDsString() {
return java.util.Arrays.toString(botIDs());
}
/**
* @param botID
* @return HashMap with bot's data
*/
public static HashMap<String, String> getBot(String botID) {
return bots.get(botID.toLowerCase()); // get the data associated with a bot
}
/**
* @param botID
* @return true if a key exists for the bot
*/
public static boolean hasBot(String botID) {
return bots.containsKey(botID.toLowerCase());
}
/**
* Get the specified bot's value at a given key
* @param botName
* @param key Key to query for in bot's HashMap
* @return botData; null if nonexistant
*/
public static String getFromBot(String botID, String key) {
return (hasBot(botID)) ? getBot(botID).get(key) : null;
}
/**
* @param botName
* @param key
* @param value
* @return True if the bot exists
*/
public static boolean setInBot(String botID, String key, String value) {
if(hasBot(botID)) {
getBot(botID).put(key, value);
return true;
}
return false;
}
public static String getBotName(String botID) {
return getFromBot(botID, "botName");
}
public static String getBotCliClassPath(String botID) {
return getFromBot(botID, "cliClassPath");
}
public static String getBotGuiClassPath(String botID) {
return getFromBot(botID, "guiClassPath");
}
public static String getBotFileName(String botID) {
return getFromBot(botID, "fileName");
}
public static boolean setBotName(String botID, String newBotName) {
return setInBot(botID, "botName", newBotName);
}
public static boolean setBotCliClassPath(String botID, String newCliClassPath) {
return setInBot(botID, "cliClassPath", newCliClassPath);
}
public static boolean setBotGuiClassPath(String botID, String newGuiClassPath) {
return setInBot(botID, "guiClassPath", newGuiClassPath);
}
public static boolean setBotFileName(String botID, String newBotFileName) {
return setInBot(botID, "fileName", newBotFileName);
}
public static String getBotFile(String botID) {
return Utils.joinFile(Utils.getPWD().getPath(), "bots", getBotFileName(botID));
}
public static String getBotFile(Bot bot) {
return getBotFile(bot.getBotID());
}
}
|
package polyglot.types;
import java.io.IOException;
import polyglot.frontend.Compiler;
import polyglot.frontend.ExtensionInfo;
import polyglot.frontend.FileSource;
import polyglot.main.Report;
import polyglot.types.reflect.ClassFile;
import polyglot.types.reflect.ClassFileLoader;
/**
* Loads class information from source files, class files, or serialized
* class infomation from within class files. An outline of the steps is
* given below.
*
* <ol>
* <li> When the polyglot translator looks for a class by the name
* "foo.bar.Quux" it first searches for that class in any file given
* on the command line. If the class is found one of these files, then
* this definition is used and the remainder of the steps are
* skipped.
*
* <li>If none of these files contain the desired class, then the source
* path is searched next. For example, if the source extension is
* ".jl" and the source path is "mydir:." then the translator looks
* for files "mydir/foo/bar/Quux.jl" and "./foo/bar/Quux.jl".
*
* <li> Regardless of whether or not a source file is found, the translator
* searches the classpath (defined as normal through the environment
* and command-line options to the interpreter) for the desired class.
*
* <li>If no source file exists, and no class is found then an error is
* reported (skipping the rest of the steps below).
*
* <li>If a source file is found, but no class, then the source file is
* parsed. If it contains the desired class definition (which it
* should) then that definition is used and the remainder of the steps
* are skipped. (If it does not contain this definition, an error is
* reported and the remainder of the steps are skipped.
*
* <li>If a class is found but no source file, then the class is examined
* for jlc class type information. If the class contains no class type
* information (this is the case if the class file was compiled from
* raw Java source rather than jlc translated output) then this class
* is used as the desired class definition (skipping all steps below).
*
* <li>(class, but no still no source) If the class does contain jlc class
* type information, then the version number of translator used to
* translate the source which created the given class file is compared
* against the version of the current instantiation of the translator.
* If the versions are compatible, then the jlc class type information
* is used as the desired definiton. If the versions are incompatible
* (see the documentation in Compiler.java) then an error is reported.
* In either case, all remaining steps are skipped.
*
* <li>If both a suitable source file and class are found then we have a
* choice. If the class definition does not contain jlc class type
* information then the source file is parsed as the definition found
* in this file is used as desired definiton and we stop here. If the
* class does contain jlc class type information, then continue.
*
* <li>(source and class with jlc info) Next the last modification date of
* the source file is compared to the last modification date of the
* source file used to generate the class file. If the source file is
* more recent, the it is parsed as used as the desired definition and
* all remaining steps are skipped.
*
* <li>(source and class with jlc info) Next the jlc version of the class
* and of the current translator are compared (as in 7.). If the
* verisions are incompatible, then we use the definition from the
* parsed source file. If the versions are compatible, then we use
* the definition given by the jlc class type information.
* </ol>
* Finally, if at any point an error occurs while reading jlc class type
* information (e.g. if this information exists but is corrupted), then
* an error is reported.
*/
public class SourceClassResolver extends LoadedClassResolver
{
Compiler compiler;
ExtensionInfo ext;
/**
* Create a loaded class resolver.
* @param ts The type system
* @param ext The extension to load sources for.
* @param classpath The class path
* @param loader The class file loader to use.
*/
public SourceClassResolver(Compiler compiler, ExtensionInfo ext,
String classpath, ClassFileLoader loader,
boolean allowRawClasses)
{
super(ext.typeSystem(), classpath, loader, ext.version(), allowRawClasses);
this.compiler = compiler;
this.ext = ext;
}
/**
* Find a type by name.
*/
public Named find(String name) throws SemanticException {
if (Report.should_report(report_topics, 3))
Report.report(3, "SourceCR.find(" + name + ")");
ClassFile clazz = null;
ClassFile encodedClazz = null;
FileSource source = null;
// First try the class file.
try {
clazz = loadFile(name);
// Check for encoded type information.
if (clazz.encodedClassType(version.name()) != null) {
if (Report.should_report(report_topics, 4))
Report.report(4, "Class " + name + " has encoded type info");
encodedClazz = clazz;
}
}
catch (NoClassException e) {
clazz = null;
}
// Now, try and find the source file.
try {
source = ext.sourceLoader().classSource(name);
if (Report.should_report(report_topics, 4))
Report.report(4, "Class " + name + " found in source " + source);
}
catch (IOException e) {
if (Report.should_report(report_topics, 4))
Report.report(4, "Class " + name + " not found in source file");
source = null;
}
// Don't use the raw class if the source or encoded class is available.
if (encodedClazz != null || source != null) {
if (Report.should_report(report_topics, 4))
Report.report(4, "Not using raw class file for " + name);
clazz = null;
}
// If both the source and encoded class are available, we decide which to
// use based on compiler compatibility and modification times.
if (encodedClazz != null && source != null) {
long classModTime = encodedClazz.sourceLastModified(version.name());
long sourceModTime = source.lastModified().getTime();
int comp = checkCompilerVersion(encodedClazz.compilerVersion(version.name()));
if (classModTime < sourceModTime) {
if (Report.should_report(report_topics, 3))
Report.report(3, "Source file version is newer than compiled for " +
name + ".");
encodedClazz = null;
}
else if (comp != COMPATIBLE) {
// Incompatible or older version, so go with the source.
if (Report.should_report(report_topics, 3))
Report.report(3, "Incompatible source file version for " + name + ".");
encodedClazz = null;
}
}
if (encodedClazz != null) {
if (Report.should_report(report_topics, 4))
Report.report(4, "Using encoded class type for " + name);
try {
return getEncodedType(encodedClazz, name);
}
catch (BadSerializationException e) {
throw e;
}
catch (SemanticException e) {
if (Report.should_report(report_topics, 4))
Report.report(4, "Could not load encoded class " + name);
encodedClazz = null;
}
}
// At this point, at most one of clazz and source should be set.
if (clazz != null && this.allowRawClasses) {
if (Report.should_report(report_topics, 4))
Report.report(4, "Using raw class file for " + name);
return clazz.type(ts);
}
if (source != null) {
if (Report.should_report(report_topics, 4))
Report.report(4, "Using source file for " + name);
return getTypeFromSource(source, name);
}
if (clazz != null && !this.allowRawClasses) {
// We have a raw class only. We do not have the source code,
// or encoded class information.
throw new SemanticException("Class \"" + name + "\" not found."
+ " A class file was found, but it did not contain appropriate"
+ " information for the Polyglot-based compiler " +
ext.compilerName() + ". Try using " + ext.compilerName()
+ " to recompile the source code.");
}
throw new NoClassException(name);
}
/**
* Get a type from a source file.
*/
protected Named getTypeFromSource(FileSource source, String name)
throws SemanticException
{
// Compile the source file just enough to get the type information out.
ext.readSource(source);
// Even if there was an error when compiling the source file, we may
// as well keep trying to compile the current class, as the error may
// have been with something source depended on, that we do not.
return ts.parsedResolver().find(name);
}
}
|
package org.intermine.web;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.Locale;
import java.text.DateFormat;
import java.text.ParseException;
import org.apache.struts.Globals;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionMessages;
import org.intermine.util.TypeUtil;
import org.intermine.objectstore.query.ConstraintOp;
/**
* The main form, using for editing constraints
* @author Mark Woodbridge
*/
public class MainForm extends ActionForm
{
protected String bagOp, bagValue;
protected String attributeOp, attributeValue;
protected String subclassValue;
protected String loopQueryOp, loopQueryValue;
protected String path;
protected String nullConstraint;
protected Object parsedAttributeValue;
/**
* Gets the value of loopQueryOp
*
* @return the value of loopQueryOp
*/
public String getLoopQueryOp() {
return loopQueryOp;
}
/**
* Sets the value of loopQueryOp
*
* @param loopOp Value to assign to loopQueryOp
*/
public void setLoopQueryOp(String loopOp) {
this.loopQueryOp = loopOp;
}
/**
* Gets the value of loopQueryValue
*
* @return the value of loopQueryValue
*/
public String getLoopQueryValue() {
return loopQueryValue;
}
/**
* Sets the value of loopQueryValue
*
* @param loopQuery value to assign to loopQueryValue
*/
public void setLoopQueryValue(String loopQuery) {
this.loopQueryValue = loopQuery;
}
/**
* Gets the value of bagOp
*
* @return the value of bagOp
*/
public String getBagOp() {
return bagOp;
}
/**
* Sets the value of bagOp
*
* @param bagOp Value to assign to bagOp
*/
public void setBagOp(String bagOp) {
this.bagOp = bagOp;
}
/**
* Gets the value of bagValue
*
* @return the value of bagValue
*/
public String getBagValue() {
return bagValue;
}
/**
* Sets the value of bagValue
*
* @param bagValue value to assign to bagValue
*/
public void setBagValue(String bagValue) {
this.bagValue = bagValue;
}
/**
* Gets the value of attributeOp
*
* @return the value of attributeOp
*/
public String getAttributeOp() {
return attributeOp;
}
/**
* Sets the value of attributeOp
*
* @param attributeOp value to assign to attributeOp
*/
public void setAttributeOp(String attributeOp) {
this.attributeOp = attributeOp;
}
/**
* Gets the value of attributeValue
*
* @return the value of attributeValue
*/
public String getAttributeValue() {
return attributeValue;
}
/**
* Sets the value of attributeValue
*
* @param attributeValue value to assign to attributeValue
*/
public void setAttributeValue(String attributeValue) {
this.attributeValue = attributeValue;
}
/**
* Gets the value of subclassValue
*
* @return the value of subclassValue
*/
public String getSubclassValue() {
return subclassValue;
}
/**
* Sets the value of subclassValue
*
* @param subclassValue value to assign to subclassValue
*/
public void setSubclassValue(String subclassValue) {
this.subclassValue = subclassValue;
}
/**
* Gets the value of path
*
* @return the value of path
*/
public String getPath() {
return path;
}
/**
* Sets the value of path
*
* @param path value to assign to path
*/
public void setPath(String path) {
this.path = path;
}
/**
* Get the null/not null constraint value. Returned value will be
* either "NULL" or "NotNULL".
*
* @return null/not null constraint value
*/
public String getNullConstraint() {
return nullConstraint;
}
/**
* Set the null/not null constraint. Parameter should be
* either "NULL" or "NotNULL".
*
* @param nullConstraint null/not null constraint
*/
public void setNullConstraint(String nullConstraint) {
this.nullConstraint = nullConstraint;
}
/**
* Gets the value of parsedAttributeValue
*
* @return the value of parsedAttributeValue
*/
public Object getParsedAttributeValue() {
return parsedAttributeValue;
}
/**
* Sets the value of parsedAttributeValue
*
* @param parsedAttributeValue value to assign to parsedAttributeValue
*/
public void setParsedAttributeValue(Object parsedAttributeValue) {
this.parsedAttributeValue = parsedAttributeValue;
}
/**
* @see ActionForm#validate
*/
public ActionErrors validate(ActionMapping mapping, HttpServletRequest request) {
HttpSession session = request.getSession();
ServletContext servletContext = session.getServletContext();
Locale locale = (Locale) session.getAttribute(Globals.LOCALE_KEY);
PathQuery query = (PathQuery) session.getAttribute(Constants.QUERY);
ActionErrors errors = new ActionErrors();
ConstraintOp constraintOp = (getAttributeOp() == null) ? null
: ConstraintOp.getOpForIndex(Integer.valueOf(getAttributeOp()));
if (request.getParameter("attribute") != null) {
PathNode node = (PathNode) query.getNodes().get(path);
Class fieldClass = MainHelper.getClass(node.getType());
parsedAttributeValue =
parseValue(attributeValue, fieldClass, constraintOp, locale, errors);
}
if (errors.size() > 0) {
session.setAttribute("editingNode", query.getNodes().get(path));
}
return errors;
}
/**
* Parse an attribute value
* @param value the value as a String
* @param type the type of the parsed value
* @param constraintOp the constraint operator for which value is an intended argument
* @param locale the user's locale
* @param errors ActionErrors to which any parse errors are added
* @return the parsed value
*/
public static Object parseValue(String value, Class type, ConstraintOp constraintOp,
Locale locale, ActionMessages errors) {
Object parsedValue = null;
if (Date.class.equals(type)) {
DateFormat df = DateFormat.getDateInstance(DateFormat.SHORT, locale);
try {
parsedValue = df.parse(value);
} catch (ParseException e) {
errors.add(ActionMessages.GLOBAL_MESSAGE,
new ActionMessage("errors.date", value, df.format(new Date())));
}
} else if (String.class.equals(type) && (constraintOp == ConstraintOp.MATCHES
|| constraintOp == ConstraintOp.DOES_NOT_MATCH)) {
// Is the expression valid? We need a non-zero length string at least
if (value.length() == 0) {
errors.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("errors.like"));
} else {
if (value instanceof String) {
value = ((String) value).trim();
}
parsedValue = wildcardUserToSql(value);
}
} else {
try {
parsedValue = TypeUtil.stringToObject(type, value);
if (parsedValue instanceof String) {
parsedValue = ((String) parsedValue).trim();
}
} catch (NumberFormatException e) {
String shortName = TypeUtil.unqualifiedName(type.getName()).toLowerCase();
errors.add(ActionMessages.GLOBAL_MESSAGE,
new ActionMessage("errors." + shortName, value));
}
}
return parsedValue;
}
/**
* Convert an SQL LIKE/NOT LIKE expression to a * wildcard expression.
*
* @param exp the wildcard expression
* @return the SQL LIKE parameter
*/
public static String wildcardSqlToUser(String exp) {
if (exp.charAt(0) == '%' && exp.charAt(exp.length() - 1) == '%') {
return exp.substring(1, exp.length() - 1);
} else if (exp.charAt(0) == '%') {
return "*" + exp.substring(1);
} else if (exp.charAt(exp.length() - 1) == '%') {
return exp.substring(0, exp.length() - 1) + "*";
} else {
return exp;
}
}
/**
* Turn a user supplied wildcard expression with * into an SQL LIKE/NOT LIKE
* expression with %'s.
*
* @param exp the SQL LIKE parameter
* @return the equivalent wildcard expression
*/
public static String wildcardUserToSql(String exp) {
if (exp.length() == 0) {
throw new IllegalArgumentException(exp);
}
if (exp.charAt(0) == '*') {
exp = '%' + exp.substring(1);
}
if (exp.charAt(exp.length() - 1) == '*') {
exp = exp.substring(0, exp.length() - 1) + '%';
}
if (exp.charAt(0) != '%' && exp.charAt(exp.length() - 1) != '%') {
exp = '%' + exp + '%';
}
return exp;
}
/**
* @see ActionForm#reset
*/
public void reset(ActionMapping mapping, HttpServletRequest request) {
bagOp = null;
bagValue = null;
attributeOp = null;
attributeValue = null;
subclassValue = null;
path = null;
nullConstraint = "NULL";
}
}
|
package balls.view;
import balls.controller.Controller;
import balls.model.Model;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javafx.fxml.FXMLLoader;
import javafx.scene.Scene;
import javafx.scene.layout.AnchorPane;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.canvas.Canvas;
import javafx.scene.canvas.GraphicsContext;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.ScrollPane;
import javafx.scene.control.Slider;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.HBox;
import javafx.scene.layout.StackPane;
import javafx.scene.layout.VBox;
import javafx.scene.paint.Color;
import javafx.scene.shape.Circle;
import javafx.scene.shape.Shape;
import javafx.stage.Stage;
/**
*
* @author n0g3
*/
public class View {
private Controller controller;
private AnchorPane root;
private Scene scene;
private Stage stage;
private Slider gravitySlider;
private Label gravityValueLabel;
private GraphicsContext gc;
private Button startButton;
public View() {
initGui();
}
private void initGui() {
VBox vBox = new VBox();
GridPane gridPane = new GridPane();
AnchorPane canPane = new AnchorPane();
Canvas canvas = new Canvas(400, 400);
gc = canvas.getGraphicsContext2D();
canPane.setStyle("-fx-background-color: #96bbfc");
Label gravityLabel = new Label("Gravity");
setGravitySlider(new Slider(1, 30,9));
startButton = new Button("START");
setGravityValueLabel(new Label(String.valueOf(gravitySlider.getValue())));
gridPane.add(gravityLabel, 0, 0);
gridPane.add(getGravitySlider(), 1, 0);
gridPane.add(getGravityValueLabel(), 2, 0);
gridPane.add(startButton,1,1);
canPane.getChildren().add(canvas);
vBox.getChildren().addAll(canPane, gridPane);
scene = new Scene(vBox);
}
/**
* @return the controller
*/
public Controller getController() {
return controller;
}
/**
* @param controller the controller to set
*/
public void setController(Controller controller) {
this.controller = controller;
}
/**
* @return the scene
*/
public Scene getScene() {
return scene;
}
/**
* @param scene the scene to set
*/
public void setScene(Scene scene) {
this.scene = scene;
}
/**
* @return the stage
*/
public Stage getStage() {
return stage;
}
/**
* @param stage the stage to set
*/
public void setStage(Stage stage) {
this.stage = stage;
}
/**
* @return the gravitySlider
*/
public Slider getGravitySlider() {
return gravitySlider;
}
/**
* @param gravitySlider the gravitySlider to set
*/
public void setGravitySlider(Slider gravitySlider) {
this.gravitySlider = gravitySlider;
}
/**
* @return the gravityValueLabel
*/
public Label getGravityValueLabel() {
return gravityValueLabel;
}
/**
* @param gravityValueLabel the gravityValueLabel to set
*/
public void setGravityValueLabel(Label gravityValueLabel) {
this.gravityValueLabel = gravityValueLabel;
}
public void drawBall(float x, float y,float r) {
gc.setFill(Color.BLACK);
gc.fillOval(x, y, r, r);
}
/**
* @return the button
*/
public Button getButton() {
return startButton;
}
/**
* @param button the button to set
*/
public void setButton(Button button) {
this.startButton = button;
}
}
|
package gnu.expr;
import gnu.bytecode.*;
import gnu.mapping.*;
/**
* Class used to implement "let" syntax (and variants) for Scheme.
* @author Per Bothner
*/
public class LetExp extends ScopeExp
{
public Expression[] inits;
public Expression body;
public LetExp (Expression[] i) { inits = i; }
public Expression getBody() { return body; }
public void setBody(Expression body) { this.body = body; }
/* Recursive helper routine, to store the values on the stack
* into the variables in vars, in reverse order. */
void store_rest (Compilation comp, int i, Declaration decl)
{
if (decl != null)
{
store_rest (comp, i+1, decl.nextDecl());
if (decl.needsInit())
{
if (decl.isIndirectBinding())
{
CodeAttr code = comp.getCode();
if (inits[i] == QuoteExp.undefined_exp)
{
Object name = decl.getSymbol();
comp.compileConstant(name, Target.pushObject);
code.emitInvokeStatic(BindingInitializer.makeLocationMethod(name));
}
else
{
decl.pushIndirectBinding(comp);
}
code.emitStore(decl.getVariable());
}
else
decl.compileStore(comp);
}
}
}
/* CPS:
* Need to ensure that ctx.pc is 0 before the this is called
* the first time. This is currently done by match0.
* Need to define concention so ReferenceExp can find appropriate binding.
* Need to define convention for what gets copied, if anything,
* when a continuation is created. (Note problem below if a half-initialized
* frame gets captuerd. Then multiple cals to the same continuation
* could clobber the frame, unless it has been copied. But copying the
* frame is tricky if we want to avoid copying the whole stack, plus we
* have to correctly handle set! to a local/
public void apply (CallContext ctx) throws Throwable
{
CallFrame fr;
if (ctx.pc == 0)
{
fr = new gnu.mapping.CallFrame();
fr.previous = ctx.frame;
fr.saveVstackLen = ctx.startFromContext();
ctx.frame = fr;
}
else
fr = ctx.frame;
int i = ctx.pc;
if (i == inits.length + 1)
{
// pop
ctx.frame = fr.previous;
return;
}
if (i > 0)
fr.values[i-1] = ctx.getFromContext(fr.saveVstackLen);
ctx.pc++;
if (i == inits.length)
{
body.match0(ctx);
return;
}
fr.saveVstackLen = ctx.startFromContext();
inits[i].match0(ctx);
}
*/
public void compile (Compilation comp, Target target)
{
gnu.bytecode.CodeAttr code = comp.getCode();
/*
if (comp.usingCPStyle())
{
for (Declartion decl = firstDecl(); decl != null; decl = decl.nextVar ())
{
decl.assignField(comp);
}
}
*/
/* Compile all the initializations, leaving the results
on the stack (in reverse order). */
Declaration decl = firstDecl();
for (int i = 0; i < inits.length; i++, decl = decl.nextDecl())
{
Target varTarget;
Expression init = inits[i];
decl.allocateVariable(code);
if (! decl.needsInit()
|| (decl.isIndirectBinding() && inits[i] == QuoteExp.undefined_exp))
varTarget = Target.Ignore;
else
{
Type varType = decl.getType();
varTarget = CheckedTarget.getInstance(varType);
if (init == QuoteExp.undefined_exp)
{
if (varType instanceof PrimType)
init = new QuoteExp(new Byte((byte) 0));
else if (varType != null && varType != Type.pointer_type)
init = QuoteExp.nullExp;
}
}
init.compile (comp, varTarget);
}
code.enterScope(getVarScope());
/* Assign the initial values to the proper variables, in reverse order. */
store_rest (comp, 0, firstDecl());
body.compileWithPosition(comp, target);
code.popScope ();
}
public final gnu.bytecode.Type getType()
{
return body.getType();
}
protected Expression walk (ExpWalker walker)
{
return walker.walkLetExp(this);
}
protected void walkChildren(ExpWalker walker)
{
if (inits != null)
inits = walker.walkExps(inits);
if (walker.exitValue == null)
body = (Expression) walker.walk(body);
}
public void print (OutPort out)
{
print(out, "(Let", ")");
}
public void print (OutPort out, String startTag, String endTag)
{
out.startLogicalBlock(startTag+"#"+id, endTag, 2);
out.writeSpaceFill();
printLineColumn(out);
out.startLogicalBlock("(", false, ")");
Declaration decl = firstDecl();
int i = 0;
for (; decl != null; decl = decl.nextDecl())
{
if (i > 0)
out.writeSpaceFill();
out.startLogicalBlock("(", false, ")");
decl.printInfo(out);
if (inits != null)
{
out.writeSpaceFill();
out.print('=');
out.writeSpaceFill();
//if (decl.isArtificial ())
//out.print ("<artificial>");
//else
{
if (i >= inits.length)
out.print("<missing init>");
else if (inits[i] == null)
out.print("<null>");
else
inits[i].print(out);
i++;
}
}
out.endLogicalBlock(")");
}
out.endLogicalBlock(")");
out.writeSpaceLinear();
body.print (out);
out.endLogicalBlock(endTag);
}
}
|
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
// all copies or substantial portions of the Software.
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
package com.uber.m3.tally.m3;
import com.uber.m3.tally.Buckets;
import com.uber.m3.tally.Capabilities;
import com.uber.m3.tally.CapableOf;
import com.uber.m3.tally.DurationBuckets;
import com.uber.m3.tally.StatsReporter;
import com.uber.m3.tally.ValueBuckets;
import com.uber.m3.tally.m3.thrift.TCalcTransport;
import com.uber.m3.tally.m3.thrift.TMultiUdpClient;
import com.uber.m3.tally.m3.thrift.TUdpClient;
import com.uber.m3.tally.m3.thrift.TUdpTransport;
import com.uber.m3.thrift.gen.CountValue;
import com.uber.m3.thrift.gen.GaugeValue;
import com.uber.m3.thrift.gen.M3;
import com.uber.m3.thrift.gen.Metric;
import com.uber.m3.thrift.gen.MetricBatch;
import com.uber.m3.thrift.gen.MetricTag;
import com.uber.m3.thrift.gen.MetricValue;
import com.uber.m3.thrift.gen.TimerValue;
import com.uber.m3.util.Duration;
import com.uber.m3.util.ImmutableMap;
import org.apache.http.annotation.NotThreadSafe;
import org.apache.thrift.TException;
import org.apache.thrift.protocol.TCompactProtocol;
import org.apache.thrift.protocol.TProtocol;
import org.apache.thrift.protocol.TProtocolFactory;
import org.apache.thrift.transport.TTransport;
import org.apache.thrift.transport.TTransportException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.net.InetAddress;
import java.net.SocketAddress;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.time.Clock;
import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ScheduledExecutorService;
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.concurrent.atomic.AtomicReference;
/**
* An M3 implementation of a {@link StatsReporter}.
*/
public class M3Reporter implements StatsReporter, AutoCloseable {
public static final String SERVICE_TAG = "service";
public static final String ENV_TAG = "env";
public static final String HOST_TAG = "host";
public static final String DEFAULT_TAG_VALUE = "default";
public static final String DEFAULT_HISTOGRAM_BUCKET_ID_NAME = "bucketid";
public static final String DEFAULT_HISTOGRAM_BUCKET_NAME = "bucket";
public static final int DEFAULT_HISTOGRAM_BUCKET_TAG_PRECISION = 6;
/**
* NOTE: DO NOT CHANGE THIS NUMBER!
* Reporter architecture is not suited for multi-processor setup and might cause some disruption
* to how metrics are processed and eventually submitted to M3 collectors;
*/
static final int NUM_PROCESSORS = 1;
private static final Logger LOG = LoggerFactory.getLogger(M3Reporter.class);
private static final int MAX_DELAY_BEFORE_FLUSHING_MILLIS = 1_000;
private static final int MAX_PROCESSOR_WAIT_ON_CLOSE_MILLIS = 5_000;
private static final int DEFAULT_METRIC_SIZE = 100;
private static final int DEFAULT_MAX_QUEUE_SIZE = 4096;
private static final int DEFAULT_MAX_PACKET_SIZE = TUdpTransport.PACKET_DATA_PAYLOAD_MAX_SIZE;
// NOTE: 256 bytes of overhead is reserved for Thrift metadata within UDP datagram payload
private static final int THRIFT_METADATA_PADDING = 256;
private static final int MIN_METRIC_BUCKET_ID_TAG_LENGTH = 4;
private static final ThreadLocal<SerializedPayloadSizeEstimator> PAYLOAD_SIZE_ESTIMATOR =
ThreadLocal.withInitial(SerializedPayloadSizeEstimator::new);
private final Duration maxBufferingDelay;
private final int payloadCapacity;
private final String bucketIdTagKey;
private final String bucketValueTagKey;
private final String bucketValFmt;
private final Set<MetricTag> commonTags;
// TODO replace w/ an evicting queue
private final BlockingQueue<SizedMetric> queue;
// Executor service running processors flushing metrics to collectors
private final ExecutorService executorService;
private final ScheduledExecutorService scheduledExecutorService;
private final Clock clock;
// This is a synchronization barrier to make sure that reporter
// is being shutdown only after all of its processor had done so
private final CountDownLatch processorsShutdownLatch;
// List of socket addresses for M3 collector endpoint
private final SocketAddress[] collectorEndpointSockedAddresses;
private final Processor[] processors;
private final TProtocolFactory protocolFactory;
private final AtomicBoolean isShutdown = new AtomicBoolean(false);
// Use inner Builder class to construct an M3Reporter
M3Reporter(Builder builder, TProtocolFactory thriftProtocolFactory) {
payloadCapacity = calculatePayloadCapacity(builder.maxPacketSizeBytes, builder.metricTagSet);
maxBufferingDelay = Duration.ofMillis(builder.maxProcessorWaitUntilFlushMillis);
bucketIdTagKey = builder.histogramBucketIdName;
bucketValueTagKey = builder.histogramBucketName;
bucketValFmt = String.format("%%.%df", builder.histogramBucketTagPrecision);
queue = new LinkedBlockingQueue<>(builder.maxQueueSize);
ThreadFactory namedThreadFactory = createThreadFactory();
executorService = builder.executor != null ? builder.executor : Executors.newFixedThreadPool(NUM_PROCESSORS, namedThreadFactory);
scheduledExecutorService = Executors.newSingleThreadScheduledExecutor(namedThreadFactory);
clock = Clock.systemUTC();
commonTags = builder.metricTagSet;
protocolFactory = thriftProtocolFactory;
processorsShutdownLatch = new CountDownLatch(NUM_PROCESSORS);
collectorEndpointSockedAddresses = builder.endpointSocketAddresses;
processors = new Processor[NUM_PROCESSORS];
for (int i = 0; i < NUM_PROCESSORS; ++i) {
processors[i] = bootProcessor(collectorEndpointSockedAddresses);
}
// Schedule regular heartbeat up-keeping processors up and running
scheduledExecutorService.scheduleAtFixedRate(this::heartbeat, 1, 1, TimeUnit.SECONDS);
}
// NOTE: This method is not concurrent
void heartbeat() {
synchronized (this) {
for (int i = 0; i < processors.length; ++i) {
if (processors[i].getState() != ProcessorState.RUNNING) {
processors[i] = bootProcessor(collectorEndpointSockedAddresses);
}
}
}
}
private int calculatePayloadCapacity(int maxPacketSizeBytes, Set<MetricTag> commonTags) {
MetricBatch metricBatch = new MetricBatch();
metricBatch.setCommonTags(commonTags);
metricBatch.setMetrics(new ArrayList<>());
int thriftRequestShellSize = PAYLOAD_SIZE_ESTIMATOR.get().evaluateThriftRequestWireSize(metricBatch);
int payloadCapacity = maxPacketSizeBytes - (THRIFT_METADATA_PADDING + thriftRequestShellSize);
if (payloadCapacity <= 0) {
throw new IllegalArgumentException("Common tags serialized size exceeds packet size");
}
return payloadCapacity;
}
private static String getHostName() {
try {
return InetAddress.getLocalHost().getHostName();
} catch (UnknownHostException e) {
LOG.warn("Unable to determine hostname. Defaulting to: {}", DEFAULT_TAG_VALUE);
return DEFAULT_TAG_VALUE;
}
}
private Processor bootProcessor(SocketAddress[] endpointSocketAddresses) {
try {
Processor processor = new Processor(endpointSocketAddresses, protocolFactory);
executorService.execute(processor);
return processor;
} catch (TTransportException | SocketException e) {
LOG.error("Failed to boot processor", e);
throw new RuntimeException(e);
}
}
@Override
public Capabilities capabilities() {
return CapableOf.REPORTING_TAGGING;
}
@Override
public void flush() {
if (isShutdown.get()) {
return;
}
for (Processor processor : processors) {
processor.scheduleFlush();
}
}
@Override
public void close() {
if (!isShutdown.compareAndSet(false, true)) {
// Shutdown already
return;
}
// Important to use `shutdownNow` instead of `shutdown` to interrupt processor
// thread(s) or else they will block forever
scheduledExecutorService.shutdownNow();
executorService.shutdownNow();
try {
// Wait a maximum of `MAX_PROCESSOR_WAIT_ON_CLOSE_MILLIS` for all processors
// to complete
if (!processorsShutdownLatch.await(MAX_PROCESSOR_WAIT_ON_CLOSE_MILLIS, TimeUnit.MILLISECONDS)) {
LOG.warn(
"M3Reporter closing before Processors complete after waiting timeout of {}ms!",
MAX_PROCESSOR_WAIT_ON_CLOSE_MILLIS
);
}
} catch (InterruptedException e) {
LOG.warn("M3Reporter closing before Processors complete due to being interrupted!");
}
}
private static Set<MetricTag> toMetricTagSet(Map<String, String> tags) {
Set<MetricTag> metricTagSet = new HashSet<>();
if (tags == null) {
return metricTagSet;
}
for (Map.Entry<String, String> tag : tags.entrySet()) {
metricTagSet.add(createMetricTag(tag.getKey(), tag.getValue()));
}
return metricTagSet;
}
private static MetricTag createMetricTag(String tagName, String tagValue) {
MetricTag metricTag = new MetricTag(tagName);
if (tagValue != null && !tagValue.isEmpty()) {
metricTag.setTagValue(tagValue);
}
return metricTag;
}
private String valueBucketString(double bucketBound) {
if (bucketBound == Double.MAX_VALUE) {
return "infinity";
}
if (bucketBound == -Double.MAX_VALUE) {
return "-infinity";
}
return String.format(bucketValFmt, bucketBound);
}
private String durationBucketString(Duration bucketBound) {
if (Duration.ZERO.equals(bucketBound)) {
return "0";
}
if (Duration.MAX_VALUE.equals(bucketBound)) {
return "infinity";
}
if (Duration.MIN_VALUE.equals(bucketBound)) {
return "-infinity";
}
return bucketBound.toString();
}
@Override
public void reportCounter(String name, Map<String, String> tags, long value) {
reportCounterInternal(name, tags, value);
}
@Override
public void reportGauge(String name, Map<String, String> tags, double value) {
GaugeValue gaugeValue = new GaugeValue();
gaugeValue.setDValue(value);
MetricValue metricValue = new MetricValue();
metricValue.setGauge(gaugeValue);
Metric metric = newMetric(name, tags, metricValue);
enqueue(new SizedMetric(metric, PAYLOAD_SIZE_ESTIMATOR.get().evaluateByteSize(metric)));
}
@Override
public void reportTimer(String name, Map<String, String> tags, Duration interval) {
TimerValue timerValue = new TimerValue();
timerValue.setI64Value(interval.getNanos());
MetricValue metricValue = new MetricValue();
metricValue.setTimer(timerValue);
Metric metric = newMetric(name, tags, metricValue);
enqueue(new SizedMetric(metric, PAYLOAD_SIZE_ESTIMATOR.get().evaluateByteSize(metric)));
}
/**
* @deprecated DO NOT USE
*
* Please use {@link #reportHistogramValueSamples(String, Map, Buckets, int, long)} instead
*/
@Deprecated
@Override
public void reportHistogramValueSamples(
String name,
Map<String, String> tags,
Buckets buckets,
double bucketLowerBound,
double bucketUpperBound,
long samples
) {
reportHistogramValueSamples(name, tags, buckets, buckets.getBucketIndexFor(bucketLowerBound), samples);
}
/**
* @deprecated DO NOT USE
*
* Please use {@link #reportHistogramValueSamples(String, Map, Buckets, int, long)} instead
*/
@Override
@Deprecated
public void reportHistogramDurationSamples(
String name,
Map<String, String> tags,
Buckets buckets,
Duration bucketLowerBound,
Duration bucketUpperBound,
long samples
) {
reportHistogramValueSamples(name, tags, buckets, buckets.getBucketIndexFor(bucketLowerBound), samples);
}
public void reportHistogramValueSamples(
String name,
Map<String, String> tags,
Buckets buckets,
int bucketIndex,
long samples
) {
// Append histogram bucket-specific tags
int bucketIdLen = String.valueOf(buckets.size()).length();
bucketIdLen = Math.max(bucketIdLen, MIN_METRIC_BUCKET_ID_TAG_LENGTH);
String bucketIdFmt = String.format("%%0%sd", bucketIdLen);
ImmutableMap.Builder<String, String> builder = new ImmutableMap.Builder<>();
if (tags != null) {
builder.putAll(tags);
}
String bucketValueTag;
if (buckets instanceof ValueBuckets) {
bucketValueTag =
String.format("%s-%s",
valueBucketString(buckets.getValueLowerBoundFor(bucketIndex)),
valueBucketString(buckets.getValueUpperBoundFor(bucketIndex))
);
} else if (buckets instanceof DurationBuckets) {
bucketValueTag =
String.format("%s-%s",
durationBucketString(buckets.getDurationLowerBoundFor(bucketIndex)),
durationBucketString(buckets.getDurationUpperBoundFor(bucketIndex))
);
} else {
throw new IllegalArgumentException("unsupported buckets format");
}
builder
.put(bucketIdTagKey, String.format(bucketIdFmt, bucketIndex))
.put(bucketValueTagKey, bucketValueTag);
reportCounterInternal(name, builder.build(), samples);
}
// Relies on the calling function to provide guarantees of the reporter being open
private void reportCounterInternal(String name, Map<String, String> tags, long value) {
CountValue countValue = new CountValue();
countValue.setI64Value(value);
MetricValue metricValue = new MetricValue();
metricValue.setCount(countValue);
Metric metric = newMetric(name, tags, metricValue);
enqueue(new SizedMetric(metric, PAYLOAD_SIZE_ESTIMATOR.get().evaluateByteSize(metric)));
}
private Metric newMetric(String name, Map<String, String> tags, MetricValue metricValue) {
Metric metric = new Metric(name);
metric.setTags(toMetricTagSet(tags));
metric.setTimestamp(System.currentTimeMillis() * Duration.NANOS_PER_MILLI);
metric.setMetricValue(metricValue);
return metric;
}
private void enqueue(SizedMetric sizedMetric) {
// Short-circuit if already shutdown
if (isShutdown.get()) {
return;
}
try {
boolean enqueued = queue.offer(sizedMetric, 10, TimeUnit.MILLISECONDS);
if (!enqueued) {
LOG.warn("Failed to enqueue metric for emission");
}
} catch (InterruptedException e) {
LOG.warn("Interrupted while waiting to enqueuing metric; dropping");
}
}
private static void runNoThrow(ThrowingRunnable r) {
try {
r.run();
} catch (Throwable t) {
// no-op
}
}
private static ThreadFactory createThreadFactory() {
return new ThreadFactory() {
private final AtomicInteger counter = new AtomicInteger(0);
@Override
public Thread newThread(Runnable r) {
return new Thread(r, String.format("m3-reporter-%d", counter.getAndIncrement()));
}
};
}
private class Processor implements Runnable {
private final List<Metric> metricsBuffer =
new ArrayList<>(payloadCapacity / 10);
private Instant lastBufferFlushTimestamp = Instant.now(clock);
private int bufferedBytes = 0;
private final M3.Client client;
private final TTransport transport;
private final AtomicReference<ProcessorState> state = new AtomicReference<>();
private final AtomicBoolean shouldFlush = new AtomicBoolean(false);
Processor(SocketAddress[] socketAddresses, TProtocolFactory protocolFactory) throws TTransportException, SocketException {
if (socketAddresses.length > 1) {
transport = new TMultiUdpClient(socketAddresses);
} else {
transport = new TUdpClient(socketAddresses[0]);
}
// Open the socket
transport.open();
client = new M3.Client(protocolFactory.getProtocol(transport));
state.set(ProcessorState.RUNNING);
LOG.info("Booted reporting processor");
}
@Override
public void run() {
while (!isShutdown.get()) {
try {
// Check whether flush has been requested by the reporter
if (shouldFlush.compareAndSet(true, false)) {
flushBuffered();
}
// This `poll` call will block for at most the specified duration to take an item
// off the queue. If we get an item, we append it to the queue to be flushed,
// otherwise we flush what we have so far.
// When this reporter is closed, shutdownNow will be called on the executor,
// which will interrupt this thread and proceed to the `InterruptedException`
// catch block.
SizedMetric sizedMetric = queue.poll(maxBufferingDelay.toMillis(), TimeUnit.MILLISECONDS);
if (sizedMetric == null) {
// If we didn't get any new metrics after waiting the specified time,
// flush what we have so far.
flushBuffered();
} else {
process(sizedMetric);
}
} catch (InterruptedException t) {
// no-op
} catch (Throwable t) {
// This is fly-away guard making sure that uncaught exception
// will be logged
LOG.error("Unhandled exception in processor", t);
break;
}
}
state.set(ProcessorState.SHUTDOWN);
LOG.warn("Processor shutting down");
shutdown();
LOG.warn("Processor shut down");
}
private void shutdown() {
// Drain queue of any remaining metrics submitted prior to shutdown;
runNoThrow(this::drainQueue);
// Flush remaining buffers at last (best effort)
runNoThrow(this::flushBuffered);
// Close transport
transport.close();
// Count down shutdown latch to notify reporter
processorsShutdownLatch.countDown();
}
private void process(SizedMetric sizedMetric) throws TException {
int size = sizedMetric.getSize();
if (bufferedBytes + size > payloadCapacity || elapsedMaxDelaySinceLastFlush()) {
flushBuffered();
}
Metric metric = sizedMetric.getMetric();
metricsBuffer.add(metric);
bufferedBytes += size;
}
private boolean elapsedMaxDelaySinceLastFlush() {
return Instant.now(clock).isAfter(
lastBufferFlushTimestamp.plus(maxBufferingDelay.toMillis(), ChronoUnit.MILLIS)
);
}
private void drainQueue() throws TException {
SizedMetric metrics;
while ((metrics = queue.poll()) != null) {
process(metrics);
}
}
private void flushBuffered() throws TException {
if (metricsBuffer.isEmpty()) {
return;
}
try {
client.emitMetricBatch(
new MetricBatch()
.setCommonTags(commonTags)
.setMetrics(metricsBuffer)
);
} catch (TException t) {
LOG.error("Failed to flush metrics", t);
throw t;
}
metricsBuffer.clear();
bufferedBytes = 0;
lastBufferFlushTimestamp = Instant.now(clock);
}
public void scheduleFlush() {
shouldFlush.set(true);
}
public ProcessorState getState() {
return state.get();
}
}
enum ProcessorState {
RUNNING,
SHUTDOWN
}
@FunctionalInterface
interface ThrowingRunnable {
void run() throws Exception;
}
/**
* This class provides the facility to calculate the size of the payload serialized through {@link TCompactProtocol},
* using phony {@link TCalcTransport} as a measurer
*/
@NotThreadSafe
private static class SerializedPayloadSizeEstimator {
private final TCalcTransport calculatingPhonyTransport = new TCalcTransport();
private final TProtocol calculatingPhonyProtocol =
new TCompactProtocol.Factory().getProtocol(calculatingPhonyTransport);
private final M3.Client phonyClient = new M3.Client(calculatingPhonyProtocol);
public int evaluateThriftRequestWireSize(MetricBatch metricBatch) {
try {
phonyClient.emitMetricBatch(metricBatch);
return calculatingPhonyTransport.getSizeAndReset();
} catch (TException e) {
LOG.warn("Unable to calculate metric batch size", e);
throw new RuntimeException(e);
}
}
public int evaluateByteSize(Metric metric) {
try {
metric.write(calculatingPhonyProtocol);
return calculatingPhonyTransport.getSizeAndReset();
} catch (TException e) {
LOG.warn("Unable to calculate metric batch size. Defaulting to: " + DEFAULT_METRIC_SIZE, e);
return DEFAULT_METRIC_SIZE;
}
}
}
/**
* Builder pattern to construct an {@link M3Reporter}.
*/
public static class Builder {
protected SocketAddress[] endpointSocketAddresses;
protected String service;
protected String env;
protected ExecutorService executor;
// Non-generic EMPTY ImmutableMap will never contain any elements
@SuppressWarnings("unchecked")
protected ImmutableMap<String, String> commonTags = ImmutableMap.EMPTY;
protected boolean includeHost = false;
protected int maxQueueSize = DEFAULT_MAX_QUEUE_SIZE;
protected int maxPacketSizeBytes = DEFAULT_MAX_PACKET_SIZE;
protected int maxProcessorWaitUntilFlushMillis = MAX_DELAY_BEFORE_FLUSHING_MILLIS;
protected String histogramBucketIdName = DEFAULT_HISTOGRAM_BUCKET_ID_NAME;
protected String histogramBucketName = DEFAULT_HISTOGRAM_BUCKET_NAME;
protected int histogramBucketTagPrecision = DEFAULT_HISTOGRAM_BUCKET_TAG_PRECISION;
private Set<MetricTag> metricTagSet;
/**
* Constructs a {@link Builder}. Having at least one {@code SocketAddress} is required.
* @param endpointSocketAddresses the array of {@code SocketAddress}es for this {@link M3Reporter}
*/
public Builder(SocketAddress[] endpointSocketAddresses) {
if (endpointSocketAddresses == null || endpointSocketAddresses.length == 0) {
throw new IllegalArgumentException("Must specify at least one SocketAddress");
}
this.endpointSocketAddresses = endpointSocketAddresses;
}
/**
* Constructs a {@link Builder}. Having at least one {@code SocketAddress} is required.
* @param socketAddress the {@code SocketAddress} for this {@link M3Reporter}
*/
public Builder(SocketAddress socketAddress) {
this(new SocketAddress[]{socketAddress});
}
/**
* Configures the service of this {@link Builder}.
* @param service the value to set
* @return this {@link Builder} with the new value set
*/
public Builder service(String service) {
this.service = service;
return this;
}
/**
* Configures the env of this {@link Builder}.
* @param env the value to set
* @return this {@link Builder} with the new value set
*/
public Builder env(String env) {
this.env = env;
return this;
}
/**
* Configures the executor of this {@link Builder}.
* @param executor the value to set
* @return this {@link Builder} with the new value set
*/
public Builder executor(ExecutorService executor) {
this.executor = executor;
return this;
}
/**
* Configures the common tags of this {@link Builder}.
* @param commonTags the value to set
* @return this {@link Builder} with the new value set
*/
public Builder commonTags(ImmutableMap<String, String> commonTags) {
this.commonTags = commonTags;
return this;
}
/**
* Configures whether to include the host tag of this {@link Builder}.
* @param includeHost the value to set
* @return this {@link Builder} with the new value set
*/
public Builder includeHost(boolean includeHost) {
this.includeHost = includeHost;
return this;
}
/**
* Configures the maximum queue size of this {@link Builder}.
* @param maxQueueSize the value to set
* @return this {@link Builder} with the new value set
*/
public Builder maxQueueSize(int maxQueueSize) {
this.maxQueueSize = maxQueueSize;
return this;
}
/**
* Configures the maximum packet size in bytes of this {@link Builder}.
* @param maxPacketSizeBytes the value to set
* @return this {@link Builder} with the new value set
*/
public Builder maxPacketSizeBytes(int maxPacketSizeBytes) {
this.maxPacketSizeBytes = maxPacketSizeBytes;
return this;
}
/**
* Configures the maximum wait time in milliseconds size in bytes of this {@link Builder}.
* @param maxProcessorWaitUntilFlushMillis the value to set
* @return this {@link Builder} with the new value set
*/
public Builder maxProcessorWaitUntilFlushMillis(int maxProcessorWaitUntilFlushMillis) {
this.maxProcessorWaitUntilFlushMillis = maxProcessorWaitUntilFlushMillis;
return this;
}
/**
* Configures the histogram bucket ID name of this {@link Builder}.
* @param histogramBucketIdName the value to set
* @return this {@link Builder} with the new value set
*/
public Builder histogramBucketIdName(String histogramBucketIdName) {
this.histogramBucketIdName = histogramBucketIdName;
return this;
}
/**
* Configures the histogram bucket name of this {@link Builder}.
* @param histogramBucketName the value to set
* @return this {@link Builder} with the new value set
*/
public Builder histogramBucketName(String histogramBucketName) {
this.histogramBucketName = histogramBucketName;
return this;
}
/**
* Configures the histogram bucket tag precision of this {@link Builder}.
* @param histogramBucketTagPrecision the value to set
* @return this {@link Builder} with the new value set
*/
public Builder histogramBucketTagPrecision(int histogramBucketTagPrecision) {
this.histogramBucketTagPrecision = histogramBucketTagPrecision;
return this;
}
/**
* Builds and returns an {@link M3Reporter} with the configured paramters.
* @return a new {@link M3Reporter} instance with the configured paramters
*/
public M3Reporter build() {
metricTagSet = toMetricTagSet(commonTags);
// Set and ensure required tags
if (!commonTags.containsKey(SERVICE_TAG)) {
if (service == null || service.isEmpty()) {
throw new IllegalArgumentException(String.format("Common tag [%s] is required", SERVICE_TAG));
}
metricTagSet.add(createMetricTag(SERVICE_TAG, service));
}
if (!commonTags.containsKey(ENV_TAG)) {
if (env == null || env.isEmpty()) {
throw new IllegalArgumentException(String.format("Common tag [%s] is required", ENV_TAG));
}
metricTagSet.add(createMetricTag(ENV_TAG, env));
}
if (includeHost && !commonTags.containsKey(HOST_TAG)) {
metricTagSet.add(createMetricTag(HOST_TAG, getHostName()));
}
return new M3Reporter(this, new TCompactProtocol.Factory());
}
}
}
|
package jodd.madvoc;
import jodd.log.Log;
import jodd.madvoc.component.MadvocConfig;
import jodd.madvoc.component.MadvocController;
import jodd.servlet.DispatcherUtil;
import jodd.typeconverter.Convert;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/**
* Initializes and configures Madvoc and passes requests to {@link jodd.madvoc.component.MadvocController}.
*/
public class MadvocServletFilter implements Filter {
private static Log log;
/**
* Web application.
*/
public static final String PARAM_MADVOC_WEBAPP = "madvoc.webapp";
/**
* Madvoc configurator.
*/
public static final String PARAM_MADVOC_CONFIGURATOR = "madvoc.configurator";
/**
* List of Madvoc params and properties files to be found on classpath.
*/
public static final String PARAM_MADVOC_PARAMS = "madvoc.params";
protected FilterConfig filterConfig;
protected WebApplication webapp;
protected MadvocConfig madvocConfig;
protected MadvocController madvocController;
/**
* Filter initialization.
*/
public void init(FilterConfig filterConfig) throws ServletException {
this.filterConfig = filterConfig;
WebApplicationStarter starter = createWebApplicationStarter(filterConfig);
try {
webapp = starter.startNewWebApplication(filterConfig.getServletContext());
} catch (Exception ex) {
ex.printStackTrace();
throw new ServletException("Unable to start Madvoc web application.", ex);
}
log = Log.getLogger(MadvocServletFilter.class);
madvocController = starter.getMadvocController();
madvocConfig = starter.getMadvocConfig();
log.info("Madvoc application started.");
}
/**
* Creates {@link WebApplicationStarter web application starter} for this web application.
* Override it to set custom {@link MadvocConfig Madvoc configurator} or other core settings.
*/
protected WebApplicationStarter createWebApplicationStarter(FilterConfig filterConfig) {
WebApplicationStarter starter = new WebApplicationStarter();
starter.setWebAppClass(filterConfig.getInitParameter(PARAM_MADVOC_WEBAPP));
starter.setParamsFiles(Convert.toStringArray(filterConfig.getInitParameter(PARAM_MADVOC_PARAMS)));
starter.setMadvocConfigurator(filterConfig.getInitParameter(PARAM_MADVOC_CONFIGURATOR));
return starter;
}
/**
* Filter destruction.
*/
public void destroy() {
webapp.destroy(madvocConfig);
}
/**
* Builds {@link ActionRequest} and invokes it. If action result is a chain, it repeats the process.
*/
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) req;
HttpServletResponse response = (HttpServletResponse) res;
String actionPath = DispatcherUtil.getServletPath(request);
try {
actionPath = madvocController.invoke(actionPath, request, response);
} catch (Exception ex) {
log.error("Exception while invoking action path: " + actionPath, ex);
ex.printStackTrace();
throw new ServletException(ex);
}
if (actionPath != null) { // action path is not consumed
actionPath = processUnhandledPath(actionPath, req, res);
if (actionPath != null) {
chain.doFilter(request, response);
}
}
}
/**
* Process unconsumed action paths. Returns <code>null</code> if action path is consumed, otherwise
* it returns action path to be consumed by filter chain.
* By default it just returns action path.
*/
@SuppressWarnings({"UnusedDeclaration"})
protected String processUnhandledPath(String actionPath, ServletRequest request, ServletResponse response) throws IOException, ServletException {
return actionPath;
}
}
|
package org.modmine.web;
import java.io.IOException;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Set;
import org.apache.log4j.Logger;
import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.StopAnalyzer;
import org.apache.lucene.analysis.snowball.SnowballAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.queryParser.ParseException;
import org.apache.lucene.queryParser.QueryParser;
import org.apache.lucene.search.Hits;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.store.RAMDirectory;
import org.intermine.api.InterMineAPI;
import org.intermine.model.bio.Submission;
import org.intermine.model.bio.SubmissionProperty;
import org.intermine.objectstore.ObjectStore;
public class ModMineSearch
{
public static String SEARCH_KEY = "modminesearch";
public static int MAX_HITS = 500;
private static final Logger LOG = Logger.getLogger(ModMineSearch.class);
private static RAMDirectory ram = null;
private static Map<Integer, Integer> submissionMap = new HashMap<Integer, Integer>();
public static void initModMineSearch(InterMineAPI im) {
if (ram == null) {
//Map<Integer, Set<String>> subProps = readSubmissionProperties(im);
Map<Integer, Set<String>> subProps = readSubmissionsFromCache(im.getObjectStore());
indexMetadata(subProps);
}
}
public static Map<Integer, Float> runLuceneSearch(String searchString) {
LinkedHashMap<Integer, Float> matches = new LinkedHashMap<Integer, Float>();
String queryString = searchString.replaceAll("(\\w+log\\b)", "$1ue $1");
queryString = queryString.replaceAll("[^a-zA-Z0-9]", " ").trim();
queryString = queryString.replaceAll("(\\w+)$", "$1 $1*");
long time = System.currentTimeMillis();
try {
IndexSearcher searcher = new IndexSearcher(ram);
Analyzer analyzer = new SnowballAnalyzer("English", StopAnalyzer.ENGLISH_STOP_WORDS);
org.apache.lucene.search.Query query;
QueryParser queryParser = new QueryParser("content", analyzer);
query = queryParser.parse(queryString);
// required to expand search terms
query = query.rewrite(IndexReader.open(ram));
Hits hits = searcher.search(query);
time = System.currentTimeMillis() - time;
LOG.info("Found " + hits.length() + " document(s) that matched query '"
+ queryString + "' in " + time + " milliseconds:");
//QueryScorer scorer = new QueryScorer(query);
for (int i = 0; (i < MAX_HITS && i < hits.length()); i++) {
Document doc = hits.doc(i);
String name = doc.get("name");
matches.put(Integer.parseInt(name), new Float(hits.score(i)));
}
// TODO proper error handling
} catch (ParseException e) {
throw new RuntimeException(e);
} catch (IOException e) {
throw new RuntimeException(e);
}
return matches;
}
private static Map<Integer, Set<String>> readSubmissionsFromCache(ObjectStore os) {
Map<Integer, Set<String>> subProps = new HashMap<Integer, Set<String>>();
for (DisplayExperiment exp : MetadataCache.getExperiments(os)) {
for (Submission sub : exp.getSubmissions()) {
Integer subId = sub.getId();
Integer dccId = sub.getdCCid();
// submission details
addMetaData(subProps, subId, sub.getdCCid().toString());
addMetaData(subProps, subId, sub.getTitle());
addMetaData(subProps, subId, sub.getDescription());
addMetaData(subProps, subId, sub.getExperimentType());
addMetaData(subProps, subId, sub.getOrganism().getName());
String genus = sub.getOrganism().getGenus();
if (genus.equals("Drosophila")) {
addMetaData(subProps, subId, "fly");
} else if (genus.equals("Caenorhabditis")) {
addMetaData(subProps, subId, "worm");
}
// experiment details
addMetaData(subProps, subId, exp.getPi());
addMetaData(subProps, subId, exp.getName());
addMetaData(subProps, subId, exp.getDescription());
addMetaData(subProps, subId, exp.getProjectName());
for (String lab : exp.getLabs()) {
addMetaData(subProps, subId, lab);
}
// add submission properties
for (SubmissionProperty prop : sub.getProperties()) {
// TODO reflection to find properties of subclasses as well
addMetaData(subProps, subId, prop.getName());
addMetaData(subProps, subId, prop.getType());
}
// add feature types
Map<String, Long> features = MetadataCache.getSubmissionFeatureCounts(os, dccId);
if (features != null) {
for (String type: features.keySet()) {
addMetaData(subProps, subId, type);
}
}
// add database repository types
for (String db : exp.getReposited().keySet()) {
addMetaData(subProps, subId, db);
}
}
}
return subProps;
}
public static Map<Integer, Integer> getSubMap() {
return submissionMap;
}
private static void addMetaData(Map<Integer, Set<String>> subProps, Integer objectId, String property) {
Set<String> props = subProps.get(objectId);
if (props == null) {
props = new HashSet<String>();
subProps.put(objectId, props);
}
props.add(property);
}
private static void addToDocument(Document doc, Integer objectId, String property) {
addToDocument(doc, objectId, property, 1.0F);
}
private static void addToDocument(Document doc, Integer objectId, String property, float boost) {
Field f = new Field("content", property, Field.Store.NO,
Field.Index.TOKENIZED);
f.setBoost(boost);
doc.add(f);
}
private static void indexMetadata(Map<Integer, Set<String>> subProps) {
long time = System.currentTimeMillis();
LOG.info("Indexing metadata.");
ram = new RAMDirectory();
IndexWriter writer;
try {
SnowballAnalyzer snowballAnalyzer =
new SnowballAnalyzer("English", StopAnalyzer.ENGLISH_STOP_WORDS);
writer = new IndexWriter(ram, snowballAnalyzer, true);
} catch (IOException err) {
throw new RuntimeException("Failed to create lucene IndexWriter", err);
}
int indexed = 0;
for (Integer objectId : subProps.keySet()) {
Document doc = new Document();
doc.add(new Field("name", objectId.toString(), Field.Store.YES,
Field.Index.TOKENIZED));
StringBuffer contentBuffer = new StringBuffer();
for (String prop : subProps.get(objectId)) {
contentBuffer.append(' ').append(prop);
}
// normalise the text
String content = contentBuffer.toString().replaceAll("[^a-zA-Z0-9]", " ");
doc.add(new Field("content", content, Field.Store.NO,
Field.Index.TOKENIZED));
try {
writer.addDocument(doc);
indexed++;
} catch (IOException e) {
LOG.error("Failed to submission " + objectId
+ " to the index", e);
}
}
try {
writer.close();
} catch (IOException e) {
LOG.error("IOException while closing IndexWriter", e);
}
time = System.currentTimeMillis() - time;
LOG.info("Indexed " + indexed + " out of " + subProps.size() + " webSearchables in "
+ time + " milliseconds");
}
}
|
package com.hss01248.dialog;
import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Build;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import com.hss01248.dialog.config.ConfigBean;
import com.hss01248.dialog.config.DefaultConfig;
public class Tool {
/**
* badtoken,
* @param dialog
*/
public static void showDialog(final Dialog dialog, final ConfigBean bean) {
StyledDialog.getMainHandler().post(new Runnable() {
@Override
public void run() {
try {
dialog.show();
if (bean.alertDialog!= null){
setMdBtnStytle(bean);
}
}catch (Exception e){
e.printStackTrace();
}
}
});
}
/**
* show,buttonnull
* @param bean
*/
public static void setMdBtnStytle(ConfigBean bean){
Button btnPositive =
bean.alertDialog.getButton(DialogInterface.BUTTON_POSITIVE);
Button btnNegative =
bean.alertDialog.getButton(DialogInterface.BUTTON_NEGATIVE);
Button btnNatural =
bean.alertDialog.getButton(DialogInterface.BUTTON_NEUTRAL);
//todo null
if(btnPositive !=null){
if(TextUtils.isEmpty(bean.text1)){
btnPositive.setText(bean.text1);
}
if (bean.btn1Color > 0)
btnPositive.setTextColor(getColor(null,bean.btn1Color));
if(bean.btnTxtSize >0){
btnPositive.setTextSize(bean.btnTxtSize);
}
}
if(btnNegative !=null){
if(TextUtils.isEmpty(bean.text2)){
btnNegative.setText(bean.text2);
}
if (bean.btn2Color > 0 )
if(bean.btn2Color == DefaultConfig.iosBtnColor ){
btnNegative.setTextColor(getColor(null,R.color.text_gray));
}else {
btnNegative.setTextColor(getColor(null,bean.btn2Color));
}
if(bean.btnTxtSize >0){
btnNegative.setTextSize(bean.btnTxtSize);
}
}
if(btnNatural !=null){
if(TextUtils.isEmpty(bean.text3)){
btnNatural.setText(bean.text3);
}
if (bean.btn3Color > 0)
btnNatural.setTextColor(getColor(null,bean.btn3Color));
if(bean.btnTxtSize >0){
btnNatural.setTextSize(bean.btnTxtSize);
}
}
}
public static ConfigBean fixContext(ConfigBean bean){
if (bean.context instanceof Activity){
Activity activity1 = (Activity) bean.context;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
if (!activity1.isDestroyed()){
return bean;
}
}else {
return bean;
}
}
Activity activity = MyActyManager.getInstance().getCurrentActivity();
if(activity!=null){
bean.context = activity;
return bean;
}
if (bean.context == null){
bean.context = StyledDialog.context;
}
if (bean.context instanceof Activity){
Activity activity1 = (Activity) bean.context;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
if (activity1.isDestroyed()){
bean.context = StyledDialog.context;
}
}
}
return bean;
}
public static ConfigBean newCustomDialog(ConfigBean bean){
Dialog dialog = new Dialog(bean.context);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
bean.dialog = dialog;
return bean;
}
public static ConfigBean setCancelable(ConfigBean bean){
if (bean.alertDialog != null){
bean.alertDialog.setCancelable(bean.cancelable);
bean.alertDialog.setCanceledOnTouchOutside(bean.outsideTouchable);
}else if (bean.dialog != null){
bean.dialog.setCancelable(bean.cancelable);
bean.dialog.setCanceledOnTouchOutside(bean.outsideTouchable);
}
return bean;
}
public static Dialog buildDialog(Context context, boolean cancleable, boolean outsideTouchable) {
if (context instanceof Activity){//todo keycode
Activity activity = (Activity) context;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
if (activity.isDestroyed()){
context = StyledDialog.context;
}
}
}
Dialog dialog = new Dialog(context);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setCancelable(cancleable);
dialog.setCanceledOnTouchOutside(outsideTouchable);
return dialog;
}
public static void setDialogStyle(ConfigBean bean) {
if (bean.alertDialog!= null){
setMdBtnStytle(bean);
}else {
setDialogStyle(bean.context,bean.dialog,bean.viewHeight,bean);
}
}
public static void setDialogStyle(Context activity, Dialog dialog, int measuredHeight,ConfigBean bean ) {
if (dialog == null){
return;
}
Window window = dialog.getWindow();
//window.setWindowAnimations(R.style.dialog_center);
if(bean.type != DefaultConfig.TYPE_PROGRESS){
window.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));//todo keycode to show round corner
}
WindowManager.LayoutParams wl = window.getAttributes();
/* wl.x = 0;
wl.y = getWindowManager().getDefaultDisplay().getHeight();*/
int width = window.getWindowManager().getDefaultDisplay().getWidth();
int height = window.getWindowManager().getDefaultDisplay().getHeight();
float ratio = 0.8f;
if(width > height){
ratio = 0.5f;
}
if (isCustomType(bean)){
wl.width = (int) (width * ratio); // todo keycode to keep gap
}else {
wl.width = ViewGroup.LayoutParams.WRAP_CONTENT;
}
wl.height = ViewGroup.LayoutParams.WRAP_CONTENT; //TODO wrapcontent,height*0.9
if (measuredHeight > height* 0.9){
wl.height = (int) (height* 0.9);
}
//wl.horizontalMargin= 0.2f;
// wl.gravity = Gravity.CENTER_HORIZONTAL;
if (activity instanceof Activity){
/* Activity activity1 = (Activity) activity;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
if (activity1.isDestroyed()){
activity = StyledDialog.context;
}
}*/
}else {
wl.type = WindowManager.LayoutParams.TYPE_TOAST;
//todo keycode to improve window level,,
//todo ,,
// wl.flags =
}
dialog.onWindowAttributesChanged(wl);
}
private static boolean isCustomType(ConfigBean bean) {
switch (bean.type){
case DefaultConfig.TYPE_IOS_HORIZONTAL:
case DefaultConfig.TYPE_IOS_VERTICAL:
case DefaultConfig.TYPE_IOS_BOTTOM:
case DefaultConfig.TYPE_IOS_CENTER_LIST:
case DefaultConfig.TYPE_IOS_INPUT:
case DefaultConfig.TYPE_CUSTOM_VIEW:
case DefaultConfig.TYPE_MD_LOADING:
return true;
default:
return false;
}
}
public static void measureView(View child) {
ViewGroup.LayoutParams p = child.getLayoutParams();
if (p == null) {
p = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT
,
ViewGroup.LayoutParams.WRAP_CONTENT);
}
int lpHeight = p.height;
int lpWidth = p.width;
int childHeightSpec;
int childWidthSpec;
if (lpHeight > 0) { //Height
childHeightSpec = View.MeasureSpec.makeMeasureSpec(lpHeight,
View.MeasureSpec.EXACTLY);
} else { // modesize0
childHeightSpec = View.MeasureSpec.makeMeasureSpec(0,
View.MeasureSpec.UNSPECIFIED);
}
if (lpWidth > 0) {
childWidthSpec= View.MeasureSpec.makeMeasureSpec(lpHeight,
View.MeasureSpec.EXACTLY);
} else {
childWidthSpec= View.MeasureSpec.makeMeasureSpec(0,
View.MeasureSpec.UNSPECIFIED);
}
child.measure(childWidthSpec, childHeightSpec);
}
/**
*
* @param root
* @param id height0,weight1scrollviewviewid,,0
* @return
*/
public static int mesureHeight(View root, int id) {
measureView(root);
int height = root.getMeasuredHeight();
int heightExtra = 0;
if (id > 0){
View view = root.findViewById(id);
if (view != null){
measureView(view);
heightExtra = view.getMeasuredHeight();
}
}
return height + heightExtra;
}
public static int mesureHeight(View root, View... subViews) {
measureView(root);
int height = root.getMeasuredHeight();
int heightExtra = 0;
if (subViews != null && subViews.length>0){
for (View view : subViews){
if(view.getVisibility() == View.VISIBLE){//goneview
measureView(view);
heightExtra += view.getMeasuredHeight();
}
}
}
return height + heightExtra;
}
public static int getColor(Context context,int colorRes){
if (context ==null){
context = StyledDialog.context;
}
return context.getResources().getColor(colorRes);
}
public static void setCancelListener(final ConfigBean bean) {
if(bean.dialog!=null){
bean.dialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
@Override
public void onCancel(DialogInterface dialog) {
if(bean.listener!=null) {
bean.listener.onCancle();
}
if (bean.dialog == StyledDialog.getLoadingDialog()) {
StyledDialog.setLoadingObj(null);
}
}
});
}
if(bean.alertDialog!=null){
bean.alertDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
@Override
public void onCancel(DialogInterface dialog) {
if (bean.listener != null) {
bean.listener.onCancle();
}
if (bean.alertDialog == StyledDialog.getLoadingDialog()) {
StyledDialog.setLoadingObj(null);
}
}
});
}
}
}
|
package jolie.doc;
import java.io.IOException;
import java.net.URI;
import jolie.CommandLineException;
import jolie.CommandLineParser;
import jolie.doc.impl.html.HtmlDocumentCreator;
import jolie.lang.parse.ParserException;
import jolie.lang.parse.ast.Program;
import jolie.lang.parse.util.ParsingUtils;
import jolie.lang.parse.util.ProgramInspector;
public class JolieDoc
{
public static void main( String[] args )
{
try {
CommandLineParser cmdParser = new CommandLineParser( args, JolieDoc.class.getClassLoader() );
args = cmdParser.arguments();
Program program = ParsingUtils.parseProgram(
cmdParser.programStream(),
URI.create( "file:" + cmdParser.programFilepath() ),
cmdParser.includePaths(), JolieDoc.class.getClassLoader(), cmdParser.definedConstants() );
ProgramInspector inspector=ParsingUtils.createInspector( program );
HtmlDocumentCreator document = new HtmlDocumentCreator( inspector, program.context().source() );
document.ConvertDocument();
/*
HTMLDocumentCreator document = new HTMLDocumentCreator();
document.createDocument( program, cmdParser.programFilepath() );*/
} catch( CommandLineException e ) {
System.out.println( e.getMessage() );
System.out.println( "Syntax is: jolieDoc [jolie options] <jolie filename> <output filename> [interface name list]" );
} catch( IOException e ) {
e.printStackTrace();
} catch( ParserException e ) {
System.out.println( e.getMessage() );
/*} catch( DocumentCreationException e ) {
e.printStackTrace();*/
}
}
}
|
package org.intermine.dataloader;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import java.util.TreeSet;
import java.lang.reflect.Constructor;
import org.intermine.metadata.CollectionDescriptor;
import org.intermine.metadata.FieldDescriptor;
import org.intermine.metadata.Model;
import org.intermine.model.FastPathObject;
import org.intermine.model.InterMineObject;
import org.intermine.objectstore.ObjectStore;
import org.intermine.objectstore.ObjectStoreWriter;
import org.intermine.objectstore.ObjectStoreWriterFactory;
import org.intermine.objectstore.ObjectStoreException;
import org.intermine.objectstore.intermine.ObjectStoreWriterInterMineImpl;
import org.intermine.objectstore.proxy.ProxyReference;
import org.intermine.sql.Database;
import org.intermine.util.DynamicUtil;
import org.intermine.util.IntPresentSet;
import org.intermine.util.StringUtil;
import org.intermine.util.TypeUtil;
import org.apache.log4j.Logger;
/**
* Priority-based implementation of IntegrationWriter. Allows field values to be chosen according
* to the relative priorities of the data sources that originated them.
*
* @author Matthew Wakeling
* @author Andrew Varley
*/
public class IntegrationWriterDataTrackingImpl extends IntegrationWriterAbstractImpl
{
private static final Logger LOG = Logger.getLogger(IntegrationWriterDataTrackingImpl.class);
protected DataTracker dataTracker;
protected Set<Class> trackerMissingClasses;
protected IntPresentSet skeletons = new IntPresentSet();
/** This is a list of the objects that did not merge with anything from a previous data
* source */
protected IntPresentSet pureObjects = new IntPresentSet();
/** This is a list of the objects in the destination database that we have written to as a
* non-skeleton. This is so that we can notice if we write to a given object twice, given
* ignoreDuplicates, so we can tell the user if ignoreDuplicates is necessary.
*/
protected IntPresentSet writtenObjects = new IntPresentSet();
/** This is a list of the objects in the destination database that we have written to as a
* non-skeleton more than once.
*/
protected IntPresentSet duplicateObjects = new IntPresentSet();
protected boolean isDuplicates = false;
protected PriorityConfig priorityConfig;
/**
* Creates a new instance of this class, given the properties defining it.
*
* @param osAlias the alias of this objectstore
* @param props the Properties
* @return an instance of this class
* @throws ObjectStoreException sometimes
*/
public static IntegrationWriterDataTrackingImpl getInstance(String osAlias, Properties props)
throws ObjectStoreException {
return getInstance(osAlias, props, IntegrationWriterDataTrackingImpl.class,
DataTracker.class);
}
/**
* Creates a new IntegrationWriter instance of the specified class and and with a specificed
* DataTracker class plus properties.
*
* @param osAlias the alias of this objectstore
* @param props the Properties
* @param iwClass Class of IntegrationWriter to create - IntegrationWriterDatatrackingImpl
* or a subclass.
* @param trackerClass Class of DataTracker to use with IntegrationWriter
* @return an instance of this class
* @throws ObjectStoreException sometimes
*/
protected static IntegrationWriterDataTrackingImpl getInstance(String osAlias, Properties props,
Class iwClass, Class trackerClass)
throws ObjectStoreException {
String writerAlias = props.getProperty("osw");
if (writerAlias == null) {
throw new ObjectStoreException(props.getProperty("alias") + " does not have an osw"
+ " alias specified (check properties file)");
}
String trackerMaxSizeString = props.getProperty("datatrackerMaxSize");
String trackerCommitSizeString = props.getProperty("datatrackerCommitSize");
if (trackerMaxSizeString == null) {
throw new ObjectStoreException(props.getProperty("alias") + " does not have a"
+ " datatracker maximum size specified (check properties file)");
}
if (trackerCommitSizeString == null) {
throw new ObjectStoreException(props.getProperty("alias") + " does not have a"
+ " datatracker commit size specified (check properties file)");
}
String trackerMissingClassesString = props.getProperty("datatrackerMissingClasses");
ObjectStoreWriter writer = ObjectStoreWriterFactory.getObjectStoreWriter(writerAlias);
try {
int maxSize = Integer.parseInt(trackerMaxSizeString);
int commitSize = Integer.parseInt(trackerCommitSizeString);
Database db = ((ObjectStoreWriterInterMineImpl) writer).getDatabase();
Set<Class> trackerMissingClasses = new HashSet();
if (trackerMissingClassesString != null) {
String trackerMissingClassesStrings[] = StringUtil.split(
trackerMissingClassesString, ",");
for (String trackerMissingClassString : trackerMissingClassesStrings) {
Class c = Class.forName(writer.getModel().getPackageName() + "."
+ trackerMissingClassString.trim());
trackerMissingClasses.add(c);
}
}
Constructor con = trackerClass.getConstructor(new Class[]
{Database.class, Integer.TYPE, Integer.TYPE});
DataTracker newDataTracker = (DataTracker) con.newInstance(new Object[]
{db, new Integer(maxSize), new Integer(commitSize)});
con = iwClass.getConstructor(new Class[] {ObjectStoreWriter.class, DataTracker.class,
Set.class});
return (IntegrationWriterDataTrackingImpl) con.newInstance(new Object[]
{writer, newDataTracker, trackerMissingClasses});
} catch (Exception e) {
IllegalArgumentException e2 = new IllegalArgumentException("Problem instantiating"
+ " IntegrationWriterDataTrackingImpl " + props.getProperty("alias"));
e2.initCause(e);
throw e2;
}
}
/**
* Constructs a new instance of IntegrationWriterDataTrackingImpl.
*
* @param osw an instance of an ObjectStoreWriter, which we can use to access the database
* @param dataTracker an instance of DataTracker, which we can use to store data tracking
* information
*/
public IntegrationWriterDataTrackingImpl(ObjectStoreWriter osw, DataTracker dataTracker) {
super(osw);
this.dataTracker = dataTracker;
this.trackerMissingClasses = Collections.emptySet();
}
/**
* Constructs a new instance of IntegrationWriterDataTrackingImpl.
*
* @param osw an instance of an ObjectStoreWriter, which we can use to access the database
* @param dataTracker an instance of DataTracker, which we can use to store data tracking
* information
* @param trackerMissingClasses a Set of classes for which DataTracker data is useless
*/
public IntegrationWriterDataTrackingImpl(ObjectStoreWriter osw, DataTracker dataTracker,
Set<Class> trackerMissingClasses) {
super(osw);
this.dataTracker = dataTracker;
this.trackerMissingClasses = trackerMissingClasses;
}
/**
* Resets the IntegrationWriter, clearing the id map and the hints
*/
public void reset() {
super.reset();
skeletons = new IntPresentSet();
pureObjects = new IntPresentSet();
writtenObjects = new IntPresentSet();
duplicateObjects = new IntPresentSet();
isDuplicates = false;
}
/**
* {@inheritDoc}
*/
public Source getMainSource(String name, String type) {
return dataTracker.stringToSource(name, type);
}
/**
* {@inheritDoc}
*/
public Source getSkeletonSource(String name, String type) {
return dataTracker.stringToSource("skel_" + name, type);
}
/**
* Returns the data tracker being used.
*
* @return dataTracker
*/
protected DataTracker getDataTracker() {
return dataTracker;
}
/**
* Returns true if the given class is NOT a subclass of any of the classes in
* trackerMissingClasses.
*
* @param c a Class
* @return a boolean
*/
public boolean doTrackerFor(Class c) {
for (Class missing : trackerMissingClasses) {
if (missing.isAssignableFrom(c)) {
return false;
}
}
return true;
}
private long timeSpentEquiv = 0;
private long timeSpentCreate = 0;
private long timeSpentPriorities = 0;
private long timeSpentCopyFields = 0;
private long timeSpentStore = 0;
private long timeSpentDataTrackerWrite = 0;
/**
* {@inheritDoc}
*/
protected InterMineObject store(FastPathObject nimo, Source source, Source skelSource,
int type) throws ObjectStoreException {
if (nimo == null) {
return null;
}
try {
if (!(nimo instanceof InterMineObject)) {
long time1 = System.currentTimeMillis();
FastPathObject newObj = DynamicUtil.createObject(nimo.getClass());
long time2 = System.currentTimeMillis();
timeSpentCreate += time2 - time1;
Map<String, FieldDescriptor> fields = getModel().getFieldDescriptorsForClass(nimo
.getClass());
for (Map.Entry<String, FieldDescriptor> entry : fields.entrySet()) {
String fieldName = entry.getKey();
FieldDescriptor field = entry.getValue();
copyField(nimo, newObj, source, skelSource, field, type);
}
time1 = System.currentTimeMillis();
timeSpentCopyFields += time1 - time2;
store(newObj);
time2 = System.currentTimeMillis();
timeSpentStore += time2 - time1;
return null;
}
InterMineObject o = (InterMineObject) nimo;
long time1 = System.currentTimeMillis();
Set equivObjects = getEquivalentObjects(o, source);
long time2 = System.currentTimeMillis();
timeSpentEquiv += time2 - time1;
if ((type != FROM_DB) && ((equivObjects.size() == 0)
|| ((equivObjects.size() == 1)
&& (o.getId() != null)
&& (pureObjects.contains(o.getId()))
&& (type == SOURCE)))) {
// Take a shortcut!
InterMineObject newObj = (InterMineObject) DynamicUtil.createObject(o.getClass());
Integer newId;
if (equivObjects.size() == 0) {
newId = getSerial();
assignMapping(o.getId(), newId);
} else {
newId = ((InterMineObject) equivObjects.iterator().next()).getId();
}
newObj.setId(newId);
if (type == SOURCE) {
if (writtenObjects.contains(newId)) {
// There are duplicate objects
if (!ignoreDuplicates) {
// Yes, this *can* happen, if two items in the tgt-items-database have
// the same item.identifier.
throw new IllegalArgumentException("Duplicate objects exist. Storing "
+ "again to id " + newId + " object from source " + o);
}
duplicateObjects.add(newId);
isDuplicates = true;
} else {
writtenObjects.add(newId);
}
}
time1 = System.currentTimeMillis();
timeSpentCreate += time1 - time2;
Map<String, FieldDescriptor> fields = getModel().getFieldDescriptorsForClass(newObj
.getClass());
Map<String, Source> trackingMap = new HashMap();
for (Map.Entry<String, FieldDescriptor> entry : fields.entrySet()) {
String fieldName = entry.getKey();
FieldDescriptor field = entry.getValue();
copyField(o, newObj, source, skelSource, field, type);
if (!(field instanceof CollectionDescriptor)) {
trackingMap.put(fieldName, type == SOURCE ? source : skelSource);
}
}
time2 = System.currentTimeMillis();
timeSpentCopyFields += time2 - time1;
store(newObj);
time1 = System.currentTimeMillis();
timeSpentStore += time1 - time2;
if (doTrackerFor(newObj.getClass())) {
dataTracker.clearObj(newId);
for (Map.Entry<String, Source> entry : trackingMap.entrySet()) {
dataTracker.setSource(newObj.getId(), entry.getKey(), entry.getValue());
}
}
if (type == SKELETON) {
skeletons.add(newObj.getId());
} else if (skeletons.contains(newObj.getId().intValue())) {
skeletons.set(newObj.getId().intValue(), false);
}
time2 = System.currentTimeMillis();
if (o.getId() != null) {
pureObjects.add(o.getId());
}
timeSpentDataTrackerWrite += time2 - time1;
return newObj;
}
if ((equivObjects.size() >= 1) && (type == SKELETON)) {
InterMineObject onlyEquivalent = (InterMineObject) equivObjects.iterator().next();
return onlyEquivalent;
}
Set classes = new HashSet();
classes.addAll(DynamicUtil.decomposeClass(o.getClass()));
Iterator objIter = equivObjects.iterator();
while (objIter.hasNext()) {
InterMineObject obj = (InterMineObject) objIter.next();
if (obj instanceof ProxyReference) {
obj = ((ProxyReference) obj).getObject();
}
try {
classes.addAll(DynamicUtil.decomposeClass(obj.getClass()));
} catch (Exception e) {
LOG.error("Broken with: " + DynamicUtil.decomposeClass(o.getClass()));
throw new ObjectStoreException(e);
}
}
InterMineObject newObj = (InterMineObject) DynamicUtil.createObject(classes);
Integer newId = null;
// if multiple equivalent objects in database just use id of first one
Iterator equivalentIter = equivObjects.iterator();
if (equivalentIter.hasNext()) {
newId = ((InterMineObject) equivalentIter.next()).getId();
newObj.setId(newId);
} else {
newObj.setId(getSerial());
}
if (type == SOURCE) {
if (writtenObjects.contains(newObj.getId())) {
// There are duplicate objects
if (!ignoreDuplicates) {
throw new IllegalArgumentException("Duplicate objects exist. Storing "
+ "again to id " + newId + " object from source " + o);
}
duplicateObjects.add(newObj.getId());
isDuplicates = true;
} else {
writtenObjects.add(newObj.getId());
}
}
time1 = System.currentTimeMillis();
timeSpentCreate += time1 - time2;
Map trackingMap = new HashMap();
Map fieldToEquivalentObjects = new HashMap();
Model model = getModel();
Map fieldDescriptors = model.getFieldDescriptorsForClass(newObj.getClass());
Set modelFieldNames = fieldDescriptors.keySet();
Set typeUtilFieldNames = TypeUtil.getFieldInfos(newObj.getClass()).keySet();
if (!modelFieldNames.equals(typeUtilFieldNames)) {
throw new ObjectStoreException("Failed to store data not in the model");
}
if (priorityConfig == null) {
priorityConfig = new PriorityConfig(osw.getModel());
}
Iterator fieldIter = fieldDescriptors.entrySet().iterator();
while (fieldIter.hasNext()) {
FieldDescriptor field = (FieldDescriptor) ((Map.Entry) fieldIter.next()).getValue();
String fieldName = field.getName();
if (!"id".equals(fieldName)) {
Set sortedEquivalentObjects;
// always add to collections, resolve other clashes by priority
if (field instanceof CollectionDescriptor) {
sortedEquivalentObjects = new HashSet();
} else {
Comparator compare = new SourcePriorityComparator(dataTracker,
newObj.getClass(), field.getName(),
(type == SOURCE ? source : skelSource), o, dbIdsStored, this,
source, skelSource, priorityConfig);
sortedEquivalentObjects = new TreeSet(compare);
}
if (model.getFieldDescriptorsForClass(o.getClass()).containsKey(fieldName)) {
sortedEquivalentObjects.add(o);
}
objIter = equivObjects.iterator();
while (objIter.hasNext()) {
InterMineObject obj = (InterMineObject) objIter.next();
Source fieldSource = dataTracker.getSource(obj.getId(), fieldName);
if ((equivObjects.size() == 1) && (fieldSource != null)
&& (fieldSource.equals(source)
|| (fieldSource.equals(skelSource) && (type != SOURCE)))) {
if (type == SOURCE) {
if (obj instanceof ProxyReference) {
obj = ((ProxyReference) obj).getObject();
}
String errMessage;
if (dbIdsStored.contains(obj.getId())) {
errMessage = "There is already an equivalent "
+ "in the database from this source (" + source
+ ") from *this* run; new object from source: \"" + o
+ "\", object from database (earlier in this run): \""
+ obj + "\"; noticed problem while merging field \""
+ field.getName() + "\" originally read from source: "
+ fieldSource;
} else {
errMessage = "There is already an equivalent "
+ "in the database from this source (" + source
+ ") from a *previous* run; "
+ "object from source in this run: \""
+ o + "\", object from database: \"" + obj
+ "\"; noticed problem while merging field \""
+ field.getName() + "\" originally read from source: "
+ fieldSource;
}
if (!ignoreDuplicates) {
LOG.error(errMessage);
throw new IllegalArgumentException(errMessage);
}
}
//LOG.debug("store() finished simply for object " + oText);
return obj;
}
// materialise proxies before searching for this field
if (obj instanceof ProxyReference) {
ProxyReference newproxy = (ProxyReference) obj;
obj = ((ProxyReference) obj).getObject();
if (obj == null) {
LOG.error("obj is null o: " + o);
LOG.error("proxyId " + newproxy.getId());
LOG.error("proxy " + newproxy);
ObjectStore os = newproxy.getObjectStore();
os.invalidateObjectById(newproxy.getId());
obj = newproxy.getObject();
LOG.error("obj: " + obj);
}
}
try {
if (model.getFieldDescriptorsForClass(obj.getClass())
.containsKey(fieldName)) {
sortedEquivalentObjects.add(obj);
}
} catch (RuntimeException e) {
LOG.error("fieldName: " + fieldName + " o: " + o + " id: "
+ obj.getId() + " obj: " + obj + " obj.getClass(): "
+ obj.getClass() + " description: " + model.
getFieldDescriptorsForClass(obj.getClass()));
LOG.error("error " , e);
throw e;
}
}
fieldToEquivalentObjects.put(field, sortedEquivalentObjects);
}
}
time2 = System.currentTimeMillis();
timeSpentPriorities += time2 - time1;
if (type != FROM_DB) {
assignMapping(o.getId(), newObj.getId());
}
Iterator fieldToEquivIter = fieldToEquivalentObjects.entrySet().iterator();
while (fieldToEquivIter.hasNext()) {
Source lastSource = null;
Map.Entry fieldToEquivEntry = (Map.Entry) fieldToEquivIter.next();
FieldDescriptor field = (FieldDescriptor) fieldToEquivEntry.getKey();
Set sortedEquivalentObjects = (Set) fieldToEquivEntry.getValue();
String fieldName = field.getName();
objIter = sortedEquivalentObjects.iterator();
while (objIter.hasNext()) {
InterMineObject obj = (InterMineObject) objIter.next();
if (obj == o) {
copyField(obj, newObj, source, skelSource, field, type);
lastSource = (type == SOURCE ? source : skelSource);
} else {
if (!(field instanceof CollectionDescriptor)) {
lastSource = dataTracker.getSource(obj.getId(), fieldName);
}
if (field instanceof CollectionDescriptor || lastSource != null) {
copyField(obj, newObj, lastSource, lastSource, field, FROM_DB);
}
}
}
if (!(field instanceof CollectionDescriptor)) {
if (lastSource == null) {
throw new NullPointerException("Error: lastSource is null for"
+ " object " + o.getId() + " and fieldName " + fieldName);
}
trackingMap.put(fieldName, lastSource);
}
}
time1 = System.currentTimeMillis();
timeSpentCopyFields += time1 - time2;
store(newObj);
time2 = System.currentTimeMillis();
timeSpentStore += time2 - time1;
if (doTrackerFor(newObj.getClass())) {
// We have called store() on an object, and we are about to write all of its data
// tracking data. We should tell the data tracker, ONLY IF THE ID OF THE OBJECT IS
// NEW, so that the data tracker can cache the writes without having to ask the db
// if records for that objectid already exist - we know there aren't.
if (newId == null) {
dataTracker.clearObj(newObj.getId());
}
Iterator trackIter = trackingMap.entrySet().iterator();
while (trackIter.hasNext()) {
Map.Entry trackEntry = (Map.Entry) trackIter.next();
String fieldName = (String) trackEntry.getKey();
Source lastSource = (Source) trackEntry.getValue();
dataTracker.setSource(newObj.getId(), fieldName, lastSource);
}
}
while (equivalentIter.hasNext()) {
InterMineObject objToDelete = (InterMineObject) equivalentIter.next();
delete(objToDelete);
}
// keep track of skeletons that are stored and remove when replaced by real object
if (type == SKELETON) {
skeletons.add(newObj.getId());
} else {
if (skeletons.contains(newObj.getId().intValue())) {
skeletons.set(newObj.getId().intValue(), false);
}
}
time1 = System.currentTimeMillis();
timeSpentDataTrackerWrite += time1 - time2;
return newObj;
} catch (RuntimeException e) {
if (idMap.size() <= 100000) {
LOG.error("IDMAP contents: " + idMap.toString());
}
if (skeletons.size() <= 100000) {
LOG.error("Skeletons: " + skeletons.toString());
}
if (pureObjects.size() <= 100000) {
LOG.error("pureObjects: " + pureObjects.toString());
}
throw new RuntimeException("Exception while loading object " + nimo, e);
} catch (ObjectStoreException e) {
if (idMap.size() <= 100000) {
LOG.error("IDMAP contents: " + idMap.toString());
}
if (skeletons.size() <= 100000) {
LOG.error("Skeletons: " + skeletons.toString());
}
if (pureObjects.size() <= 100000) {
LOG.error("pureObjects: " + pureObjects.toString());
}
throw new ObjectStoreException("Exception while loading object " + nimo, e);
} catch (IllegalAccessException e) {
throw new ObjectStoreException(e);
}
}
/**
* {@inheritDoc}
public void commitTransaction() throws ObjectStoreException {
osw.commitTransaction();
dataTracker.flush();
}
*/
/**
* {@inheritDoc}
*/
public void close() throws ObjectStoreException {
super.close();
dataTracker.close();
// There is a bug somewhere in this code that sometimes allows skeletons to
// be stored without matching up with the real object object. The problem
// seems to be erratic, some runs complete without a problem. Here we
// throw an exception if any skeletons have been stored but never replace
// by a real object to give early warning.
if (!(skeletons.size() == 0)) {
if (skeletons.size() <= 100000) {
LOG.info("Some skeletons were not replaced by real objects: "
+ skeletons.toString());
} else {
LOG.info(skeletons.size() + " skeletons were not replaced by real objects"
+ " - too many to log.");
}
if (idMap.size() <= 100000) {
LOG.info("IDMAP CONTENTS:" + idMap.toString());
}
throw new ObjectStoreException("Some skeletons where not replaced by real "
+ "objects: " + skeletons.size());
}
LOG.info("Time spent: Equivalent object queries: " + timeSpentEquiv + ", Create object: "
+ timeSpentCreate + ", Compute priorities: " + timeSpentPriorities
+ ", Copy fields: " + timeSpentCopyFields + ", Store object: " + timeSpentStore
+ ", Data tracker write: " + timeSpentDataTrackerWrite + ", recursing: "
+ timeSpentRecursing);
if (isDuplicates) {
LOG.info("There were duplicate objects, with destination IDs " + duplicateObjects);
} else {
LOG.info("There were no duplicate objects");
}
}
}
|
package com.jme3.gde.core.sceneexplorer.nodes.properties;
import com.jme3.math.Quaternion;
import java.awt.Component;
import java.awt.Graphics;
import java.awt.Rectangle;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.beans.PropertyEditor;
import java.util.Iterator;
import java.util.LinkedList;
/**
*
* @author normenhansen
*/
public class QuaternionPropertyEditor implements PropertyEditor {
private LinkedList<PropertyChangeListener> listeners = new LinkedList<PropertyChangeListener>();
private Quaternion quaternion = new Quaternion();
public void setValue(Object value) {
if (value instanceof Quaternion) {
quaternion.set((Quaternion) value);
}
}
public Object getValue() {
return quaternion;
}
public boolean isPaintable() {
return false;
}
public void paintValue(Graphics gfx, Rectangle box) {
throw new UnsupportedOperationException("Not supported yet.");
}
public String getJavaInitializationString() {
return null;
}
public String getAsText() {
float[] angles=quaternion.toAngles(new float[3]);
return "[" + (float)Math.toDegrees(angles[0]) + ", " + (float)Math.toDegrees(angles[1]) + ", " + (float)Math.toDegrees(angles[2]) + "]";
}
public void setAsText(String text) throws IllegalArgumentException {
text = text.replace('[', ' ');
text = text.replace(']', ' ');
String[] values = text.split(",");
if (values.length != 3) {
throw (new IllegalArgumentException("String not correct"));
}
float[] floats = new float[3];
for (int i = 0; i < values.length; i++) {
String string = values[i];
floats[i] = (float)Math.toRadians(Float.parseFloat(string));
}
Quaternion old=new Quaternion();
old.set(quaternion);
quaternion.fromAngles(floats);
notifyListeners(old,quaternion);
}
public String[] getTags() {
return null;
}
public Component getCustomEditor() {
throw new UnsupportedOperationException("Not supported yet.");
}
public boolean supportsCustomEditor() {
return false;
}
public void addPropertyChangeListener(PropertyChangeListener listener) {
listeners.add(listener);
}
public void removePropertyChangeListener(PropertyChangeListener listener) {
listeners.remove(listener);
}
private void notifyListeners(Quaternion before, Quaternion after) {
for (Iterator<PropertyChangeListener> it = listeners.iterator(); it.hasNext();) {
PropertyChangeListener propertyChangeListener = it.next();
//TODO: check what the "programmatic name" is supposed to be here.. for now its Quaternion
propertyChangeListener.propertyChange(new PropertyChangeEvent(this, null, before, after));
}
}
}
|
package org.kindlyops.providers.rest;
import org.keycloak.models.KeycloakSession;
import org.keycloak.models.RealmModel;
import org.keycloak.services.managers.AppAuthManager;
import org.keycloak.services.managers.AuthenticationManager;
import org.keycloak.authentication.actiontoken.idpverifyemail.IdpVerifyAccountLinkActionToken;
import org.keycloak.models.UserModel;
import org.keycloak.email.EmailException;
import javax.ws.rs.ForbiddenException;
import javax.ws.rs.NotAuthorizedException;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.GET;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Response;
import java.util.concurrent.TimeUnit;
import java.net.URI;
import org.kindlyops.providers.email.HavenEmailProvider;
import org.keycloak.theme.FreeMarkerUtil;
public class HavenRestResource {
private final KeycloakSession session;
private final AuthenticationManager.AuthResult auth;
public HavenRestResource(KeycloakSession session) {
this.session = session;
this.auth = new AppAuthManager().authenticateBearerToken(session, session.getContext().getRealm());
}
@GET
@Produces("text/plain; charset=utf-8")
public String get() {
String name = session.getContext().getRealm().getDisplayName();
if (name == null) {
name = session.getContext().getRealm().getName();
}
return "Hello " + name;
}
// REST endpoint is authenticated with
// Bearer token and user must be in realm role "admin"
@Path("organizations")
public OrganizationResource getOrganizationResource() {
checkRealmAdmin();
return new OrganizationResource(session);
}
@Path("funnel/verify-email")
@POST
public Response verifyEmail() {
checkRealmAdmin();
RealmModel realm = session.getContext().getRealm();
// TODO get email from API call
// https://github.com/keycloak/keycloak/blob/c41bcddd8db64eda84086ca370ecc2276b7f3d49/services/src/main/java/org/keycloak/services/resources/admin/UserResource.java#L656
String email = "user1@havengrc.com";
UserModel user = session.users().getUserByEmail(email, realm);
URI uri = session.getContext().getAuthServerUrl();
FreeMarkerUtil util = new FreeMarkerUtil();
HavenEmailProvider provider = new HavenEmailProvider(session, util);
int seconds = realm.getActionTokenGeneratedByUserLifespan(IdpVerifyAccountLinkActionToken.TOKEN_TYPE);
long expiration = TimeUnit.SECONDS.toMinutes(seconds);
try {
provider.setUser(user);
provider.setRealm(realm);
// TODO: build up proper link and required actions
// https://github.com/keycloak/keycloak/blob/c41bcddd8db64eda84086ca370ecc2276b7f3d49/services/src/main/java/org/keycloak/services/resources/admin/UserResource.java#L701
provider.sendFunnelVerifyEmail(uri.toString(), expiration);
} catch (EmailException e) {
return Response.serverError().build();
}
return Response.ok().build();
}
@Path("memberships")
public MembershipResource getMembershipResource() {
return new MembershipResource(session);
}
private void checkRealmAdmin() {
if (auth == null) {
throw new NotAuthorizedException("Bearer");
} else if (auth.getToken().getRealmAccess() == null
|| !auth.getToken().getRealmAccess().isUserInRole("admin")) {
throw new ForbiddenException("Does not have realm admin role");
}
}
}
|
package org.languagetool.tagging.de;
import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import morfologik.stemming.Dictionary;
import morfologik.stemming.DictionaryLookup;
import morfologik.stemming.IStemmer;
import morfologik.stemming.WordData;
import org.languagetool.AnalyzedToken;
import org.languagetool.AnalyzedTokenReadings;
import org.languagetool.JLanguageTool;
import org.languagetool.tagging.ManualTagger;
import org.languagetool.tagging.Tagger;
import org.languagetool.tokenizers.de.GermanCompoundTokenizer;
import org.languagetool.tools.StringTools;
public class GermanTagger implements Tagger {
private static final String DICT_FILENAME = "/de/german.dict";
private static final String USER_DICT_FILENAME = "/de/added.txt";
private Dictionary dictionary;
private ManualTagger manualTagger;
private GermanCompoundTokenizer compoundTokenizer;
public GermanTagger() {
}
protected void initialize() throws IOException {
final URL url = JLanguageTool.getDataBroker().getFromResourceDirAsUrl(DICT_FILENAME);
dictionary = Dictionary.read(url);
manualTagger = new ManualTagger(JLanguageTool.getDataBroker().getFromResourceDirAsStream(USER_DICT_FILENAME));
compoundTokenizer = new GermanCompoundTokenizer();
}
protected void initializeIfRequired() throws IOException {
// Lazy initialize all fields when needed and only once.
if (dictionary == null || manualTagger == null || compoundTokenizer == null) {
synchronized (this) {
if (dictionary == null || manualTagger == null || compoundTokenizer == null) {
initialize();
}
}
}
}
public AnalyzedGermanTokenReadings lookup(final String word) throws IOException {
final List<String> words = new ArrayList<>();
words.add(word);
final List<AnalyzedTokenReadings> result = tag(words, false);
final AnalyzedGermanTokenReadings atr = (AnalyzedGermanTokenReadings) result.get(0);
if (atr.getAnalyzedToken(0).getPOSTag() == null) {
return null;
}
return atr;
}
@Override
public List<AnalyzedTokenReadings> tag(final List<String> sentenceTokens) throws IOException {
return tag(sentenceTokens, true);
}
public List<AnalyzedTokenReadings> tag(final List<String> sentenceTokens, final boolean ignoreCase) throws IOException {
initializeIfRequired();
String[] taggerTokens;
boolean firstWord = true;
final List<AnalyzedTokenReadings> tokenReadings = new ArrayList<>();
int pos = 0;
final IStemmer morfologik = new DictionaryLookup(dictionary);
for (String word: sentenceTokens) {
final List<AnalyzedGermanToken> l = new ArrayList<>();
taggerTokens = lexiconLookup(word, morfologik);
if (firstWord && taggerTokens == null && ignoreCase) { // e.g. "Das" -> "das" at start of sentence
taggerTokens = lexiconLookup(word.toLowerCase(), morfologik);
firstWord = false;
}
if (taggerTokens != null) {
tagWord(taggerTokens, word, l);
} else {
// word not known, try to decompose it and use the last part for POS tagging:
if (!StringTools.isEmpty(word.trim())) {
final List<String> compoundParts = compoundTokenizer.tokenize(word);
if (compoundParts.size() <= 1) {
l.add(new AnalyzedGermanToken(word, null, null));
} else {
// last part governs a word's POS:
String lastPart = compoundParts.get(compoundParts.size()-1);
if (StringTools.startsWithUppercase(word)) {
lastPart = StringTools.uppercaseFirstChar(lastPart);
}
taggerTokens = lexiconLookup(lastPart, morfologik);
if (taggerTokens != null) {
tagWord(taggerTokens, word, l, compoundParts);
} else {
l.add(new AnalyzedGermanToken(word, null, null));
}
}
} else {
l.add(new AnalyzedGermanToken(word, null, null));
}
}
//tokenReadings.add(new AnalyzedGermanToken(new AnalyzedTokenReadings((AnalyzedToken[]) l.toArray(new AnalyzedToken[0]))));
tokenReadings.add(new AnalyzedGermanTokenReadings(l.toArray(new AnalyzedGermanToken[l.size()]), pos));
pos += word.length();
}
return tokenReadings;
}
private void tagWord(String[] taggerTokens, String word, List<AnalyzedGermanToken> l) {
tagWord(taggerTokens, word, l, null);
}
/**
* @param compoundParts all compound parts of the complete word or <code>null</code>,
* if the original input is not a compound
*/
private void tagWord(String[] taggerTokens, String word, List<AnalyzedGermanToken> l,
List<String> compoundParts) {
int i = 0;
while (i < taggerTokens.length) {
// Lametyzator returns data as String[]
// first lemma, then annotations
if (compoundParts != null) {
// was originally a compound word
final List<String> allButLastPart = compoundParts.subList(0, compoundParts.size() - 1);
final String lemma = StringTools.listToString(allButLastPart, "")
+ StringTools.lowercaseFirstChar(taggerTokens[i]);
l.add(new AnalyzedGermanToken(word, taggerTokens[i + 1], lemma));
} else {
l.add(new AnalyzedGermanToken(word, taggerTokens[i + 1], taggerTokens[i]));
}
i = i + 2;
}
}
private String[] lexiconLookup(final String word, final IStemmer morfologik) {
try {
final String[] posTagsFromUserDict = manualTagger.lookup(word);
final List<WordData> posTagsFromDict = morfologik.lookup(word);
if (posTagsFromUserDict != null && !posTagsFromDict.isEmpty()) {
final String[] allPosTags = new String[posTagsFromUserDict.length + posTagsFromDict.size() * 2];
//System.arraycopy(posTagsFromDict, 0, allPosTags, 0, posTagsFromDict.size());
int i = 0;
for (WordData wd : posTagsFromDict) {
allPosTags[i] = wd.getStem().toString();
allPosTags[i + 1] = wd.getTag().toString();
i = i + 2;
}
System.arraycopy(posTagsFromUserDict, 0, allPosTags, posTagsFromDict.size() * 2, posTagsFromUserDict.length);
return allPosTags;
} else if (posTagsFromUserDict == null && !posTagsFromDict.isEmpty()) {
final String[] allPosTags = new String[posTagsFromDict.size() * 2];
int i = 0;
for (WordData wd : posTagsFromDict) {
allPosTags[i] = wd.getStem().toString();
allPosTags[i + 1] = wd.getTag().toString();
i = i + 2;
}
return allPosTags;
} else {
return posTagsFromUserDict;
}
} catch (Exception e) {
throw new RuntimeException("Error looking up word '" + word + "'", e);
}
}
@Override
public final AnalyzedGermanTokenReadings createNullToken(final String token, final int startPos) {
return new AnalyzedGermanTokenReadings(new AnalyzedGermanToken(token, null, null), startPos);
}
@Override
public AnalyzedToken createToken(String token, String posTag) {
return new AnalyzedGermanToken(token, posTag);
}
/**
* Test only
*/
public static void main(final String[] args) throws IOException {
final GermanTagger gt = new GermanTagger();
final List<String> l = new ArrayList<>();
l.add("Einfacher");
//System.err.println(gt.lookup("Treffen", 0));
final List<AnalyzedTokenReadings> res = gt.tag(l);
System.err.println(res);
}
}
|
package java.security;
import java.util.Random;
import org.bouncycastle.crypto.digests.SHA1Digest;
import org.bouncycastle.crypto.digests.SHA256Digest;
import org.bouncycastle.crypto.prng.RandomGenerator;
import org.bouncycastle.crypto.prng.DigestRandomGenerator;
/**
* An implementation of SecureRandom specifically for the light-weight API, JDK
* 1.0, and the J2ME. Random generation is based on the traditional SHA1 with
* counter. Calling setSeed will always increase the entropy of the hash.
*/
public class SecureRandom extends java.util.Random
{
private static SecureRandom rand = new SecureRandom(new DigestRandomGenerator(new SHA1Digest()));
protected RandomGenerator generator;
// public constructors
public SecureRandom()
{
super(0);
this.generator = new DigestRandomGenerator(new SHA1Digest());
setSeed(System.currentTimeMillis());
}
public SecureRandom(byte[] inSeed)
{
super(0);
this.generator = new DigestRandomGenerator(new SHA1Digest());
setSeed(inSeed);
}
protected SecureRandom(
RandomGenerator generator)
{
super(0);
this.generator = generator;
}
// protected constructors
// protected SecureRandom(SecureRandomSpi srs, Provider provider);
// public class methods
public static SecureRandom getInstance(String algorithm)
{
if (algorithm.equals("SHA1PRNG"))
{
return new SecureRandom(new DigestRandomGenerator(new SHA1Digest()));
}
if (algorithm.equals("SHA256PRNG"))
{
return new SecureRandom(new DigestRandomGenerator(new SHA256Digest()));
}
return new SecureRandom(); // follow old behaviour
}
public static SecureRandom getInstance(String algorithm, String provider)
{
return getInstance(algorithm);
}
public static byte[] getSeed(int numBytes)
{
byte[] rv = new byte[numBytes];
rand.setSeed(System.currentTimeMillis());
rand.nextBytes(rv);
return rv;
}
// public instance methods
public byte[] generateSeed(int numBytes)
{
byte[] rv = new byte[numBytes];
nextBytes(rv);
return rv;
}
// public final Provider getProvider();
public void setSeed(byte[] inSeed)
{
generator.addSeedMaterial(inSeed);
}
// public methods overriding random
public void nextBytes(byte[] bytes)
{
generator.nextBytes(bytes);
}
public void setSeed(long rSeed)
{
if (rSeed != 0) // to avoid problems with Random calling setSeed in construction
{
generator.addSeedMaterial(rSeed);
}
}
public int nextInt()
{
byte[] intBytes = new byte[4];
nextBytes(intBytes);
int result = 0;
for (int i = 0; i < 4; i++)
{
result = (result << 8) + (intBytes[i] & 0xff);
}
return result;
}
protected final int next(int numBits)
{
int size = (numBits + 7) / 8;
byte[] bytes = new byte[size];
nextBytes(bytes);
int result = 0;
for (int i = 0; i < size; i++)
{
result = (result << 8) + (bytes[i] & 0xff);
}
return result & ((1 << numBits) - 1);
}
}
|
package cgeo.geocaching;
import butterknife.InjectView;
import butterknife.Views;
import cgeo.geocaching.activity.AbstractActivity;
import cgeo.geocaching.activity.AbstractViewPagerActivity;
import cgeo.geocaching.connector.gc.GCParser;
import cgeo.geocaching.enumerations.LogType;
import cgeo.geocaching.geopoint.Units;
import cgeo.geocaching.network.HtmlImage;
import cgeo.geocaching.network.Network;
import cgeo.geocaching.ui.AbstractCachingPageViewCreator;
import cgeo.geocaching.ui.AnchorAwareLinkMovementMethod;
import cgeo.geocaching.ui.CacheDetailsCreator;
import cgeo.geocaching.ui.Formatter;
import cgeo.geocaching.utils.BaseUtils;
import cgeo.geocaching.utils.HtmlUtils;
import cgeo.geocaching.utils.Log;
import cgeo.geocaching.utils.UnknownTagsHandler;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.tuple.ImmutablePair;
import org.apache.commons.lang3.tuple.Pair;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Html;
import android.view.ContextMenu;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
public class TrackableActivity extends AbstractViewPagerActivity<TrackableActivity.Page> {
public enum Page {
DETAILS(R.string.detail),
LOGS(R.string.cache_logs);
private final int resId;
Page(final int resId) {
this.resId = resId;
}
}
private Trackable trackable = null;
private String geocode = null;
private String name = null;
private String guid = null;
private String id = null;
private String contextMenuUser = null;
private LayoutInflater inflater = null;
private ProgressDialog waitDialog = null;
private Handler loadTrackableHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
if (trackable == null) {
if (waitDialog != null) {
waitDialog.dismiss();
}
if (StringUtils.isNotBlank(geocode)) {
showToast(res.getString(R.string.err_tb_find) + " " + geocode + ".");
} else {
showToast(res.getString(R.string.err_tb_find_that));
}
finish();
return;
}
try {
inflater = getLayoutInflater();
geocode = trackable.getGeocode();
if (StringUtils.isNotBlank(trackable.getName())) {
setTitle(Html.fromHtml(trackable.getName()).toString());
} else {
setTitle(trackable.getName());
}
invalidateOptionsMenuCompatible();
reinitializeViewPager();
} catch (Exception e) {
Log.e("TrackableActivity.loadTrackableHandler: ", e);
}
if (waitDialog != null) {
waitDialog.dismiss();
}
}
};
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState, R.layout.trackable_activity);
// set title in code, as the activity needs a hard coded title due to the intent filters
setTitle(res.getString(R.string.trackable));
// get parameters
Bundle extras = getIntent().getExtras();
Uri uri = getIntent().getData();
// try to get data from extras
if (extras != null) {
geocode = extras.getString(Intents.EXTRA_GEOCODE);
name = extras.getString(Intents.EXTRA_NAME);
guid = extras.getString(Intents.EXTRA_GUID);
id = extras.getString(Intents.EXTRA_ID);
}
// try to get data from URI
if (geocode == null && guid == null && id == null && uri != null) {
String uriHost = uri.getHost().toLowerCase(Locale.US);
if (uriHost.contains("geocaching.com")) {
geocode = uri.getQueryParameter("tracker");
guid = uri.getQueryParameter("guid");
id = uri.getQueryParameter("id");
if (StringUtils.isNotBlank(geocode)) {
geocode = geocode.toUpperCase(Locale.US);
guid = null;
id = null;
} else if (StringUtils.isNotBlank(guid)) {
geocode = null;
guid = guid.toLowerCase(Locale.US);
id = null;
} else if (StringUtils.isNotBlank(id)) {
geocode = null;
guid = null;
id = id.toLowerCase(Locale.US);
} else {
showToast(res.getString(R.string.err_tb_details_open));
finish();
return;
}
} else if (uriHost.contains("coord.info")) {
String uriPath = uri.getPath().toLowerCase(Locale.US);
if (uriPath != null && uriPath.startsWith("/tb")) {
geocode = uriPath.substring(1).toUpperCase(Locale.US);
guid = null;
id = null;
} else {
showToast(res.getString(R.string.err_tb_details_open));
finish();
return;
}
}
}
// no given data
if (geocode == null && guid == null && id == null) {
showToast(res.getString(R.string.err_tb_display));
finish();
return;
}
String message;
if (StringUtils.isNotBlank(name)) {
message = Html.fromHtml(name).toString();
} else if (StringUtils.isNotBlank(geocode)) {
message = geocode;
} else {
message = res.getString(R.string.trackable);
}
waitDialog = ProgressDialog.show(this, message, res.getString(R.string.trackable_details_loading), true, true);
createViewPager(0, null);
LoadTrackableThread thread = new LoadTrackableThread(loadTrackableHandler, geocode, guid, id);
thread.start();
}
@Override
public void onCreateContextMenu(ContextMenu menu, View view, ContextMenu.ContextMenuInfo info) {
super.onCreateContextMenu(menu, view, info);
final int viewId = view.getId();
if (viewId == R.id.author) { // Log item author
contextMenuUser = ((TextView) view).getText().toString();
} else { // Trackable owner, and user holding trackable now
RelativeLayout itemLayout = (RelativeLayout) view.getParent();
TextView itemName = (TextView) itemLayout.findViewById(R.id.name);
String selectedName = itemName.getText().toString();
if (selectedName.equals(res.getString(R.string.trackable_owner))) {
contextMenuUser = trackable.getOwner();
} else if (selectedName.equals(res.getString(R.string.trackable_spotted))) {
contextMenuUser = trackable.getSpottedName();
}
}
menu.setHeaderTitle(res.getString(R.string.user_menu_title) + " " + contextMenuUser);
menu.add(viewId, 1, 0, res.getString(R.string.user_menu_view_hidden));
menu.add(viewId, 2, 0, res.getString(R.string.user_menu_view_found));
menu.add(viewId, 3, 0, res.getString(R.string.user_menu_open_browser));
menu.add(viewId, 4, 0, res.getString(R.string.user_menu_send_message));
}
@Override
public boolean onContextItemSelected(final MenuItem item) {
switch (item.getItemId()) {
case 1:
cgeocaches.startActivityOwner(this, contextMenuUser);
return true;
case 2:
cgeocaches.startActivityUserName(this, contextMenuUser);
return true;
case 3:
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("http:
return true;
case 4:
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("http:
return true;
default:
return false;
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.trackable_activity, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_log_touch:
LogTrackableActivity.startActivity(this, trackable);
return true;
case R.id.menu_browser_trackable:
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(trackable.getUrl())));
return true;
default:
return false;
}
}
@Override
public boolean onPrepareOptionsMenu(Menu menu) {
if (trackable != null) {
menu.findItem(R.id.menu_log_touch).setEnabled(StringUtils.isNotBlank(geocode) && trackable.isLoggable());
menu.findItem(R.id.menu_browser_trackable).setEnabled(StringUtils.isNotBlank(trackable.getUrl()));
}
return super.onPrepareOptionsMenu(menu);
}
private class LoadTrackableThread extends Thread {
final private Handler handler;
final private String geocode;
final private String guid;
final private String id;
public LoadTrackableThread(Handler handlerIn, String geocodeIn, String guidIn, String idIn) {
handler = handlerIn;
geocode = geocodeIn;
guid = guidIn;
id = idIn;
}
@Override
public void run() {
trackable = cgData.loadTrackable(geocode);
if ((trackable == null || trackable.isLoggable()) && !StringUtils.startsWithIgnoreCase(geocode, "GK")) {
trackable = GCParser.searchTrackable(geocode, guid, id);
}
handler.sendMessage(Message.obtain());
}
}
private class UserActionsListener implements View.OnClickListener {
@Override
public void onClick(View view) {
if (view == null) {
return;
}
try {
registerForContextMenu(view);
openContextMenu(view);
} catch (Exception e) {
Log.e("TrackableActivity.UserActionsListener.onClick ", e);
}
}
}
private class TrackableIconThread extends Thread {
final private String url;
final private Handler handler;
public TrackableIconThread(String urlIn, Handler handlerIn) {
url = urlIn;
handler = handlerIn;
}
@Override
public void run() {
if (url == null || handler == null) {
return;
}
try {
HtmlImage imgGetter = new HtmlImage(trackable.getGeocode(), false, 0, false);
BitmapDrawable image = imgGetter.getDrawable(url);
Message message = handler.obtainMessage(0, image);
handler.sendMessage(message);
} catch (Exception e) {
Log.e("TrackableActivity.TrackableIconThread.run: ", e);
}
}
}
private static class TrackableIconHandler extends Handler {
final private TextView view;
public TrackableIconHandler(TextView viewIn) {
view = viewIn;
}
@Override
public void handleMessage(Message message) {
final BitmapDrawable image = (BitmapDrawable) message.obj;
if (image != null && view != null) {
image.setBounds(0, 0, view.getHeight(), view.getHeight());
view.setCompoundDrawables(image, null, null, null);
}
}
}
public static void startActivity(final AbstractActivity fromContext,
final String guid, final String geocode, final String name) {
final Intent trackableIntent = new Intent(fromContext, TrackableActivity.class);
trackableIntent.putExtra(Intents.EXTRA_GUID, guid);
trackableIntent.putExtra(Intents.EXTRA_GEOCODE, geocode);
trackableIntent.putExtra(Intents.EXTRA_NAME, name);
fromContext.startActivity(trackableIntent);
}
@Override
protected PageViewCreator createViewCreator(Page page) {
switch (page) {
case DETAILS:
return new DetailsViewCreator();
case LOGS:
return new LogsViewCreator();
default:
throw new IllegalArgumentException();
}
}
@Override
protected String getTitle(Page page) {
return res.getString(page.resId);
}
@Override
protected Pair<List<? extends Page>, Integer> getOrderedPages() {
List<Page> pages = new ArrayList<TrackableActivity.Page>();
pages.add(Page.DETAILS);
if (!trackable.getLogs().isEmpty()) {
pages.add(Page.LOGS);
}
return new ImmutablePair<List<? extends Page>, Integer>(pages, 0);
}
public class LogsViewCreator extends AbstractCachingPageViewCreator<ListView> {
@Override
public ListView getDispatchedView() {
view = (ListView) getLayoutInflater().inflate(R.layout.trackable_logs_view, null);
if (trackable != null && trackable.getLogs() != null) {
view.setAdapter(new ArrayAdapter<LogEntry>(TrackableActivity.this, R.layout.logs_item, trackable.getLogs()) {
@Override
public View getView(int position, View convertView, android.view.ViewGroup parent) {
View rowView = convertView;
if (null == rowView) {
rowView = getLayoutInflater().inflate(R.layout.logs_item, null);
}
LogViewHolder holder = (LogViewHolder) rowView.getTag();
if (null == holder) {
holder = new LogViewHolder(rowView);
}
final LogEntry log = getItem(position);
fillViewHolder(holder, log);
return rowView;
}
});
}
return view;
}
protected void fillViewHolder(LogViewHolder holder, final LogEntry log) {
if (log.date > 0) {
holder.date.setText(Formatter.formatShortDateVerbally(log.date));
}
holder.type.setText(log.type.getL10n());
holder.author.setText(Html.fromHtml(log.author), TextView.BufferType.SPANNABLE);
if (StringUtils.isBlank(log.cacheName)) {
holder.countOrLocation.setVisibility(View.GONE);
} else {
holder.countOrLocation.setText(Html.fromHtml(log.cacheName));
final String cacheGuid = log.cacheGuid;
final String cacheName = log.cacheName;
holder.countOrLocation.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
CacheDetailActivity.startActivityGuid(TrackableActivity.this, cacheGuid, Html.fromHtml(cacheName).toString());
}
});
}
TextView logView = holder.text;
logView.setMovementMethod(AnchorAwareLinkMovementMethod.getInstance());
String logText = log.log;
if (BaseUtils.containsHtml(logText)) {
logText = log.getDisplayText();
logView.setText(Html.fromHtml(logText, new HtmlImage(null, false, StoredList.TEMPORARY_LIST_ID, false), null), TextView.BufferType.SPANNABLE);
}
else {
logView.setText(logText);
}
ImageView statusMarker = holder.marker;
// colored marker
int marker = log.type.markerId;
if (marker != 0) {
statusMarker.setVisibility(View.VISIBLE);
statusMarker.setImageResource(marker);
}
else {
statusMarker.setVisibility(View.GONE);
}
// images
if (log.hasLogImages()) {
holder.images.setText(log.getImageTitles());
holder.images.setVisibility(View.VISIBLE);
holder.images.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
ImagesActivity.startActivityLogImages(TrackableActivity.this, trackable.getGeocode(), new ArrayList<Image>(log.getLogImages()));
}
});
} else {
holder.images.setVisibility(View.GONE);
}
holder.author.setOnClickListener(new UserActionsListener());
}
}
public class DetailsViewCreator extends AbstractCachingPageViewCreator<ScrollView> {
@InjectView(R.id.goal_box) protected LinearLayout goalBox;
@InjectView(R.id.goal) protected TextView goalTextView;
@InjectView(R.id.details_box) protected LinearLayout detailsBox;
@InjectView(R.id.details) protected TextView detailsTextView;
@InjectView(R.id.image_box) protected LinearLayout imageBox;
@InjectView(R.id.details_list) protected LinearLayout detailsList;
@InjectView(R.id.image) protected LinearLayout imageView;
@Override
public ScrollView getDispatchedView() {
view = (ScrollView) getLayoutInflater().inflate(R.layout.trackable_details_view, null);
Views.inject(this, view);
final CacheDetailsCreator details = new CacheDetailsCreator(TrackableActivity.this, detailsList);
// action bar icon
if (StringUtils.isNotBlank(trackable.getIconUrl())) {
final TrackableIconHandler iconHandler = new TrackableIconHandler(((TextView) findViewById(R.id.actionbar_title)));
final TrackableIconThread iconThread = new TrackableIconThread(trackable.getIconUrl(), iconHandler);
iconThread.start();
}
// trackable name
details.add(R.string.trackable_name, StringUtils.isNotBlank(trackable.getName()) ? Html.fromHtml(trackable.getName()).toString() : res.getString(R.string.trackable_unknown));
// trackable type
String tbType;
if (StringUtils.isNotBlank(trackable.getType())) {
tbType = Html.fromHtml(trackable.getType()).toString();
} else {
tbType = res.getString(R.string.trackable_unknown);
}
details.add(R.string.trackable_type, tbType);
// trackable geocode
details.add(R.string.trackable_code, trackable.getGeocode());
// trackable owner
TextView owner = details.add(R.string.trackable_owner, res.getString(R.string.trackable_unknown));
if (StringUtils.isNotBlank(trackable.getOwner())) {
owner.setText(Html.fromHtml(trackable.getOwner()), TextView.BufferType.SPANNABLE);
owner.setOnClickListener(new UserActionsListener());
}
// trackable spotted
if (StringUtils.isNotBlank(trackable.getSpottedName()) ||
trackable.getSpottedType() == Trackable.SPOTTED_UNKNOWN ||
trackable.getSpottedType() == Trackable.SPOTTED_OWNER) {
boolean showTimeSpan = true;
StringBuilder text;
if (trackable.getSpottedType() == Trackable.SPOTTED_CACHE) {
text = new StringBuilder(res.getString(R.string.trackable_spotted_in_cache) + ' ' + Html.fromHtml(trackable.getSpottedName()).toString());
} else if (trackable.getSpottedType() == Trackable.SPOTTED_USER) {
text = new StringBuilder(res.getString(R.string.trackable_spotted_at_user) + ' ' + Html.fromHtml(trackable.getSpottedName()).toString());
} else if (trackable.getSpottedType() == Trackable.SPOTTED_UNKNOWN) {
text = new StringBuilder(res.getString(R.string.trackable_spotted_unknown_location));
} else if (trackable.getSpottedType() == Trackable.SPOTTED_OWNER) {
text = new StringBuilder(res.getString(R.string.trackable_spotted_owner));
} else {
text = new StringBuilder("N/A");
showTimeSpan = false;
}
// days since last spotting
if (showTimeSpan && trackable.getLogs() != null) {
for (LogEntry log : trackable.getLogs()) {
if (log.type == LogType.RETRIEVED_IT || log.type == LogType.GRABBED_IT || log.type == LogType.DISCOVERED_IT || log.type == LogType.PLACED_IT) {
final int days = log.daysSinceLog();
text.append(" (").append(res.getQuantityString(R.plurals.days_ago, days, days)).append(')');
break;
}
}
}
final TextView spotted = details.add(R.string.trackable_spotted, text.toString());
spotted.setClickable(true);
if (Trackable.SPOTTED_CACHE == trackable.getSpottedType()) {
spotted.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
CacheDetailActivity.startActivityGuid(TrackableActivity.this, trackable.getSpottedGuid(), trackable.getSpottedName());
}
});
} else if (Trackable.SPOTTED_USER == trackable.getSpottedType()) {
spotted.setOnClickListener(new UserActionsListener());
}
}
// trackable origin
if (StringUtils.isNotBlank(trackable.getOrigin())) {
TextView origin = details.add(R.string.trackable_origin, "");
origin.setText(Html.fromHtml(trackable.getOrigin()), TextView.BufferType.SPANNABLE);
}
// trackable released
if (trackable.getReleased() != null) {
details.add(R.string.trackable_released, Formatter.formatDate(trackable.getReleased().getTime()));
}
// trackable distance
if (trackable.getDistance() >= 0) {
details.add(R.string.trackable_distance, Units.getDistanceFromKilometers(trackable.getDistance()));
}
// trackable goal
if (StringUtils.isNotBlank(HtmlUtils.extractText(trackable.getGoal()))) {
goalBox.setVisibility(View.VISIBLE);
goalTextView.setVisibility(View.VISIBLE);
goalTextView.setText(Html.fromHtml(trackable.getGoal(), new HtmlImage(geocode, true, 0, false), null), TextView.BufferType.SPANNABLE);
goalTextView.setMovementMethod(AnchorAwareLinkMovementMethod.getInstance());
}
// trackable details
if (StringUtils.isNotBlank(HtmlUtils.extractText(trackable.getDetails()))) {
detailsBox.setVisibility(View.VISIBLE);
detailsTextView.setVisibility(View.VISIBLE);
detailsTextView.setText(Html.fromHtml(trackable.getDetails(), new HtmlImage(geocode, true, 0, false), new UnknownTagsHandler()), TextView.BufferType.SPANNABLE);
detailsTextView.setMovementMethod(AnchorAwareLinkMovementMethod.getInstance());
}
// trackable image
if (StringUtils.isNotBlank(trackable.getImage())) {
imageBox.setVisibility(View.VISIBLE);
final ImageView trackableImage = (ImageView) inflater.inflate(R.layout.trackable_image, null);
trackableImage.setImageResource(R.drawable.image_not_loaded);
trackableImage.setClickable(true);
trackableImage.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(trackable.getImage())));
}
});
// try to load image
final Handler handler = new Handler() {
@Override
public void handleMessage(Message message) {
BitmapDrawable image = (BitmapDrawable) message.obj;
if (image != null) {
trackableImage.setImageDrawable((BitmapDrawable) message.obj);
}
}
};
new Thread() {
@Override
public void run() {
try {
HtmlImage imgGetter = new HtmlImage(geocode, true, 0, false);
BitmapDrawable image = imgGetter.getDrawable(trackable.getImage());
Message message = handler.obtainMessage(0, image);
handler.sendMessage(message);
} catch (Exception e) {
Log.e("TrackableActivity.DetailsViewCreator.ImageGetterThread: ", e);
}
}
}.start();
imageView.addView(trackableImage);
}
return view;
}
}
}
|
package cgeo.geocaching.activity;
import cgeo.geocaching.ui.dialog.CustomProgressDialog;
import cgeo.geocaching.utils.Log;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Message;
import android.view.WindowManager;
/**
* progress dialog wrapper for easier management of resources
*/
public class Progress {
private ProgressDialog dialog;
private int progress = 0;
private int progressDivider = 1;
private boolean hideAbsolute = false;
public Progress(boolean hideAbsolute) {
this.hideAbsolute = hideAbsolute;
}
public Progress() {
this(false);
}
public synchronized void dismiss() {
if (dialog != null && dialog.isShowing()) {
try {
dialog.dismiss();
} catch (final Exception e) {
Log.e("Progress.dismiss", e);
}
}
dialog = null;
}
public synchronized void show(final Context context, final String title, final String message, final boolean indeterminate, final Message cancelMessage) {
if (dialog == null) {
createProgressDialog(context, title, message, cancelMessage);
dialog.setIndeterminate(indeterminate);
dialog.show();
}
}
public synchronized void show(final Context context, final String title, final String message, final int style, final Message cancelMessage) {
if (dialog == null) {
createProgressDialog(context, title, message, cancelMessage);
dialog.setProgressStyle(style);
dialog.show();
}
}
private void createProgressDialog(Context context, String title, String message, Message cancelMessage) {
if (hideAbsolute) {
dialog = new CustomProgressDialog(context);
}
else {
dialog = new ProgressDialog(context);
}
dialog.setTitle(title);
dialog.setMessage(message);
if (cancelMessage != null) {
dialog.setCancelable(true);
dialog.setCancelMessage(cancelMessage);
dialog.setButton(DialogInterface.BUTTON_NEGATIVE, context.getResources().getString(android.R.string.cancel), cancelMessage);
} else {
dialog.setCancelable(false);
}
dialog.setProgress(0);
dialog.setCanceledOnTouchOutside(false);
dialog.getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
this.progress = 0;
}
public synchronized void setMessage(final String message) {
if (dialog != null && dialog.isShowing()) {
dialog.setMessage(message);
}
}
public synchronized boolean isShowing() {
return dialog != null && dialog.isShowing();
}
public synchronized void setMaxProgressAndReset(final int max) {
if (dialog != null && dialog.isShowing()) {
final int modMax = max / this.progressDivider;
dialog.setMax(modMax);
dialog.setProgress(0);
}
this.progress = 0;
}
public synchronized void setProgress(final int progress) {
final int modProgress = progress / this.progressDivider;
if (dialog != null && dialog.isShowing()) {
dialog.setProgress(modProgress);
}
this.progress = modProgress;
}
public synchronized int getProgress() {
if (dialog != null) {
dialog.getProgress();
}
return this.progress;
}
public synchronized void setProgressDivider(final int progressDivider) {
this.progressDivider = progressDivider;
}
}
|
package mockit;
import org.junit.*;
import static org.junit.Assert.*;
@SuppressWarnings({"UnusedDeclaration"})
public final class NonStrictExpectationsTest
{
public static class Dependency
{
public void setSomething(int value) {}
public void setSomethingElse(String value) {}
public int editABunchMoreStuff() { return 1; }
public boolean notifyBeforeSave() { return true; }
public void prepare() {}
public void save() {}
static int staticMethod(Object o, Exception e) { return -1; }
}
@Mocked Dependency mock;
private void exerciseCodeUnderTest()
{
mock.prepare();
mock.setSomething(123);
mock.setSomethingElse("anotherValue");
mock.setSomething(45);
mock.editABunchMoreStuff();
mock.notifyBeforeSave();
mock.save();
}
@Test
public void recordSimpleInvocations()
{
new NonStrictExpectations()
{{
mock.prepare();
mock.editABunchMoreStuff();
mock.setSomething(45);
}};
exerciseCodeUnderTest();
}
@Test
public void recordInvocationThatWillNotOccur()
{
new NonStrictExpectations()
{{
mock.editABunchMoreStuff(); returns(123);
}};
mock.setSomething(123);
mock.prepare();
}
@Test(expected = AssertionError.class)
public void recordInvocationWithExactExpectedNumberOfInvocationsButFailToSatisfy()
{
new NonStrictExpectations()
{{
mock.editABunchMoreStuff(); repeats(1);
}};
}
@Test(expected = AssertionError.class)
public void recordInvocationWithMinimumExpectedNumberOfInvocationsButFailToSatisfy()
{
new NonStrictExpectations()
{{
mock.editABunchMoreStuff(); repeatsAtLeast(2);
}};
mock.editABunchMoreStuff();
}
@Test(expected = AssertionError.class)
public void recordInvocationWithMaximumExpectedNumberOfInvocationsButFailToSatisfy()
{
new NonStrictExpectations()
{{
mock.editABunchMoreStuff(); repeatsAtMost(1);
}};
mock.editABunchMoreStuff();
mock.editABunchMoreStuff();
}
@Test
public void recordInvocationsWithExpectedInvocationCounts()
{
new NonStrictExpectations()
{{
mock.setSomethingElse(withAny("")); repeatsAtLeast(1);
mock.save(); repeats(2);
}};
mock.setSomething(3);
mock.save();
mock.setSomethingElse("test");
mock.save();
}
@Test(expected = AssertionError.class)
public void recordInvocationsWithMinInvocationCountLargerThanWillOccur()
{
new NonStrictExpectations()
{{
mock.save(); repeatsAtLeast(2);
}};
mock.save();
}
@Test
public void recordWithArgumentMatcherAndIndividualInvocationCounts()
{
new NonStrictExpectations(1)
{{
mock.prepare(); repeatsAtMost(1);
mock.setSomething(withAny(0)); repeatsAtLeast(2);
mock.editABunchMoreStuff(); repeats(0, 5);
mock.save(); repeats(1);
}};
exerciseCodeUnderTest();
}
@Test
public void recordWithMaxInvocationCountFollowedByReturnValue()
{
new NonStrictExpectations()
{{
Dependency.staticMethod(any, null);
repeatsAtMost(1);
returns(1);
}};
assertEquals(1, Dependency.staticMethod(new Object(), new Exception()));
}
@Test(expected = AssertionError.class)
public void recordWithMaxInvocationCountFollowedByReturnValueButReplayOneTimeBeyondMax()
{
new NonStrictExpectations()
{{
Dependency.staticMethod(any, null);
repeatsAtMost(1);
returns(1);
}};
Dependency.staticMethod(null, null);
Dependency.staticMethod(null, null);
}
@Test
public void recordWithReturnValueFollowedByExpectedInvocationCount()
{
new NonStrictExpectations()
{{
Dependency.staticMethod(any, null);
returns(1);
repeats(1);
}};
assertEquals(1, Dependency.staticMethod(null, null));
}
@Test
public void recordWithMinInvocationCountFollowedByReturnValueUsingDelegate()
{
new NonStrictExpectations()
{{
Dependency.staticMethod(any, null);
repeatsAtLeast(1);
returns(new Delegate()
{
int staticMethod(Object o, Exception e) { return 1; }
});
}};
assertEquals(1, Dependency.staticMethod(null, null));
}
@Test
public void recordInvocationsInIteratingBlock()
{
new NonStrictExpectations(2)
{{
mock.setSomething(withAny(1)); repeats(1);
mock.save(); repeats(1);
}};
mock.setSomething(123);
mock.save();
mock.setSomething(45);
mock.save();
}
@Test(expected = AssertionError.class)
public void recordInvocationInBlockWithWrongNumberOfIterations()
{
new NonStrictExpectations(3)
{{
mock.setSomething(123); repeatsAtLeast(1);
}};
mock.setSomething(123);
}
@Test
public void recordWithArgumentMatcherAndIndividualInvocationCountsInIteratingBlock()
{
new NonStrictExpectations(2)
{{
mock.prepare(); repeatsAtMost(1);
mock.setSomething(withAny(0)); repeatsAtLeast(2);
mock.editABunchMoreStuff(); repeats(1, 5);
mock.save(); repeats(1);
}};
for (int i = 0; i < 2; i++) {
exerciseCodeUnderTest();
}
}
}
|
package org.voltcore.utils;
import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.MalformedURLException;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.net.URL;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Enumeration;
import java.util.List;
import java.util.Map;
import java.util.Queue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.Callable;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.SynchronousQueue;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.locks.ReentrantLock;
import jsr166y.LinkedTransferQueue;
import org.voltcore.logging.VoltLogger;
import org.voltcore.network.ReverseDNSCache;
import com.google_voltpatches.common.base.Preconditions;
import com.google_voltpatches.common.base.Supplier;
import com.google_voltpatches.common.base.Suppliers;
import com.google_voltpatches.common.collect.ImmutableList;
import com.google_voltpatches.common.collect.ImmutableMap;
import com.google_voltpatches.common.util.concurrent.ListenableFuture;
import com.google_voltpatches.common.util.concurrent.ListeningExecutorService;
import com.google_voltpatches.common.util.concurrent.MoreExecutors;
import com.google_voltpatches.common.util.concurrent.SettableFuture;
public class CoreUtils {
private static final VoltLogger hostLog = new VoltLogger("HOST");
public static final int SMALL_STACK_SIZE = 1024 * 256;
public static final int MEDIUM_STACK_SIZE = 1024 * 512;
public static volatile Runnable m_threadLocalDeallocator = new Runnable() {
@Override
public void run() {
}
};
public static final ListenableFuture<Object> COMPLETED_FUTURE = new ListenableFuture<Object>() {
@Override
public void addListener(Runnable listener, Executor executor) { executor.execute(listener); }
@Override
public boolean cancel(boolean mayInterruptIfRunning) { return false; }
@Override
public boolean isCancelled() { return false; }
@Override
public boolean isDone() { return true; }
@Override
public Object get() { return null; }
@Override
public Object get(long timeout, TimeUnit unit) { return null; }
};
public static final Runnable EMPTY_RUNNABLE = new Runnable() {
@Override
public void run() {}
};
/**
* Get a single thread executor that caches it's thread meaning that the thread will terminate
* after keepAlive milliseconds. A new thread will be created the next time a task arrives and that will be kept
* around for keepAlive milliseconds. On creation no thread is allocated, the first task creates a thread.
*
* Uses LinkedTransferQueue to accept tasks and has a small stack.
*/
public static ListeningExecutorService getCachedSingleThreadExecutor(String name, long keepAlive) {
return MoreExecutors.listeningDecorator(new ThreadPoolExecutor(
0,
1,
keepAlive,
TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>(),
CoreUtils.getThreadFactory(null, name, SMALL_STACK_SIZE, false, null)));
}
/**
* Create an unbounded single threaded executor
*/
public static ExecutorService getSingleThreadExecutor(String name) {
ExecutorService ste =
new ThreadPoolExecutor(1, 1,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>(),
CoreUtils.getThreadFactory(null, name, SMALL_STACK_SIZE, false, null));
return ste;
}
public static ExecutorService getSingleThreadExecutor(String name, int size) {
ExecutorService ste =
new ThreadPoolExecutor(1, 1,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>(),
CoreUtils.getThreadFactory(null, name, size, false, null));
return ste;
}
/**
* Create an unbounded single threaded executor
*/
public static ListeningExecutorService getListeningSingleThreadExecutor(String name) {
ExecutorService ste =
new ThreadPoolExecutor(1, 1,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>(),
CoreUtils.getThreadFactory(null, name, SMALL_STACK_SIZE, false, null));
return MoreExecutors.listeningDecorator(ste);
}
public static ListeningExecutorService getListeningSingleThreadExecutor(String name, int size) {
ExecutorService ste =
new ThreadPoolExecutor(1, 1,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>(),
CoreUtils.getThreadFactory(null, name, size, false, null));
return MoreExecutors.listeningDecorator(ste);
}
/**
* Create a bounded single threaded executor that rejects requests if more than capacity
* requests are outstanding.
*/
public static ListeningExecutorService getBoundedSingleThreadExecutor(String name, int capacity) {
LinkedBlockingQueue<Runnable> lbq = new LinkedBlockingQueue<Runnable>(capacity);
ThreadPoolExecutor tpe =
new ThreadPoolExecutor(1, 1, 0L, TimeUnit.MILLISECONDS, lbq, CoreUtils.getThreadFactory(name));
return MoreExecutors.listeningDecorator(tpe);
}
/*
* Have shutdown actually means shutdown. Tasks that need to complete should use
* futures.
*/
public static ScheduledThreadPoolExecutor getScheduledThreadPoolExecutor(String name, int poolSize, int stackSize) {
ScheduledThreadPoolExecutor ses = new ScheduledThreadPoolExecutor(poolSize, getThreadFactory(null, name, stackSize, poolSize > 1, null));
ses.setContinueExistingPeriodicTasksAfterShutdownPolicy(false);
ses.setExecuteExistingDelayedTasksAfterShutdownPolicy(false);
return ses;
}
public static ListeningExecutorService getListeningExecutorService(
final String name,
final int threads) {
return getListeningExecutorService(name, threads, new LinkedTransferQueue<Runnable>(), null);
}
public static ListeningExecutorService getListeningExecutorService(
final String name,
final int coreThreads,
final int threads) {
return getListeningExecutorService(name, coreThreads, threads, new LinkedTransferQueue<Runnable>(), null);
}
public static ListeningExecutorService getListeningExecutorService(
final String name,
final int threads,
Queue<String> coreList) {
return getListeningExecutorService(name, threads, new LinkedTransferQueue<Runnable>(), coreList);
}
public static ListeningExecutorService getListeningExecutorService(
final String name,
int threadsTemp,
final BlockingQueue<Runnable> queue,
final Queue<String> coreList) {
if (coreList != null && !coreList.isEmpty()) {
threadsTemp = coreList.size();
}
final int threads = threadsTemp;
if (threads < 1) {
throw new IllegalArgumentException("Must specify > 0 threads");
}
if (name == null) {
throw new IllegalArgumentException("Name cannot be null");
}
return MoreExecutors.listeningDecorator(
new ThreadPoolExecutor(threads, threads,
0L, TimeUnit.MILLISECONDS,
queue,
getThreadFactory(null, name, SMALL_STACK_SIZE, threads > 1 ? true : false, coreList)));
}
public static ListeningExecutorService getListeningExecutorService(
final String name,
int coreThreadsTemp,
int threadsTemp,
final BlockingQueue<Runnable> queue,
final Queue<String> coreList) {
if (coreThreadsTemp < 0) {
throw new IllegalArgumentException("Must specify >= 0 core threads");
}
if (coreThreadsTemp > threadsTemp) {
throw new IllegalArgumentException("Core threads must be <= threads");
}
if (coreList != null && !coreList.isEmpty()) {
threadsTemp = coreList.size();
if (coreThreadsTemp > threadsTemp) {
coreThreadsTemp = threadsTemp;
}
}
final int coreThreads = coreThreadsTemp;
final int threads = threadsTemp;
if (threads < 1) {
throw new IllegalArgumentException("Must specify > 0 threads");
}
if (name == null) {
throw new IllegalArgumentException("Name cannot be null");
}
return MoreExecutors.listeningDecorator(
new ThreadPoolExecutor(coreThreads, threads,
1L, TimeUnit.MINUTES,
queue,
getThreadFactory(null, name, SMALL_STACK_SIZE, threads > 1 ? true : false, coreList)));
}
/**
* Create a bounded thread pool executor. The work queue is synchronous and can cause
* RejectedExecutionException if there is no available thread to take a new task.
* @param maxPoolSize: the maximum number of threads to allow in the pool.
* @param keepAliveTime: when the number of threads is greater than the core, this is the maximum
* time that excess idle threads will wait for new tasks before terminating.
* @param unit: the time unit for the keepAliveTime argument.
* @param threadFactory: the factory to use when the executor creates a new thread.
*/
public static ThreadPoolExecutor getBoundedThreadPoolExecutor(int maxPoolSize, long keepAliveTime, TimeUnit unit, ThreadFactory tFactory) {
return new ThreadPoolExecutor(0, maxPoolSize, keepAliveTime, unit,
new SynchronousQueue<Runnable>(), tFactory);
}
public static ThreadFactory getThreadFactory(String name) {
return getThreadFactory(name, SMALL_STACK_SIZE);
}
public static ThreadFactory getThreadFactory(String groupName, String name) {
return getThreadFactory(groupName, name, SMALL_STACK_SIZE, true, null);
}
public static ThreadFactory getThreadFactory(String name, int stackSize) {
return getThreadFactory(null, name, stackSize, true, null);
}
/**
* Creates a thread factory that creates threads within a thread group if
* the group name is given. The threads created will catch any unhandled
* exceptions and log them to the HOST logger.
*
* @param groupName
* @param name
* @param stackSize
* @return
*/
public static ThreadFactory getThreadFactory(
final String groupName,
final String name,
final int stackSize,
final boolean incrementThreadNames,
final Queue<String> coreList) {
ThreadGroup group = null;
if (groupName != null) {
group = new ThreadGroup(Thread.currentThread().getThreadGroup(), groupName);
}
final ThreadGroup finalGroup = group;
return new ThreadFactory() {
private final AtomicLong m_createdThreadCount = new AtomicLong(0);
private final ThreadGroup m_group = finalGroup;
@Override
public synchronized Thread newThread(final Runnable r) {
final String threadName = name +
(incrementThreadNames ? " - " + m_createdThreadCount.getAndIncrement() : "");
String coreTemp = null;
if (coreList != null && !coreList.isEmpty()) {
coreTemp = coreList.poll();
}
final String core = coreTemp;
Runnable runnable = new Runnable() {
@Override
public void run() {
if (core != null) {
// Remove Affinity for now to make this dependency dissapear from the client.
// Goal is to remove client dependency on this class in the medium term.
//PosixJNAAffinity.INSTANCE.setAffinity(core);
}
try {
r.run();
} catch (Throwable t) {
hostLog.error("Exception thrown in thread " + threadName, t);
} finally {
m_threadLocalDeallocator.run();
}
}
};
Thread t = new Thread(m_group, runnable, threadName, stackSize);
t.setDaemon(true);
return t;
}
};
}
/**
* Return the local hostname, if it's resolvable. If not,
* return the IPv4 address on the first interface we find, if it exists.
* If not, returns whatever address exists on the first interface.
* @return the String representation of some valid host or IP address,
* if we can find one; the empty string otherwise
*/
public static String getHostnameOrAddress() {
final InetAddress addr = m_localAddressSupplier.get();
if (addr == null) return "";
return ReverseDNSCache.hostnameOrAddress(addr);
}
private static final Supplier<InetAddress> m_localAddressSupplier =
Suppliers.memoizeWithExpiration(new Supplier<InetAddress>() {
@Override
public InetAddress get() {
try {
final InetAddress addr = InetAddress.getLocalHost();
return addr;
} catch (UnknownHostException e) {
try {
Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
if (interfaces == null) {
return null;
}
NetworkInterface intf = interfaces.nextElement();
Enumeration<InetAddress> addresses = intf.getInetAddresses();
while (addresses.hasMoreElements()) {
InetAddress address = addresses.nextElement();
if (address instanceof Inet4Address) {
return address;
}
}
addresses = intf.getInetAddresses();
if (addresses.hasMoreElements()) {
return addresses.nextElement();
}
return null;
} catch (SocketException e1) {
return null;
}
}
}
}, 1, TimeUnit.DAYS);
/**
* Return the local IP address, if it's resolvable. If not,
* return the IPv4 address on the first interface we find, if it exists.
* If not, returns whatever address exists on the first interface.
* @return the String representation of some valid host or IP address,
* if we can find one; the empty string otherwise
*/
public static InetAddress getLocalAddress() {
return m_localAddressSupplier.get();
}
public static long getHSIdFromHostAndSite(int host, int site) {
long HSId = site;
HSId = (HSId << 32) + host;
return HSId;
}
public static int getHostIdFromHSId(long HSId) {
return (int) (HSId & 0xffffffff);
}
public static String hsIdToString(long hsId) {
return Integer.toString((int)hsId) + ":" + Integer.toString((int)(hsId >> 32));
}
public static String hsIdCollectionToString(Collection<Long> ids) {
List<String> idstrings = new ArrayList<String>();
for (Long id : ids) {
idstrings.add(hsIdToString(id));
}
// Easy hack, sort hsIds lexically.
Collections.sort(idstrings);
StringBuilder sb = new StringBuilder();
boolean first = false;
for (String id : idstrings) {
if (!first) {
first = true;
} else {
sb.append(", ");
}
sb.append(id);
}
return sb.toString();
}
public static int getSiteIdFromHSId(long siteId) {
return (int)(siteId>>32);
}
public static <K,V> ImmutableMap<K, ImmutableList<V>> unmodifiableMapCopy(Map<K, List<V>> m) {
ImmutableMap.Builder<K, ImmutableList<V>> builder = ImmutableMap.builder();
for (Map.Entry<K, List<V>> e : m.entrySet()) {
builder.put(e.getKey(), ImmutableList.<V>builder().addAll(e.getValue()).build());
}
return builder.build();
}
public static byte[] urlToBytes(String url) {
if (url == null) {
return null;
}
try {
// get the URL/path for the deployment and prep an InputStream
InputStream input = null;
try {
URL inputURL = new URL(url);
input = inputURL.openStream();
} catch (MalformedURLException ex) {
// Invalid URL. Try as a file.
try {
input = new FileInputStream(url);
} catch (FileNotFoundException e) {
throw new RuntimeException(e);
}
} catch (IOException ioex) {
throw new RuntimeException(ioex);
}
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte readBytes[] = new byte[1024 * 8];
while (true) {
int read = input.read(readBytes);
if (read == -1) {
break;
}
baos.write(readBytes, 0, read);
}
return baos.toByteArray();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public static String throwableToString(Throwable t) {
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
t.printStackTrace(pw);
pw.flush();
return sw.toString();
}
public static String hsIdKeyMapToString(Map<Long, ?> m) {
StringBuilder sb = new StringBuilder();
sb.append('{');
boolean first = true;
for (Map.Entry<Long, ?> entry : m.entrySet()) {
if (!first) sb.append(", ");
first = false;
sb.append(CoreUtils.hsIdToString(entry.getKey()));
sb.append("->").append(entry.getValue());
}
sb.append('}');
return sb.toString();
}
public static String hsIdValueMapToString(Map<?, Long> m) {
StringBuilder sb = new StringBuilder();
sb.append('{');
boolean first = true;
for (Map.Entry<?, Long> entry : m.entrySet()) {
if (!first) sb.append(", ");
first = false;
sb.append(entry.getKey()).append("->");
sb.append(CoreUtils.hsIdToString(entry.getValue()));
}
sb.append('}');
return sb.toString();
}
public static String hsIdMapToString(Map<Long, Long> m) {
StringBuilder sb = new StringBuilder();
sb.append('{');
boolean first = true;
for (Map.Entry<Long, Long> entry : m.entrySet()) {
if (!first) sb.append(", ");
first = false;
sb.append(CoreUtils.hsIdToString(entry.getKey())).append(" -> ");
sb.append(CoreUtils.hsIdToString(entry.getValue()));
}
sb.append('}');
return sb.toString();
}
public static int availableProcessors() {
return Math.max(1, Runtime.getRuntime().availableProcessors());
}
public static final class RetryException extends RuntimeException {
public RetryException() {};
public RetryException(Throwable cause) {
super(cause);
}
}
/**
* A helper for retrying tasks asynchronously returns a settable future
* that can be used to attempt to cancel the task.
*
* The first executor service is used to schedule retry attempts
* The second is where the task will be subsmitted for execution
* If the two services are the same only the scheduled service is used
*
* @param maxAttempts It is the number of total attempts including the first one.
* If the value is 0, that means there is no limit.
*/
public static final<T> ListenableFuture<T> retryHelper(
final ScheduledExecutorService ses,
final ExecutorService es,
final Callable<T> callable,
final long maxAttempts,
final long startInterval,
final TimeUnit startUnit,
final long maxInterval,
final TimeUnit maxUnit) {
Preconditions.checkNotNull(maxUnit);
Preconditions.checkNotNull(startUnit);
Preconditions.checkArgument(startUnit.toMillis(startInterval) >= 1);
Preconditions.checkArgument(maxUnit.toMillis(maxInterval) >= 1);
Preconditions.checkNotNull(callable);
final SettableFuture<T> retval = SettableFuture.create();
/*
* Base case with no retry, attempt the task once
*/
es.execute(new Runnable() {
@Override
public void run() {
try {
retval.set(callable.call());
} catch (RetryException e) {
//Now schedule a retry
retryHelper(ses, es, callable, maxAttempts - 1, startInterval, startUnit, maxInterval, maxUnit, 0, retval);
} catch (Exception e) {
retval.setException(e);
}
}
});
return retval;
}
private static final <T> void retryHelper(
final ScheduledExecutorService ses,
final ExecutorService es,
final Callable<T> callable,
final long maxAttempts,
final long startInterval,
final TimeUnit startUnit,
final long maxInterval,
final TimeUnit maxUnit,
final long ii,
final SettableFuture<T> retval) {
if (maxAttempts == 0) {
retval.setException(new RuntimeException("Max attempts reached"));
return;
}
long intervalMax = maxUnit.toMillis(maxInterval);
final long interval = Math.min(intervalMax, startUnit.toMillis(startInterval) * 2);
ses.schedule(new Runnable() {
@Override
public void run() {
Runnable task = new Runnable() {
@Override
public void run() {
if (retval.isCancelled()) return;
try {
retval.set(callable.call());
} catch (RetryException e) {
retryHelper(ses, es, callable, maxAttempts - 1, interval, TimeUnit.MILLISECONDS, maxInterval, maxUnit, ii + 1, retval);
} catch (Exception e3) {
retval.setException(e3);
}
}
};
if (ses == es) task.run();
else es.execute(task);
}
}, interval, TimeUnit.MILLISECONDS);
}
public static void spinLock(ReentrantLock lock) {
int spins = 128;
ThreadLocalRandom randomYields = null;
for (;;) {
if (lock.tryLock()) {
return;
}
if (randomYields == null) {
randomYields = ThreadLocalRandom.current();
}
else if (spins > 0) {
--spins;
if (randomYields.nextInt(64) == 0)
Thread.yield();
}
else {
lock.lock();
return;
}
}
}
}
|
package org.voltdb.iv2;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutionException;
import org.apache.zookeeper_voltpatches.KeeperException;
import org.voltcore.logging.VoltLogger;
import org.voltcore.messaging.HostMessenger;
import org.voltcore.utils.CoreUtils;
import org.voltcore.zk.LeaderElector;
import org.voltcore.zk.LeaderNoticeHandler;
import org.voltdb.BackendTarget;
import org.voltdb.CatalogContext;
import org.voltdb.CatalogSpecificPlanner;
import org.voltdb.LoadedProcedureSet;
import org.voltdb.ProcedureRunnerFactory;
import org.voltdb.iv2.Site;
import org.voltdb.VoltDB;
/**
* Subclass of Initiator to manage single-partition operations.
* This class is primarily used for object construction and configuration plumbing;
* Try to avoid filling it with lots of other functionality.
*/
public abstract class BaseInitiator implements Initiator, LeaderNoticeHandler
{
VoltLogger tmLog = new VoltLogger("TM");
// External references/config
protected final HostMessenger m_messenger;
protected final int m_partitionId;
private CountDownLatch m_missingStartupSites;
private final String m_zkMailboxNode;
protected final String m_whoami;
// Encapsulated objects
protected final Scheduler m_scheduler;
protected final InitiatorMailbox m_initiatorMailbox;
protected Term m_term = null;
protected Site m_executionSite = null;
protected LeaderElector m_leaderElector = null;
protected Thread m_siteThread = null;
protected final RepairLog m_repairLog = new RepairLog();
public BaseInitiator(String zkMailboxNode, HostMessenger messenger, Integer partition,
Scheduler scheduler, String whoamiPrefix)
{
m_zkMailboxNode = zkMailboxNode;
m_messenger = messenger;
m_partitionId = partition;
m_scheduler = scheduler;
RejoinProducer rejoinProducer =
new RejoinProducer(m_partitionId, scheduler.m_tasks);
m_initiatorMailbox = new InitiatorMailbox(
m_partitionId,
m_scheduler,
m_messenger,
m_repairLog,
rejoinProducer);
// Now publish the initiator mailbox to friends and family
m_messenger.createMailbox(null, m_initiatorMailbox);
rejoinProducer.setMailbox(m_initiatorMailbox);
m_scheduler.setMailbox(m_initiatorMailbox);
String partitionString = " ";
if (m_partitionId != -1) {
partitionString = " for partition " + m_partitionId + " ";
}
m_whoami = whoamiPrefix + " " +
CoreUtils.hsIdToString(getInitiatorHSId()) + partitionString;
}
@Override
public void configure(BackendTarget backend, String serializedCatalog,
CatalogContext catalogContext,
int kfactor, CatalogSpecificPlanner csp,
int numberOfPartitions,
boolean createForRejoin)
{
try {
m_executionSite = new Site(m_scheduler.getQueue(),
m_initiatorMailbox.getHSId(),
backend, catalogContext,
serializedCatalog,
catalogContext.m_transactionId,
m_partitionId,
numberOfPartitions,
createForRejoin);
ProcedureRunnerFactory prf = new ProcedureRunnerFactory();
prf.configure(m_executionSite, m_executionSite.m_sysprocContext);
LoadedProcedureSet procSet = new LoadedProcedureSet(
m_executionSite,
prf,
m_initiatorMailbox.getHSId(),
0, // this has no meaning
numberOfPartitions);
procSet.loadProcedures(catalogContext, backend, csp);
m_executionSite.setLoadedProcedures(procSet);
m_scheduler.setProcedureSet(procSet);
m_scheduler.start();
m_siteThread = new Thread(m_executionSite);
m_siteThread.start();
// Join the leader election process after the object is fully
// configured. If we do this earlier, rejoining sites will be
// given transactions before they're ready to handle them.
// FUTURE: Consider possibly returning this and the
// m_siteThread.start() in a Runnable which RealVoltDB can use for
// configure/run sequencing in the future.
joinElectoralCollege(kfactor);
}
catch (Exception e) {
VoltDB.crashLocalVoltDB("Failed to configure initiator", true, e);
}
}
// Register with m_partition's leader elector node
// On the leader, becomeLeader() will run before joinElectoralCollage returns.
boolean joinElectoralCollege(int kfactor) throws InterruptedException, ExecutionException, KeeperException
{
m_missingStartupSites = new CountDownLatch(kfactor + 1);
m_leaderElector = new LeaderElector(m_messenger.getZK(),
LeaderElector.electionDirForPartition(m_partitionId),
Long.toString(getInitiatorHSId()), null, this);
m_leaderElector.start(true);
m_missingStartupSites = null;
boolean isLeader = m_leaderElector.isLeader();
if (isLeader) {
tmLog.info(m_whoami + "published as leader.");
}
else {
tmLog.info(m_whoami + "running as replica.");
}
return isLeader;
}
// runs on the leader elector callback thread.
@Override
public void becomeLeader()
{
try {
long startTime = System.currentTimeMillis();
Boolean success = false;
while (!success) {
// term syslogs the start of leader promotion.
m_term = new Term(m_missingStartupSites, m_messenger.getZK(),
m_partitionId, getInitiatorHSId(), m_initiatorMailbox,
m_zkMailboxNode, m_whoami);
m_initiatorMailbox.setTerm(m_term);
success = m_term.start().get();
if (success) {
m_repairLog.setLeaderState(true);
m_scheduler.setLeaderState(true);
tmLog.info(m_whoami
+ "finished leader promotion. Took "
+ (System.currentTimeMillis() - startTime) + " ms.");
}
else {
// The only known reason to fail is a failed replica during
// recovery; that's a bounded event (by k-safety).
// CrashVoltDB here means one node failure causing another.
// Don't create a cascading failure - just try again.
tmLog.info(m_whoami
+ "interrupted during leader promotion after "
+ (System.currentTimeMillis() - startTime) + " ms. of "
+ "trying. Retrying.");
}
}
} catch (Exception e) {
VoltDB.crashLocalVoltDB("Terminally failed leader promotion.", true, e);
}
}
@Override
public void shutdown()
{
// rtb: better to schedule a shutdown SiteTasker?
// than to play java interrupt() games?
if (m_scheduler != null) {
m_scheduler.shutdown();
}
if (m_executionSite != null) {
m_executionSite.startShutdown();
}
try {
if (m_leaderElector != null) {
m_leaderElector.shutdown();
}
if (m_term != null) {
m_term.shutdown();
}
if (m_initiatorMailbox != null) {
m_initiatorMailbox.shutdown();
}
} catch (InterruptedException e) {
// what to do here?
} catch (KeeperException e) {
// What to do here?
}
if (m_siteThread != null) {
try {
m_siteThread.interrupt();
m_siteThread.join();
}
catch (InterruptedException giveup) {
}
}
}
@Override
public long getInitiatorHSId()
{
return m_initiatorMailbox.getHSId();
}
}
|
package fx_clj.binding;
import clojure.lang.IReactiveAtom;
import clojure.lang.IReactiveRef;
import javafx.beans.InvalidationListener;
import javafx.beans.Observable;
import javafx.beans.binding.Bindings;
import javafx.beans.property.Property;
import javafx.beans.value.ObservableValue;
import javafx.beans.value.WritableValue;
import java.lang.ref.WeakReference;
public class ReactiveAtomObservable extends ReactiveRefObservable implements Property<Object> {
private final IReactiveAtom atom;
private ObservableValue<?> other;
private InvalidationListener listener;
public ReactiveAtomObservable(IReactiveAtom atom) {
super(atom);
this.atom = atom;
}
@Override
public void setValue(Object value) {
atom.reset(value);
}
@Override
public void bind(ObservableValue<?> other) {
if (other == null) {
throw new NullPointerException("Cannot bind to null");
}
if (!other.equals(this.other)) {
unbind();
this.other = other;
if (listener == null) {
listener = new Listener(this);
}
other.addListener(listener);
markInvalid();
}
}
@Override
public void unbind() {
if(other != null) {
other.removeListener(listener);
other = null;
}
}
@Override
public boolean isBound() {
return other != null;
}
@Override
public void bindBidirectional(Property<Object> other) {
Bindings.bindBidirectional(this, other);
}
@Override
public void unbindBidirectional(Property<Object> other) {
Bindings.unbindBidirectional(this, other);
}
@Override
public Object getBean() {
return null;
}
@Override
public String getName() {
return null;
}
private static class Listener implements InvalidationListener {
private final WeakReference<ReactiveAtomObservable> wref;
public Listener(ReactiveAtomObservable ref) {
this.wref = new WeakReference<ReactiveAtomObservable>(ref);
}
@Override
public void invalidated(Observable observable) {
ReactiveAtomObservable ref = wref.get();
if (ref == null) {
observable.removeListener(this);
} else {
ref.markInvalid();
}
}
}
private void markInvalid() {
setValue(other.getValue());
}
}
|
package solution;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/**
*
* @author Skander
*/
class FormatException extends Exception {
public FormatException() {}
public FormatException(String message) {
super(message);
}
}
public class BaseDeClauses {
private String formules;
private String sets;
private static final String errorBeginFormula = "Syntax error at line %d"
+ ". Formula begin section already"
+ " declared.";
private static final String errorEndFormula = "Syntax error at line %d"
+ ". No formula section is opened.";
private static final String errorBeginSet =
errorBeginFormula.replace("Formula","Set");
private static final String errorEndSet =
errorEndFormula.replace("formula","set");
/**
* Construct a set of clauses
*/
public BaseDeClauses() {
formules = new String();
sets = new String();
}
/**
*
* @return the list of formules
*/
public String getFormules() {
return formules;
}
/**
* @return the list of sets
*/
public String getSets() {
return sets;
}
/**
* @return the index of the line of "begin formula"
*/
public int getLineFormula(){
return sets.split("\n").length+3;
}
/**
* @return the index of the line of "begin sets"
*/
public int getLineSets(){
return 1;
}
/**
* Import the list of formules from a file
* @param path of the file containing the list of formules and sets
* @throws FileNotFoundException if the path of the file is invalid
* @throws IOException if any I/O exception occurs during file reading
* @throws FormatException if the filedefines incorrectly the formula
* section
*/
public void uploadFile(String path) throws FileNotFoundException,
IOException,
FormatException {
BufferedReader in = new BufferedReader(new FileReader(path));
String line;
boolean formulaSection = false;
boolean setSection = false;
int indexLine = 0;
while((line = in.readLine()) != null) {
indexLine ++;
String []words = line.replace("\\s+"," ").split(" ");
if(words.length == 2) {
words[0] = words[0].toLowerCase();
words[1] = words[1].toLowerCase();
if(Arrays.equals(words,new String[]{"begin","formula"})) {
if(formulaSection == true) {
String message = String.format(errorBeginFormula,indexLine);
throw new FormatException(message);
}
else {
formulaSection = true;
}
}
else if(Arrays.equals(words,new String[]{"end","formula"})) {
if(formulaSection == false) {
String message = String.format(errorEndFormula,indexLine);
throw new FormatException(message);
}
else {
formulaSection = false;
}
}
else if(Arrays.equals(words,new String[]{"begin","sets"})) {
if(setSection == true) {
String message = String.format(errorBeginSet,indexLine);
throw new FormatException(message);
}
else {
setSection = true;
}
}
else if(Arrays.equals(words,new String[]{"end","sets"})) {
if(setSection == false) {
String message = String.format(errorEndSet,indexLine);
throw new FormatException(message);
}
else {
setSection = false;
}
}
}
else if(formulaSection) {
addFormule(line);
}
else if(setSection) {
addSet(line);
}
}
}
public void saveToFile(String path) throws IOException {
int sizeBuffer = 8192;
BufferedWriter writer = new BufferedWriter(new FileWriter(path), sizeBuffer);
if(!sets.isEmpty()) {
writer.write("begin sets\n");
writer.write(sets);
writer.write("end sets\n");
}
if(!formules.isEmpty()) {
writer.write("begin formula\n");
writer.write(sets);
writer.write("end formula\n");
}
writer.flush();
writer.close();
}
/**
* Add a formule to the current String of formules
* @param A formule
*/
public void addFormule(String formule) {
formules = formules.concat(formule);
}
/**
* Add a set to the current String of sets
* @param A set
*/
public void addSet(String set) {
sets = sets.concat(set);
}
/**
* Add all formules found in a string to the current String of formules
* @param a String
*/
public void addFormules(String text) {
formules = formules.concat(text);
}
/**
* Add all sets found in a string to the current String of sets
* @param a String
*/
public void addSets(String text) {
sets = sets.concat(text);
}
public static void main(String[] args) {
System.out.println("essai");
}
}
|
package org.languagetool.rules.nl;
import org.apache.commons.lang3.StringUtils;
import org.jetbrains.annotations.Nullable;
import org.languagetool.AnalyzedTokenReadings;
import org.languagetool.rules.RuleMatch;
import org.languagetool.rules.patterns.RuleFilter;
import java.util.Map;
import static java.lang.Character.isLowerCase;
import static java.lang.Character.isUpperCase;
public class CompoundFilter extends RuleFilter {
private final static String spelledWords = "(abc|adv|aed|apk|b2b|bh|bhv|bso|btw|bv|cao|cd|cfk|ckv|cv|dc|dj|dtp|dvd|fte|gft|ggo|ggz|gm|gmo|gps|gsm|hbo|" +
"hd|hiv|hr|hrm|hst|ic|ivf|kmo|lcd|lp|lpg|lsd|mbo|mdf|mkb|mms|msn|mt|ngo|nv|ob|ov|ozb|p2p|pc|pcb|pdf|pk|pps|" +
"pr|pvc|roc|rvs|sms|tbc|tbs|tl|tv|uv|vbo|vj|vmbo|vsbo|vwo|wc|wo|xtc|zzp)";
@Nullable
@Override
public RuleMatch acceptRuleMatch(RuleMatch match, Map<String, String> arguments, int patternTokenPos, AnalyzedTokenReadings[] patternTokens) {
String word1 = arguments.get("word1");
String word2 = arguments.get("word2");
char lastChar = word1.charAt(word1.length()-1);
char firstChar = word2.charAt(0);
String connection = lastChar + String.valueOf(firstChar);
String repl;
if (StringUtils.containsAny(connection, "aa", "ae", "ai", "ao", "au", "ee", "ei", "eu", "ie", "ii", "oe", "oi", "oo", "ou", "ui", "uu", "ij")) {
repl = word1 + '-' + word2;
} else if (isUpperCase(firstChar) && isLowerCase(lastChar)) {
repl = word1 + '-' + word2;
} else if (isUpperCase(lastChar) && isLowerCase(firstChar)) {
repl = word1 + '-' + word2;
} else if (word1.matches("(^|.+-)?"+spelledWords) || word2.matches(spelledWords+"(-.+|$)?")) {
repl = word1 + '-' + word2;
} else if (word1.matches(".+-[a-z]$") || word2.matches("^[a-z]-.+")) {
repl = word1 + '-' + word2;
} else {
repl = word1 + word2;
}
String message = match.getMessage().replaceAll("<suggestion>.*?</suggestion>", "<suggestion>" + repl + "</suggestion>");
String shortMessage = match.getShortMessage().replaceAll("<suggestion>.*?</suggestion>", "<suggestion>" + repl + "</suggestion>");
RuleMatch newMatch = new RuleMatch(match.getRule(), match.getSentence(), match.getFromPos(), match.getToPos(), message, shortMessage);
newMatch.setSuggestedReplacement(repl);
return newMatch;
/*
String words = arguments.get("words");
String[] parts=words.split('|');
String compound=parts[0];
for (int i = 1; i < parts.length-1; i++)
String word1 = compound;
String word2 = parts[i+1];
char lastChar = compound.charAt(compound.length()-1);
char firstChar = word2.charAt(0);
String connection = lastChar + String.valueOf(firstChar);
String repl;
if (StringUtils.containsAny(connection, "aa", "ae", "ai", "ao", "au", "ee", "ei", "eu", "ie", "ii", "oe", "oi", "oo", "ou", "ui", "uu", "ij")) {
compound = compound + '-' + word2;
} else if (isUpperCase(firstChar) && isLowerCase(lastChar)) {
compound = compound + '-' + word2;
} else if (isUpperCase(lastChar) && isLowerCase(firstChar)) {
compound = compound + '-' + word2;
} else if (compound.matches("(^|.+-)?"+spelledWords) || word2.matches(spelledWords+"(-.+|$)?")) {
compound = compound + '-' + word2;
} else if (compound.matches(".+-[a-z]$") || word2.matches("^[a-z]-.+")) {
compound = compound + '-' + word2;
} else {
compound = compound + word2;
}
String message = match.getMessage().replaceAll("<suggestion>.*?</suggestion>", "<suggestion>" + compound + "</suggestion>");
String shortMessage = match.getShortMessage().replaceAll("<suggestion>.*?</suggestion>", "<suggestion>" + compound + "</suggestion>");
RuleMatch newMatch = new RuleMatch(match.getRule(), match.getSentence(), match.getFromPos(), match.getToPos(), message, shortMessage);
newMatch.setSuggestedReplacement(repl);
return newMatch;
*/
}
}
|
package org.dosomething.android.activities;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.dosomething.android.R;
import org.dosomething.android.cache.Cache;
import org.dosomething.android.context.UserContext;
import org.dosomething.android.dao.MyDAO;
import org.dosomething.android.domain.CompletedCampaignAction;
import org.dosomething.android.domain.UserCampaign;
import org.dosomething.android.tasks.AbstractFetchCampaignsTask;
import org.dosomething.android.transfer.Campaign;
import roboguice.inject.InjectView;
import android.content.Context;
import android.content.Intent;
import android.graphics.Typeface;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import com.google.inject.Inject;
import com.google.inject.name.Named;
import com.markupartist.android.widget.ActionBar.Action;
public class Profile extends AbstractActivity {
//private static final String TAG = "Profile";
private static final String DF = "MM/dd/yy";
@Inject private LayoutInflater inflater;
@Inject private UserContext userContext;
@Inject private @Named("DINComp-CondBold")Typeface headerTypeface;
@Inject private Cache cache;
@Inject private MyDAO dao;
@InjectView(R.id.actionbar) private CustomActionBar actionBar;
@InjectView(R.id.content) private LinearLayout content;
private ListView list;
private Context context;
@Override
protected String getPageName() {
return "profile";
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.profile);
context = this;
actionBar.setHomeAction(Campaigns.getHomeAction(this));
actionBar.addAction(logoutAction);
// onResume is always call next
}
@Override
protected void onResume() {
super.onResume();
content.removeAllViews();
new MyTask().execute();
}
private final Action logoutAction = new Action(){
@Override
public int getDrawable() {
return R.drawable.action_bar_logout;
}
@Override
public void performAction(View view) {
userContext.clear();
startActivity(new Intent(getApplicationContext(), Campaigns.class).setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP));
}
};
public void findCampaigns(View v){
finish();
}
public static Intent getIntent(Context context) {
return new Intent(context, Profile.class);
}
private final OnItemClickListener itemClickListener = new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> av, View v, int position,
long id) {
Campaign campaign = (Campaign) list.getAdapter().getItem(position);
startActivity(CampaignActions.getIntent(getApplicationContext(), campaign));
}
};
private class MyAdapter extends ArrayAdapter<Campaign> {
private List<UserCampaign> userCampaigns;
private List<Campaign> campaigns;
public MyAdapter(Context context, List<UserCampaign> userCampaigns, List<Campaign> campaigns){
super(context, android.R.layout.simple_list_item_1, campaigns);
this.userCampaigns = userCampaigns;
this.campaigns = campaigns;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
if (v == null) {
v = inflater.inflate(R.layout.profile_campaign_row, null);
}
UserCampaign userCampaign = userCampaigns.get(position);
Campaign campaign = campaigns.get(position);
TextView txtName = (TextView) v.findViewById(R.id.name);
txtName.setTypeface(headerTypeface, Typeface.BOLD);
txtName.setText(campaign.getName());
List<CompletedCampaignAction> completeActions = dao.getCompletedActions(userCampaign.getId());
TextView txtCompleted = (TextView) v.findViewById(R.id.completed);
txtCompleted.setText("Completed: " + completeActions.size() + " of " + campaign.getChallenges().size());
TextView txtEndDate = (TextView) v.findViewById(R.id.end_date);
txtEndDate.setText("Ends: " + new SimpleDateFormat(DF).format(campaign.getEndDate()));
return v;
}
}
private class MyTask extends AbstractFetchCampaignsTask {
public MyTask(){
super(context, userContext, cache, actionBar);
}
@Override
protected void onSuccess() {
List<Campaign> campaigns = new ArrayList<Campaign>();
List<UserCampaign> userCampaigns = new ArrayList<UserCampaign>();
Map<String, UserCampaign> userCampaignsMap = new HashMap<String, UserCampaign>();
List<UserCampaign> allUserCampaigns = dao.findUserCampaigns(new UserContext(context).getUserUid());
for(UserCampaign userCampaign : allUserCampaigns){
userCampaignsMap.put(userCampaign.getCampaignId(), userCampaign);
}
for(Campaign campaign : getCampaigns()){
if(userCampaignsMap.containsKey(campaign.getId())){
campaigns.add(campaign);
userCampaigns.add(userCampaignsMap.get(campaign.getId()));
}
}
if(campaigns.isEmpty()){
content.addView(inflater.inflate(R.layout.profile_no_campaigns, null));
}else{
list = new ListView(Profile.this);
content.addView(list, new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.FILL_PARENT, 1));
list.setOnItemClickListener(itemClickListener);
list.setAdapter(new MyAdapter(context, userCampaigns, campaigns));
}
}
@Override
protected void onError() {}
}
}
|
package org.pentaho.di.ui.spoon;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.commons.vfs.FileObject;
import org.pentaho.di.core.Const;
import org.pentaho.di.core.plugins.BasePluginType;
import org.pentaho.di.core.plugins.JarFileAnnotationPlugin;
import org.pentaho.di.core.plugins.KettlePluginException;
import org.pentaho.di.core.plugins.Plugin;
import org.pentaho.di.core.plugins.PluginFolder;
import org.pentaho.di.core.plugins.PluginFolderInterface;
import org.pentaho.di.core.plugins.PluginInterface;
import org.pentaho.di.core.plugins.PluginTypeInterface;
import org.pentaho.di.core.util.ResolverUtil;
import org.pentaho.di.job.entry.JobEntryInterface;
public class SpoonPluginType {//extends BasePluginType implements PluginTypeInterface {
// private SpoonPluginType() {
// super("SPOONPLUGIN", "Spoon Plugin");
// pluginFolders.add( new PluginFolder("plugins/spoon", false, true) );
// public String getId() {
// // TODO Auto-generated method stub
// return null;
// public String getName() {
// // TODO Auto-generated method stub
// return null;
// public List<PluginFolderInterface> getPluginFolders() {
// // TODO Auto-generated method stub
// return null;
// public void searchPlugins() throws KettlePluginException {
// // TODO Auto-generated method stub
// @Override
// protected List<JarFileAnnotationPlugin> findAnnotatedClassFiles(String annotationClassName) {
// // TODO Auto-generated method stub
// return super.findAnnotatedClassFiles(annotationClassName);
// @Override
// protected List<FileObject> findPluginXmlFiles(String folder) {
// // TODO Auto-generated method stub
// return super.findPluginXmlFiles(folder);
// @Override
// protected void registerAnnotations() throws KettlePluginException {
// ResolverUtil<PluginInterface> resolver = new ResolverUtil<PluginInterface>();
// resolver.findAnnotatedInPackages(SpoonPlugin.class);
// for (Class<?> clazz : resolver.getClasses())
// SpoonPlugin spoonPlugin = clazz.getAnnotation(SpoonPlugin.class);
// handleAnnotatedClass(clazz, spoonPlugin, new ArrayList<String>(), true);
// @Override
// protected void registerNatives() throws KettlePluginException {
// // TODO Auto-generated method stub
// @Override
// protected void registerPluginJars() throws KettlePluginException {
// // TODO Auto-generated method stub
// @Override
// protected void registerXmlPlugins() throws KettlePluginException {
// // TODO Auto-generated method stub
// private void handleAnnotatedClass(Class<?> clazz, SpoonPlugin spoonPlugin, List<String> libraries, boolean nativeJobEntry) throws KettlePluginException {
// // Only one ID for now
// String[] ids = new String[] { spoonPlugin.id(), };
// if (ids.length == 1 && Const.isEmpty(ids[0])) {
// throw new KettlePluginException("No ID specified for plugin with class: "+clazz.getName());
// // The package name to get the descriptions or tool tip from...
// String packageName = spoonPlugin.i18nPackageName();
// if (Const.isEmpty(packageName)) packageName = JobEntryInterface.class.getPackage().getName();
// // An alternative package to get the description or tool tip from...
// String altPackageName = clazz.getPackage().getName();
// // Determine the i18n descriptions of the step description (name), tool tip and category
// String name = getTranslation(spoonPlugin.name(), packageName, altPackageName, clazz);
// String description = getTranslation(spoonPlugin.description(), packageName, altPackageName, clazz);
// String category = getTranslation(spoonPlugin.categoryDescription(), packageName, altPackageName, clazz);
// // Register this step plugin...
// Map<Class, String> classMap = new HashMap<Class, String>();
// classMap.put(SpoonPlugin.class, clazz.getName());
// PluginInterface stepPlugin = new Plugin(ids, this.getClass(), SpoonPlugin.class, category, description, null, null, false, false, classMap, libraries, null);
// registry.registerPlugin(this.getClass(), stepPlugin);
}
|
package squeek.asmhelper;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.HashMap;
import java.util.Map;
import net.minecraft.launchwrapper.LaunchClassLoader;
import org.objectweb.asm.ClassReader;
import org.objectweb.asm.ClassWriter;
import org.objectweb.asm.tree.AbstractInsnNode;
import org.objectweb.asm.tree.ClassNode;
import org.objectweb.asm.tree.InsnList;
import org.objectweb.asm.tree.LabelNode;
import org.objectweb.asm.tree.LocalVariableNode;
import org.objectweb.asm.tree.MethodNode;
import org.objectweb.asm.util.Printer;
import org.objectweb.asm.util.Textifier;
import org.objectweb.asm.util.TraceMethodVisitor;
public class ASMHelper
{
private static Boolean isCauldron = null;
public static InsnComparator insnComparator = new InsnComparator();
public static boolean isCauldron()
{
if (ASMHelper.isCauldron == null)
{
try
{
byte[] bytes = ((LaunchClassLoader) ASMHelper.class.getClassLoader()).getClassBytes("net.minecraftforge.cauldron.api.Cauldron");
ASMHelper.isCauldron = bytes != null;
}
catch (IOException e)
{
e.printStackTrace();
}
}
return ASMHelper.isCauldron;
}
public static ClassNode readClassFromBytes(byte[] bytes)
{
ClassNode classNode = new ClassNode();
ClassReader classReader = new ClassReader(bytes);
classReader.accept(classNode, 0);
return classNode;
}
public static byte[] writeClassToBytes(ClassNode classNode)
{
ClassWriter writer = new ObfRemappingClassWriter(ClassWriter.COMPUTE_MAXS | ClassWriter.COMPUTE_FRAMES);
classNode.accept(writer);
return writer.toByteArray();
}
public static byte[] writeClassToBytesNoDeobf(ClassNode classNode)
{
ClassWriter writer = new ClassWriter(ClassWriter.COMPUTE_MAXS | ClassWriter.COMPUTE_FRAMES);
classNode.accept(writer);
return writer.toByteArray();
}
public static byte[] writeClassToBytesNoDeobfSkipFrames(ClassNode classNode)
{
ClassWriter writer = new ClassWriter(ClassWriter.COMPUTE_MAXS);
classNode.accept(writer);
return writer.toByteArray();
}
public static boolean isLabelOrLineNumber(AbstractInsnNode insn)
{
return insn.getType() == AbstractInsnNode.LABEL || insn.getType() == AbstractInsnNode.LINE;
}
public static AbstractInsnNode getOrFindInstructionOfType(AbstractInsnNode firstInsnToCheck, int type)
{
return getOrFindInstructionOfType(firstInsnToCheck, type, false);
}
public static AbstractInsnNode getOrFindInstructionOfType(AbstractInsnNode firstInsnToCheck, int type, boolean reverseDirection)
{
for (AbstractInsnNode instruction = firstInsnToCheck; instruction != null; instruction = reverseDirection ? instruction.getPrevious() : instruction.getNext())
{
if (instruction.getType() == type)
return instruction;
}
return null;
}
public static AbstractInsnNode getOrFindInstructionWithOpcode(AbstractInsnNode firstInsnToCheck, int opcode)
{
return getOrFindInstructionWithOpcode(firstInsnToCheck, opcode, false);
}
public static AbstractInsnNode getOrFindInstructionWithOpcode(AbstractInsnNode firstInsnToCheck, int opcode, boolean reverseDirection)
{
for (AbstractInsnNode instruction = firstInsnToCheck; instruction != null; instruction = reverseDirection ? instruction.getPrevious() : instruction.getNext())
{
if (instruction.getOpcode() == opcode)
return instruction;
}
return null;
}
public static AbstractInsnNode getOrFindLabelOrLineNumber(AbstractInsnNode firstInsnToCheck)
{
return getOrFindInstruction(firstInsnToCheck, false);
}
public static AbstractInsnNode getOrFindLabelOrLineNumber(AbstractInsnNode firstInsnToCheck, boolean reverseDirection)
{
for (AbstractInsnNode instruction = firstInsnToCheck; instruction != null; instruction = reverseDirection ? instruction.getPrevious() : instruction.getNext())
{
if (isLabelOrLineNumber(instruction))
return instruction;
}
return null;
}
public static AbstractInsnNode getOrFindInstruction(AbstractInsnNode firstInsnToCheck)
{
return getOrFindInstruction(firstInsnToCheck, false);
}
public static AbstractInsnNode getOrFindInstruction(AbstractInsnNode firstInsnToCheck, boolean reverseDirection)
{
for (AbstractInsnNode instruction = firstInsnToCheck; instruction != null; instruction = reverseDirection ? instruction.getPrevious() : instruction.getNext())
{
if (!isLabelOrLineNumber(instruction))
return instruction;
}
return null;
}
public static AbstractInsnNode findFirstInstruction(MethodNode method)
{
return getOrFindInstruction(method.instructions.getFirst());
}
public static AbstractInsnNode findFirstInstructionWithOpcode(MethodNode method, int opcode)
{
return getOrFindInstructionWithOpcode(method.instructions.getFirst(), opcode);
}
public static AbstractInsnNode findLastInstructionWithOpcode(MethodNode method, int opcode)
{
return getOrFindInstructionWithOpcode(method.instructions.getLast(), opcode, true);
}
public static AbstractInsnNode findNextInstruction(AbstractInsnNode instruction)
{
return getOrFindInstruction(instruction.getNext());
}
public static AbstractInsnNode findNextInstructionWithOpcode(AbstractInsnNode instruction, int opcode)
{
return getOrFindInstructionWithOpcode(instruction.getNext(), opcode);
}
public static AbstractInsnNode findNextLabelOrLineNumber(AbstractInsnNode instruction)
{
return getOrFindLabelOrLineNumber(instruction.getNext());
}
public static AbstractInsnNode findPreviousInstruction(AbstractInsnNode instruction)
{
return getOrFindInstruction(instruction.getPrevious(), true);
}
public static AbstractInsnNode findPreviousInstructionWithOpcode(AbstractInsnNode instruction, int opcode)
{
return getOrFindInstructionWithOpcode(instruction.getPrevious(), opcode, true);
}
public static AbstractInsnNode findPreviousLabelOrLineNumber(AbstractInsnNode instruction)
{
return getOrFindLabelOrLineNumber(instruction.getPrevious(), true);
}
public static MethodNode findMethodNodeOfClass(ClassNode classNode, String methodName, String methodDesc)
{
for (MethodNode method : classNode.methods)
{
if (method.name.equals(methodName) && (methodDesc == null || method.desc.equals(methodDesc)))
{
return method;
}
}
return null;
}
public static LabelNode findEndLabel(MethodNode method)
{
for (AbstractInsnNode instruction = method.instructions.getLast(); instruction != null; instruction = instruction.getPrevious())
{
if (instruction instanceof LabelNode)
return (LabelNode) instruction;
}
return null;
}
public static int removeFromInsnListUntil(InsnList insnList, AbstractInsnNode startInclusive, AbstractInsnNode endNotInclusive)
{
AbstractInsnNode insnToRemove = startInclusive;
int numDeleted = 0;
while (insnToRemove != null && insnToRemove != endNotInclusive)
{
numDeleted++;
insnToRemove = insnToRemove.getNext();
insnList.remove(insnToRemove.getPrevious());
}
return numDeleted;
}
public static AbstractInsnNode move(AbstractInsnNode start, int distance)
{
AbstractInsnNode movedTo = start;
for (int i = 0; i < Math.abs(distance) && movedTo != null; i++)
{
movedTo = distance > 0 ? movedTo.getNext() : movedTo.getPrevious();
}
return movedTo;
}
public static boolean instructionsMatch(AbstractInsnNode first, AbstractInsnNode second)
{
return insnComparator.areInsnsEqual(first, second);
}
public static boolean patternMatches(InsnList checkFor, AbstractInsnNode checkAgainst)
{
return checkForPatternAt(checkFor, checkAgainst).getFirst() != null;
}
public static InsnList checkForPatternAt(InsnList checkFor, AbstractInsnNode checkAgainst)
{
InsnList foundInsnList = new InsnList();
boolean firstNeedleFound = false;
for (AbstractInsnNode lookFor = checkFor.getFirst(); lookFor != null;)
{
if (checkAgainst == null)
return new InsnList();
if (isLabelOrLineNumber(lookFor))
{
lookFor = lookFor.getNext();
continue;
}
if (isLabelOrLineNumber(checkAgainst))
{
if (firstNeedleFound)
foundInsnList.add(checkAgainst);
checkAgainst = checkAgainst.getNext();
continue;
}
if (!instructionsMatch(lookFor, checkAgainst))
return new InsnList();
foundInsnList.add(checkAgainst);
lookFor = lookFor.getNext();
checkAgainst = checkAgainst.getNext();
firstNeedleFound = true;
}
return foundInsnList;
}
public static InsnList findAndGetFoundInsnList(AbstractInsnNode haystackStart, InsnList needle)
{
int needleStartOpcode = needle.getFirst().getOpcode();
AbstractInsnNode checkAgainstStart = getOrFindInstructionWithOpcode(haystackStart, needleStartOpcode);
while (checkAgainstStart != null)
{
InsnList found = checkForPatternAt(needle, checkAgainstStart);
if (found.getFirst() != null)
return found;
checkAgainstStart = findNextInstructionWithOpcode(checkAgainstStart, needleStartOpcode);
}
return new InsnList();
}
public static AbstractInsnNode find(InsnList haystack, InsnList needle)
{
return find(haystack.getFirst(), needle);
}
public static AbstractInsnNode find(AbstractInsnNode haystackStart, InsnList needle)
{
if (needle.getFirst() == null)
return null;
InsnList found = findAndGetFoundInsnList(haystackStart, needle);
return found.getFirst();
}
public static AbstractInsnNode find(InsnList haystack, AbstractInsnNode needle)
{
return find(haystack.getFirst(), needle);
}
public static AbstractInsnNode find(AbstractInsnNode haystackStart, AbstractInsnNode needle)
{
InsnList insnList = new InsnList();
insnList.add(needle);
return find(haystackStart, insnList);
}
public static AbstractInsnNode findAndReplace(InsnList haystack, InsnList needle, InsnList replacement)
{
return findAndReplace(haystack, needle, replacement, haystack.getFirst());
}
public static AbstractInsnNode findAndReplace(InsnList haystack, InsnList needle, InsnList replacement, AbstractInsnNode haystackStart)
{
InsnList found = findAndGetFoundInsnList(haystackStart, needle);
if (found.getFirst() != null)
{
haystack.insertBefore(found.getFirst(), replacement);
AbstractInsnNode afterNeedle = found.getLast().getNext();
removeFromInsnListUntil(haystack, found.getFirst(), afterNeedle);
return afterNeedle;
}
return null;
}
public static int findAndReplaceAll(InsnList haystack, InsnList needle, InsnList replacement)
{
return findAndReplaceAll(haystack, needle, replacement, haystack.getFirst());
}
public static int findAndReplaceAll(InsnList haystack, InsnList needle, InsnList replacement, AbstractInsnNode haystackStart)
{
int numReplaced = 0;
while ((haystackStart = findAndReplace(haystack, needle, replacement, haystackStart)) != null)
{
numReplaced++;
}
return numReplaced;
}
public static InsnList cloneInsnList(InsnList source)
{
InsnList clone = new InsnList();
// used to map the old labels to their cloned counterpart
Map<LabelNode, LabelNode> labelMap = new HashMap<LabelNode, LabelNode>();
// build the label map
for (AbstractInsnNode instruction = source.getFirst(); instruction != null; instruction = instruction.getNext())
{
if (instruction instanceof LabelNode)
{
labelMap.put(((LabelNode) instruction), new LabelNode());
}
}
for (AbstractInsnNode instruction = source.getFirst(); instruction != null; instruction = instruction.getNext())
{
clone.add(instruction.clone(labelMap));
}
return clone;
}
public static LocalVariableNode findLocalVariableOfMethod(MethodNode method, String varName, String varDesc)
{
for (LocalVariableNode localVar : method.localVariables)
{
if (localVar.name.equals(varName) && localVar.desc.equals(varDesc))
{
return localVar;
}
}
return null;
}
private static Printer printer = new Textifier();
private static TraceMethodVisitor methodprinter = new TraceMethodVisitor(printer);
public static String getInsnListAsString(InsnList insnList)
{
insnList.accept(methodprinter);
StringWriter sw = new StringWriter();
printer.print(new PrintWriter(sw));
printer.getText().clear();
return sw.toString();
}
public static String getMethodAsString(MethodNode method)
{
method.accept(methodprinter);
StringWriter sw = new StringWriter();
printer.print(new PrintWriter(sw));
printer.getText().clear();
return sw.toString();
}
}
|
package org.pentaho.di.ui.spoon;
public class SpoonPluginType {//extends BasePluginType implements PluginTypeInterface {
// private SpoonPluginType() {
// super("SPOONPLUGIN", "Spoon Plugin");
// pluginFolders.add( new PluginFolder("plugins/spoon", false, true) );
// public String getId() {
// // TODO Auto-generated method stub
// return null;
// public String getName() {
// // TODO Auto-generated method stub
// return null;
// public List<PluginFolderInterface> getPluginFolders() {
// // TODO Auto-generated method stub
// return null;
// public void searchPlugins() throws KettlePluginException {
// // TODO Auto-generated method stub
// @Override
// protected List<JarFileAnnotationPlugin> findAnnotatedClassFiles(String annotationClassName) {
// // TODO Auto-generated method stub
// return super.findAnnotatedClassFiles(annotationClassName);
// @Override
// protected List<FileObject> findPluginXmlFiles(String folder) {
// // TODO Auto-generated method stub
// return super.findPluginXmlFiles(folder);
// @Override
// protected void registerAnnotations() throws KettlePluginException {
// ResolverUtil<PluginInterface> resolver = new ResolverUtil<PluginInterface>();
// resolver.findAnnotatedInPackages(SpoonPlugin.class);
// for (Class<?> clazz : resolver.getClasses())
// SpoonPlugin spoonPlugin = clazz.getAnnotation(SpoonPlugin.class);
// handleAnnotatedClass(clazz, spoonPlugin, new ArrayList<String>(), true);
// @Override
// protected void registerNatives() throws KettlePluginException {
// // TODO Auto-generated method stub
// @Override
// protected void registerPluginJars() throws KettlePluginException {
// // TODO Auto-generated method stub
// @Override
// protected void registerXmlPlugins() throws KettlePluginException {
// // TODO Auto-generated method stub
// private void handleAnnotatedClass(Class<?> clazz, SpoonPlugin spoonPlugin, List<String> libraries, boolean nativeJobEntry) throws KettlePluginException {
// // Only one ID for now
// String[] ids = new String[] { spoonPlugin.id(), };
// if (ids.length == 1 && Const.isEmpty(ids[0])) {
// throw new KettlePluginException("No ID specified for plugin with class: "+clazz.getName());
// // The package name to get the descriptions or tool tip from...
// String packageName = spoonPlugin.i18nPackageName();
// if (Const.isEmpty(packageName)) packageName = JobEntryInterface.class.getPackage().getName();
// // An alternative package to get the description or tool tip from...
// String altPackageName = clazz.getPackage().getName();
// // Determine the i18n descriptions of the step description (name), tool tip and category
// String name = getTranslation(spoonPlugin.name(), packageName, altPackageName, clazz);
// String description = getTranslation(spoonPlugin.description(), packageName, altPackageName, clazz);
// String category = getTranslation(spoonPlugin.categoryDescription(), packageName, altPackageName, clazz);
// // Register this step plugin...
// Map<Class, String> classMap = new HashMap<Class, String>();
// classMap.put(SpoonPlugin.class, clazz.getName());
// PluginInterface stepPlugin = new Plugin(ids, this.getClass(), SpoonPlugin.class, category, description, null, null, false, false, classMap, libraries, null);
// registry.registerPlugin(this.getClass(), stepPlugin);
}
|
package me.exphc.RealisticChat;
import java.util.logging.Logger;
import java.util.Set;
import java.util.HashSet;
import java.util.ArrayList;
import java.util.Random;
import org.bukkit.plugin.java.JavaPlugin;
import org.bukkit.plugin.*;
import org.bukkit.entity.*;
import org.bukkit.event.*;
import org.bukkit.event.player.*;
import org.bukkit.inventory.ItemStack;
import org.bukkit.*;
class RealisticChatListener implements Listener {
RealisticChat plugin;
Random random;
public RealisticChatListener(RealisticChat plugin) {
this.random = new Random();
this.plugin = plugin;
Bukkit.getServer().getPluginManager().registerEvents(this, plugin);
}
@EventHandler(priority = EventPriority.NORMAL)
public void onPlayerChat(PlayerChatEvent event) {
Player sender = event.getPlayer();
String message = event.getMessage();
ArrayList<String> sendInfo = new ArrayList<String>();
int hearingRangeMeters = plugin.getConfig().getInt("hearingRangeMeters", 50);
int scrambleRangeMeters = plugin.getConfig().getInt("scrambleRangeMeters", 25);
// Yelling costs hunger and increases range
int yell = countExclamationMarks(message);
if (yell > 0) {
sendInfo.add("yell="+yell);
int hunger = plugin.getConfig().getInt("hungerPerYell", 1) * yell;
sender.setFoodLevel(sender.getFoodLevel() - hunger);
int delta = plugin.getConfig().getInt("yellRangeIncrease", 10) * yell;
hearingRangeMeters += delta;
scrambleRangeMeters += delta;
}
// Whispering decreases range
int whisper = countParenthesizeNests(message);
if (whisper > 0) {
sendInfo.add("whisper="+whisper);
int delta = plugin.getConfig().getInt("whisperRangeDecrease", 10) * whisper;
hearingRangeMeters -= delta;
scrambleRangeMeters -= delta;
}
// Megaphone
ItemStack senderHeld = sender.getItemInHand();
if (senderHeld != null && senderHeld.getType() == Material.DIAMOND) { // TODO: configurable item
sendInfo.add("mega");
int factor = 2; // TODO: hold more, increase more? but need a cap, base and max
hearingRangeMeters *= factor;
scrambleRangeMeters *= factor;
// TODO: should only increase in a conical volume in front of the player! Like a real megaphone
}
// Log that the player tried to talk
sendInfo.add("r="+hearingRangeMeters+"/"+scrambleRangeMeters);
plugin.log.info("<" + sender.getName() + ": "+joinList(sendInfo)+"> "+message);
// Send to recipients
for (Player recipient: event.getRecipients()) {
ArrayList<String> recvInfo = new ArrayList<String>();
// TODO: special item to hold, to receive all or send to all (infinity compass?)
if (sender.equals(recipient)) {
// Talking to ourselves
// TODO: still scramble? if talking through something
deliverMessage(recipient, sender, message, recvInfo);
continue;
}
if (!sender.getWorld().equals(recipient.getWorld())) {
// Not in this world!
// TODO: cross-world communication device?
continue;
}
double distance = sender.getLocation().distance(recipient.getLocation());
recvInfo.add("d="+distance);
// Talking into walkie-talkie device
if (hasWalkieTalking(sender) && hasWalkieListening(recipient)) {
if (distance < plugin.getConfig().getInt("walkieRange", 1000)) {
ArrayList<String> recvInfoWalkie = new ArrayList<String>(recvInfo);
recvInfoWalkie.add("walkie");
// TODO: reduce clarity if too far away, like with normal chat
// TODO: show as from walkie-talkie, but with callsign of sender?
deliverMessage(recipient, sender, "[via walkie] " + message, recvInfoWalkie);
// also fall through and deliver message locally
}
}
// Limit distance
if (distance > hearingRangeMeters) {
// TODO: earphones? to receive further
continue;
}
if (distance > scrambleRangeMeters) {
// At distances hearingRangeMeters..scrambleRangeMeters (50..25), break up
// with increasing probability the further away they are.
// 24 = perfectly clear
// 25 = slightly garbled
// (distance-25)/50
// 50 = half clear
double noise = (distance - scrambleRangeMeters) / hearingRangeMeters;
double clarity = 1 - noise;
recvInfo.add("clarity="+clarity);
deliverMessage(recipient, sender, breakUpMessage(message, clarity), recvInfo);
} else {
deliverMessage(recipient, sender, message, recvInfo);
}
}
// Deliver the message manually, so we can customize the chat display
event.setCancelled(true);
}
/** Get whether the player has a walkie-talkie ready to talk into.
*/
private boolean hasWalkieTalking(Player player) {
ItemStack held = player.getItemInHand();
return held != null && held.getType() == Material.COMPASS; // TODO: configurable
}
/** Get whether the player has a walkie-talkie ready for listening.
*/
private boolean hasWalkieListening(Player player) {
ItemStack[] contents = player.getInventory().getContents();
final int HOTBAR_SIZE = 9;
// Player can hear walkie if placed anywhere within their hotbar slots (not elsewhere)
for (int i = 0; i < HOTBAR_SIZE; i += 1) {
ItemStack item = contents[i];
if (item != null && item.getType() == Material.COMPASS) {
return true;
}
}
return false;
}
private String joinList(ArrayList<String> list) {
StringBuilder sb = new StringBuilder();
for (String item: list) {
sb.append(item + ",");
}
String s = sb.toString();
if (s.length() == 0) {
return "";
} else {
return s.substring(0, s.length() - 1);
}
}
/** Count number of trailing exclamation marks
*/
private int countExclamationMarks(String message) {
int yell = 0;
while (message.length() > 1 && message.endsWith("!")) {
message = message.substring(0, message.length() - 1);
yell += 1;
}
return yell;
}
/** Count number of nested surrounding parenthesizes
*/
private int countParenthesizeNests(String message) {
int whisper = 0;
while (message.length() > 2 && message.startsWith("(") && message.endsWith(")")) {
message = message.substring(1, message.length() - 1);
whisper += 1;
}
return whisper;
}
/** Randomly "break up" a message as if it was incompletely heard
*
* @param message The clear message
* @param clarity Probability of getting through
* @return The broken up message
*/
private String breakUpMessage(String message, double clarity) {
// Delete random letters
StringBuilder newMessage = new StringBuilder();
// This string character iteration method is cumbersome, but it is
// the most correct, especially if players are using plane 1 characters
int i = 0;
while (i < message.length()) {
int c = message.codePointAt(i);
i += Character.charCount(c);
if (random.nextDouble() < clarity) {
newMessage.appendCodePoint(c);
} else {
newMessage.append(' ');
}
// TODO: third case, dark gray? (barely gets through)
}
return new String(newMessage);
}
private void deliverMessage(Player recipient, Player sender, String message, ArrayList<String> info) {
ChatColor senderColor = (sender.equals(recipient) ? ChatColor.YELLOW : ChatColor.GREEN);
ChatColor messageColor = ChatColor.WHITE;
recipient.sendMessage(senderColor + sender.getDisplayName() + ": " + messageColor + message);
plugin.log.info("[RealisticChat] ("+joinList(info)+") "+sender.getName() + " -> " + recipient.getName() + ": " + message);
}
}
public class RealisticChat extends JavaPlugin {
Logger log = Logger.getLogger("Minecraft");
RealisticChatListener listener;
public void onEnable() {
listener = new RealisticChatListener(this);
}
public void onDisable() {
}
}
|
package com.arun.parallel;
import com.arun.MethodModel;
import java.util.List;
public class Signature {
private String name;
private Class<? extends Object> returnType;
private List<? extends Object> args;
private List<Class<? extends Object>> argTypes;
private Signature() {}
public String getName() {
return name;
}
public Class<? extends Object> getReturnType() {
return returnType;
}
public List<Class<? extends Object>> getArgTypes() {
return argTypes;
}
public List<? extends Object> getArgs() {
return args;
}
public static Signature method(MethodModel methodModel) {
Signature signature = new Signature();
signature.name = methodModel.getName();
signature.returnType = methodModel.getReturnType();
signature.argTypes = methodModel.getArgTypes();
signature.args = methodModel.getArgs();
return signature;
}
}
|
package org.accada.ale.server;
import java.util.ArrayList;
import java.util.Collection;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Observable;
import java.util.Observer;
import java.util.Random;
import java.util.Set;
import org.accada.ale.server.readers.LogicalReader;
import org.accada.ale.server.readers.LogicalReaderManager;
import org.accada.ale.wsdl.ale.epcglobal.ECSpecValidationException;
import org.accada.ale.wsdl.ale.epcglobal.ImplementationException;
import org.accada.ale.wsdl.ale.epcglobal.ImplementationExceptionSeverity;
import org.accada.ale.xsd.ale.epcglobal.ECReport;
import org.accada.ale.xsd.ale.epcglobal.ECReportSpec;
import org.accada.ale.xsd.ale.epcglobal.ECReports;
import org.accada.ale.xsd.ale.epcglobal.ECSpec;
import org.accada.ale.xsd.ale.epcglobal.ECTerminationCondition;
import org.accada.ale.xsd.ale.epcglobal.ECTime;
import org.accada.ale.xsd.ale.epcglobal.ECTimeUnit;
import org.accada.reader.rp.proxy.RPProxyException;
import org.accada.reader.rprm.core.msg.notification.TagType;
import org.apache.log4j.Logger;
/**
* This class represents an event cycle. It collects the tags and manages the reports.
*
* @author regli
* @author sawielan
*/
public class EventCycle implements Runnable, Observer {
/** logger. */
private static final Logger LOG = Logger.getLogger(EventCycle.class);
/** random numbers generator. */
private static final Random rand = new Random(System.currentTimeMillis());
/** ale id. */
private static final String ALEID = "ETHZ-ALE" + rand.nextInt();
/** number of this event cycle. */
private static int number = 0;
/** name of this event cycle. */
private final String name;
/** report generator which contains this event cycle. */
private final ReportsGenerator generator;
/** last event cycle of the same ec specification. */
//private final EventCycle lastEventCycle;
/** thread. */
private final Thread thread;
/** ec specfication for this event cycle. */
private final ECSpec spec;
/** set of logical readers which deliver tags for this event cycle. */
private final Set<LogicalReader> logicalReaders = new HashSet<LogicalReader>();
/** set of reports for this event cycle. */
private final Set<Report> reports = new HashSet<Report>();
/** set of tags for this event cycle. */
private Set<Tag> tags = new HashSet<Tag>();
/** this set stores the tags from the previous EventCycle run. */
private Set<Tag> lastEventCycleTags = null;
/** indicates if this event cycle is terminated or not .*/
private boolean isTerminated = false;
/** the duration of collecting tags for this event cycle in milliseconds. */
private long durationValue;
/** the total time this event cycle runs in milliseconds. */
private long totalTime;
/** the termination condition of this event cycle. */
private ECTerminationCondition terminationCondition = null;
/** flags the eventCycle whether it shall run several times or not. */
private boolean running = false;
/** flags whether the EventCycle is currently not accepting tags. */
private boolean acceptTags = false;
/**
* Constructor sets parameter and starts thread.
*
* @param generator to which this event cycle belongs to
* @throws ImplementationException if an implementation exception occurs
*/
public EventCycle(ReportsGenerator generator) throws ImplementationException {
// set name
name = generator.getName() + "_" + number++;
// set ReportGenerator
this.generator = generator;
// set spec
spec = generator.getSpec();
// get report specs and create a report for each spec
for (ECReportSpec reportSpec : spec.getReportSpecs()) {
// add report spec and report to reports
reports.add(new Report(reportSpec, this));
}
// init BoundarySpec values
durationValue = getDurationValue();
setAcceptTags(false);
// get LogicalReaderStubs
if (spec.getLogicalReaders() != null) {
String[] logicalReaderNames = spec.getLogicalReaders();
for (String logicalReaderName : logicalReaderNames) {
LogicalReader logicalReader = LogicalReaderManager.getLogicalReader(logicalReaderName);
if (logicalReader != null) {
logicalReaders.add(logicalReader);
}
}
}
for (LogicalReader logicalReader : logicalReaders) {
// subscribe this event cycle to the logical readers
logicalReader.addObserver(this);
}
// create and start Thread
thread = new Thread(this);
thread.start();
LOG.debug("New EventCycle '" + name + "' created.");
}
/**
* This method returns the ec reports.
*
* @return ec reports
* @throws ECSpecValidationException if the tags of the report are not valid
* @throws ImplementationException if an implementation exception occures
*/
public ECReports getECReports() throws ECSpecValidationException, ImplementationException {
// create ECReports
ECReports reports = new ECReports();
// set spec name
reports.setSpecName(generator.getName());
// set date
reports.setDate(new GregorianCalendar());
// set ale id
reports.setALEID(ALEID);
// set total time in milliseconds
reports.setTotalMilliseconds(totalTime);
// set termination condition
reports.setTerminationCondition(terminationCondition);
// set spec
if (spec.isIncludeSpecInReports()) {
reports.setECSpec(spec);
}
// set reports
reports.setReports(getReportList());
return reports;
}
/**
* This method return all tags of this event cylce.
*
* @return set of tags
*/
public synchronized Set<Tag> getTags() {
return tags;
}
/**
* This method adds a tag to this event cycle.
*
* @param tag to add
* @throws ImplementationException if an implementation exception occures
* @throws ECSpecValidationException if the tag is not valid
*/
public synchronized void addTag(Tag tag) throws ImplementationException, ECSpecValidationException {
if (!isAcceptingTags()) {
return;
}
// add event only if EventCycle is still running
if (thread.isAlive()) {
LOG.debug("EventCycle '" + name + "' add Tag '" + tag.getTagID() + "'.");
for (Tag atag : tags) {
// do not add the tag it is already in the list
if (atag.equals(tag)) {
return;
}
}
// add tag to tags
tags.add(tag);
// iterate over reports and add event
for (Report report : reports) {
report.addTag(tag);
}
}
}
/**
* compatibility reasons.
* @param tag to add
* @throws ImplementationException if an implementation exception occures
* @throws ECSpecValidationException if the tag is not valid
*/
public void addTag(TagType tag) throws ImplementationException, ECSpecValidationException {
if (!isAcceptingTags()) {
return;
}
Tag newTag = new Tag();
newTag.setTagID(tag.getTagIDAsPureURI());
addTag(newTag);
}
/**
* implementation of the observer interface for tags.
* @param o an observable object that triggered the update
* @param arg the arguments passed by the observable
*/
public synchronized void update(Observable o, Object arg) {
if (!isAcceptingTags()) {
return;
}
if (arg instanceof Tag) {
Tag tag = (Tag) arg;
LOG.debug("EventCycle: received tag :");
//tag.prettyPrint(LOG);
try {
addTag(tag);
} catch (ImplementationException ie) {
ie.printStackTrace();
} catch (ECSpecValidationException ive) {
ive.printStackTrace();
}
}
}
/**
* This method stops the thread.
*/
public void stop() {
// unsubscribe this event cycle from logical readers
for (LogicalReader logicalReader : logicalReaders) {
//logicalReader.unsubscribeEventCycle(this);
logicalReader.deleteObserver(this);
}
if (thread.isAlive()) {
thread.interrupt();
// stop EventCycle
LOG.debug("EventCycle '" + name + "' stopped.");
}
isTerminated = true;
synchronized (this) {
this.notifyAll();
}
}
/**
* This method returns the name of this event cycle.
*
* @return name of event cycle
*/
public String getName() {
return name;
}
/**
* This method indicates if this event cycle is terminated or not.
*
* @return true if this event cycle is terminated and false otherwise
*/
public boolean isTerminated() {
return isTerminated;
}
/**
* This method is the main loop of the event cycle in which the tags will be collected.
* At the end the reports will be generated and the subscribers will be notified.
*/
public void run() {
// wait for the start
// running will be set by the ReportsGenerator when the EventCycle
// has a subscriber
if (!running) {
synchronized (this) {
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
while (running) {
LOG.debug("starting EventCycle");
// set start time
long startTime = System.currentTimeMillis();
// accept tags
setAcceptTags(true);
try {
if (durationValue > 0) {
// if durationValue is specified and larger than zero, wait for notify or durationValue elapsed.
synchronized (this) {
this.wait(Math.max(1, durationValue - (System.currentTimeMillis() - startTime)));
terminationCondition = ECTerminationCondition.DURATION;
}
} else {
// if durationValue is not specified or smaller than zero, wait for notify.
synchronized (this) {
this.wait();
}
}
} catch (InterruptedException e) {
// if Thread is stopped with method stop(), then return without notify subscribers.
return;
}
// dont accept tags anymore
setAcceptTags(false);
// get reports
try {
ECReports ecReports = getECReports();
// notifySubscribers
generator.notifySubscribers(ecReports);
// store the current tags into the old tags
lastEventCycleTags = tags;
tags = new HashSet<Tag>();
} catch (ECSpecValidationException e) {
LOG.error("Could not create ECReports (" + e.getMessage() + ")");
} catch (ImplementationException e) {
LOG.error("Could not create ECReports (" + e.getMessage() + ")");
}
// compute total time
totalTime = System.currentTimeMillis() - startTime;
LOG.debug("EventCycle finished");
try {
synchronized (this) {
this.wait();
}
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
// stop EventCycle
stop();
}
/**
* starts this EventCycle.
*/
public void launch() {
this.running = true;
synchronized (this) {
this.notifyAll();
}
}
// private methods
/**
* This method returns all reports of this event cycle as ec reports.
*
* @return array of ec reports
* @throws ECSpecValidationException if a tag of this report is not valid
* @throws ImplementationException if an implementation exception occures
*/
private ECReport[] getReportList() throws ECSpecValidationException, ImplementationException {
ArrayList<ECReport> ecReports = new ArrayList<ECReport>();
for (Report report : reports) {
ecReports.add(report.getECReport());
}
return ecReports.toArray(new ECReport[reports.size()]);
}
/**
* This method returns the duration value extracted from the ec specification.
*
* @return duration value in milliseconds
* @throws ImplementationException if an implementation exception occurs
*/
private long getDurationValue() throws ImplementationException {
ECTime duration = spec.getBoundarySpec().getDuration();
if (duration != null) {
if (duration.getUnit() == ECTimeUnit.MS) {
return duration.get_value();
} else {
throw new ImplementationException("The only ECTimeUnit allowed is milliseconds (MS).",
ImplementationExceptionSeverity.ERROR);
}
}
return -1;
}
/**
* returns the set of tags from the previous EventCycle run.
* @return a set of tags from the previous EventCycle run
*/
public Set<Tag> getLastEventCycleTags() {
return lastEventCycleTags;
}
/**
* tells whether the ec accepts tags.
* @return boolean telling whether the ec accepts tags
*/
private boolean isAcceptingTags() {
return acceptTags;
}
/**
* sets the flag acceptTags to the passed boolean value.
* @param acceptTags sets the flag acceptTags to the passed boolean value.
*/
private void setAcceptTags(boolean acceptTags) {
this.acceptTags = acceptTags;
}
}
|
package edu.umd.cs.findbugs;
import org.apache.bcel.classfile.*;
import org.apache.bcel.generic.*;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.Branch;
import edu.umd.cs.findbugs.visitclass.BetterVisitor;
import edu.umd.cs.findbugs.visitclass.DismantleBytecode;
/**
* A BugAnnotation that records a range of source lines
* in a class.
*
* @see BugAnnotation
* @author David Hovemeyer
*/
public class SourceLineAnnotation implements BugAnnotation {
private static final String DEFAULT_ROLE = "SOURCE_LINE_DEFAULT";
/**
* String returned if the source file is unknown.
* This must match what BCEL uses when the source file is unknown.
*/
public static final String UNKNOWN_SOURCE_FILE = "<Unknown>";
private String description;
private String className;
private String sourceFile;
private int startLine;
private int endLine;
private int startBytecode;
private int endBytecode;
/**
* Constructor.
* @param className the class to which the line number(s) refer
* @param sourceFile the name of the source file
* @param startLine the first line (inclusive)
* @param endLine the ending line (inclusive)
* @param startBytecode the first bytecode offset (inclusive)
* @param endBytecode the end bytecode offset (inclusive)
*/
public SourceLineAnnotation(String className, String sourceFile, int startLine, int endLine,
int startBytecode, int endBytecode) {
if (className == null) throw new IllegalArgumentException("class name is null");
if (sourceFile == null) throw new IllegalArgumentException("source file is null");
this.description = DEFAULT_ROLE;
this.className = className;
this.sourceFile = sourceFile;
this.startLine = startLine;
this.endLine = endLine;
this.startBytecode = startBytecode;
this.endBytecode = endBytecode;
}
/**
* Factory method to create an unknown source line annotation.
* @param className the class name
* @return the SourceLineAnnotation
*/
public static SourceLineAnnotation createUnknown(String className, String sourceFile) {
return createUnknown(className, sourceFile, -1, -1);
}
public static SourceLineAnnotation createUnknown(String className, String sourceFile, int startBytecode, int endBytecode) {
SourceLineAnnotation result = new SourceLineAnnotation(className, sourceFile, -1, -1, startBytecode, endBytecode);
result.setDescription("SOURCE_LINE_UNKNOWN");
return result;
}
/**
* Factory method for creating a source line annotation describing
* an entire method.
* @param visitor a BetterVisitor which is visiting the method
* @return the SourceLineAnnotation
*/
public static SourceLineAnnotation fromVisitedMethod(BetterVisitor visitor) {
LineNumberTable lineNumberTable = getLineNumberTable(visitor);
String className = visitor.getBetterClassName();
String sourceFile = visitor.getSourceFile();
Code code = visitor.getMethod().getCode();
int codeSize = (code != null) ? code.getCode().length : 0;
if (lineNumberTable == null)
return createUnknown(className, sourceFile, 0, codeSize - 1);
return forEntireMethod(className, sourceFile, lineNumberTable, codeSize);
}
/**
* Factory method for creating a source line annotation describing
* an entire method.
* @param methodGen the method being visited
* @return the SourceLineAnnotation, or null if we do not have line number information
* for the method
*/
public static SourceLineAnnotation fromVisitedMethod(MethodGen methodGen, String sourceFile) {
LineNumberTable lineNumberTable = methodGen.getLineNumberTable(methodGen.getConstantPool());
String className = methodGen.getClassName();
int codeSize = methodGen.getInstructionList().getLength();
if (lineNumberTable == null)
return createUnknown(className, sourceFile, 0, codeSize - 1);
return forEntireMethod(className, sourceFile, lineNumberTable, codeSize);
}
private static SourceLineAnnotation forEntireMethod(String className, String sourceFile,
LineNumberTable lineNumberTable, int codeSize) {
LineNumber[] table = lineNumberTable.getLineNumberTable();
if (table != null && table.length > 0) {
LineNumber first = table[0];
LineNumber last = table[table.length-1];
return new SourceLineAnnotation(className, sourceFile, first.getLineNumber(), last.getLineNumber(),
0, codeSize - 1);
} else {
return createUnknown(className, sourceFile, 0, codeSize - 1);
}
}
/**
* Factory method for creating a source line annotation describing the
* source line number for the instruction being visited by given visitor.
* @param visitor a BetterVisitor which is visiting the method
* @param pc the bytecode offset of the instruction in the method
* @return the SourceLineAnnotation, or null if we do not have line number information
* for the instruction
*/
public static SourceLineAnnotation fromVisitedInstruction(BetterVisitor visitor, int pc) {
return fromVisitedInstructionRange(visitor, pc, pc);
}
/**
* Factory method for creating a source line annotation describing the
* source line numbers for a range of instructions in the method being
* visited by the given visitor.
* @param visitor a BetterVisitor which is visiting the method
* @param startPC the bytecode offset of the start instruction in the range
* @param endPC the bytecode offset of the end instruction in the range
* @return the SourceLineAnnotation, or null if we do not have line number information
* for the instruction
*/
public static SourceLineAnnotation fromVisitedInstructionRange(BetterVisitor visitor, int startPC, int endPC) {
LineNumberTable lineNumberTable = getLineNumberTable(visitor);
String className = visitor.getBetterClassName();
String sourceFile = visitor.getSourceFile();
if (lineNumberTable == null)
return createUnknown(className, sourceFile, startPC, endPC);
int startLine = lineNumberTable.getSourceLine(startPC);
int endLine = lineNumberTable.getSourceLine(endPC);
return new SourceLineAnnotation(className, sourceFile, startLine, endLine, startPC, endPC);
}
/**
* Factory method for creating a source line annotation describing the
* source line number for the instruction being visited by given visitor.
* @param visitor a DismantleBytecode visitor which is visiting the method
* @return the SourceLineAnnotation, or null if we do not have line number information
* for the instruction
*/
public static SourceLineAnnotation fromVisitedInstruction(DismantleBytecode visitor) {
return fromVisitedInstruction(visitor, visitor.getPC());
}
/**
* Factory method for creating a source line annotation describing the
* source line number for a visited instruction.
* @param methodGen the MethodGen object representing the method
* @param handle the InstructionHandle containing the visited instruction
* @return the SourceLineAnnotation, or null if we do not have line number information
* for the instruction
*/
public static SourceLineAnnotation fromVisitedInstruction(MethodGen methodGen, String sourceFile, InstructionHandle handle) {
LineNumberTable table = methodGen.getLineNumberTable(methodGen.getConstantPool());
String className = methodGen.getClassName();
int bytecodeOffset = handle.getPosition();
if (table == null)
return createUnknown(className, sourceFile, bytecodeOffset, bytecodeOffset);
int lineNumber = table.getSourceLine(handle.getPosition());
return new SourceLineAnnotation(className, sourceFile, lineNumber, lineNumber, bytecodeOffset, bytecodeOffset);
}
/**
* Factory method for creating a source line annotation describing
* the source line numbers for a range of instruction in a method.
* @param methodGen the method
* @param start the start instruction
* @param end the end instruction (inclusive)
*/
public static SourceLineAnnotation fromVisitedInstructionRange(MethodGen methodGen, String sourceFile, InstructionHandle start, InstructionHandle end) {
LineNumberTable lineNumberTable = methodGen.getLineNumberTable(methodGen.getConstantPool());
String className = methodGen.getClassName();
if (lineNumberTable == null)
return createUnknown(className, sourceFile, start.getPosition(), end.getPosition());
int startLine = lineNumberTable.getSourceLine(start.getPosition());
int endLine = lineNumberTable.getSourceLine(end.getPosition());
return new SourceLineAnnotation(className, sourceFile, startLine, endLine, start.getPosition(), end.getPosition());
}
private static LineNumberTable getLineNumberTable(BetterVisitor visitor) {
Code code = visitor.getMethod().getCode();
if (code == null)
return null;
return code.getLineNumberTable();
}
/**
* Get the class name.
*/
public String getClassName() {
return className;
}
/**
* Get the source file name.
*/
public String getSourceFile() {
return sourceFile;
}
/**
* Is the source file known?
*/
public boolean isSourceFileKnown() {
return !sourceFile.equals(UNKNOWN_SOURCE_FILE);
}
/**
* Set the source file name.
* @param sourceFile the source file name
*/
public void setSourceFile(String sourceFile) {
this.sourceFile = sourceFile;
}
/**
* Get the package name.
*/
public String getPackageName() {
int lastDot = className.lastIndexOf('.');
if (lastDot < 0)
return "";
else
return className.substring(0, lastDot);
}
/**
* Get the start line (inclusive).
*/
public int getStartLine() {
return startLine;
}
/**
* Get the ending line (inclusive).
*/
public int getEndLine() {
return endLine;
}
/**
* Get start bytecode (inclusive).
*/
public int getStartBytecode() {
return startBytecode;
}
/**
* Get end bytecode (inclusive).
*/
public int getEndBytecode() {
return endBytecode;
}
/**
* Is this an unknown source line annotation?
*/
public boolean isUnknown() {
return startLine < 0 || endLine < 0;
}
public void accept(BugAnnotationVisitor visitor) {
visitor.visitSourceLineAnnotation(this);
}
public String format(String key) {
if (key.equals("")) {
StringBuffer buf = new StringBuffer();
buf.append(sourceFile);
appendLines(buf);
return buf.toString();
} else if (key.equals("full")) {
StringBuffer buf = new StringBuffer();
String pkgName = getPackageName();
if (!pkgName.equals("")) {
buf.append(pkgName.replace('.','/'));
buf.append('/');
}
buf.append(sourceFile);
appendLines(buf);
return buf.toString();
} else
throw new IllegalStateException("Unknown format key " + key);
}
private void appendLines(StringBuffer buf) {
buf.append(":[");
if (startLine == endLine) {
buf.append("line ");
buf.append(startLine);
} else {
buf.append("lines ");
buf.append(startLine);
buf.append('-');
buf.append(endLine);
}
buf.append(']');
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String toString() {
String pattern = I18N.instance().getAnnotationDescription(description);
FindBugsMessageFormat format = new FindBugsMessageFormat(pattern);
return format.format(new BugAnnotation[]{this});
}
public int compareTo(BugAnnotation o) {
if (!(o instanceof SourceLineAnnotation)) // All BugAnnotations must be comparable
return this.getClass().getName().compareTo(o.getClass().getName());
SourceLineAnnotation other = (SourceLineAnnotation) o;
int cmp = className.compareTo(other.className);
if (cmp != 0)
return cmp;
cmp = startLine - other.startLine;
if (cmp != 0)
return cmp;
return endLine - other.endLine;
}
public int hashCode() {
return className.hashCode() + startLine + endLine;
}
public boolean equals(Object o) {
if (!(o instanceof SourceLineAnnotation))
return false;
SourceLineAnnotation other = (SourceLineAnnotation) o;
return className.equals(other.className)
&& startLine == other.startLine
&& endLine == other.endLine;
}
private static final String ELEMENT_NAME = "SourceLine";
private static class SourceLineAnnotationXMLTranslator implements XMLTranslator {
public String getElementName() {
return ELEMENT_NAME;
}
public XMLConvertible fromElement(Element element) throws DocumentException {
try {
String className = element.attributeValue("classname");
String sourceFile = element.attributeValue("sourcefile");
if (sourceFile == null)
sourceFile = UNKNOWN_SOURCE_FILE;
int startLine = Integer.parseInt(element.attributeValue("start"));
int endLine = Integer.parseInt(element.attributeValue("end"));
int startBytecode = -1, endBytecode = -1;
if (element.attributeValue("startBytecode") != null)
startBytecode = Integer.parseInt(element.attributeValue("startBytecode"));
if (element.attributeValue("endBytecode") != null)
endBytecode = Integer.parseInt(element.attributeValue("endBytecode"));
SourceLineAnnotation annotation = new SourceLineAnnotation(className, sourceFile, startLine, endLine,
startBytecode, endBytecode);
String role = element.attributeValue("role");
if (role != null)
annotation.setDescription(role);
return annotation;
} catch (NumberFormatException e) {
throw new DocumentException("Invalid attribute value: " + e.toString());
}
}
}
static int dummy; // XXX: needed to allow BugCollection to force static init in JDK 1.5
static {
XMLTranslatorRegistry.instance().registerTranslator(new SourceLineAnnotationXMLTranslator());
}
public Element toElement(Branch parent) {
Element element = parent.addElement(ELEMENT_NAME)
.addAttribute("classname", getClassName())
.addAttribute("start", String.valueOf(getStartLine()))
.addAttribute("end", String.valueOf(getEndLine()))
.addAttribute("startBytecode", String.valueOf(getStartBytecode()))
.addAttribute("endBytecode", String.valueOf(getEndBytecode()));
if (isSourceFileKnown())
element.addAttribute("sourcefile", sourceFile);
String role = getDescription();
if (!role.equals(DEFAULT_ROLE))
element.addAttribute("role", getDescription());
return element;
}
}
// vim:ts=4
|
package edu.umd.cs.findbugs.detect;
import edu.umd.cs.findbugs.*;
import edu.umd.cs.findbugs.ba.XFactory;
import edu.umd.cs.findbugs.ba.XMethod;
import org.apache.bcel.classfile.*;
public class TestingGround extends BytecodeScanningDetector {
private static final boolean active = Boolean.getBoolean("findbugs.tg.active");
BugReporter bugReporter;
OpcodeStack stack = new OpcodeStack();
public TestingGround(BugReporter bugReporter) {
this.bugReporter = bugReporter;
}
@Override
public Object clone() throws CloneNotSupportedException {
return super.clone();
}
boolean isInnerClass = false;
@Override
public void visit(JavaClass obj) {
isInnerClass = false;
String name = getClassName();
int i = name.lastIndexOf('$');
if (i >= 0 && i + 1 < name.length()) {
isInnerClass = Character.isDigit(name.charAt(i + 1));
}
}
boolean definedInThisClassOrSuper(JavaClass clazz, String method)
throws ClassNotFoundException {
if (clazz == null)
return false;
System.out.println("Checking to see if " + method + " is defined in " + clazz.getClassName());
for (Method m : clazz.getMethods())
if (method.equals(m.getName()+":"+m.getSignature()))
return true;
return definedInSuperClassOrInterface(clazz, method);
}
boolean definedInSuperClassOrInterface(JavaClass clazz, String method)
throws ClassNotFoundException {
if (clazz == null)
return false;
JavaClass superClass = clazz.getSuperClass();
if (definedInThisClassOrSuper(superClass, method))
return true;
for (JavaClass i : clazz.getInterfaces())
if (definedInThisClassOrSuper(i, method))
return true;
return false;
}
@Override
public void visit(Method obj) {
try {
if (isInnerClass) {
if (getMethodName().equals("<init>")) return;
JavaClass clazz = getThisClass();
XMethod xmethod = XFactory.createXMethod(clazz, obj);
if (!definedInSuperClassOrInterface(clazz, obj.getName()+":"+obj.getSignature()))
System.out.println("XXXX");
}
} catch (ClassNotFoundException e) {
System.out.println("FOFO");
}
}
@Override
public void visit(Code obj) {
// unless active, don't bother dismantling bytecode
if (false && active) {
// System.out.println("TestingGround: " +
// getFullyQualifiedMethodName());
stack.resetForMethodEntry(this);
super.visit(obj);
}
}
@Override
public void sawOpcode(int seen) {
stack.mergeJumps(this);
if (seen == INVOKESTATIC && getNameConstantOperand().equals("forName")
&& getClassConstantOperand().equals("java/lang/Class")
&& getSigConstantOperand().equals("(Ljava/lang/String;)Ljava/lang/Class;"))
if (stack.getStackDepth() == 0)
System.out.println("empty stack");
else {
OpcodeStack.Item item = stack.getStackItem(0);
Object constantValue = item.getConstant();
if (constantValue != null && constantValue instanceof String)
System.out.println("XXYYZ: " + getFullyQualifiedMethodName()
+ " Class.forName(" + constantValue + ")");
else
System.out.println("XXYYZ: " + getFullyQualifiedMethodName()
+ " Class.forName(???)");
}
stack.sawOpcode(this, seen);
}
}
|
package work1;
import java.io.IOException;
import java.util.Scanner;
public class work1 {
public static void main(String args[])
{
System.out.println("31-100:");
Scanner scanner = new Scanner(System.in);
int rightInputCount = 0;
int input;
while(rightInputCount < 3)
{
try
{
input = scanner.nextInt();
}
catch(Exception ex)
{
System.out.println("ʽ");
scanner.nextLine();
continue;
}
if(input > 100 || input < 1)
{
System.out.println("Χ");
continue;
}
++rightInputCount;
System.out.println("Ѿȷ" + rightInputCount + "");
}
System.out.println("!");
}
}
|
package gibstick.bukkit.discosheep;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import org.bukkit.Color;
import org.bukkit.DyeColor;
import org.bukkit.Location;
import org.bukkit.Sound;
import org.bukkit.World;
import org.bukkit.entity.EntityType;
import org.bukkit.entity.Firework;
import org.bukkit.entity.Player;
import org.bukkit.entity.Sheep;
import org.bukkit.FireworkEffect;
import org.bukkit.FireworkEffect.Builder;
import org.bukkit.inventory.meta.FireworkMeta;
import org.bukkit.util.Vector;
/**
*
* @author Georgiy
*/
public class DiscoParty {
private DiscoSheep ds;
private Player player;
private ArrayList<Sheep> sheepList = new ArrayList<Sheep>();
private int duration, frequency = 20;
private int numSheep = 5;
static int defaultDuration = 300; // ticks for entire party
static int defaultPeriod = 10; // ticks per state change
static int defaultRadius = 5;
static int defaultSheep = 10;
static float defaultSheepJump = 0.5f;
static int maxDuration = 2400; // 120 seconds
static int maxSheep = 100;
static int maxRadius = 100;
static int minPeriod = 5; // 0.25 seconds
static int maxPeriod = 40; // 2.0 seconds
private boolean doFireworks = false;
private boolean doJump = true;
private int state = 0;
private DiscoUpdater updater;
private static final DyeColor[] discoColours = {
DyeColor.RED,
DyeColor.ORANGE,
DyeColor.YELLOW,
DyeColor.GREEN,
DyeColor.BLUE,
DyeColor.LIGHT_BLUE,
DyeColor.PINK,
DyeColor.MAGENTA,
DyeColor.LIME,
DyeColor.CYAN,
DyeColor.PURPLE
};
public DiscoParty(DiscoSheep parent, Player player) {
this.ds = parent;
this.player = player;
}
List<Sheep> getSheep() {
return sheepList;
}
void spawnSheep(World world, Location loc) {
Sheep newSheep = (Sheep) world.spawnEntity(loc, EntityType.SHEEP);
newSheep.setMaxHealth(10000);
newSheep.setHealth(10000);
newSheep.setColor(discoColours[(int) Math.round(Math.random() * (discoColours.length - 1))]);
newSheep.setTarget(player);
newSheep.setBreed(false);
getSheep().add(newSheep);
}
// Spawn some number of sheep next to given player
void spawnSheep(int num, int sheepSpawnRadius) {
Location loc;
World world = player.getWorld();
for (int i = 0; i < num; i++) {
double x, y, z;
// random x and z coordinates within a 5 block radius
// safe y-coordinate
x = -sheepSpawnRadius + (Math.random() * ((sheepSpawnRadius * 2) + 1)) + player.getLocation().getX();
z = -sheepSpawnRadius + (Math.random() * ((sheepSpawnRadius * 2) + 1)) + player.getLocation().getZ();
y = world.getHighestBlockYAt((int) x, (int) z);
loc = new Location(world, x, y, z);
spawnSheep(world, loc);
}
}
// Mark all sheep in the sheep array for removal, then clear the array
void removeAllSheep() {
for (Sheep sheep : getSheep()) {
sheep.setHealth(0);
sheep.remove();
}
getSheep().clear();
}
// Set a random colour for all sheep in array
void randomizeSheepColour(Sheep sheep) {
sheep.setColor(discoColours[(int) Math.round(Math.random() * (discoColours.length - 1))]);
}
void jumpSheep(Sheep sheep) {
Vector orgVel = sheep.getVelocity();
Vector newVel = (new Vector()).copy(orgVel);
newVel.add(new Vector(0, defaultSheepJump, 0));
sheep.setVelocity(newVel);
}
private Color getColor(int i) {
Color c = null;
if (i == 1) {
c = Color.AQUA;
}
if (i == 2) {
c = Color.BLACK;
}
if (i == 3) {
c = Color.BLUE;
}
if (i == 4) {
c = Color.FUCHSIA;
}
if (i == 5) {
c = Color.GRAY;
}
if (i == 6) {
c = Color.GREEN;
}
if (i == 7) {
c = Color.LIME;
}
if (i == 8) {
c = Color.MAROON;
}
if (i == 9) {
c = Color.NAVY;
}
if (i == 10) {
c = Color.OLIVE;
}
if (i == 11) {
c = Color.ORANGE;
}
if (i == 12) {
c = Color.PURPLE;
}
if (i == 13) {
c = Color.RED;
}
if (i == 14) {
c = Color.SILVER;
}
if (i == 15) {
c = Color.TEAL;
}
if (i == 16) {
c = Color.WHITE;
}
if (i == 17) {
c = Color.YELLOW;
}
return c;
}
void updateAllSheep() {
for (Sheep sheep : getSheep()) {
randomizeSheepColour(sheep);
if (state % 8 == 0) { // HA HA IT LOOKS LIKE A PENIS
if (doFireworks) {
spawnRandomFireworkAtSheep(sheep);
}
if(doJump){
jumpSheep(sheep);
}
}
}
}
void playSounds() {
player.playSound(player.getLocation(), Sound.NOTE_BASS_DRUM, 1.0f, 1.0f);
if (this.state % 2 == 0) {
player.playSound(player.getLocation(), Sound.NOTE_SNARE_DRUM, 1.0f, 1.0f);
}
if (this.state % 4 == 0) {
player.playSound(player.getLocation(), Sound.NOTE_STICKS, 1.0f, 1.0f);
}
player.playSound(player.getLocation(), Sound.BURP, 0.5f, (float) Math.random() + 1);
}
void randomizeFirework(Firework firework) {
Random r = new Random();
Builder effect = FireworkEffect.builder();
FireworkMeta meta = firework.getFireworkMeta();
// construct [1, 3] random colours
int numColours = r.nextInt(3) + 1;
Color[] colourArray = new Color[numColours];
for (int i = 0; i < numColours; i++) {
colourArray[i] = getColor(r.nextInt(17) + 1);
}
// randomize effects
effect.withColor(colourArray);
effect.flicker(r.nextDouble() < 0.5);
effect.trail(r.nextDouble() < 0.5);
effect.with(FireworkEffect.Type.values()[r.nextInt(FireworkEffect.Type.values().length)]);
// set random effect and randomize power
meta.addEffect(effect.build());
meta.setPower(r.nextInt(2));
// apply it to the given firework
firework.setFireworkMeta(meta);
}
void spawnRandomFireworkAtSheep(Sheep sheep) {
Firework firework = (Firework) sheep.getWorld().spawnEntity(sheep.getEyeLocation(), EntityType.FIREWORK);
randomizeFirework(firework);
}
void update() {
if (duration > 0) {
updateAllSheep();
playSounds();
duration -= frequency;
this.scheduleUpdate();
this.state++;
} else {
this.stopDisco();
}
}
void scheduleUpdate() {
updater = new DiscoUpdater(this);
updater.runTaskLater(ds, this.frequency);
}
void startDisco(int duration, int sheepAmount, int radius, int frequency, boolean fireworks) {
if (this.duration > 0) {
stopDisco();
}
this.doFireworks = fireworks;
this.spawnSheep(sheepAmount, radius);
this.frequency = frequency;
this.duration = duration;
this.scheduleUpdate();
ds.getPartyMap().put(this.player.getName(), this);
}
void stopDisco() {
removeAllSheep();
this.duration = 0;
if (updater != null) {
updater.cancel();
}
updater = null;
ds.getPartyMap().remove(this.player.getName());
}
}
|
package gibstick.bukkit.discosheep;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.bukkit.entity.Player;
import org.bukkit.plugin.java.JavaPlugin;
public final class DiscoSheep extends JavaPlugin {
Map<String, DiscoParty> parties = new HashMap<String, DiscoParty>();
private BaaBaaBlockSheepEvents blockEvents = new BaaBaaBlockSheepEvents(this);
@Override
public void onEnable() {
getCommand("ds").setExecutor(new DiscoSheepCommandExecutor(this));
getServer().getPluginManager().registerEvents(blockEvents, this);
}
@Override
public void onDisable() {
this.stopAllParties();
}
public synchronized Map<String, DiscoParty> getPartyMap() {
return this.parties;
}
public synchronized List<DiscoParty> getParties() {
return new ArrayList(this.getPartyMap().values());
}
public void stopParty(String name) {
if (this.hasParty(name)) {
this.getParty(name).stopDisco();
}
}
public void stopAllParties(){
for(DiscoParty party :this.getParties()){
party.stopDisco();
}
}
public boolean hasParty(String name) {
return this.getPartyMap().containsKey(name);
}
public DiscoParty getParty(String name) {
return this.getPartyMap().get(name);
}
public void removeParty(String name) {
if (this.hasParty(name)) {
this.getPartyMap().remove(name);
}
}
public void startParty(Player player) {
if (!hasParty(player.getName())) {
new DiscoParty(this, player).startDisco();
}
}
}
|
package is.ru.hugb.WebUI;
import static org.junit.Assert.assertEquals;
import org.junit.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.Keys;
public class TestWebUI extends SeleniumTestWrapper {
@Test
public void testTitleMatches() {
driver.get(baseUrl);
assertEquals("Tic Tac Toe", driver.getTitle());
}
public void testClick() throws Exception {
driver.get(baseUrl);
Thread.sleep(1000);
WebElement cell = driver.findElement(By.id("0"));
cell.click();
Thread.sleep(1000);
assertEquals("O", cell.getText());
}
public void testRestart() throws Exception {
driver.get(baseUrl);
Thread.sleep(1000);
WebElement tic0 = driver.findElement(By.id("0"));
WebElement tic1 = driver.findElement(By.id("1"));
WebElement btn = driver.findElement(By.id("restart-game-button"));
// Set tic 0 to X
tic0.click();
Thread.sleep(1000);
// Restart game
btn.click();
Thread.sleep(1000);
tic0 = driver.findElement(By.id("0"));
tic1 = driver.findElement(By.id("1"));
// Set tic 1 to X
tic1.click();
Thread.sleep(1000);
// Set tic 0 to O
tic0.click();
Thread.sleep(1000);
assertEquals("O", tic0.getText());
}
@Test
public void testXWin() throws Exception {
driver.get(baseUrl);
/* Remove Thread.sleep... */
Thread.sleep(2000);
driver.findElement(By.id("0")).click();
Thread.sleep(1000);
driver.findElement(By.id("3")).click();
Thread.sleep(1000);
driver.findElement(By.id("1")).click();
Thread.sleep(1000);
driver.findElement(By.id("4")).click();
Thread.sleep(1000);
driver.findElement(By.id("2")).click();
Thread.sleep(2000);
assertEquals("X is the WINNER!", driver.findElement(By.id("gameInfo")).getAttribute("innerHTML"));
}
@Test
public void testOWin() throws Exception {
driver.get(baseUrl);
Thread.sleep(2000);
driver.findElement(By.id("0")).click();
Thread.sleep(1000);
driver.findElement(By.id("3")).click();
Thread.sleep(1000);
driver.findElement(By.id("1")).click();
Thread.sleep(1000);
driver.findElement(By.id("4")).click();
Thread.sleep(1000);
driver.findElement(By.id("6")).click();
Thread.sleep(1000);
driver.findElement(By.id("5")).click();
Thread.sleep(2000);
assertEquals("O is the WINNER!", driver.findElement(By.id("gameInfo")).getAttribute("innerHTML"));
}
@Test
public void testTie() throws Exception {
driver.get(baseUrl);
Thread.sleep(2000);
driver.findElement(By.id("0")).click();
Thread.sleep(1000);
driver.findElement(By.id("1")).click();
Thread.sleep(1000);
driver.findElement(By.id("3")).click();
Thread.sleep(1000);
driver.findElement(By.id("4")).click();
Thread.sleep(1000);
driver.findElement(By.id("7")).click();
Thread.sleep(1000);
driver.findElement(By.id("6")).click();
Thread.sleep(1000);
driver.findElement(By.id("2")).click();
Thread.sleep(1000);
driver.findElement(By.id("5")).click();
Thread.sleep(1000);
driver.findElement(By.id("8")).click();
Thread.sleep(2000);
assertEquals("Tie!", driver.findElement(By.id("gameInfo")).getAttribute("innerHTML"));
}
}
|
package net.sf.jaer.hardwareinterface.usb.cypressfx2;
import eu.seebetter.ini.chips.*;
import net.sf.jaer.aemonitor.AEPacketRaw;
import net.sf.jaer.hardwareinterface.HardwareInterfaceException;
import de.thesycon.usbio.*;
import static de.thesycon.usbio.UsbIoErrorCodes.USBIO_ERR_CANCELED;
import static de.thesycon.usbio.UsbIoErrorCodes.USBIO_ERR_DEVICE_GONE;
import static de.thesycon.usbio.UsbIoErrorCodes.USBIO_ERR_SUCCESS;
import de.thesycon.usbio.structs.*;
import eu.seebetter.ini.chips.sbret10.IMUSample;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import javax.swing.ProgressMonitor;
import java.io.*;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.concurrent.ArrayBlockingQueue;
import static net.sf.jaer.hardwareinterface.usb.cypressfx2.CypressFX2.PROPERTY_CHANGE_ASYNC_STATUS_MSG;
import static net.sf.jaer.hardwareinterface.usb.cypressfx2.CypressFX2.STATUS_ENDPOINT_ADDRESS;
import static net.sf.jaer.hardwareinterface.usb.cypressfx2.CypressFX2.VR_DOWNLOAD_FIRMWARE;
import static net.sf.jaer.hardwareinterface.usb.cypressfx2.CypressFX2.log;
import static net.sf.jaer.hardwareinterface.usb.cypressfx2libusb.CypressFX2.GUID;
/**
* Adds functionality of apsDVS sensors to based CypressFX2Biasgen class. The
* key method is translateEvents that parses the data from the sensor to
* construct jAER raw events.
*
* @author Christian/Tobi
*/
public class ApsDvsHardwareInterface extends CypressFX2Biasgen {
/**
* The USB product ID of this device
*/
static public final short PID = (short) 0x840D;
static public final short DID = (short) 0x0002;
/**
* Number of IMU samples that we can queue up from IMUDataReader before
* being consumed here by merging with event stream
*/
public static final int IMU_SAMPLE_QUEUE_LENGTH = 128;
private boolean translateRowOnlyEvents = prefs.getBoolean("ApsDvsHardwareInterface.translateRowOnlyEvents", false);
private ArrayBlockingQueue<IMUSample> imuSampleQueue; // this queue is used for holding imu samples sent to aeReader
// private long imuLastSystemTimeNano=System.nanoTime();
// private LowpassFilter imuSampleIntervalFilterNs=new LowpassFilter(100);
// private int imuSampleCounter=0;
// private static final int IMU_SAMPLE_RATE_PRINT_INTERVAL=5000;
private boolean syncEventEnabled = prefs.getBoolean("ApsDvsHardwareInterface.syncEventEnabled", true); // default is true so that device is the timestamp master by default, necessary after firmware rev 11
/** SYNC events are detected when this bit mask is detected in the input event stream.
@see HasSyncEventOutput
*/
public static final int SYNC_EVENT_BITMASK = 0x8000;
/**
* Creates a new instance of CypressFX2Biasgen
*/
public ApsDvsHardwareInterface(int devNumber) {
super(devNumber);
imuSampleQueue = new ArrayBlockingQueue<IMUSample>(IMU_SAMPLE_QUEUE_LENGTH);
}
/**
* Overridden to use PortBit powerDown in biasgen
*
* @param powerDown true to power off masterbias
* @throws HardwareInterfaceException
*/
@Override
synchronized public void setPowerDown(boolean powerDown) throws HardwareInterfaceException {
if (chip != null && chip instanceof ApsDvsChip) {
ApsDvsChip apsDVSchip = (ApsDvsChip) chip;
apsDVSchip.setPowerDown(powerDown);
}
}
private byte[] parseHexData(String firmwareFile) throws IOException {
byte[] fwBuffer;
// load firmware file (this is binary file of 8051 firmware)
log.info("reading firmware file " + firmwareFile);
FileReader reader;
LineNumberReader lineReader;
String line;
int length;
// load firmware file (this is a lattice c file)
try {
reader = new FileReader(firmwareFile);
lineReader = new LineNumberReader(reader);
line = lineReader.readLine();
while (!line.startsWith("xdata")) {
line = lineReader.readLine();
}
int scIndex = line.indexOf(";");
int eqIndex = line.indexOf("=");
int index = 0;
length = Integer.parseInt(line.substring(eqIndex + 2, scIndex));
// log.info("File length: " + length);
String[] tokens;
fwBuffer = new byte[length];
Short value;
while (!line.endsWith("};")) {
line = lineReader.readLine();
tokens = line.split("0x");
// System.out.println(line);
for (int i = 1; i < tokens.length; i++) {
value = Short.valueOf(tokens[i].substring(0, 2), 16);
fwBuffer[index++] = value.byteValue();
// System.out.println(fwBuffer[index-1]);
}
}
// log.info("index" + index);
lineReader.close();
} catch (IOException e) {
close();
log.warning(e.getMessage());
throw new IOException("can't load binary Cypress FX2 firmware file " + firmwareFile);
}
return fwBuffer;
}
@Override
synchronized public void writeCPLDfirmware(String svfFile) throws HardwareInterfaceException {
byte[] bytearray;
int status, index;
USBIO_DATA_BUFFER dataBuffer = null;
try {
bytearray = this.parseHexData(svfFile);
} catch (Exception e) {
e.printStackTrace();
return;
}
ProgressMonitor progressMonitor = makeProgressMonitor("Writing CPLD configuration - do not unplug", 0, bytearray.length);
int result;
USBIO_CLASS_OR_VENDOR_REQUEST vendorRequest = new USBIO_CLASS_OR_VENDOR_REQUEST();
int numChunks;
vendorRequest.Flags = UsbIoInterface.USBIO_SHORT_TRANSFER_OK;
vendorRequest.Type = UsbIoInterface.RequestTypeVendor; // this is a vendor, not generic USB, request
vendorRequest.Recipient = UsbIoInterface.RecipientDevice; // device (not endpoint, interface, etc) receives it
vendorRequest.RequestTypeReservedBits = 0; // set these bits to zero for Cypress-specific 'vendor request' rather that user defined
vendorRequest.Request = VR_DOWNLOAD_FIRMWARE; // this is download/upload firmware request. really it is just a 'fill RAM request'
vendorRequest.Index = 0;
// 2) send the firmware to Control Endpoint 0
// when sending firmware, we need to break up the loaded fimware
// into MAX_CONTROL_XFER_SIZE blocks
// this means:
// a) the address to load it to needs to be changed (VendorRequest.Value)
// b) need a pointer that moves through FWbuffer (pBuffer)
// c) keep track of remaining bytes to transfer (FWsize_left);
//send all but last chunk
vendorRequest.Value = 0; //address of firmware location
dataBuffer = new USBIO_DATA_BUFFER(MAX_CONTROL_XFER_SIZE);
dataBuffer.setNumberOfBytesToTransfer(dataBuffer.Buffer().length);
numChunks = bytearray.length / MAX_CONTROL_XFER_SIZE; // this is number of full chunks to send
for (int i = 0; i < numChunks; i++) {
System.arraycopy(bytearray, i * MAX_CONTROL_XFER_SIZE, dataBuffer.Buffer(), 0, MAX_CONTROL_XFER_SIZE);
result = gUsbIo.classOrVendorOutRequest(dataBuffer, vendorRequest);
if (result != USBIO_ERR_SUCCESS) {
close();
throw new HardwareInterfaceException("Error on downloading segment number " + i + " of CPLD firmware: " + UsbIo.errorText(result));
}
progressMonitor.setProgress(vendorRequest.Value);
progressMonitor.setNote(String.format("sent %d of %d bytes of CPLD configuration", vendorRequest.Value, bytearray.length));
vendorRequest.Value += MAX_CONTROL_XFER_SIZE; //change address of firmware location
if (progressMonitor.isCanceled()) {
progressMonitor = makeProgressMonitor("Writing CPLD configuration - do not unplug", 0, bytearray.length);
}
}
// now send final (short) chunk
int numBytesLeft = bytearray.length % MAX_CONTROL_XFER_SIZE; // remainder
if (numBytesLeft > 0) {
dataBuffer = new USBIO_DATA_BUFFER(numBytesLeft);
dataBuffer.setNumberOfBytesToTransfer(dataBuffer.Buffer().length);
// vendorRequest.Index = 1; // indicate that this is the last chuck, now program CPLD
System.arraycopy(bytearray, numChunks * MAX_CONTROL_XFER_SIZE, dataBuffer.Buffer(), 0, numBytesLeft);
// send remaining part of firmware
result = gUsbIo.classOrVendorOutRequest(dataBuffer, vendorRequest);
if (result != USBIO_ERR_SUCCESS) {
close();
throw new HardwareInterfaceException("Error on downloading final segment of CPLD firmware: " + UsbIo.errorText(result));
}
}
vendorRequest = new USBIO_CLASS_OR_VENDOR_REQUEST();
dataBuffer = new USBIO_DATA_BUFFER(1);
vendorRequest.Flags = UsbIoInterface.USBIO_SHORT_TRANSFER_OK;
vendorRequest.Type = UsbIoInterface.RequestTypeVendor;
vendorRequest.Recipient = UsbIoInterface.RecipientDevice;
vendorRequest.RequestTypeReservedBits = 0;
vendorRequest.Request = VR_DOWNLOAD_FIRMWARE;
vendorRequest.Index = 1;
vendorRequest.Value = 0;
dataBuffer.setNumberOfBytesToTransfer(1);
status = gUsbIo.classOrVendorOutRequest(dataBuffer, vendorRequest);
if (status != USBIO_ERR_SUCCESS) {
log.info(UsbIo.errorText(status));
try {
Thread.sleep(2000);
this.open();
} catch (Exception e) {
}
}
vendorRequest = new USBIO_CLASS_OR_VENDOR_REQUEST();
dataBuffer = new USBIO_DATA_BUFFER(10);
vendorRequest.Flags = UsbIoInterface.USBIO_SHORT_TRANSFER_OK;
vendorRequest.Type = UsbIoInterface.RequestTypeVendor;
vendorRequest.Recipient = UsbIoInterface.RecipientDevice;
vendorRequest.RequestTypeReservedBits = 0;
vendorRequest.Request = VR_DOWNLOAD_FIRMWARE;
vendorRequest.Index = 0;
vendorRequest.Value = 0;
dataBuffer.setNumberOfBytesToTransfer(10);
status = gUsbIo.classOrVendorInRequest(dataBuffer, vendorRequest);
if (status != USBIO_ERR_SUCCESS) {
throw new HardwareInterfaceException("Unable to receive error code: " + UsbIo.errorText(status));
}
HardwareInterfaceException.clearException();
// log.info("bytes transferred" + dataBuffer.getBytesTransferred());
if (dataBuffer.getBytesTransferred() == 0) {
//this.sendVendorRequest(VR_DOWNLOAD_FIRMWARE, (short) 0, (short) 0);
throw new HardwareInterfaceException("Unable to program CPLD, could not get xsvf Error code");
}
progressMonitor.close();
if (dataBuffer.Buffer()[1] != 0) {
//this.sendVendorRequest(VR_DOWNLOAD_FIRMWARE, (short) 0, (short) 0);
int dataindex = (dataBuffer.Buffer()[6] << 24) | (dataBuffer.Buffer()[7] << 16) | (dataBuffer.Buffer()[8] << 8) | (dataBuffer.Buffer()[9]);
int algoindex = (dataBuffer.Buffer()[2] << 24) | (dataBuffer.Buffer()[3] << 16) | (dataBuffer.Buffer()[4] << 8) | (dataBuffer.Buffer()[5]);
throw new HardwareInterfaceException("Unable to program CPLD, error code: " + dataBuffer.Buffer()[1] + " algo index: " + algoindex + " data index " + dataindex);
// System.out.println("Unable to program CPLD, unable to program CPLD, error code: " + dataBuffer.Buffer()[1] + ", at command: " + command + " index: " + index + " commandlength " + commandlength);
}
}
/**
* Starts reader buffer pool thread and enables in endpoints for AEs. This
* method is overridden to construct our own reader with its translateEvents
* method
*/
@Override
public void startAEReader() throws HardwareInterfaceException { // raphael: changed from private to protected, because i need to access this method
setAeReader(new RetinaAEReader(this));
allocateAEBuffers();
getAeReader().startThread(3); // arg is number of errors before giving up
HardwareInterfaceException.clearException();
}
boolean gotY = false; // TODO hack for debugging state machine
/**
* If set, then row-only events are transmitted to raw packets from USB
* interface
*
* @param translateRowOnlyEvents true to translate these parasitic events.
*/
public void setTranslateRowOnlyEvents(boolean translateRowOnlyEvents) {
this.translateRowOnlyEvents = translateRowOnlyEvents;
prefs.putBoolean("ApsDvsHardwareInterface.translateRowOnlyEvents", translateRowOnlyEvents);
}
public boolean isTranslateRowOnlyEvents() {
return translateRowOnlyEvents;
}
@Override
public synchronized void resetTimestamps() {
super.resetTimestamps();
if (imuSampleQueue != null) {
imuSampleQueue.clear();
}
}
/**
#define VR_IMU 0xC6 // this VR is for dealing with IMU
#define IMU_CMD_WRITE_REGISTER 1 // arguments are 8-bit bit register address and 8-bit value to write
#define IMU_CMD_READ_REGISTER 2 // argument is 9-bit register address to read
*/
private static final byte VR_IMU = (byte) 0xC6, IMU_CMD_READ_REGISTER=(byte)2, IMU_CMD_WRITE_REGISTER=(byte)1;
/**
* Sets an IMU register value. This is a blocking method.
*
* @param imuRegister register address on device.
* @param imuRegisterValue the value to set.*
*/
public synchronized void writeImuRegister(byte imuRegister, byte imuRegisterValue) throws HardwareInterfaceException {
// setup1 setup3,setup2 setup4 setup5
sendVendorRequest(VR_IMU, (short) IMU_CMD_WRITE_REGISTER, (short)(0xffff & (0xff & imuRegister | ((0xff & imuRegisterValue) << 8))));
// sendVendorRequest(byte request, short value, short index)
}
// /**
// * Reads an IMU register value. This method blocks until value is read.
// *
// * @param register the register address.
// * @return the value of the register.
// */
// public synchronized byte readImuRegister(byte register) throws HardwareInterfaceException {
// sendVendorRequest(VR_IMU, (short) IMU_CMD_READ_REGISTER,(short) (0xff & register));
// // read back from control endpoint to get the register value
// USBIO_CLASS_OR_VENDOR_REQUEST vr = new USBIO_CLASS_OR_VENDOR_REQUEST();
// USBIO_DATA_BUFFER buf = new USBIO_DATA_BUFFER(1);
// vr.Flags = UsbIoInterface.USBIO_SHORT_TRANSFER_OK;
// vr.Type = UsbIoInterface.RequestTypeVendor;
// vr.Recipient = UsbIoInterface.RecipientDevice;
// vr.RequestTypeReservedBits = 0;
// vr.Request = VR_IMU;
// vr.Index = 0;
// vr.Value = 0;
// buf.setNumberOfBytesToTransfer(1);
// int status = gUsbIo.classOrVendorInRequest(buf, vr);
// if (status != USBIO_ERR_SUCCESS) {
// throw new HardwareInterfaceException("Unable to receive IMU register value: " + UsbIo.errorText(status));
// if (buf.getBytesTransferred() != 1) {
// throw new HardwareInterfaceException("Wrong number of bytes transferred, recieved " + buf.getBytesTransferred() + " but should have recieved 1 byte");
// byte value = buf.Buffer()[0];
// return value;
/**
* This reader understands the format of raw USB data and translates to the
* AEPacketRaw
*/
public class RetinaAEReader extends CypressFX2.AEReader /*implements PropertyChangeListener*/ {
private static final int NONMONOTONIC_WARNING_COUNT = 30; // how many warnings to print after start or timestamp reset
public static final int IMU_POLLING_INTERVAL_EVENTS = 100; // tobi changed to 100 from 1000
public RetinaAEReader(CypressFX2 cypress) throws HardwareInterfaceException {
super(cypress);
resetFrameAddressCounters();
// getSupport().addPropertyChangeListener(CypressFX2.PROPERTY_CHANGE_ASYNC_STATUS_MSG, this);
}
/**
* Method to translate the UsbIoBuffer for the DVS320 sensor which uses
* the 32 bit address space.
* <p>
* It has a CPLD to timestamp events and uses the CypressFX2 in slave
* FIFO mode.
* <p>The DVS320 has a burst mode readout mechanism that outputs a row
* address, then all the latched column addresses. The columns are
* output left to right. A timestamp is only meaningful at the row
* addresses level. Therefore the board timestamps on row address, and
* then sends the data in the following sequence: timestamp, row, col,
* col, col,....,timestamp,row,col,col...
* <p>
* Intensity information is transmitted by bit 8, which is set by the
* chip The bit encoding of the data is as follows
* <literal>
* Address bit Address bit pattern 0 LSB Y or Polarity ON=1 1 Y1 or LSB
* X 2 Y2 or X1 3 Y3 or X2 4 Y4 or X3 5 Y5 or X4 6 Y6 or X5 7 Y7 (MSBY)
* or X6 8 intensity or X7. This bit is set for a Y address if the
* intensity neuron has spiked. This bit is also X7 for X addreses. 9 X8
* (MSBX) 10 Y=0, X=1
* </literal>
*
* The two msbs of the raw 16 bit data are used to tag the type of data,
* e.g. address, timestamp, or special events wrap or reset host
* timestamps.
* <literal>
* Address Name 00xx xxxx xxxx xxxx pixel address 01xx xxxx xxxx xxxx
* timestamp 10xx xxxx xxxx xxxx wrap 11xx xxxx xxxx xxxx timestamp
* reset
* </literal>
*
* The msb of the 16 bit timestamp is used to signal a wrap (the actual
* timestamp is only 15 bits). The wrapAdd is incremented when an empty
* event is received which has the timestamp bit 15 set to one.
* <p>
* Therefore for a valid event only 15 bits of the 16 transmitted
* timestamp bits are valid, bit 15 is the status bit. overflow happens
* every 32 ms. This way, no roll overs go by undetected, and the
* problem of invalid wraps doesn't arise.
*
* @param minusEventEffect the data buffer
* @see #translateEvents
*/
static private final byte XBIT = (byte) 0x08;
static private final byte EXTERNAL_PIN_EVENT = (byte) 0x10; // external pin has seen falling edge
public static final int ADDRESS_TYPE_BIT = 0x2000; // data part of short contains according to apsDVS USB event spec 0=DVS, 1=APS
public static final int FRAME_START_BIT = 0x1000; // signals frame start when APS sample
private int lasty = 0;
private int currentts = 0;
private int lastts = 0;
private int nonmonotonicTimestampWarningCount = NONMONOTONIC_WARNING_COUNT;
private int frameEvtDropped = 10000;
private int[] countX;
private int[] countY;
private int numReadoutTypes = 3;
private IMUSample imuSample = null;
private boolean readingIMUEvents = false; // Indicates that we are reading in IMU Events from the buffer to switch reading mode
private int countIMUEvents = 0;
private short[] dataIMUEvents = new short[7];
private class Stats{
long lastBufTime=0;
final int maxLength=50;
LinkedList<BufInfo> list=new LinkedList<BufInfo>();
void addBuf(UsbIoBuf b){
list.add(new BufInfo(b.BytesTransferred));
if(list.size()>maxLength)list.removeFirst();
}
public String toString(){
StringBuilder sb=new StringBuilder("buffer stats: ");
for(BufInfo b:list){
sb.append(String.format("%s, ",b.toString()));
}
return sb.toString();
}
private class BufInfo{
long dtNs; int numBytes;
public BufInfo(int numEvents) {
this.numBytes = numEvents;
long now=System.nanoTime();
dtNs=now-lastBufTime;
lastBufTime=now;
}
public String toString(){
return String.format("%d ns %d bytes",dtNs,numBytes);
}
}
}
private Stats stats=new Stats();
@Override
protected void translateEvents(UsbIoBuf b) {
// TODO debug
// if(imuSample!=null) System.out.println(imuSample);
//stats.addBuf(b);
try {
// data from cDVS is stateful. 2 bytes sent for each word of data can consist of either timestamp, y address, x address, or ADC value.
// The type of data is determined from bits in these two bytes.
// if(tobiLogger.isEnabled()==false) tobiLogger.setEnabled(true); //debug
synchronized (aePacketRawPool) {
AEPacketRaw buffer = aePacketRawPool.writeBuffer();
int NumberOfWrapEvents;
NumberOfWrapEvents = 0;
byte[] buf = b.BufferMem;
int bytesSent = b.BytesTransferred;
if (bytesSent % 2 != 0) {
System.err.println("warning: " + bytesSent + " bytes sent, which is not multiple of 2");
bytesSent = (bytesSent / 2) * 2; // truncate off any extra part-event
}
int[] addresses = buffer.getAddresses();
int[] timestamps = buffer.getTimestamps();
// log.info("received " + bytesSent + " bytes");
// write the start of the packet
buffer.lastCaptureIndex = eventCounter;
// tobiLogger.log("#packet");
for (int i = 0; i < bytesSent; i += 2) {
// tobiLogger.log(String.format("%d %x %x",eventCounter,buf[i],buf[i+1])); // DEBUG
// int val=(buf[i+1] << 8) + buf[i]; // 16 bit value of data
int dataword = (0xff & buf[i]) | (0xff00 & (buf[i + 1] << 8)); // data sent little endian
// Check that we are not reading IMU Events which have a different encoding scheme
// START IF readingIMUEvents
if (readingIMUEvents == false) {
final int code = (buf[i + 1] & 0xC0) >> 6; // gets two bits at XX00 0000 0000 0000. (val&0xC000)>>>14;
// log.info("code " + code);
int xmask = (ApsDvsChip.XMASK | ApsDvsChip.POLMASK) >>> ApsDvsChip.POLSHIFT;
switch (code) {
case 0: // address
// If the data is an address, we write out an address value if we either get an ADC reading or an x address.
// We also write a (fake) address if
// we get two y addresses in a row, which occurs when the on-chip AE state machine doesn't properly function.
// Here we also read y addresses but do not write out any output address until we get either 1) an x-address, or 2)
// another y address without intervening x-address.
// NOTE that because ADC events do not have a timestamp, the size of the addresses and timestamps data are not the same.
// To simplify data structure handling in AEPacketRaw and AEPacketRawPool,
// ADC events are timestamped just like address-events. ADC events get the timestamp of the most recently preceeding address-event.
// NOTE2: unmasked bits are read as 1's from the hardware. Therefore it is crucial to properly mask bits.
if ((eventCounter >= aeBufferSize) || (buffer.overrunOccuredFlag)) {
buffer.overrunOccuredFlag = true; // throw away events if we have overrun the output arrays
} else {
int addr, timestamp; // used to store event to write out
boolean haveEvent = false;
if ((dataword & ADDRESS_TYPE_BIT) == ADDRESS_TYPE_BIT) {
//APS event
if ((dataword & FRAME_START_BIT) == FRAME_START_BIT) {
resetFrameAddressCounters();
}
int readcycle = (dataword & ApsDvsChip.ADC_READCYCLE_MASK) >> ApsDvsChip.ADC_READCYCLE_SHIFT;
if (countY[readcycle] >= chip.getSizeY()) {
countY[readcycle] = 0;
countX[readcycle]++;
}
if (countX[readcycle] >= chip.getSizeX()) {
if (frameEvtDropped == 0) {
log.warning("countX above chip size, a start frame event was dropped");
frameEvtDropped = 10000;
}
else {
frameEvtDropped
}
}
int xAddr = (short) (chip.getSizeX() - 1 - countX[readcycle]);
int yAddr = (short) (chip.getSizeY() - 1 - countY[readcycle]);
// if(xAddr >= chip.getSizeX() || xAddr<0 || yAddr >= chip.getSizeY() || yAddr<0)System.out.println("out of bounds event: x = "+xAddr+", y = "+yAddr+", read = "+readcycle);
countY[readcycle]++;
addr = ApsDvsChip.ADDRESS_TYPE_APS
| ((yAddr << ApsDvsChip.YSHIFT) & ApsDvsChip.YMASK)
| ((xAddr << ApsDvsChip.XSHIFT) & ApsDvsChip.XMASK)
| (dataword & (ApsDvsChip.ADC_READCYCLE_MASK | ApsDvsChip.ADC_DATA_MASK));
timestamp = currentts; // ADC event gets last timestamp
haveEvent = true;
// System.out.println("ADC word: " + (dataword&SeeBetter20.ADC_DATA_MASK));
// Detects Special Events which can be of type IMUEvents
} else if ((buf[i + 1] & EXTERNAL_PIN_EVENT) == EXTERNAL_PIN_EVENT) {
addr = ApsDvsChip.EXTERNAL_INPUT_EVENT_ADDR;
timestamp = currentts;
haveEvent = false; // TODO set false for now
// haveEvent = true; // TODO don't write out the external pin events for now, because they mess up the IMU special events
// Detect Special / External Event of Type IMU, and set flag to start reading subsequent pairs of bytes as IMUEvents
if ((buf[i] & ApsDvsChip.IMUMASK) == ApsDvsChip.IMUMASK) {
readingIMUEvents = true;
//if (bytesSent - i < 20) System.out.println(bytesSent - i);
}
} else if ((buf[i + 1] & XBIT) == XBIT) {// received an X address, write out event to addresses/timestamps output arrays
// x/column part of DVS event
// x column adddress received, combine with previous row y address and commit to output packet
addr = (lasty << ApsDvsChip.YSHIFT) | ((dataword & xmask) << ApsDvsChip.POLSHIFT); // combine current bits with last y address bits and send
timestamp = currentts; // add in the wrap offset and convert to 1us tick
haveEvent = true;
//log.info("X: "+((dataword & ApsDvsChip.XMASK)>>1));
gotY = false;
} else { // row address came, just save it until we get a column address
addr = 0;
timestamp = 0;
// y/row part of DVS event
if (gotY) { // no col address came after last row address, last event was row-only event
if (translateRowOnlyEvents) {// make row-only event
addresses[eventCounter] = (lasty << ApsDvsChip.YSHIFT); // combine current bits with last y address bits and send
timestamps[eventCounter] = currentts; // add in the wrap offset and convert to 1us tick
eventCounter++;
}
}
// y address, save it for all the x/row addresses that should follow
int ymask = (ApsDvsChip.YMASK >>> ApsDvsChip.YSHIFT);
lasty = ymask & dataword; //(0xFF & buf[i]); //
gotY = true;
//log.info("Y: "+lasty+" - data "+dataword+" - mask: "+(ApsDvsChip.YMASK >>> ApsDvsChip.YSHIFT));
}
if (haveEvent) {
// see if there are any IMU samples to add to packet
// merge the IMUSamples to the packet, attempting to maintain timestamp monotonicity,
// even if the timestamp is on a different origin that is not related to the data on this endpoint.
if (imuSample == null) {
imuSample = imuSampleQueue.poll();
}
while (imuSample != null && imuSample.getTimestampUs() < timestamp) {
eventCounter += imuSample.writeToPacket(buffer, eventCounter);
// System.out.println(imuSample.toString());
imuSample = imuSampleQueue.poll();
}
while (imuSample != null && imuSample.getTimestampUs() > timestamp + 10000) {
imuSample = imuSampleQueue.poll(); // drain out imu samples that are too far in future
}
addresses[eventCounter] = addr;
timestamps[eventCounter++] = timestamp;
}
}
break;
case 1: // timestamp
lastts = currentts;
currentts = ((0x3f & buf[i + 1]) << 8) | (buf[i] & 0xff);
currentts = (TICK_US * (currentts + wrapAdd));
if (lastts > currentts && nonmonotonicTimestampWarningCount
log.warning(this.toString()+": non-monotonic timestamp: currentts=" + currentts + " lastts=" + lastts + " currentts-lastts=" + (currentts - lastts));
}
// log.info("received timestamp");
break;
case 2: // wrap
wrapAdd += 0x4000L;
NumberOfWrapEvents++;
// log.info("wrap");
break;
case 3: // ts reset event
nonmonotonicTimestampWarningCount = NONMONOTONIC_WARNING_COUNT;
this.resetTimestamps();
log.info("timestamp reset event received on "+super.toString());
break;
}
// Code to read IMUEvents
} else {
//*/
} // END IF readingIMUEvents
} // end loop over usb data buffer
buffer.setNumEvents(eventCounter);
// write capture size
buffer.lastCaptureLength = eventCounter - buffer.lastCaptureIndex;
// log.info("packet size " + buffer.lastCaptureLength);
// if (NumberOfWrapEvents!=0) {
//System.out.println("Number of wrap events received: "+ NumberOfWrapEvents);
//System.out.println("wrapAdd : "+ wrapAdd);
} // sync on aePacketRawPool
} catch (java.lang.IndexOutOfBoundsException e) {
log.warning(e.toString());
}
}
private void resetFrameAddressCounters() {
if (countX == null || countY == null) {
countX = new int[numReadoutTypes];
countY = new int[numReadoutTypes];
}
Arrays.fill(countX, 0, numReadoutTypes, 0);
Arrays.fill(countY, 0, numReadoutTypes, 0);
// log.info("Start of new frame");
}
private int putImuSampleToQueueWarningCounter = 0;
private static final int PUT_IMU_WARNING_INTERVAL = 10000;
// @Override
// public void propertyChange(PropertyChangeEvent evt) {
// // we come here because the IMUDataReader has generated a PropertyChangeEvent and we are subscribed to this object.
// if (evt.getPropertyName() != PROPERTY_CHANGE_ASYNC_STATUS_MSG) {
// return;
// try {
// UsbIoBuf buf = (UsbIoBuf) evt.getNewValue();
// IMUSample sample = new IMUSample(buf);
// try {
//// System.out.println(sample.getTimestampUs());
// imuSampleQueue.add(sample);
// if (putImuSampleToQueueWarningCounter++ % PUT_IMU_WARNING_INTERVAL == 0) {
// log.warning("putting IMUSample "+imuSample+" to queue not possible because queue has" + imuSampleQueue.size() + " samples and was full");
// } catch (ClassCastException e) {
// log.warning("receieved wrong type of data for the IMU: " + e.toString());
}
// /**
// * Status messages sent by device. This header byte identifies the message
// * type.
// */
// public static final byte STATUS_MSG_IMU_DATA = (byte) 0xff;
// /**
// * Property change fired when a new message is received on the asynchronous
// * status endpoint.
// *
// * @see AsyncStatusThread
// */
// public static final String PROPERTY_CHANGE_IMU_DATA = "IMUData";
// /**
// * This threads reads IMU data from the camera on endpoint 2 - currently not used.
// *
// * @author tobi delbruck
// * @see #getSupport()
// */
// protected class IMUDataReader extends UsbIoReader { // not used yet, still reading IMU samples in AsyncStatusThread
// UsbIoPipe pipe;
// CypressFX2 monitor;
// boolean stop = false;
// byte msg;
// public static final int STATUS_PRIORITY = Thread.MAX_PRIORITY; // Thread.NORM_PRIORITY+2
// public IMUDataReader(CypressFX2 monitor) {
// super();
// this.monitor = monitor;
// int status;
// status = bind(monitor.getInterfaceNumber(), (byte) 0x82, gDevList, GUID); // bind to this interface, using endpoint 2 which is an IN endpoint
// if (status != USBIO_ERR_SUCCESS) {
// log.warning("error binding to pipe for EP2 for device status: " + UsbIo.errorText(status) + ", not starting IMUDataReader");
// return;
// USBIO_PIPE_PARAMETERS pipeParams = new USBIO_PIPE_PARAMETERS();
// pipeParams.Flags = UsbIoInterface.USBIO_SHORT_TRANSFER_OK;
// status = setPipeParameters(pipeParams);
// if (status != USBIO_ERR_SUCCESS) {
// log.warning("can't set pipe parameters: " + UsbIo.errorText(status) + ": IMUDataReader may not function properly");
// @Override
// public void startThread(int MaxIoErrorCount) {
// allocateBuffers(64, 4); // 64-byte buffers, 4 of them on host side
// super.startThread(MaxIoErrorCount);
// T.setPriority(STATUS_PRIORITY); // very important that this thread have priority or the acquisition will stall on device side for substantial amounts of time!
// T.setName("IMUDataReader");
// @Override
// public void processData(UsbIoBuf buffer) {
// if (buffer.BytesTransferred > 0) {
// msg = buffer.BufferMem[0];
// switch (msg) {
// case STATUS_MSG_IMU_DATA:
// default:
// UsbIoBuf newbuf = new UsbIoBuf(64);
// // Copy data to new buffer, this one is resubmitted right away.
// System.arraycopy(buffer.BufferMem, 0, newbuf.BufferMem, 0, buffer.BytesTransferred);
// newbuf.BytesTransferred = buffer.BytesTransferred;
// newbuf.Status = buffer.Status;
// support.firePropertyChange(PROPERTY_CHANGE_IMU_DATA, null, newbuf); // tobi - send message to listeners
// } // we getString 0 byte read on stopping device
// // called before buffer is submitted to driver
// @Override
// public void processBuffer(UsbIoBuf Buf) {
// Buf.NumberOfBytesToTransfer = Buf.Size;
// Buf.BytesTransferred = 0;
// Buf.OperationFinished = false;
// @Override
// public void bufErrorHandler(UsbIoBuf Buf) {
// if (Buf.Status != USBIO_ERR_SUCCESS) {
// // print error
// // suppress CANCELED because it is caused by ABORT_PIPE
// if (Buf.Status != USBIO_ERR_CANCELED) {
// log.warning("CypressFX2.IMUDataReader.bufErrorHandler(): USB buffer error: " + UsbIo.errorText(Buf.Status));
// if (Buf.Status == USBIO_ERR_DEVICE_GONE) {
// log.warning("CypressFX2.IMUDataReader.bufErrorHandler(): device gone, shutting down buffer pool thread");
// monitor.close();
// @Override
// public void onThreadExit() {
// freeBuffers();
// /** This threads reads asynchronous status or other data from the device.
// * It handles timestamp reset messages from the device and possibly other types of data.
// It fires PropertyChangeEvent {@link #PROPERTY_CHANGE_ASYNC_STATUS_MSG} on receiving a message
// @author tobi delbruck
// * @see #getSupport()
// */
// protected class IMUDataThread extends UsbIoReader {
// UsbIoPipe pipe;
// net.sf.jaer.hardwareinterface.usb.cypressfx2.CypressFX2 monitor;
// boolean stop = false;
// byte msg;
// public static final int STATUS_PRIORITY = Thread.MAX_PRIORITY; // Thread.NORM_PRIORITY+2
// public IMUDataThread(net.sf.jaer.hardwareinterface.usb.cypressfx2.CypressFX2 monitor) {
// super();
// this.monitor = monitor;
// int status;
// status = bind(monitor.getInterfaceNumber(), STATUS_ENDPOINT_ADDRESS, gDevList, GUID);
// if (status != USBIO_ERR_SUCCESS) {
// log.warning("error binding to pipe for EP1 for device status: " + UsbIo.errorText(status) + ", not starting AsyncStatusThread");
// return;
// USBIO_PIPE_PARAMETERS pipeParams = new USBIO_PIPE_PARAMETERS();
// pipeParams.Flags = UsbIoInterface.USBIO_SHORT_TRANSFER_OK;
// status = setPipeParameters(pipeParams);
// if (status != USBIO_ERR_SUCCESS) {
// log.warning("can't set pipe parameters: " + UsbIo.errorText(status)+": AsyncStatusThread may not function properly");
// @Override
// public void startThread(int MaxIoErrorCount) {
// allocateBuffers(64,4);
// super.startThread(MaxIoErrorCount);
// T.setPriority(STATUS_PRIORITY); // very important that this thread have priority or the acquisition will stall on device side for substantial amounts of time!
// T.setName("AsyncStatusThread");
// @Override
// public void processData(UsbIoBuf buffer) {
// if (buffer.BytesTransferred > 0) {
// msg = buffer.BufferMem[0];
// switch (msg) {
// case STATUS_MSG_TIMESTAMPS_RESET:
// net.sf.jaer.hardwareinterface.usb.cypressfx2.CypressFX2.AEReader rd = getAeReader();
// if (rd != null) {
// rd.resetTimestamps();
// } else {
// log.info("Received timestamp external reset message, but monitor is not running");
// break;
// case STATUS_MSG_OTHER:
// default:
// UsbIoBuf newbuf = new UsbIoBuf(64);
// // Copy data to new buffer, this one is resubmitted right away.
// System.arraycopy(buffer.BufferMem, 0, newbuf.BufferMem, 0, buffer.BytesTransferred);
// newbuf.BytesTransferred = buffer.BytesTransferred;
// newbuf.Status = buffer.Status;
// support.firePropertyChange(PROPERTY_CHANGE_ASYNC_STATUS_MSG, null, newbuf); // tobi - send message to listeners
// } // we getString 0 byte read on stopping device
// // called before buffer is submitted to driver
// @Override
// public void processBuffer(UsbIoBuf Buf) {
// Buf.NumberOfBytesToTransfer = Buf.Size;
// Buf.BytesTransferred = 0;
// Buf.OperationFinished = false;
// @Override
// public void bufErrorHandler(UsbIoBuf Buf) {
// if (Buf.Status != USBIO_ERR_SUCCESS) {
// // print error
// // suppress CANCELED because it is caused by ABORT_PIPE
// if (Buf.Status != USBIO_ERR_CANCELED) {
// log.warning("CypressFX2.AsyncStatusThread.bufErrorHandler(): USB buffer error: " + UsbIo.errorText(Buf.Status));
// if (Buf.Status == USBIO_ERR_DEVICE_GONE) {
// log.warning("CypressFX2.AsyncStatusThread.bufErrorHandler(): device gone, shutting down buffer pool thread");
// monitor.close();
// @Override
// public void onThreadExit() {
// freeBuffers();
}
|
package org.objectweb.proactive.core.component.xml;
import org.apache.log4j.Logger;
import org.objectweb.fractal.api.Component;
import org.objectweb.fractal.api.NoSuchInterfaceException;
import org.objectweb.fractal.api.control.ContentController;
import org.objectweb.fractal.api.control.IllegalContentException;
import org.objectweb.fractal.api.control.IllegalLifeCycleException;
import org.objectweb.fractal.api.factory.InstantiationException;
import org.objectweb.proactive.core.component.Constants;
import org.objectweb.proactive.core.component.ContentDescription;
import org.objectweb.proactive.core.component.ControllerDescription;
import org.objectweb.proactive.core.component.type.Composite;
import org.objectweb.proactive.core.descriptor.data.ProActiveDescriptor;
import org.objectweb.proactive.core.descriptor.data.VirtualNode;
import org.objectweb.proactive.core.node.Node;
import org.objectweb.proactive.core.node.NodeException;
import org.objectweb.proactive.core.xml.handler.UnmarshallerHandler;
import org.objectweb.proactive.core.xml.io.Attributes;
import org.xml.sax.SAXException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
/**
* @author Matthieu Morel
*/
public class CompositeComponentHandler extends AbstractContainerComponentHandler {
public static Logger logger = Logger.getLogger(CompositeComponentHandler.class.getName());
private List subComponents;
/**
* @param deploymentDescriptor
* @param componentsCache
*/
public CompositeComponentHandler(ProActiveDescriptor deploymentDescriptor,
ComponentsCache componentsCache, HashMap componentTypes,
ComponentsHandler fatherHandler) {
super(deploymentDescriptor, componentsCache, componentTypes,
fatherHandler);
controllerDescription.setHierarchicalType(Constants.COMPOSITE);
addHandler(ComponentsDescriptorConstants.BINDINGS_TAG,
new BindingsHandler(componentsCache));
}
/* (non-Javadoc)
* @see org.objectweb.proactive.core.xml.handler.AbstractUnmarshallerDecorator#notifyEndActiveHandler(java.lang.String, org.objectweb.proactive.core.xml.handler.UnmarshallerHandler)
*/
protected void notifyEndActiveHandler(String name,
UnmarshallerHandler activeHandler) throws SAXException {
if (getContainerElementHierarchy().containsChild(activeHandler)) {
enable();
}
if (isEnabled()) {
Component composite;
if (name.equals(ComponentsDescriptorConstants.COMPONENTS_TAG)) {
// then instantiate the component and add a stub on it to the cache
try {
if (virtualNode.equals(ComponentsDescriptorConstants.NULL)) {
// componentsCache.addComponent(componentParameters.getName(),
// //PrimitiveComponentB.class.getName(),
composite = cf.newFcInstance(componentType,
new ControllerDescription(controllerDescription.getName(),
controllerDescription.getHierarchicalType()),
new ContentDescription(Composite.class.getName(),
new Object[] { }));
componentsCache.addComponent(controllerDescription.getName(),
composite);
//PrimitiveComponentB.class.getName(),
} else {
VirtualNode vn = deploymentDescriptor.getVirtualNode(virtualNode);
if (vn.getNodeCount() == 0) {
throw new NodeException(
"no node defined for the virtual node " + vn.getName());
}
if (logger.isDebugEnabled()) {
if (vn.getNodeCount() > 1) {
logger.debug("creating a composite component on a virtual node mapped onto several nodes will actually create the component on the first retreived node");
}
}
// get corresponding node (1st node retreived if the vn is multiple)
Node targeted_node = vn.getNode();
composite = cf.newFcInstance(componentType,
new ControllerDescription(controllerDescription.getName(),
controllerDescription.getHierarchicalType()),
new ContentDescription(Composite.class.getName(),
new Object[] { }, targeted_node));
componentsCache.addComponent(controllerDescription.getName(),
composite);
}
// add sub components
List sub_components = (List) getHandler(name)
.getResultObject();
Iterator iterator = sub_components.iterator();
while (iterator.hasNext()) {
String sub_component_name = (String) iterator.next();
if (logger.isDebugEnabled()) {
logger.debug("adding sub component : " +
sub_component_name);
}
((ContentController) composite.getFcInterface(Constants.CONTENT_CONTROLLER)).addFcSubComponent(componentsCache.getComponent(
sub_component_name));
}
} catch (InstantiationException e) {
logger.error("cannot instantiate component");
throw new SAXException(e);
} catch (NodeException ne) {
logger.error(
"cannot create active component: node exception");
throw new SAXException(ne);
} catch (NoSuchInterfaceException nsie) {
logger.error(
"cannot create active component : interface not found");
throw new SAXException(nsie);
} catch (IllegalLifeCycleException ilce) {
logger.error(
"cannot create active component : illegal life cycle operation");
throw new SAXException(ilce);
} catch (IllegalContentException ice) {
logger.error(
"cannot create active component : illegal content operation");
throw new SAXException(ice);
}
logger.debug("created composite component : " +
controllerDescription.getName());
}
}
}
/* (non-Javadoc)
* @see org.objectweb.proactive.core.xml.handler.UnmarshallerHandler#getResultObject()
*/
public Object getResultObject() throws SAXException {
return new ComponentResultObject(controllerDescription.getName());
}
/* (non-Javadoc)
* @see org.objectweb.proactive.core.xml.handler.UnmarshallerHandler#startContextElement(java.lang.String, org.objectweb.proactive.core.xml.io.Attributes)
*/
public void startContextElement(String name, Attributes attributes)
throws SAXException {
if (isEnabled()) {
super.startContextElement(name, attributes);
}
}
}
|
import constant.Region;
import database.models.Queryable;
import main.java.riotapi.RiotApi;
import main.java.riotapi.RiotApiException;
import java.util.List;
import java.util.function.Consumer;
abstract class AbstractCollector {
protected String baseURL = "https://br.api.pvp.net/api/lol/%s/v1.4/%s/%s/%s?api_key=%s";
protected RiotApi api;
protected static final int maxIDs = 40;
protected String apiKey;
protected static final Region[] regions = Region.values();
protected static final int SEASON = 5;
public AbstractCollector(String apiKey) {
api = new RiotApi(apiKey);
}
protected void setRegion(Region region) {
api.setRegion(region);
}
protected RiotApi getApi() {
return this.api;
}
protected void queueApiCall() {
}
}
|
package org.mobicents.protocols.ss7.map.functional;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
import junit.framework.TestCase;
import org.apache.log4j.BasicConfigurator;
import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;
import org.junit.Test;
import org.mobicents.protocols.ss7.indicator.NatureOfAddress;
import org.mobicents.protocols.ss7.map.MAPStackImpl;
import org.mobicents.protocols.ss7.sccp.SccpProvider;
import org.mobicents.protocols.ss7.sccp.impl.SccpStackImpl;
import org.mobicents.protocols.ss7.sccp.impl.router.RouterImpl;
import org.mobicents.protocols.ss7.sccp.parameter.GlobalTitle;
import org.mobicents.protocols.ss7.sccp.parameter.SccpAddress;
/**
*
* @author amit bhayani
*
*/
public class MAPFunctionalTest extends TestCase {
private static Logger logger = Logger.getLogger(MAPFunctionalTest.class);
protected static final String USSD_STRING = "*133
protected static final String USSD_MENU = "Select 1)Wallpaper 2)Ringtone 3)Games";
private static final int _WAIT_TIMEOUT = 5000;
private SccpStackImpl sccpStack = new SccpStackImpl();
private SccpProvider provider;
private MAPStackImpl stack1;
private MAPStackImpl stack2;
private SccpAddress peer1Address;
private SccpAddress peer2Address;
private Client client;
private Server server;
/* (non-Javadoc)
* @see junit.framework.TestCase#setUp()
*/
@Override
protected void setUp() throws Exception {
RouterImpl router = new RouterImpl();
sccpStack.setRouter(router);
sccpStack.start();
super.setUp();
this.setupLog4j();
this.provider = sccpStack.getSccpProvider();
//create some fake addresses.
GlobalTitle gt1 = GlobalTitle.getInstance(NatureOfAddress.NATIONAL, "123");
GlobalTitle gt2 = GlobalTitle.getInstance(NatureOfAddress.NATIONAL, "321");
peer1Address = new SccpAddress(gt1, 0);
peer2Address = new SccpAddress(gt2, 0);
this.stack1 = new MAPStackImpl(provider, peer1Address);
this.stack2 = new MAPStackImpl(provider, peer2Address);
this.stack1.start();
this.stack2.start();
//create test classes
this.client = new Client(this.stack1, this, peer1Address, peer2Address);
this.server = new Server(this.stack2, this, peer2Address, peer1Address);
}
private void setupLog4j() {
InputStream inStreamLog4j = getClass().getResourceAsStream("/log4j.properties");
Properties propertiesLog4j = new Properties();
try {
propertiesLog4j.load(inStreamLog4j);
PropertyConfigurator.configure(propertiesLog4j);
} catch (IOException e) {
e.printStackTrace();
BasicConfigurator.configure();
}
logger.debug("log4j configured");
}
/* (non-Javadoc)
* @see junit.framework.TestCase#tearDown()
*/
@Override
protected void tearDown() throws Exception {
sccpStack.stop();
// TODO Auto-generated method stub
super.tearDown();
this.stack1.stop();
this.stack2.stop();
}
@Test
public void testSimpleTCWithDialog() throws Exception {
client.start();
waitForEnd();
assertTrue("Client side did not finish: " + client.getStatus(), client.isFinished());
assertTrue("Server side did not finish: " + server.getStatus(), server.isFinished());
}
private void waitForEnd() {
try {
Thread.currentThread().sleep(_WAIT_TIMEOUT);
} catch (InterruptedException e) {
fail("Interrupted on wait!");
}
}
}
|
package com.bbva.arq.devops.ae.mirrorgate.model;
import java.time.temporal.ChronoUnit;
import org.springframework.data.mongodb.core.index.CompoundIndex;
import org.springframework.data.mongodb.core.index.Indexed;
import org.springframework.data.mongodb.core.mapping.Document;
@Document(collection = "historic_user_metrics")
@CompoundIndex(name = "average_index", def = "{'viewId' : 1, 'name': 1, 'value': 1, 'historicType': 1, 'timestamp': 1}")
public class HistoricUserMetric extends BaseModel{
@Indexed
private String identifier;
private String viewId;
private String appVersion;
private String platform;
@Indexed
private String name;
private Double value;
private Double sampleSize;
@Indexed
private Long timestamp;
/* Associated collector ID */
private String collectorId;
@Indexed
private ChronoUnit historicType;
public String getIdentifier() {
return identifier;
}
public HistoricUserMetric setIdentifier(String identifier) {
this.identifier = identifier;
return this;
}
public String getViewId() {
return viewId;
}
public HistoricUserMetric setViewId(String viewId) {
this.viewId = viewId;
return this;
}
public String getAppVersion() {
return appVersion;
}
public HistoricUserMetric setAppVersion(String appVersion) {
this.appVersion = appVersion;
return this;
}
public String getPlatform() {
return platform;
}
public HistoricUserMetric setPlatform(String platform) {
this.platform = platform;
return this;
}
public String getName() {
return name;
}
public HistoricUserMetric setName(String name) {
this.name = name;
return this;
}
public Double getValue() {
return value;
}
public HistoricUserMetric setValue(Double value) {
this.value = value;
return this;
}
public Double getSampleSize() {
return sampleSize;
}
public HistoricUserMetric setSampleSize(Double sampleSize) {
this.sampleSize = sampleSize;
return this;
}
public Long getTimestamp() {
return timestamp;
}
public HistoricUserMetric setTimestamp(Long timestamp) {
this.timestamp = timestamp;
return this;
}
public String getCollectorId() {
return collectorId;
}
public HistoricUserMetric setCollectorId(String collectorId) {
this.collectorId = collectorId;
return this;
}
public ChronoUnit getHistoricType() {
return historicType;
}
public HistoricUserMetric setHistoricType(ChronoUnit historicType) {
this.historicType = historicType;
return this;
}
}
|
package org.openlmis.report.model.params;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.NoArgsConstructor;
import org.openlmis.core.domain.ProcessingPeriod;
import org.openlmis.report.model.ReportParameter;
import java.text.SimpleDateFormat;
@Data
@NoArgsConstructor
@EqualsAndHashCode(callSuper = false)
@AllArgsConstructor
public class RegimenSummaryReportParam
extends BaseParam implements ReportParameter {
private long period;
private ProcessingPeriod periodObject;
private int rgroupId;
private int regimenCategoryId;
private String regimenCategory;
private String rgroup;
private String regimen;
private Integer regimenId;
private int programId;
private String program;
private int scheduleId;
private String schedule;
private int periodId;
private Integer year;
SimpleDateFormat dateFormatter = new SimpleDateFormat();
@Override
public String toString() {
if (periodObject != null) {
StringBuilder filtersValue = new StringBuilder("");
filtersValue.append("Period : ").append(dateFormatter.format(this.periodObject.getNextStartDate())).append("-").append(dateFormatter.format(this.periodObject.getEndDate())).append("\n").
append("Regimen Category : ").append(this.getRegimenCategory()).append("\n").
append("Regimen : ").append(this.getRegimen()).append("\n").
append("Schedule : ").append(this.getSchedule()).append("\n").
append("Program : ").append(this.getProgram()).append("\n").
append("Reporting Groups : ").append(this.getRgroup());
return filtersValue.toString();
} else {
return "No filters selected";
}
}
}
|
package org.openlmis.report.service;
import lombok.NoArgsConstructor;
import org.apache.ibatis.session.RowBounds;
import org.openlmis.core.service.ConfigurationSettingService;
import org.openlmis.report.mapper.SupplyStatusReportMapper;
import org.openlmis.report.model.ReportData;
import org.openlmis.report.util.Constants;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.util.List;
import java.util.Map;
@Component
@NoArgsConstructor
public class SupplyStatusReportDataProvider extends ReportDataProvider {
private SupplyStatusReportMapper reportMapper;
private ConfigurationSettingService configurationService;
@Autowired
public SupplyStatusReportDataProvider(SupplyStatusReportMapper mapper, ConfigurationSettingService configurationService) {
this.reportMapper = mapper;
this.configurationService = configurationService;
}
@Override
protected List<? extends ReportData> getBeanCollectionReportData(Map<String, String[]> filterCriteria) {
RowBounds rowBounds = new RowBounds(RowBounds.NO_ROW_OFFSET,RowBounds.NO_ROW_LIMIT);
return reportMapper.getSupplyStatus(filterCriteria, rowBounds);
}
@Override
protected List<? extends ReportData> getResultSetReportData(Map<String, String[]> filterCriteria) {
return null; //To change body of implemented methods use File | Settings | File Templates.0
}
@Override
public List<? extends ReportData> getReportDataByFilterCriteriaAndPagingAndSorting(Map<String, String[]> filterCriteria, Map<String, String[]> SortCriteria, int page, int pageSize) {
RowBounds rowBounds = new RowBounds((page-1) * pageSize,pageSize);
return reportMapper.getSupplyStatus(filterCriteria, rowBounds);
}
@Override
public int getReportDataCountByFilterCriteria(Map<String, String[]> filterCriteria) {
return 0;
}
@Override
public ReportData getReportFilterData(Map<String, String[]> params) {
String facilityTypeId = params.get("facilityTypeId")[0];
String periodId = params.get("periodId")[0];
String facilityType = "";
String period = "";
String productId = params.get("productId")[0];
String product = params.get("product")[0];
String program = params.get("program")[0];
String schedule = params.get("schedule")[0];
String facilityId = params.get("facilityId")[0];
String facility = params.get("facility")[0];
String zoneId = params.get("zoneId")[0];
String zone = params.get("zone")[0];
if(facilityTypeId != null && !facilityTypeId.isEmpty()){
if(facilityTypeId.equals("-1") || facilityTypeId.equals("0"))
facilityType = "All Facility Types";
else
facilityType = params.get("facilityType")[0];
}
period = params.get("period")[0];
if(productId != null && !productId.isEmpty()){
if(productId.equals("-1")){
//Indicator Products
product = configurationService.getConfigurationStringValue(Constants.CONF_INDICATOR_PRODUCTS).isEmpty() ? "Indicator Products" :
configurationService.getConfigurationStringValue(Constants.CONF_INDICATOR_PRODUCTS);
}else if(productId.equals("0"))//All Products
product = "All Products";
}
if(facilityId != null && facilityId.isEmpty()){
facility = "All Facilities";
}
if(zoneId != null && (zoneId.isEmpty() || zoneId.equals("0"))){
zone = "All Zones";
}
final String finalFacilityType = "Facility Type : " + facilityType;
final String finalPeriod = "Report Period : " + (period.isEmpty() ? " - " : period);
final String finalProgram = "Program : " + (program.isEmpty() ? " - " : program);
final String finalProduct = "Product : " + product;
final String finalSchedule = "Schedule : " + schedule;
final String finalFacility = "Facility : " + (facility.isEmpty() ? " - " : facility);
final String finalZone = "Zone : " + zone;
return new ReportData() {
@Override
public String toString() {
StringBuffer reportingFilter = new StringBuffer("");
reportingFilter.append(finalPeriod).append("\n").
append(finalSchedule).append("\n").
append(finalProgram).append("\n").
append(finalFacilityType).append("\n").
append(finalFacility).append("\n").
append(finalProduct).append("\n").
append(finalZone);
return reportingFilter.toString();
}
};
}
}
|
package org.openrdf.repository.object.trigger;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import org.openrdf.model.Literal;
import org.openrdf.model.Resource;
import org.openrdf.model.URI;
import org.openrdf.model.Value;
import org.openrdf.query.QueryEvaluationException;
import org.openrdf.repository.RepositoryConnection;
import org.openrdf.repository.RepositoryException;
import org.openrdf.repository.base.RepositoryConnectionWrapper;
import org.openrdf.repository.object.ObjectConnection;
import org.openrdf.repository.object.ObjectFactory;
import org.openrdf.repository.object.exceptions.ObjectCompositionException;
/**
* Wrapper used when triggers have been registered with the connection.
*
* @author James Leigh
*
*/
public class TriggerConnection extends RepositoryConnectionWrapper {
private static final int MAX_TRIG_STACK = 100;
private Map<URI, Set<Trigger>> triggers;
private Map<URI, Map<Resource, Set<Value>>> events = new HashMap<URI, Map<Resource, Set<Value>>>();
private ObjectConnection objects;
private ObjectFactory of;
public TriggerConnection(RepositoryConnection delegate,
Map<URI, Set<Trigger>> triggers) {
super(delegate.getRepository(), delegate);
this.triggers = triggers;
}
public void setObjectConnection(ObjectConnection objects) {
this.objects = objects;
of = objects.getObjectFactory();
}
@Override
protected boolean isDelegatingAdd() throws RepositoryException {
return false;
}
@Override
protected void addWithoutCommit(Resource subject, URI predicate,
Value object, Resource... contexts) throws RepositoryException {
boolean containsKey = triggers.containsKey(predicate);
if (containsKey && isAutoCommit()) {
setAutoCommit(false);
try {
getDelegate().add(subject, predicate, object, contexts);
recordEvent(subject, predicate, object);
setAutoCommit(true);
} finally {
if (!isAutoCommit()) {
rollback();
}
}
} else {
getDelegate().add(subject, predicate, object, contexts);
if (containsKey) {
recordEvent(subject, predicate, object);
}
}
}
@Override
public void commit() throws RepositoryException {
try {
fireEvents();
} catch (QueryEvaluationException e) {
throw new RepositoryException(e);
}
super.commit();
}
@Override
public void setAutoCommit(boolean autoCommit) throws RepositoryException {
if (autoCommit) {
try {
fireEvents();
} catch (QueryEvaluationException e) {
throw new RepositoryException(e);
}
}
super.setAutoCommit(autoCommit);
}
private synchronized void recordEvent(Resource subject, URI predicate,
Value object) {
Map<Resource, Set<Value>> map = events.get(predicate);
if (map == null) {
map = new HashMap<Resource, Set<Value>>();
events.put(predicate, map);
}
Set<Value> set = map.get(subject);
if (set == null) {
map.put(subject, set = new HashSet<Value>());
}
set.add(object);
}
private synchronized void fireEvents() throws RepositoryException,
QueryEvaluationException {
for (int i = 0; !events.isEmpty() && i < MAX_TRIG_STACK; i++) {
Map<URI, Map<Resource, Set<Value>>> firedEvents = events;
events = new HashMap(firedEvents.size());
for (URI pred : firedEvents.keySet()) {
Map<Resource, Set<Value>> map = firedEvents.get(pred);
Set<Trigger> set = triggers.get(pred);
Trigger sample = set.iterator().next();
Class<?> declaredIn = sample.getDeclaredIn();
Set<URI> roles = new HashSet<URI>(4);
Set<URI> types = getTypes(declaredIn, roles);
for (Map.Entry<Resource, Set<Value>> e : map.entrySet()) {
Object subj = of.createObject(e.getKey(), types);
for (Trigger trigger : set) {
invokeTrigger(trigger, subj, pred, e.getValue());
}
}
}
}
if (!events.isEmpty()) {
events.clear();
throw new RepositoryException("Trigger Overflow");
}
}
private <C extends Collection<URI>> C getTypes(Class<?> role, C set)
throws RepositoryException {
URI type = of.getNameOf(role);
if (type == null) {
Class<?> superclass = role.getSuperclass();
if (superclass != null) {
getTypes(superclass, set);
}
Class<?>[] interfaces = role.getInterfaces();
for (int i = 0, n = interfaces.length; i < n; i++) {
getTypes(interfaces[i], set);
}
} else {
set.add(type);
}
return set;
}
private void invokeTrigger(Trigger trigger, Object subj, URI pred, Set<Value> objs)
throws RepositoryException, QueryEvaluationException {
try {
String name = trigger.getMethodName();
Class<?>[] types = trigger.getParameterTypes();
int idx = trigger.getParameterIndex(pred);
if (idx < 0 && types.length > 0) {
logger.warn("No parameter for predicate: {} in {}", pred, trigger.getMethodName());
return;
}
Method method = subj.getClass().getMethod(name, types);
Object[] args = new Object[types.length];
boolean containsLiteral = containsLiteral(objs);
if (types.length == 0) {
// no arguments
method.invoke(subj, args);
} else if (types[idx].equals(Set.class) && !containsLiteral) {
// TODO get parameterized type
Resource[] resources = objs.toArray(new Resource[objs.size()]);
args[idx] = objects.getObjects(types[idx], resources).asSet();
method.invoke(subj, args);
} else if (types[idx].equals(Set.class)) {
Set<Object> arg = new HashSet<Object>(objs.size());
for (Value obj : objs) {
arg.add(objects.getObject(obj));
}
args[idx] = arg;
method.invoke(subj, args);
} else if (!containsLiteral) {
// TODO get parameterized type
Resource[] resources = objs.toArray(new Resource[objs.size()]);
for (Object arg : objects.getObjects(types[idx], resources).asSet()) {
args[idx] = arg;
method.invoke(subj, args);
}
} else {
for (Value obj : objs) {
args[idx] = objects.getObject(obj);
method.invoke(subj, args);
}
}
} catch (SecurityException e) {
throw new ObjectCompositionException(e);
} catch (IllegalArgumentException e) {
throw new ObjectCompositionException(e);
} catch (IllegalAccessException e) {
throw new ObjectCompositionException(e);
} catch (InvocationTargetException e) {
throw new RepositoryException(e.getCause());
} catch (NoSuchMethodException e) {
logger.debug("{} has no trigger {}", subj, trigger.getMethodName());
}
}
private boolean containsLiteral(Set<Value> objs) {
for (Value obj : objs) {
if (obj instanceof Literal) {
return true;
}
}
return false;
}
}
|
// This file is part of the OpenNMS(R) Application.
// reserved.
// OpenNMS(R) is a derivative work, containing both original code, included
// code and modified
// for modified
// and included code are below.
// OpenNMS(R) is a registered trademark of The OpenNMS Group, Inc.
// reserved.
// 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:
package org.opennms.netmgt.config;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.StringReader;
import junit.framework.TestCase;
import org.exolab.castor.xml.MarshalException;
import org.exolab.castor.xml.ValidationException;
import org.opennms.netmgt.config.monitoringLocations.LocationDef;
import org.opennms.netmgt.config.poller.Package;
import org.opennms.netmgt.mock.MockDatabase;
import org.opennms.netmgt.mock.MockNetwork;
import org.opennms.netmgt.model.OnmsMonitoredService;
/**
* @author <a href="mailto:david@opennms.org">David Hustace</a>
*/
public class MonitoringLocationsFactoryTest extends TestCase {
private MonitoringLocationsFactory m_locationFactory;
private PollerConfigManager m_pollerConfigManager;
protected void setUp() throws Exception {
super.setUp();
MockNetwork network = new MockNetwork();
MockDatabase db = new MockDatabase();
db.populate(network);
DataSourceFactory.setInstance(db);
Reader rdr = new InputStreamReader(
getClass().getResourceAsStream(
"/org/opennms/netmgt/config/monitoring-locations.testdata.xml"));
m_locationFactory = new MonitoringLocationsFactory(rdr);
rdr.close();
rdr = new InputStreamReader(
getClass().getResourceAsStream(
"/org/opennms/netmgt/config/poller-configuration.testdata.xml"));
m_pollerConfigManager = new TestPollerConfigManager(rdr, "localhost",
false);
rdr.close();
}
protected void tearDown() throws Exception {
super.tearDown();
}
@SuppressWarnings("unchecked")
public void testGetName() throws MarshalException, ValidationException,
IOException {
final String locationName = "RDU";
LocationDef def = m_locationFactory.getDef(locationName);
assertNotNull(def);
assertEquals(locationName, def.getLocationName());
assertEquals("raleigh", def.getMonitoringArea());
assertNotNull(m_pollerConfigManager.getPackage(def.getPollingPackageName()));
}
static class TestPollerConfigManager extends PollerConfigManager {
String m_xml;
public TestPollerConfigManager(Reader rdr, String localServer,
boolean verifyServer) throws MarshalException,
ValidationException, IOException {
super(rdr, localServer, verifyServer);
save();
}
public void update() throws IOException, MarshalException,
ValidationException {
reloadXML(new StringReader(m_xml));
}
protected void saveXml(String xml) throws IOException {
m_xml = xml;
}
public String getXml() {
return m_xml;
}
}
}
|
package org.eclipse.mylar.tasklist.internal;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.StringReader;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.List;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Result;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.TransformerFactoryConfigurationError;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.eclipse.mylar.core.MylarPlugin;
import org.eclipse.mylar.tasklist.AbstractCategory;
import org.eclipse.mylar.tasklist.ITask;
import org.eclipse.mylar.tasklist.ITaskHandler;
import org.eclipse.mylar.tasklist.ITaskListExternalizer;
import org.eclipse.mylar.tasklist.MylarTasklistPlugin;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
/**
* @author Mik Kersten and Ken Sueda
*/
public class TaskListExternalizer {
private List<ITaskListExternalizer> externalizers = new ArrayList<ITaskListExternalizer>();
private DefaultTaskListExternalizer defaultExternalizer = new DefaultTaskListExternalizer();
private String readVersion = "";
private boolean hasCaughtException = false;
public void initExtensions() {
TaskListExtensionReader.initExtensions(externalizers, defaultExternalizer);
}
// public void addExternalizer(ITaskListExternalizer externalizer) {
// externalizers.add(externalizer);
// defaultExternalizer.setExternalizers(externalizers);
// MylarTasklistPlugin.getTaskListManager().getTaskList().clear();
// readTaskList(MylarTasklistPlugin.getTaskListManager().getTaskList(), MylarTasklistPlugin.getTaskListManager().getTaskListFile());
// if(MylarTasklistPlugin.getDefault().getContributor() != null){
// MylarTasklistPlugin.getDefault().getContributor().restoreState(TaskListView.getDefault());
// if (TaskListView.getDefault() != null) {
// TaskListView.getDefault().getViewer().refresh();
public void removeExternalizer(ITaskListExternalizer externalizer) {
externalizers.remove(externalizer);
}
public void writeTaskList(TaskList tlist, File outFile) {
initExtensions();
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db;
Document doc = null;
try {
db = dbf.newDocumentBuilder();
doc = db.newDocument();
} catch (ParserConfigurationException e) {
MylarPlugin.log(e, "could not create document");
e.printStackTrace();
}
Element root = doc.createElement("TaskList");
root.setAttribute("Version", "1.0.1");
for (ITaskListExternalizer externalizer : externalizers) {
externalizer.createRegistry(doc, root);
}
for (AbstractCategory category : tlist.getCategories()) {
Element element = null;
for (ITaskListExternalizer externalizer : externalizers) {
if (externalizer.canCreateElementFor(category)) element = externalizer.createCategoryElement(category, doc, root);
}
if (element == null && defaultExternalizer.canCreateElementFor(category)) {
defaultExternalizer.createCategoryElement(category, doc, root);
} else if(element == null){
MylarPlugin.log("Did not externalize: " + category, this);
}
}
for (ITask task : tlist.getRootTasks()) {
try {
Element element = null;
for (ITaskListExternalizer externalizer : externalizers) {
if (externalizer.canCreateElementFor(task)) element = externalizer.createTaskElement(task, doc, root);
}
if (element == null && defaultExternalizer.canCreateElementFor(task)) {
defaultExternalizer.createTaskElement(task, doc, root);
} else if(element == null){
MylarPlugin.log("Did not externalize: " + task, this);
}
}catch (Exception e) {
MylarPlugin.log(e, e.getMessage());
}
}
doc.appendChild(root);
writeDOMtoFile(doc, outFile);
return;
}
/**
* Writes an XML file from a DOM.
*
* doc - the document to write
* file - the file to be written to
*/
private void writeDOMtoFile(Document doc, File file) {
try {
// A file output stream is an output stream for writing data to a File
OutputStream outputStream = new FileOutputStream(file);
writeDOMtoStream(doc, outputStream);
outputStream.flush();
outputStream.close();
} catch (Exception fnfe) {
MylarPlugin.log(fnfe, "Tasklist could not be found");
}
}
/**
* Writes the provided XML document out to the specified output stream.
*
* doc - the document to be written
* outputStream - the stream to which the document is to be written
*/
private void writeDOMtoStream(Document doc, OutputStream outputStream) {
// Prepare the DOM document for writing
// DOMSource - Acts as a holder for a transformation Source tree in the
// form of a Document Object Model (DOM) tree
Source source = new DOMSource(doc);
// StreamResult - Acts as an holder for a XML transformation result
// Prepare the output stream
Result result = new StreamResult(outputStream);
// An instance of this class can be obtained with the
// TransformerFactory.newTransformer method. This instance may
// then be used to process XML from a variety of sources and write
// the transformation output to a variety of sinks
Transformer xformer = null;
try {
xformer = TransformerFactory.newInstance().newTransformer();
//Transform the XML Source to a Result
xformer.transform(source, result);
} catch (TransformerConfigurationException e) {
e.printStackTrace();
} catch (TransformerFactoryConfigurationError e) {
e.printStackTrace();
} catch (TransformerException e1) {
e1.printStackTrace();
}
}
// private void writeTask(ITask task, Document doc, Element parent) {
public void readTaskList(TaskList tlist, File inFile) {
MylarTasklistPlugin.getDefault().restoreTaskHandlerState();
initExtensions();
hasCaughtException = false;
try {
// parse file
if (!inFile.exists())
return;
Document doc = openAsDOM(inFile);
if (doc == null) {
handleException(inFile, null, new MylarExternalizerException("Tasklist was not well formed XML"));
return;
}
// read root node to get version number
Element root = doc.getDocumentElement();
readVersion = root.getAttribute("Version");
if (readVersion.equals("1.0.0")) {
MylarPlugin.log("version: " + readVersion + " not supported", this);
// NodeList list = root.getChildNodes();
// for (int i = 0; i < list.getLength(); i++) {
// Node child = list.item(i);
// readTasksToNewFormat(child, tlist);
// //tlist.addRootTask(readTaskAndSubTasks(child, null, tlist));
} else {
NodeList list = root.getChildNodes();
for (int i = 0; i < list.getLength(); i++) {
Node child = list.item(i);
boolean wasRead = false;
try {
if (child.getNodeName().endsWith(DefaultTaskListExternalizer.TAG_CATEGORY)) {
for (ITaskListExternalizer externalizer : externalizers) {
if (externalizer.canReadCategory(child)) {
externalizer.readCategory(child, tlist);
wasRead = true;
break;
}
}
if (!wasRead && defaultExternalizer.canReadCategory(child)) {
defaultExternalizer.readCategory(child, tlist);
} else {
// MylarPlugin.log("Did not read: " +
// child.getNodeName(), this);
}
} else {
for (ITaskListExternalizer externalizer : externalizers) {
if (externalizer.canReadTask(child)) {
// TODO add the tasks properly
ITask newTask = externalizer.readTask(child, tlist, null, null);
ITaskHandler taskHandler = MylarTasklistPlugin.getDefault().getTaskHandlerForElement(newTask);
if(taskHandler != null){
newTask = taskHandler.taskAdded(newTask);
}
tlist.addRootTask(newTask);
wasRead = true;
break;
}
}
if (!wasRead && defaultExternalizer.canReadTask(child)) {
tlist.addRootTask(defaultExternalizer.readTask(child, tlist, null, null));
} else {
// MylarPlugin.log("Did not read: " + child.getNodeName(), this);
}
}
} catch (Exception e) {
handleException(inFile, child, e);
}
}
}
} catch (Exception e) {
handleException(inFile, null, e);
}
if (hasCaughtException) {
// if exception was caught, write out the new task file, so that it doesn't happen again.
// this is OK, since the original (corrupt) tasklist is saved.
// TODO: The problem with this is that if the orignal tasklist has tasks and bug reports, but a
// task is corrupted, the new tasklist that is written will not include the bug reports (since the
// bugzilla externalizer is not loaded. So there is a potentila that we can lose bug reports.
writeTaskList(tlist, inFile);
}
MylarTasklistPlugin.getDefault().restoreTaskHandlerState();
}
/**
* Opens the specified XML file and parses it into a DOM Document.
*
* Filename - the name of the file to open
* Return - the Document built from the XML file
* Throws - XMLException if the file cannot be parsed as XML
* - IOException if the file cannot be opened
*/
private Document openAsDOM(File inputFile) throws IOException {
// A factory API that enables applications to obtain a parser
// that produces DOM object trees from XML documents
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
// Using DocumentBuilder, obtain a Document from XML file.
DocumentBuilder builder = null;
Document document = null;
try {
// create new instance of DocumentBuilder
builder = factory.newDocumentBuilder();
} catch (ParserConfigurationException pce) {
inputFile.renameTo(new File(inputFile.getName() + "save.xml"));
MylarPlugin.log(pce, "Failed to load XML file");
}
try {
// Parse the content of the given file as an XML document
// and return a new DOM Document object. Also throws IOException
document = builder.parse(inputFile);
} catch (SAXException se) {
inputFile.renameTo(new File(inputFile.getName() + "save.xml"));
MylarPlugin.log(se, "Failed to parse XML file");
}
return document;
}
private void handleException(File inFile, Node child, Exception e) {
hasCaughtException = true;
String name = inFile.getAbsolutePath();
name = name.substring(0, name.lastIndexOf('.')) + "-save1.xml";
File save = new File(name);
int i = 2;
while(save.exists()) {
name = name.substring(0, name.lastIndexOf('.')-1) + i + ".xml";
save = new File(name);
i++;
}
if (!copy(inFile, save)) {
inFile.renameTo(new File(name));
}
if (child == null) {
MylarPlugin.log(e, "Could not read task list");
} else {
MylarPlugin.log(e, "Tasks may have been lost from " + child.getNodeName());
}
}
private boolean copy(File src, File dst) {
try {
InputStream in = new FileInputStream(src);
OutputStream out = new FileOutputStream(dst);
// Transfer bytes from in to out
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
in.close();
out.close();
return true;
} catch (IOException ioe) {
return false;
}
}
private Document openAsDOM(String input) throws IOException {
// A factory API that enables applications to obtain a parser
// that produces DOM object trees from XML documents
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
// Using DocumentBuilder, obtain a Document from XML file.
DocumentBuilder builder = null;
Document document = null;
try {
// create new instance of DocumentBuilder
builder = factory.newDocumentBuilder();
} catch (ParserConfigurationException pce) {
MylarPlugin.log(pce, "Failed to load XML file");
}
try {
// Parse the content of the given file as an XML document
// and return a new DOM Document object. Also throws IOException
StringReader s = new StringReader(input);
InputSource in = new InputSource(s);
document = builder.parse(in);
} catch (SAXException se) {
MylarPlugin.log(se, "Failed to parse XML file");
}
return document;
}
public void readTaskList(TaskList tlist, String input) {
initExtensions();
try {
Document doc = openAsDOM(input);
if (doc == null) {
return;
}
// read root node to get version number
Element root = doc.getDocumentElement();
readVersion = root.getAttribute("Version");
if (readVersion.equals("1.0.0")) {
MylarPlugin.log("version: " + readVersion + " not supported", this);
// NodeList list = root.getChildNodes();
// for (int i = 0; i < list.getLength(); i++) {
// Node child = list.item(i);
// readTasksToNewFormat(child, tlist);
// //tlist.addRootTask(readTaskAndSubTasks(child, null, tlist));
} else {
NodeList list = root.getChildNodes();
for (int i = 0; i < list.getLength(); i++) {
Node child = list.item(i);
boolean wasRead = false;
try {
if (child.getNodeName().endsWith(DefaultTaskListExternalizer.TAG_CATEGORY)) {
for (ITaskListExternalizer externalizer : externalizers) {
if (externalizer.canReadCategory(child)) {
externalizer.readCategory(child, tlist);
wasRead = true;
break;
}
}
if (!wasRead && defaultExternalizer.canReadCategory(child)) {
defaultExternalizer.readCategory(child, tlist);
} else {
// MylarPlugin.log("Did not read: " +
// child.getNodeName(), this);
}
} else {
for (ITaskListExternalizer externalizer : externalizers) {
if (externalizer.canReadTask(child)) {
// TODO add the tasks properly
ITask newTask = externalizer.readTask(child, tlist, null, null);
ITaskHandler taskHandler = MylarTasklistPlugin.getDefault().getTaskHandlerForElement(newTask);
if(taskHandler != null){
newTask = taskHandler.taskAdded(newTask);
}
tlist.addRootTask(newTask);
wasRead = true;
break;
}
}
if (!wasRead && defaultExternalizer.canReadTask(child)) {
tlist.addRootTask(defaultExternalizer.readTask(child, tlist, null, null));
} else {
// MylarPlugin.log("Did not read: " + child.getNodeName(), this);
}
}
} catch (Exception e) {
MylarPlugin.log(e, "can't read xml string");
}
}
}
} catch (Exception e) {
MylarPlugin.log(e, "can't read xml string");
}
}
public String getTaskListXml(TaskList tlist) {
// TODO make this and writeTaskList use the same base code
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db;
Document doc = null;
try {
db = dbf.newDocumentBuilder();
doc = db.newDocument();
} catch (ParserConfigurationException e) {
MylarPlugin.log(e, "could not create document");
e.printStackTrace();
}
Element root = doc.createElement("TaskList");
root.setAttribute("Version", "1.0.1");
for (ITaskListExternalizer externalizer : externalizers) {
externalizer.createRegistry(doc, root);
}
for (AbstractCategory category : tlist.getCategories()) {
Element element = null;
for (ITaskListExternalizer externalizer : externalizers) {
if (externalizer.canCreateElementFor(category)) element = externalizer.createCategoryElement(category, doc, root);
}
if (element == null && defaultExternalizer.canCreateElementFor(category)) {
defaultExternalizer.createCategoryElement(category, doc, root);
} else if(element == null){
MylarPlugin.log("Did not externalize: " + category, this);
}
}
for (ITask task : tlist.getRootTasks()) {
try {
Element element = null;
for (ITaskListExternalizer externalizer : externalizers) {
if (externalizer.canCreateElementFor(task)) element = externalizer.createTaskElement(task, doc, root);
}
if (element == null && defaultExternalizer.canCreateElementFor(task)) {
defaultExternalizer.createTaskElement(task, doc, root);
} else if(element == null){
MylarPlugin.log("Did not externalize: " + task, this);
}
}catch (Exception e) {
MylarPlugin.log(e, e.getMessage());
}
}
doc.appendChild(root);
StringWriter sw = new StringWriter();
Source source = new DOMSource(doc);
Result result = new StreamResult(sw);
Transformer xformer = null;
try {
xformer = TransformerFactory.newInstance().newTransformer();
//Transform the XML Source to a Result
xformer.transform(source, result);
} catch (Exception e) {
e.printStackTrace();
}
return sw.toString();
}
// private static ITask readTaskAndSubTasks(Node node, ITask root, TaskList
// tlist) {
// //extract node and create new sub task
// Element e = (Element) node;
// ITask t;
// String handle = "";
// if (e.hasAttribute("ID")) {
// handle = e.getAttribute("ID");
// } else {
// handle = e.getAttribute("Handle");
// String label = e.getAttribute("Label");
// String priority = e.getAttribute("Priority");
// if (e.getAttribute("Bugzilla").compareTo("true") == 0) {
// t = new BugzillaTask(handle, label, true);
// BugzillaTask bt = (BugzillaTask) t;
// bt.setState(BugTaskState.FREE);
// bt.setLastRefresh(new Date(new Long(e.getAttribute("LastDate"))
// .longValue()));
// if (e.getAttribute("Dirty").compareTo("true") == 0) {
// bt.setDirty(true);
// } else {
// bt.setDirty(false);
// if (bt.readBugReport() == false) {
// MylarPlugin.log("Failed to read bug report", null);
// } else {
// t = new Task(handle, label);
// t.setPriority(priority);
// t.setPath(e.getAttribute("Path"));
// if (e.getAttribute("Active").compareTo("true") == 0) {
// t.setActive(true);
// tlist.setActive(t, true);
// } else {
// t.setActive(false);
// if (e.getAttribute("Complete").compareTo("true") == 0) {
// t.setCompleted(true);
// } else {
// t.setCompleted(false);
// if (e.getAttribute("IsCategory").compareTo("true") == 0) {
// t.setIsCategory(true);
// } else {
// t.setIsCategory(false);
// if (e.hasAttribute("Notes")) {
// t.setNotes(e.getAttribute("Notes"));
// } else {
// t.setNotes("");
// if (e.hasAttribute("Elapsed")) {
// t.setElapsedTime(e.getAttribute("Elapsed"));
// } else {
// t.setElapsedTime("");
// if (e.hasAttribute("Estimated")) {
// t.setEstimatedTime(e.getAttribute("Estimated"));
// } else {
// t.setEstimatedTime("");
// int i = 0;
// while (e.hasAttribute("link"+i)) {
// t.getRelatedLinks().add(e.getAttribute("link"+i));
// if (!readVersion.equals("1.0.0")) {
// // for newer revisions
// i = 0;
// NodeList list = e.getChildNodes();
// for (i = 0; i < list.getLength(); i++) {
// Node child = list.item(i);
// t.addSubTask(readTaskAndSubTasks(child, t, tlist));
// if (root != null) {
// t.setParent(root);
// return t;
// private void readTaskCategory(Node node, TaskList tlist) {
// Element e = (Element) node;
// TaskCategory cat = new TaskCategory(e.getAttribute("Name"));
// tlist.addCategory(cat);
// NodeList list = node.getChildNodes();
// for (int i = 0; i < list.getLength(); i++) {
// Node child = list.item(i);
// cat.addTask(readTask(child, tlist, cat, null));
// private ITask readTask(Node node, TaskList tlist, TaskCategory cat, ITask parent) {
// Element e = (Element) node;
// ITask t;
// String handle = e.getAttribute("Handle");
// String label = e.getAttribute("Label");
// String priority = e.getAttribute("Priority");
// } else {
// t = new Task(handle, label);
// t.setPriority(priority);
// t.setPath(e.getAttribute("Path"));
// if (e.getAttribute("Active").compareTo("true") == 0) {
// t.setActive(true);
// tlist.setActive(t, true);
// } else {
// t.setActive(false);
// if (e.getAttribute("Complete").compareTo("true") == 0) {
// t.setCompleted(true);
// } else {
// t.setCompleted(false);
// if (e.hasAttribute("Notes")) {
// t.setNotes(e.getAttribute("Notes"));
// } else {
// t.setNotes("");
// if (e.hasAttribute("Elapsed")) {
// t.setElapsedTime(e.getAttribute("Elapsed"));
// } else {
// t.setElapsedTime("");
// if (e.hasAttribute("Estimated")) {
// t.setEstimatedTime(e.getAttribute("Estimated"));
// } else {
// t.setEstimatedTime("");
// int i = 0;
// while (e.hasAttribute("link"+i)) {
// t.getRelatedLinks().add(e.getAttribute("link"+i));
// t.setCategory(cat);
// t.setParent(parent);
// NodeList list = e.getChildNodes();
// for (i = 0; i < list.getLength(); i++) {
// Node child = list.item(i);
// t.addSubTask(readTask(child, tlist, null, t));
// return t;
// private void readTasksToNewFormat(Node node, TaskList tlist) {
// Element e = (Element) node;
// ITask t;
// String handle = e.getAttribute("Handle");
// String label = e.getAttribute("Label");
// if (e.getAttribute("IsCategory").compareTo("true") == 0) {
// TaskCategory c = new TaskCategory(label);
// NodeList list = e.getChildNodes();
// for (int i = 0; i < list.getLength(); i++) {
// Node child = list.item(i);
// readSubTasksToNewFormat(child, tlist, c);
// } else {
// String priority = e.getAttribute("Priority");
// if (e.getAttribute("Bugzilla").compareTo("true") == 0) {
// t = new BugzillaTask(handle, label, true);
// BugzillaTask bt = (BugzillaTask) t;
// bt.setState(BugTaskState.FREE);
// bt.setLastRefresh(new Date(new Long(e.getAttribute("LastDate"))
// .longValue()));
// if (e.getAttribute("Dirty").compareTo("true") == 0) {
// bt.setDirty(true);
// } else {
// bt.setDirty(false);
// if (bt.readBugReport() == false) {
// MylarPlugin.log("Failed to read bug report", null);
// } else {
// t = new Task(handle, label);
// t.setPriority(priority);
// t.setPath(e.getAttribute("Path"));
// t.setNotes(e.getAttribute("Notes"));
// t.setElapsedTime(e.getAttribute("Elapsed"));
// t.setEstimatedTime(e.getAttribute("Estimated"));
// if (e.getAttribute("Active").compareTo("true") == 0) {
// t.setActive(true);
// tlist.setActive(t, true);
// } else {
// t.setActive(false);
// if (e.getAttribute("Complete").compareTo("true") == 0) {
// t.setCompleted(true);
// } else {
// t.setCompleted(false);
// int i = 0;
// while (e.hasAttribute("link" + i)) {
// t.getRelatedLinks().add(e.getAttribute("link" + i));
// tlist.addRootTask(t);
// i = 0;
// NodeList list = e.getChildNodes();
// for (i = 0; i < list.getLength(); i++) {
// Node child = list.item(i);
// readSubTasksToNewFormat(child, tlist, null);
// private void readSubTasksToNewFormat(Node node, TaskList tlist, TaskCategory cat) {
// Element e = (Element) node;
// ITask t;
// String handle = e.getAttribute("Handle");
// String label = e.getAttribute("Label");
// String priority = e.getAttribute("Priority");
// if (e.getAttribute("Bugzilla").compareTo("true") == 0) {
// t = new BugzillaTask(handle, label, true);
// BugzillaTask bt = (BugzillaTask) t;
// bt.setState(BugTaskState.FREE);
// bt.setLastRefresh(new Date(new Long(e.getAttribute("LastDate"))
// .longValue()));
// if (e.getAttribute("Dirty").compareTo("true") == 0) {
// bt.setDirty(true);
// } else {
// bt.setDirty(false);
// if (bt.readBugReport() == false) {
// MylarPlugin.log("Failed to read bug report", null);
// } else {
// t = new Task(handle, label);
// t.setPriority(priority);
// t.setPath(e.getAttribute("Path"));
// t.setNotes(e.getAttribute("Notes"));
// t.setElapsedTime(e.getAttribute("Elapsed"));
// t.setEstimatedTime(e.getAttribute("Estimated"));
// if (e.getAttribute("Active").compareTo("true") == 0) {
// t.setActive(true);
// tlist.setActive(t, true);
// } else {
// t.setActive(false);
// if (e.getAttribute("Complete").compareTo("true") == 0) {
// t.setCompleted(true);
// } else {
// t.setCompleted(false);
// int i = 0;
// while (e.hasAttribute("link" + i)) {
// t.getRelatedLinks().add(e.getAttribute("link" + i));
// if (cat == null) {
// tlist.addRootTask(t);
// } else {
// cat.addTask(t);
// t.setCategory(cat);
// i = 0;
// NodeList list = e.getChildNodes();
// for (i = 0; i < list.getLength(); i++) {
// Node child = list.item(i);
// readSubTasksToNewFormat(child, tlist, cat);
}
|
package info.ata4.disunity.gui;
import info.ata4.disunity.gui.control.AssetTreePopupMenuListener;
import info.ata4.disunity.gui.model.AssetFileNode;
import info.ata4.disunity.gui.model.FieldTypeDatabaseNode;
import info.ata4.disunity.gui.util.DialogBuilder;
import info.ata4.disunity.gui.util.DialogBuilder.ReturnType;
import info.ata4.disunity.gui.util.FileExtensionFilter;
import info.ata4.disunity.gui.view.AssetTreeCellRenderer;
import info.ata4.unity.DisUnity;
import info.ata4.unity.asset.AssetFile;
import info.ata4.unity.assetbundle.AssetBundleUtils;
import info.ata4.unity.rtti.FieldTypeDatabase;
import info.ata4.util.progress.Progress;
import info.ata4.util.progress.ProgressMonitorWrapper;
import java.awt.Component;
import java.io.File;
import java.io.IOException;
import java.nio.file.Path;
import javax.swing.JFileChooser;
import javax.swing.ProgressMonitor;
import javax.swing.SwingWorker;
import javax.swing.tree.DefaultTreeModel;
import org.apache.commons.io.FilenameUtils;
/**
*
* @author Nico Bergemann <barracuda415 at yahoo.de>
*/
public class DisUnityWindow extends javax.swing.JFrame {
private File file;
/**
* Creates new form DisUnityWindow
*/
public DisUnityWindow() {
initComponents();
initComponentsCustom();
}
private void initComponentsCustom() {
dataTree.setCellRenderer(new AssetTreeCellRenderer());
dataTree.addMouseListener(new AssetTreePopupMenuListener(dataTree));
}
public void openFile(File file) {
try {
// check if the file is an asset bundle, these can't be opened or edited
// directly and need to be extracted
if (AssetBundleUtils.isAssetBundle(file.toPath())) {
ReturnType result = new DialogBuilder()
.question()
.withYesNo()
.withTitle("Extract asset bundle")
.withMessage("The selected file is an asset bundle and "
+ "first needs to be extracted to open its asset files.\n"
+ "Do you want to extract it now?")
.show();
if (result == ReturnType.YES) {
extractAssetBundles(true, file);
}
return;
}
AssetFile asset = new AssetFile();
asset.load(file.toPath());
dataTree.setModel(new DefaultTreeModel(new AssetFileNode(dataTree, asset)));
this.file = file; // for the file chooser
} catch (Exception ex) {
new DialogBuilder(this)
.exception(ex)
.withMessage("Can't open " + file.getName())
.show();
}
}
private void chooseAssetFile(File currentDirectory) {
JFileChooser fc = new JFileChooser(currentDirectory);
fc.addChoosableFileFilter(new FileExtensionFilter("Unity scene", "unity"));
fc.addChoosableFileFilter(new FileExtensionFilter("Unity asset", "asset", "assets", "sharedAssets"));
int result = fc.showOpenDialog(this);
if (result != JFileChooser.APPROVE_OPTION) {
return;
}
openFile(fc.getSelectedFile());
}
private void chooseAssetBundles(File currentDirectory) {
JFileChooser fc = new JFileChooser(currentDirectory);
fc.setDialogTitle("Select asset bundle file");
fc.setFileFilter(new FileExtensionFilter("Unity asset bundle", "unity3d"));
fc.setMultiSelectionEnabled(true);
int result = fc.showOpenDialog(this);
if (result != JFileChooser.APPROVE_OPTION) {
return;
}
extractAssetBundles(false, fc.getSelectedFiles());
}
private void extractAssetBundles(final boolean openAssetFileChooser, final File ... bundleFiles) {
JFileChooser fc = new JFileChooser(bundleFiles[bundleFiles.length - 1]);
fc.setDialogTitle("Select output directory");
fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
int result = fc.showOpenDialog(this);
if (result != JFileChooser.APPROVE_OPTION) {
return;
}
final File outputDir = fc.getSelectedFile();
new SwingWorker<Void, Void>() {
@Override
protected Void doInBackground() throws Exception {
Component parent = DisUnityWindow.this;
Path lastOutputPath = null;
for (File bundleFile : bundleFiles) {
ProgressMonitor monitor = new ProgressMonitor(parent, "Extracting " + bundleFile, null, 0, 0);
monitor.setMillisToDecideToPopup(0);
monitor.setMillisToPopup(0);
Progress progress = new ProgressMonitorWrapper(monitor);
String bundleName = FilenameUtils.removeExtension(bundleFile.getName());
Path bundlePath = bundleFile.toPath();
Path outputPath = outputDir.toPath().resolve(bundleName);
lastOutputPath = outputPath;
try {
AssetBundleUtils.extract(bundlePath, outputPath, progress);
} catch (Exception ex) {
new DialogBuilder(parent)
.exception(ex)
.withMessage("Can't extract file " + bundleFile)
.show();
}
}
// open file chooser in the last directory if requested
if (openAssetFileChooser && lastOutputPath != null) {
chooseAssetFile(lastOutputPath.toFile());
}
return null;
}
}.execute();
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
dataTreeScrollPane = new javax.swing.JScrollPane();
dataTree = new javax.swing.JTree();
menuBar = new javax.swing.JMenuBar();
fileMenu = new javax.swing.JMenu();
openMenuItem = new javax.swing.JMenuItem();
saveMenuItem = new javax.swing.JMenuItem();
saveAsMenuItem = new javax.swing.JMenuItem();
exitMenuItem = new javax.swing.JMenuItem();
jMenu1 = new javax.swing.JMenu();
openTypeDatabaseItem = new javax.swing.JMenuItem();
extractAssetBundleMenuItem = new javax.swing.JMenuItem();
helpMenu = new javax.swing.JMenu();
aboutMenuItem = new javax.swing.JMenuItem();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setTitle(DisUnity.getSignature());
dataTree.setModel(null);
dataTreeScrollPane.setViewportView(dataTree);
fileMenu.setMnemonic('f');
fileMenu.setText("File");
openMenuItem.setMnemonic('o');
openMenuItem.setText("Open");
openMenuItem.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
openMenuItemActionPerformed(evt);
}
});
fileMenu.add(openMenuItem);
saveMenuItem.setMnemonic('s');
saveMenuItem.setText("Save");
saveMenuItem.setEnabled(false);
fileMenu.add(saveMenuItem);
saveAsMenuItem.setMnemonic('a');
saveAsMenuItem.setText("Save As ...");
saveAsMenuItem.setDisplayedMnemonicIndex(5);
saveAsMenuItem.setEnabled(false);
fileMenu.add(saveAsMenuItem);
exitMenuItem.setMnemonic('x');
exitMenuItem.setText("Exit");
exitMenuItem.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
exitMenuItemActionPerformed(evt);
}
});
fileMenu.add(exitMenuItem);
menuBar.add(fileMenu);
jMenu1.setText("Tools");
openTypeDatabaseItem.setText("Open type tree database");
openTypeDatabaseItem.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
openTypeDatabaseItemActionPerformed(evt);
}
});
jMenu1.add(openTypeDatabaseItem);
extractAssetBundleMenuItem.setText("Extract asset bundle");
extractAssetBundleMenuItem.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
extractAssetBundleMenuItemActionPerformed(evt);
}
});
jMenu1.add(extractAssetBundleMenuItem);
menuBar.add(jMenu1);
helpMenu.setMnemonic('h');
helpMenu.setText("Help");
aboutMenuItem.setMnemonic('a');
aboutMenuItem.setText("About");
helpMenu.add(aboutMenuItem);
menuBar.add(helpMenu);
setJMenuBar(menuBar);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(dataTreeScrollPane, javax.swing.GroupLayout.DEFAULT_SIZE, 614, Short.MAX_VALUE)
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(dataTreeScrollPane, javax.swing.GroupLayout.DEFAULT_SIZE, 467, Short.MAX_VALUE)
.addContainerGap())
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void exitMenuItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_exitMenuItemActionPerformed
System.exit(0);
}//GEN-LAST:event_exitMenuItemActionPerformed
private void openMenuItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_openMenuItemActionPerformed
chooseAssetFile(file);
}//GEN-LAST:event_openMenuItemActionPerformed
private void openTypeDatabaseItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_openTypeDatabaseItemActionPerformed
dataTree.setModel(new DefaultTreeModel(new FieldTypeDatabaseNode(FieldTypeDatabase.getInstance())));
}//GEN-LAST:event_openTypeDatabaseItemActionPerformed
private void extractAssetBundleMenuItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_extractAssetBundleMenuItemActionPerformed
chooseAssetBundles(file);
}//GEN-LAST:event_extractAssetBundleMenuItemActionPerformed
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JMenuItem aboutMenuItem;
private javax.swing.JTree dataTree;
private javax.swing.JScrollPane dataTreeScrollPane;
private javax.swing.JMenuItem exitMenuItem;
private javax.swing.JMenuItem extractAssetBundleMenuItem;
private javax.swing.JMenu fileMenu;
private javax.swing.JMenu helpMenu;
private javax.swing.JMenu jMenu1;
private javax.swing.JMenuBar menuBar;
private javax.swing.JMenuItem openMenuItem;
private javax.swing.JMenuItem openTypeDatabaseItem;
private javax.swing.JMenuItem saveAsMenuItem;
private javax.swing.JMenuItem saveMenuItem;
// End of variables declaration//GEN-END:variables
}
|
package dr.evomodelxml.tree;
import dr.evolution.tree.*;
import dr.evomodel.tree.TreeLogger;
import dr.inference.loggers.LogFormatter;
import dr.inference.loggers.TabDelimitedFormatter;
import dr.inference.model.Likelihood;
import dr.inference.model.Model;
import dr.inferencexml.loggers.LoggerParser;
import dr.xml.*;
import java.io.PrintWriter;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
/**
* @author Karthik Gangavarapu
* @author Marc A. Suchard
*/
public class TreeReportParser extends LoggerParser {
private static final String REPORT_TREE = "reportTree";
private static final String BRANCH_LENGTHS = "branchLengths";
private static final String SUBSTITUTIONS = "substitutions";
private static final String SORT_TRANSLATION_TABLE = "sortTranslationTable";
private static final String DECIMAL_PLACES = "dp";
private static final String ALLOW_OVERWRITE_LOG = "overwrite";
private static final String FILTER_TRAITS = "traitFilter";
private static final String TREE_TRAIT = "trait";
private static final String NAME = "name";
private static final String TAG = "tag";
public String getParserName() {
return REPORT_TREE;
}
private String parseXMLParameters(XMLObject xo) throws XMLParseException {
// reset this every time...
branchRates = null;
tree = (Tree) xo.getChild(Tree.class);
sortTranslationTable = xo.getAttribute(SORT_TRANSLATION_TABLE, true);
boolean substitutions = xo.getAttribute(BRANCH_LENGTHS, "").equals(SUBSTITUTIONS);
List<TreeTraitProvider> ttps = new ArrayList<>();
// ttps2 are for TTPs that are not specified within a Trait element. These are only
// included if not already added through a trait element to avoid duplication of
// (in particular) the BranchRates which is required for substitution trees.
List<TreeTraitProvider> ttps2 = new ArrayList<>();
for (int i = 0; i < xo.getChildCount(); i++) {
Object cxo = xo.getChild(i);
if (cxo instanceof TreeTraitProvider) {
if (xo.hasAttribute(FILTER_TRAITS)) {
String[] matches = ((String) xo.getAttribute(FILTER_TRAITS)).split("[\\s,]+");
TreeTraitProvider ttp = (TreeTraitProvider) cxo;
TreeTrait[] traits = ttp.getTreeTraits();
List<TreeTrait> filteredTraits = new ArrayList<TreeTrait>();
for (String match : matches) {
for (TreeTrait trait : traits) {
if (trait.getTraitName().startsWith(match)) {
filteredTraits.add(trait);
}
}
}
if (filteredTraits.size() > 0) {
ttps2.add(new TreeTraitProvider.Helper(filteredTraits));
}
} else {
// Add all of them
ttps2.add((TreeTraitProvider) cxo);
}
}
if (cxo instanceof XMLObject) {
XMLObject xco = (XMLObject)cxo;
if (xco.getName().equals(TREE_TRAIT)) {
TreeTraitProvider ttp = (TreeTraitProvider)xco.getChild(TreeTraitProvider.class);
if (xco.hasAttribute(NAME)) {
// a specific named trait is required (optionally with a tag to name it in the tree file)
String name = xco.getStringAttribute(NAME);
final TreeTrait trait = ttp.getTreeTrait(name);
if (trait == null) {
String childName = "TreeTraitProvider";
if (ttp instanceof Likelihood) {
childName = ((Likelihood)ttp).prettyName();
} else if (ttp instanceof Model) {
childName = ((Model)ttp).getModelName();
}
throw new XMLParseException("Trait named, " + name + ", not found for " + childName);
}
final String tag;
if (xco.hasAttribute(TAG)) {
tag = xco.getStringAttribute(TAG);
} else {
tag = name;
}
ttps.add(new TreeTraitProvider.Helper(tag, new TreeTrait() {
public String getTraitName() {
return tag;
}
public Intent getIntent() {
return trait.getIntent();
}
public Class getTraitClass() {
return trait.getTraitClass();
}
public Object getTrait(Tree tree, NodeRef node) {
return trait.getTrait(tree, node);
}
public String getTraitString(Tree tree, NodeRef node) {
return trait.getTraitString(tree, node);
}
public boolean getLoggable() {
return trait.getLoggable();
}
}));
} else if (xo.hasAttribute(FILTER_TRAITS)) {
// else a filter attribute is given to ask for all traits that starts with a specific
// string
String[] matches = ((String) xo.getAttribute(FILTER_TRAITS)).split("[\\s,]+");
TreeTrait[] traits = ttp.getTreeTraits();
List<TreeTrait> filteredTraits = new ArrayList<TreeTrait>();
for (String match : matches) {
for (TreeTrait trait : traits) {
if (trait.getTraitName().startsWith(match)) {
filteredTraits.add(trait);
}
}
}
if (filteredTraits.size() > 0) {
ttps.add(new TreeTraitProvider.Helper(filteredTraits));
}
} else {
// neither named or filtered traits so just add them all
ttps.add(ttp);
}
}
}
}
if (ttps2.size() > 0) {
ttps.addAll(ttps2);
}
if (substitutions) {
branchRates = (BranchRates) xo.getChild(BranchRates.class);
}
if (substitutions && branchRates == null) {
throw new XMLParseException("To log trees in units of substitutions a BranchRateModel must be provided");
}
// decimal places
final int dp = xo.getAttribute(DECIMAL_PLACES, -1);
if (dp != -1) {
format = NumberFormat.getNumberInstance(Locale.ENGLISH);
format.setMaximumFractionDigits(dp);
}
final PrintWriter pw = getLogFile(xo, getParserName());
formatter = new TabDelimitedFormatter(pw);
treeTraitProviders = ttps.toArray(new TreeTraitProvider[ttps.size()]);
return TreeUtils.newick(tree, treeTraitProviders);
}
/**
* @return an object based on the XML element it was passed.
*/
public Object parseXMLObject(XMLObject xo) throws XMLParseException {
String report = parseXMLParameters(xo);
formatter.logLine(report);
return null;
}
protected Tree tree;
protected String title;
protected boolean nexusFormat;
protected boolean sortTranslationTable;
protected BranchRates branchRates;
protected NumberFormat format = null;
protected TreeLogger.LogUpon condition;
protected LogFormatter formatter;
protected TreeTraitProvider[] treeTraitProviders;
|
package dr.inference.markovchain;
import dr.evomodel.operators.AbstractImportanceDistributionOperator;
import dr.evomodel.operators.SimpleGibbsOperator;
import dr.inference.model.Likelihood;
import dr.inference.model.Model;
import dr.inference.model.CompoundLikelihood;
import dr.inference.operators.*;
import dr.inference.prior.Prior;
import java.util.ArrayList;
import java.util.logging.Logger;
/**
* A concrete markov chain. This is final as the only things that should need
* overriding are in the delegates (prior, likelihood, schedule and acceptor).
* The design of this class is to be fairly immutable as far as settings goes.
*
* @author Alexei Drummond
* @author Andrew Rambaut
* @version $Id: MarkovChain.java,v 1.10 2006/06/21 13:34:42 rambaut Exp $
*/
public final class MarkovChain {
private final OperatorSchedule schedule;
private final Acceptor acceptor;
private final Prior prior;
private final Likelihood likelihood;
private boolean pleaseStop = false;
private boolean isStopped = false;
private double bestScore, currentScore, initialScore;
private int currentLength;
private boolean useCoercion = true;
private final int fullEvaluationCount;
public MarkovChain(Prior prior, Likelihood likelihood,
OperatorSchedule schedule, Acceptor acceptor,
int fullEvaluationCount, boolean useCoercion) {
currentLength = 0;
this.prior = prior;
this.likelihood = likelihood;
this.schedule = schedule;
this.acceptor = acceptor;
this.useCoercion = useCoercion;
this.fullEvaluationCount = fullEvaluationCount;
currentScore = evaluate(likelihood, prior);
}
/**
* Resets the markov chain
*/
public void reset() {
currentLength = 0;
// reset operator acceptance levels
for(int i = 0; i < schedule.getOperatorCount(); i++) {
schedule.getOperator(i).reset();
}
}
/**
* Run the chain for a given number of states.
*
* @param length
* number of states to run the chain.
* @param onTheFlyOperatorWeights
* @param logOps
* Hack to log likelihood change with operators to stdout
*/
public int chain(int length, boolean disableCoerce,
int onTheFlyOperatorWeights, boolean logOps) {
boolean verbose = false;
currentScore = evaluate(likelihood, prior);
int currentState = currentLength;
final Model currentModel = likelihood.getModel();
if( currentState == 0 ) {
initialScore = currentScore;
bestScore = currentScore;
fireBestModel(currentState, currentModel);
}
if( currentScore == Double.NEGATIVE_INFINITY ) {
// identify which component of the score is zero...
if( prior != null ) {
double logPrior = prior.getLogPrior(likelihood.getModel());
if( logPrior == Double.NEGATIVE_INFINITY ) {
throw new IllegalArgumentException(
"The initial model is invalid because one of the priors has zero probability.");
}
}
String message = "The initial likelihood is zero";
if( likelihood instanceof CompoundLikelihood ) {
message += ": " + ((CompoundLikelihood) likelihood).getDiagnosis();
} else {
message += "!";
}
throw new IllegalArgumentException(message);
}
pleaseStop = false;
isStopped = false;
int otfcounter = onTheFlyOperatorWeights > 0 ? onTheFlyOperatorWeights
: 0;
double[] logr = {0.0};
while( !pleaseStop && (currentState < (currentLength + length)) ) {
// periodically log states
fireCurrentModel(currentState, currentModel);
if( pleaseStop ) {
isStopped = true;
break;
}
// Get the operator
final int op = schedule.getNextOperatorIndex();
final MCMCOperator mcmcOperator = schedule.getOperator(op);
final double oldScore = currentScore;
// not used and why must it be a "compund like"?
// String oldMessage =
// ((CompoundLikelihood)likelihood).getDiagnosis();
// assert Profiler.startProfile("Store");
// The current model is stored here in case the proposal fails
if( currentModel != null ) {
currentModel.storeModelState();
}
// assert Profiler.stopProfile("Store");
boolean operatorSucceeded = true;
double hastingsRatio = 1.0;
boolean accept = false;
logr[0] = -Double.MAX_VALUE;
try {
// The new model is proposed
// assert Profiler.startProfile("Operate");
if( verbose ) {
System.out.println("\n&& Operator: " + mcmcOperator.getOperatorName());
}
if( mcmcOperator instanceof SimpleGibbsOperator ) {
hastingsRatio = ((SimpleGibbsOperator) mcmcOperator).operate(prior, likelihood);
} else if( mcmcOperator instanceof AbstractImportanceDistributionOperator ) {
hastingsRatio = ((AbstractImportanceDistributionOperator) mcmcOperator).operate(prior, likelihood);
} else {
hastingsRatio = mcmcOperator.operate();
}
// assert Profiler.stopProfile("Operate");
} catch( OperatorFailedException e ) {
operatorSucceeded = false;
}
double score = 0.0;
double deviation = 0.0;
if( operatorSucceeded ) {
// The new model is proposed
// assert Profiler.startProfile("Evaluate");
if( verbose ) {
System.out.println("** Evaluate");
}
// The new model is evaluated
score = evaluate(likelihood, prior);
// assert Profiler.stopProfile("Evaluate");
// This is a test that the state is correctly restored. The
// restored state is fully evaluated and the likelihood compared with
// that before the operation was made.
if( currentState < fullEvaluationCount ) {
likelihood.makeDirty();
final double testScore = evaluate(likelihood, prior);
if( Math.abs(testScore - score) > 1e-6 ) {
Logger.getLogger("error").severe(
"State was not correctly calculated after an operator move.\n"
+ "Likelihood evaluation: " + score
+ "\nFull Likelihood evaluation: " + testScore
+ "\n" + "Operator: " + mcmcOperator
+ " " + mcmcOperator.getOperatorName());
}
}
if( score > bestScore ) {
bestScore = score;
fireBestModel(currentState, currentModel);
}
// accept = mcmcOperator instanceof GibbsOperator ||
// acceptor.accept(oldScore, score, hastingsRatio, logr);
if( mcmcOperator instanceof SimpleGibbsOperator ) {
accept = acceptor.accept(oldScore, score, hastingsRatio, logr);
} else {
accept = mcmcOperator instanceof GibbsOperator
|| acceptor.accept(oldScore, score, hastingsRatio, logr);
}
deviation = score - oldScore;
}
// The new model is accepted or rejected
if( accept ) {
if( verbose ) {
System.out.println("** Move accepted: new score = " + score
+ ", old score = " + oldScore);
}
if( logOps ) {
System.err.println("##" + (score - currentScore) + " "
+ mcmcOperator.getOperatorName());
}
mcmcOperator.accept(deviation);
currentModel.acceptModelState();
currentScore = score;
if( otfcounter > 0 ) {
--otfcounter;
if( otfcounter == 0 ) {
adjustOpWeights(currentState);
otfcounter = onTheFlyOperatorWeights;
}
}
} else {
if( verbose ) {
System.out.println("** Move rejected: new score = " + score
+ ", old score = " + oldScore);
}
mcmcOperator.reject();
// assert Profiler.startProfile("Restore");
currentModel.restoreModelState();
// Sebastian: can't tell why but somehow the likelihood is
// screwed up if the tree needs to be restored
// the only way to get around this problem was ->
// likelihood.makeDirty();
// Comment by AR 12/04/2009 - this problem was indicative of an
// error elsewhere any by adding this line a major efficiency saving
// was lost.
// assert Profiler.stopProfile("Restore");
// This is a test that the state is correctly restored. The
// restored state is fully evaluated and the likelihood compared with
// that before the operation was made.
if( currentState < fullEvaluationCount ) {
likelihood.makeDirty();
final double testScore = evaluate(likelihood, prior);
if( Math.abs(testScore - oldScore) > 1e-6 ) {
Logger.getLogger("error").severe(
"State was not correctly restored after reject step.\n"
+ "Likelihood before: " + oldScore
+ " Likelihood after: " + testScore
+ "\n" + "Operator: " + mcmcOperator
+ " " + mcmcOperator.getOperatorName());
}
}
}
if( !disableCoerce && mcmcOperator instanceof CoercableMCMCOperator ) {
coerceAcceptanceProbability((CoercableMCMCOperator) mcmcOperator, logr[0]);
}
currentState += 1;
}
currentLength = currentState;
fireFinished(currentLength);
// Profiler.report();
return currentLength;
}
private void adjustOpWeights(int currentState) {
final int count = schedule.getOperatorCount();
double[] s = new double[count];
final double factor = 100;
final double limitSpan = 1000;
System.err.println("start cycle " + currentState);
double sHas = 0.0/* , sNot = 0.0 */, nHas = 0.0;
for(int no = 0; no < count; ++no) {
final MCMCOperator op = schedule.getOperator(no);
final double v = op.getSpan(true);
if( v == 0 ) {
// sNot += op.getWeight();
s[no] = 0;
} else {
sHas += op.getWeight();
s[no] = Math.max(factor * Math.min(v, limitSpan), 1);
nHas += s[no];
}
}
// for(int no = 0; no < count; ++no) {
// final MCMCOperator op = schedule.getOperator(no);
// final double v = op.getSpan(false);
// if( v == 0 ) {
// System.err.println(op.getOperatorName() + " blocks");
// return;
// keep sum of changed parts unchanged
final double scaleHas = sHas / nHas;
for(int no = 0; no < count; ++no) {
final MCMCOperator op = schedule.getOperator(no);
if( s[no] > 0 ) {
final double val = s[no] * scaleHas;
op.setWeight(val);
System.err.println("set " + op.getOperatorName() + " " + val);
} else {
System.err.println("** " + op.getOperatorName() + " = "
+ op.getWeight());
}
}
schedule.operatorsHasBeenUpdated();
}
public Prior getPrior() {
return prior;
}
public Likelihood getLikelihood() {
return likelihood;
}
public Model getModel() {
return likelihood.getModel();
}
public OperatorSchedule getSchedule() {
return schedule;
}
public Acceptor getAcceptor() {
return acceptor;
}
public double getInitialScore() {
return initialScore;
}
public double getBestScore() {
return bestScore;
}
public int getCurrentLength() {
return currentLength;
}
public void setCurrentLength(int currentLength) {
this.currentLength = currentLength;
}
public double getCurrentScore() {
return currentScore;
}
public void pleaseStop() {
pleaseStop = true;
}
public boolean isStopped() {
return isStopped;
}
private double evaluate(Likelihood likelihood, Prior prior) {
double logPosterior = 0.0;
if( prior != null ) {
final double logPrior = prior.getLogPrior(likelihood.getModel());
if( logPrior == Double.NEGATIVE_INFINITY ) {
return Double.NEGATIVE_INFINITY;
}
logPosterior += logPrior;
}
final double logLikelihood = likelihood.getLogLikelihood();
if( Double.isNaN(logLikelihood) ) {
return Double.NEGATIVE_INFINITY;
}
// System.err.println("** " + logPosterior + " + " + logLikelihood +
// " = " + (logPosterior + logLikelihood));
logPosterior += logLikelihood;
return logPosterior;
}
/**
* Updates the proposal parameter, based on the target acceptance
* probability This method relies on the proposal parameter being a
* decreasing function of acceptance probability.
*
* @param op The operator
* @param logr
*/
private void coerceAcceptanceProbability(CoercableMCMCOperator op, double logr) {
if( isCoercable(op) ) {
final double p = op.getCoercableParameter();
final double i = schedule.getOptimizationTransform(MCMCOperator.Utils.getOperationCount(op));
final double target = op.getTargetAcceptanceProbability();
final double newp = p + ((1.0 / (i + 1.0)) * (Math.exp(logr) - target));
if( newp > -Double.MAX_VALUE && newp < Double.MAX_VALUE ) {
op.setCoercableParameter(newp);
}
}
}
private boolean isCoercable(CoercableMCMCOperator op) {
return op.getMode() == CoercionMode.COERCION_ON
|| (op.getMode() != CoercionMode.COERCION_OFF && useCoercion);
}
public void addMarkovChainListener(MarkovChainListener listener) {
listeners.add(listener);
}
public void removeMarkovChainListener(MarkovChainListener listener) {
listeners.remove(listener);
}
public void fireBestModel(int state, Model bestModel) {
for(MarkovChainListener listener : listeners) {
listener.bestState(state, bestModel);
}
}
public void fireCurrentModel(int state, Model currentModel) {
for(MarkovChainListener listener : listeners) {
listener.currentState(state, currentModel);
}
}
public void fireFinished(int chainLength) {
for(MarkovChainListener listener : listeners) {
listener.finished(chainLength);
}
}
private final ArrayList<MarkovChainListener> listeners = new ArrayList<MarkovChainListener>();
}
|
// samskivert library - useful routines for java programs
// This library is free software; you can redistribute it and/or modify it
// (at your option) any later version.
// This library is distributed in the hope that it will be useful,
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// You should have received a copy of the GNU Lesser General Public
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
package com.samskivert.servlet.user;
import java.sql.Date;
import com.samskivert.jdbc.jora.FieldMask;
import com.samskivert.util.StringUtil;
/**
* A user object contains information about a registered user in our web application environment.
* Users are stored in the user repository (a database table) and loaded during a request based on
* authentication information provided with the request headers.
*
* <p><b>Note:</b> Do not modify any of the fields of this object directly. Use the
* <code>set</code> methods to make updates. If no set methods exist, you shouldn't be modifying
* that field.
*/
public class User
{
/** The user's assigned integer userid. */
public int userId;
/** The user's chosen username. */
public String username;
/** The date this record was created. */
public Date created;
/** The user's real name (first, last and whatever else they opt to provide). */
public String realname;
/** The user's chosen password (encrypted). */
public String password;
/** The user's email address. */
public String email;
/** The site identifier of the site through which the user created their account. (Their
* affiliation, if you will.) */
public int siteId;
/**
* Updates the user's username.
*/
public void setUsername (Username username)
{
this.username = username.getUsername();
setModified("username");
}
/**
* Updates the user's real name.
*/
public void setRealName (String realname)
{
this.realname = realname;
setModified("realname");
}
/**
* Updates the user's password.
*
* @param password The user's new (unencrypted) password.
*/
public void setPassword (String password)
{
setPassword(Password.makeFromClear(password));
}
/**
* Updates the user's password.
*
* @param password The user's new password.
*/
public void setPassword (Password password)
{
this.password = password.getEncrypted();
setModified("password");
}
/**
* Updates the user's email address.
*/
public void setEmail (String email)
{
this.email = email;
setModified("email");
}
/**
* Updates the user's site id.
*/
public void setSiteId (int siteId)
{
this.siteId = siteId;
setModified("siteId");
}
/**
* Compares the supplied password with the password associated with this user record.
*
* @return true if the passwords match, false if they do not.
*/
public boolean passwordsMatch (Password password)
{
return this.password.equals(password.getEncrypted());
}
/**
* @return true if this User has been "deleted".
*/
public boolean isDeleted ()
{
// a deleted account has an "=" in the username
return (-1 != username.indexOf('='));
}
/**
* Returns true if this user is an admin, false otherwise. The default implementation does not
* track admin status and always returns false.
*/
public boolean isAdmin ()
{
return false;
}
@Override // from Object
public String toString ()
{
return StringUtil.fieldsToString(this);
}
/**
* Called by the repository to find out which fields have been modified since the object was
* loaded.
*/
protected FieldMask getDirtyMask ()
{
return _dirty;
}
/**
* Called by the repository to configure this user record with a field mask that it can use to
* track modified fields.
*/
protected void setDirtyMask (FieldMask dirty)
{
_dirty = dirty;
}
/**
* Marks the supplied field as dirty.
*/
protected void setModified (String field)
{
_dirty.setModified(field);
}
/** Our dirty field mask. */
protected transient FieldMask _dirty;
}
|
package dr.inference.operators;
import dr.inference.model.Bounds;
import dr.inference.model.Parameter;
import dr.inference.model.Variable;
import dr.math.MathUtils;
import dr.xml.*;
import java.util.logging.Logger;
/**
* A generic scale operator for use with a multi-dimensional parameters.
* Either scale all dimentions at once or scale one dimention at a time.
* An optional bit vector and a threshold is used to vary the rate of the individual dimentions according
* to their on/off status. For example a threshold of 1 means pick only "on" dimentions.
*
* @author Alexei Drummond
* @author Andrew Rambaut
* @version $Id: ScaleOperator.java,v 1.20 2005/06/14 10:40:34 rambaut Exp $
*/
public class ScaleOperator extends AbstractCoercableOperator {
public static final String SCALE_OPERATOR = "scaleOperator";
public static final String SCALE_ALL = "scaleAll";
public static final String SCALE_ALL_IND = "scaleAllIndependently";
public static final String SCALE_FACTOR = "scaleFactor";
public static final String DEGREES_OF_FREEDOM = "df";
public static final String INDICATORS = "indicators";
public static final String PICKONEPROB = "pickoneprob";
private Parameter indicator;
private double indicatorOnProb;
public ScaleOperator(Variable variable, double scale) {
this(variable, scale, CoercionMode.COERCION_ON, 1.0);
}
public ScaleOperator(Variable<Double> variable, double scale, CoercionMode mode, double weight) {
this(variable, false, 0, scale, mode, null, 1.0, false);
setWeight(weight);
}
public ScaleOperator(Variable<Double> variable, boolean scaleAll, int degreesOfFreedom, double scale,
CoercionMode mode, Parameter indicator, double indicatorOnProb, boolean scaleAllInd) {
super(mode);
this.variable = variable;
this.indicator = indicator;
this.indicatorOnProb = indicatorOnProb;
this.scaleAll = scaleAll;
this.scaleAllIndependently = scaleAllInd;
this.scaleFactor = scale;
this.degreesOfFreedom = degreesOfFreedom;
}
/**
* @return the parameter this operator acts on.
*/
public Variable getVariable() {
return variable;
}
/**
* change the parameter and return the hastings ratio.
*/
public final double doOperation() throws OperatorFailedException {
final double scale = (scaleFactor + (MathUtils.nextDouble() * ((1.0 / scaleFactor) - scaleFactor)));
double logq;
final Bounds<Double> bounds = variable.getBounds();
final int dim = variable.getSize();
if (scaleAllIndependently) {
// update all dimensions independently.
logq = 0;
for (int i = 0; i < dim; i++) {
final double scaleOne = (scaleFactor + (MathUtils.nextDouble() * ((1.0 / scaleFactor) - scaleFactor)));
final double value = scaleOne * variable.getValue(i);
logq -= Math.log(scaleOne);
if (value < bounds.getLowerLimit(i) || value > bounds.getUpperLimit(i)) {
throw new OperatorFailedException("proposed value outside boundaries");
}
variable.setValue(i, value);
}
} else if (scaleAll) {
// update all dimensions
// hasting ratio is dim-2 times of 1dim case. would be nice to have a reference here
// for the proof. It is supposed to be somewhere in an Alexei/Nicholes article.
if (degreesOfFreedom > 0)
// For parameters with non-uniform prior on only one dimension
logq = -degreesOfFreedom * Math.log(scale);
else
logq = (dim - 2) * Math.log(scale);
// Must first set all parameters first and check for boundaries later for the operator to work
// correctly with dependent parameters such as tree node heights.
for (int i = 0; i < dim; i++) {
variable.setValue(i, variable.getValue(i) * scale);
}
for (int i = 0; i < dim; i++) {
if (variable.getValue(i) < variable.getBounds().getLowerLimit(i) ||
variable.getValue(i) > variable.getBounds().getUpperLimit(i)) {
throw new OperatorFailedException("proposed value outside boundaries");
}
}
} else {
logq = -Math.log(scale);
// which bit to scale
int index;
if (indicator != null) {
final int idim = indicator.getDimension();
final boolean impliedOne = idim == (dim - 1);
// available bit locations
int[] loc = new int[idim + 1];
int nLoc = 0;
// choose active or non active ones?
final boolean takeOne = indicatorOnProb >= 1.0 || MathUtils.nextDouble() < indicatorOnProb;
if (impliedOne && takeOne) {
loc[nLoc] = 0;
++nLoc;
}
for (int i = 0; i < idim; i++) {
final double value = indicator.getStatisticValue(i);
if (takeOne == (value > 0)) {
loc[nLoc] = i + (impliedOne ? 1 : 0);
++nLoc;
}
}
if (nLoc > 0) {
final int rand = MathUtils.nextInt(nLoc);
index = loc[rand];
} else {
throw new OperatorFailedException("no active indicators");
}
} else {
// any is good
index = MathUtils.nextInt(dim);
}
final double oldValue = variable.getValue(index);
if (oldValue == 0) {
Logger.getLogger("dr.inference").warning("The " + SCALE_OPERATOR +
" for " +
variable.getVariableName()
+ " has failed since the parameter has a value of 0.0." +
"\nTo fix this problem, initalize the value of " +
variable.getVariableName() + " to be a positive real number"
);
throw new OperatorFailedException("");
}
final double newValue = scale * oldValue;
if (newValue < bounds.getLowerLimit(index) || newValue > bounds.getUpperLimit(index)) {
throw new OperatorFailedException("proposed value outside boundaries");
}
variable.setValue(index, newValue);
// provides a hook for subclasses
cleanupOperation(newValue, oldValue);
}
return logq;
}
/**
* This method should be overridden by operators that need to do something just before the return of doOperation.
*
* @param newValue the proposed parameter value
* @param oldValue the old parameter value
*/
void cleanupOperation(double newValue, double oldValue) {
// DO NOTHING
}
//MCMCOperator INTERFACE
public final String getOperatorName() {
return "scale(" + variable.getVariableName() + ")";
}
public double getCoercableParameter() {
return Math.log(1.0 / scaleFactor - 1.0);
}
public void setCoercableParameter(double value) {
scaleFactor = 1.0 / (Math.exp(value) + 1.0);
}
public double getRawParameter() {
return scaleFactor;
}
public double getScaleFactor() {
return scaleFactor;
}
public double getTargetAcceptanceProbability() {
return 0.234;
}
public final String getPerformanceSuggestion() {
double prob = MCMCOperator.Utils.getAcceptanceProbability(this);
double targetProb = getTargetAcceptanceProbability();
dr.util.NumberFormatter formatter = new dr.util.NumberFormatter(5);
double sf = OperatorUtils.optimizeScaleFactor(scaleFactor, prob, targetProb);
if (prob < getMinimumGoodAcceptanceLevel()) {
return "Try setting scaleFactor to about " + formatter.format(sf);
} else if (prob > getMaximumGoodAcceptanceLevel()) {
return "Try setting scaleFactor to about " + formatter.format(sf);
} else return "";
}
public static dr.xml.XMLObjectParser PARSER = new dr.xml.AbstractXMLObjectParser() {
public String getParserName() {
return SCALE_OPERATOR;
}
public Object parseXMLObject(XMLObject xo) throws XMLParseException {
final boolean scaleAll = xo.getAttribute(SCALE_ALL, false);
final boolean scaleAllInd = xo.getAttribute(SCALE_ALL_IND, false);
final int degreesOfFreedom = xo.getAttribute(DEGREES_OF_FREEDOM, 0);
final CoercionMode mode = CoercionMode.parseMode(xo);
final double weight = xo.getDoubleAttribute(WEIGHT);
final double scaleFactor = xo.getDoubleAttribute(SCALE_FACTOR);
if (scaleFactor <= 0.0 || scaleFactor >= 1.0) {
throw new XMLParseException("scaleFactor must be between 0.0 and 1.0");
}
final Parameter parameter = (Parameter) xo.getChild(Parameter.class);
Parameter indicator = null;
double indicatorOnProb = 1.0;
final XMLObject inds = xo.getChild(INDICATORS);
if (inds != null) {
indicator = (Parameter) inds.getChild(Parameter.class);
if (inds.hasAttribute(PICKONEPROB)) {
indicatorOnProb = inds.getDoubleAttribute(PICKONEPROB);
if (!(0 <= indicatorOnProb && indicatorOnProb <= 1)) {
throw new XMLParseException("pickoneprob must be between 0.0 and 1.0");
}
}
}
ScaleOperator operator = new ScaleOperator(parameter, scaleAll,
degreesOfFreedom, scaleFactor,
mode, indicator, indicatorOnProb,
scaleAllInd);
operator.setWeight(weight);
return operator;
}
|
package com.threerings.gwt.ui;
import java.util.List;
import com.google.gwt.user.client.ui.Widget;
/**
* Displays a table of UI elements in pages.
*/
public abstract class PagedTable<T> extends PagedWidget<T>
{
public PagedTable (int rows)
{
this(rows, NAV_ON_TOP);
}
public PagedTable (int rows, int navLoc)
{
super(rows, navLoc);
_rows = rows;
setStyleName("pagedGrid"); // Yoink
}
@Override
protected SmartTable createContents (int start, int count, List<T> list)
{
SmartTable table = new SmartTable();
table.setWidth("100%");
if (addRow(table, createHeader())) {
table.getRowFormatter().setStyleName(0, "header");
}
for (int row=0; row<list.size(); ++row) {
if (addRow(table, createRow(list.get(row)))) {
table.getRowFormatter().setStyleName(table.getRowCount()-1, "row" + (row%2));
didAddRow(table, table.getRowCount()-1, list.get(row));
}
}
return table;
}
/** Convenience function to append a list of widgets to a table as a new row. */
protected static boolean addRow (SmartTable table, List<Widget> widgets)
{
int row = table.getRowCount();
if (widgets != null) {
for (int col=0; col<widgets.size(); ++col) {
table.setWidget(row, col, widgets.get(col));
table.getFlexCellFormatter().setStyleName(row, col, "col"+col);
}
return true;
} else {
return false;
}
}
protected List<Widget> createHeader ()
{
// By default, don't show a header
return null;
}
/**
* Lets subclasses know that a row was just added, for example to customize row styles.
*/
protected void didAddRow (SmartTable table, int row, T item)
{
}
/** From a data item, create a table row in the form of a list of widgets. */
protected abstract List<Widget> createRow (T item);
protected int _rows;
}
|
package org.metaborg.spoofax.core.tracing;
import javax.annotation.Nullable;
import org.apache.commons.vfs2.FileObject;
import org.metaborg.core.MetaborgException;
import org.metaborg.core.source.ISourceLocation;
import org.metaborg.core.source.ISourceRegion;
import org.metaborg.spoofax.core.stratego.IStrategoCommon;
import org.metaborg.util.log.ILogger;
import org.metaborg.util.log.LoggerUtils;
import org.spoofax.interpreter.terms.IStrategoTerm;
import org.spoofax.interpreter.terms.ITermFactory;
import org.strategoxt.HybridInterpreter;
import com.google.inject.Inject;
public class TracingCommon {
/**
* Data class representing a term with its corresponding region in the source text.
*/
public static class TermWithRegion {
public final IStrategoTerm term;
public final ISourceRegion region;
public TermWithRegion(IStrategoTerm term, ISourceRegion region) {
this.term = term;
this.region = region;
}
}
private static final ILogger logger = LoggerUtils.logger(TracingCommon.class);
private final ISpoofaxTracingService tracingService;
private final IStrategoCommon common;
@Inject public TracingCommon(ISpoofaxTracingService tracingService, IStrategoCommon common) {
this.tracingService = tracingService;
this.common = common;
}
public TermWithRegion outputs(ITermFactory termFactory, HybridInterpreter runtime, FileObject location,
FileObject resource, IStrategoTerm result, Iterable<IStrategoTerm> inRegion, String strategy)
throws MetaborgException {
for(IStrategoTerm term : inRegion) {
final IStrategoTerm inputTerm = common.builderInputTerm(term, resource, location);
final IStrategoTerm output = common.invoke(runtime, inputTerm, strategy);
if(output == null) {
continue;
}
final ISourceLocation highlightLocation = tracingService.location(term);
if(highlightLocation == null) {
logger.debug("Cannot get source region for {}", term);
continue;
}
return new TermWithRegion(output, highlightLocation.region());
}
return null;
}
public @Nullable ISourceLocation getTargetLocation(IStrategoTerm term) {
final ISourceLocation targetLocation = tracingService.location(term);
if(targetLocation == null || targetLocation.resource() == null) {
return null;
}
return targetLocation;
}
}
|
package org.smeup.sys.il.esam.jdbc;
import java.sql.SQLException;
import org.smeup.sys.db.core.QConnection;
import org.smeup.sys.il.data.DataSpecial;
import org.smeup.sys.il.data.QDataContext;
import org.smeup.sys.il.data.QIndicator;
import org.smeup.sys.il.data.QNumeric;
import org.smeup.sys.il.data.QRecord;
import org.smeup.sys.il.data.QString;
import org.smeup.sys.il.esam.AccessMode;
import org.smeup.sys.il.esam.OperationRead;
import org.smeup.sys.il.esam.OperationSet;
import org.smeup.sys.il.esam.QIndex;
import org.smeup.sys.il.esam.QRRDataSet;
public class JDBCRelativeRecordDataSetImpl<R extends QRecord> extends JDBCDataSetImpl<R> implements QRRDataSet<R> {
protected JDBCRelativeRecordDataSetImpl(QConnection databaseConnection, QString tableName, QIndex index, R record, AccessMode accessMode, boolean userOpen, JDBCInfoStruct infoStruct,
QDataContext dataContext) {
super(databaseConnection, tableName, index, record, accessMode, userOpen, infoStruct, dataContext);
}
@Override
public boolean chain(int relativeRecordNumber) {
return chain(relativeRecordNumber, null, null, null);
}
@Override
public boolean chain(int relativeRecordNumber, QIndicator notFound) {
return chain(relativeRecordNumber, notFound, null, null);
}
@Override
public boolean chain(int relativeRecordNumber, QIndicator notFound, Boolean lock) {
return chain(relativeRecordNumber, notFound, null, lock);
}
@Override
public boolean chain(QNumeric relativeRecordNumber, Boolean lock) {
return chain(relativeRecordNumber, null, null, lock);
}
@Override
public boolean chain(int relativeRecordNumber, QIndicator notFound, QIndicator error, Boolean lock) {
try {
Object[] keyList = new Object[] { relativeRecordNumber };
prepareAccess(OperationSet.CHAIN, keyList, OperationRead.CHAIN, keyList, false);
// return readNext();
readNext();
} catch (SQLException e) {
handleSQLException(e);
}
if (notFound != null)
notFound.eval(!isFound());
if (error != null)
error.eval(onError());
return isFound();
}
@Override
public boolean chain(QNumeric relativeRecordNumber) {
return chain(relativeRecordNumber.asInteger());
}
@Override
public boolean chain(QNumeric relativeRecordNumber, QIndicator notFound) {
return chain(relativeRecordNumber.asInteger(), notFound);
}
@Override
public boolean chain(QNumeric relativeRecordNumber, QIndicator notFound, Boolean lock) {
return chain(relativeRecordNumber, notFound, null, lock);
}
@Override
public boolean chain(QNumeric relativeRecordNumber, QIndicator notFound, QIndicator error) {
return chain(relativeRecordNumber, notFound, error, null);
}
@Override
public boolean chain(QNumeric relativeRecordNumber, QIndicator notFound, QIndicator error, Boolean lock) {
return chain(relativeRecordNumber.asInteger(), notFound, error, lock);
}
@Override
public void setgt(DataSpecial keyField) {
setgt(Integer.MAX_VALUE);
}
@Override
public void setgt(int relativeRecordNumber) {
setgt(relativeRecordNumber, null, null);
}
@Override
public void setgt(int relativeRecordNumber, QIndicator notFound) {
setgt(relativeRecordNumber, notFound, null);
}
@Override
public void setgt(int relativeRecordNumber, QIndicator notFound, QIndicator error) {
Object[] keyList = { relativeRecordNumber };
setKeySet(OperationSet.SET_GREATER_THAN, keyList);
if (notFound != null)
notFound.eval(!isFound());
if (error != null)
error.eval(onError());
}
@Override
public void setgt(QNumeric relativeRecordNumber) {
setgt(relativeRecordNumber.asInteger());
}
@Override
public void setgt(QNumeric relativeRecordNumber, QIndicator found) {
setgt(relativeRecordNumber.asInteger(), found);
}
@Override
public void setgt(QNumeric relativeRecordNumber, QIndicator found, QIndicator error) {
setgt(relativeRecordNumber.asInteger(), found, error);
}
@Override
public void setll(DataSpecial keyField) {
setll(Integer.MAX_VALUE);
}
@Override
public void setll(int relativeRecordNumber) {
setll(relativeRecordNumber, null, null, null);
}
@Override
public void setll(int relativeRecordNumber, QIndicator notFound) {
setll(relativeRecordNumber, notFound, null, null);
}
@Override
public void setll(QNumeric relativeRecordNumber, QIndicator notFound, QIndicator equal) {
setll(relativeRecordNumber.asInteger(), notFound, equal);
}
@Override
public void setll(int relativeRecordNumber, QIndicator notFound, QIndicator equal) {
setll(relativeRecordNumber, notFound, equal, null);
}
@Override
public void setll(int relativeRecordNumber, QIndicator notFound, QIndicator equal, QIndicator error) {
Object[] keyList = { relativeRecordNumber };
setKeySet(OperationSet.SET_LOWER_LIMIT, keyList);
if (notFound != null)
notFound.eval(!isFound());
if (equal != null)
equal.eval(isEqual());
if (error != null)
error.eval(onError());
}
@Override
public void setll(QNumeric relativeRecordNumber) {
setll(relativeRecordNumber.asInteger());
}
@Override
public void delete(QNumeric relativeRecordNumber, QIndicator notFound) {
Object[] keyList = { relativeRecordNumber };
deleteRecord(keyList, notFound, null);
}
@Override
public void delete(QNumeric relativeRecordNumber, QIndicator notFound, QIndicator error) {
Object[] keyList = { relativeRecordNumber };
deleteRecord(keyList, notFound, error);
}
} // QTableDataSetImpl
|
package org.jdesktop.swingx;
import java.awt.Component;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import javax.swing.AbstractButton;
import javax.swing.BoxLayout;
import javax.swing.ButtonGroup;
import javax.swing.ButtonModel;
import javax.swing.JComponent;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
/**
* A group of radio buttons that functions as a unit.
*
* Notes
*
* (1) Enabling and disabling the JXRadioGroup will enable/disable all of the
* child buttons inside the JXRadioGroup.
*
* (2) If the generic type parameter of JXRadioGroup is a subclass of {@link AbstractButton}, then
* the buttons will be added "as is" to the container.
* If the generic type is anything else, buttons will be created as {@link JRadioButton} objects,
* and the button text will be set by calling toString() on the value object.
*
* (3) Alternatively, if you want to configure the buttons individually, construct the JXRadioGroup
* normally, and then call {@link #getChildButton(int)} or {@link #getChildButton(Object)}
* and configure the buttons.
*
* @author Amy Fowler
* @author Noel Grandin
* @version 1.0
*/
public class JXRadioGroup<T> extends JPanel {
private static final long serialVersionUID = 3257285842266567986L;
private ButtonGroup buttonGroup;
private final List<T> values = new ArrayList<T>();
private ActionSelectionListener actionHandler;
private List<ActionListener> actionListeners;
/**
* Create a default JXRadioGroup with a default layout axis of {@link BoxLayout#X_AXIS}.
*/
public JXRadioGroup() {
setLayout(new BoxLayout(this, BoxLayout.X_AXIS));
buttonGroup = new ButtonGroup();
}
/**
* Set the layout axis of the radio group.
*
* @param axis values from {@link BoxLayout}.
*/
public void setLayoutAxis(int axis)
{
setLayout(new BoxLayout(this, axis));
}
/**
* Convenience factory method.
* Reduces code clutter when dealing with generics.
*
* @param radioValues the list of values used to create the group.
*/
public static <T> JXRadioGroup<T> create(T[] radioValues)
{
return new JXRadioGroup<T>(radioValues);
}
/**
* Create a default JXRadioGroup with a default layout axis of {@link BoxLayout#X_AXIS}.
*
* @param radioValues the list of values used to create the group.
*/
public JXRadioGroup(T[] radioValues) {
this();
for (int i = 0; i < radioValues.length; i++) {
add(radioValues[i]);
}
}
public void setValues(T[] radioValues) {
clearAll();
for (int i = 0; i < radioValues.length; i++) {
add(radioValues[i]);
}
}
private void clearAll() {
values.clear();
buttonGroup = new ButtonGroup();
// remove all the child components
removeAll();
}
/**
* You can use this method to manually add your own AbstractButton objects, provided you declared
* the class as <code>JXRadioGroup<JRadioButton></code>.
*/
public void add(T radioValue) {
if (values.contains(radioValue))
{
throw new IllegalArgumentException("cannot add the same value twice " + radioValue);
}
if (radioValue instanceof AbstractButton) {
values.add(radioValue);
addButton((AbstractButton) radioValue);
} else {
values.add(radioValue);
// Note: the "quote + object" trick here allows null values
addButton(new JRadioButton(""+radioValue));
}
}
private void addButton(AbstractButton button) {
buttonGroup.add(button);
super.add(button);
if (actionHandler == null) {
actionHandler = new ActionSelectionListener();
}
button.addActionListener(actionHandler);
button.addItemListener(actionHandler);
}
private class ActionSelectionListener implements ActionListener, ItemListener
{
public void actionPerformed(ActionEvent e) {
fireActionEvent(e);
}
public void itemStateChanged(ItemEvent e) {
fireActionEvent(null);
}
}
public AbstractButton getSelectedButton() {
final ButtonModel selectedModel = buttonGroup.getSelection();
final AbstractButton children[] = getButtonComponents();
for (int i = 0; i < children.length; i++) {
AbstractButton button = children[i];
if (button.getModel() == selectedModel) {
return button;
}
}
return null;
}
private AbstractButton[] getButtonComponents() {
final Component[] children = getComponents();
final List<AbstractButton> buttons = new ArrayList<AbstractButton>();
for (int i = 0; i < children.length; i++) {
if (children[i] instanceof AbstractButton) {
buttons.add((AbstractButton) children[i]);
}
}
return buttons.toArray(new AbstractButton[buttons.size()]);
}
private int getSelectedIndex() {
final ButtonModel selectedModel = buttonGroup.getSelection();
final Component children[] = getButtonComponents();
for (int i = 0; i < children.length; i++) {
AbstractButton button = (AbstractButton) children[i];
if (button.getModel() == selectedModel) {
return i;
}
}
return -1;
}
public T getSelectedValue() {
final int index = getSelectedIndex();
return (index < 0 || index >= values.size()) ? null : values.get(index);
}
public void setSelectedValue(T value) {
final int index = values.indexOf(value);
AbstractButton button = getButtonComponents()[index];
button.setSelected(true);
}
/**
* Retrieve the child button by index.
*/
public AbstractButton getChildButton(int index) {
return getButtonComponents()[index];
}
/**
* Retrieve the child button that represents this value.
*/
public AbstractButton getChildButton(T value) {
final int index = values.indexOf(value);
return getButtonComponents()[index];
}
/**
* Get the number of child buttons.
*/
public int getChildButtonCount() {
return getButtonComponents().length;
}
public void addActionListener(ActionListener l) {
if (actionListeners == null) {
actionListeners = new ArrayList<ActionListener>();
}
actionListeners.add(l);
}
public void removeActionListener(ActionListener l) {
if (actionListeners != null) {
actionListeners.remove(l);
}
}
public ActionListener[] getActionListeners() {
if (actionListeners != null) {
return actionListeners.toArray(new ActionListener[0]);
}
return new ActionListener[0];
}
protected void fireActionEvent(ActionEvent e) {
if (actionListeners != null) {
for (int i = 0; i < actionListeners.size(); i++) {
ActionListener l = actionListeners.get(i);
l.actionPerformed(e);
}
}
}
/**
* Enable/disable all of the child buttons
*
* @see JComponent#setEnabled(boolean)
*/
@Override
public void setEnabled(boolean enabled) {
super.setEnabled(enabled);
for (Enumeration en = buttonGroup.getElements(); en.hasMoreElements();) {
AbstractButton button = (AbstractButton) en.nextElement();
button.setEnabled(enabled);
}
}
}
|
package edu.dynamic.dynamiz.structure;
import java.util.Calendar;
import java.util.Date;
/**
* Defines the date in the format DD/MM/YYYY.
*
* Constructor
* MyDate() //Creates a new instance of this date.
* MyDate(MyDate date) //the copy constructor of this class.
* MyDate(int date, int month, int year) //Creates a new instance of this date.
* MyDate(Date date) //Creates a new MyDate instance from the given Date object.
*
* Methods
* int compareTo(MyDate date) //Compares this date with the given date.
* boolean equals(Object obj) //Checks if this date and the given date represent the same date on the calendar.
* int getDayOfMonth() //Gets the day of the month.
* int getMonth() //Gets the month of the year.
* int getYear() //Gets the year.
* static boolean isValidDate(int date, int month, int year) //Checks if the given date value is valid on the calendar.
* static MyDate makeDate(String dateString) //Creates a MyDate instance from the given date string.
* void setDate(int date, int month, int year) //Sets the date values.
* protected void setDayOfMonth(int date) //Sets the day of the month.
* protected void setMonth(int month) //Sets the month of the year.
* protected void setYear(int year) //Sets the year
* String toString() //Gets the String representation of this date.
*
* @author zixian
*/
public class MyDate implements Comparable<MyDate>{
//Default date values.
protected static final int DEFAULT_DAY = 1;
protected static final int DEFAULT_MONTH = 1;
protected static final int DEFAULT_YEAR = 1970;
//String format for set date
protected static final String FORMAT_DATE = "%1$d/%2$d/%3$d";
public static final String REGEX_DATE = "[0-9]{1,2}/[0-9]{1,2}/[0-9]{1,4}";
//The main data members of this class.
private int year, month, date;
/**
* Creates and initialises this Date object to 1 January 1970.
*/
public MyDate(){
this(DEFAULT_DAY, DEFAULT_MONTH, DEFAULT_YEAR);
}
/**
* The copy constructor for this class.
* @param date The MyDate object to be copied.
*/
public MyDate(MyDate date){
this(date.getDayOfMonth(), date.getMonth(), date.getYear());
}
public MyDate(int date, int month, int year) throws IllegalArgumentException{
if(!isValidDate(date, month, year)){
throw new IllegalArgumentException();
}
setDate(date, month, year);
}
/**
* Creates a new date representation from the given java.util.Date object.
* @param date The date to create an instance from.
*/
public MyDate(Date date) {
assert date != null;
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
int dd = calendar.get(Calendar.DAY_OF_MONTH);
int mm = calendar.get(Calendar.MONTH) + 1; // Calendar.MONTH starts from 0
int yyyy = calendar.get(Calendar.YEAR);
setDate(dd, mm, yyyy);
}
/**
* Creates a new Date instance from the given date string.
* @param dateString The string representation of the date to create.
* @return The Date instance who's toString() method equals dateString.
*/
public static MyDate makeDate(String dateString){
assert dateString.matches(REGEX_DATE);
String[] temp = dateString.split("/");
int day = Integer.parseInt(temp[0]);
int month = Integer.parseInt(temp[1]);
int year = Integer.parseInt(temp[2]);
return new MyDate(day, month, year);
}
/**
* Gets the day of the month of this date object.
* @returns The day in the month of this Date object.
*/
public int getDayOfMonth(){
return date;
}
/**
* Gets the month of this date object.
* @return The month of this Date object.
*/
public int getMonth(){
return month;
}
/**
* Gets the year of this date object.
* @return The year of this Date object.
*/
public int getYear(){
return year;
}
/**
* Checks if the given date is valid.
* @param date The day of the month.
* @param month The month of the year.
* @param year The year.
* @return True if the date is valid in the calendar and false otherwise.
*/
public static boolean isValidDate(int date, int month, int year){
boolean isValidYear = year>=0;
boolean isValidMonth = (month>0 && month<13);
boolean isValidDate = date>0;
if(month==1 || month==3 || month==5 || month==7 || month==8 || month==10 || month==12){
isValidDate&=(date<32);
} else if(month==4 || month==6 || month==9 || month==11){
isValidDate&=(date<31);
} else if(month==2){
boolean isLeapYear = (year%400==0 || (year%4==0 && year%100!=0));
if(isLeapYear){
isValidDate&=(date<30);
} else{
isValidDate&=(date<29);
}
} else{
isValidDate = false;
}
return isValidYear && isValidMonth && isValidDate;
}
/**
* Returns the String representation of this Date object for printing purpose.
* Format is: DD/MM/YYYY.
* @return String representation of this Date object.
*/
public String toString(){
String output = String.format(FORMAT_DATE, getDayOfMonth(), getMonth(), getYear());
return output;
}
public void setDate(int date, int month, int year){
if(isValidDate(date, month, year)){
setDayOfMonth(date);
setMonth(month);
setYear(year);
}
}
/**
* Sets the day of the month.
* @param date The day of the month.
*/
protected void setDayOfMonth(int date) {
this.date = date;
}
/**
* Sets the month of the year.
* @param month the month of the year.
*/
protected void setMonth(int month){
this.month = month;
}
/**
* Sets the year.
* @param year The year.
*/
protected void setYear(int year){
this.year = year;
}
@Override
/**
* Compares which of the 2 Date objects comes later. If date2 is a subclass of Date,
* date2's compareTo method will be used instead but the outcome is not reversed.
* @param date2 The MyDate object to compare with.
* @return 0 if the 2 dates have same date, positive
* integer if this come later than date2, negative integer
* if this comes earlier than date2.
*/
public int compareTo(MyDate date2){
if(year!=date2.getYear()){
return year-date2.getYear();
} else if(month!=date2.getMonth()){
return month-date2.getMonth();
} else{
return date-date2.getDayOfMonth();
}
}
@Override
/**
* Checks if the 2 dates represent the same date on the calendar.
* @param obj The MyDate object to check for equality.
*/
public boolean equals(Object obj){
assert obj!=null;
if(obj instanceof MyDate){
MyDate temp = (MyDate)obj;
return (date==temp.getDayOfMonth()) && (month==temp.getMonth()) && (year==temp.getYear());
}
return false;
}
}
|
package org.neo4j.impl.transaction;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import javax.transaction.xa.Xid;
// TODO: fixed sized logs (pre-initialize them)
// keep dangling records in memory for log switch
// batch disk forces
/**
* This class is made public for testing purposes only, do not use.
* <p>
* The {@link TxManager} uses this class to keep a transaction log for
* transaction recovery.
* <p>
*/
public class TxLog
{
private String name = null;
private FileChannel fileChannel = null;
private ByteBuffer buffer = null;
private int recordCount = 0;
public static final byte TX_START = 1;
public static final byte BRANCH_ADD = 2;
public static final byte MARK_COMMIT = 3;
public static final byte TX_DONE = 4;
/**
* Initializes a transaction log using <CODE>filename</CODE>. If the
* file isn't empty the position will be set to size of file so new
* records will be appended.
*
* @param fileName Filename of file to use
* @throws IOException If unable to open file
*/
public TxLog( String fileName ) throws IOException
{
if ( fileName == null )
{
throw new IllegalArgumentException( "Null filename" );
}
fileChannel = new RandomAccessFile( fileName, "rw" ).getChannel();
fileChannel.position( fileChannel.size() );
buffer = ByteBuffer.allocateDirect( ( 3 + Xid.MAXGTRIDSIZE +
Xid.MAXBQUALSIZE ) * 1000 );
this.name = fileName;
}
/**
* Returns the name of the transaction log.
*/
public String getName()
{
return name;
}
/**
* Returns the number of records (one of TX_START,BRANCH_ADD,MARK_COMMIT or
* TX_DONE) written since this instance was created or truncated.
*/
public int getRecordCount()
{
return recordCount;
}
/**
* Closes the file representing the transaction log.
*/
public void close() throws IOException
{
fileChannel.close();
}
/**
* Forces the log file (with metadata). Useful when switching log.
*/
public void force() throws IOException
{
fileChannel.force( true );
}
/**
* Truncates the file to zero size and sets the record count to zero.
*/
public synchronized void truncate() throws IOException
{
fileChannel.position( 0 );
fileChannel.truncate( 0 );
recordCount = 0;
}
// tx_start(byte)|gid_length(byte)|globalId
/**
* Writes a <CODE>TX_START</CODE> record to the file.
*
* @param globalId The global id of the new transaction
* @throws IOException If unable to write
*/
public synchronized void txStart( byte globalId[] ) throws IOException
{
if ( globalId == null )
{
throw new IllegalArgumentException( "Null parameter" );
}
buffer.clear();
buffer.put( TX_START ).put( ( byte ) globalId.length ).put( globalId );
buffer.flip();
fileChannel.write( buffer );
recordCount++;
}
// add_branch(byte)|gid_length(byte)|bid_length(byte)|globalId|branchId
/**
* Writes a <CODE>BRANCH_ADD</CODE> record to the file.
*
* @param globalId The global id of the transaction
* @param branchId The branch id for the enlisted resource
* @throws IOException If unable to write
*/
public synchronized void addBranch( byte globalId[], byte branchId[] )
throws IOException
{
if ( globalId == null )
{
throw new IllegalArgumentException( "Null global id" );
}
if ( branchId == null )
{
throw new IllegalArgumentException( "Null branch id" );
}
buffer.clear();
buffer.put( BRANCH_ADD ).put( ( byte ) globalId.length ).put(
( byte ) branchId.length ).put( globalId ).put( branchId );
buffer.flip();
fileChannel.write( buffer );
recordCount++;
}
// mark_committing(byte)|gid_length(byte)|globalId
// forces
/**
* Writes a <CODE>MARK_COMMIT</CODE> record to the file and forces the
* file to disk.
*
* @param globalId The global id of the transaction
* @throws IOException If unable to write
*/
public synchronized void markAsCommitting( byte globalId[] )
throws IOException
{
if ( globalId == null )
{
throw new IllegalArgumentException( "Null parameter" );
}
buffer.clear();
buffer.put( MARK_COMMIT ).put( ( byte ) globalId.length ).put(
globalId );
buffer.flip();
fileChannel.write( buffer );
fileChannel.force( false );
recordCount++;
}
// tx_done(byte)|gid_length(byte)|globalId
/**
* Writes a <CODE>TX_DONE</CODE> record to the file.
*
* @param globalId The global id of the transaction completed
* @throws IOException If unable to write
*/
public synchronized void txDone( byte globalId[] ) throws IOException
{
if ( globalId == null )
{
throw new IllegalArgumentException( "Null parameter" );
}
buffer.clear();
buffer.put( TX_DONE ).put( ( byte ) globalId.length ).put( globalId );
buffer.flip();
fileChannel.write( buffer );
recordCount++;
}
/**
* Made public for testing only.
* <p>
* Wraps a transaction record in the tx log file.
*/
public static class Record
{
private byte type = 0;
private byte globalId[] = null;
private byte branchId[] = null;
private int seqNr = -1;
Record( byte type, byte globalId[], byte branchId[], int seqNr )
{
if ( type < 1 || type > 4 )
{
throw new IllegalArgumentException( "Illegal type: " + type );
}
this.type = type;
this.globalId = globalId;
this.branchId = branchId;
this.seqNr = seqNr;
}
public byte getType()
{
return type;
}
public byte[] getGlobalId()
{
return globalId;
}
public byte[] getBranchId()
{
return branchId;
}
public int getSequenceNumber()
{
return seqNr;
}
public String toString()
{
XidImpl xid = new XidImpl( globalId,
branchId == null ? new byte[0] : branchId );
return "TxLogRecord[" + type + "," + xid + "," + seqNr + "]";
}
}
void writeRecord( Record record ) throws IOException
{
if ( record.getType() == TX_START )
{
txStart( record.getGlobalId() );
}
else if ( record.getType() == BRANCH_ADD )
{
addBranch( record.getGlobalId(), record.getBranchId() );
}
else if ( record.getType() == MARK_COMMIT )
{
markAsCommitting( record.getGlobalId() );
}
else
{
// TX_DONE should never be passed in here
throw new IOException( "Illegal record type[" + record.getType() +
"]" );
}
}
/**
* Returns an array of lists, each list contains dangling records
* (transactions that han't been completed yet) grouped after global by
* transaction id.
*/
public synchronized Iterator<List<Record>> getDanglingRecords()
throws IOException
{
fileChannel.position( 0 );
buffer.clear();
fileChannel.read( buffer );
buffer.flip();
// next record position
long nextPosition = 0;
// holds possible dangling records
int seqNr = 0;
Map<Xid,List<Record>> recordMap =
new HashMap<Xid,List<Record>>();
while ( buffer.hasRemaining() )
{
byte recordType = buffer.get();
if ( recordType == TX_START )
{
byte globalId[] = new byte[ buffer.get() ];
buffer.get( globalId );
Xid xid = new XidImpl( globalId, new byte[0] );
if ( recordMap.containsKey( xid ) )
{
throw new IOException( "Tx start for same xid[" +
xid + "] found twice" );
}
List<Record> recordList =
new LinkedList<Record>();
recordList.add( new Record( recordType, globalId, null,
seqNr++ ) );
recordMap.put( xid, recordList );
nextPosition += 2 + globalId.length;
}
else if ( recordType == BRANCH_ADD )
{
byte globalId[] = new byte[ buffer.get() ];
byte branchId[] = new byte[ buffer.get() ];
buffer.get( globalId );
buffer.get( branchId );
Xid xid = new XidImpl( globalId, new byte[0] );
if ( !recordMap.containsKey( xid ) )
{
throw new IOException( "Branch[" + new String( branchId ) +
"] found for [" + xid +
"] but no record list found in map" );
}
recordMap.get( xid ).add( new Record( recordType,
globalId, branchId, seqNr++ ) );
nextPosition += 3 + globalId.length + branchId.length;
}
else if ( recordType == MARK_COMMIT )
{
byte globalId[] = new byte[ buffer.get() ];
buffer.get( globalId );
Xid xid = new XidImpl( globalId, new byte[0] );
if ( !recordMap.containsKey( xid ) )
{
throw new IOException( "Commiting xid[" + xid +
"] mark found but no record list found in map" );
}
List<Record> recordList = recordMap.get( xid );
recordList.add( new Record( recordType, globalId, null,
seqNr++ ) );
recordMap.put( xid, recordList );
nextPosition += 2 + globalId.length;
}
else if ( recordType == TX_DONE )
{
byte globalId[] = new byte[ buffer.get() ];
buffer.get( globalId );
Xid xid = new XidImpl( globalId, new byte[0] );
if ( !recordMap.containsKey( xid ) )
{
throw new IOException( "Commiting xid[" + xid +
"] mark found but no record list found in map" );
}
recordMap.remove( xid );
nextPosition += 2 + globalId.length;
}
else if ( recordType == 0 )
{
continue;
}
else
{
throw new IOException( "Unkown type: " + recordType );
}
if ( ( buffer.limit() - buffer.position() ) <
( 3 + Xid.MAXGTRIDSIZE + Xid.MAXBQUALSIZE ) )
{
// make sure we don't try to read non full entry
buffer.clear();
fileChannel.position( nextPosition );
fileChannel.read( buffer );
buffer.flip();
}
}
return recordMap.values().iterator();
}
/**
* Switches log file. Copies the dangling records in current log file
* to the <CODE>newFile</CODE> and the makes the switch closing the
* old log file.
*
* @param newFile The filename of the new file to switch to
* @throws IOException If unable to switch log file
*/
public synchronized void switchToLogFile( String newFile )
throws IOException
{
if ( newFile == null )
{
throw new IllegalArgumentException( "Null filename" );
}
// copy all dangling records from current log to new log
force();
Iterator<List<Record>> itr = getDanglingRecords();
close();
List<Record> records = new ArrayList<Record>();
while ( itr.hasNext() )
{
records.addAll( itr.next() );
}
Collections.sort( records, new Comparator<Record>()
{
public int compare( Record r1, Record r2 )
{
return r1.getSequenceNumber() - r2.getSequenceNumber();
}
} );
Iterator<Record> recordItr = records.iterator();
fileChannel = new RandomAccessFile( newFile, "rw" ).getChannel();
fileChannel.position( fileChannel.size() );
name = newFile;
truncate();
while ( recordItr.hasNext() )
{
Record record = recordItr.next();
writeRecord( record );
}
force();
}
}
|
package org.ticklefish.sisot;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Properties;
import java.util.TimeZone;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import javax.servlet.ServletConfig;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.solr.client.solrj.SolrServer;
import org.apache.solr.client.solrj.impl.HttpSolrServer;
import org.apache.solr.client.solrj.SolrQuery;
import org.apache.solr.common.SolrDocumentList;
import org.apache.solr.common.SolrInputDocument;
import org.json.JSONObject;
import org.json.JSONArray;
/**
* Sisot indexer.
*
* @author escowles
* @since 2014-07-01
**/
public class SolrIndexer extends AbstractServlet implements Runnable
{
private SimpleDateFormat utcFormat = new SimpleDateFormat(
"yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"
);
private SimpleDateFormat jsonFormat = new SimpleDateFormat(
"EEE MMM dd HH:mm:ss z yyyy"
);
private SimpleDateFormat localFormat = new SimpleDateFormat("MM/dd HH:mm");
private File dir;
ScheduledExecutorService exec;
public void init( ServletConfig cfg )
{
super.init(cfg);
init(props);
utcFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
// schedule execution
exec = new ScheduledThreadPoolExecutor(1);
exec.scheduleWithFixedDelay(this, 0, 20, TimeUnit.MINUTES);
System.out.println("SolrIndexer: scheduled to run every 20 minutes");
}
protected void init( Properties props )
{
super.init(props);
dir = new File( props.getProperty("data.dir") );
}
public void destroy()
{
exec.shutdown();
exec.shutdownNow();
}
public void run()
{
// make sure we're configured
if ( solr == null )
{
System.out.println("Not configured, will retry in 30 minutes");
return;
}
index(last(), new PrintWriter(System.out));
}
public void doGet( HttpServletRequest req, HttpServletResponse res )
{
// if we're not configured, redirect to config form
if ( solr == null )
{
try
{
res.sendRedirect("config");
}
catch ( Exception ex )
{
ex.printStackTrace();
}
return;
}
// setup output
PrintWriter out = null;
try
{
res.setContentType("text/html");
out = res.getWriter();
}
catch ( Exception ex )
{
ex.printStackTrace();
return;
}
// output html header
out.println("<html>");
out.println("<head>");
out.println("<link rel=\"stylesheet\" href=\"sisot.css\"></link>");
out.println("</head>");
out.println("<body>");
out.println("<h1>indexer</h1>");
out.println("<form method=\"GET\">");
out.println("<input type=\"submit\" name=\"reindex\" value=\"reindex all records\"/>");
out.println("<input type=\"submit\" value=\"index new records\"/>");
out.println("</form>");
out.println("<pre>");
out.println("reindexing");
out.flush();
// check reindex parameter to trigger full reindex
String last = null;
String reindex = req.getParameter("reindex");
if ( reindex == null || reindex.trim().equals("") )
{
last = last();
}
index(last, out);
// finish output
out.println("</pre>");
out.println("</body></html>");
out.flush();
}
private String last()
{
// get last tweet id
String last = "";
try
{
// lookup last-indexed tweet
SolrQuery query = new SolrQuery();
query.addSortField( "id", SolrQuery.ORDER.desc );
query.setFields( "id" );
query.setRows( 1 );
SolrDocumentList results = solr.query(query).getResults();
if ( results.size() > 0 )
{
last = (String)results.get(0).getFirstValue("id");
}
}
catch ( Exception ex )
{
ex.printStackTrace();
}
return last;
}
private void index( String since, PrintWriter out )
{
out.println("SolrIndexer.index(" + since + ")");
int records = 0;
try
{
long start = System.currentTimeMillis();
File[] jsonFiles = dir.listFiles();
for ( int i = 0; i < jsonFiles.length; i++ )
{
File f = jsonFiles[i];
if ( f.getName().endsWith(".json") )
{
String id = f.getName().replaceAll(".json","");
if ( since == null || since.compareTo(id) < 0 )
{
solr.add( toDocument(f) );
records++;
if ( records % 100 == 0 )
{
long dur = System.currentTimeMillis() - start;
out.println("indexed " + records + " tweets in "
+ dur + " msec");
out.flush();
}
}
}
}
long dur = System.currentTimeMillis() - start;
out.println("indexed " + records + " tweets in " + dur + " msec");
out.flush();
}
catch ( Exception ex )
{
ex.printStackTrace();
out.println("error indexing: " + ex.toString());
}
out.println("done: " + records + " tweets indexed");
out.flush();
out.close();
}
private SolrInputDocument toDocument( File f ) throws IOException
{
// read json file from disk
StringBuffer buf = new StringBuffer();
BufferedReader br = new BufferedReader( new FileReader(f) );
for ( String line = null; (line=br.readLine()) != null; )
{
buf.append( line );
}
JSONObject json = new JSONObject( buf.toString() );
SolrInputDocument doc = new SolrInputDocument();
// basic info
doc.addField("id", json.get("id") );
doc.addField("re_id", json.get("re_id") );
doc.addField("text", json.get("text") );
try
{
Date date = jsonFormat.parse(json.getString("date"));
doc.addField("date", utcFormat.format(date) );
}
catch ( Exception ex )
{
ex.printStackTrace();
}
// user info
doc.addField("user_id", json.get("user_id") );
doc.addField("user_name", json.get("user_name") );
doc.addField("user_image", json.get("user_image") );
// hashtags
JSONArray tags = json.getJSONArray("tags");
for ( int i = 0; i < tags.length(); i++ )
{
doc.addField("tag", tags.getString(i));
}
// media
JSONArray media = json.getJSONArray("media");
for ( int i = 0; i < media.length(); i++ )
{
doc.addField("media", media.getString(i));
}
return doc;
}
public static void main( String[] args ) throws Exception
{
SolrIndexer indexer = new SolrIndexer();
Properties props = new Properties();
props.load( new FileInputStream(args[0]) );
indexer.init(props);
if ( args.length > 1 && args[1].equals("reindex") )
{
// reindex all tweets
indexer.index(null, new PrintWriter(System.out));
}
else
{
// index new tweets
indexer.run();
}
}
}
|
package edu.jhu.hltcoe.data.conll;
import java.io.File;
import java.io.IOException;
import org.apache.commons.cli.ParseException;
import org.apache.log4j.Logger;
import edu.jhu.hltcoe.data.DepTree;
import edu.jhu.hltcoe.data.DepTreebank;
import edu.jhu.hltcoe.data.DepTreebankReader;
import edu.jhu.hltcoe.data.Label;
import edu.jhu.hltcoe.data.Sentence;
import edu.jhu.hltcoe.util.Alphabet;
import edu.jhu.hltcoe.util.Prng;
import edu.jhu.hltcoe.util.cli.ArgParser;
import edu.jhu.hltcoe.util.cli.Opt;
import edu.jhu.hltcoe.util.math.Vectors;
public class Ptb2ConllX {
private static final Logger log = Logger.getLogger(Ptb2ConllX.class);
@Opt(hasArg = true, required = true, description = "Penn Treebank training data directory")
public static File ptbIn;
@Opt(hasArg = true, required = true, description = "CoNLL-X output file")
public static File conllxOut;
@Opt(hasArg = true, description = "Pseudo random number generator seed")
public static long seed = Prng.DEFAULT_SEED;
public void run() throws IOException {
Alphabet<Label> alphabet = new Alphabet<Label>();
DepTreebank trees = DepTreebankReader.getTreebank(ptbIn.getAbsolutePath(), alphabet);
CoNLLXWriter conllxWriter = new CoNLLXWriter(conllxOut);
for (int i=0; i<trees.size(); i++) {
DepTree tree = trees.get(i);
Sentence sent = trees.getSentences().get(i);
int[] heads = tree.getParents();
Vectors.add(heads, 1);
conllxWriter.write(new CoNLLXSentence(sent, heads));
}
conllxWriter.close();
}
public static void main(String[] args) throws IOException {
ArgParser parser = new ArgParser(Ptb2ConllX.class);
parser.addClass(Ptb2ConllX.class);
parser.addClass(DepTreebankReader.class);
try {
parser.parseArgs(args);
} catch (ParseException e) {
log.error(e.getMessage());
parser.printUsage();
System.exit(1);
}
Prng.seed(seed);
Ptb2ConllX pipeline = new Ptb2ConllX();
pipeline.run();
}
}
|
package org.jaxen.test;
import junit.framework.TestCase;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;
import org.jaxen.JaxenException;
import org.jaxen.XPath;
import org.jaxen.dom.DOMXPath;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.xml.sax.SAXException;
public class DOMXPathTest extends TestCase
{
private static final String BASIC_XML = "xml/basic.xml";
private Document doc;
private DocumentBuilderFactory factory;
public DOMXPathTest(String name)
{
super( name );
}
public void setUp() throws ParserConfigurationException {
factory = DocumentBuilderFactory.newInstance();
factory.setNamespaceAware(true);
doc = factory.newDocumentBuilder().newDocument();
}
public void testConstruction() throws JaxenException
{
DOMXPath xpath = new DOMXPath( "/foo/bar/baz" );
assertEquals("/foo/bar/baz", xpath.toString());
}
public void testJaxen193() throws JaxenException
{
DOMXPath xpath = new DOMXPath( "count(/*/@*)" );
|
package ua.com.fielden.platform.entity.fetch;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Map.Entry;
import ua.com.fielden.platform.entity.AbstractEntity;
import ua.com.fielden.platform.entity.annotation.IsProperty;
import ua.com.fielden.platform.entity.query.fluent.EntityQueryUtils;
import ua.com.fielden.platform.entity.query.fluent.fetch;
import ua.com.fielden.platform.reflection.AnnotationReflector;
import ua.com.fielden.platform.reflection.PropertyTypeDeterminator;
import ua.com.fielden.platform.utils.EntityUtils;
import ua.com.fielden.platform.utils.Pair;
/**
* Default implementation for {@link IEntityFetchStrategy} contract.
*
* @author TG Team
*
*/
public class EntityFetchStrategy<T extends AbstractEntity<?>> implements IEntityFetchStrategy<T> {
private final Class<T> entityType;
private final LinkedHashMap<String, EntityFetchStrategy<AbstractEntity<?>>> propertyStrategies;
private fetch<T> fetchModel;
/**
* A factory method to create a default entity fetch strategy for entity-typed property.
*
* @param entityType
* -- the type of the property
*
* @return
*/
public static <T extends AbstractEntity<?>> EntityFetchStrategy<T> createDefaultStrategy(final Class<T> entityType) {
// TODO continue implementation -- version and id? fetchOnly analog
return new EntityFetchStrategy<T>(entityType);
}
/**
* Constructs empty {@link EntityFetchStrategy}.
*
* @param entityType
*/
private EntityFetchStrategy(final Class<T> entityType) {
this(entityType, new LinkedHashMap<>());
}
private EntityFetchStrategy(final Class<T> entityType, final LinkedHashMap<String, EntityFetchStrategy<AbstractEntity<?>>> propertyStrategies) {
this.entityType = entityType;
this.propertyStrategies = propertyStrategies;
}
@Override
public boolean shouldFetch(final String dotNotationProperty) {
validate(dotNotationProperty);
if (PropertyTypeDeterminator.isDotNotation(dotNotationProperty)) {
final Pair<String, String> firstAndRest = PropertyTypeDeterminator.firstAndRest(dotNotationProperty);
return propertyStrategies.containsKey(firstAndRest.getKey())
&& strategyForFirstLevel(firstAndRest.getKey()).shouldFetch(firstAndRest.getValue());
} else {
return propertyStrategies.containsKey(dotNotationProperty);
}
}
/**
* Getter for entity fetch strategy for first-level properties (not dot-notated).
*
* @param property
* @return
*/
private EntityFetchStrategy<AbstractEntity<?>> strategyForFirstLevel(final String property) {
final EntityFetchStrategy<AbstractEntity<?>> propStrategy = propertyStrategies.get(property);
if (propStrategy == null) {
throw new IllegalArgumentException("The property strategy should not be null.");
}
return propStrategy;
}
@Override
public <M extends AbstractEntity<?>> IEntityFetchStrategy<M> strategyFor(final String dotNotationProperty) throws IllegalArgumentException, IllegalStateException {
validateEntityTyped(dotNotationProperty);
if (!shouldFetch(dotNotationProperty)) {
throw new IllegalStateException(String.format("The property [%s] was not declared as 'fetching' property in this entity [%s] fetch strategy (please extend it).", dotNotationProperty, entityType.getSimpleName()));
}
return (EntityFetchStrategy<M>) strategyForAllLevels(dotNotationProperty);
}
/**
* Iterates through the dot-notation syntax to get the property fetch strategy (assuming it does exist).
*
* @param dotNotationProperty
* @return
*/
private EntityFetchStrategy<AbstractEntity<?>> strategyForAllLevels(final String dotNotationProperty) {
if (PropertyTypeDeterminator.isDotNotation(dotNotationProperty)) {
final Pair<String, String> firstAndRest = PropertyTypeDeterminator.firstAndRest(dotNotationProperty);
return strategyForFirstLevel(firstAndRest.getKey()).strategyForAllLevels(firstAndRest.getValue());
} else {
return strategyForFirstLevel(dotNotationProperty);
}
}
/**
* Validates <code>dotNotationProperty</code> as the property inside <code>entityType</code>.
*
* @param dotNotationProperty
*/
private Class<?> validate(final String dotNotationProperty) {
final Class<?> propType;
try {
propType = PropertyTypeDeterminator.determinePropertyType(entityType, dotNotationProperty);
} catch (final Exception e) {
throw new IllegalStateException(String.format("The property [%s] does not exist in entity type [%s].", dotNotationProperty, entityType.getSimpleName()));
}
if (!AnnotationReflector.isAnnotationPresentInHierarchy(IsProperty.class, entityType, dotNotationProperty)) {
throw new IllegalStateException(String.format("The field [%s] is not TG property (@IsProperty annotation is missing) in entity type [%s].", dotNotationProperty, entityType.getSimpleName()));
}
return propType;
}
/**
* Validates <code>dotNotationProperty</code> as the entity-typed property inside <code>entityType</code>.
*
* @param dotNotationProperty
*/
private void validateEntityTyped(final String dotNotationProperty) {
final Class<?> propertyType = validate(dotNotationProperty);
if (!EntityUtils.isEntityType(propertyType)) {
throw new IllegalStateException(String.format("The property [%s] is not entity-typed in type [%s].", dotNotationProperty, entityType.getSimpleName()));
}
}
/**
* Validates <code>dotNotationProperty</code> as the entity-typed property inside <code>entityType</code>.
*
* @param dotNotationProperty
*/
private static <M extends AbstractEntity<?>> void validateTypes(final EntityFetchStrategy<M> strategy1, final EntityFetchStrategy<M> strategy2) {
if (!EntityUtils.equalsEx(strategy1.entityType(), strategy2.entityType())) {
throw new IllegalArgumentException(String.format("Two strategies of incompatible entity types [%s and %s] is trying to be merged.", strategy1.entityType().getSimpleName(), strategy2.entityType().getSimpleName()));
}
}
@Override
public IEntityFetchStrategy<T> with(final String dotNotationProperty, final String... otherDotNotationProperties) {
final EntityFetchStrategy<T> copy = this.copy();
copy.enhanceWith(dotNotationProperty);
for (final String prop : otherDotNotationProperties) {
copy.enhanceWith(prop);
}
return copy;
}
@Override
public <M extends AbstractEntity<?>> IEntityFetchStrategy<T> with(final String dotNotationProperty, final IEntityFetchStrategy<M> propertyFetchStrategy) {
if (propertyFetchStrategy == null) {
throw new IllegalArgumentException(String.format("Please provide non-null property fetch strategy for property [%s] for type [%s]. Or use method 'with(dotNotationProperty)' for default property strategy.", dotNotationProperty, entityType.getSimpleName()));
}
final EntityFetchStrategy<T> copy = this.copy();
copy.enhanceWith(dotNotationProperty, (EntityFetchStrategy<AbstractEntity<?>>) propertyFetchStrategy);
return copy;
}
@Override
public IEntityFetchStrategy<T> with(final IEntityFetchStrategy<T> otherStrategy) {
validateTypes(this, (EntityFetchStrategy<T>) otherStrategy);
final EntityFetchStrategy<T> copy = this.copy();
final EntityFetchStrategy<T> that = (EntityFetchStrategy<T>) otherStrategy;
for (final Map.Entry<String, EntityFetchStrategy<AbstractEntity<?>>> entry : that.propertyStrategies().entrySet()) {
// no property name validation is required (it was done earlier)
copy.enhanceWith0(entry.getKey(), entry.getValue());
}
return copy;
}
/**
* Creates exact copy of entity fetch strategy.
*
* @return
*/
private EntityFetchStrategy<T> copy() {
final LinkedHashMap<String, EntityFetchStrategy<AbstractEntity<?>>> copiedPropertyStrategies = new LinkedHashMap<>();
for (final Entry<String, EntityFetchStrategy<AbstractEntity<?>>> entry : propertyStrategies.entrySet()) {
copiedPropertyStrategies.put(entry.getKey(), entry.getValue() == null ? null : entry.getValue().copy());
}
return new EntityFetchStrategy<T>(entityType, copiedPropertyStrategies);
}
/**
* Enhances (mutably) this entity fetch strategy with dot-notation property (and validates before that).
*
* @param dotNotationProperty
* @return
*/
private EntityFetchStrategy<T> enhanceWith(final String dotNotationProperty) {
validate(dotNotationProperty);
return enhanceWith0(dotNotationProperty, null);
}
/**
* Enhances (mutably) this entity fetch strategy with entity-typed dot-notation property strategy (and validates before that).
*
* @param dotNotationProperty
* @return
*/
private EntityFetchStrategy<T> enhanceWith(final String dotNotationProperty, final EntityFetchStrategy<AbstractEntity<?>> propertyStrategy) {
validateEntityTyped(dotNotationProperty);
return enhanceWith0(dotNotationProperty, propertyStrategy);
}
/**
* Enhances (mutably) this entity fetch strategy with dot-notation property.
*
* @param dotNotationProperty
* @param specifiedStrategy
* -- if not <code>null</code> -- additional strategy for the property to be merged with existing one, if <code>null</code> -- default strategy should be created
* (entity-typed property or regular)
* @return
*/
private EntityFetchStrategy<T> enhanceWith0(final String dotNotationProperty, final EntityFetchStrategy<AbstractEntity<?>> propertyStrategy) {
if (PropertyTypeDeterminator.isDotNotation(dotNotationProperty)) {
final Pair<String, String> firstAndRest = PropertyTypeDeterminator.firstAndRest(dotNotationProperty);
final String firstName = firstAndRest.getKey();
final String restDotNotation = firstAndRest.getValue();
final boolean exists = propertyStrategies.containsKey(firstName);
if (exists) {
propertyStrategies.get(firstName).enhanceWith0(restDotNotation, propertyStrategy);
} else {
final Class<?> firstType = PropertyTypeDeterminator.determinePropertyType(entityType, firstName);
propertyStrategies.put(firstName, createDefaultStrategy((Class<AbstractEntity<?>>) firstType).enhanceWith0(restDotNotation, propertyStrategy));
}
} else {
final boolean exists = propertyStrategies.containsKey(dotNotationProperty);
final Class<?> propertyType = PropertyTypeDeterminator.determinePropertyType(entityType, dotNotationProperty);
if (exists) {
if (EntityUtils.isEntityType(propertyType) && propertyStrategy != null) {
final EntityFetchStrategy<AbstractEntity<?>> merged = (EntityFetchStrategy<AbstractEntity<?>>) propertyStrategy.with(propertyStrategies.get(dotNotationProperty));
propertyStrategies.put(dotNotationProperty, merged);
} // else -- regular property or entity-typed
} else {
if (EntityUtils.isEntityType(propertyType)) { // entity-typed
propertyStrategies.put(dotNotationProperty, propertyStrategy == null ? createDefaultStrategy((Class<AbstractEntity<?>>) propertyType) : propertyStrategy.copy());
} else { // regular
propertyStrategies.put(dotNotationProperty, null);
}
}
}
return this;
}
private LinkedHashMap<String, EntityFetchStrategy<AbstractEntity<?>>> propertyStrategies() {
return propertyStrategies;
}
private Class<T> entityType() {
return entityType;
}
@Override
public fetch<T> fetchModel() {
if (fetchModel == null) {
fetchModel = createFetchModel();
}
return fetchModel;
}
/**
* Creates the fetch model from entity fetch strategy for entity retrieval process using EQL.
*
* @return
*/
private fetch<T> createFetchModel() {
fetch<T> fetchModel = EntityQueryUtils.fetchOnly(entityType);
for (final Map.Entry<String, EntityFetchStrategy<AbstractEntity<?>>> entry : propertyStrategies.entrySet()) {
final EntityFetchStrategy<AbstractEntity<?>> propModel = entry.getValue();
if (propModel == null) {
fetchModel = fetchModel.with(entry.getKey());
} else {
fetchModel = fetchModel.with(entry.getKey(), propModel.fetchModel());
}
}
return fetchModel;
}
}
|
package afc.jsp.tag;
import java.io.IOException;
import java.io.Writer;
import javax.servlet.jsp.JspContext;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.JspFragment;
import junit.framework.TestCase;
/**
* <p>Unit tests for {@link SynchronisedTag}.</p>
*
* @author Dźmitry Laŭčuk
*/
public class SynchronisedTagTest extends TestCase
{
private Object monitor;
private SynchronisedTag tag;
private StringJspWriter out;
private MockJspContext ctx;
/**
* <p>Initialises each test.</p>
*/
@Override
protected void setUp()
{
tag = new SynchronisedTag();
out = new StringJspWriter();
ctx = new MockJspContext(out);
tag.setJspContext(ctx);
monitor = new Object();
tag.setMonitor(monitor);
}
/**
* <p>De-initialises each test.</p>
*/
@Override
protected void tearDown()
{
monitor = null;
tag = null;
out = null;
ctx = null;
}
/**
* <p>Verifies that the tag body is executed only once and synchronised on the tag's monitor.</p>
*
* @throws Exception if this test fails.
*/
public void testSynchronisedCall() throws Exception
{
final MockBody body = new MockBody();
body.ctx = ctx;
body.monitor = monitor;
tag.setJspBody(body);
tag.doTag();
assertTrue(body.bodyInvoked);
}
/**
* <p>Verifies that the tag body is executed only once and synchronised on the tag's monitor
* and that if an exception is thrown in the tag body then it is not suppressed
* by {@code SynchronisedTag}.</p>
*
* @throws Exception if this test fails.
*/
public void testSynchronisedCall_TagBodyThrowsException() throws Exception
{
final JspException exception = new JspException();
final MockBody body = new MockBody();
body.ctx = ctx;
body.monitor = monitor;
body.exception = exception;
tag.setJspBody(body);
try {
tag.doTag();
fail();
}
catch (JspException ex)
{
assertSame(exception, ex);
}
assertTrue(body.bodyInvoked);
}
/**
* <p>Verifies that {@code null} is not allowed as a tag's monitor object.</p>
*
* @throws Exception if this test fails.
*/
public void testNullMonitor() throws Exception
{
try {
tag.setMonitor(null);
tag.doTag();
fail();
}
catch (NullPointerException ex) {
assertEquals("monitor", ex.getMessage());
}
}
/**
* <p>Verifies that {@code SynchronisedTag} requires to have a body.</p>
*
* @throws Exception if this test fails.
*/
public void testEmptyBody() throws Exception
{
tag.setMonitor(monitor);
try {
tag.doTag();
fail();
}
catch (JspException ex) {
assertEquals("Tag body is undefined.", ex.getMessage());
}
}
private static class MockBody extends JspFragment
{
public Object monitor;
public boolean bodyInvoked;
public JspContext ctx;
public JspException exception;
@Override
public JspContext getJspContext()
{
return ctx;
}
@Override
public void invoke(final Writer out) throws JspException, IOException
{
assertFalse(bodyInvoked);
bodyInvoked = true;
try {
monitor.wait(1);
}
catch (IllegalMonitorStateException ex) {
fail("Tag body is not invoked synchronised on the tag's monitor.");
}
catch (InterruptedException ex) {
Thread.currentThread().interrupt();
fail();
}
if (exception != null) {
throw exception;
}
}
};
}
|
package org.flexgen.map.test;
import org.junit.Assert;
import org.junit.Test;
import org.flexgen.map.MapTileEdge;
import org.flexgen.map.MapTileEdgePosition;
import org.flexgen.map.MapTileOrientation;
import org.flexgen.map.MapTileType;
import org.flexgen.map.MapUnit;
import org.flexgen.test.helper.GeneralHelper;
import org.flexgen.test.helper.MapTileEdgeHelper;
import org.flexgen.test.helper.MapTileOrientationHelper;
import org.flexgen.test.helper.MapTileTypeHelper;
import org.flexgen.test.helper.MapUnitHelper;
/**
* Test class for the MapTileType class.
*/
public class MapTileTypeTest
{
/**
* Verify that the constructor throws the correct exception when the mapUnits parameter is null.
*/
@Test
public void constructor_mapUnits_nullArray()
{
try
{
new MapTileType( null, MapTileEdgeHelper.buildArray(),
MapTileOrientationHelper.ALL_ORIENTATIONS, 0 );
Assert.fail( "Expected exception." );
}
catch ( IllegalArgumentException e )
{
Assert.assertEquals( "Unexpected message.", "Parameter 'mapUnits' cannot be null.",
e.getMessage() );
}
}
/**
* Verify that the constructor throws the correct exception when the mapUnits parameter is an
* empty array.
*/
@Test
public void constructor_mapUnits_emptyArray()
{
MapUnit[][] mapUnits = new MapUnit[][] {};
try
{
new MapTileType( mapUnits, MapTileEdgeHelper.buildArray(),
MapTileOrientationHelper.ALL_ORIENTATIONS, 0 );
Assert.fail( "Expected exception." );
}
catch ( IllegalArgumentException e )
{
Assert.assertEquals( "Unexpected message.",
"Parameter 'mapUnits' must contain at least one element.",
e.getMessage() );
}
}
/**
* Verify that the constructor throws the correct exception when the mapUnits parameter doesn't
* contain the same number of elements in all of the rows.
*/
@Test
public void constructor_mapUnits_inconsistentRowCount()
{
MapUnit[][] mapUnits = new MapUnit[][]
{
{
MapUnitHelper.build()
},
{
MapUnitHelper.build(),
MapUnitHelper.build()
},
};
try
{
new MapTileType( mapUnits, MapTileEdgeHelper.buildArray(),
MapTileOrientationHelper.ALL_ORIENTATIONS, 0 );
Assert.fail( "Expected exception." );
}
catch ( IllegalArgumentException e )
{
Assert.assertEquals(
"Unexpected message.",
"Parameter 'mapUnits' must contain the same number of elements in each row.",
e.getMessage() );
}
}
/**
* Verify that the constructor throws the correct exception when the mapUnits parameter doesn't
* contain the same number of columns as it does rows.
*/
@Test
public void constructor_mapUnits_columnCountNotEqualRowCount()
{
MapUnit[][] mapUnits = new MapUnit[][]
{
{
MapUnitHelper.build()
},
{
MapUnitHelper.build()
},
};
try
{
new MapTileType( mapUnits, MapTileEdgeHelper.buildArray(),
MapTileOrientationHelper.ALL_ORIENTATIONS, 0 );
Assert.fail( "Expected exception." );
}
catch ( IllegalArgumentException e )
{
Assert.assertEquals(
"Unexpected message.",
"Parameter 'mapUnits' must contain the same number of columns as it does rows.",
e.getMessage() );
}
}
/**
* Verify that the constructor throws the correct exception when the mapUnits parameter contains
* a null element.
*/
@Test
public void constructor_mapUnits_nullElement()
{
MapUnit[][] mapUnits = new MapUnit[][]
{
{
null
}
};
try
{
new MapTileType( mapUnits, MapTileEdgeHelper.buildArray(),
MapTileOrientationHelper.ALL_ORIENTATIONS, 0 );
Assert.fail( "Expected exception." );
}
catch ( IllegalArgumentException e )
{
Assert.assertEquals(
"Unexpected message.",
"Parameter 'mapUnits' must not contain any null elements.",
e.getMessage() );
}
}
/**
* Verify that the constructor throws the correct exception when the mapTileEdges parameter is
* null.
*/
@Test
public void constructor_mapTileEdges_nullArray()
{
try
{
new MapTileType( MapUnitHelper.buildArray( 1 ), null,
MapTileOrientationHelper.ALL_ORIENTATIONS, 0 );
Assert.fail( "Expected exception." );
}
catch ( IllegalArgumentException e )
{
Assert.assertEquals( "Unexpected message.", "Parameter 'mapTileEdges' cannot be null.",
e.getMessage() );
}
}
/**
* Verify that the constructor throws the correct exception when the mapTileEdges parameter
* doesn't contain enough elements.
*/
@Test
public void constructor_mapTileEdges_tooFew()
{
MapTileEdge[] mapTileEdges = new MapTileEdge[]
{
MapTileEdgeHelper.build(),
MapTileEdgeHelper.build(),
MapTileEdgeHelper.build()
};
try
{
new MapTileType( MapUnitHelper.buildArray( 1 ), mapTileEdges,
MapTileOrientationHelper.ALL_ORIENTATIONS, 0 );
Assert.fail( "Expected exception." );
}
catch ( IllegalArgumentException e )
{
Assert.assertEquals( "Unexpected message.",
"Parameter 'mapTileEdges' must contain 4 elements.",
e.getMessage() );
}
}
/**
* Verify that the constructor throws the correct exception when the mapTileEdges parameter
* contains too many elements.
*/
@Test
public void constructor_mapTileEdges_tooMany()
{
MapTileEdge[] mapTileEdges = new MapTileEdge[]
{
MapTileEdgeHelper.build(),
MapTileEdgeHelper.build(),
MapTileEdgeHelper.build(),
MapTileEdgeHelper.build(),
MapTileEdgeHelper.build()
};
try
{
new MapTileType( MapUnitHelper.buildArray( 1 ), mapTileEdges,
MapTileOrientationHelper.ALL_ORIENTATIONS, 0 );
Assert.fail( "Expected exception." );
}
catch ( IllegalArgumentException e )
{
Assert.assertEquals( "Unexpected message.",
"Parameter 'mapTileEdges' must contain 4 elements.",
e.getMessage() );
}
}
/**
* Verify that the constructor throws the correct exception when the mapTileEdges parameter
* contains a null element.
*/
@Test
public void constructor_mapTileEdges_nullElement()
{
MapTileEdge[] mapTileEdges = new MapTileEdge[]
{
MapTileEdgeHelper.build(),
null,
MapTileEdgeHelper.build(),
MapTileEdgeHelper.build()
};
try
{
new MapTileType( MapUnitHelper.buildArray( 1 ), mapTileEdges,
MapTileOrientationHelper.ALL_ORIENTATIONS, 0 );
Assert.fail( "Expected exception." );
}
catch ( IllegalArgumentException e )
{
Assert.assertEquals( "Unexpected message.",
"Parameter 'mapTileEdges' must not contain any null elements.",
e.getMessage() );
}
}
/**
* Verify that the constructor throws the correct exception when the distinctMapTileOrientations
* parameter is null.
*/
@Test
public void constructor_distinctMapTileOrientations_nullArray()
{
try
{
new MapTileType( MapUnitHelper.buildArray( 1 ),
MapTileEdgeHelper.buildArray(), null, 0 );
Assert.fail( "Expected exception." );
}
catch ( IllegalArgumentException e )
{
Assert.assertEquals( "Unexpected message.",
"Parameter 'distinctMapTileOrientations' cannot be null.",
e.getMessage() );
}
}
/**
* Verify that the constructor throws the correct exception when the distinctMapTileOrientations
* parameter is an empty array.
*/
@Test
public void constructor_distinctMapTileOrientations_emptyArray()
{
MapTileOrientation[] distinctMapTileOrientations = new MapTileOrientation[] {};
try
{
new MapTileType( MapUnitHelper.buildArray( 1 ), MapTileEdgeHelper.buildArray(),
distinctMapTileOrientations, 0 );
Assert.fail( "Expected exception." );
}
catch ( IllegalArgumentException e )
{
Assert.assertEquals(
"Unexpected message.",
"Parameter 'distinctMapTileOrientations' must contain at least one element.",
e.getMessage() );
}
}
/**
* Verify that the constructor throws the correct exception when the distinctMapTileOrientations
* parameter contains a null element.
*/
@Test
public void constructor_distinctMapTileOrientations_nullElement()
{
MapTileOrientation[] distinctMapTileOrientations = new MapTileOrientation[]
{
null
};
try
{
new MapTileType( MapUnitHelper.buildArray( 1 ), MapTileEdgeHelper.buildArray(),
distinctMapTileOrientations, 0 );
Assert.fail( "Expected exception." );
}
catch ( IllegalArgumentException e )
{
Assert.assertEquals(
"Unexpected message.",
"Parameter 'distinctMapTileOrientations' must not contain any null elements.",
e.getMessage() );
}
}
/**
* Verify that the constructor throws the correct exception when the distinctMapTileOrientations
* parameter contains a duplicate element.
*/
@Test
public void constructor_distinctMapTileOrientations_duplicateElement()
{
MapTileOrientation[] distinctMapTileOrientations = new MapTileOrientation[]
{
MapTileOrientation.UPRIGHT,
MapTileOrientation.UPRIGHT
};
try
{
new MapTileType( MapUnitHelper.buildArray( 1 ), MapTileEdgeHelper.buildArray(),
distinctMapTileOrientations, 0 );
Assert.fail( "Expected exception." );
}
catch ( IllegalArgumentException e )
{
Assert.assertEquals( "Unexpected message.",
"Parameter 'distinctMapTileOrientations' must not contain any " +
"duplicate elements.", e.getMessage() );
}
}
/**
* Verify that the getSize() method returns the correct value for a small array of map units.
*/
@Test
public void getSize()
{
int size = GeneralHelper.getRandom().nextInt( 5 ) + 1;
MapTileType mapTileType = MapTileTypeHelper.build( size );
Assert.assertEquals( "Unexpected return value.", size, mapTileType.getSize() );
}
/**
* Verify that the getMapUnit() method throws the correct exception when the x parameter is too
* small.
*/
@Test
public void getMapUnit_x_tooSmall()
{
MapTileType mapTileType = MapTileTypeHelper.build( 1 );
try
{
mapTileType.getMapUnit( -1, 0 );
Assert.fail( "Expected exception." );
}
catch ( IllegalArgumentException e )
{
Assert.assertEquals( "Unexpected message.",
"Parameter 'x' must be greater than or equal to 0.",
e.getMessage() );
}
}
/**
* Verify that the getMapUnit() method throws the correct exception when the x parameter is too
* large.
*/
@Test
public void getMapUnit_x_tooLarge()
{
int size = GeneralHelper.getRandom().nextInt( 5 ) + 1;
MapTileType mapTileType = MapTileTypeHelper.build( size );
try
{
mapTileType.getMapUnit( size, 0 );
Assert.fail( "Expected exception." );
}
catch ( IllegalArgumentException e )
{
Assert.assertEquals( "Unexpected message.",
"Parameter 'x' must be less than " + size + ".", e.getMessage() );
}
}
/**
* Verify that the getMapUnit() method throws the correct exception when the y parameter is too
* small.
*/
@Test
public void getMapUnit_y_tooSmall()
{
MapTileType mapTileType = MapTileTypeHelper.build( 1 );
try
{
mapTileType.getMapUnit( 0, -1 );
Assert.fail( "Expected exception." );
}
catch ( IllegalArgumentException e )
{
Assert.assertEquals( "Unexpected message.",
"Parameter 'y' must be greater than or equal to 0.",
e.getMessage() );
}
}
/**
* Verify that the getMapUnit() method throws the correct exception when the y parameter is too
* large.
*/
@Test
public void getMapUnit_y_tooLarge()
{
int size = GeneralHelper.getRandom().nextInt( 5 ) + 1;
MapTileType mapTileType = MapTileTypeHelper.build( size );
try
{
mapTileType.getMapUnit( 0, size );
Assert.fail( "Expected exception." );
}
catch ( IllegalArgumentException e )
{
Assert.assertEquals( "Unexpected message.",
"Parameter 'y' must be less than " + size + ".", e.getMessage() );
}
}
/**
* Verify that the getMapUnit() method returns the correct values for all coordinates in a small
* array of map units.
*/
@Test
public void getMapUnit()
{
int size = 2;
MapUnit[][] mapUnits = MapUnitHelper.buildArray( size );
MapTileType mapTileType = new MapTileType( mapUnits, MapTileEdgeHelper.buildArray(),
MapTileOrientationHelper.ALL_ORIENTATIONS, 0 );
for ( int i = 0; i < size; i++ )
{
for ( int j = 0; j < size; j++ )
{
Assert.assertEquals( "Unexpected return value for (" + i + ", " + j + ").",
mapUnits[ i ][ j ], mapTileType.getMapUnit( i, j ));
}
}
}
/**
* Verify that the getMapTileEdge() method throws the correct exception when the
* mapTileEdgePosition parameter is null.
*/
@Test
public void getMapTileEdge_mapTileEdgePosition_null()
{
MapTileType mapTileType = MapTileTypeHelper.build( 1 );
try
{
mapTileType.getMapTileEdge( null );
Assert.fail( "Expected exception." );
}
catch ( IllegalArgumentException e )
{
Assert.assertEquals( "Unexpected message.",
"Parameter 'mapTileEdgePosition' cannot be null.",
e.getMessage() );
}
}
/**
* Verify that the getMapTileEdge() method returns the correct values for all four edges.
*/
@Test
public void getMapTileEdge()
{
MapTileEdge[] mapTileEdges = MapTileEdgeHelper.buildArray();
MapTileType mapTileType = new MapTileType( MapUnitHelper.buildArray( 1 ), mapTileEdges,
MapTileOrientationHelper.ALL_ORIENTATIONS, 0 );
Assert.assertEquals( "Unexpected return value for \"top\".",
mapTileEdges[ 0 ],
mapTileType.getMapTileEdge( MapTileEdgePosition.TOP ));
Assert.assertEquals( "Unexpected return value for \"right\".",
mapTileEdges[ 1 ],
mapTileType.getMapTileEdge( MapTileEdgePosition.RIGHT ));
Assert.assertEquals( "Unexpected return value for \"bottom\".",
mapTileEdges[ 2 ],
mapTileType.getMapTileEdge( MapTileEdgePosition.BOTTOM ));
Assert.assertEquals( "Unexpected return value for \"left\".",
mapTileEdges[ 3 ],
mapTileType.getMapTileEdge( MapTileEdgePosition.LEFT ));
}
/**
* Verify that the getDistinctMapTileOrientations() method returns the correct values.
*/
@Test
public void getDistinctMapTileOrientations()
{
MapTileOrientation[] distinctMapTileOrientations = new MapTileOrientation[]
{
MapTileOrientation.UPRIGHT,
MapTileOrientation.FLIPPED
};
MapTileType mapTileType = new MapTileType( MapUnitHelper.buildArray( 1 ),
MapTileEdgeHelper.buildArray(),
distinctMapTileOrientations, 0 );
Assert.assertArrayEquals( "Unexpected result.", distinctMapTileOrientations,
mapTileType.getDistinctMapTileOrientations() );
}
}
|
package starbeast2.utils;
import beast.core.Input;
import beast.core.Runnable;
import beast.evolution.tree.Node;
import beast.evolution.tree.TraitSet;
import beast.evolution.tree.Tree;
import beast.evolution.tree.TreeTraceAnalysis;
import beast.util.Randomizer;
import java.io.PrintStream;
import java.util.*;
public class GeneTreeSimulator extends Runnable {
public Input<Tree> speciesTreeInput = new Input<>(
"speciesTree",
"Species tree on which to simulate gene trees",
Input.Validate.REQUIRED);
public Input<TraitSet> sampleCountsInput = new Input<>(
"sampleCounts",
"TraitSet defining number of samples per node in species tree.",
Input.Validate.REQUIRED);
public Input<Integer> nSimsInput = new Input<>(
"nSims",
"Number of gene trees to simulate from given sample distribution.",
Input.Validate.REQUIRED);
public Input<String> fileNameInput = new Input<>(
"fileName",
"Name of file to which gene trees will be written.",
Input.Validate.REQUIRED);
public Input<String> reportFileNameInput = new Input<>(
"reportFileName",
"Name of file to which topology distribution report will be written.");
public Tree speciesTree;
public TraitSet sampleCounts;
public int nSims;
public String fileName, reportFileName;
public GeneTreeSimulator() { }
@Override
public void initAndValidate() {
speciesTree = speciesTreeInput.get();
sampleCounts = sampleCountsInput.get();
nSims = nSimsInput.get();
fileName = fileNameInput.get();
reportFileName = reportFileNameInput.get();
}
int getTotalLineageCount(Map<Node, List<Node>> lineages) {
int count = 0;
for (List<Node> lineageList : lineages.values())
count += lineageList.size();
return count;
}
int getTotalSampleCount() {
int count = 0;
for (Node speciesNode : speciesTree.getExternalNodes())
count += (int)Math.round(sampleCounts.getValue(speciesNode.getID()));
return count;
}
public Tree getSimulatedGeneTree() {
List<Node> sortedSpeciesTreeNodes = new ArrayList<>(Arrays.asList(speciesTree.getNodesAsArray()));
sortedSpeciesTreeNodes.sort((o1, o2) -> {
if (o1.getHeight() < o2.getHeight())
return -1;
if (o1.getHeight() > o2.getHeight())
return 1;
return 0;
});
// Perform simulation
Map<Node,List<Node>> activeLineages = new HashMap<>();
int nextLeafNodeNr = 0;
int nextIntNodeNr = getTotalSampleCount();
double t = 0.0;
while (getTotalLineageCount(activeLineages) > 1 || !sortedSpeciesTreeNodes.isEmpty()) {
// Compute propensity
double totalPropensity = 0;
Map<Node, Double> propensities = new HashMap<>();
for (Node speciesNode : activeLineages.keySet()) {
int k=activeLineages.get(speciesNode).size();
double thisProp = 0.5*k*(k-1);
propensities.put(speciesNode, thisProp);
totalPropensity += thisProp;
}
double dt = Randomizer.nextExponential(totalPropensity);
if (!sortedSpeciesTreeNodes.isEmpty() && t + dt > sortedSpeciesTreeNodes.get(0).getHeight()) {
Node speciesNode = sortedSpeciesTreeNodes.get(0);
t = speciesNode.getHeight();
activeLineages.put(speciesNode, new ArrayList<>());
if (speciesNode.isLeaf()) {
int count = (int)Math.round(sampleCounts.getValue(speciesNode.getID()));
for (int i=0; i<count; i++) {
Node geneTreeSampleNode = new Node(String.valueOf(nextLeafNodeNr));
geneTreeSampleNode.setNr(nextLeafNodeNr++);
geneTreeSampleNode.setHeight(speciesNode.getHeight());
activeLineages.get(speciesNode).add(geneTreeSampleNode);
}
} else {
for (Node speciesChild : speciesNode.getChildren()) {
activeLineages.get(speciesNode).addAll(activeLineages.get(speciesChild));
activeLineages.get(speciesChild).clear();
}
}
sortedSpeciesTreeNodes.remove(0);
} else {
t += dt;
// Coalesce a random pair of lineages
double u = Randomizer.nextDouble()*totalPropensity;
for (Node speciesNode : propensities.keySet()) {
u -= propensities.get(speciesNode);
if (u < 0) {
List<Node> lineageList = activeLineages.get(speciesNode);
int k = lineageList.size();
Node node1 = lineageList.get(Randomizer.nextInt(k));
Node node2;
do {
node2 = lineageList.get(Randomizer.nextInt(k));
} while (node2 == node1);
Node parent = new Node(String.valueOf(nextIntNodeNr));
parent.setNr(nextIntNodeNr++);
parent.setHeight(t);
parent.addChild(node1);
parent.addChild(node2);
lineageList.remove(node1);
lineageList.remove(node2);
lineageList.add(parent);
break;
}
}
}
}
// Return tree with remaining lineage as root
return new Tree(activeLineages.get(speciesTree.getRoot()).get(0));
}
/**
* Class of "comparable" nodes
*/
class CNode extends Node {
@Override
public boolean equals(Object obj) {
if (obj instanceof CNode)
return false;
CNode that = (CNode)obj;
if (that.getID() != this.getID() || that.getHeight() != this.getHeight())
return false;
Set<CNode> thisChildSet = new HashSet<>();
Set<CNode> thatChildSet = new HashSet<>();
for (Node child : this.getChildren())
thisChildSet.add((CNode)child);
for (Node child : that.getChildren())
thisChildSet.add((CNode)child);
return thisChildSet.equals(thatChildSet);
}
}
class LineageConfiguration {
private Map<Node, Set<CNode>> lineages;
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
LineageConfiguration that = (LineageConfiguration) o;
if (!this.lineages.keySet().equals(that.lineages.keySet())
return false;
for (Node speciesNode : this.lineages.keySet()) {
}
}
@Override
public int hashCode() {
return lineages.hashCode();
}
}
public Map<String, Double> getGeneTreeTopologyDist() {
return null;
}
@Override
public void run() throws Exception {
List<Tree> treeList = new ArrayList<>();
try (PrintStream ps = new PrintStream(fileName)) {
for (int i = 0; i < nSims; i++) {
Tree tree = getSimulatedGeneTree();
treeList.add(tree);
ps.println(tree.toString() + ";");
}
}
if (reportFileName != null) {
try (PrintStream ps = new PrintStream(reportFileName)) {
TreeTraceAnalysis analysis = new TreeTraceAnalysis(treeList, 0.0);
analysis.analyze();
analysis.report(ps);
}
}
}
}
|
package JpAws;
import java.io.IOException;
import java.util.List;
import java.util.StringTokenizer;
import java.util.concurrent.TimeUnit;
import aws.datameer.awstasks.aws.ec2.InstanceGroup;
import aws.datameer.awstasks.aws.ec2.InstanceGroupImpl;
import com.xerox.amazonws.ec2.EC2Exception;
import com.xerox.amazonws.ec2.Jec2;
import com.xerox.amazonws.ec2.LaunchConfiguration;
import com.xerox.amazonws.ec2.ReservationDescription;
public class MasterMachines extends Machine {
@Override
public String[] start(int numWorkers, String imageId) throws EC2Exception,
IOException {
// TODO Auto-generated method stub
//instanceGroup.shutdown() ;
//Runtime.getRuntime().exec("/home/varsha/./mycommandstop.sh");
//File privateKeyFile = new File("/home/ubuntu/Desktop/varshap.pem") ;
String accessKeyId = "AKIAIEINGU5VPVEQ4DAA";
String accessKeySecret = "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";
String privateKeyName = "varshap";
String ipAddr = "";
Jec2 ec2 = new Jec2(accessKeyId, accessKeySecret);
InstanceGroup instanceGroup = new InstanceGroupImpl(ec2);
LaunchConfiguration launchConfiguration = new LaunchConfiguration(imageId, 1, 1);
launchConfiguration.setKeyName(privateKeyName);
ReservationDescription rs = instanceGroup.startup(launchConfiguration, TimeUnit.MINUTES, 5);
//instanceGroup.connectTo("Msster");
List list = (List) rs.getInstances();
String instanceString = list.toString();
System.out.println("ins" + instanceString);
//System.out.println(" here1111");
StringTokenizer st = new StringTokenizer(instanceString);
String privateDns = "", publicDns = "";
int i = 0;
//System.out.println(" here22222");
while (st.hasMoreTokens()) {
st.nextToken();
i++;
if (i == 2) {
//System.out.println(" here8888");
privateDns = st.nextToken();
privateDns = privateDns.substring(11, privateDns.length() - 1);
publicDns = st.nextToken();
publicDns = publicDns.substring(4, publicDns.length() - 1);
}
/*
* if(i==3) { publicDns = st.nextToken(); publicDns =
* publicDns.substring(4,publicDns.length()-1); }
*/
}
MasterThread runMaster = new MasterThread(instanceGroup, publicDns);
runMaster.start();
System.out.println("here" + publicDns);
System.out.println("here" + privateDns);
String[] Dns = {publicDns, privateDns};
return Dns;
}
@Override
public void Stop() throws EC2Exception, IOException {
}
}
|
package com.dgrid.driver;
import java.io.File;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.context.support.FileSystemXmlApplicationContext;
public abstract class BaseDgridDriver {
private static String[] defaultSpringPaths = new String[] {
"/applicationContext.xml", "/applicationContext-hibernate.xml" };
private static Log log = LogFactory.getLog(BaseDgridDriver.class);
protected static AbstractApplicationContext getContext() {
AbstractApplicationContext ctx = null;
String springConfig = System.getProperty("spring.config");
if ((springConfig != null) && (springConfig.length() > 0)) {
File file = new File(springConfig);
if (file.exists() && file.canRead()) {
if (log.isDebugEnabled()) {
log.debug(String.format(
"Loading spring context from file %1$s",
springConfig));
}
ctx = new FileSystemXmlApplicationContext(springConfig);
} else {
log
.warn(String
.format(
"Attempt to load spring context from non-existent or non-readable file %1$s. Using defaults.",
springConfig));
}
}
if (ctx == null) {
ctx = new ClassPathXmlApplicationContext(defaultSpringPaths);
}
return ctx;
}
}
|
package com.intellij.ide.structureView;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.fileEditor.FileEditor;
import com.intellij.openapi.fileEditor.TextEditor;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.Disposer;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
/**
* Default implementation of the {@link StructureViewBuilder} interface which uses the
* standard IDEA implementation of the {@link StructureView} component and allows to
* customize the data displayed in the structure view.
*
* @see StructureViewModel
* @see TextEditorBasedStructureViewModel
* @see com.intellij.lang.LanguageStructureViewBuilder#getStructureViewBuilder(com.intellij.psi.PsiFile)
*/
public abstract class TreeBasedStructureViewBuilder implements StructureViewBuilder {
/**
* Returns the structure view model defining the data displayed in the structure view
* for a specific file.
*
* @return the structure view model instance.
* @see TextEditorBasedStructureViewModel
*/
@NotNull
public abstract StructureViewModel createStructureViewModel(@Nullable Editor editor);
@Override
@NotNull
public StructureView createStructureView(FileEditor fileEditor, @NotNull Project project) {
StructureViewModel model = createStructureViewModel(fileEditor instanceof TextEditor ? ((TextEditor)fileEditor).getEditor() : null);
StructureView view = StructureViewFactory.getInstance(project).createStructureView(fileEditor, model, project, isRootNodeShown());
Disposer.register(view, model);
return view;
}
public boolean isRootNodeShown() {
return true;
}
}
|
package com.redhat.ceylon.eclipse.util;
import static com.redhat.ceylon.eclipse.core.builder.CeylonBuilder.PROBLEM_MARKER_ID;
import static org.eclipse.core.resources.IMarker.SEVERITY_ERROR;
import static org.eclipse.core.resources.IMarker.SEVERITY_WARNING;
import static org.eclipse.search.internal.ui.SearchPlugin.SEARCH_ANNOTATION_TYPE;
import java.net.URL;
import java.util.ArrayList;
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 org.eclipse.core.resources.IMarker;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.jdt.ui.PreferenceConstants;
import org.eclipse.jface.internal.text.html.HTMLPrinter;
import org.eclipse.jface.resource.JFaceResources;
import org.eclipse.jface.text.BadLocationException;
import org.eclipse.jface.text.IDocument;
import org.eclipse.jface.text.Position;
import org.eclipse.jface.text.source.Annotation;
import org.eclipse.jface.text.source.IAnnotationModel;
import org.eclipse.jface.text.source.ISourceViewer;
import org.eclipse.jface.text.source.projection.AnnotationBag;
import org.eclipse.jface.text.source.projection.ProjectionAnnotation;
import org.eclipse.search.internal.ui.SearchPlugin;
import org.eclipse.swt.graphics.FontData;
import org.eclipse.ui.texteditor.MarkerAnnotation;
import com.redhat.ceylon.compiler.typechecker.model.Declaration;
import com.redhat.ceylon.compiler.typechecker.model.TypeDeclaration;
import com.redhat.ceylon.eclipse.code.editor.CeylonAnnotation;
import com.redhat.ceylon.eclipse.code.editor.CeylonInitializerAnnotation;
import com.redhat.ceylon.eclipse.code.editor.MarkOccurrencesAction;
import com.redhat.ceylon.eclipse.code.editor.RefinementAnnotation;
import com.redhat.ceylon.eclipse.code.hover.DocHover;
import com.redhat.ceylon.eclipse.code.propose.CeylonContentProposer;
import com.redhat.ceylon.eclipse.core.builder.MarkerCreator;
public class AnnotationUtils {
// Following is just used for debugging to discover new annotation types to filter out
// private static Set<String> fAnnotationTypes= new HashSet<String>();
private static Set<String> sAnnotationTypesToFilter= new HashSet<String>();
static {
sAnnotationTypesToFilter.add("org.eclipse.ui.workbench.texteditor.quickdiffUnchanged");
sAnnotationTypesToFilter.add("org.eclipse.ui.workbench.texteditor.quickdiffChange");
sAnnotationTypesToFilter.add("org.eclipse.ui.workbench.texteditor.quickdiffAddition");
sAnnotationTypesToFilter.add("org.eclipse.ui.workbench.texteditor.quickdiffDeletion");
sAnnotationTypesToFilter.add("org.eclipse.debug.core.breakpoint");
sAnnotationTypesToFilter.add(MarkOccurrencesAction.OCCURRENCE_ANNOTATION);
sAnnotationTypesToFilter.add(ProjectionAnnotation.TYPE);
}
private AnnotationUtils() { }
/**
* @return a nicely-formatted plain text string for the given set of annotations
*/
public static String formatAnnotationList(List<Annotation> annotations) {
if (annotations!=null && !annotations.isEmpty()) {
if (annotations.size()==1) {
return AnnotationUtils.formatSingleMessage(annotations.get(0));
}
else {
return AnnotationUtils.formatMultipleMessages(annotations);
}
}
return null;
}
/**
* @return true, if the given Annotation and Position are redundant, given the annotation
* information in the given Map
*/
public static boolean addAndCheckDuplicateAnnotation(Map<Integer, List<Object>> map,
Annotation annotation, Position position) {
List<Object> annotationsAtPosition;
if (!map.containsKey(position.offset)) {
annotationsAtPosition = new ArrayList<Object>();
map.put(position.offset, annotationsAtPosition);
} else {
annotationsAtPosition = map.get(position.offset);
}
// TODO this should call out to a language extension point first to see if the language can resolve duplicates
// Check to see if an error code is present on the marker / annotation
Integer errorCode = -1;
if (annotation instanceof CeylonAnnotation) {
errorCode = ((CeylonAnnotation) annotation).getId();
}
else if (annotation instanceof MarkerAnnotation) {
errorCode = ((MarkerAnnotation) annotation).getMarker()
.getAttribute(MarkerCreator.ERROR_CODE_KEY, -1);
}
// Fall back to comparing the text associated with this annotation
if (errorCode == -1) {
if (!annotationsAtPosition.contains(annotation.getText())) {
annotationsAtPosition.add(annotation.getText());
return false;
}
}
else if (!annotationsAtPosition.contains(errorCode)) {
annotationsAtPosition.add(errorCode);
return false;
}
return true;
}
/**
* @return the list of Annotations that reside at the given line for the given ISourceViewer
*/
public static List<Annotation> getAnnotationsForLine(ISourceViewer viewer, final int line) {
final IDocument document= viewer.getDocument();
IPositionPredicate posPred= new IPositionPredicate() {
public boolean matchPosition(Position p) {
return AnnotationUtils.positionIsAtLine(p, document, line);
}
};
return getAnnotations(viewer, posPred);
}
/**
* @return the list of Annotations that reside at the given offset for the given ISourceViewer
*/
public static List<Annotation> getAnnotationsForOffset(ISourceViewer viewer, final int offset) {
IPositionPredicate posPred= new IPositionPredicate() {
public boolean matchPosition(Position p) {
return offset >= p.offset && offset < p.offset + p.length;
}
};
return getAnnotations(viewer, posPred);
}
/**
* @return true, if the given Position resides at the given line of the given IDocument
*/
public static boolean positionIsAtLine(Position position, IDocument document, int line) {
if (position.getOffset() > -1 && position.getLength() > -1) {
try {
// RMF 11/10/2006 - This used to add 1 to the line computed by the document,
// which appears to be bogus. First, it didn't work right (annotation hovers
// never appeared); second, the line passed in comes from the Eclipse
// framework, so it should be consistent (wrt the index base) with what the
// IDocument API provides.
int startLine= document.getLineOfOffset(position.getOffset());
int endLine = document.getLineOfOffset(position.getOffset()+position.getLength());
return line >= startLine && line <= endLine;
}
catch (BadLocationException x) {}
}
return false;
}
/**
* @return the IAnnotationModel for the given ISourceViewer, if any
*/
// TODO get rid of this one-line wrapper
public static IAnnotationModel getAnnotationModel(ISourceViewer viewer) {
// if (viewer instanceof ISourceViewerExtension2) {
// ISourceViewerExtension2 extension= (ISourceViewerExtension2) viewer;
// return extension.getVisualAnnotationModel();
return viewer.getAnnotationModel();
}
/**
* @return the list of Annotations on the given ISourceViewer that satisfy the given
* IPositionPredicate and that are worth showing to the user as text (e.g., ignoring
* debugger breakpoint annotations and source folding annotations)
*/
public static List<Annotation> getAnnotations(ISourceViewer viewer, IPositionPredicate posPred) {
IAnnotationModel model = getAnnotationModel(viewer);
if (model == null)
return null;
List<Annotation> annotations = new ArrayList<Annotation>();
Iterator<?> iterator = model.getAnnotationIterator();
Map<Integer, List<Object>> map = new HashMap<Integer, List<Object>>();
while (iterator.hasNext()) {
Annotation annotation = (Annotation) iterator.next();
Position position = model.getPosition(annotation);
if (annotation instanceof MarkerAnnotation) {
try {
if (((MarkerAnnotation) annotation).getMarker().getType()
.equals(PROBLEM_MARKER_ID)) {
continue;
}
}
catch (CoreException e) {
e.printStackTrace();
continue;
}
}
if (position == null)
continue;
if (!posPred.matchPosition(position))
continue;
if (annotation instanceof AnnotationBag) {
AnnotationBag bag = (AnnotationBag) annotation;
for (Iterator<?> e = bag.iterator(); e.hasNext(); ) {
Annotation bagAnnotation = (Annotation) e.next();
position = model.getPosition(bagAnnotation);
if (position != null
&& includeAnnotation(bagAnnotation, position)
&& !addAndCheckDuplicateAnnotation(map, bagAnnotation, position))
annotations.add(bagAnnotation);
}
} else {
if (includeAnnotation(annotation, position)
&& !addAndCheckDuplicateAnnotation(map, annotation, position)) {
annotations.add(annotation);
}
}
}
return annotations;
}
/**
* Check preferences, etc., to determine whether this annotation is actually showing.
* (Don't want to show a hover for a non-visible annotation.)
* @param annotation
* @param position
* @return
*/
private static boolean includeAnnotation(Annotation annotation, Position position) {
return !sAnnotationTypesToFilter.contains(annotation.getType());
}
/**
* @see IVerticalRulerHover#getHoverInfo(ISourceViewer, int)
*/
public String getHoverInfo(ISourceViewer sourceViewer, int lineNumber) {
return formatAnnotationList(getAnnotationsForLine(sourceViewer, lineNumber));
}
public static void addMessageImageAndLabel(Annotation message,
StringBuffer buffer) {
URL icon = null;
String text = null;
if (message instanceof CeylonAnnotation) {
text = HTMLPrinter.convertToHTMLContent(message.getText());
icon = getProblemIcon(((CeylonAnnotation) message).getSeverity());
}
else if (message instanceof CeylonInitializerAnnotation) {
text = message.getText();
icon = DocHover.fileUrl("information.gif");
}
else if (message instanceof RefinementAnnotation) {
Declaration dec = ((RefinementAnnotation) message).getDeclaration();
icon = dec.isFormal() ? DocHover.fileUrl("implm_co.gif") : DocHover.fileUrl("over_co.gif");
text = "refines <tt>" + HTMLPrinter.convertToHTMLContent(CeylonContentProposer.getDescriptionFor(dec))
+ "</tt> declared by <tt><b>" + ((TypeDeclaration) dec.getContainer()).getName() +
"</b></tt>";
}
else if (message instanceof MarkerAnnotation) {
try {
Integer sev = (Integer)((MarkerAnnotation) message).getMarker()
.getAttribute(IMarker.SEVERITY);
icon = getProblemIcon(sev);
text = "[Backend error] " + ((MarkerAnnotation) message).getMarker()
.getAttribute(IMarker.MESSAGE);
}
catch (CoreException e) {
e.printStackTrace();
}
}
else if (message.getType().equals(SEARCH_ANNOTATION_TYPE)) {
text = "<b>Search result</b>";
icon = DocHover.fileUrl("find_obj.gif");
}
if (icon!=null) {
DocHover.addImageAndLabel(buffer, null, icon.toExternalForm(), 16, 16, text, 20, 2);
}
}
public static URL getProblemIcon(Integer severity) {
if (severity==null) {
return null;
}
if (severity.intValue()==SEVERITY_ERROR) {
return DocHover.fileUrl("error_obj.gif");
}
else if (severity.intValue()==SEVERITY_WARNING) {
return DocHover.fileUrl("warning_obj.gif");
}
else {
return null;
}
}
/**
* Formats a message as HTML text.
*/
public static String formatSingleMessage(Annotation message) {
StringBuffer buffer= new StringBuffer();
HTMLPrinter.insertPageProlog(buffer, 0, getStyleSheet());
addMessageImageAndLabel(message, buffer);
HTMLPrinter.addPageEpilog(buffer);
return buffer.toString();
}
/**
* Formats several messages as HTML text.
*/
public static String formatMultipleMessages(List<Annotation> messages) {
StringBuffer buffer= new StringBuffer();
HTMLPrinter.insertPageProlog(buffer, 0, getStyleSheet());
DocHover.addImageAndLabel(buffer, null, DocHover.fileUrl("errorwarning_tab.gif").toExternalForm(),
16, 16, "Multiple messages at this line:", 20, 2);
buffer.append("<hr/>");
for (Annotation message: messages) {
addMessageImageAndLabel(message, buffer);
}
HTMLPrinter.addPageEpilog(buffer);
return buffer.toString();
}
private static String fgStyleSheet;
public static String getStyleSheet() {
if (fgStyleSheet == null)
fgStyleSheet= DocHover.loadStyleSheet() ;
//Color c = CeylonTokenColorer.getCurrentThemeColor("messageHover");
//String color = toHexString(c.getRed()) + toHexString(c.getGreen()) + toHexString(c.getBlue());
String css= fgStyleSheet; //+ "body { background-color: #" + color + " }";
if (css != null) {
FontData fontData= JFaceResources.getFontRegistry()
.getFontData(PreferenceConstants.APPEARANCE_JAVADOC_FONT)[0];
css= HTMLPrinter.convertTopLevelFont(css, fontData);
}
return css;
}
}
/**
* Interface that represents a single-argument predicate taking a textual Position.
* Used by AnnotationUtils to detect annotations associated with a particular range
* or location in source text.
* @author rfuhrer
*/
interface IPositionPredicate {
boolean matchPosition(Position p);
}
|
package org.tmarchuk.wurmunlimited.server.stablemaster;
// From Wurm Unlimited Server
import com.wurmonline.server.behaviours.Action;
import com.wurmonline.server.behaviours.ActionEntry;
import com.wurmonline.server.creatures.Creature;
import com.wurmonline.server.items.Item;
import com.wurmonline.server.items.ItemFactory;
import com.wurmonline.server.players.Player;
import com.wurmonline.server.questions.ExchangeAnimalQuestion;
// From Ago's modloader
import org.gotti.wurmunlimited.modsupport.actions.ActionPerformer;
import org.gotti.wurmunlimited.modsupport.actions.BehaviourProvider;
import org.gotti.wurmunlimited.modsupport.actions.ModAction;
import org.gotti.wurmunlimited.modsupport.actions.ModActions;
// Base Java
import java.util.Arrays;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
public class ExchangeAction implements ModAction, BehaviourProvider, ActionPerformer
{
private static Logger logger = Logger.getLogger(ExchangeAction.class.getName());
// Constants
private static final int HORSE_TEMPLATE_ID = 64;
private static final float ANIMAL_TOKEN_QUALITY = 100.0f;
// Configuration
private static int animalTokenId;
private final int stableMasterId;
private static int animalTokenMinimumWeightGrams;
private static int animalTokenMaximumWeightGrams;
private final int exchangeAnimalCostIrons;
private final boolean enableNoNpcExchange;
// Action data
private final short actionId;
private final ActionEntry actionEntry;
public ExchangeAction(int animalTokenId, int stableMasterId, int animalTokenMinimumWeightGrams,
int animalTokenMaximumWeightGrams, int exchangeAnimalCostIrons, boolean enableNoNpcExchange)
{
ExchangeAction.animalTokenId = animalTokenId;
this.stableMasterId = stableMasterId;
ExchangeAction.animalTokenMinimumWeightGrams = animalTokenMinimumWeightGrams;
ExchangeAction.animalTokenMaximumWeightGrams = animalTokenMaximumWeightGrams;
this.exchangeAnimalCostIrons = exchangeAnimalCostIrons;
this.enableNoNpcExchange = enableNoNpcExchange;
actionId = (short) ModActions.getNextActionId();
actionEntry = ActionEntry.createEntry(actionId, "Exchange animal", "exchanging", new int[] { 0 /* ACTION_TYPE_QUICK */, 48 /* ACTION_TYPE_ENEMY_ALWAYS */, 37 /* ACTION_TYPE_NEVER_USE_ACTIVE_ITEM */});
ModActions.registerAction(actionEntry);
}
@Override
public BehaviourProvider getBehaviourProvider() {
return this;
}
@Override
public ActionPerformer getActionPerformer() {
return this;
}
@Override
public List<ActionEntry> getBehavioursFor(Creature performer, Item subject, Creature target)
{
return getBehavioursFor(performer, target);
}
@Override
public List<ActionEntry> getBehavioursFor(Creature performer, Creature target)
{
// If we are configured to allow direct exchanges for no cost check if this is an animal we are leading.
if (this.enableNoNpcExchange && (performer instanceof Player) &&
target.leader == performer)
{
return Arrays.asList(actionEntry);
}
// Check if we're using a stable master and leading one or more animals.
if ((performer instanceof Player) &&
(target.getTemplate().getTemplateId() == stableMasterId) &&
(performer.getNumberOfFollowers() > 0))
{
return Arrays.asList(actionEntry);
}
// Doesn't apply.
return null;
}
@Override
public short getActionId() {
return actionId;
}
@Override
public boolean action(Action action, Creature performer, Creature target, short num, float counter)
{
int numLedAnimals = performer.getNumberOfFollowers();
int numAnimalsToExchange = 0;
Creature[] animalsToExchange = new Creature[] {};
int totalWeight = 0;
boolean useStableMaster = false;
// Handle the case where we're talking to a stable master.
if ((target.getTemplate().getTemplateId() == stableMasterId) && (numLedAnimals > 0))
{
useStableMaster = true;
numAnimalsToExchange = numLedAnimals;
animalsToExchange = performer.getFollowers();
for (Creature creat : animalsToExchange)
{
totalWeight += getAnimalTokenWeight(creat);
}
}
else if (this.enableNoNpcExchange && (target.leader == performer))
{
numAnimalsToExchange = 1;
totalWeight = getAnimalTokenWeight(target);
}
else
{
performer.getCommunicator().sendNormalServerMessage("Nothing to exchange!");
return true;
}
// Make sure performer has space for all the tokens in terms of item number.
final int MAX_NUM_ITEMS = 100;
if (!performer.getInventory().mayCreatureInsertItem() &&
((performer.getInventory().getNumItemsNotCoins() + numAnimalsToExchange) <= MAX_NUM_ITEMS))
{
performer.getCommunicator().sendNormalServerMessage("You do not have enough room in your inventory.");
return true;
}
// Make sure performer can carry all the tokens without being unable to move.
if (!performer.canCarry(totalWeight))
{
performer.getCommunicator().sendNormalServerMessage("You would not be able to carry the animal token(s). You need to drop some things first.");
return true;
}
// Handle processing with the stable master.
if (useStableMaster)
{
// Ask user to pay.
final ExchangeAnimalQuestion eQuestion = new ExchangeAnimalQuestion(performer,
animalsToExchange, exchangeAnimalCostIrons);
eQuestion.sendQuestion();
return true;
}
else // Above we've checked that we're enabled to exchange animals for no cost without an NPC.
{
// Do the exchange
exchangeAnimalForToken(performer, target);
return true;
}
}
@Override
public boolean action(Action action, Creature performer, Item source, Creature target, short num, float counter)
{
return action(action, performer, target, num, counter);
}
public static void exchangeAnimalForToken(final Creature performer, final Creature animal)
{
try
{
// Create new animal token from animal.
Item animalToken = ItemFactory.createItem(ExchangeAction.animalTokenId,
ANIMAL_TOKEN_QUALITY, performer.getName());
animalToken.setDescription(getAnimalDescription(animal));
animalToken.setName(getAnimalName(animal));
animalToken.setData(animal.getWurmId());
animalToken.setWeight(getAnimalTokenWeight(animal), false);
animalToken.setLastOwnerId(performer.getWurmId());
animalToken.setFemale(animal.getSex() == 1);
// Add token to player's inventory.
performer.getInventory().insertItem(animalToken, true);
// Remove animal from world.
CreatureHelper.hideCreature(animal);
// Let the player know.
performer.getCommunicator().sendNormalServerMessage("You exchange your animal with the stable master for an animal token." );
} catch (Exception e) {
logger.log(Level.WARNING, e.getMessage(), e);
}
}
private static int getAnimalTokenWeight(Creature animal)
{
int calculatedAnimalWeight = (int) animal.getStatus().getBody().getWeight(animal.getStatus().fat);
int animalTokenWeight = Math.min(animalTokenMaximumWeightGrams,
Math.max(animalTokenMinimumWeightGrams, calculatedAnimalWeight));
return animalTokenWeight;
}
private static String getAnimalDescription(Creature target)
{
String toReturn = target.getStatus().getAgeString().toLowerCase() + " ";
if(target.getTemplate().getTemplateId() == HORSE_TEMPLATE_ID)
{
toReturn += "grey";
if(target.hasTrait(15))
{
toReturn += "brown";
} else if(target.hasTrait(16))
{
toReturn += "gold";
} else if(target.hasTrait(17))
{
toReturn += "black";
} else if(target.hasTrait(18))
{
toReturn += "white";
} else if(target.hasTrait(24))
{
toReturn += "piebaldPinto";
} else if(target.hasTrait(25))
{
toReturn += "bloodBay";
} else if(target.hasTrait(23))
{
toReturn += "ebonyBlack";
}
}
toReturn += " " + target.getNameWithoutPrefixes().toLowerCase();
return toReturn;
}
private static String getAnimalName(Creature target)
{
String toReturn = "animal token";
return toReturn;
}
}
|
package org.jetbrains.idea.maven.execution;
import com.intellij.ide.actions.runAnything.activity.RunAnythingProviderBase;
import com.intellij.ide.actions.runAnything.items.RunAnythingHelpItem;
import com.intellij.ide.actions.runAnything.items.RunAnythingItem;
import com.intellij.openapi.actionSystem.DataContext;
import com.intellij.openapi.module.Module;
import com.intellij.openapi.module.ModuleManager;
import com.intellij.openapi.project.Project;
import com.intellij.util.execution.ParametersListUtil;
import icons.OpenapiIcons;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.idea.maven.model.MavenConstants;
import org.jetbrains.idea.maven.model.MavenExplicitProfiles;
import org.jetbrains.idea.maven.model.MavenPlugin;
import org.jetbrains.idea.maven.project.MavenProject;
import org.jetbrains.idea.maven.project.MavenProjectsManager;
import org.jetbrains.idea.maven.utils.MavenArtifactUtil;
import org.jetbrains.idea.maven.utils.MavenPluginInfo;
import javax.swing.*;
import java.util.*;
import java.util.stream.Collectors;
import static com.intellij.ide.actions.runAnything.RunAnythingUtil.fetchProject;
import static com.intellij.openapi.util.text.StringUtil.*;
import static java.util.Collections.emptyList;
import static java.util.stream.Collectors.toList;
/**
* @author ibessonov
*/
public class MavenRunAnythingProvider extends RunAnythingProviderBase<String> {
public final static String HELP_COMMAND = "mvn";
@NotNull
@Override
public RunAnythingItem getMainListItem(@NotNull DataContext dataContext, @NotNull String value) {
return new RunAnythingMavenItem(getCommand(value), getIcon(value));
}
@NotNull
@Override
public Collection<String> getValues(@NotNull DataContext dataContext, @NotNull String pattern) {
Project project = fetchProject(dataContext);
MavenProjectsManager projectsManager = MavenProjectsManager.getInstance(project);
if (!projectsManager.isMavenizedProject()) {
return emptyList();
}
if (getHelpCommand().startsWith(pattern)) {
pattern = getHelpCommand();
}
else if (!pattern.startsWith(getHelpCommand())) {
return emptyList();
}
List<MavenProject> mavenProjects = projectsManager.getRootProjects();
boolean onlyOneMavenProject = mavenProjects.size() == 1;
List<String> values = new ArrayList<>();
List<String> params = split(pattern, " ").stream().skip(1).map(String::trim).collect(toList());
if (!onlyOneMavenProject && (params.isEmpty() || params.size() == 1 && !pattern.endsWith(" "))) {
// list maven modules
for (MavenProject mavenProject : mavenProjects) {
Module module = projectsManager.findModule(mavenProject);
if (module != null) {
values.add(getHelpCommand() + " " + module.getName());
}
}
if (params.isEmpty()) {
return values;
}
}
Module module = onlyOneMavenProject ? projectsManager.findModule(mavenProjects.get(0))
: ModuleManager.getInstance(project).findModuleByName(params.get(0));
if (module != null) {
MavenProject mavenProject = onlyOneMavenProject ? mavenProjects.get(0) : projectsManager.findProject(module);
if (mavenProject != null) {
String prefix = notNullize(substringBeforeLast(pattern, " "), getHelpCommand()).trim() + " ";
if (!onlyOneMavenProject && prefix.trim().equals(getHelpCommand())) {
prefix = prefix + module.getName() + " ";
}
if (pattern.startsWith(prefix) && trimStart(pattern, prefix).startsWith("-")) {
boolean longName = trimStart(pattern, prefix).startsWith("
Set<MavenCommandLineOptions.Option> options = params.stream()
.skip(onlyOneMavenProject ? 0 : 1)
.map(MavenCommandLineOptions::findOption)
.filter(option -> option != null)
.collect(Collectors.toSet());
// list available cl options
for (MavenCommandLineOptions.Option option : MavenCommandLineOptions.getAllOptions()) {
if (!options.contains(option)) {
values.add(prefix + option.getName(longName));
}
}
Collections.sort(values, String::compareToIgnoreCase);
}
else {
Set<String> goals = new HashSet<>(params.subList(onlyOneMavenProject ? 0 : 1, params.size()));
// list basic phases
for (String phase : MavenConstants.BASIC_PHASES) {
if (!goals.contains(phase)) {
values.add(prefix + phase);
}
}
// list plugin-specific goals
for (MavenPlugin mavenPlugin : mavenProject.getDeclaredPlugins()) {
MavenPluginInfo pluginInfo = MavenArtifactUtil.readPluginInfo(projectsManager.getLocalRepository(), mavenPlugin.getMavenId());
if (pluginInfo == null) continue;
for (MavenPluginInfo.Mojo mojo : pluginInfo.getMojos()) {
if (!goals.contains(mojo.getDisplayName())) {
values.add(prefix + mojo.getDisplayName());
}
}
}
}
}
}
return values;
}
@Nullable
@Override
public String findMatchingValue(@NotNull DataContext dataContext, @NotNull String pattern) {
return pattern.startsWith(getHelpCommand()) ? getCommand(pattern) : null;
}
@NotNull
@Override
public String getCommand(@NotNull String value) {
return value;
}
@NotNull
@Override
public String getHelpCommand() {
return HELP_COMMAND;
}
@Nullable
@Override
public Icon getHelpIcon() {
return OpenapiIcons.RepositoryLibraryLogo;
}
@Nullable
@Override
public Icon getIcon(@NotNull String value) {
return OpenapiIcons.RepositoryLibraryLogo;
}
@NotNull
@Override
public String getCompletionGroupTitle() {
return "Maven goals";
}
@Nullable
@Override
public RunAnythingHelpItem getHelpItem(@NotNull DataContext dataContext) {
String placeholder = getHelpCommandPlaceholder(dataContext);
String commandPrefix = getHelpCommand();
return new RunAnythingHelpItem(placeholder, commandPrefix, getHelpDescription(), getHelpIcon());
}
@NotNull
@Override
public String getHelpCommandPlaceholder() {
return getHelpCommandPlaceholder(null);
}
public String getHelpCommandPlaceholder(@Nullable DataContext dataContext) {
if (dataContext != null) {
Project project = fetchProject(dataContext);
MavenProjectsManager projectsManager = MavenProjectsManager.getInstance(project);
if (projectsManager.isMavenizedProject()) {
if (projectsManager.getRootProjects().size() > 1) {
return "mvn <rootModuleName> <goals...> <options...>";
}
else {
return "mvn <goals...> <options...>";
}
}
}
return "mvn <rootModuleName?> <goals...> <options...>";
}
@Override
public void execute(@NotNull DataContext dataContext, @NotNull String value) {
Project project = fetchProject(dataContext);
MavenProjectsManager projectsManager = MavenProjectsManager.getInstance(project);
if (!projectsManager.isMavenizedProject()) {
return;
}
List<MavenProject> mavenProjects = projectsManager.getRootProjects();
boolean onlyOneMavenProject = mavenProjects.size() == 1;
List<String> goals = new ArrayList<>(ParametersListUtil.parse(trimStart(value, getHelpCommand()).trim()));
if (!goals.isEmpty()) {
MavenProject mavenProject = null;
if (onlyOneMavenProject) {
mavenProject = mavenProjects.get(0);
}
else {
String moduleName = goals.remove(0);
Module module = ModuleManager.getInstance(project).findModuleByName(moduleName);
if (module != null) {
mavenProject = projectsManager.findProject(module);
}
}
if (mavenProject != null) {
MavenExplicitProfiles explicitProfiles = projectsManager.getExplicitProfiles();
MavenRunnerParameters params = new MavenRunnerParameters(true,
mavenProject.getDirectory(),
mavenProject.getFile().getName(),
goals,
explicitProfiles.getEnabledProfiles(),
explicitProfiles.getDisabledProfiles());
MavenRunner mavenRunner = MavenRunner.getInstance(project);
mavenRunner.run(params, mavenRunner.getSettings(), null);
}
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.