answer stringlengths 17 10.2M |
|---|
package edu.wpi.first.wpilibj.hal;
import java.io.File;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.FileOutputStream;
// base class for all JNI wrappers
public class JNIWrapper {
static boolean libraryLoaded = false;
static File jniLibrary = null;
static {
try {
if (!libraryLoaded) {
InputStream is = JNIWrapper.class.getResourceAsStream("/linux-arm/libwpilibJavaJNI.so");
if (is != null) {
// create temporary file
jniLibrary = File.createTempFile("libwpilibJavaJNI", ".so");
// flag for delete on exit
jniLibrary.deleteOnExit();
byte[] buffer = new byte[1024];
int readBytes;
OutputStream os = new FileOutputStream(jniLibrary);
try {
while ((readBytes = is.read(buffer)) != -1) {
os.write(buffer, 0, readBytes);
}
} finally {
os.close();
is.close();
}
System.load(jniLibrary.getAbsolutePath());
} else {
System.loadLibrary("wpilibJavaJNI");
}
libraryLoaded = true;
}
} catch (Exception ex) {
ex.printStackTrace();
System.exit(1);
}
}
public static native long getPortWithModule(byte module, byte pin);
public static native long getPort(byte pin);
public static native void freePort(long port_pointer);
} |
package com.intellij.xdebugger;
import com.intellij.openapi.options.Configurable;
import com.intellij.testFramework.LiteFixture;
import com.intellij.util.xmlb.XmlSerializer;
import com.intellij.util.xmlb.annotations.Attribute;
import com.intellij.xdebugger.impl.XDebuggerUtilImpl;
import com.intellij.xdebugger.impl.settings.XDebuggerSettingsManager;
import com.intellij.xdebugger.settings.XDebuggerSettings;
import org.jdom.Element;
import org.jetbrains.annotations.NotNull;
/**
* @author nik
*/
public class XDebuggerSettingsTest extends LiteFixture {
protected void setUp() throws Exception {
super.setUp();
initApplication();
registerExtensionPoint(XDebuggerSettings.EXTENSION_POINT, XDebuggerSettings.class);
registerExtension(XDebuggerSettings.EXTENSION_POINT, new MyDebuggerSettings());
getApplication().registerService(XDebuggerUtil.class, XDebuggerUtilImpl.class);
getApplication().registerService(XDebuggerSettingsManager.class, XDebuggerSettingsManager.class);
}
public void testSerialize() throws Exception {
XDebuggerSettingsManager settingsManager = XDebuggerSettingsManager.getInstance();
MyDebuggerSettings settings = MyDebuggerSettings.getInstance();
assertNotNull(settings);
settings.myOption = "239";
Element element = XmlSerializer.serialize(settingsManager.getState());
//System.out.println(JDOMUtil.writeElement(element, SystemProperties.getLineSeparator()));
settings.myOption = "42";
assertSame(settings, MyDebuggerSettings.getInstance());
settingsManager.loadState(XmlSerializer.deserialize(element, XDebuggerSettingsManager.SettingsState.class));
assertSame(settings, MyDebuggerSettings.getInstance());
assertEquals("239", settings.myOption);
}
public static class MyDebuggerSettings extends XDebuggerSettings<MyDebuggerSettings> {
@Attribute("option")
public String myOption;
public MyDebuggerSettings() {
super("test");
}
public static MyDebuggerSettings getInstance() {
return getInstance(MyDebuggerSettings.class);
}
public MyDebuggerSettings getState() {
return this;
}
public void loadState(final MyDebuggerSettings state) {
myOption = state.myOption;
}
@NotNull
public Configurable createConfigurable() {
throw new UnsupportedOperationException("'createConfigurable' not implemented in " + getClass().getName());
}
}
} |
package jlibs.xml.xsd.display;
import jlibs.core.lang.ImpossibleException;
import jlibs.core.lang.StringUtil;
import jlibs.core.graph.visitors.PathReflectionVisitor;
import jlibs.xml.sax.helpers.MyNamespaceSupport;
import jlibs.xml.xsd.XSUtil;
import org.apache.xerces.xs.*;
/**
* @author Santhosh Kumar T
*/
public class XSDisplayNameVisitor extends PathReflectionVisitor<Object, String>{
XSPathDiplayFilter filter;
private MyNamespaceSupport nsSupport;
public XSDisplayNameVisitor(MyNamespaceSupport nsSupport, XSPathDiplayFilter filter){
this.nsSupport = nsSupport;
this.filter = filter;
}
@Override
protected String getDefault(Object elem){
return elem.toString();
}
protected String process(XSNamespaceItem nsItem){
return StringUtil.toString(nsItem.getSchemaNamespace());
}
protected String process(XSObject obj){
return XSUtil.getQName(obj, nsSupport);
}
private String addCardinal(String str){
if(!filter.select(path.getParentPath())){
XSParticle particle = (XSParticle)path.getParentPath().getElement();
return str+process(particle);
}else
return str;
}
protected String process(XSElementDeclaration elem){
String str = '<'+process((XSObject)elem)+'>';
return addCardinal(str);
}
protected String process(XSAttributeUse attrUse){
String str = '@' + process((XSObject)attrUse);
if(!attrUse.getRequired())
str += '?';
return str;
}
protected String process(XSParticle particle){
if(particle.getMinOccurs()==0 && particle.getMaxOccursUnbounded())
return "*";
else if(particle.getMinOccurs()==1 && particle.getMaxOccursUnbounded())
return "+";
else if(particle.getMaxOccursUnbounded())
return particle.getMinOccurs()+"+";
else if(particle.getMinOccurs()==0 && particle.getMaxOccurs()==1)
return "?";
else
return "["+particle.getMinOccurs()+","+particle.getMaxOccurs()+"]";
}
protected String process(XSModelGroup modelGroup){
String str;
switch(modelGroup.getCompositor()){
case XSModelGroup.COMPOSITOR_ALL :
str = "[ALL]";
break;
case XSModelGroup.COMPOSITOR_CHOICE :
str = "[OR]";
break;
case XSModelGroup.COMPOSITOR_SEQUENCE :
str = "[SEQUENCE]";
break;
default:
throw new ImpossibleException("Invalid Compositor: "+modelGroup.getCompositor());
}
return addCardinal(str);
}
protected String process(XSWildcard wildcard){
String str;
switch(wildcard.getConstraintType()){
case XSWildcard.NSCONSTRAINT_ANY :
str = "<*:*>";
break;
case XSWildcard.NSCONSTRAINT_LIST:
StringBuilder buff = new StringBuilder();
StringList list = wildcard.getNsConstraintList();
for(int i=0; i<list.getLength(); i++){
if(buff.length()>0)
buff.append('|');
buff.append(nsSupport.findPrefix(list.item(i)));
}
if(buff.length()==0)
str = "<*>";
else
str = "<"+buff+":*>";
break;
case XSWildcard.NSCONSTRAINT_NOT:
buff = new StringBuilder();
list = wildcard.getNsConstraintList();
for(int i=0; i<list.getLength(); i++){
String prefix = nsSupport.findPrefix(list.item(i));
if(!StringUtil.isEmpty(prefix)){
if(buff.length()>0)
buff.append(',');
buff.append(prefix);
}
}
if(buff.toString().indexOf(",")==-1)
str = "<!"+buff+":*>";
else
str = "<!("+buff+"):*>";
break;
default:
throw new ImpossibleException("Invalid Constraint: "+wildcard.getConstraintType());
}
return addCardinal(str);
}
} |
package com.nflabs.zeppelin;
import static org.junit.Assert.fail;
import java.io.File;
import org.junit.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebDriverException;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.firefox.FirefoxBinary;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.firefox.FirefoxProfile;
import org.openqa.selenium.safari.SafariDriver;
import org.openqa.selenium.support.ui.ExpectedCondition;
import org.openqa.selenium.support.ui.WebDriverWait;
public class ZeppelinIT {
private WebDriver getWebDriver(){
WebDriver driver = null;
if (driver==null){
try {
FirefoxBinary ffox = new FirefoxBinary();
if ("true".equals(System.getenv("TRAVIS"))) {
ffox.setEnvironmentProperty("DISPLAY", ":99"); // xvfb is supposed to run with DISPLAY 99
}
FirefoxProfile profile = new FirefoxProfile();
driver = new FirefoxDriver(ffox, profile);
} catch (Exception e){
}
}
if (driver==null){
try {
driver = new ChromeDriver();
} catch (Exception e){
}
}
if (driver==null){
try {
driver = new SafariDriver();
} catch (Exception e){
}
}
String url;
if (System.getProperty("url")!=null) {
url = System.getProperty("url");
} else {
url = "http://localhost:8080";
}
driver.get(url);
// wait for page load
(new WebDriverWait(driver, 10)).until(new ExpectedCondition<Boolean>() {
public Boolean apply(WebDriver d) {
return d.findElement(By.partialLinkText("Start")).isDisplayed();
}
});
return driver;
}
@Test
public void testRunSimpleQueryInNewSession() {
// Notice that the remainder of the code relies on the interface,
// not the implementation.
WebDriver driver = getWebDriver();
try {
// click start
WebElement start = driver.findElement(By.partialLinkText("Start"));
start.click();
// Wait for the page to load, timeout after 10 seconds
(new WebDriverWait(driver, 10)).until(new ExpectedCondition<Boolean>() {
public Boolean apply(WebDriver d) {
return d.findElement(By.linkText("New")).isDisplayed();
}
});
// click new
driver.findElement(By.linkText("New")).click();
// wait for run button appears
(new WebDriverWait(driver, 10)).until(new ExpectedCondition<Boolean>() {
public Boolean apply(WebDriver d) {
return d.findElement(By.linkText("Run")).isDisplayed();
}
});
// type some query
//driver.findElement(By.xpath("//div[@id='zqlEditor']//textarea")).sendKeys("create table if not exists test "+Keys.chord(Keys.SHIFT, "9")+"id STRING);\n");
//driver.findElement(By.xpath("//div[@id='zqlEditor']//textarea")).sendKeys("\nshow tables;");
driver.findElement(By.xpath("//div[@id='zqlEditor']//textarea")).sendKeys("asdf;");
// press run button
driver.findElement(By.linkText("Run")).click();
// wait for button becomes Running ...
(new WebDriverWait(driver, 5)).until(new ExpectedCondition<Boolean>() {
public Boolean apply(WebDriver d) {
return d.findElement(By.xpath("//div//a[text()='Running ...']")).isDisplayed();
}
});
// wait for button becomes Run
(new WebDriverWait(driver, 60)).until(new ExpectedCondition<Boolean>() {
public Boolean apply(WebDriver d) {
return d.findElement(By.xpath("//div//a[text()='Run']")).isDisplayed();
}
});
WebElement msg = driver.findElement(By.id("msgBox"));
if (msg!=null) {
System.out.println("msgBox="+msg.getText());
}
// wait for visualization
(new WebDriverWait(driver, 10)).until(new ExpectedCondition<Boolean>() {
public Boolean apply(WebDriver d) {
return d.findElement(By.xpath("//div[@id='visualizationContainer']//iframe")).isDisplayed();
}
});
WebDriver iframe = driver.switchTo().frame(driver.findElement(By.xpath("//div[@id='visualizationContainer']//iframe")));
// wait for result displayed
(new WebDriverWait(iframe, 20)).until(new ExpectedCondition<Boolean>() {
public Boolean apply(WebDriver d) {
return d.findElement(By.xpath("//table//td[text()='test']")).isDisplayed();
}
});
} catch (WebDriverException e){
File scrFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
System.out.println("Screenshot in: " + scrFile.getAbsolutePath());
throw e;
} finally {
// Close the browser
driver.quit();
}
}
} |
package algorithms.imageProcessing.transform;
import algorithms.matrix.MatrixUtil;
import java.util.Arrays;
import no.uib.cipr.matrix.NotConvergedException;
/**
* a utility class holding euler rotations and rodrigues formula.
*
* @author nichole
*/
public class Rotation {
/*
terms used describing axes of rotation:
heading, attitude, bank,
pitch, yaw, roll,
pan, tilt, roll
*/
public static double[][] calculateRotationXYZ(double angleX, double angleY, double angleZ) {
double[][] rotX = createEulerRollRotationMatrix(angleX);
double[][] rotY = createEulerPitchRotationMatrix(angleY);
double[][] rotZ = createEulerYawRotationMatrix(angleZ);
double[][] r = MatrixUtil.multiply(rotX, rotY);
r = MatrixUtil.multiply(r, rotZ);
return r;
}
public static double[][] createEulerRollRotationMatrix(double angle) {
double[][] rot = MatrixUtil.zeros(3, 3);
double c = Math.cos(angle);
double s = Math.sin(angle);
rot[0][0] = 1;
rot[1][1] = c;
rot[1][2] = -s;
rot[2][1] = s;
rot[2][2] = c;
return rot;
}
public static void createEulerRollRotationMatrix(double angle, double[][] out) {
if (out.length != 3 || out[0].length != 3) {
throw new IllegalArgumentException("out must be 3x3");
}
double c = Math.cos(angle);
double s = Math.sin(angle);
out[0][0] = 1;
out[0][1] = 0;
out[0][2] = 0;
out[1][0] = 0;
out[1][1] = c;
out[1][2] = -s;
out[2][0] = 0;
out[2][1] = s;
out[2][2] = c;
}
public static double[][] createEulerPitchRotationMatrix(double angle) {
double[][] rot = MatrixUtil.zeros(3, 3);
double c = Math.cos(angle);
double s = Math.sin(angle);
rot[0][0] = c;
rot[0][2] = s;
rot[1][1] = 1;
rot[2][0] = -s;
rot[2][2] = c;
return rot;
}
public static void createEulerPitchRotationMatrix(double angle,
double[][] out) {
if (out.length != 3 || out[0].length != 3) {
throw new IllegalArgumentException("out must be 3x3");
}
double c = Math.cos(angle);
double s = Math.sin(angle);
out[0][0] = c;
out[0][1] = 0;
out[0][2] = s;
out[1][0] = 0;
out[1][1] = 1;
out[1][2] = 0;
out[2][0] = -s;
out[2][1] = 0;
out[2][2] = c;
}
public static double[][] createEulerYawRotationMatrix(double angle) {
double[][] rot = MatrixUtil.zeros(3, 3);
double c = Math.cos(angle);
double s = Math.sin(angle);
rot[0][0] = c;
rot[0][1] = -s;
rot[1][0] = s;
rot[1][1] = c;
rot[2][2] = 1;
return rot;
}
public static void createEulerYawRotationMatrix(double angle, double[][] out) {
if (out.length != 3 || out[0].length != 3) {
throw new IllegalArgumentException("out must be 3x3");
}
double c = Math.cos(angle);
double s = Math.sin(angle);
out[0][0] = c;
out[0][1] = -s;
out[0][2] = 0;
out[1][0] = s;
out[1][1] = c;
out[1][2] = 0;
out[2][0] = 0;
out[2][1] = 0;
out[2][2] = 1;
}
public static double[][] createRodriguesFormulaRotationMatrix(double[] v) {
if (v.length != 3) {
throw new IllegalArgumentException("v length must be 3");
}
'''Rodrigues formula
Input: 1x3 array of rotations about x, y, and z
Output: 3x3 rotation matrix'''
double theta = MatrixUtil.lPSum(v, 2);
double[][] tmp1, tmp2;
if (theta > 1e-30) {
double[] n = Arrays.copyOf(v, v.length);
MatrixUtil.multiply(n, 1./theta);
double[][] sn = MatrixUtil.skewSymmetric(n);
//R = eye(3) + sin(theta)*Sn + (1-cos(theta))*dot(Sn,Sn)
tmp1 = MatrixUtil.copy(sn);
MatrixUtil.multiply(tmp1, Math.sin(theta));
tmp2 = MatrixUtil.multiply(sn, sn);
MatrixUtil.multiply(tmp2, 1. - Math.cos(theta));
} else {
double[][] sr = MatrixUtil.skewSymmetric(v);
double theta2 = theta*theta;
//R = eye(3) + (1-theta2/6.)*Sr + (.5-theta2/24.)*dot(Sr,Sr)
tmp1 = MatrixUtil.copy(sr);
MatrixUtil.multiply(tmp1, (1. - theta2)/6.);
tmp2 = MatrixUtil.multiply(sr, sr);
MatrixUtil.multiply(tmp2, 0.5 - theta2/24.);
}
double[][] r = MatrixUtil.createIdentityMatrix(3);
int j;
for (int i = 0; i < tmp1.length; ++i) {
for (j = 0; j < tmp1[i].length; ++j) {
r[i][j] += (tmp1[i][j] + tmp2[i][j]);
}
}
return r;
}
/**
* determine the rotation between measurements x1 and x2 when both datasets
* have the same center, that is, there is no translation between them,
* only rotation.
* (see Golub & van Loan "Matrix Computations" 11.12.4,
* Szeliski 2010, Sect 6.1.5).
* @param x1 a set of measurements having same center as x2, that is,
* there is no translation between them, only rotation.
* the expected format is nData X nDimensions.
* @param x2 another set of measurements having same center as x1, that is,
* there is no translation between them, only rotation.
* the expected format is nData X nDimensions.
* @return
* @throws no.uib.cipr.matrix.NotConvergedException
*/
public static double[][] procrustesAlgorithmForRotation(double[][] x1, double[][] x2)
throws NotConvergedException {
int m = x1.length;
int p = x1[0].length;
if (x2.length != m || x2[0].length != p) {
throw new IllegalArgumentException("x1 and x2 must have same sizes");
}
// minimize || x1 - x2*Q ||_F
// subject to Q^T * Q = I_P
double[][] c = MatrixUtil.multiply(MatrixUtil.transpose(x2), x1);
MatrixUtil.SVDProducts svdC = MatrixUtil.performSVD(c);
double[][] q = MatrixUtil.multiply(svdC.u, svdC.vT);
return q;
}
public static double[] extractRotationFromZXY(double[][] r) {
if (r.length != 3 || r[0].length != 3) {
throw new IllegalArgumentException("r must be 3x3");
}
double thetaX = Math.asin(r[2][1]);
double thetaY = Math.atan2(-r[2][0], r[2][2]);
double thetaZ = Math.atan2(-r[0][1], r[1][1]);
return new double[]{thetaX, thetaY, thetaZ};
}
/**
* extract euler angles from a rotation matrix which has been built following
* the convention of R(theta_Z) * R(theta_Y) * R(theta_X).
* @param r
* @return
*/
public static double[] extractRotationFromZYX(double[][] r) {
if (r.length != 3 || r[0].length != 3) {
throw new IllegalArgumentException("r must be 3x3");
}
double thetaX, thetaY, thetaZ;
double d = r[2][1]*r[2][1] + r[2][2]*r[2][2];
if (d == 0) {
thetaY = -Math.asin(r[2][0]);
} else {
thetaY = Math.atan2(-r[2][0], Math.sqrt(d));
}
thetaZ = Double.NEGATIVE_INFINITY;
if (r[2][2] != 0) {
thetaX = Math.atan2(r[2][1], r[2][2]);
} else {
if (r[2][1] != 0) {
thetaX = Math.asin(r[2][1]/Math.cos(thetaY));
} else {
// need thetaZ solved
if (r[0][0] != 0) {
thetaZ = Math.atan2(r[1][0], r[0][0]);
double cPsi = Math.cos(thetaY);
if (cPsi != 0) {
// can use r[2][1] or r[2][2] for simplest:
thetaX = Math.asin(r[2][1]/cPsi);
} else {
// can use r[0][1], r[0][2], r[1][1], or r[1][2] or combination
throw new UnsupportedOperationException("There are "
+ "0's in the rotation matrix, so factoring of "
+ "more than one exponential variable is needed."
+ "This case is not yet implemented.");
}
} else {
throw new UnsupportedOperationException("There are "
+ "0's in the rotation matrix, so factoring of "
+ "more than one exponential variable is needed."
+ "This case is not yet implemented.");
}
}
}
if (thetaZ == Double.NEGATIVE_INFINITY) {
if (r[0][0] != 0) {
thetaZ = Math.atan2(r[1][0], r[0][0]);
} else {
throw new UnsupportedOperationException("There are "
+ "0's in the rotation matrix, so factoring of "
+ "more than one exponential variable is needed."
+ "This case is not yet implemented.");
}
}
return new double[]{thetaX, thetaY, thetaZ};
}
public static double[] extractRotation2(double[][] r) {
if (r.length != 3 || r[0].length != 3) {
throw new IllegalArgumentException("r must be 3x3");
}
/*
theta=acos((trace(R)-1)/2);
w=(theta/(2*sin(theta)))*[R(3,2)-R(2,3); R(1,3)-R(3,1); R(2,1)-R(1,2)];
wx=w(1);
wy=w(2);
wz=w(3);
*/
int i;
double[] theta = new double[3];
double[] w = new double[3];
for (i = 0; i < 3; ++i) {
theta[i] = Math.acos((r[i][i] - 1.)/2.);
w[i] = theta[i]/(2.*Math.sin(theta[i]));
}
w[0] *= r[2][1] - r[1][2];
w[1] *= r[0][2] - r[2][0];
w[2] *= r[1][0] - r[0][1];
return w;
}
public static double[][] updateRotation(double[][] r, double[] dx) {
double[][] iMinusDX = MatrixUtil.createIdentityMatrix(3);
double[][] dxM = MatrixUtil.skewSymmetric(dx);
double[][] factor = MatrixUtil.multiply(iMinusDX, dxM);
r = MatrixUtil.multiply(r, factor);
return r;
}
public static double[][] quaternionLefthandCompoundOperator(double[] quaternion) {
if (quaternion.length != 4) {
throw new IllegalArgumentException("quaternion must be length 4");
}
double[] eps = Arrays.copyOfRange(quaternion, 0, 3);
assert(eps.length == 3);
double eta = quaternion[3];
double[][] minusSkewEps = MatrixUtil.skewSymmetric(eps);
MatrixUtil.multiply(minusSkewEps, -1);
double[][] i3Eta = MatrixUtil.createIdentityMatrix(3);
MatrixUtil.multiply(i3Eta, eta);
// 3X3
double[][] block00 = MatrixUtil.elementwiseAdd(i3Eta, minusSkewEps);
double[][] lhc = MatrixUtil.zeros(4, 4);
int i;
for (i = 0; i < 3; ++i) {
System.arraycopy(block00[i], 0, lhc[i], 0, 3);
lhc[i][3] = eps[i];
}
for (i = 0; i < 3; ++i) {
lhc[3][i] = -eps[i];
}
lhc[3][3] = eta;
return lhc;
}
public static double[][] quaternionRighthandCompoundOperator(double[] quaternion) {
if (quaternion.length != 4) {
throw new IllegalArgumentException("quaternion must be length 4");
}
double[] eps = Arrays.copyOfRange(quaternion, 0, 3);
assert(eps.length == 3);
double eta = quaternion[3];
double[][] skewEps = MatrixUtil.skewSymmetric(eps);
double[][] i3Eta = MatrixUtil.createIdentityMatrix(3);
MatrixUtil.multiply(i3Eta, eta);
// 3X3
double[][] block00 = MatrixUtil.elementwiseAdd(i3Eta, skewEps);
double[][] lhc = MatrixUtil.zeros(4, 4);
int i;
for (i = 0; i < 3; ++i) {
System.arraycopy(block00[i], 0, lhc[i], 0, 3);
lhc[i][3] = eps[i];
}
for (i = 0; i < 3; ++i) {
lhc[3][i] = -eps[i];
}
lhc[3][3] = eta;
return lhc;
}
/**
* given a quaternion, return the inverse
* <pre>
* from Barfoot, Forbes, & Furgale 2010, "Pose estimation using linearized
* rotations and quaternion algebra", Acta Astronautica (2010), doi:10.1016/j.actaastro.2010.06.049.
*
* eqn (5):
* given q = 4X1 column vector of [eps eta] where eta is the scalar,
*
* the inverse is the column vector:
*
* q^-1 = [ -eps eta ]
*
* </pre>
* <em>NOTE that if the quaternion is a unit-length quaternion, the conjugate
* operation is usually called the inverse operation.</em>
* @param quaternion
* @return
*/
public static double[] quaternionConjugateOperator(double[] quaternion) {
if (quaternion.length != 4) {
throw new IllegalArgumentException("quaternion must be length 4");
}
double[] inv = Arrays.copyOf(quaternion, 4);
int i;
for (i = 0; i < 3; ++i) {
inv[i] *= -1;
}
return inv;
}
/**
* given a quaternion, return the inverse
* <pre>
* from Barfoot, Forbes, & Furgale 2010, "Pose estimation using linearized
* rotations and quaternion algebra", Acta Astronautica (2010), doi:10.1016/j.actaastro.2010.06.049,
* near eqn (8):
*
* creates identity element: [0 0 0 1]
*
* </pre>
* @return
*/
public static double[] createIdentityQuaternion() {
double[] i4 = new double[4];
i4[3] = 1;
return i4;
}
/**
* create a rotation matrix from the given quaternion
* <pre>
* from Barfoot, Forbes, & Furgale 2010, "Pose estimation using linearized
* rotations and quaternion algebra", Acta Astronautica (2010), doi:10.1016/j.actaastro.2010.06.049.
*
* eqn (12):
*
* R = q^+ * q^(-1)^ = q^(-1)^ * q^+ = q^()^T * q^+
*
* = [ C 0 ]
* [ 0^T 1 ]
* where C is the canonical 3X3 rotation matrix.
* </pre>
* @param quaternion the quaternion 4 element array
* @return a 4x4 rotation matrix
*/
public static double[][] createRotationMatrixFromQuaternion(double[] quaternion) {
if (quaternion.length != 4) {
throw new IllegalArgumentException("quaternion must be length 4");
}
double[][] lhc = quaternionLefthandCompoundOperator(quaternion);
double[][] rhcT = quaternionRighthandCompoundOperator(quaternion);
rhcT = MatrixUtil.transpose(rhcT);
double[][] r = MatrixUtil.multiply(rhcT, lhc);
return r;
}
/**
* rotate point p by the given quaternion.
* <pre>
* from Barfoot, Forbes, & Furgale 2010, "Pose estimation using linearized
* rotations and quaternion algebra", Acta Astronautica (2010), doi:10.1016/j.actaastro.2010.06.049.
*
* eqn (11):
*
* v3 = [ p ]
* [ 0 ]
*
* rotated = q^+ * q^(-1)^ * v3 = R*v3
*
* where R is the canonical 3X3 rotation matrix.
* </pre>
* @param quaternion the quaternion 4 element array
* @param v3 the point as 3 element array.
* @return
*/
public static double[] rotateAPointByQuaternion(double[] quaternion, double[] v3) {
if (quaternion.length != 4) {
throw new IllegalArgumentException("quaternion must be length 4");
}
if (v3.length != 3) {
throw new IllegalArgumentException("v3 must be length 3");
}
double[] v = Arrays.copyOf(v3, 4);
return rotateVectorByQuaternion4(quaternion, v);
}
/**
* rotate point p by the given quaternion.
* <pre>
* from Barfoot, Forbes, & Furgale 2010, "Pose estimation using linearized
* rotations and quaternion algebra", Acta Astronautica (2010), doi:10.1016/j.actaastro.2010.06.049.
*
* eqn (11):
*
* v3 = [ p ]
* [ 0 ]
*
* rotated = q^+ * q^(-1)^ * v3 = R*v3
*
* </pre>
* @param quaternion the quaternion 4 element array
* @param v the vector as a 3 element array followed by a 0.
* @return
*/
public static double[] rotateVectorByQuaternion4(double[] quaternion, double[] v) {
if (quaternion.length != 4) {
throw new IllegalArgumentException("quaternion must be length 4");
}
if (v.length != 4) {
throw new IllegalArgumentException("v3 must be length 4");
}
double[][] r = createRotationMatrixFromQuaternion(quaternion);
double[] result = MatrixUtil.multiplyMatrixByColumnVector(r, v);
return result;
}
/**
* apply infinitesimal rotation expressed as euler angles ([1X3])
* to a rotation matrix ([3X3]).
* To the first order, this is a constraint-sensitive approach, i.e.
* r*r^T = I for the perturbed matrix to first order as long as it was
* true for the given matrix r.
* <pre>
* from Barfoot, Forbes, & Furgale 2010, "Pose estimation using linearized
* rotations and quaternion algebra", Acta Astronautica (2010), doi:10.1016/j.actaastro.2010.06.049.
*
* eqn (31) and (30c).
*
* "This update approach allows us to store and update the rotation as a
* rotation matrix, thereby avoiding singularities and the need to restore
* the constraint afterwards (i.e., constraint restoration is built in)."
*
* </pre>
* @return
*/
public static double[][] applyRotationPerturbationEuler(
double[][] r, double[] theta, double[] dTheta) {
if (r.length != 3 || r[0].length != 3) {
throw new IllegalArgumentException("r size must be [3X3]");
}
if (theta.length != 3) {
throw new IllegalArgumentException("theta must be length 3");
}
if (dTheta.length != 3) {
throw new IllegalArgumentException("dTheta must be length 3");
}
//3X3
double[] dPhi = createRotationVector(theta, dTheta);
double[][] skew = MatrixUtil.skewSymmetric(dPhi);
int i;
for (i = 0; i < skew.length; ++i) {
skew[i][i] = 1. - skew[i][i];
}
double[][] result = MatrixUtil.multiply(skew, r);
return result;
}
/**
* apply infinitesimal rotation expressed as euler angles ([1X3])
* to a rotation matrix ([3X3]).
* To the first order, this is a constraint-sensitive approach, i.e.
* r*r^T = I for the perturbed matrix to first order as long as it was
* true for the given matrix r.
* <pre>
* from Barfoot, Forbes, & Furgale 2010, "Pose estimation using linearized
* rotations and quaternion algebra", Acta Astronautica (2010), doi:10.1016/j.actaastro.2010.06.049.
*
* eqn (31) and (30c).
*
* "This update approach allows us to store and update the rotation as a
* rotation matrix, thereby avoiding singularities and the need to restore
* the constraint afterwards (i.e., constraint restoration is built in)."
*
* </pre>
*/
public static void applySingularitySafeRotationPerturbationEuler(
double[][] r, double[] theta, double[] dTheta, double[][] out) {
if (r.length != 3 || r[0].length != 3) {
throw new IllegalArgumentException("r size must be [3X3]");
}
if (theta.length != 3) {
throw new IllegalArgumentException("theta must be length 3");
}
if (dTheta.length != 3) {
throw new IllegalArgumentException("dTheta must be length 3");
}
if (out.length != 3 || out[0].length != 3) {
throw new IllegalArgumentException("out size must be [3X3]");
}
//3X3 dPhi is the perturbation of the "rotation vector"
double[] dPhi = createRotationVector(theta, dTheta);
double[][] skew = MatrixUtil.skewSymmetric(dPhi);
// I - [dPhi]_x
int i;
for (i = 0; i < skew.length; ++i) {
skew[i][i] = 1. - skew[i][i];
}
MatrixUtil.multiply(skew, r, out);
}
/**
* apply infinitesimal rotation expressed as euler angles ([1X3])
* to a rotation matrix ([3X3]).
* To the first order, this is a constraint-sensitive approach.
* <pre>
* from Barfoot, Forbes, & Furgale 2010, "Pose estimation using linearized
* rotations and quaternion algebra", Acta Astronautica (2010), doi:10.1016/j.actaastro.2010.06.049.
*
* eqn (31).
* "This update approach allows us to store and update the rotation as a
* rotation matrix, thereby avoiding singularities and the need to restore
* the constraint afterwards (i.e., constraint restoration is built in).
*
* </pre>
* @return
*/
public static double[][] applySingularitySafeRotationPerturbationRVec(
double[][] r, double[] dPhiRotationVector, double[] theta) {
if (r.length != 3 || r[0].length != 3) {
throw new IllegalArgumentException("r size must be [3X3]");
}
if (theta.length != 3) {
throw new IllegalArgumentException("theta must be length 3");
}
double[][] r1 = Rotation.calculateRotationZYX(dPhiRotationVector);
double[][] result = MatrixUtil.multiply(r1, r);
return result;
}
public static double[][] sTheta(double[] theta) {
if (theta.length != 3) {
throw new IllegalArgumentException("theta length must be 3");
}
double[][] sTheta = MatrixUtil.zeros(3, 3);
sTheta(theta, sTheta);
return sTheta;
}
public static void sTheta(double[] theta, double[][] output) {
if (theta.length != 3) {
throw new IllegalArgumentException("theta length must be 3");
}
double[] i0 = new double[]{1, 0, 0};
double[] i1 = new double[]{0, 1, 0};
double[] i2 = new double[]{0, 0, 1};
double[][] cBeta = createEulerPitchRotationMatrix(theta[1]);
double[][] cGamma = createEulerYawRotationMatrix(theta[2]);
double[] col0 = MatrixUtil.multiplyMatrixByColumnVector(
MatrixUtil.multiply(cGamma, cBeta), i0);
double[] col1 = MatrixUtil.multiplyMatrixByColumnVector(
cGamma, i1);
double[] col2 = i2;
int i;
for (i = 0; i < 3; ++i) {
output[0][i] = col0[i];
output[1][i] = col1[i];
output[2][i] = col2[i];
}
}
public static double[][] calculateRotationZYX(double[] thetas) {
if (thetas.length != 3) {
throw new IllegalArgumentException("thetas must be length 3");
}
double[][] rZ = Rotation.createEulerYawRotationMatrix(thetas[2]);
double[][] rX = Rotation.createEulerRollRotationMatrix(thetas[0]);
double[][] rY = Rotation.createEulerPitchRotationMatrix(thetas[1]);
double[][] r = MatrixUtil.multiply(rZ, MatrixUtil.multiply(rY, rX));
return r;
}
public static void calculateRotationZYX(double[] thetas, AuxiliaryArrays aa, double[][] out) {
if (thetas.length != 3) {
throw new IllegalArgumentException("thetas must be length 3");
}
double[][] rZ = aa.a3X3;
Rotation.createEulerYawRotationMatrix(thetas[2], rZ);
double[][] rY = aa.b3X3;
Rotation.createEulerPitchRotationMatrix(thetas[1], rY);
double[][] rX = aa.c3X3;
Rotation.createEulerRollRotationMatrix(thetas[0], rX);
double[][] rZY = aa.d3X3;
MatrixUtil.multiply(rZ, rY, rZY);
MatrixUtil.multiply(rZY, rX, out);
}
public static double[][] calculateRotationXYZ(double[] thetas) {
if (thetas.length != 3) {
throw new IllegalArgumentException("thetas must be length 3");
}
double[][] rZ = Rotation.createEulerYawRotationMatrix(thetas[2]);
double[][] rX = Rotation.createEulerRollRotationMatrix(thetas[0]);
double[][] rY = Rotation.createEulerPitchRotationMatrix(thetas[1]);
double[][] r = MatrixUtil.multiply(rX, MatrixUtil.multiply(rY, rZ));
return r;
}
/*
<pre>
* from Barfoot, Forbes, & Furgale 2010, "Pose estimation using linearized
* rotations and quaternion algebra", Acta Astronautica (2010), doi:10.1016/j.actaastro.2010.06.049.
*
* eqn (32)
satisfies unit-length constraint q^T*q = 1 (size [1X4]*[4X1]=[1X1].
q^T*q = q_1^2 + q_2^2 + q_3^2 + q_4^2.
</pre>
*/
public static double[] createUnitLengthQuaternion(double[] unitLengthAxis, double angle) {
double cPhi2 = Math.cos(angle)/2.;
double sPhi2 = Math.sin(angle)/2.;
double[] out = new double[]{
unitLengthAxis[0]*sPhi2, unitLengthAxis[1]*sPhi2,
unitLengthAxis[2]*sPhi2, cPhi2
};
return out;
}
/*
<pre>
* from Barfoot, Forbes, & Furgale 2010, "Pose estimation using linearized
* rotations and quaternion algebra", Acta Astronautica (2010), doi:10.1016/j.actaastro.2010.06.049.
*
* eqn (14)
satisfies unit-length constraint q^T*q = 1 (size [1X4]*[4X1]=[1X1].
q^T*q = q_1^2 + q_2^2 + q_3^2 + q_4^2.
</pre>
*/
public static double[][] createRotationFromUnitLengthAngleAxis(double[] unitLengthAxis, double angle) {
double ca = Math.cos(angle);
double oneMinusCa = 1. - ca;
double sa = Math.sin(angle);
double[][] eye = MatrixUtil.createIdentityMatrix(3);
double[][] skewA = MatrixUtil.skewSymmetric(unitLengthAxis);
double[][] aaT = MatrixUtil.outerProduct(unitLengthAxis, unitLengthAxis);
double[][] c = MatrixUtil.zeros(3, 3);
int i, j;
for (i = 0; i < 3; ++i) {
for (j = 0; j < 3; ++j) {
c[i][j] = ca*eye[i][j] + oneMinusCa*aaT[i][j] - sa*skewA[i][j];
}
}
return c;
}
/**
* apply infinitesimal rotation expressed as euler angles ([1X3])
* to a rotation matrix ([3X3]).
* To the first order, this is a constraint-sensitive approach.
* <pre>
* from Barfoot, Forbes, & Furgale 2010, "Pose estimation using linearized
* rotations and quaternion algebra", Acta Astronautica (2010), doi:10.1016/j.actaastro.2010.06.049.
*
* eqn (44).
*
* </pre>
* @return
*/
public static double[] applyRotationPerturbationToQuaternion(
double[] q, double[] theta, double[] dTheta) {
if (q.length != 4) {
throw new IllegalArgumentException("q.length must be 4");
}
if (theta.length != 3) {
throw new IllegalArgumentException("theta must be length 3");
}
if (dTheta.length != 3) {
throw new IllegalArgumentException("dTheta must be length 3");
}
double[] dPhi = createRotationVector(theta, dTheta);
double[][] skew = MatrixUtil.skewSymmetric(dPhi);
int i;
for (i = 0; i < skew.length; ++i) {
skew[i][i] = 1. - skew[i][i];
}
double[] result = MatrixUtil.multiplyMatrixByColumnVector(skew, q);
return result;
}
/*
<pre>
* from Barfoot, Forbes, & Furgale 2010, "Pose estimation using linearized
* rotations and quaternion algebra", Acta Astronautica (2010), doi:10.1016/j.actaastro.2010.06.049.
*
* eqn (35)
</pre>
@param principalAxis the axis of rotation, that is x, y, or z.
(rotation about x is roll, y is pitch, and z is yaw).
*/
public static double[] quaternionPrincipalAxisRotation(double angle, int principalAxis) {
if (principalAxis < 0 || principalAxis > 2) {
throw new IllegalArgumentException("principalAxis must be 0, 1, or 2");
}
double sa = Math.sin(angle);
double ca = Math.cos(angle);
double[] q = new double[4];
q[principalAxis] = sa;
q[3] = ca;
return q;
}
/**
* create the rotation vector dPhi = S(theta) * dTheta
* <pre>
* from Barfoot, Forbes, & Furgale 2010, "Pose estimation using linearized
* rotations and quaternion algebra", Acta Astronautica (2010), doi:10.1016/j.actaastro.2010.06.049.
*
* eqn (37)
*
* </pre>
* @return rotation matrix [3X3].
*/
public static double[][] createRotationFromEulerViaQuaternion(double[] theta) {
if (theta.length != 3) {
throw new IllegalArgumentException("theta.length must be 3");
}
double[] q0 = quaternionPrincipalAxisRotation(theta[0], 0);
double[] q1 = quaternionPrincipalAxisRotation(theta[1], 1);
double[] q2 = quaternionPrincipalAxisRotation(theta[2], 2);
double[][] q0m = quaternionRighthandCompoundOperator(q0);
double[][] q1m = quaternionRighthandCompoundOperator(q1);
double[][] q2m = quaternionRighthandCompoundOperator(q2);
double[][] q = MatrixUtil.zeros(3, 3);
MatrixUtil.multiply(q2m, q1m, q);
MatrixUtil.multiply(q, q0m, q);
return q;
}
/**
* create the rotation vector dPhi = S(theta) * dTheta
* <pre>
* from Barfoot, Forbes, & Furgale 2010, "Pose estimation using linearized
* rotations and quaternion algebra", Acta Astronautica (2010), doi:10.1016/j.actaastro.2010.06.049.
*
* text under eqn (26)
*
* </pre>
* @return dPhi= S(theta) * dTheta. length is 3.
*/
public static double[] createRotationVector(double[] theta, double[] dTheta) {
double[][] sTheta = sTheta(dTheta);
// length 3
double[] dPhi = MatrixUtil.multiplyMatrixByColumnVector(sTheta, dTheta);
return dPhi;
}
/**
* apply rotation expressed as euler angles ([1X3]) to a quaternion ([4X1]).
* To the first order, this is a constraint-sensitive approach.
* <pre>
* from Barfoot, Forbes, & Furgale 2010, "Pose estimation using linearized
* rotations and quaternion algebra", Acta Astronautica (2010), doi:10.1016/j.actaastro.2010.06.049.
*
* eqn (49), (48a)
*
* "This update approach allows us to store and update the rotation as a
* unit-length quaternion, thereby avoiding singularities and the need to
* restore the constraint afterwards (i.e., constraint restoration is
* built in)."
*
* </pre>
* @return
*/
public static double[] applySingularitySafeRotationPerturbationQuaternion(
double[] q, double[] theta, double[] dTheta) {
if (q.length != 4) {
throw new IllegalArgumentException("q length must be 4");
}
if (dTheta.length != 3) {
throw new IllegalArgumentException("theta must be length 3");
}
// length 3
double[] dPhi = createRotationVector(theta, dTheta);
// length 4
double[] qdPhi = createIdentityQuaternion();
int i;
for (i = 0; i < 3; ++i) {
qdPhi[i] += 0.5*dPhi[i];
}
double[][] qLH = quaternionLefthandCompoundOperator(qdPhi);
double[] result = MatrixUtil.multiplyMatrixByColumnVector(qLH, q);
return result;
}
public static class AuxiliaryArrays {
final double[][] a3X3;
final double[][] b3X3;
final double[][] c3X3;
final double[][] d3X3;
public AuxiliaryArrays() {
a3X3 = MatrixUtil.zeros(3, 3);
b3X3 = MatrixUtil.zeros(3, 3);
c3X3 = MatrixUtil.zeros(3, 3);
d3X3 = MatrixUtil.zeros(3, 3);
}
}
} |
package org.umlg.sqlg;
import org.junit.runner.RunWith;
import org.junit.runners.Suite;
import org.umlg.sqlg.test.gremlincompile.TestTraversalPerformance;
@RunWith(Suite.class)
@Suite.SuiteClasses({
TestTraversalPerformance.class
// TestMultiThread.class,
})
public class AnyTest {
} |
package com.plugin.gcm;
import com.google.android.gcm.GCMBaseIntentService;
import android.annotation.SuppressLint;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.NotificationCompat;
import android.util.Log;
@SuppressLint("NewApi")
public class GCMIntentService extends GCMBaseIntentService {
public static final int NOTIFICATION_ID = 237;
private static String TAG = "PushPlugin-GCMIntentService";
public static final String MESSAGE = "message";
public static final String COLDSTART = "coldstart";
public GCMIntentService() {
super("GCMIntentService");
}
@Override
public void onRegistered(Context context, String regId) {
Log.v(TAG, "onRegistered: " + regId);
NotificationService.getInstance(context).onRegistered(regId);
}
@Override
public void onUnregistered(Context context, String regId) {
Log.d(TAG, "onUnregistered - regId: " + regId);
}
@Override
protected void onMessage(Context context, Intent intent) {
boolean isPushPluginActive = NotificationService.getInstance(context).isActive();
Log.d(TAG, "onMessage - isPushPluginActive: " + isPushPluginActive);
Bundle extras = intent.getExtras();
if (extras != null) {
if (!isPushPluginActive) {
extras.putBoolean(COLDSTART, true);
}
NotificationService.getInstance(context).onMessage(extras);
if (extras.getString(MESSAGE) != null && extras.getString(MESSAGE).length() != 0) {
createNotification(context, extras);
}
}
}
public void createNotification(Context context, Bundle extras) {
NotificationManager mNotificationManager = (NotificationManager) getSystemService(
Context.NOTIFICATION_SERVICE);
String appName = getAppName(this);
Intent notificationIntent = new Intent(this, PushHandlerActivity.class);
notificationIntent.addFlags(
Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TOP);
notificationIntent.putExtra("pushBundle", extras);
PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent,
PendingIntent.FLAG_UPDATE_CURRENT);
int defaults = Notification.DEFAULT_ALL;
if (extras.getString("defaults") != null) {
try {
defaults = Integer.parseInt(extras.getString("defaults"));
} catch (NumberFormatException e) {
}
}
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(context)
.setDefaults(defaults)
.setSmallIcon(context.getApplicationInfo().icon)
.setWhen(System.currentTimeMillis())
.setContentTitle(extras.getString("title"))
.setTicker(extras.getString("title"))
.setContentIntent(contentIntent)
.setAutoCancel(true);
String message = extras.getString("message");
if (message != null) {
mBuilder.setContentText(message);
} else {
mBuilder.setContentText("<missing message content>");
}
String msgcnt = extras.getString("msgcnt");
if (msgcnt != null) {
mBuilder.setNumber(Integer.parseInt(msgcnt));
}
int notId = NOTIFICATION_ID;
try {
notId = Integer.parseInt(extras.getString("notId"));
} catch (NumberFormatException e) {
Log.e(TAG,
"Number format exception - Error parsing Notification ID: " + e.getMessage());
} catch (Exception e) {
Log.e(TAG, "Number format exception - Error parsing Notification ID" + e.getMessage());
}
mNotificationManager.notify((String) appName, notId, mBuilder.build());
}
public static void cancelNotification(Context context) {
NotificationManager mNotificationManager = (NotificationManager) context.getSystemService(
Context.NOTIFICATION_SERVICE);
mNotificationManager.cancel((String) getAppName(context), NOTIFICATION_ID);
}
private static String getAppName(Context context) {
CharSequence appName =
context
.getPackageManager()
.getApplicationLabel(context.getApplicationInfo());
return (String) appName;
}
@Override
public void onError(Context context, String errorId) {
Log.e(TAG, "onError - errorId: " + errorId);
}
} |
package am.app.feedback.measures;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import edu.stanford.nlp.parser.lexparser.GermanUnknownWordModel;
import am.app.Core;
import am.app.feedback.CandidateConcept;
import am.app.feedback.CandidateSelection;
import am.app.mappingEngine.AbstractMatcher.alignType;
import am.app.ontology.Node;
import am.app.ontology.Ontology;
public class RepeatingPatterns extends RelevanceMeasure{
Ontology sourceOntology;
Ontology targetOntology;
ArrayList<Node> sClasses;
ArrayList<Node> tClasses;
ArrayList<Node> sProps;
ArrayList<Node> tProps;
NodeComparator nc;
ArrayList<Node> noParentNodes;
//ArrayList<ArrayList<Node>> patterns;
ArrayList<Integer> patternFreqs;
ArrayList<Double> repetitiveMeasure;
CandidateConcept.ontology whichOntology;
alignType whichType;
HashMap<Pattern, Integer> patterns;
public RepeatingPatterns(double th) {
super(th);
nc = new NodeComparator();
Core core = Core.getInstance();
sourceOntology = core.getSourceOntology();
targetOntology = core.getTargetOntology();
sClasses = sourceOntology.getClassesList();
tClasses = targetOntology.getClassesList();
sProps = sourceOntology.getPropertiesList();
tProps = targetOntology.getPropertiesList();
//patterns = new ArrayList<ArrayList<Node>>();
patternFreqs = new ArrayList<Integer>();
repetitiveMeasure = new ArrayList<Double>();
patterns = new HashMap<Pattern, Integer>();
}
//Returns Lex sorted children of a node
public ArrayList<Node> getChildrenSorted(Node n){
ArrayList<Node> sortedChildren = new ArrayList<Node>();
sortedChildren = n.getChildren();
if(sortedChildren != null){
sortNodesLex(sortedChildren);
return sortedChildren;
}
else{
return null;
}
}
//Sorts given list in Lexicographical order
public ArrayList<Node> sortNodesLex(ArrayList<Node> nodeList){
Collections.sort(nodeList, nc);
return nodeList;
}
//Sorts given list in Lexicographical order
public ArrayList<Edge> sortEdgesLex(ArrayList<Edge> edgeList){
Collections.sort(edgeList);
return edgeList;
}
public void createCandidateList(){
}
public ArrayList<Edge> createEdgesFromNodeList(ArrayList<Node> list){
ArrayList<Edge> edges = new ArrayList<Edge>();
for(Node n: list){
ArrayList<Node> nAdj = n.getChildren();
for(Node child: nAdj){
Edge e = new Edge(n, child);
edges.add(e);
}
}
return edges;
}
public void run(int k, int edgeSize){
sClasses = sortNodesLex(sClasses);
ArrayList<Edge> start = createEdgesFromNodeList(sClasses);
ArrayList<Pattern> finalPatterns = getPatternsGivenLength(start, k, edgeSize);
printPatterns(finalPatterns);
}
//Generate patterns of length k
public ArrayList<Pattern> getPatternsGivenLength(ArrayList<Edge> list, int k, int edgeSize){
ArrayList<Pattern> pats = new ArrayList<Pattern>();
ArrayList<Edge> edges = sortEdgesLex(list);
Node srcNode = null;
Pattern aPat = null;
ArrayList<Edge> edgeSeq = new ArrayList<Edge>();
for(Edge a : edges){
a.setSourceVisit(1);
a.setTargetVisit(2);
edgeSeq.add(a);
Pattern p = new Pattern(1, edgeSeq, null);
p.setLastVisit(2);
if(patterns.containsKey(p)){
Integer aVal = patterns.get(p);
int val = aVal.intValue() + 1;
aVal = new Integer(val);
patterns.put(p, aVal);
}
else{
Integer freq = new Integer(1);
patterns.put(p, freq);
}
//get the siblings of the edge passed in, and recurse again on them
growEdge(p, a, k, pats, false);
//create edgelist of that list
srcNode = a.getSourceNode();
ArrayList<Node> srcNodeChildren = getChildrenSorted(srcNode);
ArrayList<Edge> asd = createEdgesFromNodeList(srcNodeChildren);
if(asd.contains(a)){
asd.remove(a);
}
//bu yeni pattern gerekli mi?
ArrayList<Pattern> pp = new ArrayList<Pattern>();
for(Edge b: asd){
for(int i = 0; i < pats.size(); i++)
{
aPat = pats.get(i);
growEdge(aPat, b, k, pp, true);
}
}
}
return pats;
}
//Find repeating patterns here
public void growEdge(Pattern p, Edge a, int k, ArrayList<Pattern> pats, boolean st){
//Decide growing source or target
Node nodeToGrow = null;
if(st){
nodeToGrow = a.getSourceNode();
}
else{
nodeToGrow = a.getTargetNode();
}
ArrayList<Pattern> pats2 = new ArrayList<Pattern>();
//Nodes are sorted lex
ArrayList<Node> ntgADJ = nodeToGrow.getChildren();
ntgADJ = sortNodesLex(ntgADJ);
//ArrayList<Edge> ntgEdges = createEdgesFromNodeList(ntgADJ);
while(!ntgADJ.isEmpty()){
Node removed = ntgADJ.get(0);
Edge passInRecursion = new Edge(nodeToGrow, removed);
//Lastvisit is the variable to keep track of the number
for(int i = 0; i < p.getEdgeSequence().size(); i++){
Edge temp = p.getEdgeAtIndex(i);
if(temp.getSourceNode().getIndex() == nodeToGrow.getIndex())
{
p.setLastVisit(temp.getSourceVisit());
}
else if(temp.getTargetNode().getIndex() == nodeToGrow.getIndex())
{
p.setLastVisit(temp.getTargetVisit());
}
}
p.setLastVisit(p.getLastVisit()+1);
passInRecursion.setSourceVisit(p.getLastVisit());
p.setLastVisit(p.getLastVisit()+1);
passInRecursion.setTargetVisit(p.getLastVisit());
ntgADJ.remove(ntgADJ.get(0));
ArrayList<Edge> edgSeq = new ArrayList<Edge>();
edgSeq.add(passInRecursion);
Pattern nextPattern = new Pattern(p.getLength()+1, edgSeq, p);
Pattern copyOfPattern = new Pattern(nextPattern);//push ...
pats.add(nextPattern);
//increment freq
//check max len pattern size is reached
//first recursion
//if less than k do recursions
if(copyOfPattern.getLength() < k)
growEdge(copyOfPattern, passInRecursion, k, pats2, st);
for(int i = 0; i < pats2.size(); i++)
{
Pattern p2 = pats2.get(i);
pats.add(pats2.get(i));
//Node curr = passInRecursion.getTargetNode();
//ArrayList<Node> currN = getChildrenSorted(curr);
//ArrayList
growEdge(p2, passInRecursion, k, pats, st); //grow also on pats2.get(i)
}
}
if(patterns.containsKey(p)){
Integer aVal = patterns.get(p);
int val = aVal.intValue() + 1;
aVal = new Integer(val);
patterns.put(p, aVal);
}
else{
Integer freq = new Integer(1);
patterns.put(p, freq);
}
}
//Print patterns in the list
public void printPatterns(){
for(int i = 0; i < patterns.size(); i++){
System.out.println(patterns.get(i));
}
}
//Print patterns in the list
public void printPatterns(ArrayList<Pattern> pats){
for(int i = 0; i < pats.size(); i++){
System.out.println(pats.get(i).toString());
}
}
//Calculates frequencies for all patterns
public double patternFreq(){
return 0.0;
}
//Returns length of given pattern
public double patternLen(ArrayList<Node> pattern){
return pattern.size();
}
//Calculate repetitive measure for each pattern in the list
public void repetitiveMeasure(){
}
//Returns frequency of given pattern
public int getFreqOfPattern(){
return -1;
}
//Returns true if a given node is in a repeating pattern
public boolean repeats(Node n){
return false;
}
public double averageRelevance(){
return 0.0;
}
/*
//
public void calculateRelevances(int k) {
whichOntology = CandidateConcept.ontology.source;
whichType = alignType.aligningClasses;
getPatternsGivenLength(sClasses, k);
int i = 0;
for( i = 0 ; i < patterns.size(); i++){
createCandidateList(patterns.get(i));
}
whichOntology = CandidateConcept.ontology.target;
getPatternsGivenLength(tClasses, k);
int j = 0;
for( j = i ; j < patterns.size(); j++){
createCandidateList(patterns.get(j));
}
whichOntology = CandidateConcept.ontology.source;
whichType = alignType.aligningProperties;
getPatternsGivenLength(sProps, k);
int m = 0;
for( m = j ; m < patterns.size(); m++){
createCandidateList(patterns.get(m));
}
whichOntology = CandidateConcept.ontology.target;
getPatternsGivenLength(tProps, k);
int n = 0;
for( n = m ; n < patterns.size(); n++){
createCandidateList(patterns.get(n));
}
}
*/
} |
package sstinc.prevoir;
import android.app.AlertDialog;
import android.app.ListFragment;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.util.Log;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.CheckBox;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
import static android.app.Activity.RESULT_OK;
public class TaskFragment extends ListFragment implements AdapterView.OnItemLongClickListener {
// Extra constants for intents
public static final String EXTRA_TASK = "sstinc.prevoir.EXTRA_TASK";
// Request codes for receiving and sending data
static final int createTaskRequestCode = 100;
static final int updateTaskRequestCode = 200;
// Boolean to show if menu shows duplicate and delete buttons
static boolean menu_multi = false;
AdapterView.OnItemClickListener editItemClickListener = new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int pos, long id) {
// Add edit view
Task task = (Task) getListAdapter().getItem(pos);
Intent intent = new Intent(getActivity(), TaskCreateActivity.class);
intent.putExtra(TaskFragment.EXTRA_TASK, task);
startActivityForResult(intent, updateTaskRequestCode);
}
};
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
// Set options menu
setHasOptionsMenu(true);
// Reset menu
menu_multi = false;
getActivity().invalidateOptionsMenu();
// Hide shuffle button
MainActivity.menu_shuffle = false;
getActivity().invalidateOptionsMenu();
// Set bottom padding
getListView().setClipToPadding(false);
float fab_margin = getResources().getDimension(R.dimen.fab_margin);
getListView().setPadding(0, 0, 0, (int) TypedValue.applyDimension(
TypedValue.COMPLEX_UNIT_SP, 56 + (fab_margin*2/3),
getActivity().getResources().getDisplayMetrics()));
// Get the tasks from database
DbAdapter dbAdapter = new DbAdapter(getActivity().getApplicationContext());
dbAdapter.open();
ArrayList<Task> tasks = dbAdapter.getTasks();
dbAdapter.close();
// Set Long Click Listener
getListView().setOnItemLongClickListener(this);
// Display the tasks from the database
setListAdapter(new TaskArrayAdapter(getActivity(), tasks));
// Floating Action Button for adding new tasks
FloatingActionButton fab = (FloatingActionButton) getActivity().findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(getActivity().getApplicationContext(),
TaskCreateActivity.class);
startActivityForResult(intent, createTaskRequestCode);
}
});
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == createTaskRequestCode) {
// Request code received after task creation
if (resultCode == RESULT_OK) {
// Get the new task from the activity
Task task = data.getParcelableExtra(EXTRA_TASK);
// Add task to database
DbAdapter dbAdapter = new DbAdapter(getActivity().getApplicationContext());
dbAdapter.open();
dbAdapter.insertTask(task);
ArrayList<Task> tasks = dbAdapter.getTasks();
dbAdapter.close();
// Reset the list adapter to show the new task
setListAdapter(new TaskArrayAdapter(getActivity(), tasks));
}
} else if (requestCode == updateTaskRequestCode) {
// Request code received after editing an existing task
if (resultCode == RESULT_OK) {
// Update to database and view again
// Get the edited task from the activity
Task task = data.getParcelableExtra(EXTRA_TASK);
// Update the task in the database
DbAdapter dbAdapter = new DbAdapter(getActivity().getApplicationContext());
dbAdapter.open();
dbAdapter.updateTask(task.getId(), task);
ArrayList<Task> tasks = dbAdapter.getTasks();
dbAdapter.close();
// Reset the list adapter to show the updated task
setListAdapter(new TaskArrayAdapter(getActivity(), tasks));
}
}
}
private int getCheckedCheckBoxes() {
int count = 0;
for (int i=getListAdapter().getCount()-1; i>=0; i
View view = getViewByPosition(i, getListView());
CheckBox checkBox = (CheckBox) view.findViewById(R.id.list_item_checkBox);
if (checkBox.isChecked()) {
count++;
}
}
return count;
}
private void hideCheckBoxes() {
for (int i=getListAdapter().getCount()-1; i>=0; i
View view = getViewByPosition(i, getListView());
// Make it invisible and uncheck
CheckBox checkBox = (CheckBox) view.findViewById(R.id.list_item_checkBox);
checkBox.setVisibility(View.GONE);
checkBox.setChecked(false);
}
}
public View getViewByPosition(int pos, ListView listView) {
final int firstListItemPosition = listView.getFirstVisiblePosition();
final int lastListItemPosition = firstListItemPosition + listView.getChildCount() - 1;
if (pos < firstListItemPosition || pos > lastListItemPosition ) {
return listView.getAdapter().getView(pos, null, listView);
} else {
final int childIndex = pos - firstListItemPosition;
return listView.getChildAt(childIndex);
}
}
@Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
// Iterate through each view
for (int i = getListAdapter().getCount()-1; i>=0; i
View v = getViewByPosition(i, getListView());
// Set checkBox to be visible
CheckBox checkBox = (CheckBox) v.findViewById(R.id.list_item_checkBox);
checkBox.setVisibility(View.VISIBLE);
// Set onClickListener for checkBoxes
checkBox.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (getCheckedCheckBoxes() == 0) {
hideCheckBoxes();
menu_multi = false;
getActivity().invalidateOptionsMenu();
}
}
});
// Set new onClickListener
getListView().setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View inner_view,
int position, long id) {
// Change it to check when clicked
// Get checkbox
CheckBox inner_view_checkBox = (CheckBox) inner_view.findViewById(
R.id.list_item_checkBox);
if (inner_view_checkBox.isChecked()) {
inner_view_checkBox.setChecked(false);
if (getCheckedCheckBoxes() == 0) {
hideCheckBoxes();
menu_multi = false;
getActivity().invalidateOptionsMenu();
// Return to normal OnItemClickListener
getListView().setOnItemClickListener(editItemClickListener);
}
} else {
inner_view_checkBox.setChecked(true);
}
}
});
}
// Reset Menu
menu_multi = true;
getActivity().invalidateOptionsMenu();
((CheckBox) view.findViewById(R.id.list_item_checkBox)).setChecked(true);
(view.findViewById(R.id.list_item_checkBox)).setVisibility(View.VISIBLE);
return true;
}
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
super.onCreateOptionsMenu(menu, inflater);
menu.findItem(R.id.nav_copy).setVisible(menu_multi);
menu.findItem(R.id.nav_delete).setVisible(menu_multi);
// Set onClickListeners
menu.findItem(R.id.nav_copy)
.setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
@Override
public boolean onMenuItemClick(MenuItem item) {
// Disable menu
menu_multi = false;
getActivity().invalidateOptionsMenu();
// Duplicate all the selected tasks
DbAdapter dbAdapter = new DbAdapter(getActivity());
dbAdapter.open();
for (int i=getListAdapter().getCount()-1; i>=0; i
// Get CheckBox
View view = getViewByPosition(i, getListView());
CheckBox checkBox = (CheckBox) view.findViewById(R.id.list_item_checkBox);
if (checkBox.isChecked()) {
dbAdapter.insertTask((Task) getListAdapter().getItem(i));
}
}
ArrayList<Task> tasks = dbAdapter.getTasks();
dbAdapter.close();
setListAdapter(new TaskArrayAdapter(getActivity(), tasks));
// Return to normal OnItemClickListener
getListView().setOnItemClickListener(editItemClickListener);
return false;
}
});
menu.findItem(R.id.nav_delete)
.setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
@Override
public boolean onMenuItemClick(MenuItem item) {
if (getCheckedCheckBoxes() == 1) {
// Disable menu
menu_multi = false;
getActivity().invalidateOptionsMenu();
// Delete immediately
DbAdapter dbAdapter = new DbAdapter(getActivity());
for (int i=getListAdapter().getCount()-1; i>=0; i
View view = getViewByPosition(i, getListView());
CheckBox checkBox = (CheckBox) view.findViewById(R.id.list_item_checkBox);
if (checkBox.isChecked()) {
dbAdapter.open();
dbAdapter.deleteTask(((Task) getListAdapter().getItem(i)).getId());
break;
}
}
ArrayList<Task> tasks = dbAdapter.getTasks();
dbAdapter.close();
setListAdapter(new TaskArrayAdapter(getActivity(), tasks));
// Return to normal OnItemClickListener
getListView().setOnItemClickListener(editItemClickListener);
dbAdapter.close();
return false;
}
// Confirm delete
new AlertDialog.Builder(getActivity())
.setTitle(R.string.dialog_confirm_delete_title)
.setMessage(R.string.dialog_confirm_delete_message)
.setPositiveButton(R.string.dialog_confirm_delete_positive,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// Disable menu
menu_multi = false;
getActivity().invalidateOptionsMenu();
// Duplicate all the selected tasks
DbAdapter dbAdapter = new DbAdapter(getActivity());
dbAdapter.open();
for (int i=getListAdapter().getCount()-1; i>=0; i
// Get CheckBox
View view = getViewByPosition(i, getListView());
CheckBox checkBox = (CheckBox) view.findViewById(
R.id.list_item_checkBox);
if (checkBox.isChecked()) {
dbAdapter.deleteTask(
((Task) getListAdapter().getItem(i)).getId());
}
}
ArrayList<Task> tasks = dbAdapter.getTasks();
dbAdapter.close();
setListAdapter(new TaskArrayAdapter(getActivity(), tasks));
// Return to normal OnItemClickListener
getListView().setOnItemClickListener(editItemClickListener);
}
})
.setNegativeButton(R.string.dialog_confirm_delete_negative,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
}
})
.show();
return false;
}
});
}
} |
package biomodel.gui;
import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.io.File;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.Scanner;
import java.util.Set;
import java.util.prefs.Preferences;
import javax.swing.JComboBox;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTabbedPane;
import javax.swing.JTextField;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import javax.swing.tree.TreeModel;
import main.Gui;
import main.Log;
import main.util.ExampleFileFilter;
import main.util.MutableBoolean;
import org.sbml.libsbml.ExternalModelDefinition;
import org.sbml.libsbml.InitialAssignment;
import org.sbml.libsbml.ListOf;
import org.sbml.libsbml.LocalParameter;
import org.sbml.libsbml.Model;
import org.sbml.libsbml.Parameter;
import org.sbml.libsbml.Reaction;
import org.sbml.libsbml.Rule;
import org.sbml.libsbml.SBMLDocument;
import org.sbml.libsbml.Species;
import org.sbml.libsbml.Submodel;
import org.sbolstandard.core.DnaComponent;
import org.sbolstandard.core.SBOLDocument;
import org.sbolstandard.core.SBOLFactory;
import analysis.ConstraintTermThread;
import analysis.AnalysisView;
import analysis.AnalysisThread;
import biomodel.annotation.AnnotationUtility;
import biomodel.annotation.SBOLAnnotation;
import biomodel.gui.movie.MovieContainer;
import biomodel.gui.movie.SchemeChooserPanel;
import biomodel.gui.schematic.Schematic;
import biomodel.gui.textualeditor.CompartmentTypes;
import biomodel.gui.textualeditor.Compartments;
import biomodel.gui.textualeditor.Constraints;
import biomodel.gui.textualeditor.ElementsPanel;
import biomodel.gui.textualeditor.Events;
import biomodel.gui.textualeditor.Functions;
import biomodel.gui.textualeditor.InitialAssignments;
import biomodel.gui.textualeditor.ModelPanel;
import biomodel.gui.textualeditor.MySpecies;
import biomodel.gui.textualeditor.Parameters;
import biomodel.gui.textualeditor.Reactions;
import biomodel.gui.textualeditor.Rules;
import biomodel.gui.textualeditor.SBMLutilities;
import biomodel.gui.textualeditor.SpeciesTypes;
import biomodel.gui.textualeditor.Units;
import biomodel.network.GeneticNetwork;
import biomodel.parser.BioModel;
import biomodel.parser.GCMParser;
import biomodel.util.GlobalConstants;
import biomodel.util.Utility;
import sbol.SBOLSynthesizer;
import sbol.SBOLUtility;
/**
* This is the GCM2SBMLEditor class. It takes in a gcm file and allows the user
* to edit it by changing different fields displayed in a frame. It also
* implements the ActionListener class, the MouseListener class, and the
* KeyListener class which allows it to perform certain actions when buttons are
* clicked on the frame, when one of the JList's items is double clicked, or
* when text is entered into the model's ID.
*
* @author Nam Nguyen
*/
public class ModelEditor extends JPanel implements ActionListener, MouseListener, ChangeListener {
private static final long serialVersionUID = 1L;
private String filename = "";
private String gcmname = "";
private BioModel biomodel = null;
private boolean paramsOnly;
private ArrayList<String> parameterChanges;
private ArrayList<String> getParams;
private String paramFile, refFile, simName;
private AnalysisView reb2sac;
private ElementsPanel elementsPanel;
private String separator;
private ModelPanel modelPanel;
private Schematic schematic;
private Compartments compartmentPanel;
private Functions functionPanel;
private MySpecies speciesPanel;
private Parameters parametersPanel;
private Reactions reactionPanel;
private Units unitPanel;
private Rules rulesPanel;
private Events eventPanel;
private Constraints consPanel;
public ModelEditor(String path) throws Exception {
this(path, null, null, null, false, null, null, null, false);
}
public ModelEditor(String path, String filename, Gui biosim, Log log, boolean paramsOnly,
String simName, String paramFile, AnalysisView reb2sac, boolean textBased) throws Exception {
super();
if (File.separator.equals("\\")) {
separator = "\\\\";
}
else {
separator = File.separator;
}
this.biosim = biosim;
this.log = log;
this.path = path;
this.paramsOnly = paramsOnly;
this.paramFile = paramFile;
this.simName = simName;
this.reb2sac = reb2sac;
this.textBased = textBased;
elementsPanel = null;
getParams = new ArrayList<String>();
if (paramFile != null) {
try {
Scanner scan = new Scanner(new File(paramFile));
if (scan.hasNextLine()) {
refFile = scan.nextLine();
getParams.add(refFile);
}
scan.close();
}
catch (Exception e) {
JOptionPane.showMessageDialog(Gui.frame, "Unable to read parameter file.", "Error",
JOptionPane.ERROR_MESSAGE);
refFile = "";
}
}
if (paramsOnly) {
parameterChanges = new ArrayList<String>();
filename = refFile;
}
biomodel = new BioModel(path);
if (filename != null) {
biomodel.load(path + separator + filename);
this.filename = filename;
this.gcmname = filename.replace(".gcm", "").replace(".xml", "");
}
else {
this.filename = "";
}
if (paramsOnly) {
loadParams();
}
buildGui();
}
public String getFilename() {
return filename;
}
public String getPath() {
return path;
}
public void reload(String newName) {
filename = newName + ".gcm";
gcmname = newName;
biomodel.load(path + separator + newName + ".gcm");
if (paramsOnly) {
/*
GCMFile refGCM = new GCMFile(path);
refGCM.load(path + separator + refFile);
HashMap<String, String> params = refGCM.getGlobalParameters();
for (String key : params.keySet()) {
gcm.setDefaultParameter(key, params.get(key));
}
*/
}
//GCMNameTextField.setText(newName);
}
public void renameComponents(String oldname, String newName) {
for (long i = 0; i < biomodel.getSBMLComp().getNumExternalModelDefinitions(); i++) {
ExternalModelDefinition extModel = biomodel.getSBMLComp().getExternalModelDefinition(i);
if (extModel.getId().equals(oldname)) {
extModel.setId(newName);
extModel.setSource("file://"+newName+".xml");
}
}
for (long i = 0; i < biomodel.getSBMLCompModel().getNumSubmodels(); i++) {
Submodel submodel = biomodel.getSBMLCompModel().getSubmodel(i);
if (submodel.getModelRef().equals(oldname)) {
submodel.setModelRef(newName);
}
}
ArrayList<String> comps = new ArrayList<String>();
for (long i = 0; i < biomodel.getSBMLCompModel().getNumSubmodels(); i++) {
Submodel submodel = biomodel.getSBMLCompModel().getSubmodel(i);
comps.add(submodel.getId() + " " + submodel.getModelRef() + " " + biomodel.getComponentPortMap(submodel.getId()));
}
components.removeAllItem();
components.addAllItem(comps);
schematic.getGraph().buildGraph();
}
public void refresh() {
refreshComponentsList();
reloadParameters();
if (paramsOnly) {
/*
GCMParser parser = new GCMParser(path + separator + refFile);
GeneticNetwork network = parser.buildNetwork();
GeneticNetwork.setRoot(path + separator);
network.mergeSBML(path + separator + simName + separator + gcmname + ".xml");
*/
//reb2sac.updateSpeciesList();
biomodel.reloadSBMLFile();
compartmentPanel.refreshCompartmentPanel(biomodel);
speciesPanel.refreshSpeciesPanel(biomodel);
parametersPanel.refreshParameterPanel(biomodel);
reactionPanel.refreshReactionPanel(biomodel);
} else {
compartmentPanel.refreshCompartmentPanel(biomodel);
parametersPanel.refreshParameterPanel(biomodel);
functionPanel.refreshFunctionsPanel();
unitPanel.refreshUnitsPanel();
rulesPanel.refreshRulesPanel();
consPanel.refreshConstraintsPanel();
eventPanel.refreshEventsPanel();
}
}
public String getGCMName() {
return gcmname;
}
public void mouseClicked(MouseEvent e) {
if (e.getClickCount() == 2) {
Object o = e.getSource();
if (o instanceof PropertyList) {
PropertyList list = (PropertyList) o;
new EditCommand("Edit " + list.getName(), list).run();
}
}
//System.err.println("reloading");
schematic.reloadGrid();
}
public void mouseEntered(MouseEvent e) {
}
public void mouseExited(MouseEvent e) {
}
public void mousePressed(MouseEvent e) {
}
public void mouseReleased(MouseEvent e) {
}
public boolean isDirty() {
return dirty.booleanValue();
}
public MutableBoolean getDirty() {
return dirty;
}
public boolean isParamsOnly() {
return paramsOnly;
}
public void setDirty(boolean dirty) {
this.dirty.setValue(dirty);
}
public BioModel getGCM() {
return biomodel;
}
public String getSBMLFile() {
return (String) sbmlFiles.getSelectedItem();
}
public HashSet<String> getSbolFiles() {
HashSet<String> filePaths = new HashSet<String>();
TreeModel tree = getGui().getFileTree().tree.getModel();
for (int i = 0; i < tree.getChildCount(tree.getRoot()); i++) {
String fileName = tree.getChild(tree.getRoot(), i).toString();
if (fileName.endsWith(".sbol"))
filePaths.add(getGui().getRoot() + File.separator + fileName);
}
return filePaths;
}
public void save(String command) {
//log.addText("save");
dirty.setValue(false);
speciesPanel.refreshSpeciesPanel(biomodel);
/*
if (!sbmlFiles.getSelectedItem().equals(none)) {
gcm.setSBMLFile(sbmlFiles.getSelectedItem().toString());
}
else {
gcm.setSBMLFile("");
}
*/
GeneticNetwork.setRoot(path + separator);
if (command.contains("GCM as")) {
String newName = JOptionPane.showInputDialog(Gui.frame, "Enter GCM name:", "GCM Name",
JOptionPane.PLAIN_MESSAGE);
if (newName == null) {
return;
}
if (newName.contains(".gcm")) {
newName = newName.replace(".gcm", "");
}
saveAs(newName);
return;
}
// Annotate SBML model with synthesized SBOL DNA component and save component to local SBOL file
saveSBOL();
// Write out species and influences to a gcm file
//gcm.getSBMLDocument().getModel().setName(modelPanel.getModelName());
biomodel.save(path + separator + gcmname + ".gcm");
//log.addText("Saving GCM file:\n" + path + separator + gcmname + ".gcm\n");
log.addText("Saving SBML file:\n" + path + separator + biomodel.getSBMLFile() + "\n");
if (command.contains("Check")) {
SBMLutilities.check(path + separator + biomodel.getSBMLFile());
}
if (command.contains("template")) {
GCMParser parser = new GCMParser(path + separator + gcmname + ".gcm");
try {
parser.buildTopLevelNetwork(null);
}
catch (IllegalStateException e) {
JOptionPane.showMessageDialog(Gui.frame, e.getMessage(), "Error",
JOptionPane.ERROR_MESSAGE);
return;
}
GeneticNetwork network = new GeneticNetwork();
String templateName = JOptionPane.showInputDialog(Gui.frame,
"Enter SBML template name:", "SBML Template Name", JOptionPane.PLAIN_MESSAGE);
if (templateName != null) {
if (!templateName.contains(".sbml") && !templateName.contains(".xml")) {
templateName = templateName + ".xml";
}
if (new File(path + separator + templateName).exists()) {
int value = JOptionPane.showOptionDialog(Gui.frame, templateName
+ " already exists. Overwrite file?", "Save file",
JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE, null, options,
options[0]);
if (value == JOptionPane.YES_OPTION) {
network.buildTemplate(parser.getSpecies(), parser.getPromoters(), gcmname
+ ".gcm", path + separator + templateName);
log.addText("Saving GCM file as SBML template:\n" + path + separator
+ templateName + "\n");
biosim.addToTree(templateName);
//biosim.updateOpenSBML(templateName);
}
else {
// Do nothing
}
}
else {
network.buildTemplate(parser.getSpecies(), parser.getPromoters(), gcmname
+ ".gcm", path + separator + templateName);
log.addText("Saving GCM file as SBML template:\n" + path + separator
+ templateName + "\n");
biosim.addToTree(templateName);
}
}
}
else if (command.contains("LHPN")) {
String lpnName = JOptionPane.showInputDialog(Gui.frame,
"Enter LPN name:", "LPN Name", JOptionPane.PLAIN_MESSAGE);
if (!lpnName.trim().contains(".lpn")) {
lpnName = lpnName.trim() + ".lpn";
}
if (new File(path + separator + lpnName).exists()) {
int value = JOptionPane.showOptionDialog(Gui.frame, lpnName
+ " already exists. Overwrite file?", "Save file", JOptionPane.YES_NO_OPTION,
JOptionPane.PLAIN_MESSAGE, null, options, options[0]);
if (value == JOptionPane.YES_OPTION) {
biomodel.createLogicalModel(path + separator + lpnName, log, biosim, lpnName);
}
else {
// Do nothing
}
}
else {
biomodel.createLogicalModel(path + separator + lpnName, log, biosim, lpnName);
}
}
else if (command.contains("SBML")) {
// Then read in the file with the GCMParser
GCMParser parser = new GCMParser(path + separator + gcmname + ".gcm");
GeneticNetwork network = null;
network = parser.buildNetwork();
if (network == null) return;
network.loadProperties(biomodel);
// Finally, output to a file
if (new File(path + separator + gcmname + ".xml").exists()) {
int value = JOptionPane.showOptionDialog(Gui.frame, gcmname
+ ".xml already exists. Overwrite file?", "Save file", JOptionPane.YES_NO_OPTION,
JOptionPane.PLAIN_MESSAGE, null, options, options[0]);
if (value == JOptionPane.YES_OPTION) {
network.mergeSBML(path + separator + gcmname + ".xml");
log.addText("Saving GCM file as SBML file:\n" + path + separator + gcmname + ".xml\n");
biosim.addToTree(gcmname + ".xml");
//biosim.updateOpenSBML(gcmname + ".xml");
}
else {
// Do nothing
}
}
else {
network.mergeSBML(path + separator + gcmname + ".xml");
log.addText("Saving GCM file as SBML file:\n" + path + separator + gcmname + ".xml\n");
biosim.addToTree(gcmname + ".xml");
}
}
biosim.updateViews(gcmname + ".gcm");
}
// Annotate SBML model with synthesized SBOL DNA component and save component to local SBOL file
public void saveSBOL() {
GCMParser parser = new GCMParser(biomodel, false);
SBOLSynthesizer synthesizer = parser.buildSbolSynthesizer();
Model sbmlModel = biomodel.getSBMLDocument().getModel();
LinkedList<String> sbolURIs = AnnotationUtility.parseSBOLAnnotation(sbmlModel);
if (synthesizer != null && synthesizer.loadSbolFiles(getSbolFiles())) {
synthesizer.setLocalPath(path);
DnaComponent synthComp = synthesizer.synthesizeDnaComponent();
if (synthComp != null) {
sbolURIs.clear();
sbolURIs.add(synthComp.getURI().toString());
}
}
if (sbolURIs.size() > 0) {
SBOLAnnotation sbolAnnot = new SBOLAnnotation(sbmlModel.getMetaId(), sbolURIs);
AnnotationUtility.setSBOLAnnotation(sbmlModel, sbolAnnot);
}
}
// Export SBOL DNA component to new SBOL file
public void exportSBOL() {
GCMParser parser = new GCMParser(biomodel, false);
SBOLSynthesizer synthesizer = parser.buildSbolSynthesizer();
if (synthesizer != null && synthesizer.loadSbolFiles(getSbolFiles())) {
File lastFilePath;
Preferences biosimrc = Preferences.userRoot();
if (biosimrc.get("biosim.general.export_dir", "").equals("")) {
lastFilePath = null;
}
else {
lastFilePath = new File(biosimrc.get("biosim.general.export_dir", ""));
}
int option;
String targetFilePath = "";
do {
option = JOptionPane.YES_OPTION;
targetFilePath = main.util.Utility.browse(Gui.frame, lastFilePath, null, JFileChooser.FILES_ONLY, "Export SBOL", -1);
if (!targetFilePath.equals("") && new File(targetFilePath).exists()) {
String targetFileId = targetFilePath.substring(targetFilePath.lastIndexOf(File.separator) + 1);
String[] options = { "Replace", "Cancel" };
option = JOptionPane.showOptionDialog(Gui.frame, "A file named " + targetFileId + " already exists. Do you want to replace it?",
"Export SBOL", JOptionPane.YES_NO_OPTION,
JOptionPane.PLAIN_MESSAGE, null, options, options[0]);
if (option != JOptionPane.YES_OPTION)
lastFilePath = new File(targetFilePath);
}
} while (option == JOptionPane.NO_OPTION);
if (!targetFilePath.equals("")) {
biosimrc.put("biosim.general.export_dir", targetFilePath);
DnaComponent synthComp = synthesizer.synthesizeDnaComponent();
if (synthComp != null) {
SBOLDocument sbolDoc = SBOLFactory.createDocument();
SBOLUtility.addDNAComponent(synthComp, sbolDoc);
SBOLUtility.exportSBOLDocument(targetFilePath, sbolDoc);
}
}
}
}
public void exportSBML() {
File lastFilePath;
Preferences biosimrc = Preferences.userRoot();
if (biosimrc.get("biosim.general.export_dir", "").equals("")) {
lastFilePath = null;
}
else {
lastFilePath = new File(biosimrc.get("biosim.general.export_dir", ""));
}
String exportPath = main.util.Utility.browse(Gui.frame, lastFilePath, null, JFileChooser.FILES_ONLY, "Export " + "SBML", -1);
if (!exportPath.equals("")) {
biosimrc.put("biosim.general.export_dir",exportPath);
biomodel.exportSingleFile(exportPath);
log.addText("Saving GCM file as SBML file:\n" + exportPath + "\n");
}
}
public void exportFlatSBML() {
File lastFilePath;
Preferences biosimrc = Preferences.userRoot();
if (biosimrc.get("biosim.general.export_dir", "").equals("")) {
lastFilePath = null;
}
else {
lastFilePath = new File(biosimrc.get("biosim.general.export_dir", ""));
}
String exportPath = main.util.Utility.browse(Gui.frame, lastFilePath, null, JFileChooser.FILES_ONLY, "Export " + "SBML", -1);
if (!exportPath.equals("")) {
biosimrc.put("biosim.general.export_dir",exportPath);
GCMParser parser = new GCMParser(path + separator + gcmname + ".xml");
GeneticNetwork network = null;
network = parser.buildNetwork();
if (network==null) return;
network.loadProperties(biomodel);
network.mergeSBML(exportPath);
log.addText("Saving GCM file as SBML file:\n" + exportPath + "\n");
}
}
public void saveAs(String newName) {
if (new File(path + separator + newName + ".xml").exists()) {
int value = JOptionPane.showOptionDialog(Gui.frame, newName
+ " already exists. Overwrite file?", "Save file", JOptionPane.YES_NO_OPTION,
JOptionPane.PLAIN_MESSAGE, null, options, options[0]);
if (value == JOptionPane.YES_OPTION) {
biomodel.save(path + separator + newName + ".gcm");
log.addText("Saving SBML file as:\n" + path + separator + newName + ".xml\n");
biosim.addToTree(newName + ".xml");
}
else {
// Do nothing
return;
}
}
else {
biomodel.save(path + separator + newName + ".gcm");
log.addText("Saving SBML file as:\n" + path + separator + newName + ".xml\n");
biosim.addToTree(newName + ".xml");
}
biosim.updateTabName(gcmname + ".xml", newName + ".xml");
reload(newName);
}
/**
* user selects a file; schematic is printed there as a JPG file
*/
public void saveSchematic() {
JFileChooser fc = new JFileChooser("Save Schematic");
fc.setFileSelectionMode(JFileChooser.FILES_ONLY);
ExampleFileFilter jpgFilter = new ExampleFileFilter();
jpgFilter.addExtension("jpg");
jpgFilter.setDescription("Image Files");
fc.addChoosableFileFilter(jpgFilter);
fc.setAcceptAllFileFilterUsed(false);
fc.setFileFilter(jpgFilter);
int returnVal = fc.showDialog(Gui.frame, "Save Schematic");
if (returnVal == JFileChooser.APPROVE_OPTION) {
File file = fc.getSelectedFile();
schematic.outputFrame(file.getAbsoluteFile().toString(), false);
}
}
private void sweepHelper(ArrayList<ArrayList<Double>> sweep, String s) {
double[] start = {0, 0};
double[] stop = {0, 0};
double[] step = {0, 0};
String temp = (s.split(" ")[s.split(" ").length - 1]).split(",")[0].substring(1).trim();
String[] tempSlash = temp.split("/");
start[0] = Double.parseDouble(tempSlash[0]);
if (tempSlash.length == 2)
start[1] = Double.parseDouble(tempSlash[1]);
temp = (s.split(" ")[s.split(" ").length - 1]).split(",")[1].trim();
tempSlash = temp.split("/");
stop[0] = Double.parseDouble(tempSlash[0]);
if (tempSlash.length == 2)
stop[1] = Double.parseDouble(tempSlash[1]);
temp = (s.split(" ")[s.split(" ").length - 1]).split(",")[2].trim();
tempSlash = temp.split("/");
step[0] = Double.parseDouble(tempSlash[0]);
if (tempSlash.length == 2)
step[1] = Double.parseDouble(tempSlash[1]);
ArrayList<Double> kf = new ArrayList<Double>();
ArrayList<Double> kr = new ArrayList<Double>();
kf.add(start[0]);
kr.add(start[1]);
while (step[0] != 0 || step[1] != 0) {
if (start[0] + step[0] > stop[0])
step[0] = 0;
if (start[1] + step[1] > stop[1])
step[1] = 0;
if (step[0] != 0 || step[1] != 0) {
start[0] += step[0];
start[1] += step[1];
kf.add(start[0]);
kr.add(start[1]);
}
}
ArrayList<Double> Keq = new ArrayList<Double>();
for (int i = 0; i < kf.size(); i++) {
if (kr.get(i) != 0) {
if (!Keq.contains(kf.get(i)/kr.get(i)))
Keq.add(kf.get(i)/kr.get(i));
} else if (!Keq.contains(kf.get(i)))
Keq.add(kf.get(i));
}
sweep.add(Keq);
}
public void saveParams(boolean run, String stem, boolean ignoreSweep) {
try {
FileOutputStream out = new FileOutputStream(new File(paramFile));
out.write((refFile + "\n").getBytes());
for (String s : parameterChanges) {
if (!s.trim().equals("")) {
out.write((s + "\n").getBytes());
}
}
out.write(("\n").getBytes());
if (elementsPanel != null) {
for (String s : elementsPanel.getElementChanges()) {
out.write((s + "\n").getBytes());
}
}
out.close();
}
catch (Exception e1) {
JOptionPane.showMessageDialog(Gui.frame, "Unable to save parameter file.", "Error Saving File", JOptionPane.ERROR_MESSAGE);
}
if (run) {
ArrayList<String> sweepThese1 = new ArrayList<String>();
ArrayList<ArrayList<Double>> sweep1 = new ArrayList<ArrayList<Double>>();
ArrayList<String> sweepThese2 = new ArrayList<String>();
ArrayList<ArrayList<Double>> sweep2 = new ArrayList<ArrayList<Double>>();
for (String s : parameterChanges) {
if (s.split(" ")[s.split(" ").length - 1].startsWith("(")) {
if ((s.split(" ")[s.split(" ").length - 1]).split(",")[3].replace(")", "").trim().equals("1")) {
sweepThese1.add(s.substring(0, s.lastIndexOf(" ")));
sweepHelper(sweep1, s);
}
else {
sweepThese2.add(s.substring(0, s.lastIndexOf(" ")));
sweepHelper(sweep2, s);
}
}
}
if (sweepThese1.size() == 0 && (sweepThese2.size() > 0)) {
sweepThese1 = sweepThese2;
sweepThese2 = new ArrayList<String>();
sweep1 = sweep2;
sweep2 = new ArrayList<ArrayList<Double>>();
}
if (sweepThese1.size() > 0) {
ArrayList<AnalysisThread> threads = new ArrayList<AnalysisThread>();
ArrayList<String> dirs = new ArrayList<String>();
ArrayList<String> levelOne = new ArrayList<String>();
int max = 0;
for (ArrayList<Double> d : sweep1) {
max = Math.max(max, d.size());
}
for (int j = 0; j < max; j++) {
String sweep = "";
for (int i = 0; i < sweepThese1.size(); i++) {
int k = j;
if (k >= sweep1.get(i).size()) {
k = sweep1.get(i).size() - 1;
}
if (sweep.equals("")) {
sweep += sweepThese1.get(i) + "=" + sweep1.get(i).get(k);
}
else {
sweep += "_" + sweepThese1.get(i) + "=" + sweep1.get(i).get(k);
}
}
if (sweepThese2.size() > 0) {
int max2 = 0;
for (ArrayList<Double> d : sweep2) {
max2 = Math.max(max2, d.size());
}
for (int l = 0; l < max2; l++) {
String sweepTwo = sweep;
for (int i = 0; i < sweepThese2.size(); i++) {
int k = l;
if (k >= sweep2.get(i).size()) {
k = sweep2.get(i).size() - 1;
}
if (sweepTwo.equals("")) {
sweepTwo += sweepThese2.get(i) + "=" + sweep2.get(i).get(k);
}
else {
sweepTwo += "_" + sweepThese2.get(i) + "=" + sweep2.get(i).get(k);
}
}
new File(path
+ separator
+ simName
+ separator
+ stem
+ sweepTwo.replace("/", "-").replace("-> ", "").replace("+> ", "").replace("-| ", "").replace("x> ", "")
.replace("\"", "").replace(" ", "_").replace(",", "")).mkdir();
createSBML(stem, sweepTwo);
AnalysisThread thread = new AnalysisThread(reb2sac);
thread.start(
stem
+ sweepTwo.replace("/", "-").replace("-> ", "").replace("+> ", "").replace("-| ", "").replace("x> ", "")
.replace("\"", "").replace(" ", "_").replace(",", ""), false);
threads.add(thread);
dirs.add(sweepTwo.replace("/", "-").replace("-> ", "").replace("+> ", "").replace("-| ", "").replace("x> ", "")
.replace("\"", "").replace(" ", "_").replace(",", ""));
reb2sac.emptyFrames();
if (ignoreSweep) {
l = max2;
j = max;
}
}
}
else {
new File(path
+ separator
+ simName
+ separator
+ stem
+ sweep.replace("/", "-").replace("-> ", "").replace("+> ", "").replace("-| ", "").replace("x> ", "")
.replace("\"", "").replace(" ", "_").replace(",", "")).mkdir();
createSBML(stem, sweep);
AnalysisThread thread = new AnalysisThread(reb2sac);
thread.start(
stem
+ sweep.replace("/", "-").replace("-> ", "").replace("+> ", "").replace("-| ", "").replace("x> ", "")
.replace("\"", "").replace(" ", "_").replace(",", ""), false);
threads.add(thread);
dirs.add(sweep.replace("/", "-").replace("-> ", "").replace("+> ", "").replace("-| ", "").replace("x> ", "")
.replace("\"", "").replace(" ", "_").replace(",", ""));
reb2sac.emptyFrames();
if (ignoreSweep) {
j = max;
}
}
levelOne.add(sweep.replace("/", "-").replace("-> ", "").replace("+> ", "").replace("-| ", "").replace("x> ", "")
.replace("\"", "").replace(" ", "_").replace(",", ""));
}
new ConstraintTermThread(reb2sac).start(threads, dirs, levelOne, stem);
}
else {
if (!stem.equals("")) {
new File(path + separator + simName + separator + stem).mkdir();
}
createSBML(stem, ".");
if (!stem.equals("")) {
new AnalysisThread(reb2sac).start(stem, true);
}
else {
new AnalysisThread(reb2sac).start(".", true);
}
reb2sac.emptyFrames();
}
}
}
public void loadParams() {
if (paramsOnly) {
getParams = new ArrayList<String>();
try {
Scanner scan = new Scanner(new File(paramFile));
if (scan.hasNextLine()) {
scan.nextLine();
}
while (scan.hasNextLine()) {
String s = scan.nextLine();
if (!s.trim().equals("")) {
boolean added = false;
for (int i = 0; i < getParams.size(); i ++) {
if (getParams.get(i).substring(0,getParams.get(i).lastIndexOf(" ")).equals(s.substring(0, s.lastIndexOf(" ")))) {
getParams.set(i, s);
added = true;
}
}
if (!added) {
getParams.add(s);
}
}
else {
break;
}
}
scan.close();
}
catch (Exception e) {
}
for (String update : getParams) {
String id;
if (update.contains("/")) {
id = update.split("/")[0];
id = id.replace("\"", "");
String prop = update.split("/")[1].substring(0, update.split("/")[1].indexOf(" ")).trim();
String value = update.split(" ")[update.split(" ").length - 1].trim();
if (prop.equals(GlobalConstants.INITIAL_STRING)) {
Species species = biomodel.getSBMLDocument().getModel().getSpecies(id);
if (species!=null) {
if (value.startsWith("(")) {
species.appendAnnotation(","+GlobalConstants.INITIAL_STRING + "=" + value);
} else {
if (value.startsWith("[")) {
species.setInitialConcentration(Double.parseDouble(value.substring(1,value.length()-1)));
} else {
species.setInitialAmount(Double.parseDouble(value));
}
}
}
} else if (prop.equals(GlobalConstants.KDECAY_STRING)) {
Reaction reaction = biomodel.getSBMLDocument().getModel().getReaction("Degradation_"+id);
if (reaction != null) {
LocalParameter kd = reaction.getKineticLaw().getLocalParameter(GlobalConstants.KDECAY_STRING);
if (kd == null) {
kd = reaction.getKineticLaw().createLocalParameter();
kd.setId(GlobalConstants.KDECAY_STRING);
}
if (value.startsWith("(")) {
kd.setAnnotation(GlobalConstants.KDECAY_STRING + "=" + value);
} else {
kd.setValue(Double.parseDouble(value));
}
}
} else if (prop.equals(GlobalConstants.KCOMPLEX_STRING)) {
Reaction reaction = biomodel.getComplexReaction(id);
if (reaction != null) {
LocalParameter kc_f = reaction.getKineticLaw().getLocalParameter(GlobalConstants.FORWARD_KCOMPLEX_STRING);
if (kc_f == null) {
kc_f = reaction.getKineticLaw().createLocalParameter();
kc_f.setId(GlobalConstants.FORWARD_KCOMPLEX_STRING);
}
LocalParameter kc_r = reaction.getKineticLaw().getLocalParameter(GlobalConstants.REVERSE_KCOMPLEX_STRING);
if (kc_r == null) {
kc_r = reaction.getKineticLaw().createLocalParameter();
kc_r.setId(GlobalConstants.REVERSE_KCOMPLEX_STRING);
}
if (value.startsWith("(")) {
kc_f.setAnnotation(GlobalConstants.FORWARD_KCOMPLEX_STRING + "=" + value);
} else {
double [] Kc = Utility.getEquilibrium(value);
kc_f.setValue(Kc[0]);
kc_r.setValue(Kc[1]);
}
}
} else if (prop.equals(GlobalConstants.MEMDIFF_STRING)) {
Reaction reaction = biomodel.getSBMLDocument().getModel().getReaction("MembraneDiffusion_"+id);
if (reaction != null) {
LocalParameter kmdiff_f = reaction.getKineticLaw().getLocalParameter(GlobalConstants.FORWARD_MEMDIFF_STRING);
if (kmdiff_f == null) {
kmdiff_f = reaction.getKineticLaw().createLocalParameter();
kmdiff_f.setId(GlobalConstants.FORWARD_MEMDIFF_STRING);
}
LocalParameter kmdiff_r = reaction.getKineticLaw().getLocalParameter(GlobalConstants.REVERSE_MEMDIFF_STRING);
if (kmdiff_r == null) {
kmdiff_r = reaction.getKineticLaw().createLocalParameter();
kmdiff_r.setId(GlobalConstants.REVERSE_MEMDIFF_STRING);
}
if (value.startsWith("(")) {
kmdiff_f.setAnnotation(GlobalConstants.FORWARD_MEMDIFF_STRING + "=" + value);
} else {
double [] Kmdiff = Utility.getEquilibrium(value);
kmdiff_f.setValue(Kmdiff[0]);
kmdiff_r.setValue(Kmdiff[1]);
}
}
} else if (prop.equals(GlobalConstants.PROMOTER_COUNT_STRING)) {
Species species = biomodel.getSBMLDocument().getModel().getSpecies(id);
if (species!=null) {
if (value.startsWith("(")) {
species.appendAnnotation(","+GlobalConstants.PROMOTER_COUNT_STRING + "=" + value);
} else {
species.setInitialAmount(Double.parseDouble(value));
}
}
} else if (prop.equals(GlobalConstants.RNAP_BINDING_STRING)) {
Reaction reaction = biomodel.getProductionReaction(id);
if (reaction != null) {
LocalParameter ko_f = reaction.getKineticLaw().getLocalParameter(GlobalConstants.FORWARD_RNAP_BINDING_STRING);
if (ko_f == null) {
ko_f = reaction.getKineticLaw().createLocalParameter();
ko_f.setId(GlobalConstants.FORWARD_RNAP_BINDING_STRING);
}
LocalParameter ko_r = reaction.getKineticLaw().getLocalParameter(GlobalConstants.REVERSE_RNAP_BINDING_STRING);
if (ko_r == null) {
ko_r = reaction.getKineticLaw().createLocalParameter();
ko_r.setId(GlobalConstants.REVERSE_RNAP_BINDING_STRING);
}
if (value.startsWith("(")) {
ko_f.setAnnotation(GlobalConstants.FORWARD_RNAP_BINDING_STRING + "=" + value);
} else {
double [] Ko = Utility.getEquilibrium(value);
ko_f.setValue(Ko[0]);
ko_r.setValue(Ko[1]);
}
}
} else if (prop.equals(GlobalConstants.ACTIVATED_RNAP_BINDING_STRING)) {
Reaction reaction = biomodel.getProductionReaction(id);
if (reaction != null) {
LocalParameter kao_f = reaction.getKineticLaw().getLocalParameter(GlobalConstants.FORWARD_ACTIVATED_RNAP_BINDING_STRING);
if (kao_f == null) {
kao_f = reaction.getKineticLaw().createLocalParameter();
kao_f.setId(GlobalConstants.FORWARD_ACTIVATED_RNAP_BINDING_STRING);
}
LocalParameter kao_r = reaction.getKineticLaw().getLocalParameter(GlobalConstants.REVERSE_ACTIVATED_RNAP_BINDING_STRING);
if (kao_r == null) {
kao_r = reaction.getKineticLaw().createLocalParameter();
kao_r.setId(GlobalConstants.REVERSE_ACTIVATED_RNAP_BINDING_STRING);
}
if (value.startsWith("(")) {
kao_f.setAnnotation(GlobalConstants.FORWARD_ACTIVATED_RNAP_BINDING_STRING + "=" + value);
} else {
double [] Kao = Utility.getEquilibrium(value);
kao_f.setValue(Kao[0]);
kao_r.setValue(Kao[1]);
}
}
} else if (prop.equals(GlobalConstants.OCR_STRING)) {
Reaction reaction = biomodel.getProductionReaction(id);
if (reaction != null) {
LocalParameter ko = reaction.getKineticLaw().getLocalParameter(GlobalConstants.OCR_STRING);
if (ko == null) {
ko = reaction.getKineticLaw().createLocalParameter();
ko.setId(GlobalConstants.OCR_STRING);
}
if (value.startsWith("(")) {
ko.setAnnotation(GlobalConstants.OCR_STRING + "=" + value);
} else {
ko.setValue(Double.parseDouble(value));
}
}
} else if (prop.equals(GlobalConstants.KBASAL_STRING)) {
Reaction reaction = biomodel.getProductionReaction(id);
if (reaction != null) {
LocalParameter kb = reaction.getKineticLaw().getLocalParameter(GlobalConstants.KBASAL_STRING);
if (kb == null) {
kb = reaction.getKineticLaw().createLocalParameter();
kb.setId(GlobalConstants.KBASAL_STRING);
}
if (value.startsWith("(")) {
kb.setAnnotation(GlobalConstants.KBASAL_STRING + "=" + value);
} else {
kb.setValue(Double.parseDouble(value));
}
}
} else if (prop.equals(GlobalConstants.ACTIVATED_STRING)) {
Reaction reaction = biomodel.getProductionReaction(id);
if (reaction != null) {
LocalParameter ka = reaction.getKineticLaw().getLocalParameter(GlobalConstants.ACTIVATED_STRING);
if (ka == null) {
ka = reaction.getKineticLaw().createLocalParameter();
ka.setId(GlobalConstants.ACTIVATED_STRING);
}
if (value.startsWith("(")) {
ka.setAnnotation(GlobalConstants.ACTIVATED_STRING + "=" + value);
} else {
ka.setValue(Double.parseDouble(value));
}
}
} else if (prop.equals(GlobalConstants.STOICHIOMETRY_STRING)) {
Reaction reaction = biomodel.getProductionReaction(id);
if (reaction != null) {
LocalParameter np = reaction.getKineticLaw().getLocalParameter(GlobalConstants.STOICHIOMETRY_STRING);
if (np == null) {
np = reaction.getKineticLaw().createLocalParameter();
np.setId(GlobalConstants.STOICHIOMETRY_STRING);
}
if (value.startsWith("(")) {
np.setAnnotation(GlobalConstants.STOICHIOMETRY_STRING + "=" + value);
} else {
np.setValue(Double.parseDouble(value));
}
for (int i = 0; i<reaction.getNumProducts(); i++) {
if (value.startsWith("(")) {
reaction.getProduct(i).setStoichiometry(1.0);
} else {
reaction.getProduct(i).setStoichiometry(Double.parseDouble(value));
}
}
}
} else if (prop.equals(GlobalConstants.COOPERATIVITY_STRING)) {
String promoterId = null;
String sourceId = null;
String complexId = null;
if (id.contains(",")) {
promoterId = id.substring(id.indexOf(",")+1);
} else {
if (id.contains("|"))
promoterId = id.substring(id.indexOf("|")+1);
else
promoterId = id.substring(id.indexOf(">")+1);
}
if (id.contains("-")) {
sourceId = id.substring(0,id.indexOf("-"));
} else {
sourceId = id.substring(0,id.indexOf("+"));
complexId = id.substring(id.indexOf(">")+1);
}
Reaction reaction = null;
if (complexId==null) {
reaction = biomodel.getProductionReaction(promoterId);
if (reaction != null) {
LocalParameter nc = null;
if (id.contains("|")) {
nc = reaction.getKineticLaw()
.getLocalParameter(GlobalConstants.COOPERATIVITY_STRING + "_" + sourceId + "_r");
if (nc == null) {
nc = reaction.getKineticLaw().createLocalParameter();
nc.setId(GlobalConstants.COOPERATIVITY_STRING + "_" + sourceId + "_r");
}
} else {
nc = reaction.getKineticLaw()
.getLocalParameter(GlobalConstants.COOPERATIVITY_STRING + "_" + sourceId + "_a");
if (nc == null) {
nc = reaction.getKineticLaw().createLocalParameter();
nc.setId(GlobalConstants.COOPERATIVITY_STRING + "_" + sourceId + "_a");
}
}
if (value.startsWith("(")) {
nc.setAnnotation(GlobalConstants.COOPERATIVITY_STRING + "=" + value);
} else {
nc.setValue(Double.parseDouble(value));
}
}
} else {
reaction = biomodel.getComplexReaction(complexId);
if (reaction != null) {
LocalParameter nc = null;
nc = reaction.getKineticLaw().getLocalParameter(GlobalConstants.COOPERATIVITY_STRING + "_" + sourceId);
if (nc == null) {
nc = reaction.getKineticLaw().createLocalParameter();
nc.setId(GlobalConstants.COOPERATIVITY_STRING + "_" + sourceId);
}
if (value.startsWith("(")) {
nc.setAnnotation(GlobalConstants.COOPERATIVITY_STRING + "=" + value);
} else {
nc.setValue(Double.parseDouble(value));
}
}
}
} else if (prop.equals(GlobalConstants.KACT_STRING)) {
String promoterId = null;
String sourceId = null;
if (id.contains(",")) {
promoterId = id.substring(id.indexOf(",")+1);
} else {
promoterId = id.substring(id.indexOf(">")+1);
}
sourceId = id.substring(0,id.indexOf("-"));
Reaction reaction = null;
reaction = biomodel.getProductionReaction(promoterId);
if (reaction != null) {
LocalParameter ka_f = reaction.getKineticLaw()
.getLocalParameter(GlobalConstants.FORWARD_KACT_STRING.replace("_","_" + sourceId + "_"));
if (ka_f == null) {
ka_f = reaction.getKineticLaw().createLocalParameter();
ka_f.setId(GlobalConstants.FORWARD_KACT_STRING.replace("_","_" + sourceId + "_"));
}
LocalParameter ka_r = reaction.getKineticLaw()
.getLocalParameter(GlobalConstants.REVERSE_KACT_STRING.replace("_","_" + sourceId + "_"));
if (ka_r == null) {
ka_r = reaction.getKineticLaw().createLocalParameter();
ka_r.setId(GlobalConstants.REVERSE_KACT_STRING.replace("_","_" + sourceId + "_"));
}
if (value.startsWith("(")) {
ka_f.setAnnotation(GlobalConstants.FORWARD_KACT_STRING + "=" + value);
} else {
double [] Ka = Utility.getEquilibrium(value);
ka_f.setValue(Ka[0]);
ka_r.setValue(Ka[1]);
}
}
} else if (prop.equals(GlobalConstants.KREP_STRING)) {
String promoterId = null;
String sourceId = null;
if (id.contains(",")) {
promoterId = id.substring(id.indexOf(",")+1);
} else {
promoterId = id.substring(id.indexOf("|")+1);
}
sourceId = id.substring(0,id.indexOf("-"));
Reaction reaction = null;
reaction = biomodel.getProductionReaction(promoterId);
if (reaction != null) {
LocalParameter kr_f = reaction.getKineticLaw()
.getLocalParameter(GlobalConstants.FORWARD_KREP_STRING.replace("_","_" + sourceId + "_"));
if (kr_f == null) {
kr_f = reaction.getKineticLaw().createLocalParameter();
kr_f.setId(GlobalConstants.FORWARD_KREP_STRING.replace("_","_" + sourceId + "_"));
}
LocalParameter kr_r = reaction.getKineticLaw()
.getLocalParameter(GlobalConstants.REVERSE_KREP_STRING.replace("_","_" + sourceId + "_"));
if (kr_r == null) {
kr_r = reaction.getKineticLaw().createLocalParameter();
kr_r.setId(GlobalConstants.REVERSE_KREP_STRING.replace("_","_" + sourceId + "_"));
}
if (value.startsWith("(")) {
kr_f.setAnnotation(GlobalConstants.FORWARD_KREP_STRING + "=" + value);
} else {
double [] Kr = Utility.getEquilibrium(value);
kr_f.setValue(Kr[0]);
kr_r.setValue(Kr[1]);
}
}
}
}
else {
String [] splits = update.split(" ");
id = splits[0];
String value = splits[1].trim();
if (splits[splits.length - 2].equals("Sweep")) {
biomodel.setParameter(id, value, splits[splits.length-1]);
} else {
biomodel.setParameter(id, value, null);
}
}
}
}
}
public void createSBML(String stem, String direct) {
try {
ArrayList<String> dd = new ArrayList<String>();
if (!direct.equals(".")) {
String[] d = direct.split("_");
for (int i = 0; i < d.length; i++) {
if (!d[i].contains("=")) {
String di = d[i];
while (!d[i].contains("=")) {
i++;
di += "_" + d[i];
}
dd.add(di);
}
else {
dd.add(d[i]);
}
}
for (String di : dd) {
if (di.contains("/")) {
// TODO: REMOVED LIKELY CAUSE PROBLEM WITH PARAMS
/*
if (gcm.getPromoters().containsKey(di.split("=")[0].split("/")[0])) {
Properties promoterProps = gcm.getPromoters().get(di.split("=")[0].split("/")[0]);
promoterProps.put(di.split("=")[0].split("/")[1],
di.split("=")[1]);
}
if (gcm.getSpecies().contains(di.split("=")[0].split("/")[0])) {
Properties speciesProps = gcm.getSpecies().get(di.split("=")[0].split("/")[0]);
speciesProps.put(di.split("=")[0].split("/")[1],
di.split("=")[1]);
}
if (gcm.getInfluences().containsKey(di.split("=")[0].split("/")[0].replace("\"", ""))) {
Properties influenceProps = gcm.getInfluences().get(
di.split("=")[0].split("/")[0].replace("\"", ""));
influenceProps.put(di.split("=")[0].split("/")[1]
.replace("\"", ""), di.split("=")[1]);
}
*/
}
else {
/*
if (gcm.getGlobalParameters().containsKey(di.split("=")[0])) {
gcm.getGlobalParameters().put(di.split("=")[0], di.split("=")[1]);
}
if (gcm.getParameters().containsKey(di.split("=")[0])) {
gcm.getParameters().put(di.split("=")[0], di.split("=")[1]);
}
*/
}
}
}
direct = direct.replace("/", "-").replace("-> ", "").replace("+> ", "").replace("-| ", "").replace("x> ", "").replace("\"", "").replace(" ", "_").replace(",", "");
if (direct.equals(".") && !stem.equals("")) {
direct = "";
}
GCMParser parser = new GCMParser(biomodel, false);
GeneticNetwork network = null;
network = parser.buildNetwork();
if (network==null) return;
if (reb2sac != null)
network.loadProperties(biomodel, reb2sac.getGcmAbstractions(), reb2sac.getInterestingSpecies(), reb2sac.getProperty());
else
network.loadProperties(biomodel);
SBMLDocument d = network.getSBML();
for (String s : elementsPanel.getElementChanges()) {
for (long i = d.getModel().getNumInitialAssignments() - 1; i >= 0; i
if (s.contains("=")) {
String formula = SBMLutilities.myFormulaToString(((InitialAssignment) d.getModel()
.getListOfInitialAssignments().get(i)).getMath());
String sFormula = s.substring(s.indexOf('=') + 1).trim();
sFormula = SBMLutilities.myFormulaToString(SBMLutilities.myParseFormula(sFormula));
sFormula = s.substring(0, s.indexOf('=') + 1) + " " + sFormula;
if ((((InitialAssignment) d.getModel().getListOfInitialAssignments().get(i))
.getSymbol()
+ " = " + formula).equals(sFormula)) {
d.getModel().getListOfInitialAssignments().remove(i);
}
}
}
for (long i = d.getModel().getNumConstraints() - 1; i >= 0; i
if (d.getModel().getListOfConstraints().get(i).getMetaId().equals(s)) {
d.getModel().getListOfConstraints().remove(i);
}
}
for (long i = d.getModel().getNumEvents() - 1; i >= 0; i
if (d.getModel().getListOfEvents().get(i).getId().equals(s)) {
d.getModel().getListOfEvents().remove(i);
}
}
for (long i = d.getModel().getNumRules() - 1; i >= 0; i
if (s.contains("=")) {
String formula = SBMLutilities.myFormulaToString(((Rule) d.getModel().getListOfRules().get(i)).getMath());
String sFormula = s.substring(s.indexOf('=') + 1).trim();
sFormula = SBMLutilities.myFormulaToString(SBMLutilities.myParseFormula(sFormula));
sFormula = s.substring(0, s.indexOf('=') + 1) + " " + sFormula;
if ((((Rule) d.getModel().getListOfRules().get(i)).getVariable() + " = " + formula).equals(sFormula)) {
d.getModel().getListOfRules().remove(i);
}
}
}
}
for (int i = 0; i < d.getModel().getNumCompartments(); i++) {
for (String change : parameterChanges) {
if (change.split(" ")[0].equals(d.getModel().getCompartment(i).getId())) {
String[] splits = change.split(" ");
if (splits[splits.length - 2].equals("Modified") || splits[splits.length - 2].equals("Custom")) {
String value = splits[splits.length - 1];
d.getModel().getCompartment(i).setSize(Double.parseDouble(value));
}
}
}
for (String di : dd) {
if (di.split("=")[0].split(" ")[0].equals(d.getModel().getCompartment(i).getId())) {
String value = di.split("=")[1];
d.getModel().getCompartment(i).setSize(Double.parseDouble(value));
}
}
}
for (int i = 0; i < d.getModel().getNumSpecies(); i++) {
for (String change : parameterChanges) {
if (change.split(" ")[0].equals(d.getModel().getSpecies(i).getId())) {
String[] splits = change.split(" ");
if (splits[splits.length - 2].equals("Modified") || splits[splits.length - 2].equals("Custom")) {
String value = splits[splits.length - 1];
if (d.getModel().getSpecies(i).isSetInitialAmount()) {
d.getModel().getSpecies(i).setInitialAmount(Double.parseDouble(value));
}
else {
d.getModel().getSpecies(i).setInitialConcentration(Double.parseDouble(value));
}
}
}
}
for (String di : dd) {
if (di.split("=")[0].split(" ")[0].equals(d.getModel().getSpecies(i).getId())) {
String value = di.split("=")[1];
if (d.getModel().getSpecies(i).isSetInitialAmount()) {
d.getModel().getSpecies(i).setInitialAmount(Double.parseDouble(value));
}
else {
d.getModel().getSpecies(i).setInitialConcentration(Double.parseDouble(value));
}
}
}
}
for (int i = 0; i < d.getModel().getNumParameters(); i++) {
for (String change : parameterChanges) {
if (change.split(" ")[0].equals(d.getModel().getParameter(i).getId())) {
String[] splits = change.split(" ");
if (splits[splits.length - 2].equals("Modified") || splits[splits.length - 2].equals("Custom")) {
String value = splits[splits.length - 1];
d.getModel().getParameter(i).setValue(Double.parseDouble(value));
}
}
}
for (String di : dd) {
if (di.split("=")[0].split(" ")[0].equals(d.getModel().getParameter(i).getId())) {
String value = di.split("=")[1];
d.getModel().getParameter(i).setValue(Double.parseDouble(value));
}
}
}
for (int i = 0; i < d.getModel().getNumReactions(); i++) {
Reaction reaction = d.getModel().getReaction(i);
ListOf parameters = reaction.getKineticLaw().getListOfParameters();
for (int j = 0; j < reaction.getKineticLaw().getNumParameters(); j++) {
Parameter paramet = ((Parameter) (parameters.get(j)));
for (String change : parameterChanges) {
if (change.split(" ")[0].equals(reaction.getId() + "/" + paramet.getId())) {
String[] splits = change.split(" ");
if (splits[splits.length - 2].equals("Modified") || splits[splits.length - 2].equals("Custom")) {
String value = splits[splits.length - 1];
paramet.setValue(Double.parseDouble(value));
}
}
}
for (String di : dd) {
if (di.split("=")[0].split(" ")[0].equals(reaction.getId() + "/" + paramet.getId())) {
String value = di.split("=")[1];
paramet.setValue(Double.parseDouble(value));
}
}
}
}
network.markAbstractable();
network.mergeSBML(path + separator + simName + separator + stem + direct + separator + gcmname + ".xml", d);
}
catch (Exception e1) {
JOptionPane.showMessageDialog(Gui.frame, "Unable to create sbml file.",
"Error Creating File", JOptionPane.ERROR_MESSAGE);
e1.printStackTrace();
}
}
public String getRefFile() {
return refFile;
}
public void actionPerformed(ActionEvent e) {
Object o = e.getSource();
if (o instanceof Runnable) {
((Runnable) o).run();
}
else if (o instanceof JComboBox && !lock
&& !biomodel.getSBMLFile().equals(sbmlFiles.getSelectedItem())) {
dirty.setValue(true);
biomodel.makeUndoPoint();
}
}
public synchronized void lock() {
lock = true;
}
public synchronized void unlock() {
lock = false;
}
public void rebuildGui() {
removeAll();
buildGui();
revalidate();
}
private void refreshComponentsList() {
components.removeAllItem();
for (long i = 0; i < biomodel.getSBMLCompModel().getNumSubmodels(); i++) {
Submodel submodel = biomodel.getSBMLCompModel().getSubmodel(i);
String locationAnnotationString = "";
//if the submodel is gridded, then get the component names from the locations parameter
if (biomodel.getSBMLDocument().getModel().getParameter(submodel.getId().replace("GRID__","") + "__locations") != null) {
locationAnnotationString =
biomodel.getSBMLDocument().getModel()
.getParameter(submodel.getId().replace("GRID__","") + "__locations")
.getAnnotationString().replace("<annotation>","").replace("</annotation>","");
String[] compIDs = locationAnnotationString.replace("\"","").split("array:");
for (int j = 2; j < compIDs.length; ++j) {
if (compIDs[j].contains("=(")) {
compIDs[j] = compIDs[j].split("=")[0].trim();
components.addItem(compIDs[j] + " " +
submodel.getModelRef() + " " + biomodel.getComponentPortMap(compIDs[j]));
}
}
}
else
components.addItem(submodel.getId() + " " + submodel.getModelRef() + " " + biomodel.getComponentPortMap(submodel.getId()));
}
}
private void buildGui() {
JPanel mainPanelNorth = new JPanel();
JPanel mainPanelCenter = new JPanel(new BorderLayout());
JPanel mainPanelCenterUp = new JPanel();
JPanel mainPanelCenterCenter = new JPanel(new GridLayout(2, 2));
//JPanel mainPanelCenterDown = new JPanel(new BorderLayout());
mainPanelCenter.add(mainPanelCenterUp, BorderLayout.NORTH);
mainPanelCenter.add(mainPanelCenterCenter, BorderLayout.CENTER);
sbmlFiles = new JComboBox();
sbmlFiles.addActionListener(this);
//reloadFiles();
// create the modelview2 (jgraph) panel
JPanel mainPanel = new JPanel(new BorderLayout());
mainPanel.setLayout(new BorderLayout());
//JPanel paramPanel = new JPanel(new BorderLayout());
//paramPanel.add(modelPanel, "North");
JPanel propPanel = new JPanel(new BorderLayout());
propPanel.add(mainPanelNorth, "North");
mainPanel.add(mainPanelCenter, "Center");
tab = new JTabbedPane();
String file = filename.replace(".gcm", ".xml");
//JComboBox compartmentList = MySpecies.createCompartmentChoices(biomodel);
compartmentPanel = new Compartments(biosim,biomodel,dirty, paramsOnly,getParams, path + separator + file, parameterChanges,false);
reactionPanel = new Reactions(biosim,biomodel,dirty, paramsOnly,getParams,path + separator + file,parameterChanges, this);
speciesPanel = new MySpecies(biosim,biomodel,dirty, paramsOnly,getParams,path + separator + file,parameterChanges,biomodel.getGrid().isEnabled());
parametersPanel = new Parameters(biosim, biomodel,dirty, paramsOnly,getParams,path + separator + file,parameterChanges,
!paramsOnly && !biomodel.getGrid().isEnabled() && !textBased);
rulesPanel = new Rules(biosim, biomodel, this, dirty);
consPanel = new Constraints(biomodel,dirty);
eventPanel = new Events(biosim,biomodel,dirty);
JPanel compPanel = new JPanel(new BorderLayout());
if (textBased) {
modelPanel = new ModelPanel(biomodel, this);
compPanel.add(modelPanel, "North");
}
compPanel.add(compartmentPanel,"Center");
biomodel.setSpeciesPanel(speciesPanel);
biomodel.setReactionPanel(reactionPanel);
biomodel.setRulePanel(rulesPanel);
biomodel.setEventPanel(eventPanel);
biomodel.setConstraintPanel(consPanel);
biomodel.setParameterPanel(parametersPanel);
components = new PropertyList("Component List");
EditButton addInit = new EditButton("Add Component", components);
RemoveButton removeInit = new RemoveButton("Remove Component", components);
EditButton editInit = new EditButton("Edit Component", components);
refreshComponentsList();
this.getSpeciesPanel().refreshSpeciesPanel(biomodel);
JPanel componentsPanel = Utility.createPanel(this, "Components", components, addInit, removeInit, editInit);
mainPanelCenterCenter.add(componentsPanel);
if (textBased) {
tab.addTab("Compartments", compPanel);
tab.addTab("Species", speciesPanel);
tab.addTab("Reactions", reactionPanel);
tab.addTab("Parameters", parametersPanel);
tab.addTab("Components", componentsPanel);
tab.addTab("Rules", rulesPanel);
tab.addTab("Constraints", propPanel);
tab.addTab("Events", eventPanel);
}
else {
this.schematic = new Schematic(biomodel, biosim, this, true, null,compartmentPanel,reactionPanel,rulesPanel,
consPanel,eventPanel,parametersPanel);
tab.addTab("Schematic", schematic);
if (biomodel.getGrid().isEnabled()) {
tab.addTab("Grid Species", speciesPanel);
tab.addTab("Parameters", parametersPanel);
} else {
tab.addTab("Constants", parametersPanel);
}
tab.addChangeListener(this);
}
functionPanel = new Functions(biomodel,dirty);
unitPanel = new Units(biosim,biomodel,dirty);
//JPanel defnPanel = new JPanel(new BorderLayout());
//defnPanel.add(mainPanelNorth, "North");
//defnPanel.add(functionPanel,"Center");
//defnPanel.add(unitPanel,"South");
//tab.addTab("Definitions", defnPanel);
tab.addTab("Functions", functionPanel);
tab.addTab("Units", unitPanel);
if (biomodel.getSBMLDocument().getLevel() < 3) {
CompartmentTypes compTypePanel = new CompartmentTypes(biosim,biomodel,dirty);
SpeciesTypes specTypePanel = new SpeciesTypes(biosim,biomodel,dirty);
JPanel typePanel = new JPanel(new BorderLayout());
typePanel.add(mainPanelNorth, "North");
typePanel.add(compTypePanel,"Center");
typePanel.add(specTypePanel,"South");
tab.addTab("Types", typePanel);
}
InitialAssignments initialsPanel = new InitialAssignments(biosim,biomodel,dirty);
compartmentPanel.setPanels(initialsPanel, rulesPanel);
functionPanel.setPanels(initialsPanel, rulesPanel);
speciesPanel.setPanels(initialsPanel, rulesPanel);
reactionPanel.setPanels(initialsPanel, rulesPanel);
setLayout(new BorderLayout());
if (paramsOnly) {
add(parametersPanel, BorderLayout.CENTER);
}
else {
add(tab, BorderLayout.CENTER);
}
species = new PropertyList("Species List");
addInit = new EditButton("Add Species", species);
removeInit = new RemoveButton("Remove Species", species);
if (paramsOnly) {
addInit.setEnabled(false);
removeInit.setEnabled(false);
}
editInit = new EditButton("Edit Species", species);
if (paramsOnly) {
ArrayList<String> specs = biomodel.getSpecies();
for (String s : getParams) {
if (s.contains("/") && specs.contains(s.split("/")[0].trim())) {
specs.remove(s.split("/")[0].trim());
specs.add(s.split("/")[0].trim() + " Modified");
parameterChanges.add(s);
}
}
species.addAllItem(specs);
}
else {
species.addAllItem(biomodel.getSpecies());
}
JPanel initPanel = Utility.createPanel(this, "Species", species, addInit, removeInit, editInit);
mainPanelCenterCenter.add(initPanel);
parameters = new PropertyList("Parameter List");
editInit = new EditButton("Edit Parameter", parameters);
parameters.addAllItem(generateParameters());
parametersPanel.setPanels(initialsPanel, rulesPanel);
propPanel.add(consPanel, "Center");
// parameters.addAllItem(gcm.getParameters().keySet());
//initPanel = Utility.createPanel(this, "Model Generation Parameters", parameters, null, null, editInit);
//paramPanel.add(initPanel, "Center");
//paramPanel.add(parametersPanel, "South");
/*
conditions = new PropertyList("Property List");
addInit = new EditButton("Add Property", conditions);
removeInit = new RemoveButton("Remove Property", conditions);
editInit = new EditButton("Edit Property", conditions);
if (paramsOnly) {
addInit.setEnabled(false);
removeInit.setEnabled(false);
editInit.setEnabled(false);
}
for (String s : gcm.getConditions()) {
conditions.addItem(s);
}
initPanel = Utility.createPanel(this, "CSL Properties", conditions, addInit, removeInit, editInit);
propPanel.add(initPanel, "Center");
*/
//propPanel.add(consPanel, "South");
}
/*
public void reloadFiles() {
lock();
// sbmlFiles.removeAll();
String[] sbmlList = Utility.getFiles(path, ".sbml");
String[] xmlList = Utility.getFiles(path, ".xml");
String[] temp = new String[sbmlList.length + xmlList.length];
System.arraycopy(sbmlList, 0, temp, 0, sbmlList.length);
System.arraycopy(xmlList, 0, temp, sbmlList.length, xmlList.length);
Arrays.sort(temp, String.CASE_INSENSITIVE_ORDER);
String[] allList = new String[temp.length + 1];
System.arraycopy(temp, 0, allList, 1, temp.length);
allList[0] = none;
DefaultComboBoxModel model = new DefaultComboBoxModel(allList);
sbmlFiles.setModel(model);
sbmlFiles.setSelectedItem(none);
sbmlFiles.setSelectedItem(gcm.getSBMLFile());
if (!gcm.getSBMLFile().equals("")) {
gcm.setSBMLDocument(Gui.readSBML(path + separator + gcm.getSBMLFile()));
if (sbmlFiles.getSelectedItem().equals(none)) {
Utility.createErrorMessage("Warning: Missing File", "Unable to find SBML file "
+ gcm.getSBMLFile() + ". Creating a default SBML file");
SBMLDocument document = new SBMLDocument(Gui.SBML_LEVEL, Gui.SBML_VERSION);
Model m = document.createModel();
document.setModel(m);
m.setId(gcmname);
Compartment c = m.createCompartment();
c.setId("default");
gcm.getUsedIDs().add("default");
c.setSize(1);
c.setSpatialDimensions(3);
c.setConstant(true);
String[] species = (String[])gcm.getSpecies().toArray();
for (int i = 0; i < species.length; i++) {
Species s = m.createSpecies();
s.setId(species[i]);
s.setCompartment("default");
s.setBoundaryCondition(false);
s.setConstant(false);
s.setInitialAmount(0);
s.setHasOnlySubstanceUnits(true);
}
SBMLutilities.addRandomFunctions(document);
SBMLWriter writer = new SBMLWriter();
writer.writeSBML(document, path + separator + gcmname + ".xml");
biosim.addToTreeNoUpdate(gcmname + ".xml");
setDirty(true);
} else {
SBMLDocument document = Gui.readSBML(path + separator + gcm.getSBMLFile());
SBMLutilities.addRandomFunctions(document);
SBMLWriter writer = new SBMLWriter();
writer.writeSBML(document, path + separator + gcmname + ".xml");
biosim.addToTreeNoUpdate(gcmname + ".xml");
setDirty(true);
}
} else {
SBMLDocument document = new SBMLDocument(Gui.SBML_LEVEL, Gui.SBML_VERSION);
Model m = document.createModel();
document.setModel(m);
m.setId(gcmname);
Compartment c = m.createCompartment();
c.setId("default");
gcm.getUsedIDs().add("default");
c.setSize(1);
c.setSpatialDimensions(3);
c.setConstant(true);
ArrayList<String> speciesList = gcm.getSpecies();
for (String species : speciesList) {
Species s = m.createSpecies();
s.setId(species);
gcm.getUsedIDs().add(species);
s.setCompartment("default");
s.setBoundaryCondition(false);
s.setConstant(false);
s.setInitialAmount(0);
s.setHasOnlySubstanceUnits(true);
}
SBMLutilities.addRandomFunctions(document);
SBMLWriter writer = new SBMLWriter();
writer.writeSBML(document, path + separator + gcmname + ".xml");
biosim.addToTreeNoUpdate(gcmname + ".xml");
setDirty(true);
}
gcm.setSBMLFile(gcmname+".xml");
sbmlFiles.setSelectedItem(gcm.getSBMLFile());
if (gcm.getSBMLDocument()==null) {
gcm.setSBMLDocument(Gui.readSBML(path + separator + gcm.getSBMLFile()));
//CompSBMLDocumentPlugin compdoc = (CompSBMLDocumentPlugin)sbml.getPlugin("comp");
gcm.getSBMLDocument().enablePackage(LayoutExtension.getXmlnsL3V1V1(), "layout", true);
gcm.getSBMLDocument().setPkgRequired("layout", false);
gcm.setSBMLLayout((LayoutModelPlugin)gcm.getSBMLDocument().getModel().getPlugin("layout"));
gcm.getSBMLDocument().enablePackage(CompExtension.getXmlnsL3V1V1(), "comp", true);
gcm.getSBMLDocument().setPkgRequired("comp", true);
gcm.setSBMLComp((CompSBMLDocumentPlugin)gcm.getSBMLDocument().getPlugin("comp"));
gcm.setSBMLCompModel((CompModelPlugin)gcm.getSBMLDocument().getModel().getPlugin("comp"));
} else {
gcm.getSBMLDocument().setModel(Gui.readSBML(path + separator + gcm.getSBMLFile()).getModel());
//CompSBMLDocumentPlugin compdoc = (CompSBMLDocumentPlugin)sbml.getPlugin("comp");
gcm.getSBMLDocument().enablePackage(LayoutExtension.getXmlnsL3V1V1(), "layout", true);
gcm.getSBMLDocument().setPkgRequired("layout", false);
gcm.setSBMLLayout((LayoutModelPlugin)gcm.getSBMLDocument().getModel().getPlugin("layout"));
gcm.getSBMLDocument().enablePackage(CompExtension.getXmlnsL3V1V1(), "comp", true);
gcm.getSBMLDocument().setPkgRequired("comp", true);
gcm.setSBMLComp((CompSBMLDocumentPlugin)gcm.getSBMLDocument().getPlugin("comp"));
gcm.setSBMLCompModel((CompModelPlugin)gcm.getSBMLDocument().getModel().getPlugin("comp"));
}
if (!paramsOnly) {
gcm.save(path + separator + gcmname + ".gcm");
SBMLWriter writer = new SBMLWriter();
writer.writeSBML(gcm.getSBMLDocument(), path + separator + gcmname + ".xml");
}
unlock();
}
*/
public void reloadParameters() {
parameters.removeAllItem();
parameters.addAllItem(generateParameters());
}
private Set<String> generateParameters() {
HashSet<String> results = new HashSet<String>();
if (paramsOnly) {
/*
HashMap<String, String> params = gcm.getGlobalParameters();
ArrayList<Object> remove = new ArrayList<Object>();
for (String key : params.keySet()) {
remove.add(key);
}
for (Object prop : remove) {
params.remove(prop);
}
*/
for (String update : parameterChanges) {
String id;
if (!update.contains("/")) {
id = update.split(" ")[0];
String value = update.split(" ")[1].trim();
biomodel.setParameter(id, value, null);
}
}
}
/*
for (String s : gcm.getParameters().keySet()) {
if (!s.equals(GlobalConstants.KBIO_STRING) && !s.equals(GlobalConstants.KASSOCIATION_STRING)
&& !s.equals(GlobalConstants.MAX_DIMER_STRING)) {
if (gcm.getGlobalParameters().containsKey(s)) {
if (gcm.getParameter(s).contains("(")) {
results.add(CompatibilityFixer.getGuiName(s) + " ("
+ s + "), Sweep, "
+ gcm.getParameter(s));
}
else {
if (paramsOnly) {
results.add(CompatibilityFixer.getGuiName(s) + " ("
+ s + "), Modified, "
+ gcm.getParameter(s));
}
else {
results.add(CompatibilityFixer.getGuiName(s) + " ("
+ s + "), Custom, "
+ gcm.getParameter(s));
}
}
}
else {
if (paramsOnly) {
GCMFile refGCM = new GCMFile(path);
refGCM.load(path + separator + refFile);
if (refGCM.getGlobalParameters().containsKey(s)) {
results.add(CompatibilityFixer.getGuiName(s) + " ("
+ s + "), Custom, "
+ gcm.getParameter(s));
}
else {
results.add(CompatibilityFixer.getGuiName(s) + " ("
+ s + "), Default, "
+ gcm.getParameter(s));
}
}
else {
results.add(CompatibilityFixer.getGuiName(s) + " ("
+ s + "), Default, "
+ gcm.getParameter(s));
}
}
}
}
*/
return results;
}
// Internal private classes used only by the gui
private class SaveButton extends AbstractRunnableNamedButton {
public SaveButton(String name, JTextField fieldNameField) {
super(name);
this.fieldNameField = fieldNameField;
}
public void run() {
save(getName());
}
private JTextField fieldNameField = null;
}
private class RemoveButton extends AbstractRunnableNamedButton {
public RemoveButton(String name, PropertyList list) {
super(name);
this.list = list;
}
public void run() {
//dirty = true;
if (getName().contains("Influence")) {
String name = null;
if (list.getSelectedValue() != null) {
name = list.getSelectedValue().toString();
if (biomodel.removeInfluenceCheck(name)) {
biomodel.removeInfluence(name);
list.removeItem(name);
}
}
}
else if (getName().contains("Species")) {
String name = null;
if (list.getSelectedValue() != null) {
name = list.getSelectedValue().toString();
biomodel.removeSpecies(name);
}
}
else if (getName().contains("Promoter")) {
String name = null;
if (list.getSelectedValue() != null) {
name = list.getSelectedValue().toString();
biomodel.removePromoter(name);
list.removeItem(name);
}
}
else if (getName().contains("Property")) {
String name = null;
if (list.getSelectedValue() != null) {
name = list.getSelectedValue().toString();
//gcm.removeCondition(name);
list.removeItem(name);
}
}
else if (getName().contains("Component")) {
String name = null;
if (list.getSelectedValue() != null) {
name = list.getSelectedValue().toString();
String comp = name.split(" ")[0];
biomodel.removeComponent(comp);
}
}
}
private PropertyList list = null;
}
private class EditButton extends AbstractRunnableNamedButton {
public EditButton(String name, PropertyList list) {
super(name);
this.list = list;
}
public void run() {
new EditCommand(getName(), list).run();
}
private PropertyList list = null;
}
private class EditCommand implements Runnable {
public EditCommand(String name, PropertyList list) {
this.name = name;
this.list = list;
}
public void run() {
if (name == null || name.equals("")) {
Utility.createErrorMessage("Error", "Nothing selected to edit");
return;
}
if (list.getSelectedValue() == null && getName().contains("Edit")) {
Utility.createErrorMessage("Error", "Nothing selected to edit");
return;
}
//dirty = true;
if (getName().contains("Species")) {
String selected = null;
if (list.getSelectedValue() != null && getName().contains("Edit")) {
selected = list.getSelectedValue().toString();
if (selected.split(" ").length > 1) {
selected = selected.split(" ")[0];
}
}
launchSpeciesPanel(selected, false);
}
else if (getName().contains("Influence")) {
String selected = null;
if (list.getSelectedValue() != null && getName().contains("Edit")) {
selected = list.getSelectedValue().toString();
if (selected.split(" ")[selected.split(" ").length - 1].equals("Modified")) {
selected = selected.substring(0, selected.length() - 9);
}
}
launchInfluencePanel(selected);
}
else if (getName().contains("Promoter")) {
String selected = null;
if (list.getSelectedValue() != null && getName().contains("Edit")) {
selected = list.getSelectedValue().toString();
if (selected.split(" ").length > 1) {
selected = selected.split(" ")[0];
}
}
launchPromoterPanel(selected);
}
else if (getName().contains("Property")) {
String selected = null;
if (list.getSelectedValue() != null && getName().contains("Edit")) {
selected = list.getSelectedValue().toString();
}
//ConditionsPanel panel = new ConditionsPanel(selected, list, gcm, paramsOnly,gcmEditor);
}
else if (getName().contains("Component")) {
displayChooseComponentDialog(getName().contains("Edit"), list, false);
}
else if (getName().contains("Parameter")) {
String selected = null;
if (list.getSelectedValue() != null && getName().contains("Edit")) {
selected = list.getSelectedValue().toString();
}
BioModel refGCM = null;
if (paramsOnly) {
refGCM = new BioModel(path);
refGCM.load(path + separator + refFile);
}
/*
ParameterPanel panel = new ParameterPanel(selected, list, gcm, paramsOnly, refGCM, gcmEditor);
if (paramsOnly) {
String updates = panel.updates();
if (!updates.equals("")) {
for (int i = parameterChanges.size() - 1; i >= 0; i--) {
if (parameterChanges.get(i).startsWith(updates.split(" ")[0])) {
parameterChanges.remove(i);
}
}
if (updates.contains(" ")) {
for (String s : updates.split("\n")) {
parameterChanges.add(s);
}
}
}
}
*/
}
}
public String getName() {
return name;
}
private String name = null;
private PropertyList list = null;
}
/**
* launches the promoter panel to edit the promoter with the given id.
* If no id is given, then it edits a new promoter.
* @param id
* @return
*/
public PromoterPanel launchPromoterPanel(String id){
BioModel refGCM = null;
if (paramsOnly) {
refGCM = new BioModel(path);
refGCM.load(path + separator + refFile);
}
PromoterPanel panel = new PromoterPanel(id, biomodel, paramsOnly, refGCM, this);
if (paramsOnly) {
String updates = panel.updates();
if (!updates.equals("")) {
for (int i = parameterChanges.size() - 1; i >= 0; i
if (parameterChanges.get(i).startsWith(updates.split("/")[0])) {
parameterChanges.remove(i);
}
}
if (updates.contains(" ")) {
for (String s : updates.split("\n")) {
parameterChanges.add(s);
}
}
}
}
return panel;
}
public SpeciesPanel launchSpeciesPanel(String id, boolean inTab) {
BioModel refGCM = null;
if (paramsOnly) {
refGCM = new BioModel(path);
refGCM.load(path + separator + refFile);
}
SpeciesPanel panel = new SpeciesPanel(biosim, id, species, conditions,
components, biomodel, paramsOnly, refGCM, this, inTab);
// if (paramsOnly) {
// String updates = panel.updates();
// if (!updates.equals("")) {
// for (int i = parameterChanges.size() - 1; i >= 0; i--) {
// if (parameterChanges.get(i).startsWith(updates.split("/")[0])) {
// parameterChanges.remove(i);
// if (updates.contains(" ")) {
// for (String s : updates.split("\n")) {
// parameterChanges.add(s);
return panel;
}
public InfluencePanel launchInfluencePanel(String id){
BioModel refGCM = null;
if (paramsOnly) {
refGCM = new BioModel(path);
refGCM.load(path + separator + refFile);
}
InfluencePanel panel = new InfluencePanel(id, influences, biomodel, paramsOnly, refGCM, this);
if (paramsOnly) {
String updates = panel.updates();
if (!updates.equals("")) {
for (int i = parameterChanges.size() - 1; i >= 0; i
if (parameterChanges.get(i).startsWith(updates.split("/")[0])) {
parameterChanges.remove(i);
}
}
if (!updates.endsWith("/")) {
for (String s : updates.split("\n")) {
parameterChanges.add(s);
}
}
}
}
return panel;
}
public String launchComponentPanel(String id){
BioModel refGCM = null;
if (paramsOnly) {
refGCM = new BioModel(path);
refGCM.load(path + separator + refFile);
}
// TODO: This is a messy way to do things. We set the selected component in the list
// and then call displayChooseComponentDialog(). This makes for tight coupling with the
// component list.
for (int i = 0; i < this.components.getModel().getSize(); i++) {
String componentsListRow = this.components.getModel().getElementAt(i).toString();
String componentsListId = componentsListRow.split(" ")[0];
//System.err.println(componentsListId + " " + id);
if (componentsListId.equals(id)) {
this.components.setSelectedIndex(i);
break;
}
}
return displayChooseComponentDialog(true, this.components, false);
}
/**
* launches a panel for grid creation
*/
public void launchGridPanel() {
//static method that builds the grid panel
//the false field means to open the grid creation panel
//and not the grid editing panel
boolean created = GridPanel.showGridPanel(this, biomodel, false);
//if the grid is built, then draw it and so on
if (created) {
this.setDirty(true);
this.refresh();
schematic.getGraph().buildGraph();
schematic.display();
biomodel.makeUndoPoint();
}
}
public SchemeChooserPanel getSchemeChooserPanel(
String cellID, MovieContainer movieContainer, boolean inTab) {
return new SchemeChooserPanel(cellID, movieContainer, inTab);
}
public boolean checkNoComponentLoop(String gcm, String checkFile) {
gcm = gcm.replace(".gcm", ".xml");
boolean check = true;
BioModel g = new BioModel(path);
g.load(path + separator + checkFile);
for (long i = 0; i < g.getSBMLComp().getNumExternalModelDefinitions(); i++) {
String compGCM = g.getSBMLComp().getExternalModelDefinition(i).getSource().substring(7);
if (compGCM.equals(gcm)) {
return false;
}
else {
check = checkNoComponentLoop(gcm, compGCM);
}
}
return check;
}
/**
* @return a list of all gcm files that can be included.
*/
public ArrayList<String> getComponentsList(){
// get a list of components
ArrayList<String> components = new ArrayList<String>();
for (String s : new File(path).list()) {
if (s.endsWith(".xml") && !s.equals(filename) /*&& checkNoComponentLoop(filename, s)*/) {
components.add(s);
}
}
// I think this sorts them
int i, j;
String index;
for (i = 1; i < components.size(); i++) {
index = components.get(i);
j = i;
while ((j > 0) && components.get(j - 1).compareToIgnoreCase(index) > 0) {
components.set(j, components.get(j - 1));
j = j - 1;
}
components.set(j, index);
}
return components;
}
public ArrayList<String> getParameterChanges() {
return parameterChanges;
}
/*
*
* Displays the "Choose Component" dialog and then adds the component afterward.
* @param tryEdit: if true then try to bring up the edit window if a component is selected.
* @param list: The PropertiesList. If left null then the gcm2sbmleditor's component
* list will be used.
* @param createUsingDefaults: If true then a component will be created with a basic name and
* no port mappings. Otherwise the user will be asked for
* the name and mappings.
*
* @return: the id of the component that was edited or created.
*/
public String displayChooseComponentDialog(boolean tryEdit, PropertyList list, boolean createUsingDefaults){
String outID = null;
if(list == null)
list = this.components;
String selected = null;
String comp = null;
if (list.getSelectedValue() != null && tryEdit) {
selected = list.getSelectedValue().toString();
comp = selected.split(" ")[1] + ".xml";
}
else {
ArrayList<String> components = getComponentsList();
if (components.size() == 0) {
comp = null;
JOptionPane.showMessageDialog(Gui.frame,
"There aren't any other models to use as components."
+ "\nCreate a new model or import a model into the project first.",
"Add Another Model To The Project", JOptionPane.ERROR_MESSAGE);
}
else {
comp = (String) JOptionPane.showInputDialog(Gui.frame,
"Choose a model to use as a component:", "Component Editor",
JOptionPane.PLAIN_MESSAGE, null, components.toArray(new String[0]), null);
}
}
if (comp != null && !comp.equals("")) {
BioModel subBioModel = new BioModel(path);
subBioModel.load(path + separator + comp);
subBioModel.flattenBioModel();
String oldPort = null;
if (selected != null) {
oldPort = selected.substring(selected.split(" ")[0].length()
+ selected.split(" ")[1].length() + 2);
selected = selected.split(" ")[0];
}
ArrayList<String> ports = subBioModel.getPorts();
if(createUsingDefaults){
// TODO: Is this correct?
outID = biomodel.addComponent(null, comp, false, null, -1, -1, 0, 0);
}else{
new ComponentsPanel(selected, list, biomodel, ports, comp, oldPort, paramsOnly, this);
outID = selected;
}
}
return outID;
}
public void undo() {
biomodel.undo();
schematic.refresh();
this.refresh();
this.setDirty(true);
}
public void redo() {
biomodel.redo();
schematic.refresh();
this.refresh();
this.setDirty(true);
}
public void setElementsPanel(ElementsPanel elementsPanel) {
this.elementsPanel = elementsPanel;
}
public Gui getGui() {
return biosim;
}
public Schematic getSchematic() {
return schematic;
}
public AnalysisView getReb2Sac() {
return reb2sac;
}
public boolean isTextBased() {
return textBased;
}
public MySpecies getSpeciesPanel() {
return speciesPanel;
}
public void setTextBased(boolean textBased) {
this.textBased = textBased;
}
public void stateChanged(ChangeEvent arg0) {
if (tab.getSelectedIndex()==0) {
schematic.getGraph().buildGraph();
}
}
private JTabbedPane tab = null;
private boolean lock = false;
private String[] options = { "Ok", "Cancel" };
private PropertyList species = null;
private PropertyList influences = null;
private PropertyList promoters = null;
private PropertyList parameters = null;
private PropertyList components = null;
private PropertyList conditions = null;
private JComboBox sbmlFiles = null;
private String path = null;
private static final String none = "--none
private Gui biosim = null;
private Log log = null;
private boolean textBased = false;
private MutableBoolean dirty = new MutableBoolean(false);
} |
package fi.hu.cs.titokone.resources;
import java.util.ListResourceBundle;
/** This translation is what all translations should be based on. It
translates keys to plain English. Note that not all keys are equal
to their values; the key may contain a specification part which
should not be translated. The specification part ought to be
put between ? and :, eg. "?Menu:File" would mean "translate the
word 'File' as if you would see it on the common menu name" as
opposed to "?Utility item:File", which might mean "translate the
word 'File' as you would if it meant a nail file". */
class Translations extends ListResourceBundle {
public Object[][] getContents() {
// To be simultaneously compatible with the general ListResourceBundle
// functionality and provide a base template array for other
// translations, we do not repeat every line in the emptyContents
// array, but instead arrange the duplication when asked for
// the real contents. (Only necessary the first time.)
if(contents == null) {
contents = new String[emptyContents.length][];
for(int i = 0; i < emptyContents.length; i++) {
contents[i] = new String[2];
contents[i][0] = emptyContents[i][0];
contents[i][1] = emptyContents[i][0];
}
}
return contents;
}
protected static Object[][] contents;
private static final Object[][] emptyContents = {
// Localize below, pairs of key-value (what key is in your language)...
// Remove lines which you do not wish to translate completely. Leaving
// in a value of "" will translate the message to "" as well.
// Class: Application.
// General messages: (none)
// Exception messages:
{ "No more keyboard data stored on application." ,
null },
{ "No more stdin data stored on application.",
null },
{ "Keyboard input string \"{0}\" invalid, should be eg. \n-separated " +
"list of integers." ,
null },
{ "Stdin input string \"{0}\" invalid, should be eg. \n-separated " +
"list of integers.",
null },
// Log messages:
{ "Application has no more keyboard data, read: {0}, buffer length " +
"{1}.",
null },
{ "Application has no more stdin data, read: {0}, buffer length {1}.",
null },
{ "Accepted \"{0}\" as keyboard input, tokens found: {1}.",
null },
{ "Accepted \"{0}\" as stdin input, tokens found: {1}.",
null },
// Class: Settings.
// General messages: (none)
// Exception messages:
{ "value", null },
{ "a linebreak", null },
{ "Illegal {0} \"{1}\", contains {2}.", null },
{ "Illegal {0}: null. Try an empty string instead.", null },
{ "Syntax error on line {0}, which was: \"{1}\".", null },
// Log messages:
{ "Settings successfully parsed, lines: {0}, unique keys found: {1}.",
null },
// Class:
// General messages:
// Exception messages:
// Localizable bit ends.
{ "Eliminator of comma-problems.", "Remove when ready!" }
};
} |
// modification, are permitted provided that the following conditions are met:
// documentation and/or other materials provided with the distribution.
// * Neither the name of the <organization> nor the
// names of its contributors may be used to endorse or promote products
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL DAVID J. PEARCE BE LIABLE FOR ANY
// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
package wyrl.util;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.BitSet;
import java.util.List;
import wyautl.core.*;
import wyautl.rw.Activation;
import wyautl.rw.RewriteRule;
import wyrl.core.Pattern;
public abstract class AbstractRewriteRule implements RewriteRule {
/**
* The pattern that this rewrite rule will match against.
*/
private final Pattern pattern;
/**
* The schema describes the automata that this rule will operate over.
*/
private final Schema schema;
private final int nPatternDeclarations;
/**
* Temporary state used during acceptance
*/
private int count;
public AbstractRewriteRule(Pattern pattern, Schema schema) {
this.schema = schema;
this.pattern = pattern;
// NOTE: +1 to include the root variable.
nPatternDeclarations = pattern.declarations().size() + 1;
}
public final List<Activation> probe(Automaton automaton, int root) {
count = 0;
Object[] initialState = new Object[nPatternDeclarations];
initialState[count++] = root;
ArrayList states = new ArrayList();
states.add(initialState);
// First, we check whether or not this pattern accepts the given
// automaton state. In the case that it does, we build an appropriate
// activation record.
if (accepts(pattern, automaton, root, states)) {
for(int i=0;i!=states.size();++i) {
Object[] state = (Object[]) states.get(i);
states.set(i,new Activation(this,null,state));
}
} else {
states = null;
}
return states;
}
private final boolean accepts(Pattern p, Automaton automaton, int root,
ArrayList<Object[]> states) {
if (p instanceof Pattern.Leaf) {
Pattern.Leaf leaf = (Pattern.Leaf) p;
return Runtime.accepts(leaf.type, automaton, automaton.get(root),
schema);
} else if (p instanceof Pattern.Term) {
return accepts((Pattern.Term) p, automaton, root, states);
} else if (p instanceof Pattern.Set) {
return accepts((Pattern.Set) p, automaton, root, states);
} else if (p instanceof Pattern.Bag) {
return accepts((Pattern.Bag) p, automaton, root, states);
} else {
return accepts((Pattern.List) p, automaton, root, states);
}
}
private final boolean accepts(Pattern.Term p, Automaton automaton, int root,
ArrayList<Object[]> states) {
Automaton.State state = automaton.get(root);
if (state instanceof Automaton.Term) {
Automaton.Term t = (Automaton.Term) state;
String actualName = schema.get(t.kind).name;
// Check term names match
if (!p.name.equals(actualName)) {
return false;
}
// Check contents matches
if (p.data == null) {
return t.contents == Automaton.K_VOID;
} else if (accepts(p.data, automaton, t.contents, states)) {
if(p.variable != null) {
// At this point, we need to store the root of the match as this
// will feed into the activation record.
assign(count++,t.contents,states);
}
return true;
}
}
return false;
}
private final boolean accepts(Pattern.BagOrSet p, Automaton automaton,
int root, ArrayList<Object[]> states) {
int startCount = count;
Automaton.State state = automaton.get(root);
if (p instanceof Pattern.Set && !(state instanceof Automaton.Set)) {
return false;
} else if (p instanceof Pattern.Bag && !(state instanceof Automaton.Bag)) {
return false;
}
Automaton.Collection c = (Automaton.Collection) state;
Pair<Pattern,String>[] p_elements = p.elements;
int minSize = p.unbounded ? p_elements.length - 1 : p_elements.length;
// First, check size of collection
if(!p.unbounded && c.size() != minSize || c.size() < minSize) {
return false;
}
boolean found = false;
BitSet matched = new BitSet(automaton.nStates());
for(int i=0;i!=states.size();++i) {
Object[] tmp = states.get(i);
// We set the state we're looking at to null to signal that it's
// done. This is because the nonDeterministicAccept function will
// load the (updated) state(s) back onto this states list if makes a
// match.
states.set(i,null);
found |= nonDeterministicAccept(c,automaton,p,0,matched,tmp,states);
}
// If we get here, then we're done.
return found;
}
/**
* Implements the non-deterministic matching required for set and bag
* patterns. For example, consider:
*
* <pre>
* reduce And{BExpr b, Not(BExpr) nb, BExpr... xs}}:
* => ...
* </pre>
*
* <p>
* Here, we are non-deterministically choosing <code>b</code> and
* <code>nb</code> from the children of the root state. In this case, we
* have two match elements (namely, for <code>b</code> and <code>nb</code>),
* along with a generic match for the rest. For each element, we consider
* every possible child which has not already been matched (i.e. so that
* <code>b<code> and <code>nb</code> don't match the same state).
* </p>
* <p>
* This method recursively matches the elements of such a pattern. At each
* invocation, a single element is matched by considering all remaining
* possibilities. As soon as we fail to make a match, the method returns
* immediately; otherwise it proceeds to try and (recursively) match all
* remaining elements.
* </p>
*
* @param children
* The child states being matched against.
* @param automaton
* The automaton which is being matched against.
* @param pattern
* The pattern we're attempting to match.
* @param elementIndex
* The current element from the pattern elements array that we
* are matching. Initially, this starts at zero and is
* incremented at each level of the match.
* @param matched
* A bitset indicating those states which are already matched and
* should not be further considered.
* @param states
* The states array onto which completed states are placed.
* @return
*/
private final boolean nonDeterministicAccept(Automaton.Collection children,
Automaton automaton, Pattern.BagOrSet pattern, int elementIndex,
BitSet matched, Object[] state, ArrayList<Object[]> states) {
Pair<Pattern, String>[] elements = pattern.elements;
if(elementIndex != elements.length) {
// At least one pattern element remains to be matched, so
// attempt to match it.
boolean found = false;
Pair<Pattern, String> pItem = elements[elementIndex];
Pattern pItem_first = pItem.first();
String pItem_second = pItem.second();
for (int i = 0; i != children.size(); ++i) {
if (matched.get(i)) {
continue;
}
int aItem = children.get(i);
if (accepts(pItem_first, automaton, aItem, states)) {
matched.set(i, true);
if (nonDeterministicAccept(children, automaton, pattern,
elementIndex + 1, matched, state, states)) {
found = true;
if (pItem_second != null) {
state[count++] = aItem;
}
}
matched.set(i, false);
}
}
return found;
} else {
// Matching elements complete complete. Now attempt to match
// remainder (where appropriate).
if (pattern.unbounded) {
int minSize = elements.length - 1;
Pair<Pattern, String> pItem = elements[elements.length];
Pattern pItem_first = pItem.first();
String pItem_second = pItem.second();
// First, we check whether or not this will succeed.
for (int j = 0; j != children.size(); ++j) {
if (matched.get(j)) {
continue;
}
int aItem = children.get(j);
if (!accepts(pItem_first, automaton, aItem, states)) {
return false;
}
}
// Second, we construct a match array (if one is required).
if (pItem_second != null) {
// In this case, we have a named variable into which we need
// to store the matched elements.
int[] nChildren = new int[children.size() - minSize];
for (int i = 0, j = 0; i != children.size(); ++i) {
if (matched.get(i)) {
continue;
}
nChildren[j++] = children.get(i);
}
if (pattern instanceof Pattern.Set) {
assign(count++, new Automaton.Set(nChildren), states);
} else {
assign(count++, new Automaton.Bag(nChildren), states);
}
}
}
// If we're get here, then we've completed the match.
states.add(Arrays.copyOf(state, state.length));
return true;
}
}
private final boolean accepts(Pattern.List p, Automaton automaton,
int root, ArrayList<Object[]> states) {
int startCount = count;
Automaton.Collection c = (Automaton.Collection) automaton.get(root);
Pair<Pattern, String>[] p_elements = p.elements;
int minSize = p.unbounded ? p_elements.length - 1 : p_elements.length;
// First, check size of collection
if (!p.unbounded && c.size() != minSize || c.size() < minSize) {
return false;
}
// Second, we need to try and match the elements.
for (int i = 0; i != minSize; ++i) {
Pair<Pattern, String> pItem = p_elements[i];
Pattern pItem_first = pItem.first();
String pItem_second = pItem.second();
int aItem = c.get(i);
if (!accepts(pItem_first, automaton, aItem, states)) {
count = startCount; // reset
return false;
} else if (pItem_second != null) {
assign(count++, aItem, states);
}
}
// Third, in the case of an unbounded match we check the remainder.
if (p.unbounded) {
Pair<Pattern, String> pItem = p_elements[minSize];
Pattern pItem_first = pItem.first();
String pItem_second = pItem.second();
for (int i = minSize; i != c.size(); ++i) {
int aItem = c.get(i);
if (!accepts(pItem_first, automaton, aItem, states)) {
count = startCount; // reset
return false;
}
}
if (pItem_second != null) {
int[] children = new int[c.size() - minSize];
for (int i = minSize; i != c.size(); ++i) {
children[i] = c.get(i);
}
assign(count++, new Automaton.List(children), states);
}
}
return true;
}
public static final void assign(int state, Object value, ArrayList<Object[]> states) {
}
} |
package control.forms.tabs;
import java.awt.Rectangle;
import java.awt.image.BufferedImage;
import view.forms.Page;
import model.settings.Status;
import model.settings.ViewSettings;
import control.ControlPaint;
import control.interfaces.MoveEvent;
import control.interfaces.TabbedListener;
/**
* Controller class for Tabs. Deals with the opening and the closing
* of the entire tab pane (not opening another tab).
*
*
* @author Julius Huelsmann
* @version %I%, %U%
*
*/
public class CTabs implements TabbedListener {
/**
* Instance of the main controller.
*/
private ControlPaint cp;
/**
* Constructor: saves the instance of the main controller
* class which offers accessibility to other
* controller, model and view classes.
*
* @param _cp instance of the main controller class which
* is saved
*/
public CTabs(final ControlPaint _cp) {
this.cp = _cp;
}
public final void closeListener() {
double timetoclose0 = System.currentTimeMillis();
Page page = cp.getView().getPage();
//set new bounds in settings
ViewSettings.setView_bounds_page(
new Rectangle(ViewSettings.getView_bounds_page()));
//re-initialize the image with the correct size
cp.getControlPic().setBi_background(new BufferedImage(
ViewSettings.getView_bounds_page().getSize().width,
ViewSettings.getView_bounds_page().getSize().height,
BufferedImage.TYPE_INT_ARGB));
cp.getControlPic().setBi(new BufferedImage(
ViewSettings.getView_bounds_page().getSize().width,
ViewSettings.getView_bounds_page().getSize().height,
BufferedImage.TYPE_INT_ARGB));
cp.setBi_preprint(new BufferedImage(
ViewSettings.getView_bounds_page().getSize().width,
ViewSettings.getView_bounds_page().getSize().height,
BufferedImage.TYPE_INT_ARGB));
//apply new size in view
//takes some time and repaints the image.
//TODO: better algorithm for opening.
//save the previously displayed image (out of BufferedImage)
//and write it into the new (greater one). Afterwards (re)paint
//the sub image that is new.
page.setSize(
(int) ViewSettings.getView_bounds_page().getWidth(),
(int) ViewSettings.getView_bounds_page().getHeight());
//time used ca. 0.8 sec
// output
double timetoclose1 = System.currentTimeMillis();
final int divisorToSeconds = 100;
System.out.println(getClass()
+ "time passed" + (timetoclose1 - timetoclose0)
/ divisorToSeconds);
//check whether location is okay.
final int d = (int) (ViewSettings.getView_bounds_page().getHeight()
/ Status.getImageShowSize().height
* Status.getImageSize().height
- page.getJlbl_painting().getLocation().getY()
- Status.getImageSize().height);
if (d > 0) {
page.getJlbl_painting().setLocation(
(int) page.getJlbl_painting().getLocation().getX(),
(int) page.getJlbl_painting().getLocation().getY() + d);
}
}
/**
* {@inheritDoc}
*/
public final void moveListener(final MoveEvent _event) {
Page page = cp.getView().getPage();
page.setLocation(
_event.getPnt_bottomLocation());
}
/**
* {@inheritDoc}
*/
public final void openListener() {
Page page = cp.getView().getPage();
//set new bounds in settings
ViewSettings.setView_bounds_page(
new Rectangle(ViewSettings.getView_bounds_page_open()));
//re-initialize the image with the correct size
cp.getControlPic().setBi_background(new BufferedImage(
ViewSettings.getView_bounds_page().getSize().width,
ViewSettings.getView_bounds_page().getSize().height,
BufferedImage.TYPE_INT_ARGB));
cp.getControlPic().setBi(new BufferedImage(
ViewSettings.getView_bounds_page().getSize().width,
ViewSettings.getView_bounds_page().getSize().height,
BufferedImage.TYPE_INT_ARGB));
cp.setBi_preprint(new BufferedImage(
ViewSettings.getView_bounds_page().getSize().width,
ViewSettings.getView_bounds_page().getSize().height,
BufferedImage.TYPE_INT_ARGB));
//apply new size in view
//takes some time and repaints the image.
//TODO: better algorithm for opening.
//save the previously displayed image (out of BufferedImage)
//and write the necessary stuff it into the new (smaller one)
page.setSize(
(int) ViewSettings.getView_bounds_page().getWidth(),
(int) ViewSettings.getView_bounds_page().getHeight());
}
} |
package com.sun.star.wizards.web.data;
import java.util.Calendar;
import java.util.Hashtable;
import java.util.Map;
import java.util.Vector;
import com.sun.star.beans.PropertyValue;
import com.sun.star.container.NoSuchElementException;
import com.sun.star.container.XNameAccess;
import com.sun.star.i18n.NumberFormatIndex;
import com.sun.star.lang.Locale;
import com.sun.star.lang.WrappedTargetException;
import com.sun.star.lang.XMultiServiceFactory;
import com.sun.star.uno.UnoRuntime;
import com.sun.star.util.DateTime;
import com.sun.star.util.XNumberFormatsSupplier;
import com.sun.star.util.XNumberFormatter;
import com.sun.star.wizards.common.*;
import com.sun.star.wizards.common.Helper.DateUtils;
/**
* @author rpiterman
*/
public class CGSettings extends ConfigGroup {
public String soTemplateDir;
public String soGalleryDir;
public String workPath = null;
public String cp_WorkDir;
public ConfigSet cp_Exporters = new ConfigSet(CGExporter.class);
public ConfigSet cp_Layouts = new ConfigSet(CGLayout.class);
public ConfigSet cp_Styles = new ConfigSet(CGStyle.class);
public ConfigSet cp_IconSets = new ConfigSet(CGIconSet.class);
public ConfigSet cp_BackgroundImages = new ConfigSet(CGImage.class);
public ConfigSet cp_SavedSessions = new ConfigSet(CGSessionName.class);
public ConfigSet cp_Filters = new ConfigSet(CGFilter.class);
public ConfigSet savedSessions = new ConfigSet(CGSessionName.class);
public CGSession cp_DefaultSession = new CGSession();
public String cp_LastSavedSession;
private Map exportersMap = new Hashtable();
private XMultiServiceFactory xmsf;
String[] resources;
public Formatter formatter;
public static final int RESOURCE_PAGES_TEMPLATE = 0;
public static final int RESOURCE_SLIDES_TEMPLATE = 1;
public static final int RESOURCE_CREATED_TEMPLATE = 2;
public static final int RESOURCE_UPDATED_TEMPLATE = 3;
public static final int RESOURCE_SIZE_TEMPLATE = 4;
public CGSettings(XMultiServiceFactory xmsf_, String[] resources_ , Object document) {
xmsf = xmsf_;
try {
soTemplateDir = FileAccess.getOfficePath(xmsf, "Config","");
soGalleryDir = FileAccess.getOfficePath(xmsf,"Gallery","share");
root = this;
formatter = new Formatter(xmsf, document );
resources = resources_;
}
catch (Exception ex) {
ex.printStackTrace();
}
}
private static final CGExporter[] EMPTY_ARRAY_1 = new CGExporter[0];
public CGExporter[] getExporters(String mime) {
CGExporter[] exps = (CGExporter[])exportersMap.get(mime);
if (exps == null)
exportersMap.put(mime,exps = createExporters(mime));
return exps;
}
private CGExporter[] createExporters(String mime) {
Object[] exporters = cp_Exporters.items();
Vector v = new Vector();
for (int i = 0; i<exporters.length; i++)
if (((CGExporter)exporters[i]).supports(mime)) {
try {
v.add(exporters[i]);
}
catch (Exception ex) {
ex.printStackTrace();
}
}
return (CGExporter[])v.toArray(EMPTY_ARRAY_1);
}
/**
* call after read.
* @param xmsf
* @param document the background document. used for date/number formatting.
*/
public void configure(XMultiServiceFactory xmsf) throws Exception {
workPath = FileAccess.connectURLs(soTemplateDir , cp_WorkDir);
calcExportersTargetTypeNames(xmsf);
}
private void calcExportersTargetTypeNames(XMultiServiceFactory xmsf) throws Exception {
Object typeDetect = xmsf.createInstance("com.sun.star.document.TypeDetection");
XNameAccess xNameAccess = (XNameAccess)UnoRuntime.queryInterface(XNameAccess.class,typeDetect);
for (int i = 0; i < cp_Exporters.getSize(); i++)
calcExporterTargetTypeName(xNameAccess,(CGExporter)cp_Exporters.getElementAt(i));
}
private void calcExporterTargetTypeName(XNameAccess xNameAccess, CGExporter exporter)
throws NoSuchElementException,
WrappedTargetException
{
if (!exporter.cp_TargetType.equals(""))
exporter.targetTypeName =
(String) Properties.getPropertyValue(
(PropertyValue[]) xNameAccess.getByName(exporter.cp_TargetType),
"UIName");
}
FileAccess fileAccess;
FileAccess getFileAccess() throws Exception {
return getFileAccess(xmsf);
}
FileAccess getFileAccess(XMultiServiceFactory xmsf) throws Exception {
if (fileAccess==null)
fileAccess = new FileAccess(xmsf);
return fileAccess;
}
public class Formatter {
private long docNullTime;
private int dateFormat, numberFormat;
private DateUtils dateUtils;
public Formatter(XMultiServiceFactory xmsf, Object document ) throws Exception {
dateUtils = new DateUtils(xmsf, document);
dateFormat = dateUtils.getFormat( NumberFormatIndex.DATE_SYS_DMMMYYYY);
numberFormat = dateUtils.getFormat( NumberFormatIndex.NUMBER_1000DEC2 );
}
public String formatCreated(DateTime date) {
String sDate = dateUtils.format( dateFormat, date );
return JavaTools.replaceSubString( resources[CGSettings.RESOURCE_CREATED_TEMPLATE], sDate, "%DATE" );
}
public String formatUpdated(DateTime date) {
String sDate = dateUtils.format( dateFormat, date );
return JavaTools.replaceSubString( resources[CGSettings.RESOURCE_UPDATED_TEMPLATE], sDate, "%DATE" );
}
public String formatFileSize(int size) {
float sizeInKB = ((float)size) / 1024f;
String sSize = dateUtils.getFormatter().convertNumberToString(numberFormat, sizeInKB );
return JavaTools.replaceSubString( resources[CGSettings.RESOURCE_SIZE_TEMPLATE], sSize, "%NUMBER" );
}
}
} |
package king.flow.net;
import com.github.jsonj.JsonObject;
import com.github.jsonj.tools.JsonParser;
import java.awt.Window;
import java.io.File;
import java.net.URL;
import java.util.Timer;
import java.util.TimerTask;
import java.util.logging.Level;
import java.util.zip.ZipFile;
import javax.xml.bind.JAXBException;
import static king.flow.common.CommonConstants.DOWNLOAD_KEY_SIGNAL;
import king.flow.design.NetConfProcessor;
import static king.flow.common.CommonUtil.getLogger;
import static king.flow.common.CommonUtil.createRegistryTLSMessage;
import static king.flow.common.CommonConstants.REGISTRY_MSG_CODE;
import static king.flow.common.CommonConstants.RESTART_SIGNAL;
import static king.flow.common.CommonConstants.SUCCESSFUL_MSG_CODE;
import static king.flow.common.CommonConstants.UPDATE_SIGNAL;
import king.flow.common.CommonUtil.DownloadCipherKey;
import static king.flow.common.CommonUtil.TerminalStatus.RESTART;
import static king.flow.common.CommonUtil.getCurrentView;
import static king.flow.common.CommonUtil.parseRegTLSMessage;
import static king.flow.common.CommonUtil.setTerminalStatus;
import king.flow.control.BankAppStarter;
import king.flow.data.RegistryTLSResult;
import static king.flow.data.RegistryTLSResult.APP_UPDATE_MD5;
import static king.flow.data.RegistryTLSResult.APP_UPDATE_PATH;
import static king.flow.data.RegistryTLSResult.APP_UPDATE_VER;
import king.flow.net.update.UpdateTools;
import king.flow.net.update.http.HttpUpdateTool;
public class TunnelBuilder {
private static final String DEFAULT_XML = "./conf/backend.xml";
private static final String TUNNEL_BUILD_SCHEME = "tunnel.build.scheme";
private static TunnelBuilder tb = new TunnelBuilder();
private String hostName;
private int portNumber;
private String prsCode;
private String terminalID;
private String token;
private String branchID;
private int period;
private volatile int authorization_flag = Integer.MIN_VALUE;
private Timer loop = null;
public static TunnelBuilder getTunnelBuilder() {
if (tb == null) {
tb = new TunnelBuilder();
}
return tb;
}
private TunnelBuilder() {
parseXML(System.getProperty(TUNNEL_BUILD_SCHEME, DEFAULT_XML));
loop = new Timer(true);
}
public void enableHeartBeat() {
loop.scheduleAtFixedRate(new HeartBeatTask(), 10, period);
}
private void parseXML(String XMLPath) {
try {
NetConfProcessor ncp = new NetConfProcessor(XMLPath).init();
Transportation tsp = ncp.parse();
this.hostName = tsp.getServer().getHost();
this.portNumber = tsp.getServer().getPort();
this.prsCode = tsp.getRegistration().getPrsCode();
this.terminalID = tsp.getRegistration().getTerminalID();
this.token = tsp.getRegistration().getToken();
this.branchID = tsp.getRegistration().getBranchno();
this.period = tsp.getRegistration().getHeartbeat();
} catch (JAXBException ex) {
getLogger(TunnelBuilder.class.getName()).log(Level.SEVERE, null, ex);
}
}
public TunnelBuilder setHostName(String hostName) {
this.hostName = hostName;
return this;
}
public TunnelBuilder setPortNumber(int portNumber) {
this.portNumber = portNumber;
return this;
}
public String getTerminalID() {
return terminalID;
}
public String getToken() {
return token;
}
public String getBranchID() {
return branchID;
}
public TunnelBuilder setXML(String filePath) {
parseXML(filePath);
return this;
}
public Tunnel createTunnel() {
Tunnel tunnel = null;
if (authorization_flag < 0) {
tunnel = new FakeTunnel();
} else {
tunnel = new P2PTunnel(hostName, portNumber);
}
return tunnel;
}
private void grant(boolean access) {
if (access) {
authorization_flag = Integer.MAX_VALUE;
} else {
authorization_flag = Integer.MIN_VALUE;
}
}
private class HeartBeatTask extends TimerTask {
@Override
public void run() {
P2PTunnel p2PTunnel = new P2PTunnel(hostName, portNumber);
final String registryTLSMessage = createRegistryTLSMessage(prsCode, terminalID, token);
getLogger(HeartBeatTask.class.getName()).log(Level.INFO, "Heartbeat message : {0}", registryTLSMessage);
try {
String response = p2PTunnel.connect(REGISTRY_MSG_CODE, registryTLSMessage);
if (response == null || response.length() == 0) {
grant(false);
getLogger(HeartBeatTask.class.getName()).log(Level.WARNING,
"Cannot receive registration response");
} else {
RegistryTLSResult result = parseRegTLSMessage(response);
if (result.getRetCode() == SUCCESSFUL_MSG_CODE) {
grant(true);
int appRestartSignal = result.getAppRestartSignal();
int downloadKeySignal = result.getDownloadKeySignal();
int systemRestartSignal = result.getSystemRestartSignal();
int appUpdateSignal = result.getAppUpdateSignal();
String appUpdateFile = result.getAppUpdateFile();
String version = null;
String appUpdatePath = null;
String appUpdateMd5 = null;
if (appUpdateFile != null) {
JsonParser jsonParser = new JsonParser();
JsonObject updateList = jsonParser.parse(appUpdateFile).asObject();
version = updateList.getString(APP_UPDATE_VER);
appUpdatePath = updateList.getString(APP_UPDATE_PATH);
appUpdateMd5 = updateList.getString(APP_UPDATE_MD5);
}
StringBuilder sb = new StringBuilder().append('[')
.append("systemRestartSignal : ").append(systemRestartSignal).append(",\n")
.append("appRestartSignal : ").append(appRestartSignal).append(",\n")
.append("downloadKeySignal : ").append(downloadKeySignal).append(",\n")
.append("appUpdateSignal : ").append(appUpdateSignal).append(",\n")
.append("version : ").append(version).append(",\n")
.append("appUpdatePath : ").append(appUpdatePath).append(",\n")
.append("appUpdateMd5 : ").append(appUpdateMd5)
.append(']');
getLogger(HeartBeatTask.class.getName()).log(Level.INFO,
"Received registration response message \n {0}", sb.toString());
if (systemRestartSignal == RESTART_SIGNAL) {
//restart operation system
getLogger(HeartBeatTask.class.getName()).log(Level.WARNING, "Restart OS now");
} else if (appRestartSignal == RESTART_SIGNAL) {
//restart bankapp
getLogger(HeartBeatTask.class.getName()).log(Level.WARNING, "Restart app now");
setTerminalStatus(RESTART);
Window window = getCurrentView();
window.dispose();
new BankAppStarter().start();
} else if (downloadKeySignal == DOWNLOAD_KEY_SIGNAL) {
//download keyboard cipher key again
getLogger(HeartBeatTask.class.getName()).log(Level.WARNING,
"Download keyboard cipher key now");
new DownloadCipherKey().execute();
} else if (appUpdateSignal == UPDATE_SIGNAL) {
getLogger(HeartBeatTask.class.getName()).log(Level.WARNING, "Update app now");
HttpUpdateTool updateTool = UpdateTools.getUpdateTool().createHttpUpdateTool(version,
new URL(appUpdatePath), appUpdateMd5);
File downloadFile = updateTool.downloadFile(updateTool.getUpdateUrl());
boolean isComprehensive = updateTool.checkSumFile(downloadFile, updateTool.getMd5());
if (isComprehensive) {
boolean success = updateTool.updateApp(new ZipFile(downloadFile));
if (success) {
System.exit(0);
}
}
}
} else {
grant(false);
getLogger(HeartBeatTask.class.getName()).log(Level.INFO,
"Fail to get authorization from server for {0}", result.getErrMsg());
}
}
} catch (Exception e) {
getLogger(HeartBeatTask.class.getName()).log(Level.SEVERE, "Fail to do heart beat communication due to {0}", e.getMessage());
grant(false);
}
}
}
} |
package view.forms;
//import declarations
import java.awt.Color;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.image.BufferedImage;
import java.io.InputStream;
import javax.swing.ImageIcon;
import start.test.BufferedViewer;
import view.tabs.PaintObjects;
import view.util.BorderThread;
import view.util.mega.MLabel;
import view.util.mega.MPanel;
import model.objects.painting.Picture;
import model.objects.painting.po.PaintObject;
import model.objects.pen.special.PenSelection;
import model.settings.Status;
import model.util.paint.Utils;
/**
*
* @author Julius Huelsmann
* @version %I%, %U%
*/
@SuppressWarnings("serial")
public class PaintLabel extends MLabel {
/**
* The bufferedImage containing the currently displayed painting stuff.
*/
private BufferedImage bi;
/**
* The location which can be changed and given.
*/
private int x = 0, y = 0;
/**
* The thread which moves the border.
*/
private BorderThread thrd_moveBorder;
/**
* Point is subtracted from new location of item JLabel.
*/
@SuppressWarnings("unused")
private Point pnt_start;
/**
* JPanel which is to be updated if location changes in
* PaintLabel.
*/
private MPanel jpnl_toMove;
/**
* Constructor.
*
* @param _jpnl_toMove JPanel which is to be updated if location changes in
* PaintLabel.
*/
public PaintLabel(final MPanel _jpnl_toMove) {
this.jpnl_toMove = _jpnl_toMove;
}
/**
* Refresh the entire image.
*/
public final void refreshPaint() {
Status.getLogger().finest("refreshing PaintLabel. \nValues: "
+ "\n\tgetSize:\t" + getSize() + " vs. " + super.getSize()
+ "\n\tgetLocation:\t" + getLocation()
+ " vs. " + super.getLocation()
+ "\n\t" + "_x:\t\t"
+ "\n\t" + "_y\t\t"
+ "\n\t" + "_width\t\t" + getWidth()
+ "\n\t" + "_height\t\t" + getHeight() + "\n");
//paint the painted stuff at graphics
setBi(Picture.getInstance().updateRectangle(
-getLocation().x,
-getLocation().y, getWidth() , getHeight(), 0, 0, getBi()));
//paint the painting background (e.g. raster / lines) at the graphical
//user interface.
if (Page.getInstance().getJlbl_background2().getWidth() != 0
&& Page.getInstance().getJlbl_background2().getHeight() != 0) {
BufferedImage ret = new BufferedImage(
Page.getInstance().getJlbl_background2().getWidth(),
Page.getInstance().getJlbl_background2().getHeight(),
BufferedImage.TYPE_INT_ARGB);
ret = Picture.getInstance().emptyRectangle(
-getLocation().x,
-getLocation().y, getWidth(), getHeight(), 0, 0, ret);
Page.getInstance().getJlbl_background2().setIcon(
new ImageIcon((Utils.getBackground(ret, -getLocation().x,
-getLocation().y, -getLocation().x + getWidth(),
-getLocation().y + getHeight(), 0, 0))));
}
setIcon(new ImageIcon(getBi()));
PaintObjects.getInstance().repaint();
}
@Override public final void repaint() {
super.repaint();
PaintObjects.getInstance().repaint();
New.getInstance().setVisible(false);
}
/**
* das gleiche wie unten nur mut zoom rec.t.
* @param _x the x coordinate in view
* @param _y the y coordinate in view
* @param _width the width
* @param _height the height
*/
public final void paintZoom(final int _x, final int _y,
final int _width, final int _height) {
BufferedViewer.show(getBi());
Page.getInstance().getJlbl_border().setBounds(_x, _y, _width, _height);
}
/**
* Paint the entire selection stuff.
* @param _r the rectangle which is selected.
*/
public final void paintEntireSelectionRect(final Rectangle _r) {
//close old border thread.
if (thrd_moveBorder != null) {
thrd_moveBorder.interrupt();
repaint();
}
//initialize the thread and start it.
thrd_moveBorder = new BorderThread(_r, true, null, null);
thrd_moveBorder.start();
//paint the background
// BufferedImage bi_fresh = Page.getInstance().getEmptyBI();
// Utils.paintRastarBlock(bi_fresh,
// ViewSettings.SELECTION_BACKGROUND_CLR, _r);
//show resize buttons
for (int a = 0; a < Page.getInstance().getJbtn_resize().length; a++) {
for (int b = 0; b < Page.getInstance().getJbtn_resize().length;
b++) {
//size of JButton
final int b_size = Page.getInstance().getJbtn_resize()[a][b]
.getWidth();
Page.getInstance().getJbtn_resize()[a][b]
.setLocation(_r.x + _r.width * a / 2 - b_size / 2,
_r.y + _r.height * b / 2 - b_size / 2);
}
}
Page.getInstance().getJlbl_border().setBounds(_r);
}
/**
* repaint a special rectangle.
* @param _x the x coordinate in view
* @param _y the y coordinate in view
* @param _width the width
* @param _height the height
* @return the graphics
*/
public final BufferedImage refreshRectangle(final int _x, final int _y,
final int _width, final int _height) {
System.out.println("refreshing PaintLabel. \nValues: "
+ "\n\tgetSize:\t" + getSize() + " vs. " + super.getSize()
+ "\n\tgetLocation:\t" + getLocation()
+ " vs. " + super.getLocation()
+ "\n\t" + "_x:\t\t" + _x
+ "\n\t" + "_y\t\t" + _y
+ "\n\t" + "_width\t\t" + _width
+ "\n\t" + "_height\t\t" + _height + "\n");
//paint the painted stuff at graphics
setBi(Picture.getInstance().updateRectangle(
-getLocation().x + _x,
-getLocation().y + _y, _width, _height, _x, _y, getBi()));
setIcon(new ImageIcon(getBi()));
PaintObjects.getInstance().repaint();
return getBi();
}
/**
* Not necessary.
*/
public void refreshPopup() {
//not necessary anymore because paitned to bi and autorefreshes.
// refreshPaint();
}
/**
* Paint a zoom box.
*
* @param _x the x coordinate
* @param _y the y coordinate
* @param _width the width
* @param _height the height
*/
public final void setZoomBox(final int _x, final int _y,
final int _width, final int _height) {
paintZoom(_x, _y, _width, _height);
}
/*
* Location is not set directly because the paint methods shell be able
* to decide for themselves what to paint at which position.
*
* Thus, the methods for changing the location and for getting it are
* overwritten and alter / return the locally saved location.
*
* methods for changing location:
*/
/**
* in here, the location is not set as usual, but just the values
* for x and y location are saved. Thus, the painting methods
* are able to calculate for themselves what to paint at what position.
* @param _x the new x coordinate which is saved
* @param _y the new y coordinate which is saved
*/
@Override public final void setLocation(final int _x, final int _y) {
//update the JPanel location because the ScrollPane fetches information
//out of that panel
jpnl_toMove.setBounds(_x, _y, jpnl_toMove.getWidth(),
jpnl_toMove.getHeight());
//if something changed, repaint
if (_x != x || _y != y) {
if (isVisible()) {
int maintainStartX = 0,
maintainStartY = 0,
maintainWidth = bi.getWidth(),
maintainHeight = bi.getHeight();
int shiftedStartX = 0,
shiftedStartY = 0;
//move to the right (new location is greater than the old one)
if (_x > x) {
shiftedStartX = _x - x;
maintainStartX = 0;
maintainWidth = bi.getWidth() - shiftedStartX;
} else if (_x < x) {
shiftedStartX = 0;
maintainStartX = x - _x;
maintainWidth = bi.getWidth() - maintainStartX;
}
//moved up (old location is greater than new location)
if (_y > y) {
shiftedStartY = _y - y;
maintainStartY = 0;
maintainHeight = bi.getHeight() - shiftedStartY;
} else if (_y < y) {
shiftedStartY = 0;
// maintainStartY = _x - x;
maintainStartY = y - _y;
maintainHeight = bi.getHeight() - maintainStartY;
}
/*
* shift the maintained stuff
*/
System.out.println("maintain:\tnew\n"
+ "x:\t" + maintainStartX
+ "\t" + shiftedStartX
+ "\ny: \t" + maintainStartY
+ "\t" + shiftedStartY
// + "\n\nw:\t" + maintainWidth
// + "\nh:\t" + maintainHeight
);
//fetch the the RGB array of the subImage which is to be
//maintained but moved somewhere.
int[] rgbArray = new int[maintainWidth * maintainHeight];
rgbArray = bi.getRGB(maintainStartX,
maintainStartY,
maintainWidth,
maintainHeight,
rgbArray, 0, maintainWidth);
//write the maintained RGB array to shifted coordinates.
bi.setRGB(shiftedStartX,
shiftedStartY,
maintainWidth,
maintainHeight,
rgbArray, 0, maintainWidth);
setBi(bi );
setIcon(new ImageIcon(bi));
/*
* paint the new stuff.
* The rectangle location is the complement of the maintained
* in size of bufferedImage.
*/
//Refresh both in direction of width and of height.
//In the simplest way of doing this, there may be an area which
//is painted twice (depicted with '!').
//For further optimization of displaying speed this should be
//eliminated by the way of refreshing done beneath the picture.
//Picture:
// shiftedStartY == 0
// | ! W W W W | | H x |
// | H x x x x | | H x |
// | H x | | H x |
// | H x | | H x |
// | H x | | H x x x x |
// | W W W W! !| | x H H |
// | x x x x H | | x H H |
// | x H | | x H H |
// | x H | | x H H |
// | x H | | x x x H H |
/*
* Width
*/
//here the (!) are painted!
int refreshWidthWidth = bi.getWidth();
int refreshWidthHeight = bi.getHeight() - maintainHeight;
int refreshWidthY = 0;
int refreshWidthX = 0;
if (shiftedStartY == 0) {
refreshWidthY = maintainHeight;
}
/*
* height
*/
int refreshHeightWidth = bi.getWidth() - maintainWidth;
int refreshHeightHeight = bi.getHeight() - refreshWidthHeight;
int refreshHeightY = 0;
int refreshHeightX = 0;
if (shiftedStartY == 0) {
refreshHeightY = 0;
} else {
refreshHeightY = shiftedStartY;
}
refreshHeightX = shiftedStartX;
//save values
this.x = _x;
this.y = _y;
for (int xw = 0; xw < refreshWidthWidth; xw ++) {
for (int yw = 0; yw < refreshWidthHeight; yw ++) {
bi.setRGB(xw + refreshWidthX,
yw + refreshWidthY,
Color.red.getRGB());
}
}
for (int xw = 0; xw < refreshHeightWidth; xw ++) {
for (int yw = 0; yw < refreshHeightHeight; yw ++) {
bi.setRGB(xw + refreshHeightX,
yw + refreshHeightY,
Color.green.getRGB());
}
}
//BufferedImage
// refreshRectangle(refreshWidthX, refreshWidthY,
// refreshWidthWidth, refreshWidthHeight);
refreshRectangle(refreshHeightX, refreshHeightY,
refreshHeightWidth, refreshHeightHeight);
}
//save values
this.x = _x;
this.y = _y;
if (isVisible()) {
// refreshPaint();
}
}
}
/**
* Really set the location.
* @param _x the new x coordinate which is saved
* @param _y the new y coordinate which is saved
*/
public final void setLoc(final int _x, final int _y) {
//if something changed, repaint
super.setLocation(_x, _y);
}
/**
* in here, the location is not set as usual, but just the values
* for x and y location are saved. Thus, the painting methods
* are able to calculate for themselves what to paint at what position.
* @param _p the new coordinates which are saved
*/
@Override public final void setLocation(final Point _p) {
//save the new location
this.x = _p.x;
this.y = _p.y;
//update the JPanel location because the ScrollPane fetches information
//out of that panel
jpnl_toMove.setBounds(x, y, jpnl_toMove.getWidth(),
jpnl_toMove.getHeight());
if (isVisible()) {
//set changed
refreshPaint();
}
}
/**
* set the size of the JLabel and save the new location. Location is not
* set because the paint methods shell be able to decide for themselves
* what to paint at which position.
*
* @param _x the x coordinate which is saved
* @param _y the y coordinate which is saved
* @param _widht the width which is set
* @param _height the height which is set
*/
@Override public final void setBounds(final int _x, final int _y,
final int _widht, final int _height) {
//save the new location
this.x = _x;
this.y = _y;
//update the JPanel location because the ScrollPane fetches information
//out of that panel
jpnl_toMove.setBounds(_x, _y, jpnl_toMove.getWidth(),
jpnl_toMove.getHeight());
//set width and height.
super.setBounds(0, 0, _widht, _height);
bi = new BufferedImage(_widht, _height, BufferedImage.TYPE_INT_ARGB);
if (isVisible()) {
//set changed
refreshPaint();
}
}
/**
* Paint line selection.
* @param _po the PaintObject.
* @param _pen the pen.
*/
public final void paintSelection(final PaintObject _po,
final PenSelection _pen) {
//interrupt border thread.
stopBorderThread();
//initialize the thread and start it.
thrd_moveBorder = new BorderThread(null, false, _po, _pen);
thrd_moveBorder.start();
//paint the background
}
/**
* Stop the border - thread.
*/
public final void stopBorderThread() {
//close old border thread.
if (thrd_moveBorder != null) {
thrd_moveBorder.interrupt();
}
}
/*
* methods for getting location
*/
/**
* @return the real coordinate!
*/
@Deprecated
@Override public final int getX() {
return super.getX();
}
/**
* @return the real coordinate!
*/
@Deprecated
@Override public final int getY() {
return super.getY();
}
/**
* returns the saved but not applied x and y coordinates.
* @return the saved but not applied x and y coordinates (point).
*/
@Override public final Point getLocation() {
return new Point(x, y);
}
/**
* returns the saved but not applied x and y coordinates together with the
* applied size in a rectangle.
* @return the saved but not applied x and y coordinates together with the
* applied size in a rectangle.
*/
@Override public final Rectangle getBounds() {
return new Rectangle(x, y, getWidth(), getHeight());
}
/**
* @return the bi
*/
public final BufferedImage getBi() {
return bi;
}
/**
* @param _bi the _bi to set
*/
public final void setBi(final BufferedImage _bi) {
this.bi = _bi;
}
} |
package com.gravity.root;
import org.newdawn.slick.AppGameContainer;
import org.newdawn.slick.GameContainer;
import org.newdawn.slick.Graphics;
import org.newdawn.slick.SlickException;
import org.newdawn.slick.state.StateBasedGame;
import com.google.common.collect.Lists;
import com.gravity.levels.LevelInfo;
/**
* Main root class for the entire game. In order to add levels to the game, please add an entry to the levels table below, using the style of previous
* levels before you. Namely:
*
* <pre>
* <code>
* new LevelInfo("Level Title", "Short Description for us", "path/to/level", levelID),
* </code>
* </pre>
*
* The level id can be any number greater than 1000 which is not used by another level already. Try to be sane about it and pick the next highest one.
* ^_^
*
* @author dxiao
*/
public class PlatformerGame extends StateBasedGame {
public static final int WIDTH = 1024;
public static final int HEIGHT = 768;
//@formatter:off
private LevelInfo[] levels = {
// Very Hard (1)
new LevelInfo("Moving", VictoryText.MOVING, "assets/Levels/moving.tmx"),
// Impossible
new LevelInfo("Falling", VictoryText.FALLING, "assets/Levels/falling.tmx"),
new LevelInfo("Split World", VictoryText.SLINGSHOT, "assets/Levels/split_world.tmx"),
// Very Hard (1)
new LevelInfo("Bouncy 2", VictoryText.BOUNCY2, "assets/Levels/Bouncy_2.tmx"),
// Hard (4)
new LevelInfo("Bouncy 1", VictoryText.BOUNCY1, "assets/Levels/Bouncy_1.tmx"),
//new LevelInfo("Test Stomps", VictoryText.TEST, "assets/Levels/checkpointing.tmx"),
//new LevelInfo("Checkpointing", VictoryText.TEST, "assets/Levels/checkpointing.tmx"),
// Medium (4)
new LevelInfo("Elevators", VictoryText.ELEVATORS, "assets/levels/Elevators.tmx"),
new LevelInfo("Shortcuts", VictoryText.SHORTCUTS, "assets/levels/shortcuts.tmx"),
new LevelInfo("Slingshot", VictoryText.SLINGSHOT, "assets/Levels/slingshot_intro.tmx"),
new LevelInfo("Platformer", VictoryText.PLATFORMER, "assets/Levels/platform.tmx"),
// Easy (2)
new LevelInfo("Lab Procedures", VictoryText.PROCEDURES, "assets/Levels/intro_tutorial.tmx"),
new LevelInfo("Lab Safety", VictoryText.SAFETY, "assets/Levels/enemies_tutorial.tmx"),
};
//@formatter:on
public PlatformerGame() {
super("Psychic Psycho Bunnies v1.1");
}
@Override
public void initStatesList(GameContainer gc) throws SlickException {
addState(new GameLoaderState(Lists.newArrayList(levels), 100));
}
@Override
protected void preRenderState(GameContainer container, Graphics g) throws SlickException {
g.translate((container.getWidth() - 1024) / 2,
(container.getHeight() - 768) / 2);
g.setWorldClip(0, 0, WIDTH, HEIGHT);
}
public static void main(String args[]) throws SlickException {
AppGameContainer app = new AppGameContainer(new PlatformerGame());
app.setDisplayMode(1024, 768, false);
app.setMaximumLogicUpdateInterval(100);
app.setMinimumLogicUpdateInterval(10);
app.setTargetFrameRate(60);
app.setShowFPS(false);
app.setAlwaysRender(true);
app.setVSync(true);
if (app.supportsMultiSample()) {
app.setMultiSample(4);
}
// app.setSmoothDeltas(true);
boolean isDebugging = false;
try {
isDebugging |= java.lang.management.ManagementFactory.getRuntimeMXBean().getInputArguments().toString().indexOf("-agentlib:jdwp") > 0;
} catch (Exception e) {
e.printStackTrace();
}
isDebugging |= args.length > 0 && args[0].equals("nofullscreen");
if (!isDebugging) {
app.setDisplayMode(1280, 800, true);
}
app.start();
}
} |
package budgetio.services.impl;
import java.util.List;
import java.util.ResourceBundle;
import me.figo.FigoSession;
import me.figo.models.Account;
import me.figo.models.AccountBalance;
import me.figo.models.Bank;
import me.figo.models.Notification;
import me.figo.models.Payment;
import me.figo.models.PaymentProposal;
import me.figo.models.Security;
import me.figo.models.Transaction;
import me.figo.models.User;
import org.springframework.stereotype.Service;
import budgetio.services.FigoService;
/**
* The FigoServiceImpl.java. This service is meant to act as a wrapper over the FigoSession.java from the Figo API SDK.
*
* @author Dragos Dobromir
*/
@Service("figoServiceImpl")
public class FigoServiceImpl implements FigoService {
/** The Constant BUNDLE. */
private static final ResourceBundle BUNDLE = ResourceBundle.getBundle("resourceBundle");
private static final String ACCESS_TOKEN = "figo.access.token";
/** Sample Figo session from the Figo SDK. */
private static final FigoSession figoSession = new FigoSession(BUNDLE.getString(ACCESS_TOKEN), 60000);
public static void main(final String... args) {
final FigoServiceImpl figo = new FigoServiceImpl();
final User user = figo.getUser();
System.out.println("User: " + user);
final List<Transaction> transactions = figo.getTransactions();
System.out.println("Transactions: " + transactions);
final List<Account> accounts = figo.getAccounts();
System.out.println("Account: " + accounts);
final List<Notification> notifications = figo.getNotifications();
System.out.println("Notifications: " + notifications);
final List<Payment> payments = figo.getPayments();
System.out.println("Payments: " + payments);
// final List<PaymentProposal> paymentProposals = figo.getPaymentProposals();
// System.out.println("Payment Proposals: " + paymentProposals);
// final List<Security> securities = figo.getSecurities();
// System.out.println("Securities: " + securities);
}
@Override
public User getUser() {
User response = null;
try {
response = FigoServiceImpl.figoSession.getUser();
} catch (final Exception e) {
e.printStackTrace();
}
return response;
}
@Override
public Account getAccount(final String accountId) {
Account response = null;
try {
response = FigoServiceImpl.figoSession.getAccount(accountId);
} catch (final Exception e) {
e.printStackTrace();
}
return response;
}
@Override
public List<Account> getAccounts() {
List<Account> response = null;
try {
response = FigoServiceImpl.figoSession.getAccounts();
} catch (final Exception e) {
e.printStackTrace();
}
return response;
}
@Override
public AccountBalance getAccountBalance(final String accountId) {
AccountBalance response = null;
try {
response = FigoServiceImpl.figoSession.getAccountBalance(accountId);
} catch (final Exception e) {
e.printStackTrace();
}
return response;
}
@Override
public Transaction getTransaction(final String accountId, final String transactionId) {
Transaction response = null;
try {
response = FigoServiceImpl.figoSession.getTransaction(accountId, transactionId);
} catch (final Exception e) {
e.printStackTrace();
}
return response;
}
@Override
public List<Transaction> getTransactions(final String accountId) {
List<Transaction> response = null;
try {
response = FigoServiceImpl.figoSession.getTransactions(accountId);
} catch (final Exception e) {
e.printStackTrace();
}
return response;
}
@Override
public List<Transaction> getTransactions() {
List<Transaction> response = null;
try {
response = FigoServiceImpl.figoSession.getTransactions();
} catch (final Exception e) {
e.printStackTrace();
}
return response;
}
@Override
public Bank getBank(final String bankId) {
Bank response = null;
try {
response = FigoServiceImpl.figoSession.getBank(bankId);
} catch (final Exception e) {
e.printStackTrace();
}
return response;
}
@Override
public Notification getNotification(final String notificationId) {
Notification response = null;
try {
response = FigoServiceImpl.figoSession.getNotification(notificationId);
} catch (final Exception e) {
e.printStackTrace();
}
return response;
}
@Override
public List<Notification> getNotifications() {
List<Notification> response = null;
try {
response = FigoServiceImpl.figoSession.getNotifications();
} catch (final Exception e) {
e.printStackTrace();
}
return response;
}
@Override
public Payment getPayment(final String accountId, final String paymentId) {
Payment response = null;
try {
response = FigoServiceImpl.figoSession.getPayment(accountId, paymentId);
} catch (final Exception e) {
e.printStackTrace();
}
return response;
}
@Override
public List<Payment> getPayments(final String accountId) {
List<Payment> response = null;
try {
response = FigoServiceImpl.figoSession.getPayments(accountId);
} catch (final Exception e) {
e.printStackTrace();
}
return response;
}
@Override
public List<Payment> getPayments() {
List<Payment> response = null;
try {
response = FigoServiceImpl.figoSession.getPayments();
} catch (final Exception e) {
e.printStackTrace();
}
return response;
}
@Override
public List<PaymentProposal> getPaymentProposals() {
List<PaymentProposal> response = null;
try {
response = FigoServiceImpl.figoSession.getPaymentProposals();
} catch (final Exception e) {
e.printStackTrace();
}
return response;
}
@Override
public List<me.figo.models.Service> getSupportedServices(final String countryCode) {
List<me.figo.models.Service> response = null;
try {
response = FigoServiceImpl.figoSession.getSupportedServices(countryCode);
} catch (final Exception e) {
e.printStackTrace();
}
return response;
}
@Override
public Security getSecurity(final String accountId, final String securityId) {
Security response = null;
try {
response = FigoServiceImpl.figoSession.getSecurity(accountId, securityId);
} catch (final Exception e) {
e.printStackTrace();
}
return response;
}
@Override
public List<Security> getSecurities(final String accountId) {
List<Security> response = null;
try {
response = FigoServiceImpl.figoSession.getSecurities(accountId);
} catch (final Exception e) {
e.printStackTrace();
}
return response;
}
@Override
public List<Security> getSecurities() {
List<Security> response = null;
try {
response = FigoServiceImpl.figoSession.getSecurities();
} catch (final Exception e) {
e.printStackTrace();
}
return response;
}
} |
package org.xtreemfs.mrc.utils;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import org.xtreemfs.common.ReplicaUpdatePolicies;
import org.xtreemfs.common.uuids.ServiceUUID;
import org.xtreemfs.common.uuids.UnknownUUIDException;
import org.xtreemfs.common.xloc.ReplicationFlags;
import org.xtreemfs.foundation.json.JSONException;
import org.xtreemfs.foundation.json.JSONParser;
import org.xtreemfs.foundation.logging.Logging;
import org.xtreemfs.foundation.logging.Logging.Category;
import org.xtreemfs.foundation.pbrpc.generatedinterfaces.RPC.POSIXErrno;
import org.xtreemfs.foundation.util.OutputUtils;
import org.xtreemfs.mrc.MRCConfig;
import org.xtreemfs.mrc.MRCException;
import org.xtreemfs.mrc.UserException;
import org.xtreemfs.mrc.ac.FileAccessManager;
import org.xtreemfs.mrc.database.AtomicDBUpdate;
import org.xtreemfs.mrc.database.DatabaseException;
import org.xtreemfs.mrc.database.DatabaseResultSet;
import org.xtreemfs.mrc.database.StorageManager;
import org.xtreemfs.mrc.database.VolumeInfo;
import org.xtreemfs.mrc.database.VolumeManager;
import org.xtreemfs.mrc.metadata.FileMetadata;
import org.xtreemfs.mrc.metadata.ReplicationPolicy;
import org.xtreemfs.mrc.metadata.StripingPolicy;
import org.xtreemfs.mrc.metadata.XAttr;
import org.xtreemfs.mrc.metadata.XLoc;
import org.xtreemfs.mrc.metadata.XLocList;
import org.xtreemfs.mrc.osdselection.OSDStatusManager;
import org.xtreemfs.pbrpc.generatedinterfaces.DIR.Service;
import org.xtreemfs.pbrpc.generatedinterfaces.DIR.ServiceDataMap;
import org.xtreemfs.pbrpc.generatedinterfaces.DIR.ServiceSet;
import org.xtreemfs.pbrpc.generatedinterfaces.DIR.ServiceType;
import org.xtreemfs.pbrpc.generatedinterfaces.GlobalTypes.KeyValuePair;
import org.xtreemfs.pbrpc.generatedinterfaces.GlobalTypes.VivaldiCoordinates;
public class MRCHelper {
public static class GlobalFileIdResolver {
final String volumeId;
final long localFileId;
public GlobalFileIdResolver(String globalFileId) throws UserException {
try {
int i = globalFileId.indexOf(':');
volumeId = globalFileId.substring(0, i);
localFileId = Long.parseLong(globalFileId.substring(i + 1));
} catch (Exception exc) {
throw new UserException(POSIXErrno.POSIX_ERROR_EINVAL, "invalid global file ID: " + globalFileId
+ "; expected pattern: <volume_ID>:<local_file_ID>");
}
}
public String getVolumeId() {
return volumeId;
}
public long getLocalFileId() {
return localFileId;
}
}
public static final String POLICY_ATTR_PREFIX = "policies";
public static final String VOL_ATTR_PREFIX = "volattr";
public static final String XTREEMFS_POLICY_ATTR_PREFIX = "xtreemfs." + POLICY_ATTR_PREFIX + ".";
public enum SysAttrs {
locations,
file_id,
object_type,
url,
owner,
group,
default_sp,
ac_policy_id,
rsel_policy,
osel_policy,
usable_osds,
free_space,
used_space,
num_files,
num_dirs,
snapshots,
snapshots_enabled,
snapshot_time,
acl,
read_only,
mark_replica_complete,
set_repl_update_policy,
default_rp
}
public enum FileType {
nexists, dir, file
}
public static Service createDSVolumeInfo(VolumeInfo vol, OSDStatusManager osdMan, StorageManager sMan,
String mrcUUID) {
String free = String.valueOf(osdMan.getFreeSpace(vol.getId()));
String volSize = null;
try {
volSize = String.valueOf(sMan.getVolumeInfo().getVolumeSize());
} catch (DatabaseException e) {
Logging.logMessage(Logging.LEVEL_WARN, Category.storage, null,
"could not retrieve volume size from database for volume '%s': %s",
new Object[] { vol.getName(), e.toString() });
}
ServiceDataMap.Builder dmap = buildServiceDataMap("mrc", mrcUUID, "free", free, "used", volSize);
try {
DatabaseResultSet<XAttr> attrIt = sMan.getXAttrs(1, StorageManager.SYSTEM_UID);
while (attrIt.hasNext()) {
XAttr attr = attrIt.next();
if (attr.getKey().startsWith("xtreemfs.volattr.")) {
byte[] value = attr.getValue();
dmap.addData(KeyValuePair.newBuilder()
.setKey("attr." + attr.getKey().substring("xtreemfs.volattr.".length()))
.setValue(value == null ? null : new String(value)));
}
}
attrIt.destroy();
} catch (DatabaseException e) {
Logging.logMessage(Logging.LEVEL_ERROR, Category.storage, null, OutputUtils.stackTraceToString(e),
new Object[0]);
}
Service sreg = Service.newBuilder().setType(ServiceType.SERVICE_TYPE_VOLUME).setUuid(vol.getId()).setVersion(0)
.setName(vol.getName()).setData(dmap).setLastUpdatedS(0).build();
return sreg;
}
public static int updateFileTimes(long parentId, FileMetadata file, boolean setATime, boolean setCTime,
boolean setMTime, StorageManager sMan, int currentTime, AtomicDBUpdate update) throws DatabaseException {
if (parentId == -1)
return -1;
if (setATime)
file.setAtime(currentTime);
if (setCTime)
file.setCtime(currentTime);
if (setMTime)
file.setMtime(currentTime);
sMan.setMetadata(file, FileMetadata.FC_METADATA, update);
return currentTime;
}
public static XLoc createReplica(StripingPolicy stripingPolicy, StorageManager sMan, OSDStatusManager osdMan,
VolumeInfo volume, long parentDirId, String path, InetAddress clientAddress,
VivaldiCoordinates clientCoordinates, XLocList currentXLoc, int replFlags) throws DatabaseException,
UserException, MRCException {
// if no striping policy is provided, try to retrieve it from the parent
// directory
if (stripingPolicy == null)
stripingPolicy = sMan.getDefaultStripingPolicy(parentDirId);
// if the parent directory has no default policy, take the one
// associated with the volume
if (stripingPolicy == null)
stripingPolicy = sMan.getDefaultStripingPolicy(1);
if (stripingPolicy == null)
throw new UserException(POSIXErrno.POSIX_ERROR_EIO, "could not open file " + path
+ ": no default striping policy available");
// determine the set of OSDs to be assigned to the replica
ServiceSet.Builder usableOSDs = osdMan.getUsableOSDs(volume.getId(), clientAddress, clientCoordinates,
currentXLoc, stripingPolicy.getWidth());
if (usableOSDs == null || usableOSDs.getServicesCount() == 0) {
Logging.logMessage(Logging.LEVEL_WARN, Category.all, (Object) null,
"no suitable OSDs available for file %s", path);
throw new UserException(POSIXErrno.POSIX_ERROR_EIO, "could not assign OSDs to file " + path
+ ": no feasible OSDs available");
}
// determine the actual striping width; if not enough OSDs are
// available, the width will be limited to the amount of available OSDs
int width = Math.min(stripingPolicy.getWidth(), usableOSDs.getServicesCount());
// convert the set of OSDs to a string array of OSD UUIDs
List<Service> osdServices = usableOSDs.getServicesList();
String[] osds = new String[width];
for (int i = 0; i < width; i++)
osds[i] = osdServices.get(i).getUuid();
if (width != stripingPolicy.getWidth())
stripingPolicy = sMan.createStripingPolicy(stripingPolicy.getPattern(), stripingPolicy.getStripeSize(),
width);
return sMan.createXLoc(stripingPolicy, osds, replFlags);
}
/**
* Checks whether the given replica (i.e. list of OSDs) can be added to the
* given X-Locations list without compromising consistency.
*
* @param xLocList
* the X-Locations list
* @param newOSDs
* the list of new OSDs to add
* @return <tt>true</tt>, if adding the OSD list is possible, <tt>false</tt>
* , otherwise
*/
public static boolean isAddable(XLocList xLocList, List<String> newOSDs) {
if (xLocList != null)
for (int i = 0; i < xLocList.getReplicaCount(); i++) {
XLoc replica = xLocList.getReplica(i);
for (int j = 0; j < replica.getOSDCount(); j++)
for (String newOsd : newOSDs)
if (replica.getOSD(j).equals(newOsd))
return false;
}
return true;
}
/**
* Checks whether all service UUIDs from the list can be resolved, i.e.
* refer to valid services.
*
* @param newOSDs
* the list of OSDs
* @return <tt>true</tt>, if all OSDs are resolvable, <tt>false</tt>,
* otherwise
*/
public static boolean isResolvable(List<String> newOSDs) {
if (newOSDs != null)
for (String osd : newOSDs) {
try {
new ServiceUUID(osd).getAddress();
} catch (Exception exc) {
return false;
}
}
return true;
}
/**
* Checks whether the given X-Locations list is consistent. It is regarded
* as consistent if no OSD in any replica occurs more than once.
*
* @param xLocList
* the X-Locations list to check for consistency
* @return <tt>true</tt>, if the list is consistent, <tt>false</tt>,
* otherwise
*/
public static boolean isConsistent(XLocList xLocList) {
Set<String> tmp = new HashSet<String>();
if (xLocList != null) {
for (int i = 0; i < xLocList.getReplicaCount(); i++) {
XLoc replica = xLocList.getReplica(i);
for (int j = 0; j < replica.getOSDCount(); j++) {
String osd = replica.getOSD(j);
if (!tmp.contains(osd))
tmp.add(osd);
else
return false;
}
}
}
return true;
}
public static String getSysAttrValue(MRCConfig config, StorageManager sMan, OSDStatusManager osdMan,
FileAccessManager faMan, String path, FileMetadata file, String keyString) throws DatabaseException,
UserException, JSONException {
if (keyString.startsWith(POLICY_ATTR_PREFIX + "."))
return getPolicyValue(sMan, keyString);
if (keyString.startsWith(VOL_ATTR_PREFIX + "."))
return getVolAttrValue(sMan, keyString);
SysAttrs key = null;
try {
key = SysAttrs.valueOf(keyString);
} catch (IllegalArgumentException exc) {
throw new UserException(POSIXErrno.POSIX_ERROR_EINVAL, "unknown system attribute '" + keyString + "'");
}
if (key != null) {
switch (key) {
case locations:
if (file.isDirectory()) {
return "";
} else {
XLocList xLocList = file.getXLocList();
try {
return xLocList == null ? "" : Converter.xLocListToJSON(xLocList, osdMan);
} catch (UnknownUUIDException exc) {
throw new UserException(POSIXErrno.POSIX_ERROR_EIO, "cannot retrieve '"
+ SysAttrs.locations.name() + "' attribute value: " + exc);
}
}
case file_id:
return sMan.getVolumeInfo().getId() + ":" + file.getId();
case object_type:
String ref = sMan.getSoftlinkTarget(file.getId());
return ref != null ? "3" : file.isDirectory() ? "2" : "1";
case url: {
InetSocketAddress addr = config.getDirectoryService();
final String hostname = (config.getHostName().length() > 0) ? config.getHostName() : addr.getAddress()
.getCanonicalHostName();
return config.getURLScheme() + "://" + hostname + ":" + addr.getPort() + "/" + path;
}
case owner:
return file.getOwnerId();
case group:
return file.getOwningGroupId();
case default_sp:
if (!file.isDirectory())
return "";
StripingPolicy sp = sMan.getDefaultStripingPolicy(file.getId());
if (sp == null)
return "";
return Converter.stripingPolicyToJSONString(sp);
case ac_policy_id:
return file.getId() == 1 ? sMan.getVolumeInfo().getAcPolicyId() + "" : "";
case osel_policy:
return file.getId() == 1 ? Converter.shortArrayToString(sMan.getVolumeInfo().getOsdPolicy()) : "";
case rsel_policy:
return file.getId() == 1 ? Converter.shortArrayToString(sMan.getVolumeInfo().getReplicaPolicy()) : "";
case read_only:
if (file.isDirectory())
return "";
return String.valueOf(file.isReadOnly());
case usable_osds: {
// only return a value for the volume root
if (file.getId() != 1)
return "";
try {
ServiceSet.Builder srvs = osdMan.getUsableOSDs(sMan.getVolumeInfo().getId());
Map<String, String> osds = new HashMap<String, String>();
for (Service srv : srvs.getServicesList()) {
ServiceUUID uuid = new ServiceUUID(srv.getUuid());
osds.put(uuid.toString(), uuid.getAddressString());
}
return JSONParser.writeJSON(osds);
} catch (UnknownUUIDException exc) {
throw new UserException(POSIXErrno.POSIX_ERROR_EIO, "cannot retrieve '"
+ SysAttrs.usable_osds.name() + "' attribute value: " + exc);
}
}
case free_space:
return file.getId() == 1 ? String.valueOf(osdMan.getFreeSpace(sMan.getVolumeInfo().getId())) : "";
case used_space:
return file.getId() == 1 ? String.valueOf(sMan.getVolumeInfo().getVolumeSize()) : "";
case num_files:
return file.getId() == 1 ? String.valueOf(sMan.getVolumeInfo().getNumFiles()) : "";
case num_dirs:
return file.getId() == 1 ? String.valueOf(sMan.getVolumeInfo().getNumDirs()) : "";
case snapshots: {
if (file.getId() != 1 || sMan.getVolumeInfo().isSnapVolume())
return "";
String[] snaps = sMan.getAllSnapshots();
Arrays.sort(snaps);
List<String> snapshots = new ArrayList<String>(snaps.length);
for (String snap : snaps) {
if (snap.equals(".dump"))
continue;
snapshots.add(snap);
}
return JSONParser.writeJSON(snapshots);
}
case snapshots_enabled:
return file.getId() == 1 && !sMan.getVolumeInfo().isSnapVolume() ? String.valueOf(sMan.getVolumeInfo()
.isSnapshotsEnabled()) : "";
case snapshot_time:
return file.getId() == 1 && sMan.getVolumeInfo().isSnapVolume() ? Long.toString(sMan.getVolumeInfo()
.getCreationTime()) : "";
case acl:
Map<String, Object> acl;
try {
acl = faMan.getACLEntries(sMan, file);
} catch (MRCException e) {
Logging.logError(Logging.LEVEL_ERROR, null, e);
throw new UserException(POSIXErrno.POSIX_ERROR_EINVAL);
}
if (acl != null) {
Map<String, Object> map = new HashMap<String, Object>();
for (Entry<String, Object> entry : acl.entrySet())
map.put(entry.getKey(), "" + entry.getValue());
return JSONParser.writeJSON(map);
}
case default_rp:
if (!file.isDirectory())
return "";
ReplicationPolicy rp = sMan.getDefaultReplicationPolicy(file.getId());
if (rp == null)
return "";
return Converter.replicationPolicyToJSONString(rp);
}
}
return "";
}
public static void setSysAttrValue(StorageManager sMan, VolumeManager vMan, FileAccessManager faMan, long parentId,
FileMetadata file, String keyString, String value, AtomicDBUpdate update) throws UserException,
DatabaseException {
// handle policy-specific values
if (keyString.startsWith(POLICY_ATTR_PREFIX.toString() + ".")) {
setPolicyValue(sMan, keyString, value, update);
return;
}
SysAttrs key = null;
try {
key = SysAttrs.valueOf(keyString);
} catch (IllegalArgumentException exc) {
throw new UserException(POSIXErrno.POSIX_ERROR_EINVAL, "unknown system attribute '" + keyString + "'");
}
switch (key) {
case default_sp:
if (!file.isDirectory())
throw new UserException(POSIXErrno.POSIX_ERROR_EPERM,
"default striping policies can only be set on volumes and directories");
try {
org.xtreemfs.pbrpc.generatedinterfaces.GlobalTypes.StripingPolicy sp = null;
sp = Converter.jsonStringToStripingPolicy(value);
if (file.getId() == 1 && sp == null)
throw new UserException(POSIXErrno.POSIX_ERROR_EPERM,
"cannot remove the volume's default striping policy");
// check if striping + rw replication would be set
String replPolicy = sMan.getDefaultReplicationPolicy(file.getId()).getName();
if (sp != null
&& sp.getWidth() > 1
&& (replPolicy.equals(ReplicaUpdatePolicies.REPL_UPDATE_PC_WARONE) || replPolicy
.equals(ReplicaUpdatePolicies.REPL_UPDATE_PC_WQRQ))) {
throw new UserException(POSIXErrno.POSIX_ERROR_EINVAL,
"striping + rw-replication is not support yet.");
}
sMan.setDefaultStripingPolicy(file.getId(), sp, update);
} catch (JSONException exc) {
throw new UserException(POSIXErrno.POSIX_ERROR_EINVAL, "invalid default striping policy: " + value);
} catch (ClassCastException exc) {
throw new UserException(POSIXErrno.POSIX_ERROR_EINVAL, "invalid default striping policy: " + value);
} catch (NullPointerException exc) {
throw new UserException(POSIXErrno.POSIX_ERROR_EINVAL, "invalid default striping policy: " + value);
} catch (IllegalArgumentException exc) {
throw new UserException(POSIXErrno.POSIX_ERROR_EINVAL, "invalid default striping policy: " + value);
}
break;
case osel_policy:
if (file.getId() != 1)
throw new UserException(POSIXErrno.POSIX_ERROR_EINVAL,
"OSD selection policies can only be set on volumes");
try {
short[] newPol = Converter.stringToShortArray(value);
sMan.getVolumeInfo().setOsdPolicy(newPol, update);
} catch (NumberFormatException exc) {
throw new UserException(POSIXErrno.POSIX_ERROR_EINVAL, "invalid OSD selection policy: " + value);
}
break;
case rsel_policy:
if (file.getId() != 1)
throw new UserException(POSIXErrno.POSIX_ERROR_EINVAL,
"replica selection policies can only be set and configured on volumes");
try {
short[] newPol = Converter.stringToShortArray(value);
sMan.getVolumeInfo().setReplicaPolicy(newPol, update);
} catch (NumberFormatException exc) {
throw new UserException(POSIXErrno.POSIX_ERROR_EINVAL, "invalid replica selection policy: " + value);
}
break;
case read_only:
// TODO: unify w/ 'set_repl_update_policy'
if (file.isDirectory())
throw new UserException(POSIXErrno.POSIX_ERROR_EPERM, "only files can be made read-only");
boolean readOnly = Boolean.valueOf(value);
if (!readOnly && file.getXLocList() != null && file.getXLocList().getReplicaCount() > 1)
throw new UserException(POSIXErrno.POSIX_ERROR_EPERM,
"read-only flag cannot be removed from files with multiple replicas");
// set the update policy string in the X-Locations list to 'read
// only replication' and mark the first replica as 'full'
if (file.getXLocList() != null) {
XLocList xLoc = file.getXLocList();
XLoc[] replicas = new XLoc[xLoc.getReplicaCount()];
for (int i = 0; i < replicas.length; i++)
replicas[i] = xLoc.getReplica(i);
replicas[0].setReplicationFlags(ReplicationFlags.setFullReplica(ReplicationFlags
.setReplicaIsComplete(replicas[0].getReplicationFlags())));
XLocList newXLoc = sMan.createXLocList(replicas, readOnly ? ReplicaUpdatePolicies.REPL_UPDATE_PC_RONLY
: ReplicaUpdatePolicies.REPL_UPDATE_PC_NONE, xLoc.getVersion() + 1);
file.setXLocList(newXLoc);
sMan.setMetadata(file, FileMetadata.RC_METADATA, update);
}
// set the read-only flag
file.setReadOnly(readOnly);
sMan.setMetadata(file, FileMetadata.RC_METADATA, update);
break;
case snapshots:
if (!file.isDirectory())
throw new UserException(POSIXErrno.POSIX_ERROR_ENOTDIR,
"snapshots of single files are not allowed so far");
// value format: "c|cr|d| name"
// TODO: restrict to admin users
int index = value.indexOf(" ");
String command = null;
String name = null;
try {
command = value.substring(0, index);
name = value.substring(index + 1);
} catch (Exception exc) {
throw new UserException(POSIXErrno.POSIX_ERROR_EINVAL, "malformed snapshot configuration");
}
// create snapshot
if (command.charAt(0) == 'c')
vMan.createSnapshot(sMan.getVolumeInfo().getId(), name, parentId, file, command.equals("cr"));
// delete snapshot
else if (command.equals("d"))
vMan.deleteSnapshot(sMan.getVolumeInfo().getId(), file, name);
else
throw new UserException(POSIXErrno.POSIX_ERROR_EINVAL, "invalid snapshot command: " + value);
break;
case snapshots_enabled:
if (file.getId() != 1)
throw new UserException(POSIXErrno.POSIX_ERROR_EINVAL,
"snapshots can only be enabled or disabled on volumes");
boolean enable = Boolean.parseBoolean(value);
sMan.getVolumeInfo().setAllowSnaps(enable, update);
break;
case mark_replica_complete:
if (file.isDirectory())
throw new UserException(POSIXErrno.POSIX_ERROR_EISDIR, "file required");
XLocList xlocs = file.getXLocList();
XLoc[] xlocArray = new XLoc[xlocs.getReplicaCount()];
Iterator<XLoc> it = xlocs.iterator();
for (int i = 0; it.hasNext(); i++) {
XLoc xloc = it.next();
if (value.equals(xloc.getOSD(0)))
xloc.setReplicationFlags(ReplicationFlags.setReplicaIsComplete(xloc.getReplicationFlags()));
xlocArray[i] = xloc;
}
XLocList newXLocList = sMan.createXLocList(xlocArray, xlocs.getReplUpdatePolicy(), xlocs.getVersion());
file.setXLocList(newXLocList);
sMan.setMetadata(file, FileMetadata.RC_METADATA, update);
break;
case acl:
// parse the modification command
index = value.indexOf(" ");
try {
command = value.substring(0, index);
String params = value.substring(index + 1);
// modify an ACL entry
if (command.equals("m")) {
int index2 = params.lastIndexOf(':');
String entity = params.substring(0, index2);
String rights = params.substring(index2 + 1);
Map<String, Object> entries = new HashMap<String, Object>();
entries.put(entity, rights);
faMan.updateACLEntries(sMan, file, parentId, entries, update);
}
// remove an ACL entry
else if (command.equals("x")) {
List<Object> entries = new ArrayList<Object>(1);
entries.add(params);
faMan.removeACLEntries(sMan, file, parentId, entries, update);
} else
throw new UserException(POSIXErrno.POSIX_ERROR_EINVAL, "invalid ACL modification command: "
+ command);
} catch (MRCException e) {
Logging.logError(Logging.LEVEL_ERROR, null, e);
throw new UserException(POSIXErrno.POSIX_ERROR_EINVAL);
} catch (Exception exc) {
throw new UserException(POSIXErrno.POSIX_ERROR_EINVAL, "malformed ACL modification request");
}
break;
case set_repl_update_policy:
if (file.isDirectory())
throw new UserException(POSIXErrno.POSIX_ERROR_EISDIR, "file required");
xlocs = file.getXLocList();
xlocArray = new XLoc[xlocs.getReplicaCount()];
it = xlocs.iterator();
for (int i = 0; it.hasNext(); i++)
xlocArray[i] = it.next();
String replUpdatePolicy = xlocs.getReplUpdatePolicy();
// Check allowed policies.
if (!ReplicaUpdatePolicies.REPL_UPDATE_PC_WQRQ.equals(value)
&& !ReplicaUpdatePolicies.REPL_UPDATE_PC_WARONE.equals(value)
&& !ReplicaUpdatePolicies.REPL_UPDATE_PC_NONE.equals(value)
&& !ReplicaUpdatePolicies.REPL_UPDATE_PC_RONLY.equals(value))
throw new UserException(POSIXErrno.POSIX_ERROR_EINVAL, "Invalid replica update policy: " + value);
// WaRa was renamed to WaR1.
if (ReplicaUpdatePolicies.REPL_UPDATE_PC_WARA.equals(value)) {
throw new UserException(
POSIXErrno.POSIX_ERROR_EINVAL,
"Do no longer use the policy WaRa. Instead you're probably looking for the WaR1 policy (write all replicas, read from one)."
+ value);
}
if (ReplicaUpdatePolicies.REPL_UPDATE_PC_RONLY.equals(replUpdatePolicy) && xlocArray.length > 1)
throw new UserException(POSIXErrno.POSIX_ERROR_EINVAL,
"changing replica update policies of read-only-replicated files is not allowed");
if (ReplicaUpdatePolicies.REPL_UPDATE_PC_NONE.equals(value)) {
// if there are more than one replica, report an error
if (xlocs.getReplicaCount() > 1)
throw new UserException(POSIXErrno.POSIX_ERROR_EINVAL,
"number of replicas has to be reduced to 1 before replica update policy can be set to "
+ ReplicaUpdatePolicies.REPL_UPDATE_PC_NONE + " (current replica count = "
+ xlocs.getReplicaCount() + ")");
}
// Do not allow to switch between read-only and read/write replication
// as there are currently no mechanisms in place to guarantee that the replicas are synchronized.
if ((ReplicaUpdatePolicies.REPL_UPDATE_PC_RONLY.equals(replUpdatePolicy)
&& (ReplicaUpdatePolicies.REPL_UPDATE_PC_WQRQ.equals(value)
|| ReplicaUpdatePolicies.REPL_UPDATE_PC_WARONE.equals(value)))
||
(ReplicaUpdatePolicies.REPL_UPDATE_PC_RONLY.equals(value)
&& (ReplicaUpdatePolicies.REPL_UPDATE_PC_WQRQ.equals(replUpdatePolicy)
|| ReplicaUpdatePolicies.REPL_UPDATE_PC_WARONE.equals(replUpdatePolicy)))) {
throw new UserException(
POSIXErrno.POSIX_ERROR_EINVAL,
"Currently, it is not possible to change from a read-only to a read/write replication policy or vise versa.");
}
// Update replication policy in new xloc list.
newXLocList = sMan.createXLocList(xlocArray, value, xlocs.getVersion() + 1);
// mark the first replica in the list as 'complete' (only relevant
// for read-only replication)
if (ReplicaUpdatePolicies.REPL_UPDATE_PC_RONLY.equals(value)) {
newXLocList.getReplica(0).setReplicationFlags(
ReplicationFlags.setFullReplica(ReplicationFlags.setReplicaIsComplete(newXLocList.getReplica(0)
.getReplicationFlags())));
file.setReadOnly(true);
}
// check if striping + rw replication would be set
StripingPolicy stripingPolicy = file.getXLocList().getReplica(0).getStripingPolicy();
if (stripingPolicy.getWidth() > 1
&& (value.equals(ReplicaUpdatePolicies.REPL_UPDATE_PC_WARONE) || value
.equals(ReplicaUpdatePolicies.REPL_UPDATE_PC_WQRQ))) {
throw new UserException(POSIXErrno.POSIX_ERROR_EINVAL, "striping + rw-replication is not support yet.");
}
// Remove read only state of file if readonly policy gets reverted.
if (ReplicaUpdatePolicies.REPL_UPDATE_PC_RONLY.equals(replUpdatePolicy)
&& ReplicaUpdatePolicies.REPL_UPDATE_PC_NONE.equals(value)) {
file.setReadOnly(false);
}
// Write back updated file data.
file.setXLocList(newXLocList);
sMan.setMetadata(file, FileMetadata.RC_METADATA, update);
break;
case default_rp:
if (!file.isDirectory())
throw new UserException(POSIXErrno.POSIX_ERROR_EPERM,
"default replication policies can only be set on volumes and directories");
try {
ReplicationPolicy rp = null;
rp = Converter.jsonStringToReplicationPolicy(value);
if (rp.getFactor() == 1 && !ReplicaUpdatePolicies.REPL_UPDATE_PC_NONE.equals(rp.getName())) {
throw new UserException(POSIXErrno.POSIX_ERROR_EPERM,
"a default replication policy requires a replication factor >= 2");
}
// check if rw replication + striping would be set
if (sMan.getDefaultStripingPolicy(file.getId()).getWidth() > 1
&& (rp.getName().equals(ReplicaUpdatePolicies.REPL_UPDATE_PC_WARONE) || rp.getName().equals(
ReplicaUpdatePolicies.REPL_UPDATE_PC_WQRQ))) {
throw new UserException(POSIXErrno.POSIX_ERROR_EINVAL,
"striping + rw-replication is not support yet.");
}
sMan.setDefaultReplicationPolicy(file.getId(), rp, update);
} catch (JSONException exc) {
throw new UserException(POSIXErrno.POSIX_ERROR_EINVAL, "invalid default replication policy: " + value);
} catch (ClassCastException exc) {
throw new UserException(POSIXErrno.POSIX_ERROR_EINVAL, "invalid default replication policy: " + value);
} catch (NullPointerException exc) {
throw new UserException(POSIXErrno.POSIX_ERROR_EINVAL, "invalid default replication policy: " + value);
} catch (IllegalArgumentException exc) {
throw new UserException(POSIXErrno.POSIX_ERROR_EINVAL, "invalid default replication policy: " + value);
}
break;
default:
throw new UserException(POSIXErrno.POSIX_ERROR_EINVAL, "system attribute '" + keyString + "' is immutable");
}
}
public static List<String> getSpecialAttrNames(StorageManager sMan, String namePrefix) throws DatabaseException {
final String prefix = "xtreemfs." + namePrefix;
final List<String> result = new LinkedList<String>();
DatabaseResultSet<XAttr> it = sMan.getXAttrs(1, StorageManager.SYSTEM_UID);
while (it.hasNext()) {
XAttr attr = it.next();
if (attr.getKey().startsWith(prefix))
result.add(attr.getKey());
}
it.destroy();
return result;
}
public static ServiceDataMap.Builder buildServiceDataMap(String... kvPairs) {
assert (kvPairs.length % 2 == 0);
ServiceDataMap.Builder builder = ServiceDataMap.newBuilder();
for (int i = 0; i < kvPairs.length; i += 2) {
KeyValuePair.Builder kvp = KeyValuePair.newBuilder();
kvp.setKey(kvPairs[i]);
kvp.setValue(kvPairs[i + 1]);
builder.addData(kvp);
}
return builder;
}
private static String getPolicyValue(StorageManager sMan, String keyString) throws DatabaseException {
byte[] value = sMan.getXAttr(1, StorageManager.SYSTEM_UID, "xtreemfs." + keyString);
return value == null ? null : new String(value);
}
private static String getVolAttrValue(StorageManager sMan, String keyString) throws DatabaseException {
byte[] value = sMan.getXAttr(1, StorageManager.SYSTEM_UID, "xtreemfs." + keyString);
return value == null ? null : new String(value);
}
private static void setPolicyValue(StorageManager sMan, String keyString, String value, AtomicDBUpdate update)
throws DatabaseException, UserException {
// remove "policies."
String checkString = keyString.substring(POLICY_ATTR_PREFIX.length()+1);
int index = checkString.indexOf('.');
if (index <= 0) {
// remove trailing "."
if (keyString.startsWith(".")) {
keyString = keyString.substring(1);
}
throw new UserException(POSIXErrno.POSIX_ERROR_EPERM,
"'"+keyString+"="+value+" :' " +
"XtreemFS no longer supports global policy attributes. " +
"It is necessary to specify a policy e.g., '1000."+keyString+"="+value+"'");
}
// set the value in the database
byte[] bytes = value.getBytes();
sMan.setXAttr(1, StorageManager.SYSTEM_UID, "xtreemfs." + keyString, bytes == null || bytes.length == 0 ? null
: bytes, update);
}
} |
package za.co.cporm.model.generate;
import za.co.cporm.model.annotation.Index;
import za.co.cporm.model.annotation.TableConstraint;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import static za.co.cporm.model.generate.TableDetails.ColumnDetails;
/**
* The java object will be converted to a table details object and the supplied information is then used to generate the
* statements.
*/
public class TableGenerator {
public static String generateTableDrop(TableDetails tableDetails, boolean prettyPrint){
StringBuilder tableQuery = new StringBuilder();
prettyPrint(0, prettyPrint, tableQuery);
tableQuery.append("DROP TABLE IF EXISTS ");
tableQuery.append(tableDetails.getTableName());
tableQuery.append(";");
return tableQuery.toString();
}
public static String generateTableCreate(TableDetails tableDetails, boolean prettyPrint) {
StringBuilder tableQuery = new StringBuilder();
prettyPrint(0, prettyPrint, tableQuery);
tableQuery.append("CREATE TABLE ");
tableQuery.append(tableDetails.getTableName());
prettyPrint(1, prettyPrint, tableQuery);
tableQuery.append("(");
prettyPrint(1, prettyPrint, tableQuery);
Iterator<ColumnDetails> columnIterator = tableDetails.getColumns().iterator();
while(columnIterator.hasNext()) {
ColumnDetails columnDetails = columnIterator.next();
prettyPrint(2, prettyPrint, tableQuery);
tableQuery.append(createColumnDefinition(columnDetails));
if(columnIterator.hasNext()) tableQuery.append(", ");
}
Iterator<TableConstraint> tableConstraintIterator = tableDetails.getConstraints().iterator();
while (tableConstraintIterator.hasNext()) {
TableConstraint tableConstraint = tableConstraintIterator.next();
if(tableConstraint.constraintType() != TableConstraint.Type.PRIMARY_KEY)
continue;
prettyPrint(3, prettyPrint, tableQuery);
tableQuery.append(createPrimaryKeyConstraint(tableConstraint));
if(tableConstraintIterator.hasNext()) tableQuery.append(",");
}
prettyPrint(1, prettyPrint, tableQuery);
tableQuery.append(");\n");
prettyPrint(1, prettyPrint, tableQuery);
tableConstraintIterator = tableDetails.getConstraints().iterator();
while (tableConstraintIterator.hasNext()) {
TableConstraint tableConstraint = tableConstraintIterator.next();
if(tableConstraint.constraintType() != TableConstraint.Type.UNIQUE)
continue;
prettyPrint(3, prettyPrint, tableQuery);
tableQuery.append(createUniqueKeyConstraint(tableDetails.getTableName(), tableConstraint));
tableQuery.append(";\n");
prettyPrint(1, prettyPrint, tableQuery);
}
for (Index index : tableDetails.getIndices()) {
prettyPrint(1, prettyPrint, tableQuery);
tableQuery.append("CREATE INDEX ");
tableQuery.append(index.indexName()).append("_").append(tableDetails.getTableName());
tableQuery.append(" ON ");
tableQuery.append(tableDetails.getTableName());
tableQuery.append(" (");
int length = index.indexColumns().length;
for (int i = 0; i < length; i++) {
String column = index.indexColumns()[i];
tableQuery.append(column);
if((i + 1) < length) tableQuery.append(", ");
}
tableQuery.append(");\n");
prettyPrint(1, prettyPrint, tableQuery);
}
return tableQuery.toString();
}
public static List<String> generateIndecesCreate(TableDetails tableDetails, boolean prettyPrint) {
List<String> indeces = new ArrayList<>();
for (Index index : tableDetails.getIndices()) {
StringBuilder tableQuery = new StringBuilder();
prettyPrint(1, prettyPrint, tableQuery);
tableQuery.append("CREATE INDEX ");
tableQuery.append("IDX_").append(tableDetails.getTableName()).append("_").append(index.indexName());
tableQuery.append(" ON ");
tableQuery.append(tableDetails.getTableName());
tableQuery.append(" (");
int length = index.indexColumns().length;
for (int i = 0; i < length; i++) {
String column = index.indexColumns()[i];
tableQuery.append(column);
if((i + 1) < length) tableQuery.append(", ");
}
tableQuery.append(");\n");
prettyPrint(1, prettyPrint, tableQuery);
indeces.add(tableQuery.toString());
}
return indeces;
}
private static void prettyPrint(int tabSpace, boolean prettyPrint, StringBuilder tableQuery) {
if(prettyPrint){
tableQuery.append("\n");
for (int i = 0; i < tabSpace; i++) {
tableQuery.append("\t");
}
}
}
private static StringBuilder createColumnDefinition(ColumnDetails columnDetails) {
StringBuilder columnDefinition = new StringBuilder();
columnDefinition.append(columnDetails.getColumnName());
columnDefinition.append(" ");
columnDefinition.append(columnDetails.getColumnTypeMapping().getSqlColumnTypeName());
if(columnDetails.isPrimaryKey()) {
columnDefinition.append(" PRIMARY KEY");
if(columnDetails.isAutoIncrement()) columnDefinition.append(" AUTOINCREMENT");
if(columnDetails.isRequired()) columnDefinition.append(" NOT NULL");
}
else if(columnDetails.isUnique()) columnDefinition.append(" UNIQUE");
else if(columnDetails.isRequired()) columnDefinition.append(" NOT NULL");
return columnDefinition;
}
private static StringBuilder createPrimaryKeyConstraint(TableConstraint constraint){
StringBuilder constraintDef = new StringBuilder();
constraintDef.append(" PRIMARY KEY ");
Iterator<String> columnIterator = Arrays.asList(constraint.constraintColumns()).iterator();
constraintDef.append("(");
while(columnIterator.hasNext()){
String columnName = columnIterator.next();
constraintDef.append(columnName);
if(columnIterator.hasNext()) constraintDef.append(", ");
}
constraintDef.append(")");
return constraintDef;
}
private static StringBuilder createUniqueKeyConstraint(String tableName, TableConstraint constraint){
StringBuilder constraintDef = new StringBuilder();
constraintDef.append(" CREATE UNIQUE INDEX ");
constraintDef.append(constraint.name());
constraintDef.append(" ON ");
constraintDef.append(tableName);
Iterator<String> columnIterator = Arrays.asList(constraint.constraintColumns()).iterator();
constraintDef.append("(");
while(columnIterator.hasNext()){
String columnName = columnIterator.next();
constraintDef.append(columnName);
if(columnIterator.hasNext()) constraintDef.append(", ");
}
constraintDef.append(")");
return constraintDef;
}
} |
package in.co.sdslabs.cognizance;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import android.database.SQLException;
import android.os.Bundle;
import android.support.v4.app.ListFragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.SimpleAdapter;
public class EventCategoryFragment extends ListFragment {
// private ListView mEventList;
private List<HashMap<String, String>> eventList;
private SimpleAdapter mAdapter;
private String EVENTNAME = "eventname";
private String EVENTVENUE = "eventvenue";
private String EVENTTIME = "eventtime";
public EventCategoryFragment() {
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Retrieving the currently selected item number
int position = getArguments().getInt("position");
String[] categories = getResources().getStringArray(
R.array.eventCategories);
// Creating view correspoding to the fragment
View v = inflater.inflate(R.layout.eventcategoryfragment_layout,
container, false);
eventList = new ArrayList<HashMap<String, String>>();
// Initialising DBhelper class
DatabaseHelper myDbHelper = new DatabaseHelper(getActivity()
.getBaseContext());
try {
myDbHelper.createDataBase();
} catch (IOException ioe) {
throw new Error("Unable to create database");
}
try {
myDbHelper.openDataBase();
} catch (SQLException sqle) {
throw sqle;
}
// TextView tv = (TextView) v.findViewById(R.id.tv_categoryDescription);
// tv.setText(categories[position]);
// mEventList = (ListView) v.findViewById(R.id.eventCategory_list);
/** Create function in DBhelper to return these three values **/
// String Data = DBhelper.getReducedEvent(categories[position]);
for (int i = 0; i < 20; i++) {
HashMap<String, String> hm = new HashMap<String, String>();
hm.put(EVENTNAME, "");
hm.put(EVENTVENUE, "");
hm.put(EVENTTIME, "");
// hm.put(IMAGE, Integer.toString(mImages[i]));
eventList.add(hm);
}
String[] from = { EVENTNAME ,EVENTVENUE , EVENTTIME};
int[] to = { R.id.tv_eName, R.id.tv_eVenue, R.id.tv_eTime };
// Instantiating an adapter to store each items
// R.layout.drawer_layout defines the layout of each item
mAdapter = new SimpleAdapter(getActivity().getBaseContext(), eventList,
R.layout.eventcategory_list_item, from, to);
setListAdapter(mAdapter);
return v;
}
} |
package uk.ac.cam.cl.ticking.ui.api;
import java.io.IOException;
import java.util.Date;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.InternalServerErrorException;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;
import org.apache.log4j.Logger;
import org.joda.time.DateTime;
import publicinterfaces.ITestService;
import publicinterfaces.ReportNotFoundException;
import publicinterfaces.ReportResult;
import publicinterfaces.TickNotInDBException;
import publicinterfaces.UserNotInDBException;
import uk.ac.cam.cl.dtg.teaching.exceptions.RemoteFailureHandler;
import uk.ac.cam.cl.dtg.teaching.exceptions.SerializableException;
import uk.ac.cam.cl.git.api.DuplicateRepoNameException;
import uk.ac.cam.cl.git.api.FileBean;
import uk.ac.cam.cl.git.api.ForkRequestBean;
import uk.ac.cam.cl.git.api.RepositoryNotFoundException;
import uk.ac.cam.cl.git.interfaces.WebInterface;
import uk.ac.cam.cl.ticking.signups.TickSignups;
import uk.ac.cam.cl.ticking.ui.actors.Role;
import uk.ac.cam.cl.ticking.ui.api.public_interfaces.IForkApiFacade;
import uk.ac.cam.cl.ticking.ui.api.public_interfaces.beans.ForkBean;
import uk.ac.cam.cl.ticking.ui.configuration.Configuration;
import uk.ac.cam.cl.ticking.ui.configuration.ConfigurationLoader;
import uk.ac.cam.cl.ticking.ui.dao.IDataManager;
import uk.ac.cam.cl.ticking.ui.exceptions.DuplicateDataEntryException;
import uk.ac.cam.cl.ticking.ui.ticks.Fork;
import uk.ac.cam.cl.ticking.ui.ticks.Tick;
import uk.ac.cam.cl.ticking.ui.util.Strings;
import com.google.inject.Inject;
public class ForkApiFacade implements IForkApiFacade {
Logger log = Logger.getLogger(ConfigurationLoader.class.getName());
private IDataManager db;
// not currently used but could quite possibly be needed in the future, will
// remove if not
@SuppressWarnings("unused")
private ConfigurationLoader<Configuration> config;
private WebInterface gitServiceProxy;
private ITestService testServiceProxy;
private TickSignups tickSignupService;
/**
* @param db
* @param config
*/
@Inject
public ForkApiFacade(IDataManager db,
ConfigurationLoader<Configuration> config,
ITestService testServiceProxy, WebInterface gitServiceProxy,
TickSignups tickSignupService) {
this.db = db;
this.config = config;
this.testServiceProxy = testServiceProxy;
this.gitServiceProxy = gitServiceProxy;
this.tickSignupService = tickSignupService;
}
@Override
public Response getFork(HttpServletRequest request, String tickId) {
String crsid = (String) request.getSession().getAttribute(
"RavenRemoteUser");
Fork fork = db.getFork(Fork.generateForkId(crsid, tickId));
if (fork == null) {
return Response.status(Status.NOT_FOUND).build();
}
return Response.ok(fork).build();
}
/*
* (non-Javadoc)
*
* @see
* uk.ac.cam.cl.ticking.ui.api.public_interfaces.ITickApiFacade#forkTick
* (javax.servlet.http.HttpServletRequest, java.lang.String)
*/
@Override
public Response forkTick(HttpServletRequest request, String tickId) {
String crsid = (String) request.getSession().getAttribute(
"RavenRemoteUser");
Fork fork = db.getFork(Fork.generateForkId(crsid, tickId));
if (fork != null) {
return Response.ok(fork).build();
}
String repo = null;
String repoName = Tick.replaceDelimeter(tickId);
try {
repo = gitServiceProxy.forkRepository(new ForkRequestBean(null,
crsid, repoName, null));
} catch (InternalServerErrorException e) {
RemoteFailureHandler h = new RemoteFailureHandler();
SerializableException s = h.readException(e);
repo = s.getMessage();
} catch (IOException | DuplicateRepoNameException e) {
return Response.status(Status.INTERNAL_SERVER_ERROR).entity(e)
.build();
// Due to exception chaining this shouldn't happen
}
try {
fork = new Fork(crsid, tickId, repo);
db.insertFork(fork);
} catch (DuplicateDataEntryException e) {
throw new RuntimeException("Schrodinger's fork");
// The fork simultaneously does and doesn't exist
}
// Execution will only reach this point if there are no git errors else
// IOException is thrown
return Response.status(Status.CREATED).entity(fork).build();
}
@Override
public Response markFork(HttpServletRequest request, String crsid,
String tickId, ForkBean forkBean) {
String myCrsid = (String) request.getSession().getAttribute(
"RavenRemoteUser");
boolean marker = false;
List<String> groupIds = db.getTick(tickId).getGroups();
for (String groupId : groupIds) {
List<Role> roles = db.getRoles(groupId, myCrsid);
if (roles.contains(Role.MARKER)) {
marker = true;
}
}
if (!marker) {
return Response.status(Status.UNAUTHORIZED)
.entity(Strings.INVALIDROLE).build();
}
Fork fork = db.getFork(Fork.generateForkId(crsid, tickId));
if (fork != null) {
if (forkBean.getHumanPass() != null) {
fork.setHumanPass(forkBean.getHumanPass());
ReportResult result = forkBean.getHumanPass() ? ReportResult.PASS
: ReportResult.FAIL;
log.info(result);
try {
testServiceProxy.setTickerResult(crsid, tickId, result,
forkBean.getTickerComments(),
forkBean.getCommitId(), forkBean.getReportDate().getMillis());
} catch (UserNotInDBException | TickNotInDBException
| ReportNotFoundException e) {
return Response.status(Status.NOT_FOUND).entity(e).build();
}
fork.setLastTickedBy(crsid);
fork.setLastTickedOn(DateTime.now());
if (!forkBean.getHumanPass()) {
tickSignupService.unbookSlot(request, tickId);
fork.setUnitPass(false);
for (String groupId : groupIds) {
tickSignupService.assignTickerForTickForUser(crsid,
groupId, tickId, forkBean.getTicker());
}
}
}
db.saveFork(fork);
return Response.status(Status.CREATED).entity(fork).build();
}
return Response.status(Status.NOT_FOUND).build();
}
@Override
public Response getAllFiles(HttpServletRequest request, String crsid,
String tickId, String commitId) {
String myCrsid = (String) request.getSession().getAttribute(
"RavenRemoteUser");
if (crsid.equals("")) {
crsid = myCrsid;
}
boolean marker = false;
List<String> groupIds = db.getTick(tickId).getGroups();
for (String groupId : groupIds) {
List<Role> roles = db.getRoles(groupId, myCrsid);
if (roles.contains(Role.MARKER)) {
marker = true;
}
}
if (!(marker||myCrsid.equals(db.getFork(Fork.generateForkId(crsid, tickId)).getAuthor()))) {
return Response.status(Status.UNAUTHORIZED)
.entity(Strings.INVALIDROLE).build();
}
List<FileBean> files;
try {
files = gitServiceProxy.getAllFiles(crsid+"/"+Tick.replaceDelimeter(tickId), commitId);
} catch (IOException | RepositoryNotFoundException e) {
return Response.status(Status.INTERNAL_SERVER_ERROR).entity(e).build();
}
return Response.ok(files).build();
}
} |
// ConsoleTools.java
package loci.formats;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.Hashtable;
public final class ConsoleTools {
// -- Constructor --
private ConsoleTools() { }
// -- Utility methods - command line --
/**
* A utility method for reading a file from the command line,
* and displaying the results in a simple display.
*/
public static boolean testRead(IFormatReader reader, String[] args)
throws FormatException, IOException
{
String id = null;
boolean pixels = true;
boolean doMeta = true;
boolean thumbs = false;
boolean minmax = false;
boolean merge = false;
boolean stitch = false;
boolean separate = false;
boolean omexml = false;
boolean normalize = false;
boolean fastBlit = false;
int start = 0;
int end = Integer.MAX_VALUE;
int series = 0;
String map = null;
if (args != null) {
for (int i=0; i<args.length; i++) {
if (args[i].startsWith("-") && args.length > 1) {
if (args[i].equals("-nopix")) pixels = false;
else if (args[i].equals("-nometa")) doMeta = false;
else if (args[i].equals("-thumbs")) thumbs = true;
else if (args[i].equals("-minmax")) minmax = true;
else if (args[i].equals("-merge")) merge = true;
else if (args[i].equals("-stitch")) stitch = true;
else if (args[i].equals("-separate")) separate = true;
else if (args[i].equals("-omexml")) omexml = true;
else if (args[i].equals("-normalize")) normalize = true;
else if (args[i].equals("-fast")) fastBlit = true;
else if (args[i].equals("-debug")) FormatHandler.setDebug(true);
else if (args[i].equals("-level")) {
try {
FormatHandler.setDebugLevel(Integer.parseInt(args[++i]));
}
catch (NumberFormatException exc) { }
}
else if (args[i].equals("-range")) {
try {
start = Integer.parseInt(args[++i]);
end = Integer.parseInt(args[++i]);
}
catch (NumberFormatException exc) { }
}
else if (args[i].equals("-series")) {
try {
series = Integer.parseInt(args[++i]);
}
catch (NumberFormatException exc) { }
}
else if (args[i].equals("-map")) map = args[++i];
else LogTools.println("Ignoring unknown command flag: " + args[i]);
}
else {
if (id == null) id = args[i];
else LogTools.println("Ignoring unknown argument: " + args[i]);
}
}
}
if (FormatHandler.debug) {
LogTools.println("Debugging at level " + FormatHandler.debugLevel);
}
if (id == null) {
String className = reader.getClass().getName();
String fmt = reader instanceof ImageReader ? "any" : reader.getFormat();
String[] s = {
"To test read a file in " + fmt + " format, run:",
" java " + className + " [-nopix] [-nometa] [-thumbs] [-minmax]",
" [-merge] [-stitch] [-separate] [-omexml] [-normalize]",
" [-fast] [-debug] [-range start end] [-series num] [-map id] file",
"",
" file: the image file to read",
" -nopix: read metadata only, not pixels",
" -nometa: output only core metadata",
" -thumbs: read thumbnails instead of normal pixels",
" -minmax: compute min/max statistics",
" -merge: combine separate channels into RGB image",
" -stitch: stitch files with similar names",
" -separate: split RGB image into separate channels",
" -omexml: populate OME-XML metadata",
"-normalize: normalize floating point images*",
" -fast: paint RGB images as quickly as possible*",
" -debug: turn on debugging output",
" -range: specify range of planes to read (inclusive)",
" -series: specify which image series to read",
" -map: specify file on disk to which name should be mapped",
"",
"* = may result in loss of precision",
""
};
for (int i=0; i<s.length; i++) LogTools.println(s[i]);
return false;
}
if (map != null) Location.mapId(id, map);
if (omexml) {
reader.setOriginalMetadataPopulated(true);
try {
// NB: avoid dependencies on optional loci.formats.ome package
Class c = Class.forName("loci.formats.ome.OMEXMLMetadataStore");
MetadataStore ms = (MetadataStore) c.newInstance();
reader.setMetadataStore(ms);
}
catch (Throwable t) {
// NB: error messages for missing OME-Java are printed later
}
}
// check file format
if (reader instanceof ImageReader) {
// determine format
ImageReader ir = (ImageReader) reader;
LogTools.print("Checking file format ");
LogTools.println("[" + ir.getFormat(id) + "]");
}
else {
// verify format
LogTools.print("Checking " + reader.getFormat() + " format ");
LogTools.println(reader.isThisType(id) ? "[yes]" : "[no]");
}
LogTools.println("Initializing reader");
if (stitch) {
reader = new FileStitcher(reader, true);
String pat = FilePattern.findPattern(new Location(id));
if (pat != null) id = pat;
}
if (separate) reader = new ChannelSeparator(reader);
if (merge) reader = new ChannelMerger(reader);
MinMaxCalculator minMaxCalc = null;
if (minmax) reader = minMaxCalc = new MinMaxCalculator(reader);
StatusEchoer status = new StatusEchoer();
reader.addStatusListener(status);
reader.close();
reader.setNormalized(normalize);
reader.setMetadataFiltered(true);
reader.setMetadataCollected(doMeta);
long s1 = System.currentTimeMillis();
reader.setId(id);
long e1 = System.currentTimeMillis();
float sec1 = (e1 - s1) / 1000f;
LogTools.println("Initialization took " + sec1 + "s");
if (!normalize && reader.getPixelType() == FormatTools.FLOAT) {
throw new FormatException("Sorry, unnormalized floating point " +
"data is not supported. Please use the '-normalize' option.");
}
// read basic metadata
LogTools.println();
LogTools.println("Reading core metadata");
LogTools.println(stitch ?
"File pattern = " + id : "Filename = " + reader.getCurrentFile());
if (map != null) LogTools.println("Mapped filename = " + map);
String[] used = reader.getUsedFiles();
boolean usedValid = used != null && used.length > 0;
if (usedValid) {
for (int u=0; u<used.length; u++) {
if (used[u] == null) {
usedValid = false;
break;
}
}
}
if (!usedValid) {
LogTools.println(
"************ Warning: invalid used files list ************");
}
if (used == null) {
LogTools.println("Used files = null");
}
else if (used.length == 0) {
LogTools.println("Used files = []");
}
else if (used.length > 1) {
LogTools.println("Used files:");
for (int u=0; u<used.length; u++) LogTools.println("\t" + used[u]);
}
else if (!id.equals(used[0])) {
LogTools.println("Used files = [" + used[0] + "]");
}
int seriesCount = reader.getSeriesCount();
LogTools.println("Series count = " + seriesCount);
for (int j=0; j<seriesCount; j++) {
reader.setSeries(j);
// read basic metadata for series
int imageCount = reader.getImageCount();
boolean rgb = reader.isRGB();
int sizeX = reader.getSizeX();
int sizeY = reader.getSizeY();
int sizeZ = reader.getSizeZ();
int sizeC = reader.getSizeC();
int sizeT = reader.getSizeT();
int pixelType = reader.getPixelType();
int effSizeC = reader.getEffectiveSizeC();
int rgbChanCount = reader.getRGBChannelCount();
int[] cLengths = reader.getChannelDimLengths();
String[] cTypes = reader.getChannelDimTypes();
int thumbSizeX = reader.getThumbSizeX();
int thumbSizeY = reader.getThumbSizeY();
boolean little = reader.isLittleEndian();
String dimOrder = reader.getDimensionOrder();
boolean orderCertain = reader.isOrderCertain();
boolean interleaved = reader.isInterleaved();
// output basic metadata for series
LogTools.println("Series
LogTools.println("\tImage count = " + imageCount);
LogTools.print("\tRGB = " + rgb + " (" + rgbChanCount + ")");
if (merge) LogTools.print(" (merged)");
else if (separate) LogTools.print(" (separated)");
if (rgb != (rgbChanCount != 1)) {
LogTools.println("\t************ Warning: RGB mismatch ************");
}
LogTools.println();
LogTools.println("\tInterleaved = " + interleaved);
LogTools.println("\tWidth = " + sizeX);
LogTools.println("\tHeight = " + sizeY);
LogTools.println("\tSizeZ = " + sizeZ);
LogTools.println("\tSizeT = " + sizeT);
LogTools.print("\tSizeC = " + sizeC);
if (sizeC != effSizeC) {
LogTools.print(" (effectively " + effSizeC + ")");
}
int cProduct = 1;
if (cLengths.length == 1 && FormatTools.CHANNEL.equals(cTypes[0])) {
cProduct = cLengths[0];
}
else {
LogTools.print(" (");
for (int i=0; i<cLengths.length; i++) {
if (i > 0) LogTools.print(" x ");
LogTools.print(cLengths[i] + " " + cTypes[i]);
cProduct *= cLengths[i];
}
LogTools.print(")");
}
LogTools.println();
if (cLengths.length == 0 || cProduct != sizeC) {
LogTools.println(
"\t************ Warning: C dimension mismatch ************");
}
if (imageCount != sizeZ * effSizeC * sizeT) {
LogTools.println("\t************ Warning: ZCT mismatch ************");
}
LogTools.println("\tThumbnail size = " +
thumbSizeX + " x " + thumbSizeY);
LogTools.println("\tEndianness = " +
(little ? "intel (little)" : "motorola (big)"));
LogTools.println("\tDimension order = " + dimOrder +
(orderCertain ? " (certain)" : " (uncertain)"));
LogTools.println("\tPixel type = " +
FormatTools.getPixelTypeString(pixelType));
LogTools.println("\tMetadata complete = " + reader.isMetadataComplete());
if (doMeta) {
LogTools.println("\t
int[] indices;
if (imageCount > 6) {
int q = imageCount / 2;
indices = new int[] {
0, q - 2, q - 1, q, q + 1, q + 2, imageCount - 1
};
}
else if (imageCount > 2) {
indices = new int[] {0, imageCount / 2, imageCount - 1};
}
else if (imageCount > 1) indices = new int[] {0, 1};
else indices = new int[] {0};
int[][] zct = new int[indices.length][];
int[] indices2 = new int[indices.length];
for (int i=0; i<indices.length; i++) {
zct[i] = reader.getZCTCoords(indices[i]);
indices2[i] = reader.getIndex(zct[i][0], zct[i][1], zct[i][2]);
LogTools.print("\tPlane #" + indices[i] + " <=> Z " + zct[i][0] +
", C " + zct[i][1] + ", T " + zct[i][2]);
if (indices[i] != indices2[i]) {
LogTools.println(" [mismatch: " + indices2[i] + "]");
}
else LogTools.println();
}
}
}
reader.setSeries(series);
String s = seriesCount > 1 ? (" series #" + series) : "";
int pixelType = reader.getPixelType();
int sizeC = reader.getSizeC();
// get a priori min/max values
Double[] preGlobalMin = null, preGlobalMax = null;
Double[] preKnownMin = null, preKnownMax = null;
Double[] prePlaneMin = null, prePlaneMax = null;
boolean preIsMinMaxPop = false;
if (minmax) {
preGlobalMin = new Double[sizeC];
preGlobalMax = new Double[sizeC];
preKnownMin = new Double[sizeC];
preKnownMax = new Double[sizeC];
for (int c=0; c<sizeC; c++) {
preGlobalMin[c] = minMaxCalc.getChannelGlobalMinimum(c);
preGlobalMax[c] = minMaxCalc.getChannelGlobalMaximum(c);
preKnownMin[c] = minMaxCalc.getChannelKnownMinimum(c);
preKnownMax[c] = minMaxCalc.getChannelKnownMaximum(c);
}
prePlaneMin = minMaxCalc.getPlaneMinimum(0);
prePlaneMax = minMaxCalc.getPlaneMaximum(0);
preIsMinMaxPop = minMaxCalc.isMinMaxPopulated();
}
// read pixels
if (pixels) {
LogTools.println();
LogTools.print("Reading" + s + " pixel data ");
status.setVerbose(false);
int num = reader.getImageCount();
if (start < 0) start = 0;
if (start >= num) start = num - 1;
if (end < 0) end = 0;
if (end >= num) end = num - 1;
if (end < start) end = start;
LogTools.print("(" + start + "-" + end + ") ");
BufferedImage[] images = new BufferedImage[end - start + 1];
long s2 = System.currentTimeMillis();
boolean mismatch = false;
for (int i=start; i<=end; i++) {
status.setEchoNext(true);
if (!fastBlit) {
images[i - start] = thumbs ?
reader.openThumbImage(i) : reader.openImage(i);
}
else {
int x = reader.getSizeX();
int y = reader.getSizeY();
byte[] b = thumbs ? reader.openThumbBytes(i) :
reader.openBytes(i);
Object pix = DataTools.makeDataArray(b,
FormatTools.getBytesPerPixel(reader.getPixelType()),
reader.getPixelType() == FormatTools.FLOAT,
reader.isLittleEndian());
images[i - start] =
ImageTools.makeImage(ImageTools.make24Bits(pix, x, y,
false, false), x, y);
}
// check for pixel type mismatch
int pixType = ImageTools.getPixelType(images[i - start]);
if (pixType != pixelType && !fastBlit) {
if (!mismatch) {
LogTools.println();
mismatch = true;
}
LogTools.println("\tPlane #" + i + ": pixel type mismatch: " +
FormatTools.getPixelTypeString(pixType) + "/" +
FormatTools.getPixelTypeString(pixelType));
}
else {
mismatch = false;
LogTools.print(".");
}
}
long e2 = System.currentTimeMillis();
if (!mismatch) LogTools.print(" ");
LogTools.println("[done]");
// output timing results
float sec2 = (e2 - s2) / 1000f;
float avg = (float) (e2 - s2) / images.length;
LogTools.println(sec2 + "s elapsed (" + avg + "ms per image)");
if (minmax) {
// get computed min/max values
Double[] globalMin = new Double[sizeC];
Double[] globalMax = new Double[sizeC];
Double[] knownMin = new Double[sizeC];
Double[] knownMax = new Double[sizeC];
for (int c=0; c<sizeC; c++) {
globalMin[c] = minMaxCalc.getChannelGlobalMinimum(c);
globalMax[c] = minMaxCalc.getChannelGlobalMaximum(c);
knownMin[c] = minMaxCalc.getChannelKnownMinimum(c);
knownMax[c] = minMaxCalc.getChannelKnownMaximum(c);
}
Double[] planeMin = minMaxCalc.getPlaneMinimum(0);
Double[] planeMax = minMaxCalc.getPlaneMaximum(0);
boolean isMinMaxPop = minMaxCalc.isMinMaxPopulated();
// output min/max results
LogTools.println();
LogTools.println("Min/max values:");
for (int c=0; c<sizeC; c++) {
LogTools.println("\tChannel " + c + ":");
LogTools.println("\t\tGlobal minimum = " +
globalMin[c] + " (initially " + preGlobalMin[c] + ")");
LogTools.println("\t\tGlobal maximum = " +
globalMax[c] + " (initially " + preGlobalMax[c] + ")");
LogTools.println("\t\tKnown minimum = " +
knownMin[c] + " (initially " + preKnownMin[c] + ")");
LogTools.println("\t\tKnown maximum = " +
knownMax[c] + " (initially " + preKnownMax[c] + ")");
}
LogTools.print("\tFirst plane minimum(s) =");
if (planeMin == null) LogTools.print(" none");
else {
for (int subC=0; subC<planeMin.length; subC++) {
LogTools.print(" " + planeMin[subC]);
}
}
LogTools.print(" (initially");
if (prePlaneMin == null) LogTools.print(" none");
else {
for (int subC=0; subC<prePlaneMin.length; subC++) {
LogTools.print(" " + prePlaneMin[subC]);
}
}
LogTools.println(")");
LogTools.print("\tFirst plane maximum(s) =");
if (planeMax == null) LogTools.print(" none");
else {
for (int subC=0; subC<planeMax.length; subC++) {
LogTools.print(" " + planeMax[subC]);
}
}
LogTools.print(" (initially");
if (prePlaneMax == null) LogTools.print(" none");
else {
for (int subC=0; subC<prePlaneMax.length; subC++) {
LogTools.print(" " + prePlaneMax[subC]);
}
}
LogTools.println(")");
LogTools.println("\tMin/max populated = " +
isMinMaxPop + " (initially " + preIsMinMaxPop + ")");
}
// display pixels in image viewer
// NB: avoid dependencies on optional loci.formats.gui package
ReflectedUniverse r = new ReflectedUniverse();
try {
r.exec("import loci.formats.gui.ImageViewer");
r.exec("viewer = new ImageViewer()");
r.setVar("reader", reader);
r.setVar("images", images);
r.setVar("true", true);
r.exec("viewer.setImages(reader, images)");
r.exec("viewer.setVisible(true)");
}
catch (ReflectException exc) {
throw new FormatException(exc);
}
}
// read format-specific metadata table
if (doMeta) {
LogTools.println();
LogTools.println("Reading" + s + " metadata");
Hashtable meta = reader.getMetadata();
String[] keys = (String[]) meta.keySet().toArray(new String[0]);
Arrays.sort(keys);
for (int i=0; i<keys.length; i++) {
LogTools.print(keys[i] + ": ");
LogTools.println(reader.getMetadataValue(keys[i]));
}
}
// output and validate OME-XML
if (omexml) {
LogTools.println();
LogTools.println("Generating OME-XML");
MetadataStore ms = reader.getMetadataStore();
// NB: avoid dependencies on optional loci.formats.ome package
if (ms.getClass().getName().equals(
"loci.formats.ome.OMEXMLMetadataStore"))
{
// output OME-XML
String xml = null;
try {
Method m = ms.getClass().getMethod("dumpXML", (Class[]) null);
xml = (String) m.invoke(ms, (Object[]) null);
LogTools.println(FormatTools.indentXML(xml));
}
catch (Throwable t) {
LogTools.println("Error generating OME-XML:");
LogTools.trace(t);
}
// check Java version (XML validation only works in Java 1.5+)
String version = System.getProperty("java.version");
int dot = version.indexOf(".");
if (dot >= 0) dot = version.indexOf(".", dot + 1);
float ver = Float.NaN;
if (dot >= 0) {
try {
ver = Float.parseFloat(version.substring(0, dot));
}
catch (NumberFormatException exc) { }
}
if (ver != ver) {
LogTools.println("Warning: cannot determine if Java version\"" +
version + "\" supports Java v1.5. OME-XML validation may fail.");
}
if (ver != ver || ver >= 1.5f) {
// validate OME-XML (Java 1.5+ only)
LogTools.println("Validating OME-XML");
// use reflection to avoid dependency on optional
// org.openmicroscopy.xml or javax.xml.validation packages
ReflectedUniverse r = new ReflectedUniverse();
try {
// look up a factory for the W3C XML Schema language
r.exec("import javax.xml.validation.SchemaFactory");
r.setVar("schemaPath", "http:
r.exec("factory = SchemaFactory.newInstance(schemaPath)");
// compile the schema
r.exec("import java.net.URL");
r.setVar("omePath",
"http:
r.exec("schemaLocation = new URL(omePath)");
r.exec("schema = factory.newSchema(schemaLocation)");
// get a validator from the schema
r.exec("validator = schema.newValidator()");
// prepare the XML source
r.exec("import java.io.StringReader");
r.exec("import javax.xml.transform.stream.StreamSource");
r.setVar("ms", ms);
r.exec("root = ms.getRoot()");
r.setVar("xml", xml);
r.exec("reader = new StringReader(xml)");
r.exec("source = new StreamSource(reader)");
// validate the OME-XML
try {
r.exec("validator.validate(source)");
LogTools.println("No validation errors found.");
}
catch (ReflectException exc) {
// display validation errors
LogTools.println(exc.getCause().getCause().getMessage());
}
}
catch (ReflectException exc) {
LogTools.println("Error validating OME-XML:");
LogTools.trace(exc);
}
}
}
else {
LogTools.println("OME-Java library not found; no OME-XML available");
}
}
return true;
}
/** A utility method for converting a file from the command line. */
public static boolean testConvert(IFormatWriter writer, String[] args)
throws FormatException, IOException
{
String in = null, out = null;
if (args != null) {
for (int i=0; i<args.length; i++) {
if (args[i].startsWith("-") && args.length > 1) {
if (args[i].equals("-debug")) FormatHandler.setDebug(true);
else LogTools.println("Ignoring unknown command flag: " + args[i]);
}
else {
if (in == null) in = args[i];
else if (out == null) out = args[i];
else LogTools.println("Ignoring unknown argument: " + args[i]);
}
}
}
if (FormatHandler.debug) {
LogTools.println("Debugging at level " + FormatHandler.debugLevel);
}
String className = writer.getClass().getName();
if (in == null || out == null) {
LogTools.println("To convert a file to " + writer.getFormat() +
" format, run:");
LogTools.println(" java " + className + " [-debug] in_file out_file");
return false;
}
long start = System.currentTimeMillis();
LogTools.print(in + " ");
ImageReader reader = new ImageReader();
reader.setOriginalMetadataPopulated(true);
try {
Class c = Class.forName("loci.formats.ome.OMEXMLMetadataStore");
MetadataStore ms = (MetadataStore) c.newInstance();
reader.setMetadataStore(ms);
}
catch (Throwable t) {
LogTools.println("OME-Java library not found.");
}
reader.setId(in);
LogTools.print("[" + reader.getFormat() + "] -> " + out + " ");
MetadataStore store = reader.getMetadataStore();
if (store instanceof MetadataRetrieve) {
writer.setMetadataRetrieve((MetadataRetrieve) store);
}
writer.setId(out);
LogTools.print("[" + writer.getFormat() + "] ");
long mid = System.currentTimeMillis();
int num = writer.canDoStacks() ? reader.getImageCount() : 1;
long read = 0, write = 0;
for (int i=0; i<num; i++) {
long s = System.currentTimeMillis();
Image image = reader.openImage(i);
long m = System.currentTimeMillis();
writer.saveImage(image, i == num - 1);
long e = System.currentTimeMillis();
LogTools.print(".");
read += m - s;
write += e - m;
}
long end = System.currentTimeMillis();
LogTools.println(" [done]");
// output timing results
float sec = (end - start) / 1000f;
long initial = mid - start;
float readAvg = (float) read / num;
float writeAvg = (float) write / num;
LogTools.println(sec + "s elapsed (" +
readAvg + "+" + writeAvg + "ms per image, " + initial + "ms overhead)");
return true;
}
// -- Helper classes --
/** Used by testRead to echo status messages to the console. */
private static class StatusEchoer implements StatusListener {
private boolean verbose = true;
private boolean next = true;
public void setVerbose(boolean value) { verbose = value; }
public void setEchoNext(boolean value) { next = value; }
public void statusUpdated(StatusEvent e) {
if (verbose) LogTools.println("\t" + e.getStatusMessage());
else if (next) {
LogTools.print(";");
next = false;
}
}
}
} |
// FileStitcher.java
package loci.formats;
import java.awt.image.BufferedImage;
import java.io.*;
import java.lang.reflect.InvocationTargetException;
import java.math.BigInteger;
import java.util.*;
public class FileStitcher implements IFormatReader {
// -- Fields --
/** FormatReader to use as a template for constituent readers. */
private IFormatReader reader;
/**
* Whether string ids given should be treated
* as file patterns rather than single file paths.
*/
private boolean patternIds = false;
/** Current file pattern string. */
private String currentId;
/** File pattern object used to build the list of files. */
private FilePattern fp;
/** Axis guesser object used to guess which dimensional axes are which. */
private AxisGuesser[] ag;
/** The matching files. */
private String[][] files;
/** Used files list. */
private String[] usedFiles;
/** Reader used for each file. */
private IFormatReader[][] readers;
/** Blank buffered image, for use when image counts vary between files. */
private BufferedImage[] blankImage;
/** Blank image bytes, for use when image counts vary between files. */
private byte[][] blankBytes;
/** Blank buffered thumbnail, for use when image counts vary between files. */
private BufferedImage[] blankThumb;
/** Blank thumbnail bytes, for use when image counts vary between files. */
private byte[][] blankThumbBytes;
/** Number of images per file. */
private int[] imagesPerFile;
/** Dimensional axis lengths per file. */
private int[] sizeZ, sizeC, sizeT;
/** Component lengths for each axis type. */
private int[][] lenZ, lenC, lenT;
/** Core metadata. */
private CoreMetadata core;
/** Current series number. */
private int series;
private String[] seriesBlocks;
private Vector fileVector;
private Vector seriesNames;
private boolean seriesInFile;
// -- Constructors --
/** Constructs a FileStitcher around a new image reader. */
public FileStitcher() { this(new ImageReader()); }
/**
* Constructs a FileStitcher around a new image reader.
* @param patternIds Whether string ids given should be treated as file
* patterns rather than single file paths.
*/
public FileStitcher(boolean patternIds) {
this(new ImageReader(), patternIds);
}
/**
* Constructs a FileStitcher with the given reader.
* @param r The reader to use for reading stitched files.
*/
public FileStitcher(IFormatReader r) { this(r, false); }
/**
* Constructs a FileStitcher with the given reader.
* @param r The reader to use for reading stitched files.
* @param patternIds Whether string ids given should be treated as file
* patterns rather than single file paths.
*/
public FileStitcher(IFormatReader r, boolean patternIds) {
reader = r;
this.patternIds = patternIds;
}
// -- FileStitcher API methods --
/** Gets the wrapped reader prototype. */
public IFormatReader getReader() { return reader; }
/**
* Gets the axis type for each dimensional block.
* @return An array containing values from the enumeration:
* <ul>
* <li>AxisGuesser.Z_AXIS: focal planes</li>
* <li>AxisGuesser.T_AXIS: time points</li>
* <li>AxisGuesser.C_AXIS: channels</li>
* <li>AxisGuesser.S_AXIS: series</li>
* </ul>
*/
public int[] getAxisTypes() {
FormatTools.assertId(currentId, true, 2);
return ag[getSeries()].getAxisTypes();
}
/**
* Sets the axis type for each dimensional block.
* @param axes An array containing values from the enumeration:
* <ul>
* <li>AxisGuesser.Z_AXIS: focal planes</li>
* <li>AxisGuesser.T_AXIS: time points</li>
* <li>AxisGuesser.C_AXIS: channels</li>
* <li>AxisGuesser.S_AXIS: series</li>
* </ul>
*/
public void setAxisTypes(int[] axes) throws FormatException {
FormatTools.assertId(currentId, true, 2);
ag[getSeries()].setAxisTypes(axes);
computeAxisLengths();
}
/** Gets the file pattern object used to build the list of files. */
public FilePattern getFilePattern() {
FormatTools.assertId(currentId, true, 2);
return fp;
}
/**
* Gets the axis guesser object used to guess
* which dimensional axes are which.
*/
public AxisGuesser getAxisGuesser() {
FormatTools.assertId(currentId, true, 2);
return ag[getSeries()];
}
/**
* Finds the file pattern for the given ID, based on the state of the file
* stitcher. Takes both ID map entries and the patternIds flag into account.
*/
public FilePattern findPattern(String id) {
FormatTools.assertId(currentId, true, 2);
if (!patternIds) {
// find the containing pattern
Hashtable map = Location.getIdMap();
String pattern = null;
if (map.containsKey(id)) {
// search ID map for pattern, rather than files on disk
String[] idList = new String[map.size()];
Enumeration en = map.keys();
for (int i=0; i<idList.length; i++) {
idList[i] = (String) en.nextElement();
}
pattern = FilePattern.findPattern(id, null, idList);
}
else {
// id is an unmapped file path; look to similar files on disk
pattern = FilePattern.findPattern(new Location(id));
}
if (pattern != null) id = pattern;
}
return new FilePattern(id);
}
// -- IFormatReader API methods --
/* @see IFormatReader#isThisType(byte[]) */
public boolean isThisType(byte[] block) {
return reader.isThisType(block);
}
/* @see IFormatReader#setId(String) */
public void setId(String id) throws FormatException, IOException {
if (!id.equals(currentId)) initFile(id);
}
/* @see IFormatReader#setId(String, boolean) */
public void setId(String id, boolean force)
throws FormatException, IOException
{
if (!id.equals(currentId) || force) initFile(id);
}
/* @see IFormatReader#getImageCount() */
public int getImageCount() {
FormatTools.assertId(currentId, true, 2);
return core.imageCount[getSeries()];
}
/* @see IFormatReader#isRGB() */
public boolean isRGB() {
FormatTools.assertId(currentId, true, 2);
return core.rgb[getSeries()];
}
/* @see IFormatReader#getSizeX() */
public int getSizeX() {
FormatTools.assertId(currentId, true, 2);
return core.sizeX[getSeries()];
}
/* @see IFormatReader#getSizeY() */
public int getSizeY() {
FormatTools.assertId(currentId, true, 2);
return core.sizeY[getSeries()];
}
/* @see IFormatReader#getSizeZ() */
public int getSizeZ() {
FormatTools.assertId(currentId, true, 2);
return core.sizeZ[getSeries()];
}
/* @see IFormatReader#getSizeC() */
public int getSizeC() {
FormatTools.assertId(currentId, true, 2);
return core.sizeC[getSeries()];
}
/* @see IFormatReader#getSizeT() */
public int getSizeT() {
FormatTools.assertId(currentId, true, 2);
return core.sizeT[getSeries()];
}
/* @see IFormatReader#getPixelType() */
public int getPixelType() {
FormatTools.assertId(currentId, true, 2);
return core.pixelType[getSeries()];
}
/* @see IFormatReader#getEffectiveSizeC() */
public int getEffectiveSizeC() {
FormatTools.assertId(currentId, true, 2);
return getImageCount() / (getSizeZ() * getSizeT());
}
/* @see IFormatReader#getRGBChannelCount() */
public int getRGBChannelCount() {
FormatTools.assertId(currentId, true, 2);
return getSizeC() / getEffectiveSizeC();
}
/* @see IFormatReader#isIndexed() */
public boolean isIndexed() {
FormatTools.assertId(currentId, true, 2);
return reader.isIndexed();
}
/* @see IFormatReader#isFalseColor() */
public boolean isFalseColor() {
FormatTools.assertId(currentId, true, 2);
return reader.isFalseColor();
}
/* @see IFormatReader#get8BitLookupTable() */
public byte[][] get8BitLookupTable() throws FormatException, IOException {
FormatTools.assertId(currentId, true, 2);
return reader.get8BitLookupTable();
}
/* @see IFormatReader#get16BitLookupTable() */
public short[][] get16BitLookupTable() throws FormatException, IOException {
FormatTools.assertId(currentId, true, 2);
return reader.get16BitLookupTable();
}
/* @see IFormatReader#getChannelDimLengths() */
public int[] getChannelDimLengths() {
FormatTools.assertId(currentId, true, 1);
return core.cLengths[getSeries()];
}
/* @see IFormatReader#getChannelDimTypes() */
public String[] getChannelDimTypes() {
FormatTools.assertId(currentId, true, 1);
return core.cTypes[getSeries()];
}
/* @see IFormatReader#getThumbSizeX() */
public int getThumbSizeX() {
FormatTools.assertId(currentId, true, 2);
return reader.getThumbSizeX();
}
/* @see IFormatReader#getThumbSizeY() */
public int getThumbSizeY() {
FormatTools.assertId(currentId, true, 2);
return reader.getThumbSizeY();
}
/* @see IFormatReader#isLittleEndian() */
public boolean isLittleEndian() {
FormatTools.assertId(currentId, true, 2);
return reader.isLittleEndian();
}
/* @see IFormatReader#getDimensionOrder() */
public String getDimensionOrder() {
FormatTools.assertId(currentId, true, 2);
return core.currentOrder[getSeries()];
}
/* @see IFormatReader#isOrderCertain() */
public boolean isOrderCertain() {
FormatTools.assertId(currentId, true, 2);
return core.orderCertain[getSeries()];
}
/* @see IFormatReader#isInterleaved() */
public boolean isInterleaved() {
FormatTools.assertId(currentId, true, 2);
return reader.isInterleaved();
}
/* @see IFormatReader#isInterleaved(int) */
public boolean isInterleaved(int subC) {
FormatTools.assertId(currentId, true, 2);
return reader.isInterleaved(subC);
}
/* @see IFormatReader#openImage(int) */
public BufferedImage openImage(int no) throws FormatException, IOException {
FormatTools.assertId(currentId, true, 2);
int[] q = computeIndices(no);
int sno = seriesInFile ? 0 : getSeries();
int fno = q[0], ino = q[1];
if (seriesInFile) readers[sno][fno].setSeries(getSeries());
if (ino < readers[sno][fno].getImageCount()) {
return readers[sno][fno].openImage(ino);
}
sno = getSeries();
// return a blank image to cover for the fact that
// this file does not contain enough image planes
if (blankImage[sno] == null) {
blankImage[sno] = ImageTools.blankImage(core.sizeX[sno], core.sizeY[sno],
sizeC[sno], getPixelType());
}
return blankImage[sno];
}
/* @see IFormatReader#openImage(int, int, int, int, int) */
public BufferedImage openImage(int no, int x, int y, int w, int h)
throws FormatException, IOException
{
return openImage(no).getSubimage(x, y, w, h);
}
/* @see IFormatReader#openBytes(int) */
public byte[] openBytes(int no) throws FormatException, IOException {
FormatTools.assertId(currentId, true, 2);
int[] q = computeIndices(no);
int sno = seriesInFile ? 0 : getSeries();
int fno = q[0], ino = q[1];
if (seriesInFile) readers[sno][fno].setSeries(getSeries());
if (ino < readers[sno][fno].getImageCount()) {
return readers[sno][fno].openBytes(ino);
}
sno = getSeries();
// return a blank image to cover for the fact that
// this file does not contain enough image planes
if (blankBytes[sno] == null) {
int bytes = FormatTools.getBytesPerPixel(getPixelType());
blankBytes[sno] = new byte[core.sizeX[sno] * core.sizeY[sno] *
bytes * getRGBChannelCount()];
}
return blankBytes[sno];
}
/* @see IFormatReader#openBytes(int, int, int, int, int) */
public byte[] openBytes(int no, int x, int y, int w, int h)
throws FormatException, IOException
{
byte[] buffer = new byte[w * h *
FormatTools.getBytesPerPixel(getPixelType()) * getRGBChannelCount()];
return openBytes(no, buffer, x, y, w, h);
}
/* @see IFormatReader#openBytes(int, byte[]) */
public byte[] openBytes(int no, byte[] buf)
throws FormatException, IOException
{
FormatTools.assertId(currentId, true, 2);
int[] q = computeIndices(no);
int sno = seriesInFile ? 0 : getSeries();
int fno = q[0], ino = q[1];
if (seriesInFile) readers[sno][fno].setSeries(getSeries());
if (ino < readers[sno][fno].getImageCount()) {
return readers[sno][fno].openBytes(ino, buf);
}
// return a blank image to cover for the fact that
// this file does not contain enough image planes
Arrays.fill(buf, (byte) 0);
return buf;
}
/* @see IFormatReader#openBytes(int, byte[], int, int, int, int) */
public byte[] openBytes(int no, byte[] buf, int x, int y, int w, int h)
throws FormatException, IOException
{
byte[] bytes = openBytes(no);
int bpp = FormatTools.getBytesPerPixel(getPixelType());
int ch = getRGBChannelCount();
if (buf.length < w * h * bpp * ch) {
throw new FormatException("Buffer too small.");
}
for (int yy=y; yy<y + h; yy++) {
for (int xx=x; xx<x + w; xx++) {
for (int cc=0; cc<ch; cc++) {
int oldNdx = -1, newNdx = -1;
if (isInterleaved()) {
oldNdx = yy*getSizeX()*bpp*ch + xx*bpp*ch + cc*bpp;
newNdx = (yy - y)*w*bpp*ch + (xx - x)*bpp*ch + cc*bpp;
}
else {
oldNdx = cc*getSizeX()*getSizeY()*bpp + yy*getSizeX()*bpp + xx*bpp;
newNdx = cc*w*h*bpp + (yy - y)*w*bpp + (xx - x)*bpp;
}
System.arraycopy(bytes, oldNdx, buf, newNdx, bpp);
}
}
}
return buf;
}
/* @see IFormatReader#openThumbImage(int) */
public BufferedImage openThumbImage(int no)
throws FormatException, IOException
{
FormatTools.assertId(currentId, true, 2);
int[] q = computeIndices(no);
int sno = seriesInFile ? 0 : getSeries();
int fno = q[0], ino = q[1];
if (seriesInFile) readers[sno][fno].setSeries(getSeries());
if (ino < readers[sno][fno].getImageCount()) {
return readers[sno][fno].openThumbImage(ino);
}
sno = getSeries();
// return a blank image to cover for the fact that
// this file does not contain enough image planes
if (blankThumb[sno] == null) {
blankThumb[sno] = ImageTools.blankImage(getThumbSizeX(),
getThumbSizeY(), sizeC[sno], getPixelType());
}
return blankThumb[sno];
}
/* @see IFormatReader#openThumbBytes(int) */
public byte[] openThumbBytes(int no) throws FormatException, IOException {
FormatTools.assertId(currentId, true, 2);
int[] q = computeIndices(no);
int sno = seriesInFile ? 0 : getSeries();
int fno = q[0], ino = q[1];
if (seriesInFile) readers[sno][fno].setSeries(getSeries());
if (ino < readers[sno][fno].getImageCount()) {
return readers[sno][fno].openThumbBytes(ino);
}
sno = getSeries();
// return a blank image to cover for the fact that
// this file does not contain enough image planes
if (blankThumbBytes[sno] == null) {
int bytes = FormatTools.getBytesPerPixel(getPixelType());
blankThumbBytes[sno] = new byte[getThumbSizeX() * getThumbSizeY() *
bytes * getRGBChannelCount()];
}
return blankThumbBytes[sno];
}
/* @see IFormatReader#close(boolean) */
public void close(boolean fileOnly) throws IOException {
if (readers == null) reader.close(fileOnly);
else {
for (int i=0; i<readers.length; i++) {
for (int j=0; j<readers[i].length; j++) {
readers[i][j].close(fileOnly);
}
}
}
if (!fileOnly) {
readers = null;
blankImage = null;
blankBytes = null;
currentId = null;
}
}
/* @see IFormatReader#close() */
public void close() throws IOException {
if (readers == null) reader.close();
else {
for (int i=0; i<readers.length; i++) {
for (int j=0; j<readers[i].length; j++) {
readers[i][j].close();
}
}
}
readers = null;
blankImage = null;
blankBytes = null;
currentId = null;
}
/* @see IFormatReader#getSeriesCount() */
public int getSeriesCount() {
FormatTools.assertId(currentId, true, 2);
return core.sizeX.length;
}
/* @see IFormatReader#setSeries(int) */
public void setSeries(int no) {
FormatTools.assertId(currentId, true, 2);
int n = reader.getSeriesCount();
if (n > 1) reader.setSeries(no);
else series = no;
}
/* @see IFormatReader#getSeries() */
public int getSeries() {
FormatTools.assertId(currentId, true, 2);
return seriesInFile ? reader.getSeries() : series;
}
/* @see IFormatReader#setGroupFiles(boolean) */
public void setGroupFiles(boolean group) {
for (int i=0; i<readers.length; i++) {
for (int j=0; j<readers[i].length; j++) {
readers[i][j].setGroupFiles(group);
}
}
}
/* @see IFormatReader#isGroupFiles() */
public boolean isGroupFiles() {
return readers[0][0].isGroupFiles();
}
/* @see IFormatReader#fileGroupOption(String) */
public int fileGroupOption(String id) throws FormatException, IOException {
return readers[0][0].fileGroupOption(id);
}
/* @see IFormatReader#isMetadataComplete() */
public boolean isMetadataComplete() {
return readers[0][0].isMetadataComplete();
}
/* @see IFormatReader#setNormalized(boolean) */
public void setNormalized(boolean normalize) {
FormatTools.assertId(currentId, false, 2);
if (readers == null) reader.setNormalized(normalize);
else {
for (int i=0; i<readers.length; i++) {
for (int j=0; j<readers[i].length; j++) {
readers[i][j].setNormalized(normalize);
}
}
}
}
/* @see IFormatReader#isNormalized() */
public boolean isNormalized() { return reader.isNormalized(); }
/* @see IFormatReader#setMetadataCollected(boolean) */
public void setMetadataCollected(boolean collect) {
FormatTools.assertId(currentId, false, 2);
if (readers == null) reader.setMetadataCollected(collect);
else {
for (int i=0; i<readers.length; i++) {
for (int j=0; j<readers[i].length; j++) {
readers[i][j].setMetadataCollected(collect);
}
}
}
}
/* @see IFormatReader#isMetadataCollected() */
public boolean isMetadataCollected() {
return reader.isMetadataCollected();
}
/* @see IFormatReader#setOriginalMetadataPopulated(boolean) */
public void setOriginalMetadataPopulated(boolean populate) {
FormatTools.assertId(currentId, false, 1);
if (readers == null) reader.setOriginalMetadataPopulated(populate);
else {
for (int i=0; i<readers.length; i++) {
for (int j=0; j<readers[i].length; j++) {
readers[i][j].setOriginalMetadataPopulated(populate);
}
}
}
}
/* @see IFormatReader#isOriginalMetadataPopulated() */
public boolean isOriginalMetadataPopulated() {
return reader.isOriginalMetadataPopulated();
}
/* @see IFormatReader#getUsedFiles() */
public String[] getUsedFiles() {
FormatTools.assertId(currentId, true, 2);
// returning the files list directly here is fast, since we do not
// have to call initFile on each constituent file; but we can only do so
// when each constituent file does not itself have multiple used files
if (reader.getUsedFiles().length > 1) {
// each constituent file has multiple used files; we must build the list
// this could happen with, e.g., a stitched collection of ICS/IDS pairs
// we have no datasets structured this way, so this logic is untested
/*
if (usedFiles == null) {
String[][][] used = new String[files.length][][];
int total = 0;
for (int i=0; i<files.length; i++) {
for (int j=0; j<files[i].length; j++) {
try {
readers[i][j].setId(files[i][j]);
}
catch (FormatException exc) {
LogTools.trace(exc);
return null;
}
catch (IOException exc) {
LogTools.trace(exc);
return null;
}
used[i][j] = readers[i][j].getUsedFiles();
total += used[i][j].length;
}
}
usedFiles = new String[total];
for (int i=0, off=0; i<used.length; i++) {
for (int j=0; j<used[i].length; j++) {
System.arraycopy(used[i][j], 0, usedFiles, off, used[i][j].length);
off += used[i][j].length;
}
}
}
*/
return reader.getUsedFiles();
}
// assume every constituent file has no other used files
// this logic could fail if the first constituent has no extra used files,
// but later constituents do; in practice, this scenario seems unlikely
Vector v = new Vector();
for (int i=0; i<files.length; i++) {
for (int j=0; j<files[i].length; j++) {
v.add(files[i][j]);
}
}
return (String[]) v.toArray(new String[0]);
}
/* @see IFormatReader#getCurrentFile() */
public String getCurrentFile() { return currentId; }
/* @see IFormatReader#getIndex(int, int, int) */
public int getIndex(int z, int c, int t) {
return FormatTools.getIndex(this, z, c, t);
}
/* @see IFormatReader#getZCTCoords(int) */
public int[] getZCTCoords(int index) {
return FormatTools.getZCTCoords(this, index);
}
/* @see IFormatReader#getMetadataValue(String) */
public Object getMetadataValue(String field) {
FormatTools.assertId(currentId, true, 2);
return reader.getMetadataValue(field);
}
/* @see IFormatReader#getMetadata() */
public Hashtable getMetadata() {
FormatTools.assertId(currentId, true, 2);
return reader.getMetadata();
}
/* @see IFormatReader#getCoreMetadata() */
public CoreMetadata getCoreMetadata() {
FormatTools.assertId(currentId, true, 2);
return core;
}
/* @see IFormatReader#setMetadataFiltered(boolean) */
public void setMetadataFiltered(boolean filter) {
FormatTools.assertId(currentId, false, 2);
reader.setMetadataFiltered(filter);
}
/* @see IFormatReader#isMetadataFiltered() */
public boolean isMetadataFiltered() {
return reader.isMetadataFiltered();
}
/* @see IFormatReader#setMetadataStore(MetadataStore) */
public void setMetadataStore(MetadataStore store) {
FormatTools.assertId(currentId, false, 2);
reader.setMetadataStore(store);
}
/* @see IFormatReader#getMetadataStore() */
public MetadataStore getMetadataStore() {
FormatTools.assertId(currentId, true, 2);
return reader.getMetadataStore();
}
/* @see IFormatReader#getMetadataStoreRoot() */
public Object getMetadataStoreRoot() {
FormatTools.assertId(currentId, true, 2);
return reader.getMetadataStoreRoot();
}
/* @see IFormatReader#getUnderlyingReaders() */
public IFormatReader[] getUnderlyingReaders() {
Vector v = new Vector();
for (int i=0; i<readers.length; i++) {
for (int j=0; j<readers[i].length; j++) {
v.add(readers[i][j]);
}
}
return (IFormatReader[]) v.toArray(new IFormatReader[0]);
}
// -- IFormatHandler API methods --
/* @see IFormatHandler#isThisType(String) */
public boolean isThisType(String name) {
return reader.isThisType(name);
}
/* @see IFormatHandler#isThisType(String, boolean) */
public boolean isThisType(String name, boolean open) {
return reader.isThisType(name, open);
}
/* @see IFormatHandler#getFormat() */
public String getFormat() {
FormatTools.assertId(currentId, true, 2);
return reader.getFormat();
}
/* @see IFormatHandler#getSuffixes() */
public String[] getSuffixes() {
return reader.getSuffixes();
}
// -- StatusReporter API methods --
/* @see IFormatHandler#addStatusListener(StatusListener) */
public void addStatusListener(StatusListener l) {
if (readers == null) reader.addStatusListener(l);
else {
for (int i=0; i<readers.length; i++) {
for (int j=0; j<readers[i].length; j++) {
readers[i][j].addStatusListener(l);
}
}
}
}
/* @see IFormatHandler#removeStatusListener(StatusListener) */
public void removeStatusListener(StatusListener l) {
if (readers == null) reader.removeStatusListener(l);
else {
for (int i=0; i<readers.length; i++) {
for (int j=0; j<readers[i].length; j++) {
readers[i][j].removeStatusListener(l);
}
}
}
}
/* @see IFormatHandler#getStatusListeners() */
public StatusListener[] getStatusListeners() {
return reader.getStatusListeners();
}
// -- Internal FormatReader API methods --
/** Initializes the given file. */
protected void initFile(String id) throws FormatException, IOException {
if (FormatHandler.debug) {
LogTools.println("calling FileStitcher.initFile(" + id + ")");
}
currentId = id;
fp = findPattern(currentId);
String[] tmpFiles = fp.getFiles();
Arrays.sort(tmpFiles);
fp = new FilePattern(new Location(tmpFiles[0]));
reader.setId(fp.getFiles()[0]);
// if this is a multi-series dataset, we need some special logic
AxisGuesser guesser = new AxisGuesser(fp, reader.getDimensionOrder(),
reader.getSizeZ(), reader.getSizeT(), reader.getEffectiveSizeC(),
reader.isOrderCertain());
int seriesCount = reader.getSeriesCount();
seriesInFile = true;
if (guesser.getAxisCountS() > 0) {
int[] count = fp.getCount();
int[] axes = guesser.getAxisTypes();
seriesInFile = false;
String[] blockPrefixes = fp.getPrefixes();
Vector sBlock = new Vector();
for (int i=0; i<axes.length; i++) {
if (axes[i] == AxisGuesser.S_AXIS) {
sBlock.add(blockPrefixes[i]);
}
}
seriesBlocks = (String[]) sBlock.toArray(new String[0]);
fileVector = new Vector();
seriesNames = new Vector();
String file = fp.getFiles()[0];
Location dir = new Location(file).getAbsoluteFile().getParentFile();
String dpath = dir.getAbsolutePath();
String[] fs = dir.list();
setFiles(fs, seriesBlocks[0], fp.getFirst()[0], fp.getLast()[0],
fp.getStep()[0], dpath, 0);
seriesCount = fileVector.size();
files = new String[seriesCount][];
for (int i=0; i<seriesCount; i++) {
files[i] = (String[]) fileVector.get(i);
}
}
// verify that file pattern is valid and matches existing files
String msg = " Please rename your files or disable file stitching.";
if (!fp.isValid()) {
throw new FormatException("Invalid " +
(patternIds ? "file pattern" : "filename") +
" (" + currentId + "): " + fp.getErrorMessage() + msg);
}
if (files == null) {
files = new String[1][];
files[0] = fp.getFiles();
}
if (files == null) {
throw new FormatException("No files matching pattern (" +
fp.getPattern() + "). " + msg);
}
for (int i=0; i<files.length; i++) {
for (int j=0; j<files[i].length; j++) {
if (!new Location(files[i][j]).exists()) {
throw new FormatException("File
" (" + files[i][j] + ") does not exist.");
}
}
}
// determine reader type for these files; assume all are the same type
Vector classes = new Vector();
IFormatReader r = reader;
while (r instanceof ReaderWrapper) {
classes.add(r.getClass());
r = ((ReaderWrapper) r).getReader();
}
if (r instanceof ImageReader) r = ((ImageReader) r).getReader(files[0][0]);
classes.add(r.getClass());
// construct list of readers for all files
readers = new IFormatReader[files.length][];
for (int i=0; i<readers.length; i++) {
readers[i] = new IFormatReader[files[i].length];
}
readers[0][0] = reader;
for (int i=0; i<readers.length; i++) {
for (int j=0; j<readers[i].length; j++) {
// use crazy reflection to instantiate a reader of the proper type
try {
r = null;
for (int k=classes.size()-1; k>=0; k
Class c = (Class) classes.elementAt(k);
if (r == null) r = (IFormatReader) c.newInstance();
else {
r = (IFormatReader) c.getConstructor(new Class[]
{IFormatReader.class}).newInstance(new Object[] {r});
}
}
readers[i][j] = (IFormatReader) r;
}
catch (InstantiationException exc) { LogTools.trace(exc); }
catch (IllegalAccessException exc) { LogTools.trace(exc); }
catch (NoSuchMethodException exc) { LogTools.trace(exc); }
catch (InvocationTargetException exc) { LogTools.trace(exc); }
}
}
// sync reader configurations with original reader
boolean normalized = reader.isNormalized();
boolean metadataFiltered = reader.isMetadataFiltered();
boolean metadataCollected = reader.isMetadataCollected();
StatusListener[] statusListeners = reader.getStatusListeners();
for (int i=0; i<readers.length; i++) {
for (int j=0; j<readers[i].length; j++) {
readers[i][j].setNormalized(normalized);
readers[i][j].setMetadataFiltered(metadataFiltered);
readers[i][j].setMetadataCollected(metadataCollected);
for (int k=0; k<statusListeners.length; k++) {
readers[i][j].addStatusListener(statusListeners[k]);
}
}
}
String[] originalUsedFiles = reader.getUsedFiles();
boolean doNotStitch = true;
for (int i=0; i<files.length; i++) {
for (int k=0; k<files[i].length; k++) {
boolean found = false;
for (int j=0; j<originalUsedFiles.length; j++) {
if (originalUsedFiles[j].endsWith(files[i][k])) {
found = true;
break;
}
}
if (!found) {
doNotStitch = false;
break;
}
}
}
if (doNotStitch) {
// the reader for this file uses its own stitching logic that is probably
// smarter than FileStitcher
readers = new IFormatReader[1][1];
readers[0][0] = reader;
String f = files[0][0];
files = new String[1][1];
files[0][0] = f;
fp = new FilePattern(files[0][0]);
}
ag = new AxisGuesser[seriesCount];
blankImage = new BufferedImage[seriesCount];
blankBytes = new byte[seriesCount][];
blankThumb = new BufferedImage[seriesCount];
blankThumbBytes = new byte[seriesCount][];
imagesPerFile = new int[seriesCount];
sizeZ = new int[seriesCount];
sizeC = new int[seriesCount];
sizeT = new int[seriesCount];
boolean[] certain = new boolean[seriesCount];
lenZ = new int[seriesCount][];
lenC = new int[seriesCount][];
lenT = new int[seriesCount][];
// analyze first file; assume each file has the same parameters
core = new CoreMetadata(seriesCount);
int oldSeries = reader.getSeries();
IFormatReader rr = reader;
for (int i=0; i<seriesCount; i++) {
if (seriesInFile) rr.setSeries(i);
else {
rr = readers[i][0];
rr.setId(files[i][0]);
}
core.sizeX[i] = rr.getSizeX();
core.sizeY[i] = rr.getSizeY();
// NB: core.sizeZ populated in computeAxisLengths below
// NB: core.sizeC populated in computeAxisLengths below
// NB: core.sizeT populated in computeAxisLengths below
core.pixelType[i] = rr.getPixelType();
imagesPerFile[i] = rr.getImageCount();
core.imageCount[i] =
imagesPerFile[i] * files[seriesInFile ? 0 : i].length;
core.thumbSizeX[i] = rr.getThumbSizeX();
core.thumbSizeY[i] = rr.getThumbSizeY();
// NB: core.cLengths[i] populated in computeAxisLengths below
// NB: core.cTypes[i] populated in computeAxisLengths below
core.currentOrder[i] = rr.getDimensionOrder();
// NB: core.orderCertain[i] populated below
core.rgb[i] = rr.isRGB();
core.littleEndian[i] = rr.isLittleEndian();
core.interleaved[i] = rr.isInterleaved();
core.seriesMetadata[i] = rr.getMetadata();
sizeZ[i] = rr.getSizeZ();
sizeC[i] = rr.getSizeC();
sizeT[i] = rr.getSizeT();
certain[i] = rr.isOrderCertain();
}
reader.setSeries(oldSeries);
// guess at dimensions corresponding to file numbering
for (int i=0; i<seriesCount; i++) {
ag[i] = new AxisGuesser(fp, core.currentOrder[i],
sizeZ[i], sizeT[i], sizeC[i], certain[i]);
}
// order may need to be adjusted
for (int i=0; i<seriesCount; i++) {
setSeries(i);
core.currentOrder[i] = ag[i].getAdjustedOrder();
core.orderCertain[i] = ag[i].isCertain();
computeAxisLengths();
}
setSeries(oldSeries);
// initialize used files list only when requested
usedFiles = null;
}
// -- Helper methods --
/** Computes axis length arrays, and total axis lengths. */
protected void computeAxisLengths() throws FormatException {
int sno = seriesInFile ? 0 : getSeries();
FilePattern p = new FilePattern(FilePattern.findPattern(files[sno][0],
new Location(files[sno][0]).getAbsoluteFile().getParentFile().getPath(),
files[sno]));
int[] count = p.getCount();
try {
readers[sno][0].setId(files[sno][0]);
readers[sno][0].setSeries(seriesInFile ? getSeries() : 0);
}
catch (IOException e) {
throw new FormatException(e);
}
ag[getSeries()] = new AxisGuesser(p, readers[sno][0].getDimensionOrder(),
readers[sno][0].getSizeZ(), readers[sno][0].getSizeT(),
readers[sno][0].getSizeC(), readers[sno][0].isOrderCertain());
sno = getSeries();
int[] axes = ag[sno].getAxisTypes();
int numZ = ag[sno].getAxisCountZ();
int numC = ag[sno].getAxisCountC();
int numT = ag[sno].getAxisCountT();
core.sizeZ[sno] = sizeZ[sno];
core.sizeC[sno] = sizeC[sno];
core.sizeT[sno] = sizeT[sno];
lenZ[sno] = new int[numZ + 1];
lenC[sno] = new int[numC + 1];
lenT[sno] = new int[numT + 1];
lenZ[sno][0] = sizeZ[sno];
lenC[sno][0] = sizeC[sno];
lenT[sno][0] = sizeT[sno];
for (int i=0, z=1, c=1, t=1; i<count.length; i++) {
switch (axes[i]) {
case AxisGuesser.Z_AXIS:
core.sizeZ[sno] *= count[i];
lenZ[sno][z++] = count[i];
break;
case AxisGuesser.C_AXIS:
core.sizeC[sno] *= count[i];
lenC[sno][c++] = count[i];
break;
case AxisGuesser.T_AXIS:
core.sizeT[sno] *= count[i];
lenT[sno][t++] = count[i];
break;
case AxisGuesser.S_AXIS:
break;
default:
throw new FormatException("Unknown axis type for axis
i + ": " + axes[i]);
}
}
int[] cLengths = reader.getChannelDimLengths();
String[] cTypes = reader.getChannelDimTypes();
int cCount = 0;
for (int i=0; i<cLengths.length; i++) {
if (cLengths[i] > 1) cCount++;
}
for (int i=1; i<lenC[sno].length; i++) {
if (lenC[sno][i] > 1) cCount++;
}
if (cCount == 0) {
core.cLengths[sno] = new int[] {1};
core.cTypes[sno] = new String[] {FormatTools.CHANNEL};
}
else {
core.cLengths[sno] = new int[cCount];
core.cTypes[sno] = new String[cCount];
}
int c = 0;
for (int i=0; i<cLengths.length; i++) {
if (cLengths[i] == 1) continue;
core.cLengths[sno][c] = cLengths[i];
core.cTypes[sno][c] = cTypes[i];
c++;
}
for (int i=1; i<lenC[sno].length; i++) {
if (lenC[sno][i] == 1) continue;
core.cLengths[sno][c] = lenC[sno][i];
core.cTypes[sno][c] = FormatTools.CHANNEL;
}
// populate metadata store
int pixelType = getPixelType();
boolean little = reader.isLittleEndian();
MetadataStore s = reader.getMetadataStore();
for (int i=0; i<core.sizeX.length; i++) {
if (seriesNames != null) {
s.setImage((String) seriesNames.get(i), null, null, new Integer(i));
}
}
FormatTools.populatePixels(s, this);
}
/**
* Gets the file index, and image index into that file,
* corresponding to the given global image index.
*
* @return An array of size 2, dimensioned {file index, image index}.
*/
protected int[] computeIndices(int no) throws FormatException, IOException {
int sno = getSeries();
int[] axes = ag[sno].getAxisTypes();
int[] count = fp.getCount();
// get Z, C and T positions
int[] zct = getZCTCoords(no);
zct[1] *= getRGBChannelCount();
int[] posZ = FormatTools.rasterToPosition(lenZ[sno], zct[0]);
int[] posC = FormatTools.rasterToPosition(lenC[sno], zct[1]);
int[] posT = FormatTools.rasterToPosition(lenT[sno], zct[2]);
// convert Z, C and T position lists into file index and image index
int[] pos = new int[axes.length];
int z = 1, c = 1, t = 1;
for (int i=0; i<axes.length; i++) {
if (axes[i] == AxisGuesser.Z_AXIS) pos[i] = posZ[z++];
else if (axes[i] == AxisGuesser.C_AXIS) pos[i] = posC[c++];
else if (axes[i] == AxisGuesser.T_AXIS) pos[i] = posT[t++];
else {
throw new FormatException("Unknown axis type for axis
i + ": " + axes[i]);
}
}
int fno = FormatTools.positionToRaster(count, pos);
if (seriesInFile) sno = 0;
// configure the reader, in case we haven't done this one yet
readers[sno][fno].setId(files[sno][fno]);
readers[sno][fno].setSeries(reader.getSeries());
int ino;
if (posZ[0] < readers[sno][fno].getSizeZ() &&
posC[0] < readers[sno][fno].getSizeC() &&
posT[0] < readers[sno][fno].getSizeT())
{
ino = FormatTools.getIndex(readers[sno][fno], posZ[0], posC[0], posT[0]);
}
else ino = Integer.MAX_VALUE; // coordinates out of range
return new int[] {fno, ino};
}
/**
* Gets a list of readers to include in relation to the given C position.
* @return Array with indices corresponding to the list of readers, and
* values indicating the internal channel index to use for that reader.
*/
protected int[] getIncludeList(int theC) throws FormatException, IOException {
int[] include = new int[readers.length];
Arrays.fill(include, -1);
for (int t=0; t<sizeT[getSeries()]; t++) {
for (int z=0; z<sizeZ[getSeries()]; z++) {
int no = getIndex(z, theC, t);
int[] q = computeIndices(no);
int fno = q[0], ino = q[1];
include[fno] = ino;
}
}
return include;
}
private FilePattern getPattern(String[] f, String dir, String block)
{
Vector v = new Vector();
for (int i=0; i<f.length; i++) {
if (f[i].indexOf(File.separator) != -1) {
f[i] = f[i].substring(f[i].lastIndexOf(File.separator) + 1);
}
if (dir.endsWith(File.separator)) f[i] = dir + f[i];
else f[i] = dir + File.separator + f[i];
if (f[i].indexOf(block) != -1 && new Location(f[i]).exists()) {
v.add(f[i].substring(f[i].lastIndexOf(File.separator) + 1));
}
}
f = (String[]) v.toArray(new String[0]);
return new FilePattern(FilePattern.findPattern(f[0], dir, f));
}
private void setFiles(String[] list, String prefix, BigInteger first,
BigInteger last, BigInteger step, String dir, int blockNum)
{
long f = first.longValue();
long l = last.longValue();
long s = step.longValue();
for (long i=f; i<=l; i+=s) {
FilePattern newPattern = getPattern(list, dir, prefix + i);
if (blockNum == seriesBlocks.length - 1) {
fileVector.add(newPattern.getFiles());
String name = newPattern.getPattern();
if (name.indexOf(File.separator) != -1) {
name = name.substring(name.lastIndexOf(File.separator) + 1);
}
seriesNames.add(name);
}
else {
String next = seriesBlocks[blockNum + 1];
String[] blocks = newPattern.getPrefixes();
BigInteger fi = null;
BigInteger la = null;
BigInteger st = null;
for (int q=0; q<blocks.length; q++) {
if (blocks[q].indexOf(next) != -1) {
fi = newPattern.getFirst()[q];
la = newPattern.getLast()[q];
st = newPattern.getStep()[q];
break;
}
}
setFiles(newPattern.getFiles(), next, fi, la, st, dir, blockNum + 1);
}
}
}
// -- Deprecated FileStitcher API methods --
/** @deprecated Replaced by {@link #getAxisTypes()} */
public int[] getAxisTypes(String id)
throws FormatException, IOException
{
setId(id);
return getAxisTypes();
}
/** @deprecated Replaced by {@link #setAxisTypes(int[])} */
public void setAxisTypes(String id, int[] axes)
throws FormatException, IOException
{
setId(id);
setAxisTypes(axes);
}
/** @deprecated Replaced by {@link #getFilePattern()} */
public FilePattern getFilePattern(String id)
throws FormatException, IOException
{
setId(id);
return getFilePattern();
}
/** @deprecated Replaced by {@link #getAxisGuesser()} */
public AxisGuesser getAxisGuesser(String id)
throws FormatException, IOException
{
setId(id);
return getAxisGuesser();
}
// -- Deprecated IFormatReader API methods --
/** @deprecated Replaced by {@link #getImageCount()} */
public int getImageCount(String id) throws FormatException, IOException {
setId(id);
return getImageCount();
}
/** @deprecated Replaced by {@link #isRGB()} */
public boolean isRGB(String id) throws FormatException, IOException {
setId(id);
return isRGB();
}
/** @deprecated Replaced by {@link #getSizeX()} */
public int getSizeX(String id) throws FormatException, IOException {
setId(id);
return getSizeX();
}
/** @deprecated Replaced by {@link #getSizeY()} */
public int getSizeY(String id) throws FormatException, IOException {
setId(id);
return getSizeY();
}
/** @deprecated Replaced by {@link #getSizeZ()} */
public int getSizeZ(String id) throws FormatException, IOException {
setId(id);
return getSizeZ();
}
/** @deprecated Replaced by {@link #getSizeC()} */
public int getSizeC(String id) throws FormatException, IOException {
setId(id);
return getSizeC();
}
/** @deprecated Replaced by {@link #getSizeT()} */
public int getSizeT(String id) throws FormatException, IOException {
setId(id);
return getSizeT();
}
/** @deprecated Replaced by {@link #getPixelType()} */
public int getPixelType(String id) throws FormatException, IOException {
setId(id);
return getPixelType();
}
/** @deprecated Replaced by {@link #getEffectiveSizeC()} */
public int getEffectiveSizeC(String id) throws FormatException, IOException {
setId(id);
return getEffectiveSizeC();
}
/** @deprecated Replaced by {@link #getRGBChannelCount()} */
public int getRGBChannelCount(String id) throws FormatException, IOException {
setId(id);
return getSizeC() / getEffectiveSizeC();
}
/** @deprecated Replaced by {@link #getChannelDimLengths()} */
public int[] getChannelDimLengths(String id)
throws FormatException, IOException
{
setId(id);
return getChannelDimLengths();
}
/** @deprecated Replaced by {@link #getChannelDimTypes()} */
public String[] getChannelDimTypes(String id)
throws FormatException, IOException
{
setId(id);
return getChannelDimTypes();
}
/** @deprecated Replaced by {@link #getThumbSizeX()} */
public int getThumbSizeX(String id) throws FormatException, IOException {
setId(id);
return getThumbSizeX();
}
/** @deprecated Replaced by {@link #getThumbSizeY()} */
public int getThumbSizeY(String id) throws FormatException, IOException {
setId(id);
return getThumbSizeY();
}
/** @deprecated Replaced by {@link #isLittleEndian()} */
public boolean isLittleEndian(String id) throws FormatException, IOException {
setId(id);
return isLittleEndian();
}
/** @deprecated Replaced by {@link #getDimensionOrder()} */
public String getDimensionOrder(String id)
throws FormatException, IOException
{
setId(id);
return getDimensionOrder();
}
/** @deprecated Replaced by {@link #isOrderCertain()} */
public boolean isOrderCertain(String id) throws FormatException, IOException {
setId(id);
return isOrderCertain();
}
/** @deprecated Replaced by {@link #isInterleaved()} */
public boolean isInterleaved(String id) throws FormatException, IOException {
setId(id);
return isInterleaved();
}
/** @deprecated Replaced by {@link #isInterleaved(int)} */
public boolean isInterleaved(String id, int subC)
throws FormatException, IOException
{
setId(id);
return isInterleaved(subC);
}
/** @deprecated Replaced by {@link #openImage(int)} */
public BufferedImage openImage(String id, int no)
throws FormatException, IOException
{
setId(id);
return openImage(no);
}
/** @deprecated Replaced by {@link #openBytes(int)} */
public byte[] openBytes(String id, int no)
throws FormatException, IOException
{
setId(id);
return openBytes(no);
}
/** @deprecated Replaced by {@link #openBytes(int, byte[])} */
public byte[] openBytes(String id, int no, byte[] buf)
throws FormatException, IOException
{
setId(id);
return openBytes(no, buf);
}
/** @deprecated Replaced by {@link #openThumbImage(int)} */
public BufferedImage openThumbImage(String id, int no)
throws FormatException, IOException
{
setId(id);
return openThumbImage(no);
}
/** @deprecated Replaced by {@link #openThumbImage(int)} */
public byte[] openThumbBytes(String id, int no)
throws FormatException, IOException
{
setId(id);
return openThumbBytes(no);
}
/** @deprecated Replaced by {@link #getSeriesCount()} */
public int getSeriesCount(String id) throws FormatException, IOException {
setId(id);
return getSeriesCount();
}
/** @deprecated Replaced by {@link #setSeries(int)} */
public void setSeries(String id, int no) throws FormatException, IOException {
setId(id);
setSeries(no);
}
/** @deprecated Replaced by {@link #getSeries()} */
public int getSeries(String id) throws FormatException, IOException {
setId(id);
return getSeries();
}
/** @deprecated Replaced by {@link #getUsedFiles()} */
public String[] getUsedFiles(String id) throws FormatException, IOException {
setId(id);
return getUsedFiles();
}
/** @deprecated Replaced by {@link #getIndex(int, int, int)} */
public int getIndex(String id, int z, int c, int t)
throws FormatException, IOException
{
setId(id);
return getIndex(z, c, t);
}
/** @deprecated Replaced by {@link #getZCTCoords(int)} */
public int[] getZCTCoords(String id, int index)
throws FormatException, IOException
{
setId(id);
return getZCTCoords(index);
}
/** @deprecated Replaced by {@link #getMetadataValue(String)} */
public Object getMetadataValue(String id, String field)
throws FormatException, IOException
{
setId(id);
return getMetadataValue(field);
}
/** @deprecated Replaced by {@link #getMetadata()} */
public Hashtable getMetadata(String id) throws FormatException, IOException {
setId(id);
return getMetadata();
}
/** @deprecated Replaced by {@link #getCoreMetadata()} */
public CoreMetadata getCoreMetadata(String id)
throws FormatException, IOException
{
setId(id);
return getCoreMetadata();
}
/** @deprecated Replaced by {@link #getMetadataStore()} */
public MetadataStore getMetadataStore(String id)
throws FormatException, IOException
{
setId(id);
return getMetadataStore();
}
/** @deprecated Replaced by {@link #getMetadataStoreRoot()} */
public Object getMetadataStoreRoot(String id)
throws FormatException, IOException
{
setId(id);
return getMetadataStoreRoot();
}
} |
package org.bimserver.plugins;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import java.nio.file.FileSystem;
import java.nio.file.FileSystemNotFoundException;
import java.nio.file.FileSystems;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
import java.util.jar.JarInputStream;
import java.util.zip.ZipEntry;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;
import org.bimserver.BimserverDatabaseException;
import org.bimserver.emf.MetaDataManager;
import org.bimserver.emf.Schema;
import org.bimserver.interfaces.objects.SPluginInformation;
import org.bimserver.interfaces.objects.SPluginType;
import org.bimserver.models.store.Parameter;
import org.bimserver.models.store.ServiceDescriptor;
import org.bimserver.plugins.deserializers.DeserializeException;
import org.bimserver.plugins.deserializers.DeserializerPlugin;
import org.bimserver.plugins.deserializers.StreamingDeserializerPlugin;
import org.bimserver.plugins.modelchecker.ModelCheckerPlugin;
import org.bimserver.plugins.modelcompare.ModelComparePlugin;
import org.bimserver.plugins.modelmerger.ModelMergerPlugin;
import org.bimserver.plugins.queryengine.QueryEnginePlugin;
import org.bimserver.plugins.renderengine.RenderEnginePlugin;
import org.bimserver.plugins.serializers.MessagingSerializerPlugin;
import org.bimserver.plugins.serializers.MessagingStreamingSerializerPlugin;
import org.bimserver.plugins.serializers.SerializerPlugin;
import org.bimserver.plugins.serializers.StreamingSerializerPlugin;
import org.bimserver.plugins.services.BimServerClientInterface;
import org.bimserver.plugins.services.NewExtendedDataOnProjectHandler;
import org.bimserver.plugins.services.NewExtendedDataOnRevisionHandler;
import org.bimserver.plugins.services.NewRevisionHandler;
import org.bimserver.plugins.services.ServicePlugin;
import org.bimserver.plugins.stillimagerenderer.StillImageRenderPlugin;
import org.bimserver.plugins.web.WebModulePlugin;
import org.bimserver.shared.AuthenticationInfo;
import org.bimserver.shared.BimServerClientFactory;
import org.bimserver.shared.ChannelConnectionException;
import org.bimserver.shared.PluginClassLoaderProvider;
import org.bimserver.shared.ServiceFactory;
import org.bimserver.shared.exceptions.PluginException;
import org.bimserver.shared.exceptions.ServiceException;
import org.bimserver.shared.meta.SServicesMap;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class PluginManager implements PluginManagerInterface, PluginClassLoaderProvider {
private static final Logger LOGGER = LoggerFactory.getLogger(PluginManager.class);
private static Unmarshaller PLUGIN_DESCRIPTOR_UNMARSHALLER;
private final Map<Class<? extends Plugin>, Set<PluginContext>> implementations = new LinkedHashMap<>();
private final Map<Plugin, PluginContext> pluginToPluginContext = new HashMap<>();
private final Path tempDir;
private final String baseClassPath;
private final ServiceFactory serviceFactory;
private final NotificationsManagerInterface notificationsManagerInterface;
private final SServicesMap servicesMap;
private PluginChangeListener pluginChangeListener;
private BimServerClientFactory bimServerClientFactory;
private MetaDataManager metaDataManager;
private BasicServerInfoProvider basicServerInfoProvider;
static {
try {
JAXBContext jaxbContext = JAXBContext.newInstance(PluginDescriptor.class);
PLUGIN_DESCRIPTOR_UNMARSHALLER = jaxbContext.createUnmarshaller();
} catch (JAXBException e) {
LOGGER.error("", e);
}
}
public PluginManager(Path tempDir, String baseClassPath, ServiceFactory serviceFactory, NotificationsManagerInterface notificationsManagerInterface,
SServicesMap servicesMap, BasicServerInfoProvider basicServerInfoProvider) {
this.basicServerInfoProvider = basicServerInfoProvider;
LOGGER.debug("Creating new PluginManager");
this.tempDir = tempDir;
this.baseClassPath = baseClassPath;
this.serviceFactory = serviceFactory;
this.notificationsManagerInterface = notificationsManagerInterface;
this.servicesMap = servicesMap;
}
public PluginDescriptor getPluginDescriptor(InputStream inputStream) throws JAXBException, IOException {
try {
PluginDescriptor pluginDescriptor = (PluginDescriptor) PLUGIN_DESCRIPTOR_UNMARSHALLER.unmarshal(inputStream);
return pluginDescriptor;
} finally {
inputStream.close();
}
}
public PluginDescriptor getPluginDescriptor(byte[] bytes) throws JAXBException, IOException {
return getPluginDescriptor(new ByteArrayInputStream(bytes));
}
@SuppressWarnings({ "unchecked", "rawtypes" })
private <T> Map<PluginContext, T> getPlugins(Class<T> requiredInterfaceClass, boolean onlyEnabled) {
Map<PluginContext, T> plugins = new HashMap<>();
for (Class interfaceClass : implementations.keySet()) {
if (requiredInterfaceClass.isAssignableFrom(interfaceClass)) {
for (PluginContext pluginContext : implementations.get(interfaceClass)) {
if (!onlyEnabled || pluginContext.isEnabled()) {
plugins.put(pluginContext, (T) pluginContext.getPlugin());
}
}
}
}
return plugins;
}
public Map<PluginContext, RenderEnginePlugin> getAllRenderEnginePlugins(boolean onlyEnabled) {
return getPlugins(RenderEnginePlugin.class, onlyEnabled);
}
public Map<PluginContext, StillImageRenderPlugin> getAllStillImageRenderPlugins(boolean onlyEnabled) {
return getPlugins(StillImageRenderPlugin.class, onlyEnabled);
}
public Map<PluginContext, QueryEnginePlugin> getAllQueryEnginePlugins(boolean onlyEnabled) {
return getPlugins(QueryEnginePlugin.class, onlyEnabled);
}
public Map<PluginContext, SerializerPlugin> getAllSerializerPlugins(boolean onlyEnabled) {
return getPlugins(SerializerPlugin.class, onlyEnabled);
}
public Map<PluginContext, MessagingSerializerPlugin> getAllMessagingSerializerPlugins(boolean onlyEnabled) {
return getPlugins(MessagingSerializerPlugin.class, onlyEnabled);
}
public Map<PluginContext, MessagingStreamingSerializerPlugin> getAllMessagingStreamingSerializerPlugins(boolean onlyEnabled) {
return getPlugins(MessagingStreamingSerializerPlugin.class, onlyEnabled);
}
public Map<PluginContext, DeserializerPlugin> getAllDeserializerPlugins(boolean onlyEnabled) {
return getPlugins(DeserializerPlugin.class, onlyEnabled);
}
public Map<PluginContext, StreamingDeserializerPlugin> getAllStreamingDeserializerPlugins(boolean onlyEnabled) {
return getPlugins(StreamingDeserializerPlugin.class, onlyEnabled);
}
public Collection<StreamingDeserializerPlugin> getAllStreamingDeserializerPlugins(String extension, boolean onlyEnabled) {
Collection<StreamingDeserializerPlugin> allDeserializerPlugins = getAllStreamingDeserializerPlugins(onlyEnabled).values();
Iterator<StreamingDeserializerPlugin> iterator = allDeserializerPlugins.iterator();
while (iterator.hasNext()) {
StreamingDeserializerPlugin deserializerPlugin = iterator.next();
if (!deserializerPlugin.canHandleExtension(extension)) {
iterator.remove();
}
}
return allDeserializerPlugins;
}
public Map<PluginContext, StreamingSerializerPlugin> getAllStreamingSeserializerPlugins(boolean onlyEnabled) {
return getPlugins(StreamingSerializerPlugin.class, onlyEnabled);
}
public Map<PluginContext, Plugin> getAllPlugins(boolean onlyEnabled) {
return getPlugins(Plugin.class, onlyEnabled);
}
public PluginContext getPluginContext(Plugin plugin) {
PluginContext pluginContext = pluginToPluginContext.get(plugin);
if (pluginContext == null) {
throw new RuntimeException("No plugin context found for " + plugin);
}
return pluginContext;
}
public void enablePlugin(String name) {
for (Set<PluginContext> pluginContexts : implementations.values()) {
for (PluginContext pluginContext : pluginContexts) {
if (pluginContext.getPlugin().getClass().getName().equals(name)) {
pluginContext.setEnabled(true, true);
}
}
}
}
public void disablePlugin(String name) {
for (Set<PluginContext> pluginContexts : implementations.values()) {
for (PluginContext pluginContext : pluginContexts) {
if (pluginContext.getPlugin().getClass().getName().equals(name)) {
pluginContext.setEnabled(false, true);
}
}
}
}
public Plugin getPlugin(String identifier, boolean onlyEnabled) {
for (Set<PluginContext> pluginContexts : implementations.values()) {
for (PluginContext pluginContext : pluginContexts) {
if (pluginContext.getIdentifier().equals(identifier)) {
if (!onlyEnabled || pluginContext.isEnabled()) {
return pluginContext.getPlugin();
}
}
}
}
return null;
}
public boolean isEnabled(String className) {
return getPlugin(className, true) != null;
}
public void setPluginChangeListener(PluginChangeListener pluginChangeListener) {
this.pluginChangeListener = pluginChangeListener;
}
public Collection<DeserializerPlugin> getAllDeserializerPlugins(String extension, boolean onlyEnabled) {
Collection<DeserializerPlugin> allDeserializerPlugins = getAllDeserializerPlugins(onlyEnabled).values();
Iterator<DeserializerPlugin> iterator = allDeserializerPlugins.iterator();
while (iterator.hasNext()) {
DeserializerPlugin deserializerPlugin = iterator.next();
if (!deserializerPlugin.canHandleExtension(extension)) {
iterator.remove();
}
}
return allDeserializerPlugins;
}
public DeserializerPlugin requireDeserializer(String extension) throws DeserializeException {
Collection<DeserializerPlugin> allDeserializerPlugins = getAllDeserializerPlugins(extension, true);
if (allDeserializerPlugins.size() == 0) {
throw new DeserializeException("No deserializers found for type '" + extension + "'");
} else {
return allDeserializerPlugins.iterator().next();
}
}
public Path getTempDir() {
if (!Files.isDirectory(tempDir)) {
try {
Files.createDirectories(tempDir);
} catch (IOException e) {
e.printStackTrace();
}
}
return tempDir;
}
public PluginContext loadPlugin(PluginBundle pluginBundle, Class<? extends Plugin> interfaceClass, URI location, String classLocation, Plugin plugin, ClassLoader classLoader, PluginSourceType pluginType,
AbstractPlugin pluginImplementation, Set<org.bimserver.plugins.Dependency> dependencies, String identifier) throws PluginException {
LOGGER.debug("Loading plugin " + plugin.getClass().getSimpleName() + " of type " + interfaceClass.getSimpleName());
if (!Plugin.class.isAssignableFrom(interfaceClass)) {
throw new PluginException("Given interface class (" + interfaceClass.getName() + ") must be a subclass of " + Plugin.class.getName());
}
if (!implementations.containsKey(interfaceClass)) {
implementations.put(interfaceClass, new LinkedHashSet<PluginContext>());
}
Set<PluginContext> set = (Set<PluginContext>) implementations.get(interfaceClass);
try {
PluginContext pluginContext = new PluginContext(this, pluginBundle, interfaceClass, classLoader, pluginType, pluginImplementation.getDescription(), location, plugin, classLocation, dependencies, identifier);
pluginToPluginContext.put(plugin, pluginContext);
set.add(pluginContext);
return pluginContext;
} catch (IOException e) {
throw new PluginException(e);
}
}
/**
* This method will initialize all the loaded plugins
*
* @throws PluginException
*/
public void initAllLoadedPlugins() throws PluginException {
LOGGER.debug("Initializig all loaded plugins");
for (Class<? extends Plugin> pluginClass : implementations.keySet()) {
Set<PluginContext> set = implementations.get(pluginClass);
for (PluginContext pluginContext : set) {
try {
pluginContext.initialize(pluginContext.getSystemSettings());
} catch (Throwable e) {
LOGGER.error("", e);
pluginContext.setEnabled(false, false);
}
}
}
}
/*
* Returns a complete classpath for all loaded plugins
*/
public String getCompleteClassPath() {
StringBuilder sb = new StringBuilder();
if (baseClassPath != null) {
sb.append(baseClassPath + File.pathSeparator);
}
for (Class<? extends Plugin> pluginClass : implementations.keySet()) {
Set<PluginContext> set = implementations.get(pluginClass);
for (PluginContext pluginContext : set) {
sb.append(pluginContext.getClassLocation() + File.pathSeparator);
}
}
return sb.toString();
}
public DeserializerPlugin getFirstDeserializer(String extension, Schema schema, boolean onlyEnabled) throws PluginException {
Collection<DeserializerPlugin> allDeserializerPlugins = getAllDeserializerPlugins(extension, onlyEnabled);
Iterator<DeserializerPlugin> iterator = allDeserializerPlugins.iterator();
while (iterator.hasNext()) {
DeserializerPlugin next = iterator.next();
if (!next.getSupportedSchemas().contains(schema)) {
iterator.remove();
}
}
if (allDeserializerPlugins.size() == 0) {
throw new PluginException("No deserializers with extension " + extension + " found");
}
return allDeserializerPlugins.iterator().next();
}
public StreamingDeserializerPlugin getFirstStreamingDeserializer(String extension, Schema schema, boolean onlyEnabled) throws PluginException {
Collection<StreamingDeserializerPlugin> allDeserializerPlugins = getAllStreamingDeserializerPlugins(extension, onlyEnabled);
Iterator<StreamingDeserializerPlugin> iterator = allDeserializerPlugins.iterator();
while (iterator.hasNext()) {
StreamingDeserializerPlugin next = iterator.next();
if (!next.getSupportedSchemas().contains(schema)) {
iterator.remove();
}
}
if (allDeserializerPlugins.size() == 0) {
throw new PluginException("No deserializers with extension " + extension + " found");
}
return allDeserializerPlugins.iterator().next();
}
public RenderEnginePlugin getRenderEnginePlugin(String className, boolean onlyEnabled) {
return getPluginByClassName(RenderEnginePlugin.class, className, onlyEnabled);
}
private <T extends Plugin> T getPluginByClassName(Class<T> clazz, String className, boolean onlyEnabled) {
Collection<T> allPlugins = getPlugins(clazz, onlyEnabled).values();
for (T t : allPlugins) {
if (t.getClass().getName().equals(className)) {
return t;
}
}
return null;
}
public QueryEnginePlugin getQueryEngine(String className, boolean onlyEnabled) {
return getPluginByClassName(QueryEnginePlugin.class, className, onlyEnabled);
}
public Map<PluginContext, ModelMergerPlugin> getAllModelMergerPlugins(boolean onlyEnabled) {
return getPlugins(ModelMergerPlugin.class, onlyEnabled);
}
public Map<PluginContext, ModelComparePlugin> getAllModelComparePlugins(boolean onlyEnabled) {
return getPlugins(ModelComparePlugin.class, onlyEnabled);
}
public ModelMergerPlugin getModelMergerPlugin(String className, boolean onlyEnabled) {
return getPluginByClassName(ModelMergerPlugin.class, className, onlyEnabled);
}
public ModelComparePlugin getModelComparePlugin(String className, boolean onlyEnabled) {
return getPluginByClassName(ModelComparePlugin.class, className, onlyEnabled);
}
public Map<PluginContext, ServicePlugin> getAllServicePlugins(boolean onlyEnabled) {
return getPlugins(ServicePlugin.class, onlyEnabled);
}
public ServicePlugin getServicePlugin(String className, boolean onlyEnabled) {
return getPluginByClassName(ServicePlugin.class, className, onlyEnabled);
}
public ServiceFactory getServiceFactory() {
return serviceFactory;
}
public void registerNewRevisionHandler(long uoid, ServiceDescriptor serviceDescriptor, NewRevisionHandler newRevisionHandler) {
if (notificationsManagerInterface != null) {
notificationsManagerInterface.registerInternalNewRevisionHandler(uoid, serviceDescriptor, newRevisionHandler);
}
}
public void unregisterNewRevisionHandler(long uoid, ServiceDescriptor serviceDescriptor) {
if (notificationsManagerInterface != null) {
notificationsManagerInterface.unregisterInternalNewRevisionHandler(uoid, serviceDescriptor.getIdentifier());
}
}
public SServicesMap getServicesMap() {
return servicesMap;
}
public Parameter getParameter(PluginContext pluginContext, String name) {
return null;
}
public SerializerPlugin getSerializerPlugin(String className, boolean onlyEnabled) {
return (SerializerPlugin) getPlugin(className, onlyEnabled);
}
public MessagingSerializerPlugin getMessagingSerializerPlugin(String className, boolean onlyEnabled) {
return (MessagingSerializerPlugin) getPlugin(className, onlyEnabled);
}
public WebModulePlugin getWebModulePlugin(String className, boolean onlyEnabled) {
return (WebModulePlugin) getPlugin(className, onlyEnabled);
}
public Map<PluginContext, WebModulePlugin> getAllWebPlugins(boolean onlyEnabled) {
return getPlugins(WebModulePlugin.class, onlyEnabled);
}
public Map<PluginContext, ModelCheckerPlugin> getAllModelCheckerPlugins(boolean onlyEnabled) {
return getPlugins(ModelCheckerPlugin.class, onlyEnabled);
}
public ModelCheckerPlugin getModelCheckerPlugin(String className, boolean onlyEnabled) {
return getPluginByClassName(ModelCheckerPlugin.class, className, onlyEnabled);
}
public BimServerClientInterface getLocalBimServerClientInterface(AuthenticationInfo tokenAuthentication) throws ServiceException, ChannelConnectionException {
return bimServerClientFactory.create(tokenAuthentication);
}
public void setBimServerClientFactory(BimServerClientFactory bimServerClientFactory) {
this.bimServerClientFactory = bimServerClientFactory;
}
public void registerNewExtendedDataOnProjectHandler(long uoid, ServiceDescriptor serviceDescriptor, NewExtendedDataOnProjectHandler newExtendedDataHandler) {
if (notificationsManagerInterface != null) {
notificationsManagerInterface.registerInternalNewExtendedDataOnProjectHandler(uoid, serviceDescriptor, newExtendedDataHandler);
}
}
public void registerNewExtendedDataOnRevisionHandler(long uoid, ServiceDescriptor serviceDescriptor, NewExtendedDataOnRevisionHandler newExtendedDataHandler) {
if (notificationsManagerInterface != null) {
notificationsManagerInterface.registerInternalNewExtendedDataOnRevisionHandler(uoid, serviceDescriptor, newExtendedDataHandler);
}
}
public DeserializerPlugin getDeserializerPlugin(String pluginClassName, boolean onlyEnabled) {
return getPluginByClassName(DeserializerPlugin.class, pluginClassName, onlyEnabled);
}
public StreamingDeserializerPlugin getStreamingDeserializerPlugin(String pluginClassName, boolean onlyEnabled) {
return getPluginByClassName(StreamingDeserializerPlugin.class, pluginClassName, onlyEnabled);
}
public StreamingSerializerPlugin getStreamingSerializerPlugin(String pluginClassName, boolean onlyEnabled) {
return getPluginByClassName(StreamingSerializerPlugin.class, pluginClassName, onlyEnabled);
}
public MetaDataManager getMetaDataManager() {
return metaDataManager;
}
public void setMetaDataManager(MetaDataManager metaDataManager) {
this.metaDataManager = metaDataManager;
}
public FileSystem getOrCreateFileSystem(URI uri) throws IOException {
FileSystem fileSystem = null;
try {
fileSystem = FileSystems.getFileSystem(uri);
} catch (FileSystemNotFoundException e) {
Map<String, String> env = new HashMap<>();
env.put("create", "true");
fileSystem = FileSystems.newFileSystem(uri, env, null);
LOGGER.debug("Created VFS for " + uri);
}
return fileSystem;
}
public MessagingStreamingSerializerPlugin getMessagingStreamingSerializerPlugin(String className, boolean onlyEnabled) {
return (MessagingStreamingSerializerPlugin) getPlugin(className, onlyEnabled);
}
public List<SPluginInformation> getPluginInformationFromJar(Path file) throws PluginException, FileNotFoundException, IOException, JAXBException {
try (JarFile jarFile = new JarFile(file.toFile())) {
ZipEntry entry = jarFile.getEntry("plugin/plugin.xml");
if (entry == null) {
throw new PluginException("No plugin/plugin.xml found in " + file.getFileName().toString());
}
InputStream pluginStream = jarFile.getInputStream(entry);
return getPluginInformationFromPluginFile(pluginStream);
}
}
public List<SPluginInformation> getPluginInformationFromJar(InputStream jarInputStream) throws PluginException, FileNotFoundException, IOException, JAXBException {
try (JarInputStream jarInputStream2 = new JarInputStream(jarInputStream)) {
JarEntry next = jarInputStream2.getNextJarEntry();
while (next != null) {
if (next.getName().equals("plugin/plugin.xml")) {
return getPluginInformationFromPluginFile(jarInputStream2);
}
next = jarInputStream2.getNextJarEntry();
}
}
return null;
}
public List<SPluginInformation> getPluginInformationFromPluginFile(InputStream inputStream) throws PluginException, FileNotFoundException, IOException, JAXBException {
PluginDescriptor pluginDescriptor = getPluginDescriptor(inputStream);
if (pluginDescriptor == null) {
throw new PluginException("No plugin descriptor could be created");
}
List<SPluginInformation> list = new ArrayList<>();
processPluginDescriptor(pluginDescriptor, list);
return list;
}
public void processPluginDescriptor(PluginDescriptor pluginDescriptor, List<SPluginInformation> list) {
for (AbstractPlugin pluginImplementation : pluginDescriptor.getPlugins()) {
if (pluginImplementation instanceof JavaPlugin) {
JavaPlugin javaPlugin = (JavaPlugin) pluginImplementation;
SPluginInformation sPluginInformation = new SPluginInformation();
String name = javaPlugin.getName();
// TODO when all plugins have a name, this code can go
if (name == null) {
name = javaPlugin.getImplementationClass();
}
sPluginInformation.setName(name);
sPluginInformation.setDescription(javaPlugin.getDescription());
sPluginInformation.setEnabled(true);
// For java plugins we use the implementation class as
// identifier
sPluginInformation.setIdentifier(javaPlugin.getImplementationClass());
sPluginInformation.setType(getPluginTypeFromClass(javaPlugin.getInterfaceClass()));
list.add(sPluginInformation);
} else if (pluginImplementation instanceof org.bimserver.plugins.WebModulePlugin) {
org.bimserver.plugins.WebModulePlugin webModulePlugin = (org.bimserver.plugins.WebModulePlugin) pluginImplementation;
SPluginInformation sPluginInformation = new SPluginInformation();
sPluginInformation.setIdentifier(webModulePlugin.getIdentifier());
sPluginInformation.setName(webModulePlugin.getName());
sPluginInformation.setDescription(webModulePlugin.getDescription());
sPluginInformation.setType(SPluginType.WEB_MODULE);
sPluginInformation.setEnabled(true);
list.add(sPluginInformation);
}
}
}
public List<SPluginInformation> getPluginInformationFromPluginFile(Path file) throws PluginException, FileNotFoundException, IOException, JAXBException {
List<SPluginInformation> list = new ArrayList<>();
try (InputStream pluginStream = Files.newInputStream(file)) {
PluginDescriptor pluginDescriptor = getPluginDescriptor(pluginStream);
if (pluginDescriptor == null) {
throw new PluginException("No plugin descriptor could be created");
}
processPluginDescriptor(pluginDescriptor, list);
}
return list;
}
public SPluginType getPluginTypeFromClass(String className) {
switch (className) {
case "org.bimserver.plugins.deserializers.DeserializerPlugin":
return SPluginType.DESERIALIZER;
case "org.bimserver.plugins.deserializers.StreamingDeserializerPlugin":
return SPluginType.DESERIALIZER;
case "org.bimserver.plugins.serializers.SerializerPlugin":
return SPluginType.SERIALIZER;
case "org.bimserver.plugins.serializers.StreamingSerializerPlugin":
return SPluginType.SERIALIZER;
case "org.bimserver.plugins.serializers.MessagingStreamingSerializerPlugin":
return SPluginType.SERIALIZER;
case "org.bimserver.plugins.serializers.MessagingSerializerPlugin":
return SPluginType.SERIALIZER;
case "org.bimserver.plugins.modelchecker.ModelCheckerPlugin":
return SPluginType.MODEL_CHECKER;
case "org.bimserver.plugins.modelmerger.ModelMergerPlugin":
return SPluginType.MODEL_MERGER;
case "org.bimserver.plugins.modelcompare.ModelComparePlugin":
return SPluginType.MODEL_COMPARE;
case "org.bimserver.plugins.objectidms.ObjectIDMPlugin":
return SPluginType.OBJECT_IDM;
case "org.bimserver.plugins.queryengine.QueryEnginePlugin":
return SPluginType.QUERY_ENGINE;
case "org.bimserver.plugins.services.ServicePlugin":
return SPluginType.SERVICE;
case "org.bimserver.plugins.renderengine.RenderEnginePlugin":
return SPluginType.RENDER_ENGINE;
case "org.bimserver.plugins.stillimagerenderer.StillImageRenderPlugin":
return SPluginType.STILL_IMAGE_RENDER;
case "org.bimserver.plugins.web.WebModulePlugin":
return SPluginType.WEB_MODULE;
}
return null;
}
@Override
public void notifyPluginStateChange(PluginContext pluginContext, boolean enabled) {
if (pluginChangeListener != null) {
pluginChangeListener.pluginStateChanged(pluginContext, enabled);
}
}
@Override
public SerializerPlugin getSerializerPlugin(String pluginClassName) {
return getPluginByClassName(SerializerPlugin.class, pluginClassName, true);
}
@Override
public BasicServerInfo getBasicServerInfo() {
return basicServerInfoProvider.getBasicServerInfo();
}
public long pluginBundleUpdated(PluginBundle pluginBundle) {
if (pluginChangeListener != null) {
return pluginChangeListener.pluginBundleUpdated(pluginBundle);
}
return -1;
}
public void pluginUpdated(long pluginBundleVersionId, PluginContext pluginContext, SPluginInformation sPluginInformation) throws BimserverDatabaseException {
if (pluginChangeListener != null) {
pluginChangeListener.pluginUpdated(pluginBundleVersionId, pluginContext, sPluginInformation);
}
}
public long pluginBundleInstalled(PluginBundle pluginBundle) {
if (pluginChangeListener != null) {
return pluginChangeListener.pluginBundleInstalled(pluginBundle);
}
return -1;
}
public void pluginInstalled(long pluginBundleVersionId, PluginContext pluginContext, SPluginInformation sPluginInformation) throws BimserverDatabaseException {
if (pluginChangeListener != null) {
pluginChangeListener.pluginInstalled(pluginBundleVersionId, pluginContext, sPluginInformation);
}
}
public void pluginUninstalled(PluginContext pluginContext) {
if (pluginChangeListener != null) {
pluginChangeListener.pluginUninstalled(pluginContext);
}
}
public void pluginBundleUninstalled(PluginBundle pluginBundle) {
if (pluginChangeListener != null) {
pluginChangeListener.pluginBundleUninstalled(pluginBundle);
}
}
public void removeImplementation(PluginContext pluginContext) {
Set<PluginContext> set = implementations.get(pluginContext.getPluginInterface());
set.remove(pluginContext);
}
@Override
public ClassLoader getClassLoaderFor(String pluginClassName) {
for (Class<? extends Plugin> class1 : implementations.keySet()) {
Set<PluginContext> set = implementations.get(class1);
for (PluginContext pluginContext : set) {
if (pluginContext.getPlugin().getClass().getName().contentEquals(pluginClassName)) {
return pluginContext.getPlugin().getClass().getClassLoader();
}
}
}
return getClass().getClassLoader();
}
} |
package slimpleslickgame;
import java.nio.ByteBuffer;
import org.newdawn.slick.GameContainer;
import org.newdawn.slick.Input;
import org.newdawn.slick.geom.Vector2f;
import client.ByteMonitor;
import util.EventProtocol;
public class LocalPlayer extends Player{
private GameContainer gc;
private ByteMonitor bm;
public LocalPlayer(GameContainer gc){
this.gc = gc;
}
@Override
public void update(int delta) {
processInput(gc.getInput());
super.updatePosition();
}
public void addByteMonitor(ByteMonitor bm){
this.bm = bm;
}
private boolean processInput(Input input) {
Vector2f direction = new Vector2f(0, 0);
boolean dirChanged = false;
if (input.isKeyDown(Input.KEY_LEFT)) {
direction.add(new Vector2f(-1, 0));
dirChanged = true;
}
if (input.isKeyDown(Input.KEY_RIGHT)) {
direction.add(new Vector2f(1, 0));
dirChanged = true;
}
if (input.isKeyDown(Input.KEY_UP)) {
direction.add(new Vector2f(0, -1));
dirChanged = true;
}
if (input.isKeyDown(Input.KEY_DOWN)) {
direction.add(new Vector2f(0, 1));
dirChanged = true;
}
if(bm != null){
bm.putArrayToServer(getPositionBytes(position));
}
System.out.println("Input processed, direction: " + direction);
// TODO: add shooting capabilities
super.setDirection(direction);
return dirChanged;
}
public byte[] appendByteArray(byte[] first, byte[] second){
byte[] both = new byte[first.length + second.length];
for(int i = 0 ; i < first.length; i++){
both[i] = first[i];
}
for(int i = 0 ; i < second.length; i++){
both[i+first.length] = second[i];
}
return both;
}
public byte[] floatToByte(float f) {
return ByteBuffer.allocate(4).putFloat(f).array();
}
public byte[] getPositionBytes(Vector2f pos){
byte[] position = new byte[1];
position[0] = EventProtocol.PLAYER_POS;
byte[] x = floatToByte(pos.x);
byte[] y = floatToByte(pos.y);
byte[] both = appendByteArray(position, x);
both = appendByteArray(both, y);
return both;
}
} |
package com.lion.rmtsndcli;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import android.os.Bundle;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.SimpleAdapter;
public class MainActivity extends Activity {
public final static String EXTRA_MESSAGE = "com.lion.rmtsndcli.MESSAGE";
private ListView listView;
private SimpleAdapter adapter;
private List<Map<String, String>> data;
MainActivity mainActPtr;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = (ListView)findViewById(R.id.listView1);
data = new ArrayList<Map<String, String>>();
mainActPtr = this;
//read saved data from file into data
readDataFromFile();
adapter = new SimpleAdapter(this, data, android.R.layout.simple_list_item_2,
new String[] {"name", "ip"},
new int[] {android.R.id.text1,
android.R.id.text2});
listView.setAdapter(adapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, final View view, int position, long id) {
Map<String, String> datum = data.get(position);
String message = datum.get("ip");
startClientActivity(message);
}
});
listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
@Override
public boolean onItemLongClick(AdapterView<?> parent, View view,
int position, long id) {
final int positionInList = position;
AlertDialog.Builder alert = new AlertDialog.Builder(mainActPtr);
alert.setTitle("Modify");
final Object item = parent.getItemAtPosition(positionInList);
if(item instanceof HashMap){
HashMap<String, String> datum = (HashMap<String,String>)item;
alert.setMessage(datum.get("name"));
}
alert.setPositiveButton("Delete", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
data.remove(positionInList);
writeDataToFile();
adapter.notifyDataSetChanged();
}
});
alert.setNegativeButton("Edit", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
// edit.
data.remove(positionInList);
HashMap<String, String> datum = (HashMap<String,String>)item;
String name = datum.get("name");
String ip = datum.get("ip");
getNameIpFromUser(name, ip);
}
});
alert.show();
return true;
}
});
}
private void readDataFromFile() {
// write to "addrList.txt";
String filename = "addrList.txt";
String string = "";
FileInputStream inputStream;
try {
inputStream = openFileInput(filename);
//inputStream.write(string.getBytes());
byte buffer[] = new byte[64];
int bytesAvailable = 0;
while((bytesAvailable = inputStream.read(buffer)) > 0){
string += new String(buffer, 0, bytesAvailable, Charset.defaultCharset());
}
inputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
//process string
while(string.length() > 0){
//find first pc
int sep = string.indexOf(',');
if(sep<0)break;
int eol = string.indexOf('\n');
if(eol<0 || eol<sep)break;
String name = string.substring(0, sep);
String ip = string.substring(sep+1, eol);
Map<String, String> datum = new HashMap<String, String>(2);
datum.put("name", name);
datum.put("ip", ip);
data.add(datum);
string = string.substring(eol+1);
}
}
/** Called when the user clicks the Send button */
public void onAddNewPCBtn(View view) {
getNameIpFromUser("","");
}
private int getNameIpFromUser(String name, String ip){
AlertDialog.Builder alert = new AlertDialog.Builder(this);
alert.setTitle("Add new PC");
alert.setMessage("Name, IP Address:");
// Set an EditText view to get user input
final LinearLayout linlay = new LinearLayout(this);
linlay.setOrientation(1); //vertical
final EditText nameInp = new EditText(this);
nameInp.setSingleLine();
nameInp.setText(name);
final EditText adrInp = new EditText(this);
adrInp.setSingleLine();
adrInp.setText(ip);
linlay.addView(nameInp);
linlay.addView(adrInp);
alert.setView(linlay);
alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
String namesValue = nameInp.getText().toString();
String ipValue = adrInp.getText().toString();
// Do something with value!
// update the ui list
Map<String, String> datum = new HashMap<String, String>(2);
datum.put("name", namesValue);
datum.put("ip", ipValue);
data.add(datum);
// save updated data to file
writeDataToFile();
adapter.notifyDataSetChanged();
}
});
alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
// Canceled.
}
});
alert.show();
return 0;
}
protected void writeDataToFile() {
// write to "addrList.txt";
String filename = "addrList.txt";
String string = "";
FileOutputStream outputStream;
for(int i = 0; i < data.size() ; i++)
{
string += data.get(i).get("name");
string += ",";
string += data.get(i).get("ip");
string += "\n";
}
try {
outputStream = openFileOutput(filename, Context.MODE_PRIVATE);
outputStream.write(string.getBytes());
outputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
}
public void startClientActivity(String message) {
// create new activity
Intent intent = new Intent(this, ClientActivity.class);
intent.putExtra(EXTRA_MESSAGE, message);
startActivity(intent);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
} |
package org.jasig.portal;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Hashtable;
import java.util.Vector;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMResult;
import javax.xml.transform.sax.SAXSource;
import org.jasig.portal.channels.CError;
import org.jasig.portal.security.IPerson;
import org.jasig.portal.security.ISecurityContext;
import org.jasig.portal.services.LogService;
import org.jasig.portal.utils.CounterStoreFactory;
import org.jasig.portal.utils.DocumentFactory;
import org.jasig.portal.utils.ICounterStore;
import org.jasig.portal.utils.IPortalDocument;
import org.jasig.portal.utils.ResourceLoader;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
/**
* SQL implementation for the 2.x relational database model
* @author George Lindholm
* @version $Revision$
*/
public class RDBMUserLayoutStore implements IUserLayoutStore {
//This class is instantiated ONCE so NO class variables can be used to keep state between calls
protected static int DEBUG = 0;
protected static final String channelPrefix = "n";
protected static final String folderPrefix = "s";
protected IChannelRegistryStore crs;
protected ICounterStore csdb;
/**
* LayoutStructure
* Encapsulate the layout structure
*/
protected final class LayoutStructure {
private class StructureParameter {
String name;
String value;
public StructureParameter(String name, String value) {
this.name = name;
this.value = value;
}
}
int structId;
int nextId;
int childId;
int chanId;
String name;
String type;
boolean hidden;
boolean unremovable;
boolean immutable;
ArrayList parameters;
public LayoutStructure(int structId, int nextId,int childId,int chanId, String hidden, String unremovable, String immutable) {
this.nextId = nextId;
this.childId = childId;
this.chanId = chanId;
this.structId = structId;
this.hidden = RDBMServices.dbFlag(hidden);
this.immutable = RDBMServices.dbFlag(immutable);
this.unremovable = RDBMServices.dbFlag(unremovable);
if (DEBUG > 1) {
System.err.println("New layout: id=" + structId + ", next=" + nextId + ", child=" + childId +", chan=" +chanId);
}
}
public void addFolderData(String name, String type) {
this.name = name;
this.type = type;
}
public boolean isChannel () {return chanId != 0;}
public void addParameter(String name, String value) {
if (parameters == null) {
parameters = new ArrayList(5);
}
parameters.add(new StructureParameter(name, value));
}
public int getNextId () {return nextId;}
public int getChildId () {return childId;}
public int getChanId () {return chanId;}
public Element getStructureDocument(Document doc) throws Exception {
Element structure = null;
if (isChannel()) {
ChannelDefinition channelDef = crs.getChannelDefinition(chanId);
if (channelDef != null && channelApproved(channelDef.getApprovalDate())) {
structure = channelDef.getDocument(doc, channelPrefix + structId);
} else {
// Create an error channel if channel is missing or not approved
ChannelDefinition cd = new ChannelDefinition(chanId);
cd.setTitle("Missing channel");
cd.setName("Missing channel");
cd.setTimeout(20000);
String missingChannel = "Unknown";
if (channelDef != null) {
missingChannel = channelDef.getName();
}
structure = cd.getDocument(doc, channelPrefix + structId,
"The '" + missingChannel + "' channel is no longer available. Please remove it from your layout.",
CError.CHANNEL_MISSING_EXCEPTION);
}
} else {
structure = doc.createElement("folder");
((IPortalDocument)doc).putIdentifier(folderPrefix+structId, structure);
structure.setAttribute("ID", folderPrefix + structId);
structure.setAttribute("name", name);
structure.setAttribute("type", (type != null ? type : "regular"));
}
structure.setAttribute("hidden", (hidden ? "true" : "false"));
structure.setAttribute("immutable", (immutable ? "true" : "false"));
structure.setAttribute("unremovable", (unremovable ? "true" : "false"));
if (parameters != null) {
for (int i = 0; i < parameters.size(); i++) {
StructureParameter sp = (StructureParameter)parameters.get(i);
if (!isChannel()) { // Folder
structure.setAttribute(sp.name, sp.value);
} else { // Channel
NodeList nodeListParameters = structure.getElementsByTagName("parameter");
for (int j = 0; j < nodeListParameters.getLength(); j++) {
Element parmElement = (Element)nodeListParameters.item(j);
NamedNodeMap nm = parmElement.getAttributes();
String nodeName = nm.getNamedItem("name").getNodeValue();
if (nodeName.equals(sp.name)) {
Node override = nm.getNamedItem("override");
if (override != null && override.getNodeValue().equals("yes")) {
Node valueNode = nm.getNamedItem("value");
valueNode.setNodeValue(sp.value);
}
}
}
}
}
}
return structure;
}
}
public RDBMUserLayoutStore () throws Exception {
crs = ChannelRegistryStoreFactory.getChannelRegistryStoreImpl();
csdb = CounterStoreFactory.getCounterStoreImpl();
if (RDBMServices.supportsOuterJoins) {
if (RDBMServices.joinQuery instanceof RDBMServices.JdbcDb) {
RDBMServices.joinQuery.addQuery("layout",
"{oj UP_LAYOUT_STRUCT ULS LEFT OUTER JOIN UP_LAYOUT_PARAM USP ON ULS.USER_ID = USP.USER_ID AND ULS.STRUCT_ID = USP.STRUCT_ID} WHERE");
RDBMServices.joinQuery.addQuery("ss_struct", "{oj UP_SS_STRUCT USS LEFT OUTER JOIN UP_SS_STRUCT_PAR USP ON USS.SS_ID=USP.SS_ID} WHERE");
RDBMServices.joinQuery.addQuery("ss_theme", "{oj UP_SS_THEME UTS LEFT OUTER JOIN UP_SS_THEME_PARM UTP ON UTS.SS_ID=UTP.SS_ID} WHERE");
} else if (RDBMServices.joinQuery instanceof RDBMServices.PostgreSQLDb) {
RDBMServices.joinQuery.addQuery("layout",
"UP_LAYOUT_STRUCT ULS LEFT OUTER JOIN UP_LAYOUT_PARAM USP ON ULS.USER_ID = USP.USER_ID AND ULS.STRUCT_ID = USP.STRUCT_ID WHERE");
RDBMServices.joinQuery.addQuery("ss_struct", "UP_SS_STRUCT USS LEFT OUTER JOIN UP_SS_STRUCT_PAR USP ON USS.SS_ID=USP.SS_ID WHERE");
RDBMServices.joinQuery.addQuery("ss_theme", "UP_SS_THEME UTS LEFT OUTER JOIN UP_SS_THEME_PARM UTP ON UTS.SS_ID=UTP.SS_ID WHERE");
} else if (RDBMServices.joinQuery instanceof RDBMServices.OracleDb) {
RDBMServices.joinQuery.addQuery("layout",
"UP_LAYOUT_STRUCT ULS, UP_LAYOUT_PARAM USP WHERE ULS.STRUCT_ID = USP.STRUCT_ID(+) AND ULS.USER_ID = USP.USER_ID(+) AND");
RDBMServices.joinQuery.addQuery("ss_struct", "UP_SS_STRUCT USS, UP_SS_STRUCT_PAR USP WHERE USS.SS_ID=USP.SS_ID(+) AND");
RDBMServices.joinQuery.addQuery("ss_theme", "UP_SS_THEME UTS, UP_SS_THEME_PARM UTP WHERE UTS.SS_ID=UTP.SS_ID(+) AND");
} else {
throw new Exception("Unknown database driver");
}
}
}
/**
* Registers a NEW structure stylesheet with the database.
* @param tsd the Stylesheet description object
* @return an <code>Integer</code> id for the registered Stylesheet description object
*/
public Integer addStructureStylesheetDescription (StructureStylesheetDescription ssd) throws Exception {
Connection con = RDBMServices.getConnection();
try {
// Set autocommit false for the connection
RDBMServices.setAutoCommit(con, false);
Statement stmt = con.createStatement();
try {
// we assume that this is a new stylesheet.
int id = csdb.getIncrementIntegerId("UP_SS_STRUCT");
ssd.setId(id);
String sQuery = "INSERT INTO UP_SS_STRUCT (SS_ID,SS_NAME,SS_URI,SS_DESCRIPTION_URI,SS_DESCRIPTION_TEXT) VALUES ("
+ id + ",'" + ssd.getStylesheetName() + "','" + ssd.getStylesheetURI() + "','" + ssd.getStylesheetDescriptionURI()
+ "','" + ssd.getStylesheetWordDescription() + "')";
LogService.log(LogService.DEBUG, "RDBMUserLayoutStore::addThemeStylesheetDescription(): " + sQuery);
stmt.executeUpdate(sQuery);
// insert all stylesheet params
for (Enumeration e = ssd.getStylesheetParameterNames(); e.hasMoreElements();) {
String pName = (String)e.nextElement();
sQuery = "INSERT INTO UP_SS_STRUCT_PAR (SS_ID,PARAM_NAME,PARAM_DEFAULT_VAL,PARAM_DESCRIPT,TYPE) VALUES (" + id
+ ",'" + pName + "','" + ssd.getStylesheetParameterDefaultValue(pName) + "','" + ssd.getStylesheetParameterWordDescription(pName)
+ "',1)";
LogService.log(LogService.DEBUG, "RDBMUserLayoutStore::addThemeStylesheetDescription(): " + sQuery);
stmt.executeUpdate(sQuery);
}
// insert all folder attributes
for (Enumeration e = ssd.getFolderAttributeNames(); e.hasMoreElements();) {
String pName = (String)e.nextElement();
sQuery = "INSERT INTO UP_SS_STRUCT_PAR (SS_ID,PARAM_NAME,PARAM_DEFAULT_VAL,PARAM_DESCRIPT,TYPE) VALUES (" + id
+ ",'" + pName + "','" + ssd.getFolderAttributeDefaultValue(pName) + "','" + ssd.getFolderAttributeWordDescription(pName)
+ "',2)";
LogService.log(LogService.DEBUG, "RDBMUserLayoutStore::addThemeStylesheetDescription(): " + sQuery);
stmt.executeUpdate(sQuery);
}
// insert all channel attributes
for (Enumeration e = ssd.getChannelAttributeNames(); e.hasMoreElements();) {
String pName = (String)e.nextElement();
sQuery = "INSERT INTO UP_SS_STRUCT_PAR (SS_ID,PARAM_NAME,PARAM_DEFAULT_VAL,PARAM_DESCRIPT,TYPE) VALUES (" + id
+ ",'" + pName + "','" + ssd.getChannelAttributeDefaultValue(pName) + "','" + ssd.getChannelAttributeWordDescription(pName)
+ "',3)";
LogService.log(LogService.DEBUG, "RDBMUserLayoutStore::addThemeStylesheetDescription(): " + sQuery);
stmt.executeUpdate(sQuery);
}
// Commit the transaction
RDBMServices.commit(con);
return new Integer(id);
} catch (Exception e) {
// Roll back the transaction
RDBMServices.rollback(con);
throw e;
} finally {
stmt.close();
}
} finally {
RDBMServices.releaseConnection(con);
}
}
/**
* Registers a NEW theme stylesheet with the database.
* @param tsd Stylesheet description object
* @return an <code>Integer</code> id of the registered Theme Stylesheet if successful;
* <code>null</code> otherwise.
*/
public Integer addThemeStylesheetDescription (ThemeStylesheetDescription tsd) throws Exception {
Connection con = RDBMServices.getConnection();
try {
// Set autocommit false for the connection
RDBMServices.setAutoCommit(con, false);
Statement stmt = con.createStatement();
try {
// we assume that this is a new stylesheet.
int id = csdb.getIncrementIntegerId("UP_SS_THEME");
tsd.setId(id);
String sQuery = "INSERT INTO UP_SS_THEME (SS_ID,SS_NAME,SS_URI,SS_DESCRIPTION_URI,SS_DESCRIPTION_TEXT,STRUCT_SS_ID,SAMPLE_URI,SAMPLE_ICON_URI,MIME_TYPE,DEVICE_TYPE,SERIALIZER_NAME,UP_MODULE_CLASS) VALUES ("
+ id + ",'" + tsd.getStylesheetName() + "','" + tsd.getStylesheetURI() + "','" + tsd.getStylesheetDescriptionURI()
+ "','" + tsd.getStylesheetWordDescription() + "'," + tsd.getStructureStylesheetId() + ",'" + tsd.getSamplePictureURI()
+ "','" + tsd.getSampleIconURI() + "','" + tsd.getMimeType() + "','" + tsd.getDeviceType() + "','" + tsd.getSerializerName()
+ "','" + tsd.getCustomUserPreferencesManagerClass() + "')";
LogService.log(LogService.DEBUG, "RDBMUserLayoutStore::addThemeStylesheetDescription(): " + sQuery);
stmt.executeUpdate(sQuery);
// insert all stylesheet params
for (Enumeration e = tsd.getStylesheetParameterNames(); e.hasMoreElements();) {
String pName = (String)e.nextElement();
sQuery = "INSERT INTO UP_SS_THEME_PARM (SS_ID,PARAM_NAME,PARAM_DEFAULT_VAL,PARAM_DESCRIPT,TYPE) VALUES (" + id +
",'" + pName + "','" + tsd.getStylesheetParameterDefaultValue(pName) + "','" + tsd.getStylesheetParameterWordDescription(pName)
+ "',1)";
LogService.log(LogService.DEBUG, "RDBMUserLayoutStore::addThemeStylesheetDescription(): " + sQuery);
stmt.executeUpdate(sQuery);
}
// insert all channel attributes
for (Enumeration e = tsd.getChannelAttributeNames(); e.hasMoreElements();) {
String pName = (String)e.nextElement();
sQuery = "INSERT INTO UP_SS_THEME_PARM (SS_ID,PARAM_NAME,PARAM_DEFAULT_VAL,PARAM_DESCRIPT,TYPE) VALUES (" + id +
",'" + pName + "','" + tsd.getChannelAttributeDefaultValue(pName) + "','" + tsd.getChannelAttributeWordDescription(pName)
+ "',3)";
LogService.log(LogService.DEBUG, "RDBMUserLayoutStore::addThemeStylesheetDescription(): " + sQuery);
stmt.executeUpdate(sQuery);
}
// Commit the transaction
RDBMServices.commit(con);
return new Integer(id);
} catch (Exception e) {
// Roll back the transaction
RDBMServices.rollback(con);
throw e;
} finally {
stmt.close();
}
} finally {
RDBMServices.releaseConnection(con);
}
}
/**
* Update the theme stylesheet description.
* @param stylesheetDescriptionURI
* @param stylesheetURI
* @param stylesheetId
* @return true if update succeeded, otherwise false
*/
public boolean updateThemeStylesheetDescription (String stylesheetDescriptionURI, String stylesheetURI, int stylesheetId) {
try {
Document stylesheetDescriptionXML = getDOM(stylesheetDescriptionURI);
String ssName = this.getRootElementTextValue(stylesheetDescriptionXML, "parentStructureStylesheet");
// should thrown an exception
if (ssName == null)
return false;
// determine id of the parent structure stylesheet
Integer ssId = getStructureStylesheetId(ssName);
// stylesheet not found, should thrown an exception here
if (ssId == null)
return false;
ThemeStylesheetDescription sssd = new ThemeStylesheetDescription();
sssd.setId(stylesheetId);
sssd.setStructureStylesheetId(ssId.intValue());
String xmlStylesheetName = this.getName(stylesheetDescriptionXML);
String xmlStylesheetDescriptionText = this.getDescription(stylesheetDescriptionXML);
sssd.setStylesheetName(xmlStylesheetName);
sssd.setStylesheetURI(stylesheetURI);
sssd.setStylesheetDescriptionURI(stylesheetDescriptionURI);
sssd.setStylesheetWordDescription(xmlStylesheetDescriptionText);
sssd.setMimeType(this.getRootElementTextValue(stylesheetDescriptionXML, "mimeType"));
LogService.log(LogService.DEBUG, "RDBMCoreStylesheetDescriptionStore::getThemeStylesheetDescription() : setting mimetype=\""
+ sssd.getMimeType() + "\"");
sssd.setSerializerName(this.getRootElementTextValue(stylesheetDescriptionXML, "serializer"));
LogService.log(LogService.DEBUG, "RDBMCoreStylesheetDescriptionStore::getThemeStylesheetDescription() : setting serializerName=\""
+ sssd.getSerializerName() + "\"");
sssd.setCustomUserPreferencesManagerClass(this.getRootElementTextValue(stylesheetDescriptionXML, "userPreferencesModuleClass"));
sssd.setSamplePictureURI(this.getRootElementTextValue(stylesheetDescriptionXML, "samplePictureURI"));
sssd.setSampleIconURI(this.getRootElementTextValue(stylesheetDescriptionXML, "sampleIconURI"));
sssd.setDeviceType(this.getRootElementTextValue(stylesheetDescriptionXML, "deviceType"));
// populate parameter and attriute tables
this.populateParameterTable(stylesheetDescriptionXML, sssd);
this.populateChannelAttributeTable(stylesheetDescriptionXML, sssd);
updateThemeStylesheetDescription(sssd);
} catch (Exception e) {
LogService.log(LogService.DEBUG, e);
return false;
}
return true;
}
/**
* Update the structure stylesheet description
* @param stylesheetDescriptionURI
* @param stylesheetURI
* @param stylesheetId
* @return true if update succeeded, otherwise false
*/
public boolean updateStructureStylesheetDescription (String stylesheetDescriptionURI, String stylesheetURI, int stylesheetId) {
try {
Document stylesheetDescriptionXML = getDOM(stylesheetDescriptionURI);
StructureStylesheetDescription fssd = new StructureStylesheetDescription();
String xmlStylesheetName = this.getName(stylesheetDescriptionXML);
String xmlStylesheetDescriptionText = this.getDescription(stylesheetDescriptionXML);
fssd.setId(stylesheetId);
fssd.setStylesheetName(xmlStylesheetName);
fssd.setStylesheetURI(stylesheetURI);
fssd.setStylesheetDescriptionURI(stylesheetDescriptionURI);
fssd.setStylesheetWordDescription(xmlStylesheetDescriptionText);
// populate parameter and attriute tables
this.populateParameterTable(stylesheetDescriptionXML, fssd);
this.populateFolderAttributeTable(stylesheetDescriptionXML, fssd);
this.populateChannelAttributeTable(stylesheetDescriptionXML, fssd);
// now write out the database record
updateStructureStylesheetDescription(fssd);
} catch (Exception e) {
LogService.log(LogService.DEBUG, e);
return false;
}
return true;
}
/**
* Add a structure stylesheet description
* @param stylesheetDescriptionURI
* @param stylesheetURI
* @return an <code>Integer</code> id of the registered Structure Stylesheet description object if successful;
* <code>null</code> otherwise.
*/
public Integer addStructureStylesheetDescription (String stylesheetDescriptionURI, String stylesheetURI) {
// need to read in the description file to obtain information such as name, word description and media list
try {
Document stylesheetDescriptionXML = getDOM(stylesheetDescriptionURI);
StructureStylesheetDescription fssd = new StructureStylesheetDescription();
String xmlStylesheetName = this.getName(stylesheetDescriptionXML);
String xmlStylesheetDescriptionText = this.getDescription(stylesheetDescriptionXML);
fssd.setStylesheetName(xmlStylesheetName);
fssd.setStylesheetURI(stylesheetURI);
fssd.setStylesheetDescriptionURI(stylesheetDescriptionURI);
fssd.setStylesheetWordDescription(xmlStylesheetDescriptionText);
// populate parameter and attriute tables
this.populateParameterTable(stylesheetDescriptionXML, fssd);
this.populateFolderAttributeTable(stylesheetDescriptionXML, fssd);
this.populateChannelAttributeTable(stylesheetDescriptionXML, fssd);
// now write out the database record
// first the basic record
//UserLayoutStoreFactory.getUserLayoutStoreImpl().addStructureStylesheetDescription(xmlStylesheetName, stylesheetURI, stylesheetDescriptionURI, xmlStylesheetDescriptionText);
return addStructureStylesheetDescription(fssd);
} catch (Exception e) {
LogService.log(LogService.DEBUG, e);
}
return null;
}
/**
* Add theme stylesheet description
* @param stylesheetDescriptionURI
* @param stylesheetURI
* @return an <code>Integer</code> id of the registered Theme Stylesheet if successful;
* <code>null</code> otherwise.
*/
public Integer addThemeStylesheetDescription (String stylesheetDescriptionURI, String stylesheetURI) {
// need to read iN the description file to obtain information such as name, word description and mime type list
try {
Document stylesheetDescriptionXML = getDOM(stylesheetDescriptionURI);
LogService.log(LogService.DEBUG, "RDBMCoreStylesheetDescriptionStore::addThemeStylesheetDescription() : stylesheet name = " + this.getName(stylesheetDescriptionXML));
LogService.log(LogService.DEBUG, "RDBMCoreStylesheetDescriptionStore::addThemeStylesheetDescription() : stylesheet description = " + this.getDescription(stylesheetDescriptionXML));
String ssName = this.getRootElementTextValue(stylesheetDescriptionXML, "parentStructureStylesheet");
// should thrown an exception
if (ssName == null)
return null;
// determine id of the parent structure stylesheet
Integer ssId = getStructureStylesheetId(ssName);
// stylesheet not found, should thrown an exception here
if (ssId == null)
return null;
ThemeStylesheetDescription sssd = new ThemeStylesheetDescription();
sssd.setStructureStylesheetId(ssId.intValue());
String xmlStylesheetName = this.getName(stylesheetDescriptionXML);
String xmlStylesheetDescriptionText = this.getDescription(stylesheetDescriptionXML);
sssd.setStylesheetName(xmlStylesheetName);
sssd.setStylesheetURI(stylesheetURI);
sssd.setStylesheetDescriptionURI(stylesheetDescriptionURI);
sssd.setStylesheetWordDescription(xmlStylesheetDescriptionText);
sssd.setMimeType(this.getRootElementTextValue(stylesheetDescriptionXML, "mimeType"));
LogService.log(LogService.DEBUG, "RDBMCoreStylesheetDescriptionStore::addThemeStylesheetDescription() : setting mimetype=\""
+ sssd.getMimeType() + "\"");
sssd.setSerializerName(this.getRootElementTextValue(stylesheetDescriptionXML, "serializer"));
LogService.log(LogService.DEBUG, "RDBMCoreStylesheetDescriptionStore::addThemeStylesheetDescription() : setting serializerName=\""
+ sssd.getSerializerName() + "\"");
sssd.setCustomUserPreferencesManagerClass(this.getRootElementTextValue(stylesheetDescriptionXML, "userPreferencesModuleClass"));
sssd.setSamplePictureURI(this.getRootElementTextValue(stylesheetDescriptionXML, "samplePictureURI"));
sssd.setSampleIconURI(this.getRootElementTextValue(stylesheetDescriptionXML, "sampleIconURI"));
sssd.setDeviceType(this.getRootElementTextValue(stylesheetDescriptionXML, "deviceType"));
// populate parameter and attriute tables
this.populateParameterTable(stylesheetDescriptionXML, sssd);
this.populateChannelAttributeTable(stylesheetDescriptionXML, sssd);
return addThemeStylesheetDescription(sssd);
} catch (Exception e) {
LogService.log(LogService.DEBUG, e);
}
return null;
}
/**
* Add a user profile
* @param person
* @param profile
* @return userProfile
* @exception Exception
*/
public UserProfile addUserProfile (IPerson person, UserProfile profile) throws Exception {
int userId = person.getID();
// generate an id for this profile
Connection con = RDBMServices.getConnection();
try {
int id = csdb.getIncrementIntegerId("UP_USER_PROFILE");
profile.setProfileId(id);
Statement stmt = con.createStatement();
try {
String sQuery = "INSERT INTO UP_USER_PROFILE (USER_ID,PROFILE_ID,PROFILE_NAME,STRUCTURE_SS_ID,THEME_SS_ID,DESCRIPTION) VALUES ("
+ userId + "," + profile.getProfileId() + ",'" + profile.getProfileName() + "'," + profile.getStructureStylesheetId()
+ "," + profile.getThemeStylesheetId() + ",'" + profile.getProfileDescription() + "')";
LogService.log(LogService.DEBUG, "RDBMUserLayoutStore::addUserProfile(): " + sQuery);
stmt.executeUpdate(sQuery);
} finally {
stmt.close();
}
} finally {
RDBMServices.releaseConnection(con);
}
return profile;
}
/**
* Checks if a channel has been approved
* @param approved Date
* @return boolean Channel is approved
*/
protected static boolean channelApproved(java.util.Date approvedDate) {
java.util.Date rightNow = new java.util.Date();
return (approvedDate != null && rightNow.after(approvedDate));
}
/**
* Create a layout
* @param doc
* @param stmt
* @param root
* @param userId
* @param profileId
* @param layoutId
* @param structId
* @param ap
* @exception java.sql.SQLException
*/
protected final void createLayout (HashMap layoutStructure, Document doc,
Element root, int structId) throws java.sql.SQLException, Exception {
while (structId != 0) {
if (DEBUG>1) {
System.err.println("CreateLayout(" + structId + ")");
}
LayoutStructure ls = (LayoutStructure) layoutStructure.get(new Integer(structId));
Element structure = ls.getStructureDocument(doc);
root.appendChild(structure);
if (!ls.isChannel()) { // Folder
createLayout(layoutStructure, doc, structure, ls.getChildId());
}
structId = ls.getNextId();
}
}
/**
* convert true/false into Y/N for database
* @param value to check
* @result boolean
*/
protected static final boolean xmlBool (String value) {
return (value != null && value.equals("true") ? true : false);
}
public void deleteUserProfile(IPerson person, int profileId) throws Exception {
int userId = person.getID();
deleteUserProfile(userId,profileId);
}
private Document getDOM(String uri) throws Exception {
DOMResult result = new DOMResult();
SAXSource source = new SAXSource(new InputSource(
ResourceLoader.getResourceAsStream(this.getClass(), uri)));
TransformerFactory tFactory = TransformerFactory.newInstance();
Transformer emptytr = tFactory.newTransformer();
emptytr.transform(source, result);
// need to return a Document
Node node = result.getNode();
if (node instanceof Document) {
return (Document)node;
}
Document dom = DocumentFactory.getNewDocument();
dom.appendChild(dom.importNode(node, true));
return dom;
}
private void deleteUserProfile(int userId, int profileId) throws Exception {
Connection con = RDBMServices.getConnection();
try {
Statement stmt = con.createStatement();
try {
String sQuery = "DELETE FROM UP_USER_PROFILE WHERE USER_ID=" + userId + " AND PROFILE_ID=" + Integer.toString(profileId);
LogService.log(LogService.DEBUG, "RDBMUserLayoutStore::deleteUserProfile() : " + sQuery);
stmt.executeUpdate(sQuery);
// remove profile mappings
sQuery= "DELETE FROM UP_USER_UA_MAP WHERE USER_ID=" + userId + " AND PROFILE_ID=" + Integer.toString(profileId);
LogService.log(LogService.DEBUG, "RDBMUserLayoutStore::deleteUserProfile() : " + sQuery);
stmt.executeUpdate(sQuery);
// remove parameter information
sQuery= "DELETE FROM UP_SS_USER_PARM WHERE USER_ID=" + userId + " AND PROFILE_ID=" + Integer.toString(profileId);
LogService.log(LogService.DEBUG, "RDBMUserLayoutStore::deleteUserProfile() : " + sQuery);
stmt.executeUpdate(sQuery);
sQuery= "DELETE FROM UP_SS_USER_ATTS WHERE USER_ID=" + userId + " AND PROFILE_ID=" + Integer.toString(profileId);
LogService.log(LogService.DEBUG, "RDBMUserLayoutStore::deleteUserProfile() : " + sQuery);
stmt.executeUpdate(sQuery);
} finally {
stmt.close();
}
} finally {
RDBMServices.releaseConnection(con);
}
}
/**
* Dump a document tree structure on stdout
* @param node
* @param indent
*/
public static final void dumpDoc (Node node, String indent) {
if (node == null) {
return;
}
if (node instanceof Element) {
System.err.print(indent + "element: tag=" + ((Element)node).getTagName() + " ");
}
else if (node instanceof Document) {
System.err.print("document:");
}
else {
System.err.print(indent + "node:");
}
System.err.println("name=" + node.getNodeName() + " value=" + node.getNodeValue());
NamedNodeMap nm = node.getAttributes();
if (nm != null) {
for (int i = 0; i < nm.getLength(); i++) {
System.err.println(indent + " " + nm.item(i).getNodeName() + ": '" + nm.item(i).getNodeValue() + "'");
}
System.err.println(indent + "
}
if (node.hasChildNodes()) {
dumpDoc(node.getFirstChild(), indent + " ");
}
dumpDoc(node.getNextSibling(), indent);
}
/**
*
* CoreStyleSheet
*
*/
public Hashtable getMimeTypeList () throws Exception {
Connection con = RDBMServices.getConnection();
try {
Statement stmt = con.createStatement();
try {
String sQuery = "SELECT A.MIME_TYPE, A.MIME_TYPE_DESCRIPTION FROM UP_MIME_TYPE A, UP_SS_MAP B WHERE B.MIME_TYPE=A.MIME_TYPE";
LogService.log(LogService.DEBUG, "RDBMUserLayoutStore::getMimeTypeList() : " + sQuery);
ResultSet rs = stmt.executeQuery(sQuery);
try {
Hashtable list = new Hashtable();
while (rs.next()) {
list.put(rs.getString("MIME_TYPE"), rs.getString("MIME_TYPE_DESCRIPTION"));
}
return list;
} finally {
rs.close();
}
} finally {
stmt.close();
}
} finally {
RDBMServices.releaseConnection(con);
}
}
/**
* Return the next available channel structure id for a user
* @param userId
* @return the next available channel structure id
*/
public String generateNewChannelSubscribeId (IPerson person) throws Exception {
return getNextStructId(person, channelPrefix);
}
/**
* Return the next available folder structure id for a user
* @param person
* @return a <code>String</code> that is the next free structure ID
* @exception Exception
*/
public String generateNewFolderId (IPerson person) throws Exception {
return getNextStructId(person, folderPrefix);
}
/**
* Return the next available structure id for a user
* @param person
* @param prefix
* @return next free structure ID
* @exception Exception
*/
protected String getNextStructId (IPerson person, String prefix) throws Exception {
int userId = person.getID();
Connection con = RDBMServices.getConnection();
try {
RDBMServices.setAutoCommit(con, false);
Statement stmt = con.createStatement();
try {
String sQuery = "SELECT NEXT_STRUCT_ID FROM UP_USER WHERE USER_ID=" + userId;
for (int i = 0; i < 25; i++) {
LogService.log(LogService.DEBUG, "RDBMUserLayoutStore::getNextStructId(): " + sQuery);
ResultSet rs = stmt.executeQuery(sQuery);
int currentStructId;
try {
rs.next();
currentStructId = rs.getInt(1);
} finally {
rs.close();
}
int nextStructId = currentStructId + 1;
try {
String sUpdate = "UPDATE UP_USER SET NEXT_STRUCT_ID=" + nextStructId + " WHERE USER_ID=" + userId + " AND NEXT_STRUCT_ID="
+ currentStructId;
LogService.log(LogService.DEBUG, "RDBMUserLayoutStore::getNextStructId(): " + sUpdate);
stmt.executeUpdate(sUpdate);
RDBMServices.commit(con);
return prefix + nextStructId;
} catch (SQLException sqle) {
RDBMServices.rollback(con);
// Assume a concurrent update. Try again after some random amount of milliseconds.
Thread.sleep(java.lang.Math.round(java.lang.Math.random()* 3 * 1000)); // Retry in up to 3 seconds
}
}
} finally {
stmt.close();
}
} finally {
RDBMServices.releaseConnection(con);
}
throw new SQLException("Unable to generate a new structure id for user " + userId);
}
/**
* Return the Structure ID tag
* @param structId
* @param chanId
* @return ID tag
*/
protected String getStructId(int structId, int chanId) {
if (chanId == 0) {
return folderPrefix + structId;
} else {
return channelPrefix + structId;
}
}
/**
* Obtain structure stylesheet description object for a given structure stylesheet id.
* @param id the id of the structure stylesheet
* @return structure stylesheet description
*/
public StructureStylesheetDescription getStructureStylesheetDescription (int stylesheetId) throws Exception {
StructureStylesheetDescription ssd = null;
Connection con = RDBMServices.getConnection();
Statement stmt = con.createStatement();
try {
int dbOffset = 0;
String sQuery = "SELECT SS_NAME,SS_URI,SS_DESCRIPTION_URI,SS_DESCRIPTION_TEXT";
if (RDBMServices.supportsOuterJoins) {
sQuery += ",TYPE,PARAM_NAME,PARAM_DEFAULT_VAL,PARAM_DESCRIPT FROM " + RDBMServices.joinQuery.getQuery("ss_struct");
dbOffset = 4;
} else {
sQuery += " FROM UP_SS_STRUCT USS WHERE";
}
sQuery += " USS.SS_ID=" + stylesheetId;
LogService.log(LogService.DEBUG, "RDBMUserLayoutStore::getStructureStylesheetDescription(): " + sQuery);
ResultSet rs = stmt.executeQuery(sQuery);
try {
if (rs.next()) {
ssd = new StructureStylesheetDescription();
ssd.setId(stylesheetId);
ssd.setStylesheetName(rs.getString(1));
ssd.setStylesheetURI(rs.getString(2));
ssd.setStylesheetDescriptionURI(rs.getString(3));
ssd.setStylesheetWordDescription(rs.getString(4));
}
if (!RDBMServices.supportsOuterJoins) {
rs.close();
// retrieve stylesheet params and attributes
sQuery = "SELECT TYPE,PARAM_NAME,PARAM_DEFAULT_VAL,PARAM_DESCRIPT FROM UP_SS_STRUCT_PAR WHERE SS_ID=" + stylesheetId;
LogService.log(LogService.DEBUG, "RDBMUserLayoutStore::getStructureStylesheetDescription(): " + sQuery);
rs = stmt.executeQuery(sQuery);
}
while (true) {
if (!RDBMServices.supportsOuterJoins && !rs.next()) {
break;
}
int type = rs.getInt(dbOffset + 1);
if (rs.wasNull()){
break;
}
if (type == 1) {
// param
ssd.addStylesheetParameter(rs.getString(dbOffset + 2), rs.getString(dbOffset + 3), rs.getString(dbOffset + 4));
}
else if (type == 2) {
// folder attribute
ssd.addFolderAttribute(rs.getString(dbOffset + 2), rs.getString(dbOffset + 3), rs.getString(dbOffset + 4));
}
else if (type == 3) {
// channel attribute
ssd.addChannelAttribute(rs.getString(dbOffset + 2), rs.getString(dbOffset + 3), rs.getString(dbOffset + 4));
}
else {
LogService.log(LogService.DEBUG, "RDBMUserLayoutStore::getStructureStylesheetDescription() : encountered param of unknown type! (stylesheetId="
+ stylesheetId + " param_name=\"" + rs.getString(dbOffset + 2) + "\" type=" + type + ").");
}
if (RDBMServices.supportsOuterJoins && !rs.next()) {
break;
}
}
} finally {
rs.close();
}
} finally {
stmt.close();
RDBMServices.releaseConnection(con);
}
return ssd;
}
/**
* Obtain ID for known structure stylesheet name
* @param ssName name of the structure stylesheet
* @return id or null if no stylesheet matches the name given.
*/
public Integer getStructureStylesheetId (String ssName) throws Exception {
Connection con = RDBMServices.getConnection();
try {
RDBMServices.setAutoCommit(con, false);
Statement stmt = con.createStatement();
try {
String sQuery = "SELECT SS_ID FROM UP_SS_STRUCT WHERE SS_NAME='" + ssName + "'";
ResultSet rs = stmt.executeQuery(sQuery);
if (rs.next()) {
int id = rs.getInt("SS_ID");
if (rs.wasNull()) {
id = 0;
}
return new Integer(id);
}
} finally {
stmt.close();
}
} finally {
RDBMServices.releaseConnection(con);
}
return null;
}
/**
* Obtain a list of structure stylesheet descriptions that have stylesheets for a given
* mime type.
* @param mimeType
* @return a mapping from stylesheet names to structure stylesheet description objects
*/
public Hashtable getStructureStylesheetList (String mimeType) throws Exception {
Connection con = RDBMServices.getConnection();
Hashtable list = new Hashtable();
try {
Statement stmt = con.createStatement();
try {
String sQuery = "SELECT A.SS_ID FROM UP_SS_STRUCT A, UP_SS_THEME B WHERE B.MIME_TYPE='" + mimeType + "' AND B.STRUCT_SS_ID=A.SS_ID";
LogService.log(LogService.DEBUG, "RDBMUserLayoutStore::getStructureStylesheeInfotList() : " + sQuery);
ResultSet rs = stmt.executeQuery(sQuery);
try {
while (rs.next()) {
StructureStylesheetDescription ssd = getStructureStylesheetDescription(rs.getInt("SS_ID"));
if (ssd != null)
list.put(new Integer(ssd.getId()), ssd);
}
} finally {
rs.close();
}
} finally {
stmt.close();
}
} finally {
RDBMServices.releaseConnection(con);
}
return list;
}
/**
* Obtain a list of strcture stylesheet descriptions registered on the system
* @return a <code>Hashtable</code> mapping stylesheet id (<code>Integer</code> objects) to {@link StructureStylesheetDescription} objects
* @exception Exception
*/
public Hashtable getStructureStylesheetList() throws Exception {
Connection con = RDBMServices.getConnection();
Hashtable list = new Hashtable();
try {
Statement stmt = con.createStatement();
try {
String sQuery = "SELECT SS_ID FROM UP_SS_STRUCT";
LogService.log(LogService.DEBUG, "RDBMUserLayoutStore::getStructureStylesheeList() : " + sQuery);
ResultSet rs = stmt.executeQuery(sQuery);
try {
while (rs.next()) {
StructureStylesheetDescription ssd = getStructureStylesheetDescription(rs.getInt("SS_ID"));
if (ssd != null)
list.put(new Integer(ssd.getId()), ssd);
}
} finally {
rs.close();
}
} finally {
stmt.close();
}
} finally {
RDBMServices.releaseConnection(con);
}
return list;
}
public StructureStylesheetUserPreferences getStructureStylesheetUserPreferences (IPerson person, int profileId, int stylesheetId) throws Exception {
int userId = person.getID();
StructureStylesheetUserPreferences ssup;
Connection con = RDBMServices.getConnection();
try {
Statement stmt = con.createStatement();
try {
// get stylesheet description
StructureStylesheetDescription ssd = getStructureStylesheetDescription(stylesheetId);
// get user defined defaults
String subSelectString = "SELECT LAYOUT_ID FROM UP_USER_PROFILE WHERE USER_ID=" + userId + " AND PROFILE_ID=" +
profileId;
LogService.log(LogService.DEBUG, "RDBMUserLayoutStore::getUserLayout(): " + subSelectString);
int layoutId;
ResultSet rs = stmt.executeQuery(subSelectString);
try {
rs.next();
layoutId = rs.getInt(1);
if (rs.wasNull()) {
layoutId = 0;
}
} finally {
rs.close();
}
if (layoutId == 0) { // First time, grab the default layout for this user
String sQuery = "SELECT USER_DFLT_USR_ID FROM UP_USER WHERE USER_ID=" + userId;
LogService.log(LogService.DEBUG, "RDBMUserLayoutStore::getUserLayout(): " + sQuery);
rs = stmt.executeQuery(sQuery);
try {
rs.next();
userId = rs.getInt(1);
} finally {
rs.close();
}
}
String sQuery = "SELECT PARAM_NAME, PARAM_VAL FROM UP_SS_USER_PARM WHERE USER_ID=" + userId + " AND PROFILE_ID="
+ profileId + " AND SS_ID=" + stylesheetId + " AND SS_TYPE=1";
LogService.log(LogService.DEBUG, "RDBMUserLayoutStore::getStructureStylesheetUserPreferences(): " + sQuery);
rs = stmt.executeQuery(sQuery);
try {
while (rs.next()) {
// stylesheet param
ssd.setStylesheetParameterDefaultValue(rs.getString(1), rs.getString(2));
//LogService.log(LogService.DEBUG,"RDBMUserLayoutStore::getStructureStylesheetUserPreferences() : read stylesheet param "+rs.getString("PARAM_NAME")+"=\""+rs.getString("PARAM_VAL")+"\"");
}
} finally {
rs.close();
}
ssup = new StructureStylesheetUserPreferences();
ssup.setStylesheetId(stylesheetId);
// fill stylesheet description with defaults
for (Enumeration e = ssd.getStylesheetParameterNames(); e.hasMoreElements();) {
String pName = (String)e.nextElement();
ssup.putParameterValue(pName, ssd.getStylesheetParameterDefaultValue(pName));
}
for (Enumeration e = ssd.getChannelAttributeNames(); e.hasMoreElements();) {
String pName = (String)e.nextElement();
ssup.addChannelAttribute(pName, ssd.getChannelAttributeDefaultValue(pName));
}
for (Enumeration e = ssd.getFolderAttributeNames(); e.hasMoreElements();) {
String pName = (String)e.nextElement();
ssup.addFolderAttribute(pName, ssd.getFolderAttributeDefaultValue(pName));
}
// get user preferences
sQuery = "SELECT PARAM_NAME, PARAM_VAL, PARAM_TYPE, ULS.STRUCT_ID, CHAN_ID FROM UP_SS_USER_ATTS UUSA, UP_LAYOUT_STRUCT ULS WHERE UUSA.USER_ID=" + userId + " AND PROFILE_ID="
+ profileId + " AND SS_ID=" + stylesheetId + " AND SS_TYPE=1 AND UUSA.STRUCT_ID = ULS.STRUCT_ID AND UUSA.USER_ID = ULS.USER_ID";
LogService.log(LogService.DEBUG, "RDBMUserLayoutStore::getStructureStylesheetUserPreferences(): " + sQuery);
rs = stmt.executeQuery(sQuery);
try {
while (rs.next()) {
String temp1=rs.getString(1); // Access columns left to right
String temp2=rs.getString(2);
int param_type = rs.getInt(3);
int structId = rs.getInt(4);
if (rs.wasNull()) {
structId = 0;
}
int chanId = rs.getInt(5);
if (rs.wasNull()) {
chanId = 0;
}
if (param_type == 1) {
// stylesheet param
LogService.log(LogService.ERROR, "RDBMUserLayoutStore::getStructureStylesheetUserPreferences() : stylesheet global params should be specified in the user defaults table ! UP_SS_USER_ATTS is corrupt. (userId="
+ Integer.toString(userId) + ", profileId=" + Integer.toString(profileId) + ", stylesheetId=" + Integer.toString(stylesheetId)
+ ", param_name=\"" + temp1 + "\", param_type=" + Integer.toString(param_type));
}
else if (param_type == 2) {
// folder attribute
ssup.setFolderAttributeValue(getStructId(structId,chanId), temp1, temp2);
//LogService.log(LogService.DEBUG,"RDBMUserLayoutStore::getStructureStylesheetUserPreferences() : read folder attribute "+rs.getString("PARAM_NAME")+"("+rs.getString("STRUCT_ID")+")=\""+rs.getString("PARAM_VAL")+"\"");
}
else if (param_type == 3) {
// channel attribute
ssup.setChannelAttributeValue(getStructId(structId,chanId), temp1, temp2);
//LogService.log(LogService.DEBUG,"RDBMUserLayoutStore::getStructureStylesheetUserPreferences() : read channel attribute "+rs.getString("PARAM_NAME")+"("+rs.getString("STRUCT_ID")+")=\""+rs.getString("PARAM_VAL")+"\"");
}
else {
// unknown param type
LogService.log(LogService.ERROR, "RDBMUserLayoutStore::getStructureStylesheetUserPreferences() : unknown param type encountered! DB corrupt. (userId="
+ Integer.toString(userId) + ", profileId=" + Integer.toString(profileId) + ", stylesheetId=" + Integer.toString(stylesheetId)
+ ", param_name=\"" + temp1 + "\", param_type=" + Integer.toString(param_type));
}
}
} finally {
rs.close();
}
} finally {
stmt.close();
}
} finally {
RDBMServices.releaseConnection(con);
}
return ssup;
}
/**
* Obtain theme stylesheet description object for a given theme stylesheet id.
* @param id the id of the theme stylesheet
* @return theme stylesheet description
*/
public ThemeStylesheetDescription getThemeStylesheetDescription (int stylesheetId) throws Exception {
ThemeStylesheetDescription tsd = null;
Connection con = RDBMServices.getConnection();
Statement stmt = con.createStatement();
try {
int dbOffset = 0;
String sQuery = "SELECT SS_NAME,SS_URI,SS_DESCRIPTION_URI,SS_DESCRIPTION_TEXT,STRUCT_SS_ID,SAMPLE_ICON_URI,SAMPLE_URI,MIME_TYPE,DEVICE_TYPE,SERIALIZER_NAME,UP_MODULE_CLASS";
if (RDBMServices.supportsOuterJoins) {
sQuery += ",TYPE,PARAM_NAME,PARAM_DEFAULT_VAL,PARAM_DESCRIPT FROM " + RDBMServices.joinQuery.getQuery("ss_theme");
dbOffset = 11;
} else {
sQuery += " FROM UP_SS_THEME UTS WHERE";
}
sQuery += " UTS.SS_ID=" + stylesheetId;
LogService.log(LogService.DEBUG, "RDBMUserLayoutStore::getThemeStylesheetDescription(): " + sQuery);
ResultSet rs = stmt.executeQuery(sQuery);
try {
if (rs.next()) {
tsd = new ThemeStylesheetDescription();
tsd.setId(stylesheetId);
tsd.setStylesheetName(rs.getString(1));
tsd.setStylesheetURI(rs.getString(2));
tsd.setStylesheetDescriptionURI(rs.getString(3));
tsd.setStylesheetWordDescription(rs.getString(4));
int ssId = rs.getInt(5);
if (rs.wasNull()) {
ssId = 0;
}
tsd.setStructureStylesheetId(ssId);
tsd.setSampleIconURI(rs.getString(6));
tsd.setSamplePictureURI(rs.getString(7));
tsd.setMimeType(rs.getString(8));
tsd.setDeviceType(rs.getString(9));
tsd.setSerializerName(rs.getString(10));
tsd.setCustomUserPreferencesManagerClass(rs.getString(11));
}
if (!RDBMServices.supportsOuterJoins) {
rs.close();
// retrieve stylesheet params and attributes
sQuery = "SELECT TYPE,PARAM_NAME,PARAM_DEFAULT_VAL,PARAM_DESCRIPT FROM UP_SS_THEME_PARM WHERE SS_ID=" + stylesheetId;
LogService.log(LogService.DEBUG, "RDBMUserLayoutStore::getThemeStylesheetDescription(): " + sQuery);
rs = stmt.executeQuery(sQuery);
}
while (true) {
if (!RDBMServices.supportsOuterJoins && !rs.next()) {
break;
}
int type = rs.getInt(dbOffset + 1);
if (rs.wasNull()) {
break;
}
if (type == 1) {
// param
tsd.addStylesheetParameter(rs.getString(dbOffset + 2), rs.getString(dbOffset + 3), rs.getString(dbOffset + 4));
}
else if (type == 3) {
// channel attribute
tsd.addChannelAttribute(rs.getString(dbOffset + 2), rs.getString(dbOffset + 3), rs.getString(dbOffset + 4));
}
else if (type == 2) {
// folder attributes are not allowed here
LogService.log(LogService.ERROR, "RDBMUserLayoutStore::getThemeStylesheetDescription() : encountered a folder attribute specified for a theme stylesheet ! Corrupted DB entry. (stylesheetId="
+ stylesheetId + " param_name=\"" + rs.getString(dbOffset + 2) + "\" type=" + type + ").");
}
else {
LogService.log(LogService.ERROR, "RDBMUserLayoutStore::getThemeStylesheetDescription() : encountered param of unknown type! (stylesheetId="
+ stylesheetId + " param_name=\"" + rs.getString(dbOffset + 2) + "\" type=" + type + ").");
}
if (RDBMServices.supportsOuterJoins && !rs.next()) {
break;
}
}
} finally {
rs.close();
}
} finally {
stmt.close();
RDBMServices.releaseConnection(con);
}
return tsd;
}
/**
* Obtain ID for known theme stylesheet name
* @param ssName name of the theme stylesheet
* @return id or null if no theme matches the name given.
*/
public Integer getThemeStylesheetId (String tsName) throws Exception {
Integer id = null;
Connection con = RDBMServices.getConnection();
try {
Statement stmt = con.createStatement();
try {
String sQuery = "SELECT SS_ID FROM UP_SS_THEME WHERE SS_NAME='" + tsName + "'";
ResultSet rs = stmt.executeQuery(sQuery);
if (rs.next()) {
id = new Integer(rs.getInt("SS_ID"));
}
} finally {
stmt.close();
}
} finally {
RDBMServices.releaseConnection(con);
}
return id;
}
/**
* Obtain a list of theme stylesheet descriptions for a given structure stylesheet
* @param structureStylesheetName
* @return a map of stylesheet names to theme stylesheet description objects
* @exception Exception
*/
public Hashtable getThemeStylesheetList (int structureStylesheetId) throws Exception {
Connection con = RDBMServices.getConnection();
Hashtable list = new Hashtable();
try {
Statement stmt = con.createStatement();
try {
String sQuery = "SELECT SS_ID FROM UP_SS_THEME WHERE STRUCT_SS_ID=" + structureStylesheetId;
LogService.log(LogService.DEBUG, "RDBMUserLayoutStore::getThemeStylesheetList() : " + sQuery);
ResultSet rs = stmt.executeQuery(sQuery);
try {
while (rs.next()) {
ThemeStylesheetDescription tsd = getThemeStylesheetDescription(rs.getInt("SS_ID"));
if (tsd != null)
list.put(new Integer(tsd.getId()), tsd);
}
} finally {
rs.close();
}
} finally {
stmt.close();
}
} finally {
RDBMServices.releaseConnection(con);
}
return list;
}
/**
* Obtain a list of theme stylesheet descriptions registered on the system
* @return a <code>Hashtable</code> mapping stylesheet id (<code>Integer</code> objects) to {@link ThemeStylesheetDescription} objects
* @exception Exception
*/
public Hashtable getThemeStylesheetList() throws Exception {
Connection con = RDBMServices.getConnection();
Hashtable list = new Hashtable();
try {
Statement stmt = con.createStatement();
try {
String sQuery = "SELECT SS_ID FROM UP_SS_THEME";
LogService.log(LogService.DEBUG, "RDBMUserLayoutStore::getThemeStylesheetList() : " + sQuery);
ResultSet rs = stmt.executeQuery(sQuery);
try {
while (rs.next()) {
ThemeStylesheetDescription tsd = getThemeStylesheetDescription(rs.getInt("SS_ID"));
if (tsd != null)
list.put(new Integer(tsd.getId()), tsd);
}
} finally {
rs.close();
}
} finally {
stmt.close();
}
} finally {
RDBMServices.releaseConnection(con);
}
return list;
}
public ThemeStylesheetUserPreferences getThemeStylesheetUserPreferences (IPerson person, int profileId, int stylesheetId) throws Exception {
int userId = person.getID();
ThemeStylesheetUserPreferences tsup;
Connection con = RDBMServices.getConnection();
try {
Statement stmt = con.createStatement();
try {
// get stylesheet description
ThemeStylesheetDescription tsd = getThemeStylesheetDescription(stylesheetId);
// get user defined defaults
String sQuery = "SELECT PARAM_NAME, PARAM_VAL FROM UP_SS_USER_PARM WHERE USER_ID=" + userId + " AND PROFILE_ID="
+ profileId + " AND SS_ID=" + stylesheetId + " AND SS_TYPE=2";
LogService.log(LogService.DEBUG, "RDBMUserLayoutStore::getThemeStylesheetUserPreferences(): " + sQuery);
ResultSet rs = stmt.executeQuery(sQuery);
try {
while (rs.next()) {
// stylesheet param
tsd.setStylesheetParameterDefaultValue(rs.getString(1), rs.getString(2));
// LogService.log(LogService.DEBUG,"RDBMUserLayoutStore::getThemeStylesheetUserPreferences() : read stylesheet param "+rs.getString("PARAM_NAME")+"=\""+rs.getString("PARAM_VAL")+"\"");
}
} finally {
rs.close();
}
tsup = new ThemeStylesheetUserPreferences();
tsup.setStylesheetId(stylesheetId);
// fill stylesheet description with defaults
for (Enumeration e = tsd.getStylesheetParameterNames(); e.hasMoreElements();) {
String pName = (String)e.nextElement();
tsup.putParameterValue(pName, tsd.getStylesheetParameterDefaultValue(pName));
}
for (Enumeration e = tsd.getChannelAttributeNames(); e.hasMoreElements();) {
String pName = (String)e.nextElement();
tsup.addChannelAttribute(pName, tsd.getChannelAttributeDefaultValue(pName));
}
// get user preferences
sQuery = "SELECT PARAM_TYPE, PARAM_NAME, PARAM_VAL, ULS.STRUCT_ID, CHAN_ID FROM UP_SS_USER_ATTS UUSA, UP_LAYOUT_STRUCT ULS WHERE UUSA.USER_ID=" + userId + " AND PROFILE_ID="
+ profileId + " AND SS_ID=" + stylesheetId + " AND SS_TYPE=2 AND UUSA.STRUCT_ID = ULS.STRUCT_ID AND UUSA.USER_ID = ULS.USER_ID";
LogService.log(LogService.DEBUG, "RDBMUserLayoutStore::getThemeStylesheetUserPreferences(): " + sQuery);
rs = stmt.executeQuery(sQuery);
try {
while (rs.next()) {
int param_type = rs.getInt(1);
if (rs.wasNull()) {
param_type = 0;
}
int structId = rs.getInt(4);
if (rs.wasNull()) {
structId = 0;
}
int chanId = rs.getInt(5);
if (rs.wasNull()) {
chanId = 0;
}
if (param_type == 1) {
// stylesheet param
LogService.log(LogService.ERROR, "RDBMUserLayoutStore::getThemeStylesheetUserPreferences() : stylesheet global params should be specified in the user defaults table ! UP_SS_USER_ATTS is corrupt. (userId="
+ Integer.toString(userId) + ", profileId=" + Integer.toString(profileId) + ", stylesheetId=" + Integer.toString(stylesheetId)
+ ", param_name=\"" + rs.getString(2) + "\", param_type=" + Integer.toString(param_type));
}
else if (param_type == 2) {
// folder attribute
LogService.log(LogService.ERROR, "RDBMUserLayoutStore::getThemeStylesheetUserPreferences() : folder attribute specified for the theme stylesheet! UP_SS_USER_ATTS corrupt. (userId="
+ Integer.toString(userId) + ", profileId=" + Integer.toString(profileId) + ", stylesheetId=" + Integer.toString(stylesheetId)
+ ", param_name=\"" + rs.getString(2) + "\", param_type=" + Integer.toString(param_type));
}
else if (param_type == 3) {
// channel attribute
tsup.setChannelAttributeValue(getStructId(structId,chanId), rs.getString(2), rs.getString(3));
//LogService.log(LogService.DEBUG,"RDBMUserLayoutStore::getThemeStylesheetUserPreferences() : read folder attribute "+rs.getString("PARAM_NAME")+"("+rs.getString("STRUCT_ID")+")=\""+rs.getString("PARAM_VAL")+"\"");
}
else {
// unknown param type
LogService.log(LogService.ERROR, "RDBMUserLayoutStore::getThemeStylesheetUserPreferences() : unknown param type encountered! DB corrupt. (userId="
+ Integer.toString(userId) + ", profileId=" + Integer.toString(profileId) + ", stylesheetId=" + Integer.toString(stylesheetId)
+ ", param_name=\"" + rs.getString(2) + "\", param_type=" + Integer.toString(param_type));
}
}
} finally {
rs.close();
}
} finally {
stmt.close();
}
} finally {
RDBMServices.releaseConnection(con);
}
return tsup;
}
// private helper modules that retreive information from the DOM structure of the description files
private String getName (Document descr) {
NodeList names = descr.getElementsByTagName("name");
Node name = null;
for (int i = names.getLength() - 1; i >= 0; i
name = names.item(i);
if (name.getParentNode().getNodeName().equals("stylesheetdescription"))
break;
else
name = null;
}
if (name != null) {
return this.getTextChildNodeValue(name);
}
else {
LogService.log(LogService.DEBUG, "RDBMCoreStylesheetDescriptionStore::getName() : no \"name\" element was found under the \"stylesheetdescription\" node!");
return null;
}
}
private String getRootElementTextValue (Document descr, String elementName) {
NodeList names = descr.getElementsByTagName(elementName);
Node name = null;
for (int i = names.getLength() - 1; i >= 0; i
name = names.item(i);
if (name.getParentNode().getNodeName().equals("stylesheetdescription"))
break;
else
name = null;
}
if (name != null) {
return this.getTextChildNodeValue(name);
}
else {
LogService.log(LogService.DEBUG, "RDBMCoreStylesheetDescriptionStore::getRootElementTextValue() : no \"" + elementName + "\" element was found under the \"stylesheetdescription\" node!");
return null;
}
}
private String getDescription (Document descr) {
NodeList descriptions = descr.getElementsByTagName("description");
Node description = null;
for (int i = descriptions.getLength() - 1; i >= 0; i
description = descriptions.item(i);
if (description.getParentNode().getNodeName().equals("stylesheetdescription"))
break;
else
description = null;
}
if (description != null) {
return this.getTextChildNodeValue(description);
}
else {
LogService.log(LogService.DEBUG, "RDBMCoreStylesheetDescriptionStore::getName() : no \"description\" element was found under the \"stylesheetdescription\" node!");
return null;
}
}
private void populateParameterTable (Document descr, CoreStylesheetDescription csd) {
NodeList parametersNodes = descr.getElementsByTagName("parameters");
Node parametersNode = null;
for (int i = parametersNodes.getLength() - 1; i >= 0; i
parametersNode = parametersNodes.item(i);
if (parametersNode.getParentNode().getNodeName().equals("stylesheetdescription"))
break;
else
parametersNode = null;
}
if (parametersNode != null) {
NodeList children = parametersNode.getChildNodes();
for (int i = children.getLength() - 1; i >= 0; i
Node child = children.item(i);
if (child.getNodeType() == Node.ELEMENT_NODE && child.getNodeName().equals("parameter")) {
Element parameter = (Element)children.item(i);
// process a <parameter> node
String name = parameter.getAttribute("name");
String description = null;
String defaultvalue = null;
NodeList pchildren = parameter.getChildNodes();
for (int j = pchildren.getLength() - 1; j >= 0; j
Node pchild = pchildren.item(j);
if (pchild.getNodeType() == Node.ELEMENT_NODE) {
if (pchild.getNodeName().equals("defaultvalue")) {
defaultvalue = this.getTextChildNodeValue(pchild);
}
else if (pchild.getNodeName().equals("description")) {
description = this.getTextChildNodeValue(pchild);
}
}
}
LogService.log(LogService.DEBUG, "RDBMCoreStylesheetDescriptionStore::populateParameterTable() : adding a stylesheet parameter : (\""
+ name + "\",\"" + defaultvalue + "\",\"" + description + "\")");
csd.addStylesheetParameter(name, defaultvalue, description);
}
}
}
}
private void populateFolderAttributeTable (Document descr, StructureStylesheetDescription cxsd) {
NodeList parametersNodes = descr.getElementsByTagName("parameters");
NodeList folderattributesNodes = descr.getElementsByTagName("folderattributes");
Node folderattributesNode = null;
for (int i = folderattributesNodes.getLength() - 1; i >= 0; i
folderattributesNode = folderattributesNodes.item(i);
if (folderattributesNode.getParentNode().getNodeName().equals("stylesheetdescription"))
break;
else
folderattributesNode = null;
}
if (folderattributesNode != null) {
NodeList children = folderattributesNode.getChildNodes();
for (int i = children.getLength() - 1; i >= 0; i
Node child = children.item(i);
if (child.getNodeType() == Node.ELEMENT_NODE && child.getNodeName().equals("attribute")) {
Element attribute = (Element)children.item(i);
// process a <attribute> node
String name = attribute.getAttribute("name");
String description = null;
String defaultvalue = null;
NodeList pchildren = attribute.getChildNodes();
for (int j = pchildren.getLength() - 1; j >= 0; j
Node pchild = pchildren.item(j);
if (pchild.getNodeType() == Node.ELEMENT_NODE) {
if (pchild.getNodeName().equals("defaultvalue")) {
defaultvalue = this.getTextChildNodeValue(pchild);
}
else if (pchild.getNodeName().equals("description")) {
description = this.getTextChildNodeValue(pchild);
}
}
}
LogService.log(LogService.DEBUG, "RDBMCoreStylesheetDescriptionStore::populateFolderAttributeTable() : adding a stylesheet folder attribute : (\""
+ name + "\",\"" + defaultvalue + "\",\"" + description + "\")");
cxsd.addFolderAttribute(name, defaultvalue, description);
}
}
}
}
private void populateChannelAttributeTable (Document descr, CoreXSLTStylesheetDescription cxsd) {
NodeList channelattributesNodes = descr.getElementsByTagName("channelattributes");
Node channelattributesNode = null;
for (int i = channelattributesNodes.getLength() - 1; i >= 0; i
channelattributesNode = channelattributesNodes.item(i);
if (channelattributesNode.getParentNode().getNodeName().equals("stylesheetdescription"))
break;
else
channelattributesNode = null;
}
if (channelattributesNode != null) {
NodeList children = channelattributesNode.getChildNodes();
for (int i = children.getLength() - 1; i >= 0; i
Node child = children.item(i);
if (child.getNodeType() == Node.ELEMENT_NODE && child.getNodeName().equals("attribute")) {
Element attribute = (Element)children.item(i);
// process a <attribute> node
String name = attribute.getAttribute("name");
String description = null;
String defaultvalue = null;
NodeList pchildren = attribute.getChildNodes();
for (int j = pchildren.getLength() - 1; j >= 0; j
Node pchild = pchildren.item(j);
if (pchild.getNodeType() == Node.ELEMENT_NODE) {
if (pchild.getNodeName().equals("defaultvalue")) {
defaultvalue = this.getTextChildNodeValue(pchild);
}
else if (pchild.getNodeName().equals("description")) {
description = this.getTextChildNodeValue(pchild);
}
}
}
LogService.log(LogService.DEBUG, "RDBMCoreStylesheetDescriptionStore::populateChannelAttributeTable() : adding a stylesheet channel attribute : (\""
+ name + "\",\"" + defaultvalue + "\",\"" + description + "\")");
cxsd.addChannelAttribute(name, defaultvalue, description);
}
}
}
}
private Vector getVectorOfSimpleTextElementValues (Document descr, String elementName) {
Vector v = new Vector();
// find "stylesheetdescription" node, take the first one
Element stylesheetdescriptionElement = (Element)(descr.getElementsByTagName("stylesheetdescription")).item(0);
if (stylesheetdescriptionElement == null) {
LogService.log(LogService.ERROR, "Could not obtain <stylesheetdescription> element");
return null;
}
NodeList elements = stylesheetdescriptionElement.getElementsByTagName(elementName);
for (int i = elements.getLength() - 1; i >= 0; i
v.add(this.getTextChildNodeValue(elements.item(i)));
// LogService.log(LogService.DEBUG,"adding "+this.getTextChildNodeValue(elements.item(i))+" to the \""+elementName+"\" vector.");
}
return v;
}
private String getTextChildNodeValue (Node node) {
if (node == null)
return null;
NodeList children = node.getChildNodes();
for (int i = children.getLength() - 1; i >= 0; i
Node child = children.item(i);
if (child.getNodeType() == Node.TEXT_NODE)
return child.getNodeValue();
}
return null;
}
/**
* UserPreferences
*/
private int getUserBrowserMapping (IPerson person, String userAgent) throws Exception {
int userId = person.getID();
int profileId = 0;
Connection con = RDBMServices.getConnection();
try {
Statement stmt = con.createStatement();
try {
String sQuery = "SELECT PROFILE_ID, USER_ID FROM UP_USER_UA_MAP WHERE USER_ID=" + userId + " AND USER_AGENT='" +
userAgent + "'";
LogService.log(LogService.DEBUG, "RDBMUserLayoutStore::getUserBrowserMapping(): " + sQuery);
ResultSet rs = stmt.executeQuery(sQuery);
try {
if (rs.next()) {
profileId = rs.getInt("PROFILE_ID");
if (rs.wasNull()) {
profileId = 0;
}
}
else {
return 0;
}
} finally {
rs.close();
}
} finally {
stmt.close();
}
} finally {
RDBMServices.releaseConnection(con);
}
return profileId;
}
public Document getUserLayout (IPerson person, UserProfile profile) throws Exception {
int userId = person.getID();
int realUserId = userId;
ResultSet rs;
Connection con = RDBMServices.getConnection();
RDBMServices.setAutoCommit(con, false); // May speed things up, can't hurt
try {
Document doc = DocumentFactory.getNewDocument();
Element root = doc.createElement("layout");
Statement stmt = con.createStatement();
// A separate statement is needed so as not to interfere with ResultSet
// of statements used for queries
Statement insertStmt = con.createStatement();
try {
long startTime = System.currentTimeMillis();
// eventually, we need to fix template layout implementations so you can just do this:
// int layoutId=profile.getLayoutId();
// but for now:
String subSelectString = "SELECT LAYOUT_ID FROM UP_USER_PROFILE WHERE USER_ID=" + userId + " AND PROFILE_ID=" + profile.getProfileId();
LogService.log(LogService.DEBUG, "RDBMUserLayoutStore::getUserLayout(): " + subSelectString);
int layoutId = 0;
rs = stmt.executeQuery(subSelectString);
try {
if (rs.next()) {
layoutId = rs.getInt(1);
if (rs.wasNull()) {
layoutId = 0;
}
}
} finally {
rs.close();
}
if (layoutId == 0) { // First time, grab the default layout for this user
String sQuery = "SELECT USER_DFLT_USR_ID, USER_DFLT_LAY_ID FROM UP_USER WHERE USER_ID=" + userId;
LogService.log(LogService.DEBUG, "RDBMUserLayoutStore::getUserLayout(): " + sQuery);
rs = stmt.executeQuery(sQuery);
try {
rs.next();
userId = rs.getInt(1);
layoutId = rs.getInt(2);
} finally {
rs.close();
}
// Make sure the next struct id is set in case the user adds a channel
sQuery = "SELECT NEXT_STRUCT_ID FROM UP_USER WHERE USER_ID=" + userId;
LogService.log(LogService.DEBUG, "RDBMUserLayoutStore::getUserLayout(): " + sQuery);
int nextStructId;
rs = stmt.executeQuery(sQuery);
try {
rs.next();
nextStructId = rs.getInt(1);
} finally {
rs.close();
}
sQuery = "UPDATE UP_USER SET NEXT_STRUCT_ID=" + nextStructId + " WHERE USER_ID=" + realUserId;
LogService.log(LogService.DEBUG, "RDBMUserLayoutStore::setUserLayout(): " + sQuery);
stmt.executeUpdate(sQuery);
/* insert row(s) into up_ss_user_atts */
sQuery = "DELETE FROM UP_SS_USER_ATTS WHERE USER_ID=" + realUserId;
LogService.log(LogService.DEBUG, "RDBMUserLayoutStore::setUserLayout(): " + sQuery);
stmt.executeUpdate(sQuery);
// modifed INSERT INTO SELECT statement for MySQL support
sQuery = " SELECT "+realUserId+", PROFILE_ID, SS_ID, SS_TYPE, STRUCT_ID, PARAM_NAME, PARAM_TYPE, PARAM_VAL "+
" FROM UP_SS_USER_ATTS WHERE USER_ID="+userId;
rs = stmt.executeQuery(sQuery);
while (rs.next()) {
String Insert = "INSERT INTO UP_SS_USER_ATTS (USER_ID, PROFILE_ID, SS_ID, SS_TYPE, STRUCT_ID, PARAM_NAME, PARAM_TYPE, PARAM_VAL) " +
"VALUES("+realUserId+","+
rs.getInt("PROFILE_ID")+","+
rs.getInt("SS_ID")+"," +
rs.getInt("SS_TYPE")+"," +
rs.getInt("STRUCT_ID")+"," +
"'"+rs.getString("PARAM_NAME")+"'," +
rs.getInt("PARAM_TYPE")+"," +
"'"+rs.getString("PARAM_VAL")+"')";
// old code
// String Insert = "INSERT INTO UP_SS_USER_ATTS (USER_ID, PROFILE_ID, SS_ID, SS_TYPE, STRUCT_ID, PARAM_NAME, PARAM_TYPE, PARAM_VAL) "+
// " SELECT "+realUserId+", USUA.PROFILE_ID, USUA.SS_ID, USUA.SS_TYPE, USUA.STRUCT_ID, USUA.PARAM_NAME, USUA.PARAM_TYPE, USUA.PARAM_VAL "+
// " FROM UP_SS_USER_ATTS USUA WHERE USUA.USER_ID="+userId;
LogService.log(LogService.DEBUG, "RDBMUserLayoutStore::setUserLayout(): " + Insert);
insertStmt.executeUpdate(Insert);
}
// Close Result Set
if ( rs != null ) rs.close();
RDBMServices.commit(con); // Make sure it appears in the store
}
int firstStructId = -1;
String sQuery = "SELECT INIT_STRUCT_ID FROM UP_USER_LAYOUT WHERE USER_ID=" + userId + " AND LAYOUT_ID = " + layoutId;
LogService.log(LogService.DEBUG, "RDBMUserLayoutStore::getUserLayout(): " + sQuery);
rs = stmt.executeQuery(sQuery);
try {
if (rs.next()) {
firstStructId = rs.getInt(1);
} else {
throw new Exception("RDBMUserLayoutStore::getUserLayout(): No INIT_STRUCT_ID in UP_USER_LAYOUT for " + userId + " and LAYOUT_ID " + layoutId);
}
} finally {
rs.close();
}
String sql = "SELECT ULS.STRUCT_ID,ULS.NEXT_STRUCT_ID,ULS.CHLD_STRUCT_ID,ULS.CHAN_ID,ULS.NAME,ULS.TYPE,ULS.HIDDEN,"+
"ULS.UNREMOVABLE,ULS.IMMUTABLE";
if (RDBMServices.supportsOuterJoins) {
sql += ",USP.STRUCT_PARM_NM,USP.STRUCT_PARM_VAL FROM " + RDBMServices.joinQuery.getQuery("layout");
} else {
sql += " FROM UP_LAYOUT_STRUCT ULS WHERE ";
}
sql += " ULS.USER_ID=" + userId + " AND ULS.LAYOUT_ID=" + layoutId + " ORDER BY ULS.STRUCT_ID";
HashMap layoutStructure = new HashMap();
LogService.log(LogService.DEBUG, "RDBMUserLayoutStore::getUserLayout(): " + sql);
StringBuffer structChanIds = new StringBuffer();
rs = stmt.executeQuery(sql);
try {
int lastStructId = 0;
LayoutStructure ls = null;
String sepChar = "";
if (rs.next()) {
int structId = rs.getInt(1);
// Result Set returns 0 by default if structId was null
// Except if you are using poolman 2.0.4 in which case you get -1 back
if (rs.wasNull()) {
structId = 0;
}
readLayout: while (true) {
if (DEBUG > 1) System.err.println("Found layout structureID " + structId);
int nextId = rs.getInt(2);
if (rs.wasNull()) {
nextId = 0;
}
int childId = rs.getInt(3);
if (rs.wasNull()) {
childId = 0;
}
int chanId = rs.getInt(4);
if (rs.wasNull()) {
chanId = 0;
}
String temp5=rs.getString(5); // Some JDBC drivers require columns accessed in order
String temp6=rs.getString(6); // Access 5 and 6 now, save till needed.
ls = new LayoutStructure(structId, nextId, childId, chanId, rs.getString(7),rs.getString(8),rs.getString(9));
layoutStructure.put(new Integer(structId), ls);
lastStructId = structId;
if (!ls.isChannel()) {
ls.addFolderData(temp5, temp6); // Plug in saved column values
}
if (RDBMServices.supportsOuterJoins) {
do {
String name = rs.getString(10);
String value = rs.getString(11); // Oracle JDBC requires us to do this for longs
if (name != null) { // may not be there because of the join
ls.addParameter(name, value);
}
if (!rs.next()) {
break readLayout;
}
structId = rs.getInt(1);
if (rs.wasNull()) {
structId = 0;
}
} while (structId == lastStructId);
} else { // Do second SELECT later on for structure parameters
if (ls.isChannel()) {
structChanIds.append(sepChar + ls.chanId);
sepChar = ",";
}
if (rs.next()) {
structId = rs.getInt(1);
if (rs.wasNull()) {
structId = 0;
}
} else {
break readLayout;
}
}
} // while
}
} finally {
rs.close();
}
if (!RDBMServices.supportsOuterJoins) { // Pick up structure parameters
// first, get the struct ids for the channels
sql = "SELECT STRUCT_ID FROM UP_LAYOUT_STRUCT WHERE USER_ID=" + userId +
" AND LAYOUT_ID=" + layoutId +
" AND CHAN_ID IN (" + structChanIds.toString() + ") ORDER BY STRUCT_ID";
LogService.log(LogService.DEBUG, "RDBMUserLayoutStore::getUserLayout(): " + sql);
StringBuffer structIdsSB = new StringBuffer( "" );
String sep = "";
rs = stmt.executeQuery(sql);
try {
// use the results to build a correct list of struct ids to look for
while( rs.next()) {
structIdsSB.append(sep + rs.getString(1));
sep = ",";
}// while
} finally {
rs.close();
} // be a good doobie
sql = "SELECT STRUCT_ID, STRUCT_PARM_NM,STRUCT_PARM_VAL FROM UP_LAYOUT_PARAM WHERE USER_ID=" + userId + " AND LAYOUT_ID=" + layoutId +
" AND STRUCT_ID IN (" + structIdsSB.toString() + ") ORDER BY STRUCT_ID";
LogService.log(LogService.DEBUG, "RDBMUserLayoutStore::getUserLayout(): " + sql);
rs = stmt.executeQuery(sql);
try {
if (rs.next()) {
int structId = rs.getInt(1);
readParm: while(true) {
LayoutStructure ls = (LayoutStructure)layoutStructure.get(new Integer(structId));
int lastStructId = structId;
do {
ls.addParameter(rs.getString(2), rs.getString(3));
if (!rs.next()) {
break readParm;
}
} while ((structId = rs.getInt(1)) == lastStructId);
}
}
} finally {
rs.close();
}
}
if (layoutStructure.size() > 0) { // We have a layout to work with
createLayout(layoutStructure, doc, root, firstStructId);
layoutStructure.clear();
long stopTime = System.currentTimeMillis();
LogService.log(LogService.DEBUG, "RDBMUserLayoutStore::getUserLayout(): Layout document for user " + userId + " took " +
(stopTime - startTime) + " milliseconds to create");
doc.appendChild(root);
if (DEBUG > 1) {
System.err.println("--> created document");
dumpDoc(doc, "");
System.err.println("<
}
}
} finally {
stmt.close();
insertStmt.close();
}
return doc;
} finally {
RDBMServices.releaseConnection(con);
}
}
public UserProfile getUserProfileById (IPerson person, int profileId) throws Exception {
int userId = person.getID();
Connection con = RDBMServices.getConnection();
try {
Statement stmt = con.createStatement();
try {
String sQuery = "SELECT USER_ID, PROFILE_ID, PROFILE_NAME, DESCRIPTION, LAYOUT_ID, STRUCTURE_SS_ID, THEME_SS_ID FROM UP_USER_PROFILE WHERE USER_ID="
+ userId + " AND PROFILE_ID=" + profileId;
LogService.log(LogService.DEBUG, "RDBMUserLayoutStore::getUserProfileById(): " + sQuery);
ResultSet rs = stmt.executeQuery(sQuery);
try {
if (rs.next()) {
String temp3 = rs.getString(3);
String temp4 = rs.getString(4);
int layoutId = rs.getInt(5);
if (rs.wasNull()) {
layoutId = 0;
}
int structSsId = rs.getInt(6);
if (rs.wasNull()) {
structSsId = 0;
}
int themeSsId = rs.getInt(7);
if (rs.wasNull()) {
themeSsId = 0;
}
return new UserProfile(profileId, temp3,temp4, layoutId,
structSsId, themeSsId);
}
else {
throw new Exception("Unable to find User Profile for user " + userId + " and profile " + profileId);
}
} finally {
rs.close();
}
} finally {
stmt.close();
}
} finally {
RDBMServices.releaseConnection(con);
}
}
public Hashtable getUserProfileList (IPerson person) throws Exception {
int userId = person.getID();
Hashtable pv = new Hashtable();
Connection con = RDBMServices.getConnection();
try {
Statement stmt = con.createStatement();
try {
String sQuery = "SELECT USER_ID, PROFILE_ID, PROFILE_NAME, DESCRIPTION, LAYOUT_ID, STRUCTURE_SS_ID, THEME_SS_ID FROM UP_USER_PROFILE WHERE USER_ID="
+ userId;
LogService.log(LogService.DEBUG, "RDBMUserLayoutStore::getUserProfileList(): " + sQuery);
ResultSet rs = stmt.executeQuery(sQuery);
try {
while (rs.next()) {
int layoutId = rs.getInt(5);
if (rs.wasNull()) {
layoutId = 0;
}
int structSsId = rs.getInt(6);
if (rs.wasNull()) {
structSsId = 0;
}
int themeSsId = rs.getInt(7);
if (rs.wasNull()) {
themeSsId = 0;
}
UserProfile upl = new UserProfile(rs.getInt(2), rs.getString(3), rs.getString(4),
layoutId, structSsId, themeSsId);
pv.put(new Integer(upl.getProfileId()), upl);
}
} finally {
rs.close();
}
} finally {
stmt.close();
}
} finally {
RDBMServices.releaseConnection(con);
}
return pv;
}
/**
* Remove (with cleanup) a structure stylesheet channel attribute
* @param stylesheetId id of the structure stylesheet
* @param pName name of the attribute
* @param con active database connection
*/
private void removeStructureChannelAttribute (int stylesheetId, String pName, Connection con) throws java.sql.SQLException {
Statement stmt = con.createStatement();
try {
String sQuery = "DELETE FROM UP_SS_STRUCT_PAR WHERE SS_ID=" + stylesheetId + " AND TYPE=3 AND PARAM_NAME='" + pName
+ "'";
LogService.log(LogService.DEBUG, "RDBMUserLayoutStore::removeStructureChannelAttribute() : " + sQuery);
stmt.executeQuery(sQuery);
// clean up user preference tables
sQuery = "DELETE FROM UP_SS_USER_ATTS WHERE SS_ID=" + stylesheetId + " AND SS_TYPE=1 AND PARAM_TYPE=3 AND PARAM_NAME='"
+ pName + "'";
LogService.log(LogService.DEBUG, "RDBMUserLayoutStore::removeStructureChannelAttribute() : " + sQuery);
stmt.executeQuery(sQuery);
} finally {
stmt.close();
}
}
/**
* Remove (with cleanup) a structure stylesheet folder attribute
* @param stylesheetId id of the structure stylesheet
* @param pName name of the attribute
* @param con active database connection
*/
private void removeStructureFolderAttribute (int stylesheetId, String pName, Connection con) throws java.sql.SQLException {
Statement stmt = con.createStatement();
try {
String sQuery = "DELETE FROM UP_SS_STRUCT_PAR WHERE SS_ID=" + stylesheetId + " AND TYPE=2 AND PARAM_NAME='" + pName
+ "'";
LogService.log(LogService.DEBUG, "RDBMUserLayoutStore::removeStructureFolderAttribute() : " + sQuery);
stmt.executeQuery(sQuery);
// clean up user preference tables
sQuery = "DELETE FROM UP_SS_USER_ATTS WHERE SS_ID=" + stylesheetId + " AND SS_TYPE=1 AND PARAM_TYPE=2 AND PARAM_NAME='"
+ pName + "'";
LogService.log(LogService.DEBUG, "RDBMUserLayoutStore::removeStructureFolderAttribute() : " + sQuery);
stmt.executeQuery(sQuery);
} finally {
stmt.close();
}
}
public void removeStructureStylesheetDescription (int stylesheetId) throws Exception {
Connection con = RDBMServices.getConnection();
try {
Statement stmt = con.createStatement();
try {
// detele all associated theme stylesheets
String sQuery = "SELECT SS_ID FROM UP_SS_THEME WHERE STRUCT_SS_ID=" + stylesheetId;
LogService.log(LogService.DEBUG, "RDBMUserLayoutStore::removeStructureStylesheetDescription() : " + sQuery);
ResultSet rs = stmt.executeQuery(sQuery);
try {
while (rs.next()) {
removeThemeStylesheetDescription(rs.getInt("SS_ID"));
}
} finally {
rs.close();
}
sQuery = "DELETE FROM UP_SS_STRUCT WHERE SS_ID=" + stylesheetId;
LogService.log(LogService.DEBUG, "RDBMUserLayoutStore::removeStructureStylesheetDescription() : " + sQuery);
stmt.executeUpdate(sQuery);
// delete params
sQuery = "DELETE FROM UP_SS_STRUCT_PAR WHERE SS_ID=" + stylesheetId;
LogService.log(LogService.DEBUG, "RDBMUserLayoutStore::removeStructureStylesheetDescription() : " + sQuery);
stmt.executeUpdate(sQuery);
RDBMServices.commit(con);
} catch (Exception e) {
// Roll back the transaction
RDBMServices.rollback(con);
throw e;
} finally {
stmt.close();
}
} finally {
RDBMServices.releaseConnection(con);
}
}
/**
* Remove (with cleanup) a structure stylesheet param
* @param stylesheetId id of the structure stylesheet
* @param pName name of the parameter
* @param con active database connection
*/
private void removeStructureStylesheetParam (int stylesheetId, String pName, Connection con) throws java.sql.SQLException {
Statement stmt = con.createStatement();
try {
String sQuery = "DELETE FROM UP_SS_STRUCT_PAR WHERE SS_ID=" + stylesheetId + " AND TYPE=1 AND PARAM_NAME='" + pName
+ "'";
LogService.log(LogService.DEBUG, "RDBMUserLayoutStore::removeStructureStylesheetParam() : " + sQuery);
stmt.executeQuery(sQuery);
// clean up user preference tables
sQuery = "DELETE FROM UP_SS_USER_PARM WHERE SS_ID=" + stylesheetId + " AND SS_TYPE=1 AND PARAM_TYPE=1 AND PARAM_NAME='"
+ pName + "'";
LogService.log(LogService.DEBUG, "RDBMUserLayoutStore::removeStructureStylesheetParam() : " + sQuery);
stmt.executeQuery(sQuery);
} finally {
stmt.close();
}
}
/**
* Remove (with cleanup) a theme stylesheet channel attribute
* @param stylesheetId id of the theme stylesheet
* @param pName name of the attribute
* @param con active database connection
*/
private void removeThemeChannelAttribute (int stylesheetId, String pName, Connection con) throws java.sql.SQLException {
Statement stmt = con.createStatement();
try {
String sQuery = "DELETE FROM UP_SS_THEME_PARM WHERE SS_ID=" + stylesheetId + " AND TYPE=3 AND PARAM_NAME='" + pName
+ "'";
LogService.log(LogService.DEBUG, "RDBMUserLayoutStore::removeThemeChannelAttribute() : " + sQuery);
stmt.executeQuery(sQuery);
// clean up user preference tables
sQuery = "DELETE FROM UP_SS_USER_ATTS WHERE SS_ID=" + stylesheetId + " AND SS_TYPE=2 AND PARAM_TYPE=3 AND PARAM_NAME='"
+ pName + "'";
LogService.log(LogService.DEBUG, "RDBMUserLayoutStore::removeThemeStylesheetParam() : " + sQuery);
stmt.executeQuery(sQuery);
} finally {
stmt.close();
}
}
public void removeThemeStylesheetDescription (int stylesheetId) throws Exception {
Connection con = RDBMServices.getConnection();
try {
Statement stmt = con.createStatement();
try {
String sQuery = "DELETE FROM UP_SS_THEME WHERE SS_ID=" + stylesheetId;
LogService.log(LogService.DEBUG, "RDBMUserLayoutStore::removeThemeStylesheetDescription() : " + sQuery);
stmt.executeUpdate(sQuery);
// delete params
sQuery = "DELETE FROM UP_SS_THEME_PARM WHERE SS_ID=" + stylesheetId;
LogService.log(LogService.DEBUG, "RDBMUserLayoutStore::removeThemeStylesheetDescription() : " + sQuery);
stmt.executeUpdate(sQuery);
// nuke all of the profiles that use it
sQuery = "SELECT USER_ID,PROFILE_ID FROM UP_USER_PROFILE WHERE THEME_SS_ID="+stylesheetId;
LogService.log(LogService.DEBUG, "RDBMUserLayoutStore::removeStructureThemeStylesheetDescription() : " + sQuery);
ResultSet rs = stmt.executeQuery(sQuery);
try {
while (rs.next()) {
deleteUserProfile(rs.getInt("USER_ID"),rs.getInt("PROFILE_ID"));
}
} finally {
rs.close();
}
// clean up user preferences - directly ( in case of loose params )
sQuery = "DELETE FROM UP_SS_USER_PARM WHERE SS_ID=" + stylesheetId + " AND SS_TYPE=2";
LogService.log(LogService.DEBUG, "RDBMUserLayoutStore::removeThemeStylesheetDescription() : " + sQuery);
stmt.executeUpdate(sQuery);
sQuery = "DELETE FROM UP_SS_USER_ATTS WHERE SS_ID=" + stylesheetId + " AND SS_TYPE=2";
LogService.log(LogService.DEBUG, "RDBMUserLayoutStore::removeThemeStylesheetDescription() : " + sQuery);
stmt.executeUpdate(sQuery);
RDBMServices.commit(con);
} catch (Exception e) {
// Roll back the transaction
RDBMServices.rollback(con);
throw e;
} finally {
stmt.close();
}
} finally {
RDBMServices.releaseConnection(con);
}
}
/**
* Remove (with cleanup) a theme stylesheet param
* @param stylesheetId id of the theme stylesheet
* @param pName name of the parameter
* @param con active database connection
*/
private void removeThemeStylesheetParam (int stylesheetId, String pName, Connection con) throws java.sql.SQLException {
Statement stmt = con.createStatement();
try {
String sQuery = "DELETE FROM UP_SS_THEME_PARM WHERE SS_ID=" + stylesheetId + " AND TYPE=1 AND PARAM_NAME='" + pName
+ "'";
LogService.log(LogService.DEBUG, "RDBMUserLayoutStore::removeThemeStylesheetParam() : " + sQuery);
stmt.executeQuery(sQuery);
// clean up user preference tables
sQuery = "DELETE FROM UP_SS_USER_PARM WHERE SS_ID=" + stylesheetId + " AND SS_TYPE=2 AND PARAM_TYPE=1 AND PARAM_NAME='"
+ pName + "'";
LogService.log(LogService.DEBUG, "RDBMUserLayoutStore::removeThemeStylesheetParam() : " + sQuery);
stmt.executeQuery(sQuery);
} finally {
stmt.close();
}
}
protected final int saveStructure (Node node, RDBMServices.PreparedStatement structStmt, RDBMServices.PreparedStatement parmStmt) throws java.sql.SQLException {
if (node == null || node.getNodeName().equals("parameter")) { // No more or parameter node
return 0;
}
Element structure = (Element)node;
int saveStructId = Integer.parseInt(structure.getAttribute("ID").substring(1));
int nextStructId = 0;
int childStructId = 0;
String sQuery;
if (DEBUG > 0) {
LogService.log(LogService.DEBUG, "-->" + node.getNodeName() + "@" + saveStructId);
}
if (node.hasChildNodes()) {
childStructId = saveStructure(node.getFirstChild(), structStmt, parmStmt);
}
nextStructId = saveStructure(node.getNextSibling(), structStmt, parmStmt);
structStmt.clearParameters();
structStmt.setInt(1, saveStructId);
structStmt.setInt(2, nextStructId);
structStmt.setInt(3, childStructId);
String externalId = structure.getAttribute("external_id");
if (externalId != null && externalId.trim().length() > 0) {
Integer eID = new Integer(externalId);
structStmt.setInt(4, eID.intValue());
} else {
structStmt.setNull(4, java.sql.Types.NUMERIC);
}
if (node.getNodeName().equals("channel")) {
int chanId = Integer.parseInt(node.getAttributes().getNamedItem("chanID").getNodeValue());
structStmt.setInt(5, chanId);
structStmt.setNull(6,java.sql.Types.VARCHAR);
}
else {
structStmt.setNull(5,java.sql.Types.NUMERIC);
structStmt.setString(6, structure.getAttribute("name"));
}
String structType = structure.getAttribute("type");
structStmt.setString(7, structType);
structStmt.setString(8, RDBMServices.dbFlag(xmlBool(structure.getAttribute("hidden"))));
structStmt.setString(9, RDBMServices.dbFlag(xmlBool(structure.getAttribute("immutable"))));
structStmt.setString(10, RDBMServices.dbFlag(xmlBool(structure.getAttribute("unremovable"))));
LogService.log(LogService.DEBUG, "RDBMUserLayoutStore::saveStructure(): " + structStmt);
structStmt.executeUpdate();
NodeList parameters = node.getChildNodes();
if (parameters != null) {
for (int i = 0; i < parameters.getLength(); i++) {
if (parameters.item(i).getNodeName().equals("parameter")) {
Element parmElement = (Element)parameters.item(i);
NamedNodeMap nm = parmElement.getAttributes();
String nodeName = nm.getNamedItem("name").getNodeValue();
String nodeValue = nm.getNamedItem("value").getNodeValue();
Node override = nm.getNamedItem("override");
if (DEBUG > 0) {
System.err.println(nodeName + "=" + nodeValue);
}
if (override == null || !override.getNodeValue().equals("yes")) {
if (DEBUG > 0)
System.err.println("Not saving channel defined parameter value " + nodeName);
}
else {
parmStmt.clearParameters();
parmStmt.setInt(1, saveStructId);
parmStmt.setString(2, nodeName);
parmStmt.setString(3, nodeValue);
LogService.log(LogService.DEBUG, "RDBMUserLayoutStore::saveStructure(): " + parmStmt);
parmStmt.executeUpdate();
}
}
}
}
return saveStructId;
}
public void setStructureStylesheetUserPreferences (IPerson person, int profileId, StructureStylesheetUserPreferences ssup) throws Exception {
int userId = person.getID();
Connection con = RDBMServices.getConnection();
try {
// Set autocommit false for the connection
int stylesheetId = ssup.getStylesheetId();
RDBMServices.setAutoCommit(con, false);
Statement stmt = con.createStatement();
try {
// write out params
for (Enumeration e = ssup.getParameterValues().keys(); e.hasMoreElements();) {
String pName = (String)e.nextElement();
// see if the parameter was already there
String sQuery = "SELECT PARAM_VAL FROM UP_SS_USER_PARM WHERE USER_ID=" + userId + " AND PROFILE_ID=" + profileId
+ " AND SS_ID=" + stylesheetId + " AND SS_TYPE=1 AND PARAM_NAME='" + pName + "'";
LogService.log(LogService.DEBUG, "RDBMUserLayoutStore::setStructureStylesheetUserPreferences(): " + sQuery);
ResultSet rs = stmt.executeQuery(sQuery);
if (rs.next()) {
// update
sQuery = "UPDATE UP_SS_USER_PARM SET PARAM_VAL='" + ssup.getParameterValue(pName) + "' WHERE USER_ID=" + userId
+ " AND PROFILE_ID=" + profileId + " AND SS_ID=" + stylesheetId + " AND SS_TYPE=1 AND PARAM_NAME='" + pName
+ "'";
}
else {
// insert
sQuery = "INSERT INTO UP_SS_USER_PARM (USER_ID,PROFILE_ID,SS_ID,SS_TYPE,PARAM_NAME,PARAM_VAL) VALUES (" + userId
+ "," + profileId + "," + stylesheetId + ",1,'" + pName + "','" + ssup.getParameterValue(pName) + "')";
}
LogService.log(LogService.DEBUG, "RDBMUserLayoutStore::setStructureStylesheetUserPreferences(): " + sQuery);
stmt.executeUpdate(sQuery);
}
// write out folder attributes
for (Enumeration e = ssup.getFolders(); e.hasMoreElements();) {
String folderId = (String)e.nextElement();
for (Enumeration attre = ssup.getFolderAttributeNames(); attre.hasMoreElements();) {
String pName = (String)attre.nextElement();
String pValue = ssup.getDefinedFolderAttributeValue(folderId, pName);
if (pValue != null) {
// store user preferences
String sQuery = "SELECT PARAM_VAL FROM UP_SS_USER_ATTS WHERE USER_ID=" + userId + " AND PROFILE_ID=" + profileId
+ " AND SS_ID=" + stylesheetId + " AND SS_TYPE=1 AND STRUCT_ID=" + folderId.substring(1) + " AND PARAM_NAME='" + pName
+ "' AND PARAM_TYPE=2";
LogService.log(LogService.DEBUG, "RDBMUserLayoutStore::setStructureStylesheetUserPreferences(): " + sQuery);
ResultSet rs = stmt.executeQuery(sQuery);
if (rs.next()) {
// update
sQuery = "UPDATE UP_SS_USER_ATTS SET PARAM_VAL='" + pValue + "' WHERE USER_ID=" + userId + " AND PROFILE_ID="
+ profileId + " AND SS_ID=" + stylesheetId + " AND SS_TYPE=1 AND STRUCT_ID=" + folderId.substring(1) + " AND PARAM_NAME='"
+ pName + "' AND PARAM_TYPE=2";
}
else {
// insert
sQuery = "INSERT INTO UP_SS_USER_ATTS (USER_ID,PROFILE_ID,SS_ID,SS_TYPE,STRUCT_ID,PARAM_NAME,PARAM_TYPE,PARAM_VAL) VALUES ("
+ userId + "," + profileId + "," + stylesheetId + ",1," + folderId.substring(1) + ",'" + pName + "',2,'" + pValue
+ "')";
}
LogService.log(LogService.DEBUG, "RDBMUserLayoutStore::setStructureStylesheetUserPreferences(): " + sQuery);
stmt.executeUpdate(sQuery);
}
}
}
// write out channel attributes
for (Enumeration e = ssup.getChannels(); e.hasMoreElements();) {
String channelId = (String)e.nextElement();
for (Enumeration attre = ssup.getChannelAttributeNames(); attre.hasMoreElements();) {
String pName = (String)attre.nextElement();
String pValue = ssup.getDefinedChannelAttributeValue(channelId, pName);
if (pValue != null) {
// store user preferences
String sQuery = "SELECT PARAM_VAL FROM UP_SS_USER_ATTS WHERE USER_ID=" + userId + " AND PROFILE_ID=" + profileId
+ " AND SS_ID=" + stylesheetId + " AND SS_TYPE=1 AND STRUCT_ID=" + channelId.substring(1) + " AND PARAM_NAME='" + pName
+ "' AND PARAM_TYPE=3";
LogService.log(LogService.DEBUG, "RDBMUserLayoutStore::setStructureStylesheetUserPreferences(): " + sQuery);
ResultSet rs = stmt.executeQuery(sQuery);
if (rs.next()) {
// update
sQuery = "UPDATE UP_SS_USER_ATTS SET PARAM_VAL='" + pValue + "' WHERE USER_ID=" + userId + " AND PROFILE_ID="
+ profileId + " AND SS_ID=" + stylesheetId + " AND SS_TYPE=1 AND STRUCT_ID=" + channelId.substring(1) + " AND PARAM_NAME='"
+ pName + "' AND PARAM_TYPE=3";
}
else {
// insert
sQuery = "INSERT INTO UP_SS_USER_ATTS (USER_ID,PROFILE_ID,SS_ID,SS_TYPE,STRUCT_ID,PARAM_NAME,PARAM_TYPE,PARAM_VAL) VALUES ("
+ userId + "," + profileId + "," + stylesheetId + ",1," + channelId.substring(1) + ",'" + pName + "',3,'" + pValue
+ "')";
}
LogService.log(LogService.DEBUG, "RDBMUserLayoutStore::setStructureStylesheetUserPreferences(): " + sQuery);
stmt.executeUpdate(sQuery);
}
}
}
// Commit the transaction
RDBMServices.commit(con);
} catch (Exception e) {
// Roll back the transaction
RDBMServices.rollback(con);
throw e;
} finally {
stmt.close();
}
} finally {
RDBMServices.releaseConnection(con);
}
}
public void setThemeStylesheetUserPreferences (IPerson person, int profileId, ThemeStylesheetUserPreferences tsup) throws Exception {
int userId = person.getID();
Connection con = RDBMServices.getConnection();
try {
// Set autocommit false for the connection
int stylesheetId = tsup.getStylesheetId();
RDBMServices.setAutoCommit(con, false);
Statement stmt = con.createStatement();
try {
// write out params
for (Enumeration e = tsup.getParameterValues().keys(); e.hasMoreElements();) {
String pName = (String)e.nextElement();
// see if the parameter was already there
String sQuery = "SELECT PARAM_VAL FROM UP_SS_USER_PARM WHERE USER_ID=" + userId + " AND PROFILE_ID=" + profileId
+ " AND SS_ID=" + stylesheetId + " AND SS_TYPE=2 AND PARAM_NAME='" + pName + "'";
LogService.log(LogService.DEBUG, "RDBMUserLayoutStore::setThemeStylesheetUserPreferences(): " + sQuery);
ResultSet rs = stmt.executeQuery(sQuery);
if (rs.next()) {
// update
sQuery = "UPDATE UP_SS_USER_PARM SET PARAM_VAL='" + tsup.getParameterValue(pName) + "' WHERE USER_ID=" + userId
+ " AND PROFILE_ID=" + profileId + " AND SS_ID=" + stylesheetId + " AND SS_TYPE=2 AND PARAM_NAME='" + pName
+ "'";
}
else {
// insert
sQuery = "INSERT INTO UP_SS_USER_PARM (USER_ID,PROFILE_ID,SS_ID,SS_TYPE,PARAM_NAME,PARAM_VAL) VALUES (" + userId
+ "," + profileId + "," + stylesheetId + ",2,'" + pName + "','" + tsup.getParameterValue(pName) + "')";
}
LogService.log(LogService.DEBUG, "RDBMUserLayoutStore::setThemeStylesheetUserPreferences(): " + sQuery);
stmt.executeUpdate(sQuery);
}
// write out channel attributes
for (Enumeration e = tsup.getChannels(); e.hasMoreElements();) {
String channelId = (String)e.nextElement();
for (Enumeration attre = tsup.getChannelAttributeNames(); attre.hasMoreElements();) {
String pName = (String)attre.nextElement();
String pValue = tsup.getDefinedChannelAttributeValue(channelId, pName);
if (pValue != null) {
// store user preferences
String sQuery = "SELECT PARAM_VAL FROM UP_SS_USER_ATTS WHERE USER_ID=" + userId + " AND PROFILE_ID=" + profileId
+ " AND SS_ID=" + stylesheetId + " AND SS_TYPE=2 AND STRUCT_ID=" + channelId.substring(1) + " AND PARAM_NAME='" + pName
+ "' AND PARAM_TYPE=3";
LogService.log(LogService.DEBUG, "RDBMUserLayoutStore::setThemeStylesheetUserPreferences(): " + sQuery);
ResultSet rs = stmt.executeQuery(sQuery);
if (rs.next()) {
// update
sQuery = "UPDATE UP_SS_USER_ATTS SET PARAM_VAL='" + pValue + "' WHERE USER_ID=" + userId + " AND PROFILE_ID="
+ profileId + " AND SS_ID=" + stylesheetId + " AND SS_TYPE=2 AND STRUCT_ID=" + channelId.substring(1) + " AND PARAM_NAME='"
+ pName + "' AND PARAM_TYPE=3";
}
else {
// insert
sQuery = "INSERT INTO UP_SS_USER_ATTS (USER_ID,PROFILE_ID,SS_ID,SS_TYPE,STRUCT_ID,PARAM_NAME,PARAM_TYPE,PARAM_VAL) VALUES ("
+ userId + "," + profileId + "," + stylesheetId + ",2," + channelId.substring(1) + ",'" + pName + "',3,'" + pValue
+ "')";
}
LogService.log(LogService.DEBUG, "RDBMUserLayoutStore::setThemeStylesheetUserPreferences(): " + sQuery);
stmt.executeUpdate(sQuery);
}
}
}
// Commit the transaction
RDBMServices.commit(con);
} catch (Exception e) {
// Roll back the transaction
RDBMServices.rollback(con);
throw e;
} finally {
stmt.close();
}
} finally {
RDBMServices.releaseConnection(con);
}
}
public void setUserBrowserMapping (IPerson person, String userAgent, int profileId) throws Exception {
int userId = person.getID();
Connection con = RDBMServices.getConnection();
try {
// Set autocommit false for the connection
RDBMServices.setAutoCommit(con, false);
// remove the old mapping and add the new one
Statement stmt = con.createStatement();
try {
String sQuery = "DELETE FROM UP_USER_UA_MAP WHERE USER_ID=" + userId + " AND USER_AGENT='" + userAgent + "'";
LogService.log(LogService.DEBUG, "RDBMUserLayoutStore::setUserBrowserMapping(): " + sQuery);
stmt.executeUpdate(sQuery);
sQuery = "INSERT INTO UP_USER_UA_MAP (USER_ID,USER_AGENT,PROFILE_ID) VALUES (" + userId + ",'" + userAgent + "',"
+ profileId + ")";
LogService.log(LogService.DEBUG, "RDBMUserLayoutStore::setUserBrowserMapping(): " + sQuery);
stmt.executeUpdate(sQuery);
// Commit the transaction
RDBMServices.commit(con);
} catch (Exception e) {
// Roll back the transaction
RDBMServices.rollback(con);
throw e;
} finally {
stmt.close();
}
} finally {
RDBMServices.releaseConnection(con);
}
}
/**
* Save the user layout
* @param person
* @param profileId
* @param layoutXML
* @throws Exception
*/
public void setUserLayout (IPerson person, UserProfile profile, Document layoutXML, boolean channelsAdded) throws Exception {
int userId = person.getID();
int profileId=profile.getProfileId();
int layoutId=0;
ResultSet rs;
Connection con = RDBMServices.getConnection();
try {
RDBMServices.setAutoCommit(con, false); // Need an atomic update here
Statement stmt = con.createStatement();
try {
long startTime = System.currentTimeMillis();
// eventually we want to be able to just get layoutId from the profile, but because of the
// template user layouts we have to do this for now ...
String query = "SELECT LAYOUT_ID FROM UP_USER_PROFILE WHERE USER_ID=" + userId + " AND PROFILE_ID=" + profileId;
LogService.log(LogService.DEBUG, "RDBMUserLayoutStore::setUserLayout(): " + query);
rs = stmt.executeQuery(query);
try {
rs.next();
layoutId = rs.getInt(1);
if (rs.wasNull()) {
layoutId = 0;
}
} finally {
rs.close();
}
boolean firstLayout = false;
if (layoutId == 0) { // First personal layout for this user/profile
layoutId = 1;
firstLayout = true;
}
String selectString = "USER_ID=" + userId + " AND LAYOUT_ID=" + layoutId;
String sSql = "DELETE FROM UP_LAYOUT_PARAM WHERE " + selectString;
LogService.log(LogService.DEBUG, "RDBMUserLayoutStore::setUserLayout(): " + sSql);
stmt.executeUpdate(sSql);
sSql = "DELETE FROM UP_LAYOUT_STRUCT WHERE " + selectString;
LogService.log(LogService.DEBUG, "RDBMUserLayoutStore::setUserLayout(): " + sSql);
stmt.executeUpdate(sSql);
if (DEBUG > 1) {
System.err.println("--> saving document");
dumpDoc(layoutXML.getFirstChild().getFirstChild(), "");
System.err.println("<
}
RDBMServices.PreparedStatement structStmt = new RDBMServices.PreparedStatement(con,
"INSERT INTO UP_LAYOUT_STRUCT " +
"(USER_ID, LAYOUT_ID, STRUCT_ID, NEXT_STRUCT_ID, CHLD_STRUCT_ID,EXTERNAL_ID,CHAN_ID,NAME,TYPE,HIDDEN,IMMUTABLE,UNREMOVABLE) " +
"VALUES ("+ userId + "," + layoutId + ",?,?,?,?,?,?,?,?,?,?)");
try {
RDBMServices.PreparedStatement parmStmt = new RDBMServices.PreparedStatement(con,
"INSERT INTO UP_LAYOUT_PARAM " +
"(USER_ID, LAYOUT_ID, STRUCT_ID, STRUCT_PARM_NM, STRUCT_PARM_VAL) " +
"VALUES ("+ userId + "," + layoutId + ",?,?,?)");
try {
int firstStructId = saveStructure(layoutXML.getFirstChild().getFirstChild(), structStmt, parmStmt);
sSql = "UPDATE UP_USER_LAYOUT SET INIT_STRUCT_ID=" + firstStructId + " WHERE " + selectString;
LogService.log(LogService.DEBUG, "RDBMUserLayoutStore::setUserLayout(): " + sSql);
stmt.executeUpdate(sSql);
// Update the last time the user saw the list of available channels
if (channelsAdded) {
sSql = "UPDATE UP_USER SET LST_CHAN_UPDT_DT=" + RDBMServices.sqlTimeStamp() +
" WHERE USER_ID=" + userId;
LogService.log(LogService.DEBUG, "RDBMUserLayoutStore::setUserLayout(): " + sSql);
stmt.executeUpdate(sSql);
}
if (firstLayout) {
int defaultUserId;
int defaultLayoutId;
// Have to copy some of data over from the default user
String sQuery = "SELECT USER_DFLT_USR_ID,USER_DFLT_LAY_ID FROM UP_USER WHERE USER_ID=" + userId;
LogService.log(LogService.DEBUG, "RDBMUserLayoutStore::setUserLayout(): " + sQuery);
rs = stmt.executeQuery(sQuery);
try {
rs.next();
defaultUserId = rs.getInt(1);
defaultLayoutId = rs.getInt(2);
} finally {
rs.close();
}
sQuery = "UPDATE UP_USER_PROFILE SET LAYOUT_ID=1 WHERE USER_ID=" + userId + " AND PROFILE_ID=" + profileId;
LogService.log(LogService.DEBUG, "RDBMUserLayoutStore::setUserLayout(): " + sQuery);
stmt.executeUpdate(sQuery);
}
long stopTime = System.currentTimeMillis();
LogService.log(LogService.DEBUG, "RDBMUserLayoutStore::setUserLayout(): Layout document for user " + userId + " took " +
(stopTime - startTime) + " milliseconds to save");
} finally {
parmStmt.close();
}
} finally {
structStmt.close();
}
} finally {
stmt.close();
}
RDBMServices.commit(con);
} catch (Exception e) {
RDBMServices.rollback(con);
throw e;
} finally {
RDBMServices.releaseConnection(con);
}
}
public void setUserProfile (IPerson person, UserProfile profile) throws Exception {
int userId = person.getID();
Connection con = RDBMServices.getConnection();
try {
Statement stmt = con.createStatement();
try {
// this is ugly, but we have to know wether to do INSERT or UPDATE
String sQuery = "SELECT USER_ID, PROFILE_NAME FROM UP_USER_PROFILE WHERE USER_ID=" + userId + " AND PROFILE_ID="
+ profile.getProfileId();
LogService.log(LogService.DEBUG, "RDBMUserLayoutStore::setUserProfile() : " + sQuery);
ResultSet rs = stmt.executeQuery(sQuery);
try {
if (rs.next()) {
sQuery = "UPDATE UP_USER_PROFILE SET THEME_SS_ID=" + profile.getThemeStylesheetId() + ", STRUCTURE_SS_ID=" +
profile.getStructureStylesheetId() + ", DESCRIPTION='" + profile.getProfileDescription() + "', PROFILE_NAME='"
+ profile.getProfileName() + "' WHERE USER_ID = " + userId + " AND PROFILE_ID=" + profile.getProfileId();
}
else {
sQuery = "INSERT INTO UP_USER_PROFILE (USER_ID,PROFILE_ID,PROFILE_NAME,STRUCTURE_SS_ID,THEME_SS_ID,DESCRIPTION) VALUES ("
+ userId + "," + profile.getProfileId() + ",'" + profile.getProfileName() + "'," + profile.getStructureStylesheetId()
+ "," + profile.getThemeStylesheetId() + ",'" + profile.getProfileDescription() + "')";
}
} finally {
rs.close();
}
LogService.log(LogService.DEBUG, "RDBMUserLayoutStore::setUserProfile(): " + sQuery);
stmt.executeUpdate(sQuery);
} finally {
stmt.close();
}
} finally {
RDBMServices.releaseConnection(con);
}
}
/**
* Updates an existing structure stylesheet description with a new one. Old stylesheet
* description is found based on the Id provided in the parameter structure.
* @param ssd new stylesheet description
*/
public void updateStructureStylesheetDescription (StructureStylesheetDescription ssd) throws Exception {
Connection con = RDBMServices.getConnection();
try {
// Set autocommit false for the connection
RDBMServices.setAutoCommit(con, false);
Statement stmt = con.createStatement();
try {
int stylesheetId = ssd.getId();
String sQuery = "UPDATE UP_SS_STRUCT SET SS_NAME='" + ssd.getStylesheetName() + "',SS_URI='" + ssd.getStylesheetURI()
+ "',SS_DESCRIPTION_URI='" + ssd.getStylesheetDescriptionURI() + "',SS_DESCRIPTION_TEXT='" + ssd.getStylesheetWordDescription()
+ "' WHERE SS_ID=" + stylesheetId;
LogService.log(LogService.DEBUG, "RDBMUserLayoutStore::addThemeStylesheetDescription() : " + sQuery);
stmt.executeUpdate(sQuery);
// first, see what was there before
HashSet oparams = new HashSet();
HashSet ofattrs = new HashSet();
HashSet ocattrs = new HashSet();
sQuery = "SELECT PARAM_NAME,PARAM_DEFAULT_VAL,PARAM_DESCRIPT,TYPE FROM UP_SS_STRUCT_PAR WHERE SS_ID=" + stylesheetId;
LogService.log(LogService.DEBUG, "RDBMUserLayoutStore::updateStructureStylesheetDescription() : " + sQuery);
Statement stmtOld = con.createStatement();
ResultSet rsOld = stmtOld.executeQuery(sQuery);
try {
while (rsOld.next()) {
int type = rsOld.getInt("TYPE");
if (type == 1) {
// stylesheet param
String pName = rsOld.getString("PARAM_NAME");
oparams.add(pName);
if (!ssd.containsParameterName(pName)) {
// delete param
removeStructureStylesheetParam(stylesheetId, pName, con);
}
else {
// update param
sQuery = "UPDATE UP_SS_STRUCT_PAR SET PARAM_DEFAULT_VAL='" + ssd.getStylesheetParameterDefaultValue(pName)
+ "',PARAM_DESCRIPT='" + ssd.getStylesheetParameterWordDescription(pName) + "' WHERE SS_ID=" + stylesheetId
+ " AND PARAM_NAME='" + pName + "' AND TYPE=1";
LogService.log(LogService.DEBUG, "RDBMUserLayoutStore::updateStructureStylesheetDescription() : " + sQuery);
stmt.executeUpdate(sQuery);
}
}
else if (type == 2) {
// folder attribute
String pName = rsOld.getString("PARAM_NAME");
ofattrs.add(pName);
if (!ssd.containsFolderAttribute(pName)) {
// delete folder attribute
removeStructureFolderAttribute(stylesheetId, pName, con);
}
else {
// update folder attribute
sQuery = "UPDATE UP_SS_STRUCT_PAR SET PARAM_DEFAULT_VAL='" + ssd.getFolderAttributeDefaultValue(pName) +
"',PARAM_DESCRIPT='" + ssd.getFolderAttributeWordDescription(pName) + "' WHERE SS_ID=" + stylesheetId
+ " AND PARAM_NAME='" + pName + "'AND TYPE=2";
LogService.log(LogService.DEBUG, "RDBMUserLayoutStore::updateStructureStylesheetDescription() : " + sQuery);
stmt.executeUpdate(sQuery);
}
}
else if (type == 3) {
// channel attribute
String pName = rsOld.getString("PARAM_NAME");
ocattrs.add(pName);
if (!ssd.containsChannelAttribute(pName)) {
// delete channel attribute
removeStructureChannelAttribute(stylesheetId, pName, con);
}
else {
// update channel attribute
sQuery = "UPDATE UP_SS_STRUCT_PAR SET PARAM_DEFAULT_VAL='" + ssd.getChannelAttributeDefaultValue(pName) +
"',PARAM_DESCRIPT='" + ssd.getChannelAttributeWordDescription(pName) + "' WHERE SS_ID=" + stylesheetId
+ " AND PARAM_NAME='" + pName + "' AND TYPE=3";
LogService.log(LogService.DEBUG, "RDBMUserLayoutStore::updateStructureStylesheetDescription() : " + sQuery);
stmt.executeUpdate(sQuery);
}
}
else {
LogService.log(LogService.DEBUG, "RDBMUserLayoutStore::getStructureStylesheetDescription() : encountered param of unknown type! (stylesheetId="
+ stylesheetId + " param_name=\"" + rsOld.getString("PARAM_NAME") + "\" type=" + type +
").");
}
}
} finally {
rsOld.close();
stmtOld.close();
}
// look for new attributes/parameters
// insert all stylesheet params
for (Enumeration e = ssd.getStylesheetParameterNames(); e.hasMoreElements();) {
String pName = (String)e.nextElement();
if (!oparams.contains(pName)) {
sQuery = "INSERT INTO UP_SS_STRUCT_PAR (SS_ID,PARAM_NAME,PARAM_DEFAULT_VAL,PARAM_DESCRIPT,TYPE) VALUES (" +
stylesheetId + ",'" + pName + "','" + ssd.getStylesheetParameterDefaultValue(pName) + "','" + ssd.getStylesheetParameterWordDescription(pName)
+ "',1)";
LogService.log(LogService.DEBUG, "RDBMUserLayoutStore::addThemeStylesheetDescription(): " + sQuery);
stmt.executeUpdate(sQuery);
}
}
// insert all folder attributes
for (Enumeration e = ssd.getFolderAttributeNames(); e.hasMoreElements();) {
String pName = (String)e.nextElement();
if (!ofattrs.contains(pName)) {
sQuery = "INSERT INTO UP_SS_STRUCT_PAR (SS_ID,PARAM_NAME,PARAM_DEFAULT_VAL,PARAM_DESCRIPT,TYPE) VALUES (" +
stylesheetId + ",'" + pName + "','" + ssd.getFolderAttributeDefaultValue(pName) + "','" + ssd.getFolderAttributeWordDescription(pName)
+ "',2)";
LogService.log(LogService.DEBUG, "RDBMUserLayoutStore::addThemeStylesheetDescription(): " + sQuery);
stmt.executeUpdate(sQuery);
}
}
// insert all channel attributes
for (Enumeration e = ssd.getChannelAttributeNames(); e.hasMoreElements();) {
String pName = (String)e.nextElement();
if (!ocattrs.contains(pName)) {
sQuery = "INSERT INTO UP_SS_STRUCT_PAR (SS_ID,PARAM_NAME,PARAM_DEFAULT_VAL,PARAM_DESCRIPT,TYPE) VALUES (" +
stylesheetId + ",'" + pName + "','" + ssd.getChannelAttributeDefaultValue(pName) + "','" + ssd.getChannelAttributeWordDescription(pName)
+ "',3)";
LogService.log(LogService.DEBUG, "RDBMUserLayoutStore::addThemeStylesheetDescription(): " + sQuery);
stmt.executeUpdate(sQuery);
}
}
// Commit the transaction
RDBMServices.commit(con);
} catch (Exception e) {
// Roll back the transaction
RDBMServices.rollback(con);
throw e;
} finally {
stmt.close();
}
} finally {
RDBMServices.releaseConnection(con);
}
}
/**
* Updates an existing structure stylesheet description with a new one. Old stylesheet
* description is found based on the Id provided in the parameter structure.
* @param ssd new stylesheet description
*/
public void updateThemeStylesheetDescription (ThemeStylesheetDescription tsd) throws Exception {
Connection con = RDBMServices.getConnection();
try {
// Set autocommit false for the connection
RDBMServices.setAutoCommit(con, false);
Statement stmt = con.createStatement();
try {
int stylesheetId = tsd.getId();
String sQuery = "UPDATE UP_SS_THEME SET SS_NAME='" + tsd.getStylesheetName() + "',SS_URI='" + tsd.getStylesheetURI()+ "',SS_DESCRIPTION_URI='" + tsd.getStylesheetDescriptionURI() + "',SS_DESCRIPTION_TEXT='" + tsd.getStylesheetWordDescription() + "',SAMPLE_ICON_URI='"+tsd.getSampleIconURI()+"',SAMPLE_URI='"+tsd.getSamplePictureURI()+"',MIME_TYPE='"+tsd.getMimeType()+"',DEVICE_TYPE='"+tsd.getDeviceType()+"',SERIALIZER_NAME='"+tsd.getSerializerName()+"',UP_MODULE_CLASS='"+tsd.getCustomUserPreferencesManagerClass()+"' WHERE SS_ID=" + stylesheetId;
LogService.log(LogService.DEBUG, "RDBMUserLayoutStore::updateThemeStylesheetDescription() : " + sQuery);
stmt.executeUpdate(sQuery);
// first, see what was there before
HashSet oparams = new HashSet();
HashSet ocattrs = new HashSet();
sQuery = "SELECT PARAM_NAME,PARAM_DEFAULT_VAL,PARAM_DESCRIPT,TYPE FROM UP_SS_THEME_PARM WHERE SS_ID=" + stylesheetId;
LogService.log(LogService.DEBUG, "RDBMUserLayoutStore::updateThemeStylesheetDescription() : " + sQuery);
Statement stmtOld = con.createStatement();
ResultSet rsOld = stmtOld.executeQuery(sQuery);
try {
while (rsOld.next()) {
int type = rsOld.getInt("TYPE");
if (type == 1) {
// stylesheet param
String pName = rsOld.getString("PARAM_NAME");
oparams.add(pName);
if (!tsd.containsParameterName(pName)) {
// delete param
removeThemeStylesheetParam(stylesheetId, pName, con);
}
else {
// update param
sQuery = "UPDATE UP_SS_THEME_PARM SET PARAM_DEFAULT_VAL='" + tsd.getStylesheetParameterDefaultValue(pName)
+ "',PARAM_DESCRIPT='" + tsd.getStylesheetParameterWordDescription(pName) + "' WHERE SS_ID=" + stylesheetId
+ " AND PARAM_NAME='" + pName + "' AND TYPE=1";
LogService.log(LogService.DEBUG, "RDBMUserLayoutStore::updateThemeStylesheetDescription() : " + sQuery);
stmt.executeUpdate(sQuery);
}
}
else if (type == 2) {
LogService.log(LogService.DEBUG, "RDBMUserLayoutStore::getThemeStylesheetDescription() : encountered a folder attribute specified for a theme stylesheet ! DB is corrupt. (stylesheetId="
+ stylesheetId + " param_name=\"" + rsOld.getString("PARAM_NAME") + "\" type=" + type +
").");
}
else if (type == 3) {
// channel attribute
String pName = rsOld.getString("PARAM_NAME");
ocattrs.add(pName);
if (!tsd.containsChannelAttribute(pName)) {
// delete channel attribute
removeThemeChannelAttribute(stylesheetId, pName, con);
}
else {
// update channel attribute
sQuery = "UPDATE UP_SS_THEME_PARM SET PARAM_DEFAULT_VAL='" + tsd.getChannelAttributeDefaultValue(pName) +
"',PARAM_DESCRIPT='" + tsd.getChannelAttributeWordDescription(pName) + "' WHERE SS_ID=" + stylesheetId
+ " AND PARAM_NAME='" + pName + "' AND TYPE=3";
LogService.log(LogService.DEBUG, "RDBMUserLayoutStore::updateThemeStylesheetDescription() : " + sQuery);
stmt.executeUpdate(sQuery);
}
}
else {
LogService.log(LogService.DEBUG, "RDBMUserLayoutStore::getThemeStylesheetDescription() : encountered param of unknown type! (stylesheetId="
+ stylesheetId + " param_name=\"" + rsOld.getString("PARAM_NAME") + "\" type=" + type +
").");
}
}
} finally {
rsOld.close();
stmtOld.close();
}
// look for new attributes/parameters
// insert all stylesheet params
for (Enumeration e = tsd.getStylesheetParameterNames(); e.hasMoreElements();) {
String pName = (String)e.nextElement();
if (!oparams.contains(pName)) {
sQuery = "INSERT INTO UP_SS_THEME_PARM (SS_ID,PARAM_NAME,PARAM_DEFAULT_VAL,PARAM_DESCRIPT,TYPE) VALUES (" + stylesheetId
+ ",'" + pName + "','" + tsd.getStylesheetParameterDefaultValue(pName) + "','" + tsd.getStylesheetParameterWordDescription(pName)
+ "',1)";
LogService.log(LogService.DEBUG, "RDBMUserLayoutStore::addThemeStylesheetDescription(): " + sQuery);
stmt.executeUpdate(sQuery);
}
}
// insert all channel attributes
for (Enumeration e = tsd.getChannelAttributeNames(); e.hasMoreElements();) {
String pName = (String)e.nextElement();
if (!ocattrs.contains(pName)) {
sQuery = "INSERT INTO UP_SS_THEME_PARM (SS_ID,PARAM_NAME,PARAM_DEFAULT_VAL,PARAM_DESCRIPT,TYPE) VALUES (" + stylesheetId
+ ",'" + pName + "','" + tsd.getChannelAttributeDefaultValue(pName) + "','" + tsd.getChannelAttributeWordDescription(pName)
+ "',3)";
LogService.log(LogService.DEBUG, "RDBMUserLayoutStore::addThemeStylesheetDescription(): " + sQuery);
stmt.executeUpdate(sQuery);
}
}
// Commit the transaction
RDBMServices.commit(con);
} catch (Exception e) {
// Roll back the transaction
RDBMServices.rollback(con);
throw e;
} finally {
stmt.close();
}
} finally {
RDBMServices.releaseConnection(con);
}
}
public void updateUserProfile (IPerson person, UserProfile profile) throws Exception {
int userId = person.getID();
Connection con = RDBMServices.getConnection();
try {
Statement stmt = con.createStatement();
try {
String sQuery = "UPDATE UP_USER_PROFILE SET THEME_SS_ID=" + profile.getThemeStylesheetId() + ", STRUCTURE_SS_ID="
+ profile.getStructureStylesheetId() + ", DESCRIPTION='" + profile.getProfileDescription() + "', PROFILE_NAME='"
+ profile.getProfileName() + "' WHERE USER_ID = " + userId + " AND PROFILE_ID=" + profile.getProfileId();
LogService.log(LogService.DEBUG, "RDBMUserLayoutStore::updateUserProfile() : " + sQuery);
stmt.executeUpdate(sQuery);
} finally {
stmt.close();
}
} finally {
RDBMServices.releaseConnection(con);
}
}
public void setSystemBrowserMapping (String userAgent, int profileId) throws Exception {
this.setUserBrowserMapping(systemUser, userAgent, profileId);
}
private int getSystemBrowserMapping (String userAgent) throws Exception {
return getUserBrowserMapping(systemUser, userAgent);
}
public UserProfile getUserProfile (IPerson person, String userAgent) throws Exception {
int profileId = getUserBrowserMapping(person, userAgent);
if (profileId == 0)
return null;
return this.getUserProfileById(person, profileId);
}
public UserProfile getSystemProfile (String userAgent) throws Exception {
int profileId = getSystemBrowserMapping(userAgent);
if (profileId == 0)
return null;
UserProfile up = this.getUserProfileById(systemUser, profileId);
up.setSystemProfile(true);
return up;
}
public UserProfile getSystemProfileById (int profileId) throws Exception {
UserProfile up = this.getUserProfileById(systemUser, profileId);
up.setSystemProfile(true);
return up;
}
public Hashtable getSystemProfileList () throws Exception {
Hashtable pl = this.getUserProfileList(systemUser);
for (Enumeration e = pl.elements(); e.hasMoreElements();) {
UserProfile up = (UserProfile)e.nextElement();
up.setSystemProfile(true);
}
return pl;
}
public void updateSystemProfile (UserProfile profile) throws Exception {
this.updateUserProfile(systemUser, profile);
}
public UserProfile addSystemProfile (UserProfile profile) throws Exception {
return addUserProfile(systemUser, profile);
}
public void deleteSystemProfile (int profileId) throws Exception {
this.deleteUserProfile(systemUser, profileId);
}
private class SystemUser implements IPerson {
public void setID(int sID) {}
public int getID() {return 0;}
public void setFullName(String sFullName) {}
public String getFullName() {return "uPortal System Account";}
public Object getAttribute (String key) {return null;}
public void setAttribute (String key, Object value) {}
public Enumeration getAttributes () {return null;}
public Enumeration getAttributeNames () {return null;}
public boolean isGuest() {return(false);}
public ISecurityContext getSecurityContext() { return(null); }
public void setSecurityContext(ISecurityContext context) {}
public EntityIdentifier getEntityIdentifier() {return null;}
}
private IPerson systemUser = new SystemUser(); // We should be getting this from the uPortal
public UserPreferences getUserPreferences (IPerson person, int profileId) throws Exception {
UserPreferences up = null;
UserProfile profile = this.getUserProfileById(person, profileId);
if (profile != null) {
up = getUserPreferences(person, profile);
}
return (up);
}
public UserPreferences getUserPreferences (IPerson person, UserProfile profile) throws Exception {
int profileId = profile.getProfileId();
UserPreferences up = new UserPreferences(profile);
up.setStructureStylesheetUserPreferences(getStructureStylesheetUserPreferences(person, profileId, profile.getStructureStylesheetId()));
up.setThemeStylesheetUserPreferences(getThemeStylesheetUserPreferences(person, profileId, profile.getThemeStylesheetId()));
return up;
}
public void putUserPreferences (IPerson person, UserPreferences up) throws Exception {
// store profile
UserProfile profile = up.getProfile();
this.updateUserProfile(person, profile);
this.setStructureStylesheetUserPreferences(person, profile.getProfileId(), up.getStructureStylesheetUserPreferences());
this.setThemeStylesheetUserPreferences(person, profile.getProfileId(), up.getThemeStylesheetUserPreferences());
}
} |
package org.jasig.portal.layout;
import java.util.Enumeration;
import java.util.Vector;
import org.apache.xpath.XPathAPI;
import org.jasig.portal.PortalException;
import org.jasig.portal.utils.XML;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.ContentHandler;
/**
* The simple user layout implementation. This
* layout is based on a Document.
*
* @author Ken Weiner, kweiner@unicon.net
* @version $Revision$
*/
public class SimpleLayout implements IUserLayout {
private Document layout;
private String layoutId;
private String cacheKey;
public SimpleLayout(String layoutId, Document layout) {
this.layoutId = layoutId;
this.layout = layout;
}
public void writeTo(ContentHandler ch) throws PortalException {
try {
XML.dom2sax(layout, ch);
} catch (Exception e) {
throw new PortalException(e);
}
}
public void writeTo(String nodeId, ContentHandler ch) throws PortalException {
try {
XML.dom2sax(layout.getElementById(nodeId), ch);
} catch (Exception e) {
throw new PortalException(e);
}
}
public void writeTo(Document document) throws PortalException {
document.appendChild(document.importNode(layout.getDocumentElement(), true));
}
public void writeTo(String nodeId, Document document) throws PortalException {
document.appendChild(document.importNode(layout.getElementById(nodeId), true));
}
public IUserLayoutNodeDescription getNodeDescription(String nodeId) throws PortalException {
Element element = (Element) layout.getElementById(nodeId);
return UserLayoutNodeDescription.createUserLayoutNodeDescription(element);
}
public String getParentId(String nodeId) throws PortalException {
String parentId = null;
Element element = (Element)layout.getElementById(nodeId);
if (element != null) {
Node parent = element.getParentNode();
if (parent != null && parent.getNodeType() == Node.ELEMENT_NODE) {
Element parentE = (Element)parent;
parentId = parentE.getAttribute("ID");
}
}
return parentId;
}
public Enumeration getChildIds(String nodeId) throws PortalException {
Vector v = new Vector();
IUserLayoutNodeDescription node = getNodeDescription(nodeId);
if (node instanceof IUserLayoutFolderDescription) {
Element element = (Element)layout.getElementById(nodeId);
for (Node n = element.getFirstChild(); n != null; n = n.getNextSibling()) {
if (n.getNodeType() == Node.ELEMENT_NODE) {
Element e = (Element)n;
if (e.getAttribute("ID") != null) {
v.add(e.getAttribute("ID"));
}
}
}
}
return v.elements();
}
public String getNextSiblingId(String nodeId) throws PortalException {
String nextSiblingId = null;
Element element = (Element)layout.getElementById(nodeId);
if (element != null) {
Node sibling = element.getNextSibling();
// Find the next element node
while (sibling != null && sibling.getNodeType() != Node.ELEMENT_NODE) {
sibling = sibling.getNextSibling();
}
if (sibling != null) {
Element e = (Element)sibling;
nextSiblingId = e.getAttribute("ID");
}
}
return nextSiblingId;
}
public String getPreviousSiblingId(String nodeId) throws PortalException {
String prevSiblingId = null;
Element element = (Element)layout.getElementById(nodeId);
if (element != null) {
Node sibling = element.getPreviousSibling();
// Find the previous element node
while (sibling != null && sibling.getNodeType() != Node.ELEMENT_NODE) {
sibling = sibling.getPreviousSibling();
}
if (sibling != null) {
Element e = (Element)sibling;
prevSiblingId = e.getAttribute("ID");
}
}
return prevSiblingId;
}
public String getCacheKey() throws PortalException {
return cacheKey;
}
public boolean addLayoutEventListener(LayoutEventListener l) {
// TODO: Implement this!
return false;
}
public boolean removeLayoutEventListener(LayoutEventListener l) {
// TODO: Implement this!
return false;
}
public String getId() {
return layoutId;
}
public String getNodeId(String fname) throws PortalException {
String nodeId = null;
NodeList nl = layout.getElementsByTagName("channel");
for (int i = 0; i < nl.getLength(); i++) {
Node node = nl.item(i);
if (node.getNodeType() == Node.ELEMENT_NODE) {
Element channelE = (Element)node;
if (fname.equals(channelE.getAttribute("fname"))) {
nodeId = channelE.getAttribute("ID");
break;
}
}
}
return nodeId;
}
public Enumeration getNodeIds() throws PortalException {
Vector v = new Vector();
try {
NodeList nl = XPathAPI.selectNodeList(layout, "*");
for (int i = 0; i < nl.getLength(); i++) {
Node node = nl.item(i);
if (node.getNodeType() == Node.ELEMENT_NODE) {
Element e = (Element)node;
v.add(e.getAttribute("ID"));
}
}
} catch (Exception e) {
// Do nothing for now
}
return v.elements();
}
public String getRootId() {
String rootNode = null;
try {
Element rootNodeE = (Element) XPathAPI.selectSingleNode(layout, "/layout/folder");
rootNode = rootNodeE.getAttribute("ID");
} catch (Exception e) {
// Do nothing for now
}
return rootNode;
}
} |
package Creator;
import java.awt.Color;
import java.awt.Component;
import java.awt.Container;
import java.awt.Font;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Point;
import java.awt.image.BufferedImage;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.BorderFactory;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.border.Border;
/**
* Background rack is the backgrounds found after the main panels, and before
* the loads panels
*
* @author EricGummerson
*/
public class BackgroundRackNew extends javax.swing.JPanel {
public DisplayFrame df;
public int numRacks;
public Rack rack;
public Font font;
public Border border;
public String img;
public String storeName;
public int rackNum;
public String[] rackNames;
private boolean canClick;
/**
* Creates new form BackgroundRack
*
* @param df
* @param rackNum
*/
public BackgroundRackNew(DisplayFrame df, int rackNum) {
initComponents();
this.df = df;
this.rack = new Rack();
this.img = "";
this.rackNum = rackNum;
this.canClick = false;
this.rackNames = new String[]{"Main", "Rack {}", "Rack {}", "Loads", "Financial"};
}
/**
* Updates the form with the right information
*
* @param rack rack list
* @param numRacks number of racks to read from the list
* @param font global font
* @param border global border
* @param img global img string for the logo
* @param storeName global string for the store name
* @param rackNames rack names as string array
*/
public void updateRacks(Rack rack, int numRacks, Font font, Border border, String img, String storeName, String[] rackNames) {
this.rack = rack;
this.numRacks = numRacks;
this.font = font;
this.border = border;
this.img = img;
this.storeName = storeName;
this.rackNames = rackNames;
this.updateView();
}
/**
* updates the rack number
*
* @param rackNum
*/
public void updateRackNum(int rackNum) {
this.rackNum = rackNum;
}
/**
* updates the storename
*
* @param storeName string of the store name
*/
public void updateStoreName(String storeName) {
this.storeName = storeName;
this.updateView();
}
/**
* updates the image url for the logo
*
* @param img string file path of the logo
*/
public void updateImageURL(String img) {
this.img = img;
this.updateView();
}
/**
* updates the font selected from the settings panel
*
* @param font Font
*/
public void updateFont(Font font) {
this.font = font;
this.updateView();
}
/**
* Updates the border
*
* @param border Border
*/
public void updateBorder(Border border) {
this.border = border;
this.updateView();
}
/**
* Updates the font and bother
*
* @param font Font
* @param border Border
*/
public void updateFontBorder(Font font, Border border) {
this.font = font;
this.border = border;
this.updateView();
}
private void buttonClick() {
if (canClick) {
Point p = this.getMousePosition();
df.returnClick(p);
}
}
public boolean canClick() {
return canClick;
}
public void setCanClick(boolean canClick) {
this.canClick = canClick;
}
/**
* 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() {
_Panel_MainPanel = new javax.swing.JPanel();
setPreferredSize(new java.awt.Dimension(1000, 800));
_Panel_MainPanel.setBackground(new java.awt.Color(0, 0, 0));
_Panel_MainPanel.addMouseListener(new java.awt.event.MouseAdapter() {
public void mousePressed(java.awt.event.MouseEvent evt) {
_Panel_MainPanelMousePressed(evt);
}
});
javax.swing.GroupLayout _Panel_MainPanelLayout = new javax.swing.GroupLayout(_Panel_MainPanel);
_Panel_MainPanel.setLayout(_Panel_MainPanelLayout);
_Panel_MainPanelLayout.setHorizontalGroup(
_Panel_MainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 1000, Short.MAX_VALUE)
);
_Panel_MainPanelLayout.setVerticalGroup(
_Panel_MainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 800, Short.MAX_VALUE)
);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
this.setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(_Panel_MainPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(_Panel_MainPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);
}// </editor-fold>//GEN-END:initComponents
private void _Panel_MainPanelMousePressed(java.awt.event.MouseEvent evt) {//GEN-FIRST:event__Panel_MainPanelMousePressed
if (canClick) {
//System.out.println(this.rack.getName() + " click "+ evt.getPoint());
df.returnClick(evt.getPoint());
}
}//GEN-LAST:event__Panel_MainPanelMousePressed
/**
* updates the panel
*/
public void updateView() {
int gridXPos, gridYPos, gridWidth, gridHeight;
int maxGridWidth = 30;
JLabel label;
JPanel panel;
GridBagLayout gbl = new GridBagLayout();
_Panel_MainPanel.setLayout(gbl);
_Panel_MainPanel.removeAll();
// Store panel info at top
// Positioning & Constraints
gridXPos = 0;
gridYPos = 0;
gridWidth = maxGridWidth;
gridHeight = 5;
// End of Constraints
panel = panelTop(img, storeName);
//addPanel(newPanel, gridx, gridy, gridwidth, gridheight, weightx, weighty, fill, padx, pady
this.addPanel(panel, gridXPos, gridYPos, gridWidth, gridHeight, 1, 0, GridBagConstraints.BOTH, 0, 0);
// Pressure/temp
// Positioning & Constraints
gridXPos = 0;
gridYPos += gridHeight;
gridWidth = maxGridWidth;
gridHeight = 10;
// End of Constraints
panel = panelLiquidDischarge();
//addPanel(newPanel, gridx, gridy, gridwidth, gridheight, weightx, weighty, fill, padx, pady
this.addPanel(panel, gridXPos, gridYPos, gridWidth, gridHeight, 1, 0, GridBagConstraints.BOTH, 0, 0);
// Filler area
gridXPos = 0;
gridYPos += gridHeight;
gridHeight = 5;
gridWidth = maxGridWidth;
panel = new JPanel();
//panel.setPreferredSize(new Dimension(5, 100));
panel.setBackground(Color.black);
//addPanel(newPanel, gridx, gridy, gridwidth, gridheight, weightx, weighty, fill, padx, pady
this.addPanel(panel, gridXPos, gridYPos, gridWidth, gridHeight, 1, 0, GridBagConstraints.BOTH, 0, 20);
// Compressor status
// Positioning & Constraints
gridXPos = 0;
gridYPos += gridHeight;
gridHeight = 20;
// End of Constraints
panel = panelCompressor();
//addPanel(newPanel, gridx, gridy, gridwidth, gridheight, weightx, weighty, fill, padx, pady
this.addPanel(panel, gridXPos, gridYPos, gridWidth, gridHeight, 1, 1, GridBagConstraints.BOTH, 0, 0);
// Condenser
// Positioning & Constraints
gridXPos = 0;
gridYPos += gridHeight;
gridWidth = maxGridWidth;
gridHeight = 15;
// End of Constraints
panel = panelCondenser();
//addPanel(newPanel, gridx, gridy, gridwidth, gridheight, weightx, weighty, fill, padx, pady
this.addPanel(panel, gridXPos, gridYPos, gridWidth, gridHeight, 1, 0, GridBagConstraints.BOTH, 0, 0);
// Fan images - blanks
// Positioning & Constraints
gridXPos = 0;
gridYPos += gridHeight;;
// End of Constraints
// Filler area
gridXPos = 0;
gridYPos += gridHeight;
gridWidth = maxGridWidth;
gridHeight = 10;
// End of Constraints
panel = new JPanel();
panel.setBackground(Color.black);
//panel.setBorder(border);
//addPanel(newPanel, gridx, gridy, gridwidth, gridheight, weightx, weighty, fill, padx, pady
this.addPanel(panel, gridXPos, gridYPos, gridWidth, gridHeight, 1, 0, GridBagConstraints.BOTH, 0, 120);
// make labels white
setLabels(_Panel_MainPanel, Colours.White.getCol());
// do it before last panel
// Bottom Panel
// Constraints
gridXPos = 0;
gridYPos += gridHeight;
gridWidth = maxGridWidth;
gridHeight = 5; // 5 per row for performance
// End of Constraints
panel = panelBottom(this.numRacks);
//addPanel(newPanel, gridx, gridy, gridwidth, gridheight, weightx, weighty, fill, padx, pady
this.addPanel(panel, gridXPos, gridYPos, gridWidth, gridHeight, 1, 0, GridBagConstraints.BOTH, 0, 0);
_Panel_MainPanel.revalidate();
_Panel_MainPanel.repaint();
}
//addPanel(newPanel, gridx, gridy, gridwidth, gridheight, weightx, weighty, fill, padx, pady
/**
* adds a panel, with all the settings needed for the gridbagconstraint
* variable
*
* @param newPanel JPanel
* @param x gridx
* @param y gridy
* @param gwid gridwidth
* @param ghei gridheight
* @param wx weightx
* @param wy weighty
* @param fill fill
* @param padx ipadx
* @param pady ipady
*/
public void addPanel(JPanel newPanel, int x, int y, int gwid, int ghei, double wx, double wy, int fill, int padx, int pady) {
GridBagConstraints c = new GridBagConstraints();
c.gridx = x;
c.gridy = y;
c.gridwidth = gwid;
c.gridheight = ghei;
c.weightx = wx;
c.weighty = wy;
c.fill = fill;
c.ipadx = padx;
c.ipady = pady;
_Panel_MainPanel.add(newPanel, c);
}
/**
* sets the labels in the container to a colour
*
* @param p1 container
* @param c colour
*/
public void setLabels(Container p1, Color c) {
for (Component p : p1.getComponents()) {
if (p instanceof JLabel) {
((JLabel) p).setForeground(Color.white);
} else {
if (p instanceof JPanel) {
setLabels((Container) p, c);
}
}
}
}
/**
* creates a pressure temp panel
*
* @return JPanel
*/
public JPanel panelLiquidDischarge() {
JLabel label;
GridBagLayout gbl = new GridBagLayout();
GridBagConstraints c = new GridBagConstraints();
// Return a panel containing two labels
JPanel panel = new JPanel(gbl);
// RACK NAMES
// Liquid | Discharge |
// DLT | COP | Subcool | Pressure | Temp |
// Liquid (3 x 2) ipady = 10
label = new JLabel("Liquid");
label.setFont(font.deriveFont(Font.BOLD, 18));
label.setBorder(border);
label.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
c.fill = GridBagConstraints.BOTH;
c.gridx = 0;
c.gridy = 0;
c.weightx = 1;
c.weighty = 0;
c.gridwidth = 3;
c.gridheight = 2;
c.ipady = 25;
label.setOpaque(true);
label.setBackground(Colours.BlueDark.getCol());
panel.add(label, c);
// Discharge (2 x 2) ipady = 10
label = new JLabel("Discharge");
label.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
label.setFont(font.deriveFont(Font.BOLD, 18));
label.setBorder(border);
c.gridx = 3;
c.gridwidth = 2;
label.setOpaque(true);
label.setBackground(Colours.BlueDark.getCol());
panel.add(label, c);
// Down 2 rows
c.ipady = 10;
// DLT (1 x 2)
label = new JLabel("Condenser Outlet Temp");
label.setFont(font.deriveFont(Font.BOLD, 16));
label.setBorder(border);
label.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
c.gridx = 0;
c.gridy = 2;
c.gridwidth = 1;
label.setOpaque(true);
label.setBackground(Colours.BlueLight.getCol());
panel.add(label, c);
// COP (1 x 2)
label = new JLabel("Condenser Outlet Pressure");
label.setFont(font.deriveFont(Font.BOLD, 16));
label.setBorder(border);
label.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
c.gridx = 1;
label.setOpaque(true);
label.setBackground(Colours.BlueLight.getCol());
panel.add(label, c);
// Subcooling (1 x 2)
label = new JLabel("Subcool");
label.setFont(font.deriveFont(Font.BOLD, 16));
label.setBorder(border);
label.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
c.gridx = 2;
label.setOpaque(true);
label.setBackground(Colours.BlueLight.getCol());
panel.add(label, c);
// Pressure (1 x 2)
label = new JLabel("Pressure");
label.setFont(font.deriveFont(Font.BOLD, 16));
label.setBorder(border);
label.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
c.gridx = 3;
label.setOpaque(true);
label.setBackground(Colours.BlueLight.getCol());
panel.add(label, c);
// Temperature (1 x 2)
label = new JLabel("Temperature");
label.setFont(font.deriveFont(Font.BOLD, 16));
label.setBorder(border);
label.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
c.gridx = 4;
//c.ipady = 100;
label.setOpaque(true);
label.setBackground(Colours.BlueLight.getCol());
panel.add(label, c);
// down a row
// Liquid (1 x 1)
c.gridx = 0;
c.gridy = 4;
c.weightx = 1;
c.weighty = 0;
c.gridwidth = 1;
c.gridheight = 1;
c.ipady = 45;
// Blank fields
for (int j = 0; j < 5; j++) {
label = new JLabel("");
label.setFont(font);
label.setBorder(border);
label.setOpaque(true);
label.setBackground(Colours.BlueLightest.getCol());
panel.add(label, c);
c.gridx++;
}
panel.setBackground(Color.black);
return panel;
}
/**
* Creates a panel condenser panel
*
* @return JPanel
*/
public JPanel panelCondenser() {
// Condenser Panel will list the condensers
JLabel label;
GridBagLayout gbl = new GridBagLayout();
GridBagConstraints c = new GridBagConstraints();
// Return a panel containing condenser labels
JPanel panel = new JPanel(gbl);
// RACK CONDENSER
c.fill = GridBagConstraints.HORIZONTAL;
c.gridx = 0;
c.weightx = 0;
c.weighty = 1;
c.gridy = 0;
c.gridheight = 2;
c.gridwidth = 1;
label = new JLabel("Fans");
label.setHorizontalAlignment(JLabel.CENTER);
label.setFont(font.deriveFont(Font.BOLD, 18));
label.setOpaque(true);
label.setBackground(Colours.BlueDark.getCol());
label.setBorder(border);
panel.add(label, c);
int numCond = rack.getNumCondenserFans();
c.weightx = 1;
for (int i = 1; i <= numCond; i++) {
label = new JLabel("Fan " + i + " ");
label.setFont(font.deriveFont(Font.BOLD, 18));
label.setOpaque(true);
label.setBackground(Colours.BlueDark.getCol());
label.setBorder(border);
label.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
c.gridx = i;
panel.add(label, c);
}
c.weightx = 0;
c.gridheight = 1;
label = new JLabel("Fan Amps");
label.setHorizontalAlignment(JLabel.CENTER);
label.setFont(font.deriveFont(Font.BOLD, 16));
label.setOpaque(true);
label.setBackground(Colours.BlueLight.getCol());
label.setBorder(border);
c.gridy = 2;
c.gridx = 0;
c.ipady = 10;
panel.add(label, c);
label = new JLabel(" Fault Detect ");
label.setHorizontalAlignment(JLabel.CENTER);
label.setFont(font.deriveFont(Font.BOLD, 16));
label.setOpaque(true);
label.setBackground(Colours.BlueLightest.getCol());
label.setBorder(border);
c.gridy = 3;
c.gridx = 0;
panel.add(label, c);
c.gridy = 2;
c.fill = GridBagConstraints.BOTH;
c.weightx = 1;
for (int j = 0; j < 2; j++) {
for (int i = 1; i <= numCond; i++) {
label = new JLabel("");
c.gridx = i;
label.setOpaque(true);
label.setBackground(j == 0 ? Colours.BlueLight.getCol() : Colours.BlueLightest.getCol());
label.setBorder(border);
panel.add(label, c);
}
c.gridy = 3;
}
panel.setBackground(Color.black);
return panel;
}
/**
* Creates a panel compressor panel
*
* @return JPanel
*/
public JPanel panelCompressor() {
// Condenser Panel will list the condensers
GridBagLayout gbl = new GridBagLayout();
GridBagConstraints c = new GridBagConstraints();
JLabel label;
JPanel panel = new JPanel(gbl);
SuctionGroup sg;
// Calculate the number of compressors
int numSg = rack.getNumSuctionGroups();
int[] comp = new int[numSg];
int numComp = rack.getNumCompressors();
for (int i = 0; i < numSg; i++) {
comp[i] = rack.getSuctionGroupIndex(i).getNumCompressors();
}
// we saved the number of compressors for each suction group
// Now we assign x number of columns for each suction group, where each
// suction group number of compressors will be x
// RACK COMPRESSOR
c.gridy = 0;
c.weightx = 0;
c.weighty = 0;
c.ipady = 25;
c.gridheight = 2;
c.gridwidth = 2;
c.fill = GridBagConstraints.BOTH;
label = new JLabel("");
label.setOpaque(true);
label.setBorder(border);
label.setBackground(Colours.BlueDark.getCol());
label.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
panel.add(label, c);
// Suction groups
c.gridx = 2;
c.gridy = 0;
c.weightx = 1;
for (int i = 0; i < numSg; i++) {
// Suction group
c.gridheight = 2;
c.gridwidth = comp[i];
if (comp[i] == 1) {
c.ipadx = 75;
}
label = new JLabel(rack.getSuctionGroupNameIndex(i));
label.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
label.setFont(font.deriveFont(Font.BOLD, 18));
label.setOpaque(true);
label.setBackground(Colours.BlueDark.getCol());
label.setBorder(border);
panel.add(label, c);
c.ipadx = 0;
c.gridx += comp[i];
}
// Add the left side titles
// row 2
// SpSt / Temp
c.gridx = 0;
c.gridy = 2;
c.gridwidth = 2;
c.weightx = 0;
c.weighty = 0;
c.ipady = 10;
label = new JLabel("Pressure");
label.setHorizontalAlignment(JLabel.CENTER);
label.setFont(font.deriveFont(Font.BOLD, 16));
label.setOpaque(true);
label.setBorder(border);
label.setBackground(Colours.BlueLight.getCol());
panel.add(label, c);
// Add columns
c.gridx += 2;
c.gridwidth = 1;
c.weightx = 1;
for (int i = 0; i < numSg; i++) {
c.gridwidth = comp[i];
label = new JLabel("Setpoint");
label.setFont(font.deriveFont(Font.BOLD, 16));
label.setOpaque(true);
label.setBorder(border);
label.setBackground(Colours.BlueLight.getCol());
panel.add(label, c);
c.gridx += comp[i];
/*
gw1 = comp[i] - gw1;
c.gridwidth = gw1;
label = new JLabel("Actual");
label.setFont(font.deriveFont(Font.BOLD, 16));
label.setOpaque(true);
label.setBorder(border);
label.setBackground(Colours.BlueLight.getCol());
panel.add(label, c);
c.gridx += gw1;*/
}
// row 4
// SH Temp / Superheat
c.gridx = 0;
c.gridy = 4;
c.gridwidth = 2;
c.weightx = 0;
label = new JLabel("Temps");
label.setHorizontalAlignment(JLabel.CENTER);
label.setFont(font.deriveFont(Font.BOLD, 16));
label.setOpaque(true);
label.setBorder(border);
label.setBackground(Colours.BlueLightest.getCol());
panel.add(label, c);
// Add columns
c.gridx += 2;
c.gridwidth = 1;
c.weightx = 1;
for (int i = 0; i < numSg; i++) {
c.gridwidth = comp[i];
label = new JLabel("Header");
label.setFont(font.deriveFont(Font.BOLD, 16));
label.setOpaque(true);
label.setBorder(border);
label.setBackground(Colours.BlueLightest.getCol());
panel.add(label, c);
c.gridx += comp[i];
/*
gw1 = comp[i] - gw1;
c.gridwidth = gw1;
label = new JLabel("Superheat");
label.setFont(font.deriveFont(Font.BOLD, 16));
label.setOpaque(true);
label.setBorder(border);
label.setBackground(Colours.BlueLightest.getCol());
panel.add(label, c);
c.gridx += gw1;*/
}
// Row 6
c.weightx = 0;
c.gridy = 6;
c.gridx = 0;
c.gridwidth = 2;
c.ipady = 10;
label = new JLabel("Compressors");
label.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
label.setFont(font.deriveFont(Font.BOLD, 20));
label.setOpaque(true);
label.setBorder(border);
label.setBackground(Colours.BlueLight.getCol());
panel.add(label, c);
c.gridx += 2;
for (int i = 0; i < numSg; i++) {
// now each compressor
c.weightx = 1;
c.gridwidth = 1;
c.ipadx = 10;
for (int j = 0; j < comp[i]; j++) {
sg = rack.getSuctionGroupIndex(i);
if (sg.getNumCompressors() == 1) {
label = new JLabel(" " + sg.getCompressorNameIndex(j) + " ");
} else {
label = new JLabel(sg.getCompressorNameIndex(j));
}
label.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
label.setFont(font.deriveFont(Font.BOLD, 18));
label.setOpaque(true);
label.setBackground(Colours.BlueLight.getCol());
label.setBorder(border);
panel.add(label, c);
c.gridx += 1;
}
c.ipadx = 0;
}
// row 8
// Discharge temp
c.gridx = 0;
c.gridy = 8;
c.gridwidth = 2;
c.weightx = 0;
label = new JLabel("Discharge Temp");
label.setHorizontalAlignment(JLabel.CENTER);
label.setFont(font.deriveFont(Font.BOLD, 16));
label.setOpaque(true);
label.setBorder(border);
label.setBackground(Colours.BlueLightest.getCol());
panel.add(label, c);
// Add columns
c.gridx += 2;
c.gridwidth = 1;
c.weightx = 1;
for (int i = 0; i < numSg; i++) {
for (int j = 0; j < comp[i]; j++) {
label = new JLabel("");
label.setFont(font);
label.setOpaque(true);
label.setBorder(border);
label.setBackground(Colours.BlueLightest.getCol());
panel.add(label, c);
c.gridx += 1;
}
}
// row 10
// Amps
c.gridx = 0;
c.gridy = 10;
c.gridwidth = 2;
c.weightx = 0;
label = new JLabel("Amps");
label.setHorizontalAlignment(JLabel.CENTER);
label.setFont(font.deriveFont(Font.BOLD, 16));
label.setOpaque(true);
label.setBorder(border);
label.setBackground(Colours.BlueLight.getCol());
panel.add(label, c);
// Add columns
c.gridx += 2;
c.gridwidth = 1;
c.weightx = 1;
for (int i = 0; i < numSg; i++) {
for (int j = 0; j < comp[i]; j++) {
label = new JLabel("");
label.setFont(font);
label.setOpaque(true);
label.setBorder(border);
label.setBackground(Colours.BlueLight.getCol());
panel.add(label, c);
c.gridx += 1;
}
}
// compressor image
c.gridy = 11;
c.gridx = 2;
c.gridwidth = 1;
c.weightx = 1;
c.ipady = 35;
ImageIcon icon;
BufferedImage buff = null;
try {
if (numComp >= 10 && numComp <= 12) {
buff = ImageIO.read(this.getClass().getResourceAsStream("/Creator/pics/compSmaller3.png"));
icon = new ImageIcon(buff);
} else if (numComp > 12) {
buff = ImageIO.read(this.getClass().getResourceAsStream("/Creator/pics/compSmaller4.png"));
icon = new ImageIcon(buff);
} else {
buff = ImageIO.read(this.getClass().getResourceAsStream("/Creator/pics/compSmaller2.png"));
icon = new ImageIcon(buff);
}
for (int i = 0; i < numSg; i++) {
for (int j = 0; j < comp[i]; j++) {
label = new JLabel(icon, JLabel.CENTER);
label.setVerticalAlignment(JLabel.BOTTOM);
label.setOpaque(true);
//label.setBorder(border);
label.setBackground(Color.black);
panel.add(label, c);
c.gridx += 1;
}
}
} catch (IOException e) {
System.out.println("Didnt read the compressor images");
}
panel.setBackground(Color.black);
return panel;
}
/**
* Creates the bottom panel
*
* @param numRacks number of racks
* @return Jpanel
*/
public JPanel panelBottom(int numRacks) {
JButton button;
JLabel label;
GridBagLayout gbl = new GridBagLayout();
GridBagConstraints c = new GridBagConstraints();
JPanel panel = new JPanel();
panel.setLayout(gbl);
// Constraints
c.fill = GridBagConstraints.HORIZONTAL;
c.weightx = 1;
c.weighty = 0; // No space between bottom and below row?
c.gridx = 0;
c.gridy = 0;
c.gridwidth = 5;
c.gridheight = 2;
//c.ipady = 100;
//c.ipady = 0;
// End of Constraints
// Powered by label
label = new JLabel("Powered by N.O.E.L");
label.setForeground(Colours.White.getCol());
//label.setBorder(border);
label.setFont(font.deriveFont(Font.BOLD, 20));
label.setAlignmentX((Component.LEFT_ALIGNMENT));
label.setHorizontalAlignment(javax.swing.SwingConstants.LEADING);
panel.add(label, c);
// Constraints
//c.fill = GridBagConstraints.HORIZONTAL;
c.weightx = 0;
//c.weighty = 0; // No space between bottom and below row?
c.gridx = 5;
//c.gridy = 0;
c.gridwidth = 1;
//c.gridheight = 2;
//c.ipady = 100;
//c.ipady = 0;
// End of Constraints
// Buttons
// Main button
//button = new JButton("<html><font color = green>Main</font></html>");
button = new JButton("Main");
button.setFont(font.deriveFont(Font.BOLD, 20));
button.setAlignmentX((Component.CENTER_ALIGNMENT));
button.addMouseListener(new java.awt.event.MouseAdapter() {
public void mousePressed(java.awt.event.MouseEvent evt) {
buttonClick();
}
});
panel.add(button, c);
// Constraints
//c.fill = GridBagConstraints.HORIZONTAL;
//c.weightx = 0;
//c.weighty = 0; // No space between bottom and below row?
c.gridx = 6;
//c.gridy = 0;
//c.gridwidth = 1;
//c.gridheight = 2;
//c.ipady = 100;
//c.ipady = 0;
// End of Constraints
// Rack buttons
for (int i = 0; i < numRacks; i++) {
c.gridx += 1;
button = new JButton(rackNames[i]);
button.setFont(font.deriveFont(Font.BOLD, 20));
button.setAlignmentX((Component.CENTER_ALIGNMENT));
if (rackNum == i) {
button.setEnabled(false);
}
button.addMouseListener(new java.awt.event.MouseAdapter() {
public void mousePressed(java.awt.event.MouseEvent evt) {
buttonClick();
}
});
panel.add(button, c);
}
// Constraints
//c.fill = GridBagConstraints.HORIZONTAL;
//c.weightx = 0;
//c.weighty = 0; // No space between bottom and below row?
c.gridx += 1;
//c.gridy = 0;
//c.gridwidth = 1;
//c.gridheight = 2;
//c.ipady = 100;
//c.ipady = 0;
// End of Constraints
// Load Button
button = new JButton("Loads");
button.setFont(font.deriveFont(Font.BOLD, 20));
button.setAlignmentX((Component.CENTER_ALIGNMENT));
button.addMouseListener(new java.awt.event.MouseAdapter() {
public void mousePressed(java.awt.event.MouseEvent evt) {
buttonClick();
}
});
panel.add(button, c);
// Financial Button
c.gridx += 1;
button = new JButton("Financial");
button.setFont(font.deriveFont(Font.BOLD, 20));
button.setAlignmentX((Component.CENTER_ALIGNMENT));
button.addMouseListener(new java.awt.event.MouseAdapter() {
public void mousePressed(java.awt.event.MouseEvent evt) {
buttonClick();
}
});
panel.add(button, c);
// Constraints
//c.fill = GridBagConstraints.HORIZONTAL;
c.weightx = 1;
//c.weighty = 0; // No space between bottom and below row?
c.gridx += 1;
//c.gridy = 0;
c.gridwidth = 5;
//c.gridheight = 2;
//c.ipady = 100;
//c.ipady = 0;
// End of Constraints
// Map Label
label = new JLabel("Map");
label.setFont(font.deriveFont(Font.BOLD, 20));
label.setAlignmentX((Component.RIGHT_ALIGNMENT));
label.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
panel.add(label, c);
panel.setBackground(Colours.Gray.getCol());
panel.setBorder(border);
return panel;
}
/**
* Creates the top panel
*
* @param imgUrl String of img file location
* @param storeName String of store name
* @return Jpanel
*/
public JPanel panelTop(String imgUrl, String storeName) {
JLabel label;
GridBagLayout gbl = new GridBagLayout();
GridBagConstraints c = new GridBagConstraints();
JPanel panel = new JPanel();
panel.setLayout(gbl);
// Constraints
c.fill = GridBagConstraints.HORIZONTAL;
c.weightx = 0;
c.weighty = 0; // No space between bottom and below row?
c.gridx = 0;
c.gridy = 1;
c.gridwidth = 10;
c.gridheight = 2;
//c.ipady = 100;
//c.ipady = 0;
// End of Constraints
// store logo
label = new JLabel();
if (!"".equals(imgUrl)) {
ImageIcon icon = new ImageIcon(imgUrl);
label.setIcon(icon);
} else {
label.setText("NO LOGO SELECTED");
}
//label.setBorder(border);
label.setAlignmentX((Component.LEFT_ALIGNMENT));
label.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
panel.add(label, c);
// Constraints
//c.fill = GridBagConstraints.HORIZONTAL;
c.weightx = 1;
//c.weighty = 0; // No space between bottom and below row?
c.gridx = 10;
//c.gridy = 0;
c.gridwidth = 20;
//c.gridheight = 2;
//c.ipady = 100;
//c.ipady = 0;
// End of Constraints
// Store
label = new JLabel("");
//label.setBorder(border);
label.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
panel.add(label, c);
// Constraints
//c.fill = GridBagConstraints.HORIZONTAL;
c.weightx = 0;
//c.weighty = 0; // No space between bottom and below row?
c.gridx = 30;
//c.gridy = 1;
c.gridwidth = 10;
//c.gridheight = 2;
//c.ipady = 100;
//c.ipady = 0;
// End of Constraints
// Store
label = new JLabel(rack.getName() + " " + storeName);
label.setOpaque(true);
label.setBackground(Color.BLACK);
label.setFont(font.deriveFont(Font.BOLD, 22));
label.setAlignmentX((Component.RIGHT_ALIGNMENT));
label.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
label.setBorder(BorderFactory.createRaisedBevelBorder());
panel.add(label, c);
panel.setBackground(Colours.Gray.getCol());
panel.setBorder(border);
return panel;
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JPanel _Panel_MainPanel;
// End of variables declaration//GEN-END:variables
} |
package org.waterforpeople.mapping.dataexport;
import java.io.File;
import java.io.PrintWriter;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import org.waterforpeople.mapping.app.gwt.client.surveyinstance.SurveyInstanceDto;
import org.waterforpeople.mapping.dataexport.service.BulkDataServiceClient;
import com.gallatinsystems.framework.dataexport.applet.AbstractDataExporter;
/**
* exports raw data based on a date
*
* @author Christopher Fagiani
*
*/
public class RawDataExporter extends AbstractDataExporter {
private static final String IMAGE_PREFIX = "http://waterforpeople.s3.amazonaws.com/images/";
private static final String SDCARD_PREFIX = "/sdcard/";
private String serverBase;
private String surveyId;
public static final String SURVEY_ID = "surveyId";
private Map<String, String> questionMap;
private List<String> keyList;
@Override
@SuppressWarnings("unchecked")
public void export(Map<String, String> criteria, File fileName,
String serverBase) {
this.serverBase = serverBase;
surveyId = criteria.get(SURVEY_ID);
PrintWriter pw = null;
try {
Object[] results = BulkDataServiceClient.loadQuestions(surveyId,
serverBase);
if (results != null) {
keyList = (List<String>) results[0];
questionMap = (Map<String, String>) results[1];
pw = new PrintWriter(fileName);
writeHeader(pw, questionMap);
exportInstances(pw, keyList);
} else {
System.out.println("Error getting questions");
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (pw != null) {
pw.close();
}
}
}
@SuppressWarnings("unchecked")
public void export(String serverBase, Long surveyIdentifier, PrintWriter pw) {
try {
this.surveyId = surveyIdentifier.toString();
this.serverBase = serverBase;
Object[] results = BulkDataServiceClient.loadQuestions(surveyId,
serverBase);
if (results != null) {
keyList = (List<String>) results[0];
questionMap = (Map<String, String>) results[1];
writeHeader(pw, questionMap);
exportInstances(pw, keyList);
} else {
System.out.println("Error getting questions");
}
} catch (Exception e) {
e.printStackTrace();
}
}
private void writeHeader(PrintWriter pw, Map<String, String> questions) {
pw.print("Instance\tSubmission Date\tSubmitter");
if (keyList != null) {
for (String key : keyList) {
pw.print("\t");
pw.write(key + "|" + questions.get(key).replace("\n", " "));
}
}
pw.print("\n");
}
private void exportInstances(PrintWriter pw, List<String> idList)
throws Exception {
Map<String, String> instances = BulkDataServiceClient.fetchInstanceIds(
surveyId, serverBase);
if (instances != null) {
int i = 0;
for (Entry<String, String> instanceEntry : instances.entrySet()) {
String instanceId = instanceEntry.getKey();
String dateString = instanceEntry.getValue();
if (instanceId != null && instanceId.trim().length() > 0) {
try {
Map<String, String> responses = BulkDataServiceClient
.fetchQuestionResponses(instanceId, serverBase);
if (responses != null) {
pw.print(instanceId);
pw.print("\t");
pw.print(dateString);
pw.print("\t");
SurveyInstanceDto dto = BulkDataServiceClient
.findSurveyInstance(
Long.parseLong(instanceId.trim()),
serverBase);
if (dto != null) {
String name = dto.getSubmitterName();
if (name != null) {
pw.print(dto.getSubmitterName()
.replaceAll("\n", " ").trim());
}
}
for (String key : idList) {
String val = responses.get(key);
pw.print("\t");
if (val != null) {
if (val.contains(SDCARD_PREFIX)) {
val = IMAGE_PREFIX
+ val.substring(val
.indexOf(SDCARD_PREFIX)
+ SDCARD_PREFIX
.length());
}
val = val.replaceAll(",", " ");
pw.print(val.replaceAll("\n", " ").trim());
}
}
pw.print("\n");
i++;
System.out.println("Row: " + i);
}
} catch (Exception ex) {
System.out.println("Swallow the exception for now and continue");
}
}
}
}
}
} |
package com.juliomarcos;
import android.app.Activity;
import android.app.Dialog;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.Canvas;
import android.graphics.Point;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.view.Display;
import android.view.View;
import android.view.Window;
import android.widget.ImageView;
public class ImageViewPopUpHelper {
private Activity context;
private Drawable imageViewDrawable;
private int finalImageWidth;
private int finalImageHeight;
private boolean requireResizingOfBitmap;
private ImageView poppedImageView;
private Dialog dialog;
@SuppressWarnings("deprecation")
private void cacheResizedDrawable(Drawable drawable, boolean shouldScaleDown, boolean shouldScaleUp) {
imageViewDrawable = drawable;
int imageRealWidth = imageViewDrawable.getIntrinsicWidth();
int imageRealHeight = imageViewDrawable.getIntrinsicHeight();
Point screenDimensions = getScreenDimensions(context);
final int screenWidth = screenDimensions.x;
final int screenHeight = screenDimensions.y;
// Algoritmo iterativo para achar um tamanho final para a imagem
while(shouldScaleDown && (imageRealWidth >= screenWidth || imageRealHeight >= screenHeight)) {
imageRealWidth *= 0.9;
imageRealHeight *= 0.9;
requireResizingOfBitmap = true;
}
while(shouldScaleUp && ((imageRealWidth * 1.1) <= screenWidth && (imageRealHeight * 1.1) <= screenHeight)) {
imageRealWidth *= 1.1;
imageRealHeight *= 1.1;
requireResizingOfBitmap = true;
}
finalImageWidth = imageRealWidth;
finalImageHeight = imageRealHeight;
if (requireResizingOfBitmap) {
Bitmap bitmap = drawableToBitmap(imageViewDrawable);
BitmapDrawable resizedBitmapDrawable = new BitmapDrawable(
context.getResources(),
Bitmap.createScaledBitmap(bitmap, finalImageWidth, finalImageHeight, false));
poppedImageView.setBackgroundDrawable(resizedBitmapDrawable);
}
else {
poppedImageView.setBackgroundDrawable(imageViewDrawable);
}
}
/**
* Enable tap to show popup image dialog with alternative drawable than imageView's drawable
* @param context Context
* @param imageView Target Image View
* @param drawable Alternative Drawable
*/
public static void enablePopUpOnClick(final Activity context, final ImageView imageView, final Drawable drawable) {
new ImageViewPopUpHelper().internalEnablePopUpOnClick(context, imageView, drawable);
}
public static void enablePopUpOnClick(final Activity context, final ImageView imageView) {
new ImageViewPopUpHelper().internalEnablePopUpOnClick(context, imageView);
}
private void internalEnablePopUpOnClick(final Activity context, final ImageView imageView, final Drawable drawable) {
this.context = context;
poppedImageView = new ImageView(context);
dialog = new Dialog(context);
dialog.requestWindowFeature((int) Window.FEATURE_NO_TITLE);
dialog.setContentView(poppedImageView);
dialog.getWindow().setBackgroundDrawable(null); // Without this line there is a very small border around the image (1px)
dialog.setCanceledOnTouchOutside(true); // Gingerbread support
imageView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (drawable != null) {
if (imageViewDrawable != drawable) {
cacheResizedDrawable(drawable, true, true);
}
}
else {
ImageView imageView = (ImageView) v;
if (imageViewDrawable != imageView.getDrawable()) {
cacheResizedDrawable(imageView.getDrawable(), true, true);
}
}
dialog.show();
}
});
}
private void internalEnablePopUpOnClick(final Activity context, final ImageView imageView) {
internalEnablePopUpOnClick(context, imageView, null);
}
@SuppressWarnings("deprecation")
private Point getScreenDimensions(Activity context) {
// Get screen size
Display display = context.getWindowManager().getDefaultDisplay();
Point size = new Point();
int currentapiVersion = android.os.Build.VERSION.SDK_INT;
if (currentapiVersion >= android.os.Build.VERSION_CODES.JELLY_BEAN_MR1){
display.getRealSize(size);
}
else if (currentapiVersion >= android.os.Build.VERSION_CODES.HONEYCOMB_MR2){
display.getSize(size);
} else{
size.x = display.getWidth();
size.y = display.getHeight();
}
return size;
}
private Bitmap drawableToBitmap (Drawable drawable) {
if (drawable instanceof BitmapDrawable) {
return ((BitmapDrawable)drawable).getBitmap();
}
Bitmap bitmap = Bitmap.createBitmap(drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight(), Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
drawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());
drawable.draw(canvas);
return bitmap;
}
} |
package nl.ncim.javaone.tsp.ea;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Random;
import nl.ncim.javaone.tsp.gui.JavaOneTSPDemo;
import nl.ncim.javaone.tsp.util.TSPUtils;
public class Algorithm
{
/**
* Our connection to the demo (view)
*/
private JavaOneTSPDemo view;
/**
* Population of the algorithm
*/
private List<CandidateSolution> population = new ArrayList<CandidateSolution>();
/**
* Thread in which the algorithm runs
*/
private Thread algorithmThread;
/**
* Probability with which a new child mutates
*/
private int mutationProbability;
/**
* Size of the population (as given by the GUI)
*/
private int populationSize;
/**
* number of generations to run max.
*/
private int nrOfGenerations;
/**
* When this fitness threshold is reached the algorithm can be stopped
*/
private int fitnessThreshold;
/**
* Number of parents to be selected for reproduction (each generation)
*/
private int parentSelectionSize;
/**
* Pool of CandidateSolution from which a number of parents will be selected for reproduction (each generation)
*/
private int parentPoolSize;
/**
* Constructor for the Evolutionary Algorithm
*
* @param view
* @param mutationProbability
* @param populationSize
* @param nrOfGenerations
* @param fitnessThreshold
* @param parentSelectionSize
* @param parentPoolSize
*/
public Algorithm(JavaOneTSPDemo view, int mutationProbability, int populationSize, int nrOfGenerations,
int fitnessThreshold, int parentSelectionSize, int parentPoolSize)
{
this.view = view;
this.mutationProbability = mutationProbability;
this.populationSize = populationSize;
this.nrOfGenerations = nrOfGenerations;
this.fitnessThreshold = fitnessThreshold;
this.parentSelectionSize = parentSelectionSize;
this.parentPoolSize = parentPoolSize;
}
/**
* Starts the algorithm using the settings given through the
* constructor.
*/
public void startAlgorithm()
{
/* let the algorithm run in a Thread */
algorithmThread = new Thread(new Runnable() {
public void run()
{
population = initialisation();
/*
* implemented a Comparable for CandidateSolution
* using its fitness. So best fitness (lowest)
* first.
*/
Collections.sort(population);
CandidateSolution bestCandidateSolution = population.get(0);
int generations = 0;
/* show the current best candidate solution on the demo screen */
view.showLastGeneration(bestCandidateSolution, generations);
/* start the iterative part of the algorithm */
while(generations != nrOfGenerations && population.get(0).getFitness() > fitnessThreshold)
{
/* Select the parents for reproduction */
List<CandidateSolution> parents = parentSelection();
/* Let the selected parents reproduce (recombine) */
for(int i = 0; i < parents.size(); i += 2)
{
CandidateSolution parent1 = parents.get(i);
CandidateSolution parent2 = parents.get(i + 1);
List<CandidateSolution> children = parent1.recombine(parent2);
/*
* let the children mutate with probability mutationProbability
* and add them to the population
*/
for(CandidateSolution child : children)
{
/* probability to mutate */
if(new Random().nextInt(101) <= mutationProbability)
{
child.mutate();
}
population.add(child);
}
}
/*
* Since evaluation of candidate solutions is done within
* the CandidateSolution itself, there is no need to evaluate
* seperately here (although that is a part of the Evolutionary
* Algorithm)
*/
/*
* Survivor selection: which individuals (CandidateSolutions)
* progress to the next generation
*/
selectSurvivors();
/* Sort the population so that the best candidates are up front */
Collections.sort(population);
generations++;
view.showLastGeneration(population.get(0), generations);
/*
* Sleep, so the Thread can be interrupted if needed
* and to make the progression of the algorithm easy
* on the eyes on the demo screen
*/
try
{
Thread.sleep(1);
}
catch(InterruptedException e)
{
view.reset();
return;
}
}
/* we're done here */
view.done();
}
});
/* start the above defined algorithm */
algorithmThread.start();
}
/**
* Selects the survivors by removing the worst candidate
* solutions from the list, so we have the original
* population size again
*/
private void selectSurvivors()
{
/* Sort the population so that the best candidates are up front */
Collections.sort(population);
/*
* cut back the population to the original size by dropping the worst
* candidates
*/
population = new ArrayList<CandidateSolution>(population.subList(0, populationSize));
}
/**
* Select the x best candidate solutions from a randomly selected
* pool from the population
*
* @return parents a list of the chosen parents
*/
private List<CandidateSolution> parentSelection()
{
List<CandidateSolution> tempPopulation = new ArrayList<CandidateSolution>(population);
List<CandidateSolution> randomCandidates = new ArrayList<CandidateSolution>();
Random random = new Random();
/* create parent pool */
for(int i = 0; i < parentPoolSize; i++)
{
/* select a random candidate solution from the temp population */
int randomlySelectedIndex = random.nextInt(tempPopulation.size());
CandidateSolution randomSelection = tempPopulation.get(randomlySelectedIndex);
randomCandidates.add(randomSelection);
/* delete the candidate from the temp population, so we can't pick it again */
tempPopulation.remove(randomlySelectedIndex);
}
/* Sort the population so that the best candidates are up front */
Collections.sort(randomCandidates);
/*
* return a list with size parentSelectionSize with the best
* CandidateSolutions
*/
return randomCandidates.subList(0, parentSelectionSize);
}
private List<CandidateSolution> initialisation()
{
/* initialize population list of CandidateSolutions */
List<CandidateSolution> populationTemp = new ArrayList<CandidateSolution>();
/* create a populationSize amount of random CandidateSolutions (routes) */
for(int i = 0; i < populationSize; i++)
{
CandidateSolution candidateSolution = new CandidateSolution(TSPUtils.getBaseCity(),
TSPUtils.getRandomizedCities());
populationTemp.add(candidateSolution);
}
return populationTemp;
}
private void printPopulation()
{
/*
* for (CandidateSolution candidateSolution : population) {
*
* System.out.println("CandidateSolution added to population: " +
* candidateSolution.toString()); }
*
* System.out.println("Population size: " + population.size());
*/
}
/**
* Stops the algorithm
*/
public void stopAlgorithm()
{
algorithmThread.interrupt();
}
} |
package com.kylewbanks.activity;
import android.app.ActionBar;
import android.app.Activity;
import android.content.Intent;
import android.content.res.AssetManager;
import android.os.Bundle;
import android.util.Log;
import android.view.MenuItem;
import android.webkit.ConsoleMessage;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import com.kylewbanks.KWBApplication;
import com.kylewbanks.R;
import com.kylewbanks.model.Post;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.Scanner;
public class PostActivity extends Activity {
private static final String TAG = "PostActivity";
private Post post;
private WebView contentView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.post_view);
//Determine which post we are showing
KWBApplication application = (KWBApplication) getApplication();
Intent intent = getIntent();
post = application.getPostById(intent.getLongExtra("postId", -1));
//Customize the action bar
ActionBar actionBar = getActionBar();
if(actionBar != null) {
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setDisplayShowHomeEnabled(false);
actionBar.setDisplayShowTitleEnabled(true);
actionBar.setTitle(post.getTitle());
actionBar.setDisplayUseLogoEnabled(false);
}
//Get references to needed UI components
contentView = (WebView) findViewById(R.id.post_content);
}
@Override
protected void onStart() {
super.onStart();
//Enable JavaScript and set the content of the WebView
WebSettings settings = contentView.getSettings();
settings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NORMAL);
settings.setJavaScriptEnabled(true);
contentView.loadData(getTemplateContent().replace("{{CONTENT}}", post.getURLEncodedBody()), "text/html", "UTF-8");
}
/**
* Called when the physical 'Back Button' is pressed. Overridden to implement custom animation.
*/
@Override
public void onBackPressed() {
super.onBackPressed();
overridePendingTransition(R.anim.left_to_right, R.anim.right_to_left);
}
/**
* Called when the navigation 'Back Button' is pressed (header bar). Overridden to implement custom animation.
* @param item
* @return
*/
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
finish();
overridePendingTransition(R.anim.left_to_right, R.anim.right_to_left);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
/**
* Reads in the contents of post_content.html and returns it as a String
* @return
*/
private String getTemplateContent() {
AssetManager assetManager = getAssets();
try {
InputStream contentStream = assetManager.open("post_content.html");
Scanner scanner = new Scanner(contentStream).useDelimiter("\\A");
if(scanner.hasNext()) {
return scanner.next();
}
} catch (IOException ex) {
Log.i(TAG, "Failed to get Template content due to: " + ex);
}
return null;
}
} |
package Vista;
import java.awt.event.ActionListener;
/**
*
* @author alexis
*/
public class IRecorrerTour extends javax.swing.JFrame {
/**
* Creates new form IRecorrerTour
*/
public IRecorrerTour() {
initComponents();
}
/**
* 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() {
jLabel1 = new javax.swing.JLabel();
jTextField1 = new javax.swing.JTextField();
jLabel2 = new javax.swing.JLabel();
jTextField2 = new javax.swing.JTextField();
jLabel3 = new javax.swing.JLabel();
jLabel4 = new javax.swing.JLabel();
jScrollPane1 = new javax.swing.JScrollPane();
jTextArea1 = new javax.swing.JTextArea();
boton_finalizar = new javax.swing.JButton();
boton_continuar = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jLabel1.setText("Tour Virtual");
jTextField1.setEditable(false);
jTextField1.setText("Nombre Tour");
jTextField1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jTextField1ActionPerformed(evt);
}
});
jLabel2.setText("Punto de Interes Actual");
jTextField2.setEditable(false);
jTextField2.setText("Nombre Punto de Interes");
jLabel3.setBackground(new java.awt.Color(255, 255, 255));
jLabel3.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));
jLabel4.setText("Descripcion");
jTextArea1.setColumns(20);
jTextArea1.setRows(5);
jScrollPane1.setViewportView(jTextArea1);
boton_finalizar.setText("Finalizar");
boton_finalizar.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
boton_finalizarActionPerformed(evt);
}
});
boton_continuar.setText("Continuar");
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(46, 46, 46)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jLabel3, javax.swing.GroupLayout.DEFAULT_SIZE, 504, Short.MAX_VALUE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jLabel4)
.addGroup(layout.createSequentialGroup()
.addComponent(boton_finalizar)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(boton_continuar))
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel1)
.addComponent(jLabel2))
.addGap(23, 23, 23)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jTextField1)
.addComponent(jTextField2, javax.swing.GroupLayout.DEFAULT_SIZE, 335, Short.MAX_VALUE)))
.addComponent(jScrollPane1)))
.addContainerGap(51, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(25, 25, 25)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(jLabel1)
.addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, 26, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel2)
.addComponent(jTextField2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addComponent(jLabel3, javax.swing.GroupLayout.PREFERRED_SIZE, 327, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(jLabel4)
.addGap(18, 18, 18)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 150, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 70, Short.MAX_VALUE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(boton_finalizar)
.addComponent(boton_continuar))
.addGap(28, 28, 28))
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void jTextField1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jTextField1ActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_jTextField1ActionPerformed
private void boton_finalizarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_boton_finalizarActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_boton_finalizarActionPerformed
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(IRecorrerTour.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(IRecorrerTour.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(IRecorrerTour.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(IRecorrerTour.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new IRecorrerTour().setVisible(true);
}
});
}
public void addBotonFinalizarListener(ActionListener listenForBotonFinalizar) {
boton_finalizar.addActionListener(listenForBotonFinalizar);
}
public void addBotonContinuarListener(ActionListener listenForBotonContinuar) {
boton_continuar.addActionListener(listenForBotonContinuar);
}
public void mostrarNombre (String nombreCJ) {
jTextField2.setText(nombreCJ);
}
public void mostrarNombreTourActual (String IDCJ){
jTextField1.setText(IDCJ);
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton boton_continuar;
private javax.swing.JButton boton_finalizar;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel4;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JTextArea jTextArea1;
private javax.swing.JTextField jTextField1;
private javax.swing.JTextField jTextField2;
// End of variables declaration//GEN-END:variables
} |
package ab.demo;
import ab.demo.logging.LoggingHandler;
import ab.demo.other.ActionRobot;
import ab.demo.other.Shot;
import ab.demo.qlearning.ProblemState;
import ab.demo.qlearning.QValuesDAO;
import ab.demo.qlearning.StateObject;
import ab.planner.TrajectoryPlanner;
import ab.server.Proxy;
import ab.utils.StateUtil;
import ab.vision.ABObject;
import ab.vision.GameStateExtractor;
import ab.vision.Vision;
import org.apache.log4j.Logger;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.util.*;
import java.util.List;
/**
* @author jgonsior
*/
public class ReinforcementLearningAgentStandalone implements Runnable, Agent {
private static Logger logger = Logger.getLogger(ReinforcementLearningAgentStandalone.class);
public int currentLevel = 1;
private TrajectoryPlanner trajectoryPlanner;
//Wrapper of the communicating messages
private ActionRobot actionRobot;
private double discountFactor = 0.9;
private double learningRate = 0.1;
private double explorationRate = 0.7;
private boolean firstShot;
private Random randomGenerator;
private QValuesDAO qValuesDAO;
// id which will be generated randomly every lvl that we can connect moves to one game
private int gameId;
private int moveCounter;
private boolean lowTrajectory = false;
private Map<Integer, Integer> scores = new LinkedHashMap<Integer, Integer>();
// a standalone implementation of the Reinforcement Agent
public ReinforcementLearningAgentStandalone(QValuesDAO qValuesDAO) {
LoggingHandler.initFileLog();
LoggingHandler.initConsoleLog();
this.actionRobot = new ActionRobot();
this.trajectoryPlanner = new TrajectoryPlanner();
this.randomGenerator = new Random();
this.firstShot = true;
this.qValuesDAO = qValuesDAO;
ActionRobot.GoFromMainMenuToLevelSelection();
}
// run the client
public void run() {
actionRobot.loadLevel(currentLevel);
gameId = qValuesDAO.saveGame(currentLevel, Proxy.getProxyPort(), explorationRate, learningRate, discountFactor);
while (true) {
GameStateExtractor.GameState state = solve();
moveCounter = moveCounter + 1;
if (state == GameStateExtractor.GameState.WON) {
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
int score = StateUtil.getScore(ActionRobot.proxy);
if (!scores.containsKey(currentLevel))
scores.put(currentLevel, score);
else {
if (scores.get(currentLevel) < score)
scores.put(currentLevel, score);
}
int totalScore = 0;
for (Integer key : scores.keySet()) {
totalScore += scores.get(key);
logger.info(" Level " + key
+ " Score: " + scores.get(key) + " ");
}
logger.info("Total Score: " + totalScore);
actionRobot.loadLevel(++currentLevel);
// make a new trajectory planner whenever a new level is entered
trajectoryPlanner = new TrajectoryPlanner();
// first shot on this level, try high shot first
firstShot = true;
gameId = qValuesDAO.saveGame(currentLevel, Proxy.getProxyPort(), explorationRate, learningRate, discountFactor);
moveCounter = 0;
} else if (state == GameStateExtractor.GameState.LOST) {
logger.info("Restart");
actionRobot.restartLevel();
gameId = qValuesDAO.saveGame(currentLevel, Proxy.getProxyPort(), explorationRate, learningRate, discountFactor);
moveCounter = 0;
} else if (state == GameStateExtractor.GameState.LEVEL_SELECTION) {
logger.warn("Unexpected level selection page, go to the last current level : "
+ currentLevel);
actionRobot.loadLevel(currentLevel);
} else if (state == GameStateExtractor.GameState.MAIN_MENU) {
logger.warn("Unexpected main menu page, go to the last current level : "
+ currentLevel);
ActionRobot.GoFromMainMenuToLevelSelection();
actionRobot.loadLevel(currentLevel);
} else if (state == GameStateExtractor.GameState.EPISODE_MENU) {
logger.warn("Unexpected episode menu page, go to the last current level : "
+ currentLevel);
ActionRobot.GoFromMainMenuToLevelSelection();
actionRobot.loadLevel(currentLevel);
}
}
}
public GameStateExtractor.GameState solve() {
// capture Image
BufferedImage screenshot = ActionRobot.doScreenShot();
// process image
Vision vision = new Vision(screenshot);
// find the slingshot
Rectangle sling = vision.findSlingshotMBR();
// confirm the slingshot
while (sling == null && actionRobot.getState() == GameStateExtractor.GameState.PLAYING) {
logger.warn("No slingshot detected. Please remove pop up or zoom out");
ActionRobot.fullyZoomOut();
screenshot = ActionRobot.doScreenShot();
vision = new Vision(screenshot);
sling = vision.findSlingshotMBR();
ActionRobot.skipPopUp();
}
// get all the pigs
java.util.List<ABObject> pigs = vision.findPigsMBR();
int birdsLeft = vision.findBirdsMBR().size();
GameStateExtractor.GameState state = actionRobot.getState();
if (state != GameStateExtractor.GameState.PLAYING) {
logger.warn("Accidentally in solving method without being in PLAYINg state");
return state;
}
// if there is a sling, then play, otherwise just skip.
if (sling != null) {
if (!pigs.isEmpty()) {
Point releasePoint = null;
Shot shot = new Shot();
int dx, dy;
ProblemState currentState = new ProblemState(vision);
int stateId = getStateId(currentState);
// get Next best Action
ActionPair nextActionPair = getNextAction(stateId);
int nextAction = nextActionPair.value;
java.util.List<ABObject> shootables = currentState.getShootableObjects();
if (shootables.size() - 1 > nextAction) {
nextAction = shootables.size() - 1;
}
ABObject obj = shootables.get(nextAction);
Point _tpt = obj.getCenter();
// estimate the trajectory
ArrayList<Point> pts = trajectoryPlanner.estimateLaunchPoint(sling, _tpt);
// do a high shot when entering a level to find an accurate velocity
if (firstShot && pts.size() > 1) {
lowTrajectory = false;
releasePoint = pts.get(1);
} else if (pts.size() == 1) {
// TODO: find out if low or high trajectory????
releasePoint = pts.get(0);
} else if (pts.size() == 2) {
// randomly choose between the trajectories, with a 1 in
// 6 chance of choosing the high one
if (randomGenerator.nextInt(6) == 0) {
lowTrajectory = false;
releasePoint = pts.get(1);
} else {
lowTrajectory = true;
releasePoint = pts.get(0);
}
} else if (pts.isEmpty()) {
logger.info("No release point found for the target");
logger.info("Try a shot with 45 degree");
releasePoint = trajectoryPlanner.findReleasePoint(sling, Math.PI / 4);
}
// Get the reference point
Point refPoint = trajectoryPlanner.getReferencePoint(sling);
//Calculate the tapping time according the bird type
if (releasePoint != null) {
double releaseAngle = trajectoryPlanner.getReleaseAngle(sling,
releasePoint);
logger.info("Release Point: " + releasePoint);
logger.info("Release Angle: "
+ Math.toDegrees(releaseAngle));
int tapInterval = 0;
switch (actionRobot.getBirdTypeOnSling()) {
case RedBird:
tapInterval = 0;
break; // start of trajectory
case YellowBird:
tapInterval = 65 + randomGenerator.nextInt(25);
break; // 65-90% of the way
case WhiteBird:
tapInterval = 70 + randomGenerator.nextInt(20);
break; // 70-90% of the way
case BlackBird:
tapInterval = 70 + randomGenerator.nextInt(20);
break; // 70-90% of the way
case BlueBird:
tapInterval = 65 + randomGenerator.nextInt(20);
break; // 65-85% of the way
default:
tapInterval = 60;
}
int tapTime = trajectoryPlanner.getTapTime(sling, releasePoint, _tpt, tapInterval);
dx = (int) releasePoint.getX() - refPoint.x;
dy = (int) releasePoint.getY() - refPoint.y;
shot = new Shot(refPoint.x, refPoint.y, dx, dy, 0, tapTime);
} else {
logger.error("No Release Point Found");
return state;
}
// check whether the slingshot is changed. the change of the slingshot indicates a change in the scale.
ActionRobot.fullyZoomOut();
BufferedImage screenshotBefore = ActionRobot.doScreenShot();
Vision visionBefore = new Vision(screenshotBefore);
List<ABObject> bnbBefore = getBlocksAndBirds(visionBefore);
Rectangle _sling = visionBefore.findSlingshotMBR();
if (_sling != null) {
double scale_diff = Math.pow((sling.width - _sling.width), 2) + Math.pow((sling.height - _sling.height), 2);
if (scale_diff < 25) {
if (dx < 0) {
actionRobot.cshoot(shot);
// make screenshots as long as 2 following screenshots are equal
while (actionRobot.getState() == GameStateExtractor.GameState.PLAYING) {
try {
Thread.sleep(500);
screenshot = ActionRobot.doScreenShot();
vision = new Vision(screenshot);
List<ABObject> bnbAfter = getBlocksAndBirds(vision);
logger.info("bnbBefore: " + bnbBefore);
logger.info("bnbAfter: " + bnbAfter);
if (bnbBefore.equals(bnbAfter)) {
break;
} else {
bnbBefore = bnbAfter;
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
if (vision.findBirdsMBR().size() == 0 || vision.findPigsMBR().size() == 0) {
// if we have no pigs left or birds, wait for winning screen
while (actionRobot.getState() == GameStateExtractor.GameState.PLAYING) {
try {
Thread.sleep(1500);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
state = actionRobot.getState();
double reward = getReward(state);
if (state == GameStateExtractor.GameState.PLAYING) {
screenshot = ActionRobot.doScreenShot();
vision = new Vision(screenshot);
java.util.List<Point> traj = vision.findTrajPoints();
trajectoryPlanner.adjustTrajectory(traj, sling, releasePoint);
firstShot = false;
updateQValue(stateId, nextActionPair, new ProblemState(vision), reward, false);
} else if (state == GameStateExtractor.GameState.WON || state == GameStateExtractor.GameState.LOST) {
updateQValue(stateId, nextActionPair, currentState, reward, true);
}
}
} else
logger.warn("Scale is changed, can not execute the shot, will re-segement the image");
} else
logger.warn("no sling detected, can not execute the shot, will re-segement the image");
}
}
return state;
}
/**
* checks if highest q_value is 0.0 which means that we have never been in this state,
* so we need to initialize all possible actions to 0.0
*
* @param s
*/
private int initProblemState(ProblemState s) {
int counter = 0;
// 1. get new StateId
int stateId = (int)qValuesDAO.insertStateId();
// 2. create all Objects and link them to this state
for (ABObject obj : s.allObjects) {
int objectId = qValuesDAO.insertObject((int)obj.getCenterX()/10, (int)obj.getCenterX()/10, String.valueOf(obj.getType()), String.valueOf(obj.shape));
qValuesDAO.insertState(stateId, objectId);
}
// 3. Generate actions in q_values if we have no actions initialised yet
if (qValuesDAO.getActionAmount(stateId) == 0) {
for (ABObject obj : s.getShootableObjects()) {
qValuesDAO.insertNewAction(0.0, stateId, counter);
counter += 1;
}
}
return stateId;
}
private int getStateId(ProblemState s) {
Set objectIds = new HashSet();
for (ABObject obj : s.allObjects) {
objectIds.add(qValuesDAO.insertObject((int)obj.getCenterX()/10, (int)obj.getCenterX()/10, String.valueOf(obj.getType()), String.valueOf(obj.shape)));
}
List<StateObject> stateObjects = qValuesDAO.getObjectListByStates();
List<Integer> candidates = new ArrayList<>();
logger.info("Current object IDs: " + objectIds);
for (StateObject obj : stateObjects){
Set<Integer> targetObjecIds = obj.objectIds;
// if they are the same, return objectId
if (objectIds.equals(targetObjecIds)){
return obj.stateId;
} else if (objectIds.size() == targetObjecIds.size()){
//else look for symmetric difference if same length
//(we assume the vision can count correctly, just had problems between rect and circle)
//@todo: maybe replace this with function from Guava or similar
Set<Integer> intersection = new HashSet<Integer>(objectIds);
intersection.retainAll(targetObjecIds);
Set<Integer> difference = new HashSet<Integer>();
difference.addAll(objectIds);
difference.addAll(targetObjecIds);
difference.removeAll(intersection);
if (difference.size() < 3){
candidates.add(obj.stateId);
logger.info("Candidate: " + targetObjecIds);
logger.info("difference was: " + difference);
}
}
}
if (candidates.size() == 0){
return this.initProblemState(s);
} else {
return candidates.get(0);
}
}
/**
* returns List of current birds and blocks
*
* @param vision
* @return List of current birds and blocks
*/
private List<ABObject> getBlocksAndBirds(Vision vision) {
List<ABObject> allObjs = new ArrayList<>();
allObjs.addAll(vision.findPigsMBR());
allObjs.addAll(vision.findBlocksMBR());
return allObjs;
}
/**
* returns reward as highscore difference
*
* @param state
* @return if the game is lost or the move was not the finishing one the reward is -1, else it is the highscore of the current level
*/
private double getReward(GameStateExtractor.GameState state) {
if (state == GameStateExtractor.GameState.WON) {
GameStateExtractor gameStateExtractor = new GameStateExtractor();
BufferedImage scoreScreenshot = actionRobot.doScreenShot();
return gameStateExtractor.getScoreEndGame(scoreScreenshot);
} else {
return -1;
}
}
/**
* updates q-value in database when new information comes in
*
* @param from
* @param nextAction
* @param to
* @param reward
* @param end true if the current level was finished (could be either won or lost)
*/
private void updateQValue(int fromId, ActionPair nextAction, ProblemState to, double reward, boolean end) {
int action = nextAction.value;
int toId = getStateId(to);
double oldValue = qValuesDAO.getQValue(fromId, action);
double newValue;
if (end) {
newValue = oldValue + learningRate * (reward - oldValue);
} else {
//possible error: highest Q value could have been different compared to when the action was selected with qValuesDAO.getBestAction
newValue = oldValue + learningRate * (reward + discountFactor * qValuesDAO.getHighestQValue(toId) - oldValue);
}
qValuesDAO.updateQValue(newValue, fromId, action);
qValuesDAO.saveMove(gameId, moveCounter, fromId, action, toId, reward, nextAction.rand, lowTrajectory);
}
/**
* Returns next action, with explorationrate as probability of taking a random action
* and else look for the so far best action
*
* @param problemState
* @return
*/
private ActionPair getNextAction(int stateId) {
int randomValue = randomGenerator.nextInt(100);
if (randomValue < explorationRate * 100) {
logger.info("Picked random action");
return new ActionPair(true, qValuesDAO.getRandomAction(stateId));
} else {
logger.info("Picked currently best available action");
return new ActionPair(false, qValuesDAO.getBestAction(stateId));
}
}
private class ActionPair {
public final boolean rand;
public final int value;
public ActionPair(boolean rand, int value) {
this.rand = rand;
this.value = value;
}
}
} |
package at.cosea.couchpipe;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.Timer;
import java.util.TimerTask;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* A dispatcher for a specific connection
*
* @author Florian Westreicher aka meredrica
* @since Jan 2, 2014
*/
public class PersistentConnection extends Thread {
private long timeout;
private URL to;
private URL from;
private long lastHeartbeat = 0;
private Timer timer = new Timer();
private String toAuth;
private String fromAuth;
private Logger logger = Logger.getLogger(getClass().getSimpleName());
private TimerTask task = new TimerTask() {
private int counter;
@Override
public void run() {
// check timeout
if (System.currentTimeMillis() - lastHeartbeat > timeout) {
// we have a timeout. restart
logger.warning("timeout detected, restarting");
restart();
} else if (counter++ == 10) {
// timeout check pass
logger.info("10 timeout checks passed");
counter = 0;
}
}
};
private boolean running;
private InputStream persistentInputStream;
private InputStreamReader persistentStreamReader;
private BufferedReader persistentBufferedReader;
/**
* Restarts all connections.
*/
private void restart() {
logger.info("restarting");
persistentInputStream = null;
persistentStreamReader = null;
persistentBufferedReader = null;
try {
URLConnection conn = from.openConnection();
conn.setDoInput(true);
conn.setReadTimeout(0);
if (fromAuth != null) {
conn.setRequestProperty("Authorization", fromAuth);
}
conn.connect();
persistentInputStream = conn.getInputStream();
persistentStreamReader = new InputStreamReader(persistentInputStream);
persistentBufferedReader = new BufferedReader(persistentStreamReader);
} catch (Exception e) {
logger.log(Level.SEVERE, "exception in restart()", e);
running = false;
closeAll();
}
}
private void closeAll() {
try {
if (persistentBufferedReader != null) {
persistentBufferedReader.close();
}
} catch (IOException e1) {
}
try {
if (persistentStreamReader != null) {
persistentStreamReader.close();
}
} catch (IOException e1) {
}
try {
if (persistentInputStream != null) {
persistentInputStream.close();
}
} catch (IOException e1) {
}
}
/**
* Creates the persistent connection
*
* @param from
* Url where the connection should be opened
* @param fromAuth
* Base64 string to use for http basic auth (or null if no auth needed)
* @param to
* Url where the packages should be delivered
* @param toAuth
* Base64 string to use for http basic auth (or null if no auth needed)
* @param timeout
* Timeout to use for checking
*
*/
public PersistentConnection(final URL from,
final String fromAuth,
final URL to,
final String toAuth,
final long timeout) {
this.from = from;
this.fromAuth = fromAuth;
this.to = to;
this.toAuth = toAuth;
this.timeout = timeout;
}
@Override
public void run() {
super.run();
// it's not a real restart, but it works the same way
restart();
// set the initial hearbeat
lastHeartbeat = System.currentTimeMillis();
// start the watchdog timer
timer.schedule(task, 1000, timeout / 10);
// connect to the stream
running = true;
while (running) {
try {
if (persistentBufferedReader != null && persistentBufferedReader.ready()) {
String line = persistentBufferedReader.readLine();
logger.fine("got: " + line);
lastHeartbeat = System.currentTimeMillis();
if (line.isEmpty()) {
// this is a heartbeat.
} else {
// deliver the response
HttpURLConnection out = (HttpURLConnection) to.openConnection();
out.setRequestMethod("POST");
if (toAuth != null) {
out.setRequestProperty("Authorization", toAuth);
}
out.setDoOutput(true);
OutputStream stream = null;
DataOutputStream dos = null;
try {
stream = out.getOutputStream();
dos = new DataOutputStream(stream);
dos.writeBytes(line);
dos.flush();
int code = out.getResponseCode(); // keep this line! it executes the whole http connection
logger.fine("response code:" + code);
} catch (Exception e) {
logger.log(Level.WARNING, "could not write to stream", e);
} finally {
if (dos != null) {
try {
dos.close();
} catch (IOException e) {
}
}
if (stream != null) {
try {
stream.close();
} catch (IOException e) {
}
}
}
}
}
sleep(10);
} catch (InterruptedException | IOException ex) {
logger.log(Level.WARNING, "error in run", ex);
}
}
}
} |
package org.pentaho.di.ui.spoon.job;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.ResourceBundle;
import java.util.Set;
import java.util.Timer;
import java.util.TimerTask;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.dialogs.MessageDialogWithToggle;
import org.eclipse.jface.window.DefaultToolTip;
import org.eclipse.jface.window.ToolTip;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.CTabFolder;
import org.eclipse.swt.custom.CTabItem;
import org.eclipse.swt.custom.SashForm;
import org.eclipse.swt.dnd.DND;
import org.eclipse.swt.dnd.DropTarget;
import org.eclipse.swt.dnd.DropTargetEvent;
import org.eclipse.swt.dnd.DropTargetListener;
import org.eclipse.swt.dnd.Transfer;
import org.eclipse.swt.events.DisposeEvent;
import org.eclipse.swt.events.DisposeListener;
import org.eclipse.swt.events.KeyAdapter;
import org.eclipse.swt.events.KeyEvent;
import org.eclipse.swt.events.KeyListener;
import org.eclipse.swt.events.MouseAdapter;
import org.eclipse.swt.events.MouseEvent;
import org.eclipse.swt.events.MouseListener;
import org.eclipse.swt.events.MouseMoveListener;
import org.eclipse.swt.events.MouseTrackListener;
import org.eclipse.swt.events.MouseWheelListener;
import org.eclipse.swt.events.PaintEvent;
import org.eclipse.swt.events.PaintListener;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.graphics.Device;
import org.eclipse.swt.graphics.GC;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.graphics.Rectangle;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.layout.FormAttachment;
import org.eclipse.swt.layout.FormData;
import org.eclipse.swt.layout.FormLayout;
import org.eclipse.swt.widgets.Canvas;
import org.eclipse.swt.widgets.Combo;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Menu;
import org.eclipse.swt.widgets.MessageBox;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.ToolBar;
import org.eclipse.swt.widgets.ToolItem;
import org.eclipse.swt.widgets.Widget;
import org.pentaho.di.core.Const;
import org.pentaho.di.core.EngineMetaInterface;
import org.pentaho.di.core.NotePadMeta;
import org.pentaho.di.core.Props;
import org.pentaho.di.core.Result;
import org.pentaho.di.core.ResultFile;
import org.pentaho.di.core.RowMetaAndData;
import org.pentaho.di.core.dnd.DragAndDropContainer;
import org.pentaho.di.core.dnd.XMLTransfer;
import org.pentaho.di.core.exception.KettleException;
import org.pentaho.di.core.gui.AreaOwner;
import org.pentaho.di.core.gui.GCInterface;
import org.pentaho.di.core.gui.Point;
import org.pentaho.di.core.gui.Redrawable;
import org.pentaho.di.core.gui.SnapAllignDistribute;
import org.pentaho.di.core.logging.CentralLogStore;
import org.pentaho.di.core.logging.HasLogChannelInterface;
import org.pentaho.di.core.logging.LogChannelInterface;
import org.pentaho.di.core.logging.LogParentProvidedInterface;
import org.pentaho.di.core.vfs.KettleVFS;
import org.pentaho.di.core.xml.XMLHandler;
import org.pentaho.di.i18n.BaseMessages;
import org.pentaho.di.job.Job;
import org.pentaho.di.job.JobEntryListener;
import org.pentaho.di.job.JobEntryResult;
import org.pentaho.di.job.JobExecutionConfiguration;
import org.pentaho.di.job.JobHopMeta;
import org.pentaho.di.job.JobListener;
import org.pentaho.di.job.JobMeta;
import org.pentaho.di.job.entries.job.JobEntryJob;
import org.pentaho.di.job.entries.trans.JobEntryTrans;
import org.pentaho.di.job.entry.JobEntryCopy;
import org.pentaho.di.job.entry.JobEntryInterface;
import org.pentaho.di.repository.Repository;
import org.pentaho.di.repository.RepositoryLock;
import org.pentaho.di.shared.SharedObjects;
import org.pentaho.di.trans.Trans;
import org.pentaho.di.trans.TransMeta;
import org.pentaho.di.trans.TransPainter;
import org.pentaho.di.ui.core.ConstUI;
import org.pentaho.di.ui.core.PropsUI;
import org.pentaho.di.ui.core.dialog.EnterTextDialog;
import org.pentaho.di.ui.core.dialog.ErrorDialog;
import org.pentaho.di.ui.core.gui.GUIResource;
import org.pentaho.di.ui.core.widget.CheckBoxToolTip;
import org.pentaho.di.ui.core.widget.CheckBoxToolTipListener;
import org.pentaho.di.ui.job.dialog.JobDialog;
import org.pentaho.di.ui.repository.dialog.RepositoryExplorerDialog;
import org.pentaho.di.ui.repository.dialog.RepositoryRevisionBrowserDialogInterface;
import org.pentaho.di.ui.spoon.AbstractGraph;
import org.pentaho.di.ui.spoon.JobPainter;
import org.pentaho.di.ui.spoon.SWTGC;
import org.pentaho.di.ui.spoon.Spoon;
import org.pentaho.di.ui.spoon.SpoonPluginManager;
import org.pentaho.di.ui.spoon.SwtScrollBar;
import org.pentaho.di.ui.spoon.TabItemInterface;
import org.pentaho.di.ui.spoon.TabMapEntry;
import org.pentaho.di.ui.spoon.XulSpoonResourceBundle;
import org.pentaho.di.ui.spoon.TabMapEntry.ObjectType;
import org.pentaho.di.ui.spoon.dialog.DeleteMessageBox;
import org.pentaho.di.ui.spoon.dialog.NotePadDialog;
import org.pentaho.di.ui.spoon.trans.DelayListener;
import org.pentaho.di.ui.spoon.trans.DelayTimer;
import org.pentaho.di.ui.spoon.trans.TransGraph;
import org.pentaho.ui.xul.XulDomContainer;
import org.pentaho.ui.xul.XulException;
import org.pentaho.ui.xul.XulLoader;
import org.pentaho.ui.xul.XulOverlay;
import org.pentaho.ui.xul.components.XulMenuitem;
import org.pentaho.ui.xul.components.XulToolbarbutton;
import org.pentaho.ui.xul.containers.XulMenu;
import org.pentaho.ui.xul.containers.XulMenupopup;
import org.pentaho.ui.xul.containers.XulToolbar;
import org.pentaho.ui.xul.dom.Document;
import org.pentaho.ui.xul.impl.XulEventHandler;
import org.pentaho.ui.xul.swt.SwtXulLoader;
public class JobGraph extends AbstractGraph implements XulEventHandler, Redrawable, TabItemInterface, LogParentProvidedInterface, MouseListener, MouseMoveListener, MouseTrackListener, MouseWheelListener, KeyListener {
private static Class<?> PKG = JobGraph.class; // for i18n purposes, needed by Translator2!! $NON-NLS-1$
private static final String XUL_FILE_JOB_GRAPH = "ui/job-graph.xul";
public final static String START_TEXT = BaseMessages.getString(PKG, "JobLog.Button.Start"); //$NON-NLS-1$
// public final static String PAUSE_TEXT = BaseMessages.getString(PKG, "JobLog.Button.PauseJob"); //$NON-NLS-1$ TODO
// public final static String RESUME_TEXT = BaseMessages.getString(PKG, "JobLog.Button.ResumeJob"); //$NON-NLS-1$ TODO
public final static String STOP_TEXT = BaseMessages.getString(PKG, "JobLog.Button.Stop"); //$NON-NLS-1$
private final static String STRING_PARALLEL_WARNING_PARAMETER = "ParallelJobEntriesWarning";
private static final int HOP_SEL_MARGIN = 9;
protected Shell shell;
protected LogChannelInterface log;
protected JobMeta jobMeta;
public Job job;
protected PropsUI props;
protected int iconsize;
protected int linewidth;
protected Point lastclick;
protected List<JobEntryCopy> selectedEntries;
protected JobEntryCopy selectedEntry;
protected Point previousLocations[];
private List<NotePadMeta> selectedNotes;
protected NotePadMeta selectedNote;
protected Point previous_note_location;
protected Point lastMove;
protected JobHopMeta hop_candidate;
protected Point drop_candidate;
protected Spoon spoon;
// public boolean shift, control;
protected boolean split_hop;
protected int lastButton;
protected JobHopMeta last_hop_split;
protected org.pentaho.di.core.gui.Rectangle selectionRegion;
protected static final double theta = Math.toRadians(10); // arrowhead sharpness
protected static final int size = 30; // arrowhead length
protected int shadowsize;
protected Map<String, XulMenupopup> menuMap = new HashMap<String, XulMenupopup>();
protected int currentMouseX = 0;
protected int currentMouseY = 0;
protected JobEntryCopy jobEntry;
protected NotePadMeta ni = null;
protected JobHopMeta currentHop;
// private Text filenameLabel;
private SashForm sashForm;
public Composite extraViewComposite;
public CTabFolder extraViewTabFolder;
private XulToolbar toolbar;
public JobLogDelegate jobLogDelegate;
public JobHistoryDelegate jobHistoryDelegate;
public JobGridDelegate jobGridDelegate;
private Composite mainComposite;
private List<RefreshListener> refreshListeners;
private Label closeButton;
private Label minMaxButton;
private CheckBoxToolTip helpTip;
private List<AreaOwner> areaOwners;
private List<JobEntryCopy> mouseOverEntries;
/** A map that keeps track of which log line was written by which job entry */
private Map<JobEntryCopy, String> entryLogMap;
private Map<JobEntryCopy, DelayTimer> delayTimers;
private JobEntryCopy startHopEntry;
private Point endHopLocation;
private JobEntryCopy endHopEntry;
private JobEntryCopy noInputEntry;
private DefaultToolTip toolTip;
private Point[] previous_step_locations;
private Point[] previous_note_locations;
private JobEntryCopy currentEntry;
private XulDomContainer xulDomContainer;
public JobGraph(Composite par, final Spoon spoon, final JobMeta jobMeta) {
super(par, SWT.NONE);
shell = par.getShell();
this.log = spoon.getLog();
this.spoon = spoon;
this.jobMeta = jobMeta;
this.props = PropsUI.getInstance();
this.areaOwners = new ArrayList<AreaOwner>();
this.mouseOverEntries = new ArrayList<JobEntryCopy>();
this.delayTimers = new HashMap<JobEntryCopy, DelayTimer>();
jobLogDelegate = new JobLogDelegate(spoon, this);
jobHistoryDelegate = new JobHistoryDelegate(spoon, this);
jobGridDelegate = new JobGridDelegate(spoon, this);
refreshListeners = new ArrayList<RefreshListener>();
try {
XulLoader loader = new SwtXulLoader();
ResourceBundle bundle = new XulSpoonResourceBundle(Spoon.class);
XulDomContainer container = loader.loadXul(XUL_FILE_JOB_GRAPH, bundle);
container.addEventHandler(this);
for(XulOverlay overlay : SpoonPluginManager.getInstance().getOverlaysforContainer("job-graph")){
xulDomContainer.loadOverlay(overlay.getOverlayUri());
}
for(XulEventHandler handler : SpoonPluginManager.getInstance().getEventHandlersforContainer("job-graph")){
xulDomContainer.addEventHandler(handler);
}
setXulDomContainer(container);
} catch (XulException e1) {
log.logError(toString(), Const.getStackTracker(e1));
}
setLayout(new FormLayout());
// Add a tool-bar at the top of the tab
// The form-data is set on the native widget automatically
addToolBar();
// The main composite contains the graph view, but if needed also
// a view with an extra tab containing log, etc.
mainComposite = new Composite(this, SWT.NONE);
mainComposite.setLayout(new FillLayout());
Control toolbarControl = (Control) toolbar.getManagedObject();
toolbarControl.setLayoutData(new FormData());
toolbarControl.setParent(this);
FormData fdMainComposite = new FormData();
fdMainComposite.left = new FormAttachment(0, 0);
fdMainComposite.top = new FormAttachment((Control) toolbar.getManagedObject(), 0);
fdMainComposite.right = new FormAttachment(100, 0);
fdMainComposite.bottom = new FormAttachment(100, 0);
mainComposite.setLayoutData(fdMainComposite);
// To allow for a splitter later on, we will add the splitter here...
sashForm = new SashForm(mainComposite, SWT.VERTICAL);
// Add a canvas below it, use up all space initially
canvas = new Canvas(sashForm, SWT.V_SCROLL | SWT.H_SCROLL | SWT.NO_BACKGROUND | SWT.BORDER);
sashForm.setWeights(new int[] { 100, });
try {
Document doc = xulDomContainer.getDocumentRoot();
menuMap.put("job-graph-hop", (XulMenupopup) doc.getElementById("job-graph-hop"));
menuMap.put("job-graph-note", (XulMenupopup) doc.getElementById("job-graph-note"));
menuMap.put("job-graph-background", (XulMenupopup) doc.getElementById("job-graph-background"));
menuMap.put("job-graph-entry", (XulMenupopup) doc.getElementById("job-graph-entry"));
} catch (Throwable t) {
log.logError(Const.getStackTracker(t));
new ErrorDialog(shell, BaseMessages.getString(PKG, "JobGraph.Exception.ErrorReadingXULFile.Title"),
BaseMessages.getString(PKG, "JobGraph.Exception.ErrorReadingXULFile.Message", Spoon.XUL_FILE_MENUS), new Exception(t));
}
toolTip = new DefaultToolTip(canvas, ToolTip.NO_RECREATE, true);
toolTip.setRespectMonitorBounds(true);
toolTip.setRespectDisplayBounds(true);
toolTip.setPopupDelay(350);
toolTip.setShift(new org.eclipse.swt.graphics.Point(ConstUI.TOOLTIP_OFFSET, ConstUI.TOOLTIP_OFFSET));
helpTip = new CheckBoxToolTip(canvas);
helpTip.addCheckBoxToolTipListener(new CheckBoxToolTipListener() {
public void checkBoxSelected(boolean enabled) {
spoon.props.setShowingHelpToolTips(enabled);
}
});
newProps();
selectionRegion = null;
hop_candidate = null;
last_hop_split = null;
selectedEntries = null;
selectedNote = null;
hori = canvas.getHorizontalBar();
vert = canvas.getVerticalBar();
hori.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
redraw();
}
});
vert.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
redraw();
}
});
hori.setThumb(100);
vert.setThumb(100);
hori.setVisible(true);
vert.setVisible(true);
setVisible(true);
canvas.addPaintListener(new PaintListener() {
public void paintControl(PaintEvent e) {
JobGraph.this.paintControl(e);
}
});
selectedEntries = null;
lastclick = null;
canvas.addMouseListener(this);
canvas.addMouseMoveListener(this);
canvas.addMouseTrackListener(this);
canvas.addMouseWheelListener(this);
// Drag & Drop for steps
Transfer[] ttypes = new Transfer[] { XMLTransfer.getInstance() };
DropTarget ddTarget = new DropTarget(canvas, DND.DROP_MOVE);
ddTarget.setTransfer(ttypes);
ddTarget.addDropListener(new DropTargetListener() {
public void dragEnter(DropTargetEvent event) {
drop_candidate = PropsUI.calculateGridPosition(getRealPosition(canvas, event.x, event.y));
redraw();
}
public void dragLeave(DropTargetEvent event) {
drop_candidate = null;
redraw();
}
public void dragOperationChanged(DropTargetEvent event) {
}
public void dragOver(DropTargetEvent event) {
drop_candidate = PropsUI.calculateGridPosition(getRealPosition(canvas, event.x, event.y));
redraw();
}
public void drop(DropTargetEvent event) {
// no data to copy, indicate failure in event.detail
if (event.data == null) {
event.detail = DND.DROP_NONE;
return;
}
Point p = getRealPosition(canvas, event.x, event.y);
try {
DragAndDropContainer container = (DragAndDropContainer) event.data;
String entry = container.getData();
switch (container.getType()) {
case DragAndDropContainer.TYPE_BASE_JOB_ENTRY: // Create a new Job Entry on the canvas
{
JobEntryCopy jge = spoon.newJobEntry(jobMeta, entry, false);
if (jge != null) {
PropsUI.setLocation(jge, p.x, p.y);
jge.setDrawn();
redraw();
// See if we want to draw a tool tip explaining how to create new hops...
if (jobMeta.nrJobEntries() > 1 && jobMeta.nrJobEntries() < 5 && spoon.props.isShowingHelpToolTips()) {
showHelpTip(p.x, p.y, BaseMessages.getString(PKG, "JobGraph.HelpToolTip.CreatingHops.Title"),
BaseMessages.getString(PKG, "JobGraph.HelpToolTip.CreatingHops.Message"));
}
}
}
break;
case DragAndDropContainer.TYPE_JOB_ENTRY: // Drag existing one onto the canvas
{
JobEntryCopy jge = jobMeta.findJobEntry(entry, 0, true);
if (jge != null) // Create duplicate of existing entry
{
// There can be only 1 start!
if (jge.isStart() && jge.isDrawn()) {
showOnlyStartOnceMessage(shell);
return;
}
boolean jge_changed = false;
// For undo :
JobEntryCopy before = (JobEntryCopy) jge.clone_deep();
JobEntryCopy newjge = jge;
if (jge.isDrawn()) {
newjge = (JobEntryCopy) jge.clone();
if (newjge != null) {
// newjge.setEntry(jge.getEntry());
if(log.isDebug()) log.logDebug("entry aft = " + ((Object) jge.getEntry()).toString()); //$NON-NLS-1$
newjge.setNr(jobMeta.findUnusedNr(newjge.getName()));
jobMeta.addJobEntry(newjge);
spoon.addUndoNew(jobMeta, new JobEntryCopy[] { newjge }, new int[] { jobMeta
.indexOfJobEntry(newjge) });
} else {
if(log.isDebug()) log.logDebug("jge is not cloned!"); //$NON-NLS-1$
}
} else {
if(log.isDebug()) log.logDebug(jge.toString() + " is not drawn"); //$NON-NLS-1$
jge_changed = true;
}
PropsUI.setLocation(newjge, p.x, p.y);
newjge.setDrawn();
if (jge_changed) {
spoon.addUndoChange(jobMeta, new JobEntryCopy[] { before }, new JobEntryCopy[] { newjge },
new int[] { jobMeta.indexOfJobEntry(newjge) });
}
redraw();
spoon.refreshTree();
log.logBasic("DropTargetEvent", "DROP " + newjge.toString() + "!, type="+newjge.getEntry().getTypeId());
} else {
log.logError("Unknown job entry dropped onto the canvas.");
}
}
break;
default:
break;
}
} catch (Exception e) {
new ErrorDialog(shell, BaseMessages.getString(PKG, "JobGraph.Dialog.ErrorDroppingObject.Message"), BaseMessages.getString(PKG, "JobGraph.Dialog.ErrorDroppingObject.Title"), e);
}
}
public void dropAccept(DropTargetEvent event) {
drop_candidate = null;
}
});
canvas.addKeyListener(this);
setBackground(GUIResource.getInstance().getColorBackground());
setControlStates();
// Add a timer to set correct the state of the run/stop buttons every 2 seconds...
final Timer timer = new Timer();
TimerTask timerTask = new TimerTask() {
public void run() {
setControlStates();
}
};
timer.schedule(timerTask, 2000, 1000);
// Make sure the timer stops when we close the tab...
addDisposeListener(new DisposeListener() {
public void widgetDisposed(DisposeEvent arg0) {
timer.cancel();
}
});
}
protected void hideToolTips() {
toolTip.hide();
helpTip.hide();
}
public void mouseDoubleClick(MouseEvent e) {
clearSettings();
Point real = screen2real(e.x, e.y);
// Hide the tooltip!
hideToolTips();
JobEntryCopy jobentry = jobMeta.getJobEntryCopy(real.x, real.y, iconsize);
if (jobentry != null) {
if (e.button == 1) {
editEntry(jobentry);
} else // open tab in Spoon
{
launchStuff(jobentry);
}
} else {
// Check if point lies on one of the many hop-lines...
JobHopMeta online = findJobHop(real.x, real.y);
if (online != null) {
// editJobHop(online);
} else {
NotePadMeta ni = jobMeta.getNote(real.x, real.y);
if (ni != null) {
editNote(ni);
}
}
}
}
public void mouseDown(MouseEvent e) {
boolean control = (e.stateMask & SWT.CONTROL) != 0;
boolean shift = (e.stateMask & SWT.SHIFT) != 0;
lastButton = e.button;
Point real = screen2real(e.x, e.y);
lastclick = new Point(real.x, real.y);
// Hide the tooltip!
hideToolTips();
// Set the pop-up menu
if (e.button == 3) {
setMenu(real.x, real.y);
return;
}
// A single left click on one of the area owners...
if (e.button == 1) {
AreaOwner areaOwner = getVisibleAreaOwner(real.x, real.y);
if (areaOwner != null) {
switch (areaOwner.getAreaType()) {
case JOB_ENTRY_MINI_ICON_OUTPUT:
// Click on the output icon means: start of drag
// Action: We show the input icons on the other steps...
{
selectedEntry = null;
startHopEntry = (JobEntryCopy) areaOwner.getOwner();
// stopEntryMouseOverDelayTimer(startHopEntry);
}
break;
case JOB_ENTRY_MINI_ICON_INPUT:
// Click on the input icon means: start to a new hop
// In this case, we set the end hop step...
{
selectedEntry = null;
startHopEntry = null;
endHopEntry = (JobEntryCopy) areaOwner.getOwner();
// stopEntryMouseOverDelayTimer(endHopEntry);
}
break;
case JOB_ENTRY_MINI_ICON_EDIT:
{
clearSettings();
currentEntry = (JobEntryCopy) areaOwner.getOwner();
stopEntryMouseOverDelayTimer(currentEntry);
editEntry(currentEntry);
}
break;
case JOB_ENTRY_MINI_ICON_CONTEXT:
clearSettings();
JobEntryCopy jobEntryCopy = (JobEntryCopy) areaOwner.getOwner();
setMenu(jobEntryCopy.getLocation().x, jobEntryCopy.getLocation().y);
break;
case JOB_ENTRY_ICON:
jobEntryCopy = (JobEntryCopy) areaOwner.getOwner();
currentEntry = jobEntryCopy;
if (hop_candidate != null) {
addCandidateAsHop();
}
// SHIFT CLICK is start of drag to create a new hop
else if (e.button == 2 || (e.button == 1 && shift)) {
startHopEntry = jobEntryCopy;
} else {
selectedEntries = jobMeta.getSelectedEntries();
selectedEntry = jobEntryCopy;
// When an icon is moved that is not selected, it gets
// selected too late.
// It is not captured here, but in the mouseMoveListener...
previous_step_locations = jobMeta.getSelectedLocations();
Point p = jobEntryCopy.getLocation();
iconoffset = new Point(real.x - p.x, real.y - p.y);
}
redraw();
break;
case NOTE:
ni = (NotePadMeta) areaOwner.getOwner();
selectedNotes = jobMeta.getSelectedNotes();
selectedNote = ni;
Point loc = ni.getLocation();
previous_note_locations = jobMeta.getSelectedNoteLocations();
noteoffset = new Point(real.x - loc.x, real.y - loc.y);
redraw();
break;
// If you click on an evaluating icon, change the evaluation...
case JOB_HOP_ICON:
JobHopMeta hop = (JobHopMeta) areaOwner.getOwner();
if (hop.getFromEntry().evaluates()) {
if (hop.isUnconditional()) {
hop.setUnconditional(false);
hop.setEvaluation(true);
} else {
if (hop.getEvaluation()) {
hop.setEvaluation(false);
} else {
hop.setUnconditional(true);
}
}
redraw();
}
break;
}
} else {
// No area-owner means: background:
startHopEntry = null;
if (!control) {
selectionRegion = new org.pentaho.di.core.gui.Rectangle(real.x, real.y, 0, 0);
}
redraw();
}
}
}
public void mouseUp(MouseEvent e) {
boolean control = (e.stateMask & SWT.CONTROL) != 0;
if (iconoffset == null)
iconoffset = new Point(0, 0);
Point real = screen2real(e.x, e.y);
Point icon = new Point(real.x - iconoffset.x, real.y - iconoffset.y);
// Quick new hop option? (drag from one step to another)
if (hop_candidate != null) {
addCandidateAsHop();
redraw();
}
// Did we select a region on the screen? Mark steps in region as
// selected
else {
if (selectionRegion != null) {
selectionRegion.width = real.x - selectionRegion.x;
selectionRegion.height = real.y - selectionRegion.y;
jobMeta.unselectAll();
selectInRect(jobMeta, selectionRegion);
selectionRegion = null;
stopEntryMouseOverDelayTimers();
redraw();
}
// Clicked on an icon?
else {
if (selectedEntry != null && startHopEntry==null) {
if (e.button == 1) {
Point realclick = screen2real(e.x, e.y);
if (lastclick.x == realclick.x && lastclick.y == realclick.y) {
// Flip selection when control is pressed!
if (control) {
selectedEntry.flipSelected();
} else {
// Otherwise, select only the icon clicked on!
jobMeta.unselectAll();
selectedEntry.setSelected(true);
}
} else {
// Find out which Steps & Notes are selected
selectedEntries = jobMeta.getSelectedEntries();
selectedNotes = jobMeta.getSelectedNotes();
// We moved around some items: store undo info...
boolean also = false;
if (selectedNotes != null && selectedNotes.size() > 0 && previous_note_locations != null) {
int indexes[] = jobMeta.getNoteIndexes(selectedNotes);
addUndoPosition(selectedNotes.toArray(new NotePadMeta[selectedNotes.size()]), indexes, previous_note_locations, jobMeta
.getSelectedNoteLocations(), also);
also = selectedEntries != null && selectedEntries.size() > 0;
}
if (selectedEntries != null && selectedEntries.size() > 0 && previous_step_locations != null) {
int indexes[] = jobMeta.getEntryIndexes(selectedEntries);
addUndoPosition(selectedEntries.toArray(new JobEntryCopy[selectedEntries.size()]), indexes, previous_step_locations, jobMeta.getSelectedLocations(), also);
}
}
}
// OK, we moved the step, did we move it across a hop?
// If so, ask to split the hop!
if (split_hop) {
JobHopMeta hi = findHop(icon.x + iconsize / 2, icon.y + iconsize / 2, selectedEntry);
if (hi != null) {
int id = 0;
if (!spoon.props.getAutoSplit()) {
MessageDialogWithToggle md = new MessageDialogWithToggle(
shell,
BaseMessages.getString(PKG, "TransGraph.Dialog.SplitHop.Title"), null, //$NON-NLS-1$
BaseMessages.getString(PKG, "TransGraph.Dialog.SplitHop.Message") + Const.CR + hi.toString(), MessageDialog.QUESTION, new String[] { //$NON-NLS-1$
BaseMessages.getString(PKG, "System.Button.Yes"), BaseMessages.getString(PKG, "System.Button.No") }, 0, BaseMessages.getString(PKG, "TransGraph.Dialog.Option.SplitHop.DoNotAskAgain"), spoon.props.getAutoSplit()); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
MessageDialogWithToggle.setDefaultImage(GUIResource.getInstance().getImageSpoon());
id = md.open();
spoon.props.setAutoSplit(md.getToggleState());
}
if ((id & 0xFF) == 0) // Means: "Yes" button clicked!
{
// Only split A-->--B by putting C in between IF...
// C-->--A or B-->--C don't exists...
// A ==> hi.getFromEntry()
// B ==> hi.getToEntry();
// C ==> selected_step
if (jobMeta.findJobHop(selectedEntry, hi.getFromEntry()) == null && jobMeta.findJobHop(hi.getToEntry(), selectedEntry) == null) {
JobHopMeta newhop1 = new JobHopMeta(hi.getFromEntry(), selectedEntry);
if (hi.getFromEntry().getEntry().isUnconditional()) {
newhop1.setUnconditional();
}
jobMeta.addJobHop(newhop1);
spoon.addUndoNew(jobMeta, new JobHopMeta[] { newhop1 }, new int[] { jobMeta.indexOfJobHop(newhop1) }, true);
JobHopMeta newhop2 = new JobHopMeta(selectedEntry, hi.getToEntry());
if (selectedEntry.getEntry().isUnconditional()) {
newhop2.setUnconditional();
}
jobMeta.addJobHop(newhop2);
spoon.addUndoNew(jobMeta, new JobHopMeta[] { newhop2 }, new int[] { jobMeta.indexOfJobHop(newhop2) }, true);
int idx = jobMeta.indexOfJobHop(hi);
spoon.addUndoDelete(jobMeta, new JobHopMeta[] { hi }, new int[] { idx }, true);
jobMeta.removeJobHop(idx);
spoon.refreshTree();
} else {
// Silently discard this hop-split attempt.
}
}
}
split_hop = false;
}
selectedEntries = null;
selectedNotes = null;
selectedEntry = null;
selectedNote = null;
startHopEntry = null;
endHopLocation = null;
redraw();
}
// Notes?
else {
if (selectedNote != null) {
if (e.button == 1) {
if (lastclick.x == e.x && lastclick.y == e.y) {
// Flip selection when control is pressed!
if (control) {
selectedNote.flipSelected();
} else {
// Otherwise, select only the note clicked on!
jobMeta.unselectAll();
selectedNote.setSelected(true);
}
} else {
// Find out which Steps & Notes are selected
selectedEntries = jobMeta.getSelectedEntries();
selectedNotes = jobMeta.getSelectedNotes();
// We moved around some items: store undo info...
boolean also = false;
if (selectedNotes != null && selectedNotes.size() > 0 && previous_note_locations != null) {
int indexes[] = jobMeta.getNoteIndexes(selectedNotes);
addUndoPosition(selectedNotes.toArray(new NotePadMeta[selectedNotes.size()]), indexes, previous_note_locations, jobMeta.getSelectedNoteLocations(), also);
also = selectedEntries != null && selectedEntries.size() > 0;
}
if (selectedEntries != null && selectedEntries.size() > 0 && previous_step_locations != null) {
int indexes[] = jobMeta.getEntryIndexes(selectedEntries);
addUndoPosition(selectedEntries.toArray(new JobEntryCopy[selectedEntries.size()]), indexes, previous_step_locations, jobMeta.getSelectedLocations(), also);
}
}
}
selectedNotes = null;
selectedEntries = null;
selectedEntry = null;
selectedNote = null;
startHopEntry = null;
endHopLocation = null;
} else {
AreaOwner areaOwner = getVisibleAreaOwner(real.x, real.y);
if (areaOwner==null && selectionRegion==null) {
// Hit absolutely nothing: clear the settings
clearSettings();
}
}
}
}
}
lastButton = 0;
}
public void mouseMove(MouseEvent e) {
boolean shift = (e.stateMask & SWT.SHIFT) != 0;
noInputEntry = null;
// disable the tooltip
toolTip.hide();
// Remember the last position of the mouse for paste with keyboard
lastMove = new Point(e.x, e.y);
Point real = screen2real(e.x, e.y);
if (iconoffset == null) {
iconoffset = new Point(0, 0);
}
Point icon = new Point(real.x - iconoffset.x, real.y - iconoffset.y);
if (noteoffset == null) {
noteoffset = new Point(0, 0);
}
Point note = new Point(real.x - noteoffset.x, real.y - noteoffset.y);
// Moved over an area?
AreaOwner areaOwner = getVisibleAreaOwner(real.x, real.y);
if (areaOwner!=null) {
switch (areaOwner.getAreaType()) {
case JOB_ENTRY_ICON :
{
JobEntryCopy jobEntryCopy = (JobEntryCopy) areaOwner.getOwner();
resetDelayTimer(jobEntryCopy);
}
break;
case MINI_ICONS_BALLOON : // Give the timer a bit more time
{
JobEntryCopy jobEntryCopy = (JobEntryCopy)areaOwner.getOwner();
resetDelayTimer(jobEntryCopy);
}
break;
default:
break;
}
}
// First see if the icon we clicked on was selected.
// If the icon was not selected, we should un-select all other
// icons, selected and move only the one icon
if (selectedEntry != null && !selectedEntry.isSelected()) {
jobMeta.unselectAll();
selectedEntry.setSelected(true);
selectedEntries = new ArrayList<JobEntryCopy>();
selectedEntries.add(selectedEntry);
previous_step_locations = new Point[] { selectedEntry.getLocation() };
redraw();
}
else if (selectedNote != null && !selectedNote.isSelected()) {
jobMeta.unselectAll();
selectedNote.setSelected(true);
selectedNotes = new ArrayList<NotePadMeta>();
selectedNotes.add(selectedNote);
previous_note_locations = new Point[] { selectedNote.getLocation() };
redraw();
}
// Did we select a region...?
else if (selectionRegion != null && startHopEntry==null) {
selectionRegion.width = real.x - selectionRegion.x;
selectionRegion.height = real.y - selectionRegion.y;
redraw();
}
// Move around steps & notes
else if (selectedEntry != null && lastButton == 1 && !shift && startHopEntry==null) {
/*
* One or more icons are selected and moved around...
*
* new : new position of the ICON (not the mouse pointer) dx : difference with previous
* position
*/
int dx = icon.x - selectedEntry.getLocation().x;
int dy = icon.y - selectedEntry.getLocation().y;
// See if we have a hop-split candidate
JobHopMeta hi = findHop(icon.x + iconsize / 2, icon.y + iconsize / 2, selectedEntry);
if (hi != null) {
// OK, we want to split the hop in 2
if (!hi.getFromEntry().equals(selectedEntry) && !hi.getToEntry().equals(selectedEntry)) {
split_hop = true;
last_hop_split = hi;
hi.split = true;
}
} else {
if (last_hop_split != null) {
last_hop_split.split = false;
last_hop_split = null;
split_hop = false;
}
}
selectedNotes = jobMeta.getSelectedNotes();
selectedEntries = jobMeta.getSelectedEntries();
// Adjust location of selected steps...
if (selectedEntries != null) {
for (int i = 0; i < selectedEntries.size(); i++) {
JobEntryCopy jobEntryCopy = selectedEntries.get(i);
PropsUI.setLocation(jobEntryCopy, jobEntryCopy.getLocation().x + dx, jobEntryCopy.getLocation().y + dy);
stopEntryMouseOverDelayTimer(jobEntryCopy);
}
}
// Adjust location of selected hops...
if (selectedNotes != null) {
for (int i = 0; i < selectedNotes.size(); i++) {
NotePadMeta ni = selectedNotes.get(i);
PropsUI.setLocation(ni, ni.getLocation().x + dx, ni.getLocation().y + dy);
}
}
redraw();
}
// Are we creating a new hop with the middle button or pressing SHIFT?
else if ((startHopEntry!=null && endHopEntry==null) || (endHopEntry!=null && startHopEntry==null)) {
JobEntryCopy jobEntryCopy = jobMeta.getJobEntryCopy(real.x, real.y, iconsize);
endHopLocation = new Point(real.x, real.y);
if (jobEntryCopy != null && ((startHopEntry!=null && !startHopEntry.equals(jobEntryCopy)) || (endHopEntry!=null && !endHopEntry.equals(jobEntryCopy))) ) {
if (hop_candidate == null) {
// See if the step accepts input. If not, we can't create a new hop...
if (startHopEntry!=null) {
if (!jobEntryCopy.isStart()) {
hop_candidate = new JobHopMeta(startHopEntry, jobEntryCopy);
endHopLocation=null;
} else {
noInputEntry=jobEntryCopy;
toolTip.setImage(null);
toolTip.setText("The start entry can only be used at the start of a Job");
toolTip.show(new org.eclipse.swt.graphics.Point(real.x, real.y));
}
} else if (endHopEntry!=null) {
hop_candidate = new JobHopMeta(jobEntryCopy, endHopEntry);
endHopLocation=null;
}
}
} else {
if (hop_candidate != null) {
hop_candidate = null;
redraw();
}
}
redraw();
}
// Move around notes & steps
if (selectedNote != null) {
if (lastButton == 1 && !shift) {
/*
* One or more notes are selected and moved around...
*
* new : new position of the note (not the mouse pointer) dx : difference with previous
* position
*/
int dx = note.x - selectedNote.getLocation().x;
int dy = note.y - selectedNote.getLocation().y;
selectedNotes = jobMeta.getSelectedNotes();
selectedEntries = jobMeta.getSelectedEntries();
// Adjust location of selected steps...
if (selectedEntries != null)
for (int i = 0; i < selectedEntries.size(); i++) {
JobEntryCopy jobEntryCopy = selectedEntries.get(i);
PropsUI.setLocation(jobEntryCopy, jobEntryCopy.getLocation().x + dx, jobEntryCopy.getLocation().y + dy);
}
// Adjust location of selected hops...
if (selectedNotes != null)
for (int i = 0; i < selectedNotes.size(); i++) {
NotePadMeta ni = selectedNotes.get(i);
PropsUI.setLocation(ni, ni.getLocation().x + dx, ni.getLocation().y + dy);
}
redraw();
}
}
}
public void mouseHover(MouseEvent e) {
boolean tip = true;
// toolTip.hide();
Point real = screen2real(e.x, e.y);
AreaOwner areaOwner = getVisibleAreaOwner(real.x, real.y);
if (areaOwner!=null) {
switch (areaOwner.getAreaType()) {
case JOB_ENTRY_ICON:
JobEntryCopy jobEntryCopy = (JobEntryCopy) areaOwner.getOwner();
if (!mouseOverEntries.contains(jobEntryCopy)) {
addEntryMouseOverDelayTimer(jobEntryCopy);
redraw();
tip=false;
}
break;
}
}
if (tip) {
// Show a tool tip upon mouse-over of an object on the canvas
if (!helpTip.isVisible()) {
setToolTip(real.x, real.y, e.x, e.y);
}
}
}
public void mouseEnter(MouseEvent event) {
}
public void mouseExit(MouseEvent event) {
};
public void mouseScrolled(MouseEvent e) {
/*
if (e.count == 3) {
// scroll up
zoomIn();
} else if (e.count == -3) {
// scroll down
zoomOut();
}
*/
}
private void addCandidateAsHop() {
if (hop_candidate != null) {
if (!hop_candidate.getFromEntry().evaluates() && hop_candidate.getFromEntry().isUnconditional()) {
hop_candidate.setUnconditional();
} else {
hop_candidate.setConditional();
int nr = jobMeta.findNrNextJobEntries(hop_candidate.getFromEntry());
// If there is one green link: make this one red! (or
// vice-versa)
if (nr == 1) {
JobEntryCopy jge = jobMeta.findNextJobEntry(hop_candidate.getFromEntry(), 0);
JobHopMeta other = jobMeta.findJobHop(hop_candidate.getFromEntry(), jge);
if (other != null) {
hop_candidate.setEvaluation(!other.getEvaluation());
}
}
}
jobMeta.addJobHop(hop_candidate);
spoon.addUndoNew(jobMeta, new JobHopMeta[] { hop_candidate }, new int[] { jobMeta.indexOfJobHop(hop_candidate) });
spoon.refreshTree();
clearSettings();
redraw();
}
}
public AreaOwner getVisibleAreaOwner(int x, int y) {
for (int i=areaOwners.size()-1;i>=0;i
AreaOwner areaOwner = areaOwners.get(i);
if (areaOwner.contains(x, y)) {
return areaOwner;
}
}
return null;
}
private synchronized void addEntryMouseOverDelayTimer(final JobEntryCopy jobEntryCopy) {
// Don't add the same mouse over delay timer twice...
if (mouseOverEntries.contains(jobEntryCopy)) return;
mouseOverEntries.add(jobEntryCopy);
DelayTimer delayTimer = new DelayTimer(2500, new DelayListener() {
public void expired() {
mouseOverEntries.remove(jobEntryCopy);
delayTimers.remove(jobEntryCopy);
asyncRedraw();
}
});
new Thread(delayTimer).start();
delayTimers.put(jobEntryCopy, delayTimer);
}
private void stopEntryMouseOverDelayTimer(final JobEntryCopy jobEntryCopy) {
DelayTimer delayTimer = delayTimers.get(jobEntryCopy);
if (delayTimer!=null) {
delayTimer.stop();
}
}
private void stopEntryMouseOverDelayTimers() {
for (DelayTimer timer : delayTimers.values()) {
timer.stop();
}
}
private void resetDelayTimer(JobEntryCopy jobEntryCopy) {
DelayTimer delayTimer = delayTimers.get(jobEntryCopy);
if (delayTimer!=null) {
delayTimer.reset();
}
}
protected void asyncRedraw() {
spoon.getDisplay().asyncExec(new Runnable() {
public void run() {
if (!isDisposed()) {
redraw();
}
}
});
}
private void addToolBar() {
try {
toolbar = (XulToolbar) getXulDomContainer().getDocumentRoot().getElementById("nav-toolbar");
ToolBar swtToolbar = (ToolBar) toolbar.getManagedObject();
swtToolbar.pack();
// Hack alert : more XUL limitations...
ToolItem sep = new ToolItem(swtToolbar, SWT.SEPARATOR);
zoomLabel = new Combo(swtToolbar, SWT.DROP_DOWN);
zoomLabel.setItems(TransPainter.magnificationDescriptions);
zoomLabel.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent arg0) {
readMagnification();
}
});
zoomLabel.addKeyListener(new KeyAdapter() {
public void keyPressed(KeyEvent event) {
if (event.character == SWT.CR) {
readMagnification();
}
}
});
setZoomLabel();
zoomLabel.pack();
sep.setWidth(80);
sep.setControl(zoomLabel);
swtToolbar.pack();
} catch (Throwable t) {
log.logError(Const.getStackTracker(t));
new ErrorDialog(shell, BaseMessages.getString(PKG, "Spoon.Exception.ErrorReadingXULFile.Title"),
BaseMessages.getString(PKG, "Spoon.Exception.ErrorReadingXULFile.Message", XUL_FILE_JOB_GRAPH), new Exception(t));
}
}
/**
* Allows for magnifying to any percentage entered by the user...
*/
private void readMagnification(){
String possibleText = zoomLabel.getText();
possibleText = possibleText.replace("%", "");
float possibleFloatMagnification;
try {
possibleFloatMagnification = Float.parseFloat(possibleText) / 100;
magnification = possibleFloatMagnification;
if (zoomLabel.getText().indexOf('%') < 0) {
zoomLabel.setText(zoomLabel.getText().concat("%"));
}
} catch (Exception e) {
MessageBox mb = new MessageBox(shell, SWT.YES | SWT.ICON_ERROR);
mb.setMessage(BaseMessages.getString(PKG, "TransGraph.Dialog.InvalidZoomMeasurement.Message", zoomLabel.getText())); //$NON-NLS-1$
mb.setText(BaseMessages.getString(PKG, "TransGraph.Dialog.InvalidZoomMeasurement.Title")); //$NON-NLS-1$
mb.open();
}
redraw();
}
public void keyPressed(KeyEvent e) {
// Delete
if (e.keyCode == SWT.DEL) {
List<JobEntryCopy> copies = jobMeta.getSelectedEntries();
if (copies != null && copies.size() > 0) {
delSelected();
}
}
// CTRL-UP : allignTop();
if (e.keyCode == SWT.ARROW_UP && (e.stateMask & SWT.CONTROL) != 0) {
alligntop();
}
// CTRL-DOWN : allignBottom();
if (e.keyCode == SWT.ARROW_DOWN && (e.stateMask & SWT.CONTROL) != 0) {
allignbottom();
}
// CTRL-LEFT : allignleft();
if (e.keyCode == SWT.ARROW_LEFT && (e.stateMask & SWT.CONTROL) != 0) {
allignleft();
}
// CTRL-RIGHT : allignRight();
if (e.keyCode == SWT.ARROW_RIGHT && (e.stateMask & SWT.CONTROL) != 0) {
allignright();
}
// ALT-RIGHT : distributeHorizontal();
if (e.keyCode == SWT.ARROW_RIGHT && (e.stateMask & SWT.ALT) != 0) {
distributehorizontal();
}
// ALT-UP : distributeVertical();
if (e.keyCode == SWT.ARROW_UP && (e.stateMask & SWT.ALT) != 0) {
distributevertical();
}
// ALT-HOME : snap to grid
if (e.keyCode == SWT.HOME && (e.stateMask & SWT.ALT) != 0) {
snaptogrid(ConstUI.GRID_SIZE);
}
// CTRL-W or CTRL-F4 : close tab
if ((e.character=='w' && (e.stateMask & SWT.CONTROL) != 0 ) ||
(e.keyCode==SWT.F4 && (e.stateMask & SWT.CONTROL) != 0 )
)
{
dispose();
}
}
public void keyReleased(KeyEvent e) {
}
public void selectInRect(JobMeta jobMeta, org.pentaho.di.core.gui.Rectangle rect) {
int i;
for (i = 0; i < jobMeta.nrJobEntries(); i++) {
JobEntryCopy je = jobMeta.getJobEntry(i);
Point p = je.getLocation();
if (((p.x >= rect.x && p.x <= rect.x + rect.width) || (p.x >= rect.x + rect.width && p.x <= rect.x))
&& ((p.y >= rect.y && p.y <= rect.y + rect.height) || (p.y >= rect.y + rect.height && p.y <= rect.y)))
je.setSelected(true);
}
}
public boolean setFocus() {
xulDomContainer.addEventHandler(this);
return canvas.setFocus();
}
/**
* Method gets called, when the user wants to change a job entries name and he indeed entered
* a different name then the old one. Make sure that no other job entry matches this name
* and rename in case of uniqueness.
*
* @param jobEntry
* @param newName
*/
public void renameJobEntry(JobEntryCopy jobEntry, String newName) {
JobEntryCopy[] jobs = jobMeta.getAllJobGraphEntries(newName);
if (jobs != null && jobs.length > 0) {
MessageBox mb = new MessageBox(shell, SWT.OK | SWT.ICON_INFORMATION);
mb.setMessage(BaseMessages.getString(PKG, "Spoon.Dialog.JobEntryNameExists.Message", newName));
mb.setText(BaseMessages.getString(PKG, "Spoon.Dialog.JobEntryNameExists.Title"));
mb.open();
} else {
jobEntry.setName(newName);
jobEntry.setChanged();
spoon.refreshTree(); // to reflect the new name
spoon.refreshGraph();
}
}
public static void showOnlyStartOnceMessage(Shell shell) {
MessageBox mb = new MessageBox(shell, SWT.YES | SWT.ICON_ERROR);
mb.setMessage(BaseMessages.getString(PKG, "JobGraph.Dialog.OnlyUseStartOnce.Message"));
mb.setText(BaseMessages.getString(PKG, "JobGraph.Dialog.OnlyUseStartOnce.Title"));
mb.open();
}
public void delSelected() {
List<JobEntryCopy> copies = jobMeta.getSelectedEntries();
int nrsels = copies.size();
if (nrsels == 0)
return;
// Load the list of steps
List<String> stepList = new ArrayList<String>();
for (int i = 0; i < copies.size(); ++i) {
stepList.add(copies.get(i).toString());
}
// Display the delete confirmation message box
MessageBox mb = new DeleteMessageBox(shell, BaseMessages.getString(PKG, "Spoon.Dialog.DeletionConfirm.Message"), //$NON-NLS-1$
stepList);
int answer = mb.open();
if (answer == SWT.YES) {
// Perform the delete
for (int i = 0; i < copies.size(); i++) {
spoon.deleteJobEntryCopies(jobMeta, copies.get(i));
}
spoon.refreshTree();
spoon.refreshGraph();
}
}
public void clearSettings() {
selectedEntry = null;
selectedNote = null;
selectedEntries = null;
selectedNotes = null;
selectionRegion = null;
hop_candidate = null;
last_hop_split = null;
lastButton = 0;
startHopEntry = null;
endHopEntry = null;
iconoffset = null;
for (int i = 0; i < jobMeta.nrJobHops(); i++) {
jobMeta.getJobHop(i).setSplit(false);
}
stopEntryMouseOverDelayTimers();
}
public Point getRealPosition(Composite canvas, int x, int y) {
Point p = new Point(0, 0);
Composite follow = canvas;
while (follow != null) {
Point xy = new Point(follow.getLocation().x, follow.getLocation().y);
p.x += xy.x;
p.y += xy.y;
follow = follow.getParent();
}
p.x = x - p.x - 8;
p.y = y - p.y - 48;
return screen2real(p.x, p.y);
}
/**
* See if location (x,y) is on a line between two steps: the hop!
* @param x
* @param y
* @return the transformation hop on the specified location, otherwise: null
*/
private JobHopMeta findJobHop(int x, int y) {
return findHop(x, y, null);
}
/**
* See if location (x,y) is on a line between two steps: the hop!
* @param x
* @param y
* @param exclude the step to exclude from the hops (from or to location). Specify null if no step is to be excluded.
* @return the transformation hop on the specified location, otherwise: null
*/
private JobHopMeta findHop(int x, int y, JobEntryCopy exclude) {
int i;
JobHopMeta online = null;
for (i = 0; i < jobMeta.nrJobHops(); i++) {
JobHopMeta hi = jobMeta.getJobHop(i);
JobEntryCopy fs = hi.getFromEntry();
JobEntryCopy ts = hi.getToEntry();
if (fs == null || ts == null)
return null;
// If either the "from" or "to" step is excluded, skip this hop.
if (exclude != null && (exclude.equals(fs) || exclude.equals(ts)))
continue;
int line[] = getLine(fs, ts);
if (pointOnLine(x, y, line))
online = hi;
}
return online;
}
protected int[] getLine(JobEntryCopy fs, JobEntryCopy ts) {
if (fs == null || ts == null)
return null;
Point from = fs.getLocation();
Point to = ts.getLocation();
offset = getOffset();
int x1 = from.x + iconsize / 2;
int y1 = from.y + iconsize / 2;
int x2 = to.x + iconsize / 2;
int y2 = to.y + iconsize / 2;
return new int[] { x1, y1, x2, y2 };
}
private void showHelpTip(int x, int y, String tipTitle, String tipMessage) {
helpTip.setTitle(tipTitle);
helpTip.setMessage(tipMessage);
helpTip.setCheckBoxMessage(BaseMessages.getString(PKG, "JobGraph.HelpToolTip.DoNotShowAnyMoreCheckBox.Message"));
// helpTip.hide();
// int iconSize = spoon.props.getIconSize();
org.eclipse.swt.graphics.Point location = new org.eclipse.swt.graphics.Point(x - 5, y - 5);
helpTip.show(location);
}
public void setJobEntry(JobEntryCopy jobEntry) {
this.jobEntry = jobEntry;
}
public JobEntryCopy getJobEntry() {
return jobEntry;
}
public void openTransformation() {
JobEntryCopy jobEntryCopy = getJobEntry();
final JobEntryInterface entry = jobEntryCopy.getEntry();
openTransformation((JobEntryTrans) entry, jobEntryCopy);
}
public void openJob() {
JobEntryCopy jobEntryCopy = getJobEntry();
final JobEntryInterface entry = jobEntryCopy.getEntry();
openJob((JobEntryJob) entry, jobEntryCopy);
}
public void newHopClick() {
selectedEntries = null;
newHop();
}
public void editEntryClick() {
selectedEntries = null;
editEntry(getJobEntry());
}
public void editEntryDescription() {
String title = BaseMessages.getString(PKG, "JobGraph.Dialog.EditDescription.Title"); //$NON-NLS-1$
String message = BaseMessages.getString(PKG, "JobGraph.Dialog.EditDescription.Message"); //$NON-NLS-1$
EnterTextDialog dd = new EnterTextDialog(shell, title, message, getJobEntry().getDescription());
String des = dd.open();
if (des != null)
jobEntry.setDescription(des);
}
/**
* Go from serial to parallel to serial execution
*/
public void editEntryParallel() {
getJobEntry().setLaunchingInParallel(!getJobEntry().isLaunchingInParallel());
if (getJobEntry().isLaunchingInParallel()) {
// Show a warning (optional)
if ("Y".equalsIgnoreCase(spoon.props.getCustomParameter(STRING_PARALLEL_WARNING_PARAMETER, "Y"))) //$NON-NLS-1$ //$NON-NLS-2$
{
MessageDialogWithToggle md = new MessageDialogWithToggle(shell,
BaseMessages.getString(PKG, "JobGraph.ParallelJobEntriesWarning.DialogTitle"), //$NON-NLS-1$
null, BaseMessages.getString(PKG, "JobGraph.ParallelJobEntriesWarning.DialogMessage", Const.CR) + Const.CR, //$NON-NLS-1$ //$NON-NLS-2$
MessageDialog.WARNING, new String[] { BaseMessages.getString(PKG, "JobGraph.ParallelJobEntriesWarning.Option1") }, //$NON-NLS-1$
0, BaseMessages.getString(PKG, "JobGraph.ParallelJobEntriesWarning.Option2"), //$NON-NLS-1$
"N".equalsIgnoreCase(spoon.props.getCustomParameter(STRING_PARALLEL_WARNING_PARAMETER, "Y")) //$NON-NLS-1$ //$NON-NLS-2$
);
MessageDialogWithToggle.setDefaultImage(GUIResource.getInstance().getImageSpoon());
md.open();
spoon.props.setCustomParameter(STRING_PARALLEL_WARNING_PARAMETER, md.getToggleState() ? "N" : "Y"); //$NON-NLS-1$ //$NON-NLS-2$
spoon.props.saveProps();
}
}
redraw();
}
public void duplicateEntry() throws KettleException {
if (!canDup(jobEntry)) {
JobGraph.showOnlyStartOnceMessage(spoon.getShell());
}
spoon.delegates.jobs.dupeJobEntry(jobMeta, jobEntry);
}
public void copyEntry() {
List<JobEntryCopy> entries = jobMeta.getSelectedEntries();
Iterator<JobEntryCopy> iterator = entries.iterator();
while (iterator.hasNext()) {
JobEntryCopy entry = iterator.next();
if (!canDup(entry)) {
iterator.remove();
}
}
spoon.delegates.jobs.copyJobEntries(jobMeta, entries);
}
private boolean canDup(JobEntryCopy entry) {
return !entry.isStart();
}
public void detatchEntry() {
detach(getJobEntry());
jobMeta.unselectAll();
}
public void hideEntry() {
getJobEntry().setDrawn(false);
// nr > 1: delete
if (jobEntry.getNr() > 0) {
int ind = jobMeta.indexOfJobEntry(jobEntry);
jobMeta.removeJobEntry(ind);
spoon.addUndoDelete(jobMeta, new JobEntryCopy[] { getJobEntry() }, new int[] { ind });
}
redraw();
}
public void deleteEntry() {
spoon.deleteJobEntryCopies(jobMeta, getJobEntry());
redraw();
}
protected synchronized void setMenu(int x, int y) {
currentMouseX = x;
currentMouseY = y;
final JobEntryCopy jobEntry = jobMeta.getJobEntryCopy(x, y, iconsize);
setJobEntry(jobEntry);
Document doc = xulDomContainer.getDocumentRoot();
if (jobEntry != null) // We clicked on a Job Entry!
{
XulMenupopup menu = (XulMenupopup) doc.getElementById("job-graph-entry");
if (menu != null) {
List<JobEntryCopy> selection = jobMeta.getSelectedEntries();
int sels = selection.size();
XulMenuitem item = (XulMenuitem) doc.getElementById("job-graph-entry-newhop");
item.setDisabled(sels < 2);
item = (XulMenuitem) doc.getElementById("job-graph-entry-launch");
if (jobEntry.isTransformation()) {
item.setDisabled(false);
item.setLabel(BaseMessages.getString(PKG, "JobGraph.PopupMenu.JobEntry.LaunchSpoon"));
} else if (jobEntry.isJob()) {
item.setDisabled(false);
item.setLabel(BaseMessages.getString(PKG, "JobGraph.PopupMenu.JobEntry.LaunchChef"));
} else {
item.setDisabled(true);
}
item = (XulMenuitem) doc.getElementById("job-graph-entry-align-snap");
item.setLabel(BaseMessages.getString(PKG, "JobGraph.PopupMenu.JobEntry.AllignDistribute.SnapToGrid") + ConstUI.GRID_SIZE
+ ")\tALT-HOME");
XulMenu aMenu = (XulMenu) doc.getElementById("job-graph-entry-align");
if (aMenu != null) {
aMenu.setDisabled(sels < 1);
}
item = (XulMenuitem) doc.getElementById("job-graph-entry-detach");
if (item != null) {
item.setDisabled(!jobMeta.isEntryUsedInHops(jobEntry));
}
item = (XulMenuitem) doc.getElementById("job-graph-entry-hide");
if (item != null) {
item.setDisabled(!(jobEntry.isDrawn() && !jobMeta.isEntryUsedInHops(jobEntry)));
}
item = (XulMenuitem) doc.getElementById("job-graph-entry-delete");
if (item != null) {
item.setDisabled(!jobEntry.isDrawn());
}
item = (XulMenuitem) doc.getElementById("job-graph-entry-parallel");
if (item != null) {
item.setSelected(jobEntry.isLaunchingInParallel());
}
ConstUI.displayMenu((Menu)menu.getManagedObject(), canvas);
}
} else // Clear the menu
{
final JobHopMeta hi = findJobHop(x, y);
setCurrentHop(hi);
if (hi != null) // We clicked on a HOP!
{
XulMenupopup menu = (XulMenupopup) doc.getElementById("job-graph-hop");
if (menu != null) {
XulMenuitem miPopEvalUncond = (XulMenuitem) doc.getElementById("job-graph-hop-evaluation-uncond");
XulMenuitem miPopEvalTrue = (XulMenuitem) doc.getElementById("job-graph-hop-evaluation-true");
XulMenuitem miPopEvalFalse = (XulMenuitem) doc.getElementById("job-graph-hop-evaluation-uncond");
XulMenuitem miDisHop = (XulMenuitem) doc.getElementById("job-graph-hop-enabled");
// Set the checkboxes in the right places...
if (hi.isUnconditional()) {
if (miPopEvalUncond != null)
miPopEvalUncond.setSelected(true);
if (miPopEvalTrue != null)
miPopEvalTrue.setSelected(false);
if (miPopEvalFalse != null)
miPopEvalFalse.setSelected(false);
} else {
if (hi.getEvaluation()) {
if (miPopEvalUncond != null)
miPopEvalUncond.setSelected(false);
if (miPopEvalTrue != null)
miPopEvalTrue.setSelected(true);
if (miPopEvalFalse != null)
miPopEvalFalse.setSelected(false);
} else {
if (miPopEvalUncond != null)
miPopEvalUncond.setSelected(false);
if (miPopEvalTrue != null)
miPopEvalTrue.setSelected(false);
if (miPopEvalFalse != null)
miPopEvalFalse.setSelected(true);
}
}
if (!hi.getFromEntry().evaluates()) {
if (miPopEvalTrue != null)
miPopEvalTrue.setDisabled(true);
if (miPopEvalFalse != null)
miPopEvalFalse.setDisabled(true);
}
if (!hi.getFromEntry().isUnconditional()) {
if (miPopEvalUncond != null)
miPopEvalUncond.setDisabled(true);
}
if (miDisHop != null) {
if (hi.isEnabled())
miDisHop.setLabel(BaseMessages.getString(PKG, "JobGraph.PopupMenu.Hop.Disable")); //$NON-NLS-1$
else
miDisHop.setLabel(BaseMessages.getString(PKG, "JobGraph.PopupMenu.Hop.Enable")); //$NON-NLS-1$
}
ConstUI.displayMenu((Menu)menu.getManagedObject(), canvas);
}
} else {
// Clicked on the background: maybe we hit a note?
final NotePadMeta ni = jobMeta.getNote(x, y);
setCurrentNote(ni);
if (ni != null) {
XulMenupopup menu = (XulMenupopup) doc.getElementById("job-graph-note");
if (menu != null) {
ConstUI.displayMenu((Menu)menu.getManagedObject(), canvas);
}
} else {
XulMenupopup menu = (XulMenupopup) doc.getElementById("job-graph-background");
if (menu != null) {
final String clipcontent = spoon.fromClipboard();
XulMenuitem item = (XulMenuitem) doc.getElementById("job-graph-note-paste");
if (item != null) {
item.setDisabled(clipcontent == null);
}
ConstUI.displayMenu((Menu)menu.getManagedObject(), canvas);
}
}
}
}
}
public void selectAll() {
spoon.editSelectAll();
}
public void clearSelection() {
spoon.editUnselectAll();
}
public void editJobProperties() {
editProperties(jobMeta, spoon, spoon.getRepository(), true);
}
public void pasteNote() {
final String clipcontent = spoon.fromClipboard();
Point loc = new Point(currentMouseX, currentMouseY);
spoon.pasteXML(jobMeta, clipcontent, loc);
}
public void newNote() {
String title = BaseMessages.getString(PKG, "JobGraph.Dialog.EditNote.Title");
String message = BaseMessages.getString(PKG, "JobGraph.Dialog.EditNote.Message");
EnterTextDialog dd = new EnterTextDialog(shell, title, message, "");
String n = dd.open();
if (n != null) {
NotePadMeta npi = new NotePadMeta(n, lastclick.x, lastclick.y, ConstUI.NOTE_MIN_SIZE, ConstUI.NOTE_MIN_SIZE);
jobMeta.addNote(npi);
spoon.addUndoNew(jobMeta, new NotePadMeta[] { npi }, new int[] { jobMeta.indexOfNote(npi) });
redraw();
}
}
public void setCurrentNote(NotePadMeta ni) {
this.ni = ni;
}
public NotePadMeta getCurrentNote() {
return ni;
}
public void editNote() {
selectionRegion = null;
editNote(getCurrentNote());
}
public void deleteNote() {
selectionRegion = null;
int idx = jobMeta.indexOfNote(getCurrentNote());
if (idx >= 0) {
jobMeta.removeNote(idx);
spoon.addUndoDelete(jobMeta, new NotePadMeta[] { getCurrentNote() }, new int[] { idx });
}
redraw();
}
public void raiseNote() {
selectionRegion = null;
int idx = jobMeta.indexOfNote(getCurrentNote());
if (idx >= 0) {
jobMeta.raiseNote(idx);
//spoon.addUndoRaise(jobMeta, new NotePadMeta[] {getCurrentNote()}, new int[] {idx} );
}
redraw();
}
public void lowerNote() {
selectionRegion = null;
int idx = jobMeta.indexOfNote(getCurrentNote());
if (idx >= 0) {
jobMeta.lowerNote(idx);
//spoon.addUndoLower(jobMeta, new NotePadMeta[] {getCurrentNote()}, new int[] {idx} );
}
redraw();
}
public void flipHop() {
selectionRegion = null;
JobEntryCopy dummy = currentHop.getFromEntry();
currentHop.setFromEntry( currentHop.getToEntry() );
currentHop.setToEntry( dummy );
if (jobMeta.hasLoop(currentHop.getFromEntry())) {
spoon.refreshGraph();
MessageBox mb = new MessageBox(shell, SWT.YES | SWT.ICON_WARNING);
mb.setMessage(BaseMessages.getString(PKG, "JobGraph.Dialog.HopFlipCausesLoop.Message"));
mb.setText(BaseMessages.getString(PKG, "JobGraph.Dialog.HopFlipCausesLoop.Title"));
mb.open();
dummy = currentHop.getFromEntry();
currentHop.setFromEntry(currentHop.getToEntry());
currentHop.setToEntry(dummy);
spoon.refreshGraph();
} else {
currentHop.setChanged();
spoon.refreshGraph();
spoon.refreshTree();
spoon.setShellText();
}
}
public void disableHop() {
selectionRegion = null;
currentHop.setEnabled(!currentHop.isEnabled());
spoon.refreshGraph();
spoon.refreshTree();
}
public void deleteHop() {
selectionRegion = null;
int idx = jobMeta.indexOfJobHop(currentHop);
jobMeta.removeJobHop(idx);
spoon.refreshTree();
spoon.refreshGraph();
}
public void setHopConditional(String id) {
if ("job-graph-hop-evaluation-uncond".equals(id)) { //$NON-NLS-1$
currentHop.setUnconditional();
spoon.refreshGraph();
} else if ("job-graph-hop-evaluation-true".equals(id)) { //$NON-NLS-1$
currentHop.setConditional();
currentHop.setEvaluation(true);
spoon.refreshGraph();
} else if ("job-graph-hop-evaluation-false".equals(id)) { //$NON-NLS-1$
currentHop.setConditional();
currentHop.setEvaluation(false);
spoon.refreshGraph();
}
}
protected void setCurrentHop(JobHopMeta hop) {
currentHop = hop;
}
protected JobHopMeta getCurrentHop() {
return currentHop;
}
protected void setToolTip(int x, int y, int screenX, int screenY) {
if (!spoon.getProperties().showToolTips())
return;
canvas.setToolTipText("-"); // Some stupid bug in GTK+ causes a phantom tool tip to pop up, even if the tip is null
canvas.setToolTipText(null);
Image tipImage = null;
JobHopMeta hi = findJobHop(x, y);
// check the area owner list...
StringBuffer tip = new StringBuffer();
AreaOwner areaOwner = getVisibleAreaOwner(x, y);
if (areaOwner!=null) {
switch (areaOwner.getAreaType()) {
case JOB_HOP_ICON:
hi = (JobHopMeta) areaOwner.getOwner();
if (hi.isUnconditional()) {
tipImage = GUIResource.getInstance().getImageUnconditionalHop();
tip.append(BaseMessages.getString(PKG, "JobGraph.Hop.Tooltip.Unconditional", hi.getFromEntry().getName(), Const.CR));
} else {
if (hi.getEvaluation()) {
tip.append(BaseMessages.getString(PKG, "JobGraph.Hop.Tooltip.EvaluatingTrue", hi.getFromEntry().getName(), Const.CR));
tipImage = GUIResource.getInstance().getImageTrue();
} else {
tip.append(BaseMessages.getString(PKG, "JobGraph.Hop.Tooltip.EvaluatingFalse", hi.getFromEntry().getName(), Const.CR));
tipImage = GUIResource.getInstance().getImageFalse();
}
}
break;
case JOB_HOP_PARALLEL_ICON:
hi = (JobHopMeta) areaOwner.getOwner();
tip.append(BaseMessages.getString(PKG, "JobGraph.Hop.Tooltip.Parallel", hi.getFromEntry().getName(), Const.CR));
tipImage = GUIResource.getInstance().getImageParallelHop();
break;
case REPOSITORY_LOCK_IMAGE:
RepositoryLock lock = (RepositoryLock) areaOwner.getOwner();
tip.append(BaseMessages.getString(PKG, "JobGraph.Locked.Tooltip", Const.CR, lock.getLogin(), lock.getUsername(), lock.getMessage(), XMLHandler.date2string(lock.getLockDate())));
tipImage = GUIResource.getInstance().getImageLocked();
break;
case JOB_ENTRY_MINI_ICON_INPUT:
tip.append(BaseMessages.getString(PKG, "JobGraph.EntryInputConnector.Tooltip"));
tipImage = GUIResource.getInstance().getImageHopInput();
resetDelayTimer((JobEntryCopy) areaOwner.getOwner());
break;
case JOB_ENTRY_MINI_ICON_OUTPUT:
tip.append(BaseMessages.getString(PKG, "JobGraph.EntryOutputConnector.Tooltip"));
tipImage = GUIResource.getInstance().getImageHopOutput();
resetDelayTimer((JobEntryCopy) areaOwner.getOwner());
break;
case JOB_ENTRY_MINI_ICON_EDIT:
tip.append(BaseMessages.getString(PKG, "JobGraph.EditStep.Tooltip"));
tipImage = GUIResource.getInstance().getImageEdit();
resetDelayTimer((JobEntryCopy) areaOwner.getOwner());
break;
case JOB_ENTRY_MINI_ICON_CONTEXT:
tip.append(BaseMessages.getString(PKG, "JobGraph.ShowMenu.Tooltip"));
tipImage = GUIResource.getInstance().getImageEdit();
resetDelayTimer((JobEntryCopy) areaOwner.getOwner());
break;
case JOB_ENTRY_RESULT_FAILURE:
case JOB_ENTRY_RESULT_SUCCESS:
JobEntryResult jobEntryResult = (JobEntryResult) areaOwner.getOwner();
JobEntryCopy jobEntryCopy = (JobEntryCopy) areaOwner.getParent();
Result result = jobEntryResult.getResult();
tip.append("'").append(jobEntryCopy.getName()).append("' ");
if (result.getResult()) {
tipImage = GUIResource.getInstance().getImageTrue();
tip.append("finished successfully.");
} else {
tipImage = GUIResource.getInstance().getImageFalse();
tip.append("failed.");
}
tip.append(Const.CR).append("
tip.append("Result : ").append(result.getResult()).append(Const.CR);
tip.append("Errors : ").append(result.getNrErrors()).append(Const.CR);
if (result.getNrLinesRead()>0) tip.append("Lines read : ").append(result.getNrLinesRead()).append(Const.CR);
if (result.getNrLinesWritten()>0) tip.append("Lines written : ").append(result.getNrLinesWritten()).append(Const.CR);
if (result.getNrLinesInput()>0) tip.append("Lines input : ").append(result.getNrLinesInput()).append(Const.CR);
if (result.getNrLinesOutput()>0) tip.append("Lines output : ").append(result.getNrLinesOutput()).append(Const.CR);
if (result.getNrLinesUpdated()>0) tip.append("Lines updated : ").append(result.getNrLinesUpdated()).append(Const.CR);
if (result.getNrLinesDeleted()>0) tip.append("Lines deleted : ").append(result.getNrLinesDeleted()).append(Const.CR);
if (result.getNrLinesRejected()>0) tip.append("Lines rejected : ").append(result.getNrLinesRejected()).append(Const.CR);
if (result.getResultFiles()!=null && !result.getResultFiles().isEmpty()) {
tip.append(Const.CR).append("Result files:").append(Const.CR);
if (result.getResultFiles().size()>10) {
tip.append(" (10 files of ").append(result.getResultFiles().size()).append(" shown");
}
List<ResultFile> files = new ArrayList<ResultFile>(result.getResultFiles().values());
for (int i=0;i<files.size();i++) {
ResultFile file = files.get(i);
tip.append(" - ").append(file.toString()).append(Const.CR);
}
}
if (result.getRows()!=null && !result.getRows().isEmpty()) {
tip.append(Const.CR).append("Result rows: ");
if (result.getRows().size()>10) {
tip.append(" (10 rows of ").append(result.getRows().size()).append(" shown");
}
tip.append(Const.CR);
for (int i=0;i<result.getRows().size() && i<10;i++) {
RowMetaAndData row = result.getRows().get(i);
tip.append(" - ").append(row.toString()).append(Const.CR);
}
}
break;
}
}
if (hi!=null && tip.length()==0) {
// Set the tooltip for the hop:
tip.append(BaseMessages.getString(PKG, "JobGraph.Dialog.HopInfo")).append(Const.CR);
tip.append(BaseMessages.getString(PKG, "JobGraph.Dialog.HopInfo.SourceEntry")).append(" ").append(hi.getFromEntry().getName()).append(Const.CR);
tip.append(BaseMessages.getString(PKG, "JobGraph.Dialog.HopInfo.TargetEntry")).append(" ").append(hi.getToEntry().getName()).append(Const.CR);
tip.append(BaseMessages.getString(PKG, "TransGraph.Dialog.HopInfo.Status")).append(" ");
tip.append((hi.isEnabled() ? BaseMessages.getString(PKG, "JobGraph.Dialog.HopInfo.Enable") : BaseMessages.getString(PKG, "JobGraph.Dialog.HopInfo.Disable")));
if (hi.isUnconditional()) {
tipImage = GUIResource.getInstance().getImageUnconditionalHop();
} else {
if (hi.getEvaluation()) {
tipImage = GUIResource.getInstance().getImageTrue();
} else {
tipImage = GUIResource.getInstance().getImageFalse();
}
}
}
if (tip==null || tip.length()==0) {
toolTip.hide();
} else {
if (!tip.toString().equalsIgnoreCase(getToolTipText())) {
if (tipImage != null) {
toolTip.setImage(tipImage);
} else {
toolTip.setImage(GUIResource.getInstance().getImageSpoon());
}
toolTip.setText(tip.toString());
toolTip.hide();
toolTip.show(new org.eclipse.swt.graphics.Point(x, y));
}
}
}
public void launchStuff(JobEntryCopy jobEntryCopy) {
if (jobEntryCopy.isJob()) {
final JobEntryJob entry = (JobEntryJob) jobEntryCopy.getEntry();
if ((entry != null && entry.getFilename() != null && spoon.rep == null)
|| (entry != null && entry.getName() != null && spoon.rep != null)) {
openJob(entry, jobEntryCopy);
}
} else if (jobEntryCopy.isTransformation()) {
final JobEntryTrans entry = (JobEntryTrans) jobEntryCopy.getEntry();
if ((entry != null && entry.getFilename() != null && spoon.rep == null)
|| (entry != null && entry.getName() != null && spoon.rep != null)) {
openTransformation(entry, jobEntryCopy);
}
}
}
public void launchStuff(){
List<JobEntryCopy> entries = jobMeta.getSelectedEntries();
if(entries == null || entries.size() > 1 || entries.size() == 0){
return;
}
JobEntryCopy current = entries.get(0);
if(current != null){
launchStuff(current);
}
}
protected void openTransformation(JobEntryTrans entry, JobEntryCopy jobEntryCopy) {
String exactFilename = jobMeta.environmentSubstitute(entry.getFilename());
String exactTransname = jobMeta.environmentSubstitute(entry.getTransname());
// check, whether a tab of this name is already opened
TabMapEntry tabEntry = spoon.delegates.tabs.findTabMapEntry(exactFilename, ObjectType.TRANSFORMATION_GRAPH);
if (tabEntry == null) {
tabEntry = spoon.delegates.tabs.findTabMapEntry(Const.filenameOnly(exactFilename), ObjectType.TRANSFORMATION_GRAPH);
}
if (tabEntry != null) {
spoon.tabfolder.setSelected(tabEntry.getTabItem());
return;
}
// Load from repository?
if (TransMeta.isRepReference(exactFilename, exactTransname)) {
try {
TransMeta newTrans;
// New transformation?
boolean exists = spoon.rep.getTransformationID(exactTransname, spoon.rep.loadRepositoryDirectoryTree().findDirectory(entry.getDirectory())) != null;
if (!exists) {
newTrans = new TransMeta(null, exactTransname, entry.arguments);
}
else {
newTrans = spoon.rep.loadTransformation(exactTransname, spoon.rep.loadRepositoryDirectoryTree().findDirectory(entry.getDirectory()), null, true, null); // reads last version
}
copyInternalJobVariables(jobMeta, newTrans);
spoon.setParametersAsVariablesInUI(newTrans, newTrans);
spoon.addTransGraph(newTrans);
newTrans.clearChanged();
TransGraph transGraph = spoon.getActiveTransGraph();
attachActiveTrans(transGraph, newTrans, jobEntryCopy);
spoon.open();
} catch (Throwable e) {
new ErrorDialog(shell, BaseMessages.getString(PKG, "JobGraph.Dialog.ErrorLaunchingSpoonCanNotLoadTransformation.Title"),
BaseMessages.getString(PKG, "JobGraph.Dialog.ErrorLaunchingSpoonCanNotLoadTransformation.Message"), (Exception) e);
}
} else {
try {
// only try to load if the file exists...
if (Const.isEmpty(exactFilename)) {
throw new Exception(BaseMessages.getString(PKG, "JobGraph.Exception.NoFilenameSpecified"));
}
TransMeta launchTransMeta = null;
if (KettleVFS.fileExists(exactFilename)) {
launchTransMeta = new TransMeta(exactFilename);
} else {
launchTransMeta = new TransMeta();
}
launchTransMeta.clearChanged();
launchTransMeta.setFilename(exactFilename);
copyInternalJobVariables(jobMeta, launchTransMeta);
spoon.setParametersAsVariablesInUI(launchTransMeta, launchTransMeta);
spoon.addTransGraph(launchTransMeta);
TransGraph transGraph = spoon.getActiveTransGraph();
attachActiveTrans(transGraph, launchTransMeta, jobEntryCopy);
spoon.open();
} catch (Throwable e) {
new ErrorDialog(shell, BaseMessages.getString(PKG, "JobGraph.Dialog.ErrorLaunchingSpoonCanNotLoadTransformationFromXML.Title"),
BaseMessages.getString(PKG, "JobGraph.Dialog.ErrorLaunchingSpoonCanNotLoadTransformationFromXML.Message"), (Exception) e);
}
}
spoon.applyVariables();
}
/**
* Finds the last active transformation in the running job to the opened transMeta
*
* @param transGraph
* @param jobEntryCopy
*/
private void attachActiveTrans(TransGraph transGraph, TransMeta newTrans, JobEntryCopy jobEntryCopy) {
if (job!=null && transGraph!=null) {
Trans trans = spoon.findActiveTrans(job, jobEntryCopy);
transGraph.setTrans(trans);
if (!transGraph.isExecutionResultsPaneVisible()) {
transGraph.showExecutionResults();
}
transGraph.setControlStates();
}
}
/**
* Finds the last active job in the running job to the openened jobMeta
*
* @param jobGraph
* @param newJob
*/
private void attachActiveJob(JobGraph jobGraph, JobMeta newJobMeta, JobEntryCopy jobEntryCopy) {
if (job!=null && jobGraph!=null) {
Job subJob = spoon.findActiveJob(job, jobEntryCopy);
if (subJob!=null) {
jobGraph.setJob(subJob);
jobGraph.jobGridDelegate.setJobTracker(subJob.getJobTracker());
if (!jobGraph.isExecutionResultsPaneVisible()) {
jobGraph.showExecutionResults();
}
jobGraph.setControlStates();
}
}
}
private synchronized void setJob(Job job) {
this.job = job;
/*
pausing = job.isPaused();
initialized = trans.isInitializing();
running = trans.isRunning();
halted = trans.isStopped();
*/
}
public static void copyInternalJobVariables(JobMeta sourceJobMeta, TransMeta targetTransMeta) {
// Also set some internal JOB variables...
String[] internalVariables = Const.INTERNAL_JOB_VARIABLES;
for (String variableName : internalVariables) {
targetTransMeta.setVariable(variableName, sourceJobMeta.getVariable(variableName));
}
}
public void openJob(JobEntryJob entry, JobEntryCopy jobEntryCopy) {
String exactFilename = jobMeta.environmentSubstitute(entry.getFilename());
String exactJobname = jobMeta.environmentSubstitute(entry.getJobName());
// Load from repository?
if (Const.isEmpty(exactFilename) && !Const.isEmpty(exactJobname)) {
try {
JobMeta newJobMeta = spoon.rep.loadJob(exactJobname, spoon.rep.loadRepositoryDirectoryTree().findDirectory(entry.getDirectory()), null, null); // reads last version
newJobMeta.clearChanged();
spoon.setParametersAsVariablesInUI(newJobMeta, newJobMeta);
spoon.delegates.jobs.addJobGraph(newJobMeta);
JobGraph jobGraph = spoon.getActiveJobGraph();
attachActiveJob(jobGraph, newJobMeta, jobEntryCopy);
} catch (Throwable e) {
new ErrorDialog(shell, BaseMessages.getString(PKG, "JobGraph.Dialog.ErrorLaunchingChefCanNotLoadJob.Title"),
BaseMessages.getString(PKG, "JobGraph.Dialog.ErrorLaunchingChefCanNotLoadJob.Message"), e);
}
} else {
try {
if (Const.isEmpty(exactFilename)) {
throw new Exception(BaseMessages.getString(PKG, "JobGraph.Exception.NoFilenameSpecified"));
}
JobMeta newJobMeta;
if (KettleVFS.fileExists(exactFilename)) {
newJobMeta = new JobMeta(exactFilename, spoon.rep, spoon);
} else {
newJobMeta = new JobMeta();
}
spoon.setParametersAsVariablesInUI(newJobMeta, newJobMeta);
newJobMeta.setFilename(exactFilename);
newJobMeta.clearChanged();
spoon.delegates.jobs.addJobGraph(newJobMeta);
JobGraph jobGraph = spoon.getActiveJobGraph();
attachActiveJob(jobGraph, newJobMeta, jobEntryCopy);
} catch (Throwable e) {
new ErrorDialog(shell, BaseMessages.getString(PKG, "JobGraph.Dialog.ErrorLaunchingChefCanNotLoadJobFromXML.Title"),
BaseMessages.getString(PKG, "JobGraph.Dialog.ErrorLaunchingChefCanNotLoadJobFromXML.Message"), e);
}
}
spoon.applyVariables();
}
public void paintControl(PaintEvent e) {
Point area = getArea();
if (area.x == 0 || area.y == 0)
return; // nothing to do!
Display disp = shell.getDisplay();
Image img = getJobImage(disp, area.x, area.y, magnification);
e.gc.drawImage(img, 0, 0);
img.dispose();
}
public Image getJobImage(Device device, int x, int y, float magnificationFactor) {
GCInterface gc = new SWTGC(device, new Point(x, y), iconsize);
JobPainter jobPainter = new JobPainter( gc,
jobMeta, new Point(x, y), new SwtScrollBar(hori), new SwtScrollBar(vert), hop_candidate, drop_candidate,
selectionRegion,
areaOwners,
mouseOverEntries,
PropsUI.getInstance().getIconSize(),
PropsUI.getInstance().getLineWidth(),
PropsUI.getInstance().getCanvasGridSize(),
PropsUI.getInstance().getShadowSize(),
PropsUI.getInstance().isAntiAliasingEnabled(),
PropsUI.getInstance().getNoteFont().getName(),
PropsUI.getInstance().getNoteFont().getHeight()
);
jobPainter.setMagnification(magnificationFactor);
jobPainter.setEntryLogMap(entryLogMap);
jobPainter.setStartHopEntry(startHopEntry);
jobPainter.setEndHopLocation(endHopLocation);
jobPainter.setEndHopEntry(endHopEntry);
jobPainter.setNoInputEntry(noInputEntry);
if (job!=null) {
jobPainter.setJobEntryResults(job.getJobEntryResults());
} else {
jobPainter.setJobEntryResults(new ArrayList<JobEntryResult>());
}
List<JobEntryCopy> activeJobEntries = new ArrayList<JobEntryCopy>();
if (job!=null) {
activeJobEntries.addAll( job.getActiveJobEntryJobs().keySet() );
activeJobEntries.addAll( job.getActiveJobEntryTransformations().keySet() );
}
jobPainter.setActiveJobEntries(activeJobEntries);
jobPainter.drawJob();
return (Image) gc.getImage();
}
protected Point getOffset() {
Point area = getArea();
Point max = jobMeta.getMaximum();
Point thumb = getThumb(area, max);
return getOffset(thumb, area);
}
protected void newHop() {
List<JobEntryCopy> selection = jobMeta.getSelectedEntries();
if(selection == null || selection.size() < 2){
return;
}
JobEntryCopy fr = selection.get(0);
JobEntryCopy to = selection.get(1);
spoon.newJobHop(jobMeta, fr, to);
}
protected void editEntry(JobEntryCopy je) {
spoon.editJobEntry(jobMeta, je);
}
protected void editNote(NotePadMeta ni) {
NotePadMeta before = (NotePadMeta) ni.clone();
String title = BaseMessages.getString(PKG, "JobGraph.Dialog.EditNote.Title");
NotePadDialog dd = new NotePadDialog(shell, title, ni);
NotePadMeta n = dd.open();
if (n != null)
{
ni.setChanged();
ni.setNote(n.getNote());
ni.setFontName(n.getFontName());
ni.setFontSize(n.getFontSize());
ni.setFontBold(n.isFontBold());
ni.setFontItalic(n.isFontItalic());
// font color
ni.setFontColorRed(n.getFontColorRed());
ni.setFontColorGreen(n.getFontColorGreen());
ni.setFontColorBlue(n.getFontColorBlue());
// background color
ni.setBackGroundColorRed(n.getBackGroundColorRed());
ni.setBackGroundColorGreen(n.getBackGroundColorGreen());
ni.setBackGroundColorBlue(n.getBackGroundColorBlue());
// border color
ni.setBorderColorRed(n.getBorderColorRed());
ni.setBorderColorGreen(n.getBorderColorGreen());
ni.setBorderColorBlue(n.getBorderColorBlue());
ni.setDrawShadow(n.isDrawShadow());
spoon.addUndoChange(jobMeta, new NotePadMeta[] { before }, new NotePadMeta[] { ni }, new int[] { jobMeta
.indexOfNote(ni) });
ni.width = ConstUI.NOTE_MIN_SIZE;
ni.height = ConstUI.NOTE_MIN_SIZE;
spoon.refreshGraph();
}
}
protected void drawArrow(GC gc, int line[]) {
int mx, my;
int x1 = line[0] + offset.x;
int y1 = line[1] + offset.y;
int x2 = line[2] + offset.x;
int y2 = line[3] + offset.y;
int x3;
int y3;
int x4;
int y4;
int a, b, dist;
double factor;
double angle;
//gc.setLineWidth(1);
//WuLine(gc, black, x1, y1, x2, y2);
gc.drawLine(x1, y1, x2, y2);
// What's the distance between the 2 points?
a = Math.abs(x2 - x1);
b = Math.abs(y2 - y1);
dist = (int) Math.sqrt(a * a + b * b);
// determine factor (position of arrow to left side or right side 0-->100%)
if (dist >= 2 * iconsize)
factor = 1.5;
else
factor = 1.2;
// in between 2 points
mx = (int) (x1 + factor * (x2 - x1) / 2);
my = (int) (y1 + factor * (y2 - y1) / 2);
// calculate points for arrowhead
angle = Math.atan2(y2 - y1, x2 - x1) + Math.PI;
x3 = (int) (mx + Math.cos(angle - theta) * size);
y3 = (int) (my + Math.sin(angle - theta) * size);
x4 = (int) (mx + Math.cos(angle + theta) * size);
y4 = (int) (my + Math.sin(angle + theta) * size);
// draw arrowhead
//gc.drawLine(mx, my, x3, y3);
//gc.drawLine(mx, my, x4, y4);
//gc.drawLine( x3, y3, x4, y4 );
Color fore = gc.getForeground();
Color back = gc.getBackground();
gc.setBackground(fore);
gc.fillPolygon(new int[] { mx, my, x3, y3, x4, y4 });
gc.setBackground(back);
}
protected boolean pointOnLine(int x, int y, int line[]) {
int dx, dy;
int pm = HOP_SEL_MARGIN / 2;
boolean retval = false;
for (dx = -pm; dx <= pm && !retval; dx++) {
for (dy = -pm; dy <= pm && !retval; dy++) {
retval = pointOnThinLine(x + dx, y + dy, line);
}
}
return retval;
}
protected boolean pointOnThinLine(int x, int y, int line[]) {
int x1 = line[0];
int y1 = line[1];
int x2 = line[2];
int y2 = line[3];
// Not in the square formed by these 2 points: ignore!
if (!(((x >= x1 && x <= x2) || (x >= x2 && x <= x1)) && ((y >= y1 && y <= y2) || (y >= y2 && y <= y1))))
return false;
double angle_line = Math.atan2(y2 - y1, x2 - x1) + Math.PI;
double angle_point = Math.atan2(y - y1, x - x1) + Math.PI;
// Same angle, or close enough?
if (angle_point >= angle_line - 0.01 && angle_point <= angle_line + 0.01)
return true;
return false;
}
protected SnapAllignDistribute createSnapAllignDistribute() {
List<JobEntryCopy> elements = jobMeta.getSelectedEntries();
int[] indices = jobMeta.getEntryIndexes(elements);
return new SnapAllignDistribute(jobMeta, elements, indices, spoon, this);
}
public void snaptogrid() {
snaptogrid(ConstUI.GRID_SIZE);
}
protected void snaptogrid(int size) {
createSnapAllignDistribute().snaptogrid(size);
}
public void allignleft() {
createSnapAllignDistribute().allignleft();
}
public void allignright() {
createSnapAllignDistribute().allignright();
}
public void alligntop() {
createSnapAllignDistribute().alligntop();
}
public void allignbottom() {
createSnapAllignDistribute().allignbottom();
}
public void distributehorizontal() {
createSnapAllignDistribute().distributehorizontal();
}
public void distributevertical() {
createSnapAllignDistribute().distributevertical();
}
protected void drawRect(GC gc, Rectangle rect) {
if (rect == null)
return;
gc.setLineStyle(SWT.LINE_DASHDOT);
gc.setLineWidth(1);
gc.setForeground(GUIResource.getInstance().getColorDarkGray());
// PDI-2619: SWT on Windows doesn't cater for negative rect.width/height so handle here.
Point s = new Point(rect.x + offset.x, rect.y + offset.y);
if (rect.width < 0) {
s.x = s.x + rect.width;
}
if (rect.height < 0) {
s.y = s.y + rect.height;
}
gc.drawRectangle(s.x, s.y, Math.abs(rect.width), Math.abs(rect.height));
gc.setLineStyle(SWT.LINE_SOLID);
}
protected void detach(JobEntryCopy je) {
JobHopMeta hfrom = jobMeta.findJobHopTo(je);
JobHopMeta hto = jobMeta.findJobHopFrom(je);
if (hfrom != null && hto != null) {
if (jobMeta.findJobHop(hfrom.getFromEntry(), hto.getToEntry()) == null) {
JobHopMeta hnew = new JobHopMeta(hfrom.getFromEntry(), hto.getToEntry());
jobMeta.addJobHop(hnew);
spoon.addUndoNew(jobMeta, new JobHopMeta[] { (JobHopMeta) hnew.clone() }, new int[] { jobMeta
.indexOfJobHop(hnew) });
}
}
if (hfrom != null) {
int fromidx = jobMeta.indexOfJobHop(hfrom);
if (fromidx >= 0) {
jobMeta.removeJobHop(fromidx);
spoon.addUndoDelete(jobMeta, new JobHopMeta[] { hfrom }, new int[] { fromidx });
}
}
if (hto != null) {
int toidx = jobMeta.indexOfJobHop(hto);
if (toidx >= 0) {
jobMeta.removeJobHop(toidx);
spoon.addUndoDelete(jobMeta, new JobHopMeta[] { hto }, new int[] { toidx });
}
}
spoon.refreshTree();
redraw();
}
public void newProps() {
iconsize = spoon.props.getIconSize();
linewidth = spoon.props.getLineWidth();
}
public String toString() {
if (jobMeta==null) {
return Spoon.APP_NAME;
} else {
return jobMeta.getName();
}
}
public EngineMetaInterface getMeta() {
return jobMeta;
}
/**
* @param jobMeta the jobMeta to set
*/
public void setJobMeta(JobMeta jobMeta) {
this.jobMeta = jobMeta;
}
public boolean applyChanges() throws KettleException {
return spoon.saveToFile(jobMeta);
}
public boolean canBeClosed() {
return !jobMeta.hasChanged();
}
public JobMeta getManagedObject() {
return jobMeta;
}
public boolean hasContentChanged() {
return jobMeta.hasChanged();
}
public int showChangedWarning() {
MessageBox mb = new MessageBox(shell, SWT.YES | SWT.NO | SWT.CANCEL | SWT.ICON_WARNING);
mb.setMessage(BaseMessages.getString(PKG, "Spoon.Dialog.FileChangedSaveFirst.Message", spoon.delegates.tabs.makeTabName(jobMeta, true)));//"This model has changed. Do you want to save it?"
mb.setText(BaseMessages.getString(PKG, "Spoon.Dialog.FileChangedSaveFirst.Title"));
return mb.open();
}
public static int showChangedWarning(Shell shell, String name) {
MessageBox mb = new MessageBox(shell, SWT.YES | SWT.NO | SWT.CANCEL | SWT.ICON_WARNING);
mb.setMessage(BaseMessages.getString(PKG, "JobGraph.Dialog.PromptSave.Message", name));
mb.setText(BaseMessages.getString(PKG, "JobGraph.Dialog.PromptSave.Title"));
return mb.open();
}
public static boolean editProperties(JobMeta jobMeta, Spoon spoon, Repository rep, boolean allowDirectoryChange) {
if (jobMeta == null)
return false;
JobDialog jd = new JobDialog(spoon.getShell(), SWT.NONE, jobMeta, rep);
jd.setDirectoryChangeAllowed(allowDirectoryChange);
JobMeta ji = jd.open();
// In this case, load shared objects
if (jd.isSharedObjectsFileChanged()) {
try {
SharedObjects sharedObjects = rep!=null ? rep.readJobMetaSharedObjects(jobMeta) : jobMeta.readSharedObjects();
spoon.sharedObjectsFileMap.put(sharedObjects.getFilename(), sharedObjects);
} catch (Exception e) {
new ErrorDialog(spoon.getShell(), BaseMessages.getString(PKG, "Spoon.Dialog.ErrorReadingSharedObjects.Title"),
BaseMessages.getString(PKG, "Spoon.Dialog.ErrorReadingSharedObjects.Message", spoon.delegates.tabs.makeTabName(jobMeta, true)), e);
}
}
// If we added properties, add them to the variables too, so that they appear in the CTRL-SPACE variable completion.
spoon.setParametersAsVariablesInUI(jobMeta, jobMeta);
if (jd.isSharedObjectsFileChanged() || ji != null) {
spoon.refreshTree();
spoon.delegates.tabs.renameTabs(); // cheap operation, might as will do it anyway
}
spoon.setShellText();
return ji != null;
}
/**
* @return the lastMove
*/
public Point getLastMove() {
return lastMove;
}
/**
* @param lastMove the lastMove to set
*/
public void setLastMove(Point lastMove) {
this.lastMove = lastMove;
}
/**
* Add an extra view to the main composite SashForm
*/
public void addExtraView() {
extraViewComposite = new Composite(sashForm, SWT.NONE);
FormLayout extraCompositeFormLayout = new FormLayout();
extraCompositeFormLayout.marginWidth = 2;
extraCompositeFormLayout.marginHeight = 2;
extraViewComposite.setLayout(extraCompositeFormLayout);
// Put a close and max button to the upper right corner...
closeButton = new Label(extraViewComposite, SWT.NONE);
closeButton.setImage(GUIResource.getInstance().getImageClosePanel());
closeButton.setToolTipText(BaseMessages.getString(PKG, "JobGraph.ExecutionResultsPanel.CloseButton.Tooltip"));
FormData fdClose = new FormData();
fdClose.right = new FormAttachment(100, 0);
fdClose.top = new FormAttachment(0, 0);
closeButton.setLayoutData(fdClose);
closeButton.addMouseListener(new MouseAdapter() {
public void mouseDown(MouseEvent e) {
disposeExtraView();
}
});
minMaxButton = new Label(extraViewComposite, SWT.NONE);
minMaxButton.setImage(GUIResource.getInstance().getImageMaximizePanel());
minMaxButton.setToolTipText(BaseMessages.getString(PKG, "JobGraph.ExecutionResultsPanel.MaxButton.Tooltip"));
FormData fdMinMax = new FormData();
fdMinMax.right = new FormAttachment(closeButton, -Const.MARGIN);
fdMinMax.top = new FormAttachment(0, 0);
minMaxButton.setLayoutData(fdMinMax);
minMaxButton.addMouseListener(new MouseAdapter() {
public void mouseDown(MouseEvent e) {
minMaxExtraView();
}
});
// Add a label at the top: Results
Label wResultsLabel = new Label(extraViewComposite, SWT.LEFT);
wResultsLabel.setFont(GUIResource.getInstance().getFontMediumBold());
wResultsLabel.setBackground(GUIResource.getInstance().getColorLightGray());
wResultsLabel.setText(BaseMessages.getString(PKG, "JobLog.ResultsPanel.NameLabel"));
FormData fdResultsLabel = new FormData();
fdResultsLabel.left = new FormAttachment(0, 0);
fdResultsLabel.right = new FormAttachment(100, 0);
fdResultsLabel.top = new FormAttachment(0, 0);
wResultsLabel.setLayoutData(fdResultsLabel);
// Add a tab folder ...
extraViewTabFolder = new CTabFolder(extraViewComposite, SWT.MULTI);
spoon.props.setLook(extraViewTabFolder, Props.WIDGET_STYLE_TAB);
extraViewTabFolder.addMouseListener(new MouseAdapter() {
@Override
public void mouseDoubleClick(MouseEvent arg0) {
if (sashForm.getMaximizedControl() == null) {
sashForm.setMaximizedControl(extraViewComposite);
} else {
sashForm.setMaximizedControl(null);
}
}
});
FormData fdTabFolder = new FormData();
fdTabFolder.left = new FormAttachment(0, 0);
fdTabFolder.right = new FormAttachment(100, 0);
fdTabFolder.top = new FormAttachment(wResultsLabel, Const.MARGIN);
fdTabFolder.bottom = new FormAttachment(100, 0);
extraViewTabFolder.setLayoutData(fdTabFolder);
sashForm.setWeights(new int[] { 60, 40, });
}
/**
* If the extra tab view at the bottom is empty, we close it.
*/
public void checkEmptyExtraView() {
if (extraViewTabFolder.getItemCount() == 0) {
disposeExtraView();
}
}
private void disposeExtraView() {
extraViewComposite.dispose();
sashForm.layout();
sashForm.setWeights(new int[] { 100, });
XulToolbarbutton button = (XulToolbarbutton) toolbar.getElementById("job-show-results");
button.setTooltiptext(BaseMessages.getString(PKG, "Spoon.Tooltip.ShowExecutionResults"));
ToolItem swtToolItem = (ToolItem) button.getManagedObject();
swtToolItem.setImage(GUIResource.getInstance().getImageShowResults());
}
private void minMaxExtraView() {
// What is the state?
boolean maximized = sashForm.getMaximizedControl() != null;
if (maximized) {
// Minimize
sashForm.setMaximizedControl(null);
minMaxButton.setImage(GUIResource.getInstance().getImageMaximizePanel());
minMaxButton.setToolTipText(BaseMessages.getString(PKG, "JobGraph.ExecutionResultsPanel.MaxButton.Tooltip"));
} else {
// Maximize
sashForm.setMaximizedControl(extraViewComposite);
minMaxButton.setImage(GUIResource.getInstance().getImageMinimizePanel());
minMaxButton.setToolTipText(BaseMessages.getString(PKG, "JobGraph.ExecutionResultsPanel.MinButton.Tooltip"));
}
}
public boolean isExecutionResultsPaneVisible() {
return extraViewComposite != null && !extraViewComposite.isDisposed();
}
public void showExecutionResults() {
if (isExecutionResultsPaneVisible()) {
disposeExtraView();
} else {
addAllTabs();
}
}
public void addAllTabs() {
CTabItem tabItemSelection = null;
if (extraViewTabFolder!=null && !extraViewTabFolder.isDisposed()) {
tabItemSelection = extraViewTabFolder.getSelection();
}
jobHistoryDelegate.addJobHistory();
jobLogDelegate.addJobLog();
jobGridDelegate.addJobGrid();
if (tabItemSelection!=null) {
extraViewTabFolder.setSelection(tabItemSelection);
} else {
extraViewTabFolder.setSelection(jobGridDelegate.getJobGridTab());
}
XulToolbarbutton button = (XulToolbarbutton) toolbar.getElementById("job-show-results");
button.setTooltiptext(BaseMessages.getString(PKG, "Spoon.Tooltip.HideExecutionResults"));
ToolItem swtToolItem = (ToolItem) button.getManagedObject();
swtToolItem.setImage(GUIResource.getInstance().getImageHideResults());
}
public void openFile() {
spoon.openFile();
}
public void saveFile() throws KettleException {
spoon.saveFile();
}
public void saveFileAs() throws KettleException {
spoon.saveFileAs();
}
public void saveXMLFileToVfs() {
spoon.saveXMLFileToVfs();
}
public void printFile() {
spoon.printFile();
}
public void runJob() {
spoon.runFile();
}
public void getSQL() {
spoon.getSQL();
}
public void exploreDatabase() {
spoon.exploreDatabase();
}
public void browseVersionHistory() {
try {
RepositoryRevisionBrowserDialogInterface dialog = RepositoryExplorerDialog.getVersionBrowserDialog(shell, spoon.rep, jobMeta.getName(), jobMeta.getRepositoryDirectory(), jobMeta.getRepositoryElementType());
String versionLabel = dialog.open();
if (versionLabel!=null) {
spoon.loadObjectFromRepository(jobMeta.getName(), jobMeta.getRepositoryElementType(), jobMeta.getRepositoryDirectory(), versionLabel);
}
} catch (Exception e) {
new ErrorDialog(shell, BaseMessages.getString(PKG, "JobGraph.VersionBrowserException.Title"), BaseMessages.getString(PKG, "JobGraph.VersionBrowserException.Message"), e);
}
}
public synchronized void startJob(JobExecutionConfiguration executionConfiguration) throws KettleException {
if (job == null || job.isFinished() && !job.isActive()) // Not running, start the transformation...
{
// Auto save feature...
if (jobMeta.hasChanged()) {
if (spoon.props.getAutoSave()) {
if(log.isDetailed()) log.logDetailed(BaseMessages.getString(PKG, "JobLog.Log.AutoSaveFileBeforeRunning")); //$NON-NLS-1$
System.out.println(BaseMessages.getString(PKG, "JobLog.Log.AutoSaveFileBeforeRunning2")); //$NON-NLS-1$
spoon.saveToFile(jobMeta);
} else {
MessageDialogWithToggle md = new MessageDialogWithToggle(
shell,
BaseMessages.getString(PKG, "JobLog.Dialog.SaveChangedFile.Title"), //$NON-NLS-1$
null,
BaseMessages.getString(PKG, "JobLog.Dialog.SaveChangedFile.Message") + Const.CR + BaseMessages.getString(PKG, "JobLog.Dialog.SaveChangedFile.Message2") + Const.CR, //$NON-NLS-1$ //$NON-NLS-2$
MessageDialog.QUESTION, new String[] {
BaseMessages.getString(PKG, "System.Button.Yes"), BaseMessages.getString(PKG, "System.Button.No") }, //$NON-NLS-1$ //$NON-NLS-2$
0, BaseMessages.getString(PKG, "JobLog.Dialog.SaveChangedFile.Toggle"), //$NON-NLS-1$
spoon.props.getAutoSave());
int answer = md.open();
if ((answer & 0xFF) == 0) {
spoon.saveToFile(jobMeta);
}
spoon.props.setAutoSave(md.getToggleState());
}
}
if (((jobMeta.getName() != null && spoon.rep != null) || // Repository available & name set
(jobMeta.getFilename() != null && spoon.rep == null) // No repository & filename set
)
&& !jobMeta.hasChanged() // Didn't change
) {
if (job == null || (job != null && !job.isActive())) {
try {
// Make sure we clear the log before executing again...
if (executionConfiguration.isClearingLog()) {
jobLogDelegate.clearLog();
}
// Also make sure to clear the old log entries in the central log store & registry
if (job!=null) {
CentralLogStore.discardLines(job.getLogChannelId(), true);
}
JobMeta runJobMeta;
if (spoon.rep!=null) {
runJobMeta = spoon.rep.loadJob(jobMeta.getName(), jobMeta.getRepositoryDirectory(), null, null); // reads last version
} else {
runJobMeta = new JobMeta(jobMeta.getFilename(), null, null);
}
job = new Job(spoon.rep, runJobMeta);
// job = new Job(jobMeta.getName(), jobMeta.getFilename(), null);
// job.open(spoon.rep, jobMeta.getFilename(), jobMeta.getName(), jobMeta.getRepositoryDirectory().getPath(), spoon);
job.getJobMeta().setArguments(jobMeta.getArguments());
job.shareVariablesWith(jobMeta);
job.setInteractive(true);
// Add job entry listeners
job.addJobEntryListener(createRefreshJobEntryListener());
// Set the named parameters
Map<String, String> paramMap = executionConfiguration.getParams();
Set<String> keys = paramMap.keySet();
for ( String key : keys ) {
job.getJobMeta().setParameterValue(key, Const.NVL(paramMap.get(key), ""));
}
job.getJobMeta().activateParameters();
log.logMinimal(BaseMessages.getString(PKG, "JobLog.Log.StartingJob")); //$NON-NLS-1$
job.start();
jobGridDelegate.previousNrItems = -1;
// Link to the new jobTracker!
jobGridDelegate.jobTracker = job.getJobTracker();
// Attach a listener to notify us that the transformation has finished.
job.addJobListener(new JobListener() {
public void jobFinished(Job job) {
JobGraph.this.jobFinished();
}
});
// Show the execution results views
addAllTabs();
} catch (KettleException e) {
new ErrorDialog(
shell,
BaseMessages.getString(PKG, "JobLog.Dialog.CanNotOpenJob.Title"), BaseMessages.getString(PKG, "JobLog.Dialog.CanNotOpenJob.Message"), e); //$NON-NLS-1$ //$NON-NLS-2$
job = null;
}
} else {
MessageBox m = new MessageBox(shell, SWT.OK | SWT.ICON_WARNING);
m.setText(BaseMessages.getString(PKG, "JobLog.Dialog.JobIsAlreadyRunning.Title")); //$NON-NLS-1$
m.setMessage(BaseMessages.getString(PKG, "JobLog.Dialog.JobIsAlreadyRunning.Message")); //$NON-NLS-1$
m.open();
}
} else {
if (jobMeta.hasChanged()) {
MessageBox m = new MessageBox(shell, SWT.OK | SWT.ICON_WARNING);
m.setText(BaseMessages.getString(PKG, "JobLog.Dialog.JobHasChangedSave.Title")); //$NON-NLS-1$
m.setMessage(BaseMessages.getString(PKG, "JobLog.Dialog.JobHasChangedSave.Message")); //$NON-NLS-1$
m.open();
} else if (spoon.rep != null && jobMeta.getName() == null) {
MessageBox m = new MessageBox(shell, SWT.OK | SWT.ICON_WARNING);
m.setText(BaseMessages.getString(PKG, "JobLog.Dialog.PleaseGiveThisJobAName.Title")); //$NON-NLS-1$
m.setMessage(BaseMessages.getString(PKG, "JobLog.Dialog.PleaseGiveThisJobAName.Message")); //$NON-NLS-1$
m.open();
} else {
MessageBox m = new MessageBox(shell, SWT.OK | SWT.ICON_WARNING);
m.setText(BaseMessages.getString(PKG, "JobLog.Dialog.NoFilenameSaveYourJobFirst.Title")); //$NON-NLS-1$
m.setMessage(BaseMessages.getString(PKG, "JobLog.Dialog.NoFilenameSaveYourJobFirst.Message")); //$NON-NLS-1$
m.open();
}
}
setControlStates();
}
}
private JobEntryListener createRefreshJobEntryListener() {
return new JobEntryListener() {
public void beforeExecution(Job job, JobEntryCopy jobEntryCopy, JobEntryInterface jobEntryInterface) {
asyncRedraw();
}
public void afterExecution(Job job, JobEntryCopy jobEntryCopy, JobEntryInterface jobEntryInterface, Result result) {
asyncRedraw();
}
};
}
/**
* This gets called at the very end, when everything is done.
*/
protected void jobFinished() {
// Do a final check to see if it all ended...
if (job != null && job.isInitialized() && job.isFinished()) {
for (RefreshListener listener : refreshListeners)
listener.refreshNeeded();
log.logMinimal(BaseMessages.getString(PKG, "JobLog.Log.JobHasEnded")); //$NON-NLS-1$
}
setControlStates();
}
public synchronized void stopJob() {
if (job != null && job.isActive() && job.isInitialized()) {
job.stopAll();
job.waitUntilFinished(5000); // wait until everything is stopped, maximum 5 seconds...
log.logMinimal(BaseMessages.getString(PKG, "JobLog.Log.JobWasStopped")); //$NON-NLS-1$
}
setControlStates();
}
private boolean controlDisposed(XulToolbarbutton button) {
if (button.getManagedObject() instanceof Widget) {
Widget widget = (Widget) button.getManagedObject();
return widget.isDisposed();
}
return false;
}
public void setControlStates() {
if (getDisplay().isDisposed()) return;
getDisplay().asyncExec(new Runnable() {
public void run() {
// Start/Run button...
boolean running = job!=null && job.isActive();
XulToolbarbutton runButton = (XulToolbarbutton) toolbar.getElementById("job-run");
if (runButton != null && !controlDisposed(runButton)) {
runButton.setDisabled(running);
}
/* TODO add pause button
*
// Pause button...
//
XulToolbarButton pauseButton = toolbar.getButtonById("trans-pause");
if (pauseButton!=null && !controlDisposed(pauseButton))
{
pauseButton.setEnable(running);
pauseButton.setText( pausing ? RESUME_TEXT : PAUSE_TEXT );
pauseButton.setHint( pausing ? BaseMessages.getString(PKG, "Spoon.Tooltip.ResumeTranformation") : BaseMessages.getString(PKG, "Spoon.Tooltip.PauseTranformation"));
}
*/
// Stop button...
XulToolbarbutton stopButton = (XulToolbarbutton) toolbar.getElementById("job-stop");
if (stopButton != null && !controlDisposed(stopButton)) {
stopButton.setDisabled(!running);
}
// version browser button...
XulToolbarbutton versionsButton = (XulToolbarbutton)toolbar.getElementById("browse-versions");
if (versionsButton != null && !controlDisposed(versionsButton)) {
boolean hasRepository = spoon.rep!=null;
boolean enabled = hasRepository && spoon.rep.getRepositoryMeta().getRepositoryCapabilities().supportsRevisions();
versionsButton.setDisabled(!enabled);
}
}
});
}
/**
* @return the refresh listeners
*/
public List<RefreshListener> getRefreshListeners() {
return refreshListeners;
}
/**
* @param refreshListeners the refresh listeners to set
*/
public void setRefreshListeners(List<RefreshListener> refreshListeners) {
this.refreshListeners = refreshListeners;
}
/**
* @param refreshListener the job refresh listener to add
*/
public void addRefreshListener(RefreshListener refreshListener) {
refreshListeners.add(refreshListener);
}
/* (non-Javadoc)
* @see org.pentaho.ui.xul.impl.XulEventHandler#getName()
*/
public String getName() {
// TODO Auto-generated method stub
return "jobgraph";
}
/* (non-Javadoc)
* @see org.pentaho.ui.xul.impl.XulEventHandler#getXulDomContainer()
*/
public XulDomContainer getXulDomContainer() {
return xulDomContainer;
}
/* (non-Javadoc)
* @see org.pentaho.ui.xul.impl.XulEventHandler#setName(java.lang.String)
*/
public void setName(String name) {
// TODO Auto-generated method stub
}
/* (non-Javadoc)
* @see org.pentaho.ui.xul.impl.XulEventHandler#setXulDomContainer(org.pentaho.ui.xul.XulDomContainer)
*/
public void setXulDomContainer(XulDomContainer xulDomContainer) {
this.xulDomContainer = xulDomContainer;
}
public boolean canHandleSave() {
return true;
}
public HasLogChannelInterface getLogChannelProvider() {
return job;
}
// Change of step, connection, hop or note...
public void addUndoPosition(Object obj[], int pos[], Point prev[], Point curr[]) {
addUndoPosition(obj, pos, prev, curr, false);
}
// Change of step, connection, hop or note...
public void addUndoPosition(Object obj[], int pos[], Point prev[], Point curr[], boolean nextAlso) {
// It's better to store the indexes of the objects, not the objects itself!
jobMeta.addUndo(obj, null, pos, prev, curr, TransMeta.TYPE_UNDO_POSITION, nextAlso);
spoon.setUndoMenu(jobMeta);
}
} |
package controller;
import java.io.File;
import utils.StreamFileUtils;
import model.PlayerModel;
import boundary.PlayerApplication;
import boundary.PlayerEndLevelView;
/**
* PlayerEndLevelCtrl handles what occurs at the end of a level.
*
* @author Bailey Sheridan, and Eli Skeggs
*/
public class PlayerEndLevelCtrl implements Runnable {
PlayerApplication app;
PlayerModel model;
boolean isComplete;
public static final File progressfile = PlayerLoadProgressCtrl.progressfile;
public static final File progressdir = PlayerLoadProgressCtrl.progressdir;
/**
* Creates a new PlayerEndLevelCtrl.
*
* @param app
* @param model
*/
public PlayerEndLevelCtrl(PlayerApplication app, PlayerModel model, boolean isComplete) {
this.app = app;
this.model = model;
this.isComplete = isComplete;
}
/**
* Get the message associated with the threshold the user passed.
*
* @return The message for the corresponding score threshold.
*/
protected String getWonMessage() {
int[] thresholds = model.level.rules.scoreThresholds;
if (thresholds.length > 0) {
for (int i = thresholds.length - 1; i > 0; i
if (model.score > thresholds[i] && isComplete) {
return " You got " + (i + 1) + (i == 0 ? " star!" : " stars!");
}
}
if(!isComplete)
return "Didn't complete level objective. :(";
return "You didn't pass the score thresholds.";
}
return "";
}
/**
* Ends the level via pop-up window.
*/
public void endLevel() {
// always set the achieved score, even if we haven't crossed a threshold
model.progress.setAchievedScore(model.levelnum, model.score, isComplete);
// writes progress to file
if (!model.disableProgress) {
if (StreamFileUtils.ensureParent(progressfile)) {
if (!StreamFileUtils.writeStream(progressfile, model.progress)) {
System.err.println("Unable to save progress");
}
} else {
System.err.println("Your progress will not be saved");
}
}
PlayerEndLevelView endView = new PlayerEndLevelView(app, model);
endView.openDialog(getWonMessage());
}
/**
* Allow this to be deferred, calls endLevel.
*/
@Override
public void run() {
endLevel();
}
} |
package com.bkahlert.nebula.dialogs;
import java.awt.MouseInfo;
import java.util.Arrays;
import java.util.List;
import org.eclipse.jface.layout.GridDataFactory;
import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Shell;
import com.bkahlert.nebula.widgets.SimpleIllustratedComposite;
import com.bkahlert.nebula.widgets.SimpleIllustratedComposite.IllustratedText;
public abstract class PopupDialog extends org.eclipse.jface.dialogs.PopupDialog {
private IllustratedText titleIllustratedText = null;
public PopupDialog(Shell parent, int shellStyle, boolean takeFocusOnOpen,
boolean persistSize, boolean persistLocation,
boolean showDialogMenu, boolean showPersistActions,
String titleText, String infoText) {
super(parent, shellStyle, takeFocusOnOpen, persistSize,
persistLocation, showDialogMenu, showPersistActions, titleText,
infoText);
}
public PopupDialog(IllustratedText title, String infoText) {
super(null, INFOPOPUPRESIZE_SHELLSTYLE, false, false, false, false,
false, null, infoText);
this.titleIllustratedText = title;
}
public PopupDialog() {
super(null, SWT.NO_FOCUS | SWT.NO_TRIM | SWT.ON_TOP, false, false,
false, false, false, null, null);
}
@Override
protected Point getInitialLocation(Point initialSize) {
int offset = 5;
int x = MouseInfo.getPointerInfo().getLocation().x - initialSize.x
- offset;
int y = MouseInfo.getPointerInfo().getLocation().y - initialSize.y
- offset;
return new Point(x, y);
}
@Override
protected boolean hasTitleArea() {
return this.titleIllustratedText != null;
}
@Override
protected Control createTitleControl(Composite parent) {
SimpleIllustratedComposite simpleIllustratedComposite = new SimpleIllustratedComposite(
parent, SWT.NONE, this.titleIllustratedText);
simpleIllustratedComposite.setSpacing(3);
GridDataFactory.fillDefaults().align(SWT.FILL, SWT.CENTER)
.grab(true, false).span(1, 1)
.applyTo(simpleIllustratedComposite);
return simpleIllustratedComposite;
}
@Override
protected Color getBackground() {
return super.getBackground();
}
private Composite composite;
@SuppressWarnings({ "rawtypes" })
@Override
protected List getBackgroundColorExclusions() {
return Arrays.asList(this.composite);
}
@Override
protected Control createDialogArea(Composite parent) {
this.composite = new Composite(parent, SWT.NONE);
this.composite.setLayout(new FillLayout());
this.createControls(this.composite);
return this.composite;
}
protected abstract Control createControls(Composite composite);
} |
package com.braintreegateway;
import java.math.BigDecimal;
import com.braintreegateway.Transaction.Type;
import com.braintreegateway.util.Http;
import com.braintreegateway.util.NodeWrapper;
import com.braintreegateway.util.QueryString;
import com.braintreegateway.util.TrUtil;
public class TransactionGateway {
private Http http;
private Configuration configuration;
public TransactionGateway(Http http, Configuration configuration) {
this.http = http;
this.configuration = configuration;
}
/**
* Confirms the transparent redirect request and creates a {@link Transaction} based on the parameters
* submitted with the transparent redirect.
* @param queryString the queryString of the transparent redirect.
* @return a {@link Result}.
*/
public Result<Transaction> confirmTransparentRedirect(String queryString) {
TransparentRedirectRequest trRequest = new TransparentRedirectRequest(configuration, queryString);
NodeWrapper node = http.post("/transactions/all/confirm_transparent_redirect_request", trRequest);
return new Result<Transaction>(node, Transaction.class);
}
/**
* Creates a credit {@link Transaction}.
* @param request the request.
* @return a {@link Result}
*/
public Result<Transaction> credit(TransactionRequest request) {
NodeWrapper response = http.post("/transactions", request.type(Type.CREDIT));
return new Result<Transaction>(response, Transaction.class);
}
/**
* Creates transparent redirect data for a credit.
* @param trData the request.
* @param redirectURL the redirect URL.
* @return a String representing the trData.
*/
public String creditTrData(TransactionRequest trData, String redirectURL) {
return new TrUtil(configuration).buildTrData(trData.type(Type.CREDIT), redirectURL);
}
/**
* Finds a {@link Transaction} by id.
* @param id the id of the {@link Transaction}.
* @return the {@link Transaction} or raises a {@link com.braintreegateway.exceptions.NotFoundException}.
*/
public Transaction find(String id) {
return new Transaction(http.get("/transactions/" + id));
}
/**
* Refunds all or part of a previous sale {@link Transaction}.
* @param id the id of the (sale) {@link Transaction} to refund.
* @return a {@link Result}.
*/
public Result<Transaction> refund(String id) {
NodeWrapper response = http.post("/transactions/" + id + "/refund");
return new Result<Transaction>(response, Transaction.class);
}
public Result<Transaction> refund(String id, BigDecimal amount) {
TransactionRequest request = new TransactionRequest().amount(amount);
NodeWrapper response = http.post("/transactions/" + id + "/refund", request);
return new Result<Transaction>(response, Transaction.class);
}
/**
* Creates a sale {@link Transaction}.
* @param request the request.
* @return a {@link Result}.
*/
public Result<Transaction> sale(TransactionRequest request) {
NodeWrapper response = http.post("/transactions", request.type(Type.SALE));
return new Result<Transaction>(response, Transaction.class);
}
/**
* Creates transparent redirect data for a sale.
* @param trData the request.
* @param redirectURL the redirect URL.
* @return a String representing the trData.
*/
public String saleTrData(TransactionRequest trData, String redirectURL) {
return new TrUtil(configuration).buildTrData(trData.type(Type.SALE), redirectURL);
}
/**
* Finds all Transactions that match the query and returns a {@link ResourceCollection} for paging through them starting at the first page.
* Analogous to "basic search" in the control panel.
* @return a {@link ResourceCollection}.
*/
public ResourceCollection<Transaction> search(String query) {
return search(query, 1);
}
public ResourceCollection<Transaction> search(TransactionSearchRequest searchRequest) {
return this.search(searchRequest, 1);
}
public ResourceCollection<Transaction> search(String query, int pageNumber) {
String queryString = new QueryString().append("q", query).append("page", pageNumber).toString();
NodeWrapper response = http.get("/transactions/all/search?" + queryString);
return new ResourceCollection<Transaction>(new TransactionPager(this, query), response, Transaction.class);
}
public ResourceCollection<Transaction> search(TransactionSearchRequest query, int pageNumber) {
NodeWrapper node = http.post("/transactions/advanced_search?page=" + pageNumber, query);
return new ResourceCollection<Transaction>(new AdvancedTransactionPager(this, query), node, Transaction.class);
}
/**
* Submits the transaction with the given id for settlement.
* @param id of the transaction to submit for settlement.
* @return a {@link Result}.
*/
public Result<Transaction> submitForSettlement(String id) {
return submitForSettlement(id, null);
}
/**
* Submits the transaction with the given id to be settled for the given amount which must be less than or equal to the authorization amount.
* @param id of the transaction to submit for settlement.
* @param amount to settle. must be less than or equal to the authorization amount.
* @return {@link Result}.
*/
public Result<Transaction> submitForSettlement(String id, BigDecimal amount) {
TransactionRequest request = new TransactionRequest().amount(amount);
NodeWrapper response = http.put("/transactions/" + id + "/submit_for_settlement", request);
return new Result<Transaction>(response, Transaction.class);
}
/**
* Returns the transparent redirect URL for creating a {@link Transaction}.
* @return a URL as a String.
*/
public String transparentRedirectURLForCreate() {
return configuration.baseMerchantURL + "/transactions/all/create_via_transparent_redirect_request";
}
/**
* Voids the transaction with the given id.
* @param id of the transaction to void.
* @return {@link Result}.
*/
public Result<Transaction> voidTransaction(String id) {
NodeWrapper response = http.put("/transactions/" + id + "/void");
return new Result<Transaction>(response, Transaction.class);
}
} |
package com.dyz.gameserver.logic;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.context.ConnectAPI;
import com.context.ErrorCode;
import com.context.Rule;
import com.dyz.gameserver.Avatar;
import com.dyz.gameserver.commons.message.ResponseMsg;
import com.dyz.gameserver.manager.RoomManager;
import com.dyz.gameserver.msg.response.ErrorResponse;
import com.dyz.gameserver.msg.response.chi.ChiResponse;
import com.dyz.gameserver.msg.response.chupai.ChuPaiResponse;
import com.dyz.gameserver.msg.response.common.ReturnInfoResponse;
import com.dyz.gameserver.msg.response.common.ReturnOnLineResponse;
import com.dyz.gameserver.msg.response.followBanker.FollowBankerResponse;
import com.dyz.gameserver.msg.response.gang.GangResponse;
import com.dyz.gameserver.msg.response.gang.OtherGangResponse;
import com.dyz.gameserver.msg.response.hu.HuPaiAllResponse;
import com.dyz.gameserver.msg.response.hu.HuPaiResponse;
import com.dyz.gameserver.msg.response.login.BackLoginResponse;
import com.dyz.gameserver.msg.response.login.OtherBackLoginResonse;
import com.dyz.gameserver.msg.response.peng.PengResponse;
import com.dyz.gameserver.msg.response.pickcard.OtherPickCardResponse;
import com.dyz.gameserver.msg.response.pickcard.PickCardResponse;
import com.dyz.gameserver.msg.response.pickcard.PickFlowerCardResponse;
import com.dyz.gameserver.msg.response.roomcard.RoomCardChangerResponse;
import com.dyz.gameserver.pojo.*;
import com.dyz.myBatis.model.*;
import com.dyz.myBatis.services.*;
import com.dyz.persist.util.*;
import java.io.IOException;
import java.text.ParseException;
import java.util.*;
import java.util.Map.Entry;
public class PlayCardsLogic {
private int paiCount;
private int curAvatarIndex;
private int pickAvatarIndex;
private List<Integer> listCard=null;
private List<Avatar> huAvatar = new ArrayList<>();
private List<Avatar> penAvatar = new ArrayList<>();
private List<Avatar> gangAvatar = new ArrayList<>();
private List<Avatar> chiAvatar = new ArrayList<>();
private List<Avatar> qishouHuAvatar = new ArrayList<>();
// List<Integer> mas = new ArrayList<Integer>();
// List<Integer> validMa = new ArrayList<Integer>();
private int nextCardindex = 0;
private int putOffCardPoint;
// private boolean qianghu = false;
private int currentCardPoint = -2;
private List<Avatar> playerList;
// private int huCount=0;
public Avatar bankerAvatar = null;
private RoomVO roomVO;
private boolean hasHu;
//private ResponseMsg responseMsg;
//private Avatar lastAvtar;
private NormalHuPai normalHuPai;
/**
* Stringuuid:1:2
*/
// private String allMas;
// int numb = 1;//
boolean followBanke = true;
int followNumber = 0;
boolean isFollow = false;
boolean hasPull = true;
PlayRecordGameVO playRecordGame;
/**
*
*Integeruuid
*/
//private List<Integer> shakeHandsInfo = new ArrayList<Integer>();
private Map<Integer , ResponseMsg> shakeHandsInfo= new HashMap<Integer,ResponseMsg>();
public void setPickAvatarIndex(int pickAvatarIndex) {
this.pickAvatarIndex = pickAvatarIndex;
}
public Map<Integer , ResponseMsg> getShakeHandsInf() {
return shakeHandsInfo;
}
public void updateShakeHandsInfo(Integer uuid , ResponseMsg msg) {
shakeHandsInfo.put(uuid, msg);
}
// public String getAllMas() {
// return allMas;
public List<Avatar> getPlayerList() {
return playerList;
}
private int theOwner;
public void setCreateRoomRoleId(int value){
theOwner = value;
}
public void setPlayerList(List<Avatar> playerList) {
this.playerList = playerList;
}
public PlayCardsLogic(){
normalHuPai = new NormalHuPai();
}
public void initCard(RoomVO value) {
roomVO = value;
paiCount = 34;
// if(roomVO.getRoomType() == 1){//12345678
// paiCount = 27;
// if(roomVO.getHong()){
// paiCount = 34;
// }else if(roomVO.getRoomType() == 2){
// if(roomVO.isAddWordCard()) {
// paiCount = 34;
// }else{
// paiCount = 27;
// }else if(roomVO.getRoomType() == 3){
// paiCount = 27;
// }else
if(roomVO.isAddFlowerCard()){
paiCount += 8;
}
listCard = new ArrayList<Integer>();
for (int i = 0; i < paiCount; i++) {
for (int k = 0; k < 4; k++) {
if(i < 27) {
listCard.add(i);
}else if(i > 26 && i< 34){
if(roomVO.isAddWordCard())
listCard.add(i);
else{
break;
}
}
else {
listCard.add(i);
break;
}
}
}
for(int i=0;i<playerList.size();i++){
playerList.get(i).avatarVO.setPaiArray(new int[2][paiCount]);
}
shuffleTheCards();
dealingTheCards();
}
public void shuffleTheCards() {
Collections.shuffle(listCard);
Collections.shuffle(listCard);
}
/**
*
* @param avatar
* @param cardIndex
* @param type type""
*/
public boolean checkAvatarIsHuPai(Avatar avatar,int cardIndex,String type){
if(checkHu(avatar,cardIndex)){
return true;
}else{
return false;
}
}
public void pickCard(){
clearAvatar();
pickAvatarIndex = getNextAvatarIndex();
//pickAvatarIndex = nextIndex;
int tempPoint = getNextCardPoint();
if(tempPoint != -1&&tempPoint<34) {
PlayRecordOperation(pickAvatarIndex,tempPoint,2,-1,null,null);
currentCardPoint = tempPoint;
Avatar avatar = playerList.get(pickAvatarIndex);
avatar.avatarVO.setHasMopaiChupai(true);
// avatar.qiangHu = true;
avatar.canHu = true;
// avatar.avatarVO.setHuType(0);//
//avatar.canHu = true;
try {
Thread.sleep(500);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
avatar.getSession().sendMsg(new PickCardResponse(1, tempPoint));
for(int i=0;i<playerList.size();i++){
if(i != pickAvatarIndex){
playerList.get(i).getSession().sendMsg(new OtherPickCardResponse(1,pickAvatarIndex));
}else {
playerList.get(i).gangIndex.clear();
}
}
StringBuffer sb = new StringBuffer();
avatar.putCardInList(tempPoint);
if (avatar.checkSelfGang()) {
gangAvatar.add(avatar);
sb.append("gang");
for (int i : avatar.gangIndex) {
sb.append(":"+i);
}
sb.append(",");
//avatar.gangIndex.clear();//9-18()
}
if(checkAvatarIsHuPai(avatar,100,"mo")){
huAvatar.add(avatar);
sb.append("hu,");
}
if(sb.length()>2){
//System.out.println(sb);
avatar.getSession().sendMsg(new ReturnInfoResponse(1, sb.toString()));
}
}else if(tempPoint != -1&&tempPoint>=34) {
PlayRecordOperation(pickAvatarIndex,tempPoint,2,-1,null,null);
Avatar avatar = playerList.get(pickAvatarIndex);
avatar.putCardInList(tempPoint);
for(int i=0;i<playerList.size();i++){
if(i != pickAvatarIndex){
playerList.get(i).getSession().sendMsg(new PickFlowerCardResponse(1,pickAvatarIndex,tempPoint));
}else {
avatar.getSession().sendMsg(new PickCardResponse(1, tempPoint));
}
}
pickAvatarIndex = getPreAvatarIndex();
pickCard();
return;
}
else{
//System.out.println("");
PlayRecordOperation(pickAvatarIndex,-1,9,-1,null,null);
settlementData("1");
}
}
/**
* (type)/
* @param avatar
*/
public void pickCardAfterGang(Avatar avatar){
int tempPoint = getNextCardPoint();
currentCardPoint = tempPoint;
//System.out.println("!--"+tempPoint);
if(tempPoint != -1) {
//int avatarIndex = playerList.indexOf(avatar); // 2016-8-2
pickAvatarIndex = playerList.indexOf(avatar);
// Avatar avatar = playerList.get(pickAvatarIndex);
for(int i=0;i<playerList.size();i++){
if(i != pickAvatarIndex){
playerList.get(i).getSession().sendMsg(new OtherPickCardResponse(1,pickAvatarIndex));
}else {
playerList.get(i).gangIndex.clear();
playerList.get(i).getSession().sendMsg(new PickCardResponse(1, tempPoint));
playerList.get(i).canHu = true;
}
}
PlayRecordOperation(pickAvatarIndex,currentCardPoint,2,-1,null,null);
StringBuffer sb = new StringBuffer();
avatar.putCardInList(tempPoint);
if (avatar.checkSelfGang()) {
gangAvatar.add(avatar);
sb.append("gang");
for (int i : avatar.gangIndex) {
sb.append(":"+i);
}
sb.append(",");
//avatar.gangIndex.clear();
}
if(checkAvatarIsHuPai(avatar,100,"ganghu")){
huAvatar.add(avatar);
sb.append("hu,");
}
if(sb.length()>2){
//System.out.println(sb);
avatar.getSession().sendMsg(new ReturnInfoResponse(1, sb.toString()));
}
}
else{
//system.out.println("");
PlayRecordOperation(pickAvatarIndex,-1,9,-1,null,null);
settlementData("1");
}
}
/**
*
* @return
*/
public int getNextAvatarIndex(){
int nextIndex = curAvatarIndex + 1;
if(nextIndex >= 4){
nextIndex = 0;
}
return nextIndex;
}
/**
*
* @return
*/
public int getPreAvatarIndex(){
int nextIndex = curAvatarIndex - 1;
if(nextIndex <= 0){
nextIndex = 4;
}
return nextIndex;
}
/**
*
* @param avatar
* @param
*
*/
public void gaveUpAction(Avatar avatar){
if(validateStatus()){
avatar.huAvatarDetailInfo.clear();
//System.out.println(JsonUtilTool.toJson(avatar.getRoomVO()));
if(pickAvatarIndex == playerList.indexOf(avatar)){
// canHu = true
avatar.canHu = true;
clearAvatar();
}else{
clearAvatar();
avatar.canHu = false;
if(huAvatar.size() == 0){
for(Avatar item : gangAvatar){
if (item.gangQuest) {
// avatar.qiangHu = false;
gangCard(item,putOffCardPoint,1);
clearArrayAndSetQuest();
return;
}
}
for(Avatar item : penAvatar) {
if (item.pengQuest) {
pengCard(item, putOffCardPoint);
clearArrayAndSetQuest();
return;
}
}
for(Avatar item : chiAvatar){
if (item.chiQuest) {
CardVO cardVo = new CardVO();
cardVo.setCardPoint(putOffCardPoint);
chiCard(item,cardVo);
clearArrayAndSetQuest();
return;
}
}
}
chuPaiCallBack();
}
}
}
/**
* false;
*/
public void clearArrayAndSetQuest(){
while (gangAvatar.size() >0){
gangAvatar.remove(0).setQuestToFalse();
}
while (penAvatar.size() >0){
penAvatar.remove(0).setQuestToFalse();
}
while (chiAvatar.size() >0){
chiAvatar.remove(0).setQuestToFalse();
}
}
/**
*
* @param avatar
* @param cardPoint
*/
public void putOffCard(Avatar avatar,int cardPoint){
//avatar.gangIndex.clear();//
//System.err.println(""+cardPoint);
// avatar.avatarVO.setHuType(0);//
System.out.println("===="+System.currentTimeMillis());
avatar.avatarVO.updateChupais(cardPoint);
avatar.avatarVO.setHasMopaiChupai(true);
clearAvatar();
putOffCardPoint = cardPoint;
curAvatarIndex = playerList.indexOf(avatar);
PlayRecordOperation(curAvatarIndex,cardPoint,1,-1,null,null);
avatar.pullCardFormList(putOffCardPoint);
for(int i=0;i<playerList.size();i++){
playerList.get(i).gangIndex.clear();
if(i != curAvatarIndex) {
playerList.get(i).getSession().sendMsg(new ChuPaiResponse(1, putOffCardPoint, curAvatarIndex));
} else {
System.out.println(" - " + curAvatarIndex);
if (!roomVO.isYikouxiangCard()
&& !avatar.getbTing()
&& checkSelfTing(avatar)) {
avatar.getSession().sendMsg(new ReturnInfoResponse(1, "canting"));
}
}
}
Avatar ava;
StringBuffer sb;
boolean bf;
for(int i=0;i<playerList.size();i++){
ava = playerList.get(i);
if(ava.getUuId() != avatar.getUuId()) {
bf = false;
sb = new StringBuffer();
if(avatar.getRoomVO().getZiMo() != 3
&& ava.canHu
&& checkAvatarIsHuPai(ava,putOffCardPoint,"chu")){
huAvatar.add(ava);
sb.append("hu,");
}
if (ava.checkGang(putOffCardPoint)) {
gangAvatar.add(ava);
sb.append("gang:"+putOffCardPoint+",");
}
if (ava.checkPeng(putOffCardPoint)) {
penAvatar.add(ava);
sb.append("peng,");
}
if ( roomVO.isCanchi() && ava.checkChi(putOffCardPoint) && getNextAvatarIndex() == i){
chiAvatar.add(ava);
sb.append("chi");
}
if (sb.length()>1) {
if (sb.indexOf("gang") != -1 || sb.indexOf("hu") != -1) {
bf = true;
} else if (!roomVO.isYikouxiangCard() || checkOtherTing(ava, putOffCardPoint)) {
bf = true;
}
if (bf) {
System.out.println(sb);
try {
System.out.println(""+System.currentTimeMillis());
Thread.sleep(200);
System.out.println(""+System.currentTimeMillis());
} catch (InterruptedException e) {
e.printStackTrace();
}
ava.getSession().sendMsg(new ReturnInfoResponse(1, sb.toString()));
} else {
penAvatar.remove(ava);
chiAvatar.remove(ava);
}
}
}
}
System.out.println("===="+System.currentTimeMillis());
chuPaiCallBack();
}
/**
*
* @param avatar
* @param
* @return
*/
public boolean chiCard(Avatar avatar , CardVO cardVo){
boolean flag = false;
int cardIndex = cardVo.getCardPoint();
int onePoint = cardVo.getOnePoint();
int twoPoint = cardVo.getTwoPoint();
if(cardIndex != putOffCardPoint ){
System.out.println(":"+cardIndex+"---"+putOffCardPoint);
}
if(cardIndex < 0){
try {
avatar.getSession().sendMsg(new ErrorResponse(ErrorCode.Error_000019));
} catch (IOException e) {
e.printStackTrace();
}
return false;
}
if(huAvatar.contains(avatar)){
huAvatar.remove(avatar);
}
if(gangAvatar.contains(avatar)){
gangAvatar.remove(avatar);
}
if(penAvatar.contains(avatar)){
penAvatar.remove(avatar);
}
//if((huAvatar.size() == 0 || huAvatar.contains(avatar)) && penAvatar.size() >= 1)) {
if((penAvatar.size() == 0 && huAvatar.size() == 0)||
( huAvatar.contains(avatar) && huAvatar.size() ==1 && penAvatar.size() ==0)||
(penAvatar.contains(avatar) && penAvatar.size() ==1 && huAvatar.size() ==0)||
(huAvatar.contains(avatar) && penAvatar.contains(avatar) && penAvatar.size() ==1 && huAvatar.size() ==1)) {
avatar.avatarVO.setHasMopaiChupai(true);
if(chiAvatar.contains(avatar)){
PlayRecordOperation(playerList.indexOf(avatar),cardIndex,3,-1,null,null);
//chupais
playerList.get(curAvatarIndex).avatarVO.removeLastChupais();
chiAvatar.remove(avatar);
flag = avatar.putCardInList(cardIndex);
avatar.setCardListStatus(cardIndex,1);
//,index
avatar.avatarVO.getHuReturnObjectVO().updateTotalInfo("chi", cardIndex+","+onePoint+","+twoPoint);
//avatar.getResultRelation().put(key, value);
clearArrayAndSetQuest();
for (int i=0;i<playerList.size();i++){
if(playerList.get(i).getUuId() == avatar.getUuId()){
//avatarresultRelation Map
playerList.get(i).putResultRelation(4,cardIndex+","+onePoint+","+twoPoint);
playerList.get(i).avatarVO.getPaiArray()[1][cardIndex]+=4;
playerList.get(i).avatarVO.getPaiArray()[1][onePoint]+=4;
playerList.get(i).avatarVO.getPaiArray()[1][twoPoint]+=4;
}
playerList.get(i).getSession().sendMsg(new ChiResponse(1,cardIndex+","+onePoint+","+twoPoint));
}
// responseMsg = new PengResponse(1,cardIndex,playerList.indexOf(avatar));
// lastAvtar = avatar;
// 2016-8-3
pickAvatarIndex = playerList.indexOf(avatar);
curAvatarIndex = playerList.indexOf(avatar);
currentCardPoint = -2;
}
}else{
if(chiAvatar.size() > 0) {
for (Avatar ava : chiAvatar) {
ava.chiQuest = true;
}
}
}
return flag;
}
/**
*
* @param avatar
* @return
*/
public boolean pengCard(Avatar avatar , int cardIndex){
boolean flag = false;
if(cardIndex != putOffCardPoint ){
System.out.println(":"+cardIndex+"---"+putOffCardPoint);
}
if(cardIndex < 0){
try {
avatar.getSession().sendMsg(new ErrorResponse(ErrorCode.Error_000019));
} catch (IOException e) {
e.printStackTrace();
}
return false;
}
if(huAvatar.contains(avatar)){
huAvatar.remove(avatar);
}
if(gangAvatar.contains(avatar)){
gangAvatar.remove(avatar);
}
chiAvatar.clear();
//if((huAvatar.size() == 0 || huAvatar.contains(avatar)) && penAvatar.size() >= 1)) {
if((penAvatar.size() >= 1 && huAvatar.size() == 0) ||
( huAvatar.contains(avatar) && huAvatar.size() ==1 && penAvatar.size() ==1)) {
avatar.avatarVO.setHasMopaiChupai(true);
if(penAvatar.contains(avatar)){
PlayRecordOperation(playerList.indexOf(avatar),cardIndex,4,-1,null,null);
//chupais
playerList.get(curAvatarIndex).avatarVO.removeLastChupais();
penAvatar.remove(avatar);
flag = avatar.putCardInList(cardIndex);
avatar.setCardListStatus(cardIndex,1);
//,index
avatar.avatarVO.getHuReturnObjectVO().updateTotalInfo("peng", cardIndex+"");
//avatar.getResultRelation().put(key, value);
clearArrayAndSetQuest();
for (int i=0;i<playerList.size();i++){
if(playerList.get(i).getUuId() == avatar.getUuId()){
//avatarresultRelation Map
playerList.get(i).putResultRelation(1,cardIndex+"");
playerList.get(i).avatarVO.getPaiArray()[1][cardIndex]+=1;
}
playerList.get(i).getSession().sendMsg(new PengResponse(1,cardIndex,playerList.indexOf(avatar)));
}
// responseMsg = new PengResponse(1,cardIndex,playerList.indexOf(avatar));
// lastAvtar = avatar;
// 2016-8-3
pickAvatarIndex = playerList.indexOf(avatar);
curAvatarIndex = playerList.indexOf(avatar);
currentCardPoint = -2;
}
}else{
if(penAvatar.size() > 0) {
for (Avatar ava : penAvatar) {
ava.pengQuest = true;
}
}
}
return flag;
}
/**
*
* @param avatar
* @return
*/
public boolean gangCard(Avatar avatar , int cardPoint,int gangType){
boolean flag = false;
int avatarIndex = playerList.indexOf(avatar);
if(huAvatar.contains(avatar)){
huAvatar.remove(avatar);
}
penAvatar.clear();
chiAvatar.clear();
if(gangAvatar.size() > 0) {
if(huAvatar.size() == 0){
avatar.avatarVO.setHasMopaiChupai(true);
if(gangAvatar.contains(avatar)){
gangAvatar.remove(avatar);
String str;
int type;
int score;
String recordType;// 4 5(type)
String endStatisticstype;
int playRecordType;
if(avatar.getUuId() == playerList.get(pickAvatarIndex).getUuId()){
String strs = avatar.getResultRelation().get(1);
if(strs != null && strs.contains(cardPoint+"")){
playRecordType = 3;
avatar.putResultRelation(2,cardPoint+"");
avatar.avatarVO.getPaiArray()[1][cardPoint] = 2;
str = "0:"+cardPoint+":"+Rule.Gang_ming;
type = 0;
score = Rule.scoreMap.get(Rule.Gang_ming);
recordType ="5";
endStatisticstype = "minggang";
}
else{
playRecordType = 2;
avatar.putResultRelation(2,cardPoint+"");
avatar.avatarVO.getPaiArray()[1][cardPoint] = 2;
str = "0:"+cardPoint+":"+Rule.Gang_an;
type = 1;
score = Rule.scoreMap.get(Rule.Gang_an);
recordType ="4";
endStatisticstype = "angang";
}
for (Avatar ava : playerList) {
if(ava.getUuId() == avatar.getUuId()){
avatar.avatarVO.getHuReturnObjectVO().updateGangAndHuInfos(recordType,score*3);
roomVO.updateEndStatistics(ava.getUuId()+"", endStatisticstype, 1);
}
else{
ava.avatarVO.getHuReturnObjectVO().updateGangAndHuInfos(recordType,-1*score);
}
}
flag = true;
}
else{
playRecordType = 1;
avatar.putResultRelation(2,cardPoint+"");
avatar.avatarVO.getPaiArray()[1][cardPoint] = 2;
//chupais
playerList.get(curAvatarIndex).avatarVO.removeLastChupais();
flag = avatar.putCardInList(cardPoint);
score = Rule.scoreMap.get(Rule.Gang_dian);;
recordType = "4";
str = playerList.get(curAvatarIndex).getUuId()+":"+cardPoint+":"+Rule.Gang_dian;
type = 0;
endStatisticstype = "minggang";
playerList.get(curAvatarIndex).avatarVO.getHuReturnObjectVO().updateGangAndHuInfos(recordType, -1*score);
avatar.avatarVO.getHuReturnObjectVO().updateGangAndHuInfos(recordType, score);
roomVO.updateEndStatistics(avatar.getUuId()+"", endStatisticstype, 1);
}
avatar.avatarVO.getHuReturnObjectVO().updateTotalInfo("gang", str);
PlayRecordOperation(avatarIndex,cardPoint,5,playRecordType,null,null);
clearArrayAndSetQuest();
/**
*
* @param avatar
* @return
*/
public boolean huPai(Avatar avatar , int cardIndex,String type){
boolean flag = false;
StringBuffer sb = new StringBuffer();
avatar.getPaiArray()[1][cardIndex] = 3;
int playRecordType = 6;
if(huAvatar.size() > 0) {
if(huAvatar.contains(avatar)){
//if(playerList.get(pickAvatarIndex).getUuId() != avatar.getUuId()){
if(pickAvatarIndex == curAvatarIndex){
int ami = playerList.indexOf(avatar);
int distance = ami - curAvatarIndex;
boolean needWait = false;
if(distance<0)
distance = 4+distance;
for(Avatar canhuAvator:huAvatar){
int curindex = playerList.indexOf(canhuAvator);
int dis = curindex - curAvatarIndex;
if(dis<0)
dis = dis+4;
if(dis<distance)
needWait = true;
}
avatar.putCardInList(cardIndex);
//system.out.println("");
if(avatar.canHu&&!needWait){
huAvatar.remove(avatar);
gangAvatar.clear();
penAvatar.clear();
chiAvatar.clear();;
roomVO.updateEndStatistics(avatar.getUuId()+"", "jiepao", 1);
roomVO.updateEndStatistics(playerList.get(curAvatarIndex).getUuId()+"", "dianpao", 1);
flag = true;
}
else{
//system.out.println("");
avatar.huQuest = true;
return false;
// huAvatar.remove(avatar);
}
calculateScore(avatar , cardIndex,curAvatarIndex);
}
else{
//system.out.println("");
huAvatar.remove(avatar);
gangAvatar.clear();
penAvatar.clear();
chiAvatar.clear();;
roomVO.updateEndStatistics(avatar.getUuId()+"", "zimo", 1);
flag = true;
calculateScore(avatar , cardIndex,-1);
}
hasHu = true;
PlayRecordOperation(playerList.indexOf(avatar),cardIndex,playRecordType,-1,null,null);
}
}
//roomlogicPlayerList
if(avatar.getUuId()==bankerAvatar.getUuId()){
followBanke = true;
followNumber++;
}else{
followBanke = false;
followNumber = 0;
int curbank = playerList.indexOf(bankerAvatar);
curbank++;
if(curbank>=4)
curbank = 0;
bankerAvatar = playerList.get(curbank);
bankerAvatar.avatarVO.setMain(true);
}
RoomManager.getInstance().getRoom(playerList.get(0).getRoomVO().getRoomId()).setPlayerList(playerList);
settlementData("0");
return flag;
}
public void settlementData(String type){
int totalCount = roomVO.getRoundNumber();
int useCount = RoomManager.getInstance().getRoom(roomVO.getRoomId()).getCount();
if(totalCount == (useCount +1) && !type.equals("2")){
// deductRoomCard();//
}
JSONArray array = new JSONArray();
JSONObject json = new JSONObject();
// if(!type.equals("0")){
// allMas = null;
StandingsDetail standingsDetail = new StandingsDetail();
StringBuffer content = new StringBuffer();
StringBuffer score = new StringBuffer();
for (Avatar avatar : playerList) {
HuReturnObjectVO huReturnObjectVO = avatar.avatarVO.getHuReturnObjectVO();
content.append(avatar.avatarVO.getAccount().getNickname()+":"+huReturnObjectVO.getTotalScore()+",");
huReturnObjectVO.setNickname(avatar.avatarVO.getAccount().getNickname());
huReturnObjectVO.setPaiArray(avatar.avatarVO.getPaiArray()[0]);
huReturnObjectVO.setUuid(avatar.getUuId());
array.add(huReturnObjectVO);
roomVO.updateEndStatistics(avatar.getUuId()+"", "scores", huReturnObjectVO.getTotalScore());
score.append(avatar.getUuId()+":"+ roomVO.getEndStatistics().get(avatar.getUuId()+"").get("scores")+",");
avatar.avatarVO.supdateScores(huReturnObjectVO.getTotalScore());
if(avatar.avatarVO.isMain()){
if(!type.equals("0")){
PlayRecordOperation(playerList.indexOf(avatar),-1,8,-1,null,null);
}
else{
PlayRecordOperation(playerList.indexOf(avatar),-1,8,-1,null,HuPaiType.getInstance().getValidMa());
}
}
}
json.put("avatarList", array);
json.put("type", type);
json.put("currentScore", score.toString());
//content
standingsDetail.setContent(content.toString());
try {
standingsDetail.setCreatetime(DateUtil.toChangeDate(new Date(), DateUtil.maskC));
int id = StandingsDetailService.getInstance().saveSelective(standingsDetail);
if(id >0){
RoomLogic roomLogic = RoomManager.getInstance().getRoom(roomVO.getRoomId());
roomLogic.getStandingsDetailsIds().add(standingsDetail.getId());
PlayRecordInitUpdateScore(standingsDetail.getId());
}
else{
System.out.println(""+new Date());
}
} catch (ParseException e) {
e.printStackTrace();
}
int count = 10;
for (Avatar avatar : playerList) {
avatar.getSession().sendMsg(new HuPaiResponse(1,json.toString()));
avatar.overOff = true;
avatar.oneSettlementInfo = json.toString();
avatar.getResultRelation().clear();
avatar.avatarVO.getChupais().clear();
avatar.avatarVO.setCommonCards(0);
avatar.avatarVO.setHasMopaiChupai(false);
// hu ReturnObjectVO
avatar.avatarVO.setHuReturnObjectVO(new HuReturnObjectVO());
count = RoomManager.getInstance().getRoom(avatar.getRoomVO().getRoomId()).getCount();
}
if(count <= 0){
Standings standings = new Standings();
StringBuffer sb = new StringBuffer();
//standings.setContent(content);
Map<String, Map<String, Integer>> endStatistics = roomVO.getEndStatistics();
Map<String,Integer> map = new HashMap<String, Integer>();
Set<Entry<String, Map<String, Integer>>> set= endStatistics.entrySet();
JSONObject js = new JSONObject();
List<FinalGameEndItemVo> list = new ArrayList<FinalGameEndItemVo>();
FinalGameEndItemVo obj;
for (Entry<String, Map<String, Integer>> param : set) {
obj = new FinalGameEndItemVo();
obj.setUuid(Integer.parseInt(param.getKey()));
sb.append(AccountService.getInstance().selectByUUid(Integer.parseInt(param.getKey())).getNickname());
map = param.getValue();
for (Entry<String, Integer> entry : map.entrySet()) {
switch (entry.getKey()) {
case "zimo":
obj.setZimo(entry.getValue());
break;
case "jiepao":
obj.setJiepao(entry.getValue());
break;
case "dianpao":
obj.setDianpao(entry.getValue());
break;
case "minggang":
obj.setMinggang(entry.getValue());
break;
case "angang":
obj.setAngang(entry.getValue());
break;
case "scores":
obj.setScores(entry.getValue());
sb.append(":"+entry.getValue()+",");
break;
default:
break;
}
}
list.add(obj);
}
js.put("totalInfo", list);
js.put("theowner",theOwner);
//system.out.println("=="+js.toJSONString());
standings.setContent(sb.toString());
try {
standings.setCreatetime(DateUtil.toChangeDate(new Date(), DateUtil.maskC));
standings.setRoomid(roomVO.getId());
int i = StandingsService.getInstance().saveSelective(standings);
if(i> 0){
StandingsRelation standingsRelation;
List<Integer> standingsDetailsIds =RoomManager.getInstance().getRoom(roomVO.getRoomId()).getStandingsDetailsIds();
for (Integer standingsDetailsId : standingsDetailsIds) {
standingsRelation = new StandingsRelation();
standingsRelation.setStandingsId(standings.getId());
standingsRelation.setStandingsdetailId(standingsDetailsId);
StandingsRelationService.getInstance().saveSelective(standingsRelation);
}
StandingsAccountRelation standingsAccountRelation;
for (Avatar avatar : playerList) {
standingsAccountRelation = new StandingsAccountRelation();
standingsAccountRelation.setStandingsId(standings.getId());
standingsAccountRelation.setAccountId(avatar.avatarVO.getAccount().getId());
StandingsAccountRelationService.getInstance().saveSelective(standingsAccountRelation);
}
}
System.out.println(""+i);
} catch (ParseException e) {
e.printStackTrace();
}
for (Avatar avatar : playerList) {
avatar.getSession().sendMsg(new HuPaiAllResponse(1,js.toString()));
}
RoomManager.getInstance().getRoom(roomVO.getRoomId()).destoryRoomLogic();
}
else{
for (Avatar avatar : playerList) {
avatar.avatarVO.setIsReady(false);
}
}
}
/**
*
* @param
*
*/
private void chuPaiCallBack(){
System.out.println("===="+System.currentTimeMillis());
if(!hasHu && checkMsgAndSend()){
pickCard();
}
System.out.println("===="+System.currentTimeMillis());
}
/**
*
* @return
*/
private boolean checkMsgAndSend(){
if(huAvatar.size() > 0){
return false;
}
if(gangAvatar.size() >0){
return false;
}
if(penAvatar.size()>0){
return false;
}
if(chiAvatar.size()>0){
return false;
}
return true;
}
private void dealingTheCards() {
nextCardindex = 0;
bankerAvatar = null;
Avatar av;
for (int i = 0; i < 13; i++) {
for (int k = 0; k < playerList.size(); k++) {
av = playerList.get(k);
if (bankerAvatar == null) {
if (av.avatarVO.isMain()) {
bankerAvatar = av;
}
}
int curCard = listCard.get(nextCardindex);
av.putCardInList(curCard);
while(curCard>33){
setFlowerCardOwnerInfo(av, curCard);
nextCardindex++;
curCard = listCard.get(nextCardindex);
av.putCardInList(curCard);
}
av.oneSettlementInfo = "";
av.overOff = false;
nextCardindex++;
}
}
int curCard = listCard.get(nextCardindex);
bankerAvatar.putCardInList(curCard);
while(curCard>33){
setFlowerCardOwnerInfo(bankerAvatar, curCard);
nextCardindex++;
curCard = listCard.get(nextCardindex);
bankerAvatar.putCardInList(curCard);
}
nextCardindex++;
if(checkHu(bankerAvatar,-1)){
huAvatar.add(bankerAvatar);
pickAvatarIndex = 0;
bankerAvatar.getSession().sendMsg(new HuPaiResponse(1,"hu,"));
bankerAvatar.huAvatarDetailInfo.add(listCard.get(nextCardindex-1)+":"+0);
}
if(bankerAvatar.checkSelfGang()){
gangAvatar.add(bankerAvatar);
StringBuffer sb = new StringBuffer();
sb.append("gang");
for (int i : bankerAvatar.gangIndex) {
sb.append(":"+i);
}
sb.append(",");
bankerAvatar.getSession().sendMsg(new ReturnInfoResponse(1, sb.toString()));
// bankerAvatar.huAvatarDetailInfo.add(bankerAvatar.gangIndex.get(0)+":"+2);
//bankerAvatar.gangIndex.clear();
}
PlayRecordInit();
}
public void PlayRecordInit(){
playRecordGame = new PlayRecordGameVO();
RoomVO roomVo = roomVO.clone();
roomVo.setEndStatistics(new HashMap<String, Map<String,Integer>>());
roomVo.setPlayerList(new ArrayList<AvatarVO>());
playRecordGame.roomvo = roomVo;
PlayRecordItemVO playRecordItemVO;
Account account;
StringBuffer sb;
for (int i = 0; i < playerList.size(); i++) {
playRecordItemVO = new PlayRecordItemVO();
account = playerList.get(i).avatarVO.getAccount();
playRecordItemVO.setAccountIndex(i);
playRecordItemVO.setAccountName(account.getNickname());
sb = new StringBuffer();
int [] str = playerList.get(i).getPaiArray()[0];
for (int j = 0; j < str.length; j++) {
sb.append(str[j]+",");
}
System.out.println(account.getUuid()+":"+sb.substring(0,sb.length()-1));
playRecordItemVO.setCardList(sb.substring(0,sb.length()-1));
playRecordItemVO.setHeadIcon(account.getHeadicon());
playRecordItemVO.setSex(account.getSex());
playRecordItemVO.setGameRound(roomVO.getCurrentRound());
playRecordItemVO.setUuid(account.getUuid());
playRecordGame.playerItems.add(playRecordItemVO);
}
}
/**
*
*
* @param curAvatarIndex
* @param cardIndex
* @param type 123456(/),7,8,9:.....
* @param gangType type -1
* @param ma null
*/
public void PlayRecordOperation(Integer curAvatarIndex , Integer cardIndex,Integer type,Integer gangType,String ma,List<Integer> valideMa){
//System.out.println(""+type);
PlayBehaviedVO behaviedvo = new PlayBehaviedVO();
behaviedvo.setAccountindex_id(curAvatarIndex);
behaviedvo.setCardIndex(cardIndex+"");
behaviedvo.setRecordindex(playRecordGame.behavieList.size());
behaviedvo.setType(type);
behaviedvo.setGangType(gangType);
if(StringUtil.isNotEmpty(ma)){
behaviedvo.setMa(ma);
behaviedvo.setValideMa(valideMa);
}
playRecordGame.behavieList.add(behaviedvo);
}
/**
*
* @param standingsDetailId id
*/
public void PlayRecordInitUpdateScore(int standingsDetailId){
if(!playRecordGame.playerItems.isEmpty()){
for (int i = 0; i < playerList.size(); i++) {
playRecordGame.playerItems.get(i).setSocre(playerList.get(i).avatarVO.getScores());
}
//playRecordGame.standingsDetailId = standingsDetailId;
//String playRecordContent = JsonUtilTool.toJson(playRecordGame);
String playRecordContent = JSONObject.toJSONString(playRecordGame);
//System.out.println(playRecordContent);
PlayRecord playRecord = new PlayRecord();
playRecord.setPlayrecord(playRecordContent);
playRecord.setStandingsdetailId(standingsDetailId);
PlayRecordService.getInstance().saveSelective(playRecord);
playRecordGame = new PlayRecordGameVO();
}
}
/**
* ,-1
* @return
*/
public int getNextCardPoint(){
nextCardindex++;
if(nextCardindex<listCard.size()){
return listCard.get(nextCardindex);
}
return -1;
}
private void checkQiShouFu(){
for(int i=0;i<playerList.size();i++){
if(qiShouFu(playerList.get(i))){
qishouHuAvatar.add(playerList.get(i));
}
}
}
/**
*
* @return
*/
public boolean qiShouFu(Avatar avatar){
/**
*
1 pai[i] == 4
2 2 5 8
3
4 2
*/
boolean flag = false;
int[] pai= avatar.avatarVO.getPaiArray()[0];
boolean flagWan = true;
boolean flagTiao= true;
boolean flagTong = true;
int threeNum = 0;
boolean dasixi = false;
boolean banbanhu = false;
boolean quyise = false;
boolean liuliushun = false;
for (int i =0 ; i< pai.length ; i++) {
if(pai[i] == 4){
dasixi = true;
private void cleanPlayListCardData(){
for(int i=0;i<playerList.size();i++){
playerList.get(i).cleanPaiData();
}
}
private boolean checkHu(Avatar avatar,Integer cardIndex){
// System.out.println(avatar.avatarVO.getAccount().getOpenid() + "checkhu - begin" + cardIndex);
boolean flag = false;
if(cardIndex!=-1&&cardIndex!=100)
avatar.putCardInList(cardIndex);
int [][] paiList = avatar.getPaiArray();
flag = flag || checkSevenDouble(paiList.clone()) > 0;
flag = flag || checkThirteen(paiList.clone());
flag = flag || normalHuPai.checkHu(paiList.clone());
if(cardIndex!=-1&&cardIndex!=100)
avatar.pullCardFormList(cardIndex);
// System.out.println(avatar.avatarVO.getAccount().getOpenid() + "checkhu - end -" + flag);
return flag;
}
private Map<String,Integer> checkHu2(Avatar avatar,Integer cardIndex){
Map<String,Integer> result = new HashMap<String,Integer>();
int [][] paiList = avatar.getPaiArray();
int isSeven = checkSevenDouble(paiList.clone());
if(isSeven == 0){
//System.out.println("");
if(checkThirteen(paiList.clone())){
result.put("Hu", 1);
result.put(Rule.Hu_shisanyao, 1);
}else{
if(normalHuPai.checkHu(paiList.clone())){
result.put("Hu", 1);
}else{
result.put("Hu", 0);
}
}
}else if(isSeven ==1){
result.put("Hu", 1);
result.put(Rule.Hu_qxd, 1);
}else{
result.put("Hu", 1);
result.put(Rule.Hu_haohuaqxd, 1);
}
if(result.get("Hu")==1){
int i = checkQys(paiList.clone());
if(i==1)
result.put(Rule.Hu_qingyise, 1);
if(i==2)
result.put(Rule.Hu_hunyise, 1);
if(checkLong(paiList.clone()))
result.put(Rule.Hu_yitiaolong, 1);
int quemen = checkQuemen(paiList.clone());
if(quemen>0)
result.put(Rule.Hu_quemen, quemen);
if(checkGouzhang(paiList.clone()))
result.put(Rule.Hu_gouzhang, 1);
if(cardIndex==4&&checkKan5(paiList.clone()))
result.put(Rule.Hu_kanwuwan, 1);
if(checkBkd(paiList.clone(),cardIndex))
result.put(Rule.Hu_biankandiao, 1);
if(checkMenqing(paiList.clone(),avatar))
result.put(Rule.Hu_menqing, 1);
if(checkPengPeng(paiList.clone(),avatar))
result.put(Rule.Hu_pengpeng, 1);
int flowers = checkFlower(paiList.clone(),avatar);
if(flowers>0)
result.put(Rule.CaiShen, flowers);
return result;
}
else
return null;
}
private int checkFlower(int[][] paiList,Avatar avatar){
int[] pai =GlobalUtil.CloneIntList(paiList[0]);
int indexMain = 0;
for(Avatar avator:playerList){
if(avator.avatarVO.isMain()){
indexMain = playerList.indexOf(avator);
break;
}
}
int indexCur = playerList.indexOf(avatar);
int dis = indexCur - indexMain;
if(dis<0)
dis = dis+4;
int flag = 1+dis;
int count = 0;
for(int i=27;i<pai.length;i++){
if(i>33&&pai[i]==flag){
count++;
}
}
return count;
}
private boolean checkPengPeng(int[][] paiList,Avatar avatar){
boolean result = true;
int[] pai =GlobalUtil.CloneIntList(paiList[0]);
int jiang = 0;
for(int i=0;i<pai.length;i++){
if(i<34&&pai[i]==2){
jiang++;
if(jiang>1)
return false;
}else if(i<34&&(pai[i]>=3||pai[i]==0)){
continue;
}else{
return false;
}
}
return result;
}
private boolean checkMenqing(int[][] paiList,Avatar avatar){
boolean result = true;
int[] pai2 = GlobalUtil.CloneIntList(paiList[1]);
for(int i=0;i<pai2.length;i++){
if((pai2[i]==1||pai2[i]==4||pai2[i]==5||(pai2[i]%4==0&&pai2[i]/4>0))&&i<34){
result = false;
return result;
}
}
List mingang =avatar.avatarVO.getHuReturnObjectVO().getGangAndHuInfos().get("5");
if(mingang!=null&&mingang.size()>0){
result = false;
return result;
}
return result;
}
private boolean checkBkd(int[][] paiList,Integer cardIndex){
boolean result = false;
int[] pai =GlobalUtil.CloneIntList(paiList[0]);
int flag = cardIndex/9;
if(cardIndex-2>=flag*9&&pai[cardIndex-1]>0&&pai[cardIndex-2]>0){
pai[cardIndex]
pai[cardIndex-1]
pai[cardIndex-2]
if(normalHuPai.isHuPai(pai))
return true;
}else if(cardIndex+2<(flag+1)*9&&pai[cardIndex+1]>0&&pai[cardIndex+2]>0){
pai[cardIndex]
pai[cardIndex+1]
pai[cardIndex+2]
if(normalHuPai.isHuPai(pai))
return true;
}
if(cardIndex-1>=flag*9&&cardIndex+1<(flag+1)*9&&pai[cardIndex+1]>0&&pai[cardIndex-1]>0){
pai[cardIndex]
pai[cardIndex+1]
pai[cardIndex-1]
if(normalHuPai.isHuPai(pai))
return true;
}
if(pai[cardIndex]>=2){
pai[cardIndex]-=2;
normalHuPai.setJIANG(1);
if(normalHuPai.isHuPai(pai))
return true;
}
return result;
}
private boolean checkKan5(int[][] paiList){
boolean result = false;
int[] pai =GlobalUtil.CloneIntList(paiList[0]);
if(pai[3] >= 1 && pai[5] >= 1){
pai[3]
pai[4]
pai[5]
if(normalHuPai.isHuPai(pai))
return true;
}
if(pai[4] >= 2){
pai[4] -=2 ;
normalHuPai.setJIANG(1);
if(normalHuPai.isHuPai(pai)){
normalHuPai.setJIANG(0);
return true;
}
normalHuPai.setJIANG(0);
}
return result;
}
private boolean checkGouzhang(int[][] paiList){
boolean result = false;
int flag=0;
for(int i=0;i<27;i++){
if(paiList[0][i]>0){
flag+=paiList[0][i];
}
if(i%9==8&&flag>=8){
return true;
}else{
flag = 0;
continue;
}
}
return result;
}
private int checkQuemen(int[][] paiList){
// boolean result = true;
int result = 3;
for(int i=0;i<9;i++){
if(paiList[0][i]>0){
result
break;
}
}
// if(!result)
for(int i=9;i<18;i++){
if(paiList[0][i]>0){
result
break;
}
}
// else{
// return true;
// if(!result)
for(int i=18;i<27;i++){
if(paiList[0][i]>0){
result
break;
}
}
// else{
// return true;
return result;
}
private boolean checkLong(int[][] paiList){
boolean result = true;
for(int i=0;i<9;i++){
if(paiList[0][i]==0){
result = false;
break;
}
}
if(!result){
result = true;
for(int i=9;i<18;i++){
if(paiList[0][i]==0){
result = false;
break;
}
}
}else{
return true;
}
if(!result){
result = true;
for(int i=18;i<27;i++){
if(paiList[0][i]==0){
result = false;
break;
}
}
}else{
return true;
}
return result;
}
private int checkQys(int[][] paiList){//120
int flag=-1;
int hunflag = -1;
int result = 1;
for(int i=0;i<paiList[0].length;i++){
int curflag = i/9;
if(paiList[0][i]>=1&&i<34){
if(flag==-1){
flag = curflag;
continue;
}else if(flag!=-1&&flag!=curflag){
if(i>26&&hunflag==-1){
hunflag = curflag;
result = 2;
continue;
}else if(i>26&&hunflag!=-1&&hunflag==curflag){
continue;
}else{
return 0;
}
}else{
continue;
}
}
}
return result;
}
/**
*
* @param paiList
* @return
*/
public int[] cleanGangAndPeng(int [] paiList ,Avatar avatar){
String str;
String strs[];
int cardIndex;
if((str =avatar.getResultRelation().get(1)) != null){
strs = str.split(",");
for (String string : strs) {
cardIndex = Integer.parseInt(string.split(":")[1]);
if(paiList[cardIndex] >=3){
paiList[cardIndex] = paiList[cardIndex] -3;
}
else{
//system.out.println("!");
}
}
}
if(avatar.getResultRelation().get(2) != null){
strs = str.split(",");
for (String string : strs) {
cardIndex = Integer.parseInt(string.split(":")[1]);
if(paiList[cardIndex] ==4){
paiList[cardIndex] = 0;
}
else{
//system.out.println("!");
}
}
}
return paiList;
}
/**
*
* @param paiList
* @return
*/
String getString(int[] paiList){
String result = "int string = ";
for(int i=0;i<paiList.length;i++){
result += paiList[i];
}
return result;
}
/**
*
* @param paiList
* @return
*/
private final static int[] idxs = {0, 8, 9, 17, 18, 26, 27, 28, 29, 30, 31, 32, 33};
public boolean checkThirteen(int[][] paiList){
boolean rv = true;
int i = 0;
while (rv && i < idxs.length) {
rv = paiList[0][idxs[i++]] >= 1;
}
return rv;
}
/**
*
* @param paiList
* @return 0-1-2-
*/
public int checkSevenDouble(int[][] paiList){
int result = 1;
for(int i=0;i<paiList[0].length&&i<34;i++){
if(paiList[0][i] != 0){
if(paiList[0][i] != 2 && paiList[0][i] != 4){
return 0;
}else{
if(paiList[1][i] != 0){
return 0;
}else {
if (paiList[0][i] == 4) {
result = 2;
}
}
}
}
}
return result;
}
/**
*
* listuuid
* list
*
* @param avatar
*/
public void shakeHandsMsg(Avatar avatar){
shakeHandsInfo.remove(avatar.getUuId());
}
/**
*
* @param avatar
*/
public void returnBackAction(Avatar avatar){
RoomVO room = roomVO.clone();
List<AvatarVO> lists = new ArrayList<AvatarVO>();
for (int i = 0; i < playerList.size(); i++) {
if(playerList.get(i).getUuId() != avatar.getUuId()){
playerList.get(i).getSession().sendMsg(new OtherBackLoginResonse(1, avatar.getUuId()+""));
}
lists.add(playerList.get(i).avatarVO);
}
AvatarVO avatarVo = null ;
List<AvatarVO> playerLists = new ArrayList<AvatarVO>();
for (int j = 0; j < lists.size(); j++) {
int paiCount = 0;
avatarVo = lists.get(j);
if(avatarVo.getAccount().getUuid() != avatar.getUuId()){
for (int k = 0; k < avatarVo.getPaiArray()[0].length; k++) {
if(avatarVo.getPaiArray()[0][k] != 0 && avatarVo.getPaiArray()[1][k] == 0){
paiCount= paiCount +avatarVo.getPaiArray()[0][k];
//avatarVo.getPaiArray()[0][k] = 0;
}
}
avatarVo.setCommonCards(paiCount);
playerLists.add(avatarVo);
}
else{
playerLists.add(avatarVo);
}
}
if(playerList.size() == 3){
playerList.add(avatar);
}
if(playerLists.size() == 3){
playerLists.add(avatar.avatarVO);
}
/*else{
for (int i = 0; i < playerLists.size(); i++) {
if(playerLists.get(i).getAccount().getUuid() == avatar.getUuId() ){
playerLists.remove(i);
playerLists.add(avatar.avatarVO);;
}
}
}*/
room.setPlayerList(playerLists);
avatar.getSession().sendMsg(new BackLoginResponse(1, room));
//lastAvtar.getSession().sendMsg(responseMsg);
}
/**
*
* @param avatar
*/
public void LoginReturnInfo(Avatar avatar){
//json
JSONObject json = new JSONObject();
StringBuffer sb = new StringBuffer();
if(huAvatar.contains(avatar)){
if(pickAvatarIndex != curAvatarIndex){
json.put("currentCardPoint", currentCardPoint);
json.put("curAvatarIndex", curAvatarIndex);
json.put("putOffCardPoint", putOffCardPoint);
}
else{
json.put("curAvatarIndex", curAvatarIndex);
json.put("putOffCardPoint", putOffCardPoint);
}
// if(qianghu){
// sb.append("qianghu:"+putOffCardPoint+",");
// //system.out.println("");
// else{
sb.append("hu,");
//system.out.println("");
}
if(penAvatar.contains(avatar)){
sb.append("peng,");
json.put("curAvatarIndex", curAvatarIndex);
json.put("putOffCardPoint", putOffCardPoint);
//system.out.println("");
}
if(gangAvatar.contains(avatar)){
StringBuffer gangCardIndex = new StringBuffer();
List<Integer> gangIndexs = avatar.gangIndex;
for (int i = 0; i < gangIndexs.size(); i++) {
gangCardIndex.append(":"+gangIndexs.get(i));
}
if(avatar.getUuId() == playerList.get(pickAvatarIndex).getUuId()){
sb.append("gang"+gangCardIndex.toString()+",");
json.put("currentCardPoint", currentCardPoint);
json.put("curAvatarIndex", curAvatarIndex);
json.put("putOffCardPoint", putOffCardPoint);
//system.out.println("");
}
else{
json.put("curAvatarIndex", curAvatarIndex);
json.put("putOffCardPoint", putOffCardPoint);
sb.append("gang"+gangCardIndex.toString()+",");
//system.out.println("");
}
}
if(sb.length()>1){
////system.out.println(sb);
int roundNum = RoomManager.getInstance().getRoom(avatar.getRoomVO().getRoomId()).getCount();
json.put("gameRound", roundNum);
json.put("surplusCards", listCard.size() - nextCardindex);
//System.out.println(json.toString());
avatar.getSession().sendMsg(new ReturnOnLineResponse(1, json.toString()));
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
//System.out.println(sb);
avatar.getSession().sendMsg(new ReturnInfoResponse(1, sb.toString()));
}
else{
if(avatar.getUuId() == playerList.get(pickAvatarIndex).getUuId()){
//system.out.println("");
json.put("currentCardPoint", currentCardPoint);//currentCardPoint = -2
json.put("pickAvatarIndex", pickAvatarIndex);
json.put("curAvatarIndex", curAvatarIndex);
json.put("putOffCardPoint", putOffCardPoint);
}
else{
json.put("curAvatarIndex", curAvatarIndex);
json.put("pickAvatarIndex", pickAvatarIndex);
json.put("putOffCardPoint", putOffCardPoint);
}
int roundNum = RoomManager.getInstance().getRoom(avatar.getRoomVO().getRoomId()).getCount();
json.put("gameRound", roundNum);
json.put("surplusCards", listCard.size() - nextCardindex);
//System.out.println(json.toString());
avatar.getSession().sendMsg(new ReturnOnLineResponse(1, json.toString()));
}
}
public void clearAvatar(){
huAvatar.clear();
penAvatar.clear();
gangAvatar.clear();
chiAvatar.clear();
qishouHuAvatar.clear();
}
public void clearAvatarExceptHu(){
penAvatar.clear();
gangAvatar.clear();
chiAvatar.clear();
qishouHuAvatar.clear();
}
public boolean validateStatus(){
if(huAvatar.size() > 0 || penAvatar.size()>0 || gangAvatar.size()>0 || chiAvatar.size()>0 ||qishouHuAvatar.size()>0){
return true;
}
else{
return false;
}
}
public void deductRoomCard(){
int currentCard = 0;
if(roomVO.getRoundNumber() == ConnectAPI.PLAYERS_NUMBER){
currentCard = -1;
}
else{
currentCard = 0 - roomVO.getRoundNumber()/8;
}
Avatar zhuangAvatar = playerList.get(0);
zhuangAvatar.updateRoomCard(currentCard);
int roomCard = zhuangAvatar.avatarVO.getAccount().getRoomcard();
zhuangAvatar.getSession().sendMsg(new RoomCardChangerResponse(1,roomCard));
}
private boolean checkSelfTing(Avatar avator) {
System.out.println(""+System.currentTimeMillis());
boolean rv = false;
for(int i = 0; i < 34; ++i) {
if(checkHu(avator,i)){
return true;
}
else{
continue;
}
}
System.out.println(""+System.currentTimeMillis());
return rv;
}
private boolean checkOtherTing(Avatar av, Integer cardIndex) {
System.out.println(""+System.currentTimeMillis());
boolean rv = false;
int[][] paiList = av.getPaiArray();
paiList[0][cardIndex]++;
for(int i = 0; i < 34; ++i) {
if (paiList[0][i] == 0 || i == cardIndex) {
continue;
}
paiList[0][i]
rv = rv || checkSelfTing(av);
paiList[0][i]++;
if (rv) {
break;
}
}
paiList[0][cardIndex]
System.out.println(""+System.currentTimeMillis());
return rv;
}
//dist0 123
private int getDistToMain(Avatar avatar) {
int indexMain = 0;
for(Avatar av:playerList){
if(av.avatarVO.isMain()){
indexMain = playerList.indexOf(av);
break;
}
}
int indexCur = playerList.indexOf(avatar);
int dis = indexCur - indexMain;
if(dis<0)
dis = dis+4;
return dis;
}
private void setFlowerCardOwnerInfo(Avatar av, int curCard) {
for (int j = 0; j < playerList.size(); ++j) {
playerList.get(j).getPaiArray()[0][curCard] = getDistToMain(av) + 1;
}
}
} |
package com.ecyrd.jspwiki.filters;
import java.io.InputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.File;
import java.util.Properties;
import java.util.Iterator;
import java.util.List;
import org.xml.sax.*;
import org.apache.log4j.Logger;
import com.ecyrd.jspwiki.WikiContext;
import com.ecyrd.jspwiki.WikiEngine;
import com.ecyrd.jspwiki.WikiException;
import com.ecyrd.jspwiki.util.PriorityList;
import com.ecyrd.jspwiki.util.ClassUtil;
/**
* Manages the page filters. Page filters are components that can be executed
* at certain places:
* <ul>
* <li>Before the page is translated into HTML.
* <li>After the page has been translated into HTML.
* <li>Before the page is saved.
* <li>After the page has been saved.
* </ul>
*
* Using page filters allows you to modify the page data on-the-fly, and do things like
* adding your own custom WikiMarkup.
*
* <p>
* The initial page filter configuration is kept in a file called "filters.xml". The
* format is really very simple:
* <pre>
* <?xml version="1.0"?>
*
* <pagefilters>
*
* <filter>
* <class>com.ecyrd.jspwiki.filters.ProfanityFilter</class>
* </filter>
*
* <filter>
* <class>com.ecyrd.jspwiki.filters.TestFilter</class>
*
* <param>
* <name>foobar</name>
* <value>Zippadippadai</value>
* </param>
*
* <param>
* <name>blatblaa</name>
* <value>5</value>
* </param>
*
* </filter>
* </pagefilters>
* </pre>
*
* The <filter> -sections define the filters. For more information, please see
* the PageFilterConfiguration page in the JSPWiki distribution.
*
* @author Janne Jalkanen
*/
public class FilterManager
extends HandlerBase
{
private PriorityList m_pageFilters = new PriorityList();
private static final Logger log = Logger.getLogger(WikiEngine.class);
public static final String PROP_FILTERXML = "jspwiki.filterConfig";
public static final String DEFAULT_XMLFILE = "/filters.xml";
public FilterManager( WikiEngine engine, Properties props )
throws WikiException
{
initialize( engine, props );
}
public void addPageFilter( PageFilter f, int priority )
{
if( f == null )
{
throw new IllegalArgumentException("Attempt to provide a null filter - this should never happen. Please check your configuration (or if you're a developer, check your own code.)");
}
m_pageFilters.add( f, priority );
}
private void initPageFilter( String className, Properties props )
{
try
{
int priority = 0; // FIXME: Currently fixed.
Class cl = ClassUtil.findClass( "com.ecyrd.jspwiki.filters",
className );
PageFilter filter = (PageFilter)cl.newInstance();
filter.initialize( props );
addPageFilter( filter, priority );
log.info("Added page filter "+cl.getName()+" with priority "+priority);
}
catch( ClassNotFoundException e )
{
log.error("Unable to find the filter class: "+className);
}
catch( InstantiationException e )
{
log.error("Cannot create filter class: "+className);
}
catch( IllegalAccessException e )
{
log.error("You are not allowed to access class: "+className);
}
catch( ClassCastException e )
{
log.error("Suggested class is not a PageFilter: "+className);
}
catch( FilterException e )
{
log.error("Filter "+className+" failed to initialize itself.", e);
}
}
/**
* Initializes the filters from an XML file.
*/
public void initialize( WikiEngine engine, Properties props )
throws WikiException
{
InputStream xmlStream = null;
String xmlFile = props.getProperty( PROP_FILTERXML );
try
{
if( xmlFile == null )
{
log.debug("Attempting to locate "+DEFAULT_XMLFILE+" from class path.");
xmlStream = getClass().getResourceAsStream( DEFAULT_XMLFILE );
}
else
{
log.debug("Attempting to load property file "+xmlFile);
xmlStream = new FileInputStream( new File(xmlFile) );
}
if( xmlStream == null )
{
log.info("Cannot find property file for filters (this is okay, expected to find it as: '"+ (xmlFile == null ? DEFAULT_XMLFILE : xmlFile ) +"')");
return;
}
Parser parser = new uk.co.wilson.xml.MinML(); // FIXME: Should be settable
parser.setDocumentHandler( this );
parser.setErrorHandler( this );
parser.parse( new InputSource(xmlStream) );
}
catch( IOException e )
{
log.error("Unable to read property file", e);
}
catch( SAXException e )
{
log.error("Problem in the XML file",e);
}
}
/*
* The XML parsing part. We use a simple SAX1 parser; we do not at this
* point need anything more complicated.
*/
private String filterName = null;
private Properties filterProperties = new Properties();
private boolean parsingFilters = false;
private String lastReadCharacters = null;
private String lastReadParamName = null;
private String lastReadParamValue = null;
public void startElement( String name, AttributeList atts )
{
if( "pagefilters".equals(name) )
{
parsingFilters = true;
}
else if( parsingFilters )
{
if( "filter".equals(name) )
{
filterName = null;
}
}
}
public void endElement( String name )
{
if( "pagefilters".equals(name) )
{
parsingFilters = false;
}
else if( parsingFilters )
{
if( "filter".equals(name) )
{
initPageFilter( filterName, filterProperties );
}
else if( "class".equals(name) )
{
filterName = lastReadCharacters;
}
else if( "param".equals(name) )
{
filterProperties.setProperty( lastReadParamName, lastReadParamValue );
}
else if( "name".equals(name) )
{
lastReadParamName = lastReadCharacters;
}
else if( "value".equals(name) )
{
lastReadParamValue = lastReadCharacters;
}
}
}
public void characters( char ch[], int start, int length )
{
lastReadCharacters = new String( ch, start, length );
}
/**
* Does the filtering before a translation.
*/
public String doPreTranslateFiltering( WikiContext context, String pageData )
throws FilterException
{
for( Iterator i = m_pageFilters.iterator(); i.hasNext(); )
{
PageFilter f = (PageFilter) i.next();
pageData = f.preTranslate( context, pageData );
}
return pageData;
}
/**
* Does the filtering after HTML translation.
*/
public String doPostTranslateFiltering( WikiContext context, String pageData )
throws FilterException
{
for( Iterator i = m_pageFilters.iterator(); i.hasNext(); )
{
PageFilter f = (PageFilter) i.next();
pageData = f.postTranslate( context, pageData );
}
return pageData;
}
/**
* Does the filtering before a save to the page repository.
*/
public String doPreSaveFiltering( WikiContext context, String pageData )
throws FilterException
{
for( Iterator i = m_pageFilters.iterator(); i.hasNext(); )
{
PageFilter f = (PageFilter) i.next();
pageData = f.preSave( context, pageData );
}
return pageData;
}
/**
* Does the page filtering after the page has been saved.
*/
public void doPostSaveFiltering( WikiContext context, String pageData )
throws FilterException
{
for( Iterator i = m_pageFilters.iterator(); i.hasNext(); )
{
PageFilter f = (PageFilter) i.next();
f.postSave( context, pageData );
}
}
public List getFilterList()
{
return m_pageFilters;
}
} |
package com.eirb.projets9;
import java.sql.Date;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Locale;
import android.app.Activity;
import android.app.Fragment;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.eirb.projets9.objects.Notification;
public class NotificationsFragment extends Fragment {
public NotificationsFragment(){}
public final int MAX_NOTIF = 5;
public SimpleDateFormat sdf = new SimpleDateFormat("hh:mm aa");
public DateFormat df = new SimpleDateFormat("HH:mm", Locale.US);
private LinearLayout listNotif;
private MainActivity a;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_notifications, container, false);
listNotif= (LinearLayout) rootView.findViewById(R.id.listNotif);
a = (MainActivity) getActivity();
if (ReferenceApplication.notificationList != null){
// Toast.makeText(getActivity(), "NOT NULL " + Integer.toString(ReferenceApplication.notificationList.size()), Toast.LENGTH_SHORT).show();
for (int i = 0; i < ReferenceApplication.notificationList.size(); i++) {
inflater = (LayoutInflater) getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = inflater.inflate(R.layout.notification_element,listNotif, false);
Notification n = ReferenceApplication.notificationList.get(i);
RelativeLayout layout = (RelativeLayout) view.findViewById(R.id.content);
// set Title
TextView title = (TextView) view.findViewById(R.id.titleNotif);
title.setText(n.getTalk().getTitle());
title.setTypeface(ReferenceApplication.fontMedium);
// set room
TextView room = (TextView) view.findViewById(R.id.roomNotif);
room.setText("Room " + n.getRoomName());
room.setTypeface(ReferenceApplication.fontLight);
// set Time
TextView time = (TextView) view.findViewById(R.id.timeNotif);
time.setText(sdf.format((new Date(n.getTimestamp()))));
time.setTypeface(ReferenceApplication.fontThin);
final Notification notif = n;
layout.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(getActivity(), Description.class);
Bundle bundle = new Bundle();
bundle.putString("Title", notif.getTalk().getTitle());
bundle.putString("Subtitle", notif.getRoomName());
bundle.putString("Start", df.format(new Date(notif.getTalk().getStartTs() * 1000)));
bundle.putString("End", df.format(new Date(notif.getTalk().getEndTs() * 1000)));
bundle.putString("Body", notif.getTalk().getBody());
intent.putExtras(bundle);
startActivityForResult(intent, 0);
}
});
listNotif.addView(view);
}
}
// else
// Toast.makeText(getActivity(), "NULL", Toast.LENGTH_SHORT).show();
return rootView;
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == Activity.RESULT_OK) {
// Toast.makeText(getActivity(), data.getStringExtra("room"), Toast.LENGTH_SHORT).show();
a.switchMapFragment(data.getStringExtra("room"));
}
}
} |
// ChargeRequest.java
// Inner Fence Credit Card Terminal for Android
// API 1.0.0
// below.
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
// included in all copies or substantial portions of the Software.
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
package com.innerfence.chargedemo;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
public class ChargeRequest
{
final static int CCTERMINAL_REQUEST_CODE = 0x12345678;
protected String _address;
protected String _amount;
protected String _city;
protected String _company;
protected String _country;
protected String _currency;
protected String _description;
protected String _email;
protected Bundle _extraParams;
protected String _firstName;
protected String _invoiceNumber;
protected String _lastName;
protected String _phone;
protected String _state;
protected String _zip;
public ChargeRequest()
{
}
public String getAddress()
{
return _address;
}
public void setAddress( String value )
{
_address = value;
}
public String getAmount()
{
return _amount;
}
public void setAmount( String value )
{
_amount = value;
}
public String getCity()
{
return _city;
}
public void setCity( String value )
{
_city = value;
}
public String getCompany()
{
return _company;
}
public void setCompany( String value )
{
_company = value;
}
public String getCountry()
{
return _country;
}
public void setCountry( String value )
{
_country = value;
}
public String getCurrency()
{
return _currency;
}
public void setCurrency( String value )
{
_currency = value;
}
public String getDescription()
{
return _description;
}
public void setDescription( String value )
{
_description = value;
}
public String getEmail()
{
return _email;
}
public void setEmail( String value )
{
_email = value;
}
public Bundle getExtraParams()
{
return _extraParams;
}
public void setExtraParams( Bundle value )
{
_extraParams = value;
}
public String getFirstName()
{
return _firstName;
}
public void setFirstName( String value )
{
_firstName = value;
}
public String getInvoiceNumber()
{
return _invoiceNumber;
}
public void setInvoiceNumber( String value )
{
_invoiceNumber = value;
}
public String getLastName()
{
return _lastName;
}
public void setLastName( String value )
{
_lastName = value;
}
public String getPhone()
{
return _phone;
}
public void setPhone( String value )
{
_phone = value;
}
public String getState()
{
return _state;
}
public void setState( String value )
{
_state = value;
}
public String getZip()
{
return _zip;
}
public void setZip( String value )
{
_zip = value;
}
public void submit( Activity callingActivity )
{
Bundle bundle = new Bundle();
bundle.putString( "address", _address );
bundle.putString( "amount", _amount );
bundle.putString( "city", _city );
bundle.putString( "company", _company );
bundle.putString( "country", _country );
bundle.putString( "currency", _currency );
bundle.putString( "description", _description );
bundle.putString( "email", _email );
bundle.putBundle( "extra_params", _extraParams );
bundle.putString( "first_name", _firstName );
bundle.putString( "invoice_number", _invoiceNumber );
bundle.putString( "last_name", _lastName );
bundle.putString( "phone", _phone );
bundle.putString( "state", _state );
bundle.putString( "zip", _zip );
bundle.putBoolean( "return_to_calling_app", true );
Intent intent = new Intent();
intent.setClassName("com.innerfence.ccterminal", "com.innerfence.ccterminal.TerminalActivity");
intent.putExtras( bundle );
callingActivity.startActivityForResult( intent, CCTERMINAL_REQUEST_CODE );
}
} |
package com.novell.spsample.client;
import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.logical.shared.CloseEvent;
import com.google.gwt.event.logical.shared.CloseHandler;
import com.google.gwt.user.client.Timer;
import com.google.gwt.user.client.ui.Anchor;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.FlowPanel;
import com.google.gwt.user.client.ui.HTMLPanel;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.PopupPanel;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.gwt.user.client.ui.Widget;
import com.novell.spiffyui.client.MessageUtil;
import com.novell.spiffyui.client.widgets.DatePickerTextBox;
import com.novell.spiffyui.client.widgets.LongMessage;
import com.novell.spiffyui.client.widgets.ProgressBar;
import com.novell.spiffyui.client.widgets.SlideDownPrefsPanel;
import com.novell.spiffyui.client.widgets.SlidingGridPanel;
import com.novell.spiffyui.client.widgets.SmallLoadingIndicator;
import com.novell.spiffyui.client.widgets.StatusIndicator;
import com.novell.spiffyui.client.widgets.TimePickerTextBox;
import com.novell.spiffyui.client.widgets.button.FancySaveButton;
import com.novell.spiffyui.client.widgets.button.RefreshAnchor;
import com.novell.spiffyui.client.widgets.button.SimpleButton;
import com.novell.spiffyui.client.widgets.dialog.ConfirmDialog;
import com.novell.spiffyui.client.widgets.dialog.Dialog;
import com.novell.spiffyui.client.widgets.multivaluesuggest.MultivalueSuggestBox;
import com.novell.spiffyui.client.widgets.multivaluesuggest.MultivalueSuggestRESTHelper;
/**
* This is the widgets sample panel
*
*/
public class WidgetsPanel extends HTMLPanel implements CloseHandler<PopupPanel>
{
private static final SPSampleStrings STRINGS = (SPSampleStrings) GWT.create(SPSampleStrings.class);
private ConfirmDialog m_dlg;
private RefreshAnchor m_refresh;
private SlidingGridPanel m_slideGridPanel;
private static final int TALL = 1;
private static final int WIDE = 2;
private static final int BIG = 3;
/**
* Creates a new panel
*/
public WidgetsPanel()
{
super("div",
"<div id=\"WidgetsPrefsPanel\"></div><h1>Spiffy Widgets</h1><br /><br />" +
STRINGS.WidgetsPanel_html() +
"<div id=\"WidgetsLongMessage\"></div><br /><br />" +
"<div id=\"WidgetsSlidingGrid\"></div>" +
"</div>");
getElement().setId("WidgetsPanel");
RootPanel.get("mainContent").add(this);
//Create the sliding grid and set it up for the rest of the controls
m_slideGridPanel = new SlidingGridPanel();
m_slideGridPanel.setGridOffset(225);
setVisible(false);
addLongMessage();
addNavPanelInfo();
addSlidingGrid();
/*
* Add widgets to the sliding grid in alphabetical order
*/
addDatePicker();
addFancyButton();
addMessageButton();
addMultiValueAutoComplete();
addOptionsPanel();
addProgressBar();
addConfirmDialog();
addRefreshAnchor();
addSmallLoadingIndicator();
addStatusIndicators();
addSimpleButton();
addTimePicker();
/*
* Add the sliding grid here. This call must go last so that the onAttach of the SlidingGridPanel can do its thing.
*/
add(m_slideGridPanel, "WidgetsSlidingGrid");
}
/**
* Create the time picker control and add it to the sliding grid
*/
private void addTimePicker()
{
/*
* Add the time picker
*/
addToSlidingGrid(new TimePickerTextBox("timepicker"), "WidgetsTimePicker", "Time Picker",
"<p>" +
"Time Picker shows a time dropdown for easy selection. It is a wrapper for a " +
"<a href=\"http://code.google.com/p/jquery-timepicker/\">JQuery time picker</a>. " +
"The time step is set to 30 min but can be configured. It is localized. " +
"Try changing your browser locale and refreshing your browser." +
"</p>");
}
/**
* Create the status indicators and add them to the sliding grid
*/
private void addStatusIndicators()
{
/*
* Add 3 status indicators
*/
StatusIndicator status1 = new StatusIndicator(StatusIndicator.IN_PROGRESS);
StatusIndicator status2 = new StatusIndicator(StatusIndicator.SUCCEEDED);
StatusIndicator status3 = new StatusIndicator(StatusIndicator.FAILED);
HTMLPanel statusPanel = addToSlidingGrid(status1, "WidgetsStatus", "Status Indicator",
"<p>The status indicator shows valid, failed, and in progress status. It can be extended for others.</p>");
statusPanel.add(status2, "WidgetsStatus");
statusPanel.add(status3, "WidgetsStatus");
}
/**
* Create the small loading indicator and add it to the sliding grid
*/
private void addSmallLoadingIndicator()
{
/*
* Add a small loading indicator to our page
*/
SmallLoadingIndicator loading = new SmallLoadingIndicator();
addToSlidingGrid(loading, "WidgetsSmallLoading", "Small Loading Indicator", "<p>This indicator shows a loading status.</p>");
}
/**
* Create the refresh anchor and add it to the sliding grid
*/
private void addRefreshAnchor()
{
/*
* Add a refresh anchor to our page
*/
m_refresh = new RefreshAnchor("Widgets_refreshAnchor");
addToSlidingGrid(m_refresh, "WidgetsRefreshAnchor", "Refresh Anchor Confirm Dialog",
"<p>" +
"The refresh anchor shows an in progress status for refreshing items with an AJAX request. Click to show its in progress status and " +
"open an example of a confirm dialog." +
"</p>" +
"<p>" +
"Dialogs are keyboard accessible. They also support autohide and modal properties. You can also override the dialog class and " +
"supply your own implementation of the dialog." +
"</p>",
TALL);
m_refresh.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event)
{
m_refresh.setLoading(true);
m_dlg.center();
m_dlg.show();
event.preventDefault();
}
});
}
/**
* Create the confirm dialog and add it to the sliding grid
*/
private void addConfirmDialog()
{
/*
* Add the ConfirmDialog which will show up when refresh is clicked
*/
m_dlg = new ConfirmDialog("WidgetsConfirmDlg", "Sample Confirm");
m_dlg.hide();
m_dlg.addCloseHandler(this);
m_dlg.setText("Are you sure you want to refresh? (Doesn't make much sense as a confirm, but this is just a sample.)");
m_dlg.addButton("btn1", "Proceed", "OK");
m_dlg.addButton("btn2", "Cancel", "CANCEL");
}
/**
* Create the progress bar and add it to the sliding grid
*/
private void addProgressBar()
{
/*
* Add a progress bar to our page
*/
ProgressBar bar = new ProgressBar("WidgetsPanelProgressBar");
bar.setValue(65);
addToSlidingGrid(bar, "WidgetsProgressSpan", "Progress Bar",
"<p>" +
"This progress bar GWT control wraps the " +
"<a href=\"http://jqueryui.com/demos/progressbar/\">JQuery UI Progressbar</a>." +
"</p>");
}
/**
* Create the options panel and add it to the sliding grid
*/
private void addOptionsPanel()
{
/*
* Add the options slide down panel
*/
SlideDownPrefsPanel prefsPanel = new SlideDownPrefsPanel("WidgetsPrefs", "Slide Down Prefs Panel");
add(prefsPanel, "WidgetsPrefsPanel");
FlowPanel prefContents = new FlowPanel();
prefContents.add(new Label("Add display option labels and fields and an 'Apply' or 'Save' button."));
prefsPanel.setPanel(prefContents);
addToSlidingGrid(null, "WidgetsDisplayOptions", "Options Slide Down Panel",
"<p>" +
"Click the 'Slide Down Prefs Panel' slide-down tab at the top of the page to view an example of this widget." +
"</p>");
}
/**
* Create the mutli-value auto-complete field and add it to the sliding grid
*/
private void addMultiValueAutoComplete()
{
/*
* Add the multivalue suggest box
*/
MultivalueSuggestBox msb = new MultivalueSuggestBox(new MultivalueSuggestRESTHelper("TotalSize", "Options", "DisplayName", "Value") {
@Override
public String buildUrl(String q, int indexFrom, int indexTo)
{
return "multivaluesuggestboxexample/colors?q=" + q + "&indexFrom=" + indexFrom + "&indexTo=" + indexTo;
}
}, true);
msb.getFeedback().addStyleName("msg-feedback");
addToSlidingGrid(msb, "WidgetsSuggestBox", "Multivalue Suggest Box",
"<p>" +
"The Multivalue suggest box is an autocompleter that allows for multiple values and browsing. It uses REST to " +
"retrieve suggestions from the server. The full process is documented in " +
"<a href=\"http:
"Creating a Multi-Valued Auto-Complete Field Using GWT SuggestBox and REST</a>." +
"</p>" +
"<p>" +
"Type blue, mac, or * to search for crayon colors." +
"</p>",
WIDE);
}
/**
* Create the date picker control and add it to the sliding grid
*/
private void addDatePicker()
{
/*
* Add the date picker
*/
addToSlidingGrid(new DatePickerTextBox("datepicker"), "WidgetsDatePicker", "Date Picker",
"<p>" +
"Spiffy UI's date picker shows a calendar for easy date selection. It wraps the <a href=\"http://jqueryui.com/demos/datepicker\">" +
"JQuery UI Date Picker</a> which is better tested, has more features, and is easier to style than the GWT date " +
"picker control. The JQuery Date Picker includes many features including the ablility to specify the minimum " +
"and maximum dates and changing the way to pick months and years." +
"</p>" +
"<p>" +
"The Spiffy UI Framework is localized into 53 languages. Try changing your browser locale and refreshing " +
"this page. In addition, since it is a GWT widget, you may get the selected date value as a java.util.Date." +
"</p>", TALL);
}
private void addNavPanelInfo()
{
Anchor css = new Anchor("CSS page", "CSSPanel");
css.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event)
{
event.preventDefault();
Index.selectItem(Index.CSS_NAV_ITEM_ID);
}
});
HTMLPanel panel = addToSlidingGrid(null, "NavPanelGridCell", "Navigation Bar",
"<p>" +
"The main navigation bar makes it easy to add styled navigation menus to your application with " +
"highlights, collapsible sections, and separators. These items navigate between different panels " +
"in your application, but can also navigate between different HTML pages." +
"</p>" +
"<p>" +
"The navigation menu also supports the back button when navigating between JavaScript panels in " +
"the same page. This makes it possible to support the back button, forward button, and browser " +
"history while maintaining the JavaScript state of your application and keeping very fast page loading." +
"</p>" +
"<p>" +
"The menus use CSS layout which supports a flexible layout. See the example on the " +
"<span id=\"cssPageWidgetsLink\"></span>." +
"</p>", TALL);
panel.add(css, "cssPageWidgetsLink");
}
/**
* Create the sliding grid
*/
private void addSlidingGrid()
{
/*
* Create the sliding grid and add its big cell
*/
addToSlidingGrid(null, "WidgetsSlidingGridCell", "Sliding Grid Panel",
"<p>" +
"All the cells here are layed out using the sliding grid panel. This panel is a wrapper for slidegrid.js, " +
"which automatically moves cells to fit nicely on the screen for any browser window size." +
"</p>" +
"<p>" +
"Resize your browser window to see it in action." +
"</p>" +
"<p>" +
"More information on the sliding grid can be found in <a href=\"http:
"Create Your Own Sliding Resizable Grid</a>." +
"</p>", TALL);
}
/**
* Create the long message control to the top of the page
*/
private void addLongMessage()
{
/*
* Add a long message to our page
*/
LongMessage message = new LongMessage("WidgetsLongMessageWidget");
add(message, "WidgetsLongMessage");
message.setHTML("<b>Long Message</b><br />" +
"Long messages are useful for showing information messages " +
"with more content than the standard messages but they are still " +
"transient messages.");
}
/**
* Create the simple button control and add it to the sliding grid
*/
private void addSimpleButton()
{
/*
* Add the simple button
*/
final SimpleButton simple = new SimpleButton("Simple Button");
simple.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event)
{
simple.setInProgress(true);
//a little timer to simulate time it takes to set loading back to false
Timer t = new Timer() {
@Override
public void run()
{
simple.setInProgress(false);
}
};
t.schedule(2000);
}
});
addToSlidingGrid(simple, "WidgetsButton", "Simple Button",
"<p>" +
"All buttons get special styling from the Spiffy UI framework. Click to demonstrate its in progress status." +
"</p>");
}
/**
* Create the fancy button control and add it to the sliding grid
*/
private void addFancyButton()
{
/*
* Add the fancy button
*/
final FancySaveButton fancy = new FancySaveButton("Save");
fancy.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event)
{
fancy.setInProgress(true);
//a little timer to simulate time it takes to set loading back to false
Timer t = new Timer() {
@Override
public void run()
{
fancy.setInProgress(false);
}
};
t.schedule(2000);
}
});
addToSlidingGrid(fancy, "WidgetsFancyButton", "Fancy Save Button",
"<p>" +
"Fancy buttons show an image and text with a disabled image and hover style. Click to demonstrate its in progress status." +
"</p>");
}
/**
* A helper method that adds a widget and some HTML description to the sliding
* grid panel
*
* @param widget the widget to add
* @param id the ID of the new cell
* @param title the title of the new cell
* @param htmlText the HTML description of the widget
*
* @return the HTMLPanel used to add the contents to the new cell
*/
private HTMLPanel addToSlidingGrid(Widget widget, String id, String title, String htmlText)
{
return addToSlidingGrid(widget, id, title, htmlText, 0);
}
/**
* A helper method that adds a widget and some HTML description to the sliding
* grid panel
*
* @param widget the widget to add
* @param id the ID of the new cell
* @param title the title of the new cell
* @param htmlText the HTML description of the widget
* @param type the type of cell to add: TALL, BIG, or WIDE
*
* @return the HTMLPanel used to add the contents to the new cell
*/
private HTMLPanel addToSlidingGrid(Widget widget, String id, String title, String htmlText, int type)
{
HTMLPanel p = new HTMLPanel("div",
"<h3>" + title + "</h3>" +
htmlText +
"<span id=\"" + id + "\"></span>");
if (widget != null) {
p.add(widget, id);
}
switch (type) {
case WIDE:
m_slideGridPanel.addWide(p);
break;
case TALL:
m_slideGridPanel.addTall(p);
break;
case BIG:
m_slideGridPanel.addBig(p);
break;
default:
m_slideGridPanel.add(p);
break;
}
return p;
}
/**
* Add the message buttons to the sliding grid
*/
private void addMessageButton()
{
/*
* Add the message buttons
*/
Button b = new Button("Show Info Message");
HTMLPanel p = addToSlidingGrid(b, "WidgetsMessages", "Humanized Messages",
"<p>" +
"The Spiffy UI framework support has an integrated message framework following the pattern of " +
"<a href=\"http://code.google.com/p/humanmsg/\">Humanized Messages</a>. " +
"These messages are non-modal and fade away without requiring further interaction. They " +
"include info messages, warnings, errors, and fatal errors. Errors and some warnings are sent to an error " +
"log at the bottom of the screen." +
"</p>",
TALL);
b.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event)
{
MessageUtil.showMessage("This is an information message");
}
});
b = new Button("Show Warning Message");
p.add(b, "WidgetsMessages");
b.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event)
{
MessageUtil.showWarning("This is a warning message", false);
}
});
b = new Button("Show Error Message");
p.add(b, "WidgetsMessages");
b.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event)
{
MessageUtil.showError("This is an error message");
}
});
b = new Button("Show Fatal Error Message");
p.add(b, "WidgetsMessages");
b.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event)
{
MessageUtil.showFatalError("This is a fatal error message");
}
});
}
@Override
public void onClose(CloseEvent<PopupPanel> event)
{
Dialog dlg = (Dialog) event.getSource();
String btn = dlg.getButtonClicked();
if (dlg == m_dlg && "OK".equals(btn)) {
MessageUtil.showMessage("Refreshing!");
//a little timer to simulate time it takes to set loading back to false
Timer t = new Timer() {
@Override
public void run()
{
m_refresh.setLoading(false);
}
};
t.schedule(2000);
} else {
m_refresh.setLoading(false);
}
}
} |
package com.valkryst.VTerminal.component;
import com.valkryst.VRadio.Radio;
import com.valkryst.VRadio.Receiver;
import com.valkryst.VTerminal.AsciiCharacter;
import com.valkryst.VTerminal.AsciiString;
import com.valkryst.VTerminal.Panel;
import com.valkryst.VTerminal.builder.component.*;
import com.valkryst.VTerminal.font.Font;
import com.valkryst.VTerminal.misc.ImageCache;
import com.valkryst.VTerminal.misc.IntRange;
import com.valkryst.VTerminal.printer.RectanglePrinter;
import lombok.Getter;
import lombok.NonNull;
import lombok.Setter;
import lombok.ToString;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.image.BufferedImage;
import java.util.*;
import java.util.concurrent.locks.ReentrantReadWriteLock;
@ToString
public class Screen extends Component implements Receiver<String> {
/** The panel on which the screen is displayed. */
@Getter @Setter private Panel parentPanel;
/** The non-layer components displayed on the screen. */
private ArrayList<Component> components = new ArrayList<>();
/** The layer components displayed on the screen. */
private ArrayList<Layer> layerComponents = new ArrayList<>();
/** The screen components displayed on the screen. */
private ArrayList<Screen> screenComponents = new ArrayList<>();
private ReentrantReadWriteLock componentsLock = new ReentrantReadWriteLock();
/**
* Constructs a new Screen.
*
* @param builder
* The builder to use.
*
* @throws NullPointerException
* If the builder is null.
*/
public Screen(final @NonNull ScreenBuilder builder) {
super(builder);
setBackgroundColor(new Color(45, 45, 45, 255));
if (builder.getJsonObject() != null) {
final JSONArray components = (JSONArray) builder.getJsonObject().get("components");
if (components != null) {
for (final Object obj : components) {
final JSONObject arrayElement = (JSONObject) obj;
if (arrayElement != null) {
final ComponentBuilder componentBuilder = loadElementFromJSON(arrayElement);
if (componentBuilder != null) {
final Component component = componentBuilder.build();
addComponent(component);
}
}
}
}
}
}
@Override
public void receive(final String event, final String data) {
if (radio != null) {
if (event.equals("DRAW")) {
transmitDraw();
}
}
}
private ComponentBuilder loadElementFromJSON(final @NonNull JSONObject jsonObject) {
String componentType = (String) jsonObject.get("type");
if (componentType == null) {
return null;
}
componentType = componentType.toLowerCase();
switch (componentType) {
case "button": {
final ButtonBuilder buttonBuilder = new ButtonBuilder();
buttonBuilder.parse(jsonObject);
return buttonBuilder;
}
case "check box": {
final CheckBoxBuilder checkBoxBuilder = new CheckBoxBuilder();
checkBoxBuilder.parse(jsonObject);
return checkBoxBuilder;
}
case "label": {
final LabelBuilder labelBuilder = new LabelBuilder();
labelBuilder.parse(jsonObject);
return labelBuilder;
}
case "layer": {
final LayerBuilder layerBuilder = new LayerBuilder();
layerBuilder.parse(jsonObject);
return layerBuilder;
}
case "progress bar": {
final ProgressBarBuilder progressBarBuilder = new ProgressBarBuilder();
progressBarBuilder.parse(jsonObject);
return progressBarBuilder;
}
case "radio button": {
final RadioButtonBuilder radioButtonBuilder = new RadioButtonBuilder();
radioButtonBuilder.parse(jsonObject);
return radioButtonBuilder;
}
case "radio button group": {
final RadioButtonGroup radioButtonGroup = new RadioButtonGroup();
final JSONArray radioButtons = (JSONArray) jsonObject.get("components");
if (radioButtons != null) {
for (final Object object : radioButtons) {
final JSONObject buttonJSON = (JSONObject) object;
final RadioButtonBuilder builder = (RadioButtonBuilder) loadElementFromJSON(buttonJSON);
builder.setGroup(radioButtonGroup);
addComponent(builder.build());
}
}
return null;
}
case "screen": {
final ScreenBuilder screenBuilder = new ScreenBuilder();
screenBuilder.parse(jsonObject);
return screenBuilder;
}
case "text field": {
final TextFieldBuilder textFieldBuilder = new TextFieldBuilder();
textFieldBuilder.parse(jsonObject);
return textFieldBuilder;
}
case "text area": {
final TextAreaBuilder textAreaBuilder = new TextAreaBuilder();
textAreaBuilder.parse(jsonObject);
return textAreaBuilder;
}
case "rectangle printer": {
final RectanglePrinter rectanglePrinter = new RectanglePrinter();
rectanglePrinter.printFromJSON(this, jsonObject);
return null;
}
default: {
throw new IllegalArgumentException("The element type '" + componentType + "' is not supported.");
}
}
}
@Override
public void draw(final @NonNull Screen screen) {
throw new UnsupportedOperationException("A Screen must be drawn using the draw(canvas, font) method.");
}
/**
* Draws the screen onto the specified graphics context..
*
* @param gc
* The graphics context to draw with.
*
* @param imageCache
* The image cache to retrieve character images from.
*
* @throws NullPointerException
* If the gc or image cache is null.
*/
public void draw(final @NonNull Graphics2D gc, final @NonNull ImageCache imageCache) {
draw(gc, imageCache, getPosition());
}
/**
* Draws the screen onto the specified graphics context..
*
* @param gc
* The graphics context to draw with.
*
* @param imageCache
* The image cache to retrieve character images from.
*
* @param offset
* The x/y-axis (column/row) offsets to alter the position at which the
* screen is drawn.
*
* @throws NullPointerException
* If the gc or image cache is null.
*/
public void draw(final @NonNull Graphics2D gc, final @NonNull ImageCache imageCache, final Point offset) {
componentsLock.readLock().lock();
// Draw non-layer components onto the screen:
components.forEach(component -> component.draw(this));
// Draw the screen onto the canvas:
final AsciiString[] strings = super.getStrings();
final Thread thread = new Thread(() -> {
for (int row = 0 ; row < getHeight()/2 ; row++) {
strings[row].draw(gc, imageCache, row, offset);
}
});
thread.start();
for (int row = getHeight()/2 ; row < getHeight() ; row++) {
strings[row].draw(gc, imageCache, row, offset);
}
try {
thread.join();
} catch(final InterruptedException e) {
e.printStackTrace();
}
// Draw layer components onto the screen:
layerComponents.forEach(layer -> layer.draw(gc, imageCache, offset));
// Draw screen components onto the screen:
screenComponents.forEach(screen -> {
final Point position = screen.getPosition();
screen.draw(gc, imageCache, position);
});
componentsLock.readLock().unlock();
}
/**
* Clears the specified section of the screen.
*
* Does nothing if the (columnIndex, rowIndex) or (width, height) pairs point
* to invalid positions.
*
* @param character
* The character to replace all characters being cleared with.
*
* @param position
* The x/y-axis (column/row) coordinates of the cell to clear.
*
* @param width
* The width of the area to clear.
*
* @param height
* The height of the area to clear.
*/
public void clear(final char character, final Point position, int width, int height) {
boolean canProceed = isPositionValid(position);
canProceed &= width >= 0;
canProceed &= height >= 0;
if (canProceed) {
width += position.x;
height += position.y;
final Point writePosition = new Point(0, 0);
for (int column = position.x ; column < width ; column++) {
for (int row = position.y ; row < height ; row++) {
writePosition.setLocation(column, row);
write(character, writePosition);
}
}
}
}
/**
* Clears the entire screen.
*
* @param character
* The character to replace every character on the screen with.
*/
public void clear(final char character) {
clear(character, new Point(0, 0), super.getWidth(), super.getHeight());
}
/**
* Write the specified character to the specified position.
*
* @param character
* The character.
*
* @param position
* The x/y-axis (column/row) coordinate to write to.
*
* @throws NullPointerException
* If the character is null.
*/
public void write(final @NonNull AsciiCharacter character, final Point position) {
if (isPositionValid(position)) {
super.getString(position.y).setCharacter(position.x, character);
}
}
/**
* Write the specified character to the specified position.
*
* @param character
* The character.
*
* @param position
* The x/y-axis (column/row) coordinates to write to.
*/
public void write(final char character, final Point position) {
if (isPositionValid(position)) {
super.getString(position.y).setCharacter(position.x, character);
}
}
/**
* Write a string to the specified position.
*
* Does nothing if the (columnIndex, rowIndex) points to invalid position.
*
* @param string
* The string.
*
* @param position
* The x/y-axis (column/row) coordinates to begin writing from.
*
* @throws NullPointerException
* If the string is null.
*/
public void write(final @NonNull AsciiString string, final Point position) {
if (isPositionValid(position)) {
final AsciiCharacter[] characters = string.getCharacters();
for (int i = 0; i < characters.length && i < super.getWidth(); i++) {
write(characters[i], new Point(position.x + i, position.y));
}
}
}
/**
* Write a string to the specified position.
*
* Does nothing if the (columnIndex, rowIndex) points to invalid position.
*
* @param string
* The string.
*
* @param position
* The x/y-axis (column/row) coordinates to begin writing from.
*
* @throws NullPointerException
* If the string is null.
*/
public void write(final @NonNull String string, final Point position) {
write(new AsciiString(string), position);
}
@Override
public void setPosition(final Point position) {
// Recalculate bounding box positions.
for (final Component component : getComponents()) {
final Rectangle boundingBox = component.getBoundingBox();
final int x = boundingBox.x - super.getPosition().x + position.x;
final int y = boundingBox.y - super.getPosition().y + position.y;
component.getBoundingBox().setLocation(x, y);
}
super.setPosition(position);
}
/**
* Draws the screen onto an image.
*
* This calls the draw function, so the screen may look a little different
* if there are blink effects or new updates to characters that haven't yet
* been drawn.
*
* This is an expensive operation as it essentially creates an in-memory
* screen and draws each AsciiCharacter onto that screen.
*
* @param imageCache
* The image cache to retrieve character images from.
*
* @return
* An image of the screen.
*
* @throws NullPointerException
* If the image cache is null.
*/
public BufferedImage screenshot(final @NonNull ImageCache imageCache) {
final Font font = imageCache.getFont();
final int width = this.getWidth() * font.getWidth();
final int height = this.getHeight() * font.getHeight();
final BufferedImage img = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
final Graphics2D gc = img.createGraphics();
draw(gc, imageCache);
gc.dispose();
return img;
}
/**
* Sets the background color of all characters.
*
* @param color
* The new background color.
*
* @throws NullPointerException
* If the color is null.
*/
public void setBackgroundColor(final @NonNull Color color) {
for (final AsciiString string : getStrings()) {
string.setBackgroundColor(color);
}
}
/**
* Sets the foreground color of all characters.
*
* @param color
* The new foreground color.
*
* @throws NullPointerException
* If the color is null.
*/
public void setForegroundColor(final @NonNull Color color) {
for (final AsciiString string : getStrings()) {
string.setForegroundColor(color);
}
}
/**
* Sets the background and foreground color of all characters.
*
* @param background
* The new background color.
*
* @param foreground
* The new foreground color.
*
* @throws NullPointerException
* If the background or foreground color is null.
*/
public void setBackgroundAndForegroundColor(final @NonNull Color background, final @NonNull Color foreground) {
for (final AsciiString string : getStrings()) {
string.setBackgroundColor(background);
string.setForegroundColor(foreground);
}
}
/**
* Adds a component to the screen and registers event listeners of the
* component, to the parent panel, if required.
*
* If the component is already present on the screen, then the component is
* not added.
*
* If the component is a screen and it has already been added to this screen,
* or any sub-screen of this screen, then the component is not added.
*
* @param component
* The component.
*/
public void addComponent(final Component component) {
componentsLock.writeLock().lock();
boolean containsComponent = containsComponent(component);
if (containsComponent) {
componentsLock.writeLock().unlock();
return;
}
// Add the component to one of the component lists:
component.getRadio().addReceiver("DRAW", this);
if (component instanceof Screen) {
((Screen) component).setParentPanel(parentPanel);
screenComponents.add((Screen) component);
} else if (component instanceof Layer) {
layerComponents.add((Layer) component);
} else {
components.add(component);
}
// Add screen position as offset to bounding box position of component.
final Rectangle boundingBox = component.getBoundingBox();
final int x = boundingBox.x + super.getPosition().x;
final int y = boundingBox.y + super.getPosition().y;
component.getBoundingBox().setLocation(x, y);
componentsLock.writeLock().unlock();
// Set up event listeners:
component.createEventListeners(parentPanel);
for (final EventListener eventListener : component.getEventListeners()) {
parentPanel.addListener(eventListener);
}
}
/**
* Adds one or more components to the screen.
*
* @param components
* The components.
*/
public void addComponents(final Component ... components) {
if (components == null) {
return;
}
for (final Component component : components) {
addComponent(component);
}
}
public void removeComponent(final Component component) {
componentsLock.writeLock().lock();
if (component == null) {
componentsLock.writeLock().unlock();
return;
}
if (component == this) {
componentsLock.writeLock().unlock();
throw new IllegalArgumentException("A screen cannot be removed from itself.");
}
component.getRadio().removeReceiver("DRAW", this);
if (component instanceof Screen) {
component.getEventListeners().forEach(listener -> parentPanel.removeListener(listener));
screenComponents.remove(component);
} else if (component instanceof Layer) {
layerComponents.remove(component);
} else {
components.remove(component);
}
// Remove screen position as offset to bounding box position of component.
final Rectangle boundingBox = component.getBoundingBox();
final int boundingBoxX = boundingBox.x - super.getPosition().x;
final int boundingBoxY = boundingBox.y - super.getPosition().y;
component.getBoundingBox().setLocation(boundingBoxX, boundingBoxY);
componentsLock.writeLock().unlock();
for (final EventListener eventListener : component.getEventListeners()) {
parentPanel.removeListener(eventListener);
}
// Reset component's characters to empty cells.
final Point position = component.getPosition();
final IntRange redrawRange = new IntRange(position.x, position.x + component.getWidth());
for (int y = position.y ; y < position.y + component.getHeight() ; y++) {
final AsciiString string = super.getString(y);
string.setCharacters(' ', redrawRange);
string.setBackgroundColor(new Color(45, 45, 45, 255), redrawRange);
string.setForegroundColor(Color.WHITE, redrawRange);
string.setUnderlined(redrawRange, false);
string.setFlippedHorizontally(redrawRange, false);
string.setFlippedVertically(redrawRange, false);
}
}
/**
* Removes one or more components from the screen.
*
* @param components
* The components.
*/
public void removeComponents(final Component ... components) {
if (components == null) {
return;
}
for (final Component component : components) {
removeComponent(component);
}
}
/**
* Moves one component above another component, in the
* draw order.
*
* Does nothing if either component is null.
*
* Does nothing if components are not of the same type.
*
* @param stationary
* The component that is not being moved.
*
* @param moving
* The component that is being moved.
*/
public void changeDrawOrder(final Component stationary, final Component moving) {
if (stationary == null || moving == null) {
return;
}
if (stationary.getClass().equals(moving.getClass()) == false) {
return;
}
final List list;
if (stationary instanceof Screen) {
list = screenComponents;
} else if (stationary instanceof Layer) {
list = layerComponents;
} else {
list = components;
}
final int index = list.indexOf(stationary);
if (index != -1) {
list.remove(moving);
list.add(index, moving);
}
}
/**
* Determines whether or not the screen contains a specific component.
*
* @param component
* The component.
*
* @return
* Whether or not the screen contains the component.
*/
public boolean containsComponent(final Component component) {
componentsLock.readLock().lock();
if (component == null) {
componentsLock.readLock().unlock();
return false;
}
if (component == this) {
componentsLock.readLock().unlock();
return false;
}
if (component instanceof Screen) {
if (screenComponents.contains(component)) {
componentsLock.readLock().unlock();
return true;
}
} else if (component instanceof Layer) {
if (layerComponents.contains(component)) {
componentsLock.readLock().unlock();
return true;
}
}
final boolean result = components.contains(component);
componentsLock.readLock().unlock();
return result;
}
/**
* Determines the total number of components.
*
* @return
* The total number of components.
*/
public int totalComponents() {
componentsLock.readLock().lock();
int sum = components.size();
sum += layerComponents.size();
sum += screenComponents.size();
componentsLock.readLock().unlock();
return sum;
}
/**
* Retrieves the first encountered component that uses the specified ID.
*
* @param id
* The id.
*
* @return
* If no component matches the ID, the null is returned.
* Else the component is returned.
*/
public Component getComponentByID(final String id) {
componentsLock.readLock().lock();
for (final Component component : components) {
if (component.getId().equals(id)) {
componentsLock.readLock().unlock();
return component;
}
}
for (final Layer layer : layerComponents) {
if (layer.getId().equals(id)) {
componentsLock.readLock().unlock();
return layer;
}
}
for (final Screen screen : screenComponents) {
if (screen.getId().equals(id)) {
componentsLock.readLock().unlock();
return screen;
}
}
componentsLock.readLock().unlock();
return null;
}
/**
* Works the same as getComponentByID, but only returns if the result is a
* Button component.
*
* @param id
* The id.
*
* @return
* If no component matches the ID, then null is returned.
* If no button component matches the ID, then null is returned.
* Else the component is returned.
*/
public Button getButtonByID(final String id) {
final Component component = getComponentByID(id);
if (component instanceof Button) {
return (Button) component;
}
return null;
}
/**
* Works the same as getComponentByID, but only returns if the result is a
* Check Box component.
*
* @param id
* The id.
*
* @return
* If no component matches the ID, then null is returned.
* If no check box component matches the ID, then null is returned.
* Else the component is returned.
*/
public CheckBox getCheckBoxByID(final String id) {
final Component component = getComponentByID(id);
if (component instanceof CheckBox) {
return (CheckBox) component;
}
return null;
}
/**
* Works the same as getComponentByID, but only returns if the result is a
* Layer component.
*
* @param id
* The id.
*
* @return
* If no component matches the ID, then null is returned.
* If no layer component matches the ID, then null is returned.
* Else the component is returned.
*/
public Layer getLayerByID(final String id) {
final Component component = getComponentByID(id);
if (component instanceof Layer) {
return (Layer) component;
}
return null;
}
/**
* Works the same as getComponentByID, but only returns if the result is a
* ProgressBar component.
*
* @param id
* The id.
*
* @return
* If no component matches the ID, then null is returned.
* If no progress bar component matches the ID, then null is returned.
* Else the component is returned.
*/
public ProgressBar getProgressBarByID(final String id) {
final Component component = getComponentByID(id);
if (component instanceof ProgressBar) {
return (ProgressBar) component;
}
return null;
}
/**
* Works the same as getComponentByID, but only returns if the result is a
* RadioButton component.
*
* @param id
* The id.
*
* @return
* If no component matches the ID, then null is returned.
* If no radio button component matches the ID, then null is returned.
* Else the component is returned.
*/
public RadioButton getRadioButtonByID(final String id) {
final Component component = getComponentByID(id);
if (component instanceof RadioButton) {
return (RadioButton) component;
}
return null;
}
/**
* Works the same as getComponentByID, but only returns if the result is a
* TextArea component.
*
* @param id
* The id.
*
* @return
* If no component matches the ID, then null is returned.
* If no text area component matches the ID, then null is returned.
* Else the component is returned.
*/
public TextArea getTextAreaByID(final String id) {
final Component component = getComponentByID(id);
if (component instanceof TextArea) {
return (TextArea) component;
}
return null;
}
/**
* Works the same as getComponentByID, but only returns if the result is a
* TextField component.
*
* @param id
* The id.
*
* @return
* If no component matches the ID, then null is returned.
* If no text field component matches the ID, then null is returned.
* Else the component is returned.
*/
public TextField getTextFieldByID(final String id) {
final Component component = getComponentByID(id);
if (component instanceof TextField) {
return (TextField) component;
}
return null;
}
/**
* Retrieves a combined set of all components.
*
* @return
* A combined set of all components.
*/
public Set<Component> getComponents() {
componentsLock.readLock().lock();
final Set<Component> set = new LinkedHashSet<>(components);
set.addAll(layerComponents);
set.addAll(screenComponents);
componentsLock.readLock().unlock();
return set;
}
public void setRadio(final Radio<String> radio) {
super.radio = radio;
}
} |
package com.valkryst.VTerminal.component;
import com.valkryst.VTerminal.AsciiCharacter;
import com.valkryst.VTerminal.AsciiString;
import com.valkryst.VTerminal.font.Font;
import lombok.Getter;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.util.ArrayList;
public class Screen extends Component {
/** The components displayed on the screen. */
@Getter private final ArrayList<Component> components = new ArrayList<>();
/**
* Constructs a new AsciiScreen.
*
* @param columnIndex
* The x-axis (column) coordinate of the top-left character.
*
* @param rowIndex
* The y-axis (row) coordinate of the top-left character.
*
* @param width
* Thw width, in characters.
*
* @param height
* The height, in characters.
*/
public Screen(final int columnIndex, final int rowIndex, final int width, final int height) {
super(columnIndex, rowIndex, width, height);
}
@Override
public void draw(final Screen screen) {
throw new UnsupportedOperationException("A Screen must be drawn using the draw(canvas, font) method.");
}
/**
* Draws the screen onto the specified canvas using the specified font.
*
* @param gc
* The graphics context to draw with.
*
* @param font
* The font to draw with.
*/
public void draw(final Graphics2D gc, final Font font) {
// Draw components onto the screen:
components.forEach(component -> component.draw(this));
// Draw the screen onto the canvas:
for (int row = 0 ; row < height ; row++) {
strings[row].draw(gc, font, row);
}
}
/**
* Clears the entire screen.
*
* @param character
* The character to replace every character on the screen with.
*
* @return
* If all characters within the screen were cleared.
*/
public void clear(final char character) {
clear(character, 0, 0, super.getWidth(), super.getHeight());
}
/**
* Clears the specified section of the screen.
*
* Does nothing if the (columnIndex, rowIndex) or (width, height) pairs point to invalid positions.
*
* @param character
* The character to replace all characters being cleared with.
*
* @param columnIndex
* The x-axis (column) coordinate of the cell to clear.
*
* @param rowIndex
* The y-axis (row) coordinate of the cell to clear.
*
* @param width
* The width of the area to clear.
*
* @param height
* The height of the area to clear.
*/
public void clear(final char character, final int columnIndex, final int rowIndex, int width, int height) {
boolean canProceed = isPositionValid(columnIndex, rowIndex);
canProceed &= width >= 0;
canProceed &= height >= 0;
if (canProceed) {
width += columnIndex;
height += rowIndex;
for (int column = columnIndex ; column < width ; column++) {
for (int row = rowIndex ; row < height ; row++) {
write(character, column, row);
}
}
}
}
/**
* Write the specified character to the specified position.
*
* @param character
* The character.
*
* @param columnIndex
* The x-axis (column) coordinate to write to.
*
* @param rowIndex
* The y-axis (row) coordinate to write to.
*
* @return
* If the write was successful.
*/
public boolean write(final AsciiCharacter character, final int columnIndex, final int rowIndex) {
boolean canProceed = isPositionValid(columnIndex, rowIndex);
canProceed &= character != null;
if (canProceed) {
strings[rowIndex].setCharacter(columnIndex, character);
}
return canProceed;
}
/**
* Write the specified character to the specified position.
*
* @param character
* The character.
*
* @param columnIndex
* The x-axis (column) coordinate to write to.
*
* @param rowIndex
* The y-axis (row) coordinate to write to.
*/
public void write(final char character, final int columnIndex, final int rowIndex) {
if (isPositionValid(columnIndex, rowIndex)) {
strings[rowIndex].setCharacter(columnIndex, character);
}
}
/**
* Write a string to the specified position.
*
* Does nothing if the (columnIndex, rowIndex) points to invalid position.
*
* @param string
* The string.
*
* @param columnIndex
* The x-axis (column) coordinate to begin writing from.
*
* @param rowIndex
* The y-axis (row) coordinate to begin writing from.
*/
public void write(final AsciiString string, final int columnIndex, final int rowIndex) {
boolean canProceed = isPositionValid(columnIndex, rowIndex);
canProceed &= string != null;
if (canProceed) {
final AsciiCharacter[] characters = string.getCharacters();
for (int i = 0; i < characters.length && i < super.getWidth(); i++) {
write(characters[i], columnIndex + i, rowIndex);
}
}
}
/**
* Draws the screen onto an image.
*
* This calls the draw function, so the screen may look a
* little different if there are blink effects or new updates
* to characters that haven't yet been drawn.
*
* This is an expensive operation as it essentially creates
* an in-memory screen and draws each AsciiCharacter onto
* that screen.
*
* @param asciiFont
* The font to render the screen with.
*
* @return
* An image of the screen.
*/
public BufferedImage screenshot(final Font asciiFont) {
final BufferedImage img = new BufferedImage(this.getWidth(), this.getHeight(), BufferedImage.TYPE_INT_RGB);
final Graphics2D gc = img.createGraphics();
for (final AsciiString string : strings) {
string.setAllCharactersToBeRedrawn();
}
draw(gc, asciiFont);
gc.dispose();
return img;
}
/**
* Sets the background color of all characters.
*
* @param color
* The new background color.
*/
public void setBackgroundColor(final Color color) {
if (color == null) {
return;
}
for (final AsciiString string : strings) {
string.setBackgroundColor(color);
}
}
/**
* Sets the foreground color of all characters.
*
* @param color
* The new foreground color.
*/
public void setForegroundColor(final Color color) {
if (color == null) {
return;
}
for (final AsciiString string : strings) {
string.setForegroundColor(color);
}
}
/**
* Sets the background and foreground color of all characters.
*
* @param background
* The new background color.
*
* @param foreground
* The new foreground color.
*/
public void setBackgroundAndForegroundColor(final Color background, final Color foreground) {
if (background == null || foreground == null) {
return;
}
for (final AsciiString string : strings) {
string.setBackgroundAndForegroundColor(background, foreground);
}
}
/**
* Adds a component to the AsciiScreen.
*
* @param component
* The component.
*/
public void addComponent(final Component component) {
if (component == null) {
return;
}
if (component == this) {
return;
}
if (component instanceof Screen) {
return;
}
if (components.contains(component)) {
return;
}
components.add(component);
}
/**
* Removes a component from the AsciiScreen.
*
* @param component
* The component.
*/
public void removeComponent(final Component component) {
if (component == null) {
return;
}
if (component == this) {
return;
}
if (component instanceof Screen) {
return;
}
components.remove(component);
}
} |
package com.vmware.loginsight.send;
import java.util.HashMap;
import java.util.Map;
import org.productivity.java.syslog4j.Syslog;
import org.productivity.java.syslog4j.SyslogIF;
import org.productivity.java.syslog4j.impl.message.processor.structured.StructuredSyslogMessageProcessor;
import org.productivity.java.syslog4j.impl.message.structured.StructuredSyslogMessage;
import org.productivity.java.syslog4j.impl.net.tcp.ssl.SSLTCPNetSyslogConfig;
public class SyslogClient {
private SyslogIF syslog = null;
public SyslogClient(String url, int port, LogInsigntProtocol proto) throws Exception {
checkParam(url, "url");
checkParam(proto, "protocol");
if (proto.equals(LogInsigntProtocol.SYSLOG_TCP)) {
syslog = Syslog.getInstance("tcp");
} else if (proto.equals(LogInsigntProtocol.SYSLOG_UDP)) {
syslog = Syslog.getInstance("udp");
} else if (proto.equals(LogInsigntProtocol.SYSLOG_TLS)) {
SSLTCPNetSyslogConfig syslogConfig = new SSLTCPNetSyslogConfig(url, port);
syslog = Syslog.createInstance("sslTcp", syslogConfig);
} else {
throw new Exception("Protocol " + proto.toString() + " is not supported. Use one of " +
LogInsigntProtocol.SYSLOG_TCP + ", " + LogInsigntProtocol.SYSLOG_UDP +
" or " + LogInsigntProtocol.SYSLOG_TLS);
}
syslog.getConfig().setUseStructuredData(true);
syslog.getConfig().setHost(url);
syslog.getConfig().setPort(port);
}
private void checkParam(Object param, String name) throws Exception {
if (param == null) {
throw new Exception("The " + name + " parameter is invalid, provide value = " + "null");
}
}
public void send(String msg) throws Exception {
send(msg, LogLevel.DEBUG, new HashMap<String, String>());
}
public void send(String msg, LogLevel l, Map<String, String> fields) throws Exception {
send(msg, l, fields, null, null);
}
/**
* Sends a syslog message to the syslog server that was provided when the class was instantiated
*
* @param msg The syslog message text
* @param l Log level
* @param fields a Map<String, String> of key-value pairs that are appended to the message for easy parsing
* @param appName The name of the app emmitting the logs, if value is null the app is not set on the header of the message
* @param processId The pid of the process emmitting the logs, if value is null the pid is not set on the header of the message
* @throws Exception if something is wrong, likely - server unreachable
*/
public void send(String msg, LogLevel l, Map<String, String> fields, String appName, String processId) throws Exception {
checkParam(msg, "msg");
Map<String, String> myFields;
if (fields == null) {
myFields = new HashMap<String, String>();
} else {
myFields = fields;
}
Map<String, Map<String, String>> outMap = new HashMap<String, Map<String, String>>();
outMap.put("Fields", myFields);
StructuredSyslogMessage message = new StructuredSyslogMessage("", outMap, msg);
StructuredSyslogMessageProcessor processor = new StructuredSyslogMessageProcessor();
syslog.setMessageProcessor(processor);
if (appName != null) {
processor.setApplicationName(appName);
}
if (processId != null) {
processor.setProcessId(processId);
}
if (l.equals(LogLevel.ALERT)) {
syslog.alert(message);
} else if (l.equals(LogLevel.CRITICAL)) {
syslog.critical(message);
} else if (l.equals(LogLevel.DEBUG)) {
syslog.debug(message);
} else if (l.equals(LogLevel.ERROR)) {
syslog.error(message);
} else if (l.equals(LogLevel.INFO)) {
syslog.info(message);
} else if (l.equals(LogLevel.WARN)) {
syslog.warn(message);
}
syslog.flush();
}
} |
package teamwap.wap;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.support.design.widget.FloatingActionButton;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.content.Intent;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.Toast;
import java.text.DateFormat;
import java.util.ArrayList;
import java.io.*;
import java.util.Date;
import java.util.List;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.res.Resources;
import android.graphics.BitmapFactory;
import android.support.v7.app.NotificationCompat;
import com.google.android.gms.appindexing.Action;
import com.google.android.gms.appindexing.AppIndex;
import com.google.android.gms.appindexing.Thing;
import com.google.android.gms.common.api.GoogleApiClient;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import java.lang.ClassNotFoundException;
public class MainActivity extends AppCompatActivity implements ListViewBtnAdapter.ListBtnClickListener{
Button button1;
Button button2;
Button button3;
ArrayList<webtoonIn> webtoonInL = new ArrayList<webtoonIn>();
File f;
private GoogleApiClient client;
private BackPressCloseHandler backPressCloseHandler;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayShowHomeEnabled(true);
getSupportActionBar().setIcon(R.mipmap.ic_launcher2);
backPressCloseHandler = new BackPressCloseHandler(this);
ListView listView;
ListViewBtnAdapter adapter;
final ArrayList<ListViewBtnItem> items = new ArrayList<ListViewBtnItem>();
loadItemsFromDB(items);
adapter = new ListViewBtnAdapter(this, R.layout.listview_btn_item, items, this);
listView = (ListView) findViewById(R.id.listview);
listView.setAdapter(adapter);
button1 = (Button) findViewById(R.id.button1);
button1.setBackgroundColor(Color.BLACK);
button1.setTextColor(Color.WHITE);
button1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(getApplicationContext(), " .", Toast.LENGTH_SHORT).show();
Intent mIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://comic.naver.com/webtoon/weekday.nhn"));
startActivity(mIntent);
}
});
button2 = (Button) findViewById(R.id.button2);
button2.setBackgroundColor(Color.BLACK);
button2.setTextColor(Color.WHITE);
button2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(getApplicationContext(), " .", Toast.LENGTH_SHORT).show();
Intent mIntent2 = new Intent(Intent.ACTION_VIEW, Uri.parse("http://m.comic.naver.com/webtoon/list.nhn?titleId=675554&week=thu"));
startActivity(mIntent2);
}
});
/*button3.setOnClickListener(new View.OnClickListener(){
@Override public void onClick(View v){
int i;
f = new java.io.File(getFilesDir(),"webtoonInfor.dat");
ObjectInputStream ois = null;
ArrayList list;
try {
ois = new ObjectInputStream(new FileInputStream(f));
list = (ArrayList) ois.readObject();
}catch(IOException ioe){
ioe.printStackTrace();
}
for (i=0; i < list.size(); i++){
webtoonInL.add(list.get(i));
}
Toast.makeText(getApplicationContext(), webtoonInL.get(0).get_name(), Toast.LENGTH_SHORT).show();
}
});
*/
/* NotificationSomethings */
button3 = (Button) findViewById(R.id.button3);
button3.setBackgroundColor(Color.BLACK);
button3.setTextColor(Color.WHITE);
button3.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
NotificationSomethings();
}
});
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
LinearLayout layout = new LinearLayout(MainActivity.this);
layout.setOrientation(LinearLayout.VERTICAL);
final EditText etName = new EditText(MainActivity.this);
etName.setHint(" ");
final EditText etURL = new EditText(MainActivity.this);
etURL.setHint(" URL ");
layout.addView(etName);
layout.addView(etURL);
AlertDialog.Builder dialog = new AlertDialog.Builder(MainActivity.this);
dialog.setTitle(" ")
.setView(layout)
.setPositiveButton("", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String name = etName.getText().toString();
String url = etURL.getText().toString();
webtoonIn webtoon = new webtoonIn(name, url);
webtoonInL.add(webtoon);
f = new File(getFilesDir(), "webtoonInfor.dat");
try {
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(f));
oos.writeObject(webtoonInL);
} catch (IOException ioe) {
ioe.printStackTrace();
}
Toast.makeText(getApplicationContext(), ".", Toast.LENGTH_SHORT).show();
items.clear();
webtoonInL.clear();
loadItemsFromDB(items);
restarLlistView(items);
}, 500);//*/
}, 500);//*/
/*
listView.setOnClickListener(new AdapterView.OnItemClickListener(){
@Override
public void onItemClick(AdapterView parent, View v, int position, long id){
// TODO : item click
}
});
*/
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
Intent set = new Intent(getApplicationContext(), SettingsActivity.class);
startActivity(set);
return true;
}
return super.onOptionsItemSelected(item);
}
public void NotificationSomethings() {
Resources res = getResources();
Intent notificationIntent = new Intent(this, NotificationSomething.class);
notificationIntent.putExtra("notificationId", 9999);
PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
builder.setContentTitle(" .")
.setContentText(" !")
.setTicker(" .")
.setSmallIcon(R.mipmap.ic_launcher)
.setLargeIcon(BitmapFactory.decodeResource(res, R.mipmap.ic_launcher))
.setContentIntent(contentIntent)
.setAutoCancel(true)
.setWhen(System.currentTimeMillis())
.setDefaults(Notification.DEFAULT_ALL);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
builder.setCategory(Notification.CATEGORY_MESSAGE)
.setPriority(Notification.PRIORITY_HIGH)
.setVisibility(Notification.VISIBILITY_PUBLIC);
}
NotificationManager nm = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
nm.notify(1234, builder.build());
}
public Action getIndexApiAction() {
Thing object = new Thing.Builder()
.setName("Main Page") // TODO: Define a title for the content shown.
// TODO: Make sure this auto-generated URL is correct.
.setUrl(Uri.parse("http://[ENTER-YOUR-URL-HERE]"))
.build();
return new Action.Builder(Action.TYPE_VIEW)
.setObject(object)
.setActionStatus(Action.STATUS_TYPE_COMPLETED)
.build();
}
@Override
public void onStart() {
super.onStart();
client.connect();
AppIndex.AppIndexApi.start(client, getIndexApiAction());
}
@Override
public void onStop() {
super.onStop();
AppIndex.AppIndexApi.end(client, getIndexApiAction());
client.disconnect();
}
@Override
public void onBackPressed() {
backPressCloseHandler.onBackPressed();
}
/*
String currentDateTimeString = DateFormat.getDateTimeInstance().format(new Date());
//
// .
textView.setText(currentDateTimeString); */
public boolean loadFromData(ArrayList<webtoonIn> list){
int i;
f = new java.io.File(getFilesDir(),"webtoonInfor.dat");
ObjectInputStream ois = null;
ArrayList list2;
try {
ois = new ObjectInputStream(new FileInputStream(f));
try{
list2 = (ArrayList) ois.readObject();
for (i=0; i < list2.size(); i++){
webtoonIn input = (webtoonIn)list2.get(i);
list.add(input);
}
}catch(ClassNotFoundException e){
e.printStackTrace();
}
}catch(IOException ioe){
ioe.printStackTrace();
}
return true;
}
public boolean loadItemsFromDB(ArrayList<ListViewBtnItem> list){
// loadFromData .
webtoonInL.clear();
loadFromData(webtoonInL);
ListViewBtnItem item;
int i;
if (list == null){
list = new ArrayList<ListViewBtnItem>();
}
i = 0;
while(i < webtoonInL.size()){
item = new ListViewBtnItem();
item.setIcon(ContextCompat.getDrawable(this, R.mipmap.ic_launcher));
webtoonIn webtoonIn1 = webtoonInL.get(i);
String name = webtoonIn1.get_name();
item.setText(name);
list.add(item);
i++;
}
return true;
}
@Override
public void onListBtnClick(int position) {
webtoonIn webtoonIn1 = webtoonInL.get(position);
String name = webtoonIn1.get_name();
String urll = webtoonIn1.get_url();
Toast.makeText(getApplicationContext(), name + " .", Toast.LENGTH_SHORT).show();
Intent mIntent2 = new Intent(Intent.ACTION_VIEW, Uri.parse(urll));
startActivity(mIntent2);
}
public void restarLlistView(ArrayList<ListViewBtnItem> items){
ListView listView;
ListViewBtnAdapter adapter;
items = new ArrayList<ListViewBtnItem>();
loadItemsFromDB(items);
adapter = new ListViewBtnAdapter(this, R.layout.listview_btn_item, items, this);
listView = (ListView) findViewById(R.id.listview);
listView.setAdapter(adapter);
}
} |
package com.lightcrafts.jai;
import com.lightcrafts.jai.operator.*;
import com.lightcrafts.jai.opimage.*;
import com.lightcrafts.jai.utils.LCTileCache;
import com.lightcrafts.jai.utils.LCRecyclingTileFactory;
import com.lightcrafts.image.color.ColorScience;
import com.lightcrafts.image.color.ColorProfileInfo;
import com.lightcrafts.platform.Platform;
import com.sun.media.jai.util.SunTileCache;
import javax.media.jai.JAI;
import javax.media.jai.OperationDescriptor;
import javax.media.jai.OperationRegistry;
import javax.media.jai.RasterFactory;
import javax.media.jai.TileCache;
import javax.media.jai.TileFactory;
import javax.media.jai.registry.CRIFRegistry;
import javax.media.jai.registry.RIFRegistry;
import java.awt.*;
import java.awt.color.ColorSpace;
import java.awt.color.ICC_ColorSpace;
import java.awt.color.ICC_Profile;
import java.awt.image.*;
import java.awt.image.renderable.ContextualRenderedImageFactory;
import java.awt.image.renderable.RenderedImageFactory;
import java.io.*;
import java.util.Collection;
import java.util.ArrayList;
public class JAIContext {
public static final Collection<ColorProfileInfo> systemProfiles;
public static final ICC_Profile linearProfile;
public static final ICC_ColorSpace linearColorSpace;
public static final ICC_Profile labProfile;
public static final ICC_ColorSpace labColorSpace;
public static final ICC_Profile gray22Profile;
public static final ICC_ColorSpace gray22ColorSpace;
public static final ICC_Profile oldLinearProfile;
public static final ICC_ColorSpace oldLinearColorSpace;
public static final ICC_Profile CMYKProfile;
public static final ICC_ColorSpace CMYKColorSpace;
public static final ICC_Profile systemProfile;
public static final ColorSpace systemColorSpace;
public static final ICC_ColorSpace linearGrayColorSpace = (ICC_ColorSpace) ColorSpace.getInstance(ColorSpace.CS_GRAY);
public static final ICC_ColorSpace sRGBColorSpace;
public static final ICC_Profile sRGBColorProfile;
public static final ICC_Profile sRGBExportColorProfile;
public static final ICC_Profile adobeRGBProfile;
public static final ColorSpace adobeRGBColorSpace;
public static final ColorModel colorModel_linear16;
public static final ColorModel colorModel_linear8;
public static final ColorModel colorModel_sRGB16;
public static final ColorModel colorModel_sRGB8;
public static final ColorModel systemColorModel;
public static final RenderingHints noCacheHint;
public static final String PERSISTENT_CACHE_TAG = "LCPersistentCache";
public static final TileCache noTileCache = new SunTileCache(0);
public static final RenderingHints fileCacheHint;
public static final TileCache fileCache;
public static final TileCache defaultTileCache;
/** Tile dimensions. */
public static final int TILE_WIDTH = 512;
public static final int TILE_HEIGHT = 512;
// public static final int fastMode = DataBuffer.TYPE_BYTE;
// public static final int preciseMode = DataBuffer.TYPE_USHORT;
static void dumpProperty(ICC_Profile profile, int tag, String name)
{
byte[] data = profile.getData(tag);
if (data != null) {
System.out.print(name + " (" + data.length + ") :");
for (byte aData : data)
System.out.print(" " + (aData & 0xFF));
System.out.println();
for (byte aData : data)
System.out.print((char) (aData & 0xFF));
System.out.println();
} else {
System.out.println("no " + name + " info");
}
}
/**
* Given a {@link ColorSpace} and a {@link Raster}, get the
* {@link ColorModel} for them.
*
* @param colorSpace The {@link ColorSpace}.
* @param raster The {@link Raster}.
* @return Returns the relevant {@link ColorModel} or <code>null</code> if
* none can be determined.
*/
public static ColorModel getColorModelFrom( ColorSpace colorSpace,
Raster raster ) {
return new ComponentColorModel(
colorSpace, false, false, Transparency.OPAQUE,
raster.getSampleModel().getDataType()
);
}
/**
* Given an {@link ICC_Profile} and a {@link Raster}, get the
* {@link ColorModel} for them.
*
* @param profile The {@link ICC_Profile}.
* @param raster The {@link Raster}.
* @return Returns the relevant {@link ColorModel} or <code>null</code> if
* none can be determined.
*/
public static ColorModel getColorModelFrom( ICC_Profile profile,
Raster raster ) {
return getColorModelFrom(
getColorSpaceFrom( profile, raster ), raster
);
}
/**
* Given an {@link ICC_Profile} and a {@link Raster}, get the
* {@link ColorSpace} for them.
*
* @param profile The {@link ICC_Profile}.
* @param raster The {@link Raster}.
* @return Returns the relevant {@link ColorSpace} or <code>null</code> if
* none can be determined.
*/
public static ColorSpace getColorSpaceFrom( ICC_Profile profile,
Raster raster ) {
if ( profile != null )
return new ICC_ColorSpace( profile );
switch ( raster.getSampleModel().getNumBands() ) {
case 1:
return gray22ColorSpace;
case 3:
return sRGBColorSpace;
case 4:
return CMYKColorSpace;
default:
return null;
}
}
static void zlum(ICC_ColorSpace cs) {
float[] zero;
synchronized (ColorSpace.class) {
zero = cs.fromCIEXYZ(new float[] {0, 0, 0});
}
System.out.println("zero: " + zero[0] + " : " + zero[1] + " : " + zero[2]);
double zlum = ColorScience.Wr * zero[0] + ColorScience.Wg * zero[1] + ColorScience.Wb * zero[2];
System.out.println("zero lum: " + zlum);
}
static {
final int MB = 1024 * 1024;
final long maxMemory = Runtime.getRuntime().maxMemory(); // -Xmx
final long totalMemory = Runtime.getRuntime().totalMemory(); // -Xms
System.out.printf("Max Memory: %6d MB%n", maxMemory / MB);
System.out.printf("Total Memory: %6d MB%n", totalMemory / MB);
JAI jaiInstance = JAI.getDefaultInstance();
// Use our own Tile Scheduler -- TODO: Needs more testing
// jaiInstance.setTileScheduler(new LCTileScheduler());
final int processors = Runtime.getRuntime().availableProcessors();
System.out.println("Running on " + processors + " processors");
// Use multiple procs only if we have enough heap
final int parallelism = (maxMemory >= 400 * MB) ? processors : 1;
jaiInstance.getTileScheduler().setParallelism(parallelism);
jaiInstance.getTileScheduler().setPrefetchParallelism(parallelism);
jaiInstance.getTileScheduler().setPrefetchPriority(7);
jaiInstance.getTileScheduler().setPriority(7);
final long tileCacheMemory = (maxMemory <= 2048L * MB)
? maxMemory / 2
: maxMemory - 1024 * MB;
System.out.printf("Tile Cache: %6d MB%n", tileCacheMemory / MB);
fileCache = new LCTileCache(tileCacheMemory, true);
// fileCache.setMemoryThreshold(0.5f);
jaiInstance.setTileCache(fileCache);
fileCacheHint = new RenderingHints(JAI.KEY_TILE_CACHE, fileCache);
defaultTileCache = jaiInstance.getTileCache();
TileFactory rtf = new LCRecyclingTileFactory();
jaiInstance.setRenderingHint(JAI.KEY_TILE_FACTORY, rtf);
jaiInstance.setRenderingHint(JAI.KEY_TILE_RECYCLER, rtf);
// TODO: causes rendering artifacts
// jaiInstance.setRenderingHint(JAI.KEY_CACHED_TILE_RECYCLING_ENABLED, Boolean.TRUE);
JAI.setDefaultTileSize(new Dimension(TILE_WIDTH, TILE_HEIGHT));
OperationRegistry or = jaiInstance.getOperationRegistry();
// register LCColorConvert
OperationDescriptor desc = new LCColorConvertDescriptor();
or.registerDescriptor(desc);
ContextualRenderedImageFactory crif = new LCColorConvertCRIF();
RIFRegistry.register(or, desc.getName(), "com.lightcrafts", crif);
CRIFRegistry.register(or, desc.getName(), crif);
// register LCMSColorConvert
desc = new LCMSColorConvertDescriptor();
or.registerDescriptor(desc);
crif = new LCMSColorConvertCRIF();
RIFRegistry.register(or, desc.getName(), "com.lightcrafts", crif);
CRIFRegistry.register(or, desc.getName(), crif);
// register BlendOp
desc = new BlendDescriptor();
or.registerDescriptor(desc);
crif = new BlendCRIF();
RIFRegistry.register(or, desc.getName(), "com.lightcrafts", crif);
CRIFRegistry.register(or, desc.getName(), crif);
// register LCSeparableConvolve
desc = new LCSeparableConvolveDescriptor();
or.registerDescriptor(desc);
RenderedImageFactory rif = new LCSeparableConvolveRIF();
RIFRegistry.register(or, desc.getName(), "com.lightcrafts", rif);
// register NOPOp
desc = new NOPDescriptor();
or.registerDescriptor(desc);
crif = new NOPCRIF();
RIFRegistry.register(or, desc.getName(), "com.lightcrafts", crif);
CRIFRegistry.register(or, desc.getName(), crif);
// register UnSharpMaskOp
desc = new UnSharpMaskDescriptor();
or.registerDescriptor(desc);
crif = new UnSharpMaskCRIF();
RIFRegistry.register(or, desc.getName(), "com.lightcrafts", crif);
CRIFRegistry.register(or, desc.getName(), crif);
// register LCErode
desc = new LCErodeDescriptor();
or.registerDescriptor(desc);
rif = new LCErodeRIF();
RIFRegistry.register(or, desc.getName(), "com.lightcrafts", rif);
// register RawAdjustments
desc = new RawAdjustmentsDescriptor();
or.registerDescriptor(desc);
rif = new RawAdjustmentsCRIF();
RIFRegistry.register(or, desc.getName(), "com.lightcrafts", rif);
// register LCBandCombine
desc = new LCBandCombineDescriptor();
or.registerDescriptor(desc);
rif = new LCBandCombineCRIF();
RIFRegistry.register(or, desc.getName(), "com.lightcrafts", rif);
// register LCBandCombine
desc = new BilateralFilterDescriptor();
or.registerDescriptor(desc);
rif = new BilateralFilterRIF();
RIFRegistry.register(or, desc.getName(), "com.lightcrafts", rif);
systemProfiles = new ArrayList<>();
final Collection<ColorProfileInfo> exportProfiles =
Platform.getPlatform().getExportProfiles();
if (exportProfiles != null) {
systemProfiles.addAll(exportProfiles);
}
final Collection<ColorProfileInfo> printerProfiles =
Platform.getPlatform().getPrinterProfiles();
if (printerProfiles != null) {
systemProfiles.addAll(printerProfiles);
}
ICC_Profile _sRGBColorProfile = null;
for (ColorProfileInfo cpi : systemProfiles) {
final String cpiName = cpi.getName();
if ((cpiName.equals("sRGB Profile") || cpiName.equals("sRGB IEC61966-2.1"))) {
try {
_sRGBColorProfile = ICC_Profile.getInstance(cpi.getPath());
System.out.println("found " + cpiName);
if (_sRGBColorProfile != null)
break;
} catch (IOException e) {
e.printStackTrace();
}
}
}
if (_sRGBColorProfile == null) {
InputStream in = JAIContext.class.getResourceAsStream("resources/sRGB.icc");
try {
_sRGBColorProfile = ICC_Profile.getInstance(in);
} catch (IOException e) {
System.err.println("Can't load resource sRGB profile, defaulting on Java's");
_sRGBColorProfile = ICC_Profile.getInstance(ColorSpace.CS_sRGB);
}
}
sRGBExportColorProfile = _sRGBColorProfile;
sRGBColorProfile = ICC_Profile.getInstance(ColorSpace.CS_sRGB);
sRGBColorSpace = (ICC_ColorSpace) ColorSpace.getInstance(ColorSpace.CS_sRGB);
ICC_Profile _linearProfile;
ICC_Profile _oldLinearProfile;
ICC_Profile _labProfile;
// ICC_Profile _uniformLabProfile;
ICC_Profile _gray22Profile;
ICC_Profile _adobeRGBProfile;
ICC_ColorSpace _linearColorSpace;
ICC_ColorSpace _oldLinearColorSpace;
ICC_ColorSpace _labColorSpace;
// ICC_ColorSpace _uniformLabColorSpace;
ICC_ColorSpace _gray22ColorSpace;
ICC_ColorSpace _adobeRGBColorSpace;
ColorModel _colorModel_linear16;
ColorModel _colorModel_linear8;
ColorModel _colorModel_sRGB16;
ColorModel _colorModel_sRGB8;
ICC_Profile _CMYKProfile;
ICC_ColorSpace _CMYKColorSpace;
RenderingHints _noCacheHint;
ICC_Profile _systemProfile;
ICC_ColorSpace _systemColorSpace;
ColorModel _systemColorModel;
try {
InputStream in = JAIContext.class.getResourceAsStream("resources/rimm.icm");
_linearProfile = ICC_Profile.getInstance(in);
_linearColorSpace = new ICC_ColorSpace(_linearProfile);
in = JAIContext.class.getResourceAsStream("resources/CIE 1931 D50 Gamma 1.icm");
_oldLinearProfile = ICC_Profile.getInstance(in);
_oldLinearColorSpace = new ICC_ColorSpace(_linearProfile);
in = JAIContext.class.getResourceAsStream("resources/Generic CMYK Profile.icc");
_CMYKProfile = ICC_Profile.getInstance(in);
_CMYKColorSpace = new ICC_ColorSpace(_CMYKProfile);
in = JAIContext.class.getResourceAsStream("resources/Generic Lab Profile.icm");
_labProfile = ICC_Profile.getInstance(in);
_labColorSpace = new ICC_ColorSpace(_labProfile);
in = JAIContext.class.getResourceAsStream("resources/Gray Gamma 2.2.icc");
_gray22Profile = ICC_Profile.getInstance(in);
_gray22ColorSpace = new ICC_ColorSpace(_gray22Profile);
in = JAIContext.class.getResourceAsStream("resources/compatibleWithAdobeRGB1998.icc");
_adobeRGBProfile = ICC_Profile.getInstance(in);
_adobeRGBColorSpace = new ICC_ColorSpace(_adobeRGBProfile);
_colorModel_linear16 =
RasterFactory.createComponentColorModel(DataBuffer.TYPE_USHORT,
_linearColorSpace,
false,
false,
Transparency.OPAQUE);
_colorModel_linear8 =
RasterFactory.createComponentColorModel(DataBuffer.TYPE_BYTE,
_linearColorSpace,
false,
false,
Transparency.OPAQUE);
_colorModel_sRGB16 =
RasterFactory.createComponentColorModel(DataBuffer.TYPE_USHORT,
sRGBColorSpace,
false,
false,
Transparency.OPAQUE);
_colorModel_sRGB8 =
RasterFactory.createComponentColorModel(DataBuffer.TYPE_BYTE,
sRGBColorSpace,
false,
false,
Transparency.OPAQUE);
_systemColorSpace = sRGBColorSpace;
_systemColorModel = _colorModel_sRGB8;
_systemProfile = _sRGBColorProfile;
try {
final ICC_Profile displayProfile = Platform.getPlatform().getDisplayProfile();
if (displayProfile != null) {
_systemProfile = displayProfile;
_systemColorSpace = new ICC_ColorSpace(_systemProfile);
_systemColorModel = RasterFactory.createComponentColorModel(DataBuffer.TYPE_BYTE,
_systemColorSpace,
false,
false,
Transparency.OPAQUE);
}
} catch (Exception e) {
e.printStackTrace();
}
_noCacheHint = new RenderingHints(JAI.KEY_TILE_CACHE, noTileCache);
// _noCacheHint = new RenderingHints(JAI.KEY_TILE_CACHE, defaultTileCache);
} catch (IOException e) {
e.printStackTrace();
// Rethrow so the Application will notice the problem:
throw new RuntimeException(
"Couldn't access color space resource",
e
);
}
linearProfile = _linearProfile;
linearColorSpace = _linearColorSpace;
oldLinearProfile = _oldLinearProfile;
oldLinearColorSpace = _oldLinearColorSpace;
colorModel_linear16 = _colorModel_linear16;
colorModel_linear8 = _colorModel_linear8;
colorModel_sRGB16 = _colorModel_sRGB16;
colorModel_sRGB8 = _colorModel_sRGB8;
CMYKProfile = _CMYKProfile;
CMYKColorSpace = _CMYKColorSpace;
labProfile = _labProfile;
labColorSpace = _labColorSpace;
gray22Profile = _gray22Profile;
gray22ColorSpace = _gray22ColorSpace;
adobeRGBProfile = _adobeRGBProfile;
adobeRGBColorSpace = _adobeRGBColorSpace;
systemProfile = _systemProfile;
systemColorSpace = _systemColorSpace;
systemColorModel = _systemColorModel;
noCacheHint = _noCacheHint;
}
}
/* vim:set et sw=4 ts=4: */ |
package com.mychess.mychess;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.IBinder;
import android.speech.RecognitionListener;
import android.speech.RecognizerIntent;
import android.speech.SpeechRecognizer;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.mychess.mychess.Chess.Chess;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.Socket;
import java.util.ArrayList;
public class Juego extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener, View.OnClickListener {
Servicio mService;
boolean mBound = false;
ImageView casillas[][] = new ImageView[8][8];
ImageView origen;
ImageView destino;
TextView tiempo;
Tiempo tiempoMovimiento;
int cOrigen;
int cDestino;
int fOrigen;
int fDestino;
Chess chess;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_juego);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
inicializarCasillas();
setOnclickListener();
setDefaultColor();
tiempo = (TextView) findViewById(R.id.textView18);
tiempoMovimiento = new Tiempo();
tiempoMovimiento.iniciar();
/* inicializcion del nuevo juego*/
chess = new Chess();
chess.newGame();
new SocketServidor().conectar();
RecibirMovimientos recibirMovimientos = new RecibirMovimientos();
recibirMovimientos.execute();
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
SpeechRecognizer speechRecognizer = SpeechRecognizer.createSpeechRecognizer(Juego.this);
Speech speech = new Speech();
speechRecognizer.setRecognitionListener(speech);
Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
speechRecognizer.startListening(intent);
}
});
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
}
@Override
protected void onStart() {
super.onStart();
Intent intent = new Intent(this, Servicio.class);
bindService(intent, mConnection, Context.BIND_AUTO_CREATE);
}
private ServiceConnection mConnection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
Servicio.LocalBinder binder = (Servicio.LocalBinder) service;
mService = binder.getService();
mBound = true;
}
@Override
public void onServiceDisconnected(ComponentName name) {
mBound = false;
}
};
@Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.juego, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
return super.onOptionsItemSelected(item);
}
@SuppressWarnings("StatementWithEmptyBody")
@Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.jugar) {
// Handle the camera action
} else if (id == R.id.amigos) {
Intent intent = new Intent(Juego.this, Amigos.class);
startActivity(intent);
} else if (id == R.id.logout) {
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
private void inicializarCasillas() {
casillas[0][0] = (ImageView) findViewById(R.id.a8);
casillas[0][1] = (ImageView) findViewById(R.id.a7);
casillas[0][2] = (ImageView) findViewById(R.id.a6);
casillas[0][3] = (ImageView) findViewById(R.id.a5);
casillas[0][4] = (ImageView) findViewById(R.id.a4);
casillas[0][5] = (ImageView) findViewById(R.id.a3);
casillas[0][6] = (ImageView) findViewById(R.id.a2);
casillas[0][7] = (ImageView) findViewById(R.id.a1);
casillas[1][0] = (ImageView) findViewById(R.id.b8);
casillas[1][1] = (ImageView) findViewById(R.id.b7);
casillas[1][2] = (ImageView) findViewById(R.id.b6);
casillas[1][3] = (ImageView) findViewById(R.id.b5);
casillas[1][4] = (ImageView) findViewById(R.id.b4);
casillas[1][5] = (ImageView) findViewById(R.id.b3);
casillas[1][6] = (ImageView) findViewById(R.id.b2);
casillas[1][7] = (ImageView) findViewById(R.id.b1);
casillas[2][0] = (ImageView) findViewById(R.id.c8);
casillas[2][1] = (ImageView) findViewById(R.id.c7);
casillas[2][2] = (ImageView) findViewById(R.id.c6);
casillas[2][3] = (ImageView) findViewById(R.id.c5);
casillas[2][4] = (ImageView) findViewById(R.id.c4);
casillas[2][5] = (ImageView) findViewById(R.id.c3);
casillas[2][6] = (ImageView) findViewById(R.id.c2);
casillas[2][7] = (ImageView) findViewById(R.id.c1);
casillas[3][0] = (ImageView) findViewById(R.id.d8);
casillas[3][1] = (ImageView) findViewById(R.id.d7);
casillas[3][2] = (ImageView) findViewById(R.id.d6);
casillas[3][3] = (ImageView) findViewById(R.id.d5);
casillas[3][4] = (ImageView) findViewById(R.id.d4);
casillas[3][5] = (ImageView) findViewById(R.id.d3);
casillas[3][6] = (ImageView) findViewById(R.id.d2);
casillas[3][7] = (ImageView) findViewById(R.id.d1);
casillas[4][0] = (ImageView) findViewById(R.id.e8);
casillas[4][1] = (ImageView) findViewById(R.id.e7);
casillas[4][2] = (ImageView) findViewById(R.id.e6);
casillas[4][3] = (ImageView) findViewById(R.id.e5);
casillas[4][4] = (ImageView) findViewById(R.id.e4);
casillas[4][5] = (ImageView) findViewById(R.id.e3);
casillas[4][6] = (ImageView) findViewById(R.id.e2);
casillas[4][7] = (ImageView) findViewById(R.id.e1);
casillas[5][0] = (ImageView) findViewById(R.id.f8);
casillas[5][1] = (ImageView) findViewById(R.id.f7);
casillas[5][2] = (ImageView) findViewById(R.id.f6);
casillas[5][3] = (ImageView) findViewById(R.id.f5);
casillas[5][4] = (ImageView) findViewById(R.id.f4);
casillas[5][5] = (ImageView) findViewById(R.id.f3);
casillas[5][6] = (ImageView) findViewById(R.id.f2);
casillas[5][7] = (ImageView) findViewById(R.id.f1);
casillas[6][0] = (ImageView) findViewById(R.id.g8);
casillas[6][1] = (ImageView) findViewById(R.id.g7);
casillas[6][2] = (ImageView) findViewById(R.id.g6);
casillas[6][3] = (ImageView) findViewById(R.id.g5);
casillas[6][4] = (ImageView) findViewById(R.id.g4);
casillas[6][5] = (ImageView) findViewById(R.id.g3);
casillas[6][6] = (ImageView) findViewById(R.id.g2);
casillas[6][7] = (ImageView) findViewById(R.id.g1);
casillas[7][0] = (ImageView) findViewById(R.id.h8);
casillas[7][1] = (ImageView) findViewById(R.id.h7);
casillas[7][2] = (ImageView) findViewById(R.id.h6);
casillas[7][3] = (ImageView) findViewById(R.id.h5);
casillas[7][4] = (ImageView) findViewById(R.id.h4);
casillas[7][5] = (ImageView) findViewById(R.id.h3);
casillas[7][6] = (ImageView) findViewById(R.id.h2);
casillas[7][7] = (ImageView) findViewById(R.id.h1);
}
private void setDefaultColor() {
boolean dark = true;
for (int i = 0; i < 8; ++i) {
for (int j = 0; j < 8; ++j) {
if (dark)
casillas[i][j].setBackgroundColor(Color.parseColor("#7986CB"));
else
casillas[i][j].setBackgroundColor(Color.parseColor("#C5CAE9"));
dark = !dark;
}
dark = !dark;
}
}
private void setOnclickListener() {
for (int i = 0; i < 8; ++i) {
for (int j = 0; j < 8; ++j) {
casillas[i][j].setOnClickListener(this);
}
}
}
private int[] getPosition(int id) {
int position[] = {-1, -1};
for (int i = 0; i < 8; ++i) {
for (int j = 0; j < 8; ++j) {
if (id == casillas[i][j].getId()) {
position[0] = i;
position[1] = j;
return position;//si el click fue en una casilla se retorna la posicion
}
}
}
return position;//si el click no fue en una casilla se devuelven valores negativos en la posicion
}
private boolean validarCoordenadas(String coordenadas) {
final String columnas = "abcdefgh";
final String filas = "87654321";
cOrigen = columnas.indexOf(coordenadas.charAt(0));
cDestino = columnas.indexOf(coordenadas.charAt(2));
fOrigen = filas.indexOf(coordenadas.charAt(1));
fDestino = filas.indexOf(coordenadas.charAt(3));
if(cOrigen == -1 || cDestino == -1 || fOrigen == -1 || fDestino == -1)
return false;
return true;
}
private void procesarResultados(ArrayList<String> listaCoordenadas) {
String coordenadas;
for (int i = 0; i < listaCoordenadas.size(); ++i) {
coordenadas = listaCoordenadas.get(i).replace(" ", "").toLowerCase();
if (coordenadas.length() == 4) {
if (validarCoordenadas(coordenadas)) {
validarMovimiento(coordenadas);
break;
}
}
}
}
private void enviarMovimiento(String coordendas) {
DataOutputStream out = null;
try {
out = new DataOutputStream(SocketServidor.getSocket().getOutputStream());
out.writeUTF(coordendas);
} catch (IOException e) {
e.printStackTrace();
}
}
private void validarMovimiento(String coordenadas){
switch (chess.mover(coordenadas.substring(0,2),coordenadas.substring(2,4)))
{
case 0:
moverPieza();
break;
case 1:
break;
case 2:
Toast.makeText(Juego.this, "movimiento no valido", Toast.LENGTH_SHORT).show();
break;
case 3:
break;
case 4:
Toast.makeText(Juego.this, "movimiento no valido", Toast.LENGTH_SHORT).show();
break;
}
}
private void moverPieza(){
casillas[cDestino][fDestino].setImageDrawable(casillas[cOrigen][fOrigen].getDrawable());
casillas[cOrigen][fOrigen].setImageDrawable(null);
}
private String crearCoordenada() {
String coordenada = "";
final String columnas = "abcdefgh";
final String filas = "87654321";
coordenada += columnas.charAt(cOrigen);
coordenada += filas.charAt(fOrigen);
coordenada += columnas.charAt(cDestino);
coordenada += filas.charAt(fDestino);
return coordenada;
}
@Override
public void onClick(View v) {
int position[] = getPosition(v.getId());
if (position[0] != -1) {//si el valor es negativo indica que el click no se realizo en una casilla
if (origen == null) {
origen = casillas[position[0]][position[1]];
cOrigen = position[0];
fOrigen = position[1];
} else {
origen = null;
cDestino = position[0];
fDestino = position[1];
}
}
}
class Speech implements RecognitionListener {
@Override
public void onReadyForSpeech(Bundle params) {
}
@Override
public void onBeginningOfSpeech() {
}
@Override
public void onRmsChanged(float rmsdB) {
}
@Override
public void onBufferReceived(byte[] buffer) {
}
@Override
public void onEndOfSpeech() {
}
@Override
public void onError(int error) {
}
@Override
public void onResults(Bundle results) {
ArrayList<String> listaPalabras = results.getStringArrayList(SpeechRecognizer.RESULTS_RECOGNITION);
procesarResultados(listaPalabras);
}
@Override
public void onPartialResults(Bundle partialResults) {
}
@Override
public void onEvent(int eventType, Bundle params) {
}
}
class Tiempo {
CountDown countDown;
public void iniciar() {
countDown = new CountDown(60000, 1000);
countDown.start();
}
public void detener() {
countDown.cancel();
}
public void reiniciar() {
tiempo.setText("60");
tiempo.setTextColor(Color.WHITE);
countDown.cancel();
}
class CountDown extends CountDownTimer {
public CountDown(long millisInFuture, long countDownInterval) {
super(millisInFuture, countDownInterval);
}
@Override
public void onTick(long millisUntilFinished) {
long time = millisUntilFinished / 1000;
tiempo.setText(String.valueOf(time));
if (time == 15)
tiempo.setTextColor(Color.RED);
}
@Override
public void onFinish() {
}
}
}
class RecibirMovimientos extends AsyncTask<Void, String, Boolean> {
Socket socket;
protected Boolean doInBackground(Void... params) {
socket = SocketServidor.getSocket();
boolean continuar = true;
while (continuar) {
try {
Thread.sleep(250);
InputStream fromServer = socket.getInputStream();
DataInputStream in = new DataInputStream(fromServer);
publishProgress(in.readUTF());
} catch (Exception ex) {
}
}
return null;
}
@Override
protected void onProgressUpdate(String... values) {
super.onProgressUpdate(values);
validarCoordenadas(values[0]);
}
}
} |
package com.sababado.mcpubs;
import android.content.Context;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import android.support.annotation.StringDef;
import com.sababado.mcpubs.models.Pub;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.text.SimpleDateFormat;
import java.util.List;
import java.util.Locale;
public class Utils {
public static final SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("dd MMM yyyy", Locale.getDefault());
public static final long DAY = 1000 * 60 * 60 * 24;
public static final long WEEK = DAY * 7;
public static final String SP_FIREBASE_PUSH = "firebasePush";
public static final String LAST_KEEP_ALIVE = "last_keep_alive";
public static final String DEVICE_TOKEN = "device_token";
@Retention(RetentionPolicy.SOURCE)
@StringDef({LAST_KEEP_ALIVE, DEVICE_TOKEN})
public @interface SpKey {
}
public static void setMetaData(Context context, @SpKey String key, String value) {
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context);
sp.edit().putString(key, value).apply();
}
public static String getMetaData(Context context, @SpKey String key) {
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context);
return sp.getString(key, null);
}
public static void setMetaData(Context context, @SpKey String key, long value) {
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context);
sp.edit().putLong(key, value).apply();
}
public static long getLongMetaData(Context context, @SpKey String key) {
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context);
return sp.getLong(key, 0L);
}
public static boolean isPastTimeWithinTime(long timeToCheck, long timePeriod) {
long now = System.currentTimeMillis();
return now - timeToCheck <= timePeriod;
}
public static String getDt(Context context) {
SharedPreferences sharedPreferences = context.getSharedPreferences(Utils.SP_FIREBASE_PUSH, Context.MODE_PRIVATE);
return sharedPreferences.getString(Utils.DEVICE_TOKEN, null);
}
public static Pub findPubByServerId(List<Pub> pubsList, long serverId) {
for (Pub pub : pubsList) {
if (pub.getPubServerId() == serverId) {
return pub;
}
}
return null;
}
} |
import org.libelektra.*;
import org.libelektra.plugin.Echo;
/**
* Simple hello world to see how Elektra can be used in Java.
*/
public class HelloElektra {
public static void main(String[] args) {
// Example 1: create a Key and print it
System.out.println("Example 1");
final Key key = Key.create("user:/hello_world", "Hello World");
System.out.println(key); // to get name
System.out.println(key.getString());
System.out.println();
// Example 2: adding basename for Key
System.out.println("Example 2");
Key subKey = Key.create("user:/hello_world", "Sub Key");
subKey.addBaseName("sub_key");
System.out.println(subKey.getName());
System.out.println(subKey.getString());
System.out.println();
// Example 3: create a KeySet and print it
System.out.println("Example 3");
final KeySet ks = KeySet.create(10, Key.create("user:/hello_world2", "Hello World2"), key);
for (Key k : ks) {
System.out.println("iter: " + k.getName() + " " + k.getString());
}
System.out.println(ks);
System.out.println();
// Example 4: duplicating a KeySet
System.out.println("Example 4");
final KeySet ks2 = ks.dup();
ks2.copy(ks);
System.out.println(ks2.size());
ks2.append(ks);
ks2.append(key);
System.out.println();
// Example 5: reading from the KDB
System.out.println("Example 5");
try (final KDB kdb = KDB.open(key)) {
kdb.get(ks, key);
ks.lookup(key).ifPresent(k -> System.out.println(k.getString()));
} catch (KDBException e) {
System.out.println(e);
}
System.out.println();
// Example 6: manually calling a Plugin (normally not needed)
System.out.println("Example 6");
final Echo dp = new Echo();
dp.open(ks, key);
dp.get(ks, key);
dp.close(key);
System.out.println();
// Example 7: Keys support different types
System.out.println("Example 7");
final Key b = Key.create("user:/boolean", "true");
System.out.println(b.getBoolean());
b.setBoolean(false);
System.out.println(b.getBoolean());
System.out.println();
// Example 8: iterating over keyname parts of a Key
System.out.println("Example 8");
Key n = Key.create("user:/weird\\/name///\\\\/is/\no/_\\\\problem");
n.keyNameIterator().forEachRemaining(s -> System.out.println("itername: " + s));
System.out.println();
// Example 9: cutting part of a KeySet
System.out.println("Example 9");
Key cutpoint = Key.create("user:/cutpoint"),
ka = Key.create("user:/cutpoint/hello", "hiback"),
kb = Key.create("user:/cutpoint/hello2", "hellotoo"),
kc = Key.create("user:/outside/cutpoint/hello", "hellothere");
KeySet whole = KeySet.create(ka, kb, kc);
System.out.println("Whole:");
System.out.println(whole);
KeySet cut = whole.cut(cutpoint);
System.out.println("Cut:");
System.out.println(cut);
System.out.println("Rest:");
System.out.println(whole);
System.out.println();
exampleSetMetaKeys();
exampleSetArrayMetaKey();
exampleCheckKeyAvailableInKDB();
exampleUpdateMetaKey();
exampleKeyIterDumpMetaData();
}
private static void exampleSetMetaKeys() {
// Example 9: Set and get meta keys
System.out.println("Example 9");
Key key = Key.create("user:/key/with/meta");
key.setMeta("example", "anExampleValue");
var returnedMeta = key.getMeta("example").orElseThrow(AssertionError::new);
System.out.println("Value of meta key 'example': " + returnedMeta.getString());
System.out.println();
}
private static void exampleSetArrayMetaKey() {
// Example 10: Create an array using meta keys
System.out.println("Example 10");
Key array = Key.create("user:/array");
// Create an array with length 2
array.setMeta("array", "
Key firstEntry = Key.create("user:/array/#0/test");
firstEntry.setString("first");
Key secondEntry = Key.create("user:/array/#1/test");
secondEntry.setString("second");
KeySet ks = KeySet.create(array, firstEntry, secondEntry);
ks.forEach(
key -> {
System.out.print(key + " = " + key.getString());
System.out.print(" | Meta: ");
for (ReadableKey metaKey : key) {
System.out.print(metaKey + " = " + metaKey.getString());
}
System.out.println();
});
System.out.println();
}
private static void exampleCheckKeyAvailableInKDB() {
// Example 11: Check whether the keys are already available in the key database
System.out.println("Example 11");
Key parentKey = Key.create("user:/e11");
Key existingKey = Key.create("user:/e11/exists", "e11Val");
Key notExistingKey = Key.create("user:/e11/doesNotExist", "e11ValNot");
try (KDB kdb = KDB.open()) {
var keySet = kdb.get(parentKey);
keySet.clear();
keySet.append(existingKey);
kdb.set(keySet, parentKey);
} catch (KDBException e) {
System.out.println(e);
}
// now retrieve them
try (KDB kdb = KDB.open()) {
KeySet keySet = kdb.get(parentKey);
var ek = keySet.lookup(existingKey);
if (ek.isPresent()) {
Key loadedExistingKey = ek.get();
System.out.println(loadedExistingKey + " is present and its value " + loadedExistingKey.getString() + " loaded.");
ek.get().release();
} else {
System.out.println(existingKey + " is not present. Setting key.");
keySet.append(existingKey);
kdb.set(keySet, parentKey);
}
var nek = keySet.lookup(notExistingKey);
if (nek.isPresent()) {
Key loadedNotExistingKey = nek.get();
System.out.println(loadedNotExistingKey + " is present and its value " + nek.get().getString() + " loaded.");
nek.get().release();
} else {
System.out.println(notExistingKey + " is not present. Setting key.");
keySet.append(notExistingKey);
kdb.set(keySet, parentKey);
}
} catch (KDBException e) {
System.out.println(e);
}
System.out.println();
}
private static void exampleUpdateMetaKey() {
// Example 12: Update meta data on a key
System.out.println("Example 12");
Key key = Key.create("user:/key/with/meta");
key.setMeta("example", "anExampleValue");
key.getMeta("example").ifPresent(
k -> System.out.println("Set new meta data: " + k.getString())
);
key.setMeta("example", "anUpdatedExampleValue");
key.getMeta("example").ifPresent(
k -> System.out.println("Updated meta data: " + k.getString())
);
System.out.println();
}
private static void exampleKeyIterDumpMetaData() {
// Example 13: Update meta data on a key
System.out.println("Example 13");
Key k1 = Key.create("user:/ex13/Hallo");
k1.setMeta("lang", "GER");
Key k2 = Key.create("user:/ex13/Hello");
k2.setMeta("lang", "ENG");
Key k3 = Key.create("user:/ex13/Hola");
k3.setMeta("lang", "ESP");
final KeySet ks = KeySet.create(10, k1, k2, k3);
for (Key key : ks) {
key.getMeta("lang").ifPresent(
k -> System.out.println("Language of Key " + key.getName() + " is " + k.getString())
);
}
System.out.println();
}
} |
package com.tlongdev.bktf;
import android.content.Context;
import android.content.SharedPreferences;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.LayerDrawable;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.preference.PreferenceManager;
import android.util.Log;
import com.tlongdev.bktf.enums.Quality;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
* Utility class (static only).
*/
public class Utility {
public static final String LOG_TAG = Utility.class.getSimpleName();
public static final String CURRENCY_USD = "usd";
public static final String CURRENCY_METAL = "metal";
public static final String CURRENCY_KEY = "keys";
public static final String CURRENCY_BUD = "earbuds";
/**
* Convenient method for getting the steamId (or vanity user name) of the user.
*/
public static String getSteamId(Context context) {
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
String steamId = prefs.getString(context.getString(R.string.pref_steam_id), null);
if (steamId != null && steamId.equals("")){
return null;
}
return steamId;
}
/**
* Convenient method for getting the steamId of the user.
*/
public static String getResolvedSteamId(Context context) {
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
return prefs.getString(context.getString(R.string.pref_resolved_steam_id), null);
}
/**
* Properly formats the item name according to its properties.
*/
public static String formatItemName(String name, int tradable, int craftable, int quality, int index) {
String formattedName = "";
if (tradable == 0) {
formattedName += "Non-Tradable ";
}
if (craftable == 0) {
formattedName += "Non-Craftable ";
}
//Convert the quality int to enum for better readability
Quality q = Quality.values()[quality];
switch (q) {
case NORMAL:
formattedName += "Normal ";
break;
case GENUINE:
formattedName += "Genuine ";
break;
case VINTAGE:
formattedName += "Vintage ";
break;
case UNIQUE:
if (index > 0) //A unique item with a number
name = name + " #" + index;
break;
case UNUSUAL:
formattedName += getUnusualEffectName(index) + " ";
break;
case COMMUNITY:
formattedName += "Community ";
break;
case VALVE:
formattedName += "Valve ";
break;
case SELF_MADE:
formattedName += "Self-made ";
break;
case STRANGE:
formattedName += "Strange ";
break;
case HAUNTED:
formattedName += "Haunted ";
break;
case COLLECTORS:
formattedName += "Collector's ";
break;
}
return formattedName + name;
}
public static String formatSimpleItemName(String name, int quality, int index, boolean isProper) {
String formattedName = "";
//Convert the quality int to enum for better readability
Quality q = Quality.values()[quality];
switch (q) {
case NORMAL:
formattedName += "Normal ";
break;
case GENUINE:
formattedName += "Genuine ";
break;
case VINTAGE:
formattedName += "Vintage ";
break;
case UNIQUE:
if (index > 0) //A unique item with a number
name = name + " #" + index;
if (isProper){
name = "The " + name;
}
break;
case UNUSUAL:
formattedName += "Unusual ";
break;
case COMMUNITY:
formattedName += "Community ";
break;
case VALVE:
formattedName += "Valve ";
break;
case SELF_MADE:
formattedName += "Self-made ";
break;
case STRANGE:
formattedName += "Strange ";
break;
case HAUNTED:
formattedName += "Haunted ";
break;
case COLLECTORS:
formattedName += "Collector's ";
break;
}
return formattedName + name;
}
/**
* Get the proper name of the unusual effect
*/
public static String getUnusualEffectName(int index) {
switch (index) {
case 4:
return "Community Sparkle";
case 5:
return "Holy Glow";
case 6:
return "Green Confetti";
case 7:
return "Purple Confetti";
case 8:
return "Haunted Ghosts";
case 9:
return "Green Energy";
case 10:
return "Purple Energy";
case 11:
return "Circling TF Logo";
case 12:
return "Massed Flies";
case 13:
return "Burning Flames";
case 14:
return "Scorching Flames";
case 15:
return "Searing Plasma";
case 16:
return "Vivid Plasma";
case 17:
return "Sunbeams";
case 18:
return "Circling Peace Sign";
case 19:
return "Circling Heart";
case 29:
return "Stormy Storm";
case 30:
return "Blizzardy Storm";
case 31:
return "Nuts n' Bolts";
case 32:
return "Orbiting Planets";
case 33:
return "Orbiting Fire";
case 34:
return "Bubbling";
case 35:
return "Smoking";
case 36:
return "Steaming";
case 37:
return "Flaming Lantern";
case 38:
return "Cloudy Moon";
case 39:
return "Cauldron Bubbles";
case 40:
return "Eerie Orbiting Fire";
case 43:
return "Knifestorm";
case 44:
return "Misty Skull";
case 45:
return "Harvest Moon";
case 46:
return "It's A Secret To Everybody";
case 47:
return "Stormy 13th Hour";
case 56:
return "Kill-a-Watt";
case 57:
return "Terror-Watt";
case 58:
return "Cloud 9";
case 59:
return "Aces High";
case 60:
return "Dead Presidents";
case 61:
return "Miami Nights";
case 62:
return "Disco Beat Down";
case 63:
return "Phosphorous";
case 64:
return "Sulphurous";
case 65:
return "Memory Leak";
case 66:
return "Overclocked";
case 67:
return "Electrostatic";
case 68:
return "Power Surge";
case 69:
return "Anti-Freeze";
case 70:
return "Time Warp";
case 71:
return "Green Black Hole";
case 72:
return "Roboactive";
case 73:
return "Arcana";
case 74:
return "Spellbound";
case 75:
return "Chiroptera Venenata";
case 76:
return "Poisoned Shadows";
case 77:
return "Something Burning This Way Comes";
case 78:
return "Hellfire";
case 79:
return "Darkblaze";
case 80:
return "Demonflame";
case 81:
return "Bonzo The All-Gnawing";
case 82:
return "Amaranthine";
case 83:
return "Stare From Beyond";
case 84:
return "The Ooze";
case 85:
return "Ghastly Ghosts Jr";
case 86:
return "Haunted Phantasm Jr";
case 87:
return "Frostbite";
case 88:
return "Molten Mallard";
case 89:
return "Morning Glory";
case 90:
return "Death at Dusk";
case 3001:
return "Showstopper";
case 3003:
return "Holy Grail";
case 3004:
return "'72";
case 3005:
return "Fountain of Delight";
case 3006:
return "Screaming Tiger";
case 3007:
return "Skill Gotten Gains";
case 3008:
return "Midnight Whirlwind";
case 3009:
return "Silver Cyclone";
case 3010:
return "Mega Strike";
case 3011:
return "Haunted Phantasm";
case 3012:
return "Ghastly Ghosts";
default:
return "";
}
}
/**
* Returns a drawable based on the item's properties to use asa background
*/
public static LayerDrawable getItemBackground(Context context, int quality, int tradable, int craftable) {
//Convert the quality int to enum for better readability
Quality q = Quality.values()[quality];
Drawable itemFrame;
Drawable craftableFrame;
Drawable tradableFrame;
switch (q) {
case GENUINE:
itemFrame = context.getResources().getDrawable(R.drawable.item_background_genuine);
break;
case VINTAGE:
itemFrame = context.getResources().getDrawable(R.drawable.item_background_vintage);
break;
case UNUSUAL:
itemFrame = context.getResources().getDrawable(R.drawable.item_background_unusual);
break;
case UNIQUE:
itemFrame = context.getResources().getDrawable(R.drawable.item_background_unique);
break;
case COMMUNITY:
itemFrame = context.getResources().getDrawable(R.drawable.item_background_community);
break;
case VALVE:
itemFrame = context.getResources().getDrawable(R.drawable.item_background_valve);
break;
case SELF_MADE:
itemFrame = context.getResources().getDrawable(R.drawable.item_background_community);
break;
case STRANGE:
itemFrame = context.getResources().getDrawable(R.drawable.item_background_strange);
break;
case HAUNTED:
itemFrame = context.getResources().getDrawable(R.drawable.item_background_haunted);
break;
case COLLECTORS:
itemFrame = context.getResources().getDrawable(R.drawable.item_background_collectors);
break;
default:
itemFrame = context.getResources().getDrawable(R.drawable.item_background_normal);
break;
}
if (craftable == 0){
craftableFrame = context.getResources().getDrawable(R.drawable.non_craftable_border);
}
else {
//Easier to use an empty drawable instead of resizing the layer drawable
craftableFrame = context.getResources().getDrawable(R.drawable.empty_drawable);
}
if (tradable == 0){
tradableFrame = context.getResources().getDrawable(R.drawable.non_tradable_border);
}
else {
//Easier to use an empty drawable instead of resizing the layer drawable
tradableFrame = context.getResources().getDrawable(R.drawable.empty_drawable);
}
return new LayerDrawable(new Drawable[] {itemFrame, craftableFrame, tradableFrame});
}
/**
* Formats the given price and converts it to the desired currency.
*/
public static String formatPrice(Context context, double low, double high, String originalCurrency, String targetCurrency, boolean twoLines) throws Throwable {
//Initial string
String product = "";
//Convert the prices first
low = convertPrice(context, low, originalCurrency, targetCurrency);
if (high > 0.0)
high = convertPrice(context, high, originalCurrency, targetCurrency);
//Check if the price is an int
if ((int)low == low)
product += (int)low;
//Check if the double has fraction smaller than 0.01, if so we need to format the double
else if (("" + low).substring(("" + low).indexOf('.') + 1).length() > 2)
product += new DecimalFormat("#0.00").format(low);
else
product += low;
if (high > 0.0){
//Check if the price is an int
if ((int)high == high)
product += "-" + (int)high;
//Check if the double has fraction smaller than 0.01, if so we need to format the double
else if (("" + high).substring(("" + high).indexOf('.') + 1).length() > 2)
product += "-" + new DecimalFormat("#0.00").format(high);
else
product += "-" + high;
}
//If the price needs to be in two lines, the currency will be in a seperate line.
if (twoLines) {
product += "\n";
}
//Append the string with the proper currency
switch(targetCurrency) {
case CURRENCY_BUD:
if (low == 1.0 && high == 0.0)
return product + " bud";
else
return product + " buds";
case CURRENCY_METAL:
return product + " ref";
case CURRENCY_KEY:
if (low == 1.0 && high == 0.0)
return product + " key";
else
return product + " keys";
case CURRENCY_USD:
return "$" + product;
default:
//App should never reach this code
if (isDebugging(context))
Log.e(LOG_TAG, "Error formatting price");
throw new Throwable("Error while formatting price");
}
}
/**
* Converts the price to that desired currency.
*/
public static double convertPrice(Context context, double price, String originalCurrency, String targetCurrency) throws Throwable {
if (originalCurrency.equals(targetCurrency))
//The target currency equals the original currency, nothing to do.
return price;
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
//Magic converter block
switch(originalCurrency){
case CURRENCY_BUD:
switch(targetCurrency){
case CURRENCY_KEY:
return price * (getDouble(prefs, context.getString(R.string.pref_buds_raw), 1)
/ getDouble(prefs, context.getString(R.string.pref_key_raw), 1));
case CURRENCY_METAL:
return price * getDouble(prefs, context.getString(R.string.pref_buds_raw), 1);
case CURRENCY_USD:
return price * (getDouble(prefs, context.getString(R.string.pref_buds_raw), 1)
* getDouble(prefs, context.getString(R.string.pref_metal_raw_usd), 1));
}
case CURRENCY_METAL:
switch(targetCurrency){
case CURRENCY_KEY:
return price / getDouble(prefs, context.getString(R.string.pref_key_raw), 1);
case CURRENCY_BUD:
return price / getDouble(prefs, context.getString(R.string.pref_buds_raw), 1);
case CURRENCY_USD:
return price * getDouble(prefs, context.getString(R.string.pref_metal_raw_usd), 1);
}
case CURRENCY_KEY:
switch(targetCurrency){
case CURRENCY_METAL:
return price * getDouble(prefs, context.getString(R.string.pref_key_raw), 1);
case CURRENCY_BUD:
return price * (getDouble(prefs, context.getString(R.string.pref_key_raw), 1)
/ getDouble(prefs, context.getString(R.string.pref_buds_raw), 1));
case CURRENCY_USD:
return price * getDouble(prefs, context.getString(R.string.pref_key_raw), 1)
* getDouble(prefs, context.getString(R.string.pref_metal_raw_usd), 1);
}
case CURRENCY_USD:
switch(targetCurrency){
case CURRENCY_METAL:
return price / getDouble(prefs, context.getString(R.string.pref_metal_raw_usd), 1);
case CURRENCY_BUD:
return price / getDouble(prefs, context.getString(R.string.pref_metal_raw_usd), 1)
/ getDouble(prefs, context.getString(R.string.pref_buds_raw), 1);
case CURRENCY_KEY:
return price * getDouble(prefs, context.getString(R.string.pref_metal_raw_usd), 1)
/ getDouble(prefs, context.getString(R.string.pref_key_raw), 1);
}
default:
String error = "Unknown currency: " + originalCurrency + " - " + targetCurrency;
if (isDebugging(context))
Log.e(LOG_TAG, error);
throw new Throwable(error);
}
}
/**
* Check if the given steamId is a 64bit steamId using Regex.
*/
public static boolean isSteamId(String id) {
return id.matches("7656119[0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9]");
}
/**
* Format the unix timestamp the a user readable string.
*/
public static String formatUnixTimeStamp(long unixSeconds){
Date date = new Date(unixSeconds*1000L); // *1000 is to convert seconds to milliseconds
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
return sdf.format(date);
}
/**
* Format the timestamp to a user friendly string that is the same as on steam profile pages.
*/
public static String formatLastOnlineTime(long time) {
//If the time is longer than 2 days tho format is X days.
if (time >= 172800000L) {
long days = time / 86400000;
return "" + days + " days ago";
}
//If the time is longer than an hour, the format is X hour(s) Y minute(s)
if (time >= 3600000L) {
long hours = time / 3600000;
if (time % 3600000L == 0) {
if (hours == 1)
return "" + hours + " hour ago";
else {
return "" + hours + " hours ago";
}
}
else {
long minutes = (time % 3600000L) / 60000;
if (hours == 1)
if (minutes == 1)
return "" + hours + " hour " + minutes + " minute ago";
else
return "" + hours + " hour " + minutes + " minutes ago";
else {
if (minutes == 1)
return "" + hours + " hours " + minutes + " minute ago";
else
return "" + hours + " hours " + minutes + " minutes ago";
}
}
}
//Else it was less than an hour ago, the format is X minute(s).
else {
long minutes = time / 60000;
if (minutes == 0){
return "Just now";
} else if (minutes == 1){
return "1 minute ago";
} else {
return "" + minutes + " minutes ago";
}
}
}
/**
* Retrieves the steamId from a properly formatted JSON.
*/
public static String parseSteamIdFromVanityJson(String userJsonStr) throws JSONException {
final String OWM_RESPONSE = "response";
final String OWM_SUCCESS = "success";
final String OWM_STEAM_ID = "steamid";
final String OWM_MESSAGE = "message";
JSONObject jsonObject = new JSONObject(userJsonStr);
JSONObject response = jsonObject.getJSONObject(OWM_RESPONSE);
if (response.getInt(OWM_SUCCESS) != 1){
//Return the error message if unsuccessful.
return response.getString(OWM_MESSAGE);
}
return response.getString(OWM_STEAM_ID);
}
/**
* Retrieves the user name from a properly formatted JSON.
*/
public static String parseUserNameFromJson(String jsonString) throws JSONException {
final String OWM_RESPONSE = "response";
final String OWM_PLAYERS = "players";
final String OWM_NAME = "personaname";
JSONObject jsonObject = new JSONObject(jsonString);
JSONObject response = jsonObject.getJSONObject(OWM_RESPONSE);
JSONArray players = response.getJSONArray(OWM_PLAYERS);
JSONObject player = players.getJSONObject(0);
return player.getString(OWM_NAME);
}
/**
* Retrieves the url for the user avatar from a proerly formatted JSON.
*/
public static String parseAvatarUrlFromJson(String jsonString) throws JSONException {
final String OWM_RESPONSE = "response";
final String OWM_PLAYERS = "players";
final String OWM_AVATAR = "avatarfull";
JSONObject jsonObject = new JSONObject(jsonString);
JSONObject response = jsonObject.getJSONObject(OWM_RESPONSE);
JSONArray players = response.getJSONArray(OWM_PLAYERS);
JSONObject player = players.getJSONObject(0);
return player.getString(OWM_AVATAR);
}
/**
* Check whether the user if connected to the internet.
*/
public static boolean isNetworkAvailable(Context context) {
ConnectivityManager connectivityManager
= (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
return activeNetworkInfo != null && activeNetworkInfo.isConnected();
}
/**
* Convenient method for storing double values in shared preferences.
*/
public static SharedPreferences.Editor putDouble(final SharedPreferences.Editor edit, final String key, final double value) {
return edit.putLong(key, Double.doubleToRawLongBits(value));
}
/**
* Convenient method for getting double values from shared preferences.
*/
public static double getDouble(final SharedPreferences prefs, final String key, final double defaultValue) {
return Double.longBitsToDouble(prefs.getLong(key, Double.doubleToLongBits(defaultValue)));
}
/**
* Whether we should log or not
*/
public static boolean isDebugging(Context context){
return PreferenceManager.getDefaultSharedPreferences(context).getBoolean(context.getString(R.string.pref_debug), false);
}
/**
* Check whether the given timestamp is older than 3 months
*/
public static boolean isPriceOld(int unixTimeStamp){
return System.currentTimeMillis() - unixTimeStamp*1000L > 7884000000L;
}
/**
* Rounds the given double
*/
public static double roundDouble(double value, int places) {
if (places < 0) throw new IllegalArgumentException();
BigDecimal bd = new BigDecimal(value);
bd = bd.setScale(places, RoundingMode.HALF_UP);
return bd.doubleValue();
}
public static double getRawMetal(int rawRef, int rawRec, int rawScraps) {
return (1.0/9.0 * rawScraps) + (1.0/3.0 * rawRec) + rawRef;
}
public static String getPaintName(int index){
switch (index){
case 7511618: return "Indubitably Green";
case 4345659: return "Zepheniah's Greed";
case 5322826: return "Noble Hatter's Violet";
case 14204632: return "Color No. 216-190-216";
case 8208497: return "Deep Commitment to Purple";
case 13595446: return "Mann Co. Orange";
case 10843461: return "Muskelmannbraun";
case 12955537: return "Peculiarly Drab Tincture";
case 6901050: return "Radigan Conagher Brown";
case 8154199: return "Ye Olde Rustic Color";
case 15185211: return "Australium Gold";
case 8289918: return "Aged Moustache Grey";
case 15132390: return "An Extraordinary Abundance of Tinge";
case 1315860: return "A Distinctive Lack of Hue";
case 16738740: return "Pink as Hell";
case 3100495: return "Color Similar to Slate";
case 8421376: return "Drably Olive";
case 3329330: return "The Bitter Taste of Defeat and Lime";
case 15787660: return "The Color of a Gentlemann's Business Pants";
case 15308410: return "Salmon Injustice";
case 12073019: return "Team Spirit";
case 4732984: return "Operator's Overalls";
case 11049612: return "Waterlogged Lab Coat";
case 3874595: return "Balaclava's Are Forever";
case 6637376: return "Air of Debonair";
case 8400928: return "The Value of Teamwork";
case 12807213: return "Cream Spirit";
case 2960676: return "After Eight";
case 12377523: return "A Mann's Mint";
default: return null;
}
}
public static boolean isPaint(int index){
switch (index){
case 7511618: return true;
case 4345659: return true;
case 5322826: return true;
case 14204632: return true;
case 8208497: return true;
case 13595446: return true;
case 10843461: return true;
case 12955537: return true;
case 6901050: return true;
case 8154199: return true;
case 15185211: return true;
case 8289918: return true;
case 15132390: return true;
case 1315860: return true;
case 16738740: return true;
case 3100495: return true;
case 8421376: return true;
case 3329330: return true;
case 15787660: return true;
case 15308410: return true;
case 12073019: return true;
case 4732984: return true;
case 11049612: return true;
case 3874595: return true;
case 6637376: return true;
case 8400928: return true;
case 12807213: return true;
case 2960676: return true;
case 12377523: return true;
default: return false;
}
}
public static boolean canHaveEffects(int defindex, int quality){
if (quality == 5 || quality == 7 || quality == 9) {
return defindex != 267 && defindex != 266;
} else if (defindex == 1899 || defindex == 125){
return true;
}
return false;
}
public static int fixDefindex(int defindex) {
//Check if the defindex is of a duplicate defindex to provide the proper price for it.
switch (defindex){
case 9: case 10: case 11: case 12: //duplicate shotguns
return 9;
case 23: //duplicate pistol
return 22;
case 28: //duplicate destruction tool
return 26;
case 190: case 191: case 192: case 193: case 194: //duplicate stock weapons
case 195: case 196: case 197: case 198: case 199:
return defindex - 190;
case 200: case 201: case 202: case 203: case 204: //duplicate stock weapons
case 205: case 206: case 207: case 208: case 209:
return defindex - 187;
case 210:
return defindex - 186;
case 211: case 212:
return defindex - 182;
case 736: //duplicate sapper
return 735;
case 737: //duplicate construction pda
return 25;
case 5041: case 5045: //duplicate crates
return 5022;
case 5735: case 5742: case 5752: case 5781: case 5802: //duplicate munitions
return 5734;
default:
return defindex;
}
}
public static int getIconIndex(int defindex) {
//Check if the defindex is of a duplicate defindex to provide the proper price for it.
switch (defindex){
case 9: case 10: case 11: case 12: //duplicate shotguns
return 9;
case 23: //duplicate pistol
return 22;
case 28: //duplicate destruction tool
return 26;
case 190: case 191: case 192: case 193: case 194: //duplicate stock weapons
case 195: case 196: case 197: case 198: case 199:
return defindex - 190;
case 200: case 201: case 202: case 203: case 204: //duplicate stock weapons
case 205: case 206: case 207: case 208: case 209:
return defindex - 187;
case 210:
return defindex - 186;
case 211: case 212:
return defindex - 182;
case 294: //lugermorph
return 160;
case 422: //companion cube pin
return 299;
case 681: case 682: case 683: case 684: //gold cup medal
return 680;
case 686: case 687: case 688: case 689: //silver cup medal
return 685;
case 691: case 692: case 693: case 694: case 695: case 696: case 697: case 698: //bronze cup medal
return 690;
case 736: //duplicate sapper
return 735;
case 737: //duplicate construction pda
return 25;
case 744: //pyrovision goggles
return 743;
case 791: case 928://pink promo gifts
return 790;
case 831: case 832: case 833: case 834: // promoasian items
case 835: case 836: case 837: case 838:
return defindex - 21;
case 839: //gift bag
return 729;
case 1132: //spell magazine
return 1070;
case 2015: case 2049: case 2079: case 2123: case 2125: //map stamps packs
return 2007;
case 2035: case 2036: case 2037: case 2038: case 2039: //dr gorbort pack
return 2034;
case 2041: case 2045: case 2047: case 2048: //deus ex pack
return 2040;
case 2042: case 2095: //soldier pack
return 2019;
case 2043: case 2044: //more soldier packs
return 2042;
case 2046: //shogun pack
return 2016;
case 2070: //promo chicken hat
return 785;
case 2081: //hong kong pac
return 2076;
case 2094: case 2096: case 2097: case 2098: case 2099:
case 2100: case 2101: case 2102: //class packs
return defindex - 76;
case 2103: //deus Ex arm
return 524;
case 5020: //desc tag
return 2093;
case 5041: case 5045: //duplicate crates
return 5022;
case 5049: case 5067: case 5072: case 5073: case 5079: case 5081: case 5628: case 5631:
case 5632: case 5713: case 5716: case 5717: case 5762: case 5791: case 5792:
return 5021; //mann co supply crate key
case 5074: //something special for someone special
return 699;
case 5601: case 5602: case 5603: case 5604: //pyro dusts
return 5600;
case 5721: case 5722: case 5723: case 5724: case 5725: case 5753: case 5754: case 5755:
case 5756: case 5757: case 5758: case 5759: case 5783: case 5784: case 6522:
return 5661; //strangifiers
case 5727: case 5728: case 5729: case 5730: case 5731: case 5732: case 5733:
case 5743: case 5744: case 5745: case 5746: case 5747: case 5748: case 5749: case 5750:
case 5751: case 5793: case 5794: case 5795: case 5796: case 5797: case 5798: case 5799:
case 5800: case 5801: case 6527: //killstreak kits
return 5726;
case 5735: case 5742: case 5752: case 5781: case 5802: //duplicate munitions
return 5734;
case 5738: //sombrero crate
return 5737;
case 5773: //halloween cauldron
return 5772;
case 8003: case 8006: //ugc medal
return 8000;
case 8004: case 8007: //ugc medal
return 8001;
case 8005: case 8008: //ugc medal
return 8002;
case 8012: //ugc medal
return 8009;
case 8013: //ugc medal
return 8010;
case 8014: //ugc medal
return 8011;
case 8018: case 8021: //ugc medal
return 8015;
case 8019: case 8022: //ugc medal
return 8016;
case 8020: case 8023: //ugc medal
return 8017;
case 8031: case 8035: case 8039: case 8043: case 8047: case 8051: case 8055:
case 8058: case 8062: case 8066: //esl gold medal
return 8027;
case 8032: case 8036: case 8040: case 8044: case 8048: case 8052: case 8056:
case 8059: case 8063: case 8067: //esl silver medal
return 8028;
case 8033: case 8037: case 8041: case 8045: case 8049: case 8053: case 8057:
case 8064: case 8068: //esl bronze medal
return 8029;
case 8034: case 8038: case 8042: case 8046: case 8050: case 8054: case 8060:
case 8061: case 8065: case 8069: //esl platinum medal
return 8030;
case 8071: //ready steady pan s1 medal
return 8070;
case 8075: case 8078: case 8081: case 8084: case 8087: case 8275: case 8307:
case 8323: case 8397: //etf2l medal gold
return 8072;
case 8076: case 8079: case 8082: case 8085: case 8088: case 8276: case 8308:
case 8324: case 8398: //etf2l medal silver
return 8073;
case 8077: case 8080: case 8083: case 8086: case 8089: case 8277: case 8309:
case 8325: case 8399: //etf2l medal bronze
return 8074;
case 8091: case 8092: case 8093: case 8094: case 8095: case 8096: case 8097:
case 8098: case 8099: case 8100: case 8101: case 8102: case 8103: case 8104:
case 8105: case 8106: case 8107: case 8108: case 8109: case 8110: case 8111:
case 8112: case 8113: case 8114: case 8115: case 8116: case 8117: case 8118:
case 8119: case 8120: case 8121: case 8122: case 8123: case 8124: case 8125:
case 8278: case 8279: case 8280: case 8281: case 8282: case 8283: case 8310:
case 8311: case 8312: case 8313: case 8314: case 8315: case 8326: case 8327:
case 8328: case 8329: case 8330: case 8331: case 8400: case 8401: case 8402:
case 8403: case 8404: //etf2l medal participant
return 8090;
case 8127: case 8128: case 8129: case 8130: case 8131: case 8132: case 8133:
case 8134: case 8135: case 8136: case 8137: case 8138: case 8139: case 8140:
case 8141: case 8142: case 8143: case 8144: case 8145: case 8146: case 8147:
case 8148: case 8149: case 8150: case 8151: case 8152: case 8153: case 8154:
case 8155: case 8156: case 8157: case 8158: case 8159: case 8160: case 8161:
case 8162: case 8163: case 8164: case 8165: case 8166: case 8167: case 8284:
case 8285: case 8286: case 8287: case 8288: case 8289: case 8290: case 8316:
case 8317: case 8318: case 8319: case 8320: case 8321: case 8322: case 8332:
case 8333: case 8334: case 8335: case 8336: case 8337: case 8338: case 8406:
case 8407: case 8408: case 8409: case 8410: case 8411: case 8412: //etf2l bottle cap
return 8126;
case 8171: case 8174: case 8291: case 8413: //etf2lry medal gold
return 8168;
case 8172: case 8175: case 8292: case 8414: //etf2lry medal silver
return 8169;
case 8173: case 8176: case 8293: case 8415: //etf2lry medal bronze
return 8170;
case 8178: case 8179: case 8180: case 8181: case 8182: case 8183: case 8184:
case 8185: case 8186: case 8187: case 8188: case 8189: case 8190: case 8191:
case 8192: case 8294: case 8295: case 8296: case 8297: case 8298: case 8299:
case 8416: case 8417: case 8418: case 8419: case 8420: case 8421: //etf2lry medal participant
return 8177;
case 8194: case 8195: case 8196: case 8197: case 8198: case 8199: case 8200:
case 8201: case 8202: case 8203: case 8204: case 8205: case 8206: case 8207:
case 8208: case 8209: case 8210: case 8211: case 8300: case 8301: case 8302:
case 8303: case 8304: case 8305: case 8306: case 8422: case 8423: case 8424:
case 8425: case 8426: case 8427: case 8428: //etf2lry bottle cap
return 8193;
case 8213: case 8214: case 8215: //soldier medal
return 8212;
case 8217: case 8218: case 8219: case 8220: case 8221: case 8222: //soldier medal2
return 8216;
case 8223: //duplicate soldier medal
return 121;
case 8236: //horseshoe medal 1st
return 8224;
case 8237: //horseshoe medal 2st
return 8225;
case 8238: //horseshoe medal 3st
return 8226;
case 8244: case 8245: case 8246: case 8247: //ready steady pan s2
return 8243;
case 8263: //wings medal first
return 8248;
case 8264: //wings medal second
return 8249;
case 8265: //wings medal third
return 8250;
case 8271: //ugc wings gold
return 8267;
case 8272: case 8274: //ugc wings silver
return 8268;
case 8273: //ugc wings bronze
return 8269;
default: //don't change
return defindex;
}
}
public static class IntegerPair{
int x;
int y;
public IntegerPair(){
this(0);
}
public IntegerPair(int x) {
this(x, 0);
}
public IntegerPair(int x, int y) {
this.x = x;
this.y = y;
}
public int getX() {
return x;
}
public void setX(int x) {
this.x = x;
}
public int getY() {
return y;
}
public void setY(int y) {
this.y = y;
}
}
} |
package blainelewis1.cmput301assignment1;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.lang.reflect.Type;
import java.util.ArrayList;
import android.content.Context;
import android.util.Log;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
/*
* This is a singleton that manages the list of claims by
* providing means of (de) serialization and interfaces to get all of the claims
*/
public class ClaimManager {
private static ClaimManager instance = null;
//This is the name of the file we serialize to, it's arbitrary...
private static final String saveFileName = "claims.sav";
private ArrayList<Claim> claims;
protected ClaimManager() {
}
/*
* Returns an instance of the claimManager
*/
public static ClaimManager getInstance() {
if (instance == null) {
instance = new ClaimManager();
}
return instance;
}
/*
* Adds a claim to the list
*/
public void addClaim(Claim claim) {
claims.add(claim);
}
public Claim createNewClaim() {
Claim claim = new Claim();
addClaim(claim);
return claim;
}
/*
* Finds a claim by its id
*/
public Claim getClaimById(String id) {
for (Claim claim : claims) {
if (claim.getId().equals(id)) {
return claim;
}
}
return null;
}
/*
* Creates an expense from it's claim.
* We manage expense creation to ensure it is done properly
*/
public Expense createNewExpense(Claim claim) {
Expense expense = new Expense(claim);
claim.addExpense(expense);
return expense;
}
/*
* Deletes a claim
*/
public void deleteClaim(Claim claim) {
claims.remove(claim);
}
/*
* Serializes the claims as JSON using GSON
*/
public void serialize(Context context) {
//Why write nothing?
if (this.claims == null) {
return;
}
Gson gson = new Gson();
try {
OutputStreamWriter writer = new OutputStreamWriter(
context.openFileOutput(saveFileName, Context.MODE_PRIVATE));
gson.toJson(claims, writer);
writer.close();
} catch (IOException e) {
// Fail silently, we can't do anything about this...
Log.e("Error", "Serialize failed", e);
}
}
/*
* Deserializes the claims that are stored as JSON using GSON
*/
public void deserialize(Context context) {
//Deserializing while we already have claims is dangerous and will overwrite data
if (this.claims != null) {
return;
}
Gson gson = new Gson();
try {
InputStreamReader reader = new InputStreamReader(
context.openFileInput(saveFileName));
Type arrayListType = new TypeToken<ArrayList<Claim>>() {
}.getType();
claims = gson.fromJson(reader, arrayListType);
reader.close();
} catch (IOException e) {
// fail silently there's nothing else we can do
Log.e("Error", "Deserialize failed", e);
}
//Either we failed to load the claims or there were none
if (claims == null) {
claims = new ArrayList<Claim>();
}
}
/*
* Returns all the claims
*/
public ArrayList<Claim> getClaims() {
return claims;
}
} |
package ch.idsia.benchmark.mario.engine;
import ch.idsia.tools.GameViewer;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimeZone;
public abstract class
GlobalOptions
{
public static final int primaryVerionUID = 0;
public static final int minorVerionUID = 1;
public static final int minorSubVerionID = 9;
public static boolean areLabels = false;
public static boolean isCameraCenteredOnMario = false;
public static Integer FPS = 24;
public static int MaxFPS = 100;
public static boolean isPauseWorld = false;
public static boolean isVisualization = true;
public static boolean isGameplayStopped = false;
public static boolean isFly = false;
private static GameViewer GameViewer = null;
// public static boolean isTimer = true;
public static int mariosecondMultiplier = 15;
public static boolean isPowerRestoration;
// required for rendering grid in ch/idsia/benchmark/mario/engine/sprites/Sprite.java
public static int receptiveFieldWidth = -1;
public static int receptiveFieldHeight = -1;
private static MarioVisualComponent marioVisualComponent;
public static int VISUAL_COMPONENT_WIDTH = 320;
public static int VISUAL_COMPONENT_HEIGHT = 240;
public static boolean isShowReceptiveField = false;
public static boolean isScale2x = false;
public static boolean isRecording = false;
public static boolean isReplaying = false;
public static int getPrimaryVersionUID()
{
return primaryVerionUID;
}
public static int getMinorVersionUID()
{
return minorVerionUID;
}
public static int getMinorSubVersionID()
{
return minorSubVerionID;
}
public static String getBenchmarkName()
{
return "[~ Mario AI Benchmark ~" + GlobalOptions.getVersionUID() + "]";
}
public static String getVersionUID()
{
return " " + getPrimaryVersionUID() + "." + getMinorVersionUID() + "." + getMinorSubVersionID();
}
public static void registerMarioVisualComponent(MarioVisualComponent mc)
{
marioVisualComponent = mc;
}
public static void registerGameViewer(GameViewer gv)
{
GameViewer = gv;
}
public static void AdjustMarioVisualComponentFPS()
{
if (marioVisualComponent != null)
marioVisualComponent.adjustFPS();
}
public static void gameViewerTick()
{
if (GameViewer != null)
GameViewer.tick();
}
public static String getDateTime(Long d)
{
final DateFormat dateFormat = (d == null) ? new SimpleDateFormat("yyyy/MM/dd HH:mm:ss:ms") :
new SimpleDateFormat("HH:mm:ss:ms");
if (d != null)
dateFormat.setTimeZone(TimeZone.getTimeZone("GMT"));
final Date date = (d == null) ? new Date() : new Date(d);
return dateFormat.format(date);
}
final static private DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd_HH-mm-ss");
public static String getTimeStamp()
{
return dateFormat.format(new Date());
}
public static void changeScale2x()
{
isScale2x = !isScale2x;
marioVisualComponent.width *= isScale2x ? 2 : 0.5;
marioVisualComponent.height *= isScale2x ? 2 : 0.5;
marioVisualComponent.changeScale2x();
}
} |
package com.elmakers.mine.bukkit.utility;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import com.elmakers.mine.bukkit.block.MaterialAndData;
import com.elmakers.mine.bukkit.integration.VaultController;
import org.apache.commons.lang.StringEscapeUtils;
import org.bukkit.ChatColor;
import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.BookMeta;
import org.bukkit.inventory.meta.ItemMeta;
public class Messages implements com.elmakers.mine.bukkit.api.magic.Messages {
private static String PARAMETER_PATTERN_STRING = "\\$([a-zA-Z0-9]+)";
private static Pattern PARAMETER_PATTERN = Pattern.compile(PARAMETER_PATTERN_STRING);
private static Random random = new Random();
private Map<String, String> messageMap = new HashMap<>();
private Map<String, List<String>> randomized = new HashMap<>();
private ConfigurationSection configuration = null;
public Messages() {
}
public void load(ConfigurationSection messages) {
configuration = messages;
Collection<String> keys = messages.getKeys(true);
for (String key : keys) {
if (key.equals("randomized")) {
ConfigurationSection randomSection = messages.getConfigurationSection(key);
Set<String> randomKeys = randomSection.getKeys(false);
for (String randomKey : randomKeys) {
randomized.put(randomKey, randomSection.getStringList(randomKey));
}
} else if (messages.isString(key)) {
String value = messages.getString(key);
value = ChatColor.translateAlternateColorCodes('&', StringEscapeUtils.unescapeHtml(value));
messageMap.put(key, value);
}
}
}
@Override
public List<String> getAll(String path) {
if (configuration == null) return new ArrayList<>();
return configuration.getStringList(path);
}
public void reset() {
messageMap.clear();
}
@Override
public boolean containsKey(String key) {
return messageMap.containsKey(key);
}
@Override
public String get(String key, String defaultValue) {
if (messageMap.containsKey(key)) {
return messageMap.get(key);
}
if (defaultValue == null) {
return "";
}
return ChatColor.translateAlternateColorCodes('&', defaultValue);
}
@Override
public String get(String key) {
return get(key, key);
}
@Override
public String getParameterized(String key, String paramName, String paramValue) {
return get(key, key).replace(paramName, paramValue);
}
@Override
public String getParameterized(String key, String paramName1, String paramValue1, String paramName2, String paramValue2) {
return get(key, key).replace(paramName1, paramValue1).replace(paramName2, paramValue2);
}
@Override
public String getRandomized(String key) {
if (!randomized.containsKey(key)) return null;
List<String> options = randomized.get(key);
if (options.size() == 0) return "";
return options.get(random.nextInt(options.size()));
}
@Override
public String escape(String source) {
Matcher matcher = PARAMETER_PATTERN.matcher(source);
String result = source;
while (matcher.find()) {
String key = matcher.group(1);
if (key != null) {
String randomized = getRandomized(key);
if (randomized != null)
{
result = result.replace("$" + key, randomized);
}
}
}
return result;
}
@Override
public String describeItem(ItemStack item) {
String displayName = null;
if (item.hasItemMeta()) {
ItemMeta meta = item.getItemMeta();
displayName = meta.getDisplayName();
if ((displayName == null || displayName.isEmpty()) && meta instanceof BookMeta) {
BookMeta book = (BookMeta)meta;
displayName = book.getTitle();
}
}
if (displayName == null || displayName.isEmpty()) {
MaterialAndData material = new MaterialAndData(item);
displayName = material.getName();
}
return displayName;
}
@Override
public String describeCurrency(double amount) {
VaultController vault = VaultController.getInstance();
String formatted = vault.format(amount);
if (!VaultController.hasEconomy()) {
formatted = get("costs.currency_amount").replace("$amount", formatted);
}
return formatted;
}
@Override
public String getCurrency() {
VaultController vault = VaultController.getInstance();
if (VaultController.hasEconomy()) {
return vault.getCurrency();
}
return get("costs.currency");
}
@Override
public String getCurrencyPlural() {
VaultController vault = VaultController.getInstance();
if (VaultController.hasEconomy()) {
return vault.getCurrencyPlural();
}
return get("costs.currency_plural");
}
@Override
public String formatList(String basePath, Collection<String> nodes, String nameKey) {
StringBuilder buffer = new StringBuilder();
for (String node : nodes) {
if (buffer.length() != 0) {
buffer.append(", ");
}
String path = node;
if (basePath != null) {
path = basePath + "." + path;
}
if (nameKey != null) {
path = path + "." + nameKey;
}
node = get(path, node);
buffer.append(node);
}
return buffer.toString();
}
@Override
public String getLevelString(String templateName, float amount)
{
return getLevelString(templateName, amount, 1);
}
@Override
public String getLevelString(String templateName, float amount, float max)
{
String templateString = get(templateName, "");
if (templateString.contains("$roman")) {
if (max != 1) {
amount = amount / max;
}
templateString = templateString.replace("$roman", getRomanString(amount));
}
return templateString.replace("$amount", Integer.toString((int) amount));
}
@Override
public String getPercentageString(String templateName, float amount)
{
String templateString = get(templateName, "");
return templateString.replace("$amount", Integer.toString((int)(amount * 100)));
}
private String getRomanString(float amount) {
String roman = "";
if (amount > 1) {
roman = get("wand.enchantment_level_max");
} else if (amount > 0.8f) {
roman = get("wand.enchantment_level_5");
} else if (amount > 0.6f) {
roman = get("wand.enchantment_level_4");
} else if (amount > 0.4f) {
roman = get("wand.enchantment_level_3");
} else if (amount > 0.2f) {
roman = get("wand.enchantment_level_2");
} else {
roman = get("wand.enchantment_level_1");
}
return roman;
}
} |
package oap.testng;
import com.typesafe.config.impl.ConfigImpl;
import lombok.extern.slf4j.Slf4j;
import oap.util.Strings;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import static oap.testng.Fixture.Scope.CLASS;
import static oap.testng.Fixture.Scope.METHOD;
import static oap.testng.Fixture.Scope.SUITE;
@Slf4j
public class EnvFixture implements Fixture {
private final Map<String, Object> properties = new HashMap<>();
private final ConcurrentHashMap<String, Integer> ports = new ConcurrentHashMap<>();
protected Scope scope = METHOD;
public EnvFixture define( String property, Object value ) {
properties.put( property, value );
return this;
}
public EnvFixture definePort( String property, String portKey ) {
return define( property, portFor( portKey ) );
}
private void init() {
properties.forEach( ( n, v ) -> {
String value = Strings.substitute( String.valueOf( v ),
k -> System.getenv( k ) == null ? System.getProperty( k ) : System.getenv( k ) );
log.debug( "system property {} = {}", n, value );
System.setProperty( n, value );
} );
ConfigImpl.reloadEnvVariablesConfig();
ConfigImpl.reloadSystemPropertiesConfig();
}
@Override
public void beforeSuite() {
if( scope == SUITE ) init();
}
@Override
public void beforeClass() {
if( scope == CLASS ) init();
}
@Override
public void beforeMethod() {
if( scope == METHOD ) init();
}
@Override
public void afterMethod() {
if( scope == METHOD ) clearPorts();
}
@Override
public void afterClass() {
if( scope == CLASS ) clearPorts();
}
@Override
public void afterSuite() {
if( scope == SUITE ) clearPorts();
}
public int portFor( Class<?> clazz ) {
return portFor( clazz.getName() );
}
public int portFor( String key ) {
return ports.computeIfAbsent( key, k -> {
try( var socket = new ServerSocket() ) {
socket.setReuseAddress( true );
socket.bind( new InetSocketAddress( 0 ) );
var localPort = socket.getLocalPort();
log.debug( this.getClass().getSimpleName() + " finding port for key=" + key + "... port=" + localPort );
return localPort;
} catch( IOException e ) {
throw new UncheckedIOException( e );
}
} );
}
public void clearPorts() {
log.debug( "clear ports" );
ports.clear();
}
} |
package cn.kerison.kit.log;
import android.text.TextUtils;
import android.util.Log;
import java.util.Locale;
public class LogKit {
/**
* Log level value {@link Log}
*/
public static final int LOG_VERBOSE = 2;
public static final int LOG_DEBUG = 3;
public static final int LOG_INFO = 4;
public static final int LOG_WARN = 5;
public static final int LOG_ERROR = 6;
public static final int LOG_ASSERT = 7;
public static final int NO_LOG = Integer.MAX_VALUE;
private static int DEFAULT_LEVEL = LOG_VERBOSE;
private static boolean IS_SHOW_DETAIL = true;
private static String DEFAULT_TAG = "LogKit";
private LogKit() {
}
public static void setLevel(int level) {
DEFAULT_LEVEL = level;
}
public static void setTag(String defaultTag) {
DEFAULT_TAG = defaultTag;
}
public static void disableDetail(){
IS_SHOW_DETAIL = false;
}
public static void v(String content) {
if (DEFAULT_LEVEL <= LOG_VERBOSE) {
LogPrint(LOG_VERBOSE, content);
}
}
public static void v(String format, Object... args) {
if (DEFAULT_LEVEL <= LOG_VERBOSE) {
LogPrint(LOG_VERBOSE, String.format(format, args));
}
}
public static void v(String content, Throwable tr) {
if (DEFAULT_LEVEL <= LOG_VERBOSE) {
LogPrint(LOG_DEBUG, content, tr);
}
}
public static void d(String content) {
if (DEFAULT_LEVEL <= LOG_DEBUG) {
LogPrint(LOG_DEBUG, content);
}
}
public static void d(String format, Object... args) {
if (DEFAULT_LEVEL <= LOG_DEBUG) {
LogPrint(LOG_DEBUG, String.format(format, args));
}
}
public static void d(String content, Throwable tr) {
if (DEFAULT_LEVEL <= LOG_DEBUG) {
LogPrint(LOG_DEBUG, content, tr);
}
}
public static void i(String content) {
if (DEFAULT_LEVEL <= LOG_INFO) {
LogPrint(LOG_INFO, content);
}
}
public static void i(String format, Object... args) {
if (DEFAULT_LEVEL <= LOG_INFO) {
LogPrint(LOG_INFO, String.format(format, args));
}
}
public static void i(String content, Throwable tr) {
if (DEFAULT_LEVEL <= LOG_INFO) {
LogPrint(LOG_INFO, content, tr);
}
}
public static void w(String content) {
if (DEFAULT_LEVEL <= LOG_WARN) {
LogPrint(LOG_WARN, content);
}
}
public static void w(String format, Object... args) {
if (DEFAULT_LEVEL <= LOG_WARN) {
LogPrint(LOG_WARN, String.format(format, args));
}
}
public static void w(String content, Throwable tr) {
if (DEFAULT_LEVEL <= LOG_WARN) {
LogPrint(LOG_WARN, content, tr);
}
}
public static void e(String content) {
if (DEFAULT_LEVEL <= LOG_ERROR) {
LogPrint(LOG_ERROR, content);
}
}
public static void e(String format, Object... args) {
if (DEFAULT_LEVEL <= LOG_ERROR) {
LogPrint(LOG_ERROR, String.format(format, args));
}
}
public static void e(String content, Throwable tr) {
if (DEFAULT_LEVEL <= LOG_ERROR) {
LogPrint(LOG_ERROR, content, tr);
}
}
public static void wft(String content) {
if (DEFAULT_LEVEL <= LOG_ASSERT) {
LogPrint(LOG_ASSERT, content);
}
}
public static void wft(String format, Object... args) {
if (DEFAULT_LEVEL <= LOG_ASSERT) {
LogPrint(LOG_ASSERT, String.format(format, args));
}
}
public static void wft(String content, Throwable tr) {
if (DEFAULT_LEVEL <= LOG_ASSERT) {
LogPrint(LOG_ASSERT, content, tr);
}
}
private static String wrapMessage(String msg) {
StackTraceElement caller = Thread.currentThread().getStackTrace()[4];
String callerClazzName = caller.getClassName();
callerClazzName = callerClazzName.substring(callerClazzName
.lastIndexOf(".") + 1);
return String.format(
Locale.ENGLISH,
"[%s.%s(L:%d)]
new Object[]{callerClazzName, caller.getMethodName(),
Integer.valueOf(caller.getLineNumber())},msg);
}
private static void LogPrint(int logLevel, String msg) {
Log.println(logLevel, DEFAULT_TAG, IS_SHOW_DETAIL ? wrapMessage(msg) : msg);
}
private static void LogPrint(int logLevel, String msg,
Throwable tr) {
Log.println(logLevel, DEFAULT_TAG, IS_SHOW_DETAIL ? wrapMessage(msg + "\n" + Log.getStackTraceString(tr)) : msg + "\n" + Log.getStackTraceString(tr));
}
} |
package burlap.domain.singleagent.cartpole;
import java.util.List;
import burlap.debugtools.RandomFactory;
import burlap.oomdp.auxiliary.DomainGenerator;
import burlap.oomdp.core.Attribute;
import burlap.oomdp.core.Domain;
import burlap.oomdp.core.ObjectClass;
import burlap.oomdp.core.ObjectInstance;
import burlap.oomdp.core.State;
import burlap.oomdp.core.TerminalFunction;
import burlap.oomdp.core.TransitionProbability;
import burlap.oomdp.singleagent.Action;
import burlap.oomdp.singleagent.GroundedAction;
import burlap.oomdp.singleagent.RewardFunction;
import burlap.oomdp.singleagent.SADomain;
import burlap.oomdp.singleagent.explorer.VisualExplorer;
import burlap.oomdp.visualizer.Visualizer;
/**
* A simplified version of the {@link CartPoleDomain} in which the movement of the pole depends only on gravity and the force applied, and not the velocity of the
* underlying cart. The track is also always assumed to be infinite. Therefore, the state space for this domain is fully described by two variables:
* the angle and angular velocity of the pole. However, there is also noise included in the actions
* of this domain as well a noop action. This version of the inverted pendulum is the version used in the original
* Least-Squares Policy Iteration paper [1].
* <p/>
*
*
* 1. Lagoudakis, Michail G., and Ronald Parr. "Least-squares policy iteration." The Journal of Machine Learning Research 4 (2003): 1107-1149.
*
*
*
* @author James MacGlashan
*
*/
public class InvertedPendulum implements DomainGenerator {
/**
* A constant for the name of the angle attribute
*/
public static final String ATTANGLE = "angleAtt";
/**
* A constant for the name of the angle velocity
*/
public static final String ATTANGLEV = "angleVAtt";
/**
* The object class for the pendulum.
*/
public static final String CLASSPENDULUM = "pendulum";
/**
* A constant for the name of the left action
*/
public static final String ACTIONLEFT = "left";
/**
* A constant for the name of the right action
*/
public static final String ACTIONRIGHT = "right";
/**
* A constant for the name of the no force action (which due to stochasticity may include a small force)
*/
public static final String ACTIONNOFORCE = "noForce";
/**
* The maximimum radius the pole can fall. Note, physics get weird and non-realisitc at pi/2;
* task should terminate before then.
*/
public double angleRange = Math.PI/2;
/**
* the force of gravity; should be *positive* for the correct mechanics.
*/
public double gravity = 9.8;
/**
* The mass of the cart.
*/
public double cartMass = 8.;
/**
* The mass of the pole.
*/
public double poleMass = 2.;
/**
* The length of the pole
*/
public double poleLength = 0.5;
/**
* The force (magnitude) applied by a left or right action.
*/
public double actionForce = 50.;
/**
* The force (magnitude) noise in any action, including the no force action.
*/
public double actionNoise = 10.;
/**
* The maximum speed (manitude) of the change in angle. The default sets it to 1
*/
public double maxAngleSpeed = 1.;
/**
* The time between each action selection
*/
public double timeDelta = 0.1;
@Override
public Domain generateDomain() {
SADomain domain = new SADomain();
Attribute angleatt = new Attribute(domain, ATTANGLE, Attribute.AttributeType.REAL);
angleatt.setLims(-this.angleRange, this.angleRange);
Attribute anglevatt = new Attribute(domain, ATTANGLEV, Attribute.AttributeType.REAL);
anglevatt.setLims(-this.maxAngleSpeed, this.maxAngleSpeed);
ObjectClass pendulum = new ObjectClass(domain, CLASSPENDULUM);
pendulum.addAttribute(angleatt);
pendulum.addAttribute(anglevatt);
new ForceAction(ACTIONLEFT, domain, -this.actionForce);
new ForceAction(ACTIONRIGHT, domain, this.actionForce);
new ForceAction(ACTIONNOFORCE, domain, 0.);
return domain;
}
/**
* Updates the given state object given the control force.
* @param s the input state
* @param controlForce the control force acted upon the cart.
*/
public void updateState(State s, double controlForce){
ObjectInstance pend = s.getFirstObjectOfClass(CLASSPENDULUM);
double a0 = pend.getRealValForAttribute(ATTANGLE);
double av0 = pend.getRealValForAttribute(ATTANGLEV);
double alpha = 1./ (this.cartMass + this.poleMass);
double sinA = Math.sin(a0);
double cosA = Math.cos(a0);
double num = (this.gravity*sinA) -
(alpha * this.poleMass*this.poleLength*av0*av0*Math.sin(2.*a0)*0.5) -
(alpha * cosA * controlForce);
double denom = ((4./3.)*this.poleLength) - alpha*this.poleMass*this.poleLength*cosA*cosA;
double accel = num / denom;
//now perform Euler's
double af = a0 + this.timeDelta*av0;
double avf = av0 + this.timeDelta*accel;
//clamp it
if(Math.abs(af) >= this.angleRange){
af = Math.signum(af) * this.angleRange;
avf = 0.;
}
if(Math.abs(avf) > this.maxAngleSpeed){
avf = Math.signum(avf) * this.maxAngleSpeed;
}
//set it
pend.setValue(ATTANGLE, af);
pend.setValue(ATTANGLEV, avf);
}
/**
* Returns an initial state with 0 angle (perfectly vertical) and 0 angle velocity.
* @param domain the domain object to which the state will be belong.
* @return an initial state with 0 angle (perfectly vertical) and 0 angle velocity.
*/
public static State getInitialState(Domain domain){
return getInitialState(domain, 0., 0.);
}
/**
* Returns an initial state with the pole at the given angle and with the given angular velocity of the pole.
* @param domain the domain object to which the state will belong.
* @param angle the angle of the pole from the vertical axis.
* @param angleVelocity the angular velocity of the pole.
* @return an initial state with the pole at the given angle and with the given angular velocity of the pole.
*/
public static State getInitialState(Domain domain, double angle, double angleVelocity){
State s = new State();
ObjectInstance o = new ObjectInstance(domain.getObjectClass(CLASSPENDULUM), CLASSPENDULUM);
o.setValue(ATTANGLE, angle);
o.setValue(ATTANGLEV, angleVelocity);
s.addObject(o);
return s;
}
/**
* An action that applies a given force to the cart + uniform random noise in the range defined in the {@link InvertedPendulum#actionNoise} data member.
* @author James MacGlashan
*
*/
public class ForceAction extends Action{
/**
* The base noise to which noise will be added.
*/
protected double baseForce;
/**
* Initializes the force action
* @param name the name of the action
* @param domain the domain object to which the action will belong.
* @param force the base force this action applies; noise will be added to this force according to the {@link InvertedPendulum#actionNoise} data member.
*/
public ForceAction(String name, Domain domain, double force){
super(name, domain, "");
this.baseForce = force;
}
@Override
protected State performActionHelper(State s, String[] params) {
double roll = RandomFactory.getMapped(0).nextDouble()*(2*InvertedPendulum.this.actionNoise) - InvertedPendulum.this.actionNoise;
double force = this.baseForce + roll;
InvertedPendulum.this.updateState(s, force);
return s;
}
@Override
public List<TransitionProbability> getTransitions(State s, String [] params){
throw new RuntimeException("Transition Probabilities cannot be enumerated.");
}
}
/**
* A default terminal function for this domain. Terminates when the
* angle between pole and vertical axis is greater than PI/2 radians or some other user specified threshold.
* @author James MacGlashan
*
*/
public static class InvertedPendulumTerminalFunction implements TerminalFunction{
/**
* The maximum pole angle to cause termination/failure.
*/
double maxAbsoluteAngle = (Math.PI / 2.);
public InvertedPendulumTerminalFunction() {
}
/**
* Initializes with a max pole angle as specified in radians
* @param maxAbsoluteAngle the maximum pole angle in radians that causes task termination/failure.
*/
public InvertedPendulumTerminalFunction(double maxAbsoluteAngle){
this.maxAbsoluteAngle = maxAbsoluteAngle;
}
@Override
public boolean isTerminal(State s) {
ObjectInstance pendulum = s.getFirstObjectOfClass(CLASSPENDULUM);
double a = pendulum.getRealValForAttribute(ATTANGLE);
if(Math.abs(a) >= maxAbsoluteAngle){
return true;
}
return false;
}
}
/**
* A default reward function for this domain. Returns 0 everywhere except at fail conditions, which return -1 and
* are defined by the pole being grater than some threshold (default PI/2 radians.
* @author James MacGlashan
*
*/
public static class InvertedPendulumRewardFunction implements RewardFunction{
/**
* The maximum pole angle to cause termination/failure.
*/
double maxAbsoluteAngle = (Math.PI / 2.);
public InvertedPendulumRewardFunction() {
}
/**
* Initializes with a max pole angle as specified in radians
* @param maxAbsoluteAngle the maximum pole angle in radians that causes task termination/failure.
*/
public InvertedPendulumRewardFunction(double maxAbsoluteAngle){
this.maxAbsoluteAngle = maxAbsoluteAngle;
}
@Override
public double reward(State s, GroundedAction a, State sprime) {
double failReward = -1;
ObjectInstance pendulum = s.getFirstObjectOfClass(CLASSPENDULUM);
double ang = pendulum.getRealValForAttribute(ATTANGLE);
if(Math.abs(ang) >= maxAbsoluteAngle){
return failReward;
}
return 0;
}
}
/**
* @param args none expect
*/
public static void main(String[] args) {
InvertedPendulum ivp = new InvertedPendulum();
Domain domain = ivp.generateDomain();
State s = InvertedPendulum.getInitialState(domain);
Visualizer v = InvertedPendulumVisualizer.getInvertedPendulumVisualizer();
VisualExplorer exp = new VisualExplorer(domain, v, s);
exp.addKeyAction("a", ACTIONLEFT);
exp.addKeyAction("d", ACTIONRIGHT);
exp.addKeyAction("s", ACTIONNOFORCE);
exp.initGUI();
}
} |
package com.biggestnerd.radarjammer;
import java.util.Collections;
import java.util.Enumeration;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.Map.Entry;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.logging.Logger;
import org.bukkit.Bukkit;
import org.bukkit.Material;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerJoinEvent;
import org.bukkit.event.player.PlayerMoveEvent;
import org.bukkit.event.player.PlayerQuitEvent;
import org.bukkit.inventory.ItemStack;
import org.bukkit.potion.PotionEffect;
import org.bukkit.potion.PotionEffectType;
import org.bukkit.scheduler.BukkitRunnable;
import com.comphenix.protocol.PacketType;
import com.comphenix.protocol.ProtocolLibrary;
import com.comphenix.protocol.events.ListenerPriority;
import com.comphenix.protocol.events.PacketAdapter;
import com.comphenix.protocol.events.PacketContainer;
import com.comphenix.protocol.events.PacketEvent;
import net.md_5.bungee.api.ChatColor;
public class VisibilityManager extends BukkitRunnable implements Listener{
private int minCheck;
private int maxCheck;
private double hFov;
private double vFov;
private boolean showCombatTagged;
private boolean timing;
private float maxSpin;
private long flagTime;
private int maxFlags;
private int blindDuration;
private long maxLogoutTime;
private ConcurrentHashMap<UUID, HashSet<UUID>[]> maps;
private ConcurrentHashMap<UUID, Long> blinded;
private ConcurrentLinkedQueue<UUID> blindQueue;
private ConcurrentHashMap<UUID, Integer> offlineTaskMap;
private AtomicBoolean buffer;
private CalculationThread calcThread;
private AntiBypassThread antiBypassThread;
private Logger log;
private RadarJammer plugin;
public VisibilityManager(RadarJammer plugin, int minCheck, int maxCheck, double hFov, double vFov, boolean showCombatTagged, boolean timing,
float maxSpin, long flagTime, int maxFlags, int blindDuration, boolean loadtest, long maxLogoutTime) {
this.plugin = plugin;
log = plugin.getLogger();
maps = new ConcurrentHashMap<UUID, HashSet<UUID>[]>();
blinded = new ConcurrentHashMap<UUID, Long>();
blindQueue = new ConcurrentLinkedQueue<UUID>();
offlineTaskMap = new ConcurrentHashMap<UUID, Integer>();
buffer = new AtomicBoolean();
this.minCheck = minCheck*minCheck;
this.maxCheck = maxCheck*maxCheck;
this.hFov = hFov;
this.vFov = vFov;
boolean ctEnabled = plugin.getServer().getPluginManager().isPluginEnabled("CombatTagPlus");
if(!ctEnabled || !showCombatTagged) {
this.showCombatTagged = false;
} else {
log.info("RadarJammer will show combat tagged players.");
this.showCombatTagged = true;
CombatTagManager.initialize();
}
this.timing = timing;
this.maxSpin = maxSpin;
this.flagTime = flagTime;
this.maxFlags = maxFlags;
this.blindDuration = blindDuration;
this.maxLogoutTime = maxLogoutTime;
runTaskTimer(plugin, 1L, 1L);
calcThread = new CalculationThread();
calcThread.start();
antiBypassThread = new AntiBypassThread();
antiBypassThread.start();
if(loadtest) new SyntheticLoadTest().runTaskTimerAsynchronously(plugin, 1L, 1L);
log.info("VisibilityManager initialized!");
}
private long lastCheckRun = 0l;
enum btype {
SHOW,
HIDE
}
public int getBuffer(btype buf) {
if (buffer.get()) {
switch(buf) {
case SHOW:
return 1;
case HIDE:
return 3;
}
} else {
switch(buf) {
case SHOW:
return 2;
case HIDE:
return 4;
}
}
return -1;
}
@Override
public void run() {
long s = System.currentTimeMillis();
long b = 0l;
long t = 0l;
long pl = 0l;
long sh = 0l;
long hi = 0l;
double aqp = 0.0d;
boolean buff = false;
// Flip buffers.
synchronized(buffer) {
buff = buffer.get();
buffer.set(!buff);
}
for(Player p : Bukkit.getOnlinePlayers()) {
if(timing) {
b = System.currentTimeMillis();
pl++;
}
if(blindQueue.remove(p.getUniqueId())) {
int amplifyMin = blindDuration + (int) antiBypassThread.angleChange.get(p.getUniqueId())[3];
int amplifyTicks = amplifyMin * 7200;
p.addPotionEffect(new PotionEffect(PotionEffectType.BLINDNESS, amplifyTicks, 1));
p.addPotionEffect(new PotionEffect(PotionEffectType.CONFUSION, amplifyTicks, 1));
p.sendMessage(ChatColor.DARK_RED + "You're spinning too fast and dizziness sets in. You are temporarily blinded for " + amplifyMin + " minutes!");
}
// now get the set of arrays. Careful to only deal with the "locked" ones
// based on the semaphore. In this case, "true" gives low-order buffers.
UUID pu = p.getUniqueId();
HashSet<UUID>[] buffers = maps.get(pu);
if (buffers == null) {
maps.put(pu, allocate());
continue;
}
HashSet<UUID> show = buffers[buff?1:2];
HashSet<UUID> hide = buffers[buff?3:4];
if(!show.isEmpty()) {
for(UUID id : show) {
Player o = Bukkit.getPlayer(id);
if(timing) sh++;
if(o != null) {
log.info(String.format("Showing %s to %s", o.getName(), p.getName()));
p.showPlayer(o);
if (hide.remove(id)) { // prefer to show rather then hide. In case of conflict, show wins.
log.info(String.format("Suppressed hide of %s from %s", o.getName(), p.getName()));
}
}
}
show.clear(); // prepare buffer for next swap.
}
if (p.hasPermission("jammer.bypass")) continue;
if(!hide.isEmpty()) {
for(UUID id : hide) {
Player o = Bukkit.getPlayer(id);
if(timing) hi++;
if(o != null) {
log.info(String.format("Hiding %s from %s", o.getName(), p.getName()));
p.hidePlayer(o);
}
}
hide.clear();
}
if(timing) {
t = System.currentTimeMillis();
aqp = aqp + ((double)(t-b) - aqp)/pl;
}
}
if ((s - lastCheckRun) > 1000l && timing) {
if (pl > 0)
log.info(String.format("Updated %d players in %d milliseconds, spending %.2f per player. Total %d seen updates and %d hide updates", pl, (t-s), aqp, sh, hi));
else
log.info("No players currently tracked.");
lastCheckRun = s;
}
}
@EventHandler
public void onPlayerJoin(PlayerJoinEvent event) {
Player player = event.getPlayer();
PlayerLocation location = getLocation(player);
calcThread.queueLocation(location);
HashSet<UUID>[] buffers = maps.get(player.getUniqueId());
if (buffers == null) {
maps.put(player.getUniqueId(), allocate());
} else {
for (HashSet<UUID> buffer : buffers){
buffer.clear();
}
}
Integer task = offlineTaskMap.remove(player.getUniqueId());
if(task != null) {
plugin.getServer().getScheduler().cancelTask(task);
}
}
@EventHandler
public void onPlayerLeave(PlayerQuitEvent event) {
UUID id = event.getPlayer().getUniqueId();
OfflinePlayerCheck offlineTask = new OfflinePlayerCheck(id);
offlineTaskMap.put(id, offlineTask.runTaskLater(plugin, maxLogoutTime).getTaskId());
}
@SuppressWarnings("unchecked")
private HashSet<UUID>[] allocate() {
return (HashSet<UUID>[]) new HashSet[] { new HashSet<UUID>(), new HashSet<UUID>(),
new HashSet<UUID>(), new HashSet<UUID>(), new HashSet<UUID>() };
}
@EventHandler
public void onPlayerMove(PlayerMoveEvent event) {
Player player = event.getPlayer();
PlayerLocation location = getLocation(player);
calcThread.queueLocation(location);
}
private PlayerLocation getLocation(Player player) {
boolean invis = player.hasPotionEffect(PotionEffectType.INVISIBILITY);
ItemStack inHand = player.getInventory().getItemInMainHand();
ItemStack offHand = player.getInventory().getItemInOffHand();
ItemStack[] armor = player.getInventory().getArmorContents();
boolean hasArmor = false;
for(ItemStack item : armor) if(item != null && item.getType() != Material.AIR) hasArmor = true;
invis = invis && (inHand == null || inHand.getType() == Material.AIR) && (offHand == null || offHand.getType() == Material.AIR) && !hasArmor;
return new PlayerLocation(player.getEyeLocation(), player.getUniqueId(), invis);
}
class CalculationThread extends Thread {
private final ConcurrentHashMap<UUID, PlayerLocation> locationMap = new ConcurrentHashMap<UUID, PlayerLocation>();
private final Set<UUID> movedPlayers = Collections.synchronizedSet(new LinkedHashSet<UUID>());
private final Set<UUID> recalc = Collections.synchronizedSet(new HashSet<UUID>());
public void run() {
log.info("RadarJammer: Starting calculation thread!");
long lastLoopStart = 0l;
Iterator<UUID> movedIterator = movedPlayers.iterator();
while(true) {
lastLoopStart = System.currentTimeMillis();
while (System.currentTimeMillis() - lastLoopStart < 50l && movedIterator.hasNext()) {
UUID id = movedIterator.next();
PlayerLocation next = locationMap.get(id);
if (next != null) {
recalc.add(id);
movedIterator.remove();
}
try {
sleep(1l);
}catch(InterruptedException ie) {}
}
if(!recalc.isEmpty()) {
doCalculations();
}
if (calcRuns > 20) {
showAvg();
}
try {
sleep(1l);
}catch(InterruptedException ie) {}
}
}
private void showAvg() {
if(!timing) return;
if (calcRuns == 0d || calcPerPlayerRuns == 0d) {
log.info("RadarJammer Calculations Performance: none done.");
} else {
log.info(String.format("RadarJammer Calculations Performance: %.0f runs, %.0f players calculated for.", calcRuns, calcPerPlayerRuns));
log.info(String.format(" on average: %.5fms in setup, %.4fms per player per run, %.4fms per run", (calcSetupAverage / calcRuns), (calcPerPlayerAverage / calcPerPlayerRuns), (calcAverage / calcRuns)));
}
calcSetupAverage = 0d;
calcPerPlayerAverage = 0d;
calcPerPlayerRuns = 0d;
calcAverage =0d;
calcRuns = 0d;
}
private void queueLocation(PlayerLocation location) {
if(location == null) return;
locationMap.put(location.getID(), location);
movedPlayers.add(location.getID());
}
private double calcSetupAverage = 0d;
private double calcPerPlayerAverage = 0d;
private double calcPerPlayerRuns = 0d;
private double calcAverage = 0d;
private double calcRuns = 0d;
long s_ = 0L;
long b_ = 0l;
long e_ = 0l;
private void doCalculations() {
for (UUID player : recalc) {
doCalculations(locationMap.get(player));
}
recalc.clear();
}
private void doCalculations(PlayerLocation location) {
if (location == null) return;
if(timing) {
calcRuns ++;
s_ = System.currentTimeMillis();
e_ = System.currentTimeMillis();
calcSetupAverage += (double) (e_ - s_);
}
UUID id = location.getID();
Enumeration<PlayerLocation> players = locationMap.elements();
while(players.hasMoreElements()) {
PlayerLocation other = players.nextElement();
UUID oid = other.getID();
if (id.equals(oid)) continue;
if(timing) {
calcPerPlayerRuns++;
b_ = System.currentTimeMillis();
}
boolean hidePlayer = shouldHide(other, location);
boolean hideOther = shouldHide(location, other);
/*
double dist = location.getSquaredDistance(other);
if(dist > minCheck) {
if(dist < maxCheck) {
hideOther = location.getAngle(other) > maxFov || other.isInvis();
hidePlayer = other.getAngle(location) > maxFov || location.isInvis();
} else {
hidePlayer = hideOther = true;
}
} else {
hidePlayer = hideOther = false;
}
*/
HashSet<UUID>[] buffers = maps.get(id);
if (buffers == null) return;
boolean hidingOther = buffers[0].contains(oid);
if(hidingOther != hideOther) {
if(hideOther) {
buffers[getBuffer(btype.HIDE)].add(oid);
buffers[0].add(oid);
} else {
buffers[getBuffer(btype.SHOW)].add(oid);
buffers[0].remove(oid);
}
}
buffers = maps.get(oid);
if (buffers == null) return;
boolean hidingPlayer = buffers[0].contains(id);
if(hidingPlayer != hidePlayer) {
if(hidePlayer) {
buffers[getBuffer(btype.HIDE)].add(id);
buffers[0].add(id);
} else {
buffers[getBuffer(btype.SHOW)].add(id);
buffers[0].remove(id);
}
}
if(timing) {
e_ = System.currentTimeMillis();
calcPerPlayerAverage += (e_ - b_);
}
}
if(timing) {
e_ = System.currentTimeMillis();
calcAverage += (e_ - s_);
}
}
private boolean shouldHide(PlayerLocation loc, PlayerLocation other) {
if(showCombatTagged && CombatTagManager.isTagged(loc.getID())) return false;
boolean blind = blinded.containsKey(loc.getID());
if(blind || other.isInvis()) return true;
double dist = loc.getSquaredDistance(other);
if(dist > minCheck) {
if(dist < maxCheck) {
double vAngle = loc.getVerticalAngle(other);
double hAngle = loc.getHorizontalAngle(other);
return !(vAngle < vFov && hAngle < hFov);
} else {
return true;
}
} else {
return false;
}
}
}
class AntiBypassThread extends Thread {
private ConcurrentHashMap<UUID, float[]> angleChange = new ConcurrentHashMap<UUID, float[]>();
public AntiBypassThread() {
ProtocolLibrary.getProtocolManager().addPacketListener(new PacketAdapter(plugin, ListenerPriority.NORMAL, PacketType.Play.Client.LOOK, PacketType.Play.Client.POSITION_LOOK) {
@Override
public void onPacketReceiving(PacketEvent event) {
PacketContainer packet = event.getPacket();
float yaw = packet.getFloat().read(0);
updatePlayer(event.getPlayer().getUniqueId(), yaw);
}
});
}
@Override
public void run() {
long lastLoopStart = 0l;
long lastFlagCheck = 0l;
while(true) {
if(System.currentTimeMillis() - lastFlagCheck > flagTime) {
lastFlagCheck = System.currentTimeMillis();
for(Entry<UUID, float[]> entry : angleChange.entrySet()) {
if(entry.getValue()[2] >= maxFlags) {
angleChange.get(entry.getKey())[3] += 1;
UUID id = entry.getKey();
log.info(id + " has reached the threshold for bypass flags, blinding them for a few minutes.");
blinded.put(id, System.currentTimeMillis());
entry.getValue()[2] = 0;
}
}
}
//Every second check angle change
if(System.currentTimeMillis() - lastLoopStart > 1000l) {
lastLoopStart = System.currentTimeMillis();
for(Entry<UUID, Long> entry : blinded.entrySet()) {
long blindLengthMillis = blindDuration * 60000;
if(System.currentTimeMillis() - entry.getValue() > blindLengthMillis) {
blinded.remove(entry.getKey());
}
}
for(Entry<UUID, float[]> entry : angleChange.entrySet()) {
boolean blind = entry.getValue()[0] > maxSpin;
entry.getValue()[0] = 0;
if(blind) {
entry.getValue()[2] += 1;
}
}
}
try {
sleep(1l);
}catch(InterruptedException ie) {}
}
}
private void updatePlayer(UUID player, float newAngle) {
if(!angleChange.containsKey(player)) {
angleChange.put(player, new float[]{0,newAngle,0,0});
} else {
float last = angleChange.get(player)[1];
float change = Math.abs(last - newAngle);
angleChange.get(player)[1] = newAngle;
angleChange.get(player)[0] += change;
}
}
}
class SyntheticLoadTest extends BukkitRunnable {
private PlayerLocation[] locations;
public SyntheticLoadTest() {
locations = new PlayerLocation[100];
int i = 0;
for(int x = 0; x < 10; x++) {
for(int z = 0; z < 10; z++) {
UUID id = UUID.randomUUID();
PlayerLocation location = new PlayerLocation(x * 10, 60, z * 10, 0, 0, id, false);
locations[i++] = location;
calcThread.queueLocation(location);
HashSet<UUID>[] buffers = maps.get(id);
if (buffers == null) {
maps.put(id, allocate());
} else {
for (HashSet<UUID> buffer : buffers){
buffer.clear();
}
}
}
}
}
@Override
public void run() {
for(int i = 0; i < locations.length; i++) {
if(locations[i] == null) break;
locations[i].addYaw(.5F);
calcThread.queueLocation(locations[i]);
}
}
}
class OfflinePlayerCheck extends BukkitRunnable {
private UUID id;
public OfflinePlayerCheck(UUID player) {
this.id = player;
}
@Override
public void run () {
Player player = Bukkit.getPlayer(id);
if(player == null || !player.isOnline()) {
maps.remove(id);
blinded.remove(id);
blindQueue.remove(id);
offlineTaskMap.remove(player);
}
}
}
} |
package com.googlecode.jmxtrans.model.naming;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Set;
import com.googlecode.jmxtrans.model.Query;
import com.googlecode.jmxtrans.model.Result;
import com.googlecode.jmxtrans.model.Server;
import static com.google.common.collect.Maps.newHashMap;
public final class KeyUtils {
private KeyUtils() {}
/**
* Gets the key string.
*
*
* @param server
* @param query the query
* @param result the result
* @param values the values
* @param typeNames the type names
* @param rootPrefix the root prefix
* @return the key string
*/
public static String getKeyString(Server server, Query query, Result result, Map.Entry<String, Object> values, List<String> typeNames, String rootPrefix, boolean useObjDomain) {
StringBuilder sb = new StringBuilder();
addRootPrefix(rootPrefix, sb);
addAlias(server, sb);
sb.append(".");
addKey(result, sb, useObjDomain);
sb.append(".");
addTypeName(query, result, typeNames, sb);
addKeyString(result, values, sb);
return sb.toString();
}
/**
* Gets the key string, without rootPrefix nor Alias
*
* @param query the query
* @param result the result
* @param values the values
* @param typeNames the type names
* @return the key string
*/
public static String getKeyString(Query query, Result result, Map.Entry<String, Object> values, List<String> typeNames) {
StringBuilder sb = new StringBuilder();
addKey(result, sb, false);
sb.append(".");
addTypeName(query, result, typeNames, sb);
addKeyString(result, values, sb);
return sb.toString();
}
/**
* Gets the key string, with dot allowed
*
* @param query the query
* @param result the result
* @param values the values
* @param typeNames the type names
* @return the key string
*/
public static String getKeyStringWithDottedKeys(Query query, Result result, Map.Entry<String, Object> values, List<String> typeNames) {
StringBuilder sb = new StringBuilder();
addKey(result, sb, false);
sb.append(".");
addTypeName(query, result, typeNames, sb);
addKeyStringDotted(result, values, query.isAllowDottedKeys(), sb);
return sb.toString();
}
private static void addRootPrefix(String rootPrefix, StringBuilder sb) {
if (rootPrefix != null) {
sb.append(rootPrefix);
sb.append(".");
}
}
private static void addAlias(Server server, StringBuilder sb) {
String alias;
if (server.getAlias() != null) {
alias = server.getAlias();
} else {
alias = server.getHost() + "_" + server.getPort();
alias = StringUtils.cleanupStr(alias);
}
sb.append(alias);
}
/**
* Adds a key to the StringBuilder
*
* It uses in order of preference:
*
* 1. resultAlias if that was specified as part of the query
* 2. The domain portion of the ObjectName in the query if useObjDomain is set to true
* 3. else, the Class Name of the MBean. I.e. ClassName will be used by default if the
* user doesn't specify anything special
*
* @param result
* @param sb
* @param useObjectDomain
*/
private static void addKey(Result result, StringBuilder sb, boolean useObjectDomain) {
if (result.getKeyAlias() != null) {
sb.append(result.getKeyAlias());
} else if (useObjectDomain) {
sb.append(StringUtils.cleanupStr(result.getObjDomain(), true));
} else {
sb.append(StringUtils.cleanupStr(result.getClassName()));
}
}
private static void addTypeName(Query query, Result result, List<String> typeNames, StringBuilder sb) {
String typeName = StringUtils.cleanupStr(getConcatedTypeNameValues(query, typeNames, result.getTypeName()), query.isAllowDottedKeys());
if (typeName != null && typeName.length() > 0) {
sb.append(typeName);
sb.append(".");
}
}
private static void addKeyString(Result result, Map.Entry<String, Object> values, StringBuilder sb) {
String keyStr = computeKey(result, values);
sb.append(StringUtils.cleanupStr(keyStr));
}
private static void addKeyStringDotted(Result result, Map.Entry<String, Object> values, boolean isAllowDottedKeys, StringBuilder sb) {
String keyStr = computeKey(result, values);
sb.append(StringUtils.cleanupStr(keyStr, isAllowDottedKeys));
}
private static String computeKey(Result result, Map.Entry<String, Object> values) {
String keyStr;
if (values.getKey().startsWith(result.getAttributeName())) {
keyStr = values.getKey();
} else {
keyStr = result.getAttributeName() + "." + values.getKey();
}
return keyStr;
}
/**
* Given a typeName string, get the first match from the typeNames setting.
* In other words, suppose you have:
* <p/>
* typeName=name=PS Eden Space,type=MemoryPool
* <p/>
* If you addTypeName("name"), then it'll retrieve 'PS Eden Space' from the
* string
*
* @param typeNames the type names
* @param typeNameStr the type name str
* @return the concated type name values
*/
public static String getConcatedTypeNameValues(List<String> typeNames, String typeNameStr) {
return getConcatedTypeNameValues(typeNames, typeNameStr, getTypeNameValuesSeparator(null));
}
/**
* Given a typeName string, get the first match from the typeNames setting.
* In other words, suppose you have:
* <p/>
* typeName=name=PS Eden Space,type=MemoryPool
* <p/>
* If you addTypeName("name"), then it'll retrieve 'PS Eden Space' from the
* string
*
* @param typeNames the type names
* @param typeNameStr the type name str
* @param separator
* @return the concated type name values
*/
public static String getConcatedTypeNameValues(List<String> typeNames, String typeNameStr, String separator) {
if ((typeNames == null) || (typeNames.size() == 0)) {
return null;
}
Map<String, String> typeNameValueMap = getTypeNameValueMap(typeNameStr);
StringBuilder sb = new StringBuilder();
for (String key : typeNames) {
String result = typeNameValueMap.get(key);
if (result != null) {
sb.append(result);
sb.append(separator);
}
}
return org.apache.commons.lang.StringUtils.chomp(sb.toString(), separator);
}
/**
* Given a typeName string, create a Map with every key and value in the typeName.
* For example:
* <p/>
* typeName=name=PS Eden Space,type=MemoryPool
* <p/>
* Returns a Map with the following key/value pairs (excluding the quotes):
* <p/>
* "name" => "PS Eden Space"
* "type" => "MemoryPool"
*
* @param typeNameStr the type name str
* @return Map<String, String> of type-name-key / value pairs.
*/
public static Map<String, String> getTypeNameValueMap(String typeNameStr) {
if (typeNameStr == null) {
return Collections.emptyMap();
}
Map<String, String> result = newHashMap();
String[] tokens = typeNameStr.split(",");
for (String oneToken : tokens) {
if (oneToken.length() > 0) {
String[] keyValue = splitTypeNameValue(oneToken);
result.put(keyValue[0], keyValue[1]);
}
}
return result;
}
/**
* Given a typeName string, get the first match from the typeNames setting.
* In other words, suppose you have:
* <p/>
* typeName=name=PS Eden Space,type=MemoryPool
* <p/>
* If you addTypeName("name"), then it'll retrieve 'PS Eden Space' from the
* string
*
* @param query the query
* @param typeNames the type names
* @param typeName the type name
* @return the concated type name values
*/
public static String getConcatedTypeNameValues(Query query, List<String> typeNames, String typeName) {
Set<String> queryTypeNames = query.getTypeNames();
if (queryTypeNames != null && queryTypeNames.size() > 0) {
List<String> filteredTypeNames = new ArrayList<String>(queryTypeNames);
for (String name : typeNames) {
if (!filteredTypeNames.contains(name)) {
filteredTypeNames.add(name);
}
}
return getConcatedTypeNameValues(filteredTypeNames, typeName, getTypeNameValuesSeparator(query));
} else {
return getConcatedTypeNameValues(typeNames, typeName, getTypeNameValuesSeparator(query));
}
}
/**
* Given a query, return a separator for type names based on its configuration.
* If query is null, return the default separator.
*
* @param query the query
* @return the separator
*/
private static String getTypeNameValuesSeparator(Query query) {
if (query != null && query.isAllowDottedKeys()) {
return ".";
}
return "_";
}
/**
* Given a single type-name-key and value from a typename strig (e.g. "type=MemoryPool"), extract the key and
* the value and return both.
*
* @param typeNameToken - the string containing the pair.
* @return String[2] where String[0] = the key and String[1] = the value. If the given string is not in the
* format "key=value" then String[0] = the original string and String[1] = "".
*/
private static String[] splitTypeNameValue(String typeNameToken) {
String[] result;
String[] keys = typeNameToken.split("=", 2);
if (keys.length == 2) {
result = keys;
} else {
result = new String[2];
result[0] = keys[0];
result[1] = "";
}
return result;
}
} |
package com.miviclin.droidengine2d.scene;
import android.util.SparseArray;
import com.miviclin.droidengine2d.Game;
import com.miviclin.droidengine2d.graphics.Graphics;
/**
* SceneManager.
*
* @author Miguel Vicente Linares
*
*/
public class SceneManager {
private SparseArray<Scene> scenes;
private Scene activeScene;
/**
* Constructor.
*/
public SceneManager() {
this(16);
}
/**
* Constructor.
*
* @param initialCapacity Initial capacity for Scenes. If this capacity is reached, the data structure that holds
* the Scenes will be resized automatically.
*/
public SceneManager(int initialCapacity) {
this.scenes = new SparseArray<Scene>(initialCapacity);
this.activeScene = null;
}
/**
* Registers an Scene in this SceneManager using the specified sceneId.<br>
* If an Scene with the specified sceneId was previously registered in this SceneManager, it will be replaced by the
* new one.<br>
* The active Scene will not change.
*
* @param sceneId Identifier of the Scene. It can be used to get the Scene from this SceneManager later.
* @param scene Scene (can not be null).
*/
public void registerScene(int sceneId, Scene scene) {
registerScene(sceneId, scene, false);
}
/**
* Registers an Scene in this SceneManager using the specified sceneId.<br>
* If an Scene with the specified sceneId was previously registered in this SceneManager, it will be replaced by the
* new one.
*
* @param sceneId Identifier of the Scene. It can be used to get the Scene from this SceneManager later.
* @param scene Scene (can not be null).
* @param activate true to make the Scene the active Scene of this SceneManager.
*/
public void registerScene(int sceneId, Scene scene, boolean activate) {
if (scene == null) {
throw new IllegalArgumentException("The Scene can not be null");
}
scenes.put(sceneId, scene);
scene.onRegister();
if (activate) {
setActiveScene(sceneId);
}
}
/**
* Unregisters the specified Scene from this SceneManager.<br>
* If an Scene was registered with the specified sceneId, {@link Scene#onDispose()} is called on the Scene before it
* is removed from this SceneManager.
*
* @param sceneId Identifier of the Scene.
* @return Removed Scene or null
*/
public Scene unregisterScene(int sceneId) {
Scene scene = scenes.get(sceneId);
if (scene == activeScene) {
scene.onDeactivation();
activeScene = null;
}
if (scene != null) {
scene.dispose();
scenes.remove(sceneId);
}
return scene;
}
/**
* Returns the Scene associated with the specified sceneId.
*
* @param sceneId Identifier of the Scene.
* @return Scene or null
*/
public Scene getScene(int sceneId) {
return scenes.get(sceneId);
}
/**
* Returns the active Scene of this SceneManager.
*
* @return Scene or null
*/
public Scene getActiveScene() {
return activeScene;
}
/**
* Sets the active Scene of this SceneManager.<br>
* The Scene must have been previously registered with the specified sceneId.
*
* @param sceneId Identifier of the Scene we want to set as the active Scene.
*/
public void setActiveScene(int sceneId) {
if (activeScene != null) {
activeScene.onDeactivation();
}
this.activeScene = scenes.get(sceneId);
if (activeScene != null) {
activeScene.onActivation();
}
}
/**
* This method is called when the engine is paused, usually when the activity goes to background.<br>
* Calls {@link Scene#onPause()} on the active Scene.
*/
public void pause() {
if (activeScene != null) {
activeScene.onPause();
}
}
/**
* This method is called when the engine is resumed, usually when the activity comes to foreground.<br>
* Calls {@link Scene#onResume()} on the active Scene.
*/
public void resume() {
if (activeScene != null) {
activeScene.onResume();
}
}
/**
* Calls {@link Scene#onDispose()} on all Scenes registered in this SceneManager and removes them from the
* SceneManager.<br>
* This SceneManager will be left empty.
*/
public void dispose() {
int numScenes = scenes.size();
for (int i = 0; i < numScenes; i++) {
Scene scene = scenes.valueAt(i);
if (scene != null) {
scene.dispose();
}
}
scenes.clear();
activeScene = null;
}
/**
* Calls {@link Scene#update(float)} on the active Scene .<br>
* This method is called from {@link Game#update(float)}.
*
* @param delta Elapsed time, in milliseconds, since the last update.
*/
public void update(float delta) {
if (activeScene != null) {
activeScene.update(delta);
}
}
/**
* Calls {@link Scene#draw(Graphics)} on the active Scene.<br>
* This method is called from {@link Game#draw(Graphics)}.<br>
* This method is called from the redering thread after {@link SceneManager#update(float)} has been executed in the
* game thread.
*/
public void draw(Graphics graphics) {
if (activeScene != null) {
activeScene.draw(graphics);
}
}
} |
package com.strobel.reflection.emit;
import com.strobel.core.VerifyArgument;
import com.strobel.reflection.ConstructorInfo;
import com.strobel.reflection.FieldInfo;
import com.strobel.reflection.MethodBuilder;
import com.strobel.reflection.MethodInfo;
import com.strobel.reflection.Type;
import com.strobel.util.ContractUtils;
import java.util.Arrays;
/**
* @author strobelm
*/
@SuppressWarnings(
{
"PointlessBitwiseExpression",
"PointlessArithmeticExpression",
"UnusedDeclaration",
"PackageVisibleField"
})
public class BytecodeGenerator {
final static int DefaultFixupArraySize = 64;
final static int DefaultLabelArraySize = 16;
final static int DefaultExceptionArraySize = 8;
private int _length;
private byte[] _bytecodeStream;
private int[] _labelList;
private int _labelCount;
private __FixupData[] _fixupData;
private int _fixupCount;
private int[] _rvaFixupList;
private int _rvaFixupCount;
private int[] _relocateFixupList;
private int _relocateFixupCount;
private int _exceptionCount;
private int _currExcStackCount;
private __ExceptionInfo[] _exceptions; //This is the list of all of the exceptions in this BytecodeStream.
private __ExceptionInfo[] _currExcStack; //This is the stack of exceptions which we're currently in.
ScopeTree _scopeTree; // this variable tracks all debugging scope information
MethodInfo _methodBuilder;
int _localCount;
// SignatureHelper _localSignature;
private int _maxStackSize = 0; // Maximum stack size not counting the exceptions.
private int _maxMidStack = 0; // Maximum stack size for a given basic block.
private int _maxMidStackCur = 0; // Running count of the maximum stack size for the current basic block.
public Label defineLabel() {
// Declares a new Label. This is just a token and does not yet represent any
// particular location within the stream. In order to set the position of the
// label within the stream, you must call markLabel().
if (_labelList == null) {
_labelList = new int[DefaultLabelArraySize];
}
if (_labelCount >= _labelList.length) {
_labelList = enlargeArray(_labelList);
}
_labelList[_labelCount] = -1;
return new Label(_labelCount++);
}
public void markLabel(final Label label) {
// Defines a label by setting the position where that label is found
// within the stream. Verifies the label is not defined more than once.
final int labelIndex = label.getLabelValue();
// This should never happen.
if (labelIndex < 0 || labelIndex >= _labelList.length) {
throw Error.badLabel();
}
if (_labelList[labelIndex] != -1) {
throw Error.labelAlreadyDefined();
}
_labelList[labelIndex] = _length;
}
public LocalBuilder declareLocal(final Type localType) {
VerifyArgument.notNull(localType, "localType");
// Declare a local of type "local". The current active lexical scope
// will be the scope that local will live.
final LocalBuilder localBuilder;
if (!(_methodBuilder instanceof MethodBuilder)) {
throw Error.bytecodeGeneratorNotOwnedByMethodBuilder();
}
final MethodBuilder methodBuilder = (MethodBuilder)_methodBuilder;
if (methodBuilder.isTypeCreated()) {
// cannot change method after its containing type has been created
throw Error.typeHasBeenCreated();
}
if (methodBuilder.isFinished()) {
throw Error.methodIsFinished();
}
// add the localType to local signature
// _localSignature.AddArgument(localType, pinned);
localBuilder = new LocalBuilder(_localCount, localType, methodBuilder);
_localCount++;
return localBuilder;
}
public void emit(final OpCode opCode) {
ensureCapacity(opCode.getSizeWithOperands());
internalEmit(opCode);
}
public void emit(final OpCode opCode, final byte arg) {
emit(opCode);
emitByteOperand(arg);
}
public void emit(final OpCode opCode, final short arg) {
emit(opCode);
emitShortOperand(arg);
}
public void emit(final OpCode opCode, final int arg) {
emit(opCode);
emitIntOperand(arg);
}
public void emit(final OpCode opCode, final long arg) {
emit(opCode);
emitLongOperand(arg);
}
public void emit(final OpCode opCode, final float arg) {
emit(opCode);
emitFloatOperand(arg);
}
public void emit(final OpCode opCode, final double arg) {
emit(opCode);
emitDoubleOperand(arg);
}
public void emit(final OpCode opCode, final String arg) {
throw ContractUtils.unreachable();
}
public void emit(final OpCode opCode, final Type<?> type) {
throw ContractUtils.unreachable();
}
public void emit(final OpCode opCode, final ConstructorInfo constructor) {
throw ContractUtils.unreachable();
}
public void emit(final OpCode opCode, final FieldInfo field) {
throw ContractUtils.unreachable();
}
public void emit(final OpCode opCode, final MethodInfo method) {
throw ContractUtils.unreachable();
}
public void emit(final OpCode opCode, final Label label) {
// Puts opCode onto the stream and leaves space to include label when fix-ups
// are done. Labels are created using BytecodeGenerator.defineLabel() and their
// location within the stream is fixed by using BytecodeGenerator.defineLabel().
// opCode must represent a branch instruction (although we don't explicitly
// verify this). Since branches are relative instructions, label will be
// replaced with the correct offset to branch during the fixup process.
final int tempVal = label.getLabelValue();
emit(opCode);
if (opCode.getOperandType() == OperandType.Branch) {
addFixup(label, _length, 2);
_length++;
}
else {
addFixup(label, _length, 4);
_length += 4;
}
}
public void emit(final OpCode opCode, final LocalBuilder local) {
// Puts the opcode onto the bytecode stream followed by the information
// for local variable local.
VerifyArgument.notNull(opCode, "opCode");
VerifyArgument.notNull(local, "local");
final int localIndex = local.getLocalIndex();
if (local.getMethodBuilder() != _methodBuilder) {
throw Error.unmatchedLocal();
}
final OpCode optimalOpCode;
if (opCode.getOperandType() == OperandType.Local) {
if (opCode.getCode() <= OpCode.ALOAD.getCode()) {
optimalOpCode = getLocalLoadOpCode(local.getLocalType(), localIndex);
}
else {
optimalOpCode = getLocalStoreOpCode(local.getLocalType(), localIndex);
}
}
else {
optimalOpCode = opCode;
}
emit(optimalOpCode);
if (optimalOpCode.getOperandType() == OperandType.Local) {
emitByteOperand((byte)localIndex);
}
}
public void emitCall(final OpCode opCode, final MethodInfo method) {
throw ContractUtils.unreachable();
}
public final void emitLoad(final LocalBuilder local) {
emit(
getLocalLoadOpCode(
local.getLocalType(),
local.getLocalIndex()
),
local
);
}
public final void emitStore(final LocalBuilder local) {
emit(
getLocalStoreOpCode(
local.getLocalType(),
local.getLocalIndex()
),
local
);
}
void emitByteOperand(final byte value) {
_bytecodeStream[_length] = value;
}
void emitCharOperand(final char value) {
_bytecodeStream[_length++] = (byte)((value >> 8) & 0xFF);
_bytecodeStream[_length++] = (byte)((value >> 0) & 0xFF);
}
void emitShortOperand(final short value) {
_bytecodeStream[_length++] = (byte)((value >> 8) & 0xFF);
_bytecodeStream[_length++] = (byte)((value >> 0) & 0xFF);
}
void emitIntOperand(final int value) {
_bytecodeStream[_length++] = (byte)((value >> 24) & 0xFF);
_bytecodeStream[_length++] = (byte)((value >> 16) & 0xFF);
_bytecodeStream[_length++] = (byte)((value >> 8) & 0xFF);
_bytecodeStream[_length++] = (byte)((value >> 0) & 0xFF);
}
void emitLongOperand(final long value) {
_bytecodeStream[_length++] = (byte)((value >> 56) & 0xFF);
_bytecodeStream[_length++] = (byte)((value >> 48) & 0xFF);
_bytecodeStream[_length++] = (byte)((value >> 40) & 0xFF);
_bytecodeStream[_length++] = (byte)((value >> 32) & 0xFF);
_bytecodeStream[_length++] = (byte)((value >> 24) & 0xFF);
_bytecodeStream[_length++] = (byte)((value >> 16) & 0xFF);
_bytecodeStream[_length++] = (byte)((value >> 8) & 0xFF);
_bytecodeStream[_length++] = (byte)((value >> 0) & 0xFF);
}
void emitFloatOperand(final float value) {
emitIntOperand(Float.floatToIntBits(value));
}
void emitDoubleOperand(final double value) {
emitLongOperand(Double.doubleToRawLongBits(value));
}
void internalEmit(final OpCode opCode) {
if (opCode.getSize() == 1) {
_bytecodeStream[_length++] = (byte)(opCode.getCode() & 0xFF);
}
else {
_bytecodeStream[_length++] = (byte)((opCode.getCode() >> 16) & 0xFF);
_bytecodeStream[_length++] = (byte)((opCode.getCode() >> 0) & 0xFF);
}
updateStackSize(opCode, opCode.getStackChange());
}
static byte getByteOperand(final byte[] codes, final int index) {
return codes[index];
}
static char getCharOperand(final byte[] codes, final int index) {
final int hi = ((codes[index + 0] & 0xFF) << 8);
final int lo = ((codes[index + 1] & 0xFF) << 0);
return (char)(hi + lo);
}
static short getShortOperand(final byte[] codes, final int index) {
final int hi = ((codes[index + 0] & 0xFF) << 8);
final int lo = ((codes[index + 1] & 0xFF) << 0);
return (short)(hi + lo);
}
static int getIntOperand(final byte[] codes, final int index) {
final int hh = ((codes[index + 0] & 0xFF) << 24);
final int hl = ((codes[index + 1] & 0xFF) << 16);
final int lh = ((codes[index + 2] & 0xFF) << 8);
final int ll = ((codes[index + 3] & 0xFF) << 0);
return hh + hl + lh + ll;
}
static long getLongOperand(final byte[] codes, final int index) {
return ((long)getIntOperand(codes, index) << 32) +
((long)getIntOperand(codes, index) << 0);
}
static float getFloatOperand(final byte[] codes, final int index) {
return Float.intBitsToFloat(getIntOperand(codes, index));
}
static double getDoubleOperand(final byte[] codes, final int index) {
return Double.longBitsToDouble(getIntOperand(codes, index));
}
static void putByteOperand(final byte[] codes, final int index, final byte value) {
codes[index] = value;
}
static void putCharOperand(final byte[] codes, final int index, final char value) {
codes[index + 0] = (byte)((value >> 8) & 0xFF);
codes[index + 1] = (byte)((value >> 0) & 0xFF);
}
static void putShortOperand(final byte[] codes, final int index, final short value) {
codes[index + 0] = (byte)((value >> 8) & 0xFF);
codes[index + 1] = (byte)((value >> 0) & 0xFF);
}
static void putIntOperand(final byte[] codes, final int index, final int value) {
codes[index + 0] = (byte)((value >> 24) & 0xFF);
codes[index + 1] = (byte)((value >> 16) & 0xFF);
codes[index + 2] = (byte)((value >> 8) & 0xFF);
codes[index + 3] = (byte)((value >> 0) & 0xFF);
}
static void putLongOperand(final byte[] codes, final int index, final long value) {
codes[index + 0] = (byte)((value >> 56) & 0xFF);
codes[index + 1] = (byte)((value >> 48) & 0xFF);
codes[index + 2] = (byte)((value >> 40) & 0xFF);
codes[index + 3] = (byte)((value >> 32) & 0xFF);
codes[index + 4] = (byte)((value >> 24) & 0xFF);
codes[index + 5] = (byte)((value >> 16) & 0xFF);
codes[index + 6] = (byte)((value >> 8) & 0xFF);
codes[index + 7] = (byte)((value >> 0) & 0xFF);
}
static void putFloatOperand(final byte[] codes, final int index, final float value) {
putIntOperand(codes, index, Float.floatToRawIntBits(value));
}
static void putDoubleOperand(final byte[] codes, final int index, final double value) {
putLongOperand(codes, index, Double.doubleToRawLongBits(value));
}
private void addFixup(final Label label, final int position, final int operandSize) {
// Notes the label, position, and instruction size of a new fixup. Expands
// all of the fixup arrays as appropriate.
if (_fixupData == null) {
_fixupData = new __FixupData[DefaultFixupArraySize];
}
if (_fixupCount >= _fixupData.length) {
_fixupData = enlargeArray(_fixupData);
}
_fixupData[_fixupCount].fixupPosition = position;
_fixupData[_fixupCount].fixupLabel = label;
_fixupData[_fixupCount].operandSize = operandSize;
_fixupCount++;
}
void ensureCapacity(final int size) {
// Guarantees an array capable of holding at least size elements.
if (_length + size >= _bytecodeStream.length) {
if (_length + size >= 2 * _bytecodeStream.length) {
_bytecodeStream = enlargeArray(_bytecodeStream, _length + size);
}
else {
_bytecodeStream = enlargeArray(_bytecodeStream);
}
}
}
void updateStackSize(final OpCode opCode, final int stackChange) {
// Updates internal variables for keeping track of the stack size
// requirements for the function. stackChange specifies the amount
// by which the stack size needs to be updated.
// Special case for the Return. Returns pops 1 if there is a
// non-void return value.
// Update the running stack size. _maxMidStack specifies the maximum
// amount of stack required for the current basic block irrespective of
// where you enter the block.
_maxMidStackCur += stackChange;
if (_maxMidStackCur > _maxMidStack) {
_maxMidStack = _maxMidStackCur;
}
else if (_maxMidStackCur < 0) {
_maxMidStackCur = 0;
}
// If the current instruction signifies end of a basic, which basically
// means an unconditional branch, add _maxMidStack to _maxStackSize.
// _maxStackSize will eventually be the sum of the stack requirements for
// each basic block.
if (opCode.endsUnconditionalJumpBlock()) {
_maxStackSize += _maxMidStack;
_maxMidStack = 0;
_maxMidStackCur = 0;
}
}
private int getLabelPosition(final Label label) {
// Gets the position in the stream of a particular label.
// Verifies that the label exists and that it has been given a value.
final int index = label.getLabelValue();
if (index < 0 || index >= _labelCount) {
throw Error.badLabel();
}
if (_labelList[index] < 0) {
throw Error.badLabelContent();
}
return _labelList[index];
}
byte[] bakeByteArray() {
// bakeByteArray() is a package private function designed to be called by
// MethodBuilder to do all of the fix-ups and return a new byte array
// representing the byte stream with labels resolved, etc.
final int newSize;
final byte[] newBytes;
int updateAddress;
if (_currExcStackCount != 0) {
throw Error.unclosedExceptionBlock();
}
if (_length == 0) {
return null;
}
newSize = _length;
newBytes = Arrays.copyOf(_bytecodeStream, newSize);
// Do the fix-ups. This involves iterating over all of the labels and replacing
// them with their proper values.
for (int i = 0; i < _fixupCount; i++) {
updateAddress = getLabelPosition(_fixupData[i].fixupLabel) -
(_fixupData[i].fixupPosition + _fixupData[i].operandSize);
// Handle single byte instructions
// Throw an exception if they're trying to store a jump in a single byte instruction that doesn't fit.
if (_fixupData[i].operandSize == 2) {
// Verify that our two-byte arg will fit into a Short.
if (updateAddress < Short.MIN_VALUE || updateAddress > Short.MAX_VALUE) {
throw Error.illegalTwoByteBranch(_fixupData[i].fixupPosition, updateAddress);
}
putShortOperand(newBytes, _fixupData[i].fixupPosition, (short)updateAddress);
}
else {
// Emit the four-byte arg.
putIntOperand(newBytes, _fixupData[i].fixupPosition, updateAddress);
}
}
return newBytes;
}
static int[] enlargeArray(final int[] incoming) {
return Arrays.copyOf(
VerifyArgument.notNull(incoming, "incoming"),
incoming.length * 2
);
}
static <T> T[] enlargeArray(final T[] incoming) {
return Arrays.copyOf(
incoming,
incoming.length * 2
);
}
static byte[] enlargeArray(final byte[] incoming) {
return Arrays.copyOf(
VerifyArgument.notNull(incoming, "incoming"),
incoming.length * 2
);
}
static byte[] enlargeArray(final byte[] incoming, final int requiredSize) {
return Arrays.copyOf(
VerifyArgument.notNull(incoming, "incoming"),
requiredSize
);
}
static OpCode getLocalLoadOpCode(final Type<?> type, final int localIndex) {
switch (type.getKind()) {
case BOOLEAN:
case BYTE:
case CHAR:
case SHORT:
case INT:
switch (localIndex) {
case 0:
return OpCode.ILOAD_0;
case 1:
return OpCode.ILOAD_1;
case 2:
return OpCode.ILOAD_2;
case 3:
return OpCode.ILOAD_3;
default:
return OpCode.ILOAD;
}
case LONG:
switch (localIndex) {
case 0:
return OpCode.LLOAD_0;
case 1:
return OpCode.LLOAD_1;
case 2:
return OpCode.LLOAD_2;
case 3:
return OpCode.LLOAD_3;
default:
return OpCode.LLOAD;
}
case FLOAT:
switch (localIndex) {
case 0:
return OpCode.FLOAD_0;
case 1:
return OpCode.FLOAD_1;
case 2:
return OpCode.FLOAD_2;
case 3:
return OpCode.FLOAD_3;
default:
return OpCode.FLOAD;
}
case DOUBLE:
switch (localIndex) {
case 0:
return OpCode.DLOAD_0;
case 1:
return OpCode.DLOAD_1;
case 2:
return OpCode.DLOAD_2;
case 3:
return OpCode.DLOAD_3;
default:
return OpCode.DLOAD;
}
default:
switch (localIndex) {
case 0:
return OpCode.ALOAD_0;
case 1:
return OpCode.ALOAD_1;
case 2:
return OpCode.ALOAD_2;
case 3:
return OpCode.ALOAD_3;
default:
return OpCode.ALOAD;
}
}
}
static OpCode getLocalStoreOpCode(final Type<?> type, final int localIndex) {
switch (type.getKind()) {
case BOOLEAN:
case BYTE:
case CHAR:
case SHORT:
case INT:
switch (localIndex) {
case 0:
return OpCode.ISTORE_0;
case 1:
return OpCode.ISTORE_1;
case 2:
return OpCode.ISTORE_2;
case 3:
return OpCode.ISTORE_3;
default:
return OpCode.ISTORE;
}
case LONG:
switch (localIndex) {
case 0:
return OpCode.LSTORE_0;
case 1:
return OpCode.LSTORE_1;
case 2:
return OpCode.LSTORE_2;
case 3:
return OpCode.LSTORE_3;
default:
return OpCode.LSTORE;
}
case FLOAT:
switch (localIndex) {
case 0:
return OpCode.FSTORE_0;
case 1:
return OpCode.FSTORE_1;
case 2:
return OpCode.FSTORE_2;
case 3:
return OpCode.FSTORE_3;
default:
return OpCode.FSTORE;
}
case DOUBLE:
switch (localIndex) {
case 0:
return OpCode.DSTORE_0;
case 1:
return OpCode.DSTORE_1;
case 2:
return OpCode.DSTORE_2;
case 3:
return OpCode.DSTORE_3;
default:
return OpCode.DSTORE;
}
default:
switch (localIndex) {
case 0:
return OpCode.ASTORE_0;
case 1:
return OpCode.ASTORE_1;
case 2:
return OpCode.ASTORE_2;
case 3:
return OpCode.ASTORE_3;
default:
return OpCode.ASTORE;
}
}
}
} |
package com.ecyrd.jspwiki.providers;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.IOException;
import java.io.FileNotFoundException;
import java.io.File;
import java.io.FilenameFilter;
import java.io.FileOutputStream;
import java.io.FileInputStream;
import java.util.Collection;
import java.util.Properties;
import java.util.ArrayList;
import org.apache.log4j.Category;
import com.ecyrd.jspwiki.*;
import com.ecyrd.jspwiki.attachment.Attachment;
/**
* Provides basic, versioning attachments.
*
* <PRE>
* Structure is as follows:
* attachment_dir/
* ThisPage/
* attachment.doc/
* attachment.properties
* 1.doc
* 2.doc
* 3.doc
* picture.png/
* attachment.properties
* 1.png
* 2.png
* ThatPage/
* picture.png/
* attachment.properties
* 1.png
*
* </PRE>
*
* "attachment.properties" consists of the following items:
* <UL>
* <LI>1.author = author name for version 1 (etc)
* </UL>
*/
public class BasicAttachmentProvider
implements WikiAttachmentProvider
{
private String m_storageDir;
public static final String PROP_STORAGEDIR = "jspwiki.basicAttachmentProvider.storageDir";
public static final String PROPERTY_FILE = "attachment.properties";
public static final String DIR_EXTENSION = "-att";
static final Category log = Category.getInstance( BasicAttachmentProvider.class );
public void initialize( Properties properties )
throws NoRequiredPropertyException,
IOException
{
m_storageDir = WikiEngine.getRequiredProperty( properties, PROP_STORAGEDIR );
}
/**
* Finds storage dir, makes sure it exists.
*
* @param wikipage Page to which this attachment is attached.
*/
private File findPageDir( String wikipage )
throws ProviderException
{
File f = new File( m_storageDir, wikipage+DIR_EXTENSION );
if( !f.exists() )
{
f.mkdirs();
}
if( !f.isDirectory() )
{
throw new ProviderException("Storage dir '"+f.getAbsolutePath()+"' is not a directory!");
}
return f;
}
/**
* Finds the dir in which the attachment lives.
*/
private File findAttachmentDir( Attachment att )
throws ProviderException
{
File f = new File( findPageDir(att.getName()), att.getFileName() );
return f;
}
/**
* Goes through the repository and decides which version is
* the newest one in that directory.
*
* @return Latest version number in the repository, or 0, if
* there is no page in the repository.
*/
private int findLatestVersion( Attachment att )
throws ProviderException
{
// File pageDir = findPageDir( att.getName() );
File attDir = findAttachmentDir( att );
System.out.println("Finding pages in "+attDir.getAbsolutePath());
String[] pages = attDir.list( new AttachmentVersionFilter() );
if( pages == null )
{
return 0; // No such thing found.
}
int version = 0;
for( int i = 0; i < pages.length; i++ )
{
System.out.println("Checking: "+pages[i]);
int cutpoint = pages[i].indexOf( '.' );
if( cutpoint > 0 )
{
String pageNum = pages[i].substring( 0, cutpoint );
try
{
int res = Integer.parseInt( pageNum );
if( res > version )
{
version = res;
}
}
catch( NumberFormatException e ) {} // It's okay to skip these.
}
}
return version;
}
/**
* Returns the file extension. For example "test.png" returns "png".
*/
protected static String getFileExtension( String filename )
{
String fileExt = "";
int dot = filename.lastIndexOf('.');
if( dot >= 0 )
{
fileExt = filename.substring( dot+1 );
}
return fileExt;
}
/**
* Writes the page properties back to the file system.
* Note that it WILL overwrite any previous properties.
*/
private void putPageProperties( Attachment att, Properties properties )
throws IOException,
ProviderException
{
File attDir = findAttachmentDir( att );
File propertyFile = new File( attDir, PROPERTY_FILE );
OutputStream out = new FileOutputStream( propertyFile );
properties.store( out,
" JSPWiki page properties for "+
att.getName()+"/"+att.getFileName()+
". DO NOT MODIFY!" );
out.close();
}
/**
* Reads page properties from the file system.
*/
private Properties getPageProperties( Attachment att )
throws IOException,
ProviderException
{
Properties props = new Properties();
File propertyFile = new File( findAttachmentDir(att), PROPERTY_FILE );
if( propertyFile != null && propertyFile.exists() )
{
InputStream in = new FileInputStream( propertyFile );
props.load(in);
in.close();
}
return props;
}
public void putAttachmentData( Attachment att, InputStream data )
throws ProviderException,
IOException
{
OutputStream out = null;
File attDir = findAttachmentDir( att );
if(!attDir.exists())
{
attDir.mkdirs();
}
int latestVersion = findLatestVersion( att );
System.out.println("Latest version is "+latestVersion);
try
{
int versionNumber = latestVersion+1;
File newfile = new File( attDir, versionNumber+"."+
getFileExtension(att.getFileName()) );
log.info("Uploading attachment "+att.getFileName()+" to page "+att.getName());
log.info("Saving attachment contents to "+newfile.getAbsolutePath());
out = new FileOutputStream(newfile);
FileUtil.copyContents( data, out );
out.close();
Properties props = getPageProperties( att );
props.setProperty( versionNumber+".author", att.getAuthor() );
putPageProperties( att, props );
}
catch( IOException e )
{
log.error( "Could not save attachment data: ", e );
throw (IOException) e.fillInStackTrace();
}
finally
{
if( out != null ) out.close();
}
}
public String getProviderInfo()
{
return "";
}
public InputStream getAttachmentData( Attachment att )
throws IOException,
ProviderException
{
File attDir = findAttachmentDir( att );
int version = att.getVersion();
if( version == WikiProvider.LATEST_VERSION )
{
version = findLatestVersion( att );
}
File f = new File( attDir, version+"."+getFileExtension(att.getFileName()) );
if( !f.exists() )
{
throw new FileNotFoundException("No such file: "+f.getAbsolutePath()+" exists.");
}
return new FileInputStream( f );
}
public Collection listAttachments( WikiPage page )
throws ProviderException
{
Collection result = new ArrayList();
File dir = findPageDir( page.getName() );
String[] attachments = dir.list();
for( int i = 0; i < attachments.length; i++ )
{
File f = new File( dir, attachments[i] );
if( f.isDirectory() )
{
Attachment att = getAttachmentInfo( page, attachments[i],
WikiProvider.LATEST_VERSION );
result.add( att );
}
}
return result;
}
public Collection findAttachments( QueryItem[] query )
{
return null;
}
public Attachment getAttachmentInfo( WikiPage page, String name, int version )
throws ProviderException
{
File dir = new File( findPageDir( page.getName() ), name );
if( !dir.exists() )
{
log.debug("Attachment dir not found - thus no attachment can exist.");
return null;
}
Attachment att = new Attachment( page.getName() );
att.setFileName( name );
if( version == WikiProvider.LATEST_VERSION )
{
version = findLatestVersion(att);
}
att.setVersion( version );
System.out.println("Fetching info on version "+version);
try
{
Properties props = getPageProperties(att);
att.setAuthor( props.getProperty( version+".author" ) );
}
catch( IOException e )
{
log.error("Can't read page properties", e );
throw new ProviderException("Cannot read page properties: "+e.getMessage());
}
// FIXME: Check for existence of this particular version.
return att;
}
public Collection getVersionHistory( String wikiname )
{
return null;
}
/**
* Returns only those directories that contain attachments.
*/
public class AttachmentFilter
implements FilenameFilter
{
public boolean accept( File dir, String name )
{
return name.endsWith( DIR_EXTENSION );
}
}
/**
* Accepts only files that are actual versions, no control files.
*/
public class AttachmentVersionFilter
implements FilenameFilter
{
public boolean accept( File dir, String name )
{
return !name.equals( PROPERTY_FILE );
}
}
} |
package com.esotericsoftware.kryonet;
import java.net.DatagramPacket;
import com.esotericsoftware.kryo.Kryo;
import com.esotericsoftware.kryo.io.Input;
public interface ClientDiscoveryHandler {
/** This implementation of the {@link ClientDiscoveryHandler} is responsible for providing the {@link Client} with it's default
* behavior. */
public static final ClientDiscoveryHandler DEFAULT = new ClientDiscoveryHandler() {
public DatagramPacket onRequestNewDatagramPacket () {
return new DatagramPacket(new byte[0], 0);
}
public void onDiscoveredHost (DatagramPacket datagramPacket, Kryo kryo) {
}
public void onFinally () {
}
};
/** Implementations of this method should return a new {@link DatagramPacket} that the {@link Client} will use to fill with the
* incoming packet data sent by the {@link ServerDiscoveryHandler}.
* @return a new {@link DatagramPacket} */
public DatagramPacket onRequestNewDatagramPacket ();
/** Called when the {@link Client} discovers a host.
* @param datagramPacket the same {@link DatagramPacket} from {@link #onRequestNewDatagramPacket()}, after being filled with
* the incoming packet data.
* @param kryo the {@link Kryo} instance, or null. */
public void onDiscoveredHost (DatagramPacket datagramPacket, Kryo kryo);
/** Called right before the {@link Client#discoverHost(int, int)} or {@link Client#discoverHosts(int, int)} method exits. This
* allows the implementation to clean up any resources used, i.e. an {@link Input}. */
public void onFinally ();
} |
package com.hp.hpl.jena.reasoner.rulesys.test;
import com.hp.hpl.jena.reasoner.*;
import com.hp.hpl.jena.reasoner.test.*;
import com.hp.hpl.jena.vocabulary.OWL;
import com.hp.hpl.jena.vocabulary.RDF;
import com.hp.hpl.jena.vocabulary.RDFS;
import com.hp.hpl.jena.reasoner.rulesys.*;
import com.hp.hpl.jena.rdf.model.*;
import junit.framework.TestCase;
import junit.framework.TestSuite;
import java.io.IOException;
import java.util.Iterator;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
public class TestRDFSRules extends TestCase {
/** Base URI for the test names */
public static final String NAMESPACE = "http:
protected static Log logger = LogFactory.getLog(TestRDFSRules.class);
/**
* Boilerplate for junit
*/
public TestRDFSRules( String name ) {
super( name );
}
/**
* Boilerplate for junit.
* This is its own test suite
*/
public static TestSuite suite() {
return new TestSuite(TestRDFSRules.class);
// TestSuite suite = new TestSuite();
// suite.addTest(new TestRDFSRules( "hiddenTestRDFSReasonerDebug" ));
// return suite;
}
/**
* Test a single RDFS case.
*/
public void hiddenTestRDFSReasonerDebug() throws IOException {
ReasonerTester tester = new ReasonerTester("rdfs/manifest-nodirect-noresource.rdf");
ReasonerFactory rf = RDFSRuleReasonerFactory.theInstance();
assertTrue("RDFS hybrid-tgc reasoner test", tester.runTest("http:
}
/**
* Test the basic functioning of the hybrid RDFS rule reasoner
*/
public void testRDFSFBReasoner() throws IOException {
ReasonerTester tester = new ReasonerTester("rdfs/manifest-nodirect-noresource.rdf");
ReasonerFactory rf = RDFSFBRuleReasonerFactory.theInstance();
assertTrue("RDFS hybrid reasoner tests", tester.runTests(rf, this, null));
}
/**
* Test the basic functioning of the hybrid RDFS rule reasoner with TGC cache
*/
public void testRDFSExptReasoner() throws IOException {
ReasonerTester tester = new ReasonerTester("rdfs/manifest-nodirect-noresource.rdf");
ReasonerFactory rf = RDFSRuleReasonerFactory.theInstance();
assertTrue("RDFS experimental (hybrid+tgc) reasoner tests", tester.runTests(rf, this, null));
}
/**
* Test the capabilities description.
*/
public void testRDFSDescription() {
ReasonerFactory rf = RDFSFBRuleReasonerFactory.theInstance();
Reasoner r = rf.create(null);
assertTrue(r.supportsProperty(RDFS.subClassOf));
assertTrue(r.supportsProperty(RDFS.domain));
assertTrue( ! r.supportsProperty(OWL.allValuesFrom));
}
/**
* Time a trial list of results from an inf graph.
*/
private static void doTiming(Reasoner r, Model tbox, Model data, String name, int loop) {
Resource C1 = ResourceFactory.createResource("http://www.hpl.hp.com/semweb/2003/eg
Resource C2 = ResourceFactory.createResource("http://www.hpl.hp.com/semweb/2003/eg
long t1 = System.currentTimeMillis();
int count = 0;
for (int lp = 0; lp < loop; lp++) {
Model m = ModelFactory.createModelForGraph(r.bindSchema(tbox.getGraph()).bind(data.getGraph()));
count = 0;
for (Iterator i = m.listStatements(null, RDF.type, C1); i.hasNext(); i.next()) count++;
}
long t2 = System.currentTimeMillis();
long time10 = (t2-t1)*10/loop;
long time = time10/10;
long timeFraction = time10 - (time*10);
System.out.println(name + ": " + count +" results in " + time + "." + timeFraction +"ms");
// t1 = System.currentTimeMillis();
// for (int j = 0; j < 10; j++) {
// count = 0;
// for (Iterator i = m.listStatements(null, RDF.type, C1); i.hasNext(); i.next()) count++;
// t2 = System.currentTimeMillis();
// System.out.println(name + ": " + count + " results in " + (t2-t1)/10 +"ms");
}
} |
package com.itmill.toolkit.terminal.gwt.client;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.FlowPanel;
import com.google.gwt.user.client.ui.Label;
import com.itmill.toolkit.terminal.gwt.client.ui.IWindow;
public final class DebugConsole extends IWindow implements Console {
private FlowPanel panel;
public DebugConsole() {
super();
panel = new FlowPanel();
this.setWidget(panel);
this.setCaption("Debug window");
minimize();
show();
}
private void minimize() {
// TODO stack to bottom (create window manager of some sort)
setPixelSize(60, 60);
setPopupPosition(Window.getClientWidth() - 66, Window.getClientHeight() - 66);
}
/* (non-Javadoc)
* @see com.itmill.toolkit.terminal.gwt.client.Console#log(java.lang.String)
*/
public void log(String msg) {
panel.add(new Label(msg));
System.out.println(msg);
}
/* (non-Javadoc)
* @see com.itmill.toolkit.terminal.gwt.client.Console#error(java.lang.String)
*/
public void error(String msg) {
panel.add((new Label(msg)));
System.out.println(msg);
}
/* (non-Javadoc)
* @see com.itmill.toolkit.terminal.gwt.client.Console#printObject(java.lang.Object)
*/
public void printObject(Object msg) {
panel.add((new Label(msg.toString())));
}
/* (non-Javadoc)
* @see com.itmill.toolkit.terminal.gwt.client.Console#dirUIDL(com.itmill.toolkit.terminal.gwt.client.UIDL)
*/
public void dirUIDL(UIDL u) {
panel.add(u.print_r());
}
} |
package com.lysdev.transperthcached.silverrails;
import java.util.Vector;
import android.location.Location;
public class TransitStop {
private int code;
private int zone;
private Location position;
private String dataSet;
private String description;
private String stopUid;
private String[] routes;
private String[] supportedModes;
private double latitude, longitude;
public TransitStop(double latitude, double longitude, String description, int code) {
this.latitude = latitude;
this.longitude = longitude;
this.position = new Location("TransitStop");
this.position.setLatitude(latitude);
this.position.setLongitude(longitude);
this.description = description;
this.code = code;
}
public Location getPosition() {
return this.position;
}
public String getCode() {
return Integer.toString(code);
}
public String getDescription() {
return this.description;
}
}
// DataSet = "PerthRestricted"
// Code = "11990"
// StopUid = "PerthRestricted:11990"
// Description = "Walanna Dr Before Lowan Loop"
// Position = "-32.0055906, 115.8858706"
// Zone = "1"
// SupportedModes = "Bus"
// Routes = "PerthRestricted:39002;PerthRestricted:39146" |
package com.rapidminer.gui.properties;
import java.util.Collection;
import java.util.LinkedList;
import java.util.List;
import com.rapidminer.operator.Operator;
import com.rapidminer.parameter.ParameterType;
import com.rapidminer.parameter.Parameters;
import com.rapidminer.parameter.UndefinedParameterError;
/**
* This panel might be used, where ever ParameterTypes should be editable without presence of an operator
* or special circumstances.
*
* @author Sebastian Land
*
*/
public class GenericParameterPanel extends PropertyPanel {
private static final long serialVersionUID = -8633435565053835262L;
private Parameters parameters = null;
// private Map<String, String> keyValueMap = new LinkedHashMap<String, String>();
// private Map<String, ParameterType> keyTypeMap = new LinkedHashMap<String, ParameterType>();
public GenericParameterPanel() {
}
public GenericParameterPanel(Parameters parameters) {
super();
setParameters(parameters);
}
@Override
protected Operator getOperator() {
return null;
}
@Override
protected Collection<ParameterType> getProperties() {
List<ParameterType> visible = new LinkedList<ParameterType>();
if (parameters != null) {
for (ParameterType type: parameters.getParameterTypes()) {
if (!type.isHidden())
visible.add(type);
}
}
return visible;
}
@Override
protected String getValue(ParameterType type) {
if (parameters != null) {
try {
return parameters.getParameter(type.getKey());
} catch (UndefinedParameterError e) {
return type.getDefaultValueAsString();
}
} else {
return null;
}
//return keyValueMap.get(type.getKey());
}
@Override
/**
* This implementation ignores the operator, since it is null anyway.
*/
protected void setValue(Operator operator, ParameterType type, String value) {
if (parameters != null) {
parameters.setParameter(type.getKey(), value);
//keyValueMap.put(type.getKey(), value);
setupComponents();
}
}
public void setValue(String key, String value) {
parameters.setParameter(key, value);
//keyValueMap.put(key, value);
setupComponents();
}
public void setParameters(Parameters parameters) {
this.parameters = parameters;
// keyValueMap.clear();
// keyTypeMap.clear();
// for (ParameterType type: parameters) {
// keyValueMap.put(type.getKey(), type.getDefaultValueAsString());
// keyTypeMap.put(type.getKey(), type);
// calling super method for rebuilding panel
setupComponents();
}
public void clearProperties() {
this.parameters = null;
setupComponents();
}
public Parameters getParameters() {
return parameters;
}
// public Collection<String> getPropertyKeys() {
// return keyValueMap.keySet();
// public String getValue(String key) {
// return keyValueMap.get(key);
} |
package com.toscana.model.reports.types;
import com.toscana.model.sessions.Session;
import java.io.Serializable;
import javax.persistence.*;
@Entity
@Table (name ="summaryPayments")
public class SummaryPaymentsType implements Serializable {
/*
* Class' methods
*/
/*
* Getters and Setters
*/
public String getCurrency() {
return currency;
}
public void setCurrency(String currency) {
this.currency = currency;
}
public double getAmount() {
return amount;
}
public void setAmount(double amount) {
this.amount = amount;
}
public Session getSession() {
return session;
}
public void setSession(Session session) {
this.session = session;
}
public int getID() {
return ID;
}
public void setID(int ID) {
this.ID = ID;
}
/*
* Inner methods
*/
/*
* Attributes
*/
@Id
@Column (name ="id")
@GeneratedValue
private int ID;
@Column (name = "currency")
private String currency;
@Column (name = "amount")
private double amount;
@Column (name = "session")
@OneToOne
private Session session;
} |
package de.lmu.ifi.dbs.algorithm.clustering;
import de.lmu.ifi.dbs.algorithm.AbstractAlgorithm;
import de.lmu.ifi.dbs.algorithm.Algorithm;
import de.lmu.ifi.dbs.algorithm.result.clustering.ClustersPlusNoise;
import de.lmu.ifi.dbs.data.RealVector;
import de.lmu.ifi.dbs.database.AssociationID;
import de.lmu.ifi.dbs.database.Database;
import de.lmu.ifi.dbs.distance.DoubleDistance;
import de.lmu.ifi.dbs.distance.LocallyWeightedDistanceFunction;
import de.lmu.ifi.dbs.logging.LoggingConfiguration;
import de.lmu.ifi.dbs.logging.ProgressLogRecord;
import de.lmu.ifi.dbs.varianceanalysis.AbstractLocalPCA;
import de.lmu.ifi.dbs.preprocessing.ProjectedDBSCANPreprocessor;
import de.lmu.ifi.dbs.utilities.Progress;
import de.lmu.ifi.dbs.utilities.QueryResult;
import de.lmu.ifi.dbs.utilities.Util;
import de.lmu.ifi.dbs.utilities.optionhandling.AttributeSettings;
import de.lmu.ifi.dbs.utilities.optionhandling.OptionHandler;
import de.lmu.ifi.dbs.utilities.optionhandling.ParameterException;
import de.lmu.ifi.dbs.utilities.optionhandling.WrongParameterValueException;
import java.util.*;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* Provides an abstract algorithm requiring a VarianceAnalysisPreprocessor.
*
* @author Arthur Zimek (<a href="mailto:zimek@dbs.ifi.lmu.de">zimek@dbs.ifi.lmu.de</a>)
*/
public abstract class ProjectedDBSCAN<P extends ProjectedDBSCANPreprocessor> extends AbstractAlgorithm<RealVector> implements Clustering<RealVector> {
/**
* Holds the class specific debug status.
*/
@SuppressWarnings({"UNUSED_SYMBOL"})
private static final boolean DEBUG = LoggingConfiguration.DEBUG;
/**
* The logger of this class.
*/
private Logger logger = Logger.getLogger(this.getClass().getName());
/**
* Parameter for epsilon.
*/
public static final String EPSILON_P = DBSCAN.EPSILON_P;
/**
* Description for parameter epsilon.
*/
public static final String EPSILON_D = "<epsilon>the maximum radius of the neighborhood to be considered, must be suitable to " + LocallyWeightedDistanceFunction.class.getName();
/**
* Parameter minimum points.
*/
public static final String MINPTS_P = DBSCAN.MINPTS_P;
/**
* Description for parameter minimum points.
*/
public static final String MINPTS_D = DBSCAN.MINPTS_D;
/**
* Epsilon.
*/
protected String epsilon;
/**
* Minimum points.
*/
protected int minpts;
/**
* Parameter lambda.
*/
public static final String LAMBDA_P = "lambda";
/**
* Description for parameter lambda.
*/
public static final String LAMBDA_D = "<lambda>a positive integer specifiying the intrinsic dimensionality of clusters to be found.";
/**
* Keeps lambda.
*/
private int lambda;
/**
* Holds a list of clusters found.
*/
private List<List<Integer>> resultList;
/**
* Provides the result of the algorithm.
*/
private ClustersPlusNoise<RealVector> result;
/**
* Holds a set of noise.
*/
private Set<Integer> noise;
/**
* Holds a set of processed ids.
*/
private Set<Integer> processedIDs;
/**
* The distance function.
*/
private LocallyWeightedDistanceFunction distanceFunction = new LocallyWeightedDistanceFunction();
/**
* Provides the abstract algorithm for variance analysis based DBSCAN.
*/
protected ProjectedDBSCAN() {
super();
parameterToDescription.put(EPSILON_P + OptionHandler.EXPECTS_VALUE, EPSILON_D);
parameterToDescription.put(MINPTS_P + OptionHandler.EXPECTS_VALUE, MINPTS_D);
parameterToDescription.put(LAMBDA_P + OptionHandler.EXPECTS_VALUE, LAMBDA_D);
parameterToDescription.put(ProjectedDBSCANPreprocessor.DELTA_P + OptionHandler.EXPECTS_VALUE, ProjectedDBSCANPreprocessor.DELTA_D);
optionHandler = new OptionHandler(parameterToDescription, this.getClass().getName());
}
/**
* @see AbstractAlgorithm#runInTime(Database)
*/
protected void runInTime(Database<RealVector> database) throws IllegalStateException {
if (isVerbose()) {
logger.info("\n");
}
try {
Progress progress = new Progress("Clustering", database.size());
resultList = new ArrayList<List<Integer>>();
noise = new HashSet<Integer>();
processedIDs = new HashSet<Integer>(database.size());
distanceFunction.setDatabase(database, isVerbose(), isTime());
if (isVerbose()) {
logger.info("\nClustering:\n");
}
if (database.size() >= minpts) {
for (Iterator<Integer> iter = database.iterator(); iter.hasNext();) {
Integer id = iter.next();
if (!processedIDs.contains(id)) {
expandCluster(database, id, progress);
if (processedIDs.size() == database.size() && noise.size() == 0) {
break;
}
}
if (isVerbose()) {
progress.setProcessed(processedIDs.size());
logger.log(new ProgressLogRecord(Level.INFO, Util.status(progress, resultList.size()), progress.getTask(), progress.status()));
}
}
}
else {
for (Iterator<Integer> iter = database.iterator(); iter.hasNext();) {
Integer id = iter.next();
noise.add(id);
if (isVerbose()) {
progress.setProcessed(processedIDs.size());
logger.log(new ProgressLogRecord(Level.INFO, Util.status(progress, resultList.size()), progress.getTask(), progress.status()));
}
}
}
if (isVerbose()) {
progress.setProcessed(processedIDs.size());
logger.log(new ProgressLogRecord(Level.INFO, Util.status(progress, resultList.size()), progress.getTask(), progress.status()));
}
Integer[][] resultArray = new Integer[resultList.size() + 1][];
int i = 0;
for (Iterator<List<Integer>> resultListIter = resultList.iterator(); resultListIter.hasNext(); i++) {
resultArray[i] = resultListIter.next().toArray(new Integer[0]);
}
resultArray[resultArray.length - 1] = noise.toArray(new Integer[0]);
result = new ClustersPlusNoise<RealVector>(resultArray, database);
if (isVerbose()) {
progress.setProcessed(processedIDs.size());
logger.log(new ProgressLogRecord(Level.INFO, Util.status(progress, resultList.size()), progress.getTask(), progress.status()));
}
}
catch (Exception e) {
throw new IllegalStateException(e);
}
}
/**
* ExpandCluster function of DBSCAN.
*/
protected void expandCluster(Database<RealVector> database, Integer startObjectID, Progress progress) {
List<QueryResult<DoubleDistance>> neighborhoodIDs = database.rangeQuery(startObjectID, epsilon, distanceFunction);
if (neighborhoodIDs.size() < minpts) {
noise.add(startObjectID);
processedIDs.add(startObjectID);
if (isVerbose()) {
progress.setProcessed(processedIDs.size());
logger.log(new ProgressLogRecord(Level.INFO, Util.status(progress, resultList.size()), progress.getTask(), progress.status()));
}
}
else {
List<Integer> currentCluster = new ArrayList<Integer>();
if ((Integer) database.getAssociation(AssociationID.LOCAL_DIMENSIONALITY, startObjectID) > lambda) {
noise.add(startObjectID);
processedIDs.add(startObjectID);
if (isVerbose()) {
progress.setProcessed(processedIDs.size());
logger.log(new ProgressLogRecord(Level.INFO, Util.status(progress, resultList.size()), progress.getTask(), progress.status()));
}
}
else {
List<QueryResult<DoubleDistance>> seeds = database.rangeQuery(startObjectID, epsilon, distanceFunction);
if (seeds.size() < minpts) {
noise.add(startObjectID);
processedIDs.add(startObjectID);
if (isVerbose()) {
progress.setProcessed(processedIDs.size());
logger.log(new ProgressLogRecord(Level.INFO, Util.status(progress, resultList.size()), progress.getTask(), progress.status()));
}
}
else {
for (QueryResult<DoubleDistance> nextSeed : seeds) {
Integer nextID = nextSeed.getID();
if (!processedIDs.contains(nextID)) {
currentCluster.add(nextID);
processedIDs.add(nextID);
}
else if (noise.contains(nextID)) {
currentCluster.add(nextID);
noise.remove(nextID);
}
if (isVerbose()) {
progress.setProcessed(processedIDs.size());
logger.log(new ProgressLogRecord(Level.INFO, Util.status(progress, resultList.size()), progress.getTask(), progress.status()));
}
}
seeds.remove(0);
processedIDs.add(startObjectID);
if (isVerbose()) {
progress.setProcessed(processedIDs.size());
logger.log(new ProgressLogRecord(Level.INFO, Util.status(progress, resultList.size()), progress.getTask(), progress.status()));
}
while (seeds.size() > 0) {
Integer seedID = seeds.remove(0).getID();
List<QueryResult<DoubleDistance>> seedNeighborhoodIDs = database.rangeQuery(seedID, epsilon, distanceFunction);
if (seedNeighborhoodIDs.size() >= minpts) {
if ((Integer) database.getAssociation(AssociationID.LOCAL_DIMENSIONALITY, seedID) <= lambda) {
List<QueryResult<DoubleDistance>> reachables = database.rangeQuery(seedID, epsilon, distanceFunction);
if (reachables.size() >= minpts) {
for (QueryResult<DoubleDistance> reachable : reachables) {
boolean inNoise = noise.contains(reachable.getID());
boolean unclassified = !processedIDs.contains(reachable.getID());
if (inNoise || unclassified) {
if (unclassified) {
seeds.add(reachable);
}
currentCluster.add(reachable.getID());
processedIDs.add(reachable.getID());
if (inNoise) {
noise.remove(reachable.getID());
}
if (isVerbose()) {
progress.setProcessed(processedIDs.size());
logger.log(new ProgressLogRecord(Level.INFO, Util.status(progress, resultList.size()), progress.getTask(), progress.status()));
}
}
}
}
}
}
}
if (currentCluster.size() >= minpts) {
resultList.add(currentCluster);
}
else {
for (Integer id : currentCluster) {
noise.add(id);
}
noise.add(startObjectID);
processedIDs.add(startObjectID);
}
if (isVerbose()) {
progress.setProcessed(processedIDs.size());
logger.log(new ProgressLogRecord(Level.INFO, Util.status(progress, resultList.size()), progress.getTask(), progress.status()));
}
}
}
}
}
/**
* @see de.lmu.ifi.dbs.utilities.optionhandling.Parameterizable#setParameters(String[])
*/
public String[] setParameters(String[] args) throws ParameterException {
String[] remainingParameters = super.setParameters(args);
epsilon = optionHandler.getOptionValue(EPSILON_P);
try {
// test whether epsilon is compatible with distance function
distanceFunction.valueOf(epsilon);
}
catch (IllegalArgumentException e) {
throw new WrongParameterValueException(EPSILON_P, epsilon, EPSILON_D);
}
// minpts
String minptsString = optionHandler.getOptionValue(MINPTS_P);
try {
minpts = Integer.parseInt(minptsString);
if (minpts <= 0) {
throw new WrongParameterValueException(MINPTS_P, minptsString, MINPTS_D);
}
}
catch (NumberFormatException e) {
throw new WrongParameterValueException(MINPTS_P, minptsString, MINPTS_D, e);
}
// lambda
String lambdaString = optionHandler.getOptionValue(LAMBDA_P);
try {
lambda = Integer.parseInt(lambdaString);
if (lambda <= 0) {
throw new WrongParameterValueException(LAMBDA_P, lambdaString, LAMBDA_D);
}
}
catch (NumberFormatException e) {
throw new WrongParameterValueException(LAMBDA_P, lambdaString, LAMBDA_D, e);
}
// delta
String deltaString;
if (optionHandler.isSet(ProjectedDBSCANPreprocessor.DELTA_P)) {
deltaString = optionHandler.getOptionValue(ProjectedDBSCANPreprocessor.DELTA_P);
}
else {
deltaString = Double.toString(ProjectedDBSCANPreprocessor.DEFAULT_DELTA);
}
// parameters for the distance function
List<String> distanceFunctionParameters = new ArrayList<String>();
// omit preprocessing flag
distanceFunctionParameters.add(OptionHandler.OPTION_PREFIX + LocallyWeightedDistanceFunction.OMIT_PREPROCESSING_F);
// big value for PCA
distanceFunctionParameters.add(OptionHandler.OPTION_PREFIX + AbstractLocalPCA.BIG_VALUE_P);
distanceFunctionParameters.add("50");
// small value for PCA
distanceFunctionParameters.add(OptionHandler.OPTION_PREFIX + AbstractLocalPCA.SMALL_VALUE_P);
distanceFunctionParameters.add("1");
// delta
distanceFunctionParameters.add(OptionHandler.OPTION_PREFIX + ProjectedDBSCANPreprocessor.DELTA_P);
distanceFunctionParameters.add(deltaString);
// preprocessor
distanceFunctionParameters.add(OptionHandler.OPTION_PREFIX + LocallyWeightedDistanceFunction.PREPROCESSOR_CLASS_P);
distanceFunctionParameters.add(preprocessorClass().getName());
// preprocessor epsilon
distanceFunctionParameters.add(OptionHandler.OPTION_PREFIX + ProjectedDBSCANPreprocessor.EPSILON_P);
distanceFunctionParameters.add(epsilon);
distanceFunction.setParameters(distanceFunctionParameters.toArray(new String[distanceFunctionParameters.size()]));
setParameters(args, remainingParameters);
return remainingParameters;
}
/**
* @see Algorithm#getAttributeSettings()
*/
@Override
public List<AttributeSettings> getAttributeSettings() {
List<AttributeSettings> attributeSettings = super.getAttributeSettings();
AttributeSettings mySettings = attributeSettings.get(0);
mySettings.addSetting(LAMBDA_P, Integer.toString(lambda));
mySettings.addSetting(EPSILON_P, epsilon);
mySettings.addSetting(MINPTS_P, Integer.toString(minpts));
attributeSettings.addAll(distanceFunction.getAttributeSettings());
return attributeSettings;
}
/**
* Returns the class actually used as
* {@link ProjectedDBSCANPreprocessor VarianceAnalysisPreprocessor}.
*
* @return the class actually used as
* {@link ProjectedDBSCANPreprocessor VarianceAnalysisPreprocessor}
*/
public abstract Class<P> preprocessorClass();
/**
* @see de.lmu.ifi.dbs.algorithm.Algorithm#getResult()
*/
public ClustersPlusNoise<RealVector> getResult() {
return result;
}
} |
package de.st_ddt.crazyspawner.entities;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.World;
import org.bukkit.command.CommandSender;
import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.entity.Ageable;
import org.bukkit.entity.Boat;
import org.bukkit.entity.Creature;
import org.bukkit.entity.Creeper;
import org.bukkit.entity.Enderman;
import org.bukkit.entity.Entity;
import org.bukkit.entity.EntityType;
import org.bukkit.entity.ExperienceOrb;
import org.bukkit.entity.Explosive;
import org.bukkit.entity.FallingBlock;
import org.bukkit.entity.Firework;
import org.bukkit.entity.Horse;
import org.bukkit.entity.IronGolem;
import org.bukkit.entity.Item;
import org.bukkit.entity.LightningStrike;
import org.bukkit.entity.LivingEntity;
import org.bukkit.entity.Ocelot;
import org.bukkit.entity.Pig;
import org.bukkit.entity.PigZombie;
import org.bukkit.entity.Sheep;
import org.bukkit.entity.Skeleton;
import org.bukkit.entity.Slime;
import org.bukkit.entity.Tameable;
import org.bukkit.entity.Villager;
import org.bukkit.entity.Wolf;
import org.bukkit.entity.Zombie;
import org.bukkit.inventory.ItemStack;
import org.bukkit.material.Colorable;
import org.bukkit.metadata.MetadataValue;
import de.st_ddt.crazyplugin.exceptions.CrazyException;
import de.st_ddt.crazyspawner.CrazySpawner;
import de.st_ddt.crazyspawner.entities.properties.AgeProperty;
import de.st_ddt.crazyspawner.entities.properties.AlarmProperty;
import de.st_ddt.crazyspawner.entities.properties.BoatProperty;
import de.st_ddt.crazyspawner.entities.properties.BurningProperty;
import de.st_ddt.crazyspawner.entities.properties.ColorableProperty;
import de.st_ddt.crazyspawner.entities.properties.CreeperProperty;
import de.st_ddt.crazyspawner.entities.properties.DamageProperty;
import de.st_ddt.crazyspawner.entities.properties.DespawnProperty;
import de.st_ddt.crazyspawner.entities.properties.DetectionProperty;
import de.st_ddt.crazyspawner.entities.properties.DroppedItemProperty;
import de.st_ddt.crazyspawner.entities.properties.EndermanProperty;
import de.st_ddt.crazyspawner.entities.properties.EntityPropertyInterface;
import de.st_ddt.crazyspawner.entities.properties.EquipmentProperties;
import de.st_ddt.crazyspawner.entities.properties.ExperienceOrbProperty;
import de.st_ddt.crazyspawner.entities.properties.ExplosiveProperty;
import de.st_ddt.crazyspawner.entities.properties.FallingBlockProperties;
import de.st_ddt.crazyspawner.entities.properties.FireworkProperty;
import de.st_ddt.crazyspawner.entities.properties.HealthProperty;
import de.st_ddt.crazyspawner.entities.properties.HorseProperty;
import de.st_ddt.crazyspawner.entities.properties.InvulnerableProperty;
import de.st_ddt.crazyspawner.entities.properties.IronGolemProperty;
import de.st_ddt.crazyspawner.entities.properties.LightningProperty;
import de.st_ddt.crazyspawner.entities.properties.LivingDespawnProperty;
import de.st_ddt.crazyspawner.entities.properties.NameProperty;
import de.st_ddt.crazyspawner.entities.properties.OcelotProperty;
import de.st_ddt.crazyspawner.entities.properties.PassengerProperty;
import de.st_ddt.crazyspawner.entities.properties.PeacefulProperty;
import de.st_ddt.crazyspawner.entities.properties.PigProperty;
import de.st_ddt.crazyspawner.entities.properties.PigZombieProperty;
import de.st_ddt.crazyspawner.entities.properties.PotionProterty;
import de.st_ddt.crazyspawner.entities.properties.SheepProperty;
import de.st_ddt.crazyspawner.entities.properties.SkeletonProperty;
import de.st_ddt.crazyspawner.entities.properties.SlimeProperty;
import de.st_ddt.crazyspawner.entities.properties.TameableProperty;
import de.st_ddt.crazyspawner.entities.properties.VelocityProperty;
import de.st_ddt.crazyspawner.entities.properties.VillagerProperty;
import de.st_ddt.crazyspawner.entities.properties.WolfProperty;
import de.st_ddt.crazyspawner.entities.properties.XPProperty;
import de.st_ddt.crazyspawner.entities.properties.ZombieProperty;
import de.st_ddt.crazyutil.ChatHelper;
import de.st_ddt.crazyutil.ConfigurationSaveable;
import de.st_ddt.crazyutil.EntitySpawner;
import de.st_ddt.crazyutil.NamedEntitySpawner;
import de.st_ddt.crazyutil.VersionComparator;
import de.st_ddt.crazyutil.paramitrisable.NamedEntitySpawnerParamitrisable;
import de.st_ddt.crazyutil.paramitrisable.Paramitrisable;
import de.st_ddt.crazyutil.paramitrisable.StringParamitrisable;
import de.st_ddt.crazyutil.paramitrisable.TabbedParamitrisable;
import de.st_ddt.crazyutil.source.Localized;
public class CustomEntitySpawner implements NamedEntitySpawner, MetadataValue, ConfigurationSaveable
{
public final static String METAHEADER = "CustomEntityMeta";
protected final static boolean v146OrLater = VersionComparator.compareVersions(ChatHelper.getMinecraftVersion(), "1.4.6") >= 0;
protected final static boolean v150OrLater = VersionComparator.compareVersions(ChatHelper.getMinecraftVersion(), "1.5.0") >= 0;
protected final static boolean v161OrLater = VersionComparator.compareVersions(ChatHelper.getMinecraftVersion(), "1.6.1") >= 0;
protected final static boolean v162OrLater = VersionComparator.compareVersions(ChatHelper.getMinecraftVersion(), "1.6.2") >= 0;
protected final static EntitySpawner[] ENTITYSPAWNER = new EntitySpawner[EntityType.values().length];
@SuppressWarnings("unchecked")
protected final static Set<Class<? extends EntityPropertyInterface>>[] ENTITYPROPERTIES = new Set[EntityType.values().length];
static
{
// Spawner - Default
for (final EntityType type : EntityType.values())
if (type.isSpawnable())
registerEntitySpawner(new DefaultSpawner(type));
// Spawner - Fixes
registerEntitySpawner(new CenteredSpawner(EntityType.ENDER_CRYSTAL)
{
@Override
public Entity spawn(final Location location)
{
final Entity entity = super.spawn(location);
location.clone().add(0, 1, 0).getBlock().setType(Material.FIRE);
location.getBlock().setType(Material.BEDROCK);
return entity;
}
});
registerEntitySpawner(new BasicSpawner(EntityType.DROPPED_ITEM)
{
private final ItemStack item = new ItemStack(1);
@Override
public Entity spawn(final Location location)
{
return location.getWorld().dropItem(location, item);
}
});
registerEntitySpawner(new ClassSpawner(EntityType.FIREWORK));
registerEntitySpawner(new FallingBlockSpawner());
registerEntitySpawner(new LightningSpawner());
// Add Spawners to NamedEntitySpawnerParamitrisable
for (final EntitySpawner spawner : ENTITYSPAWNER)
if (spawner != null)
if (spawner instanceof NamedEntitySpawner)
NamedEntitySpawnerParamitrisable.registerNamedEntitySpawner((NamedEntitySpawner) spawner, spawner.getType().name(), spawner.getType().getName());
// Properties
for (final EntityType type : EntityType.values())
ENTITYPROPERTIES[type.ordinal()] = new LinkedHashSet<Class<? extends EntityPropertyInterface>>();
// Properties - VIP required to be first!
registerEntityProperty(FallingBlockProperties.class, FallingBlock.class);
registerEntityProperty(LightningProperty.class, LightningStrike.class);
// Properties - Sorted by EntityInterfaces
registerEntityProperty(AgeProperty.class, Ageable.class);
registerEntityProperty(BoatProperty.class, Boat.class);
registerEntityProperty(ColorableProperty.class, Colorable.class);
registerEntityProperty(AlarmProperty.class, Creature.class);
registerEntityProperty(DetectionProperty.class, Creature.class);
registerEntityProperty(CreeperProperty.class, Creeper.class);
if (v146OrLater)
registerEntityProperty(HealthProperty.class, LivingEntity.class);
registerEntityProperty(EndermanProperty.class, Enderman.class);
registerEntityProperty(DespawnProperty.class, Entity.class, LivingEntity.class);
registerEntityProperty(BurningProperty.class, Entity.class);
registerEntityProperty(InvulnerableProperty.class, Entity.class);
registerEntityProperty(VelocityProperty.class, Entity.class);
registerEntityProperty(PassengerProperty.class, Entity.class);
registerEntityProperty(PeacefulProperty.class, Entity.class);
registerEntityProperty(ExperienceOrbProperty.class, ExperienceOrb.class);
registerEntityProperty(ExplosiveProperty.class, Explosive.class);
// Fireball required?
registerEntityProperty(FireworkProperty.class, Firework.class);
// Hanging required?
if (v162OrLater)
registerEntityProperty(HorseProperty.class, Horse.class);
// InventoryHolder required?
registerEntityProperty(IronGolemProperty.class, IronGolem.class);
registerEntityProperty(AlarmProperty.class, Item.class);
registerEntityProperty(DroppedItemProperty.class, Item.class);
// ItemFrame required?
registerEntityProperty(DamageProperty.class, LivingEntity.class);
registerEntityProperty(LivingDespawnProperty.class, LivingEntity.class);
registerEntityProperty(EquipmentProperties.class, LivingEntity.class);
if (v150OrLater)
registerEntityProperty(NameProperty.class, LivingEntity.class);
registerEntityProperty(PotionProterty.class, LivingEntity.class);
registerEntityProperty(XPProperty.class, LivingEntity.class);
// Minecard required?
registerEntityProperty(OcelotProperty.class, Ocelot.class);
// Painting required?
registerEntityProperty(PigProperty.class, Pig.class);
registerEntityProperty(PigZombieProperty.class, PigZombie.class);
// Projectile required?
registerEntityProperty(SheepProperty.class, Sheep.class);
registerEntityProperty(SkeletonProperty.class, Skeleton.class);
registerEntityProperty(SlimeProperty.class, Slime.class);
registerEntityProperty(TameableProperty.class, Tameable.class);
// TNTPrimed impossible?
registerEntityProperty(VillagerProperty.class, Villager.class);
registerEntityProperty(WolfProperty.class, Wolf.class);
registerEntityProperty(ZombieProperty.class, Zombie.class);
}
public static void registerEntitySpawner(final EntitySpawner spawner)
{
ENTITYSPAWNER[spawner.getType().ordinal()] = spawner;
}
public static Set<EntityType> getSpawnableEntityTypes()
{
final Set<EntityType> res = new HashSet<EntityType>();
for (final EntityType type : EntityType.values())
if (ENTITYSPAWNER[type.ordinal()] != null)
res.add(type);
return res;
}
public static void registerEntityProperty(final Class<? extends EntityPropertyInterface> propertyClass, final Class<?> targetClass)
{
for (final EntityType type : EntityType.values())
if (type.getEntityClass() != null && targetClass.isAssignableFrom(type.getEntityClass()))
ENTITYPROPERTIES[type.ordinal()].add(propertyClass);
}
public static void registerEntityProperty(final Class<? extends EntityPropertyInterface> propertyClass, final Class<?> targetClass, final Class<?>... ignoredClasses)
{
for (final EntityType type : EntityType.values())
if (type.getEntityClass() != null && targetClass.isAssignableFrom(type.getEntityClass()))
{
for (final Class<?> ignoredClass : ignoredClasses)
if (ignoredClass.isAssignableFrom(type.getEntityClass()))
return;
ENTITYPROPERTIES[type.ordinal()].add(propertyClass);
}
}
protected static List<EntityPropertyInterface> getDefaultEntityProperties(final EntityType type)
{
final Set<Class<? extends EntityPropertyInterface>> properties = ENTITYPROPERTIES[type.ordinal()];
final List<EntityPropertyInterface> res = new ArrayList<EntityPropertyInterface>(properties.size());
for (final Class<? extends EntityPropertyInterface> property : properties)
try
{
res.add(property.newInstance());
}
catch (final Exception e)
{
System.err.println("WARNING: Serious Bug detected, please report this!");
System.err.println("EntityType: " + type.name() + ", Property: " + property.getSimpleName());
e.printStackTrace();
}
return res;
}
protected static List<EntityPropertyInterface> getEntityPropertiesFromConfig(final EntityType type, final ConfigurationSection config)
{
final Set<Class<? extends EntityPropertyInterface>> properties = ENTITYPROPERTIES[type.ordinal()];
final List<EntityPropertyInterface> res = new ArrayList<EntityPropertyInterface>(properties.size());
for (final Class<? extends EntityPropertyInterface> property : properties)
try
{
res.add(property.getConstructor(ConfigurationSection.class).newInstance(config));
}
catch (final Exception e)
{
System.err.println("WARNING: Serious Bug detected, please report this!");
System.err.println("EntityType: " + type.name() + ", Property: " + property.getSimpleName());
e.printStackTrace();
}
return res;
}
protected static List<EntityPropertyInterface> getEntityPropertiesFromParams(final EntityType type, final Map<String, ? extends Paramitrisable> params)
{
final Set<Class<? extends EntityPropertyInterface>> properties = ENTITYPROPERTIES[type.ordinal()];
final List<EntityPropertyInterface> res = new ArrayList<EntityPropertyInterface>(properties.size());
for (final Class<? extends EntityPropertyInterface> property : properties)
try
{
res.add(property.getConstructor(Map.class).newInstance(params));
}
catch (final Exception e)
{
System.err.println("WARNING: Serious Bug detected, please report this!");
System.err.println("EntityType: " + type.name() + ", Property: " + property.getSimpleName());
e.printStackTrace();
}
return res;
}
public static StringParamitrisable getCommandParams(final EntityType type, final Map<String, ? super TabbedParamitrisable> params, final CommandSender sender)
{
final StringParamitrisable nameParam = new StringParamitrisable(null);
params.put("n", nameParam);
params.put("name", nameParam);
for (final EntityPropertyInterface property : getDefaultEntityProperties(type))
property.getCommandParams(params, sender);
return nameParam;
}
protected final String name;
protected final EntityType type;
protected final List<EntityPropertyInterface> properties;
public CustomEntitySpawner(final EntityType type)
{
this(type.getName(), type);
}
public CustomEntitySpawner(final String name, final EntityType type)
{
super();
if (name == null)
throw new IllegalArgumentException("Name cannot be null!");
if (name.length() == 0)
throw new IllegalArgumentException("Name cannot be empty!");
this.name = name.toUpperCase();
if (type == null)
throw new IllegalArgumentException("Type cannot be null!");
this.type = type;
this.properties = getDefaultEntityProperties(type);
}
public CustomEntitySpawner(final ConfigurationSection config)
{
super();
if (config == null)
throw new IllegalArgumentException("Config cannot be null!");
this.name = config.getString("name", "UNNAMED").toUpperCase();
final String typeName = config.getString("type", null);
if (typeName == null)
throw new IllegalArgumentException("Type cannot be null!");
this.type = EntityType.valueOf(typeName.toUpperCase());
if (type == null)
throw new IllegalArgumentException("Type cannot be null!");
this.properties = getEntityPropertiesFromConfig(type, config);
}
public CustomEntitySpawner(final EntityType type, final Map<String, ? extends Paramitrisable> params)
{
super();
final StringParamitrisable nameParam = (StringParamitrisable) params.get("name");
this.name = nameParam.getValue().toUpperCase();
if (type == null)
throw new IllegalArgumentException("EntityType cannot be null!");
this.type = type;
this.properties = getEntityPropertiesFromParams(type, params);
}
/**
* Creates a CustomEntitySpawner from args.<br>
* This is a helper method for default custom entities.
*
* @param name
* The name of the custom entity.
* @param type
* The entity type of this spawner.
* @param sender
* The CommandSender how creates this object.
* @param args
* The params to create this object.
*/
public CustomEntitySpawner(final String name, final EntityType type, final CommandSender sender, final String... args)
{
super();
this.name = name;
if (type == null)
throw new IllegalArgumentException("Type cannot be null!");
this.type = type;
final Map<String, Paramitrisable> params = new HashMap<String, Paramitrisable>();
getCommandParams(type, params, sender);
for (final String arg : args)
{
final String[] split = arg.split(":", 2);
final Paramitrisable param = params.get(split[0]);
if (param != null)
try
{
param.setParameter(split[1]);
}
catch (final CrazyException e)
{
e.printStackTrace();
}
}
this.properties = getEntityPropertiesFromParams(type, params);
}
@Override
public final String getName()
{
return name;
}
@Override
public final EntityType getType()
{
return type;
}
@Override
public final Class<? extends Entity> getEntityClass()
{
return type.getEntityClass();
}
protected EntitySpawner getSpawner()
{
if (!properties.isEmpty())
{
final EntityPropertyInterface property = properties.get(0);
if (property instanceof EntitySpawner)
return (EntitySpawner) property;
}
return ENTITYSPAWNER[type.ordinal()];
}
public final boolean isSpawnable()
{
return getSpawner() != null;
}
@Override
public final Entity spawn(final Location location)
{
final EntitySpawner spawner = getSpawner();
if (spawner == null)
return null;
final Entity entity = spawner.spawn(location);
if (entity == null)
return null;
entity.setMetadata(METAHEADER, this);
apply(entity);
return entity;
}
@Localized({ "CRAZYSPAWNER.ENTITY.PROPERTY.NAME $Name$", "CRAZYSPAWNER.ENTITY.PROPERTY.TYPE $EntityType$" })
public void show(final CommandSender target)
{
CrazySpawner.getPlugin().sendLocaleMessage("ENTITY.PROPERTY.NAME", target, name);
CrazySpawner.getPlugin().sendLocaleMessage("ENTITY.PROPERTY.TYPE", target, type.name());
for (final EntityPropertyInterface property : properties)
property.show(target);
}
/**
* Apply all features to the given entity.<br>
* EntityType of this Spawner must match the EntityType of the given entity.
*
* @param entity
* The entity the properties should be applied to.
*/
public final void apply(final Entity entity)
{
for (final EntityPropertyInterface property : properties)
property.apply(entity);
}
@Override
public Collection<? extends Entity> getEntities(final World world)
{
// EDIT include entity properties or check meta
return world.getEntitiesByClass(type.getEntityClass());
}
public final StringParamitrisable getCommandParams(final Map<String, ? super TabbedParamitrisable> params, final CommandSender sender)
{
final StringParamitrisable nameParam = new StringParamitrisable(name);
params.put("n", nameParam);
params.put("name", nameParam);
for (final EntityPropertyInterface property : properties)
property.getCommandParams(params, sender);
return nameParam;
}
public final void addEntityProperty(final EntityPropertyInterface property)
{
if (property == null)
return;
for (int i = 0; i < properties.size(); i++)
if (properties.get(i).getClass().getName().equals(property.getClass().getName()))
{
properties.set(i, property);
return;
}
properties.add(property);
}
@Override
public void save(final ConfigurationSection config, final String path)
{
config.set(path + "name", name.toUpperCase());
config.set(path + "type", type.name());
for (final EntityPropertyInterface property : properties)
property.save(config, path);
}
public void dummySave(final ConfigurationSection config, final String path)
{
config.set(path + "name", "String");
config.set(path + "type", "EntityType");
for (final EntityPropertyInterface property : properties)
property.dummySave(config, path);
}
private abstract static class BasicSpawner implements NamedEntitySpawner
{
protected final EntityType type;
public BasicSpawner(final EntityType type)
{
this.type = type;
}
@Override
public final EntityType getType()
{
return type;
}
@Override
public String getName()
{
return type.getName();
}
@Override
public final Class<? extends Entity> getEntityClass()
{
return type.getEntityClass();
}
@Override
public abstract Entity spawn(Location location);
@Override
public Collection<? extends Entity> getEntities(final World world)
{
return world.getEntitiesByClass(type.getEntityClass());
}
}
private static class DefaultSpawner extends BasicSpawner
{
public DefaultSpawner(final EntityType type)
{
super(type);
}
@Override
public Entity spawn(final Location location)
{
return location.getWorld().spawnEntity(location, type);
}
}
private static class CenteredSpawner extends DefaultSpawner
{
public CenteredSpawner(final EntityType type)
{
super(type);
}
@Override
public Entity spawn(final Location location)
{
location.setX(Math.floor(location.getX()) + 0.5);
location.setY(Math.floor(location.getY()));
location.setZ(Math.floor(location.getZ()) + 0.5);
location.setYaw(0);
location.setPitch(0);
return super.spawn(location);
}
}
private static class ClassSpawner extends DefaultSpawner
{
public ClassSpawner(final EntityType type)
{
super(type);
}
@Override
public Entity spawn(final Location location)
{
try
{
return location.getWorld().spawn(location, type.getEntityClass());
}
catch (final Exception e)
{
e.printStackTrace();
return null;
}
}
}
public static class FallingBlockSpawner extends DefaultSpawner
{
protected final Material material;
protected final byte data;
public FallingBlockSpawner()
{
super(EntityType.FALLING_BLOCK);
this.material = Material.STONE;
this.data = 0;
}
public FallingBlockSpawner(final Material material, final byte data)
{
super(EntityType.FALLING_BLOCK);
if (material == null)
throw new IllegalArgumentException("Material cannot be null!");
this.material = material;
this.data = data;
}
@Override
public final FallingBlock spawn(final Location location)
{
try
{
return location.getWorld().spawnFallingBlock(location, material, data);
}
catch (final Exception e)
{
e.printStackTrace();
return null;
}
}
@Override
public final Collection<FallingBlock> getEntities(final World world)
{
final Collection<FallingBlock> entities = world.getEntitiesByClass(FallingBlock.class);
final Iterator<FallingBlock> it = entities.iterator();
while (it.hasNext())
if (it.next().getMaterial() != material)
it.remove();
return entities;
}
}
public static class LightningSpawner extends DefaultSpawner
{
protected final boolean effect;
public LightningSpawner()
{
super(EntityType.LIGHTNING);
this.effect = false;
}
public LightningSpawner(final boolean effect)
{
super(EntityType.LIGHTNING);
this.effect = effect;
}
@Override
public final String getName()
{
return "LIGHTNINGSTRIKE";
}
@Override
public final LightningStrike spawn(final Location location)
{
if (effect)
return location.getWorld().strikeLightningEffect(location);
else
return location.getWorld().strikeLightning(location);
}
@Override
public final Collection<LightningStrike> getEntities(final World world)
{
final Collection<LightningStrike> entities = world.getEntitiesByClass(LightningStrike.class);
final Iterator<LightningStrike> it = entities.iterator();
while (it.hasNext())
if (it.next().isEffect() != effect)
it.remove();
return entities;
}
}
@Override
public boolean equals(final Object obj)
{
if (obj instanceof CustomEntitySpawner)
return name.equals(((CustomEntitySpawner) obj).name);
else
return false;
}
@Override
public int hashCode()
{
return name.hashCode();
}
@Override
public final CustomEntitySpawner value()
{
return this;
}
@Override
public final int asInt()
{
return 0;
}
@Override
public final float asFloat()
{
return 0;
}
@Override
public final double asDouble()
{
return 0;
}
@Override
public final long asLong()
{
return 0;
}
@Override
public final short asShort()
{
return 0;
}
@Override
public final byte asByte()
{
return 0;
}
@Override
public final boolean asBoolean()
{
return false;
}
@Override
public final String asString()
{
return toString();
}
@Override
public final CrazySpawner getOwningPlugin()
{
return CrazySpawner.getPlugin();
}
@Override
public final void invalidate()
{
}
} |
package gw.lang;
import gw.config.CommonServices;
import gw.lang.cli.CommandLineAccess;
import gw.lang.init.ClasspathToGosuPathEntryUtil;
import gw.lang.init.GosuInitialization;
import gw.lang.parser.GosuParserFactory;
import gw.lang.parser.IFileContext;
import gw.lang.parser.IGosuProgramParser;
import gw.lang.parser.IParseResult;
import gw.lang.parser.ParserOptions;
import gw.lang.parser.StandardSymbolTable;
import gw.lang.parser.exceptions.ParseResultsException;
import gw.lang.reflect.IType;
import gw.lang.reflect.TypeSystem;
import gw.lang.reflect.gs.IGosuProgram;
import gw.lang.reflect.java.JavaTypes;
import gw.util.OSPlatform;
import gw.util.StreamUtil;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.Reader;
import java.lang.reflect.Method;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.StringTokenizer;
public class Gosu
{
private static List<File> _classpath;
public static void main( String[] args )
{
new Gosu().start( args );
}
private int start( String[] args )
{
try
{
int ret;
if( args.length == 0 )
{
showHelpAndQuit();
}
int i = 0;
String cpValue = null;
boolean cmdLineCP = args[0].equals( "-classpath" );
if(cmdLineCP)
{
i = 2;
if(i >= args.length)
{
showHelpAndQuit();
}
cpValue = args[1];
}
if(args[i].equals( "-e" )) {
List<File> classpath = makeClasspath( cpValue, "", cmdLineCP );
init(classpath);
ret = runWithInlineScript(args[i+1], collectArgs(i+2, args));
}
else
{
File script = new File( args[i] );
if( !script.isFile() || !script.exists() )
{
showHelpAndQuit();
}
if ( cpValue == null ) {
cpValue = extractClassPathFromSrc( script.getAbsolutePath() );
}
List<File> classpath = makeClasspath( cpValue, script.getParent(), cmdLineCP );
init(classpath);
ret = runWithFile(script, collectArgs(i+1, args));
}
return ret;
}
catch( Throwable t )
{
t.printStackTrace( System.err );
return 2;
}
}
private List<String> collectArgs(int i, String[] args) {
List<String> scriptArgs = new ArrayList<String>();
while( i < args.length )
{
scriptArgs.add( args[i] );
i++;
}
return scriptArgs;
}
private String extractClassPathFromSrc(String file) {
BufferedReader br = null;
String line;
String ret = null;
try
{
br = new BufferedReader( new FileReader(file) );
while ( (line = br.readLine()).trim().isEmpty() ); //ignore
if (line.startsWith("classpath"))
{
int b = line.indexOf('"');
if (b != -1)
{
int e = line.indexOf('"', b+1);
if (e != -1)
{
ret = line.substring(b + 1, e);
}
}
}
} catch (IOException e) {} //ignore
finally
{
try
{
if (br != null)
br.close();
} catch (IOException ex) {} //ignore
}
return ret;
}
private static List<File> makeClasspath(String cpValue, String scriptRoot, boolean cmdLineCP)
{
ArrayList<File> cp = new ArrayList<File>();
if ( cpValue != null ) {
StringTokenizer st = new StringTokenizer( cpValue, ",", false );
while( st.hasMoreTokens() )
{
String s = st.nextToken();
if( ( s.contains( ":" ) && !OSPlatform.isWindows()) || s.contains( ";" ) )
{
System.err.println( "WARNING: The Gosu classpath argument should be comma separated to avoid system dependencies.\n" +
"It appears you are passing in a system-dependent path delimiter" );
}
String pathname = cmdLineCP ? s : scriptRoot + File.separatorChar + s;
cp.add(new File(pathname));
}
}
return cp;
}
// Note this is a giant hack, we need to instead get the type name from the psiClass
private static String makeFqn( File file )
{
String path = file.getAbsolutePath();
int srcIndex = path.indexOf( "src" + File.separatorChar );
if (srcIndex >= 0) {
String fqn = path.substring(srcIndex + 4).replace(File.separatorChar, '.');
return fqn.substring(0, fqn.lastIndexOf('.'));
} else { // the Gosu Scratchpad case
String fqn = file.getName();
fqn = "nopackage." + fqn.substring(0, fqn.lastIndexOf('.')).replace(" ", "");
return fqn;
}
}
public static void setClasspath( List<File> classpath )
{
removeDups( classpath );
if( classpath.equals( _classpath ) )
{
return;
}
_classpath = classpath;
ClassLoader loader = TypeSystem.getCurrentModule() == null
// Can be null if called before the exec environment is setup, so assume the future parent of the module loader is the plugin loader
? CommonServices.getEntityAccess().getPluginClassLoader()
: TypeSystem.getGosuClassLoader().getActualLoader();
if( loader instanceof URLClassLoader )
{
for( File entry : classpath )
{
try
{
Method addURL = URLClassLoader.class.getDeclaredMethod( "addURL", URL.class );
addURL.setAccessible( true );
addURL.invoke( loader, entry.toURI().toURL() );
}
catch( Exception e )
{
throw new RuntimeException( e );
}
}
}
reinitGosu( classpath );
TypeSystem.refresh( true );
}
private static void reinitGosu( List<File> classpath )
{
try
{
GosuInitialization.instance( TypeSystem.getExecutionEnvironment() ).reinitializeRuntime( ClasspathToGosuPathEntryUtil.convertClasspathToGosuPathEntries( classpath ) );
}
catch( Exception e )
{
e.printStackTrace();
}
}
private static void removeDups( List<File> classpath )
{
for( int i = classpath.size()-1; i >= 0; i
{
File f = classpath.get( i );
classpath.remove( i );
if( !classpath.contains( f ) )
{
classpath.add( i, f );
}
}
}
/**
* Initializes Gosu using the classpath derived from the current classloader and system classpath.
*/
public static void init()
{
init( null );
}
public static void init( List<File> classpath )
{
List<File> combined = new ArrayList<File>();
combined.addAll( deriveClasspathFrom( Gosu.class ) );
if( classpath != null )
{
combined.addAll( classpath );
}
setClasspath(combined);
}
public static boolean bootstrapGosuWhenInitiatedViaClassfile()
{
if( GosuInitialization.isAnythingInitialized() &&
GosuInitialization.instance( TypeSystem.getExecutionEnvironment() ).isInitialized() )
{
return false;
}
init();
return true;
}
static void showHelpAndQuit()
{
System.out.println("Gosu version: " + getVersion() +
"\nUsage:\n" +
" gosu [-classpath 'entry1,entry2...'] program.gsp [args...]\n" +
" gosu [-classpath 'entry1,entry2...'] -e 'inline script' [args...]\n");
System.exit(1);
}
public static List<File> deriveClasspathFrom( Class clazz )
{
List<File> ll = new LinkedList<File>();
ClassLoader loader = clazz.getClassLoader();
while( loader != null )
{
if( loader instanceof URLClassLoader )
{
for( URL url : ((URLClassLoader)loader).getURLs() )
{
try
{
File file = new File( url.toURI() );
if( file.exists() )
{
ll.add( file );
}
}
catch( Exception e )
{
//ignore
}
}
}
loader = loader.getParent();
}
return ll;
}
public static GosuVersion getVersion()
{
InputStream in = Gosu.class.getClassLoader().getResourceAsStream(GosuVersion.RESOURCE_PATH);
Reader reader = StreamUtil.getInputStreamReader(in);
return GosuVersion.parse(reader);
}
private int runWithFile(File script, List<String> args) throws IOException, ParseResultsException
{
CommandLineAccess.setCurrentProgram(script);
// set remaining arguments as arguments to the Gosu program
CommandLineAccess.setRawArgs( args );
byte[] bytes = StreamUtil.getContent( new BufferedInputStream(new FileInputStream(script)));
String content = StreamUtil.toString( bytes );
IFileContext ctx = null;
ctx = new ProgramFileContext( script, makeFqn( script ) );
IGosuProgramParser programParser = GosuParserFactory.createProgramParser();
ParserOptions options = new ParserOptions().withFileContext( ctx );
IParseResult result = programParser.parseExpressionOrProgram( content, new StandardSymbolTable( true ), options );
IGosuProgram program = result.getProgram();
Object ret = program.getProgramInstance().evaluate(null); // evaluate it
IType expressionType = result.getType();
if( expressionType != null && !JavaTypes.pVOID().equals(expressionType) )
{
GosuShop.print( ret );
}
return 0;
}
private int runWithInlineScript(String script, List<String> args) throws IOException, ParseResultsException
{
CommandLineAccess.setCurrentProgram(null);
// set remaining arguments as arguments to the Gosu program
CommandLineAccess.setRawArgs( args );
IGosuProgramParser programParser = GosuParserFactory.createProgramParser();
IParseResult result = programParser.parseExpressionOrProgram( script, new StandardSymbolTable( true ), new ParserOptions() );
IGosuProgram program = result.getProgram();
Object ret = program.getProgramInstance().evaluate(null); // evaluate it
IType expressionType = result.getType();
if( expressionType != null && !JavaTypes.pVOID().equals(expressionType) )
{
GosuShop.print( ret );
}
return 0;
}
} |
package grok.core;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonValue;
import com.google.auto.value.AutoValue;
@AutoValue
public abstract class Id {
@JsonCreator
public static Id of(String id) {
return new AutoValue_Id(id);
}
/**
* Use {@link #of(String)} instead. This is here for Jersey deserialization.
*/
@Deprecated
public static Id valueOf(String id) {
return of(id);
}
Id() {}
@Deprecated
public String id() {
return value();
}
@JsonValue
public abstract String value();
@Override
public String toString() {
return value();
}
} |
package yaplstack;
import yaplstack.ast.AST;
import yaplstack.ast.Generator;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.io.PrintStream;
import static yaplstack.ast.AST.Factory.*;
public class Main {
public static void main(String[] args) throws NoSuchMethodException, NoSuchFieldException {
/*
What primivites are necessary to simulate tradition fn calls?
// Three registers:
// Operand frame
// Call frame
// Current environment
// Store all registers:
// [..., operand frame, visitApply frame, environment]
// storeEnvironment
// [..., operand frame, visitApply frame]
// storeCallFrame
// [..., operand frame]
// storeOperandFrame
// [...']
*/
/*
Create reader:
{
inputStream = ...
atEnd() => inputStream.available() <= 0;
next() => inputStream.read();
}
*/
// push nth element in stack
/*
{
var currentChar = null;
peek = function() {
return currentChar;
}
consume = function() {
if(inputStream.hasMore())
currentChar = inputStream.nextChar();
else
currentChar = '\0';
}
nextToken = function() {
ignore();
if(Character.isDigit(peek())) {
StringBuilder digits = new StringBuilder();
digits.append(peek());
consume();
while(Character.isDigit(peek())) {
StringBuilder digits = new StringBuilder();
digits.append(peek());
consume();
return {
type = "Integer";
value = Integer.parseInt(digits.toString());
};
}
} else if(peek() == '(') {
return {
type = "OpenPar";
};
} else if(peek() == ')') {
return {
type = "ClosePar";
};
}
return null;
}
}
or:
tokens = function(inputStream) {
var currentChar = null;
peek = function() {
return currentChar;
}
consume = function() {
if(inputStream.hasMore())
currentChar = inputStream.nextChar();
else
currentChar = '\0';
}
ignore = ...
ignore();
while(inputStream.hasMore()) {
if(Character.isDigit(peek())) {
StringBuilder digits = new StringBuilder();
digits.append(peek());
consume();
while(Character.isDigit(peek())) {
StringBuilder digits = new StringBuilder();
digits.append(peek());
consume();
return {
type = "Integer";
value = Integer.parseInt(digits.toString());
};
}
} else if(peek() == '(') {
yield {
type = "OpenPar";
};
} else if(peek() == ')') {
return {
type = "ClosePar";
};
}
}
}
defun threeNumbers(m) {
m.yield(1);
m.yield(2);
m.yield(3);
}
defun generate(producer) {
{
var producer = producer;
var hasNext = false;
var atEnd = () -> {!hasNext};
var next = () -> {
var res = current;
hasNext = false;
yielder.returnFrame = frame;
resume(yielder.yieldFrame, nil);
return res;
};
var yielder = producer({
var returnFrame = nil;
var yieldFrame = nil;
yield = value -> {
hasNext = true;
current = value;
yieldFrame = frame;
resume(returnFrame, nil);
}
};
yielder.returnFrame = frame;
var current;
() -> {
producer(yielder);
resume(yielder.returnFrame, nil);
}()
}
}
var generator1 = generate(threeNumbers);
while(!generator1.atEnd()) {
println(generator1.next());
}
*/
/*AST program = program(block(
local("y", literal(9)),
local("obj",
object(block(
local("outer", env()),
local("x", literal(7)),
defun("getY", load(load("outer"), "y")),
local("yCopy", load("y"))
))
),
local("y", literal(19)),
//send(load("obj"), "getY")
load("obj")
));*/
AST program = program(block(
defun("println", new String[]{"str"},
invoke(fieldGet(System.class.getField("out")), PrintStream.class.getMethod("println", String.class), invoke(load("str"), Object.class.getMethod("toString")))
),
defun("numbers", new String[]{"m"}, block(
local("i", literal(0)),
loop(lti(load("i"), literal(100)), block(
send(load("m"), "yield", load("i")),
store("i", addi(load("i"), literal(1)))
))
)),
/*defun("generate", new String[]{"producer"}, object(block(
local("producer", load("producer")),
local("hasNext", literal(false)),
defun("atEnd", not(load("hasNext"))),
defun("next", block(
local("res", load("current")),
store("hasNext", literal(false)),
store(load("yielder"), "returnFrame", frame),
//bp,
resume(load(load("yielder"), "yieldFrame"), literal(null)),
load("res")
)),
local("yielder", object(block(
local("outer", env()),
local("returnFrame", literal(false)),
local("yieldFrame", literal(false)),
defun("yield", new String[]{"value"}, block(
store(load("outer"), "hasNext", literal(true)),
store(load("outer"), "current", load("value")),
store("yieldFrame", frame),
//bp,
resume(load("returnFrame"), literal(null))
))
))),
local("current", literal(false)),
local(load("yielder"), "returnFrame", frame),
apply(fn(block(
call("producer", load("yielder")),
resume(load(load("yielder"), "returnFrame"), literal(null))
)))
))),*/
/*defun("generate", new String[]{"producer"}, block(
local("generator", object(block(
local("producer", load("producer")),
local("hasNext", literal(false)),
defun("atEnd", not(load("hasNext"))),
defun("next", block(
local("res", load("current")),
store("hasNext", literal(false)),
store(load("yielder"), "returnFrame", frame),
//bp,
resume(load(load("yielder"), "yieldFrame"), literal(null)),
load("res")
)),
local("yielder", object(block(
local("returnFrame", literal(false)),
local("yieldFrame", literal(false)),
defun("yield", new String[]{"value"}, block(
store(load("outer"), "hasNext", literal(true)),
store(load("outer"), "current", load("value")),
store("yieldFrame", frame),
//bp,
resume(load("returnFrame"), literal(null))
))
))),
local("current", literal(false))
))),
local(load(load("generator"), "yielder"), "returnFrame", frame),
local(load(load("generator"), "yielder"), "outer", load("generator")),
apply(fn(new String[]{"producer", "generator"}, block(
call("producer", load(load("generator"), "yielder")),
resume(load(load(load("generator"), "yielder"), "returnFrame"), literal(null))
)), load("producer"), load("generator")),
load("generator")
)),*/
defun("generate", new String[]{"producer"}, block(
local("generator", object(block(
local("producer", load("producer")),
local("hasNext", literal(false)),
defun("atEnd", not(load("hasNext"))),
defun("next", block(
local("res", load("current")),
store("hasNext", literal(false)),
store("returnFrame", frame),
resume(load("yieldFrame"), literal(null)),
load("res")
)),
local("returnFrame", literal(false)),
local("yieldFrame", literal(false)),
defun("yield", new String[]{"value"}, block(
store("hasNext", literal(true)),
store("current", load("value")),
store("yieldFrame", frame),
resume(load("returnFrame"), literal(null))
)),
local("current", literal(false)),
local("returnFrame", frame)
))),
apply(fn(new String[]{"producer", "generator"}, block(
call("producer", load("generator")),
resume(load(load("generator"), "returnFrame"), literal(null))
)), load("producer"), load("generator")),
load("generator")
)),
local("gen", call("generate", load("numbers"))),
loop(not(send(load("gen"), "atEnd")), block(
call("println", send(load("gen"), "next"))
))
));
/*String sourceCode = "( 1 ) 34";
AST program = program(block(
defun("println", new String[]{"str"},
invoke(fieldGet(System.class.getField("out")), PrintStream.class.getMethod("println", String.class), invoke(load("str"), Object.class.getMethod("toString")))
),
call("println", literal("Hello World")),
local("inputStream", object(block(
local("input", literal(new ByteArrayInputStream(sourceCode.getBytes()))),
defun("next", invoke(load("input"), InputStream.class.getMethod("read"))),
defun("nextChar", itoc(call("next"))),
defun("hasMore", gti(invoke(load("input"), InputStream.class.getMethod("available")), literal(0)))
))),
local("scanner", object(block(
defun("nextToken", invoke(load("inputStream"), InputStream.class.getMethod("read"))),
defun("hasMoreTokens", gti(invoke(load("input"), InputStream.class.getMethod("available")), literal(0)))
))),
loop(send(load("inputStream"), "hasMore"),
call("println", send(load("inputStream"), "nextChar"))
)
));*/
/*AST program = program(block(
local("myPoint", object(block(
local("x", literal(3)),
local("y", literal(5)),
defun("someFunc", new String[]{}, muli(load("x"), load("y"))),
defun("setX", new String[]{"x"}, store(outerEnv(env()), "x", load("x"))),
defun("setX2", new String[]{"x"}, block(
local("tmpX", addi(load("x"), literal(1))),
store(env(), "x", load("tmpX"))
))
))),
defun("strconcat", new String[]{"x", "y"}, invoke(load("x"), String.class.getMethod("concat", String.class), load("y"))),
defun("exclamator", new String[]{"x"}, call("strconcat", load("x"), literal("!!!"))),
call("exclamator", literal("Hello world")),
on(load("myPoint"), call("setX2", literal(77))),
on(load("myPoint"), load("x"))
));*/
/*AST program = program(block(
local("myFunc", fn(new String[]{"x", "y"},
addi(load("x"), load("y"))
)),
local("sq", fn(new String[]{"x"},
muli(load("x"), literal(2))
)),
pushCallFrame(load("myFunc"), pushCallFrame(load("sq"), literal(5)), literal(6))
));*/
/*AST program = program(block(
local("x", literal(5)),
local("y", literal(9)),
test(lti(load("x"), load("y")),
invoke(fieldGet(System.class.getField("out")), PrintStream.class.getMethod("println", String.class), literal("YES!!!")),
invoke(fieldGet(System.class.getField("out")), PrintStream.class.getMethod("println", String.class), literal("No..."))
)
));*/
/*AST program = program(block(
local("x", literal(0)),
loop(lti(load("x"), literal(10)),
store("x", addi(load("x"), literal(1)))
),
load("x")
));*/
Instruction[] instructions = Generator.toInstructions(program);
Thread thread = new Thread(new CallFrame(instructions));
/*Thread thread = new Thread(new CallFrame(new Instruction[] {
loadEnvironment,
newInstance(ArrayList.class.getConstructor()),
local("list"),
loadEnvironment,
load("list"),
loadConst(5),
invoke(ArrayList.class.getMethod("add", Object.class)),
loadEnvironment,
load("list"),
loadConst(7),
invoke(ArrayList.class.getMethod("add", Object.class)),
loadEnvironment,
load("list"),
finish
}));*/
/*Thread thread = new Thread(new CallFrame(new Instruction[] {
loadEnvironment,
loadConst(0),
local("i"),
loadEnvironment,
load("i"),
loadConst(10),
lti,
not,
jumpIfTrue(17),
loadEnvironment,
loadEnvironment,
load("i"),
loadConst(1),
addi,
store("i"),
loadConst(true),
jumpIfTrue(3),
loadEnvironment,
load("i"),
finish
}));*/
/*Thread thread = new Thread(new CallFrame(new Instruction[] {
loadEnvironment,
dup,
loadConst(new Instruction[]{
loadEnvironment,
extendEnvironment,
storeEnvironment,
pushOperandFrame(0),
loadEnvironment,
loadConst(5),
local("x"),
loadConst(7),
loadEnvironment,
load("x"),
addi,
popOperandFrame(1),
loadEnvironment,
outerEnvironment,
storeEnvironment,
popCallFrame
}),
local("myFunc"),
load("myFunc"),
visitApply,
finish
}));*/
Object result = thread.evalAll().callFrame.pop();
System.out.println(result);
}
} |
package dr.evomodel.coalescent;
import dr.evomodel.tree.TreeModel;
import dr.inference.model.Likelihood;
import dr.math.distributions.GammaDistribution;
/**
* Calculates a product of gamma densities and gamma tail probabilities.
*
* @author Guy Baele
*/
public class GammaProductLikelihood extends Likelihood.Abstract {
public final static boolean USE_EXPONENTIAL = false;
public final static boolean REDUCE_TO_EXPONENTIAL = false;
public final static boolean DEBUG = false;
//let's forget about this for the moment
public final static boolean FIXED_TREE = false;
private TreeModel treeModel;
private double popSize;
private double[] means;
private double[] variances;
private double[] alphas;
private double[] betas;
public GammaProductLikelihood(TreeModel treeModel, double popSize, double[] means, double[] variances) {
super(treeModel);
this.treeModel = treeModel;
this.popSize = popSize;
this.means = means;
this.variances = variances;
System.err.println("\nProvided empirical means and variances: ");
for (int i = 0; i < means.length; i++) {
System.err.println(means[i] + " " + variances[i]);
}
System.err.println("Ratio of mean squared and variance:");
for (int i = 0; i < means.length; i++) {
System.err.println(means[i]*means[i]/variances[i]);
}
//calculate alpha and beta for the gamma distributions
alphas = new double[means.length];
betas = new double[means.length];
//approach 1
for (int i = 0; i < alphas.length; i++) {
alphas[i] = means[i]*means[i]/variances[i];
}
for (int i = 0; i < betas.length; i++) {
betas[i] = means[i]/variances[i];
}
/*for (int i = 0; i < alphas.length; i++) {
alphas[i] = 2.0*means[i]*means[i]/variances[i];
}
for (int i = 0; i < betas.length; i++) {
betas[i] = 2.0*means[i]/variances[i];
}*/
/*for (int i = 0; i < alphas.length; i++) {
alphas[i] = 4.0*means[i]*means[i]/variances[i];
}
for (int i = 0; i < betas.length; i++) {
betas[i] = 4.0*means[i]/variances[i];
}*/
//approach 2 - DEFINITELY NOT
/*for (int i = 0; i < alphas.length; i++) {
alphas[i] = 1.0/variances[i];
}
for (int i = 0; i < betas.length; i++) {
betas[i] = 1.0/(means[i]*variances[i]);
}*/
//approach 3
/*for (int i = 0; i < alphas.length; i++) {
alphas[i] = means[i]/variances[i];
}
for (int i = 0; i < betas.length; i++) {
betas[i] = 1.0/variances[i];
}*/
//approach 4 - reduce approach 1 to exponential
/*for (int i = 0; i < alphas.length; i++) {
alphas[i] = 1.0;
}
for (int i = 0; i < betas.length; i++) {
betas[i] = 1.0/means[i];
}*/
/*for (int i = 0; i < alphas.length; i++) {
alphas[i] = 2.0;
}
for (int i = 0; i < betas.length; i++) {
betas[i] = 2.0/means[i];
}*/
//approach 5
/*for (int i = 0; i < alphas.length; i++) {
alphas[i] = (means[i]*means[i]*means[i])/variances[i];
}
for (int i = 0; i < betas.length; i++) {
betas[i] = (means[i]*means[i])/variances[i];
}*/
//approach 6 - still run 50 replicates for this approach
/*for (int i = 0; i < alphas.length; i++) {
alphas[i] = means[i];
}
for (int i = 0; i < betas.length; i++) {
betas[i] = 1.0;
}*/
//approach 7 - still run 50 replicates for this approach
/*for (int i = 0; i < alphas.length; i++) {
alphas[i] = 1.0/means[i];
}
for (int i = 0; i < betas.length; i++) {
betas[i] = 1.0/(means[i]*means[i]);
}*/
//approach 8
/*for (int i = 0; i < alphas.length; i++) {
alphas[i] = means[i]*variances[i];
}
for (int i = 0; i < betas.length; i++) {
betas[i] = variances[i];
}*/
//approach 9
/*for (int i = 0; i < alphas.length; i++) {
alphas[i] = variances[i];
}
for (int i = 0; i < betas.length; i++) {
betas[i] = variances[i]/means[i];
}*/
//approach 10
/*for (int i = 0; i < alphas.length; i++) {
alphas[i] = means[i];
}
for (int i = 0; i < betas.length; i++) {
betas[i] = 1.0;
}*/
if (REDUCE_TO_EXPONENTIAL) {
for (int i = 0; i < alphas.length; i++) {
alphas[i] = 1.0;
}
for (int i = 0; i < betas.length; i++) {
betas[i] = 1.0/popSize;
}
}
System.err.println("\nResulting alphas and betas: ");
for (int i = 0; i < alphas.length; i++) {
System.err.println(alphas[i] + " " + betas[i] + " --> mean = " + (alphas[i]/betas[i]) + " variance = " + (alphas[i]/(betas[i]*betas[i])));
}
}
public GammaProductLikelihood(TreeModel treeModel, double popSize, int dim) {
super(treeModel);
this.treeModel = treeModel;
this.popSize = popSize;
int dimension = dim;
System.err.println("Number of intervals: " + dimension);
//calculate alpha and beta for the gamma distributions
alphas = new double[dimension];
betas = new double[dimension];
for (int i = 0; i < alphas.length; i++) {
alphas[i] = 0.5;
}
for (int i = 0; i < betas.length; i++) {
betas[i] = 0.5/this.popSize;
}
System.err.println("\nResulting alphas and betas: ");
for (int i = 0; i < alphas.length; i++) {
System.err.println(alphas[i] + " " + betas[i] + " --> mean = " + (alphas[i]/betas[i]) + " variance = " + (alphas[i]/(betas[i]*betas[i])));
}
}
public double calculateLogLikelihood() {
double logPDF = 0.0;
if (USE_EXPONENTIAL) {
CoalescentTreeIntervalStatistic ctis = new CoalescentTreeIntervalStatistic(treeModel);
for (int i = 0; i < ctis.getDimension(); i++) {
int combinations = (int)ctis.getLineageCount(i)*((int)ctis.getLineageCount(i)-1)/2;
double branchLength = ctis.getStatisticValue(i);
if (ctis.getLineageCount(i) != 1) {
//GammaDistribution is not parameterized in terms of alpha and beta, but in terms of shape and scale!
if (i == ctis.getDimension()-1) {
//coalescent event at root: exponential density
logPDF += GammaDistribution.logPdf(branchLength, 1.0, 1.0/(combinations*(1.0/popSize))) - 1.0*Math.log(combinations);
} else if (ctis.getLineageCount(i) > ctis.getLineageCount(i+1)) {
//coalescent event: exponential density
logPDF += GammaDistribution.logPdf(branchLength, 1.0, 1.0/(combinations*(1.0/popSize))) - 1.0*Math.log(combinations);
} else {
//sampling event: exponential tail probability
logPDF += Math.log(1-GammaDistribution.cdf(branchLength, 1.0, 1.0/(combinations*(1.0/popSize))));
}
}
}
} else {
CoalescentTreeIntervalStatistic ctis = new CoalescentTreeIntervalStatistic(treeModel);
if (DEBUG) {
System.err.println(treeModel);
System.err.println("CoalescentTreeIntervalStatistic dimension = " + ctis.getDimension() + "\n");
}
int coalescentIntervalCounter = 0;
for (int i = 0; i < ctis.getDimension(); i++) {
int combinations = (int)ctis.getLineageCount(i)*((int)ctis.getLineageCount(i)-1)/2;
double branchLength = ctis.getStatisticValue(i);
if (DEBUG) {
System.err.println("\nIteration: " + i);
System.err.println("combinations = " + combinations);
System.err.println("branchLength = " + branchLength);
}
if (ctis.getLineageCount(i) != 1) {
//GammaDistribution is not parameterized in terms of alpha and beta, but in terms of shape and scale!
if (i == ctis.getDimension()-1) {
//coalescent event at root: gamma density
//GammaDistribution.logPdf uses shape and scale, rather than shape and rate
logPDF += GammaDistribution.logPdf(branchLength, alphas[coalescentIntervalCounter], 1.0/(combinations*betas[coalescentIntervalCounter])) - Math.log(combinations);
if (DEBUG) {
System.err.print("coalescent event at root: ");
System.err.println("branchLength = " + branchLength);
System.err.println("alpha = " + alphas[coalescentIntervalCounter]);
System.err.println("beta = " + combinations*betas[coalescentIntervalCounter]);
System.err.println("mean = " + (alphas[coalescentIntervalCounter]/(combinations*betas[coalescentIntervalCounter])));
System.err.println("variance = " + (alphas[coalescentIntervalCounter]/((combinations*betas[coalescentIntervalCounter])*(combinations*betas[coalescentIntervalCounter]))));
System.err.println("combinations = " + combinations);
}
} else if (ctis.getLineageCount(i) > ctis.getLineageCount(i+1)) {
//GammaDistribution.logPdf uses shape and scale, rather than shape and rate
logPDF += GammaDistribution.logPdf(branchLength, alphas[coalescentIntervalCounter], 1.0/(combinations*betas[coalescentIntervalCounter])) - Math.log(combinations);
if (DEBUG) {
System.err.print("coalescent event (not at root): ");
System.err.println(GammaDistribution.logPdf(branchLength, combinations*alphas[coalescentIntervalCounter], 1.0/(combinations*betas[coalescentIntervalCounter])) - Math.log(combinations));
System.err.println("coalescentIntervalCounter = " + coalescentIntervalCounter);
}
//coalesent event: move towards next empirical mean/variance
coalescentIntervalCounter++;
} else {
//sampling event: gamma tail probability
//GammaDistribution.cdf also uses shape and scale, rather than shape and rate
logPDF += Math.log(1-GammaDistribution.cdf(branchLength, alphas[coalescentIntervalCounter], 1.0/(combinations*betas[coalescentIntervalCounter])));
if (DEBUG) {
System.err.print("sampling event: ");
System.err.println("branchLength = " + branchLength);
System.err.println("alpha = " + alphas[coalescentIntervalCounter]);
System.err.println("beta = " + combinations*betas[coalescentIntervalCounter]);
System.err.println("mean = " + (alphas[coalescentIntervalCounter]/(combinations*betas[coalescentIntervalCounter])));
System.err.println("variance = " + (alphas[coalescentIntervalCounter]/((combinations*betas[coalescentIntervalCounter])*(combinations*betas[coalescentIntervalCounter]))));
System.err.println("combinations = " + combinations);
System.err.println(GammaDistribution.cdf(branchLength, alphas[coalescentIntervalCounter], 1.0/(combinations*betas[coalescentIntervalCounter])));
System.err.println(Math.log(1-GammaDistribution.cdf(branchLength, alphas[coalescentIntervalCounter], 1.0/(combinations*betas[coalescentIntervalCounter]))));
}
}
}
}
}
if (DEBUG) {
System.err.println("logPDF = " + logPDF);
}
return logPDF;
}
/**
* Overridden to always return false.
*/
protected boolean getLikelihoodKnown() {
return false;
}
}
/*public class GammaProductLikelihood extends Likelihood.Abstract {
public final static boolean USE_EXPONENTIAL = false;
public final static boolean REDUCE_TO_EXPONENTIAL = false;
private TreeModel treeModel;
private double popSize;
private double[] means;
private double[] variances;
public GammaProductLikelihood(TreeModel treeModel, double popSize, double[] means, double[] variances) {
super(treeModel);
this.treeModel = treeModel;
this.popSize = popSize;
this.means = means;
this.variances = variances;
}
//make sure to provide a log(popSize)
//public GammaProductLikelihood(TreeModel treeModel, double popSize) {
// super(treeModel);
// this.treeModel = treeModel;
// this.popSize = popSize;
//}
public double calculateLogLikelihood() {
double logPDF = 0.0;
if (USE_EXPONENTIAL) {
CoalescentTreeIntervalStatistic ctis = new CoalescentTreeIntervalStatistic(treeModel);
for (int i = 0; i < ctis.getDimension(); i++) {
int combinations = (int)ctis.getLineageCount(i)*((int)ctis.getLineageCount(i)-1)/2;
double branchLength = ctis.getStatisticValue(i);
if (ctis.getLineageCount(i) != 1) {
//GammaDistribution is not parameterized in terms of alpha and beta, but in terms of shape and scale!
if (i == ctis.getDimension()-1) {
//coalescent event at root: exponential density
logPDF += GammaDistribution.logPdf(branchLength, 1.0, 1.0/(combinations*(1.0/popSize))) - 1.0*Math.log(combinations);
} else if (ctis.getLineageCount(i) > ctis.getLineageCount(i+1)) {
//coalescent event: exponential density
logPDF += GammaDistribution.logPdf(branchLength, 1.0, 1.0/(combinations*(1.0/popSize))) - 1.0*Math.log(combinations);
} else {
//sampling event: exponential tail probability
logPDF += Math.log(1-GammaDistribution.cdf(branchLength, 1.0, 1.0/(combinations*(1.0/popSize))));
}
}
}
} else {
//System.err.println("\nProvided empirical means and variances: ");
//for (int i = 0; i < means.length; i++) {
// System.err.println(means[i] + " " + variances[i]);
//}
//calculate alpha and beta for the gamma distributions
double[] alphas = new double[means.length];
for (int i = 0; i < alphas.length; i++) {
alphas[i] = means[i]*means[i]/variances[i];
}
double[] betas = new double[means.length];
for (int i = 0; i < betas.length; i++) {
betas[i] = means[i]/variances[i];
}
if (REDUCE_TO_EXPONENTIAL) {
for (int i = 0; i < alphas.length; i++) {
alphas[i] = 1.0;
}
for (int i = 0; i < betas.length; i++) {
betas[i] = 1.0/popSize;
}
}
//System.err.println("\nResulting alphas and betas: ");
//for (int i = 0; i < alphas.length; i++) {
// System.err.println(alphas[i] + " " + betas[i]);
//}
CoalescentTreeIntervalStatistic ctis = new CoalescentTreeIntervalStatistic(treeModel);
//System.err.println(treeModel);
//System.err.println("CoalescentTreeIntervalStatistic dimension = " + ctis.getDimension());
int coalescentIntervalCounter = 0;
for (int i = 0; i < ctis.getDimension(); i++) {
int combinations = (int)ctis.getLineageCount(i)*((int)ctis.getLineageCount(i)-1)/2;
//System.err.println("combinations = " + combinations);
double branchLength = ctis.getStatisticValue(i);
//System.err.println("branchLength = " + branchLength);
if (ctis.getLineageCount(i) != 1) {
//GammaDistribution is not parameterized in terms of alpha and beta, but in terms of shape and scale!
if (i == ctis.getDimension()-1) {
//coalescent event at root: gamma density
//System.err.print("coalescent event at root: ");
logPDF += GammaDistribution.logPdf(branchLength, alphas[coalescentIntervalCounter], 1.0/(combinations*betas[coalescentIntervalCounter])) - Math.log(combinations);
//logPDF += GammaDistribution.logPdf(branchLength, alphas[coalescentIntervalCounter], 1.0/(combinations*betas[coalescentIntervalCounter])) - alphas[coalescentIntervalCounter]*Math.log(combinations);
//System.err.println(GammaDistribution.logPdf(branchLength, alphas[coalescentIntervalCounter], 1.0/(combinations*betas[coalescentIntervalCounter])) - Math.log(combinations));
//coalesent event: move towards next empirical mean/variance but nowhere else to go
//coalescentIntervalCounter++;
} else if (ctis.getLineageCount(i) > ctis.getLineageCount(i+1)) {
//coalescent event: gamma density
//System.err.print("coalescent event (not at root): ");
logPDF += GammaDistribution.logPdf(branchLength, alphas[coalescentIntervalCounter], 1.0/(combinations*betas[coalescentIntervalCounter])) - Math.log(combinations);
//logPDF += GammaDistribution.logPdf(branchLength, alphas[coalescentIntervalCounter], 1.0/(combinations*betas[coalescentIntervalCounter])) - alphas[coalescentIntervalCounter]*Math.log(combinations);
//System.err.println(GammaDistribution.logPdf(branchLength, alphas[coalescentIntervalCounter], 1.0/(combinations*betas[coalescentIntervalCounter])) - Math.log(combinations));
//coalesent event: move towards next empirical mean/variance
coalescentIntervalCounter++;
} else {
//sampling event: gamma tail probability
//System.err.print("sampling event: ");
logPDF += Math.log(1-GammaDistribution.cdf(branchLength, alphas[coalescentIntervalCounter], 1.0/(combinations*betas[coalescentIntervalCounter])));
//System.err.println(Math.log(1-GammaDistribution.cdf(branchLength, alphas[coalescentIntervalCounter], 1.0/(combinations*betas[coalescentIntervalCounter]))));
//System.err.println(alphas[coalescentIntervalCounter]);
//System.err.println(betas[coalescentIntervalCounter]);
//System.err.println("coalescentIntervalCounter = " + coalescentIntervalCounter);
//System.err.println(1-GammaDistribution.cdf(branchLength, alphas[coalescentIntervalCounter], 1.0/(combinations*betas[coalescentIntervalCounter])));
}
}
}
}
//System.err.println("logPDF = " + logPDF);
//System.exit(0);
return logPDF;
}
public double calculateOldLogLikelihood() {
double logPDF = 0.0;
//Should not be used
double logPopSize = 0.0;
//means and variances are probably in the reverse order
//System.err.println("\nProvided empirical means and variances: ");
//for (int i = 0; i < means.length; i++) {
//System.err.println(means[i] + " " + variances[i]);
//}
CoalescentTreeIntervalStatistic ctis = new CoalescentTreeIntervalStatistic(treeModel);
//System.err.println("\nDimension = " + ctis.getDimension() + "\nLineage info: ");
//for (int i = ctis.getDimension()-1; i >= 0; i--) {
//System.err.println(ctis.getLineageCount(i));
//}
//System.err.println("\nStatistic values: ");
//for (int i = ctis.getDimension()-1; i >= 0; i--) {
//System.err.println(ctis.getStatisticValue(i));
//}
//ignore possibility of more than 1 dimension for now
//System.err.println("\nPopulation size = " + popSize);
//System.err.println("\nTree: " + treeModel);
//calculate alpha and beta for the gamma distributions
double[] alphas = new double[means.length];
for (int i = 0; i < alphas.length; i++) {
alphas[i] = means[i]*means[i]/variances[i];
}
double[] betas = new double[means.length];
for (int i = 0; i < betas.length; i++) {
betas[i] = means[i]/variances[i];
}
if (REDUCE_TO_EXPONENTIAL) {
for (int i = 0; i < alphas.length; i++) {
alphas[i] = 1.0;
}
for (int i = 0; i < betas.length; i++) {
betas[i] = 1.0/logPopSize;
}
}
int indicator = 0;
for (int i = ctis.getDimension()-1; i > 0; i--) {
//System.err.println("\nInterval " + i);
if (i == ctis.getDimension()-1) {
//coalescent event: gamma density
//System.err.println("Coalescent event at root");
//System.err.println("Interval length = " + ctis.getStatisticValue(i));
//System.err.println("Lineage count = " + ctis.getLineageCount(i));
int combinations = (int)ctis.getLineageCount(i)*((int)ctis.getLineageCount(i)-1)/2;
//System.err.println("Combinations = " + combinations);
logPDF += GammaDistribution.logPdf(ctis.getStatisticValue(i), alphas[indicator], 1.0/(combinations*betas[indicator])) - alphas[indicator]*Math.log(combinations);
//System.err.println(GammaDistribution.logPdf(ctis.getStatisticValue(i), alphas[indicator], 1.0/(combinations*betas[indicator])) - alphas[indicator]*Math.log(combinations));
if (indicator < (means.length-1)) {
indicator++;
}
} else if (ctis.getLineageCount(i) - ctis.getLineageCount(i+1) > 0) {
//coalescent event: gamma density
//System.err.println("Coalescent event");
//System.err.println("Interval length = " + ctis.getStatisticValue(i));
//System.err.println("Lineage count = " + ctis.getLineageCount(i));
int combinations = (int)ctis.getLineageCount(i)*((int)ctis.getLineageCount(i)-1)/2;
//System.err.println("Combinations = " + combinations);
logPDF += GammaDistribution.logPdf(ctis.getStatisticValue(i), alphas[indicator], 1.0/(combinations*betas[indicator])) - alphas[indicator]*Math.log(combinations);
//System.err.println(GammaDistribution.logPdf(ctis.getStatisticValue(i), alphas[indicator], 1.0/(combinations*betas[indicator])) - alphas[indicator]*Math.log(combinations));
if (indicator < (means.length-1)) {
indicator++;
}
} else {
//new sample: gamma tail probability
//System.err.println("New sample");
//System.err.println("Interval length = " + ctis.getStatisticValue(i));
//System.err.println("Lineage count = " + ctis.getLineageCount(i));
int combinations = (int)ctis.getLineageCount(i)*((int)ctis.getLineageCount(i)-1)/2;
//System.err.println("Combinations = " + combinations);
logPDF += Math.log(1-GammaDistribution.cdf(ctis.getStatisticValue(i), alphas[indicator], 1.0/(combinations*betas[indicator])));
//System.err.println(Math.log(1-GammaDistribution.cdf(ctis.getStatisticValue(i), alphas[indicator], 1.0/(combinations*betas[indicator]))));
}
}
//System.err.println("\nlogPDF = " + logPDF);
//System.exit(0);
return logPDF;
}
protected boolean getLikelihoodKnown() {
return false;
}
}*/ |
package edu.jhu.thrax.hadoop.datatypes;
import org.apache.hadoop.io.WritableComparable;
import org.apache.hadoop.io.WritableComparator;
import org.apache.hadoop.io.WritableUtils;
import org.apache.hadoop.io.Text;
import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;
public class AlignmentArray implements WritableComparable<AlignmentArray> {
private Text[][] array;
public AlignmentArray() {
// do nothing
}
public AlignmentArray(Text[][] values) {
array = values;
}
public AlignmentArray(String[][] values) {
array = new Text[values.length][];
for (int i = 0; i < values.length; i++) {
array[i] = new Text[values[i].length];
for (int j = 0; j < values[i].length; j++)
array[i][j] = new Text(values[i][j]);
}
}
public void set(Text[][] values) {
array = values;
}
public Text[][] get() {
return array;
}
public boolean isEmpty() {
return (array == null || array.length == 0);
}
public void readFields(DataInput in) throws IOException {
int length = in.readInt();
if (length == 0)
array = null;
else {
array = new Text[length][];
for (int i = 0; i < array.length; i++)
array[i] = new Text[in.readInt()];
for (int i = 0; i < array.length; i++) {
for (int j = 0; j < array[i].length; j++) {
Text t = new Text();
t.readFields(in);
array[i][j] = t;
}
}
}
}
public void write(DataOutput out) throws IOException {
if (array == null)
out.writeInt(0);
else {
out.writeInt(array.length);
for (int i = 0; i < array.length; i++)
out.writeInt(array[i].length);
for (int i = 0; i < array.length; i++) {
for (int j = 0; j < array[i].length; j++) {
array[i][j].write(out);
}
}
}
}
public int compareTo(AlignmentArray other) {
Text[][] mine = array;
Text[][] theirs = other.get();
int mine_length = (mine != null) ? mine.length : 0;
int their_length = (theirs != null) ? theirs.length : 0;
if (mine_length != their_length)
return mine.length - theirs.length;
for (int i = 0; i < mine.length; i++) {
Text[] mc = mine[i];
Text[] tc = theirs[i];
if (mc.length != tc.length)
return mc.length - tc.length;
for (int j = 0; j < mc.length; j++) {
int cmp = mc[j].compareTo(tc[j]);
if (cmp != 0)
return cmp;
}
}
return 0;
}
public boolean equals(Object o) {
if (!(o instanceof AlignmentArray))
return false;
AlignmentArray other = (AlignmentArray) o;
return (compareTo(other) == 0);
}
public int hashCode() {
int result = 163;
if (array == null)
return result;
Text[][] text = array;
result = result * 37 + text.length;
for (Text[] ct : text) {
result = result * 37 + ct.length;
for (Text t : ct)
result = result * 37 + t.hashCode();
}
return result;
}
public static class Comparator extends WritableComparator {
private static final Text.Comparator TEXT_COMPARATOR = new Text.Comparator();
public Comparator() {
super(AlignmentArray.class);
}
public int compare(byte[] b1, int s1, int l1, byte[] b2, int s2, int l2) {
int h1 = readInt(b1, s1);
int h2 = readInt(b2, s2);
if (h1 != h2)
return h1 - h2;
int idx1 = s1 + 4;
int idx2 = s2 + 4;
int total = 0;
for (int i = 0; i < h1; i++) {
int r1 = readInt(b1, idx1);
int r2 = readInt(b2, idx2);
if (r1 != r2)
return r1 - r2;
idx1 += 4;
idx2 += 4;
total += r1;
}
for (int j = 0; j < total; j++) {
try {
int length1 = WritableUtils.decodeVIntSize(b1[idx1])
+ readVInt(b1, idx1);
int length2 = WritableUtils.decodeVIntSize(b2[idx2])
+ readVInt(b2, idx2);
int cmp = TEXT_COMPARATOR.compare(b1, idx1, length1, b2, idx2,
length2);
if (cmp != 0)
return cmp;
idx1 += length1;
idx2 += length2;
} catch (IOException e) {
throw new IllegalArgumentException();
}
}
return 0;
}
public int encodedLength(byte[] b1, int s1) {
int idx = s1;
int h = readInt(b1, s1);
idx += 4;
int numTexts = 0;
for (int i = 0; i < h; i++) {
numTexts += readInt(b1, idx);
idx += 4;
}
for (int j = 0; j < numTexts; j++) {
try {
int length = WritableUtils.decodeVIntSize(b1[idx])
+ readVInt(b1, idx);
idx += length;
} catch (IOException e) {
throw new IllegalArgumentException();
}
}
return idx - s1;
}
}
static {
WritableComparator.define(AlignmentArray.class, new Comparator());
}
} |
package edu.mit.streamjit.impl.compiler2;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Iterables;
import edu.mit.streamjit.util.bytecode.BasicBlock;
import edu.mit.streamjit.util.bytecode.Field;
import edu.mit.streamjit.util.bytecode.Klass;
import edu.mit.streamjit.util.bytecode.Method;
import edu.mit.streamjit.util.bytecode.Modifier;
import edu.mit.streamjit.util.bytecode.Module;
import edu.mit.streamjit.util.bytecode.ModuleClassLoader;
import edu.mit.streamjit.util.bytecode.insts.CallInst;
import edu.mit.streamjit.util.bytecode.insts.CastInst;
import edu.mit.streamjit.util.bytecode.insts.LoadInst;
import edu.mit.streamjit.util.bytecode.insts.ReturnInst;
import edu.mit.streamjit.util.bytecode.insts.StoreInst;
import edu.mit.streamjit.util.bytecode.types.VoidType;
import java.lang.invoke.MethodHandle;
import java.lang.invoke.MethodHandles;
import java.util.EnumSet;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;
/**
* Bytecodifies MethodHandles. That is, stores them in a static final field,
* spins a method that calls through that field, and returns a MethodHandle
* to that new method. The effect is to provide a specialization point for the
* JVM to inline into.
* @author Jeffrey Bosboom <jeffreybosboom@gmail.com>
* @since 12/3/2013
*/
public final class Bytecodifier {
private Bytecodifier() {}
/**
* A "bounce point" for setting up static final fields in classes we spin.
* We generate a new integer and store our state in the map, while the spun
* class removes it in a static initializer. This avoids spinning an extra
* "field helper" class.
*
* The keys are all stringized integers; we use String to avoid having to
* generate boxing code for an integer constant.
*/
public static final ConcurrentHashMap<String, MethodHandle> BOUNCER = new ConcurrentHashMap<>();
private static final AtomicInteger BOUNCER_KEY_FACTORY = new AtomicInteger();
private static final MethodHandles.Lookup PUBLIC_LOOKUP = MethodHandles.publicLookup();
/**
* Returns a MethodHandle that redirects through a newly-spun static method
* before calling the given handle. The returned handle is behaviorally
* identical to the given handle.
* @param handle the handle to bytecodify
* @param className the name of the class to be spun; must be unique within
* the module
* @param module the module to spin the class in
* @param loader the class loader to load the class with
* @return a behaviorally identical MethodHandle
*/
public static MethodHandle bytecodify(MethodHandle handle, String className, Module module, ModuleClassLoader loader) {
Klass klass = new Klass(className, module.getKlass(Object.class), ImmutableList.<Klass>of(), module);
klass.modifiers().addAll(EnumSet.of(Modifier.PUBLIC, Modifier.FINAL));
Field field = new Field(module.types().getRegularType(MethodHandle.class), "handle", EnumSet.of(Modifier.PRIVATE, Modifier.STATIC, Modifier.FINAL), klass);
String key = String.valueOf(BOUNCER_KEY_FACTORY.getAndIncrement());
MethodHandle previousHandle = BOUNCER.putIfAbsent(key, handle);
assert previousHandle == null : "reused "+key;
Method clinit = new Method("<clinit>",
module.types().getMethodType(void.class),
EnumSet.of(Modifier.STATIC),
klass);
BasicBlock clinitBlock = new BasicBlock(module);
clinit.basicBlocks().add(clinitBlock);
LoadInst loadBouncer = new LoadInst(module.getKlass(Bytecodifier.class).getField("BOUNCER"));
Method chmGet = Iterables.getOnlyElement(module.getKlass(ConcurrentHashMap.class).getMethods("get"));
CallInst get = new CallInst(chmGet, loadBouncer, module.constants().getConstant(key));
CastInst unerase = new CastInst(field.getType().getFieldType(), get);
StoreInst storeField = new StoreInst(field, unerase);
clinitBlock.instructions().addAll(ImmutableList.of(loadBouncer, get, unerase, storeField,
new ReturnInst(module.types().getVoidType())));
Method invoke = new Method("$invoke",
module.types().getMethodType(handle.type()),
EnumSet.of(Modifier.PUBLIC, Modifier.STATIC),
klass);
BasicBlock invokeBlock = new BasicBlock(module);
invoke.basicBlocks().add(invokeBlock);
LoadInst loadHandle = new LoadInst(field);
Method invokeExact = Iterables.getOnlyElement(module.getKlass(MethodHandle.class).getMethods("invokeExact"));
CallInst call = new CallInst(invokeExact, invoke.getType().prependArgument(module.types().getRegularType(MethodHandle.class)), loadHandle);
for (int i = 0; i < invoke.arguments().size(); ++i)
call.setArgument(i+1, invoke.arguments().get(i));
invokeBlock.instructions().addAll(ImmutableList.of(loadHandle, call,
call.getType() instanceof VoidType ?
new ReturnInst(module.types().getVoidType()) :
new ReturnInst(invoke.getType().getReturnType(), call)));
try {
Class<?> liveClass = loader.loadClass(className);
return PUBLIC_LOOKUP.findStatic(liveClass, "$invoke", handle.type());
} catch (ClassNotFoundException | NoSuchMethodException | IllegalAccessException ex) {
throw new AssertionError(ex);
}
}
public static ImmutableList<Runnable> runnableProxies(List<MethodHandle> handles) {
ImmutableList.Builder<String> names = ImmutableList.builder();
for (int i = 0; i < handles.size(); ++i)
names.add("Proxy"+i);
return runnableProxies(handles, names.build());
}
public static ImmutableList<Runnable> runnableProxies(List<MethodHandle> handles, List<String> proxyNames) {
try {
Module m = new Module();
ModuleClassLoader mcl = new ModuleClassLoader(m);
Klass fieldHelperKlass = new Klass("ProxyFieldHelper", m.getKlass(Object.class), ImmutableList.<Klass>of(), m);
fieldHelperKlass.modifiers().addAll(EnumSet.of(Modifier.FINAL)); //TODO: public?
for (int i = 0; i < handles.size(); ++i)
new Field(m.types().getRegularType(MethodHandle.class), "handle"+i, EnumSet.of(Modifier.PUBLIC, Modifier.STATIC), fieldHelperKlass);
Class<?> fieldHelper = mcl.loadClass(fieldHelperKlass.getName());
for (int i = 0; i < handles.size(); ++i) {
java.lang.reflect.Field field = fieldHelper.getField("handle"+i);
field.setAccessible(true);
field.set(null, handles.get(i));
}
ImmutableList.Builder<Runnable> builder = ImmutableList.builder();
for (int i = 0; i < handles.size(); ++i) {
Klass proxyKlass = new Klass(proxyNames.get(i), m.getKlass(Object.class), ImmutableList.of(m.getKlass(Runnable.class)), m);
proxyKlass.modifiers().addAll(EnumSet.of(Modifier.PUBLIC, Modifier.FINAL));
Field handle = new Field(m.types().getRegularType(MethodHandle.class), "handle"+i, EnumSet.of(Modifier.PRIVATE, Modifier.STATIC, Modifier.FINAL), proxyKlass);
Method clinit = new Method("<clinit>",
m.types().getMethodType(void.class),
EnumSet.of(Modifier.STATIC),
proxyKlass);
BasicBlock clinitBlock = new BasicBlock(m);
clinit.basicBlocks().add(clinitBlock);
LoadInst loadHelperField = new LoadInst(fieldHelperKlass.getField("handle"+i));
StoreInst storeProxyField = new StoreInst(handle, loadHelperField);
clinitBlock.instructions().addAll(ImmutableList.of(loadHelperField, storeProxyField,
new ReturnInst(m.types().getVoidType())));
Method init = new Method("<init>",
m.types().getMethodType(m.types().getType(proxyKlass)),
EnumSet.of(Modifier.PUBLIC),
proxyKlass);
BasicBlock initBlock = new BasicBlock(m);
init.basicBlocks().add(initBlock);
Method objCtor = m.getKlass(Object.class).getMethods("<init>").iterator().next();
initBlock.instructions().add(new CallInst(objCtor));
initBlock.instructions().add(new ReturnInst(m.types().getVoidType()));
Method run = new Method("run",
m.types().getMethodType(void.class).appendArgument(m.types().getRegularType(proxyKlass)),
EnumSet.of(Modifier.PUBLIC, Modifier.FINAL),
proxyKlass);
BasicBlock runBlock = new BasicBlock(m);
run.basicBlocks().add(runBlock);
LoadInst li = new LoadInst(handle);
runBlock.instructions().add(li);
runBlock.instructions().add(new CallInst(
Iterables.getOnlyElement(m.getKlass("java.lang.invoke.MethodHandle").getMethods("invokeExact")),
m.types().getMethodType(void.class, MethodHandle.class),
li));
runBlock.instructions().add(new ReturnInst(m.types().getVoidType()));
Class<?> proxy = mcl.loadClass(proxyKlass.getName());
builder.add((Runnable)proxy.newInstance());
}
return builder.build();
} catch (ClassNotFoundException | NoSuchFieldException | IllegalAccessException | InstantiationException ex) {
throw new AssertionError(ex);
}
}
} |
package edu.wheaton.simulator.gui;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.Map;
import javax.swing.JFileChooser;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JOptionPane;
import com.google.common.collect.ImmutableMap;
import net.sourceforge.jeval.EvaluationException;
import edu.wheaton.simulator.datastructure.Field;
import edu.wheaton.simulator.datastructure.Grid;
import edu.wheaton.simulator.entity.Agent;
import edu.wheaton.simulator.gui.screen.EditEntityScreen;
import edu.wheaton.simulator.gui.screen.EditFieldScreen;
import edu.wheaton.simulator.gui.screen.NewSimulationScreen;
import edu.wheaton.simulator.gui.screen.SetupScreen;
import edu.wheaton.simulator.gui.screen.SpawningScreen;
import edu.wheaton.simulator.gui.screen.StatDisplayScreen;
import edu.wheaton.simulator.gui.screen.TitleScreen;
import edu.wheaton.simulator.gui.screen.ViewSimScreen1;
import edu.wheaton.simulator.simulation.Simulator;
import edu.wheaton.simulator.simulation.end.SimulationEnder;
import edu.wheaton.simulator.statistics.Loader;
import edu.wheaton.simulator.statistics.Saver;
import edu.wheaton.simulator.statistics.StatisticsManager;
public class SimulatorGuiManager {
private ScreenManager sm;
private SimulationEnder se;
private StatisticsManager statMan;
private Simulator simulator;
private boolean simulationIsRunning;
private ArrayList<SpawnCondition> spawnConditions;
private boolean canSpawn;
private GridPanel gridPanel;
private GridPanelObserver gpo;
private Loader loader;
private Saver saver;
private boolean hasStarted;
private JFileChooser fc;
public SimulatorGuiManager(Display d) {
spawnConditions = new ArrayList<SpawnCondition>();
canSpawn = true;
initSim("New Simulation",10, 10);
gridPanel = new GridPanel(this);
sm = new ScreenManager(d);
sm.putScreen("Title", new TitleScreen(this));
sm.putScreen("New Simulation", new NewSimulationScreen(this));
sm.putScreen("Edit Fields", new EditFieldScreen(this));
sm.putScreen("Edit Entities", new EditEntityScreen(this));
sm.putScreen("Spawning", new SpawningScreen(this));
sm.putScreen("View Simulation", new ViewSimScreen1(this));
sm.putScreen("Statistics", new StatDisplayScreen(this));
sm.putScreen("Grid Setup", new SetupScreen(this));
sm.getDisplay().setJMenuBar(makeMenuBar());
se = new SimulationEnder();
loader = new Loader();
statMan = StatisticsManager.getInstance();
hasStarted = false;
gpo = new GridPanelObserver(gridPanel);
fc = new JFileChooser();
}
public SimulatorGuiManager(){
this(new Display());
}
public ScreenManager getScreenManager(){
return sm;
}
public GridPanel getGridPanel(){
return gridPanel;
}
public void initSim(String name,int x, int y) {
System.out.println("Reset prototypes");
simulator = new Simulator(name, x, y, se);
simulator.addGridObserver(gpo);
if(gridPanel != null)
gridPanel.setGrid(getSimGrid());
}
private Simulator getSim() {
return simulator;
}
public Grid getSimGrid(){
return getSim().getGrid();
}
public Map<String,String> getSimGridFieldMap(){
return getSimGrid().getFieldMap();
}
public Field getSimGlobalField(String name){
return getSim().getGlobalField(name);
}
public void addSimGlobalField(String name, String value){
getSim().addGlobalField(name, value);
}
public void removeSimGlobalField(String name){
getSim().removeGlobalField(name);
}
private SimulationEnder getSimEnder() {
return se;
}
public void setSimStepLimit(int maxSteps){
getSimEnder().setStepLimit(maxSteps);
}
public int getSimStepLimit(){
return getSimEnder().getStepLimit();
}
public void setSimPopLimit(String typeName, int maxPop){
getSimEnder().setPopLimit(typeName, maxPop);
}
public ImmutableMap<String, Integer> getSimPopLimits(){
return getSimEnder().getPopLimits();
}
public void removeSimPopLimit(String typeName){
getSimEnder().removePopLimit(typeName);
}
public StatisticsManager getStatManager(){
return statMan;
}
public String getSimName(){
return getSim().getName();
}
public void updateGuiManager(String nos, int width, int height){
getSim().setName(nos);
resizeSimGrid(width, height);
}
public boolean isSimRunning() {
return simulationIsRunning;
}
public void setSimRunning(boolean b) {
simulationIsRunning = b;
}
public void setSimStarted(boolean b) {
hasStarted = b;
}
public boolean hasSimStarted() {
return hasStarted;
}
public ArrayList<SpawnCondition> getSimSpawnConditions() {
return spawnConditions;
}
public int getSimGridHeight(){
return getSim().getGrid().getHeight();
}
public void resizeSimGrid(int width,int height){
getSim().resizeGrid(width, height);
}
public int getSimGridWidth(){
return getSim().getGrid().getWidth();
}
public void setSimLayerExtremes() throws EvaluationException{
getSim().setLayerExtremes();
}
public Agent getSimAgent(int x, int y){
return getSim().getAgent(x, y);
}
public void removeSimAgent(int x, int y){
getSim().removeAgent(x, y);
}
public void initSampleSims(){
getSim().initSamples();
}
public void initGameOfLifeSim(){
getSim().initGameOfLife();
}
public void initRockPaperScissorsSim(){
getSim().initRockPaperScissors();
}
public void setSimLinearUpdate(){
getSim().setLinearUpdate();
}
public void setSimAtomicUpdate(){
getSim().setAtomicUpdate();
}
public void setSimPriorityUpdate(int a, int b){
getSim().setPriorityUpdate(a, b);
}
public String getCurrentSimUpdater(){
return getSim().currentUpdater();
}
public void pauseSim(){
setSimRunning(false);
canSpawn = true;
simulator.pause();
}
public boolean canSimSpawn() {
return canSpawn;
}
public boolean spiralSpawnSimAgent(String prototypeName, int x, int y){
return getSim().spiralSpawn(prototypeName, x, y);
}
public boolean spiralSpawnSimAgent(String string) {
return getSim().spiralSpawn(string);
}
public boolean horizontalSpawnSimAgent(String prototypeName, int x) {
return getSim().horizontalSpawn(prototypeName, x);
}
public boolean verticalSpawnSimAgent(String name, int y) {
return getSim().verticalSpawn(name, y);
}
public void loadSim() {
final JFileChooser fc = new JFileChooser();
int returnVal = fc.showOpenDialog(null);
String fileName = "";
if (returnVal == JFileChooser.APPROVE_OPTION) {
fileName = fc.getSelectedFile().getName();
//TODO make new simulator
loader.loadSimulation(fileName);
}
}
public void saveSim(String fileName) {
//StatisticsManager.save(fileName);
}
public void startSim(){
setSimRunning(true);
setSimStarted(true);
canSpawn = false;
simulator.resume();
}
private JMenuBar makeMenuBar() {
JMenuBar menuBar = new JMenuBar();
JMenu fileMenu = makeFileMenu(this);
//JMenu editMenu = makeEditMenu(sm);
JMenu helpMenu = makeHelpMenu(sm);
menuBar.add(fileMenu);
//menuBar.add(editMenu);
menuBar.add(helpMenu);
return menuBar;
}
private JMenu makeFileMenu(final SimulatorGuiManager guiManager) {
JMenu menu = Gui.makeMenu("File");
menu.add(Gui.makeMenuItem("New Simulation",
new GeneralButtonListener("New Simulation",guiManager.sm)));
menu.add(Gui.makeMenuItem("Save Simulation",
new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
String fileName = JOptionPane.showInputDialog("Please enter file name: ");
saveSim(fileName);
}
}
));
menu.add(Gui.makeMenuItem("Load Simulation",
new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
loadSim();
}
}
));
menu.add(Gui.makeMenuItem("Exit",new ActionListener(){
@Override
public void actionPerformed(ActionEvent e) {
guiManager.setSimRunning(false);
System.exit(0);
}
}));
return menu;
}
private JMenu makeEditMenu(final ScreenManager sm) {
JMenu menu = Gui.makeMenu("Edit");
menu.add(Gui.makeMenuItem("Edit Global Fields",
new GeneralButtonListener("Fields",sm)));
return menu;
}
private static JMenu makeHelpMenu(final ScreenManager sm) {
JMenu menu = Gui.makeMenu("Help");
menu.add(Gui.makeMenuItem("About",new ActionListener(){
@Override
public void actionPerformed(ActionEvent e) {
JOptionPane.showMessageDialog(sm.getDisplay(),
"Wheaton College. Software Development 2013.",
"About",JOptionPane.PLAIN_MESSAGE);
}
}));
menu.add(Gui.makeMenuItem("Help Contents",new ActionListener(){
@Override
public void actionPerformed(ActionEvent e) {
JOptionPane.showMessageDialog(sm.getDisplay(),
"Wheaton College. Software Development 2013.\n Help Contents",
"Help Contents",JOptionPane.PLAIN_MESSAGE);
}
}));
return menu;
}
public void setSimName(String name) {
getSim().setName(name);
}
} |
/* Open Source Software - may be modified and shared by FRC teams. The code */
/* the project. */
package edu.wpi.first.wpilibj.templates;
import edu.wpi.first.wpilibj.IterativeRobot;
import edu.wpi.first.wpilibj.CANJaguar;
import edu.wpi.first.wpilibj.DigitalInput;
import edu.wpi.first.wpilibj.DigitalOutput;
import edu.wpi.first.wpilibj.Joystick;
import edu.wpi.first.wpilibj.SimpleRobot;
import edu.wpi.first.wpilibj.Timer;
import edu.wpi.first.wpilibj.Ultrasonic;
import edu.wpi.first.wpilibj.camera.AxisCamera;
import edu.wpi.first.wpilibj.can.CANTimeoutException;
import edu.wpi.first.wpilibj.DriverStation;
import edu.wpi.first.wpilibj.DriverStationLCD;
/**
* The VM is configured to automatically run this class, and to call the
* functions corresponding to each mode, as described in the IterativeRobot
* documentation. If you change the name of this class or the package after
* creating this project, you must also update the manifest file in the resource
* directory.
*/
public class RobotTemplate extends IterativeRobot
{
/**
* This function is run when the robot is first started up and should be
* used for any initialization code.
*/
Joystick j1 = new Joystick(1);
Joystick j2 = new Joystick(2);
Joystick controller = new Joystick(3);
CANJaguar fLeft, fRight, bLeft, bRight,unused1, unused2, lowerArm, upperArm; //motors
DigitalOutput output; // for ultrasonic
DigitalInput input;
Ultrasonic ultraSonic;
AxisCamera cam; // camera
Timer timer = new Timer(); // timer
DigitalInput left; // for LineTracker
DigitalInput middle;
DigitalInput right;
DriverStation ds;
boolean forkLeft;
boolean pauseAtBegin; //Will the robot pause at the beginning of autonomous before moving?
boolean stopAfterHang; //Will the robot stop after it hangs a ubertube?
boolean turnAfterHang; //Will the robot turn as it's backing away, or go straight back? (Assuming that stopAfterHang is false)
boolean hasHangedTube; // Has the robot hanged its ubertube (or at least attempted to)?
boolean hasAlreadyPaused; //Has the robot already paused at the beginning? (Assuming that pauseAtBegin is true)
boolean doneWithAuto; //Has the robot done what it needs to in auto mode?
public void robotInit()
{
try
{
fLeft = new CANJaguar(10); // motors for wheels with CAN ports as arguements
fRight = new CANJaguar(4);
bLeft = new CANJaguar(9);
bRight = new CANJaguar(7);
lowerArm = new CANJaguar(5);
upperArm = new CANJaguar(8);
// setCoast(fLeft); // set them to drive in coast mode (no sudden brakes)
// setCoast(fRight);
// setCoast(bLeft);
// setCoast(bRight);
left = new DigitalInput(3); // for LineTracker
middle = new DigitalInput(2);
right = new DigitalInput(14);
output = new DigitalOutput(10); // ultrasonic output
input = new DigitalInput(8); //ultrasonic input
ultraSonic = new Ultrasonic(output, input, Ultrasonic.Unit.kMillimeter); //initialize ultrasonic
ultraSonic.setEnabled(true);
ultraSonic.setAutomaticMode(true);
ds = DriverStation.getInstance();
hasHangedTube = false;
hasAlreadyPaused = false;
doneWithAuto = false;
} catch (Exception e) { e.printStackTrace(); }
timer.delay(1);
}
/**
* This function is called periodically during autonomous
*/
boolean atFork = false; // if robot has arrived at fork
int lastSense = 0; // last LineTracker which saw line (1 for left, 2 for right)
public void autonomousPeriodic()
{
if (doneWithAuto)
{
return;
}
forkLeft = ds.getDigitalIn(1);//left
pauseAtBegin = ds.getDigitalIn(2);
stopAfterHang = ds.getDigitalIn(3);
turnAfterHang = !stopAfterHang && ds.getDigitalIn(4); //This will only be true if stopAfterHang is false
boolean leftValue = left.get();
boolean middleValue = middle.get();
boolean rightValue = right.get();
//System.out.print("Autonomous Start");
double speed = 0.3;
int lineState = (int)(rightValue?1:0)+
(int)(middleValue?2:0)+
(int)(leftValue?4:0);
if (hasHangedTube && !turnAfterHang) //If the robot has hanged the tube, and then should back straight up...
{
straight(-speed); // Back straight up
try
{
Thread.sleep(2000); //And after two seconds...
}
catch (Exception e)
{
e.printStackTrace();
}
straight(0); //Stop backing up
doneWithAuto = true;
return;
}
else if (hasHangedTube && turnAfterHang) //If the robot has hanged the tube, and then should turn around...
{
straight(-speed); //Back straight up
try
{
Thread.sleep(2000); //And after two seconds...
}
catch (Exception e)
{
e.printStackTrace();
}
hardRight(speed); //Start turning around
try
{
Thread.sleep(3000);
while(!middleValue)
Thread.sleep(50);
straight(0);
}
catch (Exception e)
{
e.printStackTrace();
}
straight(0); //Stop turning around
doneWithAuto = true;
return;
}
if(closerThan(500))
{
straight(0); //Stop
//Here I'm guessing we'd have the hangTube() method
hasHangedTube = true;
if (stopAfterHang) //If the robot is supposed to stay put after it hangs a tube
doneWithAuto = true;
return;
}
if (pauseAtBegin && !hasAlreadyPaused) //If the robot should pause at the beginning and it hasn't already paused...
{
try
{
Thread.sleep(3000); //Pause for 3 seconds
}
catch (Exception e)
{
e.printStackTrace();
}
hasAlreadyPaused = true; //The robot has now paused
}
moveWhileTracking(lineState, speed);
}
public void teleopPeriodic()
{
try{
setCoast(fLeft); // set them to drive in coast mode (no sudden brakes)
setCoast(fRight);
setCoast(bLeft);
setCoast(bRight);
setBreak(lowerArm);
setBreak(upperArm);
}catch (Exception e) {}
setLefts(deadzone(-j1.getY()));
setRights(deadzone(-j2.getY()));
updateLowerArm();
updateUpperArm();
}
private void setLefts(double d)
{
try{
fLeft.setX(d);
bLeft.setX(d);
} catch (CANTimeoutException e){
DriverStationLCD lcd = DriverStationLCD.getInstance();
lcd.println(DriverStationLCD.Line.kMain6, 1, "CAN on the Left!!!");
lcd.updateLCD();
}
}
private void setRights(double d)
{
try{
fRight.setX(-d);
bRight.setX(-d);
} catch (CANTimeoutException e){
e.printStackTrace();
DriverStationLCD lcd = DriverStationLCD.getInstance();
lcd.println(DriverStationLCD.Line.kMain6, 1, "CAN on the Right!!!");
lcd.updateLCD();
}
}
public void setCoast(CANJaguar jag) throws CANTimeoutException
{//Sets the drive motors to coast mode
try{jag.configNeutralMode(CANJaguar.NeutralMode.kCoast);} catch (Exception e) {e.printStackTrace();}
}
public void setBreak(CANJaguar jag) throws CANTimeoutException
{//Sets the drive motors to brake mode
try{jag.configNeutralMode(CANJaguar.NeutralMode.kBrake);} catch (Exception e) {e.printStackTrace();}
}
public double deadzone(double d)
{//deadzone for input devices
if (Math.abs(d) < .05) {
return 0;
}
return d / Math.abs(d) * ((Math.abs(d) - .05) / .95);
}
//comment
public double rampArm(double input)
{
if(input < 0)
{
return input * 0.01;
}
else return input;
}
public void straight(double speed)
{
setLefts(speed);
setRights(speed);
}
public void hardLeft(double speed)
{
setLefts(-speed);
setRights(speed);
}
public void hardRight(double speed)
{
setLefts(speed);
setRights(-speed);
}
public void softLeft(double speed)
{
setLefts(0);
setRights(speed);
}
public void softRight(double speed)
{
setLefts(speed);
setRights(0);
}
int lastRange = 0; // ascertains that you are less than 1500mm
public boolean closerThan(int millimeters)
{
if (ultraSonic.isRangeValid() && ultraSonic.getRangeMM() < millimeters)
{
if (lastRange > 4) // 4 checks to stop
{
return true;
}
else lastRange++;
}
else
{
lastRange = 0;
}
return false;
}
public void updateLowerArm()
{//state machine for the lower arm
try{
lowerArm.setX(deadzone(controller.getZ()));
} catch (CANTimeoutException e){
DriverStationLCD lcd = DriverStationLCD.getInstance();
lcd.println(DriverStationLCD.Line.kMain6, 1, "Arm is failing");
lcd.updateLCD();
}
}
public void updateUpperArm()
{
if(controller.getRawButton(6))
{
System.out.println("Upper arm: .5");
try{
upperArm.setX(0.5);
} catch (CANTimeoutException e){
DriverStationLCD lcd = DriverStationLCD.getInstance();
lcd.println(DriverStationLCD.Line.kMain6, 1, "Arm is failing");
lcd.updateLCD();
}
}
else if (controller.getRawButton(5))
{
System.out.println("Upper arm: -.5");
try{
upperArm.setX(-0.35);
} catch (CANTimeoutException e){
DriverStationLCD lcd = DriverStationLCD.getInstance();
lcd.println(DriverStationLCD.Line.kMain6, 1, "Arm is failing");
lcd.updateLCD();
}
}
else
{
try{
upperArm.setX(0.0);
} catch (CANTimeoutException e){
DriverStationLCD lcd = DriverStationLCD.getInstance();
lcd.println(DriverStationLCD.Line.kMain6, 1, "Arm is failing");
lcd.updateLCD();
}
}
//feedMe.feed();
}
public void moveWhileTracking(int lineState, double speed)
{
switch (lineState)
{
case 0: //No sensors see the line
System.out.println("Lost the line: " + lastSense);
speed = .25;
if (lastSense == 1) // left is last seen, go left
{
setLefts(-speed);//speed * 0.7);
setRights(speed);
}
else if (lastSense == 2) // go right
{
setLefts(speed);
setRights(-speed);//speed * 0.7);
}
else
{
setLefts(0.2); // CAUTION! Go Slowly!
setRights(0.2);
}
break;
case 1: //Right sees the line
softRight(speed);
lastSense = 2;
break;
case 2: //Middle sees the line
straight(speed);
break;
case 3: //Middle and right sees the line
softRight(speed);
lastSense = 2;
break;
case 4: //Left sees the line
// System.out.println("Hard left");
softLeft(speed);
lastSense = 1;
break;
case 5: //Left and right see the line
System.out.println("At Cross");
if(forkLeft)
{
hardLeft(speed);
}
else
{
hardRight(speed);
}
break;
case 6: //Left and middle see the line
softLeft(speed);
lastSense = 1;
break;
case 7: //All three see the line
System.out.println("At Cross 7");
if(forkLeft)
{
hardLeft(speed);
}
else
{
hardRight(speed);
}
break;
default:
System.out.println("You're doomed. Run.");
}
}
} |
/* Open Source Software - may be modified and shared by FRC teams. The code */
/* the project. */
//Make sure to "Commit" code on your local computer with relevant comments
//At end of session, "Push" code to the remote repository online.
package edu.wpi.first.wpilibj.templates;
import edu.wpi.first.wpilibj.Relay;
import edu.wpi.first.wpilibj.IterativeRobot;
import edu.wpi.first.wpilibj.Joystick;
import edu.wpi.first.wpilibj.RobotDrive;
import edu.wpi.first.wpilibj.Talon;
import com.sun.squawk.util.*;
import edu.wpi.first.wpilibj.Compressor;
import edu.wpi.first.wpilibj.Timer;
/**
* The VM is configured to automatically run this class, and to call the
* functions corresponding to each mode, as described in the IterativeRobot
* documentation. If you change the name of this class or the package after
* creating this project, you must also update the manifest file in the resource
* directory.
*/
public class RobotTemplate extends IterativeRobot {
double STARTINGTHRESHOLD = 0.0;
Talon frontleft;
Talon frontright;
Talon backleft;
Talon backright;
RobotDrive drive;
Joystick operatorStick;
Joystick driverStick;
Talon winch1;
Talon winch2;
Compressor compressor;
Talon collector;
Relay pancakeRelay;
Timer pancakeTimer;
boolean isPancakeTimerOn = false;
boolean isPS2Joystick = true;
/**
* This function is run when the robot is first started up and should be
* used for any initialization code.
*/
public void robotInit() {
driverStick= new Joystick(1);
operatorStick = new Joystick(2);
collector = new Talon (5);
frontleft = new Talon (1);
frontright = new Talon (2);
backleft = new Talon (3);
backright = new Talon (4);
winch1 = new Talon (6);
winch2 = new Talon (7);
drive = new RobotDrive (frontleft,backleft, frontright,backright);
compressor = new Compressor(5,5);
compressor.start();
pancakeRelay = new Relay(4);
pancakeRelay.setDirection(Relay.Direction.kForward);
pancakeTimer = new Timer();
}
/**
* This function is called periodically during autonomous
*/
public void autonomousPeriodic() {
}
/**
* This function is called periodically during operator control
*/
public void teleopPeriodic() {
checkDrive();
checkWinch();
checkCollector();
checkCompressor();
}
public void checkCollector()
{
if(operatorStick.getRawButton(8))
{
collector.set(1.0);
}
else
{
collector.set(0.0);
}
if(operatorStick.getRawButton(9))
{
collector.set(-1.0);
}
}
public void checkCompressor()
{
}
public void checkWinch()
{
if(operatorStick.getRawButton(7))
{
winch1.set(1.0);
winch2.set(1.0);
}
else
{
winch1.set(0.0);
winch2.set(0.0);
}
}
public void checkPancake()
{
if(operatorStick.getRawButton(10) && isPancakeTimerOn == false)
{
pancakeTimer.start();
isPancakeTimerOn = true;
pancakeRelay.setDirection(Relay.Direction.kReverse);
}
// after 2 secs
if(pancakeTimer.get() >= 2)
{
pancakeRelay.set(Relay.Value.kForward);
pancakeTimer.stop();
pancakeTimer.reset();
isPancakeTimerOn = false;
}
}
private void checkDrive(){
double x = driverStick.getRawAxis(1);
if(x < 0.1 && x > -0.1){
x = 0;
}
if(x > 0){
x = (1-STARTINGTHRESHOLD) * MathUtils.pow(x,2) + STARTINGTHRESHOLD;
}
else if(x < 0){
x = -1 * ((1-STARTINGTHRESHOLD) * MathUtils.pow(x,2) + STARTINGTHRESHOLD);
}
double y = driverStick.getRawAxis(2);
if(y < 0.1 && y > -0.1){
y = 0;
}
if(y > 0){
y = (1-STARTINGTHRESHOLD) * MathUtils.pow(y,2) + STARTINGTHRESHOLD;
}
else if(y < 0){
y = -1 * ((1-STARTINGTHRESHOLD) * MathUtils.pow(y,2) + STARTINGTHRESHOLD);
}
double rotation = 0;
if(isPS2Joystick)
{
rotation = operatorStick.getRawAxis(4);
}
else
{
rotation = driverStick.getRawAxis(3);
}
if(rotation < 0.05 && rotation > -0.05){
rotation = 0;
}
if(rotation > 0){
rotation = (1-STARTINGTHRESHOLD) * MathUtils.pow(rotation,2) + STARTINGTHRESHOLD;
}
else if (rotation < 0){
rotation = -1 * ((1-STARTINGTHRESHOLD) * MathUtils.pow(rotation,2) + STARTINGTHRESHOLD);
}
double gyroAngle = 0;
drive.mecanumDrive_Cartesian(x, y, rotation, 0.0);
}
/**
* This function is called periodically during test mode
*/
public void testPeriodic() {
}
} |
package com.civilizer.extra.tools;
import java.awt.AWTException;
import java.awt.Color;
import java.awt.Desktop;
import java.awt.EventQueue;
import java.awt.Font;
import java.awt.FontFormatException;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.MenuItem;
import java.awt.Point;
import java.awt.PopupMenu;
import java.awt.Rectangle;
import java.awt.RenderingHints;
import java.awt.SystemTray;
import java.awt.TrayIcon;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
//import java.awt.event.MouseAdapter;
//import java.awt.event.MouseEvent;
import java.io.File;
import java.io.FileFilter;
import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import java.net.URISyntaxException;
import java.text.MessageFormat;
import java.util.Arrays;
import java.util.Enumeration;
import java.util.regex.Pattern;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
//import javax.swing.ImageIcon;
//import javax.swing.JMenuItem;
//import javax.swing.JPopupMenu;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.util.resource.ResourceCollection;
import org.eclipse.jetty.webapp.WebAppContext;
import com.civilizer.config.Configurator;
import com.civilizer.utils.FsUtil;
public final class Launcher {
private static final String PORT = "civilizer.port";
private static final String STATUS = "civilizer.status";
private static final String BROWSE_AT_STARTUP = "civilizer.browse_at_startup";
private static final String STARTING = "Starting Civilizer...";
private static final String RUNNING = "Civilizer is running...";
private static Font fontForIcon;
private final Server server;
private final int port;
private enum LogType {
INFO,
WARN,
ERROR,
}
public static void main(String[] args) {
try {
System.setProperty(STATUS, STARTING);
System.setProperty(PORT, "");
setupSystemTray();
int port = 8080;
Arrays.sort(args);
final int iii = Arrays.binarySearch(args, "--port");
if (-1 < iii && iii < args.length-1) {
try {
port = Integer.parseInt(args[iii + 1]);
if (port <= 0)
throw new NumberFormatException();
} catch (NumberFormatException e) {
l(LogType.ERROR, "'" + port + "' is not a valid port number. exiting...");
System.exit(1);
}
}
new Launcher(port).startServer();
} catch (Exception e) {
l(LogType.ERROR, "An unhandled exception triggered. exiting...");
e.printStackTrace();
System.exit(1);
}
}
private static String getCvzUrl() {
final String portStr = System.getProperty(PORT);
assert portStr.isEmpty() == false;
int port = 0;
try {
port = Integer.parseInt(portStr);
} catch (NumberFormatException e) {
throw new Error(e);
}
return "http://localhost:" + port + "/civilizer/app/home";
}
private static String getFullJarPath(final Pattern pattern){
for(final String element : System.getProperty("java.class.path", ".").split("[:;]")){
if (pattern.matcher(element).matches())
return element;
}
return null;
}
private static String getResourcePathFromJarFile(final File file, final Pattern pattern){
try (ZipFile zf = new ZipFile(file);){
final Enumeration<?> e = zf.entries();
while(e.hasMoreElements()){
final ZipEntry ze = (ZipEntry) e.nextElement();
final String fileName = ze.getName();
if(pattern.matcher(fileName).matches())
return fileName;
}
} catch(final IOException e){
e.printStackTrace();
throw new Error(e);
}
return "";
}
private static Font createFont() {
final String tgtJarPath = getFullJarPath(Pattern.compile(".*/primefaces.*"));
final String fontPath = getResourcePathFromJarFile(new File(tgtJarPath), Pattern.compile(".*/fontawesome-webfont\\.ttf"));
assert fontPath.isEmpty() == false;
final InputStream is = Launcher.class.getClassLoader().getResourceAsStream(fontPath);
assert is != null;
Font font;
try {
font = Font.createFont(Font.TRUETYPE_FONT, is);
} catch (FontFormatException e) {
e.printStackTrace();
throw new Error(e);
} catch (IOException e) {
e.printStackTrace();
throw new Error(e);
}
return font.deriveFont(Font.PLAIN, 24f);
}
private static Point calcDrawPoint(Font font, String icon, int size, Graphics2D graphics) {
int center = size / 2; // Center X and Center Y are the same
Rectangle stringBounds = graphics.getFontMetrics().getStringBounds(icon, graphics).getBounds();
Rectangle visualBounds = font.createGlyphVector(graphics.getFontRenderContext(), icon).getVisualBounds().getBounds();
return new Point(center - stringBounds.width / 2, center - visualBounds.height / 2 - visualBounds.y);
}
private static Image createFontIcon(Font font, String code, Color clr) {
final int iconSize = 24;
final BufferedImage img = new BufferedImage(iconSize, iconSize, BufferedImage.TYPE_INT_ARGB);
final Graphics2D graphics = img.createGraphics();
graphics.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
graphics.setColor(clr);
graphics.setFont(font);
final String icon = code;
final Point pt = calcDrawPoint(font, icon, iconSize, graphics);
graphics.drawString(icon, pt.x, pt.y);
graphics.dispose();
return img;
}
private static void setupSystemTray() {
if (SystemTray.isSupported() == false)
return;
fontForIcon = createFont();
final Image img = createFontIcon(fontForIcon, "\uf19c", new Color(0xff, 0x0, 0x0));
EventQueue.invokeLater(
new Runnable() {
public void run() {
final SystemTray tray = SystemTray.getSystemTray();
assert tray != null;
assert img != null;
// final TrayIcon trayIcon = new TrayIcon(img, STARTING, null);
// trayIcon.setImageAutoSize(true);
// final JPopupMenu jpopup = new JPopupMenu();
// JMenuItem javaCupMI = new JMenuItem("Example", new ImageIcon("javacup.gif"));
// jpopup.add(javaCupMI);
// jpopup.addSeparator();
// JMenuItem exitMI = new JMenuItem("Exit");
// jpopup.add(exitMI);
// trayIcon.addMouseListener(new MouseAdapter() {
// public void mouseReleased(MouseEvent e) {
// if (e.getButton() == MouseEvent.BUTTON1) {
// jpopup.setLocation(e.getX(), e.getY());
// jpopup.setInvoker(null);
// jpopup.setVisible(true);
PopupMenu popup = new PopupMenu();
final TrayIcon trayIcon = new TrayIcon(img, STARTING, popup);
trayIcon.setImageAutoSize(true);
MenuItem item;
item = new MenuItem("\u2716 Shutdown");
item.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
tray.remove(trayIcon);
System.exit(0);
}
});
popup.add(item);
try {
tray.add(trayIcon);
} catch (AWTException e) {
e.printStackTrace();
throw new Error(e);
}
}
}
); // EventQueue.invokeLater()
}
private static void updateSystemTray() {
// We change appearance of the system tray icon to notify that the server is ready.
// Also add extra menus.
if (SystemTray.isSupported() == false)
return;
for (TrayIcon icon : SystemTray.getSystemTray().getTrayIcons()) {
if (icon.getToolTip().equals(STARTING)) {
assert fontForIcon != null;
final Image img = createFontIcon(fontForIcon, "\uf19c", new Color(0xf0, 0xff, 0xff));
icon.setImage(img);
icon.setToolTip(RUNNING);
MenuItem item = new MenuItem("\u270d Browse");
item.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
openBrowser();
}
});
icon.getPopupMenu().insert(item, 0);
break;
}
}
}
private static void openBrowser() {
if (System.getProperty(PORT).isEmpty() || ! System.getProperty(STATUS).equals(RUNNING))
return;
final String url = getCvzUrl();
try {
Desktop.getDesktop().browse(new URI(url));
} catch (IOException e1) {
e1.printStackTrace();
} catch (URISyntaxException e1) {
e1.printStackTrace();
}
}
private static void l(LogType type, String msg) {
System.out.println(MessageFormat.format("{0} : [{1}] {2}", Launcher.class.getSimpleName(), type.toString(), msg));
}
private Launcher(int port) {
assert 0 < port && port <= 0xffff;
server = new Server(port);
assert server != null;
this.port = port;
}
private boolean setupWebAppContextForDevelopment(WebAppContext waCtxt) {
if (!FsUtil.exists("pom.xml"))
return false;
final String webAppDir = FsUtil.concatPath("src", "main", "webapp");
final String tgtDir = "target";
final String webXmlFile = FsUtil.concatPath(webAppDir, "WEB-INF", "web.xml");
if (!FsUtil.exists(webAppDir) || !FsUtil.exists(tgtDir) || !FsUtil.exists(webXmlFile))
return false;
waCtxt.setBaseResource(new ResourceCollection(
new String[] { webAppDir, tgtDir }
));
waCtxt.setResourceAlias("/WEB-INF/classes/", "/classes/");
waCtxt.setDescriptor(webXmlFile);
l(LogType.INFO, "Running under the development environment...");
return true;
}
private boolean setupWebAppContextForProduction(WebAppContext waCtxt) {
final File usrDir = new File(System.getProperty("user.dir"));
final File[] pkgs = usrDir.listFiles(new FileFilter() {
@Override
public boolean accept(File pathname) {
return (pathname.isDirectory() && pathname.getName().startsWith("civilizer"));
}
});
for (File pkg : pkgs) {
final String pkgPath = pkg.getAbsolutePath();
if (FsUtil.exists(pkgPath, "WEB-INF", "web.xml") == false
|| FsUtil.exists(pkgPath, "WEB-INF", "classes") == false
|| FsUtil.exists(pkgPath, "WEB-INF", "lib") == false
)
continue;
waCtxt.setWar(pkgPath);
return true;
}
return false;
}
private WebAppContext setupWebAppContext() {
final WebAppContext waCtxt = new WebAppContext();
waCtxt.setContextPath("/civilizer");
if (! setupWebAppContextForProduction(waCtxt))
if (! setupWebAppContextForDevelopment(waCtxt))
return null;
return waCtxt;
}
private void startServer() throws Exception {
assert server != null;
final WebAppContext waCtxt = setupWebAppContext();
assert waCtxt != null;
server.setHandler(waCtxt);
server.setStopAtShutdown(true);
server.start();
System.setProperty(STATUS, RUNNING);
System.setProperty(PORT, new Integer(port).toString());
assert System.getProperty(PORT).equals(new Integer(port).toString());
l(LogType.INFO, "Civilizer is running... access to " + getCvzUrl());
updateSystemTray();
if (Configurator.isTrue(BROWSE_AT_STARTUP)) {
openBrowser();
}
server.join();
}
} |
package fr.monsieurfreezee.markovgenerator;
import java.io.*;
import java.nio.charset.Charset;
import java.util.HashMap;
public class Calculator {
public static void main(String args[]) throws IOException {
HashMap<String, Integer> probabilities = new HashMap<>();
// File to scan is program args[0]
BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream("src/" + args[0]), Charset.forName("UTF-8")));
reader.readLine(); // Discard file header
String line;
while ((line = reader.readLine()) != null) {
String word = line.split("\t")[0];
if (word.length() >= 2 && !word.contains("-") && !word.contains(" ")) {
System.err.print(word + ": \t\t\t");
for (int i = 0; i < word.length() + 1; i++) {
String letters = charAt(word, i - 2) + "" + charAt(word, i - 1) + ">" + charAt(word, i);
int characterOccurences = 1;
try { characterOccurences = probabilities.get(letters); }
catch (NullPointerException ignored) { }
probabilities.put(letters, characterOccurences + 1);
System.err.print(letters + " (" + characterOccurences + ") \t");
}
System.err.println("");
}
}
}
private static char charAt(String str, int index) {
try {
return str.charAt(index);
} catch (StringIndexOutOfBoundsException e) {
return '!';
}
}
} |
package org.voltdb.compilereport;
import java.io.IOException;
import java.net.URL;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.commons.lang3.StringUtils;
import org.voltdb.VoltDB;
import org.voltdb.VoltType;
import org.voltdb.catalog.Catalog;
import org.voltdb.catalog.CatalogMap;
import org.voltdb.catalog.Cluster;
import org.voltdb.catalog.Column;
import org.voltdb.catalog.ColumnRef;
import org.voltdb.catalog.Connector;
import org.voltdb.catalog.ConnectorTableInfo;
import org.voltdb.catalog.Constraint;
import org.voltdb.catalog.Database;
import org.voltdb.catalog.GroupRef;
import org.voltdb.catalog.Index;
import org.voltdb.catalog.ProcParameter;
import org.voltdb.catalog.Procedure;
import org.voltdb.catalog.Statement;
import org.voltdb.catalog.StmtParameter;
import org.voltdb.catalog.Table;
import org.voltdb.dtxn.SiteTracker;
import org.voltdb.types.ConstraintType;
import org.voltdb.types.IndexType;
import org.voltdb.utils.CatalogUtil;
import org.voltdb.utils.Encoder;
import org.voltdb.utils.PlatformProperties;
import org.voltdb.utils.SystemStatsCollector;
import com.google.common.base.Charsets;
import com.google.common.io.Resources;
public class ReportMaker {
static Date m_timestamp = new Date();
/**
* Make an html bootstrap tag with our custom css class.
*/
static void tag(StringBuilder sb, String color, String text) {
sb.append("<span class='label label");
if (color != null) {
sb.append("-").append(color);
}
String classText = text.replace(' ', '_');
sb.append(" l-").append(classText).append("'>").append(text).append("</span>");
}
static String genrateIndexRow(Table table, Index index) {
StringBuilder sb = new StringBuilder();
sb.append(" <tr class='primaryrow2'>");
// name column
String anchor = (table.getTypeName() + "-" + index.getTypeName()).toLowerCase();
sb.append("<td style='white-space: nowrap'><i id='s-" + anchor + "--icon' class='icon-chevron-right'></i> <a href='#' id='s-");
sb.append(anchor).append("' class='togglex'>");
sb.append(index.getTypeName());
sb.append("</a></td>");
// type column
sb.append("<td>");
sb.append(IndexType.get(index.getType()).toString());
sb.append("</td>");
// columns column
sb.append("<td>");
List<ColumnRef> cols = CatalogUtil.getSortedCatalogItems(index.getColumns(), "index");
List<String> columnNames = new ArrayList<String>();
for (ColumnRef colRef : cols) {
columnNames.add(colRef.getColumn().getTypeName());
}
sb.append(StringUtils.join(columnNames, ", "));
sb.append("</td>");
// uniqueness column
sb.append("<td>");
if (index.getUnique()) {
tag(sb, "important", "Unique");
}
else {
tag(sb, "info", "Multikey");
}
sb.append("</td>");
sb.append("</tr>\n");
// BUILD THE DROPDOWN FOR THE PLAN/DETAIL TABLE
sb.append("<tr class='dropdown2'><td colspan='5' id='s-"+ table.getTypeName().toLowerCase() +
"-" + index.getTypeName().toLowerCase() + "--dropdown'>\n");
IndexAnnotation annotation = (IndexAnnotation) index.getAnnotation();
if (annotation != null) {
if (annotation.proceduresThatUseThis.size() > 0) {
sb.append("<p>Used by procedures: ");
List<String> procs = new ArrayList<String>();
for (Procedure proc : annotation.proceduresThatUseThis) {
procs.add("<a href='#p-" + proc.getTypeName() + "'>" + proc.getTypeName() + "</a>");
}
sb.append(StringUtils.join(procs, ", "));
sb.append("</p>");
}
}
sb.append("</td></tr>\n");
return sb.toString();
}
static String generateIndexesTable(Table table) {
StringBuilder sb = new StringBuilder();
sb.append(" <table class='table tableL2 table-condensed'>\n <thead><tr>" +
"<th>Index Name</th>" +
"<th>Type</th>" +
"<th>Columns</th>" +
"<th>Uniqueness</th>" +
"</tr></thead>\n <tbody>\n");
for (Index index : table.getIndexes()) {
sb.append(genrateIndexRow(table, index));
}
sb.append(" </tbody>\n </table>\n");
return sb.toString();
}
static String generateSchemaRow(Table table, boolean isExportTable) {
StringBuilder sb = new StringBuilder();
sb.append("<tr class='primaryrow'>");
// column 1: table name
String anchor = table.getTypeName().toLowerCase();
sb.append("<td style='white-space: nowrap;'><i id='s-" + anchor + "--icon' class='icon-chevron-right'></i> <a href='#' id='s-");
sb.append(anchor).append("' class='togglex'>");
sb.append(table.getTypeName());
sb.append("</a></td>");
// column 2: type
sb.append("<td>");
if (table.getMaterializer() != null) {
tag(sb, "info", "Materialized View");
}
else {
if (isExportTable) {
tag(sb, null, "Export Table");
} else {
tag(sb, null, "Table");
}
}
sb.append("</td>");
// column 3: partitioning
sb.append("<td style='whitespace: nowrap;'>");
if (table.getIsreplicated()) {
tag(sb, "warning", "Replicated");
}
else {
tag(sb, "success", "Partitioned");
Column partitionCol = table.getPartitioncolumn();
if (partitionCol != null) {
sb.append("<small> on " + partitionCol.getName() + "</small>");
}
else {
Table matSrc = table.getMaterializer();
if (matSrc != null) {
sb.append("<small> with " + matSrc.getTypeName() + "</small>");
}
}
}
sb.append("</td>");
// column 4: column count
sb.append("<td>");
sb.append(table.getColumns().size());
sb.append("</td>");
// column 5: index count
sb.append("<td>");
sb.append(table.getIndexes().size());
sb.append("</td>");
// column 6: has pkey
sb.append("<td>");
boolean found = false;
for (Constraint constraint : table.getConstraints()) {
if (ConstraintType.get(constraint.getType()) == ConstraintType.PRIMARY_KEY) {
found = true;
break;
}
}
if (found) {
tag(sb, "info", "Has-PKey");
}
else {
tag(sb, null, "No-PKey");
}
sb.append("</td>");
sb.append("</tr>\n");
// BUILD THE DROPDOWN FOR THE DDL / INDEXES DETAIL
sb.append("<tr class='tablesorter-childRow'><td class='invert' colspan='6' id='s-"+ table.getTypeName().toLowerCase() + "--dropdown'>\n");
TableAnnotation annotation = (TableAnnotation) table.getAnnotation();
if (annotation != null) {
// output the DDL
if (annotation.ddl == null) {
sb.append("<p>MISSING DDL</p>\n");
}
else {
String ddl = annotation.ddl;
sb.append("<p><pre>" + ddl + "</pre></p>\n");
}
// make sure procs appear in only one category
annotation.proceduresThatReadThis.removeAll(annotation.proceduresThatUpdateThis);
if (annotation.proceduresThatReadThis.size() > 0) {
sb.append("<p>Read-only by procedures: ");
List<String> procs = new ArrayList<String>();
for (Procedure proc : annotation.proceduresThatReadThis) {
procs.add("<a href='#p-" + proc.getTypeName() + "'>" + proc.getTypeName() + "</a>");
}
sb.append(StringUtils.join(procs, ", "));
sb.append("</p>");
}
if (annotation.proceduresThatUpdateThis.size() > 0) {
sb.append("<p>Read/Write by procedures: ");
List<String> procs = new ArrayList<String>();
for (Procedure proc : annotation.proceduresThatUpdateThis) {
procs.add("<a href='#p-" + proc.getTypeName() + "'>" + proc.getTypeName() + "</a>");
}
sb.append(StringUtils.join(procs, ", "));
sb.append("</p>");
}
}
if (table.getIndexes().size() > 0) {
sb.append(generateIndexesTable(table));
}
else {
sb.append("<p>No indexes defined on table.</p>\n");
}
sb.append("</td></tr>\n");
return sb.toString();
}
static String generateSchemaTable(CatalogMap<Table> tables, CatalogMap<Connector> connectors) {
StringBuilder sb = new StringBuilder();
List<Table> exportTables = getExportTables(connectors);
for (Table table : tables) {
sb.append(generateSchemaRow(table, exportTables.contains(table) ? true : false));
}
return sb.toString();
}
static String genrateStatementRow(Procedure procedure, Statement statement) {
StringBuilder sb = new StringBuilder();
sb.append(" <tr class='primaryrow2'>");
// name column
String anchor = (procedure.getTypeName() + "-" + statement.getTypeName()).toLowerCase();
sb.append("<td style='white-space: nowrap'><i id='p-" + anchor + "--icon' class='icon-chevron-right'></i> <a href='#' id='p-");
sb.append(anchor).append("' class='togglex'>");
sb.append(statement.getTypeName());
sb.append("</a></td>");
// sql column
sb.append("<td><tt>");
sb.append(statement.getSqltext());
sb.append("</td></tt>");
// params column
sb.append("<td>");
List<StmtParameter> params = CatalogUtil.getSortedCatalogItems(statement.getParameters(), "index");
List<String> paramTypes = new ArrayList<String>();
for (StmtParameter param : params) {
paramTypes.add(VoltType.get((byte) param.getSqltype()).name());
}
if (paramTypes.size() == 0) {
sb.append("<i>None</i>");
}
sb.append(StringUtils.join(paramTypes, ", "));
sb.append("</td>");
// r/w column
sb.append("<td>");
if (statement.getReadonly()) {
tag(sb, "success", "Read");
}
else {
tag(sb, "warning", "Write");
}
sb.append("</td>");
// attributes
sb.append("<td>");
if (!statement.getIscontentdeterministic() || !statement.getIsorderdeterministic()) {
tag(sb, "inverse", "Determinism");
}
if (statement.getSeqscancount() > 0) {
tag(sb, "important", "Scans");
}
sb.append("</td>");
sb.append("</tr>\n");
// BUILD THE DROPDOWN FOR THE PLAN/DETAIL TABLE
sb.append("<tr class='dropdown2'><td colspan='5' id='p-"+ procedure.getTypeName().toLowerCase() +
"-" + statement.getTypeName().toLowerCase() + "--dropdown'>\n");
sb.append("<div class='well well-small'><h4>Explain Plan:</h4>\n");
StatementAnnotation annotation = (StatementAnnotation) statement.getAnnotation();
if (annotation != null) {
String plan = annotation.explainPlan;
plan = plan.replace("\n", "<br/>");
plan = plan.replace(" ", " ");
for (Table t : annotation.tablesRead) {
String name = t.getTypeName().toUpperCase();
String link = "\"<a href='#s-" + t.getTypeName() + "'>" + name + "</a>\"";
plan = plan.replace("\"" + name + "\"", link);
}
for (Table t : annotation.tablesUpdated) {
String name = t.getTypeName().toUpperCase();
String link = "\"<a href='#s-" + t.getTypeName() + "'>" + name + "</a>\"";
plan = plan.replace("\"" + name + "\"", link);
}
for (Index i : annotation.indexesUsed) {
Table t = (Table) i.getParent();
String name = i.getTypeName().toUpperCase();
String link = "\"<a href='#s-" + t.getTypeName() + "-" + i.getTypeName() +"'>" + name + "</a>\"";
plan = plan.replace("\"" + name + "\"", link);
}
sb.append("<tt>").append(plan).append("</tt>");
}
else {
sb.append("<i>No SQL explain plan found.</i>\n");
}
sb.append("</div>\n");
sb.append("</td></tr>\n");
return sb.toString();
}
static String generateStatementsTable(Procedure procedure) {
StringBuilder sb = new StringBuilder();
sb.append(" <table class='table tableL2 table-condensed'>\n <thead><tr>" +
"<th><span style='white-space: nowrap;'>Statement Name</span></th>" +
"<th>Statement SQL</th>" +
"<th>Params</th>" +
"<th>R/W</th>" +
"<th>Attributes</th>" +
"</tr></thead>\n <tbody>\n");
for (Statement statement : procedure.getStatements()) {
sb.append(genrateStatementRow(procedure, statement));
}
sb.append(" </tbody>\n </table>\n");
return sb.toString();
}
static String generateProcedureRow(Procedure procedure) {
StringBuilder sb = new StringBuilder();
sb.append("<tr class='primaryrow'>");
// column 1: procedure name
String anchor = procedure.getTypeName().toLowerCase();
sb.append("<td style='white-space: nowrap'><i id='p-" + anchor + "--icon' class='icon-chevron-right'></i> <a href='
sb.append(anchor).append("' id='p-").append(anchor).append("' class='togglex'>");
sb.append(procedure.getTypeName());
sb.append("</a></td>");
// column 2: parameter types
sb.append("<td>");
List<ProcParameter> params = CatalogUtil.getSortedCatalogItems(procedure.getParameters(), "index");
List<String> paramTypes = new ArrayList<String>();
for (ProcParameter param : params) {
String paramType = VoltType.get((byte) param.getType()).name();
if (param.getIsarray()) {
paramType += "[]";
}
paramTypes.add(paramType);
}
if (paramTypes.size() == 0) {
sb.append("<i>None</i>");
}
sb.append(StringUtils.join(paramTypes, ", "));
sb.append("</td>");
// column 3: partitioning
sb.append("<td>");
if (procedure.getSinglepartition()) {
tag(sb, "success", "Single");
}
else {
tag(sb, "warning", "Multi");
}
sb.append("</td>");
// column 4: read/write
sb.append("<td>");
if (procedure.getReadonly()) {
tag(sb, "success", "Read");
}
else {
tag(sb, "warning", "Write");
}
sb.append("</td>");
// column 5: access
sb.append("<td>");
List<String> groupNames = new ArrayList<String>();
for (GroupRef groupRef : procedure.getAuthgroups()) {
groupNames.add(groupRef.getGroup().getTypeName());
}
if (groupNames.size() == 0) {
sb.append("<i>None</i>");
}
sb.append(StringUtils.join(groupNames, ", "));
sb.append("</td>");
// column 6: attributes
sb.append("<td>");
if (procedure.getHasjava()) {
tag(sb, "info", "Java");
}
else {
tag(sb, null, "Single-Stmt");
}
boolean isND = false;
int scanCount = 0;
for (Statement stmt : procedure.getStatements()) {
scanCount += stmt.getSeqscancount();
if (!stmt.getIscontentdeterministic() || !stmt.getIsorderdeterministic()) {
isND = false;
}
}
if (isND) {
tag(sb, "inverse", "Determinism");
}
if (scanCount > 0) {
tag(sb, "important", "Scans");
}
sb.append("</td>");
sb.append("</tr>\n");
// BUILD THE DROPDOWN FOR THE STATEMENT/DETAIL TABLE
sb.append("<tr class='tablesorter-childRow'><td class='invert' colspan='6' id='p-"+ procedure.getTypeName().toLowerCase() + "--dropdown'>\n");
// output partitioning parameter info
if (procedure.getSinglepartition()) {
String pTable = procedure.getPartitioncolumn().getParent().getTypeName();
String pColumn = procedure.getPartitioncolumn().getTypeName();
int pIndex = procedure.getPartitionparameter();
sb.append(String.format("<p>Partitioned on parameter %d which maps to column %s" +
" of table <a class='invert' href='#s-%s'>%s</a>.</p>",
pIndex, pColumn, pTable, pTable));
}
// output what schema this interacts with
ProcedureAnnotation annotation = (ProcedureAnnotation) procedure.getAnnotation();
if (annotation != null) {
// make sure tables appear in only one category
annotation.tablesRead.removeAll(annotation.tablesUpdated);
if (annotation.tablesRead.size() > 0) {
sb.append("<p>Read-only access to tables: ");
List<String> tables = new ArrayList<String>();
for (Table table : annotation.tablesRead) {
tables.add("<a href='#s-" + table.getTypeName() + "'>" + table.getTypeName() + "</a>");
}
sb.append(StringUtils.join(tables, ", "));
sb.append("</p>");
}
if (annotation.tablesUpdated.size() > 0) {
sb.append("<p>Read/Write access to tables: ");
List<String> tables = new ArrayList<String>();
for (Table table : annotation.tablesUpdated) {
tables.add("<a href='#s-" + table.getTypeName() + "'>" + table.getTypeName() + "</a>");
}
sb.append(StringUtils.join(tables, ", "));
sb.append("</p>");
}
if (annotation.indexesUsed.size() > 0) {
sb.append("<p>Uses indexes: ");
List<String> indexes = new ArrayList<String>();
for (Index index : annotation.indexesUsed) {
Table table = (Table) index.getParent();
indexes.add("<a href='#s-" + table.getTypeName() + "-" + index.getTypeName() + "'>" + index.getTypeName() + "</a>");
}
sb.append(StringUtils.join(indexes, ", "));
sb.append("</p>");
}
}
sb.append(generateStatementsTable(procedure));
sb.append("</td></tr>\n");
return sb.toString();
}
static String generateProceduresTable(CatalogMap<Procedure> procedures) {
StringBuilder sb = new StringBuilder();
for (Procedure procedure : procedures) {
if (procedure.getDefaultproc()) {
continue;
}
sb.append(generateProcedureRow(procedure));
}
return sb.toString();
}
/**
* Get some embeddable HTML of some generic catalog/application stats
* that is drawn on the first page of the report.
*/
static String getStatsHTML(Database db) {
StringBuilder sb = new StringBuilder();
sb.append("<table class='table table-condensed'>\n");
// count things
int indexes = 0, views = 0, statements = 0;
int partitionedTables = 0, replicatedTables = 0;
int partitionedProcs = 0, replicatedProcs = 0;
int readProcs = 0, writeProcs = 0;
for (Table t : db.getTables()) {
if (t.getMaterializer() != null) {
views++;
}
else {
if (t.getIsreplicated()) {
replicatedTables++;
}
else {
partitionedTables++;
}
}
indexes += t.getIndexes().size();
}
for (Procedure p : db.getProcedures()) {
// skip auto-generated crud procs
if (p.getDefaultproc()) {
continue;
}
if (p.getSinglepartition()) {
partitionedProcs++;
}
else {
replicatedProcs++;
}
if (p.getReadonly()) {
readProcs++;
}
else {
writeProcs++;
}
statements += p.getStatements().size();
}
// version
sb.append("<tr><td>Compiled by VoltDB Version</td><td>");
sb.append(VoltDB.instance().getVersionString()).append("</td></tr>\n");
// timestamp
sb.append("<tr><td>Compiled on</td><td>");
SimpleDateFormat sdf = new SimpleDateFormat("EEE, d MMM yyyy HH:mm:ss z");
sb.append(sdf.format(m_timestamp)).append("</td></tr>\n");
// tables
sb.append("<tr><td>Table Count</td><td>");
sb.append(String.format("%d (%d partitioned / %d replicated)",
partitionedTables + replicatedTables, partitionedTables, replicatedTables));
sb.append("</td></tr>\n");
// views
sb.append("<tr><td>Materialized View Count</td><td>").append(views).append("</td></tr>\n");
// indexes
sb.append("<tr><td>Index Count</td><td>").append(indexes).append("</td></tr>\n");
// procedures
sb.append("<tr><td>Procedure Count</td><td>");
sb.append(String.format("%d (%d partitioned / %d replicated) (%d read-only / %d read-write)",
partitionedProcs + replicatedProcs, partitionedProcs, replicatedProcs,
readProcs, writeProcs));
sb.append("</td></tr>\n");
// statements
sb.append("<tr><td>SQL Statement Count</td><td>").append(statements).append("</td></tr>\n");
sb.append("</table>\n");
return sb.toString();
}
/**
* Generate the HTML catalog report from a newly compiled VoltDB catalog
*/
public static String report(Catalog catalog) throws IOException {
// asynchronously get platform properties
new Thread() {
@Override
public void run() {
PlatformProperties.getPlatformProperties();
}
}.start();
URL url = Resources.getResource(ReportMaker.class, "template.html");
String contents = Resources.toString(url, Charsets.UTF_8);
Cluster cluster = catalog.getClusters().get("cluster");
assert(cluster != null);
Database db = cluster.getDatabases().get("database");
assert(db != null);
String statsData = getStatsHTML(db);
contents = contents.replace("##STATS##", statsData);
String schemaData = generateSchemaTable(db.getTables(), db.getConnectors());
contents = contents.replace("##SCHEMA##", schemaData);
String procData = generateProceduresTable(db.getProcedures());
contents = contents.replace("##PROCS##", procData);
String platformData = PlatformProperties.getPlatformProperties().toHTML();
contents = contents.replace("##PLATFORM##", platformData);
contents = contents.replace("##VERSION##", VoltDB.instance().getVersionString());
DateFormat df = new SimpleDateFormat("d MMM yyyy HH:mm:ss z");
contents = contents.replace("##TIMESTAMP##", df.format(m_timestamp));
String msg = Encoder.hexEncode(VoltDB.instance().getVersionString() + "," + System.currentTimeMillis());
contents = contents.replace("get.py?a=KEY&", String.format("get.py?a=%s&", msg));
return contents;
}
private static List<Table> getExportTables(CatalogMap<Connector> connectors) {
List<Table> retval = new ArrayList<Table>();
for (Connector conn : connectors) {
for (ConnectorTableInfo cti : conn.getTableinfo()) {
retval.add(cti.getTable());
}
}
return retval;
}
public static String getLiveSystemOverview()
{
// get the start time
long t = SystemStatsCollector.getStartTime();
Date date = new Date(t);
long duration = System.currentTimeMillis() - t;
long minutes = duration / 60000;
long hours = minutes / 60; minutes -= hours * 60;
long days = hours / 24; hours -= days * 24;
String starttime = String.format("%s (%dd %dh %dm)",
date.toString(), days, hours, minutes);
// handle the basic info page below this
SiteTracker st = VoltDB.instance().getSiteTrackerForSnapshot();
// get the cluster info
String clusterinfo = st.getAllHosts().size() + " hosts ";
clusterinfo += " with " + st.getAllSites().size() + " sites ";
clusterinfo += " (" + st.getAllSites().size() / st.getAllHosts().size();
clusterinfo += " per host)";
StringBuilder sb = new StringBuilder();
sb.append("<table class='table table-condensed'>\n");
sb.append("<tr><td>Mode </td><td>" + VoltDB.instance().getMode().toString() + "</td><td>\n");
sb.append("<tr><td>VoltDB Version </td><td>" + VoltDB.instance().getVersionString() + "</td><td>\n");
sb.append("<tr><td>Buildstring </td><td>" + VoltDB.instance().getBuildString() + "</td><td>\n");
sb.append("<tr><td>Cluster Composition </td><td>" + clusterinfo + "</td><td>\n");
sb.append("<tr><td>Running Since </td><td>" + starttime + "</td><td>\n");
sb.append("</table>\n");
return sb.toString();
}
/**
* Find the pre-compild catalog report in the jarfile, and modify it for use in the
* the built-in web portal.
*/
public static String liveReport() {
byte[] reportbytes = VoltDB.instance().getCatalogContext().getFileInJar("catalog-report.html");
String report = new String(reportbytes, Charsets.UTF_8);
// remove commented out code
report = report.replace("<!--##RESOURCES", "");
report = report.replace("##RESOURCES-->", "");
// inject the cluster overview
String clusterStr = "<h4>System Overview</h4>\n<p>" + getLiveSystemOverview() + "</p><br/>\n";
report = report.replace("<!--##CLUSTER##-->", clusterStr);
// inject the running system platform properties
PlatformProperties pp = PlatformProperties.getPlatformProperties();
String ppStr = "<h4>Cluster Platform</h4>\n<p>" + pp.toHTML() + "</p><br/>\n";
report = report.replace("<!--##PLATFORM2##-->", ppStr);
// change the live/static var to live
if (VoltDB.instance().getConfig().m_isEnterprise) {
report = report.replace("&b=r&", "&b=e&");
}
else {
report = report.replace("&b=r&", "&b=c&");
}
return report;
}
} |
package cc.mallet.fst;
import java.util.ArrayList;
import java.util.Collections;
import cc.mallet.fst.TransducerTrainer.ByInstanceIncrements;
import cc.mallet.types.FeatureVectorSequence;
import cc.mallet.types.Instance;
import cc.mallet.types.InstanceList;
import cc.mallet.types.Sequence;
/**
* Trains CRF by stochastic gradient. Most effective on large training sets.
*
* @author kedarb
*
*/
public class CRFTrainerByStochasticGradient extends ByInstanceIncrements {
CRF crf;
// t is the decaying factor. lambda is some regularization depending on the
// training set size and the gaussian prior.
double learningRate, t, lambda;
int iterationCount = 0;
boolean converged = false;
CRF.Factors expectations, constraints;
public CRFTrainerByStochasticGradient(CRF crf, double learningRate) {
this.crf = crf;
this.learningRate = learningRate;
this.expectations = new CRF.Factors(crf);
this.constraints = new CRF.Factors(crf);
}
public int getIteration() {
return iterationCount;
}
public Transducer getTransducer() {
return crf;
}
public boolean isFinishedTraining() {
return converged;
}
// Best way to choose learning rate is to run training on a sample and set
// it to the rate that produces maximum increase in likelihood or accuracy.
// Then, to be conservative just halve the learning rate.
// In general, eta = 1/(lambda*t) where
// lambda=priorVariance*numTrainingInstances
// After an initial eta_0 is set, t_0 = 1/(lambda*eta_0)
// After each training step eta = 1/(lambda*(t+t_0)), t=0,1,2,..,Infinity
/** Automatically set the learning rate to one that would be good */
public void setLearningRateByLikelihood (InstanceList trainingSample) {
int numIterations = 10;
double bestLearningRate = Double.NEGATIVE_INFINITY;
double bestLikelihoodChange = Double.NEGATIVE_INFINITY;
double currLearningRate = 5e-11;
while (currLearningRate < 1) {
currLearningRate *= 2;
crf.parameters.zero();
double beforeLikelihood = computeLikelihood(trainingSample);
double likelihoodChange = trainSample(trainingSample,
numIterations, currLearningRate)
- beforeLikelihood;
System.out.println("likelihood change = " + likelihoodChange
+ " for eta=" + currLearningRate);
if (likelihoodChange > bestLikelihoodChange) {
bestLikelihoodChange = likelihoodChange;
bestLearningRate = currLearningRate;
}
}
// reset the parameters
crf.parameters.zero();
// conservative estimate for learning rate
bestLearningRate /= 2;
System.out.println("Setting learning rate to " + bestLearningRate);
setLearningRate(bestLearningRate);
}
private double trainSample(InstanceList trainingSample, int numIterations,
double rate) {
double lambda = trainingSample.size();
double t = 1 / (lambda * rate);
double loglik = Double.NEGATIVE_INFINITY;
for (int i = 0; i < numIterations; i++) {
loglik = 0.0;
for (int j = 0; j < trainingSample.size(); j++) {
rate = 1 / (lambda * t);
loglik += trainSingle(trainingSample.get(j), rate);
t += 1.0;
}
}
return loglik;
}
private double computeLikelihood(InstanceList trainingSample) {
double loglik = 0.0;
for (int i = 0; i < trainingSample.size(); i++) {
Instance trainingInstance = trainingSample.get(i);
FeatureVectorSequence fvs = (FeatureVectorSequence) trainingInstance
.getData();
Sequence labelSequence = (Sequence) trainingInstance.getTarget();
loglik += new SumLatticeDefault(crf, fvs, labelSequence,
constraints.new Incrementor()).getTotalWeight();
loglik -= new SumLatticeDefault(crf, fvs, null,
expectations.new Incrementor()).getTotalWeight();
}
constraints.zero();
expectations.zero();
return loglik;
}
public void setLearningRate(double r) {
this.learningRate = r;
}
public double getLearningRate() {
return this.learningRate;
}
public boolean train(InstanceList trainingSet, int numIterations) {
assert (expectations.structureMatches(crf.parameters));
assert (constraints.structureMatches(crf.parameters));
lambda = 1.0 / trainingSet.size();
t = 1.0 / (lambda * learningRate);
converged = false;
ArrayList<Integer> trainingIndices = new ArrayList<Integer>();
for (int i = 0; i < trainingSet.size(); i++)
trainingIndices.add(i);
double oldLoglik = Double.NEGATIVE_INFINITY;
while (numIterations
iterationCount++;
// shuffle the indices
Collections.shuffle(trainingIndices);
double loglik = 0.0;
for (int i = 0; i < trainingSet.size(); i++) {
learningRate = 1.0 / (lambda * t);
loglik += trainSingle(trainingSet.get(trainingIndices.get(i)));
t += 1.0;
}
System.out.println("loglikelihood[" + numIterations + "] = "
+ loglik);
if (Math.abs(loglik - oldLoglik) < 1e-3) {
converged = true;
break;
}
oldLoglik = loglik;
runEvaluators();
}
return converged;
}
// TODO Add some way to train by batches of instances, where the batch
// memberships are determined externally
public boolean trainIncremental(InstanceList trainingSet) {
this.train(trainingSet, 1);
return false;
}
public boolean trainIncremental(Instance trainingInstance) {
assert (expectations.structureMatches(crf.parameters));
trainSingle(trainingInstance);
return false;
}
private double trainSingle(Instance trainingInstance) {
return trainSingle(trainingInstance, learningRate);
}
private double trainSingle(Instance trainingInstance, double rate) {
double singleLoglik = 0.0;
constraints.zero();
expectations.zero();
FeatureVectorSequence fvs = (FeatureVectorSequence) trainingInstance
.getData();
Sequence labelSequence = (Sequence) trainingInstance.getTarget();
singleLoglik += new SumLatticeDefault(crf, fvs, labelSequence,
constraints.new Incrementor()).getTotalWeight();
singleLoglik -= new SumLatticeDefault(crf, fvs, null,
expectations.new Incrementor()).getTotalWeight();
// Calculate parameter gradient given these instances:
// (constraints - expectations)
constraints.plusEquals(expectations, -1);
// Change the parameters a little by this difference,
// obeying weightsFrozen
crf.parameters.plusEquals(constraints, rate, true);
return singleLoglik;
}
} |
package com.corner23.android.i9000.notifier;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.preference.PreferenceActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class Settings extends PreferenceActivity
implements ColorPickerDialog.OnColorChangedListener {
public static final String SHARED_PREFS_NAME = "men_settings";
public static final String PREF_ENABLE = "enable";
public static final String PREF_APPEARANCE = "appearance";
public static final String PREF_DISPLAY_INTERVAL = "display_interval";
public static final String PREF_DOT_COLOR = "dot_color";
public static final int PREF_APPEARANCE_DOT = 0;
public static final int PREF_APPEARANCE_LED = 1;
TextView mTextView = null;
@Override
protected void onCreate(Bundle icicle) {
super.onCreate(icicle);
getPreferenceManager().setSharedPreferencesName(SHARED_PREFS_NAME);
addPreferencesFromResource(R.xml.preferences);
setContentView(R.layout.settings);
Button colorPicker = (Button) findViewById(R.id.ColorPicker);
colorPicker.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
int color =
Settings.this.getSharedPreferences(SHARED_PREFS_NAME, 0).getInt(PREF_DOT_COLOR, Color.RED);
new ColorPickerDialog(Settings.this, Settings.this, color).show();
}
});
mTextView = (TextView) findViewById(R.id.Preview);
mTextView.setBackgroundColor(getSharedPreferences(SHARED_PREFS_NAME, 0).getInt(PREF_DOT_COLOR, Color.RED));
}
@Override
public void colorChanged(int color) {
Settings.this.getSharedPreferences(SHARED_PREFS_NAME, 0).edit().putInt(PREF_DOT_COLOR, color).commit();
mTextView.setBackgroundColor(color);
}
@Override
protected void onPause() {
Log.d("Settings", "onPause");
super.onPause();
// start service to trigger on/off
Intent serviceIntent = new Intent(this, MissEventNotifierService.class);
startService(serviceIntent);
}
} |
package com.github.andlyticsproject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.lang.reflect.Field;
import java.net.ProtocolException;
import java.net.SocketException;
import java.net.URI;
import java.net.URL;
import java.net.URLEncoder;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.StringTokenizer;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.net.ssl.HttpsURLConnection;
import org.apache.http.Header;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.HttpVersion;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.params.HttpClientParams;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.scheme.PlainSocketFactory;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.AllowAllHostnameVerifier;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.client.RedirectLocations;
import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.params.HttpProtocolParams;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.HTTP;
import org.apache.http.protocol.HttpContext;
import org.apache.http.util.EntityUtils;
import org.json.JSONException;
import org.json.JSONObject;
import android.content.Context;
import android.util.Log;
import com.github.andlyticsproject.exception.AuthenticationException;
import com.github.andlyticsproject.exception.DeveloperConsoleException;
import com.github.andlyticsproject.exception.InvalidJSONResponseException;
import com.github.andlyticsproject.exception.MultiAccountAcception;
import com.github.andlyticsproject.exception.NetworkException;
import com.github.andlyticsproject.exception.NoCookieSetException;
import com.github.andlyticsproject.exception.SignupException;
import com.github.andlyticsproject.gwt.Base64Utils;
import com.github.andlyticsproject.gwt.GwtParser;
import com.github.andlyticsproject.model.AppInfo;
import com.github.andlyticsproject.model.Comment;
public class DeveloperConsole {
private static final String GWT_PERMUTATION = "6D75CBE66FE85272BB1AD2C64A98B720";
//"com.github.andlyticsproject", but it seems "Andlytics"
private static final String PARAM_APPNAME = "<<appname>>";
private static final String PARAM_XSRFTOKEN = "<<xsrftoken>>";
private static final String PARAM_PACKAGELIST = "<<packagelist>>";
private static final String PARAM_STARTINDEX = "<<start>>";
private static final String PARAM_LENGTH = "<<length>>";
private static final long PARAM_MAX_APPS_NUMBER = 9;
public static final String ACCOUNT_TYPE = "GOOGLE";
public static final String SERVICE = "androiddeveloper";
private static final String URL_GOOGLE_LOGIN = "https:
private static final String URL_DEVELOPER_CONSOLE = "https://play.google.com/apps/publish";
private static final String URL_DEVELOPER_EDIT_APP = "https://play.google.com/apps/publish/editapp";
private static final String URL_COMMENTS = "https://play.google.com/apps/publish/comments";
private static final String URL_FEEDBACK = "https://play.google.com/apps/publish/feedback";
private static final String GET_FULL_ASSET_INFO_FOR_USER_REQUEST = "7|2|9|https://play.google.com/apps/publish/gwt/|3DF4994263B7BFE1C6E2AB34E241C0F5|com.google.gwt.user.client.rpc.XsrfToken/4254043109|"+PARAM_XSRFTOKEN+"|com.google.wireless.android.vending.developer.shared.AppEditorService|getProductInfosForUser|java.lang.String/2004016611|I|"+PARAM_APPNAME+"|1|2|3|4|5|6|4|7|8|8|7|9|0|4|0|";
private static final String GET_ASSET_FOR_USER_COUNT_REQUEST = "7|0|4|https://play.google.com/apps/publish/gwt/|11B29A336607683DE538737452FFF924|com.google.wireless.android.vending.developer.shared.AppEditorService|getAssetForUserCount|1|2|3|4|0|";
private static final String GET_USER_COMMENTS_REQUEST = "7|2|11|https://play.google.com/apps/publish/gwt/|3B4252B1EA6FFDBEAC02B41B3975C468|com.google.gwt.user.client.rpc.XsrfToken/4254043109|"+PARAM_XSRFTOKEN+"|com.google.wireless.android.vending.developer.shared.CommentsService|getUserComments|java.lang.String/2004016611|J|java.lang.Iterable|"+PARAM_APPNAME+"|java.util.ArrayList/4159755760|1|2|3|4|5|6|7|7|8|8|9|9|9|7|10|"+PARAM_STARTINDEX+"|"+PARAM_LENGTH+"|11|0|11|0|11|0|0|";
private static final String GET_FEEDBACK_OVERVIEW = "7|0|6|https://play.google.com/apps/publish/gwt/|8A88A8C8E8E60107C7E013322C6CE8F2|com.google.wireless.android.vending.developer.shared.FeedbackService|getOverviewsForPackages|com.google.protos.userfeedback.gwt.AndroidFrontend$AndroidPackageListRequest$Json/4146859527|[,[<<packagelist>>] ] |1|2|3|4|1|5|5|6|";
private String cookie;
private String devacc;
private Context context;
private String cookieAuthtoken;
private String postData;
public DeveloperConsole(Context context) {
this.context = context;
}
public List<AppInfo> getAppDownloadInfos(String authtoken, String accountName) throws NetworkException, InvalidJSONResponseException, DeveloperConsoleException, SignupException, AuthenticationException, NoCookieSetException, MultiAccountAcception {
return getFullAssetListRequest(accountName, authtoken, false);
}
private List<AppInfo> getFullAssetListRequest(String accountName, String authtoken, boolean reuseAuthentication) throws NetworkException, DeveloperConsoleException, InvalidJSONResponseException, SignupException, AuthenticationException, NoCookieSetException, MultiAccountAcception{
developerConsoleAuthentication(authtoken, reuseAuthentication);
String json = grapAppStatistics();
List<AppInfo> result = parseAppStatisticsResponse(json, accountName);
// user with more than 9 apps
/*
if(PARAM_MAX_APPS_NUMBER == result.size()) {
// test how many apps there are
json = grepGetAssetForUserCount();
long numberOfApps = parseGetAssetForUserCount(json);
// get 9 for number of apps
boolean stop = false;
while(result.size() < numberOfApps && !stop) {
json = grapAppStatistics(result.size(), PARAM_MAX_APPS_NUMBER);
List<AppInfo> subresult = parseAppStatisticsResponse(json, accountName);
result.addAll(subresult);
if(subresult.size() < PARAM_MAX_APPS_NUMBER) {
stop = true;
}
}
}
*/
List<String> packageNames = new ArrayList<String>();
// remove drafts from result
Iterator<AppInfo> iterator = result.iterator();
while (iterator.hasNext()) {
AppInfo appInfo = (AppInfo) iterator.next();
if(appInfo.isDraftOnly()) {
iterator.remove();
} else {
packageNames.add(appInfo.getPackageName());
}
}
// get feedback
/*
if(packageNames.size() > 0) {
String feedbackJson = grapFeedbackOverview(packageNames);
Map<String, Integer> errorMap = parseFeedbackOverviewResponse(feedbackJson);
for (AppInfo appInfo: result) {
Integer errors = errorMap.get(appInfo.getPackageName());
if(errors != null) {
appInfo.setNumberOfErrors(errors);
}
}
}*/
return result;
}
public List<Comment> getAppComments(String authtoken, String accountName, String packageName, int startIndex, int lenght) throws NetworkException,
DeveloperConsoleException, InvalidJSONResponseException, SignupException, AuthenticationException, NoCookieSetException, MultiAccountAcception {
List<Comment> result = null;
try {
developerConsoleAuthentication(authtoken, true);
String json = grapComments(packageName, startIndex, lenght);
result = parseCommentsResponse(json, accountName);
} catch (DeveloperConsoleException e) {
developerConsoleAuthentication(authtoken, false);
String json = grapComments(packageName, startIndex, lenght);
result = parseCommentsResponse(json, accountName);
}
return result;
}
public List<AppInfo> parseAppStatisticsResponse(String json, String accountName) throws DeveloperConsoleException,
InvalidJSONResponseException, AuthenticationException {
List<AppInfo> result = new ArrayList<AppInfo>();
testIfJsonIsValid(json);
GwtParser parser = new GwtParser(json);
result = parser.getAppInfos(accountName);
return result;
}
public Map<String, Integer> parseFeedbackOverviewResponse(String json) throws DeveloperConsoleException,
InvalidJSONResponseException, AuthenticationException {
Map<String, Integer> result = new HashMap<String, Integer>();
testIfJsonIsValid(json);
GwtParser parser = new GwtParser(json);
result = parser.getFeedbackOverview();
return result;
}
private long parseGetAssetForUserCount(String json) throws InvalidJSONResponseException, AuthenticationException {
long result = 0;
testIfJsonIsValid(json);
GwtParser parser = new GwtParser(json);
result = parser.getAppInfoSize();
return result;
}
private void testIfJsonIsValid(String json) throws InvalidJSONResponseException, AuthenticationException {
if (json == null || !json.startsWith("
if(json != null && (json.indexOf("NewServiceAccount") > -1 || json.indexOf("WrongUserException") > -1)) {
throw new AuthenticationException();
}
throw new InvalidJSONResponseException("Invalid JSON response", json);
}
}
public List<Comment> parseCommentsResponse(String json, String accountName) throws DeveloperConsoleException, AuthenticationException {
List<Comment> result = new ArrayList<Comment>();
try {
testIfJsonIsValid(json);
} catch (InvalidJSONResponseException e) {
DeveloperConsoleException de = new DeveloperConsoleException(postData + "response::" + json,e);
throw de;
}
try {
GwtParser parser = new GwtParser(json);
result = parser.getComments();
} catch (Exception e) {
throw new RuntimeException(postData + "response::" + json, e);
}
return result;
}
protected boolean isInteger(String string) {
boolean result = true;
try {
Integer.parseInt(string);
} catch (NumberFormatException e) {
result = false;
}
return result;
}
protected String grapAppStatistics() throws DeveloperConsoleException {
return grapAppStatistics(0, PARAM_MAX_APPS_NUMBER);
}
private String grapAppStatistics(int startIndex, long lenght) throws DeveloperConsoleException {
String developerPostData = Preferences.getRequestFullAssetInfo(context);
if (developerPostData == null) {
developerPostData = GET_FULL_ASSET_INFO_FOR_USER_REQUEST;
}
String startIndexString = Base64Utils.toBase64(startIndex);
String lengthString = Base64Utils.toBase64(lenght);
String xsrfToken = ((AndlyticsApp) context.getApplicationContext()).getXsrfToken();
developerPostData = developerPostData.replace(PARAM_STARTINDEX, startIndexString);
developerPostData = developerPostData.replace(PARAM_LENGTH, lengthString);
developerPostData = developerPostData.replace(PARAM_XSRFTOKEN, xsrfToken!=null ? xsrfToken:"");
String result = null;
try {
URL aURL = new java.net.URL(URL_DEVELOPER_EDIT_APP + "?dev_acc=" + devacc);
result = getGwtRpcResponse(developerPostData, aURL);
} catch (Exception f) {
throw new DeveloperConsoleException(result, f);
}
return result;
}
private String grepGetAssetForUserCount() throws DeveloperConsoleException {
String result = null;
String postData = Preferences.getRequestGetAssetForUserCount(context);
if (postData == null) {
postData = GET_ASSET_FOR_USER_COUNT_REQUEST;
}
try {
URL aURL = new java.net.URL(URL_DEVELOPER_EDIT_APP);
result = getGwtRpcResponse(postData, aURL);
} catch (Exception f) {
throw new DeveloperConsoleException(postData, f);
}
return result;
}
private String getGwtPermutation() {
String gwtPermutation = Preferences.getGwtPermutation(context);
if (gwtPermutation == null) {
gwtPermutation = GWT_PERMUTATION;
}
return gwtPermutation;
}
protected String grapComments(String packageName, int startIndex, int lenght) throws DeveloperConsoleException {
String postData = Preferences.getRequestUserComments(context);
if (postData == null) {
postData = GET_USER_COMMENTS_REQUEST;
}
String startIndexString = Base64Utils.toBase64(startIndex);
String lengthString = Base64Utils.toBase64(lenght);
String xsrfToken = ((AndlyticsApp) context.getApplicationContext()).getXsrfToken();
postData = postData.replace(PARAM_APPNAME, packageName);
postData = postData.replace(PARAM_STARTINDEX, startIndexString);
postData = postData.replace(PARAM_LENGTH, lengthString);
postData = postData.replace(PARAM_XSRFTOKEN, xsrfToken!=null ? xsrfToken:"");
String result = null;
this.postData = postData;
try {
URL aURL = new java.net.URL(URL_COMMENTS + "?dev_acc=" + devacc);
result = getGwtRpcResponse(postData, aURL);
} catch (Exception f) {
throw new DeveloperConsoleException(result, f);
}
return result;
}
protected String grapFeedbackOverview(List<String> packageNames) throws DeveloperConsoleException {
String postData = Preferences.getRequestFeedback(context);
if (postData == null) {
postData = GET_FEEDBACK_OVERVIEW;
}
String jsonList = "";
for (int i = 0; i < packageNames.size(); i++) {
if (i != 0) {
jsonList += ",";
}
jsonList += "\"" + packageNames.get(i) + "\"";
}
postData = postData.replace(PARAM_PACKAGELIST, jsonList);
System.out.println("feedback post request: " + postData);
String result = null;
this.postData = postData;
try {
URL aURL = new java.net.URL(URL_FEEDBACK);
result = getGwtRpcResponse(postData, aURL);
} catch (Exception f) {
throw new DeveloperConsoleException(result, f);
}
return result;
}
private String getGwtRpcResponse(String developerPostData, URL aURL) throws IOException,
ProtocolException {
String result;
HttpsURLConnection connection = (HttpsURLConnection) aURL.openConnection();
connection.setHostnameVerifier(new AllowAllHostnameVerifier());
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setRequestMethod("POST");
connection.setConnectTimeout(4000);
connection.setRequestProperty("Host", "play.google.com");
connection.setRequestProperty("User-Agent",
"Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10.6; de; rv:1.9.2.13) Gecko/20101203 Firefox/3.6.13");
connection.setRequestProperty("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
connection.setRequestProperty("Accept-Language", "en-us,en;q=0.5");
connection.setRequestProperty("Accept-Charset", "ISO-8859-1,utf-8;q=0.7,*;q=0.7");
connection.setRequestProperty("Keep-Alive", "115");
connection.setRequestProperty("Cookie", cookie);
connection.setRequestProperty("Connection", "keep-alive");
connection.setRequestProperty("Content-Type", "text/x-gwt-rpc; charset=utf-8");
connection.setRequestProperty("X-GWT-Permutation", getGwtPermutation());
connection.setRequestProperty("X-GWT-Module-Base", "https://play.google.com/apps/publish/gwt-play/");
connection.setRequestProperty("Referer", "https://play.google.com/apps/publish/Home");
OutputStreamWriter streamToAuthorize = new java.io.OutputStreamWriter(connection.getOutputStream());
streamToAuthorize.write(developerPostData);
streamToAuthorize.flush();
streamToAuthorize.close();
// Get the Response from Autorize.net
InputStream resultStream = connection.getInputStream();
BufferedReader aReader = new java.io.BufferedReader(new java.io.InputStreamReader(resultStream));
StringBuffer aResponse = new StringBuffer();
String aLine = aReader.readLine();
while (aLine != null) {
aResponse.append(aLine + "\n");
aLine = aReader.readLine();
}
resultStream.close();
result = aResponse.toString();
return result;
}
protected void developerConsoleAuthentication(String authtoken, boolean reuseAuthentication) throws NetworkException, SignupException, AuthenticationException, NoCookieSetException, MultiAccountAcception {
// login to Android Market
// this results in a 302
// and is necessary for a cookie to be set
// authtoken = "DQAAAMsAAAA6XRgg47KgvSY9AaQ32d9hOAglYRoW9oJmwd4HxZvMicVeWFciKp5MgyXVDMCxd-xSfgmEeUl-9YFGuVsbAGJI5t09gBioQBb758jCxJbHmzd8utW7tQcK1VtVS4zkRDF_eUzN7KgyDU7AYt8wDsg9Gm8YYAB7vkhIlCGTWNCcvgYnewszM2giu-mOlcaKKjgUW5yiQj3xdZo77CTaZkj5LNeVaCSYF2s_QRKqNkIgXp2jFPQtzFHaGZ76QG4SNq6vKVaD61LF2lswgnPEnSNS";
this.cookieAuthtoken = authtoken;
HttpClient httpclient = null;
try {
if(!reuseAuthentication) {
cookie = null;
}
// reuse cookie for performance
if(cookie == null || cookieAuthtoken == null || !cookieAuthtoken.equals(authtoken)) {
String cookie1 = null;
HttpGet httpget = new HttpGet(URL_DEVELOPER_CONSOLE + "?auth=" + authtoken);
//httpget.setHeader("Authorization", "GoogleLogin auth=" + auth);
HttpParams params = new BasicHttpParams();
HttpClientParams.setRedirecting(params, true);
HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);
HttpProtocolParams.setUseExpectContinue(params, true);
SSLSocketFactory sf = SSLSocketFactory.getSocketFactory();
sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
SchemeRegistry schReg = new SchemeRegistry();
schReg.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
schReg.register(new Scheme("https", sf, 443));
ClientConnectionManager conMgr = new ThreadSafeClientConnManager(params, schReg);
int timeoutSocket = 30 * 1000;
HttpConnectionParams.setSoTimeout(params, timeoutSocket);
HttpContext context = new BasicHttpContext();
httpclient = new DefaultHttpClient(conMgr, params);
HttpResponse httpResponse = httpclient.execute(httpget, context);
// 8p8 fix for xsrfToken
Matcher m1 = Pattern.compile("userInfo = (\\{.+\\});").matcher(EntityUtils.toString(httpResponse.getEntity()));
if (m1.find()) {
String xsrfToken = new JSONObject(m1.group(1)).getString("gwtRpcXsrfToken");
((AndlyticsApp) this.context.getApplicationContext()).setXsrfToken(xsrfToken);
}
//TODO this is /apps/publish authorization's header payload (multi-acc)
final int statusCode = httpResponse.getStatusLine().getStatusCode();
if (statusCode != HttpStatus.SC_OK) {
throw new AuthenticationException("Got HTTP " + statusCode
+ " (" + httpResponse.getStatusLine().getReasonPhrase() + ')');
}
boolean asp = false; //TODO get hasher here?
Object obj = context.getAttribute("http.protocol.redirect-locations");
if(obj != null) {
RedirectLocations locs = (RedirectLocations)obj;
try {
Field privateStringField = RedirectLocations.class.getDeclaredField("uris");
privateStringField.setAccessible(true);
HashSet<URI> uris = (HashSet<URI>) privateStringField.get(locs);
for (URI uri : uris) {
String string = uri.toASCIIString();
if(string.indexOf("dev_acc=") > -1) {
devacc = string.substring(string.indexOf("=")+1, string.length());
break;
} else if (string.indexOf("asp=1") > -1) {
asp = true;
}
}
} catch (NoSuchFieldException e) {
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
Header[] allHeaders = httpResponse.getHeaders("Set-Cookie");
if(allHeaders != null && allHeaders.length > 0) {
if(allHeaders[0].getValue().startsWith("ANDROID_DEV")) {
cookie1 = allHeaders[0].getValue();
}
}
if(devacc == null && asp) {
throw new MultiAccountAcception();
}
if(devacc == null) {
Log.e("andlytics", "missing devacc");
throw new AuthenticationException();
}
if(cookie1 == null) {
throw new AuthenticationException();
}
this.cookie = cookie1;
}
} catch (SocketException e) {
throw new NetworkException(e);
} catch (UnknownHostException e) {
throw new NetworkException(e);
} catch (IOException e) {
throw new NetworkException(e);
} catch (JSONException e) {
throw new NetworkException(e);
} finally {
if (httpclient != null) {
httpclient.getConnectionManager().shutdown();
httpclient = null;
}
}
}
private static String convertStreamToString(InputStream is) {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append((line + "\n"));
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}
public String login(String email, String password) {
Map<String, String> params = new LinkedHashMap<String, String>();
params.put("Email", email);
params.put("Passwd", password);
params.put("service", SERVICE);
// params.put("source", source);
params.put("accountType", ACCOUNT_TYPE);
String authKey = null;
// Login at Google.com
try {
String data = postUrl(URL_GOOGLE_LOGIN, params);
StringTokenizer st = new StringTokenizer(data, "\n\r=");
while (st.hasMoreTokens()) {
if (st.nextToken().equalsIgnoreCase("Auth")) {
authKey = st.nextToken();
break;
}
}
if (authKey == null)
throw new RuntimeException("authKey not found in " + data);
} catch (IOException ex) {
throw new RuntimeException(ex);
}
return authKey;
}
protected String postUrl(String url, Map<String, String> params) throws IOException {
String data = "";
for (String key : params.keySet()) {
data += "&" + URLEncoder.encode(key, "UTF-8") + "=" + URLEncoder.encode(params.get(key), "UTF-8");
}
data = data.substring(1);
// Make the connection to Authoize.net
URL aURL = new java.net.URL(url);
HttpsURLConnection aConnection = (HttpsURLConnection) aURL.openConnection();
aConnection.setDoOutput(true);
aConnection.setDoInput(true);
aConnection.setRequestMethod("POST");
aConnection.setHostnameVerifier(new AllowAllHostnameVerifier());
// aConnection.setAllowUserInteraction(false);
// POST the data
OutputStreamWriter streamToAuthorize = new java.io.OutputStreamWriter(aConnection.getOutputStream());
streamToAuthorize.write(data);
streamToAuthorize.flush();
streamToAuthorize.close();
// Get the Response from Autorize.net
InputStream resultStream = aConnection.getInputStream();
BufferedReader aReader = new java.io.BufferedReader(new java.io.InputStreamReader(resultStream));
StringBuffer aResponse = new StringBuffer();
String aLine = aReader.readLine();
while (aLine != null) {
aResponse.append(aLine + "\n");
aLine = aReader.readLine();
}
resultStream.close();
return aResponse.toString();
}
} |
package com.github.assisstion.ModulePack;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.math.MathContext;
import java.math.RoundingMode;
//import java.util.Random;
import javax.lang.model.SourceVersion;
import com.github.assisstion.ModulePack.annotation.CompileVersion;
import com.github.assisstion.ModulePack.annotation.Immutable;
/** <p>
* Immutable fractions represented by a ratio of two BigIntegers. Operations use the operations of BigIntegers to modify the private fields.
* Most operations of BigFractions return a new BigFraction, which represents the modified value of the fraction.
* BigFractions include most basic arithmetic operations, and some special fraction operations including simplifying the fraction.
* </p><p>
* This class also includes some private static fields to modify the behavior when using the fraction operations, including a MathContext to change the precision when converting to decimals and the mode used to round decimals.
* Because of the fact that the value fields are represented by two BigIntegers, theoretically BigFractions can go up to infinite size. However, certain operations are unstable for use after the size overflows the primitive type long.
* </p><p>
* The constructors of this class are used to create the fractions themselves, along with many methods provided by this class.
* There is a special static method to parse fractions from Strings. The fractions must be in the format of x/y. There can be a negative sign in front of the x and/or y, and the values can be larger than the size overflow values of long.
* </p>2
* @see java.math.BigInteger
* @see java.math.BigDecimal
* @see java.math.RoundingMode
*
* @author Markus Feng
*/
@Immutable
@CompileVersion(SourceVersion.RELEASE_5) // Generics
public class BigFraction extends Number implements Comparable<BigFraction>, Cloneable{
private static final long serialVersionUID = -1038055196274812800L;
protected static MathContext mathContext = MathContext.DECIMAL128;
protected static boolean autoSimplify = false;
protected BigInteger numerator;
protected BigInteger denominator;
/**
* Creates a fraction using another fraction.
* Copies the numerator and denominator of the fraction and creates a new fraction with the numerator and denominator values.
* Same effect as cloning the fraction.
* @see #clone()
* @param fraction Fraction used for cloning.
*/
public BigFraction(BigFraction fraction){
this(fraction.numerator, fraction.denominator);
}
/**
* Creates a fraction with the numerator Numerator and the denominator Denominator.
* Same as using new BigFraction(BigInteger.valueOf(numerator), BigInteger.valueOf(denominator));
* @see #BigFraction(BigInteger, BigInteger)
* @param numerator Numerator of the created fraction.
* @param denominator Denominator of the created fraction.
*/
public BigFraction(long numerator, long denominator) {
this(BigInteger.valueOf(numerator), BigInteger.valueOf(denominator));
}
/**
* Creates a fraction with the numerator Numerator and the denominator Denominator.
* If the denominator is zero, the constructor throws an ArithmeticException.
* @see #BigFraction(long, long)
* @param numerator Numerator of the created fraction.
* @param denominator Denominator of the created fraction.
*/
public BigFraction(BigInteger numerator, BigInteger denominator) {
if(denominator.equals(BigInteger.valueOf(0))){
throw new ArithmeticException("BigFraction: zero denominator");
}
this.numerator = autoSimplify ? numerator.divide(numerator.gcd(denominator)).abs().multiply(BigInteger.valueOf(numerator.signum() * denominator.signum() >= 0 ? 1 : -1)) : numerator;
this.denominator = autoSimplify ? denominator.divide(numerator.gcd(denominator)).abs() : denominator;
}
/**
* Returns the closest double approximation of the fraction.
* @return the value of the fraction in the closest double approximation.
*/
@Override
public double doubleValue() {
return new BigDecimal(numerator).divide(new BigDecimal(denominator), mathContext).doubleValue();
}
/**
* Returns the closest float approximation of the fraction.
* @return the value of the fraction in the closest float approximation.
*/
@Override
public float floatValue() {
return new BigDecimal(numerator).divide(new BigDecimal(denominator), mathContext).floatValue();
}
/**
* Returns the closest integer approximation of the fraction.
* @return the value of the fraction in the closest integer approximation.
*/
@Override
public int intValue() {
return new BigDecimal(numerator).divide(new BigDecimal(denominator), mathContext).intValue();
}
/**
* Returns the closest long approximation of the fraction.
* @return the value of the fraction in the closest long approximation.
*/
@Override
public long longValue() {
return new BigDecimal(numerator).divide(new BigDecimal(denominator), mathContext).longValue();
}
/**
* Compares to BigFraction bf.
* If more than bf, return 1. If less than bf, return -1. If equal to bf, return 0.
* Note that this method compares the value, while the next method compares the numerator and the denominator.
* @see #equals(Object)
* @see #min(BigFraction)
* @see #max(BigFraction)
* @param bf the BigFraction to compare to.
* @return 1 if more than bf, -1 if less than bf, 0 if equal to bf.
*/
@Override
public int compareTo(BigFraction bf) {
return (denominator.multiply(bf.denominator).compareTo(BigInteger.valueOf(0)) > 0 ? 1 : -1) * numerator.multiply(bf.denominator).compareTo(bf.numerator.multiply(denominator));
}
/**
* Checks if equal to Object o.
* If both the numerator and the denominator are equal, returns true. Otherwise, returns false.
* Note that when a compareTo(b) == 0, a equals(b) may be but not necessarily true, but when a compareTo(b) != 0, a equals(b) is always false.
* @see #compareTo(BigFraction)
* @see #hashCode()
* @param o the object to compare to.
* @return true if both the numerator and the denominator are equal, false if otherwise.
*/
@Override
public boolean equals(Object o){
if(!(o instanceof BigFraction)){
return false;
}
BigFraction bf = (BigFraction) o;
return numerator.equals(bf.numerator) && denominator.equals(bf.denominator);
}
/**
* Creates a fraction with the same numerator and denominator.
* Copies the numerator and denominator of the fraction and creates a new fraction with the numerator and denominator values.
* @see #BigFraction(BigFraction)
* @return the cloned fraction.
*/
@Override
public BigFraction clone(){
return new BigFraction(this);
}
/**
* Returns the hashCode of the object.
* Finds the hashCode of the object by finding the sum of the hashCode of numerator and the hashCode of the denominator.
* @see #equals(Object)
* @return the hashCode of the object.
*/
@Override
public int hashCode(){
return numerator.hashCode() ^
denominator.hashCode() << 16 ^
denominator.hashCode() >> 16;
/*if(!inLongRange()){
return new Float(numerator.hashCode() / denominator.hashCode()).hashCode();
};
Random random = new Random(numerator.longValue());
long l = denominator.abs().longValue();
for(long i = 0;i < l; i++){
random.nextInt();
}
return denominator.longValue() > 0?random.nextInt():0 - random.nextInt();*/
}
/**
* Returns the String value of the fraction.
* Makes the fraction in to a string in the form of x/y where x is the numerator and y is the denominator.
* @return the String value of the fraction.
*/
@Override
public String toString(){
return numerator.toString() + "/" + denominator.toString();
}
/**
* Converts the BigFraction into the closest BigDecimal approximation.
* Accuracy determined by the static fields scale and rounding mode.
* @return the BigDecimal converted version of the BigFraction.
*/
public BigDecimal toBigDecimal(){
return new BigDecimal(numerator).divide(new BigDecimal(denominator), mathContext);
}
/**
* Returns the numerator of the fraction as a long.
* @see #getBigIntegerNumerator()
* @return the long numerator of the fraction.
*/
public long getNumerator() {
return numerator.longValue();
}
/**
* Returns the numerator of the fraction as a BigInteger.
* @see #getNumerator()
* @return the BigInteger numerator of the fraction.
*/
public BigInteger getBigIntegerNumerator(){
return numerator;
}
/**
* Returns the denominator of the fraction as a long.
* @see #getBigIntegerDenominator()
* @return the long denominator of the fraction.
*/
public long getDenominator() {
return denominator.longValue();
}
/**
* Returns the denominator of the fraction as a BigInteger.
* @see #getDenominator()
* @return the BigInteger denominator of the fraction.
*/
public BigInteger getBigIntegerDenominator(){
return denominator;
}
/**
* Sets the precision of the MathContext.
* This change applies to all BigFractions. By default the precision is 34.
* The MathContext determines what to round to and the precision when converting BigFractions in to BigDecimals, floats, and doubles.
* @see #setMathContext(MathContext)
* @param precision the digits of precision to round to.
*/
public static void setPrecision(int precision){
mathContext = new MathContext(precision, mathContext.getRoundingMode());
}
/**
* Sets the RoundingMode of the MathContext.
* This change applies to all BigFractions. By default the RoundingMode is RoundingMode.HALF_UP.
* The MathContext determines what to round to and the precision when converting BigFractions in to BigDecimals, floats, and doubles.
* @see #setMathContext(MathContext)
* @param r the RoundingMode to use to round integers.
*/
public static void setRoundingMode(RoundingMode r){
mathContext = new MathContext(mathContext.getPrecision(), r);
}
/**
* Sets the MathContext.
* This change applies to all BigFractions. By default the MathContext is MathContext.DECIMAL_128.
* The MathContext determines what to round to and the precision when converting BigFractions in to BigDecimals, floats, and doubles.
* @param m
*/
public static void setMathContext(MathContext m){
mathContext = m;
}
/**
* Turns on or off autoSimplify.
* This change applies to all BigFractions. By default autoSimplify is false.
* If autoSimplify is on, all created fractions will be automatically simplified using the simplifying technique in the method simplify.
* @see #simplify()
* @param b turn on or off autoSimplify.
*/
public static void setAutoSimplify(boolean b){
autoSimplify = b;
}
/**
* Simplifies the fraction in to the simplest form.
* If the fraction is negative, the numerator becomes negative.
* If autoSimplify is turned on, every fraction is automatically simplified.
* @see #setAutoSimplify(boolean)
* @return the simplified fraction.
*/
public BigFraction simplify(){
return new BigFraction(numerator.divide(numerator.gcd(denominator)).abs().multiply(BigInteger.valueOf(numerator.signum() * denominator.signum() >= 0 ? 1 : -1)), denominator.divide(numerator.gcd(denominator)).abs());
}
/**
* Returns a BigFraction with the value of (a/c + b/d).
* (a is the numerator of the first fraction, b is the numerator of the second fraction, c is the denominator of the frist fraction, and d is the denominator of the second fraction).
* The value of the numerator is (ad + cb) and the value of the denominator is (bd).
* @param bf the fraction to add.
* @return the sum of the fractions.
*/
public BigFraction add(BigFraction bf){
return new BigFraction(numerator.multiply(bf.denominator).add(bf.numerator.multiply(denominator)), denominator.multiply(bf.denominator));
}
/**
* Returns a BigFraction with the value of (a/c - b/d).
* (a is the numerator of the first fraction, b is the numerator of the second fraction, c is the denominator of the frist fraction, and d is the denominator of the second fraction).
* The value of the numerator is (ad - cb) and the value of the denominator is (bd).
* @param bf the fraction to subtract.
* @return the difference of the fractions.
*/
public BigFraction subtract(BigFraction bf){
return new BigFraction(numerator.multiply(bf.denominator).subtract(bf.numerator.multiply(denominator)), denominator.multiply(bf.denominator));
}
/**
* Returns a BigFraction with the value of (a/c * b/d).
* (a is the numerator of the first fraction, b is the numerator of the second fraction, c is the denominator of the frist fraction, and d is the denominator of the second fraction).
* The value of the numerator is (ab) and the value of the denominator is (cd).
* @param bf the fraction to multiply.
* @return the product of the fractions.
*/
public BigFraction multiply(BigFraction bf){
return new BigFraction(numerator.multiply(bf.numerator), denominator.multiply(bf.denominator));
}
/**
* Returns a BigFraction with the value of (a/c / b/d).
* (a is the numerator of the first fraction, b is the numerator of the second fraction, c is the denominator of the frist fraction, and d is the denominator of the second fraction).
* The value of the numerator is (ad) and the value of the denominator is (bc).
* @param bf the fraction to divide.
* @return the quotient of the fractions.
*/
public BigFraction divide(BigFraction bf){
return new BigFraction(numerator.multiply(bf.denominator), denominator.multiply(bf.numerator));
}
/**
* Returns a BigFraction with the value of Math.pow(this, i).
* (a is the numerator of the fraction, c is the denominator if the fraction)
* The value of the numerator is (Math.pow(a, i)) and the value of the denominator is (Math.pow(c, i)).
* @param i the power to raise to.
* @return this fraction to the power of i.
*/
public BigFraction pow(int i){
return new BigFraction(numerator.pow(i), denominator.pow(i));
}
/**
* Returns a BigFraction with the absolute value of the fraction.
* This is the same as new BigFraction(numerator.abs(), denominator.abs()).
* @return the absolute value the fraction.
*/
public BigFraction abs(){
return new BigFraction(numerator.abs(), denominator.abs());
}
/**
* Returns a BigFraction equal to the maximum of this fraction and the argument.
* If both arguments are equal, the method returns this fraction.
* @see #min(BigFraction)
* @see #compareTo(BigFraction)
* @param bf the BigFraction to compare to.
* @return the maximum of this fraction and bf.
*/
public BigFraction max(BigFraction bf){
return compareTo(bf) < 0 ? new BigFraction(bf) : new BigFraction(this);
}
/**
* Returns a BigFraction equal to the minimum of this fraction and the argument.
* If both arguments are equal, the method returns this fraction.
* @see #max(BigFraction)
* @see #compareTo(BigFraction)
* @param bf the BigFraction to compare to.
* @return the minimum of this fraction and bf.
*/
public BigFraction min(BigFraction bf){
return compareTo(bf) > 0 ? new BigFraction(bf) : new BigFraction(this);
}
/**
* Returns the signum of this fraction.
* Returns -1 if this fraction is less than 0, 0 if this fraction is equal to 0, 1 if this fraction is more than 0.
* Same as compareTo(new BigFraction(0, 1)).
* @see #compareTo(BigFraction)
* @return the signum of this fraction.
*/
public int signum(){
return numerator.multiply(denominator).compareTo(BigInteger.valueOf(0));
}
/**
* Returns true if this fraction is an integer, false if otherwise.
* @return true if this fraction is an integer, false if otherwise.
*/
public boolean isInteger(){
return numerator.mod(denominator).equals(BigInteger.valueOf(0));
}
/**
* Returns true if the BigFraction is in long range.
* If both the numerator and the denominator is in long range, the BigFraction is in long range.
* @return true if the BigFraction is in long range
*/
public boolean inLongRange(){
return !(numerator.max(BigInteger.valueOf(Long.MAX_VALUE)).equals(numerator) || numerator.min(BigInteger.valueOf(Long.MIN_VALUE)).equals(numerator) || denominator.max(BigInteger.valueOf(Long.MAX_VALUE)).equals(denominator) || denominator.min(BigInteger.valueOf(Long.MIN_VALUE)).equals(denominator));
}
/**
* Returns true if the BigFraction is in int range.
* If both the numerator and the denominator is in int range, the BigFraction is in int range.
* @return true if the BigFraction is in int range
*/
public boolean inIntRange(){
return !(numerator.max(BigInteger.valueOf(Integer.MAX_VALUE)).equals(numerator) || numerator.min(BigInteger.valueOf(Integer.MIN_VALUE)).equals(numerator) || denominator.max(BigInteger.valueOf(Integer.MAX_VALUE)).equals(denominator) || denominator.min(BigInteger.valueOf(Integer.MIN_VALUE)).equals(denominator));
}
/**
* Parses the String s to convert it in to a fraction.
* The fractions must be in the format of x/y.
* There can be a negative sign in front of the x and/or y, and the values can be larger than the size overflow values of long.
* @param s this String to parse.
* @return the parsed fraction.
*/
public static BigFraction parseFraction(String s){
try{
return Parser.parse(s);
}
catch (NumberFormatException e){
throw new NumberFormatException("For input string: \""+ s +"\"");
}
}
private static class Parser{
private static final char[] ACCEPTABLE_FIRST_DIGITS = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '-'};
private static final char[] ACCEPTABLE_DIGITS = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '/'};
private static final char[] ACCEPTABLE_AFTER_DIGITS = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9'};
private static final byte[] ACCEPTABLE_FIRST_DIGIT_NUMERALS = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, -1};
private static final byte[] ACCEPTABLE_DIGIT_NUMERALS = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, -2};
private static final byte[] ACCEPTABLE_AFTER_DIGIT_NUMERALS = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
private static BigFraction parse(String s){
try{
if(s == null){
return null;
}
if(s.isEmpty()){
return null;
}
char[] c = s.toCharArray();
c = removeChar(c, (char) 32);
c = removeChar(c, (char) 43);
int l = c.length;
byte[] b = new byte[l];
b[0] = findFirst(c[0]);
int i = 1;
for(;i < l;i++){
b[i] = find(c[i]);
if(b[i] == -2){
break;
}
}
if(b[i] != -2){
throw new NumberFormatException();
}
i++;
b[i] = findFirst(c[i]);
i++;
for(;i < l; i++){
b[i] = findAfter(c[i]);
}
return fromByteArray(b);
}
catch(IllegalArgumentException e){
throw new NumberFormatException();
}
catch(ArrayIndexOutOfBoundsException e){
throw new NumberFormatException();
}
}
private static byte findFirst(char c){
int i = 0;
int j = ACCEPTABLE_FIRST_DIGITS.length;
for(;i < j; i++){
if(ACCEPTABLE_FIRST_DIGITS[i] == c){
return ACCEPTABLE_FIRST_DIGIT_NUMERALS[i];
}
}
throw new IllegalArgumentException();
}
private static byte find(char c){
int i = 0;
int j = ACCEPTABLE_DIGITS.length;
for(;i < j; i++){
if(ACCEPTABLE_DIGITS[i] == c){
return ACCEPTABLE_DIGIT_NUMERALS[i];
}
}
throw new IllegalArgumentException();
}
private static byte findAfter(char c){
int i = 0;
int j = ACCEPTABLE_AFTER_DIGITS.length;
for(;i < j; i++){
if(ACCEPTABLE_AFTER_DIGITS[i] == c){
return ACCEPTABLE_AFTER_DIGIT_NUMERALS[i];
}
}
throw new IllegalArgumentException();
}
private static BigFraction fromByteArray(byte[] b){
int numeratorSign = 0;
int denominatorSign = 0;
byte[] numeratorArray;
byte[] denominatorArray;
BigInteger numerator = BigInteger.valueOf(0);
BigInteger denominator = BigInteger.valueOf(0);
int i = 0;
int j = b.length;
if(b[0] == -1){
numeratorSign = -1;
byte[] c = new byte[j - 1];
System.arraycopy(b, 1, c, 0, j - 1);
b = c.clone();
}
else{
numeratorSign = 1;
}
j = b.length;
for(;i < j;i++){
if(b[i] == -2){
break;
}
}
if(b[i] != -2){
throw new IllegalArgumentException();
}
numeratorArray = new byte[i];
System.arraycopy(b, 0, numeratorArray, 0, i);
i++;
j = b.length;
if(b[i] == -1){
denominatorSign = -1;
denominatorArray = new byte[j - i - 1];
System.arraycopy(b, i + 1, denominatorArray, 0, j - i - 1);
}
else{
denominatorSign = 1;
denominatorArray = new byte[j - i];
System.arraycopy(b, i, denominatorArray, 0, j - i);
}
numerator = byteArrayToBigInteger(numeratorArray, numeratorSign);
denominator = byteArrayToBigInteger(denominatorArray, denominatorSign);
return new BigFraction(numerator, denominator);
}
private static BigInteger byteArrayToBigInteger(byte[] b, int sign){
int i = 0;
BigInteger n = BigInteger.valueOf(0);
int l = b.length;
for(;i < l;i++){
if(b[i] < 0 || b[i] > 9){
throw new IllegalArgumentException();
}
n = n.add(BigInteger.valueOf(10).pow(l-i-1).multiply(BigInteger.valueOf(b[i])));
}
if(sign < 0){
return n.multiply(BigInteger.valueOf(-1));
}
else{
return n;
}
}
private static char[] removeChar(char[] ca, char c){
int x = 0;
char[] l = new char[ca.length + 1];
for(int i = 0; i < ca.length; i++){
char y = ca[i];
if(y != c){
l[x] = y;
x++;
}
}
char[] n = new char[x];
System.arraycopy(l, 0, n, 0, x);
return n;
}
}
} |
package com.jcwhatever.bukkit.phantom;
import com.jcwhatever.bukkit.phantom.commands.PhantomCommandDispatcher;
import com.jcwhatever.bukkit.phantom.entities.PhantomEntitiesManager;
import com.jcwhatever.bukkit.phantom.nms.INmsHandler;
import com.jcwhatever.bukkit.phantom.nms.v1_8_R1.NmsHandler_v1_8_R1;
import com.jcwhatever.bukkit.phantom.nms.v1_8_R2.NmsHandler_v1_8_R2;
import com.jcwhatever.bukkit.phantom.regions.PhantomRegionManager;
import com.jcwhatever.bukkit.phantom.scripts.PhantomScriptApi;
import com.jcwhatever.nucleus.Nucleus;
import com.jcwhatever.nucleus.NucleusPlugin;
import com.jcwhatever.nucleus.mixins.IDisposable;
import com.jcwhatever.nucleus.managed.scripting.IEvaluatedScript;
import com.jcwhatever.nucleus.managed.scripting.IScriptApi;
import com.jcwhatever.nucleus.managed.scripting.SimpleScriptApi;
import com.jcwhatever.nucleus.managed.scripting.SimpleScriptApi.IApiObjectCreator;
import com.jcwhatever.nucleus.utils.nms.NmsManager;
import com.jcwhatever.nucleus.utils.text.TextColor;
import org.bukkit.Bukkit;
import org.bukkit.plugin.Plugin;
public class PhantomPackets extends NucleusPlugin {
private static PhantomPackets _plugin;
public static PhantomPackets getPlugin() {
return _plugin;
}
private PhantomRegionManager _regionManager;
private PhantomEntitiesManager _entitiesManager;
private IScriptApi _scriptApi;
private NmsManager _reflectionManager;
private INmsHandler _reflectionHandler;
public PhantomPackets() {
super();
_plugin = this;
}
@Override
public String getChatPrefix() {
return TextColor.WHITE.toString() + '[' + TextColor.GRAY + "PhantomPackets" + TextColor.WHITE + "] ";
}
@Override
public String getConsolePrefix() {
return "[PhantomPackets] ";
}
public PhantomRegionManager getRegionManager() {
return _regionManager;
}
public PhantomEntitiesManager getEntitiesManager() {
return _entitiesManager;
}
public NmsManager getReflectionManager() {
return _reflectionManager;
}
public static INmsHandler getNms() {
return _plugin._reflectionHandler;
}
@Override
protected void onEnablePlugin() {
_reflectionManager = new NmsManager(this, "v1_8_R1", "v1_8_R2");
_reflectionManager.registerHandler("v1_8_R1", "nms", NmsHandler_v1_8_R1.class);
_reflectionManager.registerHandler("v1_8_R2", "nms", NmsHandler_v1_8_R2.class);
_reflectionHandler = _reflectionManager.getHandler("nms");
if (_reflectionHandler == null) {
Msg.warning("Failed to get an NMS handler. Disabling plugin.");
Bukkit.getPluginManager().disablePlugin(this);
return;
}
_regionManager = new PhantomRegionManager(this);
_entitiesManager = new PhantomEntitiesManager(this);
registerCommands(new PhantomCommandDispatcher(this));
_scriptApi = new SimpleScriptApi(this, "phantom", new IApiObjectCreator() {
@Override
public IDisposable create(Plugin plugin, IEvaluatedScript script) {
return new PhantomScriptApi();
}
});
Nucleus.getScriptApiRepo().registerApi(_scriptApi);
}
@Override
protected void onDisablePlugin() {
if (_regionManager != null)
_regionManager.dispose();
Nucleus.getScriptApiRepo().unregisterApi(_scriptApi);
}
} |
package com.opencms.workplace;
import com.opencms.file.*;
import com.opencms.core.*;
import com.opencms.util.*;
import com.opencms.template.*;
import java.util.*;
import java.io.*;
import javax.servlet.http.*;
public class CmsAdminProjectPublish extends CmsWorkplaceDefault implements I_CmsConstants,I_CmsLogChannels {
private final String C_PUBLISH_THREAD = "publishprojectthread";
/**
* Gets the content of a defined section in a given template file and its subtemplates
* with the given parameters.
*
* @see getContent(CmsObject cms, String templateFile, String elementName, Hashtable parameters)
* @param cms CmsObject Object for accessing system resources.
* @param templateFile Filename of the template file.
* @param elementName Element name of this template in our parent template.
* @param parameters Hashtable with all template class parameters.
* @param templateSelector template section that should be processed.
*/
public byte[] getContent(CmsObject cms, String templateFile, String elementName,
Hashtable parameters, String templateSelector) throws CmsException {
if(I_CmsLogChannels.C_PREPROCESSOR_IS_LOGGING && A_OpenCms.isLogging() && C_DEBUG ) {
A_OpenCms.log(C_OPENCMS_DEBUG, this.getClassName() + "getting content of element " + ((elementName == null) ? "<root>" : elementName));
A_OpenCms.log(C_OPENCMS_DEBUG, this.getClassName() + "template file is: " + templateFile);
A_OpenCms.log(C_OPENCMS_DEBUG, this.getClassName() + "selected template section is: " + ((templateSelector == null) ? "<default>" : templateSelector));
}
CmsXmlWpTemplateFile xmlTemplateDocument = (CmsXmlWpTemplateFile)getOwnTemplateFile(cms,
templateFile, elementName, parameters, templateSelector);
I_CmsSession session = cms.getRequestContext().getSession(true);
String paraId = (String)parameters.get("projectid");
int projectId = -1;
int projectType = C_PROJECT_TYPE_TEMPORARY;
if(paraId != null) {
projectId = Integer.parseInt(paraId);
CmsProject project = cms.readProject(projectId);
projectType = project.getType();
xmlTemplateDocument.setData("projectid", projectId + "");
xmlTemplateDocument.setData("projectname", project.getName());
}
String action = (String)parameters.get("action");
// look if user called from Explorer
String fromExplorer = (String)parameters.get("fromExplorer");
if (fromExplorer != null){
// this is Explorer calling lets talk about currentProject
CmsProject currentProject = cms.getRequestContext().currentProject();
projectId = currentProject.getId();
projectType = currentProject.getType();
xmlTemplateDocument.setData("projectid", projectId + "");
xmlTemplateDocument.setData("projectname", currentProject.getName());
// in this case we have to check if there are locked resources in the project
if ((action != null) && "check".equals(action)){
if(cms.countLockedResources(projectId) == 0){
action = "ok";
}else{
// ask user if the locks should be removed
return startProcessing(cms, xmlTemplateDocument, elementName, parameters,"asklock");
}
}else if((action != null) && "rmlocks".equals(action)){
// remouve the locks and publish
try{
cms.unlockProject(projectId);
action = "ok";
}catch (CmsException exc){
xmlTemplateDocument.setData("details", Utils.getStackTrace(exc));
return startProcessing(cms, xmlTemplateDocument, elementName, parameters,"errorlock");
}
}
}
if((action != null) && "ok".equals(action)) {
// start the publishing
// first clear the session entry if necessary
if(session.getValue(C_SESSION_THREAD_ERROR) != null) {
session.removeValue(C_SESSION_THREAD_ERROR);
}
if(projectType == C_PROJECT_TYPE_TEMPORARY){
cms.getRequestContext().setCurrentProject(cms.onlineProject().getId());
}
Thread doPublish = new CmsAdminPublishProjectThread(cms, projectId);
doPublish.start();
session.putValue(C_PUBLISH_THREAD, doPublish);
xmlTemplateDocument.setData("time", "10");
templateSelector = "wait";
} else {
if((action != null) && ("working".equals(action))) {
// still working?
Thread doPublish = (Thread)session.getValue(C_PUBLISH_THREAD);
if(doPublish.isAlive()) {
String time = (String)parameters.get("time");
int wert = Integer.parseInt(time);
//wert += 20;
wert += 2;
xmlTemplateDocument.setData("time", "" + wert);
templateSelector = "wait";
} else {
// thread has come to an end, was there an error?
String errordetails = (String)session.getValue(C_SESSION_THREAD_ERROR);
if(errordetails == null) {
// clear the languagefile cache
CmsXmlWpTemplateFile.clearcache();
templateSelector = "done";
} else {
// get errorpage:
xmlTemplateDocument.setData("details", errordetails);
templateSelector = "error";
session.removeValue(C_SESSION_THREAD_ERROR);
}
}
}
}
// Now load the template file and start the processing
return startProcessing(cms, xmlTemplateDocument, elementName, parameters,
templateSelector);
}
/**
* Indicates if the results of this class are cacheable.
*
* @param cms CmsObject Object for accessing system resources
* @param templateFile Filename of the template file
* @param elementName Element name of this template in our parent template.
* @param parameters Hashtable with all template class parameters.
* @param templateSelector template section that should be processed.
* @return <EM>true</EM> if cacheable, <EM>false</EM> otherwise.
*/
public boolean isCacheable(CmsObject cms, String templateFile, String elementName,
Hashtable parameters, String templateSelector) {
return false;
}
} |
package com.shakenearth.rhyme_essentials;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.nio.charset.*;
import java.nio.file.*;
import java.util.*;
/**
* This class contains a set of methods to find how well two words rhyme with one another.
*@author Thomas Lisankie
*/
public class RhymeFinder {
public final static boolean DEBUGGING = false, SAMPLESIZE = false;
private Hashtable<String, String> dictionary = null;
private Hashtable<String, Integer> structureReference = null;
private ArrayList<String> wordList = null;
private static Hashtable<String, ArrayList<Integer>> features = null;
/**
* Creates a new RhymeFinder object.
*@param pathToDict The path to the CMU Dictionary (or any stylistic equivalent) to be loaded.
*/
public RhymeFinder(String pathToDict, String pathToFeatureSet){
buildWords(pathToDict, pathToFeatureSet);
}
/**
* builds the list of Word objects that can be compared to one another.
* @param path The path to the CMU Dictionary (or any stylistic equivalent) to be loaded.*/
public void buildWords(String path, String featureSetPath){
List<String> linesOfDictionary = null;
List<String> linesOfFeatureSet = null;
//loads all the lines in the CMU Phonemic Dictionary. Each line contains a word and its phonemic translation.
try{
linesOfDictionary = Files.readAllLines(Paths.get(path), Charset.defaultCharset());
}catch(Exception e){
debugPrint("there was an exception");
}
//loads lines of feature set
try{
linesOfFeatureSet = Files.readAllLines(Paths.get(featureSetPath), Charset.defaultCharset());
}catch(Exception e){
debugPrint("there was an exception");
}
setDictionary(new Hashtable<String, String>());
setStructureReference(new Hashtable<String, Integer>());
setWordList(new ArrayList<String>());
setFeatures(new Hashtable<String, ArrayList<Integer>>());
for(int l = 0; l < linesOfDictionary.size(); l++){
String[] components = linesOfDictionary.get(l).split(" ");
if(components.length != 2){
System.out.println("The lines aren't separated by two spaces.");
break;
}
if(components[0].equals("
getStructureReference().put(components[1], l - getStructureReference().size());
}else{
String lowerCaseWord = components[0].toLowerCase();
getWordList().add(lowerCaseWord);
dictionary.put(lowerCaseWord, components[1]);
}
}
//import phonemes and their features
for(int l = 0; l < linesOfFeatureSet.size(); l++){
String[] components = linesOfFeatureSet.get(l).split(" ");
if(components.length != 2){
System.out.println("The lines aren't separated by two spaces.");
break;
}
String[] features = components[1].split(" ");
ArrayList<Integer> featureInts = new ArrayList<Integer>();
for(int i = 0; i < features.length; i++){
featureInts.add(Integer.parseInt(features[i]));
}
getFeatures().put(components[0], featureInts);
}
}
/**This method goes through the entire process of finding how well two words rhyme with one another.
* How well two words rhyme is given by the Rhyme Percentile returned. The higher the Rhyme Percentile, the better the two words rhyme.
* @return Rhyme Percentile between two Words*/
public double findRhymePercentileForWords(Word anchor, Word satellite) {
double rhymePercentile = 0.0;
if(anchor.getListOfPhonemes().size() == satellite.getListOfPhonemes().size()){
/*rhyme percentile for words of same phonemic length uses the anchor word as the denominator. This is to keep the focus on
* the anchor word which is the focus word*/
rhymePercentile = regularRhymeValue(anchor, satellite);
System.out.println("NEW METHOD RESULT: " + newFindRhymePercentileForWords(anchor, satellite)*100 + "%");
}else{//do ideal Rhyme Value process
rhymePercentile = idealRhymeValue(anchor, satellite);
System.out.println("NEW METHOD RESULT: " + newFindRhymePercentileForWords(anchor, satellite)*100 + "%");
}
return rhymePercentile;
}
public double newFindRhymePercentileForWords(Word word1, Word word2){
double rhymePercentile = 0.0;
Word longerWord = null;
//these conditionals find which word is longer and which is shorter
if(word1.getListOfPhonemes().size() < word2.getListOfPhonemes().size()){
longerWord = word2;
}else{
longerWord = word1;
}
ArrayList<Double> allRVs = new ArrayList<Double>();
//1 - Find Cartesian product (shorterWord X longerWord)
ArrayList<ArrayList<OrderedPair>> cartesianProduct = findCartesianProduct(word1, word2);
//2 - Calculate RVs
int echelon = 0;
while(cartesianProduct.size() != 0){
System.out.println("LOOP ITERATION");
System.out.println("CARTESIAN PRODUCT HEIGHT: " + cartesianProduct.size());
//print REF CP:
for(int i = 0; i < cartesianProduct.size(); i++){
ArrayList<OrderedPair> currentRow = cartesianProduct.get(i);
for(int j = 0; j < echelon; j++){
System.out.print(" ");
}
for(int j = echelon; j < currentRow.size(); j++){
OrderedPair pair = currentRow.get(j);
if(pair.getShorterWordPhoneme().length() == 2 && pair.getLongerWordPhoneme().length() == 2){
System.out.print(pair + ", " + pair.getRhymeValue() + " ");
}else if(pair.getShorterWordPhoneme().length() != pair.getLongerWordPhoneme().length()){
System.out.print(pair + ", " + pair.getRhymeValue() + " ");
}else if(pair.getShorterWordPhoneme().length() == 1 && pair.getLongerWordPhoneme().length() == 1){
System.out.print(pair + ", " + pair.getRhymeValue() + " ");
}
}
System.out.println();
echelon = echelon + 1;
}
//end REF CP print
allRVs.add(findBestRV(cartesianProduct, 0.0, new ArrayList<Integer>(), longerWord.getListOfPhonemes().size()));
cartesianProduct.remove(0);
}
//3 - Find Rhyme Percentile
System.out.println("Rhyme Values: " + allRVs);
System.out.println("MAX: " + Collections.max(allRVs));
rhymePercentile = (double) findRhymePercentile(Collections.max(allRVs), longerWord);
return rhymePercentile;
}
private ArrayList<ArrayList<OrderedPair>> findCartesianProduct(Word word1, Word word2){
Word shorterWord = null;
Word longerWord = null;
System.out.println("Cartesian Product of Newest Method: \n");
//these conditionals find which word is longer and which is shorter
if(word1.getListOfPhonemes().size() < word2.getListOfPhonemes().size()){
shorterWord = word1;
longerWord = word2;
}else{
shorterWord = word2;
longerWord = word1;
}
ArrayList<ArrayList<OrderedPair>> cartesianProduct = new ArrayList<ArrayList<OrderedPair>>();
//creates Cartesian product (shorterWord X longerWord)
for(int s = 0; s < shorterWord.getListOfPhonemes().size(); s++){
ArrayList<OrderedPair> currentRow = new ArrayList<OrderedPair>();
for(int l = 0; l < longerWord.getListOfPhonemes().size(); l++){
OrderedPair newOrderedPair = new OrderedPair(shorterWord.getListOfPhonemes().get(s), longerWord.getListOfPhonemes().get(l), l);
currentRow.add(newOrderedPair);
//print the Ordered Pairs and make it look pretty
if(newOrderedPair.getShorterWordPhoneme().length() == 2 && newOrderedPair.getLongerWordPhoneme().length() == 2){
System.out.print(newOrderedPair + " ");
}else if(newOrderedPair.getShorterWordPhoneme().length() != newOrderedPair.getLongerWordPhoneme().length()){
System.out.print(newOrderedPair + " ");
}else if(newOrderedPair.getShorterWordPhoneme().length() == 1 && newOrderedPair.getLongerWordPhoneme().length() == 1){
System.out.print(newOrderedPair + " ");
}
//End print of ordered pairs
}
System.out.println();
cartesianProduct.add(currentRow);
}
System.out.println();
return cartesianProduct;
}
private double findBestRV(ArrayList<ArrayList<OrderedPair>> matrix, double addition, ArrayList<Integer> indexes, int lSize){
@SuppressWarnings("unchecked")
ArrayList<ArrayList<OrderedPair>> matrixCopy = (ArrayList<ArrayList<OrderedPair>>) matrix.clone();
OrderedPair bestPair = null;
int echelonIndex = matrixCopy.size() - 1;
int index = echelonIndex;
System.out.println("ADDITION: " + addition);
ArrayList<OrderedPair> currentRow = matrixCopy.get(echelonIndex);
// add addition to an OrderedPair's RV
for(int i = 0; i < currentRow.size(); i++){
currentRow.get(i).setRhymeValue(currentRow.get(i).getRhymeValue() + addition);
}
for(int i = echelonIndex; i < currentRow.size(); i++){
if(i == echelonIndex){
bestPair = currentRow.get(echelonIndex);
}else{
if(currentRow.get(i).getRhymeValue() > bestPair.getRhymeValue()){
bestPair = currentRow.get(i);
index = i;
}
}
}
indexes.add(index);
matrixCopy.remove(matrixCopy.size() - 1);
if(matrixCopy.size() == 0){
bestPair.setIndexes(indexes);
bestPair.calculateGapPenalty(lSize);
System.out.println("BestPair RV: " + bestPair.getRhymeValue());
return bestPair.getRhymeValue();
}else{
return findBestRV(matrixCopy, bestPair.getRhymeValue(), indexes, lSize);
}
}
/**This method is called when two words have the same phonemic lengths (contain the same number of phonemes).
* 1. Iterate through each phoneme in one of the words and compare it to its corresponding phoneme in the other word, adding the resulting points awarded to the total Rhyme Value along the way.
* 2. Find Homophonic Rhyme Value (as previously defined)
* 3. Divide Rhyme Value by Homophonic Rhyme Value and multiply by 100
* @return Regular Rhyme Value between two Words*/
private double regularRhymeValue(Word anchor, Word satellite){
debugPrint("REGULAR RHYME VALUE");
debugPrint("Anchor:");
anchor.printListOfPhonemes();
debugPrint("Satellite:");
satellite.printListOfPhonemes();
boolean foundConsonantCluster = false;
boolean anchorOrSatellite = false; //true if anchor, false if satellite.
double rhymeValue = 0.0;
Word newWord = null;
double weightTowardsWordEnd = 0.1;
if(anchor.getListOfPhonemes().get(0).isAVowelPhoneme() == false && anchor.getListOfPhonemes().get(1).isAVowelPhoneme() == false
&& (!anchor.getListOfPhonemes().get(0).isEqualTo(satellite.getListOfPhonemes().get(0)) && !anchor.getListOfPhonemes().get(1).isEqualTo(satellite.getListOfPhonemes().get(1)))){
foundConsonantCluster = true;
List<Phoneme> shortenedListOfPhonemes = anchor.getListOfPhonemes().subList(1, anchor.getListOfPhonemes().size());
newWord = new Word(anchor.getWordName(), shortenedListOfPhonemes);
anchorOrSatellite = true;
}else if(satellite.getListOfPhonemes().get(0).isAVowelPhoneme() == false && satellite.getListOfPhonemes().get(1).isAVowelPhoneme() == false
&& (!anchor.getListOfPhonemes().get(0).isEqualTo(satellite.getListOfPhonemes().get(0)) && !anchor.getListOfPhonemes().get(1).isEqualTo(satellite.getListOfPhonemes().get(1)))){
foundConsonantCluster = true;
List<Phoneme> shortenedListOfPhonemes = satellite.getListOfPhonemes().subList(1, anchor.getListOfPhonemes().size());
newWord = new Word(satellite.getWordName(), shortenedListOfPhonemes);
anchorOrSatellite = false;
}
if(foundConsonantCluster == false){
for(int s = 0; s < anchor.getListOfPhonemes().size(); s++){
rhymeValue = (double) rhymeValue + (double)findRVBetweenPhonemes(anchor.getListOfPhonemes().get(s),
satellite.getListOfPhonemes().get(s), true, s*weightTowardsWordEnd);
}
}else{
//nothing, it'll be taken care of in the next if-else statement.
}
debugPrint("Rhyme Value:" + rhymeValue);
if(foundConsonantCluster == false){
return (double) findRhymePercentile(rhymeValue, anchor);
}else{
if(anchorOrSatellite == true){
return idealRhymeValue(newWord, satellite);
}else{
return idealRhymeValue(anchor, newWord);
}
}
}
/**This method is called when two words have differing phonemic lengths (contain the same number of phonemes).
* Ideal Rhyme Value is just the rhyme value before spacing between phoneme matches is taken into account.
* @return Ideal Rhyme Value between two Words*/
private double idealRhymeValue(Word anchor, Word satellite){
debugPrint("IDEAL RHYME VALUE");
debugPrint("Anchor:");
anchor.printListOfPhonemes();
debugPrint("Satellite:");
satellite.printListOfPhonemes();
Word shorterWord = null;
Word longerWord = null;
//these conditionals find which word is longer and which is shorter
if(anchor.getListOfPhonemes().size() < satellite.getListOfPhonemes().size()){
shorterWord = anchor;
longerWord = satellite;
}else{
shorterWord = satellite;
longerWord = anchor;
}
double idealRhymeValue = 0.0;
boolean firstSearch = true;
boolean foundStartingIndex = false;
ArrayList<Layer> layers = new ArrayList<Layer>();
ArrayList<Node> nodesForThisLayer = new ArrayList<Node>();
int pastLayerNum = 0;
// find all possible sequence lineups for the two phonemic sequences
for(int s = 0; s < shorterWord.getListOfPhonemes().size(); s++){
double weightTowardsWordEnd = 0.1;
if(firstSearch == true){
Node startNode = new Node();
for(int l = 0; l < longerWord.getListOfPhonemes().size(); l++){
double RVBetweenPhonemes = findRVBetweenPhonemes(shorterWord.getListOfPhonemes().get(s), longerWord.getListOfPhonemes().get(l), true, l * weightTowardsWordEnd);
if(RVBetweenPhonemes > 1){
foundStartingIndex = true;
RVIndexPair indexSet = new RVIndexPair(l, RVBetweenPhonemes);
startNode.addIndexSet(indexSet);
}
}
if(foundStartingIndex == true){
nodesForThisLayer.add(startNode);
layers.add(new Layer(nodesForThisLayer));
firstSearch = false;
}
nodesForThisLayer = new ArrayList<Node>();
debugPrint(startNode.toString());
}else{
for(int n = 0; n < layers.get(pastLayerNum).getNodes().size(); n++){
//loop for each node in the previous layer (aka every group of possibilites found)
debugPrint("Layer: " + (pastLayerNum) + ", " + "Node: " + n);
Node nodeBeingExamined = layers.get(pastLayerNum).getNodes().get(n);
for(int i = 0; i < nodeBeingExamined.getIndexSets().size(); i++){
//loop for the index sets in the node being examined
RVIndexPair setBeingExamined = nodeBeingExamined.getIndexSets().get(i);
Node childNode = new Node(); //node to be attached to the index set being examined.
int indexToStartAt = setBeingExamined.getIndexes().get(0);
debugPrint("setBeingExamined: " + setBeingExamined.toString());
if(indexToStartAt + 1 == longerWord.getListOfPhonemes().size()){
//do nothing
}else{
for(int l = indexToStartAt + 1; l < longerWord.getListOfPhonemes().size(); l++){
double RVBetweenPhonemes = findRVBetweenPhonemes(shorterWord.getListOfPhonemes().get(s), longerWord.getListOfPhonemes().get(l), true, l*weightTowardsWordEnd);
if(RVBetweenPhonemes > 1){
RVIndexPair indexSet = new RVIndexPair(l, RVBetweenPhonemes);
childNode.addIndexSet(indexSet);
}
}
setBeingExamined.attachChildNode(childNode);
nodesForThisLayer.add(childNode);
debugPrint("childNode: " + childNode.toString());
}
}
}
layers.add(new Layer(nodesForThisLayer));
nodesForThisLayer = new ArrayList<Node>();
pastLayerNum = pastLayerNum + 1;
}
}
//find best path
RVIndexPair bestSet = null;
Node nodeBeingExamined = null;
for(int l = layers.size()-1; l >= 0; l
for(int n = 0; n < layers.get(l).getNodes().size(); n++){
nodeBeingExamined = layers.get(l).getNodes().get(n);
if(nodeBeingExamined.getIndexSets().size()>0){
nodeBeingExamined.findBestIndexSetAndSendItUp();
}
}
if(l == 0 && layers.get(l).getNodes().size() == 1){
bestSet = nodeBeingExamined.getBestSet();
}
}
System.out.println(bestSet.getIndexes());
idealRhymeValue = bestSet.getRhymeValueForSet();
double rhymeValue = idealRhymeValue;
//subtract specing to get actual rhyme value
rhymeValue = rhymeValue - findDeductionForIndexSet(bestSet, longerWord);
return (double) findRhymePercentile(rhymeValue, longerWord);
}
/**Finds the Rhyme Value that a word has with itself (homophonic Rhyme Value) and then finds the percentage that the
* actual Rhyme Value matches with the homophonic RV
* @return Rhyme Percentile between two Words*/
private double findRhymePercentile(double rhymeValue, Word longerWord){
double homophonicRhymeValue = 0.0;
double rhymePercentile = 0.0;
double weightTowardsWordEnd = 0.1;
for(int i = 0; i < longerWord.getListOfPhonemes().size(); i++){
homophonicRhymeValue = homophonicRhymeValue +
findRVBetweenPhonemes(longerWord.getListOfPhonemes().get(i), longerWord.getListOfPhonemes().get(i), true, i*weightTowardsWordEnd);
}
debugPrint("RV: " + rhymeValue);
System.out.println("HRV: " + homophonicRhymeValue);
rhymePercentile = (double) rhymeValue / (double)homophonicRhymeValue;
if(rhymePercentile < 0){
rhymePercentile = 0;
}
return rhymePercentile;
}
/**Takes in two Phonemes and finds the amount that should be added to the Rhyme Value based on how well the two Phonemes match.
* @return The Rhyme Value between two phonemes*/
public double findRVBetweenPhonemes(Phoneme p1, Phoneme p2, boolean addWeight, double weight){
ArrayList<Integer> p1Features = p1.getFeatures();
ArrayList<Integer> p2Features = p2.getFeatures();
ArrayList<Integer> biggerList = null;
if(p1Features.size() >= p2Features.size()){
biggerList = p1Features;
}else{
biggerList = p2Features;
}
//contains just the features that the phonemes share
ArrayList<Integer> commonFeatures = new ArrayList<Integer>(p1Features);
commonFeatures.retainAll(p2Features);
int difference = biggerList.size() - commonFeatures.size();
if(p1.isAVowelPhoneme() && p2.isAVowelPhoneme()){
int stressDifference = Math.abs(p1.getStress() - p2.getStress());
return 5.0 - (1*difference) - stressDifference;
}else if(p1.isAVowelPhoneme() == false && p2.isAVowelPhoneme() == false){
int commonFeaturesSize = commonFeatures.size();
double specialDifference = 0; /*this is used for keeping track of differences that need different values to be subtracted
as opposed to the standard amount*/
if(p1.getPhoneme().equals(p2.getPhoneme()) == false){ /*This is here so that when homophonic rhyme value is being
calculated, the homophonic rhyme value won't differ according to feature sets and thus rhyme percentile won't be
altered based on the order in which the words were entered*/
if(commonFeatures.contains(9) == false){ //difference in voicing
specialDifference = specialDifference + 0.1;
commonFeaturesSize = commonFeaturesSize - 1;
}
if(commonFeatures.contains(2)){ //difference in sonority
specialDifference = specialDifference + 1;
commonFeaturesSize = commonFeaturesSize - 1;
}
}
difference = biggerList.size() - commonFeaturesSize;
return 2.0 - (0.15*difference) - specialDifference;
}else{ /*this is a bit different because we're starting at the assumption that they won't have much in common so it's structured
for rewarding common features rather than punishing for differences*/
//run same sonority and voicing tests but perhaps with different amounts rewarded for each
int commonFeaturesSize = commonFeatures.size();
double specialDifference = 0; /*this is used for keeping track of differences that need different values to be subtracted
as opposed to the standard amount*/
if(commonFeatures.contains(9) == false){ //difference in voicing
specialDifference = specialDifference + 0.1;
commonFeaturesSize = commonFeaturesSize - 1;
}
if(commonFeatures.contains(2)){ //difference in sonority
specialDifference = specialDifference + 1;
commonFeaturesSize = commonFeaturesSize - 1;
}
difference = biggerList.size() - commonFeaturesSize;
return 0.1*commonFeaturesSize + specialDifference;
}
}
/**To be used with Ideal Rhyme Value. Finds the amount that should be subtracted from the Ideal Rhyme Value based on the number of
* spaces between phonemes.
* @return The number to subtract from Ideal Rhyme Value*/
private double findDeductionForIndexSet(RVIndexPair bestSet, Word longerWord){
double deduction = 0.0;
debugPrint(bestSet.toString());
if(bestSet.getIndexes().get(0) > 0){
if(bestSet.getIndexes().get(0) > 1){
deduction = deduction + Math.log10(bestSet.getIndexes().get(0));
}else{
deduction = deduction + 0.25;
}
debugPrint("first index: " + bestSet.getIndexes().get(0));
debugPrint("DEDUCTION FROM FRONT: " + deduction);
}
if((longerWord.getListOfPhonemes().size() - 1) - bestSet.getIndexes().get(bestSet.getIndexes().size()-1) > 0){
deduction = deduction + Math.log10((longerWord.getListOfPhonemes().size() - 1) - bestSet.getIndexes().get(bestSet.getIndexes().size()-1));
}
for(int i = 0; i < bestSet.getIndexes().size() - 1; i++){
int index1 = bestSet.getIndexes().get(i);
int index2 = bestSet.getIndexes().get(i + 1);
debugPrint("index subtraction" + (index2 - index1-1));
deduction = deduction + (0.25 * (index2 - index1-1));
}
System.out.println("DEDUCTION: " + deduction);
return deduction;
}
public void debugPrint(Object x){
if(DEBUGGING == true){
System.out.println(x);
}
}
/**Returns the trie of the CMU Dictionary
* @return A trie of the CMU Dictionary*/
public Hashtable<String, String> getDictionary() {
return dictionary;
}
/**
* Sets this object's trie of the CMU Dictionary
* @param trie a RhymeDictionaryTrie*/
public void setDictionary(Hashtable<String, String> dictionary) {
this.dictionary = dictionary;
}
public Hashtable<String, Integer> getStructureReference() {
return structureReference;
}
public void setStructureReference(Hashtable<String, Integer> structureReference) {
this.structureReference = structureReference;
}
public ArrayList<String> getWordList() {
return wordList;
}
public void setWordList(ArrayList<String> wordList) {
this.wordList = wordList;
}
public static Hashtable<String, ArrayList<Integer>> getFeatures() {
return features;
}
public static void setFeatures(Hashtable<String, ArrayList<Integer>> featureList) {
features = featureList;
}
} |
package com.vaadin.terminal.gwt.client;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import com.google.gwt.core.client.Duration;
import com.google.gwt.core.client.JsArrayString;
import com.google.gwt.dom.client.Element;
import com.google.gwt.dom.client.Style.Unit;
import com.google.gwt.user.client.Timer;
import com.vaadin.terminal.gwt.client.MeasuredSize.MeasureResult;
import com.vaadin.terminal.gwt.client.ui.ManagedLayout;
import com.vaadin.terminal.gwt.client.ui.PostLayoutListener;
import com.vaadin.terminal.gwt.client.ui.SimpleManagedLayout;
import com.vaadin.terminal.gwt.client.ui.VNotification;
import com.vaadin.terminal.gwt.client.ui.layout.ElementResizeEvent;
import com.vaadin.terminal.gwt.client.ui.layout.ElementResizeListener;
import com.vaadin.terminal.gwt.client.ui.layout.LayoutDependencyTree;
import com.vaadin.terminal.gwt.client.ui.layout.RequiresOverflowAutoFix;
public class LayoutManager {
private static final String LOOP_ABORT_MESSAGE = "Aborting layout after 100 passes. This would probably be an infinite loop.";
private static final boolean debugLogging = false;
private ApplicationConnection connection;
private final Set<Element> measuredNonPaintableElements = new HashSet<Element>();
private final MeasuredSize nullSize = new MeasuredSize();
private LayoutDependencyTree currentDependencyTree;
private final Collection<ManagedLayout> needsHorizontalLayout = new HashSet<ManagedLayout>();
private final Collection<ManagedLayout> needsVerticalLayout = new HashSet<ManagedLayout>();
private final Collection<ComponentConnector> needsMeasure = new HashSet<ComponentConnector>();
private final Collection<ComponentConnector> pendingOverflowFixes = new HashSet<ComponentConnector>();
private final Map<Element, Collection<ElementResizeListener>> elementResizeListeners = new HashMap<Element, Collection<ElementResizeListener>>();
private final Set<Element> listenersToFire = new HashSet<Element>();
private boolean layoutPending = false;
private Timer layoutTimer = new Timer() {
@Override
public void run() {
cancel();
layoutNow();
}
};
private boolean everythingNeedsMeasure = false;
public void setConnection(ApplicationConnection connection) {
if (this.connection != null) {
throw new RuntimeException(
"LayoutManager connection can never be changed");
}
this.connection = connection;
}
public static LayoutManager get(ApplicationConnection connection) {
return connection.getLayoutManager();
}
public void registerDependency(ManagedLayout owner, Element element) {
MeasuredSize measuredSize = ensureMeasured(element);
setNeedsUpdate(owner);
measuredSize.addDependent(owner.getConnectorId());
}
private MeasuredSize ensureMeasured(Element element) {
MeasuredSize measuredSize = getMeasuredSize(element, null);
if (measuredSize == null) {
measuredSize = new MeasuredSize();
if (ConnectorMap.get(connection).getConnector(element) == null) {
measuredNonPaintableElements.add(element);
}
setMeasuredSize(element, measuredSize);
}
return measuredSize;
}
private boolean needsMeasure(Element e) {
if (connection.getConnectorMap().getConnectorId(e) != null) {
return true;
} else if (elementResizeListeners.containsKey(e)) {
return true;
} else if (getMeasuredSize(e, nullSize).hasDependents()) {
return true;
} else {
return false;
}
}
protected native void setMeasuredSize(Element element,
MeasuredSize measuredSize)
/*-{
if (measuredSize) {
element.vMeasuredSize = measuredSize;
} else {
delete element.vMeasuredSize;
}
}-*/;
private static native final MeasuredSize getMeasuredSize(Element element,
MeasuredSize defaultSize)
/*-{
return element.vMeasuredSize || defaultSize;
}-*/;
private final MeasuredSize getMeasuredSize(ComponentConnector connector) {
Element element = connector.getWidget().getElement();
MeasuredSize measuredSize = getMeasuredSize(element, null);
if (measuredSize == null) {
measuredSize = new MeasuredSize();
setMeasuredSize(element, measuredSize);
}
return measuredSize;
}
public void unregisterDependency(ManagedLayout owner, Element element) {
MeasuredSize measuredSize = getMeasuredSize(element, null);
if (measuredSize == null) {
return;
}
measuredSize.removeDependent(owner.getConnectorId());
stopMeasuringIfUnecessary(element);
}
public boolean isLayoutRunning() {
return currentDependencyTree != null;
}
private void countLayout(Map<ManagedLayout, Integer> layoutCounts,
ManagedLayout layout) {
Integer count = layoutCounts.get(layout);
if (count == null) {
count = Integer.valueOf(0);
} else {
count = Integer.valueOf(count.intValue() + 1);
}
layoutCounts.put(layout, count);
if (count.intValue() > 2) {
VConsole.error(Util.getConnectorString(layout)
+ " has been layouted " + count.intValue() + " times");
}
}
private void layoutLater() {
if (!layoutPending) {
layoutPending = true;
layoutTimer.schedule(100);
}
}
public void layoutNow() {
if (isLayoutRunning()) {
throw new IllegalStateException(
"Can't start a new layout phase before the previous layout phase ends.");
}
layoutPending = false;
try {
currentDependencyTree = new LayoutDependencyTree();
doLayout();
} finally {
currentDependencyTree = null;
}
}
private void doLayout() {
VConsole.log("Starting layout phase");
Map<ManagedLayout, Integer> layoutCounts = new HashMap<ManagedLayout, Integer>();
int passes = 0;
Duration totalDuration = new Duration();
for (ManagedLayout layout : needsHorizontalLayout) {
currentDependencyTree.setNeedsHorizontalLayout(layout, true);
}
for (ManagedLayout layout : needsVerticalLayout) {
currentDependencyTree.setNeedsVerticalLayout(layout, true);
}
needsHorizontalLayout.clear();
needsVerticalLayout.clear();
for (ComponentConnector connector : needsMeasure) {
currentDependencyTree.setNeedsMeasure(connector, true);
}
needsMeasure.clear();
measureNonPaintables();
VConsole.log("Layout init in " + totalDuration.elapsedMillis() + " ms");
while (true) {
Duration passDuration = new Duration();
passes++;
int measuredConnectorCount = measureConnectors(
currentDependencyTree, everythingNeedsMeasure);
everythingNeedsMeasure = false;
int measureTime = passDuration.elapsedMillis();
VConsole.log(" Measured " + measuredConnectorCount
+ " elements in " + measureTime + " ms");
if (!listenersToFire.isEmpty()) {
for (Element element : listenersToFire) {
Collection<ElementResizeListener> listeners = elementResizeListeners
.get(element);
ElementResizeListener[] array = listeners
.toArray(new ElementResizeListener[listeners.size()]);
ElementResizeEvent event = new ElementResizeEvent(this,
element);
for (ElementResizeListener listener : array) {
listener.onElementResize(event);
}
}
int measureListenerTime = passDuration.elapsedMillis();
VConsole.log(" Fired resize listeners for "
+ listenersToFire.size() + " elements in "
+ (measureListenerTime - measureTime) + " ms");
measureTime = measuredConnectorCount;
listenersToFire.clear();
}
FastStringSet updatedSet = FastStringSet.create();
boolean changed = false;
while (currentDependencyTree.hasHorizontalConnectorToLayout()
|| currentDependencyTree.hasVerticaConnectorToLayout()) {
changed = true;
for (ManagedLayout layout : currentDependencyTree
.getHorizontalLayoutTargets()) {
if (layout instanceof DirectionalManagedLayout) {
currentDependencyTree
.markAsHorizontallyLayouted(layout);
DirectionalManagedLayout cl = (DirectionalManagedLayout) layout;
cl.layoutHorizontally();
countLayout(layoutCounts, cl);
} else {
currentDependencyTree
.markAsHorizontallyLayouted(layout);
currentDependencyTree.markAsVerticallyLayouted(layout);
SimpleManagedLayout rr = (SimpleManagedLayout) layout;
rr.layout();
countLayout(layoutCounts, rr);
}
if (debugLogging) {
updatedSet.add(layout.getConnectorId());
}
}
for (ManagedLayout layout : currentDependencyTree
.getVerticalLayoutTargets()) {
if (layout instanceof DirectionalManagedLayout) {
currentDependencyTree.markAsVerticallyLayouted(layout);
DirectionalManagedLayout cl = (DirectionalManagedLayout) layout;
cl.layoutVertically();
countLayout(layoutCounts, cl);
} else {
currentDependencyTree
.markAsHorizontallyLayouted(layout);
currentDependencyTree.markAsVerticallyLayouted(layout);
SimpleManagedLayout rr = (SimpleManagedLayout) layout;
rr.layout();
countLayout(layoutCounts, rr);
}
if (debugLogging) {
updatedSet.add(layout.getConnectorId());
}
}
}
if (debugLogging) {
JsArrayString changedCids = updatedSet.dump();
StringBuilder b = new StringBuilder(" ");
b.append(changedCids.length());
b.append(" requestLayout invocations in ");
b.append(passDuration.elapsedMillis() - measureTime);
b.append(" ms");
if (changedCids.length() < 30) {
for (int i = 0; i < changedCids.length(); i++) {
if (i != 0) {
b.append(", ");
} else {
b.append(": ");
}
String connectorString = changedCids.get(i);
if (changedCids.length() < 10) {
ServerConnector connector = ConnectorMap.get(
connection).getConnector(connectorString);
connectorString = Util
.getConnectorString(connector);
}
b.append(connectorString);
}
}
VConsole.log(b.toString());
}
if (!changed) {
VConsole.log("No more changes in pass " + passes);
break;
}
VConsole.log("Pass " + passes + " completed in "
+ passDuration.elapsedMillis() + " ms");
if (passes > 100) {
VConsole.log(LOOP_ABORT_MESSAGE);
VNotification.createNotification(VNotification.DELAY_FOREVER)
.show(LOOP_ABORT_MESSAGE, VNotification.CENTERED,
"error");
break;
}
}
int postLayoutStart = totalDuration.elapsedMillis();
for (ComponentConnector connector : connection.getConnectorMap()
.getComponentConnectors()) {
if (connector instanceof PostLayoutListener) {
((PostLayoutListener) connector).postLayout();
}
}
VConsole.log("Invoke post layout listeners in "
+ (totalDuration.elapsedMillis() - postLayoutStart) + " ms");
VConsole.log("Total layout phase time: "
+ totalDuration.elapsedMillis() + "ms");
}
private void logConnectorStatus(int connectorId) {
currentDependencyTree
.logDependencyStatus((ComponentConnector) ConnectorMap.get(
connection).getConnector(Integer.toString(connectorId)));
}
private int measureConnectors(LayoutDependencyTree layoutDependencyTree,
boolean measureAll) {
if (!pendingOverflowFixes.isEmpty()) {
Duration duration = new Duration();
for (ComponentConnector componentConnector : pendingOverflowFixes) {
componentConnector.getWidget().getElement().getParentElement()
.getStyle().setTop(1, Unit.PX);
}
for (ComponentConnector componentConnector : pendingOverflowFixes) {
componentConnector.getWidget().getElement().getParentElement()
.getOffsetHeight();
}
for (ComponentConnector componentConnector : pendingOverflowFixes) {
componentConnector.getWidget().getElement().getParentElement()
.getStyle().setTop(0, Unit.PX);
layoutDependencyTree.setNeedsMeasure(componentConnector, true);
ComponentContainerConnector parent = componentConnector
.getParent();
if (parent instanceof ManagedLayout) {
ManagedLayout managedParent = (ManagedLayout) parent;
layoutDependencyTree.setNeedsHorizontalLayout(
managedParent, true);
layoutDependencyTree.setNeedsVerticalLayout(managedParent,
true);
}
}
VConsole.log("Did overflow fix for " + pendingOverflowFixes.size()
+ " elements in " + duration.elapsedMillis() + " ms");
pendingOverflowFixes.clear();
}
int measureCount = 0;
if (measureAll) {
ComponentConnector[] connectors = ConnectorMap.get(connection)
.getComponentConnectors();
for (ComponentConnector connector : connectors) {
measueConnector(connector);
}
for (ComponentConnector connector : connectors) {
layoutDependencyTree.setNeedsMeasure(connector, false);
}
measureCount += connectors.length;
}
while (layoutDependencyTree.hasConnectorsToMeasure()) {
Collection<ComponentConnector> measureTargets = layoutDependencyTree
.getMeasureTargets();
for (ComponentConnector connector : measureTargets) {
measueConnector(connector);
measureCount++;
}
for (ComponentConnector connector : measureTargets) {
layoutDependencyTree.setNeedsMeasure(connector, false);
}
}
return measureCount;
}
private void measueConnector(ComponentConnector connector) {
Element element = connector.getWidget().getElement();
MeasuredSize measuredSize = getMeasuredSize(connector);
MeasureResult measureResult = measuredAndUpdate(element, measuredSize);
if (measureResult.isChanged()) {
onConnectorChange(connector, measureResult.isWidthChanged(),
measureResult.isHeightChanged());
}
}
private void onConnectorChange(ComponentConnector connector,
boolean widthChanged, boolean heightChanged) {
doOverflowAutoFix(connector);
if (heightChanged) {
currentDependencyTree.markHeightAsChanged(connector);
}
if (widthChanged) {
currentDependencyTree.markWidthAsChanged(connector);
}
}
private void doOverflowAutoFix(ComponentConnector connector) {
if (connector.getParent() instanceof RequiresOverflowAutoFix
&& BrowserInfo.get().requiresOverflowAutoFix()
&& !"absolute".equals(connector.getWidget().getElement()
.getStyle().getPosition())) {
pendingOverflowFixes.add(connector);
}
}
private void measureNonPaintables() {
for (Element element : measuredNonPaintableElements) {
measuredAndUpdate(element, getMeasuredSize(element, null));
}
VConsole.log("Measured " + measuredNonPaintableElements.size()
+ " non paintable elements");
}
private MeasureResult measuredAndUpdate(Element element,
MeasuredSize measuredSize) {
MeasureResult measureResult = measuredSize.measure(element);
if (measureResult.isChanged()) {
notifyListenersAndDepdendents(element,
measureResult.isWidthChanged(),
measureResult.isHeightChanged());
}
return measureResult;
}
private void notifyListenersAndDepdendents(Element element,
boolean widthChanged, boolean heightChanged) {
assert widthChanged || heightChanged;
MeasuredSize measuredSize = getMeasuredSize(element, nullSize);
JsArrayString dependents = measuredSize.getDependents();
for (int i = 0; i < dependents.length(); i++) {
String pid = dependents.get(i);
ManagedLayout dependent = (ManagedLayout) connection
.getConnectorMap().getConnector(pid);
if (dependent != null) {
if (heightChanged) {
currentDependencyTree.setNeedsVerticalLayout(dependent,
true);
}
if (widthChanged) {
currentDependencyTree.setNeedsHorizontalLayout(dependent,
true);
}
}
}
if (elementResizeListeners.containsKey(element)) {
listenersToFire.add(element);
}
}
private static boolean isManagedLayout(ComponentConnector paintable) {
return paintable instanceof ManagedLayout;
}
public void forceLayout() {
ConnectorMap paintableMap = connection.getConnectorMap();
ComponentConnector[] paintableWidgets = paintableMap
.getComponentConnectors();
for (ComponentConnector connector : paintableWidgets) {
if (connector instanceof ManagedLayout) {
setNeedsUpdate((ManagedLayout) connector);
}
}
setEverythingNeedsMeasure();
layoutNow();
}
// TODO Rename to setNeedsLayout
public final void setNeedsUpdate(ManagedLayout layout) {
setWidthNeedsUpdate(layout);
setHeightNeedsUpdate(layout);
}
public final void setWidthNeedsUpdate(ManagedLayout layout) {
needsHorizontalLayout.add(layout);
}
public final void setHeightNeedsUpdate(ManagedLayout layout) {
needsVerticalLayout.add(layout);
}
public boolean isMeasured(Element element) {
return getMeasuredSize(element, nullSize) != nullSize;
}
public final int getOuterHeight(Element element) {
return getMeasuredSize(element, nullSize).getOuterHeight();
}
public final int getOuterWidth(Element element) {
return getMeasuredSize(element, nullSize).getOuterWidth();
}
public final int getInnerHeight(Element element) {
return getMeasuredSize(element, nullSize).getInnerHeight();
}
public final int getInnerWidth(Element element) {
return getMeasuredSize(element, nullSize).getInnerWidth();
}
public final int getBorderHeight(Element element) {
return getMeasuredSize(element, nullSize).getBorderHeight();
}
public int getPaddingHeight(Element element) {
return getMeasuredSize(element, nullSize).getPaddingHeight();
}
public int getBorderWidth(Element element) {
return getMeasuredSize(element, nullSize).getBorderWidth();
}
public int getPaddingWidth(Element element) {
return getMeasuredSize(element, nullSize).getPaddingWidth();
}
public int getPaddingTop(Element element) {
return getMeasuredSize(element, nullSize).getPaddingTop();
}
public int getPaddingLeft(Element element) {
return getMeasuredSize(element, nullSize).getPaddingLeft();
}
public int getPaddingBottom(Element element) {
return getMeasuredSize(element, nullSize).getPaddingBottom();
}
public int getPaddingRight(Element element) {
return getMeasuredSize(element, nullSize).getPaddingRight();
}
public int getMarginTop(Element element) {
return getMeasuredSize(element, nullSize).getMarginTop();
}
public int getMarginRight(Element element) {
return getMeasuredSize(element, nullSize).getMarginRight();
}
public int getMarginBottom(Element element) {
return getMeasuredSize(element, nullSize).getMarginBottom();
}
public int getMarginLeft(Element element) {
return getMeasuredSize(element, nullSize).getMarginLeft();
}
public void reportOuterHeight(ComponentConnector component, int outerHeight) {
MeasuredSize measuredSize = getMeasuredSize(component);
if (isLayoutRunning()) {
boolean heightChanged = measuredSize.setOuterHeight(outerHeight);
if (heightChanged) {
onConnectorChange(component, false, true);
notifyListenersAndDepdendents(component.getWidget()
.getElement(), false, true);
}
currentDependencyTree.setNeedsVerticalMeasure(component, false);
} else if (measuredSize.getOuterHeight() != outerHeight) {
setNeedsMeasure(component);
}
}
public void reportHeightAssignedToRelative(ComponentConnector component,
int assignedHeight) {
assert component.isRelativeHeight();
float percentSize = parsePercent(component.getState().getHeight());
int effectiveHeight = Math.round(assignedHeight * (percentSize / 100));
reportOuterHeight(component, effectiveHeight);
}
public void reportWidthAssignedToRelative(ComponentConnector component,
int assignedWidth) {
assert component.isRelativeWidth();
float percentSize = parsePercent(component.getState().getWidth());
int effectiveWidth = Math.round(assignedWidth * (percentSize / 100));
reportOuterWidth(component, effectiveWidth);
}
private static float parsePercent(String size) {
return Float.parseFloat(size.substring(0, size.length() - 1));
}
public void reportOuterWidth(ComponentConnector component, int outerWidth) {
MeasuredSize measuredSize = getMeasuredSize(component);
if (isLayoutRunning()) {
boolean widthChanged = measuredSize.setOuterWidth(outerWidth);
if (widthChanged) {
onConnectorChange(component, true, false);
notifyListenersAndDepdendents(component.getWidget()
.getElement(), true, false);
}
currentDependencyTree.setNeedsHorizontalMeasure(component, false);
} else if (measuredSize.getOuterWidth() != outerWidth) {
setNeedsMeasure(component);
}
}
public void addElementResizeListener(Element element,
ElementResizeListener listener) {
Collection<ElementResizeListener> listeners = elementResizeListeners
.get(element);
if (listeners == null) {
listeners = new HashSet<ElementResizeListener>();
elementResizeListeners.put(element, listeners);
ensureMeasured(element);
}
listeners.add(listener);
}
public void removeElementResizeListener(Element element,
ElementResizeListener listener) {
Collection<ElementResizeListener> listeners = elementResizeListeners
.get(element);
if (listeners != null) {
listeners.remove(listener);
if (listeners.isEmpty()) {
elementResizeListeners.remove(element);
stopMeasuringIfUnecessary(element);
}
}
}
private void stopMeasuringIfUnecessary(Element element) {
if (!needsMeasure(element)) {
measuredNonPaintableElements.remove(element);
setMeasuredSize(element, null);
}
}
public void setNeedsMeasure(ComponentConnector component) {
if (isLayoutRunning()) {
currentDependencyTree.setNeedsMeasure(component, true);
} else {
needsMeasure.add(component);
layoutLater();
}
}
public void setEverythingNeedsMeasure() {
everythingNeedsMeasure = true;
}
} |
package com.vaadin.terminal.gwt.client;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import com.google.gwt.core.client.Duration;
import com.google.gwt.core.client.JsArrayString;
import com.google.gwt.dom.client.Element;
import com.google.gwt.dom.client.Style.Unit;
import com.vaadin.terminal.gwt.client.MeasuredSize.MeasureResult;
import com.vaadin.terminal.gwt.client.ui.ManagedLayout;
import com.vaadin.terminal.gwt.client.ui.PostLayoutListener;
import com.vaadin.terminal.gwt.client.ui.SimpleManagedLayout;
import com.vaadin.terminal.gwt.client.ui.VNotification;
import com.vaadin.terminal.gwt.client.ui.layout.LayoutDependencyTree;
import com.vaadin.terminal.gwt.client.ui.layout.RequiresOverflowAutoFix;
public class LayoutManager {
private static final String LOOP_ABORT_MESSAGE = "Aborting layout after 100 passes. This would probably be an infinite loop.";
private ApplicationConnection connection;
private final Set<Element> nonPaintableElements = new HashSet<Element>();
private final MeasuredSize nullSize = new MeasuredSize();
private LayoutDependencyTree currentDependencyTree;
private final Collection<ManagedLayout> needsHorizontalLayout = new HashSet<ManagedLayout>();
private final Collection<ManagedLayout> needsVerticalLayout = new HashSet<ManagedLayout>();
private final Collection<ComponentConnector> pendingOverflowFixes = new HashSet<ComponentConnector>();
public void setConnection(ApplicationConnection connection) {
if (this.connection != null) {
throw new RuntimeException(
"LayoutManager connection can never be changed");
}
this.connection = connection;
}
public static LayoutManager get(ApplicationConnection connection) {
return connection.getLayoutManager();
}
public void registerDependency(ManagedLayout owner, Element element) {
MeasuredSize measuredSize = ensureMeasured(element);
setNeedsUpdate(owner);
measuredSize.addDependent(owner.getConnectorId());
}
private MeasuredSize ensureMeasured(Element element) {
MeasuredSize measuredSize = getMeasuredSize(element, null);
if (measuredSize == null) {
measuredSize = new MeasuredSize();
if (ConnectorMap.get(connection).getConnector(element) == null) {
nonPaintableElements.add(element);
}
setMeasuredSize(element, measuredSize);
}
return measuredSize;
}
private boolean needsMeasure(Element e) {
if (connection.getConnectorMap().getConnectorId(e) != null) {
return true;
} else if (getMeasuredSize(e, nullSize).hasDependents()) {
return true;
} else {
return false;
}
}
protected native void setMeasuredSize(Element element,
MeasuredSize measuredSize)
/*-{
if (measuredSize) {
element.vMeasuredSize = measuredSize;
} else {
delete element.vMeasuredSize;
}
}-*/;
private static native final MeasuredSize getMeasuredSize(Element element,
MeasuredSize defaultSize)
/*-{
return element.vMeasuredSize || defaultSize;
}-*/;
private final MeasuredSize getMeasuredSize(ComponentConnector paintable) {
Element element = paintable.getWidget().getElement();
MeasuredSize measuredSize = getMeasuredSize(element, null);
if (measuredSize == null) {
measuredSize = new MeasuredSize();
setMeasuredSize(element, measuredSize);
}
return measuredSize;
}
public void unregisterDependency(ManagedLayout owner, Element element) {
MeasuredSize measuredSize = getMeasuredSize(element, null);
if (measuredSize == null) {
return;
}
measuredSize.removeDependent(owner.getConnectorId());
if (!needsMeasure(element)) {
nonPaintableElements.remove(element);
setMeasuredSize(element, null);
}
}
public boolean isLayoutRunning() {
return currentDependencyTree != null;
}
private void countLayout(Map<ManagedLayout, Integer> layoutCounts,
ManagedLayout layout) {
Integer count = layoutCounts.get(layout);
if (count == null) {
count = Integer.valueOf(0);
} else {
count = Integer.valueOf(count.intValue() + 1);
}
layoutCounts.put(layout, count);
if (count.intValue() > 2) {
VConsole.error(Util.getConnectorString(layout)
+ " has been layouted " + count.intValue() + " times");
}
}
public void doLayout() {
if (isLayoutRunning()) {
throw new IllegalStateException(
"Can't start a new layout phase before the previous layout phase ends.");
}
VConsole.log("Starting layout phase");
Map<ManagedLayout, Integer> layoutCounts = new HashMap<ManagedLayout, Integer>();
int passes = 0;
Duration totalDuration = new Duration();
currentDependencyTree = new LayoutDependencyTree();
for (ManagedLayout layout : needsHorizontalLayout) {
currentDependencyTree.setNeedsHorizontalLayout(layout, true);
}
for (ManagedLayout layout : needsVerticalLayout) {
currentDependencyTree.setNeedsVerticalLayout(layout, true);
}
needsHorizontalLayout.clear();
needsVerticalLayout.clear();
measureNonPaintables(currentDependencyTree);
VConsole.log("Layout init in " + totalDuration.elapsedMillis() + " ms");
while (true) {
Duration passDuration = new Duration();
passes++;
int measuredConnectorCount = measureConnectors(
currentDependencyTree, passes == 1);
int measureTime = passDuration.elapsedMillis();
VConsole.log(" Measured " + measuredConnectorCount
+ " elements in " + measureTime + " ms");
FastStringSet updatedSet = FastStringSet.create();
while (currentDependencyTree.hasHorizontalConnectorToLayout()
|| currentDependencyTree.hasVerticaConnectorToLayout()) {
for (ManagedLayout layout : currentDependencyTree
.getHorizontalLayoutTargets()) {
if (layout instanceof DirectionalManagedLayout) {
currentDependencyTree
.markAsHorizontallyLayouted(layout);
DirectionalManagedLayout cl = (DirectionalManagedLayout) layout;
cl.layoutHorizontally();
countLayout(layoutCounts, cl);
} else {
currentDependencyTree
.markAsHorizontallyLayouted(layout);
currentDependencyTree.markAsVerticallyLayouted(layout);
SimpleManagedLayout rr = (SimpleManagedLayout) layout;
rr.layout();
countLayout(layoutCounts, rr);
}
updatedSet.add(layout.getConnectorId());
}
for (ManagedLayout layout : currentDependencyTree
.getVerticalLayoutTargets()) {
if (layout instanceof DirectionalManagedLayout) {
currentDependencyTree.markAsVerticallyLayouted(layout);
DirectionalManagedLayout cl = (DirectionalManagedLayout) layout;
cl.layoutVertically();
countLayout(layoutCounts, cl);
} else {
currentDependencyTree
.markAsHorizontallyLayouted(layout);
currentDependencyTree.markAsVerticallyLayouted(layout);
SimpleManagedLayout rr = (SimpleManagedLayout) layout;
rr.layout();
countLayout(layoutCounts, rr);
}
updatedSet.add(layout.getConnectorId());
}
}
JsArrayString changed = updatedSet.dump();
StringBuilder b = new StringBuilder(" ");
b.append(changed.length());
b.append(" requestLayout invocations in ");
b.append(passDuration.elapsedMillis() - measureTime);
b.append(" ms");
if (changed.length() < 30) {
for (int i = 0; i < changed.length(); i++) {
if (i != 0) {
b.append(", ");
} else {
b.append(": ");
}
String connectorString = changed.get(i);
if (changed.length() < 10) {
ServerConnector connector = ConnectorMap
.get(connection).getConnector(connectorString);
connectorString = Util.getConnectorString(connector);
}
b.append(connectorString);
}
}
VConsole.log(b.toString());
if (changed.length() == 0) {
VConsole.log("No more changes in pass " + passes);
break;
}
VConsole.log("Pass " + passes + " completed in "
+ passDuration.elapsedMillis() + " ms");
if (passes > 100) {
VConsole.log(LOOP_ABORT_MESSAGE);
VNotification.createNotification(VNotification.DELAY_FOREVER)
.show(LOOP_ABORT_MESSAGE, VNotification.CENTERED,
"error");
break;
}
}
int postLayoutStart = totalDuration.elapsedMillis();
for (ComponentConnector connector : connection.getConnectorMap()
.getComponentConnectors()) {
if (connector instanceof PostLayoutListener) {
((PostLayoutListener) connector).postLayout();
}
}
VConsole.log("Invoke post layout listeners in "
+ (totalDuration.elapsedMillis() - postLayoutStart) + " ms");
currentDependencyTree = null;
VConsole.log("Total layout phase time: "
+ totalDuration.elapsedMillis() + "ms");
}
private void logConnectorStatus(int connectorId) {
currentDependencyTree
.logDependencyStatus((ComponentConnector) ConnectorMap.get(
connection).getConnector(Integer.toString(connectorId)));
}
private int measureConnectors(LayoutDependencyTree layoutDependencyTree,
boolean measureAll) {
if (!pendingOverflowFixes.isEmpty()) {
Duration duration = new Duration();
for (ComponentConnector componentConnector : pendingOverflowFixes) {
componentConnector.getWidget().getElement().getParentElement()
.getStyle().setTop(1, Unit.PX);
}
for (ComponentConnector componentConnector : pendingOverflowFixes) {
componentConnector.getWidget().getElement().getParentElement()
.getOffsetHeight();
}
for (ComponentConnector componentConnector : pendingOverflowFixes) {
componentConnector.getWidget().getElement().getParentElement()
.getStyle().setTop(0, Unit.PX);
layoutDependencyTree.setNeedsMeasure(componentConnector, true);
ComponentContainerConnector parent = componentConnector
.getParent();
if (parent instanceof ManagedLayout) {
ManagedLayout managedParent = (ManagedLayout) parent;
layoutDependencyTree.setNeedsHorizontalLayout(
managedParent, true);
layoutDependencyTree.setNeedsVerticalLayout(managedParent,
true);
}
}
VConsole.log("Did overflow fix for " + pendingOverflowFixes.size()
+ " elements in " + duration.elapsedMillis() + " ms");
pendingOverflowFixes.clear();
}
int measureCount = 0;
if (measureAll) {
ComponentConnector[] connectors = ConnectorMap.get(connection)
.getComponentConnectors();
for (ComponentConnector connector : connectors) {
measueConnector(layoutDependencyTree, connector);
}
for (ComponentConnector connector : connectors) {
layoutDependencyTree.setNeedsMeasure(connector, false);
}
measureCount += connectors.length;
}
while (layoutDependencyTree.hasConnectorsToMeasure()) {
Collection<ComponentConnector> measureTargets = layoutDependencyTree
.getMeasureTargets();
for (ComponentConnector connector : measureTargets) {
measueConnector(layoutDependencyTree, connector);
measureCount++;
}
for (ComponentConnector connector : measureTargets) {
layoutDependencyTree.setNeedsMeasure(connector, false);
}
}
return measureCount;
}
private void measueConnector(LayoutDependencyTree layoutDependencyTree,
ComponentConnector connector) {
Element element = connector.getWidget().getElement();
MeasuredSize measuredSize = getMeasuredSize(connector);
MeasureResult measureResult = measuredAndUpdate(element, measuredSize,
layoutDependencyTree);
if (measureResult.isChanged()) {
doOverflowAutoFix(connector);
}
if (measureResult.isHeightChanged()) {
layoutDependencyTree.markHeightAsChanged(connector);
}
if (measureResult.isWidthChanged()) {
layoutDependencyTree.markWidthAsChanged(connector);
}
}
private void doOverflowAutoFix(ComponentConnector connector) {
if (connector.getParent() instanceof RequiresOverflowAutoFix
&& BrowserInfo.get().requiresOverflowAutoFix()
&& !"absolute".equals(connector.getWidget().getElement()
.getStyle().getPosition())) {
pendingOverflowFixes.add(connector);
}
}
private void measureNonPaintables(LayoutDependencyTree layoutDependencyTree) {
for (Element element : nonPaintableElements) {
MeasuredSize measuredSize = getMeasuredSize(element, null);
measuredAndUpdate(element, measuredSize, layoutDependencyTree);
}
VConsole.log("Measured " + nonPaintableElements.size()
+ " non paintable elements");
}
private MeasureResult measuredAndUpdate(Element element,
MeasuredSize measuredSize, LayoutDependencyTree layoutDependencyTree) {
MeasureResult measureResult = measuredSize.measure(element);
if (measureResult.isChanged()) {
JsArrayString dependents = measuredSize.getDependents();
for (int i = 0; i < dependents.length(); i++) {
String pid = dependents.get(i);
ManagedLayout dependent = (ManagedLayout) connection
.getConnectorMap().getConnector(pid);
if (dependent != null) {
if (measureResult.isHeightChanged()) {
layoutDependencyTree.setNeedsVerticalLayout(dependent,
true);
}
if (measureResult.isWidthChanged()) {
layoutDependencyTree.setNeedsHorizontalLayout(
dependent, true);
}
}
}
}
return measureResult;
}
private static boolean isManagedLayout(ComponentConnector paintable) {
return paintable instanceof ManagedLayout;
}
public void forceLayout() {
ConnectorMap paintableMap = connection.getConnectorMap();
ComponentConnector[] paintableWidgets = paintableMap
.getComponentConnectors();
for (ComponentConnector connector : paintableWidgets) {
if (connector instanceof ManagedLayout) {
setNeedsUpdate((ManagedLayout) connector);
}
}
doLayout();
}
// TODO Rename to setNeedsLayout
public final void setNeedsUpdate(ManagedLayout layout) {
setWidthNeedsUpdate(layout);
setHeightNeedsUpdate(layout);
}
public final void setWidthNeedsUpdate(ManagedLayout layout) {
needsHorizontalLayout.add(layout);
}
public final void setHeightNeedsUpdate(ManagedLayout layout) {
needsVerticalLayout.add(layout);
}
public boolean isMeasured(Element element) {
return getMeasuredSize(element, nullSize) != nullSize;
}
public final int getOuterHeight(Element element) {
return getMeasuredSize(element, nullSize).getOuterHeight();
}
public final int getOuterWidth(Element element) {
return getMeasuredSize(element, nullSize).getOuterWidth();
}
public final int getInnerHeight(Element element) {
return getMeasuredSize(element, nullSize).getInnerHeight();
}
public final int getInnerWidth(Element element) {
return getMeasuredSize(element, nullSize).getInnerWidth();
}
public final int getBorderHeight(Element element) {
return getMeasuredSize(element, nullSize).getBorderHeight();
}
public int getPaddingHeight(Element element) {
return getMeasuredSize(element, nullSize).getPaddingHeight();
}
public int getBorderWidth(Element element) {
return getMeasuredSize(element, nullSize).getBorderWidth();
}
public int getPaddingWidth(Element element) {
return getMeasuredSize(element, nullSize).getPaddingWidth();
}
public int getPaddingTop(Element element) {
return getMeasuredSize(element, nullSize).getPaddingTop();
}
public int getPaddingLeft(Element element) {
return getMeasuredSize(element, nullSize).getPaddingLeft();
}
public int getPaddingBottom(Element element) {
return getMeasuredSize(element, nullSize).getPaddingBottom();
}
public int getPaddingRight(Element element) {
return getMeasuredSize(element, nullSize).getPaddingRight();
}
public int getMarginTop(Element element) {
return getMeasuredSize(element, nullSize).getMarginTop();
}
public int getMarginRight(Element element) {
return getMeasuredSize(element, nullSize).getMarginRight();
}
public int getMarginBottom(Element element) {
return getMeasuredSize(element, nullSize).getMarginBottom();
}
public int getMarginLeft(Element element) {
return getMeasuredSize(element, nullSize).getMarginLeft();
}
public void reportOuterHeight(ComponentConnector component, int outerHeight) {
if (!isLayoutRunning()) {
throw new IllegalStateException(
"Can only report sizes when layout is running");
}
MeasuredSize measuredSize = getMeasuredSize(component);
boolean heightChanged = measuredSize.setOuterHeight(outerHeight);
if (heightChanged) {
currentDependencyTree.markHeightAsChanged(component);
doOverflowAutoFix(component);
}
currentDependencyTree.setNeedsVerticalMeasure(component, false);
}
public void reportHeightAssignedToRelative(ComponentConnector component,
int assignedHeight) {
assert component.isRelativeHeight();
float percentSize = parsePercent(component.getState().getHeight());
int effectiveHeight = Math.round(assignedHeight * (percentSize / 100));
reportOuterHeight(component, effectiveHeight);
}
public void reportWidthAssignedToRelative(ComponentConnector component,
int assignedWidth) {
assert component.isRelativeWidth();
float percentSize = parsePercent(component.getState().getWidth());
int effectiveWidth = Math.round(assignedWidth * (percentSize / 100));
reportOuterWidth(component, effectiveWidth);
}
private static float parsePercent(String size) {
return Float.parseFloat(size.substring(0, size.length() - 1));
}
public void reportOuterWidth(ComponentConnector component, int outerWidth) {
if (!isLayoutRunning()) {
throw new IllegalStateException(
"Can only report sizes when layout is running");
}
MeasuredSize measuredSize = getMeasuredSize(component);
boolean widthChanged = measuredSize.setOuterWidth(outerWidth);
if (widthChanged) {
currentDependencyTree.markWidthAsChanged(component);
doOverflowAutoFix(component);
}
currentDependencyTree.setNeedsHorizontalMeasure(component, false);
}
} |
package com.vaadin.terminal.gwt.client.ui;
import java.util.HashSet;
import java.util.Iterator;
import java.util.NoSuchElementException;
import java.util.Set;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.logical.shared.CloseEvent;
import com.google.gwt.event.logical.shared.CloseHandler;
import com.google.gwt.user.client.DOM;
import com.google.gwt.user.client.Element;
import com.google.gwt.user.client.Event;
import com.google.gwt.user.client.ui.Focusable;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.PopupPanel;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.gwt.user.client.ui.Widget;
import com.vaadin.terminal.gwt.client.ApplicationConnection;
import com.vaadin.terminal.gwt.client.Container;
import com.vaadin.terminal.gwt.client.Paintable;
import com.vaadin.terminal.gwt.client.RenderSpace;
import com.vaadin.terminal.gwt.client.UIDL;
import com.vaadin.terminal.gwt.client.Util;
import com.vaadin.terminal.gwt.client.VCaption;
import com.vaadin.terminal.gwt.client.VCaptionWrapper;
import com.vaadin.terminal.gwt.client.VTooltip;
import com.vaadin.terminal.gwt.client.RenderInformation.Size;
public class VPopupView extends HTML implements Container, Iterable<Widget> {
public static final String CLASSNAME = "v-popupview";
/** For server-client communication */
private String uidlId;
private ApplicationConnection client;
/** This variable helps to communicate popup visibility to the server */
private boolean hostPopupVisible;
private final CustomPopup popup;
private final Label loading = new Label();
/**
* loading constructor
*/
public VPopupView() {
super();
popup = new CustomPopup();
setStyleName(CLASSNAME);
popup.setStylePrimaryName(CLASSNAME + "-popup");
loading.setStyleName(CLASSNAME + "-loading");
setHTML("");
popup.setWidget(loading);
// When we click to open the popup...
addClickHandler(new ClickHandler() {
public void onClick(ClickEvent event) {
updateState(true);
}
});
// ..and when we close it
popup.addCloseHandler(new CloseHandler<PopupPanel>() {
public void onClose(CloseEvent<PopupPanel> event) {
updateState(false);
}
});
popup.setAnimationEnabled(true);
sinkEvents(VTooltip.TOOLTIP_EVENTS);
}
/**
*
*
* @see com.vaadin.terminal.gwt.client.Paintable#updateFromUIDL(com.vaadin.terminal.gwt.client.UIDL,
* com.vaadin.terminal.gwt.client.ApplicationConnection)
*/
public void updateFromUIDL(UIDL uidl, ApplicationConnection client) {
// This call should be made first. Ensure correct implementation,
// and don't let the containing layout manage caption.
if (client.updateComponent(this, uidl, false)) {
return;
}
// These are for future server connections
this.client = client;
uidlId = uidl.getId();
hostPopupVisible = uidl.getBooleanVariable("popupVisibility");
setHTML(uidl.getStringAttribute("html"));
if (uidl.hasAttribute("hideOnMouseOut")) {
popup.setHideOnMouseOut(uidl.getBooleanAttribute("hideOnMouseOut"));
}
// Render the popup if visible and show it.
if (hostPopupVisible) {
UIDL popupUIDL = uidl.getChildUIDL(0);
// showPopupOnTop(popup, hostReference);
preparePopup(popup);
popup.updateFromUIDL(popupUIDL, client);
if (uidl.hasAttribute("style")) {
final String[] styles = uidl.getStringAttribute("style").split(
" ");
final StringBuffer styleBuf = new StringBuffer();
final String primaryName = popup.getStylePrimaryName();
styleBuf.append(primaryName);
for (int i = 0; i < styles.length; i++) {
styleBuf.append(" ");
styleBuf.append(primaryName);
styleBuf.append("-");
styleBuf.append(styles[i]);
}
popup.setStyleName(styleBuf.toString());
} else {
popup.setStyleName(popup.getStylePrimaryName());
}
showPopup(popup);
// The popup shouldn't be visible, try to hide it.
} else {
popup.hide();
}
}// updateFromUIDL
/**
* Update popup visibility to server
*
* @param visibility
*/
private void updateState(boolean visible) {
// If we know the server connection
// then update the current situation
if (uidlId != null && client != null && isAttached()) {
client.updateVariable(uidlId, "popupVisibility", visible, true);
}
}
private void preparePopup(final CustomPopup popup) {
popup.setVisible(false);
popup.show();
}
private void showPopup(final CustomPopup popup) {
int windowTop = RootPanel.get().getAbsoluteTop();
int windowLeft = RootPanel.get().getAbsoluteLeft();
int windowRight = windowLeft + RootPanel.get().getOffsetWidth();
int windowBottom = windowTop + RootPanel.get().getOffsetHeight();
int offsetWidth = popup.getOffsetWidth();
int offsetHeight = popup.getOffsetHeight();
int hostHorizontalCenter = VPopupView.this.getAbsoluteLeft()
+ VPopupView.this.getOffsetWidth() / 2;
int hostVerticalCenter = VPopupView.this.getAbsoluteTop()
+ VPopupView.this.getOffsetHeight() / 2;
int left = hostHorizontalCenter - offsetWidth / 2;
int top = hostVerticalCenter - offsetHeight / 2;
// Don't show the popup outside the screen.
if ((left + offsetWidth) > windowRight) {
left -= (left + offsetWidth) - windowRight;
}
if ((top + offsetHeight) > windowBottom) {
top -= (top + offsetHeight) - windowBottom;
}
if (left < 0) {
left = 0;
}
if (top < 0) {
top = 0;
}
popup.setPopupPosition(left, top);
popup.setVisible(true);
}
/**
* Make sure that we remove the popup when the main widget is removed.
*
* @see com.google.gwt.user.client.ui.Widget#onUnload()
*/
@Override
protected void onDetach() {
popup.hide();
super.onDetach();
}
private static native void nativeBlur(Element e)
/*-{
if(e && e.blur) {
e.blur();
}
}-*/;
private class CustomPopup extends VOverlay {
private Paintable popupComponentPaintable = null;
private Widget popupComponentWidget = null;
private VCaptionWrapper captionWrapper = null;
private boolean hasHadMouseOver = false;
private boolean hideOnMouseOut = true;
private final Set<Element> activeChildren = new HashSet<Element>();
private boolean hiding = false;
public CustomPopup() {
super(true, false, true); // autoHide, not modal, dropshadow
}
// For some reason ONMOUSEOUT events are not always received, so we have
// to use ONMOUSEMOVE that doesn't target the popup
@Override
public boolean onEventPreview(Event event) {
Element target = DOM.eventGetTarget(event);
boolean eventTargetsPopup = DOM.isOrHasChild(getElement(), target);
int type = DOM.eventGetType(event);
// Catch children that use keyboard, so we can unfocus them when
// hiding
if (eventTargetsPopup && type == Event.ONKEYPRESS) {
activeChildren.add(target);
}
if (eventTargetsPopup && type == Event.ONMOUSEMOVE) {
hasHadMouseOver = true;
}
if (!eventTargetsPopup && type == Event.ONMOUSEMOVE) {
if (hasHadMouseOver && hideOnMouseOut) {
hide();
return true;
}
}
return super.onEventPreview(event);
}
@Override
public void hide(boolean autoClosed) {
hiding = true;
syncChildren();
unregisterPaintables();
if (popupComponentWidget != null && popupComponentWidget != loading) {
remove(popupComponentWidget);
}
hasHadMouseOver = false;
super.hide(autoClosed);
}
@Override
public void show() {
hiding = false;
super.show();
}
/**
* Try to sync all known active child widgets to server
*/
public void syncChildren() {
// Notify children with focus
if ((popupComponentWidget instanceof Focusable)) {
((Focusable) popupComponentWidget).setFocus(false);
}
// Notify children that have used the keyboard
for (Element e : activeChildren) {
try {
nativeBlur(e);
} catch (Exception ignored) {
}
}
activeChildren.clear();
}
@Override
public boolean remove(Widget w) {
popupComponentPaintable = null;
popupComponentWidget = null;
captionWrapper = null;
return super.remove(w);
}
public void updateFromUIDL(UIDL uidl, ApplicationConnection client) {
Paintable newPopupComponent = client.getPaintable(uidl
.getChildUIDL(0));
if (newPopupComponent != popupComponentPaintable) {
setWidget((Widget) newPopupComponent);
popupComponentWidget = (Widget) newPopupComponent;
popupComponentPaintable = newPopupComponent;
}
popupComponentPaintable
.updateFromUIDL(uidl.getChildUIDL(0), client);
}
public void unregisterPaintables() {
if (popupComponentPaintable != null) {
client.unregisterPaintable(popupComponentPaintable);
}
}
public void setHideOnMouseOut(boolean hideOnMouseOut) {
this.hideOnMouseOut = hideOnMouseOut;
}
/*
*
* We need a hack make popup act as a child of VPopupView in Vaadin's
* component tree, but work in default GWT manner when closing or
* opening.
*
* (non-Javadoc)
*
* @see com.google.gwt.user.client.ui.Widget#getParent()
*/
@Override
public Widget getParent() {
if (!isAttached() || hiding) {
return super.getParent();
} else {
return VPopupView.this;
}
}
@Override
protected void onDetach() {
super.onDetach();
hiding = false;
}
@Override
public Element getContainerElement() {
return super.getContainerElement();
}
}// class CustomPopup
// Container methods
public RenderSpace getAllocatedSpace(Widget child) {
Size popupExtra = calculatePopupExtra();
return new RenderSpace(RootPanel.get().getOffsetWidth()
- popupExtra.getWidth(), RootPanel.get().getOffsetHeight()
- popupExtra.getHeight());
}
/**
* Calculate extra space taken by the popup decorations
*
* @return
*/
protected Size calculatePopupExtra() {
Element pe = popup.getElement();
Element ipe = popup.getContainerElement();
// border + padding
int width = Util.getRequiredWidth(pe) - Util.getRequiredWidth(ipe);
int height = Util.getRequiredHeight(pe) - Util.getRequiredHeight(ipe);
return new Size(width, height);
}
public boolean hasChildComponent(Widget component) {
if (popup.popupComponentWidget != null) {
return popup.popupComponentWidget == component;
} else {
return false;
}
}
public void replaceChildComponent(Widget oldComponent, Widget newComponent) {
popup.setWidget(newComponent);
popup.popupComponentWidget = newComponent;
}
public boolean requestLayout(Set<Paintable> child) {
popup.updateShadowSizeAndPosition();
return true;
}
public void updateCaption(Paintable component, UIDL uidl) {
if (VCaption.isNeeded(uidl)) {
if (popup.captionWrapper != null) {
popup.captionWrapper.updateCaption(uidl);
} else {
popup.captionWrapper = new VCaptionWrapper(component, client);
popup.setWidget(popup.captionWrapper);
popup.captionWrapper.updateCaption(uidl);
}
} else {
if (popup.captionWrapper != null) {
popup.setWidget(popup.popupComponentWidget);
}
}
popup.popupComponentWidget = (Widget) component;
popup.popupComponentPaintable = component;
}
@Override
public void onBrowserEvent(Event event) {
super.onBrowserEvent(event);
if (client != null) {
client.handleTooltipEvent(event, this);
}
}
public Iterator<Widget> iterator() {
return new Iterator<Widget>() {
int pos = 0;
public boolean hasNext() {
// There is a child widget only if next() has not been called.
return (pos == 0);
}
public Widget next() {
// Next can be called only once to return the popup.
if (pos != 0) {
throw new NoSuchElementException();
}
pos++;
return popup;
}
public void remove() {
throw new UnsupportedOperationException();
}
};
}
}// class VPopupView |
package de.impelon.geotools.region;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.function.Consumer;
import org.bukkit.Location;
import org.bukkit.World;
import org.bukkit.util.Vector;
import de.impelon.geotools.Axis;
import de.impelon.geotools.RegionFormat;
import de.impelon.geotools.area.RectangularArea;
/**
* <p> Implementation of IRegion for a cuboid region. </p>
*
* @author Impelon
*
*/
public class CuboidRegion extends RectangularArea implements IRegion {
public CuboidRegion(Location locationA, Location locationB, boolean floor) throws IllegalArgumentException {
this(locationA.toVector(), locationB.toVector(), locationA.getWorld(), floor);
if (locationA.getWorld() != locationB.getWorld())
throw new IllegalArgumentException("Cannot add Locations of different Worlds to an Region");
}
public CuboidRegion(Location locationA, Location locationB) throws IllegalArgumentException {
this(locationA, locationB, false);
}
/**
* <p> Create a CuboidRegion from two given Vectors (corners) and a {@linkplain World}. </p>
*
* @param start determines first corner of the CuboidRegion
* @param end determines second corner of the CuboidRegion
* @param floor If true the corners will be converted to Block-Positions (aka. floored)
* @param world the {@linkplain World} this CuboidRegion is in
*/
public CuboidRegion(Vector start, Vector end, World world, boolean floor) {
this(floor ? new Vector(start.getBlockX(), start.getBlockY(), start.getBlockZ()) : start,
floor ? new Vector(end.getBlockX(), end.getBlockY(), end.getBlockZ()) : end, world);
}
/**
* <p> Create a CuboidRegion from two given Vectors (corners) and a {@linkplain World}. </p>
*
* @param start determines first corner of the CuboidRegion
* @param end determines second corner of the CuboidRegion
* @param world the {@linkplain World} this CuboidRegion is in
*/
public CuboidRegion(Vector start, Vector end, World world) {
super(start, end, world);
}
/**
* {@inheritDoc}
*/
@Override
public double getLength(Axis axis) {
switch (axis) {
case X:
case Z:
return super.getLength(axis);
case Y:
return this.endPos.getY() - this.startPos.getY();
default:
return 0;
}
}
/**
* {@inheritDoc}
*/
@Override
public long getBlockLength(Axis axis) {
switch (axis) {
case X:
case Z:
return super.getBlockLength(axis);
case Y:
return this.endPos.getBlockY() - this.startPos.getBlockY() + 1;
default:
return 0;
}
}
/**
* {@inheritDoc}
*/
@Override
public boolean getOverlap(Vector pos) {
return (pos.getX() <= this.endPos.getX() && pos.getX() >= this.startPos.getX()) &&
(pos.getY() <= this.endPos.getY() && pos.getY() >= this.startPos.getY()) &&
(pos.getZ() <= this.endPos.getZ() && pos.getZ() >= this.startPos.getZ());
}
/**
* {@inheritDoc}
*/
@Override
public boolean getOverlap(IRegion region) {
if (region instanceof CuboidRegion)
return this.getOverlap((CuboidRegion) region);
if (region.getWorld() != this.getWorld())
return false;
for (Iterator<Vector> iterator = this.iterator(); iterator.hasNext();)
if (region.getOverlap(iterator.next()))
return true;
return false;
}
/**
* <p> Determines if another CuboidRegion is within this Region. </p>
*
* @param region CuboidRegion to check
* @return Whether this Region overlaps with the given CuboidRegion
*/
public boolean getOverlap(CuboidRegion region) {
return region.getWorld() == this.getWorld()
&& (this.getOverlap(region.getStartPosition()) || this.getOverlap(region.getEndPosition()) ||
region.getOverlap(this.startPos) || region.getOverlap(this.endPos));
}
/**
* {@inheritDoc}
*/
@Override
public double getVolume() {
return this.getSurfaceArea() * this.getLength(Axis.Y);
}
/**
* {@inheritDoc}
*/
@Override
public long getBlockVolume() {
return this.getBlockSurfaceArea() * this.getBlockLength(Axis.Y);
}
/**
* {@inheritDoc}
*/
@Override
public IRegion getSubRegion(RegionFormat format) {
switch (format) {
case HOLLOW:
PositionRegion region = new PositionRegion(this);
region.remove(this.getSubRegion(RegionFormat.ENCLOSED));
return region;
case WIREFRAME:
HashSet<Vector> set = new HashSet<Vector>();
iterator().forEachRemaining(new Consumer<Vector>() {
@Override
public void accept(Vector v) {
if (((v.getBlockX() == getStartPosition().getBlockX() || v.getBlockX() == getEndPosition().getBlockX()) &&
(v.getBlockY() == getStartPosition().getBlockY() || v.getBlockY() == getEndPosition().getBlockY())) ||
((v.getBlockX() == getStartPosition().getBlockX() || v.getBlockX() == getEndPosition().getBlockX()) &&
(v.getBlockZ() == getStartPosition().getBlockZ() || v.getBlockZ() == getEndPosition().getBlockZ())) ||
((v.getBlockY() == getStartPosition().getBlockY() || v.getBlockY() == getEndPosition().getBlockY()) &&
(v.getBlockZ() == getStartPosition().getBlockZ() || v.getBlockZ() == getEndPosition().getBlockZ())))
set.add(v);
}
});
return new PositionRegion(this.getWorld(), set);
case FLOORED:
return new CuboidRegion(this.getStartPosition().toLocation(this.getWorld()), this.getEndPosition().toLocation(this.getWorld()), true);
case ENCLOSED:
return new CuboidRegion(this.getStartPosition().clone().add(new Vector(1, 1, 1)), this.getEndPosition().clone().add(new Vector(-1, -1, -1)), this.getWorld());
case SURROUNDING:
return new CuboidRegion(this.getStartPosition().clone().add(new Vector(-1, -1, -1)), this.getEndPosition().clone().add(new Vector(1, 1, 1)), this.getWorld());
case FULL:
default:
return new CuboidRegion(this.getStartPosition().clone(), this.getEndPosition().clone(), this.getWorld());
}
}
/**
* {@inheritDoc}
*/
@Override
public Iterator<Vector> iterator() {
Iterator<Vector> iterator = new Iterator<Vector>() {
private long x = 0;
private long y = 0;
private long z = 0;
private final Vector direction = endPos.clone().subtract(startPos).divide(new Vector(getBlockLength(Axis.X) - 1, getBlockLength(Axis.Y) - 1, getBlockLength(Axis.Z) - 1));
@Override
public boolean hasNext() {
return this.z < getBlockLength(Axis.Z);
}
@Override
public Vector next() {
Vector vector = startPos.clone().add(new Vector(x, y, z).multiply(direction));
x = (x + 1) % getBlockLength(Axis.X);
if (x == 0) {
y = (y + 1) % getBlockLength(Axis.Y);
if (y == 0)
z++;
}
return vector;
}
};
return iterator;
}
/**
* {@inheritDoc}
*/
@Override
public Iterator<Location> getLocationIterator() {
Iterator<Vector> vectoriterator = this.iterator();
Iterator<Location> iterator = new Iterator<Location>() {
@Override
public boolean hasNext() {
return vectoriterator.hasNext();
}
@Override
public Location next() {
return vectoriterator.next().toLocation(getWorld());
}
};
return iterator;
}
/**
* {@inheritDoc}
*/
@Override
public List<Vector> getVectors() {
ArrayList<Vector> vectors = new ArrayList<Vector>((int) this.getBlockVolume());
for (Iterator<Vector> iterator = this.iterator(); iterator.hasNext();)
vectors.add(iterator.next());
return vectors;
}
/**
* {@inheritDoc}
*/
@Override
public List<Location> getLocations() {
ArrayList<Location> locations = new ArrayList<Location>((int) this.getBlockVolume());
for (Iterator<Location> iterator = this.getLocationIterator(); iterator.hasNext();)
locations.add(iterator.next());
return locations;
}
} |
// JSONCoder.java
// xal
package xal.tools.json;
import xal.tools.ConversionAdaptor;
import java.lang.reflect.Array;
import java.util.*;
import java.util.regex.*;
/** encode and decode objects with JSON */
public class JSONCoder {
/** default coder */
static JSONCoder DEFAULT_CODER;
/** adaptors between all custom types and representation JSON types */
final MutableConversionAdaptorStore CONVERSION_ADAPTOR_STORE;
// static initializer
static {
DEFAULT_CODER = new JSONCoder( true );
}
/** get a new JSON Coder only if you need to customize it, otherwise use the static methods to encode/decode */
static public JSONCoder getInstance() {
return new JSONCoder( false );
}
/** Constructor to be called for the default coder */
private JSONCoder( final boolean isDefault ) {
CONVERSION_ADAPTOR_STORE = isDefault ? new MutableConversionAdaptorStore( true ) : new MutableConversionAdaptorStore( DEFAULT_CODER.CONVERSION_ADAPTOR_STORE );
}
/** Get a list of types (including JSON standard types plus default extensions) which are supported for coding and decoding */
static public List<String> getDefaultTypes() {
return DEFAULT_CODER.getSupportedTypes();
}
/** Get a list of the standard types encoded directly into JSON */
static public List<String> getStandardTypes() {
return ConversionAdaptorStore.getStandardTypes();
}
/** Determine whether the specified type is a standard JSON type */
static public boolean isStandardType( final String type ) {
return ConversionAdaptorStore.isStandardType( type );
}
/** Get a list of all types which are supported for coding and decoding */
public List<String> getSupportedTypes() {
return CONVERSION_ADAPTOR_STORE.getSupportedTypes();
}
/** Get a list of types which extend beyond the JSON standard types */
public List<String> getExtendedTypes() {
return CONVERSION_ADAPTOR_STORE.getExtendedTypes();
}
/**
* Register the custom type and its associated adaptor
* @param type type to identify and process for encoding and decoding
* @param adaptor translator between the custom type and representation JSON constructs
*/
public <CustomType,RepresentationType> void registerType( final Class<CustomType> type, final ConversionAdaptor<CustomType,RepresentationType> adaptor ) {
CONVERSION_ADAPTOR_STORE.registerType( type, adaptor );
}
/** Get the conversion adaptor for the given value */
protected ConversionAdaptor getConversionAdaptor( final String valueType ) {
return CONVERSION_ADAPTOR_STORE.getConversionAdaptor( valueType );
}
/**
* Decode the JSON string
* @param archive JSON string representation of an object
* @return an object with the data described in the archive
*/
static public Object decode( final String archive ) {
return DEFAULT_CODER.unarchive( archive );
}
/**
* Decode the JSON string
* @param archive JSON string representation of an object
* @return an object with the data described in the archive
*/
public Object unarchive( final String archive ) {
final AbstractDecoder decoder = AbstractDecoder.getInstance( archive, new ConversionAdaptorStore( CONVERSION_ADAPTOR_STORE ) );
return decoder != null ? decoder.decode() : null;
}
/** encode an object */
static public String encode( final Object value ) {
return DEFAULT_CODER.archive( value );
}
/** encode an object */
public String archive( final Object value ) {
return AbstractEncoder.encode( value, new ConversionAdaptorStore( CONVERSION_ADAPTOR_STORE ) );
}
}
/** Base class of encoders */
abstract class AbstractEncoder {
/** encode the value using the coder */
static public String encode( final Object value, final ConversionAdaptorStore conversionAdaptorStore ) {
return record( value, conversionAdaptorStore ).encode();
}
/** encode the archived value to JSON */
abstract public String encode();
/** record the value for encoding later */
static public AbstractEncoder record( final Object value, final ConversionAdaptorStore conversionAdaptorStore ) {
return record( value, conversionAdaptorStore, new ReferenceStore() );
}
/** record a value for encoding later and store references in the supplied store */
@SuppressWarnings( "unchecked" ) // no way to guarantee at compile time conversion types
static protected AbstractEncoder record( final Object value, final ConversionAdaptorStore conversionAdaptorStore, final ReferenceStore referenceStore ) {
final Class<?> valueClass = value != null ? value.getClass() : null;
if ( valueClass == null ) {
return NullEncoder.getInstance();
}
else if ( valueClass.equals( Boolean.class ) ) {
return new BooleanEncoder( (Boolean)value );
}
else if ( valueClass.equals( Double.class ) ) {
return new DoubleEncoder( (Double)value );
}
else if ( valueClass.equals( Long.class ) ) {
return new LongEncoder( (Long)value );
}
else if ( valueClass.equals( String.class ) ) {
final String stringValue = (String)value;
final IdentityReference reference = StringEncoder.allowsReference( stringValue ) ? referenceStore.store( value ) : null;
return reference != null && reference.hasMultiple() ? new ReferenceEncoder( reference.getID() ) : new StringEncoder( stringValue, reference );
}
else { // these are the ones that support references
final IdentityReference reference = referenceStore.store( value );
if ( reference.hasMultiple() ) {
return new ReferenceEncoder( reference.getID() );
}
else if ( valueClass.equals( HashMap.class ) ) { // no way to check at compile time that the key type is string
return new DictionaryEncoder( (HashMap<String,Object>)value, conversionAdaptorStore, reference, referenceStore );
}
else if ( valueClass.isArray() ) {
return ArrayEncoder.getInstance( value, conversionAdaptorStore, reference, referenceStore );
}
else { // if the type is not among the standard ones then look to extensions
return new ExtensionEncoder( value, conversionAdaptorStore, reference, referenceStore );
}
}
}
}
/** Base class of encoders for hard objects (not references) */
abstract class HardEncoder<DataType> extends AbstractEncoder {
/** value to encode */
final protected DataType VALUE;
/** Constructor */
public HardEncoder( final DataType value ) {
VALUE = value;
}
}
/** Base class of encoders for objects that support references */
abstract class SoftValueEncoder extends AbstractEncoder {
/** key identifies an object that is referenced */
static final public String OBJECT_ID_KEY = "__XALID";
/** key for the referenced value */
static final public String VALUE_KEY = "value";
/** reference to this value */
final private IdentityReference REFERENCE;
/** Constructor */
public SoftValueEncoder( final IdentityReference reference ) {
REFERENCE = reference;
}
/** encode an object ID and value if there are multiple references to the value, otherwise just encode the value */
public String encode() {
final String valueEncoding = encodeValue();
if ( REFERENCE.hasMultiple() ) {
return DictionaryEncoder.encodeKeyValueStringPairs( new KeyValueStringPair( OBJECT_ID_KEY, LongEncoder.encode( REFERENCE.getID() ) ), new KeyValueStringPair( VALUE_KEY, valueEncoding ) );
}
else {
return valueEncoding;
}
}
/** encode just the value */
abstract String encodeValue();
}
/** encoder for references */
class ReferenceEncoder extends AbstractEncoder {
/** key to indicate a reference */
static final public String REFERENCE_KEY = "__XALREF";
/** ID of referenced object */
final private long REFERENCE_ID;
/** Constructor */
public ReferenceEncoder( final long referenceID ) {
REFERENCE_ID = referenceID;
}
/** encode the reference to JSON */
public String encode() {
return DictionaryEncoder.encodeKeyValueStringPairs( new KeyValueStringPair( REFERENCE_KEY, LongEncoder.encode( REFERENCE_ID ) ) );
}
}
/** encode a null to JSON */
class NullEncoder extends AbstractEncoder {
/** encoder singleton */
static final private NullEncoder SHARED_ENCODER;
// static initializer
static {
SHARED_ENCODER = new NullEncoder();
}
/** get the shared instance */
static public NullEncoder getInstance() {
return SHARED_ENCODER;
}
/** Constructor */
private NullEncoder() {}
/** encode the archived value to JSON */
public String encode() {
return "null";
}
}
/** encode a string to JSON */
class StringEncoder extends SoftValueEncoder {
/** value to encode */
final private String VALUE;
/** Constructor */
public StringEncoder( final String value, final IdentityReference reference ) {
super( reference );
VALUE = value;
}
/** determine whether the string allows referencing */
static public boolean allowsReference( final String value ) {
return value.length() > 20; // don't bother using references unless the string is long enough to warrant the overhead
}
/** encode an object ID and value if there are multiple references to the value, otherwise just encode the value */
public String encode() {
return allowsReference( VALUE ) ? super.encode() : encodeValue();
}
/** encode the archived value to JSON */
public String encodeValue() {
return encode( VALUE );
}
/** encode a string */
static public String encode( final String value ) {
return "\"" + value.replace( "\\", "\\\\" ).replace( "\"", "\\\"" ) + "\"";
}
}
/** encode a boolean to JSON */
class BooleanEncoder extends HardEncoder<Boolean> {
/** Constructor */
public BooleanEncoder( final Boolean value ) {
super( value );
}
/** encode the archived value to JSON */
public String encode() {
return VALUE.booleanValue() ? "true" : "false";
}
}
/** encode a double to JSON */
class DoubleEncoder extends HardEncoder<Double> {
/** Constructor */
public DoubleEncoder( final Double value ) {
super( value );
}
/** encode the archived value to JSON */
public String encode() {
return encode( VALUE );
}
/** encode a double value */
static public String encode( final Double value ) {
return value.toString();
}
}
/** encode a long integer to JSON */
class LongEncoder extends HardEncoder<Long> {
/** Constructor */
public LongEncoder( final Long value ) {
super( value );
}
/** encode the archived value to JSON */
public String encode() {
return encode( VALUE );
}
/** encode a long value */
static public String encode( final Long value ) {
return value.toString();
}
}
/** encode a hash map to JSON */
class DictionaryEncoder extends SoftValueEncoder {
/** map of item encoders keyed by the corresponding orignal map keys */
final private Map<String,AbstractEncoder> ENCODER_MAP;
/** Constructor */
public DictionaryEncoder( final HashMap<String,Object> map, final ConversionAdaptorStore conversionAdaptorStore, final IdentityReference reference, final ReferenceStore referenceStore ) {
super( reference );
ENCODER_MAP = new HashMap<String,AbstractEncoder>( map.size() );
final Set<Map.Entry<String,Object>> entries = map.entrySet();
for ( final Map.Entry<String,Object> entry : entries ) {
final AbstractEncoder itemEncoder = AbstractEncoder.record( entry.getValue(), conversionAdaptorStore, referenceStore );
ENCODER_MAP.put( entry.getKey(), itemEncoder );
}
}
/** encode key value string pairs where the value is already encoded */
static public String encodeKeyValueStringPairs( final KeyValueStringPair ... keyValuePairs ) {
final StringBuffer buffer = new StringBuffer();
buffer.append( "{" );
int index = 0;
for ( final KeyValueStringPair keyValuePair : keyValuePairs ) {
switch ( index ) {
case 0:
break;
default:
buffer.append( ", " );
break;
}
buffer.append( StringEncoder.encode( keyValuePair.KEY ) );
buffer.append( ": " );
buffer.append( keyValuePair.VALUE );
++index;
}
buffer.append( "}" );
return buffer.toString();
}
/** encode the archived value to JSON */
public String encodeValue() {
final Set<Map.Entry<String,AbstractEncoder>> entries = ENCODER_MAP.entrySet();
final KeyValueStringPair[] keyValuePairs = new KeyValueStringPair[ entries.size() ];
int index = 0;
for ( final Map.Entry<String,AbstractEncoder> entry : entries ) {
final String key = entry.getKey();
final AbstractEncoder itemEncoder = entry.getValue();
final String value = itemEncoder.encode();
keyValuePairs[index] = new KeyValueStringPair( key, value );
++index;
}
return encodeKeyValueStringPairs( keyValuePairs );
}
}
/** encoder for extensions which piggybacks on the dictionary encoder */
class ExtensionEncoder extends DictionaryEncoder {
/** custom key identifying a custom type translated in terms of JSON representations */
static final public String EXTENDED_TYPE_KEY = "__XALTYPE";
/** custom key identifying a custom value to translate in terms of JSON representations */
static final public String EXTENDED_VALUE_KEY = "value";
/** Constructor */
public ExtensionEncoder( final Object value, final ConversionAdaptorStore conversionAdaptorStore, final IdentityReference reference, final ReferenceStore referenceStore ) {
super( getValueRep( value, conversionAdaptorStore ), conversionAdaptorStore, reference, referenceStore );
}
/** get the value representation as a dictionary keyed for the extended type and value */
@SuppressWarnings( "unchecked" )
static private HashMap<String,Object> getValueRep( final Object value, final ConversionAdaptorStore conversionAdaptorStore ) {
final String valueType = value.getClass().getName();
final ConversionAdaptor adaptor = conversionAdaptorStore.getConversionAdaptor( valueType );
if ( adaptor != null ) {
final HashMap<String,Object> valueRep = new HashMap<String,Object>();
final Object representationValue = adaptor.toRepresentation( value );
valueRep.put( EXTENDED_TYPE_KEY, valueType );
valueRep.put( EXTENDED_VALUE_KEY, representationValue );
return valueRep;
}
else {
throw new RuntimeException( "No coder for encoding objects of type: " + valueType );
}
}
}
/** encoder for an array of items of a common extended type which piggybacks on the dictionary encoder */
class TypedArrayEncoder extends DictionaryEncoder {
/** key for identifying the array data of an extended type */
static final public String ARRAY_ITEM_TYPE_KEY = "__XALITEMTYPE";
/** key for identifying the array data of an extended type */
static final public String ARRAY_KEY = "array";
/** primitive classes keyed by type name */
static final private Map<String,Class<?>> PRIMITIVE_CLASSES;
// static initializer
static {
PRIMITIVE_CLASSES = generatePrimitiveClassMap();
}
/** Constructor */
public TypedArrayEncoder( final Object array, final ConversionAdaptorStore conversionAdaptorStore, final IdentityReference reference, final ReferenceStore referenceStore ) {
super( getArrayRep( array, conversionAdaptorStore ), conversionAdaptorStore, reference, referenceStore );
}
/** get the value representation as a dictionary keyed for the array item type and generic object array */
@SuppressWarnings( "unchecked" )
static private HashMap<String,Object> getArrayRep( final Object array, final ConversionAdaptorStore conversionAdaptorStore ) {
final String itemType = array.getClass().getComponentType().getName();
final HashMap<String,Object> arrayRep = new HashMap<String,Object>();
final int arrayLength = Array.getLength( array );
final Object[] objectArray = new Object[ arrayLength ]; // encode as a generic object array
for ( int index = 0 ; index < arrayLength ; index++ ) {
objectArray[index] = Array.get( array, index );
}
arrayRep.put( ARRAY_ITEM_TYPE_KEY, itemType );
arrayRep.put( ARRAY_KEY, objectArray );
return arrayRep;
}
/** get the primitive type for the specified type name */
static public Class<?> getPrimitiveType( final String typeName ) {
return PRIMITIVE_CLASSES.get( typeName );
}
/** generate the table of primitive classes keyed by name */
static private Map<String,Class<?>> generatePrimitiveClassMap() {
final Map<String,Class<?>> classTable = new Hashtable<String,Class<?>>();
registerPrimitiveType( classTable, Float.TYPE );
registerPrimitiveType( classTable, Double.TYPE );
registerPrimitiveType( classTable, Byte.TYPE );
registerPrimitiveType( classTable, Character.TYPE );
registerPrimitiveType( classTable, Short.TYPE );
registerPrimitiveType( classTable, Integer.TYPE );
registerPrimitiveType( classTable, Long.TYPE );
return classTable;
}
/** register the primitive type in the table */
static private void registerPrimitiveType( final Map<String,Class<?>> table, final Class<?> type ) {
table.put( type.getName(), type );
}
}
/** encode an array to JSON */
class ArrayEncoder extends SoftValueEncoder {
/** array of encoders each of which corresponds to an item in the original array */
final private AbstractEncoder[] ITEM_ENCODERS;
/** Constructor */
public ArrayEncoder( final Object array, final ConversionAdaptorStore conversionAdaptorStore, final IdentityReference reference, final ReferenceStore referenceStore ) {
super( reference );
final int arrayLength = Array.getLength( array );
ITEM_ENCODERS = new AbstractEncoder[ arrayLength ];
for ( int index = 0 ; index < arrayLength ; index++ ) {
ITEM_ENCODERS[index] = AbstractEncoder.record( Array.get( array, index ), conversionAdaptorStore, referenceStore );
}
}
/** Get an instance that can encode arrays and efficiently arrays of extended types */
static public SoftValueEncoder getInstance( final Object array, final ConversionAdaptorStore conversionAdaptorStore, final IdentityReference reference, final ReferenceStore referenceStore ) {
return isTypedArray( array ) ? new TypedArrayEncoder( array, conversionAdaptorStore, reference, referenceStore ) : new ArrayEncoder( array, conversionAdaptorStore, reference, referenceStore );
}
/** Determine whether the array is of a common extended type */
static private boolean isTypedArray( final Object array ) {
final Class<?> itemClass = array.getClass().getComponentType();
return itemClass != null && itemClass != Object.class;
}
/** encode the archived value to JSON */
public String encodeValue() {
final int count = ITEM_ENCODERS.length;
final StringBuffer buffer = new StringBuffer();
buffer.append( "[" );
for ( int index = 0 ; index < count ; index++ ) {
switch ( index ) {
case 0:
break;
default:
buffer.append( ", " );
break;
}
final AbstractEncoder itemEncoder = ITEM_ENCODERS[index];
buffer.append( itemEncoder.encode() );
}
buffer.append( "]" );
return buffer.toString();
}
}
/** Base class of decoders */
abstract class AbstractDecoder<DataType> {
/** archive to parse */
final protected String ARCHIVE;
/** unparsed remainder of the source string after parsing */
protected String _remainder;
/** Constructor */
protected AbstractDecoder( final String archive ) {
ARCHIVE = archive;
}
/** decode the source to extract the next object */
abstract protected DataType decode();
/** get the unparsed remainder of the source string */
protected String getRemainder() {
return _remainder;
}
/** check for a match of the archive against the specified pattern, update the remainder and return the matching string */
protected String processMatch( final Pattern pattern ) {
final Matcher matcher = pattern.matcher( ARCHIVE );
matcher.find();
final int nextIndex = matcher.end();
_remainder = ARCHIVE.length() > nextIndex ? ARCHIVE.substring( nextIndex ) : null;
return matcher.group();
}
/** Get a decoder for the archive */
public static AbstractDecoder getInstance( final String archive, final ConversionAdaptorStore conversionAdaptorStore ) {
return AbstractDecoder.getInstance( archive, conversionAdaptorStore, new KeyedReferenceStore() );
}
/** Get a decoder for the archive */
protected static AbstractDecoder getInstance( final String archive, final ConversionAdaptorStore conversionAdaptorStore, final KeyedReferenceStore referenceStore ) {
final String source = archive.trim();
if ( source.length() > 0 ) {
final char firstChar = source.charAt( 0 );
switch ( firstChar ) {
case '+': case '-': case '.':
case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9':
return new NumberDecoder( source );
case 't': case 'f':
return new BooleanDecoder( source );
case 'n':
return new NullDecoder( source );
case '\"':
return new StringDecoder( source );
case '[':
return new ArrayDecoder( source, conversionAdaptorStore, referenceStore );
case '{':
return new DictionaryDecoder( source, conversionAdaptorStore, referenceStore );
default:
return null;
}
}
else {
return null;
}
}
}
/** decode a number from a source string */
class NumberDecoder extends AbstractDecoder<Number> {
/** pattern for matching a number */
static final Pattern NUMBER_PATTERN;
// static initializer
static {
NUMBER_PATTERN = Pattern.compile( "[+-]?((\\d+\\.?\\d*)|(\\.?\\d+))([eE][+-]?\\d+)?" );
}
/** Constructor */
protected NumberDecoder( final String archive ) {
super( archive );
}
/** decode the source to extract the next object */
protected Number decode() {
final String match = processMatch( NUMBER_PATTERN );
// doubles always have a decimal point even if the fraction is zero, so the absence of a period indicates a long integer
if ( match != null ) {
if ( match.contains( "." ) ) {
return Double.valueOf( match );
}
else {
return Long.valueOf( match );
}
}
else {
return null;
}
}
}
/** decode a boolean from a source string */
class BooleanDecoder extends AbstractDecoder<Boolean> {
/** pattern for matching booleans */
static final Pattern BOOLEAN_PATTERN;
// static initializer
static {
BOOLEAN_PATTERN = Pattern.compile( "(true)|(false)" );
}
/** Constructor */
protected BooleanDecoder( final String archive ) {
super( archive );
}
/** decode the source to extract the next object */
protected Boolean decode() {
final String match = processMatch( BOOLEAN_PATTERN );
return match != null ? Boolean.valueOf( match ) : null;
}
}
/** decode a null identifier from a source string */
class NullDecoder extends AbstractDecoder<Object> {
/** pattern for matching the null identifier */
static final Pattern NULL_PATTERN;
// static initializer
static {
NULL_PATTERN = Pattern.compile( "null" );
}
/** Constructor */
protected NullDecoder( final String archive ) {
super( archive );
}
/** decode the source to extract the next object */
protected Object decode() {
final String match = processMatch( NULL_PATTERN );
return null;
}
}
/** decode a string from a source string */
class StringDecoder extends AbstractDecoder<String> {
/** pattern for matching a string */
static final Pattern STRING_PATTERN;
// static initializer
static {
// a string begins and ends with a quotation mark and no unescaped quotation marks in between them
STRING_PATTERN = Pattern.compile( "\\\"(((\\\\)+\")|[^\"])*\\\"" );
}
/** Constructor */
protected StringDecoder( final String archive ) {
super( archive );
}
/** decode the source to extract the next object */
protected String decode() {
final String match = processMatch( STRING_PATTERN );
if ( match != null ) {
final int length = match.length();
return length > 0 ? unescape( match.substring( 1, length-1 ) ) : "";
}
else {
return null;
}
}
/** unescape (replace occurences of a backslash and a character by the character itself) the input and return the resulting string */
static private String unescape( final String input ) {
final StringBuffer buffer = new StringBuffer();
unescapeToBuffer( buffer, input );
return buffer.toString();
}
/** unescape the input and append the text to the buffer */
static private void unescapeToBuffer( final StringBuffer buffer, final String input ) {
if ( input != null && input.length() > 0 ) {
final int location = input.indexOf( '\\' );
if ( location < 0 ) {
buffer.append( input );
}
else {
buffer.append( input.substring( 0, location ) );
final int inputLength = input.length();
if ( inputLength > location ) {
buffer.append( input.charAt( location + 1 ) );
final String remainder = inputLength > location + 1 ? input.substring( location + 2 ) : null;
unescapeToBuffer( buffer, remainder );
}
}
}
}
}
/** decode an array from a source string */
class ArrayDecoder extends AbstractDecoder<Object[]> {
/** custom type adaptors */
final private ConversionAdaptorStore CONVERSION_ADAPTOR_STORE;
/** reference store */
final private KeyedReferenceStore REFERENCE_STORE;
/** Constructor */
protected ArrayDecoder( final String archive, final ConversionAdaptorStore conversionAdaptorStore, final KeyedReferenceStore referenceStore ) {
super( archive );
CONVERSION_ADAPTOR_STORE = conversionAdaptorStore;
REFERENCE_STORE = referenceStore;
}
/** decode the source to extract the next object */
protected Object[] decode() {
final String arrayString = ARCHIVE.substring( 1 ).trim(); // strip the leading bracket
final List<Object> items = new ArrayList<Object>();
appendItems( items, arrayString );
return items.toArray();
}
/** append to the items the parsed items from the array string */
private void appendItems( final List<Object> items, final String arrayString ) {
if ( arrayString != null && arrayString.length() > 0 ) {
try {
if ( arrayString.charAt( 0 ) == ']' ) {
_remainder = arrayString.substring( 1 ).trim();
return;
}
else {
final AbstractDecoder itemDecoder = AbstractDecoder.getInstance( arrayString, CONVERSION_ADAPTOR_STORE, REFERENCE_STORE );
items.add( itemDecoder.decode() );
final String itemRemainder = itemDecoder.getRemainder().trim();
final char closure = itemRemainder.charAt( 0 );
final String archiveRemainder = itemRemainder.substring(1).trim();
switch ( closure ) {
case ',':
appendItems( items, archiveRemainder );
return;
case ']':
_remainder = archiveRemainder;
return;
default:
throw new RuntimeException( "Invalid array closure mark: " + closure );
}
}
}
catch ( Exception exception ) {
exception.printStackTrace();
}
}
else {
_remainder = null;
}
}
}
/** decode a dictionary from a source string */
class DictionaryDecoder extends AbstractDecoder<Object> {
/** custom type adaptors */
final private ConversionAdaptorStore CONVERSION_ADAPTOR_STORE;
/** reference store */
final private KeyedReferenceStore REFERENCE_STORE;
/** Constructor */
protected DictionaryDecoder( final String archive, final ConversionAdaptorStore conversionAdaptorStore, final KeyedReferenceStore referenceStore ) {
super( archive );
CONVERSION_ADAPTOR_STORE = conversionAdaptorStore;
REFERENCE_STORE = referenceStore;
}
/** decode the source to extract the next object */
@SuppressWarnings( "unchecked" ) // no way to validate representation value and type at compile time
protected Object decode() {
final String dictionaryString = ARCHIVE.substring( 1 ).trim(); // strip the leading brace
final Map<String,Object> dictionary = new HashMap<String,Object>();
appendItems( dictionary, dictionaryString );
if ( dictionary.containsKey( ExtensionEncoder.EXTENDED_TYPE_KEY ) && dictionary.containsKey( ExtensionEncoder.EXTENDED_VALUE_KEY ) ) {
// decode object of extended type
final String extendedType = (String)dictionary.get( ExtensionEncoder.EXTENDED_TYPE_KEY );
final Object representationValue = dictionary.get( ExtensionEncoder.EXTENDED_VALUE_KEY );
final ConversionAdaptor adaptor = CONVERSION_ADAPTOR_STORE.getConversionAdaptor( extendedType );
if ( adaptor == null ) throw new RuntimeException( "Missing JSON adaptor for type: " + extendedType );
return adaptor.toNative( representationValue );
}
else if ( dictionary.containsKey( TypedArrayEncoder.ARRAY_ITEM_TYPE_KEY ) && dictionary.containsKey( TypedArrayEncoder.ARRAY_KEY ) ) {
// decode array of with a specified item type from a generic object array
final String itemType = (String)dictionary.get( TypedArrayEncoder.ARRAY_ITEM_TYPE_KEY );
final Object[] objectArray = (Object[])dictionary.get( TypedArrayEncoder.ARRAY_KEY );
try {
final Class primitiveType = TypedArrayEncoder.getPrimitiveType( itemType );
final Class itemClass = primitiveType != null ? primitiveType : Class.forName( itemType );
final Object array = Array.newInstance( itemClass, objectArray.length );
for ( int index = 0 ; index < objectArray.length ; index++ ) {
Array.set( array, index, objectArray[index] );
}
return array;
}
catch( Exception exception ) {
throw new RuntimeException( "Exception decoding a typed array of type: " + itemType, exception );
}
}
else if ( dictionary.containsKey( SoftValueEncoder.OBJECT_ID_KEY ) && dictionary.containsKey( SoftValueEncoder.VALUE_KEY ) ) {
// decode a referenced object definition and store it
final Long itemID = (Long)dictionary.get( SoftValueEncoder.OBJECT_ID_KEY );
final Object item = dictionary.get( SoftValueEncoder.VALUE_KEY );
REFERENCE_STORE.store( itemID, item );
return item;
}
else if ( dictionary.containsKey( ReferenceEncoder.REFERENCE_KEY ) ) {
// decode a reference to an object in the store
final Long itemID = (Long)dictionary.get( ReferenceEncoder.REFERENCE_KEY );
return REFERENCE_STORE.get( itemID );
}
else {
return dictionary;
}
}
/** append to the items the parsed items from the array string */
private void appendItems( final Map<String,Object> dictionary, final String dictionaryString ) {
if ( dictionaryString != null && dictionaryString.length() > 0 ) {
try {
if ( dictionaryString.charAt( 0 ) == '}' ) {
_remainder = dictionaryString.substring( 1 ).trim();
return;
}
else {
final StringDecoder keyDecoder = new StringDecoder( dictionaryString );
final String key = keyDecoder.decode();
final String keyRemainder = keyDecoder.getRemainder();
final String valueBuffer = keyRemainder.trim().substring( 1 ); // trim spaces and strip the leading colon
final AbstractDecoder valueDecoder = AbstractDecoder.getInstance( valueBuffer, CONVERSION_ADAPTOR_STORE, REFERENCE_STORE );
final Object value = valueDecoder.decode();
dictionary.put( key, value );
final String itemRemainder = valueDecoder.getRemainder().trim();
final char closure = itemRemainder.charAt( 0 );
final String archiveRemainder = itemRemainder.substring(1).trim();
switch ( closure ) {
case ',':
appendItems( dictionary, archiveRemainder );
return;
case '}':
_remainder = archiveRemainder;
return;
default:
throw new RuntimeException( "Invalid dictionary closure mark: " + closure );
}
}
}
catch ( Exception exception ) {
exception.printStackTrace();
}
}
else {
_remainder = null;
}
}
}
/** Stores referenced items keyed by ID */
class KeyedReferenceStore {
/** references keyed by ID */
final private Map<Double,Object> REFERENCES;
/** Constructor */
public KeyedReferenceStore() {
REFERENCES = new HashMap<Double,Object>();
}
/** store the value associated with the key */
public void store( final double key, final Object value ) {
REFERENCES.put( key, value );
}
/** get the item associated with the key */
public Object get( final double key ) {
return REFERENCES.get( key );
}
}
/** pair of strings representing the key and value */
class KeyValueStringPair {
/** key */
final public String KEY;
/** value */
final public String VALUE;
/** Constructor */
public KeyValueStringPair( final String key, final String value ) {
KEY = key;
VALUE = value;
}
}
/** storage of possible references */
class ReferenceStore {
/** set of objects with a common equality */
final private Map<Object,EqualityReference<Object>> EQUALITY_REFERENCES;
/** counter of unique objects */
private long _objectCounter;
/** Constructor */
public ReferenceStore() {
EQUALITY_REFERENCES = new HashMap<Object,EqualityReference<Object>>();
_objectCounter = 0;
}
/** store the item */
@SuppressWarnings( "unchecked" ) // no way to test type at compile time
public <ItemType> IdentityReference<ItemType> store( final ItemType item ) {
if ( !EQUALITY_REFERENCES.containsKey( item ) ) {
EQUALITY_REFERENCES.put( item, new EqualityReference<Object>() );
}
final EqualityReference<ItemType> equalityReference = (EqualityReference<ItemType>)EQUALITY_REFERENCES.get( item );
return equalityReference.add( item, ++_objectCounter );
}
}
/** reference to a collection of objects which are equal among themselves */
class EqualityReference<ItemType> {
/** list of identity references */
final private List<IdentityReference<ItemType>> IDENTITY_REFERENCES;
/** Constructor */
public EqualityReference() {
IDENTITY_REFERENCES = new ArrayList<IdentityReference<ItemType>>();
}
/** add the object to the set of equals */
public IdentityReference<ItemType> add( final ItemType item, final long uniqueID ) {
for ( final IdentityReference<ItemType> reference : IDENTITY_REFERENCES ) {
if ( reference.getItem() == item ) {
reference.setHasMultiple( true );
return reference;
}
}
final IdentityReference<ItemType> reference = new IdentityReference<ItemType>( item, uniqueID );
IDENTITY_REFERENCES.add( reference );
return reference;
}
}
/** reference to an object along with the count */
class IdentityReference<ItemType> {
/** referenced item */
final private ItemType ITEM;
/** unique ID for this object */
final private long ID;
/** indicates multiple references to the item */
private boolean _hasMultiple;
/** Constructor */
public IdentityReference( final ItemType item, final long uniqueID ) {
ITEM = item;
ID = uniqueID;
_hasMultiple = false;
}
/** get the item */
public ItemType getItem() {
return ITEM;
}
/** get the unique ID for the item */
public long getID() {
return ID;
}
/** indicates whether more than one reference exists to the referenced item */
public boolean hasMultiple() {
return _hasMultiple;
}
/** mark whether multiple (more than one) references are made to the item */
public void setHasMultiple( final boolean hasMultiple ) {
_hasMultiple = hasMultiple;
}
}
/** conversion adaptors container whose contents cannot be changed */
class ConversionAdaptorStore {
/** adaptors between all custom types and representation JSON types */
final protected Map<String,ConversionAdaptor> TYPE_EXTENSION_ADAPTORS;
/** set of standard types */
static final private Set<String> STANDARD_TYPES;
// static initializer
static {
STANDARD_TYPES = new HashSet<String>();
populateStandardTypes();
}
/** Constructor */
protected ConversionAdaptorStore() {
TYPE_EXTENSION_ADAPTORS = new HashMap<String,ConversionAdaptor>();
}
/** Unmodifiable Copy Constructor */
public ConversionAdaptorStore( final ConversionAdaptorStore sourceAdaptors ) {
TYPE_EXTENSION_ADAPTORS = Collections.unmodifiableMap( sourceAdaptors.TYPE_EXTENSION_ADAPTORS );
}
/** populate the set of standard types */
static private void populateStandardTypes() {
final Set<String> types = new HashSet<String>();
types.add( Boolean.class.getName() );
types.add( Double.class.getName() );
types.add( Long.class.getName() );
types.add( Map.class.getName() );
types.add( Object[].class.getName() );
types.add( String.class.getName() );
STANDARD_TYPES.addAll( types );
}
/** Get a list of all types which are supported for coding and decoding */
static public List<String> getStandardTypes() {
final List<String> types = new ArrayList<String>( STANDARD_TYPES );
Collections.sort( types );
return types;
}
/** determine whether the specified type is a standard JSON type */
static public boolean isStandardType( final String type ) {
return STANDARD_TYPES.contains( type );
}
/** Get a list of all types which are supported for coding and decoding */
public List<String> getSupportedTypes() {
final List<String> types = new ArrayList<String>();
types.addAll( getStandardTypes() );
types.addAll( getExtendedTypes() );
Collections.sort( types );
return types;
}
/** Get a list of types which extend beyond the JSON standard types */
public List<String> getExtendedTypes() {
final List<String> types = new ArrayList<String>();
for ( final String type : TYPE_EXTENSION_ADAPTORS.keySet() ) {
types.add( type );
}
Collections.sort( types );
return types;
}
/** Get the conversion adaptor for the given value */
public ConversionAdaptor getConversionAdaptor( final String valueType ) {
return TYPE_EXTENSION_ADAPTORS.get( valueType );
}
}
/** conversion adaptors container whose contents can be changed */
class MutableConversionAdaptorStore extends ConversionAdaptorStore {
/** Constructor */
public MutableConversionAdaptorStore( final boolean shouldRegisterStandardExtensions ) {
super();
if( shouldRegisterStandardExtensions ) registerStandardExtensions();
}
/** Copy Constructor */
public MutableConversionAdaptorStore( final MutableConversionAdaptorStore sourceAdaptors ) {
this( false );
TYPE_EXTENSION_ADAPTORS.putAll( sourceAdaptors.TYPE_EXTENSION_ADAPTORS );
}
/**
* Register the custom type and its associated adaptor
* @param type type to identify and process for encoding and decoding
* @param adaptor translator between the custom type and representation JSON constructs
*/
public <CustomType,RepresentationType> void registerType( final Class<CustomType> type, final ConversionAdaptor<CustomType,RepresentationType> adaptor ) {
TYPE_EXTENSION_ADAPTORS.put( type.getName(), adaptor );
}
/** register the standard type extensions (only needs to be done for the default coder) */
private void registerStandardExtensions() {
registerType( Character.class, new ConversionAdaptor<Character,String>() {
/** convert the custom type to a representation in terms of representation JSON constructs */
public String toRepresentation( final Character custom ) {
return custom.toString();
}
/** convert the JSON representation construct into the custom type */
public Character toNative( final String representation ) {
return representation.charAt( 0 );
}
});
registerType( Short.class, new ConversionAdaptor<Short,Long>() {
/** convert the custom type to a representation in terms of representation JSON constructs */
public Long toRepresentation( final Short custom ) {
return custom.longValue();
}
/** convert the JSON representation construct into the custom type */
public Short toNative( final Long representation ) {
return representation.shortValue();
}
});
registerType( Byte.class, new ConversionAdaptor<Byte,Long>() {
/** convert the custom type to a representation in terms of representation JSON constructs */
public Long toRepresentation( final Byte custom ) {
return custom.longValue();
}
/** convert the JSON representation construct into the custom type */
public Byte toNative( final Long representation ) {
return representation.byteValue();
}
});
registerType( Integer.class, new ConversionAdaptor<Integer,Long>() {
/** convert the custom type to a representation in terms of representation JSON constructs */
public Long toRepresentation( final Integer custom ) {
return custom.longValue();
}
/** convert the JSON representation construct into the custom type */
public Integer toNative( final Long representation ) {
return representation.intValue();
}
});
registerType( Float.class, new ConversionAdaptor<Float,Double>() {
/** convert the custom type to a representation in terms of representation JSON constructs */
public Double toRepresentation( final Float custom ) {
return custom.doubleValue();
}
/** convert the JSON representation construct into the custom type */
public Float toNative( final Double representation ) {
return representation.floatValue();
}
});
registerType( Date.class, new ConversionAdaptor<Date,Long>() {
/** convert the custom type to a representation in terms of representation JSON constructs */
public Long toRepresentation( final Date timestamp ) {
return timestamp.getTime();
}
/** convert the JSON representation construct into the custom type */
public Date toNative( final Long msecFromEpoch ) {
return new Date( msecFromEpoch );
}
});
registerType( ArrayList.class, new ConversionAdaptor<ArrayList,Object[]>() {
/** convert the custom type to a representation in terms of representation JSON constructs */
public Object[] toRepresentation( final ArrayList list ) {
return list.toArray();
}
/** convert the JSON representation construct into the custom type */
@SuppressWarnings( "unchecked" ) // list can represent any type
public ArrayList toNative( final Object[] array ) {
final ArrayList list = new ArrayList( array.length );
for ( final Object item : array ) {
list.add( item );
}
return list;
}
});
registerType( Vector.class, new ConversionAdaptor<Vector,Object[]>() {
/** convert the custom type to a representation in terms of representation JSON constructs */
public Object[] toRepresentation( final Vector list ) {
return list.toArray();
}
/** convert the JSON representation construct into the custom type */
@SuppressWarnings( "unchecked" ) // list can represent any type
public Vector toNative( final Object[] array ) {
final Vector list = new Vector( array.length );
for ( final Object item : array ) {
list.add( item );
}
return list;
}
});
registerType( Hashtable.class, new ConversionAdaptor<Hashtable,HashMap>() {
/** convert the custom type to a representation in terms of representation JSON constructs */
@SuppressWarnings( "unchecked" ) // map and table don't have compile time types
public HashMap toRepresentation( final Hashtable table ) {
return new HashMap( table );
}
/** convert the JSON representation construct into the custom type */
@SuppressWarnings( "unchecked" ) // list can represent any type
public Hashtable toNative( final HashMap map ) {
return new Hashtable( map );
}
});
registerType( StackTraceElement.class, new ConversionAdaptor<StackTraceElement,HashMap>() {
/** convert the custom type to a representation in terms of representation JSON constructs */
@SuppressWarnings( "unchecked" ) // map and table don't have compile time types
public HashMap toRepresentation( final StackTraceElement traceElement ) {
final HashMap traceElementMap = new HashMap( 3 );
traceElementMap.put( "className", traceElement.getClassName() );
traceElementMap.put( "methodName", traceElement.getMethodName() );
traceElementMap.put( "fileName", traceElement.getFileName() );
traceElementMap.put( "lineNumber", traceElement.getLineNumber() );
return traceElementMap;
}
/** convert the JSON representation construct into the custom type */
@SuppressWarnings( "unchecked" ) // list can represent any type
public StackTraceElement toNative( final HashMap traceElementMap ) {
final String className = (String)traceElementMap.get( "className" );
final String methodName = (String)traceElementMap.get( "methodName" );
final String fileName = (String)traceElementMap.get( "fileName" );
final int lineNumber = (Integer)traceElementMap.get( "lineNumber" );
return new StackTraceElement( className, methodName, fileName, lineNumber );
}
});
}
} |
package info.tregmine.listeners;
import java.util.Set;
import java.util.ArrayList;
import java.util.EnumSet;
import java.util.List;
import org.bukkit.ChatColor;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.entity.Player;
import org.bukkit.block.Block;
import org.bukkit.block.Sign;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerInteractEvent;
import org.bukkit.inventory.meta.ItemMeta;
import org.bukkit.event.block.BlockBreakEvent;
import org.bukkit.event.block.BlockBurnEvent;
import org.bukkit.event.block.BlockIgniteEvent;
import org.bukkit.event.block.BlockPlaceEvent;
import org.bukkit.event.block.BlockSpreadEvent;
import org.bukkit.event.block.LeavesDecayEvent;
import info.tregmine.Tregmine;
import info.tregmine.api.TregminePlayer;
import info.tregmine.database.DAOException;
import info.tregmine.database.IBlockDAO;
import info.tregmine.database.IContext;
import info.tregmine.database.ILogDAO;
import info.tregmine.database.IWalletDAO;
import net.minecraft.server.v1_9_R1.BlockFire;
public class TregmineBlockListener implements Listener
{
private Set<Material> loggedMaterials = EnumSet.of(Material.DIAMOND_ORE,
Material.EMERALD_ORE,
Material.GOLD_ORE,
Material.LAPIS_ORE,
Material.QUARTZ_ORE,
Material.REDSTONE_ORE,
Material.MOB_SPAWNER);
private Tregmine plugin;
public TregmineBlockListener(Tregmine instance)
{
this.plugin = instance;
}
@EventHandler
public void onBlockPlace(BlockPlaceEvent event)
{
TregminePlayer player = plugin.getPlayer(event.getPlayer());
if (event.getBlock().getType().equals(Material.SPONGE)) {
if (!player.getRank().canPlaceBannedBlocks()) {
event.setCancelled(true);
return;
}
}
}
@EventHandler
public void onBlockBurn(BlockBurnEvent event){
event.setCancelled(true);
}
@EventHandler
public void onBlockSpread(BlockSpreadEvent event){
Material sourceblock = event.getSource().getType();
if(sourceblock == Material.FIRE){
event.setCancelled(true);
}
}
@EventHandler
public void onBlockBreak(BlockBreakEvent event)
{
TregminePlayer player = plugin.getPlayer(event.getPlayer());
Block block = event.getBlock();
Material material = block.getType();
if (loggedMaterials.contains(material)) {
try (IContext ctx = plugin.createContext()) {
ILogDAO logDAO = ctx.getLogDAO();
logDAO.insertOreLog(player, block.getLocation(), material.getId());
} catch (DAOException e) {
throw new RuntimeException(e);
}
}
if (event.getBlock().getType().equals(Material.SPONGE)) {
if (!player.getRank().canBreakBannedBlocks()) {
event.setCancelled(true);
return;
}
}
try(IContext ctx = plugin.createContext()){
IBlockDAO blockDAO = ctx.getBlockDAO();
int blockvalue = blockDAO.blockValue(block);
if(!blockDAO.isPlaced(block) && !event.isCancelled() && blockvalue != 0){
try(IContext ctxNew = plugin.createContext()){
IWalletDAO walletDAO = ctx.getWalletDAO();
walletDAO.add(player, blockvalue);
//That message is annoying.
//player.sendMessage(ChatColor.GREEN + "You received " + ChatColor.GOLD + blockvalue + ChatColor.GREEN + " Tregs for breaking " + ChatColor.GOLD + block.getType().name().toLowerCase());
}catch(DAOException e){
e.printStackTrace();
}
}
}catch(DAOException e){
e.printStackTrace();
}
}
} |
package it.unimi.dsi.sux4j.mph;
import it.unimi.dsi.Util;
import it.unimi.dsi.bits.BitVector;
import it.unimi.dsi.bits.LongArrayBitVector;
import it.unimi.dsi.bits.TransformationStrategies;
import it.unimi.dsi.bits.TransformationStrategy;
import it.unimi.dsi.fastutil.objects.AbstractObject2LongFunction;
import it.unimi.dsi.fastutil.objects.AbstractObjectIterator;
import it.unimi.dsi.fastutil.objects.Object2LongFunction;
import it.unimi.dsi.fastutil.objects.Object2LongOpenHashMap;
import it.unimi.dsi.io.InputBitStream;
import it.unimi.dsi.io.OutputBitStream;
import it.unimi.dsi.logging.ProgressLogger;
import it.unimi.dsi.sux4j.bits.BalancedParentheses;
import it.unimi.dsi.sux4j.util.EliasFanoLongBigList;
import it.unimi.dsi.util.LongBigList;
import java.io.File;
import java.io.IOException;
import java.util.Iterator;
import java.util.NoSuchElementException;
import org.apache.log4j.Logger;
/** A distributor based on a hollow trie.
*
* <h2>Implementation details</h2>
*
* <p>This class implements a distributor on top of a hollow trie. First, a compacted trie is built from the delimiter set.
* Then, for each key we compute the node of the trie in which the bucket of the key is established. This gives us,
* for each node of the trie, a set of paths to which we must associate an action (exit on the left,
* go through, exit on the right). Overall, the number of such paths is equal to the number of keys plus the number of delimiters, so
* the mapping from each pair node/path to the respective action takes linear space. Now, from the compacted trie we just
* retain a hollow trie, as the path-length information is sufficient to rebuild the keys of the above mapping.
* By sizing the bucket size around the logarithm of the average length, we obtain a distributor that occupies linear space.
*/
public class HollowTrieDistributor4<T> extends AbstractObject2LongFunction<T> {
private final static Logger LOGGER = Util.getLogger( HollowTrieDistributor4.class );
private static final long serialVersionUID = 2L;
private static final boolean DEBUG = false;
private static final boolean ASSERTS = true;
/** An integer representing the exit-on-the-left behaviour. */
private final static int LEFT = 0;
/** An integer representing the exit-on-the-right behaviour. */
private final static int RIGHT = 1;
/** An integer representing the follow-the-try behaviour. */
private final static int FOLLOW = 2;
/** The transformation used to map object to bit vectors. */
private final TransformationStrategy<? super T> transformationStrategy;
/** The bitstream representing the hollow trie. */
private final LongArrayBitVector trie;
/** The list of skips, indexed by the internal nodes (we do not need skips on the leaves). */
private final EliasFanoLongBigList skips;
/** For each external node and each possible path, the related behaviour. */
private final MWHCFunction<BitVector> externalBehaviour;
/** The number of (internal and external) nodes of the trie. */
private final int size;
private final BalancedParentheses balParen;
private final MWHCFunction<BitVector> falseFollowsDetector;
/** The average skip. */
protected double meanSkip;
/** A debug function used to store explicitly the internal behaviour. */
Object2LongFunction<BitVector> externalTestFunction = null;
/** A debug function used to store explicitly the false follow detector. */
Object2LongFunction<BitVector> falseFollows;
/** Creates a partial compacted trie using given elements, bucket size and transformation strategy.
*
* @param elements the elements among which the trie must be able to rank.
* @param log2BucketSize the logarithm of the size of a bucket.
* @param transformationStrategy a transformation strategy that must turn the elements in <code>elements</code> into a list of
* distinct, lexicographically increasing (in iteration order) bit vectors.
*/
public HollowTrieDistributor4( final Iterable<? extends T> elements, final int log2BucketSize, final TransformationStrategy<? super T> transformationStrategy ) throws IOException {
this( elements, log2BucketSize, transformationStrategy, null );
}
/** Creates a hollow trie distributor.
*
* @param elements the elements among which the trie must be able to rank.
* @param log2BucketSize the logarithm of the size of a bucket.
* @param transformationStrategy a transformation strategy that must turn the elements in <code>elements</code> into a list of
* distinct, lexicographically increasing (in iteration order) bit vectors.
* @param tempDir the directory where temporary files will be created, or <code>for the default directory</code>.
*/
public HollowTrieDistributor4( final Iterable<? extends T> elements, final int log2BucketSize, final TransformationStrategy<? super T> transformationStrategy, final File tempDir ) throws IOException {
this.transformationStrategy = transformationStrategy;
final int bucketSize = 1 << log2BucketSize;
/** The file containing the external keys (pairs node/path). */
final File externalKeysFile;
/** The values associated to the keys in {@link #externalKeysFile}. */
LongBigList externalValues;
/** The file containing the keys (pairs node/path) that are (either true or false) follows. */
final File falseFollowsKeyFile;
/** The values (true/false) associated to the keys in {@link #falseFollows}. */
LongBigList falseFollowsValues;
if ( DEBUG ) System.err.println( "Bucket size: " + bucketSize );
final HollowTrie<T> intermediateTrie = new HollowTrie<T>( new Iterable<T>() {
public Iterator<T> iterator() {
final Iterator<? extends T> iterator = elements.iterator();
return new AbstractObjectIterator<T>() {
boolean toAdvance = true;
private T curr;
public boolean hasNext() {
if ( toAdvance ) {
toAdvance = false;
int i;
for( i = 0; i < bucketSize && iterator.hasNext(); i++ ) curr = iterator.next();
if ( i != bucketSize ) curr = null;
}
return curr != null;
}
public T next() {
if ( ! hasNext() ) throw new NoSuchElementException();
toAdvance = true;
return curr;
}
};
}
}, transformationStrategy );
if ( ASSERTS ) {
externalTestFunction = new Object2LongOpenHashMap<BitVector>();
externalTestFunction.defaultReturnValue( -1 );
falseFollows = new Object2LongOpenHashMap<BitVector>();
falseFollows.defaultReturnValue( -1 );
}
externalKeysFile = File.createTempFile( HollowTrieDistributor4.class.getName(), "ext", tempDir );
externalKeysFile.deleteOnExit();
falseFollowsKeyFile = File.createTempFile( HollowTrieDistributor4.class.getName(), "false", tempDir );
falseFollowsKeyFile.deleteOnExit();
final OutputBitStream externalKeys = new OutputBitStream( externalKeysFile );
final OutputBitStream falseFollowsKeys = new OutputBitStream( falseFollowsKeyFile );
externalValues = LongArrayBitVector.getInstance().asLongBigList( 1 );
falseFollowsValues = LongArrayBitVector.getInstance().asLongBigList( 1 );
if ( intermediateTrie.size() > 0 ) {
Iterator<? extends T> iterator = elements.iterator();
LongArrayBitVector bucketKey[] = new LongArrayBitVector[ bucketSize ];
LongArrayBitVector leftDelimiter, rightDelimiter = null;
long delimiterLcp = -1;
int count = 0;
trie = intermediateTrie.trie;
skips = intermediateTrie.skips;
balParen = intermediateTrie.balParen;
LongArrayBitVector emitted = LongArrayBitVector.ofLength( intermediateTrie.size() );
ProgressLogger pl = new ProgressLogger( LOGGER );
pl.displayFreeMemory = true;
pl.start( "Computing function keys..." );
while( iterator.hasNext() ) {
int realBucketSize;
for( realBucketSize = 0; realBucketSize < bucketSize && iterator.hasNext(); realBucketSize++ ) {
bucketKey[ realBucketSize ] = LongArrayBitVector.copy( transformationStrategy.toBitVector( iterator.next() ) );
pl.lightUpdate();
}
// The next delimiter
leftDelimiter = rightDelimiter;
rightDelimiter = realBucketSize == bucketSize ? bucketKey[ bucketSize - 1 ] : null;
delimiterLcp = ( rightDelimiter != null && leftDelimiter != null ) ? rightDelimiter.longestCommonPrefixLength( leftDelimiter ) : -1;
// The stack of nodes visited the last time
//final Node stack[] = new Node[ (int)maxLength ];
// The length of the path compacted in the trie up to the corresponding node, excluded
//final int[] len = new int[ (int)maxLength ];
//stack[ 0 ] = root;
int pathLength;
long lastNode = -1;
BitVector lastPath = null;
BitVector curr;
for( int j = 0; j < realBucketSize; j++ ) {
curr = bucketKey[ j ];
if ( DEBUG ) System.err.println( curr );
/*if ( ! first ) {
// Adjust stack using lcp between present string and previous one
prefix = (int)prev.longestCommonPrefixLength( curr );
while( depth > 0 && len[ depth ] > prefix ) depth--;
}
else first = false;
node = stack[ depth ];
pos = len[ depth ];*/
long p = 1, length = curr.length(), index = 0, r = 0;
int s = 0, skip = 0;
boolean isInternal;
int startPath = -1, endPath = -1;
boolean exitLeft = false;
final boolean isDelimiter = j == bucketSize - 1;
if ( DEBUG ) System.err.println( "Distributing " + curr + "\ntrie:" + trie );
long maxDescentLength;
if ( leftDelimiter == null ) {
maxDescentLength = rightDelimiter.longestCommonPrefixLength( curr ) + 1;
exitLeft = true;
}
else if ( rightDelimiter == null ) {
maxDescentLength = leftDelimiter.longestCommonPrefixLength( curr ) + 1;
exitLeft = false;
}
else maxDescentLength = ( exitLeft = curr.getBoolean( delimiterLcp ) ) ? rightDelimiter.longestCommonPrefixLength( curr ) + 1 : leftDelimiter.longestCommonPrefixLength( curr ) + 1;
for(;;) {
isInternal = trie.getBoolean( p );
if ( isInternal ) skip = (int)skips.getLong( r );
if ( DEBUG ) {
final int usedLength = (int)( isInternal ? Math.min( length, s + skip ) : length - s );
final BitVector usedPath = curr.subVector( s, s + usedLength );
System.err.println( "Interrogating" + ( isInternal ? "" : " leaf" ) + " <" + ( p - 1 ) + ", [" + usedLength + ", " + Integer.toHexString( usedPath.hashCode() ) + "] " + usedPath + "> " + ( isInternal ? "" : "(skip: " + skip + ")" ) );
}
if ( isDelimiter && isInternal && ! emitted.getBoolean( r ) ) {
emitted.set( r, true );
falseFollowsValues.add( 0 );
falseFollowsKeys.writeLong( p - 1, Long.SIZE );
falseFollowsKeys.writeDelta( skip );
for( int i = 0; i < skip; i += Long.SIZE )
falseFollowsKeys.writeLong( curr.getLong( s + i, Math.min( s + i + Long.SIZE, s + skip ) ), Math.min( Long.SIZE, skip - i ) );
if ( DEBUG ) System.err.println( "Adding true follow at " + r + " [" + skip + ", " + Integer.toHexString( curr.subVector( s, s + skip ).hashCode() ) + "] " + curr.subVector( s, s + skip ) );
if ( ASSERTS ) {
long key[] = new long[ ( skip + Long.SIZE - 1 ) / Long.SIZE + 1 ];
key[ 0 ] = p - 1;
for( int i = 0; i < skip; i += Long.SIZE ) key[ i / Long.SIZE + 1 ] = curr.getLong( s + i, Math.min( s + i + Long.SIZE, s + skip ) );
long result = falseFollows.put( LongArrayBitVector.wrap( key, skip + Long.SIZE ), 0 );
assert result == -1 : result + " != " + -1;
if ( DEBUG ) System.err.println( falseFollows );
}
}
if ( ! isInternal || ( s += skip ) >= maxDescentLength ) break;
if ( DEBUG ) System.err.println( "Turning " + ( curr.getBoolean( s ) ? "right" : "left" ) + " at bit " + s + "... " );
if ( curr.getBoolean( s ) ) {
final long q = balParen.findClose( p ) + 1;
index += ( q - p ) / 2;
r += ( q - p ) / 2;
//System.err.println( "Increasing index by " + ( q - p + 1 ) / 2 + " to " + index + "..." );
p = q;
}
else {
p++;
r++;
}
if ( ASSERTS ) assert p < trie.length();
s++;
}
if ( isInternal ) {
startPath = s - skip;
endPath = (int)Math.min( length, s );
}
else {
startPath = s;
endPath = (int)length;
}
// If we exit on a leaf, we invalidate last node/path data
if ( ! isInternal ) lastNode = -1;
if ( lastNode != p - 1 || ! curr.subVector( startPath, endPath ).equals( lastPath ) ) {
externalValues.add( exitLeft ? LEFT : RIGHT );
pathLength = endPath - startPath;
externalKeys.writeLong( p - 1, Long.SIZE );
externalKeys.writeDelta( pathLength );
for( int i = 0; i < pathLength; i += Long.SIZE )
externalKeys.writeLong( curr.getLong( startPath + i, Math.min( startPath + i + Long.SIZE, endPath ) ), Math.min( Long.SIZE, endPath - i - startPath ) );
if ( DEBUG ) System.err.println( "Computed " + ( isInternal ? "" : "leaf " ) + "mapping <" + ( p - 1 ) + ", [" + pathLength + ", " + Integer.toHexString( curr.subVector( startPath, endPath ).hashCode() ) + "] " + curr.subVector( startPath, endPath ) + "> -> " + ( exitLeft ? "left" : "right" ) );
if ( ASSERTS ) {
long key[] = new long[ ( pathLength + Long.SIZE - 1 ) / Long.SIZE + 1 ];
key[ 0 ] = p - 1;
for( int i = 0; i < pathLength; i += Long.SIZE ) key[ i / Long.SIZE + 1 ] = curr.getLong( startPath + i, Math.min( startPath + i + Long.SIZE, endPath ) );
assert externalTestFunction.put( LongArrayBitVector.wrap( key, pathLength + Long.SIZE ), exitLeft ? LEFT : RIGHT ) == -1;
if ( DEBUG ) System.err.println( externalTestFunction );
}
if ( isInternal ) {
if ( DEBUG ) System.err.println( "Adding false follow [" + pathLength + ", " + Integer.toHexString( curr.subVector( startPath, endPath ).hashCode() ) + "] " + curr.subVector( startPath, endPath ) );
lastPath = curr.subVector( startPath, endPath );
lastNode = p - 1;
falseFollowsValues.add( 1 );
falseFollowsKeys.writeLong( p - 1, Long.SIZE );
falseFollowsKeys.writeDelta( pathLength );
for( int i = 0; i < pathLength; i += Long.SIZE )
falseFollowsKeys.writeLong( curr.getLong( startPath + i, Math.min( startPath + i + Long.SIZE, endPath ) ), Math.min( Long.SIZE, endPath - i - startPath ) );
if ( ASSERTS ) {
long key[] = new long[ ( pathLength + Long.SIZE - 1 ) / Long.SIZE + 1 ];
key[ 0 ] = p - 1;
for( int i = 0; i < pathLength; i += Long.SIZE ) key[ i / Long.SIZE + 1 ] = curr.getLong( startPath + i, Math.min( startPath + i + Long.SIZE, endPath ) );
assert falseFollows.put( LongArrayBitVector.wrap( key, pathLength + Long.SIZE ), 1 ) == -1;
if ( DEBUG ) System.err.println( falseFollows );
}
}
}
count++;
}
}
size = count;
pl.done();
externalKeys.close();
falseFollowsKeys.close();
}
else {
trie = null;
balParen = null;
skips = null;
size = 0;
falseFollowsDetector = null;
externalBehaviour = null;
return;
}
/*else {
// No elements.
this.root = null;
this.size = this.numElements = 0;
falseFollowsKeyFile = externalKeysFile = null;
}*/
/** A class iterating over the temporary files produced by the intermediate trie. */
class IterableStream implements Iterable<BitVector> {
private InputBitStream ibs;
private int n;
private Object2LongFunction<BitVector> test;
private LongBigList values;
public IterableStream( final InputBitStream ibs, final Object2LongFunction<BitVector> testFunction, final LongBigList testValues ) {
this.ibs = ibs;
this.n = testValues.size();
this.test = testFunction;
this.values = testValues;
}
public Iterator<BitVector> iterator() {
try {
ibs.position( 0 );
return new AbstractObjectIterator<BitVector>() {
private int pos = 0;
public boolean hasNext() {
return pos < n;
}
public BitVector next() {
if ( ! hasNext() ) throw new NoSuchElementException();
try {
final long index = ibs.readLong( 64 );
assert index >= 0;
final int pathLength = ibs.readDelta();
final long key[] = new long[ ( ( pathLength + Long.SIZE - 1 ) / Long.SIZE + 1 ) ];
key[ 0 ] = index;
for( int i = 0; i < ( pathLength + Long.SIZE - 1 ) / Long.SIZE; i++ ) key[ i + 1 ] = ibs.readLong( Math.min( Long.SIZE, pathLength - i * Long.SIZE ) );
if ( DEBUG ) {
System.err.println( "Adding mapping <" + index + ", " + LongArrayBitVector.wrap( key, pathLength + Long.SIZE ).subVector( Long.SIZE ) + "> -> " + values.getLong( pos ));
System.err.println( LongArrayBitVector.wrap( key, pathLength + Long.SIZE ) );
}
if ( ASSERTS && test != null ) assert test.getLong( LongArrayBitVector.wrap( key, pathLength + Long.SIZE ) ) == values.getLong( pos ) : test.getLong( LongArrayBitVector.wrap( key, pathLength + Long.SIZE ) ) + " != " + values.getLong( pos ) ;
pos++;
return LongArrayBitVector.wrap( key, pathLength + Long.SIZE );
}
catch ( IOException e ) {
throw new RuntimeException( e );
}
}
};
}
catch ( IOException e ) {
throw new RuntimeException( e );
}
}
};
externalBehaviour = new MWHCFunction<BitVector>( new IterableStream( new InputBitStream( externalKeysFile ), externalTestFunction, externalValues ), TransformationStrategies.identity(), externalValues, 1 );
falseFollowsDetector = new MWHCFunction<BitVector>( new IterableStream( new InputBitStream( falseFollowsKeyFile ), falseFollows, falseFollowsValues ), TransformationStrategies.identity(), falseFollowsValues, 1 );
if ( ASSERTS ) {
assert externalBehaviour.size() == externalTestFunction.size();
assert falseFollowsDetector.size() == falseFollows.size();
}
LOGGER.debug( "False positives: " + ( falseFollowsDetector.size() - size / 2 ) );
externalKeysFile.delete();
falseFollowsKeyFile.delete();
/* if ( ASSERTS ) {
if ( size > 0 ) {
Iterator<BitVector>iterator = TransformationStrategies.wrap( elements.iterator(), transformationStrategy );
int c = 0;
while( iterator.hasNext() ) {
BitVector curr = iterator.next();
if ( DEBUG ) System.err.println( "Checking element number " + c + ( ( c + 1 ) % bucketSize == 0 ? " (bucket)" : "" ));
long t = getLong( curr );
assert c / bucketSize == t : c / bucketSize + " != " + t;
c++;
}
}
}*/
}
@SuppressWarnings("unchecked")
public long getLong( final Object o ) {
if ( size == 0 ) return 0;
final BitVector bitVector = transformationStrategy.toBitVector( (T)o ).fast();
LongArrayBitVector key = LongArrayBitVector.getInstance();
BitVector fragment = null;
long p = 1, length = bitVector.length(), index = 0, r = 0;
int s = 0, skip = 0, behaviour;
long lastLeftTurn = 0;
long lastLeftTurnIndex = 0;
boolean isInternal;
if ( DEBUG ) System.err.println( "Distributing " + bitVector + "\ntrie:" + trie );
for(;;) {
isInternal = trie.getBoolean( p );
if ( isInternal ) skip = (int)skips.getLong( r );
if ( DEBUG ) {
final int usedLength = (int)( isInternal ? Math.min( length, s + skip ) : length - s );
final BitVector usedPath = bitVector.subVector( s, s + usedLength );
System.err.println( "Interrogating" + ( isInternal ? "" : " leaf" ) + " <" + ( p - 1 ) +
", [" + Math.min( length, s + skip ) + ", "
+ Integer.toHexString( usedPath.hashCode() ) + "] " +
usedPath + "> " + ( isInternal ? "" : "(skip: " + skip + ")" ) );
}
if ( isInternal && falseFollowsDetector.getLong( key.length( 0 ).append( p - 1, Long.SIZE ).append( fragment = bitVector.subVector( s, Math.min( length, s + skip ) ) ) ) == 0 ) behaviour = FOLLOW;
else behaviour = (int)externalBehaviour.getLong( key.length( 0 ).append( p - 1, Long.SIZE ).append( isInternal ? fragment : bitVector.subVector( s, length ) ) );
if ( ASSERTS ) {
assert ! isInternal || falseFollows.getLong( key.length( 0 ).append( p - 1, Long.SIZE ).append( fragment ) ) != -1;
if ( behaviour != FOLLOW ) {
assert ! isInternal || falseFollows.getLong( key.length( 0 ).append( p - 1, Long.SIZE ).append( fragment ) ) == 1;
final long result;
result = externalTestFunction.getLong( key.length( 0 ).append( p - 1, Long.SIZE ).append( isInternal ? fragment : bitVector.subVector( s, length ) ) );
assert result != -1 : isInternal ? "Missing internal node" : "Missing leaf"; // Only if you don't test with non-keys
if ( result != -1 ) assert result == behaviour : result + " != " + behaviour;
}
else {
assert s + skip <= length;
assert falseFollows.getLong( key.length( 0 ).append( p - 1, Long.SIZE ).append( fragment ) ) == 0;
}
}
if ( DEBUG ) System.err.println( "Exit behaviour: " + behaviour );
if ( behaviour != FOLLOW || ! isInternal || ( s += skip ) >= length ) break;
if ( DEBUG ) System.err.println( "Turning " + ( bitVector.getBoolean( s ) ? "right" : "left" ) + " at bit " + s + "... " );
if ( bitVector.getBoolean( s ) ) {
final long q = balParen.findClose( p ) + 1;
index += ( q - p ) / 2;
r += ( q - p ) / 2;
//System.err.println( "Increasing index by " + ( q - p + 1 ) / 2 + " to " + index + "..." );
p = q;
}
else {
lastLeftTurn = p;
lastLeftTurnIndex = index;
p++;
r++;
}
if ( ASSERTS ) assert p < trie.length();
s++;
}
if ( behaviour == LEFT ) {
if ( DEBUG ) System.err.println( "Returning (on the left) " + index );
return index;
}
else {
if ( isInternal ) {
final long q = balParen.findClose( lastLeftTurn );
//System.err.println( p + ", " + q + " ," + lastLeftTurn + ", " +lastLeftTurnIndex);;
index = ( q - lastLeftTurn + 1 ) / 2 + lastLeftTurnIndex;
if ( DEBUG ) System.err.println( "Returning (on the right, internal) " + index );
}
else {
index++;
if ( DEBUG ) System.err.println( "Returning (on the right, external) " + index );
}
return index;
}
}
public long numBits() {
return trie.length() + skips.numBits() + falseFollowsDetector.numBits() + balParen.numBits() + externalBehaviour.numBits() + transformationStrategy.numBits();
}
public boolean containsKey( Object o ) {
return true;
}
public int size() {
return size;
}
public double bitsPerSkip() {
return (double)skips.numBits() / skips.length();
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.