diff
stringlengths 262
553k
| is_single_chunk
bool 2
classes | is_single_function
bool 1
class | buggy_function
stringlengths 20
391k
| fixed_function
stringlengths 0
392k
|
---|---|---|---|---|
diff --git a/java/test/net/razorvine/pickle/test/ArrayConstructorTest.java b/java/test/net/razorvine/pickle/test/ArrayConstructorTest.java
index bbf2451..593dd3e 100644
--- a/java/test/net/razorvine/pickle/test/ArrayConstructorTest.java
+++ b/java/test/net/razorvine/pickle/test/ArrayConstructorTest.java
@@ -1,188 +1,189 @@
package net.razorvine.pickle.test;
import static org.junit.Assert.*;
import junit.framework.Assert;
import net.razorvine.pickle.PickleException;
import net.razorvine.pickle.objects.ArrayConstructor;
import org.junit.Test;
public class ArrayConstructorTest {
@Test
public void testInvalidMachineTypes()
{
ArrayConstructor ac=new ArrayConstructor();
try {
ac.construct('b', -1, new byte[]{0});
Assert.fail("expected pickleexception");
} catch (PickleException x) {
//ok
}
try {
ac.construct('b', 0, new byte[]{0});
Assert.fail("expected pickleexception");
} catch (PickleException x) {
//ok
}
try {
ac.construct('?', 0, new byte[]{0});
Assert.fail("expected pickleexception");
} catch (PickleException x) {
//ok
}
try {
ac.construct('b', 22, new byte[]{0});
Assert.fail("expected pickleexception");
} catch (PickleException x) {
//ok
}
try {
ac.construct('d', 16, new byte[]{0});
Assert.fail("expected pickleexception");
} catch (PickleException x) {
//ok
}
}
@Test
public void testChars()
{
ArrayConstructor ac=new ArrayConstructor();
+ char EURO=(char)0x20ac;
// c/u
- assertArrayEquals(new char[]{'A','�'}, (char[])ac.construct('c', 18, new byte[]{65,0,(byte)0xac,0x20}));
- assertArrayEquals(new char[]{'A','�'}, (char[])ac.construct('u', 18, new byte[]{65,0,(byte)0xac,0x20}));
- assertArrayEquals(new char[]{'A','�'}, (char[])ac.construct('c', 19, new byte[]{0,65,0x20,(byte)0xac}));
- assertArrayEquals(new char[]{'A','�'}, (char[])ac.construct('u', 19, new byte[]{0,65,0x20,(byte)0xac}));
- assertArrayEquals(new char[]{'A','�'}, (char[])ac.construct('c', 20, new byte[]{65,0,0,0,(byte)0xac,0x20,0,0}));
- assertArrayEquals(new char[]{'A','�'}, (char[])ac.construct('u', 20, new byte[]{65,0,0,0,(byte)0xac,0x20,0,0}));
- assertArrayEquals(new char[]{'A','�'}, (char[])ac.construct('c', 21, new byte[]{0,0,0,65,0,0,0x20,(byte)0xac}));
- assertArrayEquals(new char[]{'A','�'}, (char[])ac.construct('u', 21, new byte[]{0,0,0,65,0,0,0x20,(byte)0xac}));
- assertArrayEquals(new char[]{'A','�'}, (char[])ac.construct('u', 21, new byte[]{1,0,0,65,1,0,0x20,(byte)0xac}));
+ assertArrayEquals(new char[]{'A',EURO}, (char[])ac.construct('c', 18, new byte[]{65,0,(byte)0xac,0x20}));
+ assertArrayEquals(new char[]{'A',EURO}, (char[])ac.construct('u', 18, new byte[]{65,0,(byte)0xac,0x20}));
+ assertArrayEquals(new char[]{'A',EURO}, (char[])ac.construct('c', 19, new byte[]{0,65,0x20,(byte)0xac}));
+ assertArrayEquals(new char[]{'A',EURO}, (char[])ac.construct('u', 19, new byte[]{0,65,0x20,(byte)0xac}));
+ assertArrayEquals(new char[]{'A',EURO}, (char[])ac.construct('c', 20, new byte[]{65,0,0,0,(byte)0xac,0x20,0,0}));
+ assertArrayEquals(new char[]{'A',EURO}, (char[])ac.construct('u', 20, new byte[]{65,0,0,0,(byte)0xac,0x20,0,0}));
+ assertArrayEquals(new char[]{'A',EURO}, (char[])ac.construct('c', 21, new byte[]{0,0,0,65,0,0,0x20,(byte)0xac}));
+ assertArrayEquals(new char[]{'A',EURO}, (char[])ac.construct('u', 21, new byte[]{0,0,0,65,0,0,0x20,(byte)0xac}));
+ assertArrayEquals(new char[]{'A',EURO}, (char[])ac.construct('u', 21, new byte[]{1,0,0,65,1,0,0x20,(byte)0xac}));
// b/B
assertArrayEquals(new byte[]{1,2,3,4,-1,-2,-3,-4}, (byte[])ac.construct('b', 1, new byte[]{1,2,3,4,(byte)0xff,(byte)0xfe,(byte)0xfd,(byte)0xfc}));
assertArrayEquals(new short[]{1,2,3,4,0xff,0xfe,0xfd,0xfc}, (short[])ac.construct('B', 0, new byte[]{1,2,3,4,(byte)0xff,(byte)0xfe,(byte)0xfd,(byte)0xfc}));
}
@Test
public void testInts()
{
ArrayConstructor ac=new ArrayConstructor();
//h
assertEquals((short)0x80ff, ((short[])ac.construct('h', 5, new byte[]{(byte)0x80,(byte)0xff}))[0]);
assertEquals((short)0x7fff, ((short[])ac.construct('h', 5, new byte[]{(byte)0x7f,(byte)0xff}))[0]);
assertEquals((short)0xffff, ((short[])ac.construct('h', 5, new byte[]{(byte)0xff,(byte)0xff}))[0]);
assertEquals((short)0xffff, ((short[])ac.construct('h', 4, new byte[]{(byte)0xff,(byte)0xff}))[0]);
assertArrayEquals(new short[]{0x1234,0x5678}, (short[])ac.construct('h', 5, new byte[]{0x12,0x34,0x56,0x78}));
assertArrayEquals(new short[]{0x3412,0x7856}, (short[])ac.construct('h', 4, new byte[]{0x12,0x34,0x56,0x78}));
//H
assertEquals((int)0x80ff, ((int[])ac.construct('H', 3, new byte[]{(byte)0x80,(byte)0xff}))[0]);
assertEquals((int)0x7fff, ((int[])ac.construct('H', 3, new byte[]{(byte)0x7f,(byte)0xff}))[0]);
assertEquals((int)0xffff, ((int[])ac.construct('H', 3, new byte[]{(byte)0xff,(byte)0xff}))[0]);
assertEquals((int)0xffff, ((int[])ac.construct('H', 2, new byte[]{(byte)0xff,(byte)0xff}))[0]);
assertArrayEquals(new int[]{0x1234,0x5678}, (int[])ac.construct('H', 3, new byte[]{0x12,0x34,0x56,0x78}));
assertArrayEquals(new int[]{0x3412,0x7856}, (int[])ac.construct('H', 2, new byte[]{0x12,0x34,0x56,0x78}));
//i
assertEquals((int)0x800000ff, ((int[])ac.construct('i', 9, new byte[]{(byte)0x80,0x00,0x00,(byte)0xff}))[0]);
assertEquals((int)0x7f0000ff, ((int[])ac.construct('i', 9, new byte[]{(byte)0x7f,0x00,0x00,(byte)0xff}))[0]);
assertEquals((int)0xf00000f1, ((int[])ac.construct('i', 9, new byte[]{(byte)0xf0,0x00,0x00,(byte)0xf1}))[0]);
assertEquals((int)-2, ((int[])ac.construct('i', 8, new byte[]{(byte)0xfe,(byte)0xff,(byte)0xff,(byte)0xff}))[0]);
assertArrayEquals(new int[]{0x11223344,0x55667788}, (int[])ac.construct('i', 9, new byte[]{0x11,0x22,0x33,0x44,0x55,0x66,0x77,(byte)0x88}));
assertArrayEquals(new int[]{0x44332211,0x88776655}, (int[])ac.construct('i', 8, new byte[]{0x11,0x22,0x33,0x44,0x55,0x66,0x77,(byte)0x88}));
//l-4bytes
assertEquals(0x800000ff, ((int[])ac.construct('l', 9, new byte[]{(byte)0x80,0x00,0x00,(byte)0xff}))[0]);
assertEquals(0x7f0000ff, ((int[])ac.construct('l', 9, new byte[]{(byte)0x7f,0x00,0x00,(byte)0xff}))[0]);
assertEquals(0xf00000f1, ((int[])ac.construct('l', 9, new byte[]{(byte)0xf0,0x00,0x00,(byte)0xf1}))[0]);
assertEquals(-2, ((int[])ac.construct('l', 8, new byte[]{(byte)0xfe,(byte)0xff,(byte)0xff,(byte)0xff}))[0]);
assertArrayEquals(new int[]{0x11223344,0x55667788}, (int[])ac.construct('l', 9, new byte[]{0x11,0x22,0x33,0x44,0x55,0x66,0x77,(byte)0x88}));
assertArrayEquals(new int[]{0x44332211,0x88776655}, (int[])ac.construct('l', 8, new byte[]{0x11,0x22,0x33,0x44,0x55,0x66,0x77,(byte)0x88}));
//l-8bytes
assertEquals(0x3400000000000012L, ((long[])ac.construct('l', 12, new byte[]{(byte)0x12,0x00,0x00,0x00,0x00,0x00,0x00,(byte)0x34}))[0]);
assertEquals(0x3400009009000012L, ((long[])ac.construct('l', 12, new byte[]{(byte)0x12,0x00,0x00,0x09,(byte)0x90,0x00,0x00,(byte)0x34}))[0]);
assertEquals(0x1200000000000034L, ((long[])ac.construct('l', 13, new byte[]{(byte)0x12,0x00,0x00,0x00,0x00,0x00,0x00,(byte)0x34}))[0]);
assertEquals(0x1200000990000034L, ((long[])ac.construct('l', 13, new byte[]{(byte)0x12,0x00,0x00,0x09,(byte)0x90,0x00,0x00,(byte)0x34}))[0]);
assertEquals(0x7fffffffffffffffL, ((long[])ac.construct('l', 13, new byte[]{(byte)0x7f,(byte)0xff,(byte)0xff,(byte)0xff,(byte)0xff,(byte)0xff,(byte)0xff,(byte)0xff}))[0]);
assertEquals(0x7fffffffffffffffL, ((long[])ac.construct('l', 12, new byte[]{(byte)0xff,(byte)0xff,(byte)0xff,(byte)0xff,(byte)0xff,(byte)0xff,(byte)0xff,(byte)0x7f}))[0]);
assertEquals(-2L, ((long[])ac.construct('l', 12, new byte[]{(byte)0xfe,(byte)0xff,(byte)0xff,(byte)0xff,(byte)0xff,(byte)0xff,(byte)0xff,(byte)0xff}))[0]);
assertEquals(-2L, ((long[])ac.construct('l', 13, new byte[]{(byte)0xff,(byte)0xff,(byte)0xff,(byte)0xff,(byte)0xff,(byte)0xff,(byte)0xff,(byte)0xfe}))[0]);
assertArrayEquals(new long[]{1,2}, (long[])ac.construct('l', 13, new byte[]{0,0,0,0,0,0,0,1, 0,0,0,0,0,0,0,2}));
assertArrayEquals(new long[]{1,2}, (long[])ac.construct('l', 12, new byte[]{1,0,0,0,0,0,0,0, 2,0,0,0,0,0,0,0}));
//I
assertEquals(0x001000000L, ((long[])ac.construct('I', 6, new byte[]{0,0,0,0x01}))[0]);
assertEquals(0x088000000L, ((long[])ac.construct('I', 6, new byte[]{0,0,0,(byte)0x88}))[0]);
assertEquals(0x000000001L, ((long[])ac.construct('I', 7, new byte[]{0,0,0,0x01}))[0]);
assertEquals(0x000000088L, ((long[])ac.construct('I', 7, new byte[]{0,0,0,(byte)0x88}))[0]);
assertEquals(0x099000088L, ((long[])ac.construct('I', 7, new byte[]{(byte)0x99,0,0,(byte)0x88}))[0]);
//L
try {
ac.construct('L', 6, new byte[]{0,0,0,0x01});
fail("expected exception");
} catch (PickleException x) {
//ok
}
}
@Test
public void testFloats()
{
// f/d
ArrayConstructor ac=new ArrayConstructor();
assertTrue(16711938.0f ==
((float[])ac.construct('f', 14, new byte[]{0x4b,0x7f,0x01,0x02}))[0] );
assertTrue(Float.POSITIVE_INFINITY ==
((float[])ac.construct('f', 14, new byte[]{(byte)0x7f,(byte)0x80,0x00,0x00}))[0]);
assertTrue(Float.NEGATIVE_INFINITY ==
((float[])ac.construct('f', 14, new byte[]{(byte)0xff,(byte)0x80,0x00,0x00}))[0]);
assertTrue(-0.0f ==
((float[])ac.construct('f', 14, new byte[]{(byte)0x80,0x00,0x00,0x00}))[0]);
assertTrue(16711938.0f ==
((float[])ac.construct('f', 15, new byte[]{0x02,0x01,0x7f,0x4b}))[0]);
assertTrue(Float.POSITIVE_INFINITY ==
((float[])ac.construct('f', 15, new byte[]{0x00,0x00,(byte)0x80,(byte)0x7f}))[0]);
assertTrue(Float.NEGATIVE_INFINITY ==
((float[])ac.construct('f', 15, new byte[]{0x00,0x00,(byte)0x80,(byte)0xff}))[0]);
assertTrue(-0.0f ==
((float[])ac.construct('f', 15, new byte[]{0x00,0x00,0x00,(byte)0x80}))[0]);
assertTrue(9006104071832581.0d ==
((double[])ac.construct('d', 16, new byte[]{0x43,0x3f,(byte)0xff,0x01,0x02,0x03,0x04,0x05}))[0]);
assertTrue(Double.POSITIVE_INFINITY ==
((double[])ac.construct('d', 16, new byte[]{(byte)0x7f,(byte)0xf0,0x00,0x00,0x00,0x00,0x00,0x00}))[0]);
assertTrue(Double.NEGATIVE_INFINITY ==
((double[])ac.construct('d', 16, new byte[]{(byte)0xff,(byte)0xf0,0x00,0x00,0x00,0x00,0x00,0x00}))[0]);
assertTrue(-0.0d ==
((double[])ac.construct('d', 16, new byte[]{(byte)0x80,0x00,0x00,0x00,0x00,0x00,0x00,0x00}))[0]);
assertTrue(9006104071832581.0d ==
((double[])ac.construct('d', 17, new byte[]{0x05,0x04,0x03,0x02,0x01,(byte)0xff,0x3f,0x43}))[0]);
assertTrue(Double.POSITIVE_INFINITY ==
((double[])ac.construct('d', 17, new byte[]{0x00,0x00,0x00,0x00,0x00,0x00,(byte)0xf0,(byte)0x7f}))[0]);
assertTrue(Double.NEGATIVE_INFINITY ==
((double[])ac.construct('d', 17, new byte[]{0x00,0x00,0x00,0x00,0x00,0x00,(byte)0xf0,(byte)0xff}))[0]);
assertTrue(-0.0d ==
((double[])ac.construct('d', 17, new byte[]{0x00,0x00,0x00,0x00,0x00,0x00,0x00,(byte)0x80}))[0]);
// check if multiple values in an array work
assertArrayEquals(new float[] {1.1f, 2.2f}, (float[]) ac.construct('f', 14, new byte[]{0x3f,(byte)0x8c,(byte)0xcc,(byte)0xcd, 0x40,0x0c,(byte)0xcc,(byte)0xcd}) ,0);
assertArrayEquals(new float[] {1.1f, 2.2f}, (float[]) ac.construct('f', 15, new byte[]{(byte)0xcd,(byte)0xcc,(byte)0x8c,0x3f, (byte)0xcd,(byte)0xcc,0x0c,0x40}) ,0);
assertArrayEquals(new double[]{1.1d, 2.2d}, (double[]) ac.construct('d', 16, new byte[]{(byte)0x3f,(byte)0xf1,(byte)0x99,(byte)0x99,(byte)0x99,(byte)0x99,(byte)0x99,(byte)0x9a, (byte)0x40,(byte)0x01,(byte)0x99,(byte)0x99,(byte)0x99,(byte)0x99,(byte)0x99,(byte)0x9a}) ,0);
assertArrayEquals(new double[]{1.1d, 2.2d}, (double[]) ac.construct('d', 17, new byte[]{(byte)0x9a,(byte)0x99,(byte)0x99,(byte)0x99,(byte)0x99,(byte)0x99,(byte)0xf1,(byte)0x3f, (byte)0x9a,(byte)0x99,(byte)0x99,(byte)0x99,(byte)0x99,(byte)0x99,(byte)0x01,(byte)0x40}) ,0);
}
}
| false | true | public void testChars()
{
ArrayConstructor ac=new ArrayConstructor();
// c/u
assertArrayEquals(new char[]{'A','�'}, (char[])ac.construct('c', 18, new byte[]{65,0,(byte)0xac,0x20}));
assertArrayEquals(new char[]{'A','�'}, (char[])ac.construct('u', 18, new byte[]{65,0,(byte)0xac,0x20}));
assertArrayEquals(new char[]{'A','�'}, (char[])ac.construct('c', 19, new byte[]{0,65,0x20,(byte)0xac}));
assertArrayEquals(new char[]{'A','�'}, (char[])ac.construct('u', 19, new byte[]{0,65,0x20,(byte)0xac}));
assertArrayEquals(new char[]{'A','�'}, (char[])ac.construct('c', 20, new byte[]{65,0,0,0,(byte)0xac,0x20,0,0}));
assertArrayEquals(new char[]{'A','�'}, (char[])ac.construct('u', 20, new byte[]{65,0,0,0,(byte)0xac,0x20,0,0}));
assertArrayEquals(new char[]{'A','�'}, (char[])ac.construct('c', 21, new byte[]{0,0,0,65,0,0,0x20,(byte)0xac}));
assertArrayEquals(new char[]{'A','�'}, (char[])ac.construct('u', 21, new byte[]{0,0,0,65,0,0,0x20,(byte)0xac}));
assertArrayEquals(new char[]{'A','�'}, (char[])ac.construct('u', 21, new byte[]{1,0,0,65,1,0,0x20,(byte)0xac}));
// b/B
assertArrayEquals(new byte[]{1,2,3,4,-1,-2,-3,-4}, (byte[])ac.construct('b', 1, new byte[]{1,2,3,4,(byte)0xff,(byte)0xfe,(byte)0xfd,(byte)0xfc}));
assertArrayEquals(new short[]{1,2,3,4,0xff,0xfe,0xfd,0xfc}, (short[])ac.construct('B', 0, new byte[]{1,2,3,4,(byte)0xff,(byte)0xfe,(byte)0xfd,(byte)0xfc}));
}
@Test
public void testInts()
{
ArrayConstructor ac=new ArrayConstructor();
//h
assertEquals((short)0x80ff, ((short[])ac.construct('h', 5, new byte[]{(byte)0x80,(byte)0xff}))[0]);
assertEquals((short)0x7fff, ((short[])ac.construct('h', 5, new byte[]{(byte)0x7f,(byte)0xff}))[0]);
assertEquals((short)0xffff, ((short[])ac.construct('h', 5, new byte[]{(byte)0xff,(byte)0xff}))[0]);
assertEquals((short)0xffff, ((short[])ac.construct('h', 4, new byte[]{(byte)0xff,(byte)0xff}))[0]);
assertArrayEquals(new short[]{0x1234,0x5678}, (short[])ac.construct('h', 5, new byte[]{0x12,0x34,0x56,0x78}));
assertArrayEquals(new short[]{0x3412,0x7856}, (short[])ac.construct('h', 4, new byte[]{0x12,0x34,0x56,0x78}));
//H
assertEquals((int)0x80ff, ((int[])ac.construct('H', 3, new byte[]{(byte)0x80,(byte)0xff}))[0]);
assertEquals((int)0x7fff, ((int[])ac.construct('H', 3, new byte[]{(byte)0x7f,(byte)0xff}))[0]);
assertEquals((int)0xffff, ((int[])ac.construct('H', 3, new byte[]{(byte)0xff,(byte)0xff}))[0]);
assertEquals((int)0xffff, ((int[])ac.construct('H', 2, new byte[]{(byte)0xff,(byte)0xff}))[0]);
assertArrayEquals(new int[]{0x1234,0x5678}, (int[])ac.construct('H', 3, new byte[]{0x12,0x34,0x56,0x78}));
assertArrayEquals(new int[]{0x3412,0x7856}, (int[])ac.construct('H', 2, new byte[]{0x12,0x34,0x56,0x78}));
//i
assertEquals((int)0x800000ff, ((int[])ac.construct('i', 9, new byte[]{(byte)0x80,0x00,0x00,(byte)0xff}))[0]);
assertEquals((int)0x7f0000ff, ((int[])ac.construct('i', 9, new byte[]{(byte)0x7f,0x00,0x00,(byte)0xff}))[0]);
assertEquals((int)0xf00000f1, ((int[])ac.construct('i', 9, new byte[]{(byte)0xf0,0x00,0x00,(byte)0xf1}))[0]);
assertEquals((int)-2, ((int[])ac.construct('i', 8, new byte[]{(byte)0xfe,(byte)0xff,(byte)0xff,(byte)0xff}))[0]);
assertArrayEquals(new int[]{0x11223344,0x55667788}, (int[])ac.construct('i', 9, new byte[]{0x11,0x22,0x33,0x44,0x55,0x66,0x77,(byte)0x88}));
assertArrayEquals(new int[]{0x44332211,0x88776655}, (int[])ac.construct('i', 8, new byte[]{0x11,0x22,0x33,0x44,0x55,0x66,0x77,(byte)0x88}));
//l-4bytes
assertEquals(0x800000ff, ((int[])ac.construct('l', 9, new byte[]{(byte)0x80,0x00,0x00,(byte)0xff}))[0]);
assertEquals(0x7f0000ff, ((int[])ac.construct('l', 9, new byte[]{(byte)0x7f,0x00,0x00,(byte)0xff}))[0]);
assertEquals(0xf00000f1, ((int[])ac.construct('l', 9, new byte[]{(byte)0xf0,0x00,0x00,(byte)0xf1}))[0]);
assertEquals(-2, ((int[])ac.construct('l', 8, new byte[]{(byte)0xfe,(byte)0xff,(byte)0xff,(byte)0xff}))[0]);
assertArrayEquals(new int[]{0x11223344,0x55667788}, (int[])ac.construct('l', 9, new byte[]{0x11,0x22,0x33,0x44,0x55,0x66,0x77,(byte)0x88}));
assertArrayEquals(new int[]{0x44332211,0x88776655}, (int[])ac.construct('l', 8, new byte[]{0x11,0x22,0x33,0x44,0x55,0x66,0x77,(byte)0x88}));
//l-8bytes
assertEquals(0x3400000000000012L, ((long[])ac.construct('l', 12, new byte[]{(byte)0x12,0x00,0x00,0x00,0x00,0x00,0x00,(byte)0x34}))[0]);
assertEquals(0x3400009009000012L, ((long[])ac.construct('l', 12, new byte[]{(byte)0x12,0x00,0x00,0x09,(byte)0x90,0x00,0x00,(byte)0x34}))[0]);
assertEquals(0x1200000000000034L, ((long[])ac.construct('l', 13, new byte[]{(byte)0x12,0x00,0x00,0x00,0x00,0x00,0x00,(byte)0x34}))[0]);
assertEquals(0x1200000990000034L, ((long[])ac.construct('l', 13, new byte[]{(byte)0x12,0x00,0x00,0x09,(byte)0x90,0x00,0x00,(byte)0x34}))[0]);
assertEquals(0x7fffffffffffffffL, ((long[])ac.construct('l', 13, new byte[]{(byte)0x7f,(byte)0xff,(byte)0xff,(byte)0xff,(byte)0xff,(byte)0xff,(byte)0xff,(byte)0xff}))[0]);
assertEquals(0x7fffffffffffffffL, ((long[])ac.construct('l', 12, new byte[]{(byte)0xff,(byte)0xff,(byte)0xff,(byte)0xff,(byte)0xff,(byte)0xff,(byte)0xff,(byte)0x7f}))[0]);
assertEquals(-2L, ((long[])ac.construct('l', 12, new byte[]{(byte)0xfe,(byte)0xff,(byte)0xff,(byte)0xff,(byte)0xff,(byte)0xff,(byte)0xff,(byte)0xff}))[0]);
assertEquals(-2L, ((long[])ac.construct('l', 13, new byte[]{(byte)0xff,(byte)0xff,(byte)0xff,(byte)0xff,(byte)0xff,(byte)0xff,(byte)0xff,(byte)0xfe}))[0]);
assertArrayEquals(new long[]{1,2}, (long[])ac.construct('l', 13, new byte[]{0,0,0,0,0,0,0,1, 0,0,0,0,0,0,0,2}));
assertArrayEquals(new long[]{1,2}, (long[])ac.construct('l', 12, new byte[]{1,0,0,0,0,0,0,0, 2,0,0,0,0,0,0,0}));
//I
assertEquals(0x001000000L, ((long[])ac.construct('I', 6, new byte[]{0,0,0,0x01}))[0]);
assertEquals(0x088000000L, ((long[])ac.construct('I', 6, new byte[]{0,0,0,(byte)0x88}))[0]);
assertEquals(0x000000001L, ((long[])ac.construct('I', 7, new byte[]{0,0,0,0x01}))[0]);
assertEquals(0x000000088L, ((long[])ac.construct('I', 7, new byte[]{0,0,0,(byte)0x88}))[0]);
assertEquals(0x099000088L, ((long[])ac.construct('I', 7, new byte[]{(byte)0x99,0,0,(byte)0x88}))[0]);
//L
try {
ac.construct('L', 6, new byte[]{0,0,0,0x01});
fail("expected exception");
} catch (PickleException x) {
//ok
}
}
@Test
public void testFloats()
{
// f/d
ArrayConstructor ac=new ArrayConstructor();
assertTrue(16711938.0f ==
((float[])ac.construct('f', 14, new byte[]{0x4b,0x7f,0x01,0x02}))[0] );
assertTrue(Float.POSITIVE_INFINITY ==
((float[])ac.construct('f', 14, new byte[]{(byte)0x7f,(byte)0x80,0x00,0x00}))[0]);
assertTrue(Float.NEGATIVE_INFINITY ==
((float[])ac.construct('f', 14, new byte[]{(byte)0xff,(byte)0x80,0x00,0x00}))[0]);
assertTrue(-0.0f ==
((float[])ac.construct('f', 14, new byte[]{(byte)0x80,0x00,0x00,0x00}))[0]);
assertTrue(16711938.0f ==
((float[])ac.construct('f', 15, new byte[]{0x02,0x01,0x7f,0x4b}))[0]);
assertTrue(Float.POSITIVE_INFINITY ==
((float[])ac.construct('f', 15, new byte[]{0x00,0x00,(byte)0x80,(byte)0x7f}))[0]);
assertTrue(Float.NEGATIVE_INFINITY ==
((float[])ac.construct('f', 15, new byte[]{0x00,0x00,(byte)0x80,(byte)0xff}))[0]);
assertTrue(-0.0f ==
((float[])ac.construct('f', 15, new byte[]{0x00,0x00,0x00,(byte)0x80}))[0]);
assertTrue(9006104071832581.0d ==
((double[])ac.construct('d', 16, new byte[]{0x43,0x3f,(byte)0xff,0x01,0x02,0x03,0x04,0x05}))[0]);
assertTrue(Double.POSITIVE_INFINITY ==
((double[])ac.construct('d', 16, new byte[]{(byte)0x7f,(byte)0xf0,0x00,0x00,0x00,0x00,0x00,0x00}))[0]);
assertTrue(Double.NEGATIVE_INFINITY ==
((double[])ac.construct('d', 16, new byte[]{(byte)0xff,(byte)0xf0,0x00,0x00,0x00,0x00,0x00,0x00}))[0]);
assertTrue(-0.0d ==
((double[])ac.construct('d', 16, new byte[]{(byte)0x80,0x00,0x00,0x00,0x00,0x00,0x00,0x00}))[0]);
assertTrue(9006104071832581.0d ==
((double[])ac.construct('d', 17, new byte[]{0x05,0x04,0x03,0x02,0x01,(byte)0xff,0x3f,0x43}))[0]);
assertTrue(Double.POSITIVE_INFINITY ==
((double[])ac.construct('d', 17, new byte[]{0x00,0x00,0x00,0x00,0x00,0x00,(byte)0xf0,(byte)0x7f}))[0]);
assertTrue(Double.NEGATIVE_INFINITY ==
((double[])ac.construct('d', 17, new byte[]{0x00,0x00,0x00,0x00,0x00,0x00,(byte)0xf0,(byte)0xff}))[0]);
assertTrue(-0.0d ==
((double[])ac.construct('d', 17, new byte[]{0x00,0x00,0x00,0x00,0x00,0x00,0x00,(byte)0x80}))[0]);
// check if multiple values in an array work
assertArrayEquals(new float[] {1.1f, 2.2f}, (float[]) ac.construct('f', 14, new byte[]{0x3f,(byte)0x8c,(byte)0xcc,(byte)0xcd, 0x40,0x0c,(byte)0xcc,(byte)0xcd}) ,0);
assertArrayEquals(new float[] {1.1f, 2.2f}, (float[]) ac.construct('f', 15, new byte[]{(byte)0xcd,(byte)0xcc,(byte)0x8c,0x3f, (byte)0xcd,(byte)0xcc,0x0c,0x40}) ,0);
assertArrayEquals(new double[]{1.1d, 2.2d}, (double[]) ac.construct('d', 16, new byte[]{(byte)0x3f,(byte)0xf1,(byte)0x99,(byte)0x99,(byte)0x99,(byte)0x99,(byte)0x99,(byte)0x9a, (byte)0x40,(byte)0x01,(byte)0x99,(byte)0x99,(byte)0x99,(byte)0x99,(byte)0x99,(byte)0x9a}) ,0);
assertArrayEquals(new double[]{1.1d, 2.2d}, (double[]) ac.construct('d', 17, new byte[]{(byte)0x9a,(byte)0x99,(byte)0x99,(byte)0x99,(byte)0x99,(byte)0x99,(byte)0xf1,(byte)0x3f, (byte)0x9a,(byte)0x99,(byte)0x99,(byte)0x99,(byte)0x99,(byte)0x99,(byte)0x01,(byte)0x40}) ,0);
}
}
| public void testChars()
{
ArrayConstructor ac=new ArrayConstructor();
char EURO=(char)0x20ac;
// c/u
assertArrayEquals(new char[]{'A',EURO}, (char[])ac.construct('c', 18, new byte[]{65,0,(byte)0xac,0x20}));
assertArrayEquals(new char[]{'A',EURO}, (char[])ac.construct('u', 18, new byte[]{65,0,(byte)0xac,0x20}));
assertArrayEquals(new char[]{'A',EURO}, (char[])ac.construct('c', 19, new byte[]{0,65,0x20,(byte)0xac}));
assertArrayEquals(new char[]{'A',EURO}, (char[])ac.construct('u', 19, new byte[]{0,65,0x20,(byte)0xac}));
assertArrayEquals(new char[]{'A',EURO}, (char[])ac.construct('c', 20, new byte[]{65,0,0,0,(byte)0xac,0x20,0,0}));
assertArrayEquals(new char[]{'A',EURO}, (char[])ac.construct('u', 20, new byte[]{65,0,0,0,(byte)0xac,0x20,0,0}));
assertArrayEquals(new char[]{'A',EURO}, (char[])ac.construct('c', 21, new byte[]{0,0,0,65,0,0,0x20,(byte)0xac}));
assertArrayEquals(new char[]{'A',EURO}, (char[])ac.construct('u', 21, new byte[]{0,0,0,65,0,0,0x20,(byte)0xac}));
assertArrayEquals(new char[]{'A',EURO}, (char[])ac.construct('u', 21, new byte[]{1,0,0,65,1,0,0x20,(byte)0xac}));
// b/B
assertArrayEquals(new byte[]{1,2,3,4,-1,-2,-3,-4}, (byte[])ac.construct('b', 1, new byte[]{1,2,3,4,(byte)0xff,(byte)0xfe,(byte)0xfd,(byte)0xfc}));
assertArrayEquals(new short[]{1,2,3,4,0xff,0xfe,0xfd,0xfc}, (short[])ac.construct('B', 0, new byte[]{1,2,3,4,(byte)0xff,(byte)0xfe,(byte)0xfd,(byte)0xfc}));
}
@Test
public void testInts()
{
ArrayConstructor ac=new ArrayConstructor();
//h
assertEquals((short)0x80ff, ((short[])ac.construct('h', 5, new byte[]{(byte)0x80,(byte)0xff}))[0]);
assertEquals((short)0x7fff, ((short[])ac.construct('h', 5, new byte[]{(byte)0x7f,(byte)0xff}))[0]);
assertEquals((short)0xffff, ((short[])ac.construct('h', 5, new byte[]{(byte)0xff,(byte)0xff}))[0]);
assertEquals((short)0xffff, ((short[])ac.construct('h', 4, new byte[]{(byte)0xff,(byte)0xff}))[0]);
assertArrayEquals(new short[]{0x1234,0x5678}, (short[])ac.construct('h', 5, new byte[]{0x12,0x34,0x56,0x78}));
assertArrayEquals(new short[]{0x3412,0x7856}, (short[])ac.construct('h', 4, new byte[]{0x12,0x34,0x56,0x78}));
//H
assertEquals((int)0x80ff, ((int[])ac.construct('H', 3, new byte[]{(byte)0x80,(byte)0xff}))[0]);
assertEquals((int)0x7fff, ((int[])ac.construct('H', 3, new byte[]{(byte)0x7f,(byte)0xff}))[0]);
assertEquals((int)0xffff, ((int[])ac.construct('H', 3, new byte[]{(byte)0xff,(byte)0xff}))[0]);
assertEquals((int)0xffff, ((int[])ac.construct('H', 2, new byte[]{(byte)0xff,(byte)0xff}))[0]);
assertArrayEquals(new int[]{0x1234,0x5678}, (int[])ac.construct('H', 3, new byte[]{0x12,0x34,0x56,0x78}));
assertArrayEquals(new int[]{0x3412,0x7856}, (int[])ac.construct('H', 2, new byte[]{0x12,0x34,0x56,0x78}));
//i
assertEquals((int)0x800000ff, ((int[])ac.construct('i', 9, new byte[]{(byte)0x80,0x00,0x00,(byte)0xff}))[0]);
assertEquals((int)0x7f0000ff, ((int[])ac.construct('i', 9, new byte[]{(byte)0x7f,0x00,0x00,(byte)0xff}))[0]);
assertEquals((int)0xf00000f1, ((int[])ac.construct('i', 9, new byte[]{(byte)0xf0,0x00,0x00,(byte)0xf1}))[0]);
assertEquals((int)-2, ((int[])ac.construct('i', 8, new byte[]{(byte)0xfe,(byte)0xff,(byte)0xff,(byte)0xff}))[0]);
assertArrayEquals(new int[]{0x11223344,0x55667788}, (int[])ac.construct('i', 9, new byte[]{0x11,0x22,0x33,0x44,0x55,0x66,0x77,(byte)0x88}));
assertArrayEquals(new int[]{0x44332211,0x88776655}, (int[])ac.construct('i', 8, new byte[]{0x11,0x22,0x33,0x44,0x55,0x66,0x77,(byte)0x88}));
//l-4bytes
assertEquals(0x800000ff, ((int[])ac.construct('l', 9, new byte[]{(byte)0x80,0x00,0x00,(byte)0xff}))[0]);
assertEquals(0x7f0000ff, ((int[])ac.construct('l', 9, new byte[]{(byte)0x7f,0x00,0x00,(byte)0xff}))[0]);
assertEquals(0xf00000f1, ((int[])ac.construct('l', 9, new byte[]{(byte)0xf0,0x00,0x00,(byte)0xf1}))[0]);
assertEquals(-2, ((int[])ac.construct('l', 8, new byte[]{(byte)0xfe,(byte)0xff,(byte)0xff,(byte)0xff}))[0]);
assertArrayEquals(new int[]{0x11223344,0x55667788}, (int[])ac.construct('l', 9, new byte[]{0x11,0x22,0x33,0x44,0x55,0x66,0x77,(byte)0x88}));
assertArrayEquals(new int[]{0x44332211,0x88776655}, (int[])ac.construct('l', 8, new byte[]{0x11,0x22,0x33,0x44,0x55,0x66,0x77,(byte)0x88}));
//l-8bytes
assertEquals(0x3400000000000012L, ((long[])ac.construct('l', 12, new byte[]{(byte)0x12,0x00,0x00,0x00,0x00,0x00,0x00,(byte)0x34}))[0]);
assertEquals(0x3400009009000012L, ((long[])ac.construct('l', 12, new byte[]{(byte)0x12,0x00,0x00,0x09,(byte)0x90,0x00,0x00,(byte)0x34}))[0]);
assertEquals(0x1200000000000034L, ((long[])ac.construct('l', 13, new byte[]{(byte)0x12,0x00,0x00,0x00,0x00,0x00,0x00,(byte)0x34}))[0]);
assertEquals(0x1200000990000034L, ((long[])ac.construct('l', 13, new byte[]{(byte)0x12,0x00,0x00,0x09,(byte)0x90,0x00,0x00,(byte)0x34}))[0]);
assertEquals(0x7fffffffffffffffL, ((long[])ac.construct('l', 13, new byte[]{(byte)0x7f,(byte)0xff,(byte)0xff,(byte)0xff,(byte)0xff,(byte)0xff,(byte)0xff,(byte)0xff}))[0]);
assertEquals(0x7fffffffffffffffL, ((long[])ac.construct('l', 12, new byte[]{(byte)0xff,(byte)0xff,(byte)0xff,(byte)0xff,(byte)0xff,(byte)0xff,(byte)0xff,(byte)0x7f}))[0]);
assertEquals(-2L, ((long[])ac.construct('l', 12, new byte[]{(byte)0xfe,(byte)0xff,(byte)0xff,(byte)0xff,(byte)0xff,(byte)0xff,(byte)0xff,(byte)0xff}))[0]);
assertEquals(-2L, ((long[])ac.construct('l', 13, new byte[]{(byte)0xff,(byte)0xff,(byte)0xff,(byte)0xff,(byte)0xff,(byte)0xff,(byte)0xff,(byte)0xfe}))[0]);
assertArrayEquals(new long[]{1,2}, (long[])ac.construct('l', 13, new byte[]{0,0,0,0,0,0,0,1, 0,0,0,0,0,0,0,2}));
assertArrayEquals(new long[]{1,2}, (long[])ac.construct('l', 12, new byte[]{1,0,0,0,0,0,0,0, 2,0,0,0,0,0,0,0}));
//I
assertEquals(0x001000000L, ((long[])ac.construct('I', 6, new byte[]{0,0,0,0x01}))[0]);
assertEquals(0x088000000L, ((long[])ac.construct('I', 6, new byte[]{0,0,0,(byte)0x88}))[0]);
assertEquals(0x000000001L, ((long[])ac.construct('I', 7, new byte[]{0,0,0,0x01}))[0]);
assertEquals(0x000000088L, ((long[])ac.construct('I', 7, new byte[]{0,0,0,(byte)0x88}))[0]);
assertEquals(0x099000088L, ((long[])ac.construct('I', 7, new byte[]{(byte)0x99,0,0,(byte)0x88}))[0]);
//L
try {
ac.construct('L', 6, new byte[]{0,0,0,0x01});
fail("expected exception");
} catch (PickleException x) {
//ok
}
}
@Test
public void testFloats()
{
// f/d
ArrayConstructor ac=new ArrayConstructor();
assertTrue(16711938.0f ==
((float[])ac.construct('f', 14, new byte[]{0x4b,0x7f,0x01,0x02}))[0] );
assertTrue(Float.POSITIVE_INFINITY ==
((float[])ac.construct('f', 14, new byte[]{(byte)0x7f,(byte)0x80,0x00,0x00}))[0]);
assertTrue(Float.NEGATIVE_INFINITY ==
((float[])ac.construct('f', 14, new byte[]{(byte)0xff,(byte)0x80,0x00,0x00}))[0]);
assertTrue(-0.0f ==
((float[])ac.construct('f', 14, new byte[]{(byte)0x80,0x00,0x00,0x00}))[0]);
assertTrue(16711938.0f ==
((float[])ac.construct('f', 15, new byte[]{0x02,0x01,0x7f,0x4b}))[0]);
assertTrue(Float.POSITIVE_INFINITY ==
((float[])ac.construct('f', 15, new byte[]{0x00,0x00,(byte)0x80,(byte)0x7f}))[0]);
assertTrue(Float.NEGATIVE_INFINITY ==
((float[])ac.construct('f', 15, new byte[]{0x00,0x00,(byte)0x80,(byte)0xff}))[0]);
assertTrue(-0.0f ==
((float[])ac.construct('f', 15, new byte[]{0x00,0x00,0x00,(byte)0x80}))[0]);
assertTrue(9006104071832581.0d ==
((double[])ac.construct('d', 16, new byte[]{0x43,0x3f,(byte)0xff,0x01,0x02,0x03,0x04,0x05}))[0]);
assertTrue(Double.POSITIVE_INFINITY ==
((double[])ac.construct('d', 16, new byte[]{(byte)0x7f,(byte)0xf0,0x00,0x00,0x00,0x00,0x00,0x00}))[0]);
assertTrue(Double.NEGATIVE_INFINITY ==
((double[])ac.construct('d', 16, new byte[]{(byte)0xff,(byte)0xf0,0x00,0x00,0x00,0x00,0x00,0x00}))[0]);
assertTrue(-0.0d ==
((double[])ac.construct('d', 16, new byte[]{(byte)0x80,0x00,0x00,0x00,0x00,0x00,0x00,0x00}))[0]);
assertTrue(9006104071832581.0d ==
((double[])ac.construct('d', 17, new byte[]{0x05,0x04,0x03,0x02,0x01,(byte)0xff,0x3f,0x43}))[0]);
assertTrue(Double.POSITIVE_INFINITY ==
((double[])ac.construct('d', 17, new byte[]{0x00,0x00,0x00,0x00,0x00,0x00,(byte)0xf0,(byte)0x7f}))[0]);
assertTrue(Double.NEGATIVE_INFINITY ==
((double[])ac.construct('d', 17, new byte[]{0x00,0x00,0x00,0x00,0x00,0x00,(byte)0xf0,(byte)0xff}))[0]);
assertTrue(-0.0d ==
((double[])ac.construct('d', 17, new byte[]{0x00,0x00,0x00,0x00,0x00,0x00,0x00,(byte)0x80}))[0]);
// check if multiple values in an array work
assertArrayEquals(new float[] {1.1f, 2.2f}, (float[]) ac.construct('f', 14, new byte[]{0x3f,(byte)0x8c,(byte)0xcc,(byte)0xcd, 0x40,0x0c,(byte)0xcc,(byte)0xcd}) ,0);
assertArrayEquals(new float[] {1.1f, 2.2f}, (float[]) ac.construct('f', 15, new byte[]{(byte)0xcd,(byte)0xcc,(byte)0x8c,0x3f, (byte)0xcd,(byte)0xcc,0x0c,0x40}) ,0);
assertArrayEquals(new double[]{1.1d, 2.2d}, (double[]) ac.construct('d', 16, new byte[]{(byte)0x3f,(byte)0xf1,(byte)0x99,(byte)0x99,(byte)0x99,(byte)0x99,(byte)0x99,(byte)0x9a, (byte)0x40,(byte)0x01,(byte)0x99,(byte)0x99,(byte)0x99,(byte)0x99,(byte)0x99,(byte)0x9a}) ,0);
assertArrayEquals(new double[]{1.1d, 2.2d}, (double[]) ac.construct('d', 17, new byte[]{(byte)0x9a,(byte)0x99,(byte)0x99,(byte)0x99,(byte)0x99,(byte)0x99,(byte)0xf1,(byte)0x3f, (byte)0x9a,(byte)0x99,(byte)0x99,(byte)0x99,(byte)0x99,(byte)0x99,(byte)0x01,(byte)0x40}) ,0);
}
}
|
diff --git a/src/org/flowvisor/message/FVPortMod.java b/src/org/flowvisor/message/FVPortMod.java
index 95b968f..d6ff01a 100644
--- a/src/org/flowvisor/message/FVPortMod.java
+++ b/src/org/flowvisor/message/FVPortMod.java
@@ -1,50 +1,50 @@
package org.flowvisor.message;
import org.flowvisor.classifier.FVClassifier;
import org.flowvisor.log.FVLog;
import org.flowvisor.log.LogLevel;
import org.flowvisor.slicer.FVSlicer;
import org.openflow.protocol.OFPhysicalPort;
import org.openflow.protocol.OFPortMod;
import org.openflow.protocol.OFError.OFPortModFailedCode;
public class FVPortMod extends OFPortMod implements Classifiable, Slicable {
/**
* Send to all slices with this port
*
* FIXME: decide if port_mod's can come *up* from switch?
*/
@Override
public void classifyFromSwitch(FVClassifier fvClassifier) {
FVLog.log(LogLevel.DEBUG, fvClassifier, "recv from switch: " + this);
for (FVSlicer fvSlicer : fvClassifier.getSlicers())
if (fvSlicer.portInSlice(this.portNumber))
fvSlicer.sendMsg(this, fvClassifier);
}
/**
* First, check to see if this port is available in this slice Second, check
* to see if they're changing the FLOOD bit FIXME: prevent slices from
* administratrively bringing down a port!
*/
@Override
public void sliceFromController(FVClassifier fvClassifier, FVSlicer fvSlicer) {
// First, check if this port is in the slice
if (!fvSlicer.portInSlice(this.portNumber)) {
fvSlicer.sendMsg(FVMessageUtil.makeErrorMsg(
OFPortModFailedCode.OFPPMFC_BAD_PORT, this), fvClassifier);
return;
}
// Second, update the port's flood state
boolean oldValue = fvSlicer.getFloodPortStatus(this.portNumber);
FVLog.log(LogLevel.DEBUG, fvSlicer, "Setting port " + this.portNumber + " to " +
- ((this.mask & OFPhysicalPort.OFPortConfig.OFPPC_NO_FLOOD.ordinal()) == 0));
+ ((this.mask & OFPhysicalPort.OFPortConfig.OFPPC_NO_FLOOD.getValue()) == 0));
fvSlicer.setFloodPortStatus(this.portNumber,
(this.mask & OFPhysicalPort.OFPortConfig.OFPPC_NO_FLOOD
.ordinal()) == 0);
if (oldValue != fvSlicer.getFloodPortStatus(this.portNumber))
FVLog.log(LogLevel.CRIT, fvSlicer,
"FIXME: need to implement FLOODING port changes");
}
}
| true | true | public void sliceFromController(FVClassifier fvClassifier, FVSlicer fvSlicer) {
// First, check if this port is in the slice
if (!fvSlicer.portInSlice(this.portNumber)) {
fvSlicer.sendMsg(FVMessageUtil.makeErrorMsg(
OFPortModFailedCode.OFPPMFC_BAD_PORT, this), fvClassifier);
return;
}
// Second, update the port's flood state
boolean oldValue = fvSlicer.getFloodPortStatus(this.portNumber);
FVLog.log(LogLevel.DEBUG, fvSlicer, "Setting port " + this.portNumber + " to " +
((this.mask & OFPhysicalPort.OFPortConfig.OFPPC_NO_FLOOD.ordinal()) == 0));
fvSlicer.setFloodPortStatus(this.portNumber,
(this.mask & OFPhysicalPort.OFPortConfig.OFPPC_NO_FLOOD
.ordinal()) == 0);
if (oldValue != fvSlicer.getFloodPortStatus(this.portNumber))
FVLog.log(LogLevel.CRIT, fvSlicer,
"FIXME: need to implement FLOODING port changes");
}
| public void sliceFromController(FVClassifier fvClassifier, FVSlicer fvSlicer) {
// First, check if this port is in the slice
if (!fvSlicer.portInSlice(this.portNumber)) {
fvSlicer.sendMsg(FVMessageUtil.makeErrorMsg(
OFPortModFailedCode.OFPPMFC_BAD_PORT, this), fvClassifier);
return;
}
// Second, update the port's flood state
boolean oldValue = fvSlicer.getFloodPortStatus(this.portNumber);
FVLog.log(LogLevel.DEBUG, fvSlicer, "Setting port " + this.portNumber + " to " +
((this.mask & OFPhysicalPort.OFPortConfig.OFPPC_NO_FLOOD.getValue()) == 0));
fvSlicer.setFloodPortStatus(this.portNumber,
(this.mask & OFPhysicalPort.OFPortConfig.OFPPC_NO_FLOOD
.ordinal()) == 0);
if (oldValue != fvSlicer.getFloodPortStatus(this.portNumber))
FVLog.log(LogLevel.CRIT, fvSlicer,
"FIXME: need to implement FLOODING port changes");
}
|
diff --git a/examples/de/fhpotsdam/unfolding/examples/marker/connectionmarker/ConnectionMarker.java b/examples/de/fhpotsdam/unfolding/examples/marker/connectionmarker/ConnectionMarker.java
index 6c8c86e..50f911d 100644
--- a/examples/de/fhpotsdam/unfolding/examples/marker/connectionmarker/ConnectionMarker.java
+++ b/examples/de/fhpotsdam/unfolding/examples/marker/connectionmarker/ConnectionMarker.java
@@ -1,49 +1,49 @@
package de.fhpotsdam.unfolding.examples.marker.connectionmarker;
import processing.core.PGraphics;
import processing.core.PVector;
import de.fhpotsdam.unfolding.Map;
import de.fhpotsdam.unfolding.geo.Location;
import de.fhpotsdam.unfolding.marker.AbstractMarker;
import de.fhpotsdam.unfolding.marker.AbstractMultiMarker;
import de.fhpotsdam.unfolding.marker.Marker;
public class ConnectionMarker extends AbstractMultiMarker {
// public Marker fromMarker;
// public Marker toMarker;
public ConnectionMarker(Marker fromMarker, Marker toMarker) {
addLocation(fromMarker.getLocation());
addLocation(toMarker.getLocation());
}
@Override
public void drawOuter(Map map) {
- PGraphics pg = map.mapDisplay.getPG();
- float[] xy1 = map.mapDisplay.getScreenPositionFromLocation(getLocation(0));
+ PGraphics pg = map.mapDisplay.getOuterPG();
+ float[] xy1 = map.mapDisplay.getObjectFromLocation(getLocation(0));
PVector v1 = new PVector(xy1[0], xy1[1]);
- float[] xy2 = map.mapDisplay.getScreenPositionFromLocation(getLocation(1));
+ float[] xy2 = map.mapDisplay.getObjectFromLocation(getLocation(1));
PVector v2 = new PVector(xy2[0], xy2[1]);
pg.line(v1.x, v1.y, v2.x, v2.y);
}
@Override
public Location getLocation() {
return getLocation(0);
}
@Override
public void draw(PGraphics pg, float x, float y) {
}
@Override
public void drawOuter(PGraphics pg, float x, float y) {
}
@Override
protected boolean isInside(float checkX, float checkY, float x, float y) {
return false;
}
}
| false | true | public void drawOuter(Map map) {
PGraphics pg = map.mapDisplay.getPG();
float[] xy1 = map.mapDisplay.getScreenPositionFromLocation(getLocation(0));
PVector v1 = new PVector(xy1[0], xy1[1]);
float[] xy2 = map.mapDisplay.getScreenPositionFromLocation(getLocation(1));
PVector v2 = new PVector(xy2[0], xy2[1]);
pg.line(v1.x, v1.y, v2.x, v2.y);
}
| public void drawOuter(Map map) {
PGraphics pg = map.mapDisplay.getOuterPG();
float[] xy1 = map.mapDisplay.getObjectFromLocation(getLocation(0));
PVector v1 = new PVector(xy1[0], xy1[1]);
float[] xy2 = map.mapDisplay.getObjectFromLocation(getLocation(1));
PVector v2 = new PVector(xy2[0], xy2[1]);
pg.line(v1.x, v1.y, v2.x, v2.y);
}
|
diff --git a/programs/21_arrays/array_18_clone.java b/programs/21_arrays/array_18_clone.java
index 185dadb..65375c9 100644
--- a/programs/21_arrays/array_18_clone.java
+++ b/programs/21_arrays/array_18_clone.java
@@ -1,105 +1,105 @@
/*
array.clone
- one dim, array of ints, length = 0, full test
- two dims, array of ints, [zero][zero], full test
- int[3], full test
- int[2][0], full test
- int[2][2], full test
- Object[2] - values are string, RuntimeException, full test
- null.clone(), full test
- int[][] = {{...}, null} , clone, full test
By full test we mean test for ==, and full test on all elements
(possible recursively).
*/
public class array_18_clone {
public static void main(String[] args) {
new main();
System.out.println("Done!");
}
}
class main {
main() {
int[] v1 = new int[0];
- int[] v2 = v1.clone();
+ int[] v2 = (int[]) v1.clone();
cloneTest(v1,v2);
int[][] m1 = new int[0][0];
- int[][] m2 = m1.clone();
+ int[][] m2 = (int[][]) m1.clone();
matrixCloneTest(m1,m2);
v1 = allocateAndInitArray(4,2);
- cloneTest(v1, v1.clone());
+ cloneTest(v1, (int[])v1.clone());
m1 = new int[2][0];
- matrixCloneTest(m1, m1.clone());
+ matrixCloneTest(m1, (int[][])m1.clone());
m1 = new int[2][];
m1[0] = allocateAndInitArray(10,2);
m1[1] = allocateAndInitArray(20,2);
- matrixCloneTest(m1,m1.clone());
+ matrixCloneTest(m1, (int[][])m1.clone());
Object[] vo = new Object[4];
vo[0] = "str";
vo[1] = new RuntimeException("re");
vo[2] = new Object();
vo[3] = null;
- Object[] vo2 = vo.clone();
+ Object[] vo2 = (Object[])vo.clone();
System.out.print("Object[] : "+ (vo == vo2) + " : ");
for(int i=0; i<vo2.length; i++) {
System.out.print((vo[i] == vo2[i]) + " ");
}
System.out.println();
System.out.println("Null tests:");
v1 = null;
try {
- v2 = v1.clone();
+ v2 = (int[])v1.clone();
cloneTest(v1, v2);
} catch (NullPointerException e) {
System.out.println(e);
}
m1[1] = null;
try {
- m2 = m1.clone();
+ m2 = (int[][])m1.clone();
matrixCloneTest(m1, m2);
} catch (NullPointerException e) {
System.out.println(e);
}
}
void cloneTest(int[] v1, int[] v2) {
System.out.print((v1 == v2)+" : ");
if (v1 == null) {
System.out.println(v1 + "+" + v2);
} else {
for(int i=0; i<v1.length; i++) {
System.out.print((v1[i] == v2[i]));
}
System.out.println();
}
}
void matrixCloneTest(int[][] m1, int[][] m2) {
System.out.println("Matrix " + (m1 == m2)+" : ");
if (m1 == null) {
System.out.println(m1 + "+" + m2);
} else {
for(int i=0; i<m1.length; i++) {
cloneTest(m1[i],m2[i]);
}
System.out.println("end matrix.\n");
}
}
int[] allocateAndInitArray(int start, int length) {
int[] v = new int[length];
for(int i=0; i<length; i++) {
v[i] = start + i;
}
return v;
}
}
| false | true | main() {
int[] v1 = new int[0];
int[] v2 = v1.clone();
cloneTest(v1,v2);
int[][] m1 = new int[0][0];
int[][] m2 = m1.clone();
matrixCloneTest(m1,m2);
v1 = allocateAndInitArray(4,2);
cloneTest(v1, v1.clone());
m1 = new int[2][0];
matrixCloneTest(m1, m1.clone());
m1 = new int[2][];
m1[0] = allocateAndInitArray(10,2);
m1[1] = allocateAndInitArray(20,2);
matrixCloneTest(m1,m1.clone());
Object[] vo = new Object[4];
vo[0] = "str";
vo[1] = new RuntimeException("re");
vo[2] = new Object();
vo[3] = null;
Object[] vo2 = vo.clone();
System.out.print("Object[] : "+ (vo == vo2) + " : ");
for(int i=0; i<vo2.length; i++) {
System.out.print((vo[i] == vo2[i]) + " ");
}
System.out.println();
System.out.println("Null tests:");
v1 = null;
try {
v2 = v1.clone();
cloneTest(v1, v2);
} catch (NullPointerException e) {
System.out.println(e);
}
m1[1] = null;
try {
m2 = m1.clone();
matrixCloneTest(m1, m2);
} catch (NullPointerException e) {
System.out.println(e);
}
}
| main() {
int[] v1 = new int[0];
int[] v2 = (int[]) v1.clone();
cloneTest(v1,v2);
int[][] m1 = new int[0][0];
int[][] m2 = (int[][]) m1.clone();
matrixCloneTest(m1,m2);
v1 = allocateAndInitArray(4,2);
cloneTest(v1, (int[])v1.clone());
m1 = new int[2][0];
matrixCloneTest(m1, (int[][])m1.clone());
m1 = new int[2][];
m1[0] = allocateAndInitArray(10,2);
m1[1] = allocateAndInitArray(20,2);
matrixCloneTest(m1, (int[][])m1.clone());
Object[] vo = new Object[4];
vo[0] = "str";
vo[1] = new RuntimeException("re");
vo[2] = new Object();
vo[3] = null;
Object[] vo2 = (Object[])vo.clone();
System.out.print("Object[] : "+ (vo == vo2) + " : ");
for(int i=0; i<vo2.length; i++) {
System.out.print((vo[i] == vo2[i]) + " ");
}
System.out.println();
System.out.println("Null tests:");
v1 = null;
try {
v2 = (int[])v1.clone();
cloneTest(v1, v2);
} catch (NullPointerException e) {
System.out.println(e);
}
m1[1] = null;
try {
m2 = (int[][])m1.clone();
matrixCloneTest(m1, m2);
} catch (NullPointerException e) {
System.out.println(e);
}
}
|
diff --git a/core/src/main/java/com/google/bitcoin/core/Transaction.java b/core/src/main/java/com/google/bitcoin/core/Transaction.java
index 40e7962..bf136a9 100644
--- a/core/src/main/java/com/google/bitcoin/core/Transaction.java
+++ b/core/src/main/java/com/google/bitcoin/core/Transaction.java
@@ -1,1081 +1,1081 @@
/**
* Copyright 2011 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.bitcoin.core;
import com.google.bitcoin.core.TransactionConfidence.ConfidenceType;
import com.google.common.base.Preconditions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.*;
import java.math.BigInteger;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import static com.google.bitcoin.core.Utils.*;
/**
* <p>A transaction represents the movement of coins from some addresses to some other addresses. It can also represent
* the minting of new coins. A Transaction object corresponds to the equivalent in the Bitcoin C++ implementation.</p>
*
* <p>Transactions are the fundamental atoms of Bitcoin and have many powerful features. Read
* <a href="http://code.google.com/p/bitcoinj/wiki/WorkingWithTransactions">"Working with transactions"</a> in the
* documentation to learn more about how to use this class.</p>
*
* <p>All Bitcoin transactions are at risk of being reversed, though the risk is much less than with traditional payment
* systems. Transactions have <i>confidence levels</i>, which help you decide whether to trust a transaction or not.
* Whether to trust a transaction is something that needs to be decided on a case by case basis - a rule that makes
* sense for selling MP3s might not make sense for selling cars, or accepting payments from a family member. If you
* are building a wallet, how to present confidence to your users is something to consider carefully.</p>
*/
public class Transaction extends ChildMessage implements Serializable {
private static final Logger log = LoggerFactory.getLogger(Transaction.class);
private static final long serialVersionUID = -8567546957352643140L;
// Threshold for lockTime: below this value it is interpreted as block number, otherwise as timestamp.
static final int LOCKTIME_THRESHOLD = 500000000; // Tue Nov 5 00:53:20 1985 UTC
// These are serialized in both bitcoin and java serialization.
private long version;
private ArrayList<TransactionInput> inputs;
private ArrayList<TransactionOutput> outputs;
private long lockTime;
// This is either the time the transaction was broadcast as measured from the local clock, or the time from the
// block in which it was included. Note that this can be changed by re-orgs so the wallet may update this field.
// Old serialized transactions don't have this field, thus null is valid. It is used for returning an ordered
// list of transactions from a wallet, which is helpful for presenting to users.
private Date updatedAt;
// This is an in memory helper only.
private transient Sha256Hash hash;
// Data about how confirmed this tx is. Serialized, may be null.
private TransactionConfidence confidence;
// This records which blocks the transaction has been included in. For most transactions this set will have a
// single member. In the case of a chain split a transaction may appear in multiple blocks but only one of them
// is part of the best chain. It's not valid to have an identical transaction appear in two blocks in the same chain
// but this invariant is expensive to check, so it's not directly enforced anywhere.
//
// If this transaction is not stored in the wallet, appearsInHashes is null.
private Set<Sha256Hash> appearsInHashes;
// Transactions can be encoded in a way that will use more bytes than is optimal
// (due to VarInts having multiple encodings)
// MAX_BLOCK_SIZE must be compared to the optimal encoding, not the actual encoding, so when parsing, we keep track
// of the size of the ideal encoding in addition to the actual message size (which Message needs) so that Blocks
// can properly keep track of optimal encoded size
private transient int optimalEncodingMessageSize;
public Transaction(NetworkParameters params) {
super(params);
version = 1;
inputs = new ArrayList<TransactionInput>();
outputs = new ArrayList<TransactionOutput>();
// We don't initialize appearsIn deliberately as it's only useful for transactions stored in the wallet.
length = 8; // 8 for std fields
}
public Transaction(NetworkParameters params, int version, Sha256Hash hash) {
super(params);
this.version = version & ((1L<<32) - 1); // this field is unsigned - remove any sign extension
inputs = new ArrayList<TransactionInput>();
outputs = new ArrayList<TransactionOutput>();
this.hash = hash;
// We don't initialize appearsIn deliberately as it's only useful for transactions stored in the wallet.
length = 8; //8 for std fields
}
/**
* Creates a transaction from the given serialized bytes, eg, from a block or a tx network message.
*/
public Transaction(NetworkParameters params, byte[] payloadBytes) throws ProtocolException {
super(params, payloadBytes, 0);
}
/**
* Creates a transaction by reading payload starting from offset bytes in. Length of a transaction is fixed.
*/
public Transaction(NetworkParameters params, byte[] payload, int offset) throws ProtocolException {
super(params, payload, offset);
// inputs/outputs will be created in parse()
}
/**
* Creates a transaction by reading payload starting from offset bytes in. Length of a transaction is fixed.
* @param params NetworkParameters object.
* @param msg Bitcoin protocol formatted byte array containing message content.
* @param offset The location of the first msg byte within the array.
* @param parseLazy Whether to perform a full parse immediately or delay until a read is requested.
* @param parseRetain Whether to retain the backing byte array for quick reserialization.
* If true and the backing byte array is invalidated due to modification of a field then
* the cached bytes may be repopulated and retained if the message is serialized again in the future.
* @param length The length of message if known. Usually this is provided when deserializing of the wire
* as the length will be provided as part of the header. If unknown then set to Message.UNKNOWN_LENGTH
* @throws ProtocolException
*/
public Transaction(NetworkParameters params, byte[] msg, int offset, Message parent, boolean parseLazy, boolean parseRetain, int length)
throws ProtocolException {
super(params, msg, offset, parent, parseLazy, parseRetain, length);
}
/**
* Creates a transaction by reading payload starting from offset bytes in. Length of a transaction is fixed.
*/
public Transaction(NetworkParameters params, byte[] msg, Message parent, boolean parseLazy, boolean parseRetain, int length)
throws ProtocolException {
super(params, msg, 0, parent, parseLazy, parseRetain, length);
}
/**
* Returns the transaction hash as you see them in the block explorer.
*/
public Sha256Hash getHash() {
if (hash == null) {
byte[] bits = bitcoinSerialize();
hash = new Sha256Hash(reverseBytes(doubleDigest(bits)));
}
return hash;
}
/**
* Used by BitcoinSerializer. The serializer has to calculate a hash for checksumming so to
* avoid wasting the considerable effort a set method is provided so the serializer can set it.
*
* No verification is performed on this hash.
*/
void setHash(Sha256Hash hash) {
this.hash = hash;
}
public String getHashAsString() {
return getHash().toString();
}
/**
* Calculates the sum of the outputs that are sending coins to a key in the wallet. The flag controls whether to
* include spent outputs or not.
*/
BigInteger getValueSentToMe(Wallet wallet, boolean includeSpent) {
maybeParse();
// This is tested in WalletTest.
BigInteger v = BigInteger.ZERO;
for (TransactionOutput o : outputs) {
if (!o.isMine(wallet)) continue;
if (!includeSpent && !o.isAvailableForSpending()) continue;
v = v.add(o.getValue());
}
return v;
}
/*
* If isSpent - check that all my outputs spent, otherwise check that there at least
* one unspent.
*/
boolean isConsistent(Wallet wallet, boolean isSpent) {
boolean isActuallySpent = true;
for (TransactionOutput o : outputs) {
if (o.isAvailableForSpending()) {
if (o.isMine(wallet)) isActuallySpent = false;
if (o.getSpentBy() != null) {
log.error("isAvailableForSpending != spentBy");
return false;
}
} else {
if (o.getSpentBy() == null) {
log.error("isAvailableForSpending != spentBy");
return false;
}
}
}
return isActuallySpent == isSpent;
}
/**
* Calculates the sum of the outputs that are sending coins to a key in the wallet.
*/
public BigInteger getValueSentToMe(Wallet wallet) {
return getValueSentToMe(wallet, true);
}
/**
* Returns a set of blocks which contain the transaction, or null if this transaction doesn't have that data
* because it's not stored in the wallet or because it has never appeared in a block.
*/
public Collection<Sha256Hash> getAppearsInHashes() {
return appearsInHashes;
}
/**
* Convenience wrapper around getConfidence().getConfidenceType()
* @return true if this transaction hasn't been seen in any block yet.
*/
public boolean isPending() {
return getConfidence().getConfidenceType() == TransactionConfidence.ConfidenceType.NOT_SEEN_IN_CHAIN;
}
/**
* <p>Puts the given block in the internal serializable set of blocks in which this transaction appears. This is
* used by the wallet to ensure transactions that appear on side chains are recorded properly even though the
* block stores do not save the transaction data at all.</p>
*
* <p>If there is a re-org this will be called once for each block that was previously seen, to update which block
* is the best chain. The best chain block is guaranteed to be called last. So this must be idempotent.</p>
*
* <p>Sets updatedAt to be the earliest valid block time where this tx was seen.</p>
*
* @param block The {@link StoredBlock} in which the transaction has appeared.
* @param bestChain whether to set the updatedAt timestamp from the block header (only if not already set)
*/
public void setBlockAppearance(StoredBlock block, boolean bestChain) {
long blockTime = block.getHeader().getTimeSeconds() * 1000;
if (bestChain && (updatedAt == null || updatedAt.getTime() == 0 || updatedAt.getTime() > blockTime)) {
updatedAt = new Date(blockTime);
}
addBlockAppearance(block.getHeader().getHash());
if (bestChain) {
// This can cause event listeners on TransactionConfidence to run. After these lines complete, the wallets
// state may have changed!
TransactionConfidence transactionConfidence = getConfidence();
transactionConfidence.setAppearedAtChainHeight(block.getHeight());
// Reset the confidence block depth.
transactionConfidence.setDepthInBlocks(1);
// Reset the work done.
try {
transactionConfidence.setWorkDone(block.getHeader().getWork());
} catch (VerificationException e) {
throw new RuntimeException(e); // Cannot happen.
}
// The transaction is now on the best chain.
transactionConfidence.setConfidenceType(ConfidenceType.BUILDING);
}
}
public void addBlockAppearance(final Sha256Hash blockHash) {
if (appearsInHashes == null) {
appearsInHashes = new HashSet<Sha256Hash>();
}
appearsInHashes.add(blockHash);
}
/** Called by the wallet once a re-org means we don't appear in the best chain anymore. */
void notifyNotOnBestChain() {
TransactionConfidence transactionConfidence = getConfidence();
transactionConfidence.setConfidenceType(TransactionConfidence.ConfidenceType.NOT_IN_BEST_CHAIN);
transactionConfidence.setDepthInBlocks(0);
transactionConfidence.setWorkDone(BigInteger.ZERO);
}
/**
* Calculates the sum of the inputs that are spending coins with keys in the wallet. This requires the
* transactions sending coins to those keys to be in the wallet. This method will not attempt to download the
* blocks containing the input transactions if the key is in the wallet but the transactions are not.
*
* @return sum in nanocoins.
*/
public BigInteger getValueSentFromMe(Wallet wallet) throws ScriptException {
maybeParse();
// This is tested in WalletTest.
BigInteger v = BigInteger.ZERO;
for (TransactionInput input : inputs) {
// This input is taking value from a transaction in our wallet. To discover the value,
// we must find the connected transaction.
TransactionOutput connected = input.getConnectedOutput(wallet.unspent);
if (connected == null)
connected = input.getConnectedOutput(wallet.spent);
if (connected == null)
connected = input.getConnectedOutput(wallet.pending);
if (connected == null)
continue;
// The connected output may be the change to the sender of a previous input sent to this wallet. In this
// case we ignore it.
if (!connected.isMine(wallet))
continue;
v = v.add(connected.getValue());
}
return v;
}
/**
* Returns the difference of {@link Transaction#getValueSentFromMe(Wallet)} and {@link Transaction#getValueSentToMe(Wallet)}.
*/
public BigInteger getValue(Wallet wallet) throws ScriptException {
return getValueSentToMe(wallet).subtract(getValueSentFromMe(wallet));
}
boolean disconnectInputs() {
boolean disconnected = false;
maybeParse();
for (TransactionInput input : inputs) {
disconnected |= input.disconnect();
}
return disconnected;
}
/**
* Connects all inputs using the provided transactions. If any input cannot be connected returns that input or
* null on success.
*/
TransactionInput connectForReorganize(Map<Sha256Hash, Transaction> transactions) {
maybeParse();
for (TransactionInput input : inputs) {
// Coinbase transactions, by definition, do not have connectable inputs.
if (input.isCoinBase()) continue;
TransactionInput.ConnectionResult result =
input.connect(transactions, TransactionInput.ConnectMode.ABORT_ON_CONFLICT);
// Connected to another tx in the wallet?
if (result == TransactionInput.ConnectionResult.SUCCESS)
continue;
// The input doesn't exist in the wallet, eg because it belongs to somebody else (inbound spend).
if (result == TransactionInput.ConnectionResult.NO_SUCH_TX)
continue;
// Could not connect this input, so return it and abort.
return input;
}
return null;
}
/**
* Returns true if every output is marked as spent.
*/
public boolean isEveryOutputSpent() {
maybeParse();
for (TransactionOutput output : outputs) {
if (output.isAvailableForSpending())
return false;
}
return true;
}
/**
* Returns true if every output owned by the given wallet is spent.
*/
public boolean isEveryOwnedOutputSpent(Wallet wallet) {
maybeParse();
for (TransactionOutput output : outputs) {
if (output.isAvailableForSpending() && output.isMine(wallet))
return false;
}
return true;
}
/**
* Returns the earliest time at which the transaction was seen (broadcast or included into the chain),
* or the epoch if that information isn't available.
*/
public Date getUpdateTime() {
if (updatedAt == null) {
// Older wallets did not store this field. Set to the epoch.
updatedAt = new Date(0);
}
return updatedAt;
}
public void setUpdateTime(Date updatedAt) {
this.updatedAt = updatedAt;
}
/**
* These constants are a part of a scriptSig signature on the inputs. They define the details of how a
* transaction can be redeemed, specifically, they control how the hash of the transaction is calculated.
* <p/>
* In the official client, this enum also has another flag, SIGHASH_ANYONECANPAY. In this implementation,
* that's kept separate. Only SIGHASH_ALL is actually used in the official client today. The other flags
* exist to allow for distributed contracts.
*/
public enum SigHash {
ALL, // 1
NONE, // 2
SINGLE, // 3
}
protected void unCache() {
super.unCache();
hash = null;
}
protected void parseLite() throws ProtocolException {
//skip this if the length has been provided i.e. the tx is not part of a block
if (parseLazy && length == UNKNOWN_LENGTH) {
//If length hasn't been provided this tx is probably contained within a block.
//In parseRetain mode the block needs to know how long the transaction is
//unfortunately this requires a fairly deep (though not total) parse.
//This is due to the fact that transactions in the block's list do not include a
//size header and inputs/outputs are also variable length due the contained
//script so each must be instantiated so the scriptlength varint can be read
//to calculate total length of the transaction.
//We will still persist will this semi-light parsing because getting the lengths
//of the various components gains us the ability to cache the backing bytearrays
//so that only those subcomponents that have changed will need to be reserialized.
//parse();
//parsed = true;
length = calcLength(bytes, cursor, offset);
cursor = offset + length;
}
}
protected static int calcLength(byte[] buf, int cursor, int offset) {
VarInt varint;
// jump past version (uint32)
cursor = offset + 4;
int i;
long scriptLen;
varint = new VarInt(buf, cursor);
long txInCount = varint.value;
cursor += varint.getOriginalSizeInBytes();
for (i = 0; i < txInCount; i++) {
// 36 = length of previous_outpoint
cursor += 36;
varint = new VarInt(buf, cursor);
scriptLen = varint.value;
// 4 = length of sequence field (unint32)
cursor += scriptLen + 4 + varint.getOriginalSizeInBytes();
}
varint = new VarInt(buf, cursor);
long txOutCount = varint.value;
cursor += varint.getOriginalSizeInBytes();
for (i = 0; i < txOutCount; i++) {
// 8 = length of tx value field (uint64)
cursor += 8;
varint = new VarInt(buf, cursor);
scriptLen = varint.value;
cursor += scriptLen + varint.getOriginalSizeInBytes();
}
// 4 = length of lock_time field (uint32)
return cursor - offset + 4;
}
void parse() throws ProtocolException {
if (parsed)
return;
cursor = offset;
version = readUint32();
optimalEncodingMessageSize = 4;
// First come the inputs.
long numInputs = readVarInt();
optimalEncodingMessageSize += VarInt.sizeOf(numInputs);
inputs = new ArrayList<TransactionInput>((int) numInputs);
for (long i = 0; i < numInputs; i++) {
TransactionInput input = new TransactionInput(params, this, bytes, cursor, parseLazy, parseRetain);
inputs.add(input);
long scriptLen = readVarInt(TransactionOutPoint.MESSAGE_LENGTH);
optimalEncodingMessageSize += TransactionOutPoint.MESSAGE_LENGTH + VarInt.sizeOf(scriptLen) + scriptLen + 4;
cursor += scriptLen + 4;
}
// Now the outputs
long numOutputs = readVarInt();
optimalEncodingMessageSize += VarInt.sizeOf(numOutputs);
outputs = new ArrayList<TransactionOutput>((int) numOutputs);
for (long i = 0; i < numOutputs; i++) {
TransactionOutput output = new TransactionOutput(params, this, bytes, cursor, parseLazy, parseRetain);
outputs.add(output);
long scriptLen = readVarInt(8);
optimalEncodingMessageSize += 8 + VarInt.sizeOf(scriptLen) + scriptLen;
cursor += scriptLen;
}
lockTime = readUint32();
optimalEncodingMessageSize += 4;
length = cursor - offset;
}
public int getOptimalEncodingMessageSize() {
if (optimalEncodingMessageSize != 0)
return optimalEncodingMessageSize;
maybeParse();
if (optimalEncodingMessageSize != 0)
return optimalEncodingMessageSize;
optimalEncodingMessageSize = getMessageSize();
return optimalEncodingMessageSize;
}
/**
* A coinbase transaction is one that creates a new coin. They are the first transaction in each block and their
* value is determined by a formula that all implementations of BitCoin share. In 2011 the value of a coinbase
* transaction is 50 coins, but in future it will be less. A coinbase transaction is defined not only by its
* position in a block but by the data in the inputs.
*/
public boolean isCoinBase() {
maybeParse();
return inputs.size() == 1 && inputs.get(0).isCoinBase();
}
/**
* A transaction is mature if it is either a building coinbase tx that is as deep or deeper than the required coinbase depth, or a non-coinbase tx.
*/
public boolean isMature() {
if (!isCoinBase())
return true;
if (getConfidence().getConfidenceType() != ConfidenceType.BUILDING)
return false;
return getConfidence().getDepthInBlocks() >= params.getSpendableCoinbaseDepth();
}
public String toString() {
return toString(null);
}
/**
* A human readable version of the transaction useful for debugging. The format is not guaranteed to be stable.
* @param chain If provided, will be used to estimate lock times (if set). Can be null.
*/
public String toString(AbstractBlockChain chain) {
// Basic info about the tx.
StringBuffer s = new StringBuffer();
s.append(String.format(" %s: %s%n", getHashAsString(), getConfidence()));
if (lockTime > 0) {
String time;
if (lockTime < LOCKTIME_THRESHOLD) {
time = "block " + lockTime;
if (chain != null) {
time = time + " (estimated to be reached at " +
chain.estimateBlockTime((int)lockTime).toString() + ")";
}
} else {
time = new Date(lockTime).toString();
}
s.append(String.format(" time locked until %s%n", time));
}
if (inputs.size() == 0) {
s.append(String.format(" INCOMPLETE: No inputs!%n"));
return s.toString();
}
if (isCoinBase()) {
String script;
String script2;
try {
script = inputs.get(0).getScriptSig().toString();
script2 = outputs.get(0).getScriptPubKey().toString();
} catch (ScriptException e) {
script = "???";
script2 = "???";
}
return " == COINBASE TXN (scriptSig " + script + ") (scriptPubKey " + script2 + ")\n";
}
for (TransactionInput in : inputs) {
s.append(" ");
s.append("from ");
try {
Script scriptSig = in.getScriptSig();
if (scriptSig.chunks.size() == 2)
s.append(scriptSig.getFromAddress().toString());
else if (scriptSig.chunks.size() == 1)
s.append("[sig:" + bytesToHexString(scriptSig.getPubKey()) + "]");
else
s.append("???");
s.append(" / ");
s.append(in.getOutpoint().toString());
} catch (Exception e) {
s.append("[exception: ").append(e.getMessage()).append("]");
}
s.append(String.format("%n"));
}
for (TransactionOutput out : outputs) {
s.append(" ");
s.append("to ");
try {
Script scriptPubKey = out.getScriptPubKey();
if (scriptPubKey.isSentToAddress()) {
s.append(scriptPubKey.getToAddress().toString());
} else if (scriptPubKey.isSentToRawPubKey()) {
s.append("[pubkey:");
s.append(bytesToHexString(scriptPubKey.getPubKey()));
s.append("]");
}
s.append(" ");
s.append(bitcoinValueToFriendlyString(out.getValue()));
s.append(" BTC");
if (!out.isAvailableForSpending()) {
s.append(" Spent");
}
if (out.getSpentBy() != null) {
s.append(" by ");
s.append(out.getSpentBy().getParentTransaction().getHashAsString());
}
} catch (Exception e) {
s.append("[exception: ").append(e.getMessage()).append("]");
}
s.append(String.format("%n"));
}
return s.toString();
}
/**
* Adds an input to this transaction that imports value from the given output. Note that this input is NOT
* complete and after every input is added with addInput() and every output is added with addOutput(),
* signInputs() must be called to finalize the transaction and finish the inputs off. Otherwise it won't be
* accepted by the network.
*/
public void addInput(TransactionOutput from) {
addInput(new TransactionInput(params, this, from));
}
/**
* Adds an input directly, with no checking that it's valid.
*/
public void addInput(TransactionInput input) {
unCache();
input.setParent(this);
inputs.add(input);
adjustLength(inputs.size(), input.length);
}
/**
* Adds the given output to this transaction. The output must be completely initialized.
*/
public void addOutput(TransactionOutput to) {
unCache();
to.setParent(this);
outputs.add(to);
adjustLength(outputs.size(), to.length);
}
/**
* Creates an output based on the given address and value, adds it to this transaction.
*/
public void addOutput(BigInteger value, Address address) {
addOutput(new TransactionOutput(params, this, value, address));
}
/**
* Creates an output that pays to the given pubkey directly (no address) with the given value, and adds it to this
* transaction.
*/
public void addOutput(BigInteger value, ECKey pubkey) {
addOutput(new TransactionOutput(params, this, value, pubkey));
}
/**
* Once a transaction has some inputs and outputs added, the signatures in the inputs can be calculated. The
* signature is over the transaction itself, to prove the redeemer actually created that transaction,
* so we have to do this step last.<p>
* <p/>
* This method is similar to SignatureHash in script.cpp
*
* @param hashType This should always be set to SigHash.ALL currently. Other types are unused.
* @param wallet A wallet is required to fetch the keys needed for signing.
*/
public synchronized void signInputs(SigHash hashType, Wallet wallet) throws ScriptException {
Preconditions.checkState(inputs.size() > 0);
Preconditions.checkState(outputs.size() > 0);
// I don't currently have an easy way to test other modes work, as the official client does not use them.
Preconditions.checkArgument(hashType == SigHash.ALL, "Only SIGHASH_ALL is currently supported");
// The transaction is signed with the input scripts empty except for the input we are signing. In the case
// where addInput has been used to set up a new transaction, they are already all empty. The input being signed
// has to have the connected OUTPUT program in it when the hash is calculated!
//
// Note that each input may be claiming an output sent to a different key. So we have to look at the outputs
// to figure out which key to sign with.
byte[][] signatures = new byte[inputs.size()][];
ECKey[] signingKeys = new ECKey[inputs.size()];
for (int i = 0; i < inputs.size(); i++) {
TransactionInput input = inputs.get(i);
if (input.getScriptBytes().length != 0)
log.warn("Re-signing an already signed transaction! Be sure this is what you want.");
// Find the signing key we'll need to use.
ECKey key = input.getOutpoint().getConnectedKey(wallet);
// This assert should never fire. If it does, it means the wallet is inconsistent.
Preconditions.checkNotNull(key, "Transaction exists in wallet that we cannot redeem: %s",
input.getOutpoint().getHash());
// Keep the key around for the script creation step below.
signingKeys[i] = key;
// The anyoneCanPay feature isn't used at the moment.
boolean anyoneCanPay = false;
byte[] connectedPubKeyScript = input.getOutpoint().getConnectedPubKeyScript();
Sha256Hash hash = hashTransactionForSignature(i, connectedPubKeyScript, hashType, anyoneCanPay);
// Now sign for the output so we can redeem it. We use the keypair to sign the hash,
// and then put the resulting signature in the script along with the public key (below).
try {
// Usually 71-73 bytes.
ByteArrayOutputStream bos = new UnsafeByteArrayOutputStream(73);
bos.write(key.sign(hash).encodeToDER());
bos.write((hashType.ordinal() + 1) | (anyoneCanPay ? 0x80 : 0));
signatures[i] = bos.toByteArray();
bos.close();
} catch (IOException e) {
throw new RuntimeException(e); // Cannot happen.
}
}
// Now we have calculated each signature, go through and create the scripts. Reminder: the script consists:
// 1) For pay-to-address outputs: a signature (over a hash of the simplified transaction) and the complete
// public key needed to sign for the connected output. The output script checks the provided pubkey hashes
// to the address and then checks the signature.
// 2) For pay-to-key outputs: just a signature.
for (int i = 0; i < inputs.size(); i++) {
TransactionInput input = inputs.get(i);
ECKey key = signingKeys[i];
Script scriptPubKey = input.getOutpoint().getConnectedOutput().getScriptPubKey();
if (scriptPubKey.isSentToAddress()) {
input.setScriptBytes(Script.createInputScript(signatures[i], key.getPubKey()));
} else if (scriptPubKey.isSentToRawPubKey()) {
input.setScriptBytes(Script.createInputScript(signatures[i]));
} else {
// Should be unreachable - if we don't recognize the type of script we're trying to sign for, we should
// have failed above when fetching the key to sign with.
throw new RuntimeException("Do not understand script type: " + scriptPubKey);
}
}
// Every input is now complete.
}
/**
* Calculates a signature hash, that is, a hash of a simplified form of the transaction. How exactly the transaction
* is simplified is specified by the type and anyoneCanPay parameters.<p>
*
* You don't normally ever need to call this yourself. It will become more useful in future as the contracts
* features of Bitcoin are developed.
*
* @param inputIndex input the signature is being calculated for. Tx signatures are always relative to an input.
* @param connectedScript the bytes that should be in the given input during signing.
* @param type Should be SigHash.ALL
* @param anyoneCanPay should be false.
* @throws ScriptException if connectedScript is invalid
*/
public synchronized Sha256Hash hashTransactionForSignature(int inputIndex, byte[] connectedScript,
SigHash type, boolean anyoneCanPay) throws ScriptException {
return hashTransactionForSignature(inputIndex, connectedScript, (byte)((type.ordinal() + 1) | (anyoneCanPay ? 0x80 : 0x00)));
}
/**
* This is required for signatures which use a sigHashType which cannot be represented using SigHash and anyoneCanPay
* See transaction c99c49da4c38af669dea436d3e73780dfdb6c1ecf9958baa52960e8baee30e73, which has sigHashType 0
*/
synchronized Sha256Hash hashTransactionForSignature(int inputIndex, byte[] connectedScript,
byte sigHashType) throws ScriptException {
// TODO: This whole separate method should be un-necessary if we fix how we deserialize sighash flags.
// The SIGHASH flags are used in the design of contracts, please see this page for a further understanding of
// the purposes of the code in this method:
//
// https://en.bitcoin.it/wiki/Contracts
try {
// Store all the input scripts and clear them in preparation for signing. If we're signing a fresh
// transaction that step isn't very helpful, but it doesn't add much cost relative to the actual
// EC math so we'll do it anyway.
//
// Also store the input sequence numbers in case we are clearing them with SigHash.NONE/SINGLE
byte[][] inputScripts = new byte[inputs.size()][];
long[] inputSequenceNumbers = new long[inputs.size()];
for (int i = 0; i < inputs.size(); i++) {
inputScripts[i] = inputs.get(i).getScriptBytes();
inputSequenceNumbers[i] = inputs.get(i).getSequenceNumber();
inputs.get(i).setScriptBytes(TransactionInput.EMPTY_ARRAY);
}
// This step has no purpose beyond being synchronized with the reference clients bugs. OP_CODESEPARATOR
// is a legacy holdover from a previous, broken design of executing scripts that shipped in Bitcoin 0.1.
// It was seriously flawed and would have let anyone take anyone elses money. Later versions switched to
// the design we use today where scripts are executed independently but share a stack. This left the
// OP_CODESEPARATOR instruction having no purpose as it was only meant to be used internally, not actually
// ever put into scripts. Deleting OP_CODESEPARATOR is a step that should never be required but if we don't
// do it, we could split off the main chain.
connectedScript = Script.removeAllInstancesOfOp(connectedScript, Script.OP_CODESEPARATOR);
// Set the input to the script of its output. Satoshi does this but the step has no obvious purpose as
// the signature covers the hash of the prevout transaction which obviously includes the output script
// already. Perhaps it felt safer to him in some way, or is another leftover from how the code was written.
TransactionInput input = inputs.get(inputIndex);
input.setScriptBytes(connectedScript);
ArrayList<TransactionOutput> outputs = this.outputs;
if ((sigHashType & 0x1f) == (SigHash.NONE.ordinal() + 1)) {
// SIGHASH_NONE means no outputs are signed at all - the signature is effectively for a "blank cheque".
this.outputs = new ArrayList<TransactionOutput>(0);
// The signature isn't broken by new versions of the transaction issued by other parties.
for (int i = 0; i < inputs.size(); i++)
if (i != inputIndex)
inputs.get(i).setSequenceNumber(0);
} else if ((sigHashType & 0x1f) == (SigHash.SINGLE.ordinal() + 1)) {
// SIGHASH_SINGLE means only sign the output at the same index as the input (ie, my output).
if (inputIndex >= this.outputs.size()) {
// The input index is beyond the number of outputs, it's a buggy signature made by a broken
// Bitcoin implementation. The reference client also contains a bug in handling this case:
// any transaction output that is signed in this case will result in both the signed output
// and any future outputs to this public key being steal-able by anyone who has
// the resulting signature and the public key (both of which are part of the signed tx input).
// Put the transaction back to how we found it.
//
// TODO: Only allow this to happen if we are checking a signature, not signing a transactions
for (int i = 0; i < inputs.size(); i++) {
inputs.get(i).setScriptBytes(inputScripts[i]);
inputs.get(i).setSequenceNumber(inputSequenceNumbers[i]);
}
this.outputs = outputs;
// Satoshis bug is that SignatureHash was supposed to return a hash and on this codepath it
// actually returns the constant "1" to indicate an error, which is never checked for. Oops.
return new Sha256Hash("0100000000000000000000000000000000000000000000000000000000000000");
}
// In SIGHASH_SINGLE the outputs after the matching input index are deleted, and the outputs before
// that position are "nulled out". Unintuitively, the value in a "null" transaction is set to -1.
this.outputs = new ArrayList<TransactionOutput>(this.outputs.subList(0, inputIndex));
for (int i = 0; i < inputIndex; i++)
this.outputs.set(i, new TransactionOutput(params, this, BigInteger.valueOf(-1), new byte[] {}));
// The signature isn't broken by new versions of the transaction issued by other parties.
for (int i = 0; i < inputs.size(); i++)
if (i != inputIndex)
inputs.get(i).setSequenceNumber(0);
}
ArrayList<TransactionInput> inputs = this.inputs;
if ((sigHashType & 0x80) == 0x80) {
// SIGHASH_ANYONECANPAY means the signature in the input is not broken by changes/additions/removals
// of other inputs. For example, this is useful for building assurance contracts.
this.inputs = new ArrayList<TransactionInput>();
this.inputs.add(input);
}
ByteArrayOutputStream bos = new UnsafeByteArrayOutputStream(length == UNKNOWN_LENGTH ? 256 : length + 4);
bitcoinSerialize(bos);
- // We also have to write a hash type.
- uint32ToByteStreamLE(sigHashType, bos);
+ // We also have to write a hash type (sigHashType is actually an unsigned char)
+ uint32ToByteStreamLE(0x000000ff & sigHashType, bos);
// Note that this is NOT reversed to ensure it will be signed correctly. If it were to be printed out
// however then we would expect that it is IS reversed.
Sha256Hash hash = new Sha256Hash(doubleDigest(bos.toByteArray()));
bos.close();
// Put the transaction back to how we found it.
this.inputs = inputs;
for (int i = 0; i < inputs.size(); i++) {
inputs.get(i).setScriptBytes(inputScripts[i]);
inputs.get(i).setSequenceNumber(inputSequenceNumbers[i]);
}
this.outputs = outputs;
return hash;
} catch (IOException e) {
throw new RuntimeException(e); // Cannot happen.
}
}
@Override
protected void bitcoinSerializeToStream(OutputStream stream) throws IOException {
uint32ToByteStreamLE(version, stream);
stream.write(new VarInt(inputs.size()).encode());
for (TransactionInput in : inputs)
in.bitcoinSerialize(stream);
stream.write(new VarInt(outputs.size()).encode());
for (TransactionOutput out : outputs)
out.bitcoinSerialize(stream);
uint32ToByteStreamLE(lockTime, stream);
}
/**
* @return the lockTime
*/
public long getLockTime() {
maybeParse();
return lockTime;
}
/**
* @param lockTime the lockTime to set
*/
public void setLockTime(long lockTime) {
unCache();
this.lockTime = lockTime;
}
/**
* @return the version
*/
public long getVersion() {
maybeParse();
return version;
}
/**
* @return a read-only list of the inputs of this transaction.
*/
public List<TransactionInput> getInputs() {
maybeParse();
return Collections.unmodifiableList(inputs);
}
/**
* @return a read-only list of the outputs of this transaction.
*/
public List<TransactionOutput> getOutputs() {
maybeParse();
return Collections.unmodifiableList(outputs);
}
/** @return the given transaction: same as getInputs().get(index). */
public TransactionInput getInput(int index) {
maybeParse();
return inputs.get(index);
}
public TransactionOutput getOutput(int index) {
maybeParse();
return outputs.get(index);
}
public synchronized TransactionConfidence getConfidence() {
if (confidence == null) {
confidence = new TransactionConfidence(this);
}
return confidence;
}
/** Check if the transaction has a known confidence */
public synchronized boolean hasConfidence() {
return confidence != null && confidence.getConfidenceType() != TransactionConfidence.ConfidenceType.UNKNOWN;
}
@Override
public boolean equals(Object other) {
if (!(other instanceof Transaction)) return false;
Transaction t = (Transaction) other;
return t.getHash().equals(getHash());
}
@Override
public int hashCode() {
return getHash().hashCode();
}
/**
* Ensure object is fully parsed before invoking java serialization. The backing byte array
* is transient so if the object has parseLazy = true and hasn't invoked checkParse yet
* then data will be lost during serialization.
*/
private void writeObject(ObjectOutputStream out) throws IOException {
maybeParse();
out.defaultWriteObject();
}
/**
* Gets the count of regular SigOps in this transactions
*/
public int getSigOpCount() throws ScriptException {
maybeParse();
int sigOps = 0;
for (TransactionInput input : inputs)
sigOps += Script.getSigOpCount(input.getScriptBytes());
for (TransactionOutput output : outputs)
sigOps += Script.getSigOpCount(output.getScriptBytes());
return sigOps;
}
/**
* Checks the transaction contents for sanity, in ways that can be done in a standalone manner.
* Does <b>not</b> perform all checks on a transaction such as whether the inputs are already spent.
*
* @throws VerificationException
*/
public void verify() throws VerificationException {
maybeParse();
if (inputs.size() == 0 || outputs.size() == 0)
throw new VerificationException("Transaction had no inputs or no outputs.");
if (this.getMessageSize() > Block.MAX_BLOCK_SIZE)
throw new VerificationException("Transaction larger than MAX_BLOCK_SIZE");
BigInteger valueOut = BigInteger.ZERO;
for (TransactionOutput output : outputs) {
if (output.getValue().compareTo(BigInteger.ZERO) < 0)
throw new VerificationException("Transaction output negative");
valueOut = valueOut.add(output.getValue());
}
if (valueOut.compareTo(params.MAX_MONEY) > 0)
throw new VerificationException("Total transaction output value greater than possible");
if (isCoinBase()) {
if (inputs.get(0).getScriptBytes().length < 2 || inputs.get(0).getScriptBytes().length > 100)
throw new VerificationException("Coinbase script size out of range");
} else {
for (TransactionInput input : inputs)
if (input.isCoinBase())
throw new VerificationException("Coinbase input as input in non-coinbase transaction");
}
}
/**
* <p>Returns true if this transaction is considered finalized and can be placed in a block. Non-finalized
* transactions won't be included by miners and can be replaced with newer versions using sequence numbers.
* This is useful in certain types of <a href="http://en.bitcoin.it/wiki/Contracts">contracts</a>, such as
* micropayment channels.</p>
*
* <p>Note that currently the replacement feature is disabled in the Satoshi client and will need to be
* re-activated before this functionality is useful.</p>
*/
public boolean isFinal(int height, long blockTimeSeconds) {
// Time based nLockTime implemented in 0.1.6
long time = getLockTime();
if (time == 0)
return true;
if (time < (time < LOCKTIME_THRESHOLD ? height : blockTimeSeconds))
return true;
for (TransactionInput in : inputs)
if (in.hasSequence())
return false;
return true;
}
/**
* Parses the string either as a whole number of blocks, or if it contains slashes as a YYYY/MM/DD format date
* and returns the lock time in wire format.
*/
public static long parseLockTimeStr(String lockTimeStr) throws ParseException {
if (lockTimeStr.indexOf("/") != -1) {
SimpleDateFormat format = new SimpleDateFormat("yyyy/MM/dd");
Date date = format.parse(lockTimeStr);
return date.getTime() / 1000;
}
return Long.parseLong(lockTimeStr);
}
/**
* Returns either the lock time as a date, if it was specified in seconds, or an estimate based on the time in
* the current head block if it was specified as a block time.
*/
public Date estimateLockTime(AbstractBlockChain chain) {
if (lockTime < LOCKTIME_THRESHOLD)
return chain.estimateBlockTime((int)getLockTime());
else
return new Date(getLockTime()*1000);
}
}
| true | true | synchronized Sha256Hash hashTransactionForSignature(int inputIndex, byte[] connectedScript,
byte sigHashType) throws ScriptException {
// TODO: This whole separate method should be un-necessary if we fix how we deserialize sighash flags.
// The SIGHASH flags are used in the design of contracts, please see this page for a further understanding of
// the purposes of the code in this method:
//
// https://en.bitcoin.it/wiki/Contracts
try {
// Store all the input scripts and clear them in preparation for signing. If we're signing a fresh
// transaction that step isn't very helpful, but it doesn't add much cost relative to the actual
// EC math so we'll do it anyway.
//
// Also store the input sequence numbers in case we are clearing them with SigHash.NONE/SINGLE
byte[][] inputScripts = new byte[inputs.size()][];
long[] inputSequenceNumbers = new long[inputs.size()];
for (int i = 0; i < inputs.size(); i++) {
inputScripts[i] = inputs.get(i).getScriptBytes();
inputSequenceNumbers[i] = inputs.get(i).getSequenceNumber();
inputs.get(i).setScriptBytes(TransactionInput.EMPTY_ARRAY);
}
// This step has no purpose beyond being synchronized with the reference clients bugs. OP_CODESEPARATOR
// is a legacy holdover from a previous, broken design of executing scripts that shipped in Bitcoin 0.1.
// It was seriously flawed and would have let anyone take anyone elses money. Later versions switched to
// the design we use today where scripts are executed independently but share a stack. This left the
// OP_CODESEPARATOR instruction having no purpose as it was only meant to be used internally, not actually
// ever put into scripts. Deleting OP_CODESEPARATOR is a step that should never be required but if we don't
// do it, we could split off the main chain.
connectedScript = Script.removeAllInstancesOfOp(connectedScript, Script.OP_CODESEPARATOR);
// Set the input to the script of its output. Satoshi does this but the step has no obvious purpose as
// the signature covers the hash of the prevout transaction which obviously includes the output script
// already. Perhaps it felt safer to him in some way, or is another leftover from how the code was written.
TransactionInput input = inputs.get(inputIndex);
input.setScriptBytes(connectedScript);
ArrayList<TransactionOutput> outputs = this.outputs;
if ((sigHashType & 0x1f) == (SigHash.NONE.ordinal() + 1)) {
// SIGHASH_NONE means no outputs are signed at all - the signature is effectively for a "blank cheque".
this.outputs = new ArrayList<TransactionOutput>(0);
// The signature isn't broken by new versions of the transaction issued by other parties.
for (int i = 0; i < inputs.size(); i++)
if (i != inputIndex)
inputs.get(i).setSequenceNumber(0);
} else if ((sigHashType & 0x1f) == (SigHash.SINGLE.ordinal() + 1)) {
// SIGHASH_SINGLE means only sign the output at the same index as the input (ie, my output).
if (inputIndex >= this.outputs.size()) {
// The input index is beyond the number of outputs, it's a buggy signature made by a broken
// Bitcoin implementation. The reference client also contains a bug in handling this case:
// any transaction output that is signed in this case will result in both the signed output
// and any future outputs to this public key being steal-able by anyone who has
// the resulting signature and the public key (both of which are part of the signed tx input).
// Put the transaction back to how we found it.
//
// TODO: Only allow this to happen if we are checking a signature, not signing a transactions
for (int i = 0; i < inputs.size(); i++) {
inputs.get(i).setScriptBytes(inputScripts[i]);
inputs.get(i).setSequenceNumber(inputSequenceNumbers[i]);
}
this.outputs = outputs;
// Satoshis bug is that SignatureHash was supposed to return a hash and on this codepath it
// actually returns the constant "1" to indicate an error, which is never checked for. Oops.
return new Sha256Hash("0100000000000000000000000000000000000000000000000000000000000000");
}
// In SIGHASH_SINGLE the outputs after the matching input index are deleted, and the outputs before
// that position are "nulled out". Unintuitively, the value in a "null" transaction is set to -1.
this.outputs = new ArrayList<TransactionOutput>(this.outputs.subList(0, inputIndex));
for (int i = 0; i < inputIndex; i++)
this.outputs.set(i, new TransactionOutput(params, this, BigInteger.valueOf(-1), new byte[] {}));
// The signature isn't broken by new versions of the transaction issued by other parties.
for (int i = 0; i < inputs.size(); i++)
if (i != inputIndex)
inputs.get(i).setSequenceNumber(0);
}
ArrayList<TransactionInput> inputs = this.inputs;
if ((sigHashType & 0x80) == 0x80) {
// SIGHASH_ANYONECANPAY means the signature in the input is not broken by changes/additions/removals
// of other inputs. For example, this is useful for building assurance contracts.
this.inputs = new ArrayList<TransactionInput>();
this.inputs.add(input);
}
ByteArrayOutputStream bos = new UnsafeByteArrayOutputStream(length == UNKNOWN_LENGTH ? 256 : length + 4);
bitcoinSerialize(bos);
// We also have to write a hash type.
uint32ToByteStreamLE(sigHashType, bos);
// Note that this is NOT reversed to ensure it will be signed correctly. If it were to be printed out
// however then we would expect that it is IS reversed.
Sha256Hash hash = new Sha256Hash(doubleDigest(bos.toByteArray()));
bos.close();
// Put the transaction back to how we found it.
this.inputs = inputs;
for (int i = 0; i < inputs.size(); i++) {
inputs.get(i).setScriptBytes(inputScripts[i]);
inputs.get(i).setSequenceNumber(inputSequenceNumbers[i]);
}
this.outputs = outputs;
return hash;
} catch (IOException e) {
throw new RuntimeException(e); // Cannot happen.
}
}
| synchronized Sha256Hash hashTransactionForSignature(int inputIndex, byte[] connectedScript,
byte sigHashType) throws ScriptException {
// TODO: This whole separate method should be un-necessary if we fix how we deserialize sighash flags.
// The SIGHASH flags are used in the design of contracts, please see this page for a further understanding of
// the purposes of the code in this method:
//
// https://en.bitcoin.it/wiki/Contracts
try {
// Store all the input scripts and clear them in preparation for signing. If we're signing a fresh
// transaction that step isn't very helpful, but it doesn't add much cost relative to the actual
// EC math so we'll do it anyway.
//
// Also store the input sequence numbers in case we are clearing them with SigHash.NONE/SINGLE
byte[][] inputScripts = new byte[inputs.size()][];
long[] inputSequenceNumbers = new long[inputs.size()];
for (int i = 0; i < inputs.size(); i++) {
inputScripts[i] = inputs.get(i).getScriptBytes();
inputSequenceNumbers[i] = inputs.get(i).getSequenceNumber();
inputs.get(i).setScriptBytes(TransactionInput.EMPTY_ARRAY);
}
// This step has no purpose beyond being synchronized with the reference clients bugs. OP_CODESEPARATOR
// is a legacy holdover from a previous, broken design of executing scripts that shipped in Bitcoin 0.1.
// It was seriously flawed and would have let anyone take anyone elses money. Later versions switched to
// the design we use today where scripts are executed independently but share a stack. This left the
// OP_CODESEPARATOR instruction having no purpose as it was only meant to be used internally, not actually
// ever put into scripts. Deleting OP_CODESEPARATOR is a step that should never be required but if we don't
// do it, we could split off the main chain.
connectedScript = Script.removeAllInstancesOfOp(connectedScript, Script.OP_CODESEPARATOR);
// Set the input to the script of its output. Satoshi does this but the step has no obvious purpose as
// the signature covers the hash of the prevout transaction which obviously includes the output script
// already. Perhaps it felt safer to him in some way, or is another leftover from how the code was written.
TransactionInput input = inputs.get(inputIndex);
input.setScriptBytes(connectedScript);
ArrayList<TransactionOutput> outputs = this.outputs;
if ((sigHashType & 0x1f) == (SigHash.NONE.ordinal() + 1)) {
// SIGHASH_NONE means no outputs are signed at all - the signature is effectively for a "blank cheque".
this.outputs = new ArrayList<TransactionOutput>(0);
// The signature isn't broken by new versions of the transaction issued by other parties.
for (int i = 0; i < inputs.size(); i++)
if (i != inputIndex)
inputs.get(i).setSequenceNumber(0);
} else if ((sigHashType & 0x1f) == (SigHash.SINGLE.ordinal() + 1)) {
// SIGHASH_SINGLE means only sign the output at the same index as the input (ie, my output).
if (inputIndex >= this.outputs.size()) {
// The input index is beyond the number of outputs, it's a buggy signature made by a broken
// Bitcoin implementation. The reference client also contains a bug in handling this case:
// any transaction output that is signed in this case will result in both the signed output
// and any future outputs to this public key being steal-able by anyone who has
// the resulting signature and the public key (both of which are part of the signed tx input).
// Put the transaction back to how we found it.
//
// TODO: Only allow this to happen if we are checking a signature, not signing a transactions
for (int i = 0; i < inputs.size(); i++) {
inputs.get(i).setScriptBytes(inputScripts[i]);
inputs.get(i).setSequenceNumber(inputSequenceNumbers[i]);
}
this.outputs = outputs;
// Satoshis bug is that SignatureHash was supposed to return a hash and on this codepath it
// actually returns the constant "1" to indicate an error, which is never checked for. Oops.
return new Sha256Hash("0100000000000000000000000000000000000000000000000000000000000000");
}
// In SIGHASH_SINGLE the outputs after the matching input index are deleted, and the outputs before
// that position are "nulled out". Unintuitively, the value in a "null" transaction is set to -1.
this.outputs = new ArrayList<TransactionOutput>(this.outputs.subList(0, inputIndex));
for (int i = 0; i < inputIndex; i++)
this.outputs.set(i, new TransactionOutput(params, this, BigInteger.valueOf(-1), new byte[] {}));
// The signature isn't broken by new versions of the transaction issued by other parties.
for (int i = 0; i < inputs.size(); i++)
if (i != inputIndex)
inputs.get(i).setSequenceNumber(0);
}
ArrayList<TransactionInput> inputs = this.inputs;
if ((sigHashType & 0x80) == 0x80) {
// SIGHASH_ANYONECANPAY means the signature in the input is not broken by changes/additions/removals
// of other inputs. For example, this is useful for building assurance contracts.
this.inputs = new ArrayList<TransactionInput>();
this.inputs.add(input);
}
ByteArrayOutputStream bos = new UnsafeByteArrayOutputStream(length == UNKNOWN_LENGTH ? 256 : length + 4);
bitcoinSerialize(bos);
// We also have to write a hash type (sigHashType is actually an unsigned char)
uint32ToByteStreamLE(0x000000ff & sigHashType, bos);
// Note that this is NOT reversed to ensure it will be signed correctly. If it were to be printed out
// however then we would expect that it is IS reversed.
Sha256Hash hash = new Sha256Hash(doubleDigest(bos.toByteArray()));
bos.close();
// Put the transaction back to how we found it.
this.inputs = inputs;
for (int i = 0; i < inputs.size(); i++) {
inputs.get(i).setScriptBytes(inputScripts[i]);
inputs.get(i).setSequenceNumber(inputSequenceNumbers[i]);
}
this.outputs = outputs;
return hash;
} catch (IOException e) {
throw new RuntimeException(e); // Cannot happen.
}
}
|
diff --git a/src/test/org/apache/commons/jexl/JexlTest.java b/src/test/org/apache/commons/jexl/JexlTest.java
index 0182acaf..253c4949 100644
--- a/src/test/org/apache/commons/jexl/JexlTest.java
+++ b/src/test/org/apache/commons/jexl/JexlTest.java
@@ -1,758 +1,758 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.jexl;
import java.io.StringReader;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.BitSet;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
import org.apache.commons.jexl.parser.ParseException;
import org.apache.commons.jexl.parser.Parser;
/**
* Simple testcases
*
* @since 1.0
* @author <a href="mailto:[email protected]">Geir Magnusson Jr.</a>
* @version $Id$
*/
public class JexlTest extends TestCase
{
protected static final String METHOD_STRING = "Method string";
protected static final String GET_METHOD_STRING = "GetMethod string";
public static Test suite()
{
return new TestSuite(JexlTest.class);
}
public JexlTest(String testName)
{
super(testName);
}
/**
* test a simple property expression
*/
public void testProperty()
throws Exception
{
/*
* tests a simple property expression
*/
Expression e = ExpressionFactory.createExpression("foo.bar");
JexlContext jc = JexlHelper.createContext();
jc.getVars().put("foo", new Foo() );
Object o = e.evaluate(jc);
assertTrue("o not instanceof String", o instanceof String);
assertEquals("o incorrect", GET_METHOD_STRING, o);
}
public void testBoolean()
throws Exception
{
JexlContext jc = JexlHelper.createContext();
jc.getVars().put("foo", new Foo() );
jc.getVars().put("a", Boolean.TRUE);
jc.getVars().put("b", Boolean.FALSE);
assertExpression(jc, "foo.convertBoolean(a==b)", "Boolean : false");
assertExpression(jc, "foo.convertBoolean(a==true)", "Boolean : true");
assertExpression(jc, "foo.convertBoolean(a==false)", "Boolean : false");
assertExpression(jc, "foo.convertBoolean(true==false)", "Boolean : false");
assertExpression(jc, "true eq false", Boolean.FALSE);
assertExpression(jc, "true ne false", Boolean.TRUE);
}
public void testStringLit()
throws Exception
{
/*
* tests a simple property expression
*/
JexlContext jc = JexlHelper.createContext();
jc.getVars().put("foo", new Foo() );
assertExpression(jc, "foo.get(\"woogie\")", "Repeat : woogie");
}
public void testExpression()
throws Exception
{
JexlContext jc = JexlHelper.createContext();
jc.getVars().put("foo", new Foo() );
jc.getVars().put("a", Boolean.TRUE);
jc.getVars().put("b", Boolean.FALSE);
jc.getVars().put("num", new Integer(5));
jc.getVars().put("now", Calendar.getInstance().getTime());
GregorianCalendar gc = new GregorianCalendar(5000, 11, 20);
jc.getVars().put("now2", gc.getTime());
- jc.getVars().put("bdec", new BigDecimal(7));
+ jc.getVars().put("bdec", new BigDecimal("7"));
jc.getVars().put("bint", new BigInteger("7"));
assertExpression(jc, "a == b", Boolean.FALSE);
assertExpression(jc, "a==true", Boolean.TRUE);
assertExpression(jc, "a==false", Boolean.FALSE);
assertExpression(jc, "true==false", Boolean.FALSE);
assertExpression(jc, "2 < 3", Boolean.TRUE);
assertExpression(jc, "num < 5", Boolean.FALSE);
assertExpression(jc, "num < num", Boolean.FALSE);
assertExpression(jc, "num < null", Boolean.FALSE);
assertExpression(jc, "num < 2.5", Boolean.FALSE);
assertExpression(jc, "now2 < now", Boolean.FALSE); // test comparable
//
assertExpression(jc, "'6' <= '5'", Boolean.FALSE);
assertExpression(jc, "num <= 5", Boolean.TRUE);
assertExpression(jc, "num <= num", Boolean.TRUE);
assertExpression(jc, "num <= null", Boolean.FALSE);
assertExpression(jc, "num <= 2.5", Boolean.FALSE);
assertExpression(jc, "now2 <= now", Boolean.FALSE); // test comparable
//
assertExpression(jc, "'6' >= '5'", Boolean.TRUE);
assertExpression(jc, "num >= 5", Boolean.TRUE);
assertExpression(jc, "num >= num", Boolean.TRUE);
assertExpression(jc, "num >= null", Boolean.FALSE);
assertExpression(jc, "num >= 2.5", Boolean.TRUE);
assertExpression(jc, "now2 >= now", Boolean.TRUE); // test comparable
assertExpression(jc, "'6' > '5'", Boolean.TRUE);
assertExpression(jc, "num > 4", Boolean.TRUE);
assertExpression(jc, "num > num", Boolean.FALSE);
assertExpression(jc, "num > null", Boolean.FALSE);
assertExpression(jc, "num > 2.5", Boolean.TRUE);
assertExpression(jc, "now2 > now", Boolean.TRUE); // test comparable
assertExpression(jc, "\"foo\" + \"bar\" == \"foobar\"", Boolean.TRUE);
assertExpression(jc, "bdec > num", Boolean.TRUE);
assertExpression(jc, "bdec >= num", Boolean.TRUE);
assertExpression(jc, "num <= bdec", Boolean.TRUE);
assertExpression(jc, "num < bdec", Boolean.TRUE);
assertExpression(jc, "bint > num", Boolean.TRUE);
assertExpression(jc, "bint == bdec", Boolean.TRUE);
assertExpression(jc, "bint >= num", Boolean.TRUE);
assertExpression(jc, "num <= bint", Boolean.TRUE);
assertExpression(jc, "num < bint", Boolean.TRUE);
}
public void testEmpty()
throws Exception
{
JexlContext jc = JexlHelper.createContext();
jc.getVars().put("string", "");
jc.getVars().put("array", new Object[0]);
jc.getVars().put("map", new HashMap());
jc.getVars().put("list", new ArrayList());
jc.getVars().put("set", (new HashMap()).keySet());
jc.getVars().put("longstring", "thingthing");
/*
* I can't believe anyone thinks this is a syntax.. :)
*/
assertExpression(jc, "empty nullthing", Boolean.TRUE);
assertExpression(jc, "empty string", Boolean.TRUE);
assertExpression(jc, "empty array", Boolean.TRUE);
assertExpression(jc, "empty map", Boolean.TRUE);
assertExpression(jc, "empty set", Boolean.TRUE);
assertExpression(jc, "empty list", Boolean.TRUE);
assertExpression(jc, "empty longstring", Boolean.FALSE);
assertExpression(jc, "not empty longstring", Boolean.TRUE);
}
public void testSize()
throws Exception
{
JexlContext jc = JexlHelper.createContext();
jc.getVars().put("s", "five!");
jc.getVars().put("array", new Object[5]);
Map map = new HashMap();
map.put("1", new Integer(1));
map.put("2", new Integer(2));
map.put("3", new Integer(3));
map.put("4", new Integer(4));
map.put("5", new Integer(5));
jc.getVars().put("map", map);
List list = new ArrayList();
list.add("1");
list.add("2");
list.add("3");
list.add("4");
list.add("5");
jc.getVars().put("list", list);
// 30652 - support for set
Set set = new HashSet();
set.addAll(list);
set.add("1");
jc.getVars().put("set", set);
// support generic int size() method
BitSet bitset = new BitSet(5);
jc.getVars().put("bitset", bitset);
assertExpression(jc, "size(s)", new Integer(5));
assertExpression(jc, "size(array)", new Integer(5));
assertExpression(jc, "size(list)", new Integer(5));
assertExpression(jc, "size(map)", new Integer(5));
assertExpression(jc, "size(set)", new Integer(5));
assertExpression(jc, "size(bitset)", new Integer(64));
assertExpression(jc, "list.size()", new Integer(5));
assertExpression(jc, "map.size()", new Integer(5));
assertExpression(jc, "set.size()", new Integer(5));
assertExpression(jc, "bitset.size()", new Integer(64));
assertExpression(jc, "list.get(size(list) - 1)", "5");
assertExpression(jc, "list[size(list) - 1]", "5");
assertExpression(jc, "list.get(list.size() - 1)", "5");
}
public void testSizeAsProperty() throws Exception
{
JexlContext jc = JexlHelper.createContext();
Map map = new HashMap();
map.put("size", "cheese");
jc.getVars().put("map", map);
jc.getVars().put("foo", new Foo());
assertExpression(jc, "map['size']", "cheese");
// PR - unsure whether or not we should support map.size or force usage of the above 'escaped' version
// assertExpression(jc, "map.size", "cheese");
assertExpression(jc, "foo.getSize()", new Integer(22));
// failing assertion for size property
//assertExpression(jc, "foo.size", new Integer(22));
}
/**
* test some simple mathematical calculations
*/
public void testCalculations()
throws Exception
{
JexlContext jc = JexlHelper.createContext();
/*
* test to ensure new string cat works
*/
jc.getVars().put("stringy", "thingy" );
assertExpression(jc, "stringy + 2", "thingy2");
/*
* test new null coersion
*/
jc.getVars().put("imanull", null );
assertExpression(jc, "imanull + 2", new Long(2));
assertExpression(jc, "imanull + imanull", new Long(0));
/* test for bugzilla 31577 */
jc.getVars().put("n", new Integer(0));
assertExpression(jc, "n != null && n != 0", Boolean.FALSE);
}
/**
* test some simple conditions
*/
public void testConditions()
throws Exception
{
JexlContext jc = JexlHelper.createContext();
jc.getVars().put("foo", new Integer(2) );
jc.getVars().put("aFloat", new Float(1));
jc.getVars().put("aDouble", new Double(2));
jc.getVars().put("aChar", new Character('A'));
jc.getVars().put("aBool", Boolean.TRUE);
StringBuffer buffer = new StringBuffer("abc");
List list = new ArrayList();
List list2 = new LinkedList();
jc.getVars().put("aBuffer", buffer);
jc.getVars().put("aList", list);
jc.getVars().put("bList", list2);
assertExpression(jc, "foo == 2", Boolean.TRUE);
assertExpression(jc, "2 == 3", Boolean.FALSE);
assertExpression(jc, "3 == foo", Boolean.FALSE);
assertExpression(jc, "3 != foo", Boolean.TRUE);
assertExpression(jc, "foo != 2", Boolean.FALSE);
// test float and double equality
assertExpression(jc, "aFloat eq aDouble", Boolean.FALSE);
assertExpression(jc, "aFloat ne aDouble", Boolean.TRUE);
assertExpression(jc, "aFloat == aDouble", Boolean.FALSE);
assertExpression(jc, "aFloat != aDouble", Boolean.TRUE);
// test number and character equality
assertExpression(jc, "foo == aChar", Boolean.FALSE);
assertExpression(jc, "foo != aChar", Boolean.TRUE);
// test string and boolean
assertExpression(jc, "aBool == 'true'", Boolean.TRUE);
assertExpression(jc, "aBool == 'false'", Boolean.FALSE);
assertExpression(jc, "aBool != 'false'", Boolean.TRUE);
// test null and boolean
assertExpression(jc, "aBool == notThere", Boolean.FALSE);
assertExpression(jc, "aBool != notThere", Boolean.TRUE);
// anything and string as a string comparison
assertExpression(jc, "aBuffer == 'abc'", Boolean.TRUE);
assertExpression(jc, "aBuffer != 'abc'", Boolean.FALSE);
// arbitrary equals
assertExpression(jc, "aList == bList", Boolean.TRUE);
assertExpression(jc, "aList != bList", Boolean.FALSE);
}
/**
* test some simple conditions
*/
public void testNotConditions()
throws Exception
{
JexlContext jc = JexlHelper.createContext();
Foo foo = new Foo();
jc.getVars().put("x", Boolean.TRUE );
jc.getVars().put("foo", foo );
jc.getVars().put("bar", "true" );
assertExpression(jc, "!x", Boolean.FALSE);
assertExpression(jc, "x", Boolean.TRUE);
assertExpression(jc, "!bar", Boolean.FALSE);
assertExpression(jc, "!foo.isSimple()", Boolean.FALSE);
assertExpression(jc, "foo.isSimple()", Boolean.TRUE);
assertExpression(jc, "!foo.simple", Boolean.FALSE);
assertExpression(jc, "foo.simple", Boolean.TRUE);
assertExpression(jc, "foo.getCheeseList().size() == 3", Boolean.TRUE);
assertExpression(jc, "foo.cheeseList.size() == 3", Boolean.TRUE);
jc.getVars().put("string", "");
assertExpression(jc, "not empty string", Boolean.FALSE);
assertExpression(jc, "not(empty string)", Boolean.FALSE);
assertExpression(jc, "not empty(string)", Boolean.FALSE);
assertExpression(jc, "! empty string", Boolean.FALSE);
assertExpression(jc, "!(empty string)", Boolean.FALSE);
assertExpression(jc, "!empty(string)", Boolean.FALSE);
}
/**
* test some simple conditions
*/
public void testNotConditionsWithDots()
throws Exception
{
JexlContext jc = JexlHelper.createContext();
jc.getVars().put("x.a", Boolean.TRUE );
jc.getVars().put("x.b", Boolean.FALSE );
assertExpression(jc, "x.a", Boolean.TRUE);
assertExpression(jc, "!x.a", Boolean.FALSE);
assertExpression(jc, "!x.b", Boolean.TRUE);
}
/**
* test some simple conditions
*/
public void testComparisons()
throws Exception
{
JexlContext jc = JexlHelper.createContext();
jc.getVars().put("foo", "the quick and lazy fox" );
assertExpression(jc, "foo.indexOf('quick') > 0", Boolean.TRUE);
assertExpression(jc, "foo.indexOf('bar') >= 0", Boolean.FALSE);
assertExpression(jc, "foo.indexOf('bar') < 0", Boolean.TRUE);
}
/**
* test some null conditions
*/
public void testNull()
throws Exception
{
JexlContext jc = JexlHelper.createContext();
jc.getVars().put("bar", new Integer(2) );
assertExpression(jc, "empty foo", Boolean.TRUE);
assertExpression(jc, "bar == null", Boolean.FALSE);
assertExpression(jc, "foo == null", Boolean.TRUE);
assertExpression(jc, "bar != null", Boolean.TRUE);
assertExpression(jc, "foo != null", Boolean.FALSE);
assertExpression(jc, "empty(bar)", Boolean.FALSE);
assertExpression(jc, "empty(foo)", Boolean.TRUE);
}
/**
* test quoting in strings
*/
public void testStringQuoting() throws Exception {
JexlContext jc = JexlHelper.createContext();
assertExpression(jc, "'\"Hello\"'", "\"Hello\"");
assertExpression(jc, "\"I'm testing\"", "I'm testing");
}
/**
* test some blank strings
*/
public void testBlankStrings()
throws Exception
{
JexlContext jc = JexlHelper.createContext();
jc.getVars().put("bar", "" );
assertExpression(jc, "foo == ''", Boolean.FALSE);
assertExpression(jc, "bar == ''", Boolean.TRUE);
assertExpression(jc, "barnotexist == ''", Boolean.FALSE);
assertExpression(jc, "empty bar", Boolean.TRUE);
assertExpression(jc, "bar.length() == 0", Boolean.TRUE);
assertExpression(jc, "size(bar) == 0", Boolean.TRUE);
}
/**
* test some blank strings
*/
public void testLogicExpressions()
throws Exception
{
JexlContext jc = JexlHelper.createContext();
jc.getVars().put("foo", "abc" );
jc.getVars().put("bar", "def" );
assertExpression(jc, "foo == 'abc' || bar == 'abc'", Boolean.TRUE);
assertExpression(jc, "foo == 'abc' or bar == 'abc'", Boolean.TRUE);
assertExpression(jc, "foo == 'abc' && bar == 'abc'", Boolean.FALSE);
assertExpression(jc, "foo == 'abc' and bar == 'abc'", Boolean.FALSE);
assertExpression(jc, "foo == 'def' || bar == 'abc'", Boolean.FALSE);
assertExpression(jc, "foo == 'def' or bar == 'abc'", Boolean.FALSE);
assertExpression(jc, "foo == 'abc' && bar == 'def'", Boolean.TRUE);
assertExpression(jc, "foo == 'abc' and bar == 'def'", Boolean.TRUE);
}
/**
* test variables with underscore names
*/
public void testVariableNames()
throws Exception
{
JexlContext jc = JexlHelper.createContext();
jc.getVars().put("foo_bar", "123" );
assertExpression(jc, "foo_bar", "123");
}
/**
* test the use of dot notation to lookup map entries
*/
public void testMapDot()
throws Exception
{
Map foo = new HashMap();
foo.put( "bar", "123" );
JexlContext jc = JexlHelper.createContext();
jc.getVars().put("foo", foo );
assertExpression(jc, "foo.bar", "123");
}
/**
* Tests string literals
*/
public void testStringLiterals()
throws Exception
{
JexlContext jc = JexlHelper.createContext();
jc.getVars().put("foo", "bar" );
assertExpression(jc, "foo == \"bar\"", Boolean.TRUE);
assertExpression(jc, "foo == 'bar'", Boolean.TRUE);
}
/**
* test the use of an int based property
*/
public void testIntProperty()
throws Exception
{
Foo foo = new Foo();
// lets check the square function first..
assertEquals(4, foo.square(2));
assertEquals(4, foo.square(-2));
JexlContext jc = JexlHelper.createContext();
jc.getVars().put("foo", foo );
assertExpression(jc, "foo.count", new Integer(5));
assertExpression(jc, "foo.square(2)", new Integer(4));
assertExpression(jc, "foo.square(-2)", new Integer(4));
}
/**
* test the -1 comparison bug
*/
public void testNegativeIntComparison()
throws Exception
{
JexlContext jc = JexlHelper.createContext();
Foo foo = new Foo();
jc.getVars().put("foo", foo );
assertExpression(jc, "foo.count != -1", Boolean.TRUE);
assertExpression(jc, "foo.count == 5", Boolean.TRUE);
assertExpression(jc, "foo.count == -1", Boolean.FALSE);
}
/**
* Attempts to recreate bug http://jira.werken.com/ViewIssue.jspa?key=JELLY-8
*/
public void testCharAtBug()
throws Exception
{
JexlContext jc = JexlHelper.createContext();
jc.getVars().put("foo", "abcdef");
assertExpression(jc, "foo.substring(2,4)", "cd");
assertExpression(jc, "foo.charAt(2)", new Character('c'));
try {
assertExpression(jc, "foo.charAt(-2)", null);
fail("this test should have thrown an exception" );
}
catch (Exception e) {
// expected behaviour
}
}
public void testEmptyDottedVariableName() throws Exception
{
JexlContext jc = JexlHelper.createContext();
jc.getVars().put( "this.is.a.test", "");
assertExpression(jc, "empty(this.is.a.test)", Boolean.TRUE);
}
public void testEmptySubListOfMap() throws Exception
{
JexlContext jc = JexlHelper.createContext();
Map m = new HashMap();
m.put("aList", new ArrayList());
jc.getVars().put( "aMap", m );
assertExpression( jc, "empty( aMap.aList )", Boolean.TRUE );
}
public void testCoercionWithComparisionOperators()
throws Exception
{
JexlContext jc = JexlHelper.createContext();
assertExpression(jc, "'2' > 1", Boolean.TRUE);
assertExpression(jc, "'2' >= 1", Boolean.TRUE);
assertExpression(jc, "'2' >= 2", Boolean.TRUE);
assertExpression(jc, "'2' < 1", Boolean.FALSE);
assertExpression(jc, "'2' <= 1", Boolean.FALSE);
assertExpression(jc, "'2' <= 2", Boolean.TRUE);
assertExpression(jc, "2 > '1'", Boolean.TRUE);
assertExpression(jc, "2 >= '1'", Boolean.TRUE);
assertExpression(jc, "2 >= '2'", Boolean.TRUE);
assertExpression(jc, "2 < '1'", Boolean.FALSE);
assertExpression(jc, "2 <= '1'", Boolean.FALSE);
assertExpression(jc, "2 <= '2'", Boolean.TRUE);
}
/**
* Test that 'and' only evaluates the second item if needed
* @throws Exception if there are errors
*/
public void testBooleanShortCircuitAnd() throws Exception
{
// handle false for the left arg of 'and'
Foo tester = new Foo();
JexlContext jc = JexlHelper.createContext();
jc.getVars().put("first", Boolean.FALSE);
jc.getVars().put("foo", tester);
Expression expr = ExpressionFactory.createExpression("first and foo.trueAndModify");
expr.evaluate(jc);
assertTrue("Short circuit failure: rhs evaluated when lhs FALSE", !tester.getModified());
// handle true for the left arg of 'and'
tester = new Foo();
jc.getVars().put("first", Boolean.TRUE);
jc.getVars().put("foo", tester);
expr.evaluate(jc);
assertTrue("Short circuit failure: rhs not evaluated when lhs TRUE", tester.getModified());
}
/**
* Test that 'or' only evaluates the second item if needed
* @throws Exception if there are errors
*/
public void testBooleanShortCircuitOr() throws Exception
{
// handle false for the left arg of 'or'
Foo tester = new Foo();
JexlContext jc = JexlHelper.createContext();
jc.getVars().put("first", Boolean.FALSE);
jc.getVars().put("foo", tester);
Expression expr = ExpressionFactory.createExpression("first or foo.trueAndModify");
expr.evaluate(jc);
assertTrue("Short circuit failure: rhs not evaluated when lhs FALSE", tester.getModified());
// handle true for the left arg of 'or'
tester = new Foo();
jc.getVars().put("first", Boolean.TRUE);
jc.getVars().put("foo", tester);
expr.evaluate(jc);
assertTrue("Short circuit failure: rhs evaluated when lhs TRUE", !tester.getModified());
}
/**
* Simple test of '+' as a string concatenation operator
* @throws Exception
*/
public void testStringConcatenation() throws Exception
{
JexlContext jc = JexlHelper.createContext();
jc.getVars().put("first", "Hello");
jc.getVars().put("second", "World");
assertExpression(jc, "first + ' ' + second", "Hello World");
}
public void testToString() throws Exception {
String code = "abcd";
Expression expr = ExpressionFactory.createExpression(code);
assertEquals("Bad expression value", code, expr.toString());
}
/**
* Make sure bad syntax throws ParseException
* @throws Exception on errors
*/
public void testBadParse() throws Exception
{
try
{
assertExpression(JexlHelper.createContext(), "empty()", null);
fail("Bad expression didn't throw ParseException");
}
catch (ParseException pe)
{
// expected behaviour
}
}
/**
* Test the ## comment in a string
* @throws Exception
*/
public void testComment() throws Exception
{
assertExpression(JexlHelper.createContext(), "## double or nothing\n 1 + 1", Long.valueOf("2"));
}
/**
* Test assignment.
* @throws Exception
*/
public void testAssignment() throws Exception
{
JexlContext jc = JexlHelper.createContext();
jc.getVars().put("aString", "Hello");
Foo foo = new Foo();
jc.getVars().put("foo", foo);
Parser parser = new Parser(new StringReader(";"));
parser.parse(new StringReader("aString = 'World';"));
assertExpression(jc, "hello = 'world'", "world");
assertEquals("hello variable not changed", "world", jc.getVars().get("hello"));
assertExpression(jc, "result = 1 + 1", new Long(2));
assertEquals("result variable not changed", new Long(2), jc.getVars().get("result"));
// todo: make sure properties can be assigned to, fall back to flat var if no property
// assertExpression(jc, "foo.property1 = '99'", "99");
// assertEquals("property not set", "99", foo.getProperty1());
}
public void testAntPropertiesWithMethods() throws Exception
{
JexlContext jc = JexlHelper.createContext();
String value = "Stinky Cheese";
jc.getVars().put("maven.bob.food", value);
assertExpression(jc, "maven.bob.food.length()", new Integer(value.length()));
assertExpression(jc, "empty(maven.bob.food)", Boolean.FALSE);
assertExpression(jc, "size(maven.bob.food)", new Integer(value.length()));
assertExpression(jc, "maven.bob.food + ' is good'", value + " is good");
// DG: Note the following ant properties don't work
// String version = "1.0.3";
// jc.getVars().put("commons-logging", version);
// assertExpression(jc, "commons-logging", version);
}
public void testUnicodeSupport() throws Exception
{
assertExpression(JexlHelper.createContext(), "myvar == 'Użytkownik'", Boolean.FALSE);
}
/**
* Asserts that the given expression returns the given value when applied to the
* given context
*/
protected void assertExpression(JexlContext jc, String expression, Object expected) throws Exception
{
Expression e = ExpressionFactory.createExpression(expression);
Object actual = e.evaluate(jc);
assertEquals(expression, expected, actual);
}
/**
* Helps in debugging the testcases when working with it
*
*/
public static void main(String[] args)
throws Exception
{
JexlTest jt = new JexlTest("foo");
jt.testEmpty();
}
}
| true | true | public void testExpression()
throws Exception
{
JexlContext jc = JexlHelper.createContext();
jc.getVars().put("foo", new Foo() );
jc.getVars().put("a", Boolean.TRUE);
jc.getVars().put("b", Boolean.FALSE);
jc.getVars().put("num", new Integer(5));
jc.getVars().put("now", Calendar.getInstance().getTime());
GregorianCalendar gc = new GregorianCalendar(5000, 11, 20);
jc.getVars().put("now2", gc.getTime());
jc.getVars().put("bdec", new BigDecimal(7));
jc.getVars().put("bint", new BigInteger("7"));
assertExpression(jc, "a == b", Boolean.FALSE);
assertExpression(jc, "a==true", Boolean.TRUE);
assertExpression(jc, "a==false", Boolean.FALSE);
assertExpression(jc, "true==false", Boolean.FALSE);
assertExpression(jc, "2 < 3", Boolean.TRUE);
assertExpression(jc, "num < 5", Boolean.FALSE);
assertExpression(jc, "num < num", Boolean.FALSE);
assertExpression(jc, "num < null", Boolean.FALSE);
assertExpression(jc, "num < 2.5", Boolean.FALSE);
assertExpression(jc, "now2 < now", Boolean.FALSE); // test comparable
//
assertExpression(jc, "'6' <= '5'", Boolean.FALSE);
assertExpression(jc, "num <= 5", Boolean.TRUE);
assertExpression(jc, "num <= num", Boolean.TRUE);
assertExpression(jc, "num <= null", Boolean.FALSE);
assertExpression(jc, "num <= 2.5", Boolean.FALSE);
assertExpression(jc, "now2 <= now", Boolean.FALSE); // test comparable
//
assertExpression(jc, "'6' >= '5'", Boolean.TRUE);
assertExpression(jc, "num >= 5", Boolean.TRUE);
assertExpression(jc, "num >= num", Boolean.TRUE);
assertExpression(jc, "num >= null", Boolean.FALSE);
assertExpression(jc, "num >= 2.5", Boolean.TRUE);
assertExpression(jc, "now2 >= now", Boolean.TRUE); // test comparable
assertExpression(jc, "'6' > '5'", Boolean.TRUE);
assertExpression(jc, "num > 4", Boolean.TRUE);
assertExpression(jc, "num > num", Boolean.FALSE);
assertExpression(jc, "num > null", Boolean.FALSE);
assertExpression(jc, "num > 2.5", Boolean.TRUE);
assertExpression(jc, "now2 > now", Boolean.TRUE); // test comparable
assertExpression(jc, "\"foo\" + \"bar\" == \"foobar\"", Boolean.TRUE);
assertExpression(jc, "bdec > num", Boolean.TRUE);
assertExpression(jc, "bdec >= num", Boolean.TRUE);
assertExpression(jc, "num <= bdec", Boolean.TRUE);
assertExpression(jc, "num < bdec", Boolean.TRUE);
assertExpression(jc, "bint > num", Boolean.TRUE);
assertExpression(jc, "bint == bdec", Boolean.TRUE);
assertExpression(jc, "bint >= num", Boolean.TRUE);
assertExpression(jc, "num <= bint", Boolean.TRUE);
assertExpression(jc, "num < bint", Boolean.TRUE);
}
| public void testExpression()
throws Exception
{
JexlContext jc = JexlHelper.createContext();
jc.getVars().put("foo", new Foo() );
jc.getVars().put("a", Boolean.TRUE);
jc.getVars().put("b", Boolean.FALSE);
jc.getVars().put("num", new Integer(5));
jc.getVars().put("now", Calendar.getInstance().getTime());
GregorianCalendar gc = new GregorianCalendar(5000, 11, 20);
jc.getVars().put("now2", gc.getTime());
jc.getVars().put("bdec", new BigDecimal("7"));
jc.getVars().put("bint", new BigInteger("7"));
assertExpression(jc, "a == b", Boolean.FALSE);
assertExpression(jc, "a==true", Boolean.TRUE);
assertExpression(jc, "a==false", Boolean.FALSE);
assertExpression(jc, "true==false", Boolean.FALSE);
assertExpression(jc, "2 < 3", Boolean.TRUE);
assertExpression(jc, "num < 5", Boolean.FALSE);
assertExpression(jc, "num < num", Boolean.FALSE);
assertExpression(jc, "num < null", Boolean.FALSE);
assertExpression(jc, "num < 2.5", Boolean.FALSE);
assertExpression(jc, "now2 < now", Boolean.FALSE); // test comparable
//
assertExpression(jc, "'6' <= '5'", Boolean.FALSE);
assertExpression(jc, "num <= 5", Boolean.TRUE);
assertExpression(jc, "num <= num", Boolean.TRUE);
assertExpression(jc, "num <= null", Boolean.FALSE);
assertExpression(jc, "num <= 2.5", Boolean.FALSE);
assertExpression(jc, "now2 <= now", Boolean.FALSE); // test comparable
//
assertExpression(jc, "'6' >= '5'", Boolean.TRUE);
assertExpression(jc, "num >= 5", Boolean.TRUE);
assertExpression(jc, "num >= num", Boolean.TRUE);
assertExpression(jc, "num >= null", Boolean.FALSE);
assertExpression(jc, "num >= 2.5", Boolean.TRUE);
assertExpression(jc, "now2 >= now", Boolean.TRUE); // test comparable
assertExpression(jc, "'6' > '5'", Boolean.TRUE);
assertExpression(jc, "num > 4", Boolean.TRUE);
assertExpression(jc, "num > num", Boolean.FALSE);
assertExpression(jc, "num > null", Boolean.FALSE);
assertExpression(jc, "num > 2.5", Boolean.TRUE);
assertExpression(jc, "now2 > now", Boolean.TRUE); // test comparable
assertExpression(jc, "\"foo\" + \"bar\" == \"foobar\"", Boolean.TRUE);
assertExpression(jc, "bdec > num", Boolean.TRUE);
assertExpression(jc, "bdec >= num", Boolean.TRUE);
assertExpression(jc, "num <= bdec", Boolean.TRUE);
assertExpression(jc, "num < bdec", Boolean.TRUE);
assertExpression(jc, "bint > num", Boolean.TRUE);
assertExpression(jc, "bint == bdec", Boolean.TRUE);
assertExpression(jc, "bint >= num", Boolean.TRUE);
assertExpression(jc, "num <= bint", Boolean.TRUE);
assertExpression(jc, "num < bint", Boolean.TRUE);
}
|
diff --git a/MakeTestOmeTiff.java b/MakeTestOmeTiff.java
index fc7dcc2..f4f5c4b 100644
--- a/MakeTestOmeTiff.java
+++ b/MakeTestOmeTiff.java
@@ -1,555 +1,556 @@
//
// MakeTestOmeTiff.java
//
import java.awt.*;
import java.awt.image.BufferedImage;
import java.awt.geom.Rectangle2D;
import java.io.IOException;
import java.util.*;
import loci.formats.*;
import loci.formats.out.TiffWriter;
/** Creates a sample OME-TIFF dataset according to the given parameters. */
public class MakeTestOmeTiff {
private static int gradient(int type, int num, int total) {
final int max = 96;
int split = type / 2 + 1;
boolean reverse = type % 2 == 0;
int v = max;
total /= split;
for (int i=1; i<=split+1; i++) {
if (num < i * total) {
if (i % 2 == 0) v = max * (num % total) / total;
else v = max * (total - num % total) / total;
break;
}
}
if (reverse) v = max - v;
return v;
}
/** Fisher-Yates shuffle, stolen from Wikipedia. */
public static void shuffle(int[] array) {
Random r = new Random();
int n = array.length;
while (--n > 0) {
int k = r.nextInt(n + 1); // 0 <= k <= n (!)
int temp = array[n];
array[n] = array[k];
array[k] = temp;
}
}
/**
* Constructs a TiffData element matching the given parameters.
* @param ifd Value to use for IFD attribute; 0 is default/none.
* @param num Value to use for NumPlanes attribute, or -1 for none.
* @param firstZ Value to use for FirstZ attribute; 0 is default/none.
* @param firstC Value to use for FirstC attribute; 0 is default/none.
* @param firstT Value to use for FirstT attribute; 0 is default/none.
* @param order Dimension order; only used when scrambling.
* @param sizeZ Number of focal planes; only used when scrambling.
* @param sizeC Number of channels; only used when scrambling.
* @param sizeT Number of time points; only used when scrambling.
* @param total Total number of IFDs in the file;
* if null, no scrambling will be performed.
*/
private static String tiffData(int ifd, int num,
int firstZ, int firstC, int firstT,
String order, int sizeZ, int sizeC, int sizeT, Integer total)
{
StringBuffer sb = new StringBuffer();
if (total == null) {
sb.append("<TiffData");
if (ifd > 0) sb.append(" IFD=\"" + ifd + "\"");
if (num >= 0) sb.append(" NumPlanes=\"" + num + "\"");
if (firstZ > 0) sb.append(" FirstZ=\"" + firstZ + "\"");
if (firstC > 0) sb.append(" FirstC=\"" + firstC + "\"");
if (firstT > 0) sb.append(" FirstT=\"" + firstT + "\"");
sb.append("/>");
}
else {
// scramble planes
if (ifd < 0) ifd = 0;
if (num < 0) num = total.intValue();
int len = sizeZ * sizeC * sizeT;
int index = FormatTools.getIndex(order,
sizeZ, sizeC, sizeT, len, firstZ, firstC, firstT);
int[] planes = new int[num];
for (int i=0; i<num; i++) planes[i] = index + i;
shuffle(planes);
for (int i=0; i<num; i++) {
int[] zct = FormatTools.getZCTCoords(order,
sizeZ, sizeC, sizeT, len, planes[i]);
sb.append("<TiffData IFD=\"" + (i + ifd) + "\"" +
" NumPlanes=\"1\" FirstZ=\"" + zct[0] + "\"" +
" FirstC=\"" + zct[1] + "\" FirstT=\"" + zct[2] + "\"/>");
}
}
return sb.toString();
}
public static void main(String[] args) throws FormatException, IOException {
boolean usage = false;
// parse command line arguments
String name = null;
String dist = null;
boolean scramble = false;
int numImages = 0;
int[] numPixels = null;
int[][] sizeX = null, sizeY = null;
int[][] sizeZ = null, sizeC = null, sizeT = null;
String[][] dimOrder = null;
if (args == null || args.length < 2) usage = true;
else {
name = args[0];
dist = args[1].toLowerCase();
scramble = args.length > 2 && args[2].equalsIgnoreCase("-scramble");
int startIndex = scramble ? 3 : 2;
// count number of images
int ndx = startIndex;
while (ndx < args.length) {
int numPix = Integer.parseInt(args[ndx]);
ndx += 1 + 6 * numPix;
numImages++;
}
// parse pixels's dimensional information
if (ndx > args.length) usage = true;
else {
numPixels = new int[numImages];
sizeX = new int[numImages][];
sizeY = new int[numImages][];
sizeZ = new int[numImages][];
sizeC = new int[numImages][];
sizeT = new int[numImages][];
dimOrder = new String[numImages][];
ndx = startIndex;
for (int i=0; i<numImages; i++) {
numPixels[i] = Integer.parseInt(args[ndx++]);
sizeX[i] = new int[numPixels[i]];
sizeY[i] = new int[numPixels[i]];
sizeZ[i] = new int[numPixels[i]];
sizeC[i] = new int[numPixels[i]];
sizeT[i] = new int[numPixels[i]];
dimOrder[i] = new String[numPixels[i]];
for (int p=0; p<numPixels[i]; p++) {
sizeX[i][p] = Integer.parseInt(args[ndx++]);
sizeY[i][p] = Integer.parseInt(args[ndx++]);
sizeZ[i][p] = Integer.parseInt(args[ndx++]);
sizeC[i][p] = Integer.parseInt(args[ndx++]);
sizeT[i][p] = Integer.parseInt(args[ndx++]);
dimOrder[i][p] = args[ndx++].toUpperCase();
}
}
}
}
if (usage) {
System.out.println(
"Usage: java MakeTestOmeTiff name dist [-scramble]");
System.out.println(" image1_NumPixels");
System.out.println(" image1_pixels1_SizeX " +
"image1_pixels1_SizeY image1_pixels1_SizeZ");
System.out.println(" image1_pixels1_SizeC " +
"image1_pixels1_SizeT image1_pixels1_DimOrder");
System.out.println(" image1_pixels2_SizeX " +
"image1_pixels2_SizeY image1_pixels2_SizeZ");
System.out.println(" image1_pixels2_SizeC " +
"image1_pixels2_SizeT image1_pixels2_DimOrder");
System.out.println(" [...]");
System.out.println(" image2_NumPixels");
System.out.println(" image2_pixels1_SizeX " +
"image2_pixels1_SizeY image1_pixels1_SizeZ");
System.out.println(" image2_pixels1_SizeC " +
"image2_pixels1_SizeT image1_pixels1_DimOrder");
System.out.println(" image2_pixels2_SizeX " +
"image2_pixels2_SizeY image1_pixels2_SizeZ");
System.out.println(" image2_pixels2_SizeC " +
"image2_pixels2_SizeT image1_pixels2_DimOrder");
System.out.println(" [...]");
System.out.println(" [...]");
System.out.println();
System.out.println(" name: prefix for filenames");
System.out.println(" dist: code for how to distribute across files:");
System.out.println(" ipzct = all Images + Pixels in one file");
System.out.println(" pzct = each Image in its own file");
System.out.println(" zct = each Pixels in its own file");
System.out.println(" zc = all Z + C positions per file");
System.out.println(" zt = all Z + T positions per file");
System.out.println(" ct = all C + T positions per file");
System.out.println(" z = all Z positions per file");
System.out.println(" c = all C positions per file");
System.out.println(" t = all T positions per file");
System.out.println(" x = single plane per file");
System.out.println(" -scramble: randomizes IFD ordering");
System.out.println(" image*_pixels*_SizeX: width of image planes");
System.out.println(" image*_pixels*_SizeY: height of image planes");
System.out.println(" image*_pixels*_SizeZ: number of focal planes");
System.out.println(" image*_pixels*_SizeC: number of channels");
System.out.println(" image*_pixels*_SizeT: number of time points");
System.out.println(" image*_pixels*_DimOrder: planar ordering:");
System.out.println(" XYZCT, XYZTC, XYCZT, XYCTZ, XYTZC, or XYTCZ");
System.out.println();
System.out.println("Example:");
System.out.println(" java MakeTestOmeTiff test ipzct \\");
System.out.println(" 2 431 555 1 2 7 XYTCZ \\");
System.out.println(" 348 461 2 1 6 XYZTC \\");
System.out.println(" 1 517 239 5 3 4 XYCZT");
System.exit(1);
}
if (!dist.equals("ipzct") && !dist.equals("pzct") && !dist.equals("zct") &&
!dist.equals("zc") && !dist.equals("zt") && !dist.equals("ct") &&
!dist.equals("z") && !dist.equals("c") && !dist.equals("t") &&
!dist.equals("x"))
{
System.out.println("Invalid dist value: " + dist);
System.exit(2);
}
boolean allI = dist.indexOf("i") >= 0;
boolean allP = dist.indexOf("p") >= 0;
boolean allZ = dist.indexOf("z") >= 0;
boolean allC = dist.indexOf("c") >= 0;
boolean allT = dist.indexOf("t") >= 0;
BufferedImage[][][] images = new BufferedImage[numImages][][];
int[][] globalOffsets = new int[numImages][]; // IFD offsets across Images
int[][] localOffsets = new int[numImages][]; // IFD offsets per Image
int globalOffset = 0, localOffset = 0;
for (int i=0; i<numImages; i++) {
images[i] = new BufferedImage[numPixels[i]][];
globalOffsets[i] = new int[numPixels[i]];
localOffsets[i] = new int[numPixels[i]];
localOffset = 0;
for (int p=0; p<numPixels[i]; p++) {
int len = sizeZ[i][p] * sizeC[i][p] * sizeT[i][p];
images[i][p] = new BufferedImage[len];
globalOffsets[i][p] = globalOffset;
globalOffset += len;
localOffsets[i][p] = localOffset;
localOffset += len;
}
}
System.out.println("Generating image planes");
for (int i=0, ipNum=0; i<numImages; i++) {
System.out.println(" Image #" + (i + 1) + ":");
for (int p=0; p<numPixels[i]; p++, ipNum++) {
System.out.print(" Pixels #" + (p + 1) + " - " +
sizeX[i][p] + " x " + sizeY[i][p] + ", " +
sizeZ[i][p] + "Z " + sizeC[i][p] + "C " + sizeT[i][p] + "T");
int len = images[i][p].length;
for (int j=0; j<len; j++) {
int[] zct = FormatTools.getZCTCoords(dimOrder[i][p],
sizeZ[i][p], sizeC[i][p], sizeT[i][p], len, j);
System.out.print(".");
images[i][p][j] = new BufferedImage(
sizeX[i][p], sizeY[i][p], BufferedImage.TYPE_BYTE_GRAY);
Graphics2D g = images[i][p][j].createGraphics();
// draw gradient
boolean even = ipNum % 2 == 0;
int type = ipNum / 2;
if (even) {
// draw vertical gradient for even-numbered pixelses
for (int y=0; y<sizeY[i][p]; y++) {
int v = gradient(type, y, sizeY[i][p]);
g.setColor(new Color(v, v, v));
g.drawLine(0, y, sizeX[i][p], y);
}
}
else {
// draw horizontal gradient for odd-numbered pixelses
for (int x=0; x<sizeX[i][p]; x++) {
int v = gradient(type, x, sizeX[i][p]);
g.setColor(new Color(v, v, v));
g.drawLine(x, 0, x, sizeY[i][p]);
}
}
// build list of text lines from planar information
Vector lines = new Vector();
Font font = g.getFont();
lines.add(new TextLine(name, font.deriveFont(32f), 5, -5));
lines.add(new TextLine(sizeX[i][p] + " x " + sizeY[i][p],
font.deriveFont(Font.ITALIC, 16f), 20, 10));
lines.add(new TextLine(dimOrder[i][p],
font.deriveFont(Font.ITALIC, 14f), 30, 5));
int space = 5;
if (numImages > 1) {
lines.add(new TextLine("Image #" + (i + 1) + "/" + numImages,
font, 20, space));
space = 2;
}
if (numPixels[i] > 1) {
lines.add(new TextLine("Pixels #" + (p + 1) + "/" + numPixels[i],
font, 20, space));
space = 2;
}
if (sizeZ[i][p] > 1) {
lines.add(new TextLine("Focal plane = " +
(zct[0] + 1) + "/" + sizeZ[i][p], font, 20, space));
space = 2;
}
if (sizeC[i][p] > 1) {
lines.add(new TextLine("Channel = " +
(zct[1] + 1) + "/" + sizeC[i][p], font, 20, space));
space = 2;
}
if (sizeT[i][p] > 1) {
lines.add(new TextLine("Time point = " +
(zct[2] + 1) + "/" + sizeT[i][p], font, 20, space));
space = 2;
}
// draw text lines to image
g.setColor(Color.white);
int yoff = 0;
for (int l=0; l<lines.size(); l++) {
TextLine text = (TextLine) lines.get(l);
g.setFont(text.font);
Rectangle2D r = g.getFont().getStringBounds(
text.line, g.getFontRenderContext());
yoff += r.getHeight() + text.ypad;
g.drawString(text.line, text.xoff, yoff);
}
g.dispose();
}
System.out.println();
}
}
System.out.println("Writing output files");
// determine filename for each image plane
String[][][] filenames = new String[numImages][][];
Hashtable lastHash = new Hashtable();
boolean[][][] last = new boolean[numImages][][];
Hashtable ifdTotal = new Hashtable();
Hashtable firstZ = new Hashtable();
Hashtable firstC = new Hashtable();
Hashtable firstT = new Hashtable();
StringBuffer sb = new StringBuffer();
for (int i=0; i<numImages; i++) {
filenames[i] = new String[numPixels[i]][];
last[i] = new boolean[numPixels[i]][];
for (int p=0; p<numPixels[i]; p++) {
int len = images[i][p].length;
filenames[i][p] = new String[len];
last[i][p] = new boolean[len];
for (int j=0; j<len; j++) {
sb.append(name);
if (!allI && numImages > 1) sb.append("_image" + (i + 1));
if (!allP && numPixels[i] > 1) sb.append("_pixels" + (p + 1));
int[] zct = FormatTools.getZCTCoords(dimOrder[i][p],
sizeZ[i][p], sizeC[i][p], sizeT[i][p], len, j);
if (!allZ && sizeZ[i][p] > 1) sb.append("_Z" + (zct[0] + 1));
if (!allC && sizeC[i][p] > 1) sb.append("_C" + (zct[1] + 1));
if (!allT && sizeT[i][p] > 1) sb.append("_T" + (zct[2] + 1));
sb.append(".ome.tif");
filenames[i][p][j] = sb.toString();
sb.setLength(0);
last[i][p][j] = true;
// update last flag for this filename
String key = filenames[i][p][j];
ImageIndex index = (ImageIndex) lastHash.get(key);
if (index != null) {
last[index.image][index.pixels][index.plane] = false;
}
lastHash.put(key, new ImageIndex(i, p, j));
// update IFD count for this filename
Integer total = (Integer) ifdTotal.get(key);
if (total == null) total = new Integer(1);
else total = new Integer(total.intValue() + 1);
ifdTotal.put(key, total);
// update FirstZ, FirstC and FirstT values for this filename
if (!allZ && sizeZ[i][p] > 1) {
firstZ.put(filenames[i][p][j], new Integer(zct[0]));
}
if (!allC && sizeC[i][p] > 1) {
firstC.put(filenames[i][p][j], new Integer(zct[1]));
}
if (!allT && sizeT[i][p] > 1) {
firstT.put(filenames[i][p][j], new Integer(zct[2]));
}
}
}
}
// build OME-XML block
// CreationDate is required; initialize a default value (current time)
// use ISO 8601 dateTime format (e.g., 1988-04-07T18:39:09)
sb.setLength(0);
Calendar now = Calendar.getInstance();
int year = now.get(Calendar.YEAR);
int month = now.get(Calendar.MONTH);
int day = now.get(Calendar.DAY_OF_MONTH);
int hour = now.get(Calendar.HOUR_OF_DAY);
int min = now.get(Calendar.MINUTE);
int sec = now.get(Calendar.SECOND);
sb.append(year);
sb.append("-");
if (month < 9) sb.append("0");
sb.append(month + 1);
sb.append("-");
if (day < 10) sb.append("0");
sb.append(day);
sb.append("T");
if (hour < 10) sb.append("0");
sb.append(hour);
sb.append(":");
if (min < 10) sb.append("0");
sb.append(min);
sb.append(":");
if (sec < 10) sb.append("0");
sb.append(sec);
String creationDate = sb.toString();
sb.setLength(0);
sb.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>" +
"<!-- Warning: this comment is an OME-XML metadata block, which " +
"contains crucial dimensional parameters and other important metadata. " +
"Please edit cautiously (if at all), and back up the original data " +
"before doing so. For more information, see the OME-TIFF web site: " +
"http://loci.wisc.edu/ome/ome-tiff.html. --><OME " +
"xmlns=\"http://www.openmicroscopy.org/XMLschemas/OME/FC/ome.xsd\" " +
"xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" " +
"xsi:schemaLocation=\"" +
+ "http://www.openmicroscopy.org/XMLschemas/OME/FC/ome.xsd " +
"http://www.openmicroscopy.org/XMLschemas/OME/FC/ome.xsd\">");
for (int i=0; i<numImages; i++) {
sb.append("<Image " +
"ID=\"openmicroscopy.org:Image:" + (i + 1) + "\" " +
"Name=\"" + name + "\" " +
"DefaultPixels=\"openmicroscopy.org:Pixels:" + (i + 1) + "-1\">" +
"<CreationDate>" + creationDate + "</CreationDate>");
for (int p=0; p<numPixels[i]; p++) {
sb.append("<Pixels " +
"ID=\"openmicroscopy.org:Pixels:" + (i + 1) + "-" + (p + 1) + "\" " +
"DimensionOrder=\"" + dimOrder[i][p] + "\" " +
"PixelType=\"uint8\" " +
"BigEndian=\"true\" " +
"SizeX=\"" + sizeX[i][p] + "\" " +
"SizeY=\"" + sizeY[i][p] + "\" " +
"SizeZ=\"" + sizeZ[i][p] + "\" " +
"SizeC=\"" + sizeC[i][p] + "\" " +
"SizeT=\"" + sizeT[i][p] + "\">" +
"TIFF_DATA_IMAGE_" + i + "_PIXELS_" + p + // placeholder
"</Pixels>");
}
sb.append("</Image>");
}
sb.append("</OME>");
String xmlTemplate = sb.toString();
TiffWriter out = new TiffWriter();
for (int i=0; i<numImages; i++) {
System.out.println(" Image #" + (i + 1) + ":");
for (int p=0; p<numPixels[i]; p++) {
System.out.println(" Pixels #" + (p + 1) + " - " +
sizeX[i][p] + " x " + sizeY[i][p] + ", " +
sizeZ[i][p] + "Z " + sizeC[i][p] + "C " + sizeT[i][p] + "T:");
int len = images[i][p].length;
for (int j=0; j<len; j++) {
int[] zct = FormatTools.getZCTCoords(dimOrder[i][p],
sizeZ[i][p], sizeC[i][p], sizeT[i][p], len, j);
System.out.println(" " +
"Z" + zct[0] + " C" + zct[1] + " T" + zct[2] +
" -> " + filenames[i][p][j] + (last[i][p][j] ? "*" : ""));
out.setId(filenames[i][p][j]);
// write comment stub, to be overwritten later
Hashtable ifdHash = new Hashtable();
TiffTools.putIFDValue(ifdHash, TiffTools.IMAGE_DESCRIPTION, "");
out.saveImage(images[i][p][j], ifdHash, last[i][p][j]);
if (last[i][p][j]) {
// inject OME-XML block
String xml = xmlTemplate;
String key = filenames[i][p][j];
Integer fzObj = (Integer) firstZ.get(key);
Integer fcObj = (Integer) firstC.get(key);
Integer ftObj = (Integer) firstT.get(key);
int fz = fzObj == null ? 0 : fzObj.intValue();
int fc = fcObj == null ? 0 : fcObj.intValue();
int ft = ftObj == null ? 0 : ftObj.intValue();
Integer total = (Integer) ifdTotal.get(key);
if (!scramble) total = null;
for (int ii=0; ii<numImages; ii++) {
for (int pp=0; pp<numPixels[ii]; pp++) {
String pattern = "TIFF_DATA_IMAGE_" + ii + "_PIXELS_" + pp;
if (!allI && ii != i || !allP && pp != p) {
// current Pixels is not part of this file
xml = xml.replaceFirst(pattern,
tiffData(0, 0, 0, 0, 0, dimOrder[ii][pp],
sizeZ[ii][pp], sizeC[ii][pp], sizeT[ii][pp], total));
continue;
}
if (allP) {
int ifd;
if (allI) {
// all Images in one file; need to use global offset
ifd = globalOffsets[ii][pp];
}
else { // ii == i
// one Image per file; use local offset
ifd = localOffsets[ii][pp];
}
int num = images[ii][pp].length;
if ((!allI || numImages == 1) && numPixels[i] == 1) {
// only one Pixels in this file; don't need IFD/NumPlanes
ifd = 0;
num = -1;
}
xml = xml.replaceFirst(pattern,
tiffData(ifd, num, 0, 0, 0, dimOrder[ii][pp],
sizeZ[ii][pp], sizeC[ii][pp], sizeT[ii][pp], total));
}
else { // pp == p
xml = xml.replaceFirst(pattern,
tiffData(0, -1, fz, fc, ft, dimOrder[ii][pp],
sizeZ[ii][pp], sizeC[ii][pp], sizeT[ii][pp], total));
}
}
}
TiffTools.overwriteComment(filenames[i][p][j], xml);
}
}
}
}
}
private static class TextLine {
private String line;
private Font font;
private int xoff;
private int ypad;
private TextLine(String line, Font font, int xoff, int ypad) {
this.line = line;
this.font = font;
this.xoff = xoff;
this.ypad = ypad;
}
}
private static class ImageIndex {
private int image;
private int pixels;
private int plane;
private ImageIndex(int i, int p, int j) {
this.image = i;
this.pixels = p;
this.plane = j;
}
}
}
| true | true | public static void main(String[] args) throws FormatException, IOException {
boolean usage = false;
// parse command line arguments
String name = null;
String dist = null;
boolean scramble = false;
int numImages = 0;
int[] numPixels = null;
int[][] sizeX = null, sizeY = null;
int[][] sizeZ = null, sizeC = null, sizeT = null;
String[][] dimOrder = null;
if (args == null || args.length < 2) usage = true;
else {
name = args[0];
dist = args[1].toLowerCase();
scramble = args.length > 2 && args[2].equalsIgnoreCase("-scramble");
int startIndex = scramble ? 3 : 2;
// count number of images
int ndx = startIndex;
while (ndx < args.length) {
int numPix = Integer.parseInt(args[ndx]);
ndx += 1 + 6 * numPix;
numImages++;
}
// parse pixels's dimensional information
if (ndx > args.length) usage = true;
else {
numPixels = new int[numImages];
sizeX = new int[numImages][];
sizeY = new int[numImages][];
sizeZ = new int[numImages][];
sizeC = new int[numImages][];
sizeT = new int[numImages][];
dimOrder = new String[numImages][];
ndx = startIndex;
for (int i=0; i<numImages; i++) {
numPixels[i] = Integer.parseInt(args[ndx++]);
sizeX[i] = new int[numPixels[i]];
sizeY[i] = new int[numPixels[i]];
sizeZ[i] = new int[numPixels[i]];
sizeC[i] = new int[numPixels[i]];
sizeT[i] = new int[numPixels[i]];
dimOrder[i] = new String[numPixels[i]];
for (int p=0; p<numPixels[i]; p++) {
sizeX[i][p] = Integer.parseInt(args[ndx++]);
sizeY[i][p] = Integer.parseInt(args[ndx++]);
sizeZ[i][p] = Integer.parseInt(args[ndx++]);
sizeC[i][p] = Integer.parseInt(args[ndx++]);
sizeT[i][p] = Integer.parseInt(args[ndx++]);
dimOrder[i][p] = args[ndx++].toUpperCase();
}
}
}
}
if (usage) {
System.out.println(
"Usage: java MakeTestOmeTiff name dist [-scramble]");
System.out.println(" image1_NumPixels");
System.out.println(" image1_pixels1_SizeX " +
"image1_pixels1_SizeY image1_pixels1_SizeZ");
System.out.println(" image1_pixels1_SizeC " +
"image1_pixels1_SizeT image1_pixels1_DimOrder");
System.out.println(" image1_pixels2_SizeX " +
"image1_pixels2_SizeY image1_pixels2_SizeZ");
System.out.println(" image1_pixels2_SizeC " +
"image1_pixels2_SizeT image1_pixels2_DimOrder");
System.out.println(" [...]");
System.out.println(" image2_NumPixels");
System.out.println(" image2_pixels1_SizeX " +
"image2_pixels1_SizeY image1_pixels1_SizeZ");
System.out.println(" image2_pixels1_SizeC " +
"image2_pixels1_SizeT image1_pixels1_DimOrder");
System.out.println(" image2_pixels2_SizeX " +
"image2_pixels2_SizeY image1_pixels2_SizeZ");
System.out.println(" image2_pixels2_SizeC " +
"image2_pixels2_SizeT image1_pixels2_DimOrder");
System.out.println(" [...]");
System.out.println(" [...]");
System.out.println();
System.out.println(" name: prefix for filenames");
System.out.println(" dist: code for how to distribute across files:");
System.out.println(" ipzct = all Images + Pixels in one file");
System.out.println(" pzct = each Image in its own file");
System.out.println(" zct = each Pixels in its own file");
System.out.println(" zc = all Z + C positions per file");
System.out.println(" zt = all Z + T positions per file");
System.out.println(" ct = all C + T positions per file");
System.out.println(" z = all Z positions per file");
System.out.println(" c = all C positions per file");
System.out.println(" t = all T positions per file");
System.out.println(" x = single plane per file");
System.out.println(" -scramble: randomizes IFD ordering");
System.out.println(" image*_pixels*_SizeX: width of image planes");
System.out.println(" image*_pixels*_SizeY: height of image planes");
System.out.println(" image*_pixels*_SizeZ: number of focal planes");
System.out.println(" image*_pixels*_SizeC: number of channels");
System.out.println(" image*_pixels*_SizeT: number of time points");
System.out.println(" image*_pixels*_DimOrder: planar ordering:");
System.out.println(" XYZCT, XYZTC, XYCZT, XYCTZ, XYTZC, or XYTCZ");
System.out.println();
System.out.println("Example:");
System.out.println(" java MakeTestOmeTiff test ipzct \\");
System.out.println(" 2 431 555 1 2 7 XYTCZ \\");
System.out.println(" 348 461 2 1 6 XYZTC \\");
System.out.println(" 1 517 239 5 3 4 XYCZT");
System.exit(1);
}
if (!dist.equals("ipzct") && !dist.equals("pzct") && !dist.equals("zct") &&
!dist.equals("zc") && !dist.equals("zt") && !dist.equals("ct") &&
!dist.equals("z") && !dist.equals("c") && !dist.equals("t") &&
!dist.equals("x"))
{
System.out.println("Invalid dist value: " + dist);
System.exit(2);
}
boolean allI = dist.indexOf("i") >= 0;
boolean allP = dist.indexOf("p") >= 0;
boolean allZ = dist.indexOf("z") >= 0;
boolean allC = dist.indexOf("c") >= 0;
boolean allT = dist.indexOf("t") >= 0;
BufferedImage[][][] images = new BufferedImage[numImages][][];
int[][] globalOffsets = new int[numImages][]; // IFD offsets across Images
int[][] localOffsets = new int[numImages][]; // IFD offsets per Image
int globalOffset = 0, localOffset = 0;
for (int i=0; i<numImages; i++) {
images[i] = new BufferedImage[numPixels[i]][];
globalOffsets[i] = new int[numPixels[i]];
localOffsets[i] = new int[numPixels[i]];
localOffset = 0;
for (int p=0; p<numPixels[i]; p++) {
int len = sizeZ[i][p] * sizeC[i][p] * sizeT[i][p];
images[i][p] = new BufferedImage[len];
globalOffsets[i][p] = globalOffset;
globalOffset += len;
localOffsets[i][p] = localOffset;
localOffset += len;
}
}
System.out.println("Generating image planes");
for (int i=0, ipNum=0; i<numImages; i++) {
System.out.println(" Image #" + (i + 1) + ":");
for (int p=0; p<numPixels[i]; p++, ipNum++) {
System.out.print(" Pixels #" + (p + 1) + " - " +
sizeX[i][p] + " x " + sizeY[i][p] + ", " +
sizeZ[i][p] + "Z " + sizeC[i][p] + "C " + sizeT[i][p] + "T");
int len = images[i][p].length;
for (int j=0; j<len; j++) {
int[] zct = FormatTools.getZCTCoords(dimOrder[i][p],
sizeZ[i][p], sizeC[i][p], sizeT[i][p], len, j);
System.out.print(".");
images[i][p][j] = new BufferedImage(
sizeX[i][p], sizeY[i][p], BufferedImage.TYPE_BYTE_GRAY);
Graphics2D g = images[i][p][j].createGraphics();
// draw gradient
boolean even = ipNum % 2 == 0;
int type = ipNum / 2;
if (even) {
// draw vertical gradient for even-numbered pixelses
for (int y=0; y<sizeY[i][p]; y++) {
int v = gradient(type, y, sizeY[i][p]);
g.setColor(new Color(v, v, v));
g.drawLine(0, y, sizeX[i][p], y);
}
}
else {
// draw horizontal gradient for odd-numbered pixelses
for (int x=0; x<sizeX[i][p]; x++) {
int v = gradient(type, x, sizeX[i][p]);
g.setColor(new Color(v, v, v));
g.drawLine(x, 0, x, sizeY[i][p]);
}
}
// build list of text lines from planar information
Vector lines = new Vector();
Font font = g.getFont();
lines.add(new TextLine(name, font.deriveFont(32f), 5, -5));
lines.add(new TextLine(sizeX[i][p] + " x " + sizeY[i][p],
font.deriveFont(Font.ITALIC, 16f), 20, 10));
lines.add(new TextLine(dimOrder[i][p],
font.deriveFont(Font.ITALIC, 14f), 30, 5));
int space = 5;
if (numImages > 1) {
lines.add(new TextLine("Image #" + (i + 1) + "/" + numImages,
font, 20, space));
space = 2;
}
if (numPixels[i] > 1) {
lines.add(new TextLine("Pixels #" + (p + 1) + "/" + numPixels[i],
font, 20, space));
space = 2;
}
if (sizeZ[i][p] > 1) {
lines.add(new TextLine("Focal plane = " +
(zct[0] + 1) + "/" + sizeZ[i][p], font, 20, space));
space = 2;
}
if (sizeC[i][p] > 1) {
lines.add(new TextLine("Channel = " +
(zct[1] + 1) + "/" + sizeC[i][p], font, 20, space));
space = 2;
}
if (sizeT[i][p] > 1) {
lines.add(new TextLine("Time point = " +
(zct[2] + 1) + "/" + sizeT[i][p], font, 20, space));
space = 2;
}
// draw text lines to image
g.setColor(Color.white);
int yoff = 0;
for (int l=0; l<lines.size(); l++) {
TextLine text = (TextLine) lines.get(l);
g.setFont(text.font);
Rectangle2D r = g.getFont().getStringBounds(
text.line, g.getFontRenderContext());
yoff += r.getHeight() + text.ypad;
g.drawString(text.line, text.xoff, yoff);
}
g.dispose();
}
System.out.println();
}
}
System.out.println("Writing output files");
// determine filename for each image plane
String[][][] filenames = new String[numImages][][];
Hashtable lastHash = new Hashtable();
boolean[][][] last = new boolean[numImages][][];
Hashtable ifdTotal = new Hashtable();
Hashtable firstZ = new Hashtable();
Hashtable firstC = new Hashtable();
Hashtable firstT = new Hashtable();
StringBuffer sb = new StringBuffer();
for (int i=0; i<numImages; i++) {
filenames[i] = new String[numPixels[i]][];
last[i] = new boolean[numPixels[i]][];
for (int p=0; p<numPixels[i]; p++) {
int len = images[i][p].length;
filenames[i][p] = new String[len];
last[i][p] = new boolean[len];
for (int j=0; j<len; j++) {
sb.append(name);
if (!allI && numImages > 1) sb.append("_image" + (i + 1));
if (!allP && numPixels[i] > 1) sb.append("_pixels" + (p + 1));
int[] zct = FormatTools.getZCTCoords(dimOrder[i][p],
sizeZ[i][p], sizeC[i][p], sizeT[i][p], len, j);
if (!allZ && sizeZ[i][p] > 1) sb.append("_Z" + (zct[0] + 1));
if (!allC && sizeC[i][p] > 1) sb.append("_C" + (zct[1] + 1));
if (!allT && sizeT[i][p] > 1) sb.append("_T" + (zct[2] + 1));
sb.append(".ome.tif");
filenames[i][p][j] = sb.toString();
sb.setLength(0);
last[i][p][j] = true;
// update last flag for this filename
String key = filenames[i][p][j];
ImageIndex index = (ImageIndex) lastHash.get(key);
if (index != null) {
last[index.image][index.pixels][index.plane] = false;
}
lastHash.put(key, new ImageIndex(i, p, j));
// update IFD count for this filename
Integer total = (Integer) ifdTotal.get(key);
if (total == null) total = new Integer(1);
else total = new Integer(total.intValue() + 1);
ifdTotal.put(key, total);
// update FirstZ, FirstC and FirstT values for this filename
if (!allZ && sizeZ[i][p] > 1) {
firstZ.put(filenames[i][p][j], new Integer(zct[0]));
}
if (!allC && sizeC[i][p] > 1) {
firstC.put(filenames[i][p][j], new Integer(zct[1]));
}
if (!allT && sizeT[i][p] > 1) {
firstT.put(filenames[i][p][j], new Integer(zct[2]));
}
}
}
}
// build OME-XML block
// CreationDate is required; initialize a default value (current time)
// use ISO 8601 dateTime format (e.g., 1988-04-07T18:39:09)
sb.setLength(0);
Calendar now = Calendar.getInstance();
int year = now.get(Calendar.YEAR);
int month = now.get(Calendar.MONTH);
int day = now.get(Calendar.DAY_OF_MONTH);
int hour = now.get(Calendar.HOUR_OF_DAY);
int min = now.get(Calendar.MINUTE);
int sec = now.get(Calendar.SECOND);
sb.append(year);
sb.append("-");
if (month < 9) sb.append("0");
sb.append(month + 1);
sb.append("-");
if (day < 10) sb.append("0");
sb.append(day);
sb.append("T");
if (hour < 10) sb.append("0");
sb.append(hour);
sb.append(":");
if (min < 10) sb.append("0");
sb.append(min);
sb.append(":");
if (sec < 10) sb.append("0");
sb.append(sec);
String creationDate = sb.toString();
sb.setLength(0);
sb.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>" +
"<!-- Warning: this comment is an OME-XML metadata block, which " +
"contains crucial dimensional parameters and other important metadata. " +
"Please edit cautiously (if at all), and back up the original data " +
"before doing so. For more information, see the OME-TIFF web site: " +
"http://loci.wisc.edu/ome/ome-tiff.html. --><OME " +
"xmlns=\"http://www.openmicroscopy.org/XMLschemas/OME/FC/ome.xsd\" " +
"xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" " +
"xsi:schemaLocation=\"" +
"http://www.openmicroscopy.org/XMLschemas/OME/FC/ome.xsd\">");
for (int i=0; i<numImages; i++) {
sb.append("<Image " +
"ID=\"openmicroscopy.org:Image:" + (i + 1) + "\" " +
"Name=\"" + name + "\" " +
"DefaultPixels=\"openmicroscopy.org:Pixels:" + (i + 1) + "-1\">" +
"<CreationDate>" + creationDate + "</CreationDate>");
for (int p=0; p<numPixels[i]; p++) {
sb.append("<Pixels " +
"ID=\"openmicroscopy.org:Pixels:" + (i + 1) + "-" + (p + 1) + "\" " +
"DimensionOrder=\"" + dimOrder[i][p] + "\" " +
"PixelType=\"uint8\" " +
"BigEndian=\"true\" " +
"SizeX=\"" + sizeX[i][p] + "\" " +
"SizeY=\"" + sizeY[i][p] + "\" " +
"SizeZ=\"" + sizeZ[i][p] + "\" " +
"SizeC=\"" + sizeC[i][p] + "\" " +
"SizeT=\"" + sizeT[i][p] + "\">" +
"TIFF_DATA_IMAGE_" + i + "_PIXELS_" + p + // placeholder
"</Pixels>");
}
sb.append("</Image>");
}
sb.append("</OME>");
String xmlTemplate = sb.toString();
TiffWriter out = new TiffWriter();
for (int i=0; i<numImages; i++) {
System.out.println(" Image #" + (i + 1) + ":");
for (int p=0; p<numPixels[i]; p++) {
System.out.println(" Pixels #" + (p + 1) + " - " +
sizeX[i][p] + " x " + sizeY[i][p] + ", " +
sizeZ[i][p] + "Z " + sizeC[i][p] + "C " + sizeT[i][p] + "T:");
int len = images[i][p].length;
for (int j=0; j<len; j++) {
int[] zct = FormatTools.getZCTCoords(dimOrder[i][p],
sizeZ[i][p], sizeC[i][p], sizeT[i][p], len, j);
System.out.println(" " +
"Z" + zct[0] + " C" + zct[1] + " T" + zct[2] +
" -> " + filenames[i][p][j] + (last[i][p][j] ? "*" : ""));
out.setId(filenames[i][p][j]);
// write comment stub, to be overwritten later
Hashtable ifdHash = new Hashtable();
TiffTools.putIFDValue(ifdHash, TiffTools.IMAGE_DESCRIPTION, "");
out.saveImage(images[i][p][j], ifdHash, last[i][p][j]);
if (last[i][p][j]) {
// inject OME-XML block
String xml = xmlTemplate;
String key = filenames[i][p][j];
Integer fzObj = (Integer) firstZ.get(key);
Integer fcObj = (Integer) firstC.get(key);
Integer ftObj = (Integer) firstT.get(key);
int fz = fzObj == null ? 0 : fzObj.intValue();
int fc = fcObj == null ? 0 : fcObj.intValue();
int ft = ftObj == null ? 0 : ftObj.intValue();
Integer total = (Integer) ifdTotal.get(key);
if (!scramble) total = null;
for (int ii=0; ii<numImages; ii++) {
for (int pp=0; pp<numPixels[ii]; pp++) {
String pattern = "TIFF_DATA_IMAGE_" + ii + "_PIXELS_" + pp;
if (!allI && ii != i || !allP && pp != p) {
// current Pixels is not part of this file
xml = xml.replaceFirst(pattern,
tiffData(0, 0, 0, 0, 0, dimOrder[ii][pp],
sizeZ[ii][pp], sizeC[ii][pp], sizeT[ii][pp], total));
continue;
}
if (allP) {
int ifd;
if (allI) {
// all Images in one file; need to use global offset
ifd = globalOffsets[ii][pp];
}
else { // ii == i
// one Image per file; use local offset
ifd = localOffsets[ii][pp];
}
int num = images[ii][pp].length;
if ((!allI || numImages == 1) && numPixels[i] == 1) {
// only one Pixels in this file; don't need IFD/NumPlanes
ifd = 0;
num = -1;
}
xml = xml.replaceFirst(pattern,
tiffData(ifd, num, 0, 0, 0, dimOrder[ii][pp],
sizeZ[ii][pp], sizeC[ii][pp], sizeT[ii][pp], total));
}
else { // pp == p
xml = xml.replaceFirst(pattern,
tiffData(0, -1, fz, fc, ft, dimOrder[ii][pp],
sizeZ[ii][pp], sizeC[ii][pp], sizeT[ii][pp], total));
}
}
}
TiffTools.overwriteComment(filenames[i][p][j], xml);
}
}
}
}
}
| public static void main(String[] args) throws FormatException, IOException {
boolean usage = false;
// parse command line arguments
String name = null;
String dist = null;
boolean scramble = false;
int numImages = 0;
int[] numPixels = null;
int[][] sizeX = null, sizeY = null;
int[][] sizeZ = null, sizeC = null, sizeT = null;
String[][] dimOrder = null;
if (args == null || args.length < 2) usage = true;
else {
name = args[0];
dist = args[1].toLowerCase();
scramble = args.length > 2 && args[2].equalsIgnoreCase("-scramble");
int startIndex = scramble ? 3 : 2;
// count number of images
int ndx = startIndex;
while (ndx < args.length) {
int numPix = Integer.parseInt(args[ndx]);
ndx += 1 + 6 * numPix;
numImages++;
}
// parse pixels's dimensional information
if (ndx > args.length) usage = true;
else {
numPixels = new int[numImages];
sizeX = new int[numImages][];
sizeY = new int[numImages][];
sizeZ = new int[numImages][];
sizeC = new int[numImages][];
sizeT = new int[numImages][];
dimOrder = new String[numImages][];
ndx = startIndex;
for (int i=0; i<numImages; i++) {
numPixels[i] = Integer.parseInt(args[ndx++]);
sizeX[i] = new int[numPixels[i]];
sizeY[i] = new int[numPixels[i]];
sizeZ[i] = new int[numPixels[i]];
sizeC[i] = new int[numPixels[i]];
sizeT[i] = new int[numPixels[i]];
dimOrder[i] = new String[numPixels[i]];
for (int p=0; p<numPixels[i]; p++) {
sizeX[i][p] = Integer.parseInt(args[ndx++]);
sizeY[i][p] = Integer.parseInt(args[ndx++]);
sizeZ[i][p] = Integer.parseInt(args[ndx++]);
sizeC[i][p] = Integer.parseInt(args[ndx++]);
sizeT[i][p] = Integer.parseInt(args[ndx++]);
dimOrder[i][p] = args[ndx++].toUpperCase();
}
}
}
}
if (usage) {
System.out.println(
"Usage: java MakeTestOmeTiff name dist [-scramble]");
System.out.println(" image1_NumPixels");
System.out.println(" image1_pixels1_SizeX " +
"image1_pixels1_SizeY image1_pixels1_SizeZ");
System.out.println(" image1_pixels1_SizeC " +
"image1_pixels1_SizeT image1_pixels1_DimOrder");
System.out.println(" image1_pixels2_SizeX " +
"image1_pixels2_SizeY image1_pixels2_SizeZ");
System.out.println(" image1_pixels2_SizeC " +
"image1_pixels2_SizeT image1_pixels2_DimOrder");
System.out.println(" [...]");
System.out.println(" image2_NumPixels");
System.out.println(" image2_pixels1_SizeX " +
"image2_pixels1_SizeY image1_pixels1_SizeZ");
System.out.println(" image2_pixels1_SizeC " +
"image2_pixels1_SizeT image1_pixels1_DimOrder");
System.out.println(" image2_pixels2_SizeX " +
"image2_pixels2_SizeY image1_pixels2_SizeZ");
System.out.println(" image2_pixels2_SizeC " +
"image2_pixels2_SizeT image1_pixels2_DimOrder");
System.out.println(" [...]");
System.out.println(" [...]");
System.out.println();
System.out.println(" name: prefix for filenames");
System.out.println(" dist: code for how to distribute across files:");
System.out.println(" ipzct = all Images + Pixels in one file");
System.out.println(" pzct = each Image in its own file");
System.out.println(" zct = each Pixels in its own file");
System.out.println(" zc = all Z + C positions per file");
System.out.println(" zt = all Z + T positions per file");
System.out.println(" ct = all C + T positions per file");
System.out.println(" z = all Z positions per file");
System.out.println(" c = all C positions per file");
System.out.println(" t = all T positions per file");
System.out.println(" x = single plane per file");
System.out.println(" -scramble: randomizes IFD ordering");
System.out.println(" image*_pixels*_SizeX: width of image planes");
System.out.println(" image*_pixels*_SizeY: height of image planes");
System.out.println(" image*_pixels*_SizeZ: number of focal planes");
System.out.println(" image*_pixels*_SizeC: number of channels");
System.out.println(" image*_pixels*_SizeT: number of time points");
System.out.println(" image*_pixels*_DimOrder: planar ordering:");
System.out.println(" XYZCT, XYZTC, XYCZT, XYCTZ, XYTZC, or XYTCZ");
System.out.println();
System.out.println("Example:");
System.out.println(" java MakeTestOmeTiff test ipzct \\");
System.out.println(" 2 431 555 1 2 7 XYTCZ \\");
System.out.println(" 348 461 2 1 6 XYZTC \\");
System.out.println(" 1 517 239 5 3 4 XYCZT");
System.exit(1);
}
if (!dist.equals("ipzct") && !dist.equals("pzct") && !dist.equals("zct") &&
!dist.equals("zc") && !dist.equals("zt") && !dist.equals("ct") &&
!dist.equals("z") && !dist.equals("c") && !dist.equals("t") &&
!dist.equals("x"))
{
System.out.println("Invalid dist value: " + dist);
System.exit(2);
}
boolean allI = dist.indexOf("i") >= 0;
boolean allP = dist.indexOf("p") >= 0;
boolean allZ = dist.indexOf("z") >= 0;
boolean allC = dist.indexOf("c") >= 0;
boolean allT = dist.indexOf("t") >= 0;
BufferedImage[][][] images = new BufferedImage[numImages][][];
int[][] globalOffsets = new int[numImages][]; // IFD offsets across Images
int[][] localOffsets = new int[numImages][]; // IFD offsets per Image
int globalOffset = 0, localOffset = 0;
for (int i=0; i<numImages; i++) {
images[i] = new BufferedImage[numPixels[i]][];
globalOffsets[i] = new int[numPixels[i]];
localOffsets[i] = new int[numPixels[i]];
localOffset = 0;
for (int p=0; p<numPixels[i]; p++) {
int len = sizeZ[i][p] * sizeC[i][p] * sizeT[i][p];
images[i][p] = new BufferedImage[len];
globalOffsets[i][p] = globalOffset;
globalOffset += len;
localOffsets[i][p] = localOffset;
localOffset += len;
}
}
System.out.println("Generating image planes");
for (int i=0, ipNum=0; i<numImages; i++) {
System.out.println(" Image #" + (i + 1) + ":");
for (int p=0; p<numPixels[i]; p++, ipNum++) {
System.out.print(" Pixels #" + (p + 1) + " - " +
sizeX[i][p] + " x " + sizeY[i][p] + ", " +
sizeZ[i][p] + "Z " + sizeC[i][p] + "C " + sizeT[i][p] + "T");
int len = images[i][p].length;
for (int j=0; j<len; j++) {
int[] zct = FormatTools.getZCTCoords(dimOrder[i][p],
sizeZ[i][p], sizeC[i][p], sizeT[i][p], len, j);
System.out.print(".");
images[i][p][j] = new BufferedImage(
sizeX[i][p], sizeY[i][p], BufferedImage.TYPE_BYTE_GRAY);
Graphics2D g = images[i][p][j].createGraphics();
// draw gradient
boolean even = ipNum % 2 == 0;
int type = ipNum / 2;
if (even) {
// draw vertical gradient for even-numbered pixelses
for (int y=0; y<sizeY[i][p]; y++) {
int v = gradient(type, y, sizeY[i][p]);
g.setColor(new Color(v, v, v));
g.drawLine(0, y, sizeX[i][p], y);
}
}
else {
// draw horizontal gradient for odd-numbered pixelses
for (int x=0; x<sizeX[i][p]; x++) {
int v = gradient(type, x, sizeX[i][p]);
g.setColor(new Color(v, v, v));
g.drawLine(x, 0, x, sizeY[i][p]);
}
}
// build list of text lines from planar information
Vector lines = new Vector();
Font font = g.getFont();
lines.add(new TextLine(name, font.deriveFont(32f), 5, -5));
lines.add(new TextLine(sizeX[i][p] + " x " + sizeY[i][p],
font.deriveFont(Font.ITALIC, 16f), 20, 10));
lines.add(new TextLine(dimOrder[i][p],
font.deriveFont(Font.ITALIC, 14f), 30, 5));
int space = 5;
if (numImages > 1) {
lines.add(new TextLine("Image #" + (i + 1) + "/" + numImages,
font, 20, space));
space = 2;
}
if (numPixels[i] > 1) {
lines.add(new TextLine("Pixels #" + (p + 1) + "/" + numPixels[i],
font, 20, space));
space = 2;
}
if (sizeZ[i][p] > 1) {
lines.add(new TextLine("Focal plane = " +
(zct[0] + 1) + "/" + sizeZ[i][p], font, 20, space));
space = 2;
}
if (sizeC[i][p] > 1) {
lines.add(new TextLine("Channel = " +
(zct[1] + 1) + "/" + sizeC[i][p], font, 20, space));
space = 2;
}
if (sizeT[i][p] > 1) {
lines.add(new TextLine("Time point = " +
(zct[2] + 1) + "/" + sizeT[i][p], font, 20, space));
space = 2;
}
// draw text lines to image
g.setColor(Color.white);
int yoff = 0;
for (int l=0; l<lines.size(); l++) {
TextLine text = (TextLine) lines.get(l);
g.setFont(text.font);
Rectangle2D r = g.getFont().getStringBounds(
text.line, g.getFontRenderContext());
yoff += r.getHeight() + text.ypad;
g.drawString(text.line, text.xoff, yoff);
}
g.dispose();
}
System.out.println();
}
}
System.out.println("Writing output files");
// determine filename for each image plane
String[][][] filenames = new String[numImages][][];
Hashtable lastHash = new Hashtable();
boolean[][][] last = new boolean[numImages][][];
Hashtable ifdTotal = new Hashtable();
Hashtable firstZ = new Hashtable();
Hashtable firstC = new Hashtable();
Hashtable firstT = new Hashtable();
StringBuffer sb = new StringBuffer();
for (int i=0; i<numImages; i++) {
filenames[i] = new String[numPixels[i]][];
last[i] = new boolean[numPixels[i]][];
for (int p=0; p<numPixels[i]; p++) {
int len = images[i][p].length;
filenames[i][p] = new String[len];
last[i][p] = new boolean[len];
for (int j=0; j<len; j++) {
sb.append(name);
if (!allI && numImages > 1) sb.append("_image" + (i + 1));
if (!allP && numPixels[i] > 1) sb.append("_pixels" + (p + 1));
int[] zct = FormatTools.getZCTCoords(dimOrder[i][p],
sizeZ[i][p], sizeC[i][p], sizeT[i][p], len, j);
if (!allZ && sizeZ[i][p] > 1) sb.append("_Z" + (zct[0] + 1));
if (!allC && sizeC[i][p] > 1) sb.append("_C" + (zct[1] + 1));
if (!allT && sizeT[i][p] > 1) sb.append("_T" + (zct[2] + 1));
sb.append(".ome.tif");
filenames[i][p][j] = sb.toString();
sb.setLength(0);
last[i][p][j] = true;
// update last flag for this filename
String key = filenames[i][p][j];
ImageIndex index = (ImageIndex) lastHash.get(key);
if (index != null) {
last[index.image][index.pixels][index.plane] = false;
}
lastHash.put(key, new ImageIndex(i, p, j));
// update IFD count for this filename
Integer total = (Integer) ifdTotal.get(key);
if (total == null) total = new Integer(1);
else total = new Integer(total.intValue() + 1);
ifdTotal.put(key, total);
// update FirstZ, FirstC and FirstT values for this filename
if (!allZ && sizeZ[i][p] > 1) {
firstZ.put(filenames[i][p][j], new Integer(zct[0]));
}
if (!allC && sizeC[i][p] > 1) {
firstC.put(filenames[i][p][j], new Integer(zct[1]));
}
if (!allT && sizeT[i][p] > 1) {
firstT.put(filenames[i][p][j], new Integer(zct[2]));
}
}
}
}
// build OME-XML block
// CreationDate is required; initialize a default value (current time)
// use ISO 8601 dateTime format (e.g., 1988-04-07T18:39:09)
sb.setLength(0);
Calendar now = Calendar.getInstance();
int year = now.get(Calendar.YEAR);
int month = now.get(Calendar.MONTH);
int day = now.get(Calendar.DAY_OF_MONTH);
int hour = now.get(Calendar.HOUR_OF_DAY);
int min = now.get(Calendar.MINUTE);
int sec = now.get(Calendar.SECOND);
sb.append(year);
sb.append("-");
if (month < 9) sb.append("0");
sb.append(month + 1);
sb.append("-");
if (day < 10) sb.append("0");
sb.append(day);
sb.append("T");
if (hour < 10) sb.append("0");
sb.append(hour);
sb.append(":");
if (min < 10) sb.append("0");
sb.append(min);
sb.append(":");
if (sec < 10) sb.append("0");
sb.append(sec);
String creationDate = sb.toString();
sb.setLength(0);
sb.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>" +
"<!-- Warning: this comment is an OME-XML metadata block, which " +
"contains crucial dimensional parameters and other important metadata. " +
"Please edit cautiously (if at all), and back up the original data " +
"before doing so. For more information, see the OME-TIFF web site: " +
"http://loci.wisc.edu/ome/ome-tiff.html. --><OME " +
"xmlns=\"http://www.openmicroscopy.org/XMLschemas/OME/FC/ome.xsd\" " +
"xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" " +
"xsi:schemaLocation=\"" +
"http://www.openmicroscopy.org/XMLschemas/OME/FC/ome.xsd " +
"http://www.openmicroscopy.org/XMLschemas/OME/FC/ome.xsd\">");
for (int i=0; i<numImages; i++) {
sb.append("<Image " +
"ID=\"openmicroscopy.org:Image:" + (i + 1) + "\" " +
"Name=\"" + name + "\" " +
"DefaultPixels=\"openmicroscopy.org:Pixels:" + (i + 1) + "-1\">" +
"<CreationDate>" + creationDate + "</CreationDate>");
for (int p=0; p<numPixels[i]; p++) {
sb.append("<Pixels " +
"ID=\"openmicroscopy.org:Pixels:" + (i + 1) + "-" + (p + 1) + "\" " +
"DimensionOrder=\"" + dimOrder[i][p] + "\" " +
"PixelType=\"uint8\" " +
"BigEndian=\"true\" " +
"SizeX=\"" + sizeX[i][p] + "\" " +
"SizeY=\"" + sizeY[i][p] + "\" " +
"SizeZ=\"" + sizeZ[i][p] + "\" " +
"SizeC=\"" + sizeC[i][p] + "\" " +
"SizeT=\"" + sizeT[i][p] + "\">" +
"TIFF_DATA_IMAGE_" + i + "_PIXELS_" + p + // placeholder
"</Pixels>");
}
sb.append("</Image>");
}
sb.append("</OME>");
String xmlTemplate = sb.toString();
TiffWriter out = new TiffWriter();
for (int i=0; i<numImages; i++) {
System.out.println(" Image #" + (i + 1) + ":");
for (int p=0; p<numPixels[i]; p++) {
System.out.println(" Pixels #" + (p + 1) + " - " +
sizeX[i][p] + " x " + sizeY[i][p] + ", " +
sizeZ[i][p] + "Z " + sizeC[i][p] + "C " + sizeT[i][p] + "T:");
int len = images[i][p].length;
for (int j=0; j<len; j++) {
int[] zct = FormatTools.getZCTCoords(dimOrder[i][p],
sizeZ[i][p], sizeC[i][p], sizeT[i][p], len, j);
System.out.println(" " +
"Z" + zct[0] + " C" + zct[1] + " T" + zct[2] +
" -> " + filenames[i][p][j] + (last[i][p][j] ? "*" : ""));
out.setId(filenames[i][p][j]);
// write comment stub, to be overwritten later
Hashtable ifdHash = new Hashtable();
TiffTools.putIFDValue(ifdHash, TiffTools.IMAGE_DESCRIPTION, "");
out.saveImage(images[i][p][j], ifdHash, last[i][p][j]);
if (last[i][p][j]) {
// inject OME-XML block
String xml = xmlTemplate;
String key = filenames[i][p][j];
Integer fzObj = (Integer) firstZ.get(key);
Integer fcObj = (Integer) firstC.get(key);
Integer ftObj = (Integer) firstT.get(key);
int fz = fzObj == null ? 0 : fzObj.intValue();
int fc = fcObj == null ? 0 : fcObj.intValue();
int ft = ftObj == null ? 0 : ftObj.intValue();
Integer total = (Integer) ifdTotal.get(key);
if (!scramble) total = null;
for (int ii=0; ii<numImages; ii++) {
for (int pp=0; pp<numPixels[ii]; pp++) {
String pattern = "TIFF_DATA_IMAGE_" + ii + "_PIXELS_" + pp;
if (!allI && ii != i || !allP && pp != p) {
// current Pixels is not part of this file
xml = xml.replaceFirst(pattern,
tiffData(0, 0, 0, 0, 0, dimOrder[ii][pp],
sizeZ[ii][pp], sizeC[ii][pp], sizeT[ii][pp], total));
continue;
}
if (allP) {
int ifd;
if (allI) {
// all Images in one file; need to use global offset
ifd = globalOffsets[ii][pp];
}
else { // ii == i
// one Image per file; use local offset
ifd = localOffsets[ii][pp];
}
int num = images[ii][pp].length;
if ((!allI || numImages == 1) && numPixels[i] == 1) {
// only one Pixels in this file; don't need IFD/NumPlanes
ifd = 0;
num = -1;
}
xml = xml.replaceFirst(pattern,
tiffData(ifd, num, 0, 0, 0, dimOrder[ii][pp],
sizeZ[ii][pp], sizeC[ii][pp], sizeT[ii][pp], total));
}
else { // pp == p
xml = xml.replaceFirst(pattern,
tiffData(0, -1, fz, fc, ft, dimOrder[ii][pp],
sizeZ[ii][pp], sizeC[ii][pp], sizeT[ii][pp], total));
}
}
}
TiffTools.overwriteComment(filenames[i][p][j], xml);
}
}
}
}
}
|
diff --git a/plugins/darep/plugins/UnchangedChecker.java b/plugins/darep/plugins/UnchangedChecker.java
index 572d77a..f317682 100644
--- a/plugins/darep/plugins/UnchangedChecker.java
+++ b/plugins/darep/plugins/UnchangedChecker.java
@@ -1,46 +1,46 @@
package darep.plugins;
import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import darep.server.CompletenessChecker;
public class UnchangedChecker implements CompletenessChecker{
private int quietPeriodInSeconds;
@Override
public File[] getCompletedFiles(File directory) {
File files[] = directory.listFiles();
ArrayList<File> completedFiles = new ArrayList<File>(files.length);
long time = new Date().getTime();
for(File f:files) {
if(f.lastModified() <= time - quietPeriodInSeconds * 1000) {
completedFiles.add(f);
}
}
return completedFiles.toArray(new File[0]);
}
@Override
public void setProperty(String key, String value)
throws IllegalArgumentException {
String expectedKey = "quiet-period-in-seconds";
if(key.equals(expectedKey) == false) {
throw new IllegalArgumentException("UnchangedChecker only accepts the property " + expectedKey);
}
- if(value == null || value == "") {
+ if(value == null || value.trim().length() == 0) {
throw new IllegalArgumentException("value for " + key + " can not be null or empty");
}
try {
quietPeriodInSeconds = Integer.parseInt(value);
} catch(Exception e) {
throw new IllegalArgumentException(key + " must be a integer", e);
}
if(quietPeriodInSeconds <= 0) {
throw new IllegalArgumentException(key + " must be greater than 0");
}
}
}
| true | true | public void setProperty(String key, String value)
throws IllegalArgumentException {
String expectedKey = "quiet-period-in-seconds";
if(key.equals(expectedKey) == false) {
throw new IllegalArgumentException("UnchangedChecker only accepts the property " + expectedKey);
}
if(value == null || value == "") {
throw new IllegalArgumentException("value for " + key + " can not be null or empty");
}
try {
quietPeriodInSeconds = Integer.parseInt(value);
} catch(Exception e) {
throw new IllegalArgumentException(key + " must be a integer", e);
}
if(quietPeriodInSeconds <= 0) {
throw new IllegalArgumentException(key + " must be greater than 0");
}
}
| public void setProperty(String key, String value)
throws IllegalArgumentException {
String expectedKey = "quiet-period-in-seconds";
if(key.equals(expectedKey) == false) {
throw new IllegalArgumentException("UnchangedChecker only accepts the property " + expectedKey);
}
if(value == null || value.trim().length() == 0) {
throw new IllegalArgumentException("value for " + key + " can not be null or empty");
}
try {
quietPeriodInSeconds = Integer.parseInt(value);
} catch(Exception e) {
throw new IllegalArgumentException(key + " must be a integer", e);
}
if(quietPeriodInSeconds <= 0) {
throw new IllegalArgumentException(key + " must be greater than 0");
}
}
|
diff --git a/Projects/TLDR/src/com/datastore/TaskDatastore.java b/Projects/TLDR/src/com/datastore/TaskDatastore.java
index 4eb30f6..a32cfc3 100644
--- a/Projects/TLDR/src/com/datastore/TaskDatastore.java
+++ b/Projects/TLDR/src/com/datastore/TaskDatastore.java
@@ -1,262 +1,262 @@
package com.datastore;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import android.nfc.FormatException;
import android.os.AsyncTask;
import android.util.Log;
import com.google.api.client.extensions.android.http.AndroidHttp;
import com.google.api.client.googleapis.extensions.android.gms.auth.GoogleAccountCredential;
import com.google.api.client.json.gson.GsonFactory;
import com.tldr.gamelogic.GoalStructure;
import com.tldr.gamelogic.GoalStructureFactory;
import com.tldr.goalendpoint.Goalendpoint;
import com.tldr.goalendpoint.model.CollectionResponseGoal;
import com.tldr.goalendpoint.model.Goal;
import com.tldr.taskendpoint.Taskendpoint;
import com.tldr.taskendpoint.model.CollectionResponseTask;
import com.tldr.taskendpoint.model.Task;
import com.tldr.tools.CloudEndpointUtils;
import com.tldr.tools.JsonParser;
/**
* @author manuschmanu
* This Datastore handles access to Tasks and Goals!
*/
public class TaskDatastore extends BaseDatastore {
Taskendpoint service;
Goalendpoint goal_service;
public TaskDatastore(DatastoreResultHandler context, GoogleAccountCredential credential) {
super(context);
Taskendpoint.Builder builder = new Taskendpoint.Builder(
AndroidHttp.newCompatibleTransport(), new GsonFactory(),
credential);
service = CloudEndpointUtils.updateBuilder(builder).build();
Goalendpoint.Builder goal_builder = new Goalendpoint.Builder(AndroidHttp.newCompatibleTransport(), new GsonFactory(), credential);
goal_service = CloudEndpointUtils.updateBuilder(goal_builder).build();
}
public void createFakeTasks(){
new CreateFakeTasksTask().execute();
}
public void getNearbyTasks(){
new GetNearbyTasksTask().execute();
}
public void getGoalsForTask(Task t){
new GetGoalsTask().execute();
}
private class CreateFakeTasksTask extends
AsyncTask<Void, Void, Void> {
@Override
protected Void doInBackground(Void... v) {
try {
// GoalStructure gs_t1 = new GoalStructure();
// GoalStructure gs_t2= new GoalStructure();
// GoalStructure gs_t3= new GoalStructure();
// GoalStructure gs_t4 = new GoalStructure();
// List<GoalStructure> gs_polyline_t4;
// GoalStructure gs1_tDemo = new GoalStructure();
// GoalStructure gs2_tDemo = new GoalStructure();
// GoalStructure two_2conditions = new GoalStructure();
GoalStructure gs_e2a = new GoalStructure();
GoalStructure gs_e2b = new GoalStructure();
GoalStructure gs_e1a = new GoalStructure();
GoalStructure gs_e1c = new GoalStructure();
List<GoalStructure> gs_e1b_polyline;
// gs_t1.addBaseData("Fahre langsamer als 50km/h", "null").addCondition("Speed", "leq", "50").addReward("xp", "2000");
// gs_t2.addBaseData("Radiofrequenz an Ampel wechseln", "traffic_lights_entry").addCondition("Speed", "leq", "10").addCondition("radio_freq", "change", "null").addReward("xp", "4000");
// gs_t3.addBaseData("Schalte Warnblinklicht an Baustelle ein", "null").addCondition("hazards_light", "eq", "on").addReward("xp", "3000");
// gs_t4.addBaseData("Melde Stoppschilder", "stop_sign_entry").addCondition("handbreak", "eq", "on").addReward("xp", "1600");
// gs_polyline_t4 = GoalStructureFactory.generatePolyLineGoals("Fahre Route ab", "52.456114,13.295408;52.457742,13.298584;52.458605,13.303626;52.454512,13.299463;52.453806,13.2972;52.454434,13.295644;52.455676,13.294474", "xp", 100);
// gs1_tDemo.addBaseData("Schalte in den 1. Gang", "null").addCondition("CurrentGear", "eq", "1").addReward("xp", "2000");
// two_2conditions.addBaseData("Fahre 50km/h im 4 Gang.", "null").addCondition("CurrentGear", "eq", "4").addCondition("VehicleSpeed", "eqr", "50").addReward("xp", "2000");
gs_e2a.addBaseData("Parke!", "null").addCondition("handbreak", "eq", "on").addReward("xp", "1300");
gs_e2b.addBaseData("Schalte die Klimaanlage an!", "parking_space_entry").addCondition("aircondition", "eq", "on").addReward("xp", "1700");
- gs_e1a.addBaseData("Lade Agenten ein!", "null").addCondition("SeatBeltLock", "eq", "on").addReward("xp", "1000");
+ gs_e1a.addBaseData("Lade Agenten ein!", "null").addCondition("SeatBeltLock", "eq", "locked").addReward("xp", "1000");
gs_e1b_polyline = GoalStructureFactory.generatePolyLineGoals("Fahre Route ab", "52.52286,13.321506;52.522828,13.322027;52.521196,13.322357;52.520921,13.32137;52.519681,13.319739;52.517514,13.325061;52.515516,13.327936;52.516691,13.329395", "xp", 100);
- gs_e1c.addBaseData("Lade Agenten aus!", "null").addCondition("SeatBeltLock", "eq", "off").addReward("xp", "2000");
+ gs_e1c.addBaseData("Lade Agenten aus!", "null").addCondition("SeatBeltLock", "eq", "unlocked").addReward("xp", "2000");
try {
// String goal_t1= JsonParser.writeNewJsonGoalString(gs_t1.getJsonParse());
// String goal_t2= JsonParser.writeNewJsonGoalString(gs_t2.getJsonParse());
// String goal_t3= JsonParser.writeNewJsonGoalString(gs_t3.getJsonParse());
// String goal_t4= JsonParser.writeNewJsonGoalString(gs_t4.getJsonParse());
// String goal_demo= JsonParser.writeNewJsonGoalString(gs1_tDemo.getJsonParse());
// String goal_demo2= JsonParser.writeNewJsonGoalString(gs2_tDemo.getJsonParse());
// String two_conditions_str= JsonParser.writeNewJsonGoalString(two_2conditions.getJsonParse());
String g_e2a_str = JsonParser.writeNewJsonGoalString(gs_e2a.getJsonParse());
String g_e2b_str = JsonParser.writeNewJsonGoalString(gs_e2b.getJsonParse());
String g_e1a_str = JsonParser.writeNewJsonGoalString(gs_e1a.getJsonParse());
String g_e1c_str = JsonParser.writeNewJsonGoalString(gs_e1c.getJsonParse());
// Goal g_t1=goal_service.insertGoal(new Goal().setJsonString(goal_t1)).execute();
// Goal g_t2=goal_service.insertGoal(new Goal().setJsonString(goal_t2)).execute();
// Goal g_t3=goal_service.insertGoal(new Goal().setJsonString(goal_t3)).execute();
// Goal g_t4=goal_service.insertGoal(new Goal().setJsonString(goal_t4)).execute();
// Goal g1_demo=goal_service.insertGoal(new Goal().setJsonString(goal_demo)).execute();
// Goal g2_demo=goal_service.insertGoal(new Goal().setJsonString(goal_demo2)).execute();
// Goal two_conditions = goal_service.insertGoal(new Goal().setJsonString(two_conditions_str)).execute();
Goal g_e2a = goal_service.insertGoal(new Goal().setJsonString(g_e2a_str)).execute();
Goal g_e2b = goal_service.insertGoal(new Goal().setJsonString(g_e2b_str)).execute();
Goal g_e1a = goal_service.insertGoal(new Goal().setJsonString(g_e1a_str)).execute();
Goal g_e1c = goal_service.insertGoal(new Goal().setJsonString(g_e1c_str)).execute();
// List<Goal> gs_parsed_polyline_t4 = new ArrayList<Goal>();
// for(GoalStructure gs:gs_polyline_t4){
// gs_parsed_polyline_t4.add(goal_service.insertGoal(new Goal().setJsonString(JsonParser.writeNewJsonGoalString(gs.getJsonParse()))).execute());
// }
List<Goal> gs_parsed_e1b_polyline = new ArrayList<Goal>();
for(GoalStructure gs:gs_e1b_polyline){
gs_parsed_e1b_polyline.add(goal_service.insertGoal(new Goal().setJsonString(JsonParser.writeNewJsonGoalString(gs.getJsonParse()))).execute());
}
// List<Long> goals_t1= new ArrayList<Long>();
// List<Long> goals_t2= new ArrayList<Long>();
// List<Long> goals_t3= new ArrayList<Long>();
// List<Long> goals_t4= new ArrayList<Long>();
// List<Long> goals_demo= new ArrayList<Long>();
// List<Long> goals_two= new ArrayList<Long>();
List<Long> goals_ende1= new ArrayList<Long>();
List<Long> goals_ende2= new ArrayList<Long>();
// goals_t1.add(g_t1.getId());
// goals_t2.add(g_t2.getId());
// goals_t3.add(g_t3.getId());
// goals_t4.add(g_t4.getId());
// for(Goal g: gs_parsed_polyline_t4){
// goals_t4.add(g.getId());
// }
// goals_t4.add(g2_t4.getId());
// goals_demo.add(g1_demo.getId());
// goals_demo.add(g2_demo.getId());
// goals_two.add(two_conditions.getId());
goals_ende1.add(g_e1a.getId());
for(Goal g: gs_parsed_e1b_polyline){
goals_ende1.add(g.getId());
}
goals_ende1.add(g_e1c.getId());
goals_ende2.add(g_e2a.getId());
goals_ende2.add(g_e2b.getId());
// service.insertTask(new Task().setTitle("Observiere den Monbijoupark")
// .setDescription("Es wird von Autonomy Komplikationen am Monbijou Park berichtet."+
// "Umrunden Sie den Monbijou Park und melden Sie Unregelm����igkeiten. "+
// "Fahren sie nicht schneller als 50km/h um unentdeckt zu bleiben!")
// .setGeoLat(52.523702).setGeoLon(13.397588).setGoals(goals_t1)).execute();
// service.insertTask(new Task().setTitle("Sabotage")
// .setDescription("Versuche die Ampeln der Lindauer Allee unter unsere Kontrolle zu bringen."+
// "Fahren Sie dazu ��ber die Lindauer Allee und wechseln sie die Radiofrequenz, wenn Sie an einer Ampel stehen.")
// .setGeoLat(52.574211).setGeoLon(13.349095 ).setGoals(goals_t2)).execute();
// service.insertTask(new Task().setTitle("Untersuchung am Salzufer")
// .setDescription("Ein Informant hat uns mitgeteilt, dass eine oder mehrere Baustellen am Salzufer von der gegnerischen Fraktion sabotiert wurde."+
// "Fahren das Salzufer entlang und markieren Sie Baustellen durch kurzes Bet��tigen vom Warnblinker")
// .setGeoLat(52.518493).setGeoLon(13.321928).setGoals(goals_t3)).execute();
// service.insertTask(new Task().setTitle("Spuren der Vergangenheit")
// .setDescription("Angeblich existieren an der angegebenen Route noch Relikte aus vergangenen Tagen. "+
// "Melden Sie diese durch anziehen der Handbremse, während Sie davor stehen.")
// .setGeoLat(52.455669).setGeoLon(13.294496).setGoals(goals_t4)).execute();
// service.insertTask(new Task().setTitle("Echte Autonomie")
// .setDescription("Du wurdest von Autonomy abgekopselt. Vergewissere dich einer Autonomie in dem du die Funktionen deines Fahrzeuges selber kontrolierst.")
// .setGeoLat(52.436114).setGeoLon(13.285428).setGoals(goals_demo)).execute();
// service.insertTask(new Task().setTitle("Besuche den Großmeister")
// .setDescription("Der Großmeister des Ministy of Freedom will sich sehen. Reise zu ihm!")
// .setGeoLat(52.5753092766).setGeoLon(13.3530235291).setGoals(goals_demo)).execute();
// service.insertTask(new Task().setTitle("Reaktiviere die Alten")
// .setDescription("Viele potenzielle Indidivuen, die sich unserer Sache anschließen können leben in dieser Gegend. Reaktiviere sie aus diesem Dauerschlaf")
// .setGeoLat(52.5753192766).setGeoLon(13.3531235291).setGoals(goals_two)).execute();
service.insertTask(new Task().setTitle("Zeugenschutzprogram!")
.setDescription("Ihr habt es geschafft einen Anh�nger des Ministry of Freedom zum �berlaufen zu bringen. Dieser Zeuge hat wichtige Informationen und muss nun vor den Feind gesch�tzt werden. " +
"Sorge daf�r, dass er sicher aus der Reichweite des Ministries entkommt!")
.setGeoLat(52.52286).setGeoLon(13.321506).setGoals(goals_ende1)).execute();
service.insertTask(new Task().setTitle("Tauche unter!")
.setDescription("Bei deiner letzten Mission wurdest du von Agenten des Ministry of Freedom entdeckt und wirst seitdem verfolgt. Parke und verbirg deine Hitzesignatur um unterzutauchen!")
.setGeoLat(52.517837).setGeoLon(13.328733).setGoals(goals_ende2)).execute();
} catch (FormatException e) {
// TODO Auto-generated catch block
Log.e("TLDR", e.getMessage());
}
} catch (Exception e) {
Log.d("TLDR", e.getMessage(), e);
}
return null;
}
}
private class GetNearbyTasksTask extends
AsyncTask<Void, Void, CollectionResponseTask> {
@Override
protected CollectionResponseTask doInBackground(Void... v) {
CollectionResponseTask registeredUser = null;
try {
registeredUser = service.listTask()
.execute();
return registeredUser;
} catch (IOException e) {
Log.d("TLDR", e.getMessage(), e);
}
return registeredUser;
}
@Override
protected void onPostExecute(CollectionResponseTask tasks) {
if(context!=null)
if(tasks!=null)
context.handleRequestResult(REQUEST_TASK_FETCHNEARBY, tasks.getItems());
else
context.handleRequestResult(REQUEST_TASK_FETCHNEARBY, new ArrayList<Task>());
}
}
private class GetGoalsTask extends
AsyncTask<Void, Void, CollectionResponseGoal> {
@Override
protected CollectionResponseGoal doInBackground(Void... v) {
CollectionResponseGoal goals = null;
try {
goals = goal_service.listGoal()
.execute();
return goals;
} catch (IOException e) {
Log.d("TLDR", e.getMessage(), e);
}
return goals;
}
@Override
protected void onPostExecute(CollectionResponseGoal goals) {
if(context!=null)
context.handleRequestResult(REQUEST_TASK_FETCHGOALS, goals.getItems());
}
}
}
| false | true | protected Void doInBackground(Void... v) {
try {
// GoalStructure gs_t1 = new GoalStructure();
// GoalStructure gs_t2= new GoalStructure();
// GoalStructure gs_t3= new GoalStructure();
// GoalStructure gs_t4 = new GoalStructure();
// List<GoalStructure> gs_polyline_t4;
// GoalStructure gs1_tDemo = new GoalStructure();
// GoalStructure gs2_tDemo = new GoalStructure();
// GoalStructure two_2conditions = new GoalStructure();
GoalStructure gs_e2a = new GoalStructure();
GoalStructure gs_e2b = new GoalStructure();
GoalStructure gs_e1a = new GoalStructure();
GoalStructure gs_e1c = new GoalStructure();
List<GoalStructure> gs_e1b_polyline;
// gs_t1.addBaseData("Fahre langsamer als 50km/h", "null").addCondition("Speed", "leq", "50").addReward("xp", "2000");
// gs_t2.addBaseData("Radiofrequenz an Ampel wechseln", "traffic_lights_entry").addCondition("Speed", "leq", "10").addCondition("radio_freq", "change", "null").addReward("xp", "4000");
// gs_t3.addBaseData("Schalte Warnblinklicht an Baustelle ein", "null").addCondition("hazards_light", "eq", "on").addReward("xp", "3000");
// gs_t4.addBaseData("Melde Stoppschilder", "stop_sign_entry").addCondition("handbreak", "eq", "on").addReward("xp", "1600");
// gs_polyline_t4 = GoalStructureFactory.generatePolyLineGoals("Fahre Route ab", "52.456114,13.295408;52.457742,13.298584;52.458605,13.303626;52.454512,13.299463;52.453806,13.2972;52.454434,13.295644;52.455676,13.294474", "xp", 100);
// gs1_tDemo.addBaseData("Schalte in den 1. Gang", "null").addCondition("CurrentGear", "eq", "1").addReward("xp", "2000");
// two_2conditions.addBaseData("Fahre 50km/h im 4 Gang.", "null").addCondition("CurrentGear", "eq", "4").addCondition("VehicleSpeed", "eqr", "50").addReward("xp", "2000");
gs_e2a.addBaseData("Parke!", "null").addCondition("handbreak", "eq", "on").addReward("xp", "1300");
gs_e2b.addBaseData("Schalte die Klimaanlage an!", "parking_space_entry").addCondition("aircondition", "eq", "on").addReward("xp", "1700");
gs_e1a.addBaseData("Lade Agenten ein!", "null").addCondition("SeatBeltLock", "eq", "on").addReward("xp", "1000");
gs_e1b_polyline = GoalStructureFactory.generatePolyLineGoals("Fahre Route ab", "52.52286,13.321506;52.522828,13.322027;52.521196,13.322357;52.520921,13.32137;52.519681,13.319739;52.517514,13.325061;52.515516,13.327936;52.516691,13.329395", "xp", 100);
gs_e1c.addBaseData("Lade Agenten aus!", "null").addCondition("SeatBeltLock", "eq", "off").addReward("xp", "2000");
try {
// String goal_t1= JsonParser.writeNewJsonGoalString(gs_t1.getJsonParse());
// String goal_t2= JsonParser.writeNewJsonGoalString(gs_t2.getJsonParse());
// String goal_t3= JsonParser.writeNewJsonGoalString(gs_t3.getJsonParse());
// String goal_t4= JsonParser.writeNewJsonGoalString(gs_t4.getJsonParse());
// String goal_demo= JsonParser.writeNewJsonGoalString(gs1_tDemo.getJsonParse());
// String goal_demo2= JsonParser.writeNewJsonGoalString(gs2_tDemo.getJsonParse());
// String two_conditions_str= JsonParser.writeNewJsonGoalString(two_2conditions.getJsonParse());
String g_e2a_str = JsonParser.writeNewJsonGoalString(gs_e2a.getJsonParse());
String g_e2b_str = JsonParser.writeNewJsonGoalString(gs_e2b.getJsonParse());
String g_e1a_str = JsonParser.writeNewJsonGoalString(gs_e1a.getJsonParse());
String g_e1c_str = JsonParser.writeNewJsonGoalString(gs_e1c.getJsonParse());
// Goal g_t1=goal_service.insertGoal(new Goal().setJsonString(goal_t1)).execute();
// Goal g_t2=goal_service.insertGoal(new Goal().setJsonString(goal_t2)).execute();
// Goal g_t3=goal_service.insertGoal(new Goal().setJsonString(goal_t3)).execute();
// Goal g_t4=goal_service.insertGoal(new Goal().setJsonString(goal_t4)).execute();
// Goal g1_demo=goal_service.insertGoal(new Goal().setJsonString(goal_demo)).execute();
// Goal g2_demo=goal_service.insertGoal(new Goal().setJsonString(goal_demo2)).execute();
// Goal two_conditions = goal_service.insertGoal(new Goal().setJsonString(two_conditions_str)).execute();
Goal g_e2a = goal_service.insertGoal(new Goal().setJsonString(g_e2a_str)).execute();
Goal g_e2b = goal_service.insertGoal(new Goal().setJsonString(g_e2b_str)).execute();
Goal g_e1a = goal_service.insertGoal(new Goal().setJsonString(g_e1a_str)).execute();
Goal g_e1c = goal_service.insertGoal(new Goal().setJsonString(g_e1c_str)).execute();
// List<Goal> gs_parsed_polyline_t4 = new ArrayList<Goal>();
// for(GoalStructure gs:gs_polyline_t4){
// gs_parsed_polyline_t4.add(goal_service.insertGoal(new Goal().setJsonString(JsonParser.writeNewJsonGoalString(gs.getJsonParse()))).execute());
// }
List<Goal> gs_parsed_e1b_polyline = new ArrayList<Goal>();
for(GoalStructure gs:gs_e1b_polyline){
gs_parsed_e1b_polyline.add(goal_service.insertGoal(new Goal().setJsonString(JsonParser.writeNewJsonGoalString(gs.getJsonParse()))).execute());
}
// List<Long> goals_t1= new ArrayList<Long>();
// List<Long> goals_t2= new ArrayList<Long>();
// List<Long> goals_t3= new ArrayList<Long>();
// List<Long> goals_t4= new ArrayList<Long>();
// List<Long> goals_demo= new ArrayList<Long>();
// List<Long> goals_two= new ArrayList<Long>();
List<Long> goals_ende1= new ArrayList<Long>();
List<Long> goals_ende2= new ArrayList<Long>();
// goals_t1.add(g_t1.getId());
// goals_t2.add(g_t2.getId());
// goals_t3.add(g_t3.getId());
// goals_t4.add(g_t4.getId());
// for(Goal g: gs_parsed_polyline_t4){
// goals_t4.add(g.getId());
// }
// goals_t4.add(g2_t4.getId());
// goals_demo.add(g1_demo.getId());
// goals_demo.add(g2_demo.getId());
// goals_two.add(two_conditions.getId());
goals_ende1.add(g_e1a.getId());
for(Goal g: gs_parsed_e1b_polyline){
goals_ende1.add(g.getId());
}
goals_ende1.add(g_e1c.getId());
goals_ende2.add(g_e2a.getId());
goals_ende2.add(g_e2b.getId());
// service.insertTask(new Task().setTitle("Observiere den Monbijoupark")
// .setDescription("Es wird von Autonomy Komplikationen am Monbijou Park berichtet."+
// "Umrunden Sie den Monbijou Park und melden Sie Unregelm����igkeiten. "+
// "Fahren sie nicht schneller als 50km/h um unentdeckt zu bleiben!")
// .setGeoLat(52.523702).setGeoLon(13.397588).setGoals(goals_t1)).execute();
// service.insertTask(new Task().setTitle("Sabotage")
// .setDescription("Versuche die Ampeln der Lindauer Allee unter unsere Kontrolle zu bringen."+
// "Fahren Sie dazu ��ber die Lindauer Allee und wechseln sie die Radiofrequenz, wenn Sie an einer Ampel stehen.")
// .setGeoLat(52.574211).setGeoLon(13.349095 ).setGoals(goals_t2)).execute();
// service.insertTask(new Task().setTitle("Untersuchung am Salzufer")
// .setDescription("Ein Informant hat uns mitgeteilt, dass eine oder mehrere Baustellen am Salzufer von der gegnerischen Fraktion sabotiert wurde."+
// "Fahren das Salzufer entlang und markieren Sie Baustellen durch kurzes Bet��tigen vom Warnblinker")
// .setGeoLat(52.518493).setGeoLon(13.321928).setGoals(goals_t3)).execute();
// service.insertTask(new Task().setTitle("Spuren der Vergangenheit")
// .setDescription("Angeblich existieren an der angegebenen Route noch Relikte aus vergangenen Tagen. "+
// "Melden Sie diese durch anziehen der Handbremse, während Sie davor stehen.")
// .setGeoLat(52.455669).setGeoLon(13.294496).setGoals(goals_t4)).execute();
// service.insertTask(new Task().setTitle("Echte Autonomie")
// .setDescription("Du wurdest von Autonomy abgekopselt. Vergewissere dich einer Autonomie in dem du die Funktionen deines Fahrzeuges selber kontrolierst.")
// .setGeoLat(52.436114).setGeoLon(13.285428).setGoals(goals_demo)).execute();
// service.insertTask(new Task().setTitle("Besuche den Großmeister")
// .setDescription("Der Großmeister des Ministy of Freedom will sich sehen. Reise zu ihm!")
// .setGeoLat(52.5753092766).setGeoLon(13.3530235291).setGoals(goals_demo)).execute();
// service.insertTask(new Task().setTitle("Reaktiviere die Alten")
// .setDescription("Viele potenzielle Indidivuen, die sich unserer Sache anschließen können leben in dieser Gegend. Reaktiviere sie aus diesem Dauerschlaf")
// .setGeoLat(52.5753192766).setGeoLon(13.3531235291).setGoals(goals_two)).execute();
service.insertTask(new Task().setTitle("Zeugenschutzprogram!")
.setDescription("Ihr habt es geschafft einen Anh�nger des Ministry of Freedom zum �berlaufen zu bringen. Dieser Zeuge hat wichtige Informationen und muss nun vor den Feind gesch�tzt werden. " +
"Sorge daf�r, dass er sicher aus der Reichweite des Ministries entkommt!")
.setGeoLat(52.52286).setGeoLon(13.321506).setGoals(goals_ende1)).execute();
service.insertTask(new Task().setTitle("Tauche unter!")
.setDescription("Bei deiner letzten Mission wurdest du von Agenten des Ministry of Freedom entdeckt und wirst seitdem verfolgt. Parke und verbirg deine Hitzesignatur um unterzutauchen!")
.setGeoLat(52.517837).setGeoLon(13.328733).setGoals(goals_ende2)).execute();
} catch (FormatException e) {
// TODO Auto-generated catch block
Log.e("TLDR", e.getMessage());
}
} catch (Exception e) {
Log.d("TLDR", e.getMessage(), e);
}
return null;
}
| protected Void doInBackground(Void... v) {
try {
// GoalStructure gs_t1 = new GoalStructure();
// GoalStructure gs_t2= new GoalStructure();
// GoalStructure gs_t3= new GoalStructure();
// GoalStructure gs_t4 = new GoalStructure();
// List<GoalStructure> gs_polyline_t4;
// GoalStructure gs1_tDemo = new GoalStructure();
// GoalStructure gs2_tDemo = new GoalStructure();
// GoalStructure two_2conditions = new GoalStructure();
GoalStructure gs_e2a = new GoalStructure();
GoalStructure gs_e2b = new GoalStructure();
GoalStructure gs_e1a = new GoalStructure();
GoalStructure gs_e1c = new GoalStructure();
List<GoalStructure> gs_e1b_polyline;
// gs_t1.addBaseData("Fahre langsamer als 50km/h", "null").addCondition("Speed", "leq", "50").addReward("xp", "2000");
// gs_t2.addBaseData("Radiofrequenz an Ampel wechseln", "traffic_lights_entry").addCondition("Speed", "leq", "10").addCondition("radio_freq", "change", "null").addReward("xp", "4000");
// gs_t3.addBaseData("Schalte Warnblinklicht an Baustelle ein", "null").addCondition("hazards_light", "eq", "on").addReward("xp", "3000");
// gs_t4.addBaseData("Melde Stoppschilder", "stop_sign_entry").addCondition("handbreak", "eq", "on").addReward("xp", "1600");
// gs_polyline_t4 = GoalStructureFactory.generatePolyLineGoals("Fahre Route ab", "52.456114,13.295408;52.457742,13.298584;52.458605,13.303626;52.454512,13.299463;52.453806,13.2972;52.454434,13.295644;52.455676,13.294474", "xp", 100);
// gs1_tDemo.addBaseData("Schalte in den 1. Gang", "null").addCondition("CurrentGear", "eq", "1").addReward("xp", "2000");
// two_2conditions.addBaseData("Fahre 50km/h im 4 Gang.", "null").addCondition("CurrentGear", "eq", "4").addCondition("VehicleSpeed", "eqr", "50").addReward("xp", "2000");
gs_e2a.addBaseData("Parke!", "null").addCondition("handbreak", "eq", "on").addReward("xp", "1300");
gs_e2b.addBaseData("Schalte die Klimaanlage an!", "parking_space_entry").addCondition("aircondition", "eq", "on").addReward("xp", "1700");
gs_e1a.addBaseData("Lade Agenten ein!", "null").addCondition("SeatBeltLock", "eq", "locked").addReward("xp", "1000");
gs_e1b_polyline = GoalStructureFactory.generatePolyLineGoals("Fahre Route ab", "52.52286,13.321506;52.522828,13.322027;52.521196,13.322357;52.520921,13.32137;52.519681,13.319739;52.517514,13.325061;52.515516,13.327936;52.516691,13.329395", "xp", 100);
gs_e1c.addBaseData("Lade Agenten aus!", "null").addCondition("SeatBeltLock", "eq", "unlocked").addReward("xp", "2000");
try {
// String goal_t1= JsonParser.writeNewJsonGoalString(gs_t1.getJsonParse());
// String goal_t2= JsonParser.writeNewJsonGoalString(gs_t2.getJsonParse());
// String goal_t3= JsonParser.writeNewJsonGoalString(gs_t3.getJsonParse());
// String goal_t4= JsonParser.writeNewJsonGoalString(gs_t4.getJsonParse());
// String goal_demo= JsonParser.writeNewJsonGoalString(gs1_tDemo.getJsonParse());
// String goal_demo2= JsonParser.writeNewJsonGoalString(gs2_tDemo.getJsonParse());
// String two_conditions_str= JsonParser.writeNewJsonGoalString(two_2conditions.getJsonParse());
String g_e2a_str = JsonParser.writeNewJsonGoalString(gs_e2a.getJsonParse());
String g_e2b_str = JsonParser.writeNewJsonGoalString(gs_e2b.getJsonParse());
String g_e1a_str = JsonParser.writeNewJsonGoalString(gs_e1a.getJsonParse());
String g_e1c_str = JsonParser.writeNewJsonGoalString(gs_e1c.getJsonParse());
// Goal g_t1=goal_service.insertGoal(new Goal().setJsonString(goal_t1)).execute();
// Goal g_t2=goal_service.insertGoal(new Goal().setJsonString(goal_t2)).execute();
// Goal g_t3=goal_service.insertGoal(new Goal().setJsonString(goal_t3)).execute();
// Goal g_t4=goal_service.insertGoal(new Goal().setJsonString(goal_t4)).execute();
// Goal g1_demo=goal_service.insertGoal(new Goal().setJsonString(goal_demo)).execute();
// Goal g2_demo=goal_service.insertGoal(new Goal().setJsonString(goal_demo2)).execute();
// Goal two_conditions = goal_service.insertGoal(new Goal().setJsonString(two_conditions_str)).execute();
Goal g_e2a = goal_service.insertGoal(new Goal().setJsonString(g_e2a_str)).execute();
Goal g_e2b = goal_service.insertGoal(new Goal().setJsonString(g_e2b_str)).execute();
Goal g_e1a = goal_service.insertGoal(new Goal().setJsonString(g_e1a_str)).execute();
Goal g_e1c = goal_service.insertGoal(new Goal().setJsonString(g_e1c_str)).execute();
// List<Goal> gs_parsed_polyline_t4 = new ArrayList<Goal>();
// for(GoalStructure gs:gs_polyline_t4){
// gs_parsed_polyline_t4.add(goal_service.insertGoal(new Goal().setJsonString(JsonParser.writeNewJsonGoalString(gs.getJsonParse()))).execute());
// }
List<Goal> gs_parsed_e1b_polyline = new ArrayList<Goal>();
for(GoalStructure gs:gs_e1b_polyline){
gs_parsed_e1b_polyline.add(goal_service.insertGoal(new Goal().setJsonString(JsonParser.writeNewJsonGoalString(gs.getJsonParse()))).execute());
}
// List<Long> goals_t1= new ArrayList<Long>();
// List<Long> goals_t2= new ArrayList<Long>();
// List<Long> goals_t3= new ArrayList<Long>();
// List<Long> goals_t4= new ArrayList<Long>();
// List<Long> goals_demo= new ArrayList<Long>();
// List<Long> goals_two= new ArrayList<Long>();
List<Long> goals_ende1= new ArrayList<Long>();
List<Long> goals_ende2= new ArrayList<Long>();
// goals_t1.add(g_t1.getId());
// goals_t2.add(g_t2.getId());
// goals_t3.add(g_t3.getId());
// goals_t4.add(g_t4.getId());
// for(Goal g: gs_parsed_polyline_t4){
// goals_t4.add(g.getId());
// }
// goals_t4.add(g2_t4.getId());
// goals_demo.add(g1_demo.getId());
// goals_demo.add(g2_demo.getId());
// goals_two.add(two_conditions.getId());
goals_ende1.add(g_e1a.getId());
for(Goal g: gs_parsed_e1b_polyline){
goals_ende1.add(g.getId());
}
goals_ende1.add(g_e1c.getId());
goals_ende2.add(g_e2a.getId());
goals_ende2.add(g_e2b.getId());
// service.insertTask(new Task().setTitle("Observiere den Monbijoupark")
// .setDescription("Es wird von Autonomy Komplikationen am Monbijou Park berichtet."+
// "Umrunden Sie den Monbijou Park und melden Sie Unregelm����igkeiten. "+
// "Fahren sie nicht schneller als 50km/h um unentdeckt zu bleiben!")
// .setGeoLat(52.523702).setGeoLon(13.397588).setGoals(goals_t1)).execute();
// service.insertTask(new Task().setTitle("Sabotage")
// .setDescription("Versuche die Ampeln der Lindauer Allee unter unsere Kontrolle zu bringen."+
// "Fahren Sie dazu ��ber die Lindauer Allee und wechseln sie die Radiofrequenz, wenn Sie an einer Ampel stehen.")
// .setGeoLat(52.574211).setGeoLon(13.349095 ).setGoals(goals_t2)).execute();
// service.insertTask(new Task().setTitle("Untersuchung am Salzufer")
// .setDescription("Ein Informant hat uns mitgeteilt, dass eine oder mehrere Baustellen am Salzufer von der gegnerischen Fraktion sabotiert wurde."+
// "Fahren das Salzufer entlang und markieren Sie Baustellen durch kurzes Bet��tigen vom Warnblinker")
// .setGeoLat(52.518493).setGeoLon(13.321928).setGoals(goals_t3)).execute();
// service.insertTask(new Task().setTitle("Spuren der Vergangenheit")
// .setDescription("Angeblich existieren an der angegebenen Route noch Relikte aus vergangenen Tagen. "+
// "Melden Sie diese durch anziehen der Handbremse, während Sie davor stehen.")
// .setGeoLat(52.455669).setGeoLon(13.294496).setGoals(goals_t4)).execute();
// service.insertTask(new Task().setTitle("Echte Autonomie")
// .setDescription("Du wurdest von Autonomy abgekopselt. Vergewissere dich einer Autonomie in dem du die Funktionen deines Fahrzeuges selber kontrolierst.")
// .setGeoLat(52.436114).setGeoLon(13.285428).setGoals(goals_demo)).execute();
// service.insertTask(new Task().setTitle("Besuche den Großmeister")
// .setDescription("Der Großmeister des Ministy of Freedom will sich sehen. Reise zu ihm!")
// .setGeoLat(52.5753092766).setGeoLon(13.3530235291).setGoals(goals_demo)).execute();
// service.insertTask(new Task().setTitle("Reaktiviere die Alten")
// .setDescription("Viele potenzielle Indidivuen, die sich unserer Sache anschließen können leben in dieser Gegend. Reaktiviere sie aus diesem Dauerschlaf")
// .setGeoLat(52.5753192766).setGeoLon(13.3531235291).setGoals(goals_two)).execute();
service.insertTask(new Task().setTitle("Zeugenschutzprogram!")
.setDescription("Ihr habt es geschafft einen Anh�nger des Ministry of Freedom zum �berlaufen zu bringen. Dieser Zeuge hat wichtige Informationen und muss nun vor den Feind gesch�tzt werden. " +
"Sorge daf�r, dass er sicher aus der Reichweite des Ministries entkommt!")
.setGeoLat(52.52286).setGeoLon(13.321506).setGoals(goals_ende1)).execute();
service.insertTask(new Task().setTitle("Tauche unter!")
.setDescription("Bei deiner letzten Mission wurdest du von Agenten des Ministry of Freedom entdeckt und wirst seitdem verfolgt. Parke und verbirg deine Hitzesignatur um unterzutauchen!")
.setGeoLat(52.517837).setGeoLon(13.328733).setGoals(goals_ende2)).execute();
} catch (FormatException e) {
// TODO Auto-generated catch block
Log.e("TLDR", e.getMessage());
}
} catch (Exception e) {
Log.d("TLDR", e.getMessage(), e);
}
return null;
}
|
diff --git a/src/replicatorg/drivers/gen3/Makerbot4GAlternateDriver.java b/src/replicatorg/drivers/gen3/Makerbot4GAlternateDriver.java
index 516aac0f..ac91d9be 100644
--- a/src/replicatorg/drivers/gen3/Makerbot4GAlternateDriver.java
+++ b/src/replicatorg/drivers/gen3/Makerbot4GAlternateDriver.java
@@ -1,234 +1,235 @@
package replicatorg.drivers.gen3;
import java.util.EnumMap;
import java.util.Map;
import java.util.Vector;
import java.util.logging.Level;
import org.w3c.dom.Element;
import replicatorg.app.Base;
import replicatorg.drivers.RetryException;
import replicatorg.machine.model.AxisId;
import replicatorg.machine.model.MachineModel;
import replicatorg.machine.model.ToolModel;
import replicatorg.util.Point5d;
public class Makerbot4GAlternateDriver extends Makerbot4GDriver {
public String getDriverName() {
return "Makerbot4GAlternate";
}
/**
* Overloaded to manage a hijacked axis and run this axis in relative mode instead of the extruder DC motor
*/
public void queuePoint(Point5d p) throws RetryException {
// Filter away any hijacked axes from the given point.
// This is necessary to avoid taking deltas into account where we
// compare the relative p coordinate (usually 0) with the absolute
// currentPosition (which we get from the Motherboard).
Point5d filteredpoint = new Point5d(p);
Point5d filteredcurrent = new Point5d(getCurrentPosition());
for (AxisId axis : getHijackedAxes()) {
filteredpoint.setAxis(axis, 0d);
filteredcurrent.setAxis(axis, 0d);
}
// is this point even step-worthy? Only compute nonzero moves
Point5d deltaSteps = getAbsDeltaSteps(filteredcurrent, filteredpoint);
if (deltaSteps.length() > 0.0) {
Point5d delta = new Point5d();
delta.sub(filteredpoint, filteredcurrent); // delta = p - current
delta.absolute(); // absolute value of each component
Point5d axesmovement = calcHijackedAxesMovement(delta);
delta.add(axesmovement);
+ filteredpoint.add(axesmovement);
// Calculate time for move in usec
Point5d steps = machine.mmToSteps(filteredpoint);
int relative = 0;
for (int i=0;i<5;i++) {
if (axesmovement.get(i) != 0d) relative |= 1 << i;
}
// okay, send it off!
double minutes = delta.length() / getSafeFeedrate(delta);
queueNewPoint(steps, (long) (60 * 1000 * 1000 * minutes), relative);
setInternalPosition(filteredpoint);
}
}
/**
* Overloaded to support extruding without moving by converting a delay in to an extruder command
*/
public void delay(long millis) throws RetryException {
if (Base.logger.isLoggable(Level.FINER)) {
Base.logger.log(Level.FINER,"Delaying " + millis + " millis.");
}
Point5d steps = new Point5d();
modifyHijackedAxes(steps, millis / 60000d);
if (steps.length() > 0) {
queueNewPoint(steps, millis * 1000, 0x1f); // All axes relative to avoid dealing with absolute coords
}
else {
super.delay(millis); // This resulted in no stepper movements -> fall back to normal delay
}
}
/**
* Returns the hijacked axes for the current tool.
*/
private Iterable<AxisId> getHijackedAxes() {
Vector<AxisId> axes = new Vector<AxisId>();
for ( Map.Entry<AxisId,ToolModel> entry : stepExtruderMap.entrySet()) {
ToolModel curTool = machine.currentTool();
AxisId axis = entry.getKey();
if (curTool.equals(entry.getValue())) {
axes.add(axis);
}
}
return axes;
}
/**
* Calculate and return the corresponding movement of any hijacked axes where the extruder is on.
* The returned movement is in mm of incoming filament (corresponding to mm in machines.xml)
* If the extruder is off, the hijacked axes are not moved.
* @param delta relative XYZ movement.
* @return The relative movement (in mm) of the hijacked axes
*/
private Point5d calcHijackedAxesMovement(Point5d delta) {
Point5d movement = new Point5d();
double minutes = delta.length() / getCurrentFeedrate();
for (AxisId axis : getHijackedAxes()) {
ToolModel curTool = machine.currentTool();
if (curTool.isMotorEnabled()) {
double extruderStepsPerMinute = curTool.getMotorSpeedRPM() * curTool.getMotorSteps();
final boolean clockwise = machine.currentTool().getMotorDirection() == ToolModel.MOTOR_CLOCKWISE;
movement.setAxis(axis, extruderStepsPerMinute * minutes / machine.getStepsPerMM().axis(axis) * (clockwise?-1d:1d));
}
}
return movement;
}
/**
* Write a relative movement to any axes which has been hijacked where the extruder is turned on.
* The axis will be moved with a length corresponding to the duration of the movement.
* The speed of the hijacked axis will be clamped to its maximum feedrate.
* If the extruder is off, the corresponding axes are set to a zero relative movement.
* @param steps
* @param minutes
* @return a bitmask with the relative bit set for all hijacked axes
*/
private int modifyHijackedAxes(Point5d steps, double minutes) {
int relative = 0;
for (AxisId axis : getHijackedAxes()) {
relative |= 1 << axis.getIndex();
double extruderSteps = 0;
ToolModel curTool = machine.currentTool();
if (curTool.isMotorEnabled()) {
double maxrpm = machine.getMaximumFeedrates().axis(axis) * machine.getStepsPerMM().axis(axis) / curTool.getMotorSteps();
double rpm = curTool.getMotorSpeedRPM() > maxrpm ? maxrpm : curTool.getMotorSpeedRPM();
boolean clockwise = machine.currentTool().getMotorDirection() == ToolModel.MOTOR_CLOCKWISE;
extruderSteps = rpm * curTool.getMotorSteps() * minutes * (clockwise?-1d:1d);
}
steps.setAxis(axis, extruderSteps);
}
return relative;
}
protected void queueNewPoint(Point5d steps, long us, int relative) throws RetryException {
PacketBuilder pb = new PacketBuilder(MotherboardCommandCode.QUEUE_POINT_NEW.getCode());
if (Base.logger.isLoggable(Level.FINE)) {
Base.logger.log(Level.FINE,"Queued new-style point " + steps + " over "
+ Long.toString(us) + " usec., relative " + Integer.toString(relative));
}
// just add them in now.
pb.add32((int) steps.x());
pb.add32((int) steps.y());
pb.add32((int) steps.z());
pb.add32((int) steps.a());
pb.add32((int) steps.b());
pb.add32((int) us);
pb.add8((int) relative);
runCommand(pb.getPacket());
}
/**
* Overridden to not talk to the DC motor driver. This driver is reused for the stepper motor fan
*/
public void enableMotor() throws RetryException {
machine.currentTool().enableMotor();
}
/**
* Overridden to not talk to the DC motor driver. This driver is reused for the stepper motor fan
*/
public void disableMotor() throws RetryException {
machine.currentTool().disableMotor();
}
/**
* Overridden to not talk to the DC motor driver. This driver is reused for the stepper motor fan
*/
public void setMotorSpeedPWM(int pwm) throws RetryException {
machine.currentTool().setMotorSpeedPWM(pwm);
}
/**
* Overridden to not talk to the DC motor driver. This driver is reused for the stepper motor fan
*/
public void setMotorRPM(double rpm) throws RetryException {
machine.currentTool().setMotorSpeedRPM(rpm);
}
EnumMap<AxisId,ToolModel> stepExtruderMap = new EnumMap<AxisId,ToolModel>(AxisId.class);
@Override
/**
* When the machine is set for this driver, some toolheads may poach the an extrusion axis.
*/
public void setMachine(MachineModel m) {
super.setMachine(m);
for (ToolModel tm : m.getTools()) {
Element e = (Element)tm.getXml();
if (e.hasAttribute("stepper_axis")) {
final String stepAxisStr = e.getAttribute("stepper_axis");
try {
AxisId axis = AxisId.valueOf(stepAxisStr.toUpperCase());
if (m.hasAxis(axis)) {
// If we're seizing an axis for an extruder, remove it from the available axes and get
// the data associated with that axis.
stepExtruderMap.put(axis,tm);
m.getAvailableAxes().remove(axis);
} else {
Base.logger.severe("Tool claims unavailable axis "+axis.name());
}
} catch (IllegalArgumentException iae) {
Base.logger.severe("Unintelligible axis designator "+stepAxisStr);
}
}
}
}
@Override
/**
* Overridden to not ask the board for the RPM as it would report the RPM from the extruder controller, which doesn't know about it in this case.
*/
public double getMotorRPM() {
double rpm = machine.currentTool().getMotorSpeedRPM();
machine.currentTool().setMotorSpeedReadingRPM(rpm);
return rpm;
}
}
| true | true | public void queuePoint(Point5d p) throws RetryException {
// Filter away any hijacked axes from the given point.
// This is necessary to avoid taking deltas into account where we
// compare the relative p coordinate (usually 0) with the absolute
// currentPosition (which we get from the Motherboard).
Point5d filteredpoint = new Point5d(p);
Point5d filteredcurrent = new Point5d(getCurrentPosition());
for (AxisId axis : getHijackedAxes()) {
filteredpoint.setAxis(axis, 0d);
filteredcurrent.setAxis(axis, 0d);
}
// is this point even step-worthy? Only compute nonzero moves
Point5d deltaSteps = getAbsDeltaSteps(filteredcurrent, filteredpoint);
if (deltaSteps.length() > 0.0) {
Point5d delta = new Point5d();
delta.sub(filteredpoint, filteredcurrent); // delta = p - current
delta.absolute(); // absolute value of each component
Point5d axesmovement = calcHijackedAxesMovement(delta);
delta.add(axesmovement);
// Calculate time for move in usec
Point5d steps = machine.mmToSteps(filteredpoint);
int relative = 0;
for (int i=0;i<5;i++) {
if (axesmovement.get(i) != 0d) relative |= 1 << i;
}
// okay, send it off!
double minutes = delta.length() / getSafeFeedrate(delta);
queueNewPoint(steps, (long) (60 * 1000 * 1000 * minutes), relative);
setInternalPosition(filteredpoint);
}
}
| public void queuePoint(Point5d p) throws RetryException {
// Filter away any hijacked axes from the given point.
// This is necessary to avoid taking deltas into account where we
// compare the relative p coordinate (usually 0) with the absolute
// currentPosition (which we get from the Motherboard).
Point5d filteredpoint = new Point5d(p);
Point5d filteredcurrent = new Point5d(getCurrentPosition());
for (AxisId axis : getHijackedAxes()) {
filteredpoint.setAxis(axis, 0d);
filteredcurrent.setAxis(axis, 0d);
}
// is this point even step-worthy? Only compute nonzero moves
Point5d deltaSteps = getAbsDeltaSteps(filteredcurrent, filteredpoint);
if (deltaSteps.length() > 0.0) {
Point5d delta = new Point5d();
delta.sub(filteredpoint, filteredcurrent); // delta = p - current
delta.absolute(); // absolute value of each component
Point5d axesmovement = calcHijackedAxesMovement(delta);
delta.add(axesmovement);
filteredpoint.add(axesmovement);
// Calculate time for move in usec
Point5d steps = machine.mmToSteps(filteredpoint);
int relative = 0;
for (int i=0;i<5;i++) {
if (axesmovement.get(i) != 0d) relative |= 1 << i;
}
// okay, send it off!
double minutes = delta.length() / getSafeFeedrate(delta);
queueNewPoint(steps, (long) (60 * 1000 * 1000 * minutes), relative);
setInternalPosition(filteredpoint);
}
}
|
diff --git a/src/me/desht/scrollingmenusign/SMSPlayerListener.java b/src/me/desht/scrollingmenusign/SMSPlayerListener.java
index a52ef58..e0fb41f 100644
--- a/src/me/desht/scrollingmenusign/SMSPlayerListener.java
+++ b/src/me/desht/scrollingmenusign/SMSPlayerListener.java
@@ -1,142 +1,143 @@
package me.desht.scrollingmenusign;
import java.util.logging.Level;
import org.bukkit.Location;
import org.bukkit.block.Block;
import org.bukkit.block.Sign;
import org.bukkit.entity.Player;
import org.bukkit.event.block.Action;
import org.bukkit.event.player.PlayerInteractEvent;
import org.bukkit.event.player.PlayerItemHeldEvent;
import org.bukkit.event.player.PlayerListener;
public class SMSPlayerListener extends PlayerListener {
private ScrollingMenuSign plugin;
public SMSPlayerListener(ScrollingMenuSign plugin) {
this.plugin = plugin;
}
@Override
public void onPlayerInteract(PlayerInteractEvent event) {
if (event.isCancelled()) {
return;
}
Block block = event.getClickedBlock();
if (block == null || !(block.getState() instanceof Sign)) {
return;
}
Player player = event.getPlayer();
String menuName = SMSMenu.getMenuNameAt(block.getLocation());
try {
if (menuName == null) {
// No menu attached to this sign, but a left-click could create a new menu if the sign's
// text is in the right format...
if (event.getAction() == Action.LEFT_CLICK_BLOCK && player.getItemInHand().getTypeId() == 0) {
tryToActivateSign(block, player);
}
} else {
// ok, it's a sign, and there's a menu on it
plugin.debug("player interact event @ " + block.getLocation() + ", " + player.getName() + " did " + event.getAction() + ", menu=" + menuName);
SMSMenu menu = SMSMenu.getMenu(menuName);
SMSAction action = SMSAction.getAction(event);
processAction(action, player, menu, block.getLocation());
}
} catch (SMSException e) {
SMSUtils.errorMessage(player, e.getMessage());
}
}
@Override
public void onItemHeldChange(PlayerItemHeldEvent event) {
try {
Player player = event.getPlayer();
Block b = player.getTargetBlock(null, 3);
String menuName = SMSMenu.getMenuNameAt(b.getLocation());
if (menuName == null)
return;
SMSMenu menu = SMSMenu.getMenu(menuName);
SMSAction action = SMSAction.getAction(event);
processAction(action, player, menu, b.getLocation());
} catch (SMSException e) {
SMSUtils.log(Level.WARNING, e.getMessage());
}
}
private void processAction(SMSAction action, Player p, SMSMenu menu, Location l) throws SMSException {
if (action == null)
return;
switch (action) {
case EXECUTE:
executeMenu(p, menu, l);
break;
case SCROLLDOWN:
case SCROLLUP:
scrollMenu(p, menu, l, action);
break;
}
}
private void scrollMenu(Player player, SMSMenu menu, Location l, SMSAction dir) throws SMSException {
if (!SMSPermissions.isAllowedTo(player, "scrollingmenusign.scroll"))
return;
switch (dir) {
case SCROLLDOWN:
menu.nextItem(l);
break;
case SCROLLUP:
menu.prevItem(l);
break;
}
menu.updateSign(l);
}
private void executeMenu(Player player, SMSMenu menu, Location l) throws SMSException {
if (!SMSPermissions.isAllowedTo(player, "scrollingmenusign.execute"))
return;
SMSMenuItem item = menu.getCurrentItem(l);
if (item != null) {
item.execute(player);
item.feedbackMessage(player);
}
}
private void tryToActivateSign(Block b, Player player) throws SMSException {
Sign sign = (Sign) b.getState();
if (!sign.getLine(0).equals("[sms]"))
return;
String name = sign.getLine(1);
String title = SMSUtils.parseColourSpec(player, sign.getLine(2));
if (name.isEmpty())
return;
if (SMSMenu.checkForMenu(name)) {
if (title.isEmpty()) {
SMSPermissions.requirePerms(player, "scrollingmenusign.commands.sync");
try {
SMSMenu menu = SMSMenu.getMenu(name);
menu.addSign(b.getLocation(), true);
SMSUtils.statusMessage(player, "Sign @ &f" + SMSUtils.formatLocation(b.getLocation()) +
"&- was added to menu &e" + name + "&-");
} catch (SMSException e) {
SMSUtils.errorMessage(player, e.getMessage());
}
} else {
SMSUtils.errorMessage(player, "A menu called '" + name + "' already exists.");
}
} else if (title.length() > 0) {
SMSPermissions.requirePerms(player, "scrollingmenusign.commands.create");
- plugin.getHandler().createMenu(name, title, player.getName());
+ SMSMenu menu = plugin.getHandler().createMenu(name, title, player.getName());
+ menu.addSign(b.getLocation(), true);
SMSUtils.statusMessage(player, "Sign @ &f" + SMSUtils.formatLocation(b.getLocation()) +
"&- was added to new menu &e" + name + "&-");
}
}
}
| true | true | private void tryToActivateSign(Block b, Player player) throws SMSException {
Sign sign = (Sign) b.getState();
if (!sign.getLine(0).equals("[sms]"))
return;
String name = sign.getLine(1);
String title = SMSUtils.parseColourSpec(player, sign.getLine(2));
if (name.isEmpty())
return;
if (SMSMenu.checkForMenu(name)) {
if (title.isEmpty()) {
SMSPermissions.requirePerms(player, "scrollingmenusign.commands.sync");
try {
SMSMenu menu = SMSMenu.getMenu(name);
menu.addSign(b.getLocation(), true);
SMSUtils.statusMessage(player, "Sign @ &f" + SMSUtils.formatLocation(b.getLocation()) +
"&- was added to menu &e" + name + "&-");
} catch (SMSException e) {
SMSUtils.errorMessage(player, e.getMessage());
}
} else {
SMSUtils.errorMessage(player, "A menu called '" + name + "' already exists.");
}
} else if (title.length() > 0) {
SMSPermissions.requirePerms(player, "scrollingmenusign.commands.create");
plugin.getHandler().createMenu(name, title, player.getName());
SMSUtils.statusMessage(player, "Sign @ &f" + SMSUtils.formatLocation(b.getLocation()) +
"&- was added to new menu &e" + name + "&-");
}
}
| private void tryToActivateSign(Block b, Player player) throws SMSException {
Sign sign = (Sign) b.getState();
if (!sign.getLine(0).equals("[sms]"))
return;
String name = sign.getLine(1);
String title = SMSUtils.parseColourSpec(player, sign.getLine(2));
if (name.isEmpty())
return;
if (SMSMenu.checkForMenu(name)) {
if (title.isEmpty()) {
SMSPermissions.requirePerms(player, "scrollingmenusign.commands.sync");
try {
SMSMenu menu = SMSMenu.getMenu(name);
menu.addSign(b.getLocation(), true);
SMSUtils.statusMessage(player, "Sign @ &f" + SMSUtils.formatLocation(b.getLocation()) +
"&- was added to menu &e" + name + "&-");
} catch (SMSException e) {
SMSUtils.errorMessage(player, e.getMessage());
}
} else {
SMSUtils.errorMessage(player, "A menu called '" + name + "' already exists.");
}
} else if (title.length() > 0) {
SMSPermissions.requirePerms(player, "scrollingmenusign.commands.create");
SMSMenu menu = plugin.getHandler().createMenu(name, title, player.getName());
menu.addSign(b.getLocation(), true);
SMSUtils.statusMessage(player, "Sign @ &f" + SMSUtils.formatLocation(b.getLocation()) +
"&- was added to new menu &e" + name + "&-");
}
}
|
diff --git a/javafxdoc/src/com/sun/tools/xslhtml/XHTMLProcessingUtils.java b/javafxdoc/src/com/sun/tools/xslhtml/XHTMLProcessingUtils.java
index 2f331ad5d..cff1bf341 100644
--- a/javafxdoc/src/com/sun/tools/xslhtml/XHTMLProcessingUtils.java
+++ b/javafxdoc/src/com/sun/tools/xslhtml/XHTMLProcessingUtils.java
@@ -1,308 +1,309 @@
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package com.sun.tools.xslhtml;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.io.Writer;
import java.net.URL;
import java.text.ChoiceFormat;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.MissingResourceException;
import java.util.ResourceBundle;
import java.util.logging.ConsoleHandler;
import java.util.logging.Handler;
import java.util.logging.Level;
import java.util.logging.LogRecord;
import java.util.logging.Logger;
import java.util.logging.SimpleFormatter;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.ErrorListener;
import javax.xml.transform.Result;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.ErrorHandler;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;
import static java.util.logging.Level.*;
/**
*
* @author joshy
*/
public class XHTMLProcessingUtils {
private static ResourceBundle messageRB = null;
private static Logger logger = Logger.getLogger(XHTMLProcessingUtils.class.getName());;
static {
// set verbose for initial development
logger.setLevel(ALL); //TODO: remove or set to INFO when finished
}
/**
* Transform XMLDoclet output to XHTML using XSLT.
*
* @param xmlInputPath the path of the XMLDoclet output to transform
* @param xsltStream the XSLT to implement the transformation, as an input stream.
* @throws java.lang.Exception
*/
public static void process(String xmlInputPath, InputStream xsltStream) throws Exception {
System.out.println(getString("transforming.to.html"));
// TODO code application logic here
//hack to get this to work on the mac
System.setProperty("javax.xml.parsers.DocumentBuilderFactory",
"com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderFactoryImpl");
System.setProperty("javax.xml.parsers.SAXParserFactory",
"com.sun.org.apache.xerces.internal.jaxp.SAXParserFactoryImpl");
if (xsltStream == null)
xsltStream = XHTMLProcessingUtils.class.getResourceAsStream("resources/javadoc.xsl");
File file = new File(xmlInputPath);
p(INFO, MessageFormat.format(getString("reading.doc"), file.getAbsolutePath()));
p(FINE, "exists: " + file.exists());
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
builder.setErrorHandler(new ErrorHandler() {
public void warning(SAXParseException exception) throws SAXException {
p(WARNING, "error: " + exception.getLineNumber());
}
public void error(SAXParseException exception) throws SAXException {
p(SEVERE, "error: " + exception.getLineNumber());
}
public void fatalError(SAXParseException exception) throws SAXException {
p(SEVERE, "error: " + exception.getLineNumber());
}
});
Document doc = builder.parse(file);
File docsdir = new File("fxdocs");
if (!docsdir.exists()) {
docsdir.mkdir();
}
p(INFO, getString("copying"));
copy(XHTMLProcessingUtils.class.getResource("resources/frameset.html"), new File(docsdir, "frameset.html"));
- copy(XHTMLProcessingUtils.class.getResource("resources/demo.css"), new File(docsdir, "demo.css"));
+ copy(XHTMLProcessingUtils.class.getResource("resources/master.css"), new File(docsdir, "master.css"));
+ copy(XHTMLProcessingUtils.class.getResource("resources/styled.css"), new File(docsdir, "styled.css"));
File images = new File(docsdir,"images");
images.mkdir();
copy(XHTMLProcessingUtils.class.getResource("resources/quote-background-1.gif"), new File(images, "quote-background-1.gif"));
//copy(new File("demo.css"), new File(docsdir, "demo.css"));
p(INFO, getString("transforming"));
//File xsltFile = new File("javadoc.xsl");
//p("reading xslt exists in: " + xsltFile.exists());
Source xslt = new StreamSource(xsltStream);
Transformer trans = TransformerFactory.newInstance().newTransformer(xslt);
trans.setErrorListener(new ErrorListener() {
public void warning(TransformerException exception) throws TransformerException {
p(WARNING, "warning: " + exception);
}
public void error(TransformerException exception) throws TransformerException {
Throwable thr = exception;
while (true) {
p(SEVERE, "error: " + exception.getMessageAndLocation(), thr.getCause());
if (thr.getCause() != null) {
thr = thr.getCause();
} else {
break;
}
}
}
public void fatalError(TransformerException exception) throws TransformerException {
p(SEVERE, "fatal error: " + exception.getMessageAndLocation(), exception);
}
});
XPath xpath = XPathFactory.newInstance().newXPath();
// packages
NodeList packages = (NodeList) xpath.evaluate("//package", doc, XPathConstants.NODESET); MessageFormat form = new MessageFormat("The disk \"{1}\" contains {0}.");
p(INFO, MessageFormat.format(getString("creating.packages"), packages.getLength()));
FileOutputStream packages_html = new FileOutputStream(new File(docsdir, "packages.html"));
Writer packages_writer = new OutputStreamWriter(packages_html);
packages_writer.write("<html><head><link href='demo.css' rel='stylesheet'/></head><body><ul class='package-list'>");
FileOutputStream classes_html = new FileOutputStream(new File(docsdir, "classes.html"));
Writer classes_writer = new OutputStreamWriter(classes_html);
classes_writer.write("<html><head><link href='../demo.css' rel='stylesheet'/></head><body><ul>");
for (int i = 0; i < packages.getLength(); i++) {
Element pkg = ((Element) packages.item(i));
String name = pkg.getAttribute("name");
packages_writer.write("<li><a href='"+name+"/classes.html' target='classListFrame'>" + name + "</a></li>");
processPackage(name, pkg, xpath, docsdir, trans);
}
classes_writer.write("</ul></body></html>");
classes_writer.close();
packages_writer.write("</ul></body></html>");
packages_writer.close();
System.out.println(getString("finished"));
}
private static void processPackage(String packageName, Element pkg, XPath xpath, File docsdir, Transformer trans) throws TransformerException, XPathExpressionException, IOException, FileNotFoundException {
File packageDir = new File(docsdir, packageName);
packageDir.mkdir();
//classes
NodeList classesNodeList = (NodeList) xpath.evaluate(
"*[name() = 'class' or name() = 'abstractClass' or name() = 'interface']",
pkg, XPathConstants.NODESET);
List<Element> classes = sort(classesNodeList);
p(INFO, MessageFormat.format(getString("creating.classes"), classes.size()));
FileOutputStream package_classes_html = new FileOutputStream(new File(packageDir, "classes.html"));
Writer package_classes_writer = new OutputStreamWriter(package_classes_html);
package_classes_writer.write("<html><head><link href='../demo.css' rel='stylesheet'/></head><body><ul class='class-list'>");
for(Element clazz : classes) {
processClass(clazz, package_classes_writer,trans, packageDir);
}
package_classes_writer.write("</ul></body></html>");
package_classes_writer.close();
}
private static void processClass(Element clazz, Writer package_classes_writer, Transformer trans, File packageDir) throws TransformerException, IOException {
String qualifiedName = clazz.getAttribute("qualifiedName");
String name = clazz.getAttribute("name");
package_classes_writer.write("<li><a href='" + qualifiedName + ".html" + "' target='classFrame'>" + name + "</a>\n");
File xhtmlFile = new File(packageDir, qualifiedName + ".html");
Result xhtmlResult = new StreamResult(xhtmlFile);
Source xmlSource = new DOMSource(clazz);
trans.transform(xmlSource, xhtmlResult);
}
private static List<Element> sort(NodeList classesNodeList) {
List<Element> nodes = new ArrayList<Element>();
for(int i=0; i<classesNodeList.getLength(); i++) {
nodes.add((Element)classesNodeList.item(i));
}
Collections.sort(nodes,new Comparator<Element>() {
public int compare(Element o1, Element o2) {
return o1.getAttribute("qualifiedName").compareTo(
o2.getAttribute("qualifiedName"));
}
}
);
return nodes;
}
private static void copy(URL url, File file) throws FileNotFoundException, IOException {
p(FINE, "copying from: " + url);
p(FINE, "copying to: " + file.getAbsolutePath());
InputStream in = url.openStream();
FileOutputStream out = new FileOutputStream(file);
byte[] buf = new byte[1024];
while (true) {
int n = in.read(buf);
if (n < 0) {
break;
}
out.write(buf, 0, n);
}
}
private static void copy(File infile, File outfile) throws FileNotFoundException, IOException {
FileInputStream in = new FileInputStream(infile);
FileOutputStream out = new FileOutputStream(outfile);
byte[] buf = new byte[1024];
while (true) {
int n = in.read(buf);
if (n < 0) {
break;
}
out.write(buf, 0, n);
}
}
static String getString(String key) {
ResourceBundle msgRB = messageRB;
if (msgRB == null) {
try {
messageRB = msgRB =
ResourceBundle.getBundle("com.sun.tools.xslhtml.resources.xslhtml");
} catch (MissingResourceException e) {
throw new Error("Fatal: Resource for javafxdoc is missing");
}
}
return msgRB.getString(key);
}
private static void p(Level level, String string) {
if (level.intValue() >= logger.getLevel().intValue())
System.err.println(string);
}
private static void p(Level level, String string, Throwable t) {
if (level.intValue() >= logger.getLevel().intValue()) {
StringBuilder sb = new StringBuilder();
sb.append(string);
if (t != null) {
sb.append(System.getProperty("line.separator"));
try {
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
t.printStackTrace(pw);
pw.close();
sb.append(sw.toString());
} catch (Exception ex) {
}
}
System.err.println(sb.toString());
}
}
/**
* Command-line/debugging entry
*/
public static void main(String[] args) throws Exception {
process("javadoc.xml", null);
}
}
| true | true | public static void process(String xmlInputPath, InputStream xsltStream) throws Exception {
System.out.println(getString("transforming.to.html"));
// TODO code application logic here
//hack to get this to work on the mac
System.setProperty("javax.xml.parsers.DocumentBuilderFactory",
"com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderFactoryImpl");
System.setProperty("javax.xml.parsers.SAXParserFactory",
"com.sun.org.apache.xerces.internal.jaxp.SAXParserFactoryImpl");
if (xsltStream == null)
xsltStream = XHTMLProcessingUtils.class.getResourceAsStream("resources/javadoc.xsl");
File file = new File(xmlInputPath);
p(INFO, MessageFormat.format(getString("reading.doc"), file.getAbsolutePath()));
p(FINE, "exists: " + file.exists());
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
builder.setErrorHandler(new ErrorHandler() {
public void warning(SAXParseException exception) throws SAXException {
p(WARNING, "error: " + exception.getLineNumber());
}
public void error(SAXParseException exception) throws SAXException {
p(SEVERE, "error: " + exception.getLineNumber());
}
public void fatalError(SAXParseException exception) throws SAXException {
p(SEVERE, "error: " + exception.getLineNumber());
}
});
Document doc = builder.parse(file);
File docsdir = new File("fxdocs");
if (!docsdir.exists()) {
docsdir.mkdir();
}
p(INFO, getString("copying"));
copy(XHTMLProcessingUtils.class.getResource("resources/frameset.html"), new File(docsdir, "frameset.html"));
copy(XHTMLProcessingUtils.class.getResource("resources/demo.css"), new File(docsdir, "demo.css"));
File images = new File(docsdir,"images");
images.mkdir();
copy(XHTMLProcessingUtils.class.getResource("resources/quote-background-1.gif"), new File(images, "quote-background-1.gif"));
//copy(new File("demo.css"), new File(docsdir, "demo.css"));
p(INFO, getString("transforming"));
//File xsltFile = new File("javadoc.xsl");
//p("reading xslt exists in: " + xsltFile.exists());
Source xslt = new StreamSource(xsltStream);
Transformer trans = TransformerFactory.newInstance().newTransformer(xslt);
trans.setErrorListener(new ErrorListener() {
public void warning(TransformerException exception) throws TransformerException {
p(WARNING, "warning: " + exception);
}
public void error(TransformerException exception) throws TransformerException {
Throwable thr = exception;
while (true) {
p(SEVERE, "error: " + exception.getMessageAndLocation(), thr.getCause());
if (thr.getCause() != null) {
thr = thr.getCause();
} else {
break;
}
}
}
public void fatalError(TransformerException exception) throws TransformerException {
p(SEVERE, "fatal error: " + exception.getMessageAndLocation(), exception);
}
});
XPath xpath = XPathFactory.newInstance().newXPath();
// packages
NodeList packages = (NodeList) xpath.evaluate("//package", doc, XPathConstants.NODESET); MessageFormat form = new MessageFormat("The disk \"{1}\" contains {0}.");
p(INFO, MessageFormat.format(getString("creating.packages"), packages.getLength()));
FileOutputStream packages_html = new FileOutputStream(new File(docsdir, "packages.html"));
Writer packages_writer = new OutputStreamWriter(packages_html);
packages_writer.write("<html><head><link href='demo.css' rel='stylesheet'/></head><body><ul class='package-list'>");
FileOutputStream classes_html = new FileOutputStream(new File(docsdir, "classes.html"));
Writer classes_writer = new OutputStreamWriter(classes_html);
classes_writer.write("<html><head><link href='../demo.css' rel='stylesheet'/></head><body><ul>");
for (int i = 0; i < packages.getLength(); i++) {
Element pkg = ((Element) packages.item(i));
String name = pkg.getAttribute("name");
packages_writer.write("<li><a href='"+name+"/classes.html' target='classListFrame'>" + name + "</a></li>");
processPackage(name, pkg, xpath, docsdir, trans);
}
classes_writer.write("</ul></body></html>");
classes_writer.close();
packages_writer.write("</ul></body></html>");
packages_writer.close();
System.out.println(getString("finished"));
}
| public static void process(String xmlInputPath, InputStream xsltStream) throws Exception {
System.out.println(getString("transforming.to.html"));
// TODO code application logic here
//hack to get this to work on the mac
System.setProperty("javax.xml.parsers.DocumentBuilderFactory",
"com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderFactoryImpl");
System.setProperty("javax.xml.parsers.SAXParserFactory",
"com.sun.org.apache.xerces.internal.jaxp.SAXParserFactoryImpl");
if (xsltStream == null)
xsltStream = XHTMLProcessingUtils.class.getResourceAsStream("resources/javadoc.xsl");
File file = new File(xmlInputPath);
p(INFO, MessageFormat.format(getString("reading.doc"), file.getAbsolutePath()));
p(FINE, "exists: " + file.exists());
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
builder.setErrorHandler(new ErrorHandler() {
public void warning(SAXParseException exception) throws SAXException {
p(WARNING, "error: " + exception.getLineNumber());
}
public void error(SAXParseException exception) throws SAXException {
p(SEVERE, "error: " + exception.getLineNumber());
}
public void fatalError(SAXParseException exception) throws SAXException {
p(SEVERE, "error: " + exception.getLineNumber());
}
});
Document doc = builder.parse(file);
File docsdir = new File("fxdocs");
if (!docsdir.exists()) {
docsdir.mkdir();
}
p(INFO, getString("copying"));
copy(XHTMLProcessingUtils.class.getResource("resources/frameset.html"), new File(docsdir, "frameset.html"));
copy(XHTMLProcessingUtils.class.getResource("resources/master.css"), new File(docsdir, "master.css"));
copy(XHTMLProcessingUtils.class.getResource("resources/styled.css"), new File(docsdir, "styled.css"));
File images = new File(docsdir,"images");
images.mkdir();
copy(XHTMLProcessingUtils.class.getResource("resources/quote-background-1.gif"), new File(images, "quote-background-1.gif"));
//copy(new File("demo.css"), new File(docsdir, "demo.css"));
p(INFO, getString("transforming"));
//File xsltFile = new File("javadoc.xsl");
//p("reading xslt exists in: " + xsltFile.exists());
Source xslt = new StreamSource(xsltStream);
Transformer trans = TransformerFactory.newInstance().newTransformer(xslt);
trans.setErrorListener(new ErrorListener() {
public void warning(TransformerException exception) throws TransformerException {
p(WARNING, "warning: " + exception);
}
public void error(TransformerException exception) throws TransformerException {
Throwable thr = exception;
while (true) {
p(SEVERE, "error: " + exception.getMessageAndLocation(), thr.getCause());
if (thr.getCause() != null) {
thr = thr.getCause();
} else {
break;
}
}
}
public void fatalError(TransformerException exception) throws TransformerException {
p(SEVERE, "fatal error: " + exception.getMessageAndLocation(), exception);
}
});
XPath xpath = XPathFactory.newInstance().newXPath();
// packages
NodeList packages = (NodeList) xpath.evaluate("//package", doc, XPathConstants.NODESET); MessageFormat form = new MessageFormat("The disk \"{1}\" contains {0}.");
p(INFO, MessageFormat.format(getString("creating.packages"), packages.getLength()));
FileOutputStream packages_html = new FileOutputStream(new File(docsdir, "packages.html"));
Writer packages_writer = new OutputStreamWriter(packages_html);
packages_writer.write("<html><head><link href='demo.css' rel='stylesheet'/></head><body><ul class='package-list'>");
FileOutputStream classes_html = new FileOutputStream(new File(docsdir, "classes.html"));
Writer classes_writer = new OutputStreamWriter(classes_html);
classes_writer.write("<html><head><link href='../demo.css' rel='stylesheet'/></head><body><ul>");
for (int i = 0; i < packages.getLength(); i++) {
Element pkg = ((Element) packages.item(i));
String name = pkg.getAttribute("name");
packages_writer.write("<li><a href='"+name+"/classes.html' target='classListFrame'>" + name + "</a></li>");
processPackage(name, pkg, xpath, docsdir, trans);
}
classes_writer.write("</ul></body></html>");
classes_writer.close();
packages_writer.write("</ul></body></html>");
packages_writer.close();
System.out.println(getString("finished"));
}
|
diff --git a/src/web/org/openmrs/web/controller/encounter/EncounterFormController.java b/src/web/org/openmrs/web/controller/encounter/EncounterFormController.java
index 3e49d51b..488378e8 100644
--- a/src/web/org/openmrs/web/controller/encounter/EncounterFormController.java
+++ b/src/web/org/openmrs/web/controller/encounter/EncounterFormController.java
@@ -1,267 +1,272 @@
/**
* The contents of this file are subject to the OpenMRS Public License
* Version 1.0 (the "License"); you may not use this file except in
* compliance with the License. You may obtain a copy of the License at
* http://license.openmrs.org
*
* Software distributed under the License is distributed on an "AS IS"
* basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the
* License for the specific language governing rights and limitations
* under the License.
*
* Copyright (C) OpenMRS, LLC. All Rights Reserved.
*/
package org.openmrs.web.controller.encounter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.SortedMap;
import java.util.TreeMap;
import java.util.Vector;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.openmrs.Encounter;
import org.openmrs.EncounterType;
import org.openmrs.Form;
import org.openmrs.FormField;
import org.openmrs.Location;
import org.openmrs.Obs;
import org.openmrs.api.EncounterService;
import org.openmrs.api.FormService;
import org.openmrs.api.context.Context;
import org.openmrs.propertyeditor.EncounterTypeEditor;
import org.openmrs.propertyeditor.FormEditor;
import org.openmrs.propertyeditor.LocationEditor;
import org.openmrs.util.OpenmrsConstants;
import org.openmrs.util.OpenmrsUtil;
import org.openmrs.web.WebConstants;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.beans.propertyeditors.CustomNumberEditor;
import org.springframework.util.StringUtils;
import org.springframework.validation.BindException;
import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.SimpleFormController;
import org.springframework.web.servlet.view.RedirectView;
/**
* This class controls the encounter.form jsp page.
* See /web/WEB-INF/view/admin/encounters/encounterForm.jsp
*/
public class EncounterFormController extends SimpleFormController {
/** Logger for this class and subclasses */
protected final Log log = LogFactory.getLog(getClass());
/**
*
* Allows for Integers to be used as values in input tags.
* Normally, only strings and lists are expected
*
* @see org.springframework.web.servlet.mvc.BaseCommandController#initBinder(javax.servlet.http.HttpServletRequest, org.springframework.web.bind.ServletRequestDataBinder)
*/
protected void initBinder(HttpServletRequest request, ServletRequestDataBinder binder) throws Exception {
super.initBinder(request, binder);
binder.registerCustomEditor(java.lang.Integer.class,
new CustomNumberEditor(java.lang.Integer.class, true));
binder.registerCustomEditor(java.util.Date.class,
new CustomDateEditor(OpenmrsUtil.getDateFormat(), true));
binder.registerCustomEditor(EncounterType.class, new EncounterTypeEditor());
binder.registerCustomEditor(Location.class, new LocationEditor());
binder.registerCustomEditor(Form.class, new FormEditor());
}
/**
* @see org.springframework.web.servlet.mvc.SimpleFormController#processFormSubmission(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse, java.lang.Object, org.springframework.validation.BindException)
*/
protected ModelAndView processFormSubmission(HttpServletRequest request, HttpServletResponse reponse, Object obj, BindException errors) throws Exception {
Encounter encounter = (Encounter)obj;
Context.addProxyPrivilege(OpenmrsConstants.PRIV_VIEW_USERS);
Context.addProxyPrivilege(OpenmrsConstants.PRIV_VIEW_PATIENTS);
try {
if (Context.isAuthenticated()) {
if (StringUtils.hasText(request.getParameter("patientId")))
encounter.setPatient(Context.getPatientService().getPatient(Integer.valueOf(request.getParameter("patientId"))));
if (StringUtils.hasText(request.getParameter("providerId")))
encounter.setProvider(Context.getUserService().getUser(Integer.valueOf(request.getParameter("providerId"))));
if (encounter.isVoided())
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "voidReason", "error.null");
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "patient", "error.null");
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "provider", "error.null");
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "location", "error.null");
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "encounterDatetime", "error.null");
}
} finally {
Context.removeProxyPrivilege(OpenmrsConstants.PRIV_VIEW_USERS);
Context.removeProxyPrivilege(OpenmrsConstants.PRIV_VIEW_PATIENTS);
}
return super.processFormSubmission(request, reponse, encounter, errors);
}
/**
*
* The onSubmit function receives the form/command object that was modified
* by the input form and saves it to the db
*
* @see org.springframework.web.servlet.mvc.SimpleFormController#onSubmit(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse, java.lang.Object, org.springframework.validation.BindException)
*/
protected ModelAndView onSubmit(HttpServletRequest request, HttpServletResponse response, Object obj, BindException errors) throws Exception {
HttpSession httpSession = request.getSession();
String view = getFormView();
Context.addProxyPrivilege(OpenmrsConstants.PRIV_VIEW_USERS);
Context.addProxyPrivilege(OpenmrsConstants.PRIV_VIEW_PATIENTS);
try {
if (Context.isAuthenticated()) {
Encounter encounter = (Encounter)obj;
// if this is a new encounter, they can specify a patient. add it
if (request.getParameter("patientId") != null)
encounter.setPatient(Context.getPatientService().getPatient(Integer.valueOf(request.getParameter("patientId"))));
// set the provider if they changed it
encounter.setProvider(Context.getUserService().getUser(Integer.valueOf(request.getParameter("providerId"))));
if (encounter.isVoided() && encounter.getVoidedBy() == null)
// if this is a "new" voiding, call voidEncounter to set appropriate attributes
Context.getEncounterService().voidEncounter(encounter, encounter.getVoidReason());
else if (!encounter.isVoided() && encounter.getVoidedBy() != null)
// if this was just unvoided, call unvoidEncounter to unset appropriate attributes
Context.getEncounterService().unvoidEncounter(encounter);
else
Context.getEncounterService().updateEncounter(encounter);
view = getSuccessView();
view = view + "?encounterId=" + encounter.getEncounterId();
httpSession.setAttribute(WebConstants.OPENMRS_MSG_ATTR, "Encounter.saved");
}
} finally {
Context.removeProxyPrivilege(OpenmrsConstants.PRIV_VIEW_USERS);
Context.removeProxyPrivilege(OpenmrsConstants.PRIV_VIEW_PATIENTS);
}
return new ModelAndView(new RedirectView(view));
}
/**
*
* This is called prior to displaying a form for the first time. It tells Spring
* the form/command object to load into the request
*
* @see org.springframework.web.servlet.mvc.AbstractFormController#formBackingObject(javax.servlet.http.HttpServletRequest)
*/
protected Object formBackingObject(HttpServletRequest request) throws ServletException {
Encounter encounter = null;
if (Context.isAuthenticated()) {
EncounterService es = Context.getEncounterService();
String encounterId = request.getParameter("encounterId");
if (encounterId != null) {
encounter = es.getEncounter(Integer.valueOf(encounterId));
}
}
if (encounter == null)
encounter = new Encounter();
return encounter;
}
/**
* @see org.springframework.web.servlet.mvc.SimpleFormController#referenceData(javax.servlet.http.HttpServletRequest, java.lang.Object, org.springframework.validation.Errors)
*/
protected Map<String, Object> referenceData(HttpServletRequest request, Object obj, Errors error) throws Exception {
Encounter encounter = (Encounter)obj;
// the generic returned key-value pair mapping
Map<String, Object> map = new HashMap<String, Object>();
// obsIds of obs that were edited
List<Integer> editedObs = new Vector<Integer>();
// the map returned to the form
- // This is a mapping between the formfield and the Obs/ObsGroup
+ // This is a mapping between the formfield and a list of the Obs/ObsGroup in that field
// This mapping is sorted according to the comparator in FormField.java
- SortedMap<FormField, Obs> obsMapToReturn = new TreeMap<FormField, Obs>();
+ SortedMap<FormField, List<Obs>> obsMapToReturn = new TreeMap<FormField, List<Obs>>();
// this maps the obs to form field objects for non top-level obs
// it is keyed on obs so that when looping over an exploded obsGroup
// the formfield can be fetched easily (in order to show the field numbers etc)
Map<Obs, FormField> otherFormFields = new HashMap<Obs, FormField>();
if (Context.isAuthenticated()) {
EncounterService es = Context.getEncounterService();
FormService fs = Context.getFormService();
// used to restrict the form field lookup
Form form = encounter.getForm();
map.put("encounterTypes", es.getEncounterTypes());
map.put("forms", Context.getFormService().getForms());
// loop over the encounter's observations to find the edited obs
String reason = "";
for (Obs o : encounter.getObsAtTopLevel(true)) {
// only the voided obs have been edited
if (o.isVoided()){
// assumes format of: ".* (new obsId: \d*)"
reason = o.getVoidReason();
int start = reason.lastIndexOf(" ") + 1;
int end = reason.length() - 1;
try {
reason = reason.substring(start, end);
editedObs.add(Integer.valueOf(reason));
} catch (Exception e) {}
}
// get the formfield for this obs
FormField ff = fs.getFormField(form, o.getConcept(), obsMapToReturn.keySet(), false);
if (ff == null) ff = new FormField();
// we only put the top-level obs in the obsMap. Those would
// be the obs that don't have an obs grouper
if (o.getObsGroup() == null) {
// populate the obs map with this formfield and obs
- obsMapToReturn.put(ff, o);
+ List<Obs> list = obsMapToReturn.get(ff);
+ if (list == null) {
+ list = new Vector<Obs>();
+ obsMapToReturn.put(ff, list);
+ }
+ list.add(o);
}
else {
// this is not a top-level obs, just put the formField
// in a separate list and be done with it
otherFormFields.put(o, ff);
}
}
}
if (log.isDebugEnabled())
log.debug("setting obsMap in page context (size: " + obsMapToReturn.size() + ")");
map.put("obsMap", obsMapToReturn);
map.put("otherFormFields", otherFormFields);
map.put("locale", Context.getLocale());
map.put("editedObs", editedObs);
return map;
}
}
| false | true | protected Map<String, Object> referenceData(HttpServletRequest request, Object obj, Errors error) throws Exception {
Encounter encounter = (Encounter)obj;
// the generic returned key-value pair mapping
Map<String, Object> map = new HashMap<String, Object>();
// obsIds of obs that were edited
List<Integer> editedObs = new Vector<Integer>();
// the map returned to the form
// This is a mapping between the formfield and the Obs/ObsGroup
// This mapping is sorted according to the comparator in FormField.java
SortedMap<FormField, Obs> obsMapToReturn = new TreeMap<FormField, Obs>();
// this maps the obs to form field objects for non top-level obs
// it is keyed on obs so that when looping over an exploded obsGroup
// the formfield can be fetched easily (in order to show the field numbers etc)
Map<Obs, FormField> otherFormFields = new HashMap<Obs, FormField>();
if (Context.isAuthenticated()) {
EncounterService es = Context.getEncounterService();
FormService fs = Context.getFormService();
// used to restrict the form field lookup
Form form = encounter.getForm();
map.put("encounterTypes", es.getEncounterTypes());
map.put("forms", Context.getFormService().getForms());
// loop over the encounter's observations to find the edited obs
String reason = "";
for (Obs o : encounter.getObsAtTopLevel(true)) {
// only the voided obs have been edited
if (o.isVoided()){
// assumes format of: ".* (new obsId: \d*)"
reason = o.getVoidReason();
int start = reason.lastIndexOf(" ") + 1;
int end = reason.length() - 1;
try {
reason = reason.substring(start, end);
editedObs.add(Integer.valueOf(reason));
} catch (Exception e) {}
}
// get the formfield for this obs
FormField ff = fs.getFormField(form, o.getConcept(), obsMapToReturn.keySet(), false);
if (ff == null) ff = new FormField();
// we only put the top-level obs in the obsMap. Those would
// be the obs that don't have an obs grouper
if (o.getObsGroup() == null) {
// populate the obs map with this formfield and obs
obsMapToReturn.put(ff, o);
}
else {
// this is not a top-level obs, just put the formField
// in a separate list and be done with it
otherFormFields.put(o, ff);
}
}
}
if (log.isDebugEnabled())
log.debug("setting obsMap in page context (size: " + obsMapToReturn.size() + ")");
map.put("obsMap", obsMapToReturn);
map.put("otherFormFields", otherFormFields);
map.put("locale", Context.getLocale());
map.put("editedObs", editedObs);
return map;
}
| protected Map<String, Object> referenceData(HttpServletRequest request, Object obj, Errors error) throws Exception {
Encounter encounter = (Encounter)obj;
// the generic returned key-value pair mapping
Map<String, Object> map = new HashMap<String, Object>();
// obsIds of obs that were edited
List<Integer> editedObs = new Vector<Integer>();
// the map returned to the form
// This is a mapping between the formfield and a list of the Obs/ObsGroup in that field
// This mapping is sorted according to the comparator in FormField.java
SortedMap<FormField, List<Obs>> obsMapToReturn = new TreeMap<FormField, List<Obs>>();
// this maps the obs to form field objects for non top-level obs
// it is keyed on obs so that when looping over an exploded obsGroup
// the formfield can be fetched easily (in order to show the field numbers etc)
Map<Obs, FormField> otherFormFields = new HashMap<Obs, FormField>();
if (Context.isAuthenticated()) {
EncounterService es = Context.getEncounterService();
FormService fs = Context.getFormService();
// used to restrict the form field lookup
Form form = encounter.getForm();
map.put("encounterTypes", es.getEncounterTypes());
map.put("forms", Context.getFormService().getForms());
// loop over the encounter's observations to find the edited obs
String reason = "";
for (Obs o : encounter.getObsAtTopLevel(true)) {
// only the voided obs have been edited
if (o.isVoided()){
// assumes format of: ".* (new obsId: \d*)"
reason = o.getVoidReason();
int start = reason.lastIndexOf(" ") + 1;
int end = reason.length() - 1;
try {
reason = reason.substring(start, end);
editedObs.add(Integer.valueOf(reason));
} catch (Exception e) {}
}
// get the formfield for this obs
FormField ff = fs.getFormField(form, o.getConcept(), obsMapToReturn.keySet(), false);
if (ff == null) ff = new FormField();
// we only put the top-level obs in the obsMap. Those would
// be the obs that don't have an obs grouper
if (o.getObsGroup() == null) {
// populate the obs map with this formfield and obs
List<Obs> list = obsMapToReturn.get(ff);
if (list == null) {
list = new Vector<Obs>();
obsMapToReturn.put(ff, list);
}
list.add(o);
}
else {
// this is not a top-level obs, just put the formField
// in a separate list and be done with it
otherFormFields.put(o, ff);
}
}
}
if (log.isDebugEnabled())
log.debug("setting obsMap in page context (size: " + obsMapToReturn.size() + ")");
map.put("obsMap", obsMapToReturn);
map.put("otherFormFields", otherFormFields);
map.put("locale", Context.getLocale());
map.put("editedObs", editedObs);
return map;
}
|
diff --git a/services/loanout/client/src/test/java/org/collectionspace/services/client/test/LoanoutAuthRefsTest.java b/services/loanout/client/src/test/java/org/collectionspace/services/client/test/LoanoutAuthRefsTest.java
index 954df1a57..ed87a83ed 100644
--- a/services/loanout/client/src/test/java/org/collectionspace/services/client/test/LoanoutAuthRefsTest.java
+++ b/services/loanout/client/src/test/java/org/collectionspace/services/client/test/LoanoutAuthRefsTest.java
@@ -1,375 +1,376 @@
/**
* This document is a part of the source code and related artifacts
* for CollectionSpace, an open source collections management system
* for museums and related institutions:
*
* http://www.collectionspace.org
* http://wiki.collectionspace.org
*
* Copyright © 2009 Regents of the University of California
*
* Licensed under the Educational Community License (ECL), Version 2.0.
* You may not use this file except in compliance with this License.
*
* You may obtain a copy of the ECL 2.0 License at
* https://source.collectionspace.org/collection-space/LICENSE.txt
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.collectionspace.services.client.test;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import org.collectionspace.services.PersonJAXBSchema;
import org.collectionspace.services.client.CollectionSpaceClient;
import org.collectionspace.services.client.LoanoutClient;
import org.collectionspace.services.client.PersonAuthorityClient;
import org.collectionspace.services.client.PersonAuthorityClientUtils;
import org.collectionspace.services.common.authorityref.AuthorityRefList;
//import org.collectionspace.services.common.authorityref.AuthorityRefList.AuthorityRefItem;
import org.collectionspace.services.jaxb.AbstractCommonList;
import org.collectionspace.services.loanout.LoansoutCommon;
//import org.collectionspace.services.loanout.LoansoutCommonList;
import org.jboss.resteasy.client.ClientResponse;
import org.jboss.resteasy.plugins.providers.multipart.MultipartInput;
import org.jboss.resteasy.plugins.providers.multipart.MultipartOutput;
import org.jboss.resteasy.plugins.providers.multipart.OutputPart;
import org.testng.Assert;
import org.testng.annotations.AfterClass;
import org.testng.annotations.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* LoanoutAuthRefsTest, carries out Authority References tests against a
* deployed and running Loanout (aka Loans Out) Service.
*
* $LastChangedRevision$
* $LastChangedDate$
*/
public class LoanoutAuthRefsTest extends BaseServiceTest {
private final String CLASS_NAME = LoanoutAuthRefsTest.class.getName();
private final Logger logger = LoggerFactory.getLogger(CLASS_NAME);
// Instance variables specific to this test.
final String SERVICE_PATH_COMPONENT = "loansout";
final String PERSON_AUTHORITY_NAME = "TestPersonAuth";
private String knownResourceId = null;
private List<String> loanoutIdsCreated = new ArrayList<String>();
private List<String> personIdsCreated = new ArrayList<String>();
private String personAuthCSID = null;
private String borrowerRefName = null;
private String borrowersContactRefName = null;
private String lendersAuthorizerRefName = null;
private String lendersContactRefName = null;
// FIXME: Can add 'borrower' - likely to be an organization
// authority - as an authRef to tests below, and increase the
// number of expected authRefs to 4.
private final int NUM_AUTH_REFS_EXPECTED = 4;
/* (non-Javadoc)
* @see org.collectionspace.services.client.test.BaseServiceTest#getClientInstance()
*/
@Override
protected CollectionSpaceClient getClientInstance() {
throw new UnsupportedOperationException(); //method not supported (or needed) in this test class
}
/* (non-Javadoc)
* @see org.collectionspace.services.client.test.BaseServiceTest#getAbstractCommonList(org.jboss.resteasy.client.ClientResponse)
*/
@Override
protected AbstractCommonList getAbstractCommonList(
ClientResponse<AbstractCommonList> response) {
throw new UnsupportedOperationException(); //method not supported (or needed) in this test class
}
// ---------------------------------------------------------------
// CRUD tests : CREATE tests
// ---------------------------------------------------------------
// Success outcomes
@Test(dataProvider="testName", dataProviderClass=AbstractServiceTestImpl.class)
public void createWithAuthRefs(String testName) throws Exception {
if (logger.isDebugEnabled()) {
logger.debug(testBanner(testName, CLASS_NAME));
}
testSetup(STATUS_CREATED, ServiceRequestType.CREATE);
// Submit the request to the service and store the response.
String identifier = createIdentifier();
// Create all the person refs and entities
createPersonRefs();
// Create a new Loans In resource.
//
// One or more fields in this resource will be PersonAuthority
// references, and will refer to Person resources by their refNames.
LoanoutClient loanoutClient = new LoanoutClient();
MultipartOutput multipart = createLoanoutInstance(
"loanOutNumber-" + identifier,
"returnDate-" + identifier,
borrowerRefName,
borrowersContactRefName,
lendersAuthorizerRefName,
lendersContactRefName);
ClientResponse<Response> res = loanoutClient.create(multipart);
int statusCode = res.getStatus();
// Check the status code of the response: does it match
// the expected response(s)?
//
// Specifically:
// Does it fall within the set of valid status codes?
// Does it exactly match the expected status code?
if(logger.isDebugEnabled()){
logger.debug(testName + ": status = " + statusCode);
}
Assert.assertTrue(REQUEST_TYPE.isValidStatusCode(statusCode),
invalidStatusCodeMessage(REQUEST_TYPE, statusCode));
Assert.assertEquals(statusCode, EXPECTED_STATUS_CODE);
// Store the ID returned from the first resource created
// for additional tests below.
if (knownResourceId == null){
knownResourceId = extractId(res);
if (logger.isDebugEnabled()) {
logger.debug(testName + ": knownResourceId=" + knownResourceId);
}
}
// Store the IDs from every resource created by tests,
// so they can be deleted after tests have been run.
loanoutIdsCreated.add(extractId(res));
}
protected void createPersonRefs(){
PersonAuthorityClient personAuthClient = new PersonAuthorityClient();
// Create a temporary PersonAuthority resource, and its corresponding
// refName by which it can be identified.
MultipartOutput multipart = PersonAuthorityClientUtils.createPersonAuthorityInstance(
PERSON_AUTHORITY_NAME, PERSON_AUTHORITY_NAME, personAuthClient.getCommonPartName());
ClientResponse<Response> res = personAuthClient.create(multipart);
int statusCode = res.getStatus();
Assert.assertTrue(REQUEST_TYPE.isValidStatusCode(statusCode),
invalidStatusCodeMessage(REQUEST_TYPE, statusCode));
Assert.assertEquals(statusCode, STATUS_CREATED);
personAuthCSID = extractId(res);
String authRefName = PersonAuthorityClientUtils.getAuthorityRefName(personAuthCSID, null);
// Create temporary Person resources, and their corresponding refNames
// by which they can be identified.
String csid = "";
csid = createPerson("Betty", "Borrower", "bettyBorrower", authRefName);
personIdsCreated.add(csid);
borrowerRefName = PersonAuthorityClientUtils.getPersonRefName(personAuthCSID, csid, null);
csid = createPerson("Bradley", "BorrowersContact", "bradleyBorrowersContact", authRefName);
personIdsCreated.add(csid);
borrowersContactRefName = PersonAuthorityClientUtils.getPersonRefName(personAuthCSID, csid, null);
csid = createPerson("Art", "Lendersauthorizor", "artLendersauthorizor", authRefName);
personIdsCreated.add(csid);
lendersAuthorizerRefName = PersonAuthorityClientUtils.getPersonRefName(personAuthCSID, csid, null);
csid = createPerson("Larry", "Lenderscontact", "larryLenderscontact", authRefName);
personIdsCreated.add(csid);
lendersContactRefName = PersonAuthorityClientUtils.getPersonRefName(personAuthCSID, csid, null);
}
protected String createPerson(String firstName, String surName, String shortId, String authRefName ) {
PersonAuthorityClient personAuthClient = new PersonAuthorityClient();
Map<String, String> personInfo = new HashMap<String,String>();
personInfo.put(PersonJAXBSchema.FORE_NAME, firstName);
personInfo.put(PersonJAXBSchema.SUR_NAME, surName);
personInfo.put(PersonJAXBSchema.SHORT_IDENTIFIER, shortId);
MultipartOutput multipart =
PersonAuthorityClientUtils.createPersonInstance(personAuthCSID,
authRefName, personInfo, personAuthClient.getItemCommonPartName());
ClientResponse<Response> res = personAuthClient.createItem(personAuthCSID, multipart);
int statusCode = res.getStatus();
Assert.assertTrue(REQUEST_TYPE.isValidStatusCode(statusCode),
invalidStatusCodeMessage(REQUEST_TYPE, statusCode));
Assert.assertEquals(statusCode, STATUS_CREATED);
return extractId(res);
}
// Success outcomes
@Test(dataProvider="testName", dataProviderClass=AbstractServiceTestImpl.class,
dependsOnMethods = {"createWithAuthRefs"})
public void readAndCheckAuthRefs(String testName) throws Exception {
if (logger.isDebugEnabled()) {
logger.debug(testBanner(testName, CLASS_NAME));
}
// Perform setup.
testSetup(STATUS_OK, ServiceRequestType.READ);
// Submit the request to the service and store the response.
LoanoutClient loanoutClient = new LoanoutClient();
ClientResponse<MultipartInput> res = loanoutClient.read(knownResourceId);
int statusCode = res.getStatus();
// Check the status code of the response: does it match
// the expected response(s)?
if(logger.isDebugEnabled()){
logger.debug(testName + ".read: status = " + statusCode);
}
Assert.assertTrue(REQUEST_TYPE.isValidStatusCode(statusCode),
invalidStatusCodeMessage(REQUEST_TYPE, statusCode));
Assert.assertEquals(statusCode, EXPECTED_STATUS_CODE);
MultipartInput input = (MultipartInput) res.getEntity();
LoansoutCommon loanout = (LoansoutCommon) extractPart(input,
loanoutClient.getCommonPartName(), LoansoutCommon.class);
Assert.assertNotNull(loanout);
if(logger.isDebugEnabled()){
logger.debug(objectAsXmlString(loanout, LoansoutCommon.class));
}
// Check a couple of fields
+ Assert.assertEquals(loanout.getBorrower(), borrowerRefName);
Assert.assertEquals(loanout.getBorrowersContact(), borrowersContactRefName);
Assert.assertEquals(loanout.getLendersAuthorizer(), lendersAuthorizerRefName);
Assert.assertEquals(loanout.getLendersContact(), lendersContactRefName);
// Get the auth refs and check them
ClientResponse<AuthorityRefList> res2 =
loanoutClient.getAuthorityRefs(knownResourceId);
statusCode = res2.getStatus();
if(logger.isDebugEnabled()){
logger.debug(testName + ".getAuthorityRefs: status = " + statusCode);
}
Assert.assertTrue(REQUEST_TYPE.isValidStatusCode(statusCode),
invalidStatusCodeMessage(REQUEST_TYPE, statusCode));
Assert.assertEquals(statusCode, EXPECTED_STATUS_CODE);
AuthorityRefList list = res2.getEntity();
List<AuthorityRefList.AuthorityRefItem> items = list.getAuthorityRefItem();
int numAuthRefsFound = items.size();
if(logger.isDebugEnabled()){
logger.debug("Expected " + NUM_AUTH_REFS_EXPECTED +
" authority references, found " + numAuthRefsFound);
}
Assert.assertEquals(numAuthRefsFound, NUM_AUTH_REFS_EXPECTED,
"Did not find all expected authority references! " +
"Expected " + NUM_AUTH_REFS_EXPECTED + ", found " + numAuthRefsFound);
// Optionally output additional data about list members for debugging.
boolean iterateThroughList = true;
if(iterateThroughList && logger.isDebugEnabled()){
int i = 0;
for(AuthorityRefList.AuthorityRefItem item : items){
logger.debug(testName + ": list-item[" + i + "] Field:" +
item.getSourceField() + "= " +
item.getAuthDisplayName() +
item.getItemDisplayName());
logger.debug(testName + ": list-item[" + i + "] refName=" +
item.getRefName());
logger.debug(testName + ": list-item[" + i + "] URI=" +
item.getUri());
i++;
}
}
}
// ---------------------------------------------------------------
// Cleanup of resources created during testing
// ---------------------------------------------------------------
/**
* Deletes all resources created by tests, after all tests have been run.
*
* This cleanup method will always be run, even if one or more tests fail.
* For this reason, it attempts to remove all resources created
* at any point during testing, even if some of those resources
* may be expected to be deleted by certain tests.
*/
@AfterClass(alwaysRun=true)
public void cleanUp() {
String noTest = System.getProperty("noTestCleanup");
if(Boolean.TRUE.toString().equalsIgnoreCase(noTest)) {
if (logger.isDebugEnabled()) {
logger.debug("Skipping Cleanup phase ...");
}
return;
}
if (logger.isDebugEnabled()) {
logger.debug("Cleaning up temporary resources created for testing ...");
}
PersonAuthorityClient personAuthClient = new PersonAuthorityClient();
// Delete Person resource(s) (before PersonAuthority resources).
for (String resourceId : personIdsCreated) {
// Note: Any non-success responses are ignored and not reported.
personAuthClient.deleteItem(personAuthCSID, resourceId);
}
// Delete PersonAuthority resource(s).
// Note: Any non-success response is ignored and not reported.
if (personAuthCSID != null) {
personAuthClient.delete(personAuthCSID);
// Delete Loans In resource(s).
LoanoutClient loanoutClient = new LoanoutClient();
for (String resourceId : loanoutIdsCreated) {
// Note: Any non-success responses are ignored and not reported.
loanoutClient.delete(resourceId);
}
}
}
// ---------------------------------------------------------------
// Utility methods used by tests above
// ---------------------------------------------------------------
@Override
public String getServicePathComponent() {
return SERVICE_PATH_COMPONENT;
}
private MultipartOutput createLoanoutInstance(String loanoutNumber,
String returnDate,
String borrower,
String borrowersContact,
String lendersAuthorizer,
String lendersContact) {
LoansoutCommon loanout = new LoansoutCommon();
loanout.setLoanOutNumber(loanoutNumber);
loanout.setLoanReturnDate(returnDate);
loanout.setBorrower(borrower);
loanout.setBorrowersContact(borrowersContact);
loanout.setLendersAuthorizer(lendersAuthorizer);
loanout.setLendersContact(lendersContact);
MultipartOutput multipart = new MultipartOutput();
OutputPart commonPart =
multipart.addPart(loanout, MediaType.APPLICATION_XML_TYPE);
commonPart.getHeaders().add("label", new LoanoutClient().getCommonPartName());
if(logger.isDebugEnabled()){
logger.debug("to be created, loanout common");
logger.debug(objectAsXmlString(loanout, LoansoutCommon.class));
}
return multipart;
}
}
| true | true | public void readAndCheckAuthRefs(String testName) throws Exception {
if (logger.isDebugEnabled()) {
logger.debug(testBanner(testName, CLASS_NAME));
}
// Perform setup.
testSetup(STATUS_OK, ServiceRequestType.READ);
// Submit the request to the service and store the response.
LoanoutClient loanoutClient = new LoanoutClient();
ClientResponse<MultipartInput> res = loanoutClient.read(knownResourceId);
int statusCode = res.getStatus();
// Check the status code of the response: does it match
// the expected response(s)?
if(logger.isDebugEnabled()){
logger.debug(testName + ".read: status = " + statusCode);
}
Assert.assertTrue(REQUEST_TYPE.isValidStatusCode(statusCode),
invalidStatusCodeMessage(REQUEST_TYPE, statusCode));
Assert.assertEquals(statusCode, EXPECTED_STATUS_CODE);
MultipartInput input = (MultipartInput) res.getEntity();
LoansoutCommon loanout = (LoansoutCommon) extractPart(input,
loanoutClient.getCommonPartName(), LoansoutCommon.class);
Assert.assertNotNull(loanout);
if(logger.isDebugEnabled()){
logger.debug(objectAsXmlString(loanout, LoansoutCommon.class));
}
// Check a couple of fields
Assert.assertEquals(loanout.getBorrowersContact(), borrowersContactRefName);
Assert.assertEquals(loanout.getLendersAuthorizer(), lendersAuthorizerRefName);
Assert.assertEquals(loanout.getLendersContact(), lendersContactRefName);
// Get the auth refs and check them
ClientResponse<AuthorityRefList> res2 =
loanoutClient.getAuthorityRefs(knownResourceId);
statusCode = res2.getStatus();
if(logger.isDebugEnabled()){
logger.debug(testName + ".getAuthorityRefs: status = " + statusCode);
}
Assert.assertTrue(REQUEST_TYPE.isValidStatusCode(statusCode),
invalidStatusCodeMessage(REQUEST_TYPE, statusCode));
Assert.assertEquals(statusCode, EXPECTED_STATUS_CODE);
AuthorityRefList list = res2.getEntity();
List<AuthorityRefList.AuthorityRefItem> items = list.getAuthorityRefItem();
int numAuthRefsFound = items.size();
if(logger.isDebugEnabled()){
logger.debug("Expected " + NUM_AUTH_REFS_EXPECTED +
" authority references, found " + numAuthRefsFound);
}
Assert.assertEquals(numAuthRefsFound, NUM_AUTH_REFS_EXPECTED,
"Did not find all expected authority references! " +
"Expected " + NUM_AUTH_REFS_EXPECTED + ", found " + numAuthRefsFound);
// Optionally output additional data about list members for debugging.
boolean iterateThroughList = true;
if(iterateThroughList && logger.isDebugEnabled()){
int i = 0;
for(AuthorityRefList.AuthorityRefItem item : items){
logger.debug(testName + ": list-item[" + i + "] Field:" +
item.getSourceField() + "= " +
item.getAuthDisplayName() +
item.getItemDisplayName());
logger.debug(testName + ": list-item[" + i + "] refName=" +
item.getRefName());
logger.debug(testName + ": list-item[" + i + "] URI=" +
item.getUri());
i++;
}
}
}
| public void readAndCheckAuthRefs(String testName) throws Exception {
if (logger.isDebugEnabled()) {
logger.debug(testBanner(testName, CLASS_NAME));
}
// Perform setup.
testSetup(STATUS_OK, ServiceRequestType.READ);
// Submit the request to the service and store the response.
LoanoutClient loanoutClient = new LoanoutClient();
ClientResponse<MultipartInput> res = loanoutClient.read(knownResourceId);
int statusCode = res.getStatus();
// Check the status code of the response: does it match
// the expected response(s)?
if(logger.isDebugEnabled()){
logger.debug(testName + ".read: status = " + statusCode);
}
Assert.assertTrue(REQUEST_TYPE.isValidStatusCode(statusCode),
invalidStatusCodeMessage(REQUEST_TYPE, statusCode));
Assert.assertEquals(statusCode, EXPECTED_STATUS_CODE);
MultipartInput input = (MultipartInput) res.getEntity();
LoansoutCommon loanout = (LoansoutCommon) extractPart(input,
loanoutClient.getCommonPartName(), LoansoutCommon.class);
Assert.assertNotNull(loanout);
if(logger.isDebugEnabled()){
logger.debug(objectAsXmlString(loanout, LoansoutCommon.class));
}
// Check a couple of fields
Assert.assertEquals(loanout.getBorrower(), borrowerRefName);
Assert.assertEquals(loanout.getBorrowersContact(), borrowersContactRefName);
Assert.assertEquals(loanout.getLendersAuthorizer(), lendersAuthorizerRefName);
Assert.assertEquals(loanout.getLendersContact(), lendersContactRefName);
// Get the auth refs and check them
ClientResponse<AuthorityRefList> res2 =
loanoutClient.getAuthorityRefs(knownResourceId);
statusCode = res2.getStatus();
if(logger.isDebugEnabled()){
logger.debug(testName + ".getAuthorityRefs: status = " + statusCode);
}
Assert.assertTrue(REQUEST_TYPE.isValidStatusCode(statusCode),
invalidStatusCodeMessage(REQUEST_TYPE, statusCode));
Assert.assertEquals(statusCode, EXPECTED_STATUS_CODE);
AuthorityRefList list = res2.getEntity();
List<AuthorityRefList.AuthorityRefItem> items = list.getAuthorityRefItem();
int numAuthRefsFound = items.size();
if(logger.isDebugEnabled()){
logger.debug("Expected " + NUM_AUTH_REFS_EXPECTED +
" authority references, found " + numAuthRefsFound);
}
Assert.assertEquals(numAuthRefsFound, NUM_AUTH_REFS_EXPECTED,
"Did not find all expected authority references! " +
"Expected " + NUM_AUTH_REFS_EXPECTED + ", found " + numAuthRefsFound);
// Optionally output additional data about list members for debugging.
boolean iterateThroughList = true;
if(iterateThroughList && logger.isDebugEnabled()){
int i = 0;
for(AuthorityRefList.AuthorityRefItem item : items){
logger.debug(testName + ": list-item[" + i + "] Field:" +
item.getSourceField() + "= " +
item.getAuthDisplayName() +
item.getItemDisplayName());
logger.debug(testName + ": list-item[" + i + "] refName=" +
item.getRefName());
logger.debug(testName + ": list-item[" + i + "] URI=" +
item.getUri());
i++;
}
}
}
|
diff --git a/SeriesGuide/src/main/java/com/battlelancer/seriesguide/ui/ConnectTraktCredentialsFragment.java b/SeriesGuide/src/main/java/com/battlelancer/seriesguide/ui/ConnectTraktCredentialsFragment.java
index ab76f28a4..5cd019a37 100644
--- a/SeriesGuide/src/main/java/com/battlelancer/seriesguide/ui/ConnectTraktCredentialsFragment.java
+++ b/SeriesGuide/src/main/java/com/battlelancer/seriesguide/ui/ConnectTraktCredentialsFragment.java
@@ -1,297 +1,300 @@
/*
* Copyright 2012 Uwe Trottmann
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.battlelancer.seriesguide.ui;
import com.actionbarsherlock.app.SherlockFragment;
import com.battlelancer.seriesguide.enums.TraktAction;
import com.battlelancer.seriesguide.enums.TraktStatus;
import com.battlelancer.seriesguide.settings.TraktSettings;
import com.battlelancer.seriesguide.util.ServiceUtils;
import com.battlelancer.seriesguide.util.ShareUtils.ProgressDialog;
import com.battlelancer.seriesguide.util.ShareUtils.ShareItems;
import com.battlelancer.seriesguide.util.SimpleCrypto;
import com.battlelancer.seriesguide.util.TraktTask;
import com.battlelancer.seriesguide.util.Utils;
import com.jakewharton.trakt.Trakt;
import com.jakewharton.trakt.entities.Response;
import com.jakewharton.trakt.services.AccountService;
import com.uwetrottmann.androidutils.AndroidUtils;
import com.uwetrottmann.seriesguide.R;
import android.content.Context;
import android.content.SharedPreferences.Editor;
import android.os.AsyncTask;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.EditText;
import android.widget.TextView;
import retrofit.RetrofitError;
public class ConnectTraktCredentialsFragment extends SherlockFragment {
private boolean isForwardingGivenTask;
public static ConnectTraktCredentialsFragment newInstance(Bundle traktData) {
ConnectTraktCredentialsFragment f = new ConnectTraktCredentialsFragment();
f.setArguments(traktData);
f.isForwardingGivenTask = true;
return f;
}
public static ConnectTraktCredentialsFragment newInstance() {
ConnectTraktCredentialsFragment f = new ConnectTraktCredentialsFragment();
f.isForwardingGivenTask = false;
return f;
}
@Override
public void onStart() {
super.onStart();
Utils.trackView(getActivity(), "Connect Trakt Credentials");
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final Context context = getActivity().getApplicationContext();
final View layout = inflater.inflate(R.layout.trakt_credentials_dialog, container, false);
final FragmentManager fm = getFragmentManager();
final Bundle args = getArguments();
// restore the username from settings
final String username = TraktSettings.getUsername(context);
// new account toggle
final View mailviews = layout.findViewById(R.id.mailviews);
mailviews.setVisibility(View.GONE);
CheckBox newAccCheckBox = (CheckBox) layout.findViewById(R.id.checkNewAccount);
newAccCheckBox.setOnCheckedChangeListener(new OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
mailviews.setVisibility(View.VISIBLE);
} else {
mailviews.setVisibility(View.GONE);
}
}
});
// status strip
final TextView status = (TextView) layout.findViewById(R.id.status);
final View progressbar = layout.findViewById(R.id.progressbar);
final View progress = layout.findViewById(R.id.progress);
progress.setVisibility(View.GONE);
final Button connectbtn = (Button) layout.findViewById(R.id.connectbutton);
final Button disconnectbtn = (Button) layout.findViewById(R.id.disconnectbutton);
// enable buttons based on if there are saved credentials
if (TextUtils.isEmpty(username)) {
// user has to enable first
disconnectbtn.setEnabled(false);
} else {
// make it obvious trakt is connected
connectbtn.setEnabled(false);
EditText usernameField = (EditText) layout.findViewById(R.id.username);
usernameField.setEnabled(false);
usernameField.setText(username);
EditText passwordField = (EditText) layout.findViewById(R.id.password);
passwordField.setEnabled(false);
passwordField.setText("********"); // fake password
newAccCheckBox.setEnabled(false);
}
connectbtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// prevent multiple instances
connectbtn.setEnabled(false);
disconnectbtn.setEnabled(false);
final String username = ((EditText) layout.findViewById(R.id.username)).getText()
.toString();
final String passwordHash = Utils.toSHA1(context, ((EditText) layout
.findViewById(R.id.password)).getText().toString());
final String email = ((EditText) layout.findViewById(R.id.email)).getText()
.toString();
final boolean isNewAccount = ((CheckBox) layout.findViewById(R.id.checkNewAccount))
.isChecked();
final String traktApiKey = getResources().getString(R.string.trakt_apikey);
AsyncTask<String, Void, Response> accountValidatorTask
= new AsyncTask<String, Void, Response>() {
@Override
protected void onPreExecute() {
progress.setVisibility(View.VISIBLE);
progressbar.setVisibility(View.VISIBLE);
status.setText(R.string.waitplease);
}
@Override
protected Response doInBackground(String... params) {
// check if we have any usable data
if (username.length() == 0 || passwordHash == null) {
return null;
}
// check for connectivity
if (!AndroidUtils.isNetworkConnected(context)) {
Response r = new Response();
r.status = TraktStatus.FAILURE;
r.error = context.getString(R.string.offline);
return r;
}
// use a separate ServiceManager here to avoid
// setting wrong credentials
final Trakt manager = new Trakt();
manager.setApiKey(traktApiKey);
manager.setAuthentication(username, passwordHash);
Response response = null;
try {
if (isNewAccount) {
// create new account
response = manager.accountService().create(
new AccountService.NewAccount(username, passwordHash,
email));
} else {
// validate existing account
response = manager.accountService().test();
}
} catch (RetrofitError e) {
response = null;
}
return response;
}
@Override
protected void onPostExecute(Response response) {
progressbar.setVisibility(View.GONE);
connectbtn.setEnabled(true);
if (response == null) {
status.setText(R.string.trakt_error_credentials);
return;
}
if (response.status.equals(TraktStatus.FAILURE)) {
status.setText(response.error);
return;
}
// try to encrypt the password before storing it
String passwordEncr = SimpleCrypto.encrypt(passwordHash, context);
if (passwordEncr == null) {
// password encryption failed
status.setText(R.string.trakt_error_credentials);
return;
}
// prepare writing credentials to settings
final Editor editor = PreferenceManager.getDefaultSharedPreferences(context)
.edit();
editor.putString(TraktSettings.KEY_USERNAME, username).putString(
TraktSettings.KEY_PASSWORD_SHA1_ENCR, passwordEncr);
if (response.status.equals(TraktStatus.SUCCESS)
&& passwordEncr.length() != 0 && editor.commit()) {
// try setting new auth data for service manager
if (ServiceUtils.getTraktServiceManagerWithAuth(context, true)
== null) {
status.setText(R.string.trakt_error_credentials);
return;
}
if (isForwardingGivenTask) {
// continue with original task
if (TraktAction.values()[args.getInt(ShareItems.TRAKTACTION)]
== TraktAction.CHECKIN_EPISODE) {
FragmentTransaction ft = fm.beginTransaction();
Fragment prev = fm.findFragmentByTag("progress-dialog");
if (prev != null) {
ft.remove(prev);
}
ProgressDialog newFragment = ProgressDialog.newInstance();
newFragment.show(ft, "progress-dialog");
}
// relaunch the trakt task which called us
AndroidUtils.executeAsyncTask(
new TraktTask(context, args, null), new Void[]{
null
});
FragmentActivity activity = getActivity();
if (activity != null) {
activity.finish();
}
} else {
// show options after successful connection
- ConnectTraktFinishedFragment f = new ConnectTraktFinishedFragment();
- FragmentTransaction ft = getFragmentManager().beginTransaction();
- ft.replace(android.R.id.content, f);
- ft.commit();
+ FragmentManager fm = getFragmentManager();
+ if (fm != null) {
+ ConnectTraktFinishedFragment f = new ConnectTraktFinishedFragment();
+ FragmentTransaction ft = fm.beginTransaction();
+ ft.replace(android.R.id.content, f);
+ ft.commit();
+ }
}
}
}
};
accountValidatorTask.execute();
}
});
disconnectbtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// clear trakt credentials
new AsyncTask<Void, Void, Void>() {
@Override
protected Void doInBackground(Void... params) {
ServiceUtils.clearTraktCredentials(context);
return null;
}
}.execute();
getActivity().finish();
}
});
return layout;
}
}
| true | true | public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final Context context = getActivity().getApplicationContext();
final View layout = inflater.inflate(R.layout.trakt_credentials_dialog, container, false);
final FragmentManager fm = getFragmentManager();
final Bundle args = getArguments();
// restore the username from settings
final String username = TraktSettings.getUsername(context);
// new account toggle
final View mailviews = layout.findViewById(R.id.mailviews);
mailviews.setVisibility(View.GONE);
CheckBox newAccCheckBox = (CheckBox) layout.findViewById(R.id.checkNewAccount);
newAccCheckBox.setOnCheckedChangeListener(new OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
mailviews.setVisibility(View.VISIBLE);
} else {
mailviews.setVisibility(View.GONE);
}
}
});
// status strip
final TextView status = (TextView) layout.findViewById(R.id.status);
final View progressbar = layout.findViewById(R.id.progressbar);
final View progress = layout.findViewById(R.id.progress);
progress.setVisibility(View.GONE);
final Button connectbtn = (Button) layout.findViewById(R.id.connectbutton);
final Button disconnectbtn = (Button) layout.findViewById(R.id.disconnectbutton);
// enable buttons based on if there are saved credentials
if (TextUtils.isEmpty(username)) {
// user has to enable first
disconnectbtn.setEnabled(false);
} else {
// make it obvious trakt is connected
connectbtn.setEnabled(false);
EditText usernameField = (EditText) layout.findViewById(R.id.username);
usernameField.setEnabled(false);
usernameField.setText(username);
EditText passwordField = (EditText) layout.findViewById(R.id.password);
passwordField.setEnabled(false);
passwordField.setText("********"); // fake password
newAccCheckBox.setEnabled(false);
}
connectbtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// prevent multiple instances
connectbtn.setEnabled(false);
disconnectbtn.setEnabled(false);
final String username = ((EditText) layout.findViewById(R.id.username)).getText()
.toString();
final String passwordHash = Utils.toSHA1(context, ((EditText) layout
.findViewById(R.id.password)).getText().toString());
final String email = ((EditText) layout.findViewById(R.id.email)).getText()
.toString();
final boolean isNewAccount = ((CheckBox) layout.findViewById(R.id.checkNewAccount))
.isChecked();
final String traktApiKey = getResources().getString(R.string.trakt_apikey);
AsyncTask<String, Void, Response> accountValidatorTask
= new AsyncTask<String, Void, Response>() {
@Override
protected void onPreExecute() {
progress.setVisibility(View.VISIBLE);
progressbar.setVisibility(View.VISIBLE);
status.setText(R.string.waitplease);
}
@Override
protected Response doInBackground(String... params) {
// check if we have any usable data
if (username.length() == 0 || passwordHash == null) {
return null;
}
// check for connectivity
if (!AndroidUtils.isNetworkConnected(context)) {
Response r = new Response();
r.status = TraktStatus.FAILURE;
r.error = context.getString(R.string.offline);
return r;
}
// use a separate ServiceManager here to avoid
// setting wrong credentials
final Trakt manager = new Trakt();
manager.setApiKey(traktApiKey);
manager.setAuthentication(username, passwordHash);
Response response = null;
try {
if (isNewAccount) {
// create new account
response = manager.accountService().create(
new AccountService.NewAccount(username, passwordHash,
email));
} else {
// validate existing account
response = manager.accountService().test();
}
} catch (RetrofitError e) {
response = null;
}
return response;
}
@Override
protected void onPostExecute(Response response) {
progressbar.setVisibility(View.GONE);
connectbtn.setEnabled(true);
if (response == null) {
status.setText(R.string.trakt_error_credentials);
return;
}
if (response.status.equals(TraktStatus.FAILURE)) {
status.setText(response.error);
return;
}
// try to encrypt the password before storing it
String passwordEncr = SimpleCrypto.encrypt(passwordHash, context);
if (passwordEncr == null) {
// password encryption failed
status.setText(R.string.trakt_error_credentials);
return;
}
// prepare writing credentials to settings
final Editor editor = PreferenceManager.getDefaultSharedPreferences(context)
.edit();
editor.putString(TraktSettings.KEY_USERNAME, username).putString(
TraktSettings.KEY_PASSWORD_SHA1_ENCR, passwordEncr);
if (response.status.equals(TraktStatus.SUCCESS)
&& passwordEncr.length() != 0 && editor.commit()) {
// try setting new auth data for service manager
if (ServiceUtils.getTraktServiceManagerWithAuth(context, true)
== null) {
status.setText(R.string.trakt_error_credentials);
return;
}
if (isForwardingGivenTask) {
// continue with original task
if (TraktAction.values()[args.getInt(ShareItems.TRAKTACTION)]
== TraktAction.CHECKIN_EPISODE) {
FragmentTransaction ft = fm.beginTransaction();
Fragment prev = fm.findFragmentByTag("progress-dialog");
if (prev != null) {
ft.remove(prev);
}
ProgressDialog newFragment = ProgressDialog.newInstance();
newFragment.show(ft, "progress-dialog");
}
// relaunch the trakt task which called us
AndroidUtils.executeAsyncTask(
new TraktTask(context, args, null), new Void[]{
null
});
FragmentActivity activity = getActivity();
if (activity != null) {
activity.finish();
}
} else {
// show options after successful connection
ConnectTraktFinishedFragment f = new ConnectTraktFinishedFragment();
FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.replace(android.R.id.content, f);
ft.commit();
}
}
}
};
accountValidatorTask.execute();
}
});
disconnectbtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// clear trakt credentials
new AsyncTask<Void, Void, Void>() {
@Override
protected Void doInBackground(Void... params) {
ServiceUtils.clearTraktCredentials(context);
return null;
}
}.execute();
getActivity().finish();
}
});
return layout;
}
| public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final Context context = getActivity().getApplicationContext();
final View layout = inflater.inflate(R.layout.trakt_credentials_dialog, container, false);
final FragmentManager fm = getFragmentManager();
final Bundle args = getArguments();
// restore the username from settings
final String username = TraktSettings.getUsername(context);
// new account toggle
final View mailviews = layout.findViewById(R.id.mailviews);
mailviews.setVisibility(View.GONE);
CheckBox newAccCheckBox = (CheckBox) layout.findViewById(R.id.checkNewAccount);
newAccCheckBox.setOnCheckedChangeListener(new OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
mailviews.setVisibility(View.VISIBLE);
} else {
mailviews.setVisibility(View.GONE);
}
}
});
// status strip
final TextView status = (TextView) layout.findViewById(R.id.status);
final View progressbar = layout.findViewById(R.id.progressbar);
final View progress = layout.findViewById(R.id.progress);
progress.setVisibility(View.GONE);
final Button connectbtn = (Button) layout.findViewById(R.id.connectbutton);
final Button disconnectbtn = (Button) layout.findViewById(R.id.disconnectbutton);
// enable buttons based on if there are saved credentials
if (TextUtils.isEmpty(username)) {
// user has to enable first
disconnectbtn.setEnabled(false);
} else {
// make it obvious trakt is connected
connectbtn.setEnabled(false);
EditText usernameField = (EditText) layout.findViewById(R.id.username);
usernameField.setEnabled(false);
usernameField.setText(username);
EditText passwordField = (EditText) layout.findViewById(R.id.password);
passwordField.setEnabled(false);
passwordField.setText("********"); // fake password
newAccCheckBox.setEnabled(false);
}
connectbtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// prevent multiple instances
connectbtn.setEnabled(false);
disconnectbtn.setEnabled(false);
final String username = ((EditText) layout.findViewById(R.id.username)).getText()
.toString();
final String passwordHash = Utils.toSHA1(context, ((EditText) layout
.findViewById(R.id.password)).getText().toString());
final String email = ((EditText) layout.findViewById(R.id.email)).getText()
.toString();
final boolean isNewAccount = ((CheckBox) layout.findViewById(R.id.checkNewAccount))
.isChecked();
final String traktApiKey = getResources().getString(R.string.trakt_apikey);
AsyncTask<String, Void, Response> accountValidatorTask
= new AsyncTask<String, Void, Response>() {
@Override
protected void onPreExecute() {
progress.setVisibility(View.VISIBLE);
progressbar.setVisibility(View.VISIBLE);
status.setText(R.string.waitplease);
}
@Override
protected Response doInBackground(String... params) {
// check if we have any usable data
if (username.length() == 0 || passwordHash == null) {
return null;
}
// check for connectivity
if (!AndroidUtils.isNetworkConnected(context)) {
Response r = new Response();
r.status = TraktStatus.FAILURE;
r.error = context.getString(R.string.offline);
return r;
}
// use a separate ServiceManager here to avoid
// setting wrong credentials
final Trakt manager = new Trakt();
manager.setApiKey(traktApiKey);
manager.setAuthentication(username, passwordHash);
Response response = null;
try {
if (isNewAccount) {
// create new account
response = manager.accountService().create(
new AccountService.NewAccount(username, passwordHash,
email));
} else {
// validate existing account
response = manager.accountService().test();
}
} catch (RetrofitError e) {
response = null;
}
return response;
}
@Override
protected void onPostExecute(Response response) {
progressbar.setVisibility(View.GONE);
connectbtn.setEnabled(true);
if (response == null) {
status.setText(R.string.trakt_error_credentials);
return;
}
if (response.status.equals(TraktStatus.FAILURE)) {
status.setText(response.error);
return;
}
// try to encrypt the password before storing it
String passwordEncr = SimpleCrypto.encrypt(passwordHash, context);
if (passwordEncr == null) {
// password encryption failed
status.setText(R.string.trakt_error_credentials);
return;
}
// prepare writing credentials to settings
final Editor editor = PreferenceManager.getDefaultSharedPreferences(context)
.edit();
editor.putString(TraktSettings.KEY_USERNAME, username).putString(
TraktSettings.KEY_PASSWORD_SHA1_ENCR, passwordEncr);
if (response.status.equals(TraktStatus.SUCCESS)
&& passwordEncr.length() != 0 && editor.commit()) {
// try setting new auth data for service manager
if (ServiceUtils.getTraktServiceManagerWithAuth(context, true)
== null) {
status.setText(R.string.trakt_error_credentials);
return;
}
if (isForwardingGivenTask) {
// continue with original task
if (TraktAction.values()[args.getInt(ShareItems.TRAKTACTION)]
== TraktAction.CHECKIN_EPISODE) {
FragmentTransaction ft = fm.beginTransaction();
Fragment prev = fm.findFragmentByTag("progress-dialog");
if (prev != null) {
ft.remove(prev);
}
ProgressDialog newFragment = ProgressDialog.newInstance();
newFragment.show(ft, "progress-dialog");
}
// relaunch the trakt task which called us
AndroidUtils.executeAsyncTask(
new TraktTask(context, args, null), new Void[]{
null
});
FragmentActivity activity = getActivity();
if (activity != null) {
activity.finish();
}
} else {
// show options after successful connection
FragmentManager fm = getFragmentManager();
if (fm != null) {
ConnectTraktFinishedFragment f = new ConnectTraktFinishedFragment();
FragmentTransaction ft = fm.beginTransaction();
ft.replace(android.R.id.content, f);
ft.commit();
}
}
}
}
};
accountValidatorTask.execute();
}
});
disconnectbtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// clear trakt credentials
new AsyncTask<Void, Void, Void>() {
@Override
protected Void doInBackground(Void... params) {
ServiceUtils.clearTraktCredentials(context);
return null;
}
}.execute();
getActivity().finish();
}
});
return layout;
}
|
diff --git a/OVE/src/main/java/Mail/MailConfirmServlet.java b/OVE/src/main/java/Mail/MailConfirmServlet.java
index d6db4a4..7241e09 100644
--- a/OVE/src/main/java/Mail/MailConfirmServlet.java
+++ b/OVE/src/main/java/Mail/MailConfirmServlet.java
@@ -1,87 +1,87 @@
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package Mail;
import EJB.UserRegistry;
import Model.Account;
import java.io.IOException;
import java.io.PrintWriter;
import javax.ejb.EJB;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
*
* @author kristofferskjutar
*/
@WebServlet(name="BasicServlet", urlPatterns={"/confirm"})
public class MailConfirmServlet extends HttpServlet {
public MailConfirmServlet()
{
super();
}
@EJB
private UserRegistry reg;
@Override
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doPost(request, response);
}
@Override
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String token = request.getParameter("token");
Account a = reg.find(Long.parseLong(token));
a.setActivated(true);
reg.update(a);
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
try {
out.println("<html>");
out.println("<head>");
out.println("<title>OVE confirm</title>");
out.println("</head>");
out.println("<body>");
- out.println("<h1>You have successfully created your account" + a.getPerson().getName() +" !</h1>");
- out.println("<hlink>http://localhost:8080/OVE/<hlink>");
+ out.println("<h1>You have successfully created your account " + a.getPerson().getName() +" !</h1>");
+ out.println("<a href=http://localhost:8080/OVE/>Go to OVE</a>");
out.println("</body>");
out.println("</html>");
} finally {
out.close();
}
}
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String token = request.getParameter("token");
Account a = reg.find(Long.parseLong(token));
a.setActivated(true);
reg.update(a);
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
try {
out.println("<html>");
out.println("<head>");
out.println("<title>OVE confirm</title>");
out.println("</head>");
out.println("<body>");
out.println("<h1>You have successfully created your account!</h1>");
out.println("</body>");
out.println("</html>");
} finally {
out.close();
}
}
}
| true | true | public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String token = request.getParameter("token");
Account a = reg.find(Long.parseLong(token));
a.setActivated(true);
reg.update(a);
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
try {
out.println("<html>");
out.println("<head>");
out.println("<title>OVE confirm</title>");
out.println("</head>");
out.println("<body>");
out.println("<h1>You have successfully created your account" + a.getPerson().getName() +" !</h1>");
out.println("<hlink>http://localhost:8080/OVE/<hlink>");
out.println("</body>");
out.println("</html>");
} finally {
out.close();
}
}
| public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String token = request.getParameter("token");
Account a = reg.find(Long.parseLong(token));
a.setActivated(true);
reg.update(a);
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
try {
out.println("<html>");
out.println("<head>");
out.println("<title>OVE confirm</title>");
out.println("</head>");
out.println("<body>");
out.println("<h1>You have successfully created your account " + a.getPerson().getName() +" !</h1>");
out.println("<a href=http://localhost:8080/OVE/>Go to OVE</a>");
out.println("</body>");
out.println("</html>");
} finally {
out.close();
}
}
|
diff --git a/src/osm/src/main/java/org/geogit/osm/cli/commands/OSMDownload.java b/src/osm/src/main/java/org/geogit/osm/cli/commands/OSMDownload.java
index 2c778e87..d6345fe7 100644
--- a/src/osm/src/main/java/org/geogit/osm/cli/commands/OSMDownload.java
+++ b/src/osm/src/main/java/org/geogit/osm/cli/commands/OSMDownload.java
@@ -1,270 +1,275 @@
/* Copyright (c) 2013 OpenPlans. All rights reserved.
* This code is licensed under the BSD New License, available at the root
* application directory.
*/
package org.geogit.osm.cli.commands;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Preconditions.checkState;
import java.io.File;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;
import org.geogit.api.GeoGIT;
import org.geogit.api.Ref;
import org.geogit.api.RevCommit;
import org.geogit.api.SymRef;
import org.geogit.api.plumbing.RefParse;
import org.geogit.api.porcelain.BranchCreateOp;
import org.geogit.api.porcelain.CheckoutOp;
import org.geogit.api.porcelain.LogOp;
import org.geogit.cli.AbstractCommand;
import org.geogit.cli.CLICommand;
import org.geogit.cli.GeogitCLI;
import org.geogit.osm.internal.AddOSMLogEntry;
import org.geogit.osm.internal.EmptyOSMDownloadException;
import org.geogit.osm.internal.Mapping;
import org.geogit.osm.internal.OSMDownloadReport;
import org.geogit.osm.internal.OSMImportOp;
import org.geogit.osm.internal.OSMLogEntry;
import org.geogit.osm.internal.ReadOSMFilterFile;
import org.geogit.osm.internal.ReadOSMLogEntries;
import org.geogit.osm.internal.WriteOSMFilterFile;
import com.beust.jcommander.Parameter;
import com.beust.jcommander.Parameters;
import com.google.common.base.Charsets;
import com.google.common.base.Joiner;
import com.google.common.base.Optional;
import com.google.common.base.Preconditions;
import com.google.common.collect.Lists;
import com.google.common.io.Files;
/**
* Imports data from OSM using the Overpass API
*
* Data is filtered using an Overpass QL filter.
*
* If the --update modifier is used, it updates previously imported OSM data, connecting again to
* the Overpass API
*
* It reuses the filter from the last import that can be reached from the the current branch
*
* WARNING: The current update mechanism is not smart, since it downloads all data, not just the
* elements modified/added since the last import (which is stored on the OSM log file)
*
*/
@Parameters(commandNames = "download", commandDescription = "Download OpenStreetMap data")
public class OSMDownload extends AbstractCommand implements CLICommand {
private static final String OSM_FETCH_BRANCH = "OSM_FETCH";
private static final String DEFAULT_API_ENDPOINT = "http://overpass-api.de/api/interpreter";
private static final String FR_API_ENDPOINT = "http://api.openstreetmap.fr/oapi/interpreter/";
private static final String RU_API_ENDPOINT = "http://overpass.osm.rambler.ru/";
@Parameter(names = { "--filter", "-f" }, description = "The filter file to use.")
private File filterFile;
@Parameter(arity = 1, description = "<OSM Overpass api URL. eg: http://api.openstreetmap.org/api>", required = false)
public List<String> apiUrl = Lists.newArrayList();
@Parameter(names = { "--bbox", "-b" }, description = "The bounding box to use as filter (S W N E).", arity = 4)
private List<String> bbox;
@Parameter(names = "--saveto", description = "Directory where to save the dowloaded OSM data files.")
public File saveFile;
@Parameter(names = { "--keep-files", "-k" }, description = "If specified, downloaded files are kept in the --saveto folder")
public boolean keepFiles = false;
@Parameter(names = { "--update", "-u" }, description = "Update the OSM data currently in the geogit repository")
public boolean update = false;
@Parameter(names = { "--rebase" }, description = "Use rebase instead of merge when updating")
public boolean rebase = false;
@Parameter(names = { "--mapping" }, description = "The file that contains the data mapping to use")
public File mappingFile;
private String osmAPIUrl;
private GeogitCLI cli;
@Override
protected void runInternal(GeogitCLI cli) throws Exception {
checkState(cli.getGeogit() != null, "Not a geogit repository: " + cli.getPlatform().pwd());
checkArgument(filterFile != null ^ bbox != null || update,
"You must specify a filter file or a bounding box");
checkArgument((filterFile != null || bbox != null) ^ update,
"Filters cannot be used when updating");
checkState(cli.getGeogit().getRepository().getIndex().countStaged(null)
+ cli.getGeogit().getRepository().getWorkingTree().countUnstaged(null) == 0,
"Working tree and index are not clean");
checkArgument(!rebase || update, "--rebase switch can only be used when updating");
checkArgument(filterFile == null || filterFile.exists(),
"The specified filter file does not exist");
checkArgument(bbox == null || bbox.size() == 4, "The specified bounding box is not correct");
osmAPIUrl = resolveAPIURL();
this.cli = cli;
if (update) {
update();
} else {
download();
}
}
private void download() throws Exception {
Mapping mapping = null;
if (mappingFile != null) {
mapping = Mapping.fromFile(mappingFile.getAbsolutePath());
}
OSMImportOp op = cli.getGeogit().command(OSMImportOp.class).setDataSource(osmAPIUrl)
.setDownloadFile(saveFile).setMapping(mapping).setKeepFile(keepFiles);
String filter = null;
if (filterFile != null) {
try {
filter = readFile(filterFile);
} catch (IOException e) {
throw new IllegalArgumentException("Error reading filter file:" + e.getMessage(), e);
}
} else if (bbox != null) {
filter = "way(" + bbox.get(0) + "," + bbox.get(1) + "," + bbox.get(2) + ","
+ bbox.get(3) + ");\n(._;>;);\nout meta;";
}
try {
Optional<OSMDownloadReport> report = op.setFilter(filter)
.setProgressListener(cli.getProgressListener()).call();
if (!report.isPresent()) {
return;
}
if (report.get().getUnpprocessedCount() > 0) {
cli.getConsole().println(
"Some elements returned by the specified filter could not be processed.\nProcessed entities: "
+ report.get().getCount() + "\nWrong or uncomplete elements: "
+ report.get().getUnpprocessedCount());
}
cli.execute("add");
String message = "Updated OSM data";
cli.execute("commit", "-m", message);
OSMLogEntry entry = new OSMLogEntry(cli.getGeogit().getRepository().getWorkingTree()
.getTree().getId(), report.get().getLatestChangeset(), report.get()
.getLatestTimestamp());
cli.getGeogit().command(AddOSMLogEntry.class).setEntry(entry).call();
cli.getGeogit().command(WriteOSMFilterFile.class).setEntry(entry).setFilterCode(filter)
.call();
} catch (EmptyOSMDownloadException e) {
throw new IllegalArgumentException("The specified filter did not return any element.\n"
+ "No changes were made to the repository.\n"
+ "To check the downloaded elements, use the --saveto and"
+ " --keep-files options and verify the intermediate file.");
} catch (RuntimeException e) {
throw new IllegalStateException("Error importing OSM data: " + e.getMessage(), e);
}
}
private void update() throws Exception {
GeoGIT geogit = cli.getGeogit();
final Optional<Ref> currHead = geogit.command(RefParse.class).setName(Ref.HEAD).call();
Preconditions.checkState(currHead.isPresent(), "Repository has no HEAD, can't update.");
Preconditions.checkState(currHead.get() instanceof SymRef,
"Can't update from detached HEAD");
List<OSMLogEntry> entries = geogit.command(ReadOSMLogEntries.class).call();
checkArgument(!entries.isEmpty(), "Not in a geogit repository with OSM data");
Iterator<RevCommit> log = geogit.command(LogOp.class).setFirstParentOnly(false)
.setTopoOrder(false).call();
RevCommit lastCommit = null;
OSMLogEntry lastEntry = null;
while (log.hasNext()) {
RevCommit commit = log.next();
for (OSMLogEntry entry : entries) {
if (entry.getId().equals(commit.getTreeId())) {
lastCommit = commit;
lastEntry = entry;
break;
}
}
+ if (lastCommit != null) {
+ break;
+ }
}
checkNotNull(lastCommit, "The current branch does not contain OSM data");
geogit.command(BranchCreateOp.class).setSource(lastCommit.getId().toString())
.setName(OSM_FETCH_BRANCH).setAutoCheckout(true).setForce(true).call();
Optional<String> filter = geogit.command(ReadOSMFilterFile.class).setEntry(lastEntry)
.call();
Preconditions.checkState(filter.isPresent(), "Filter file not found");
Optional<OSMDownloadReport> report = geogit.command(OSMImportOp.class)
.setFilter(filter.get()).setDataSource(resolveAPIURL())
.setProgressListener(cli.getProgressListener()).call();
OSMLogEntry entry = new OSMLogEntry(cli.getGeogit().getRepository().getWorkingTree()
.getTree().getId(), report.get().getLatestChangeset(), report.get()
.getLatestTimestamp());
if (!report.isPresent()) {
return;
}
cli.getConsole().println();
if (cli.getGeogit().getRepository().getWorkingTree().countUnstaged(null) != 0) {
cli.execute("add");
String message = "Updated OSM data";
cli.execute("commit", "-m", message);
cli.getGeogit().command(AddOSMLogEntry.class).setEntry(entry).call();
cli.getGeogit().command(WriteOSMFilterFile.class).setEntry(entry)
.setFilterCode(filter.get()).call();
} else {
// no changes, so we exit and do not continue with the merge
+ geogit.command(CheckoutOp.class).setSource(((SymRef) currHead.get()).getTarget())
+ .call();
cli.getConsole().println("No changes found");
return;
}
- geogit.command(CheckoutOp.class).setSource(currHead.get().getName()).call();
+ geogit.command(CheckoutOp.class).setSource(((SymRef) currHead.get()).getTarget()).call();
if (rebase) {
cli.execute("rebase", OSM_FETCH_BRANCH);
} else {
cli.execute("merge", OSM_FETCH_BRANCH);
}
}
private String readFile(File file) throws IOException {
List<String> lines = Files.readLines(file, Charsets.UTF_8);
return Joiner.on("\n").join(lines);
}
private String resolveAPIURL() {
String osmAPIUrl;
if (apiUrl.isEmpty()) {
osmAPIUrl = DEFAULT_API_ENDPOINT;
} else {
osmAPIUrl = apiUrl.get(0);
}
return osmAPIUrl;
}
}
| false | true | private void update() throws Exception {
GeoGIT geogit = cli.getGeogit();
final Optional<Ref> currHead = geogit.command(RefParse.class).setName(Ref.HEAD).call();
Preconditions.checkState(currHead.isPresent(), "Repository has no HEAD, can't update.");
Preconditions.checkState(currHead.get() instanceof SymRef,
"Can't update from detached HEAD");
List<OSMLogEntry> entries = geogit.command(ReadOSMLogEntries.class).call();
checkArgument(!entries.isEmpty(), "Not in a geogit repository with OSM data");
Iterator<RevCommit> log = geogit.command(LogOp.class).setFirstParentOnly(false)
.setTopoOrder(false).call();
RevCommit lastCommit = null;
OSMLogEntry lastEntry = null;
while (log.hasNext()) {
RevCommit commit = log.next();
for (OSMLogEntry entry : entries) {
if (entry.getId().equals(commit.getTreeId())) {
lastCommit = commit;
lastEntry = entry;
break;
}
}
}
checkNotNull(lastCommit, "The current branch does not contain OSM data");
geogit.command(BranchCreateOp.class).setSource(lastCommit.getId().toString())
.setName(OSM_FETCH_BRANCH).setAutoCheckout(true).setForce(true).call();
Optional<String> filter = geogit.command(ReadOSMFilterFile.class).setEntry(lastEntry)
.call();
Preconditions.checkState(filter.isPresent(), "Filter file not found");
Optional<OSMDownloadReport> report = geogit.command(OSMImportOp.class)
.setFilter(filter.get()).setDataSource(resolveAPIURL())
.setProgressListener(cli.getProgressListener()).call();
OSMLogEntry entry = new OSMLogEntry(cli.getGeogit().getRepository().getWorkingTree()
.getTree().getId(), report.get().getLatestChangeset(), report.get()
.getLatestTimestamp());
if (!report.isPresent()) {
return;
}
cli.getConsole().println();
if (cli.getGeogit().getRepository().getWorkingTree().countUnstaged(null) != 0) {
cli.execute("add");
String message = "Updated OSM data";
cli.execute("commit", "-m", message);
cli.getGeogit().command(AddOSMLogEntry.class).setEntry(entry).call();
cli.getGeogit().command(WriteOSMFilterFile.class).setEntry(entry)
.setFilterCode(filter.get()).call();
} else {
// no changes, so we exit and do not continue with the merge
cli.getConsole().println("No changes found");
return;
}
geogit.command(CheckoutOp.class).setSource(currHead.get().getName()).call();
if (rebase) {
cli.execute("rebase", OSM_FETCH_BRANCH);
} else {
cli.execute("merge", OSM_FETCH_BRANCH);
}
}
| private void update() throws Exception {
GeoGIT geogit = cli.getGeogit();
final Optional<Ref> currHead = geogit.command(RefParse.class).setName(Ref.HEAD).call();
Preconditions.checkState(currHead.isPresent(), "Repository has no HEAD, can't update.");
Preconditions.checkState(currHead.get() instanceof SymRef,
"Can't update from detached HEAD");
List<OSMLogEntry> entries = geogit.command(ReadOSMLogEntries.class).call();
checkArgument(!entries.isEmpty(), "Not in a geogit repository with OSM data");
Iterator<RevCommit> log = geogit.command(LogOp.class).setFirstParentOnly(false)
.setTopoOrder(false).call();
RevCommit lastCommit = null;
OSMLogEntry lastEntry = null;
while (log.hasNext()) {
RevCommit commit = log.next();
for (OSMLogEntry entry : entries) {
if (entry.getId().equals(commit.getTreeId())) {
lastCommit = commit;
lastEntry = entry;
break;
}
}
if (lastCommit != null) {
break;
}
}
checkNotNull(lastCommit, "The current branch does not contain OSM data");
geogit.command(BranchCreateOp.class).setSource(lastCommit.getId().toString())
.setName(OSM_FETCH_BRANCH).setAutoCheckout(true).setForce(true).call();
Optional<String> filter = geogit.command(ReadOSMFilterFile.class).setEntry(lastEntry)
.call();
Preconditions.checkState(filter.isPresent(), "Filter file not found");
Optional<OSMDownloadReport> report = geogit.command(OSMImportOp.class)
.setFilter(filter.get()).setDataSource(resolveAPIURL())
.setProgressListener(cli.getProgressListener()).call();
OSMLogEntry entry = new OSMLogEntry(cli.getGeogit().getRepository().getWorkingTree()
.getTree().getId(), report.get().getLatestChangeset(), report.get()
.getLatestTimestamp());
if (!report.isPresent()) {
return;
}
cli.getConsole().println();
if (cli.getGeogit().getRepository().getWorkingTree().countUnstaged(null) != 0) {
cli.execute("add");
String message = "Updated OSM data";
cli.execute("commit", "-m", message);
cli.getGeogit().command(AddOSMLogEntry.class).setEntry(entry).call();
cli.getGeogit().command(WriteOSMFilterFile.class).setEntry(entry)
.setFilterCode(filter.get()).call();
} else {
// no changes, so we exit and do not continue with the merge
geogit.command(CheckoutOp.class).setSource(((SymRef) currHead.get()).getTarget())
.call();
cli.getConsole().println("No changes found");
return;
}
geogit.command(CheckoutOp.class).setSource(((SymRef) currHead.get()).getTarget()).call();
if (rebase) {
cli.execute("rebase", OSM_FETCH_BRANCH);
} else {
cli.execute("merge", OSM_FETCH_BRANCH);
}
}
|
diff --git a/ps3mediaserver/net/pms/network/HTTPServer.java b/ps3mediaserver/net/pms/network/HTTPServer.java
index 35d0abd4..846465ee 100644
--- a/ps3mediaserver/net/pms/network/HTTPServer.java
+++ b/ps3mediaserver/net/pms/network/HTTPServer.java
@@ -1,246 +1,246 @@
/*
* PS3 Media Server, for streaming any medias to your PS3.
* Copyright (C) 2008 A.Brochard
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; version 2
* of the License only.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package net.pms.network;
import java.io.IOException;
import java.net.Inet6Address;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.NetworkInterface;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketAddress;
import java.nio.channels.ClosedByInterruptException;
import java.nio.channels.ServerSocketChannel;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.concurrent.Executors;
import net.pms.PMS;
import net.pms.util.PMSUtil;
import org.apache.commons.lang.StringUtils;
import org.jboss.netty.bootstrap.ServerBootstrap;
import org.jboss.netty.channel.Channel;
import org.jboss.netty.channel.ChannelFactory;
import org.jboss.netty.channel.group.ChannelGroup;
import org.jboss.netty.channel.group.DefaultChannelGroup;
import org.jboss.netty.channel.socket.nio.NioServerSocketChannelFactory;
public class HTTPServer implements Runnable {
//private boolean newHTTP = false;
private ArrayList<String> ips;
private int port;
private String hostName;
private ServerSocketChannel serverSocketChannel;
private ServerSocket serverSocket;
private boolean stop;
private Thread runnable;
private InetAddress iafinal = null;
public InetAddress getIafinal() {
return iafinal;
}
private NetworkInterface ni = null;
public NetworkInterface getNi() {
return ni;
}
public HTTPServer(int port) {
this.port = port;
ips = new ArrayList<String>();
}
public boolean start() throws IOException {
Enumeration<NetworkInterface> enm = NetworkInterface.getNetworkInterfaces();
InetAddress ia = null;
boolean found = false;
String fixedNetworkInterfaceName = PMS.getConfiguration().getNetworkInterface();
NetworkInterface fixedNI = NetworkInterface.getByName(fixedNetworkInterfaceName);
while (enm.hasMoreElements()) {
ni = enm.nextElement();
if (fixedNI != null)
ni = fixedNI;
PMS.minimal("Scanning network interface " + ni.getName() + " / " + ni.getDisplayName());
- if (!PMSUtil.isNetworkInterfaceLoopback(ni) && ni.getName() != null && !ni.getDisplayName().toLowerCase().contains("vmnet") && !ni.getName().toLowerCase().contains("vmnet")) {
+ if (!PMSUtil.isNetworkInterfaceLoopback(ni) && ni.getName() != null && (ni.getDisplayName() == null || !ni.getDisplayName().toLowerCase().contains("vmnet")) && !ni.getName().toLowerCase().contains("vmnet")) {
Enumeration<InetAddress> addrs = ni.getInetAddresses();
while (addrs.hasMoreElements()) {
ia = addrs.nextElement();
if (!(ia instanceof Inet6Address) && !ia.isLoopbackAddress()) {
iafinal = ia;
found = true;
if (StringUtils.isNotEmpty(PMS.getConfiguration().getServerHostname())) {
found = iafinal.equals(InetAddress.getByName(PMS.getConfiguration().getServerHostname()));
}
break;
}
}
}
if (found || fixedNI != null)
break;
}
hostName = PMS.getConfiguration().getServerHostname();
SocketAddress address = null;
if (hostName != null && hostName.length() > 0) {
PMS.minimal("Using forced address " + hostName);
InetAddress tempIA = InetAddress.getByName(hostName);
if (tempIA != null && ni != null && ni.equals(NetworkInterface.getByInetAddress(tempIA))) {
address = new InetSocketAddress(tempIA, port);
} else
address = new InetSocketAddress(hostName, port);
} else if (iafinal != null) {
PMS.minimal("Using address " + iafinal + " found on network interface: " + ni.toString().trim().replace('\n', ' '));
address = new InetSocketAddress(iafinal, port);
} else {
PMS.minimal("Using localhost address");
address = new InetSocketAddress(port);
}
PMS.minimal("Created socket: " + address);
if (!PMS.getConfiguration().isHTTPEngineV2()) {
serverSocketChannel = ServerSocketChannel.open();
serverSocket = serverSocketChannel.socket();
serverSocket.setReuseAddress(true);
serverSocket.bind(address);
if (hostName == null && iafinal !=null)
hostName = iafinal.getHostAddress();
else if (hostName == null)
hostName = InetAddress.getLocalHost().getHostAddress();
runnable = new Thread(this);
runnable.setDaemon(false);
runnable.start();
} else {
group = new DefaultChannelGroup("myServer");
factory = new NioServerSocketChannelFactory(
Executors.newCachedThreadPool(),
Executors.newCachedThreadPool());
ServerBootstrap bootstrap = new ServerBootstrap(factory);
HttpServerPipelineFactory pipeline = new HttpServerPipelineFactory();
bootstrap.setPipelineFactory(pipeline);
bootstrap.setOption("child.tcpNoDelay", true);
bootstrap.setOption("child.keepAlive", true);
bootstrap.setOption("reuseAddress", true);
bootstrap.setOption("child.reuseAddress", true);
bootstrap.setOption("child.sendBufferSize", 65536);
bootstrap.setOption("child.receiveBufferSize", 65536);
channel = bootstrap.bind(address);
group.add(channel);
if (hostName == null && iafinal !=null)
hostName = iafinal.getHostAddress();
else if (hostName == null)
hostName = InetAddress.getLocalHost().getHostAddress();
}
return true;
}
private ChannelFactory factory;
private Channel channel;
public static ChannelGroup group ;
public void stop() {
PMS.info( "Stopping server on host " + hostName + " and port " + port + "...");
if (!PMS.getConfiguration().isHTTPEngineV2()) {
runnable.interrupt();
runnable = null;
try {
serverSocket.close();
serverSocketChannel.close();
} catch (IOException e) {}
} else if (channel != null) {
/*channel.disconnect().awaitUninterruptibly();
channel.close().awaitUninterruptibly();
channel.unbind().awaitUninterruptibly();*/
if (group != null)
group.close().awaitUninterruptibly();
if (factory != null)
factory.releaseExternalResources();
}
}
public void run() {
PMS.minimal( "Starting DLNA Server on host " + hostName + " and port " + port + "...");
while (!stop) {
try {
Socket socket = serverSocket.accept();
String ip = socket.getInetAddress().getHostAddress();
// basic ipfilter [email protected]
boolean ignore = false;
if (!ips.contains(ip)) {
if(PMS.getConfiguration().getIpFilter().length() > 0 && !PMS.getConfiguration().getIpFilter().equals(ip)){
ignore = true;
socket.close();
PMS.minimal("Ignoring request from: " + ip);
}else{
ips.add(ip);
PMS.minimal("Receiving a request from: " + ip);
}
}
if(!ignore){
RequestHandler request = new RequestHandler(socket);
Thread thread = new Thread(request);
thread.start();
}
} catch (ClosedByInterruptException e) {
stop = true;
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (stop && serverSocket != null)
serverSocket.close();
if (stop && serverSocketChannel != null)
serverSocketChannel.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
public String getURL() {
return "http://" + hostName + ":" + port;
}
public String getURLP() {
return "http://" + hostName + ":" + (port+1);
}
public String getHost() {
return hostName;
}
public int getPort() {
return port;
}
}
| true | true | public boolean start() throws IOException {
Enumeration<NetworkInterface> enm = NetworkInterface.getNetworkInterfaces();
InetAddress ia = null;
boolean found = false;
String fixedNetworkInterfaceName = PMS.getConfiguration().getNetworkInterface();
NetworkInterface fixedNI = NetworkInterface.getByName(fixedNetworkInterfaceName);
while (enm.hasMoreElements()) {
ni = enm.nextElement();
if (fixedNI != null)
ni = fixedNI;
PMS.minimal("Scanning network interface " + ni.getName() + " / " + ni.getDisplayName());
if (!PMSUtil.isNetworkInterfaceLoopback(ni) && ni.getName() != null && !ni.getDisplayName().toLowerCase().contains("vmnet") && !ni.getName().toLowerCase().contains("vmnet")) {
Enumeration<InetAddress> addrs = ni.getInetAddresses();
while (addrs.hasMoreElements()) {
ia = addrs.nextElement();
if (!(ia instanceof Inet6Address) && !ia.isLoopbackAddress()) {
iafinal = ia;
found = true;
if (StringUtils.isNotEmpty(PMS.getConfiguration().getServerHostname())) {
found = iafinal.equals(InetAddress.getByName(PMS.getConfiguration().getServerHostname()));
}
break;
}
}
}
if (found || fixedNI != null)
break;
}
hostName = PMS.getConfiguration().getServerHostname();
SocketAddress address = null;
if (hostName != null && hostName.length() > 0) {
PMS.minimal("Using forced address " + hostName);
InetAddress tempIA = InetAddress.getByName(hostName);
if (tempIA != null && ni != null && ni.equals(NetworkInterface.getByInetAddress(tempIA))) {
address = new InetSocketAddress(tempIA, port);
} else
address = new InetSocketAddress(hostName, port);
} else if (iafinal != null) {
PMS.minimal("Using address " + iafinal + " found on network interface: " + ni.toString().trim().replace('\n', ' '));
address = new InetSocketAddress(iafinal, port);
} else {
PMS.minimal("Using localhost address");
address = new InetSocketAddress(port);
}
PMS.minimal("Created socket: " + address);
if (!PMS.getConfiguration().isHTTPEngineV2()) {
serverSocketChannel = ServerSocketChannel.open();
serverSocket = serverSocketChannel.socket();
serverSocket.setReuseAddress(true);
serverSocket.bind(address);
if (hostName == null && iafinal !=null)
hostName = iafinal.getHostAddress();
else if (hostName == null)
hostName = InetAddress.getLocalHost().getHostAddress();
runnable = new Thread(this);
runnable.setDaemon(false);
runnable.start();
} else {
group = new DefaultChannelGroup("myServer");
factory = new NioServerSocketChannelFactory(
Executors.newCachedThreadPool(),
Executors.newCachedThreadPool());
ServerBootstrap bootstrap = new ServerBootstrap(factory);
HttpServerPipelineFactory pipeline = new HttpServerPipelineFactory();
bootstrap.setPipelineFactory(pipeline);
bootstrap.setOption("child.tcpNoDelay", true);
bootstrap.setOption("child.keepAlive", true);
bootstrap.setOption("reuseAddress", true);
bootstrap.setOption("child.reuseAddress", true);
bootstrap.setOption("child.sendBufferSize", 65536);
bootstrap.setOption("child.receiveBufferSize", 65536);
channel = bootstrap.bind(address);
group.add(channel);
if (hostName == null && iafinal !=null)
hostName = iafinal.getHostAddress();
else if (hostName == null)
hostName = InetAddress.getLocalHost().getHostAddress();
}
return true;
}
| public boolean start() throws IOException {
Enumeration<NetworkInterface> enm = NetworkInterface.getNetworkInterfaces();
InetAddress ia = null;
boolean found = false;
String fixedNetworkInterfaceName = PMS.getConfiguration().getNetworkInterface();
NetworkInterface fixedNI = NetworkInterface.getByName(fixedNetworkInterfaceName);
while (enm.hasMoreElements()) {
ni = enm.nextElement();
if (fixedNI != null)
ni = fixedNI;
PMS.minimal("Scanning network interface " + ni.getName() + " / " + ni.getDisplayName());
if (!PMSUtil.isNetworkInterfaceLoopback(ni) && ni.getName() != null && (ni.getDisplayName() == null || !ni.getDisplayName().toLowerCase().contains("vmnet")) && !ni.getName().toLowerCase().contains("vmnet")) {
Enumeration<InetAddress> addrs = ni.getInetAddresses();
while (addrs.hasMoreElements()) {
ia = addrs.nextElement();
if (!(ia instanceof Inet6Address) && !ia.isLoopbackAddress()) {
iafinal = ia;
found = true;
if (StringUtils.isNotEmpty(PMS.getConfiguration().getServerHostname())) {
found = iafinal.equals(InetAddress.getByName(PMS.getConfiguration().getServerHostname()));
}
break;
}
}
}
if (found || fixedNI != null)
break;
}
hostName = PMS.getConfiguration().getServerHostname();
SocketAddress address = null;
if (hostName != null && hostName.length() > 0) {
PMS.minimal("Using forced address " + hostName);
InetAddress tempIA = InetAddress.getByName(hostName);
if (tempIA != null && ni != null && ni.equals(NetworkInterface.getByInetAddress(tempIA))) {
address = new InetSocketAddress(tempIA, port);
} else
address = new InetSocketAddress(hostName, port);
} else if (iafinal != null) {
PMS.minimal("Using address " + iafinal + " found on network interface: " + ni.toString().trim().replace('\n', ' '));
address = new InetSocketAddress(iafinal, port);
} else {
PMS.minimal("Using localhost address");
address = new InetSocketAddress(port);
}
PMS.minimal("Created socket: " + address);
if (!PMS.getConfiguration().isHTTPEngineV2()) {
serverSocketChannel = ServerSocketChannel.open();
serverSocket = serverSocketChannel.socket();
serverSocket.setReuseAddress(true);
serverSocket.bind(address);
if (hostName == null && iafinal !=null)
hostName = iafinal.getHostAddress();
else if (hostName == null)
hostName = InetAddress.getLocalHost().getHostAddress();
runnable = new Thread(this);
runnable.setDaemon(false);
runnable.start();
} else {
group = new DefaultChannelGroup("myServer");
factory = new NioServerSocketChannelFactory(
Executors.newCachedThreadPool(),
Executors.newCachedThreadPool());
ServerBootstrap bootstrap = new ServerBootstrap(factory);
HttpServerPipelineFactory pipeline = new HttpServerPipelineFactory();
bootstrap.setPipelineFactory(pipeline);
bootstrap.setOption("child.tcpNoDelay", true);
bootstrap.setOption("child.keepAlive", true);
bootstrap.setOption("reuseAddress", true);
bootstrap.setOption("child.reuseAddress", true);
bootstrap.setOption("child.sendBufferSize", 65536);
bootstrap.setOption("child.receiveBufferSize", 65536);
channel = bootstrap.bind(address);
group.add(channel);
if (hostName == null && iafinal !=null)
hostName = iafinal.getHostAddress();
else if (hostName == null)
hostName = InetAddress.getLocalHost().getHostAddress();
}
return true;
}
|
diff --git a/opentripplanner-api-webapp/src/main/java/org/opentripplanner/api/ws/PlanGenerator.java b/opentripplanner-api-webapp/src/main/java/org/opentripplanner/api/ws/PlanGenerator.java
index 4fb35cb82..b517204d0 100644
--- a/opentripplanner-api-webapp/src/main/java/org/opentripplanner/api/ws/PlanGenerator.java
+++ b/opentripplanner-api-webapp/src/main/java/org/opentripplanner/api/ws/PlanGenerator.java
@@ -1,821 +1,821 @@
/* This program is free software: you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public License
as published by the Free Software Foundation, either version 3 of
the License, or (props, at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>. */
package org.opentripplanner.api.ws;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.onebusaway.gtfs.model.AgencyAndId;
import org.onebusaway.gtfs.model.Trip;
import org.opentripplanner.api.model.Itinerary;
import org.opentripplanner.api.model.Leg;
import org.opentripplanner.api.model.Place;
import org.opentripplanner.api.model.RelativeDirection;
import org.opentripplanner.api.model.TripPlan;
import org.opentripplanner.api.model.WalkStep;
import org.opentripplanner.common.geometry.DirectionUtils;
import org.opentripplanner.common.geometry.PackedCoordinateSequence;
import org.opentripplanner.routing.core.DirectEdge;
import org.opentripplanner.routing.core.Edge;
import org.opentripplanner.routing.core.EdgeNarrative;
import org.opentripplanner.routing.core.Graph;
import org.opentripplanner.routing.core.RouteSpec;
import org.opentripplanner.routing.core.State;
import org.opentripplanner.routing.core.TraverseMode;
import org.opentripplanner.routing.core.TraverseModeSet;
import org.opentripplanner.routing.core.TraverseOptions;
import org.opentripplanner.routing.core.Vertex;
import org.opentripplanner.routing.edgetype.Dwell;
import org.opentripplanner.routing.edgetype.EdgeWithElevation;
import org.opentripplanner.routing.edgetype.LegSwitchingEdge;
import org.opentripplanner.routing.edgetype.PatternDwell;
import org.opentripplanner.routing.edgetype.PatternInterlineDwell;
import org.opentripplanner.routing.edgetype.FreeEdge;
import org.opentripplanner.routing.edgetype.PlainStreetEdge;
import org.opentripplanner.routing.edgetype.StreetVertex;
import org.opentripplanner.routing.edgetype.TinyTurnEdge;
import org.opentripplanner.routing.error.PathNotFoundException;
import org.opentripplanner.routing.error.VertexNotFoundException;
import org.opentripplanner.routing.patch.Alert;
import org.opentripplanner.routing.services.FareService;
import org.opentripplanner.routing.services.PathService;
import org.opentripplanner.routing.services.PathServiceFactory;
import org.opentripplanner.routing.spt.GraphPath;
import org.opentripplanner.util.PolylineEncoder;
import com.vividsolutions.jts.geom.Coordinate;
import com.vividsolutions.jts.geom.Geometry;
import com.vividsolutions.jts.geom.GeometryFactory;
public class PlanGenerator {
private static final Logger LOGGER = Logger.getLogger(PlanGenerator.class.getCanonicalName());
Request request;
private PathService pathService;
private FareService fareService;
public PlanGenerator(Request request, PathServiceFactory pathServiceFactory) {
this.request = request;
pathService = pathServiceFactory.getPathService(request.getRouterId());
Graph graph = pathService.getGraphService().getGraph();
fareService = graph.getService(FareService.class);
}
/**
* Generates a TripPlan from a Request;
*
*/
public TripPlan generate() {
TraverseOptions options = getOptions(request);
checkLocationsAccessible(request, options);
/* try to plan the trip */
List<GraphPath> paths = null;
boolean tooSloped = false;
try {
List<String> intermediates = request.getIntermediatePlaces();
if (intermediates.size() == 0) {
paths = pathService.plan(request.getFrom(), request.getTo(), request.getDateTime(),
options, request.getNumItineraries());
if (paths == null && request.getWheelchair()) {
// There are no paths that meet the user's slope restrictions.
// Try again without slope restrictions (and warn user).
options.maxSlope = Double.MAX_VALUE;
paths = pathService.plan(request.getFrom(), request.getTo(), request
.getDateTime(), options, request.getNumItineraries());
tooSloped = true;
}
} else {
paths = pathService.plan(request.getFrom(), request.getTo(), intermediates, request
.getDateTime(), options);
}
} catch (VertexNotFoundException e) {
LOGGER.log(Level.INFO, "Vertex not found: " + request.getFrom() + " : "
+ request.getTo(), e);
throw e;
}
if (paths == null || paths.size() == 0) {
LOGGER
.log(Level.INFO, "Path not found: " + request.getFrom() + " : "
+ request.getTo());
throw new PathNotFoundException();
}
TripPlan plan = generatePlan(paths, request);
if (plan != null) {
for (Itinerary i : plan.itinerary) {
i.tooSloped = tooSloped;
}
}
return plan;
}
/**
* Generates a TripPlan from a set of paths
*/
public TripPlan generatePlan(List<GraphPath> paths, Request request) {
GraphPath exemplar = paths.get(0);
Vertex tripStartVertex = exemplar.getStartVertex();
Vertex tripEndVertex = exemplar.getEndVertex();
String startName = tripStartVertex.getName();
String endName = tripEndVertex.getName();
// Use vertex labels if they don't have names
if (startName == null) {
startName = tripStartVertex.getLabel();
}
if (endName == null) {
endName = tripEndVertex.getLabel();
}
Place from = new Place(tripStartVertex.getX(), tripStartVertex.getY(), startName);
Place to = new Place(tripEndVertex.getX(), tripEndVertex.getY(), endName);
TripPlan plan = new TripPlan(from, to, request.getDateTime());
for (GraphPath path : paths) {
Itinerary itinerary = generateItinerary(path, request.getShowIntermediateStops());
plan.addItinerary(itinerary);
}
return plan;
}
/**
* Generate an itinerary from a @{link GraphPath}. The algorithm here is to
* walk over each state in the graph path, accumulating geometry, time, and
* length data from the incoming edge. When the incoming edge and outgoing
* edge have different modes (or when a vehicle changes names due to
* interlining) a new leg is generated. Street legs undergo an additional
* processing step to generate turn-by-turn directions.
*
* @param path
* @param showIntermediateStops
* whether intermediate stops are included in the generated
* itinerary
* @return itinerary
*/
private Itinerary generateItinerary(GraphPath path, boolean showIntermediateStops) {
Itinerary itinerary = makeEmptyItinerary(path);
Leg leg = null;
CoordinateArrayListSequence coordinates = new CoordinateArrayListSequence();
double previousElevation = Double.MAX_VALUE;
double edgeElapsedTime;
GeometryFactory geometryFactory = new GeometryFactory();
int startWalk = -1;
int i = -1;
State prevState = null;
EdgeNarrative backEdgeNarrative = null;
for (State nextState : path.states) {
i++;
/* grab base edge and associated narrative information from SPT edge */
if (prevState == null) {
prevState = nextState;
continue;
}
EdgeNarrative frontEdgeNarrative = nextState.getBackEdgeNarrative();
backEdgeNarrative = prevState.getBackEdgeNarrative();
Edge backEdge = prevState.getBackEdge();
TraverseMode mode = frontEdgeNarrative.getMode();
if (backEdgeNarrative == null) {
// this is the first state, so we need to create the initial leg
leg = makeLeg(nextState);
leg.mode = mode.toString(); // maybe makeLeg should be setting the mode ?
itinerary.addLeg(leg);
if (mode.isOnStreetNonTransit()) {
startWalk = i;
}
prevState = nextState;
continue;
}
- /* skip initial state, which has no back edges */
edgeElapsedTime = nextState.getTimeInMillis()
- nextState.getBackState().getTimeInMillis();
TraverseMode previousMode = backEdgeNarrative.getMode();
if (previousMode == null) {
previousMode = prevState.getBackState().getBackEdgeNarrative().getMode();
}
if (backEdgeNarrative instanceof LegSwitchingEdge) {
leg.walkSteps = getWalkSteps(pathService, path.states.subList(startWalk, i - 1));
leg = makeLeg(nextState);
leg.mode = mode.toString(); //may need to fix this up
itinerary.addLeg(leg);
if (mode.isOnStreetNonTransit()) {
startWalk = i;
}
prevState = nextState;
continue;
}
// handle the effects of the previous edge on the leg
/* ignore edges that should not contribute to the narrative */
if (backEdge instanceof FreeEdge) {
+ leg.mode = frontEdgeNarrative.getMode().toString();
prevState = nextState;
continue;
}
if (previousMode == TraverseMode.BOARDING || previousMode == TraverseMode.ALIGHTING) {
itinerary.waitingTime += edgeElapsedTime;
}
leg.distance += backEdgeNarrative.getDistance();
/* for all edges with geometry, append their coordinates to the leg's. */
Geometry edgeGeometry = backEdgeNarrative.getGeometry();
if (edgeGeometry != null) {
Coordinate[] edgeCoordinates = edgeGeometry.getCoordinates();
if (coordinates.size() > 0
&& coordinates.getCoordinate(coordinates.size() - 1).equals(
edgeCoordinates[0])) {
coordinates.extend(edgeCoordinates, 1);
} else {
coordinates.extend(edgeCoordinates);
}
}
addNotesToLeg(leg, backEdgeNarrative);
/*
* we are not boarding, alighting, etc. so are we walking/biking/driving or using
* transit?
*/
if (previousMode.isOnStreetNonTransit()) {
/* we are on the street (non-transit) */
itinerary.walkTime += edgeElapsedTime;
itinerary.walkDistance += backEdgeNarrative.getDistance();
if (backEdge instanceof EdgeWithElevation) {
PackedCoordinateSequence profile = ((EdgeWithElevation) backEdge)
.getElevationProfile();
previousElevation = applyElevation(profile, itinerary, previousElevation);
}
leg.endTime = new Date(nextState.getTimeInMillis());
} else if (previousMode.isTransit()) {
leg.endTime = new Date(nextState.getTimeInMillis());
/* we are on a transit trip */
itinerary.transitTime += edgeElapsedTime;
if (showIntermediateStops) {
/* add an intermediate stop to the current leg */
if (leg.stop == null) {
/*
* first transit edge, just create the list (the initial stop is current
* "from" vertex)
*/
leg.stop = new ArrayList<Place>();
}
/* any further transit edge, add "from" vertex to intermediate stops */
if (!(nextState.getBackEdge() instanceof Dwell
|| nextState.getBackEdge() instanceof PatternDwell || nextState
.getBackEdge() instanceof PatternInterlineDwell)) {
Place stop = makePlace(nextState);
leg.stop.add(stop);
} else {
leg.stop.get(leg.stop.size() - 1).departure = new Date(nextState.getTime());
}
}
}
// now, transition between legs if necessary
boolean changingToInterlinedTrip = leg != null && leg.route != null
&& !leg.route.equals(backEdgeNarrative.getName()) && mode.isTransit()
&& previousMode != null && previousMode.isTransit();
if ((mode != previousMode || changingToInterlinedTrip) && mode != TraverseMode.STL) {
/*
* change in mode. make a new leg if we are entering walk or transit, otherwise just
* update the general itinerary info and move to next edge.
*/
boolean endLeg = false;
if (previousMode == TraverseMode.STL && mode.isOnStreetNonTransit()) {
// switching from STL to wall or bike, so we need to fix up
// the start time,
// mode, etc
leg.startTime = new Date(nextState.getTimeInMillis());
leg.route = frontEdgeNarrative.getName();
leg.mode = mode.toString();
startWalk = i;
} else if (mode == TraverseMode.TRANSFER) {
/* transferring mode is only used in transit-only planners */
itinerary.walkTime += edgeElapsedTime;
itinerary.walkDistance += backEdgeNarrative.getDistance();
} else if (mode == TraverseMode.BOARDING) {
/* boarding mode */
itinerary.transfers++;
endLeg = true;
} else if (mode == TraverseMode.ALIGHTING || changingToInterlinedTrip) {
endLeg = true;
} else {
if (previousMode == TraverseMode.ALIGHTING) {
// in this case, we are changing from an alighting mode
// (preAlight) to
// an onstreetnontransit. In this case, we have already
// closed the
// transit leg with alighting, so we don't want to
// finalize a leg.
} else if (previousMode == TraverseMode.BOARDING) {
// we are changing from boarding to an on-transit mode,
// so we need to
// fix up the leg's route and departure time data
leg.startTime = new Date(prevState.getTimeInMillis());
leg.route = frontEdgeNarrative.getName();
leg.mode = mode.toString();
Trip trip = frontEdgeNarrative.getTrip();
if (trip != null) {
leg.headsign = trip.getTripHeadsign();
leg.agencyId = trip.getId().getAgencyId();
leg.tripShortName = trip.getTripShortName();
leg.routeShortName = trip.getRoute().getShortName();
leg.routeLongName = trip.getRoute().getLongName();
}
} else {
// we are probably changing between walk and bike
endLeg = true;
}
}
if (endLeg) {
/* finalize leg */
/* finalize prior leg if it exists */
if (startWalk != -1) {
leg.walkSteps = getWalkSteps(pathService, path.states.subList(startWalk,
i - 1));
}
leg.to = makePlace(frontEdgeNarrative.getFromVertex());
leg.endTime = new Date(prevState.getTimeInMillis());
Geometry geometry = geometryFactory.createLineString(coordinates);
leg.legGeometry = PolylineEncoder.createEncodings(geometry);
/* reset coordinates */
coordinates = new CoordinateArrayListSequence();
if (showIntermediateStops && leg.stop != null) {
// Remove the last stop -- it's the alighting one
leg.stop.remove(leg.stop.size() - 1);
if (leg.stop.isEmpty()) {
leg.stop = null;
}
}
/* initialize new leg */
leg = makeLeg(nextState);
if (changingToInterlinedTrip) {
leg.interlineWithPreviousLeg = true;
}
leg.mode = mode.toString();
startWalk = -1;
leg.route = backEdgeNarrative.getName();
if (mode.isOnStreetNonTransit()) {
/*
* on-street (walk/bike) leg mark where in edge list on-street legs begin,
* so step-by-step instructions can be generated for this sublist later
*/
startWalk = i;
} else {
/* transit leg */
startWalk = -1;
}
itinerary.addLeg(leg);
}
} /* end handling mode changes */
prevState = nextState;
} /* end loop over graphPath edge list */
if (leg != null) {
/* finalize leg */
leg.to = makePlace(backEdgeNarrative.getToVertex());
State finalState = path.states.getLast();
leg.endTime = new Date(finalState.getTimeInMillis());
Geometry geometry = geometryFactory.createLineString(coordinates);
leg.legGeometry = PolylineEncoder.createEncodings(geometry);
if (startWalk != -1) {
leg.walkSteps = getWalkSteps(pathService, path.states.subList(startWalk, i + 1));
}
if (showIntermediateStops && leg.stop != null) {
// Remove the last stop -- it's the alighting one
leg.stop.remove(leg.stop.size() - 1);
if (leg.stop.isEmpty()) {
leg.stop = null;
}
}
}
if (itinerary.transfers == -1) {
itinerary.transfers = 0;
}
itinerary.removeBogusLegs();
return itinerary;
}
private Set<Alert> addNotesToLeg(Leg leg, EdgeNarrative edgeNarrative) {
Set<Alert> notes = edgeNarrative.getNotes();
if (notes != null) {
for (Alert note : notes) {
leg.addAlert(note);
}
}
return notes;
}
/**
* Adjusts an Itinerary's elevation fields from an elevation profile
*
* @return the elevation at the end of the profile
*/
private double applyElevation(PackedCoordinateSequence profile, Itinerary itinerary,
double previousElevation) {
if (profile != null) {
for (Coordinate coordinate : profile.toCoordinateArray()) {
if (previousElevation == Double.MAX_VALUE) {
previousElevation = coordinate.y;
continue;
}
double elevationChange = previousElevation - coordinate.y;
if (elevationChange > 0) {
itinerary.elevationGained += elevationChange;
} else {
itinerary.elevationLost -= elevationChange;
}
previousElevation = coordinate.y;
}
}
return previousElevation;
}
/**
* Makes a new empty leg from a starting edge
*/
private Leg makeLeg(State s) {
Leg leg = new Leg();
leg.startTime = new Date(s.getBackState().getTimeInMillis());
EdgeNarrative en = s.getBackEdgeNarrative();
leg.route = en.getName();
Trip trip = en.getTrip();
if (trip != null) {
leg.headsign = trip.getTripHeadsign();
leg.agencyId = trip.getId().getAgencyId();
leg.tripShortName = trip.getTripShortName();
leg.routeShortName = trip.getRoute().getShortName();
leg.routeLongName = trip.getRoute().getLongName();
}
leg.distance = 0.0;
leg.from = makePlace(en.getFromVertex());
return leg;
}
/**
* Makes a new empty Itinerary for a given path.
*
* @return
*/
private Itinerary makeEmptyItinerary(GraphPath path) {
Itinerary itinerary = new Itinerary();
State startState = path.states.getFirst();
State endState = path.states.getLast();
itinerary.startTime = new Date(startState.getTimeInMillis());
itinerary.endTime = new Date(endState.getTimeInMillis());
itinerary.duration = endState.getTimeInMillis() - startState.getTimeInMillis();
if (fareService != null) {
itinerary.fare = fareService.getCost(path);
}
itinerary.transfers = -1;
return itinerary;
}
/**
* Makes a new Place from a state. Contains information about time.
*
* @return
*/
private Place makePlace(State state) {
Coordinate endCoord = state.getVertex().getCoordinate();
String name = state.getVertex().getName();
AgencyAndId stopId = state.getVertex().getStopId();
Date timeAtState = new Date(state.getTimeInMillis());
Place place = new Place(endCoord.x, endCoord.y, name, stopId, timeAtState);
return place;
}
/**
* Makes a new Place from a vertex.
*
* @return
*/
private Place makePlace(Vertex vertex) {
Coordinate endCoord = vertex.getCoordinate();
Place place = new Place(endCoord.x, endCoord.y, vertex.getName());
place.stopId = vertex.getStopId();
return place;
}
/**
* Throw an exception if the start and end locations are not wheelchair accessible given the
* user's specified maximum slope.
*/
private void checkLocationsAccessible(Request request, TraverseOptions options) {
if (request.getWheelchair()) {
// check if the start and end locations are accessible
if (!pathService.isAccessible(request.getFrom(), options)
|| !pathService.isAccessible(request.getTo(), options)) {
throw new LocationNotAccessible();
}
}
}
/**
* Get the traverse options for a request
*
* @param request
* @return
*/
private TraverseOptions getOptions(Request request) {
TraverseModeSet modeSet = request.getModeSet();
assert (modeSet.isValid());
TraverseOptions options = new TraverseOptions(modeSet);
options.optimizeFor = request.getOptimize();
options.setArriveBy(request.isArriveBy());
options.wheelchairAccessible = request.getWheelchair();
if (request.getMaxSlope() > 0) {
options.maxSlope = request.getMaxSlope();
}
if (request.getMaxWalkDistance() > 0) {
options.setMaxWalkDistance(request.getMaxWalkDistance());
}
if (request.getWalkSpeed() > 0) {
options.speed = request.getWalkSpeed();
}
options.triangleSafetyFactor = request.getTriangleSafetyFactor();
options.triangleSlopeFactor = request.getTriangleSlopeFactor();
options.triangleTimeFactor = request.getTriangleTimeFactor();
if (request.getMinTransferTime() != null) {
options.minTransferTime = request.getMinTransferTime();
}
if (request.getPreferredRoutes() != null) {
for (String element : request.getPreferredRoutes()) {
String[] routeSpec = element.split("_", 2);
if (routeSpec.length != 2) {
throw new IllegalArgumentException(
"AgencyId or routeId not set in preferredRoutes list");
}
options.preferredRoutes.add(new RouteSpec(routeSpec[0], routeSpec[1]));
}
}
if (request.getUnpreferredRoutes() != null) {
for (String element : request.getUnpreferredRoutes()) {
String[] routeSpec = element.split("_", 2);
if (routeSpec.length != 2) {
throw new IllegalArgumentException(
"AgencyId or routeId not set in unpreferredRoutes list");
}
options.unpreferredRoutes.add(new RouteSpec(routeSpec[0], routeSpec[1]));
}
}
if (request.getBannedRoutes() != null) {
for (String element : request.getBannedRoutes()) {
String[] routeSpec = element.split("_", 2);
if (routeSpec.length != 2) {
throw new IllegalArgumentException(
"AgencyId or routeId not set in bannedRoutes list");
}
options.bannedRoutes.add(new RouteSpec(routeSpec[0], routeSpec[1]));
}
}
if (request.getTransferPenalty() != null) {
options.transferPenalty = request.getTransferPenalty();
}
return options;
}
/**
* Converts a list of street edges to a list of turn-by-turn directions.
*
* @param edges : A list of street edges
* @return
*/
private List<WalkStep> getWalkSteps(PathService pathService, List<State> states) {
List<WalkStep> steps = new ArrayList<WalkStep>();
WalkStep step = null;
double lastAngle = 0, distance = 0; // distance used for appending elevation profiles
int roundaboutExit = 0; // track whether we are in a roundabout, and if so the exit number
for (State currState : states) {
Edge edge = currState.getBackEdge();
EdgeNarrative edgeNarrative = currState.getBackEdgeNarrative();
if (edge instanceof FreeEdge) {
continue;
}
if (!edgeNarrative.getMode().isOnStreetNonTransit()) {
continue; // ignore STLs and the like
}
Geometry geom = edgeNarrative.getGeometry();
if (geom == null) {
continue;
}
String streetName = edgeNarrative.getName();
if (step == null) {
// first step
step = createWalkStep(currState);
steps.add(step);
double thisAngle = DirectionUtils.getFirstAngle(geom);
step.setAbsoluteDirection(thisAngle);
// new step, set distance to length of first edge
distance = edgeNarrative.getDistance();
} else if (step.streetName != streetName
&& (step.streetName != null && !step.streetName.equals(streetName))) {
/* street name has changed */
if (roundaboutExit > 0) {
// if we were just on a roundabout,
// make note of which exit was taken in the existing step
step.exit = Integer.toString(roundaboutExit); // ordinal numbers from
// localization
roundaboutExit = 0;
}
/* start a new step */
step = createWalkStep(currState);
steps.add(step);
if (edgeNarrative.isRoundabout()) {
// indicate that we are now on a roundabout
// and use one-based exit numbering
roundaboutExit = 1;
}
double thisAngle = DirectionUtils.getFirstAngle(geom);
step.setDirections(lastAngle, thisAngle, edgeNarrative.isRoundabout());
// new step, set distance to length of first edge
distance = edgeNarrative.getDistance();
} else {
/* street name has not changed */
double thisAngle = DirectionUtils.getFirstAngle(geom);
RelativeDirection direction = WalkStep.getRelativeDirection(lastAngle, thisAngle,
edgeNarrative.isRoundabout());
boolean optionsBefore = pathService.multipleOptionsBefore(edge, currState
.getBackState());
if (edgeNarrative.isRoundabout()) {
// we are on a roundabout, and have already traversed at least one edge of it.
if (optionsBefore) {
// increment exit count if we passed one.
roundaboutExit += 1;
}
}
if (edgeNarrative.isRoundabout() || direction == RelativeDirection.CONTINUE) {
// we are continuing almost straight, or continuing along a roundabout.
// just append elevation info onto the existing step.
if (step.elevation != null) {
String s = encodeElevationProfile(edge, distance);
if (step.elevation.length() > 0 && s != null && s.length() > 0)
step.elevation += ",";
step.elevation += s;
}
// extending a step, increment the existing distance
distance += edgeNarrative.getDistance();
} else {
// we are not on a roundabout, and not continuing straight through.
// figure out if there were other plausible turn options at the last
// intersection
// to see if we should generate a "left to continue" instruction.
boolean shouldGenerateContinue = false;
if (edge instanceof PlainStreetEdge) {
// the next edges will be TinyTurnEdges or PlainStreetEdges, we hope
double angleDiff = getAbsoluteAngleDiff(thisAngle, lastAngle);
for (DirectEdge alternative : pathService.getOutgoingEdges(currState
.getBackState().getVertex())) {
if (alternative instanceof TinyTurnEdge) {
alternative = pathService.getOutgoingEdges(
alternative.getToVertex()).get(0);
}
double altAngle = DirectionUtils.getFirstAngle(alternative
.getGeometry());
double altAngleDiff = getAbsoluteAngleDiff(altAngle, lastAngle);
if (altAngleDiff - angleDiff < Math.PI / 16) {
shouldGenerateContinue = true;
break;
}
}
} else if (edge instanceof TinyTurnEdge) {
// do nothing as this will be handled in other cases
} else {
double newAngle;
if (currState.getVertex() instanceof StreetVertex) {
newAngle = DirectionUtils.getFirstAngle(((StreetVertex) currState
.getVertex()).getGeometry());
} else {
List<DirectEdge> outgoingEdges = pathService.getOutgoingEdges(currState
.getVertex());
Edge oge = outgoingEdges.get(0);
newAngle = DirectionUtils.getFirstAngle(((DirectEdge) oge)
.getGeometry());
}
double angleDiff = getAbsoluteAngleDiff(newAngle, thisAngle);
for (DirectEdge alternative : pathService.getOutgoingEdges(currState
.getBackState().getVertex())) {
if (alternative == edge) {
continue;
}
alternative = pathService.getOutgoingEdges(alternative.getToVertex())
.get(0);
double altAngle = DirectionUtils.getFirstAngle(alternative
.getGeometry());
double altAngleDiff = getAbsoluteAngleDiff(altAngle, lastAngle);
if (altAngleDiff - angleDiff < Math.PI / 16) {
shouldGenerateContinue = true;
break;
}
}
}
if (shouldGenerateContinue) {
// turn to stay on same-named street
step = createWalkStep(currState);
steps.add(step);
step.setDirections(lastAngle, thisAngle, false);
step.stayOn = true;
// new step, set distance to length of first edge
distance = edgeNarrative.getDistance();
}
}
}
// increment the total length for this step
step.distance += edgeNarrative.getDistance();
step.addAlerts(edgeNarrative.getNotes());
lastAngle = DirectionUtils.getLastAngle(geom);
}
return steps;
}
private double getAbsoluteAngleDiff(double thisAngle, double lastAngle) {
double angleDiff = thisAngle - lastAngle;
if (angleDiff < 0) {
angleDiff += Math.PI * 2;
}
double ccwAngleDiff = Math.PI * 2 - angleDiff;
if (ccwAngleDiff < angleDiff) {
angleDiff = ccwAngleDiff;
}
return angleDiff;
}
private WalkStep createWalkStep(State s) {
EdgeNarrative en = s.getBackEdgeNarrative();
WalkStep step;
step = new WalkStep();
step.streetName = en.getName();
step.lon = en.getFromVertex().getX();
step.lat = en.getFromVertex().getY();
step.elevation = encodeElevationProfile(s.getBackEdge(), 0);
step.bogusName = en.hasBogusName();
step.addAlerts(en.getNotes());
return step;
}
private String encodeElevationProfile(Edge edge, double offset) {
if (!(edge instanceof EdgeWithElevation)) {
return "";
}
EdgeWithElevation elevEdge = (EdgeWithElevation) edge;
if (elevEdge.getElevationProfile() == null) {
return "";
}
StringBuilder str = new StringBuilder();
Coordinate[] coordArr = elevEdge.getElevationProfile().toCoordinateArray();
for (int i = 0; i < coordArr.length; i++) {
str.append(Math.round(coordArr[i].x + offset));
str.append(",");
str.append(Math.round(coordArr[i].y * 10.0) / 10.0);
str.append(i < coordArr.length - 1 ? "," : "");
}
return str.toString();
}
}
| false | true | private Itinerary generateItinerary(GraphPath path, boolean showIntermediateStops) {
Itinerary itinerary = makeEmptyItinerary(path);
Leg leg = null;
CoordinateArrayListSequence coordinates = new CoordinateArrayListSequence();
double previousElevation = Double.MAX_VALUE;
double edgeElapsedTime;
GeometryFactory geometryFactory = new GeometryFactory();
int startWalk = -1;
int i = -1;
State prevState = null;
EdgeNarrative backEdgeNarrative = null;
for (State nextState : path.states) {
i++;
/* grab base edge and associated narrative information from SPT edge */
if (prevState == null) {
prevState = nextState;
continue;
}
EdgeNarrative frontEdgeNarrative = nextState.getBackEdgeNarrative();
backEdgeNarrative = prevState.getBackEdgeNarrative();
Edge backEdge = prevState.getBackEdge();
TraverseMode mode = frontEdgeNarrative.getMode();
if (backEdgeNarrative == null) {
// this is the first state, so we need to create the initial leg
leg = makeLeg(nextState);
leg.mode = mode.toString(); // maybe makeLeg should be setting the mode ?
itinerary.addLeg(leg);
if (mode.isOnStreetNonTransit()) {
startWalk = i;
}
prevState = nextState;
continue;
}
/* skip initial state, which has no back edges */
edgeElapsedTime = nextState.getTimeInMillis()
- nextState.getBackState().getTimeInMillis();
TraverseMode previousMode = backEdgeNarrative.getMode();
if (previousMode == null) {
previousMode = prevState.getBackState().getBackEdgeNarrative().getMode();
}
if (backEdgeNarrative instanceof LegSwitchingEdge) {
leg.walkSteps = getWalkSteps(pathService, path.states.subList(startWalk, i - 1));
leg = makeLeg(nextState);
leg.mode = mode.toString(); //may need to fix this up
itinerary.addLeg(leg);
if (mode.isOnStreetNonTransit()) {
startWalk = i;
}
prevState = nextState;
continue;
}
// handle the effects of the previous edge on the leg
/* ignore edges that should not contribute to the narrative */
if (backEdge instanceof FreeEdge) {
prevState = nextState;
continue;
}
if (previousMode == TraverseMode.BOARDING || previousMode == TraverseMode.ALIGHTING) {
itinerary.waitingTime += edgeElapsedTime;
}
leg.distance += backEdgeNarrative.getDistance();
/* for all edges with geometry, append their coordinates to the leg's. */
Geometry edgeGeometry = backEdgeNarrative.getGeometry();
if (edgeGeometry != null) {
Coordinate[] edgeCoordinates = edgeGeometry.getCoordinates();
if (coordinates.size() > 0
&& coordinates.getCoordinate(coordinates.size() - 1).equals(
edgeCoordinates[0])) {
coordinates.extend(edgeCoordinates, 1);
} else {
coordinates.extend(edgeCoordinates);
}
}
addNotesToLeg(leg, backEdgeNarrative);
/*
* we are not boarding, alighting, etc. so are we walking/biking/driving or using
* transit?
*/
if (previousMode.isOnStreetNonTransit()) {
/* we are on the street (non-transit) */
itinerary.walkTime += edgeElapsedTime;
itinerary.walkDistance += backEdgeNarrative.getDistance();
if (backEdge instanceof EdgeWithElevation) {
PackedCoordinateSequence profile = ((EdgeWithElevation) backEdge)
.getElevationProfile();
previousElevation = applyElevation(profile, itinerary, previousElevation);
}
leg.endTime = new Date(nextState.getTimeInMillis());
} else if (previousMode.isTransit()) {
leg.endTime = new Date(nextState.getTimeInMillis());
/* we are on a transit trip */
itinerary.transitTime += edgeElapsedTime;
if (showIntermediateStops) {
/* add an intermediate stop to the current leg */
if (leg.stop == null) {
/*
* first transit edge, just create the list (the initial stop is current
* "from" vertex)
*/
leg.stop = new ArrayList<Place>();
}
/* any further transit edge, add "from" vertex to intermediate stops */
if (!(nextState.getBackEdge() instanceof Dwell
|| nextState.getBackEdge() instanceof PatternDwell || nextState
.getBackEdge() instanceof PatternInterlineDwell)) {
Place stop = makePlace(nextState);
leg.stop.add(stop);
} else {
leg.stop.get(leg.stop.size() - 1).departure = new Date(nextState.getTime());
}
}
}
// now, transition between legs if necessary
boolean changingToInterlinedTrip = leg != null && leg.route != null
&& !leg.route.equals(backEdgeNarrative.getName()) && mode.isTransit()
&& previousMode != null && previousMode.isTransit();
if ((mode != previousMode || changingToInterlinedTrip) && mode != TraverseMode.STL) {
/*
* change in mode. make a new leg if we are entering walk or transit, otherwise just
* update the general itinerary info and move to next edge.
*/
boolean endLeg = false;
if (previousMode == TraverseMode.STL && mode.isOnStreetNonTransit()) {
// switching from STL to wall or bike, so we need to fix up
// the start time,
// mode, etc
leg.startTime = new Date(nextState.getTimeInMillis());
leg.route = frontEdgeNarrative.getName();
leg.mode = mode.toString();
startWalk = i;
} else if (mode == TraverseMode.TRANSFER) {
/* transferring mode is only used in transit-only planners */
itinerary.walkTime += edgeElapsedTime;
itinerary.walkDistance += backEdgeNarrative.getDistance();
} else if (mode == TraverseMode.BOARDING) {
/* boarding mode */
itinerary.transfers++;
endLeg = true;
} else if (mode == TraverseMode.ALIGHTING || changingToInterlinedTrip) {
endLeg = true;
} else {
if (previousMode == TraverseMode.ALIGHTING) {
// in this case, we are changing from an alighting mode
// (preAlight) to
// an onstreetnontransit. In this case, we have already
// closed the
// transit leg with alighting, so we don't want to
// finalize a leg.
} else if (previousMode == TraverseMode.BOARDING) {
// we are changing from boarding to an on-transit mode,
// so we need to
// fix up the leg's route and departure time data
leg.startTime = new Date(prevState.getTimeInMillis());
leg.route = frontEdgeNarrative.getName();
leg.mode = mode.toString();
Trip trip = frontEdgeNarrative.getTrip();
if (trip != null) {
leg.headsign = trip.getTripHeadsign();
leg.agencyId = trip.getId().getAgencyId();
leg.tripShortName = trip.getTripShortName();
leg.routeShortName = trip.getRoute().getShortName();
leg.routeLongName = trip.getRoute().getLongName();
}
} else {
// we are probably changing between walk and bike
endLeg = true;
}
}
if (endLeg) {
/* finalize leg */
/* finalize prior leg if it exists */
if (startWalk != -1) {
leg.walkSteps = getWalkSteps(pathService, path.states.subList(startWalk,
i - 1));
}
leg.to = makePlace(frontEdgeNarrative.getFromVertex());
leg.endTime = new Date(prevState.getTimeInMillis());
Geometry geometry = geometryFactory.createLineString(coordinates);
leg.legGeometry = PolylineEncoder.createEncodings(geometry);
/* reset coordinates */
coordinates = new CoordinateArrayListSequence();
if (showIntermediateStops && leg.stop != null) {
// Remove the last stop -- it's the alighting one
leg.stop.remove(leg.stop.size() - 1);
if (leg.stop.isEmpty()) {
leg.stop = null;
}
}
/* initialize new leg */
leg = makeLeg(nextState);
if (changingToInterlinedTrip) {
leg.interlineWithPreviousLeg = true;
}
leg.mode = mode.toString();
startWalk = -1;
leg.route = backEdgeNarrative.getName();
if (mode.isOnStreetNonTransit()) {
/*
* on-street (walk/bike) leg mark where in edge list on-street legs begin,
* so step-by-step instructions can be generated for this sublist later
*/
startWalk = i;
} else {
/* transit leg */
startWalk = -1;
}
itinerary.addLeg(leg);
}
} /* end handling mode changes */
prevState = nextState;
} /* end loop over graphPath edge list */
if (leg != null) {
/* finalize leg */
leg.to = makePlace(backEdgeNarrative.getToVertex());
State finalState = path.states.getLast();
leg.endTime = new Date(finalState.getTimeInMillis());
Geometry geometry = geometryFactory.createLineString(coordinates);
leg.legGeometry = PolylineEncoder.createEncodings(geometry);
if (startWalk != -1) {
leg.walkSteps = getWalkSteps(pathService, path.states.subList(startWalk, i + 1));
}
if (showIntermediateStops && leg.stop != null) {
// Remove the last stop -- it's the alighting one
leg.stop.remove(leg.stop.size() - 1);
if (leg.stop.isEmpty()) {
leg.stop = null;
}
}
}
if (itinerary.transfers == -1) {
itinerary.transfers = 0;
}
itinerary.removeBogusLegs();
return itinerary;
}
| private Itinerary generateItinerary(GraphPath path, boolean showIntermediateStops) {
Itinerary itinerary = makeEmptyItinerary(path);
Leg leg = null;
CoordinateArrayListSequence coordinates = new CoordinateArrayListSequence();
double previousElevation = Double.MAX_VALUE;
double edgeElapsedTime;
GeometryFactory geometryFactory = new GeometryFactory();
int startWalk = -1;
int i = -1;
State prevState = null;
EdgeNarrative backEdgeNarrative = null;
for (State nextState : path.states) {
i++;
/* grab base edge and associated narrative information from SPT edge */
if (prevState == null) {
prevState = nextState;
continue;
}
EdgeNarrative frontEdgeNarrative = nextState.getBackEdgeNarrative();
backEdgeNarrative = prevState.getBackEdgeNarrative();
Edge backEdge = prevState.getBackEdge();
TraverseMode mode = frontEdgeNarrative.getMode();
if (backEdgeNarrative == null) {
// this is the first state, so we need to create the initial leg
leg = makeLeg(nextState);
leg.mode = mode.toString(); // maybe makeLeg should be setting the mode ?
itinerary.addLeg(leg);
if (mode.isOnStreetNonTransit()) {
startWalk = i;
}
prevState = nextState;
continue;
}
edgeElapsedTime = nextState.getTimeInMillis()
- nextState.getBackState().getTimeInMillis();
TraverseMode previousMode = backEdgeNarrative.getMode();
if (previousMode == null) {
previousMode = prevState.getBackState().getBackEdgeNarrative().getMode();
}
if (backEdgeNarrative instanceof LegSwitchingEdge) {
leg.walkSteps = getWalkSteps(pathService, path.states.subList(startWalk, i - 1));
leg = makeLeg(nextState);
leg.mode = mode.toString(); //may need to fix this up
itinerary.addLeg(leg);
if (mode.isOnStreetNonTransit()) {
startWalk = i;
}
prevState = nextState;
continue;
}
// handle the effects of the previous edge on the leg
/* ignore edges that should not contribute to the narrative */
if (backEdge instanceof FreeEdge) {
leg.mode = frontEdgeNarrative.getMode().toString();
prevState = nextState;
continue;
}
if (previousMode == TraverseMode.BOARDING || previousMode == TraverseMode.ALIGHTING) {
itinerary.waitingTime += edgeElapsedTime;
}
leg.distance += backEdgeNarrative.getDistance();
/* for all edges with geometry, append their coordinates to the leg's. */
Geometry edgeGeometry = backEdgeNarrative.getGeometry();
if (edgeGeometry != null) {
Coordinate[] edgeCoordinates = edgeGeometry.getCoordinates();
if (coordinates.size() > 0
&& coordinates.getCoordinate(coordinates.size() - 1).equals(
edgeCoordinates[0])) {
coordinates.extend(edgeCoordinates, 1);
} else {
coordinates.extend(edgeCoordinates);
}
}
addNotesToLeg(leg, backEdgeNarrative);
/*
* we are not boarding, alighting, etc. so are we walking/biking/driving or using
* transit?
*/
if (previousMode.isOnStreetNonTransit()) {
/* we are on the street (non-transit) */
itinerary.walkTime += edgeElapsedTime;
itinerary.walkDistance += backEdgeNarrative.getDistance();
if (backEdge instanceof EdgeWithElevation) {
PackedCoordinateSequence profile = ((EdgeWithElevation) backEdge)
.getElevationProfile();
previousElevation = applyElevation(profile, itinerary, previousElevation);
}
leg.endTime = new Date(nextState.getTimeInMillis());
} else if (previousMode.isTransit()) {
leg.endTime = new Date(nextState.getTimeInMillis());
/* we are on a transit trip */
itinerary.transitTime += edgeElapsedTime;
if (showIntermediateStops) {
/* add an intermediate stop to the current leg */
if (leg.stop == null) {
/*
* first transit edge, just create the list (the initial stop is current
* "from" vertex)
*/
leg.stop = new ArrayList<Place>();
}
/* any further transit edge, add "from" vertex to intermediate stops */
if (!(nextState.getBackEdge() instanceof Dwell
|| nextState.getBackEdge() instanceof PatternDwell || nextState
.getBackEdge() instanceof PatternInterlineDwell)) {
Place stop = makePlace(nextState);
leg.stop.add(stop);
} else {
leg.stop.get(leg.stop.size() - 1).departure = new Date(nextState.getTime());
}
}
}
// now, transition between legs if necessary
boolean changingToInterlinedTrip = leg != null && leg.route != null
&& !leg.route.equals(backEdgeNarrative.getName()) && mode.isTransit()
&& previousMode != null && previousMode.isTransit();
if ((mode != previousMode || changingToInterlinedTrip) && mode != TraverseMode.STL) {
/*
* change in mode. make a new leg if we are entering walk or transit, otherwise just
* update the general itinerary info and move to next edge.
*/
boolean endLeg = false;
if (previousMode == TraverseMode.STL && mode.isOnStreetNonTransit()) {
// switching from STL to wall or bike, so we need to fix up
// the start time,
// mode, etc
leg.startTime = new Date(nextState.getTimeInMillis());
leg.route = frontEdgeNarrative.getName();
leg.mode = mode.toString();
startWalk = i;
} else if (mode == TraverseMode.TRANSFER) {
/* transferring mode is only used in transit-only planners */
itinerary.walkTime += edgeElapsedTime;
itinerary.walkDistance += backEdgeNarrative.getDistance();
} else if (mode == TraverseMode.BOARDING) {
/* boarding mode */
itinerary.transfers++;
endLeg = true;
} else if (mode == TraverseMode.ALIGHTING || changingToInterlinedTrip) {
endLeg = true;
} else {
if (previousMode == TraverseMode.ALIGHTING) {
// in this case, we are changing from an alighting mode
// (preAlight) to
// an onstreetnontransit. In this case, we have already
// closed the
// transit leg with alighting, so we don't want to
// finalize a leg.
} else if (previousMode == TraverseMode.BOARDING) {
// we are changing from boarding to an on-transit mode,
// so we need to
// fix up the leg's route and departure time data
leg.startTime = new Date(prevState.getTimeInMillis());
leg.route = frontEdgeNarrative.getName();
leg.mode = mode.toString();
Trip trip = frontEdgeNarrative.getTrip();
if (trip != null) {
leg.headsign = trip.getTripHeadsign();
leg.agencyId = trip.getId().getAgencyId();
leg.tripShortName = trip.getTripShortName();
leg.routeShortName = trip.getRoute().getShortName();
leg.routeLongName = trip.getRoute().getLongName();
}
} else {
// we are probably changing between walk and bike
endLeg = true;
}
}
if (endLeg) {
/* finalize leg */
/* finalize prior leg if it exists */
if (startWalk != -1) {
leg.walkSteps = getWalkSteps(pathService, path.states.subList(startWalk,
i - 1));
}
leg.to = makePlace(frontEdgeNarrative.getFromVertex());
leg.endTime = new Date(prevState.getTimeInMillis());
Geometry geometry = geometryFactory.createLineString(coordinates);
leg.legGeometry = PolylineEncoder.createEncodings(geometry);
/* reset coordinates */
coordinates = new CoordinateArrayListSequence();
if (showIntermediateStops && leg.stop != null) {
// Remove the last stop -- it's the alighting one
leg.stop.remove(leg.stop.size() - 1);
if (leg.stop.isEmpty()) {
leg.stop = null;
}
}
/* initialize new leg */
leg = makeLeg(nextState);
if (changingToInterlinedTrip) {
leg.interlineWithPreviousLeg = true;
}
leg.mode = mode.toString();
startWalk = -1;
leg.route = backEdgeNarrative.getName();
if (mode.isOnStreetNonTransit()) {
/*
* on-street (walk/bike) leg mark where in edge list on-street legs begin,
* so step-by-step instructions can be generated for this sublist later
*/
startWalk = i;
} else {
/* transit leg */
startWalk = -1;
}
itinerary.addLeg(leg);
}
} /* end handling mode changes */
prevState = nextState;
} /* end loop over graphPath edge list */
if (leg != null) {
/* finalize leg */
leg.to = makePlace(backEdgeNarrative.getToVertex());
State finalState = path.states.getLast();
leg.endTime = new Date(finalState.getTimeInMillis());
Geometry geometry = geometryFactory.createLineString(coordinates);
leg.legGeometry = PolylineEncoder.createEncodings(geometry);
if (startWalk != -1) {
leg.walkSteps = getWalkSteps(pathService, path.states.subList(startWalk, i + 1));
}
if (showIntermediateStops && leg.stop != null) {
// Remove the last stop -- it's the alighting one
leg.stop.remove(leg.stop.size() - 1);
if (leg.stop.isEmpty()) {
leg.stop = null;
}
}
}
if (itinerary.transfers == -1) {
itinerary.transfers = 0;
}
itinerary.removeBogusLegs();
return itinerary;
}
|
diff --git a/SimpleWebServer/src/protocol/HttpRequest.java b/SimpleWebServer/src/protocol/HttpRequest.java
index 8f76b2c..31bf5c2 100644
--- a/SimpleWebServer/src/protocol/HttpRequest.java
+++ b/SimpleWebServer/src/protocol/HttpRequest.java
@@ -1,185 +1,185 @@
/*
* HttpRequest.java
* Oct 7, 2012
*
* Simple Web Server (SWS) for CSSE 477
*
* Copyright (C) 2012 Chandan Raj Rupakheti
*
* This program is free software: you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public License
* as published by the Free Software Foundation, either
* version 3 of the License, or any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/lgpl.html>.
*
*/
package protocol;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.StringTokenizer;
/**
* Represents a request object for HTTP.
*
* @author Chandan R. Rupakheti ([email protected])
*/
public class HttpRequest {
private String method;
private String uri;
private String version;
private Map<String, String> header;
private HttpRequest() {
this.header = new HashMap<String, String>();
}
/**
* The request method.
*
* @return the method
*/
public String getMethod() {
return method;
}
/**
* The URI of the request object.
*
* @return the uri
*/
public String getUri() {
return uri;
}
/**
* The version of the http request.
* @return the version
*/
public String getVersion() {
return version;
}
/**
* The key to value mapping in the request header fields.
*
* @return the header
*/
public Map<String, String> getHeader() {
// Lets return the unmodifable view of the header map
return Collections.unmodifiableMap(header);
}
/**
* Reads raw data from the supplied input stream and constructs a
* <tt>HttpRequest</tt> object out of the raw data.
*
* @param inputStream The input stream to read from.
* @return A <tt>HttpRequest</tt> object.
* @throws Exception Throws either {@link ProtocolException} for bad request or
* {@link IOException} for socket input stream read errors.
*/
public static HttpRequest read(InputStream inputStream) throws Exception {
// We will fill this object with the data from input stream and return it
HttpRequest request = new HttpRequest();
InputStreamReader inStreamReader = new InputStreamReader(inputStream);
BufferedReader reader = new BufferedReader(inStreamReader);
//First Request Line: GET /somedir/page.html HTTP/1.1
String line = reader.readLine(); // A line ends with either a \r, or a \n, or both
if(line == null) {
throw new ProtocolException(Protocol.BAD_REQUEST_CODE, Protocol.BAD_REQUEST_TEXT);
}
// We will break this line using space as delimeter into three parts
StringTokenizer tokenizer = new StringTokenizer(line, " ");
// Error checking the first line must have exactly three elements
if(tokenizer.countTokens() != 3) {
throw new ProtocolException(Protocol.BAD_REQUEST_CODE, Protocol.BAD_REQUEST_TEXT);
}
request.method = tokenizer.nextToken(); // GET
request.uri = tokenizer.nextToken(); // /somedir/page.html
request.version = tokenizer.nextToken(); // HTTP/1.1
- if(request.method != Protocol.GET){
+ if(!request.method.equals(Protocol.GET)){
throw new ProtocolException(Protocol.NOT_SUPPORTED_CODE, Protocol.NOT_SUPPORTED_TEXT);
}
// Rest of the request is a header that maps keys to values
// e.g. Host: www.rose-hulman.edu
// We will convert both the strings to lower case to be able to search later
line = reader.readLine().trim();
while(!line.equals("")) {
// THIS IS A PATCH
// Instead of a string tokenizer, we are using string split
// Lets break the line into two part with first space as a separator
// First lets trim the line to remove escape characters
line = line.trim();
// Now, get index of the first occurrence of space
int index = line.indexOf(' ');
if(index > 0 && index < line.length()-1) {
// Now lets break the string in two parts
String key = line.substring(0, index); // Get first part, e.g. "Host:"
String value = line.substring(index+1); // Get the rest, e.g. "www.rose-hulman.edu"
// Lets strip off the white spaces from key if any and change it to lower case
key = key.trim().toLowerCase();
// Lets also remove ":" from the key
key = key.substring(0, key.length() - 1);
// Lets strip white spaces if any from value as well
value = value.trim();
// Now lets put the key=>value mapping to the header map
request.header.put(key, value);
}
// Processed one more line, now lets read another header line and loop
line = reader.readLine().trim();
}
return request;
}
@Override
public String toString() {
StringBuffer buffer = new StringBuffer();
buffer.append("----------------------------------\n");
buffer.append(this.method);
buffer.append(Protocol.SPACE);
buffer.append(this.uri);
buffer.append(Protocol.SPACE);
buffer.append(this.version);
buffer.append(Protocol.LF);
for(Map.Entry<String, String> entry : this.header.entrySet()) {
buffer.append(entry.getKey());
buffer.append(Protocol.SEPERATOR);
buffer.append(Protocol.SPACE);
buffer.append(entry.getValue());
buffer.append(Protocol.LF);
}
buffer.append("----------------------------------\n");
return buffer.toString();
}
}
| true | true | public static HttpRequest read(InputStream inputStream) throws Exception {
// We will fill this object with the data from input stream and return it
HttpRequest request = new HttpRequest();
InputStreamReader inStreamReader = new InputStreamReader(inputStream);
BufferedReader reader = new BufferedReader(inStreamReader);
//First Request Line: GET /somedir/page.html HTTP/1.1
String line = reader.readLine(); // A line ends with either a \r, or a \n, or both
if(line == null) {
throw new ProtocolException(Protocol.BAD_REQUEST_CODE, Protocol.BAD_REQUEST_TEXT);
}
// We will break this line using space as delimeter into three parts
StringTokenizer tokenizer = new StringTokenizer(line, " ");
// Error checking the first line must have exactly three elements
if(tokenizer.countTokens() != 3) {
throw new ProtocolException(Protocol.BAD_REQUEST_CODE, Protocol.BAD_REQUEST_TEXT);
}
request.method = tokenizer.nextToken(); // GET
request.uri = tokenizer.nextToken(); // /somedir/page.html
request.version = tokenizer.nextToken(); // HTTP/1.1
if(request.method != Protocol.GET){
throw new ProtocolException(Protocol.NOT_SUPPORTED_CODE, Protocol.NOT_SUPPORTED_TEXT);
}
// Rest of the request is a header that maps keys to values
// e.g. Host: www.rose-hulman.edu
// We will convert both the strings to lower case to be able to search later
line = reader.readLine().trim();
while(!line.equals("")) {
// THIS IS A PATCH
// Instead of a string tokenizer, we are using string split
// Lets break the line into two part with first space as a separator
// First lets trim the line to remove escape characters
line = line.trim();
// Now, get index of the first occurrence of space
int index = line.indexOf(' ');
if(index > 0 && index < line.length()-1) {
// Now lets break the string in two parts
String key = line.substring(0, index); // Get first part, e.g. "Host:"
String value = line.substring(index+1); // Get the rest, e.g. "www.rose-hulman.edu"
// Lets strip off the white spaces from key if any and change it to lower case
key = key.trim().toLowerCase();
// Lets also remove ":" from the key
key = key.substring(0, key.length() - 1);
// Lets strip white spaces if any from value as well
value = value.trim();
// Now lets put the key=>value mapping to the header map
request.header.put(key, value);
}
// Processed one more line, now lets read another header line and loop
line = reader.readLine().trim();
}
return request;
}
| public static HttpRequest read(InputStream inputStream) throws Exception {
// We will fill this object with the data from input stream and return it
HttpRequest request = new HttpRequest();
InputStreamReader inStreamReader = new InputStreamReader(inputStream);
BufferedReader reader = new BufferedReader(inStreamReader);
//First Request Line: GET /somedir/page.html HTTP/1.1
String line = reader.readLine(); // A line ends with either a \r, or a \n, or both
if(line == null) {
throw new ProtocolException(Protocol.BAD_REQUEST_CODE, Protocol.BAD_REQUEST_TEXT);
}
// We will break this line using space as delimeter into three parts
StringTokenizer tokenizer = new StringTokenizer(line, " ");
// Error checking the first line must have exactly three elements
if(tokenizer.countTokens() != 3) {
throw new ProtocolException(Protocol.BAD_REQUEST_CODE, Protocol.BAD_REQUEST_TEXT);
}
request.method = tokenizer.nextToken(); // GET
request.uri = tokenizer.nextToken(); // /somedir/page.html
request.version = tokenizer.nextToken(); // HTTP/1.1
if(!request.method.equals(Protocol.GET)){
throw new ProtocolException(Protocol.NOT_SUPPORTED_CODE, Protocol.NOT_SUPPORTED_TEXT);
}
// Rest of the request is a header that maps keys to values
// e.g. Host: www.rose-hulman.edu
// We will convert both the strings to lower case to be able to search later
line = reader.readLine().trim();
while(!line.equals("")) {
// THIS IS A PATCH
// Instead of a string tokenizer, we are using string split
// Lets break the line into two part with first space as a separator
// First lets trim the line to remove escape characters
line = line.trim();
// Now, get index of the first occurrence of space
int index = line.indexOf(' ');
if(index > 0 && index < line.length()-1) {
// Now lets break the string in two parts
String key = line.substring(0, index); // Get first part, e.g. "Host:"
String value = line.substring(index+1); // Get the rest, e.g. "www.rose-hulman.edu"
// Lets strip off the white spaces from key if any and change it to lower case
key = key.trim().toLowerCase();
// Lets also remove ":" from the key
key = key.substring(0, key.length() - 1);
// Lets strip white spaces if any from value as well
value = value.trim();
// Now lets put the key=>value mapping to the header map
request.header.put(key, value);
}
// Processed one more line, now lets read another header line and loop
line = reader.readLine().trim();
}
return request;
}
|
diff --git a/gerrit-gwtui/src/main/java/com/google/gerrit/client/changes/CommitMessageBlock.java b/gerrit-gwtui/src/main/java/com/google/gerrit/client/changes/CommitMessageBlock.java
index 6a364e043..eff3cd59d 100644
--- a/gerrit-gwtui/src/main/java/com/google/gerrit/client/changes/CommitMessageBlock.java
+++ b/gerrit-gwtui/src/main/java/com/google/gerrit/client/changes/CommitMessageBlock.java
@@ -1,110 +1,112 @@
// Copyright (C) 2010 The Android Open Source Project
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.gerrit.client.changes;
import com.google.gerrit.client.Gerrit;
import com.google.gerrit.client.ui.ChangeLink;
import com.google.gerrit.client.ui.CommentLinkProcessor;
import com.google.gerrit.reviewdb.client.Change;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.core.client.GWT;
import com.google.gwt.dom.client.PreElement;
import com.google.gwt.dom.client.Style.Display;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.user.client.ui.FlowPanel;
import com.google.gwt.user.client.ui.HTMLPanel;
import com.google.gwt.user.client.ui.SimplePanel;
import com.google.gwtexpui.clippy.client.CopyableLabel;
import com.google.gwtexpui.globalkey.client.KeyCommandSet;
import com.google.gwtexpui.safehtml.client.SafeHtml;
import com.google.gwtexpui.safehtml.client.SafeHtmlBuilder;
public class CommitMessageBlock extends Composite {
interface Binder extends UiBinder<HTMLPanel, CommitMessageBlock> {
}
private static Binder uiBinder = GWT.create(Binder.class);
private KeyCommandSet keysAction;
@UiField
SimplePanel starPanel;
@UiField
FlowPanel permalinkPanel;
@UiField
PreElement commitSummaryPre;
@UiField
PreElement commitBodyPre;
public CommitMessageBlock() {
initWidget(uiBinder.createAndBindUi(this));
}
public CommitMessageBlock(KeyCommandSet keysAction) {
this.keysAction = keysAction;
initWidget(uiBinder.createAndBindUi(this));
}
public void display(final String commitMessage) {
display(null, null, commitMessage);
}
public void display(Change.Id changeId, Boolean starred, String commitMessage) {
starPanel.clear();
if (changeId != null && starred != null && Gerrit.isSignedIn()) {
StarredChanges.Icon star = StarredChanges.createIcon(changeId, starred);
star.setStyleName(Gerrit.RESOURCES.css().changeScreenStarIcon());
starPanel.add(star);
if (keysAction != null) {
keysAction.add(StarredChanges.newKeyCommand(star));
}
}
permalinkPanel.clear();
if (changeId != null) {
permalinkPanel.add(new ChangeLink(Util.C.changePermalink(), changeId));
permalinkPanel.add(new CopyableLabel(ChangeLink.permalink(changeId), false));
}
String[] splitCommitMessage = commitMessage.split("\n", 2);
String commitSummary = splitCommitMessage[0];
String commitBody = "";
if (splitCommitMessage.length > 1) {
commitBody = splitCommitMessage[1];
}
// Linkify commit summary
SafeHtml commitSummaryLinkified = new SafeHtmlBuilder().append(commitSummary);
commitSummaryLinkified = commitSummaryLinkified.linkify();
commitSummaryLinkified = CommentLinkProcessor.apply(commitSummaryLinkified);
commitSummaryPre.setInnerHTML(commitSummaryLinkified.asString());
// Hide commit body if there is no body
if (commitBody.trim().isEmpty()) {
commitBodyPre.getStyle().setDisplay(Display.NONE);
} else {
// Linkify commit body
SafeHtml commitBodyLinkified = new SafeHtmlBuilder().append(commitBody);
commitBodyLinkified = commitBodyLinkified.linkify();
commitBodyLinkified = CommentLinkProcessor.apply(commitBodyLinkified);
+ commitBodyLinkified = commitBodyLinkified.replaceAll("\n\n", "<p></p>");
+ commitBodyLinkified = commitBodyLinkified.replaceAll("\n", "<br />");
commitBodyPre.setInnerHTML(commitBodyLinkified.asString());
}
}
}
| true | true | public void display(Change.Id changeId, Boolean starred, String commitMessage) {
starPanel.clear();
if (changeId != null && starred != null && Gerrit.isSignedIn()) {
StarredChanges.Icon star = StarredChanges.createIcon(changeId, starred);
star.setStyleName(Gerrit.RESOURCES.css().changeScreenStarIcon());
starPanel.add(star);
if (keysAction != null) {
keysAction.add(StarredChanges.newKeyCommand(star));
}
}
permalinkPanel.clear();
if (changeId != null) {
permalinkPanel.add(new ChangeLink(Util.C.changePermalink(), changeId));
permalinkPanel.add(new CopyableLabel(ChangeLink.permalink(changeId), false));
}
String[] splitCommitMessage = commitMessage.split("\n", 2);
String commitSummary = splitCommitMessage[0];
String commitBody = "";
if (splitCommitMessage.length > 1) {
commitBody = splitCommitMessage[1];
}
// Linkify commit summary
SafeHtml commitSummaryLinkified = new SafeHtmlBuilder().append(commitSummary);
commitSummaryLinkified = commitSummaryLinkified.linkify();
commitSummaryLinkified = CommentLinkProcessor.apply(commitSummaryLinkified);
commitSummaryPre.setInnerHTML(commitSummaryLinkified.asString());
// Hide commit body if there is no body
if (commitBody.trim().isEmpty()) {
commitBodyPre.getStyle().setDisplay(Display.NONE);
} else {
// Linkify commit body
SafeHtml commitBodyLinkified = new SafeHtmlBuilder().append(commitBody);
commitBodyLinkified = commitBodyLinkified.linkify();
commitBodyLinkified = CommentLinkProcessor.apply(commitBodyLinkified);
commitBodyPre.setInnerHTML(commitBodyLinkified.asString());
}
}
| public void display(Change.Id changeId, Boolean starred, String commitMessage) {
starPanel.clear();
if (changeId != null && starred != null && Gerrit.isSignedIn()) {
StarredChanges.Icon star = StarredChanges.createIcon(changeId, starred);
star.setStyleName(Gerrit.RESOURCES.css().changeScreenStarIcon());
starPanel.add(star);
if (keysAction != null) {
keysAction.add(StarredChanges.newKeyCommand(star));
}
}
permalinkPanel.clear();
if (changeId != null) {
permalinkPanel.add(new ChangeLink(Util.C.changePermalink(), changeId));
permalinkPanel.add(new CopyableLabel(ChangeLink.permalink(changeId), false));
}
String[] splitCommitMessage = commitMessage.split("\n", 2);
String commitSummary = splitCommitMessage[0];
String commitBody = "";
if (splitCommitMessage.length > 1) {
commitBody = splitCommitMessage[1];
}
// Linkify commit summary
SafeHtml commitSummaryLinkified = new SafeHtmlBuilder().append(commitSummary);
commitSummaryLinkified = commitSummaryLinkified.linkify();
commitSummaryLinkified = CommentLinkProcessor.apply(commitSummaryLinkified);
commitSummaryPre.setInnerHTML(commitSummaryLinkified.asString());
// Hide commit body if there is no body
if (commitBody.trim().isEmpty()) {
commitBodyPre.getStyle().setDisplay(Display.NONE);
} else {
// Linkify commit body
SafeHtml commitBodyLinkified = new SafeHtmlBuilder().append(commitBody);
commitBodyLinkified = commitBodyLinkified.linkify();
commitBodyLinkified = CommentLinkProcessor.apply(commitBodyLinkified);
commitBodyLinkified = commitBodyLinkified.replaceAll("\n\n", "<p></p>");
commitBodyLinkified = commitBodyLinkified.replaceAll("\n", "<br />");
commitBodyPre.setInnerHTML(commitBodyLinkified.asString());
}
}
|
diff --git a/sdk/jme3-core/src/com/jme3/gde/core/assets/AssetDataObject.java b/sdk/jme3-core/src/com/jme3/gde/core/assets/AssetDataObject.java
index c55676a08..3ad3f3a49 100644
--- a/sdk/jme3-core/src/com/jme3/gde/core/assets/AssetDataObject.java
+++ b/sdk/jme3-core/src/com/jme3/gde/core/assets/AssetDataObject.java
@@ -1,220 +1,221 @@
/*
* Copyright (c) 2009-2010 jMonkeyEngine
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* * Neither the name of 'jMonkeyEngine' nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.jme3.gde.core.assets;
import com.jme3.asset.AssetKey;
import com.jme3.export.Savable;
import com.jme3.export.binary.BinaryExporter;
import com.jme3.gde.core.scene.SceneApplication;
import java.io.IOException;
import java.io.OutputStream;
import java.util.concurrent.Callable;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.netbeans.api.progress.ProgressHandle;
import org.netbeans.api.progress.ProgressHandleFactory;
import org.netbeans.api.project.Project;
import org.netbeans.api.project.ProjectManager;
import org.openide.awt.StatusDisplayer;
import org.openide.cookies.SaveCookie;
import org.openide.filesystems.FileLock;
import org.openide.filesystems.FileObject;
import org.openide.filesystems.FileUtil;
import org.openide.loaders.DataNode;
import org.openide.loaders.DataObjectExistsException;
import org.openide.loaders.MultiDataObject;
import org.openide.loaders.MultiFileLoader;
import org.openide.nodes.Children;
import org.openide.nodes.Node;
import org.openide.util.Exceptions;
import org.openide.util.Lookup;
import org.openide.util.lookup.AbstractLookup;
import org.openide.util.lookup.InstanceContent;
import org.openide.util.lookup.Lookups;
import org.openide.util.lookup.ProxyLookup;
/**
*
* @author normenhansen
*/
public class AssetDataObject extends MultiDataObject {
protected final Lookup lookup;
protected final InstanceContent lookupContents = new InstanceContent();
protected SaveCookie saveCookie = new SaveCookie() {
public void save() throws IOException {
//TODO: On OpenGL thread? -- safest way.. with get()?
SceneApplication.getApplication().enqueue(new Callable() {
public Object call() throws Exception {
saveAsset();
return null;
}
});
}
};
protected DataNode dataNode;
protected Savable savable;
protected String saveExtension;
public AssetDataObject(FileObject pf, MultiFileLoader loader) throws DataObjectExistsException, IOException {
super(pf, loader);
lookup = new ProxyLookup(getCookieSet().getLookup(), new AbstractLookup(getLookupContents()), Lookups.fixed(new AssetData(this)));
setSaveCookie(saveCookie);
findAssetManager();
}
protected void findAssetManager() {
FileObject file = getPrimaryFile();
ProjectManager pm = ProjectManager.getDefault();
while (file != null) {
if (file.isFolder() && pm.isProject(file)) {
try {
Project project = ProjectManager.getDefault().findProject(file);
if (project != null) {
ProjectAssetManager mgr = project.getLookup().lookup(ProjectAssetManager.class);
if (mgr != null) {
getLookupContents().add(mgr);
return;
}
}
} catch (IOException ex) {
} catch (IllegalArgumentException ex) {
}
}
file = file.getParent();
}
}
@Override
protected Node createNodeDelegate() {
DataNode node = new DataNode(this, Children.LEAF, getLookup());
node.setIconBaseWithExtension("com/jme3/gde/core/assets/jme-logo.png");
return node;
}
@Override
public void setModified(boolean modif) {
super.setModified(modif);
if (modif && saveCookie != null) {
getCookieSet().assign(SaveCookie.class, saveCookie);
} else {
getCookieSet().assign(SaveCookie.class);
}
}
@Override
public Lookup getLookup() {
return lookup;
}
public InstanceContent getLookupContents() {
return lookupContents;
}
public void setSaveCookie(SaveCookie cookie) {
this.saveCookie = cookie;
getCookieSet().assign(SaveCookie.class, saveCookie);
setModified(false);
}
//TODO: make save as j3o
public Savable loadAsset() {
if (isModified() && savable != null) {
return savable;
}
ProjectAssetManager mgr = getLookup().lookup(ProjectAssetManager.class);
if (mgr == null) {
return null;
}
String assetKey = mgr.getRelativeAssetPath(getPrimaryFile().getPath());
FileLock lock = null;
try {
lock = getPrimaryFile().lock();
Savable spatial = (Savable) mgr.loadAsset(new AssetKey(assetKey));
savable = spatial;
lock.releaseLock();
} catch (Exception ex) {
Exceptions.printStackTrace(ex);
} finally {
if (lock != null) {
lock.releaseLock();
}
}
return savable;
}
public void saveAsset() throws IOException {
if (savable == null) {
Logger.getLogger(AssetDataObject.class.getName()).log(Level.WARNING, "Trying to save asset that has not been loaded before or does not support saving!");
return;
}
final Savable savable = this.savable;
ProgressHandle progressHandle = ProgressHandleFactory.createHandle("Saving File..");
progressHandle.start();
BinaryExporter exp = BinaryExporter.getInstance();
FileLock lock = null;
OutputStream out = null;
try {
if (saveExtension == null) {
out = getPrimaryFile().getOutputStream();
} else {
FileObject outFileObject = getPrimaryFile().getParent().getFileObject(getPrimaryFile().getName(), saveExtension);
if (outFileObject == null) {
outFileObject = getPrimaryFile().getParent().createData(getPrimaryFile().getName(), saveExtension);
}
out = outFileObject.getOutputStream();
+ outFileObject.getParent().refresh();
}
exp.save(savable, out);
} finally {
if (lock != null) {
lock.releaseLock();
}
if (out != null) {
out.close();
}
}
progressHandle.finish();
StatusDisplayer.getDefault().setStatusText(getPrimaryFile().getNameExt() + " saved.");
setModified(false);
}
public AssetKey<?> getAssetKey() {
ProjectAssetManager mgr = getLookup().lookup(ProjectAssetManager.class);
if (mgr == null) {
return null;
}
String assetKey = mgr.getRelativeAssetPath(getPrimaryFile().getPath());
return new AssetKey<Object>(assetKey);
}
}
| true | true | public void saveAsset() throws IOException {
if (savable == null) {
Logger.getLogger(AssetDataObject.class.getName()).log(Level.WARNING, "Trying to save asset that has not been loaded before or does not support saving!");
return;
}
final Savable savable = this.savable;
ProgressHandle progressHandle = ProgressHandleFactory.createHandle("Saving File..");
progressHandle.start();
BinaryExporter exp = BinaryExporter.getInstance();
FileLock lock = null;
OutputStream out = null;
try {
if (saveExtension == null) {
out = getPrimaryFile().getOutputStream();
} else {
FileObject outFileObject = getPrimaryFile().getParent().getFileObject(getPrimaryFile().getName(), saveExtension);
if (outFileObject == null) {
outFileObject = getPrimaryFile().getParent().createData(getPrimaryFile().getName(), saveExtension);
}
out = outFileObject.getOutputStream();
}
exp.save(savable, out);
} finally {
if (lock != null) {
lock.releaseLock();
}
if (out != null) {
out.close();
}
}
progressHandle.finish();
StatusDisplayer.getDefault().setStatusText(getPrimaryFile().getNameExt() + " saved.");
setModified(false);
}
| public void saveAsset() throws IOException {
if (savable == null) {
Logger.getLogger(AssetDataObject.class.getName()).log(Level.WARNING, "Trying to save asset that has not been loaded before or does not support saving!");
return;
}
final Savable savable = this.savable;
ProgressHandle progressHandle = ProgressHandleFactory.createHandle("Saving File..");
progressHandle.start();
BinaryExporter exp = BinaryExporter.getInstance();
FileLock lock = null;
OutputStream out = null;
try {
if (saveExtension == null) {
out = getPrimaryFile().getOutputStream();
} else {
FileObject outFileObject = getPrimaryFile().getParent().getFileObject(getPrimaryFile().getName(), saveExtension);
if (outFileObject == null) {
outFileObject = getPrimaryFile().getParent().createData(getPrimaryFile().getName(), saveExtension);
}
out = outFileObject.getOutputStream();
outFileObject.getParent().refresh();
}
exp.save(savable, out);
} finally {
if (lock != null) {
lock.releaseLock();
}
if (out != null) {
out.close();
}
}
progressHandle.finish();
StatusDisplayer.getDefault().setStatusText(getPrimaryFile().getNameExt() + " saved.");
setModified(false);
}
|
diff --git a/src/com/palmergames/bukkit/towny/command/TownyAdminCommand.java b/src/com/palmergames/bukkit/towny/command/TownyAdminCommand.java
index 661c46b..c23e790 100644
--- a/src/com/palmergames/bukkit/towny/command/TownyAdminCommand.java
+++ b/src/com/palmergames/bukkit/towny/command/TownyAdminCommand.java
@@ -1,676 +1,676 @@
package com.palmergames.bukkit.towny.command;
import com.palmergames.bukkit.towny.*;
import com.palmergames.bukkit.towny.exceptions.AlreadyRegisteredException;
import com.palmergames.bukkit.towny.exceptions.EmptyTownException;
import com.palmergames.bukkit.towny.exceptions.NotRegisteredException;
import com.palmergames.bukkit.towny.exceptions.TownyException;
import com.palmergames.bukkit.towny.object.*;
import com.palmergames.bukkit.towny.permissions.PermissionNodes;
import com.palmergames.bukkit.towny.tasks.ResidentPurge;
import com.palmergames.bukkit.towny.tasks.TownClaim;
import com.palmergames.bukkit.towny.utils.AreaSelectionUtil;
import com.palmergames.bukkit.util.BukkitTools;
import com.palmergames.bukkit.util.ChatTools;
import com.palmergames.bukkit.util.Colors;
import com.palmergames.bukkit.util.NameValidation;
import com.palmergames.util.MemMgmt;
import com.palmergames.util.StringMgmt;
import com.palmergames.util.TimeTools;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
/**
* Send a list of all general townyadmin help commands to player Command:
* /townyadmin
*/
public class TownyAdminCommand implements CommandExecutor {
private static Towny plugin;
private static final List<String> ta_help = new ArrayList<String>();
private static final List<String> ta_panel = new ArrayList<String>();
private static final List<String> ta_unclaim = new ArrayList<String>();
private boolean isConsole;
private Player player;
private CommandSender sender;
static {
ta_help.add(ChatTools.formatTitle("/townyadmin"));
ta_help.add(ChatTools.formatCommand("", "/townyadmin", "", TownySettings.getLangString("admin_panel_1")));
ta_help.add(ChatTools.formatCommand("", "/townyadmin", "set [] .. []", "'/townyadmin set' " + TownySettings.getLangString("res_5")));
ta_help.add(ChatTools.formatCommand("", "/townyadmin", "unclaim [radius]", ""));
ta_help.add(ChatTools.formatCommand("", "/townyadmin", "town/nation", ""));
ta_help.add(ChatTools.formatCommand("", "/townyadmin", "givebonus [town/player] [num]", ""));
ta_help.add(ChatTools.formatCommand("", "/townyadmin", "toggle neutral/war/debug/devmode", ""));
// TODO: ta_help.add(ChatTools.formatCommand("", "/townyadmin",
// "npc rename [old name] [new name]", ""));
// TODO: ta_help.add(ChatTools.formatCommand("", "/townyadmin",
// "npc list", ""));
ta_help.add(ChatTools.formatCommand("", "/townyadmin", "reload", TownySettings.getLangString("admin_panel_2")));
ta_help.add(ChatTools.formatCommand("", "/townyadmin", "reset", ""));
ta_help.add(ChatTools.formatCommand("", "/townyadmin", "backup", ""));
ta_help.add(ChatTools.formatCommand("", "/townyadmin", "newday", TownySettings.getLangString("admin_panel_3")));
ta_help.add(ChatTools.formatCommand("", "/townyadmin", "purge [number of days]", ""));
ta_help.add(ChatTools.formatCommand("", "/townyadmin", "delete [] .. []", "delete a residents data files."));
ta_unclaim.add(ChatTools.formatTitle("/townyadmin unclaim"));
ta_unclaim.add(ChatTools.formatCommand(TownySettings.getLangString("admin_sing"), "/townyadmin unclaim", "", TownySettings.getLangString("townyadmin_help_1")));
ta_unclaim.add(ChatTools.formatCommand(TownySettings.getLangString("admin_sing"), "/townyadmin unclaim", "[radius]", TownySettings.getLangString("townyadmin_help_2")));
}
public TownyAdminCommand(Towny instance) {
plugin = instance;
}
@Override
public boolean onCommand(CommandSender sender, Command cmd, String commandLabel, String[] args) {
this.sender = sender;
if (sender instanceof Player) {
player = (Player) sender;
isConsole = false;
System.out.println("[PLAYER_COMMAND] " + player.getName() + ": /" + commandLabel + " " + StringMgmt.join(args));
} else {
isConsole = true;
this.player = null;
}
try {
return parseTownyAdminCommand(args);
} catch (TownyException e) {
TownyMessaging.sendErrorMsg(sender, e.getMessage());
}
return true;
}
private Object getSender() {
if (isConsole)
return sender;
else
return player;
}
public boolean parseTownyAdminCommand(String[] split) throws TownyException {
if (split.length == 0) {
buildTAPanel();
for (String line : ta_panel) {
sender.sendMessage(line);
}
} else if (split[0].equalsIgnoreCase("?") || split[0].equalsIgnoreCase("help")) {
for (String line : ta_help) {
sender.sendMessage(line);
}
} else {
if (split[0].equalsIgnoreCase("set")) {
adminSet(StringMgmt.remFirstArg(split));
return true;
} else if (split[0].equalsIgnoreCase("town")) {
parseAdminTownCommand(StringMgmt.remFirstArg(split));
return true;
} else if (split[0].equalsIgnoreCase("nation")) {
parseAdminNationCommand(StringMgmt.remFirstArg(split));
return true;
} else if (split[0].equalsIgnoreCase("toggle")) {
parseToggleCommand(StringMgmt.remFirstArg(split));
return true;
}
- if (!TownyUniverse.getPermissionSource().testPermission(player, PermissionNodes.TOWNY_COMMAND_TOWNYADMIN.getNode(split[0].toLowerCase())))
+ if ((!isConsole) && (!TownyUniverse.getPermissionSource().testPermission(player, PermissionNodes.TOWNY_COMMAND_TOWNYADMIN.getNode(split[0].toLowerCase()))))
throw new TownyException(TownySettings.getLangString("msg_err_command_disable"));
if (split[0].equalsIgnoreCase("givebonus")) {
giveBonus(StringMgmt.remFirstArg(split));
} else if (split[0].equalsIgnoreCase("reload")) {
reloadTowny(false);
} else if (split[0].equalsIgnoreCase("reset")) {
reloadTowny(true);
} else if (split[0].equalsIgnoreCase("backup")) {
try {
TownyUniverse.getDataSource().backup();
TownyMessaging.sendMsg(getSender(), TownySettings.getLangString("mag_backup_success"));
} catch (IOException e) {
TownyMessaging.sendErrorMsg(getSender(), "Error: " + e.getMessage());
}
} else if (split[0].equalsIgnoreCase("newday")) {
TownyTimerHandler.newDay();
} else if (split[0].equalsIgnoreCase("purge")) {
purge(StringMgmt.remFirstArg(split));
} else if (split[0].equalsIgnoreCase("delete")) {
String[] newSplit = StringMgmt.remFirstArg(split);
residentDelete(player, newSplit);
} else if (split[0].equalsIgnoreCase("unclaim")) {
parseAdminUnclaimCommand(StringMgmt.remFirstArg(split));
/*
* else if (split[0].equalsIgnoreCase("seed") &&
* TownySettings.getDebug()) seedTowny(); else if
* (split[0].equalsIgnoreCase("warseed") &&
* TownySettings.getDebug()) warSeed(player);
*/
} else {
TownyMessaging.sendErrorMsg(getSender(), TownySettings.getLangString("msg_err_invalid_sub"));
return false;
}
}
return true;
}
private void giveBonus(String[] split) throws TownyException {
Town town;
try {
if (split.length != 2)
throw new TownyException(String.format(TownySettings.getLangString("msg_err_invalid_input"), "Eg: givebonus [town/player] [n]"));
try {
town = TownyUniverse.getDataSource().getTown(split[0]);
} catch (NotRegisteredException e) {
town = TownyUniverse.getDataSource().getResident(split[0]).getTown();
}
try {
town.setBonusBlocks(town.getBonusBlocks() + Integer.parseInt(split[1].trim()));
TownyMessaging.sendMsg(getSender(), String.format(TownySettings.getLangString("msg_give_total"), town.getName(), split[1], town.getBonusBlocks()));
} catch (NumberFormatException nfe) {
throw new TownyException(TownySettings.getLangString("msg_error_must_be_int"));
}
TownyUniverse.getDataSource().saveTown(town);
} catch (TownyException e) {
throw new TownyException(e.getMessage());
}
}
private void buildTAPanel() {
ta_panel.clear();
Runtime run = Runtime.getRuntime();
ta_panel.add(ChatTools.formatTitle(TownySettings.getLangString("ta_panel_1")));
ta_panel.add(Colors.Blue + "[" + Colors.LightBlue + "Towny" + Colors.Blue + "] " + Colors.Green + TownySettings.getLangString("ta_panel_2") + Colors.LightGreen + TownyUniverse.isWarTime() + Colors.Gray + " | " + Colors.Green + TownySettings.getLangString("ta_panel_3") + (TownyTimerHandler.isHealthRegenRunning() ? Colors.LightGreen + "On" : Colors.Rose + "Off") + Colors.Gray + " | " + (Colors.Green + TownySettings.getLangString("ta_panel_5") + (TownyTimerHandler.isDailyTimerRunning() ? Colors.LightGreen + "On" : Colors.Rose + "Off")));
/*
* ta_panel.add(Colors.Blue + "[" + Colors.LightBlue + "Towny" +
* Colors.Blue + "] " + Colors.Green +
* TownySettings.getLangString("ta_panel_4") +
* (TownySettings.isRemovingWorldMobs() ? Colors.LightGreen + "On" :
* Colors.Rose + "Off") + Colors.Gray + " | " + Colors.Green +
* TownySettings.getLangString("ta_panel_4_1") +
* (TownySettings.isRemovingTownMobs() ? Colors.LightGreen + "On" :
* Colors.Rose + "Off"));
*
* try { TownyEconomyObject.checkEconomy(); ta_panel.add(Colors.Blue +
* "[" + Colors.LightBlue + "Economy" + Colors.Blue + "] " +
* Colors.Green + TownySettings.getLangString("ta_panel_6") +
* Colors.LightGreen + TownyFormatter.formatMoney(getTotalEconomy()) +
* Colors.Gray + " | " + Colors.Green +
* TownySettings.getLangString("ta_panel_7") + Colors.LightGreen +
* getNumBankAccounts()); } catch (Exception e) { }
*/
ta_panel.add(Colors.Blue + "[" + Colors.LightBlue + TownySettings.getLangString("ta_panel_8") + Colors.Blue + "] " + Colors.Green + TownySettings.getLangString("ta_panel_9") + Colors.LightGreen + MemMgmt.getMemSize(run.totalMemory()) + Colors.Gray + " | " + Colors.Green + TownySettings.getLangString("ta_panel_10") + Colors.LightGreen + Thread.getAllStackTraces().keySet().size() + Colors.Gray + " | " + Colors.Green + TownySettings.getLangString("ta_panel_11") + Colors.LightGreen + TownyFormatter.getTime());
ta_panel.add(Colors.Yellow + MemMgmt.getMemoryBar(50, run));
}
public void parseAdminUnclaimCommand(String[] split) {
if (split.length == 1 && split[0].equalsIgnoreCase("?")) {
for (String line : ta_unclaim)
((CommandSender) getSender()).sendMessage(line);
} else {
if (isConsole) {
sender.sendMessage("[Towny] InputError: This command was designed for use in game only.");
return;
}
try {
if (TownyUniverse.isWarTime())
throw new TownyException(TownySettings.getLangString("msg_war_cannot_do"));
List<WorldCoord> selection;
selection = AreaSelectionUtil.selectWorldCoordArea(null, new WorldCoord(player.getWorld().getName(), Coord.parseCoord(player)), split);
new TownClaim(plugin, player, null, selection, false, false, true).start();
} catch (TownyException x) {
TownyMessaging.sendErrorMsg(player, x.getMessage());
return;
}
}
}
public void parseAdminTownCommand(String[] split) throws TownyException {
// TODO Make this use the actual town command procedually.
if (split.length == 0 || split[0].equalsIgnoreCase("?")) {
sender.sendMessage(ChatTools.formatTitle("/townyadmin town"));
sender.sendMessage(ChatTools.formatCommand(TownySettings.getLangString("admin_sing"), "/townyadmin town", "[town]", ""));
sender.sendMessage(ChatTools.formatCommand(TownySettings.getLangString("admin_sing"), "/townyadmin town", "[town] add/kick [] .. []", ""));
sender.sendMessage(ChatTools.formatCommand(TownySettings.getLangString("admin_sing"), "/townyadmin town", "[town] rename [newname]", ""));
sender.sendMessage(ChatTools.formatCommand(TownySettings.getLangString("admin_sing"), "/townyadmin town", "[town] delete", ""));
return;
}
try {
Town town = TownyUniverse.getDataSource().getTown(split[0]);
if (split.length == 1) {
TownyMessaging.sendMessage(getSender(), TownyFormatter.getStatus(town));
return;
}
if (!TownyUniverse.getPermissionSource().testPermission(player, PermissionNodes.TOWNY_COMMAND_TOWNYADMIN_TOWN.getNode(split[1].toLowerCase())))
throw new TownyException(TownySettings.getLangString("msg_err_command_disable"));
if (split[1].equalsIgnoreCase("add")) {
/*
* if (isConsole) { sender.sendMessage(
* "[Towny] InputError: This command was designed for use in game only."
* ); return; }
*/
TownCommand.townAdd(getSender(), town, StringMgmt.remArgs(split, 2));
} else if (split[1].equalsIgnoreCase("kick")) {
TownCommand.townKickResidents(getSender(), town.getMayor(), town, TownyUniverse.getValidatedResidents(getSender(), StringMgmt.remArgs(split, 2)));
} else if (split[1].equalsIgnoreCase("delete")) {
TownyUniverse.getDataSource().removeTown(town);
} else if (split[1].equalsIgnoreCase("rename")) {
if (!NameValidation.isBlacklistName(split[2])) {
TownyUniverse.getDataSource().renameTown(town, split[2]);
TownyMessaging.sendTownMessage(town, String.format(TownySettings.getLangString("msg_town_set_name"), ((getSender() instanceof Player) ? player.getName() : "CONSOLE"), town.getName()));
} else
TownyMessaging.sendErrorMsg(getSender(), TownySettings.getLangString("msg_invalid_name"));
}
} catch (NotRegisteredException e) {
TownyMessaging.sendErrorMsg(getSender(), e.getMessage());
} catch (TownyException e) {
TownyMessaging.sendErrorMsg(getSender(), e.getMessage());
}
}
public void parseAdminNationCommand(String[] split) throws TownyException {
if (split.length == 0 || split[0].equalsIgnoreCase("?")) {
sender.sendMessage(ChatTools.formatTitle("/townyadmin nation"));
sender.sendMessage(ChatTools.formatCommand(TownySettings.getLangString("admin_sing"), "/townyadmin nation", "[nation]", ""));
sender.sendMessage(ChatTools.formatCommand(TownySettings.getLangString("admin_sing"), "/townyadmin nation", "[nation] add [] .. []", ""));
sender.sendMessage(ChatTools.formatCommand(TownySettings.getLangString("admin_sing"), "/townyadmin nation", "[nation] rename [newname]", ""));
sender.sendMessage(ChatTools.formatCommand(TownySettings.getLangString("admin_sing"), "/townyadmin nation", "[nation] delete", ""));
return;
}
try {
Nation nation = TownyUniverse.getDataSource().getNation(split[0]);
if (split.length == 1) {
TownyMessaging.sendMessage(getSender(), TownyFormatter.getStatus(nation));
return;
}
if (!TownyUniverse.getPermissionSource().testPermission(player, PermissionNodes.TOWNY_COMMAND_TOWNYADMIN_NATION.getNode(split[1].toLowerCase())))
throw new TownyException(TownySettings.getLangString("msg_err_command_disable"));
if (split[1].equalsIgnoreCase("add")) {
/*
* if (isConsole) { sender.sendMessage(
* "[Towny] InputError: This command was designed for use in game only."
* ); return; }
*/
NationCommand.nationAdd(nation, TownyUniverse.getDataSource().getTowns(StringMgmt.remArgs(split, 2)));
} else if (split[1].equalsIgnoreCase("delete")) {
TownyUniverse.getDataSource().removeNation(nation);
} else if (split[1].equalsIgnoreCase("rename")) {
if (!NameValidation.isBlacklistName(split[2])) {
TownyUniverse.getDataSource().renameNation(nation, split[2]);
TownyMessaging.sendNationMessage(nation, String.format(TownySettings.getLangString("msg_nation_set_name"), ((getSender() instanceof Player) ? player.getName() : "CONSOLE"), nation.getName()));
} else
TownyMessaging.sendErrorMsg(getSender(), TownySettings.getLangString("msg_invalid_name"));
}
} catch (NotRegisteredException e) {
TownyMessaging.sendErrorMsg(getSender(), e.getMessage());
} catch (AlreadyRegisteredException e) {
TownyMessaging.sendErrorMsg(getSender(), e.getMessage());
}
}
public void adminSet(String[] split) throws TownyException {
if (split.length == 0) {
sender.sendMessage(ChatTools.formatTitle("/townyadmin set"));
// TODO: player.sendMessage(ChatTools.formatCommand("",
// "/townyadmin set", "king [nation] [king]", ""));
sender.sendMessage(ChatTools.formatCommand("", "/townyadmin set", "mayor [town] " + TownySettings.getLangString("town_help_2"), ""));
sender.sendMessage(ChatTools.formatCommand("", "/townyadmin set", "mayor [town] npc", ""));
// player.sendMessage(ChatTools.formatCommand("", "/townyadmin set",
// "debugmode [on/off]", ""));
// player.sendMessage(ChatTools.formatCommand("", "/townyadmin set",
// "devmode [on/off]", ""));
return;
}
if (!TownyUniverse.getPermissionSource().testPermission(player, PermissionNodes.TOWNY_COMMAND_TOWNYADMIN_SET.getNode(split[0].toLowerCase())))
throw new TownyException(TownySettings.getLangString("msg_err_command_disable"));
if (split[0].equalsIgnoreCase("mayor")) {
if (split.length < 3) {
sender.sendMessage(ChatTools.formatTitle("/townyadmin set mayor"));
sender.sendMessage(ChatTools.formatCommand("Eg", "/townyadmin set mayor", "[town] " + TownySettings.getLangString("town_help_2"), ""));
sender.sendMessage(ChatTools.formatCommand("Eg", "/townyadmin set mayor", "[town] npc", ""));
} else
try {
Resident newMayor = null;
Town town = TownyUniverse.getDataSource().getTown(split[1]);
if (split[2].equalsIgnoreCase("npc")) {
String name = nextNpcName();
TownyUniverse.getDataSource().newResident(name);
newMayor = TownyUniverse.getDataSource().getResident(name);
newMayor.setRegistered(System.currentTimeMillis());
newMayor.setLastOnline(0);
newMayor.setNPC(true);
TownyUniverse.getDataSource().saveResident(newMayor);
TownyUniverse.getDataSource().saveResidentList();
// set for no upkeep as an NPC mayor is assigned
town.setHasUpkeep(false);
} else {
newMayor = TownyUniverse.getDataSource().getResident(split[2]);
// set upkeep again
town.setHasUpkeep(true);
}
if (!town.hasResident(newMayor))
TownCommand.townAddResident(town, newMayor);
// Delete the resident if the old mayor was an NPC.
Resident oldMayor = town.getMayor();
town.setMayor(newMayor);
if (oldMayor.isNPC()) {
try {
town.removeResident(oldMayor);
TownyUniverse.getDataSource().removeResident(oldMayor);
TownyUniverse.getDataSource().removeResidentList(oldMayor);
} catch (EmptyTownException e) {
// Should never reach here as we are setting a new
// mayor before removing the old one.
e.printStackTrace();
}
}
TownyUniverse.getDataSource().saveTown(town);
String[] msg = TownySettings.getNewMayorMsg(newMayor.getName());
TownyMessaging.sendTownMessage(town, msg);
// TownyMessaging.sendMessage(player, msg);
} catch (TownyException e) {
TownyMessaging.sendErrorMsg(getSender(), e.getMessage());
}
} else {
TownyMessaging.sendErrorMsg(getSender(), String.format(TownySettings.getLangString("msg_err_invalid_property"), "administrative"));
return;
}
}
public String nextNpcName() throws TownyException {
String name;
int i = 0;
do {
name = TownySettings.getNPCPrefix() + ++i;
if (!TownyUniverse.getDataSource().hasResident(name))
return name;
if (i > 100000)
throw new TownyException(TownySettings.getLangString("msg_err_too_many_npc"));
} while (true);
}
public void reloadTowny(Boolean reset) {
if (reset) {
TownyUniverse.getDataSource().deleteFile(plugin.getConfigPath());
}
TownyLogger.shutDown();
plugin.load();
TownyMessaging.sendMsg(sender, TownySettings.getLangString("msg_reloaded"));
// TownyMessaging.sendMsg(TownySettings.getLangString("msg_reloaded"));
}
/**
* Remove residents who havn't logged in for X amount of days.
*
* @param split
*/
public void purge(String[] split) {
if (split.length == 0) {
// command was '/townyadmin purge'
player.sendMessage(ChatTools.formatTitle("/townyadmin purge"));
player.sendMessage(ChatTools.formatCommand("", "/townyadmin purge", "[number of days]", ""));
player.sendMessage(ChatTools.formatCommand("", "", "Removes offline residents not seen for this duration.", ""));
return;
}
int days = 1;
try {
days = Integer.parseInt(split[0]);
} catch (NumberFormatException e) {
TownyMessaging.sendErrorMsg(getSender(), TownySettings.getLangString("msg_error_must_be_int"));
return;
}
// Run a purge in it's own thread
new ResidentPurge(plugin, this.sender, TimeTools.getMillis(days + "d")).start();
}
/**
* Delete a resident and it's data file (if not online) Available Only to
* players with the 'towny.admin' permission node.
*
* @param player
* @param split
*/
public void residentDelete(Player player, String[] split) {
if (split.length == 0)
TownyMessaging.sendErrorMsg(player, TownySettings.getLangString("msg_invalid_name"));
else
try {
if (!TownyUniverse.getPermissionSource().isTownyAdmin(player))
throw new TownyException(TownySettings.getLangString("msg_err_admin_only_delete"));
for (String name : split) {
try {
Resident resident = TownyUniverse.getDataSource().getResident(name);
if (!resident.isNPC() && !BukkitTools.isOnline(resident.getName())) {
TownyUniverse.getDataSource().removeResident(resident);
TownyUniverse.getDataSource().removeResidentList(resident);
TownyMessaging.sendGlobalMessage(TownySettings.getDelResidentMsg(resident));
} else
TownyMessaging.sendErrorMsg(player, String.format(TownySettings.getLangString("msg_err_online_or_npc"), name));
} catch (NotRegisteredException x) {
// This name isn't registered as a resident
TownyMessaging.sendErrorMsg(player, String.format(TownySettings.getLangString("msg_err_invalid_name"), name));
}
}
} catch (TownyException x) {
// Admin only escape
TownyMessaging.sendErrorMsg(player, x.getMessage());
return;
}
}
public void parseToggleCommand(String[] split) throws TownyException {
boolean choice;
if (split.length == 0) {
// command was '/townyadmin toggle'
player.sendMessage(ChatTools.formatTitle("/townyadmin toggle"));
player.sendMessage(ChatTools.formatCommand("", "/townyadmin toggle", "war", ""));
player.sendMessage(ChatTools.formatCommand("", "/townyadmin toggle", "neutral", ""));
player.sendMessage(ChatTools.formatCommand("", "/townyadmin toggle", "devmode", ""));
player.sendMessage(ChatTools.formatCommand("", "/townyadmin toggle", "debug", ""));
player.sendMessage(ChatTools.formatCommand("", "/townyadmin toggle", "townwithdraw/nationwithdraw", ""));
return;
}
if (!TownyUniverse.getPermissionSource().testPermission(player, PermissionNodes.TOWNY_COMMAND_TOWNYADMIN_TOGGLE.getNode(split[0].toLowerCase())))
throw new TownyException(TownySettings.getLangString("msg_err_command_disable"));
if (split[0].equalsIgnoreCase("war")) {
choice = TownyUniverse.isWarTime();
if (!choice) {
plugin.getTownyUniverse().startWarEvent();
TownyMessaging.sendMsg(getSender(), TownySettings.getLangString("msg_war_started"));
} else {
plugin.getTownyUniverse().endWarEvent();
TownyMessaging.sendMsg(getSender(), TownySettings.getLangString("msg_war_ended"));
}
} else if (split[0].equalsIgnoreCase("neutral")) {
try {
choice = !TownySettings.isDeclaringNeutral();
TownySettings.setDeclaringNeutral(choice);
TownyMessaging.sendMsg(getSender(), String.format(TownySettings.getLangString("msg_nation_allow_neutral"), choice ? "Enabled" : "Disabled"));
} catch (Exception e) {
TownyMessaging.sendErrorMsg(getSender(), TownySettings.getLangString("msg_err_invalid_choice"));
return;
}
} else if (split[0].equalsIgnoreCase("devmode")) {
try {
choice = !TownySettings.isDevMode();
TownySettings.setDevMode(choice);
TownyMessaging.sendMsg(getSender(), "Dev Mode " + (choice ? Colors.Green + "Enabled" : Colors.Red + "Disabled"));
} catch (Exception e) {
TownyMessaging.sendErrorMsg(getSender(), TownySettings.getLangString("msg_err_invalid_choice"));
}
} else if (split[0].equalsIgnoreCase("debug")) {
try {
choice = !TownySettings.getDebug();
TownySettings.setDebug(choice);
TownyMessaging.sendMsg(getSender(), "Debug Mode " + (choice ? Colors.Green + "Enabled" : Colors.Red + "Disabled"));
} catch (Exception e) {
TownyMessaging.sendErrorMsg(getSender(), TownySettings.getLangString("msg_err_invalid_choice"));
}
} else if (split[0].equalsIgnoreCase("townwithdraw")) {
try {
choice = !TownySettings.getTownBankAllowWithdrawls();
TownySettings.SetTownBankAllowWithdrawls(choice);
TownyMessaging.sendMsg(getSender(), "Town Withdrawls " + (choice ? Colors.Green + "Enabled" : Colors.Red + "Disabled"));
} catch (Exception e) {
TownyMessaging.sendErrorMsg(getSender(), TownySettings.getLangString("msg_err_invalid_choice"));
}
} else if (split[0].equalsIgnoreCase("nationwithdraw")) {
try {
choice = !TownySettings.geNationBankAllowWithdrawls();
TownySettings.SetNationBankAllowWithdrawls(choice);
TownyMessaging.sendMsg(getSender(), "Nation Withdrawls " + (choice ? Colors.Green + "Enabled" : Colors.Red + "Disabled"));
} catch (Exception e) {
TownyMessaging.sendErrorMsg(getSender(), TownySettings.getLangString("msg_err_invalid_choice"));
}
} else {
// parameter error message
// neutral/war/townmobs/worldmobs
TownyMessaging.sendErrorMsg(getSender(), TownySettings.getLangString("msg_err_invalid_choice"));
}
}
/*
* private void warSeed(Player player) { Resident r1 =
* plugin.getTownyUniverse().newResident("r1"); Resident r2 =
* plugin.getTownyUniverse().newResident("r2"); Resident r3 =
* plugin.getTownyUniverse().newResident("r3"); Coord key =
* Coord.parseCoord(player); Town t1 = newTown(plugin.getTownyUniverse(),
* player.getWorld(), "t1", r1, key, player.getLocation()); Town t2 =
* newTown(plugin.getTownyUniverse(), player.getWorld(), "t2", r2, new
* Coord(key.getX() + 1, key.getZ()), player.getLocation()); Town t3 =
* newTown(plugin.getTownyUniverse(), player.getWorld(), "t3", r3, new
* Coord(key.getX(), key.getZ() + 1), player.getLocation()); Nation n1 =
*
* }
*
* public void seedTowny() { TownyUniverse townyUniverse =
* plugin.getTownyUniverse(); Random r = new Random(); for (int i = 0; i <
* 1000; i++) {
*
* try { townyUniverse.newNation(Integer.toString(r.nextInt())); } catch
* (TownyException e) { } try {
* townyUniverse.newTown(Integer.toString(r.nextInt())); } catch
* (TownyException e) { } try {
* townyUniverse.newResident(Integer.toString(r.nextInt())); } catch
* (TownyException e) { } } }
*
* private static double getTotalEconomy() { double total = 0; try { return
* total; } catch (Exception e) { } return total; }
*
* private static int getNumBankAccounts() { try { return 0; } catch
* (Exception e) { return 0; } }
*/
}
| true | true | public boolean parseTownyAdminCommand(String[] split) throws TownyException {
if (split.length == 0) {
buildTAPanel();
for (String line : ta_panel) {
sender.sendMessage(line);
}
} else if (split[0].equalsIgnoreCase("?") || split[0].equalsIgnoreCase("help")) {
for (String line : ta_help) {
sender.sendMessage(line);
}
} else {
if (split[0].equalsIgnoreCase("set")) {
adminSet(StringMgmt.remFirstArg(split));
return true;
} else if (split[0].equalsIgnoreCase("town")) {
parseAdminTownCommand(StringMgmt.remFirstArg(split));
return true;
} else if (split[0].equalsIgnoreCase("nation")) {
parseAdminNationCommand(StringMgmt.remFirstArg(split));
return true;
} else if (split[0].equalsIgnoreCase("toggle")) {
parseToggleCommand(StringMgmt.remFirstArg(split));
return true;
}
if (!TownyUniverse.getPermissionSource().testPermission(player, PermissionNodes.TOWNY_COMMAND_TOWNYADMIN.getNode(split[0].toLowerCase())))
throw new TownyException(TownySettings.getLangString("msg_err_command_disable"));
if (split[0].equalsIgnoreCase("givebonus")) {
giveBonus(StringMgmt.remFirstArg(split));
} else if (split[0].equalsIgnoreCase("reload")) {
reloadTowny(false);
} else if (split[0].equalsIgnoreCase("reset")) {
reloadTowny(true);
} else if (split[0].equalsIgnoreCase("backup")) {
try {
TownyUniverse.getDataSource().backup();
TownyMessaging.sendMsg(getSender(), TownySettings.getLangString("mag_backup_success"));
} catch (IOException e) {
TownyMessaging.sendErrorMsg(getSender(), "Error: " + e.getMessage());
}
} else if (split[0].equalsIgnoreCase("newday")) {
TownyTimerHandler.newDay();
} else if (split[0].equalsIgnoreCase("purge")) {
purge(StringMgmt.remFirstArg(split));
} else if (split[0].equalsIgnoreCase("delete")) {
String[] newSplit = StringMgmt.remFirstArg(split);
residentDelete(player, newSplit);
} else if (split[0].equalsIgnoreCase("unclaim")) {
parseAdminUnclaimCommand(StringMgmt.remFirstArg(split));
/*
* else if (split[0].equalsIgnoreCase("seed") &&
* TownySettings.getDebug()) seedTowny(); else if
* (split[0].equalsIgnoreCase("warseed") &&
* TownySettings.getDebug()) warSeed(player);
*/
} else {
TownyMessaging.sendErrorMsg(getSender(), TownySettings.getLangString("msg_err_invalid_sub"));
return false;
}
}
return true;
}
| public boolean parseTownyAdminCommand(String[] split) throws TownyException {
if (split.length == 0) {
buildTAPanel();
for (String line : ta_panel) {
sender.sendMessage(line);
}
} else if (split[0].equalsIgnoreCase("?") || split[0].equalsIgnoreCase("help")) {
for (String line : ta_help) {
sender.sendMessage(line);
}
} else {
if (split[0].equalsIgnoreCase("set")) {
adminSet(StringMgmt.remFirstArg(split));
return true;
} else if (split[0].equalsIgnoreCase("town")) {
parseAdminTownCommand(StringMgmt.remFirstArg(split));
return true;
} else if (split[0].equalsIgnoreCase("nation")) {
parseAdminNationCommand(StringMgmt.remFirstArg(split));
return true;
} else if (split[0].equalsIgnoreCase("toggle")) {
parseToggleCommand(StringMgmt.remFirstArg(split));
return true;
}
if ((!isConsole) && (!TownyUniverse.getPermissionSource().testPermission(player, PermissionNodes.TOWNY_COMMAND_TOWNYADMIN.getNode(split[0].toLowerCase()))))
throw new TownyException(TownySettings.getLangString("msg_err_command_disable"));
if (split[0].equalsIgnoreCase("givebonus")) {
giveBonus(StringMgmt.remFirstArg(split));
} else if (split[0].equalsIgnoreCase("reload")) {
reloadTowny(false);
} else if (split[0].equalsIgnoreCase("reset")) {
reloadTowny(true);
} else if (split[0].equalsIgnoreCase("backup")) {
try {
TownyUniverse.getDataSource().backup();
TownyMessaging.sendMsg(getSender(), TownySettings.getLangString("mag_backup_success"));
} catch (IOException e) {
TownyMessaging.sendErrorMsg(getSender(), "Error: " + e.getMessage());
}
} else if (split[0].equalsIgnoreCase("newday")) {
TownyTimerHandler.newDay();
} else if (split[0].equalsIgnoreCase("purge")) {
purge(StringMgmt.remFirstArg(split));
} else if (split[0].equalsIgnoreCase("delete")) {
String[] newSplit = StringMgmt.remFirstArg(split);
residentDelete(player, newSplit);
} else if (split[0].equalsIgnoreCase("unclaim")) {
parseAdminUnclaimCommand(StringMgmt.remFirstArg(split));
/*
* else if (split[0].equalsIgnoreCase("seed") &&
* TownySettings.getDebug()) seedTowny(); else if
* (split[0].equalsIgnoreCase("warseed") &&
* TownySettings.getDebug()) warSeed(player);
*/
} else {
TownyMessaging.sendErrorMsg(getSender(), TownySettings.getLangString("msg_err_invalid_sub"));
return false;
}
}
return true;
}
|
diff --git a/src/java/net/spy/memcached/MemcachedClient.java b/src/java/net/spy/memcached/MemcachedClient.java
index 23e84e5..be025b4 100644
--- a/src/java/net/spy/memcached/MemcachedClient.java
+++ b/src/java/net/spy/memcached/MemcachedClient.java
@@ -1,913 +1,918 @@
// Copyright (c) 2006 Dustin Sallings <[email protected]>
package net.spy.memcached;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.atomic.AtomicReference;
import net.spy.SpyThread;
import net.spy.memcached.ops.DeleteOperation;
import net.spy.memcached.ops.GetOperation;
import net.spy.memcached.ops.Mutator;
import net.spy.memcached.ops.Operation;
import net.spy.memcached.ops.OperationCallback;
import net.spy.memcached.ops.OperationState;
import net.spy.memcached.ops.OperationStatus;
import net.spy.memcached.ops.StatsOperation;
import net.spy.memcached.ops.StoreType;
/**
* Client to a memcached server.
*
* <h2>Basic usage</h2>
*
* <pre>
* MemcachedClient c=new MemcachedClient(
* new InetSocketAddress("hostname", portNum));
*
* // Store a value (async) for one hour
* c.set("someKey", 3600, someObject);
* // Retrieve a value.
* Object myObject=c.get("someKey");
* </pre>
*
* <h2>Advanced Usage</h2>
*
* <p>
* MemcachedClient may be processing a great deal of asynchronous messages or
* possibly dealing with an unreachable memcached, which may delay processing.
* If a memcached is disabled, for example, MemcachedConnection will continue
* to attempt to reconnect and replay pending operations until it comes back
* up. To prevent this from causing your application to hang, you can use
* one of the asynchronous mechanisms to time out a request and cancel the
* operation to the server.
* </p>
*
* <pre>
* // Get a memcached client connected to several servers
* MemcachedClient c=new MemcachedClient(
* AddrUtil.getAddresses("server1:11211 server2:11211"));
*
* // Try to get a value, for up to 5 seconds, and cancel if it doesn't return
* Object myObj=null;
* Future<Object> f=c.asyncGet("someKey");
* try {
* myObj=f.get(5, TimeUnit.SECONDS);
* } catch(TimeoutException e) {
* // Since we don't need this, go ahead and cancel the operation. This
* // is not strictly necessary, but it'll save some work on the server.
* f.cancel();
* // Do other timeout related stuff
* }
* </pre>
*/
public final class MemcachedClient extends SpyThread {
private static final int MAX_KEY_LENGTH = 250;
private volatile boolean running=true;
private volatile boolean shuttingDown=false;
private final MemcachedConnection conn;
final OperationFactory opFact;
private HashAlgorithm hashAlg=HashAlgorithm.NATIVE_HASH;
Transcoder transcoder=null;
/**
* Get a memcache client operating on the specified memcached locations.
*
* @param ia the memcached locations
* @throws IOException if connections cannot be established
*/
public MemcachedClient(InetSocketAddress... ia) throws IOException {
this(new DefaultConnectionFactory(), Arrays.asList(ia));
}
/**
* Get a memcache client over the specified memcached locations.
*
* @param addrs the socket addrs
* @throws IOException if connections cannot be established
*/
public MemcachedClient(List<InetSocketAddress> addrs)
throws IOException {
this(new DefaultConnectionFactory(), addrs);
}
/**
* Get a memcache client over the specified memcached locations.
*
* @param bufSize read buffer size per connection (in bytes)
* @param addrs the socket addresses
* @throws IOException if connections cannot be established
*/
public MemcachedClient(ConnectionFactory cf, List<InetSocketAddress> addrs)
throws IOException {
transcoder=new SerializingTranscoder();
conn=cf.createConnection(addrs);
opFact=cf.getOperationFactory();
setName("Memcached IO over " + conn);
start();
}
/**
* Set the hash algorithm.
*/
public HashAlgorithm getHashAlgorithm() {
return hashAlg;
}
/**
* Set the hash algorithm for computing which server should receive
* requests for a given key.
*/
public void setHashAlgorithm(HashAlgorithm to) {
if(to == null) {
throw new NullPointerException("Null hash algorithm not allowed");
}
hashAlg=to;
}
/**
* Set the transcoder for managing the cache representations of objects
* going in and out of the cache.
*/
public void setTranscoder(Transcoder to) {
if(to == null) {
throw new NullPointerException("Can't use a null transcoder");
}
transcoder=to;
}
/**
* Get the current transcoder that's in use.
*/
public Transcoder getTranscoder() {
return transcoder;
}
private void validateKey(String key) {
if(key.length() > MAX_KEY_LENGTH) {
throw new IllegalArgumentException("Key is too long (maxlen = "
+ MAX_KEY_LENGTH + ")");
}
// Validate the key
for(char c : key.toCharArray()) {
if(Character.isWhitespace(c) || Character.isISOControl(c)) {
throw new IllegalArgumentException(
"Key contains invalid characters: ``" + key + "''");
}
}
}
/**
* (internal use) Add a raw operation to a numbered connection.
* This method is exposed for testing.
*
* @param which server number
* @param op the operation to perform
* @return the Operation
*/
Operation addOp(final String key, final Operation op) {
if(shuttingDown) {
throw new IllegalStateException("Shutting down");
}
validateKey(key);
assert isAlive() : "IO Thread is not running.";
conn.addOperation(key, op);
return op;
}
Operation addOp(final MemcachedNode node, final Operation op) {
if(shuttingDown) {
throw new IllegalStateException("Shutting down");
}
assert isAlive() : "IO Thread is not running.";
conn.addOperation(node, op);
return op;
}
CountDownLatch broadcastOp(final BroadcastOpFactory of) {
return broadcastOp(of, true);
}
private CountDownLatch broadcastOp(BroadcastOpFactory of,
boolean checkShuttingDown) {
if(checkShuttingDown && shuttingDown) {
throw new IllegalStateException("Shutting down");
}
return conn.broadcastOperation(of);
}
private Future<Boolean> asyncStore(StoreType storeType,
String key, int exp, Object value) {
CachedData co=transcoder.encode(value);
final CountDownLatch latch=new CountDownLatch(1);
final OperationFuture<Boolean> rv=new OperationFuture<Boolean>(latch);
Operation op=opFact.store(storeType, key, co.getFlags(),
exp, co.getData(), new OperationCallback() {
public void receivedStatus(OperationStatus val) {
rv.set(val.isSuccess());
}
public void complete() {
latch.countDown();
}});
rv.setOperation(op);
addOp(key, op);
return rv;
}
/**
* Add an object to the cache iff it does not exist already.
*
* <p>
* The <code>exp</code> value is passed along to memcached exactly as
* given, and will be processed per the memcached protocol specification:
* </p>
*
* <blockquote>
* <p>
* The actual value sent may either be
* Unix time (number of seconds since January 1, 1970, as a 32-bit
* value), or a number of seconds starting from current time. In the
* latter case, this number of seconds may not exceed 60*60*24*30 (number
* of seconds in 30 days); if the number sent by a client is larger than
* that, the server will consider it to be real Unix time value rather
* than an offset from current time.
* </p>
* </blockquote>
*
* @param key the key under which this object should be added.
* @param exp the expiration of this object
* @param o the object to store
* @return a future representing the processing of this operation
*/
public Future<Boolean> add(String key, int exp, Object o) {
return asyncStore(StoreType.add, key, exp, o);
}
/**
* Set an object in the cache regardless of any existing value.
*
* <p>
* The <code>exp</code> value is passed along to memcached exactly as
* given, and will be processed per the memcached protocol specification:
* </p>
*
* <blockquote>
* <p>
* The actual value sent may either be
* Unix time (number of seconds since January 1, 1970, as a 32-bit
* value), or a number of seconds starting from current time. In the
* latter case, this number of seconds may not exceed 60*60*24*30 (number
* of seconds in 30 days); if the number sent by a client is larger than
* that, the server will consider it to be real Unix time value rather
* than an offset from current time.
* </p>
* </blockquote>
*
* @param key the key under which this object should be added.
* @param exp the expiration of this object
* @param o the object to store
* @return a future representing the processing of this operation
*/
public Future<Boolean> set(String key, int exp, Object o) {
return asyncStore(StoreType.set, key, exp, o);
}
/**
* Replace an object with the given value iff there is already a value
* for the given key.
*
* <p>
* The <code>exp</code> value is passed along to memcached exactly as
* given, and will be processed per the memcached protocol specification:
* </p>
*
* <blockquote>
* <p>
* The actual value sent may either be
* Unix time (number of seconds since January 1, 1970, as a 32-bit
* value), or a number of seconds starting from current time. In the
* latter case, this number of seconds may not exceed 60*60*24*30 (number
* of seconds in 30 days); if the number sent by a client is larger than
* that, the server will consider it to be real Unix time value rather
* than an offset from current time.
* </p>
* </blockquote>
*
* @param key the key under which this object should be added.
* @param exp the expiration of this object
* @param o the object to store
* @return a future representing the processing of this operation
*/
public Future<Boolean> replace(String key, int exp, Object o) {
return asyncStore(StoreType.replace, key, exp, o);
}
/**
* Get the given key asynchronously.
*
* @param key the key to fetch
* @return a future that will hold the return value of the fetch
*/
public Future<Object> asyncGet(final String key) {
final CountDownLatch latch=new CountDownLatch(1);
final OperationFuture<Object> rv=new OperationFuture<Object>(latch);
Operation op=opFact.get(key,
new GetOperation.Callback() {
private Object val=null;
public void receivedStatus(OperationStatus status) {
rv.set(val);
}
public void gotData(String k, int flags, byte[] data) {
assert key.equals(k) : "Wrong key returned";
val=transcoder.decode(new CachedData(flags, data));
}
public void complete() {
latch.countDown();
}});
rv.setOperation(op);
addOp(key, op);
return rv;
}
/**
* Get with a single key.
*
* @param key the key to get
* @return the result from the cache (null if there is none)
*/
public Object get(String key) {
try {
return asyncGet(key).get();
} catch (InterruptedException e) {
throw new RuntimeException("Interrupted waiting for value", e);
} catch (ExecutionException e) {
throw new RuntimeException("Exception waiting for value", e);
}
}
/**
* Asynchronously get a bunch of objects from the cache.
*
* @param keys the keys to request
* @return a Future result of that fetch
*/
public Future<Map<String, Object>> asyncGetBulk(Collection<String> keys) {
final Map<String, Object> m=new ConcurrentHashMap<String, Object>();
// Break the gets down into groups by key
final Map<MemcachedNode, Collection<String>> chunks
=new HashMap<MemcachedNode, Collection<String>>();
final NodeLocator locator=conn.getLocator();
for(String key : keys) {
validateKey(key);
final MemcachedNode primaryNode=locator.getPrimary(key);
MemcachedNode node=null;
if(primaryNode.isActive()) {
node=primaryNode;
} else {
for(Iterator<MemcachedNode> i=locator.getSequence(key);
node == null && i.hasNext();) {
MemcachedNode n=i.next();
if(n.isActive()) {
node=n;
}
}
if(node == null) {
node=primaryNode;
}
}
assert node != null : "Didn't find a node for " + key;
Collection<String> ks=chunks.get(node);
if(ks == null) {
ks=new ArrayList<String>();
chunks.put(node, ks);
}
ks.add(key);
}
final CountDownLatch latch=new CountDownLatch(chunks.size());
final Collection<Operation> ops=new ArrayList<Operation>();
GetOperation.Callback cb=new GetOperation.Callback() {
@SuppressWarnings("synthetic-access")
public void receivedStatus(OperationStatus status) {
if(!status.isSuccess()) {
getLogger().warn("Unsuccessful get: %s", status);
}
}
public void gotData(String k, int flags, byte[] data) {
- m.put(k, transcoder.decode(new CachedData(flags, data)));
+ Object val = transcoder.decode(new CachedData(flags, data));
+ // val may be null if the transcoder did not understand
+ // the value.
+ if(val != null) {
+ m.put(k, val);
+ }
}
public void complete() {
latch.countDown();
}
};
for(Map.Entry<MemcachedNode, Collection<String>> me
: chunks.entrySet()) {
ops.add(addOp(me.getKey(), opFact.get(me.getValue(), cb)));
}
return new BulkGetFuture(m, ops, latch);
}
/**
* Varargs wrapper for asynchronous bulk gets.
*
* @param keys one more more keys to get
* @return the future values of those keys
*/
public Future<Map<String, Object>> asyncGetBulk(String... keys) {
return asyncGetBulk(Arrays.asList(keys));
}
/**
* Get the values for multiple keys from the cache.
*
* @param keys the keys
* @return a map of the values (for each value that exists)
*/
public Map<String, Object> getBulk(Collection<String> keys) {
try {
return asyncGetBulk(keys).get();
} catch (InterruptedException e) {
throw new RuntimeException("Interrupted getting bulk values", e);
} catch (ExecutionException e) {
throw new RuntimeException("Failed getting bulk values", e);
}
}
/**
* Get the values for multiple keys from the cache.
*
* @param keys the keys
* @return a map of the values (for each value that exists)
*/
public Map<String, Object> getBulk(String... keys) {
return getBulk(Arrays.asList(keys));
}
/**
* Get the versions of all of the connected memcacheds.
*/
public Map<SocketAddress, String> getVersions() {
final Map<SocketAddress, String>rv=
new ConcurrentHashMap<SocketAddress, String>();
CountDownLatch blatch = broadcastOp(new BroadcastOpFactory(){
public Operation newOp(final MemcachedNode n,
final CountDownLatch latch) {
final SocketAddress sa=n.getSocketAddress();
return opFact.version(
new OperationCallback() {
public void receivedStatus(OperationStatus s) {
rv.put(sa, s.getMessage());
}
public void complete() {
latch.countDown();
}
});
}});
try {
blatch.await();
} catch (InterruptedException e) {
throw new RuntimeException("Interrupted waiting for versions", e);
}
return rv;
}
/**
* Get all of the stats from all of the connections.
*/
public Map<SocketAddress, Map<String, String>> getStats() {
return getStats(null);
}
private Map<SocketAddress, Map<String, String>> getStats(final String arg) {
final Map<SocketAddress, Map<String, String>> rv
=new HashMap<SocketAddress, Map<String, String>>();
CountDownLatch blatch = broadcastOp(new BroadcastOpFactory(){
public Operation newOp(final MemcachedNode n,
final CountDownLatch latch) {
final SocketAddress sa=n.getSocketAddress();
rv.put(sa, new HashMap<String, String>());
return opFact.stats(arg,
new StatsOperation.Callback() {
public void gotStat(String name, String val) {
rv.get(sa).put(name, val);
}
@SuppressWarnings("synthetic-access") // getLogger()
public void receivedStatus(OperationStatus status) {
if(!status.isSuccess()) {
getLogger().warn("Unsuccessful stat fetch: %s",
status);
}
}
public void complete() {
latch.countDown();
}});
}});
try {
blatch.await();
} catch (InterruptedException e) {
throw new RuntimeException("Interrupted waiting for stats", e);
}
return rv;
}
private long mutate(Mutator m, String key, int by, long def, int exp) {
final AtomicLong rv=new AtomicLong();
final CountDownLatch latch=new CountDownLatch(1);
addOp(key, opFact.mutate(m, key, by, def, exp, new OperationCallback() {
public void receivedStatus(OperationStatus s) {
// XXX: Potential abstraction leak.
// The handling of incr/decr in the binary protocol is
// yet undefined.
rv.set(new Long(s.isSuccess()?s.getMessage():"-1"));
}
public void complete() {
latch.countDown();
}}));
try {
latch.await();
} catch (InterruptedException e) {
throw new RuntimeException("Interrupted", e);
}
getLogger().debug("Mutation returned %s", rv);
return rv.get();
}
/**
* Increment the given key by the given amount.
*
* @param key the key
* @param by the amount to increment
* @return the new value (-1 if the key doesn't exist)
*/
public long incr(String key, int by) {
return mutate(Mutator.incr, key, by, 0, -1);
}
/**
* Decrement the given key by the given value.
*
* @param key the key
* @param by the value
* @return the new value (-1 if the key doesn't exist)
*/
public long decr(String key, int by) {
return mutate(Mutator.decr, key, by, 0, -1);
}
private long mutateWithDefault(Mutator t, String key,
int by, long def, int exp) {
long rv=mutate(t, key, by, def, exp);
// The ascii protocol doesn't support defaults, so I added them
// manually here.
if(rv == -1) {
Future<Boolean> f=asyncStore(StoreType.add,
key, 0, String.valueOf(def));
try {
if(f.get()) {
rv=def;
} else {
rv=mutate(t, key, by, 0, 0);
assert rv != -1 : "Failed to mutate or init value";
}
} catch (InterruptedException e) {
throw new RuntimeException("Interrupted waiting for store", e);
} catch (ExecutionException e) {
throw new RuntimeException("Failed waiting for store", e);
}
}
return rv;
}
/**
* Increment the given counter, returning the new value.
*
* @param key the key
* @param by the amount to increment
* @param def the default value (if the counter does not exist)
* @return the new value, or -1 if we were unable to increment or add
*/
public long incr(String key, int by, int def) {
return mutateWithDefault(Mutator.incr, key, by, def, 0);
}
/**
* Decrement the given counter, returning the new value.
*
* @param key the key
* @param by the amount to decrement
* @param def the default value (if the counter does not exist)
* @return the new value, or -1 if we were unable to decrement or add
*/
public long decr(String key, int by, long def) {
return mutateWithDefault(Mutator.decr, key, by, def, 0);
}
/**
* Delete the given key from the cache.
*
* @param key the key to delete
* @param when when the deletion should take effect
*/
public Future<Boolean> delete(String key, int when) {
final CountDownLatch latch=new CountDownLatch(1);
final OperationFuture<Boolean> rv=new OperationFuture<Boolean>(latch);
DeleteOperation op=opFact.delete(key, when,
new OperationCallback() {
public void receivedStatus(OperationStatus s) {
rv.set(s.isSuccess());
}
public void complete() {
latch.countDown();
}});
rv.setOperation(op);
addOp(key, op);
return rv;
}
/**
* Shortcut to delete that will immediately delete the item from the cache.
*/
public Future<Boolean> delete(String key) {
return delete(key, 0);
}
/**
* Flush all caches from all servers with a delay of application.
*/
public Future<Boolean> flush(final int delay) {
final AtomicReference<Boolean> flushResult=
new AtomicReference<Boolean>(null);
final ConcurrentLinkedQueue<Operation> ops=
new ConcurrentLinkedQueue<Operation>();
CountDownLatch blatch = broadcastOp(new BroadcastOpFactory(){
public Operation newOp(final MemcachedNode n,
final CountDownLatch latch) {
Operation op=opFact.flush(delay, new OperationCallback(){
public void receivedStatus(OperationStatus s) {
flushResult.set(s.isSuccess());
}
public void complete() {
latch.countDown();
}});
ops.add(op);
return op;
}});
return new OperationFuture<Boolean>(blatch, flushResult) {
@Override
public boolean cancel(boolean ign) {
boolean rv=false;
for(Operation op : ops) {
op.cancel();
rv |= op.getState() == OperationState.WRITING;
}
return rv;
}
@Override
public boolean isCancelled() {
boolean rv=false;
for(Operation op : ops) {
rv |= op.isCancelled();
}
return rv;
}
@Override
public boolean isDone() {
boolean rv=true;
for(Operation op : ops) {
rv &= op.getState() == OperationState.COMPLETE;
}
return rv || isCancelled();
}
};
}
/**
* Flush all caches from all servers immediately.
*/
public Future<Boolean> flush() {
return flush(-1);
}
/**
* Infinitely loop processing IO.
*/
@Override
public void run() {
while(running) {
try {
conn.handleIO();
} catch(IOException e) {
getLogger().warn("Problem handling memcached IO", e);
}
}
getLogger().info("Shut down memcached client");
}
/**
* Shut down immediately.
*/
public void shutdown() {
shutdown(-1, TimeUnit.MILLISECONDS);
}
/**
* Shut down this client gracefully.
*/
public boolean shutdown(long timeout, TimeUnit unit) {
shuttingDown=true;
String baseName=getName();
setName(baseName + " - SHUTTING DOWN");
boolean rv=false;
try {
// Conditionally wait
if(timeout > 0) {
setName(baseName + " - SHUTTING DOWN (waiting)");
rv=waitForQueues(timeout, unit);
}
} finally {
// But always begin the shutdown sequence
try {
setName(baseName + " - SHUTTING DOWN (telling client)");
running=false;
conn.shutdown();
setName(baseName + " - SHUTTING DOWN (informed client)");
} catch (IOException e) {
getLogger().warn("exception while shutting down", e);
}
}
return rv;
}
/**
* Wait for the queues to die down.
*/
public boolean waitForQueues(long timeout, TimeUnit unit) {
CountDownLatch blatch = broadcastOp(new BroadcastOpFactory(){
public Operation newOp(final MemcachedNode n,
final CountDownLatch latch) {
return opFact.noop(
new OperationCallback() {
public void complete() {
latch.countDown();
}
public void receivedStatus(OperationStatus s) {
// Nothing special when receiving status, only
// necessary to complete the interface
}
});
}}, false);
try {
return blatch.await(timeout, unit);
} catch (InterruptedException e) {
throw new RuntimeException("Interrupted waiting for queues", e);
}
}
static class BulkGetFuture implements Future<Map<String, Object>> {
private final Map<String, Object> rvMap;
private final Collection<Operation> ops;
private final CountDownLatch latch;
private boolean cancelled=false;
public BulkGetFuture(Map<String, Object> m,
Collection<Operation> getOps, CountDownLatch l) {
super();
rvMap = m;
ops = getOps;
latch=l;
}
public boolean cancel(boolean ign) {
boolean rv=false;
for(Operation op : ops) {
rv |= op.getState() == OperationState.WRITING;
op.cancel();
}
cancelled=true;
return rv;
}
public Map<String, Object> get()
throws InterruptedException, ExecutionException {
try {
return get(Long.MAX_VALUE, TimeUnit.MILLISECONDS);
} catch (TimeoutException e) {
throw new RuntimeException("Timed out waiting forever", e);
}
}
public Map<String, Object> get(long timeout, TimeUnit unit)
throws InterruptedException,
ExecutionException, TimeoutException {
latch.await(timeout, unit);
for(Operation op : ops) {
if(op.isCancelled()) {
throw new ExecutionException(
new RuntimeException("Cancelled"));
}
if(op.hasErrored()) {
throw new ExecutionException(op.getException());
}
}
return rvMap;
}
public boolean isCancelled() {
return cancelled;
}
public boolean isDone() {
return latch.getCount() == 0;
}
}
static class OperationFuture<T> implements Future<T> {
private final CountDownLatch latch;
private final AtomicReference<T> objRef;
private Operation op;
public OperationFuture(CountDownLatch l) {
this(l, new AtomicReference<T>(null));
}
public OperationFuture(CountDownLatch l, AtomicReference<T> oref) {
super();
latch=l;
objRef=oref;
}
public boolean cancel(boolean ign) {
assert op != null : "No operation";
op.cancel();
// This isn't exactly correct, but it's close enough. If we're in
// a writing state, we *probably* haven't started.
return op.getState() == OperationState.WRITING;
}
public T get() throws InterruptedException, ExecutionException {
latch.await();
assert isDone() : "Latch released, but operation wasn't done.";
if(op != null && op.hasErrored()) {
throw new ExecutionException(op.getException());
}
if(isCancelled()) {
throw new ExecutionException(new RuntimeException("Cancelled"));
}
return objRef.get();
}
public T get(long duration, TimeUnit units)
throws InterruptedException, TimeoutException {
latch.await(duration, units);
return objRef.get();
}
void set(T o) {
objRef.set(o);
}
void setOperation(Operation to) {
op=to;
}
public boolean isCancelled() {
assert op != null : "No operation";
return op.isCancelled();
}
public boolean isDone() {
assert op != null : "No operation";
return latch.getCount() == 0 ||
op.isCancelled() || op.getState() == OperationState.COMPLETE;
}
}
}
| true | true | public Future<Map<String, Object>> asyncGetBulk(Collection<String> keys) {
final Map<String, Object> m=new ConcurrentHashMap<String, Object>();
// Break the gets down into groups by key
final Map<MemcachedNode, Collection<String>> chunks
=new HashMap<MemcachedNode, Collection<String>>();
final NodeLocator locator=conn.getLocator();
for(String key : keys) {
validateKey(key);
final MemcachedNode primaryNode=locator.getPrimary(key);
MemcachedNode node=null;
if(primaryNode.isActive()) {
node=primaryNode;
} else {
for(Iterator<MemcachedNode> i=locator.getSequence(key);
node == null && i.hasNext();) {
MemcachedNode n=i.next();
if(n.isActive()) {
node=n;
}
}
if(node == null) {
node=primaryNode;
}
}
assert node != null : "Didn't find a node for " + key;
Collection<String> ks=chunks.get(node);
if(ks == null) {
ks=new ArrayList<String>();
chunks.put(node, ks);
}
ks.add(key);
}
final CountDownLatch latch=new CountDownLatch(chunks.size());
final Collection<Operation> ops=new ArrayList<Operation>();
GetOperation.Callback cb=new GetOperation.Callback() {
@SuppressWarnings("synthetic-access")
public void receivedStatus(OperationStatus status) {
if(!status.isSuccess()) {
getLogger().warn("Unsuccessful get: %s", status);
}
}
public void gotData(String k, int flags, byte[] data) {
m.put(k, transcoder.decode(new CachedData(flags, data)));
}
public void complete() {
latch.countDown();
}
};
for(Map.Entry<MemcachedNode, Collection<String>> me
: chunks.entrySet()) {
ops.add(addOp(me.getKey(), opFact.get(me.getValue(), cb)));
}
return new BulkGetFuture(m, ops, latch);
}
| public Future<Map<String, Object>> asyncGetBulk(Collection<String> keys) {
final Map<String, Object> m=new ConcurrentHashMap<String, Object>();
// Break the gets down into groups by key
final Map<MemcachedNode, Collection<String>> chunks
=new HashMap<MemcachedNode, Collection<String>>();
final NodeLocator locator=conn.getLocator();
for(String key : keys) {
validateKey(key);
final MemcachedNode primaryNode=locator.getPrimary(key);
MemcachedNode node=null;
if(primaryNode.isActive()) {
node=primaryNode;
} else {
for(Iterator<MemcachedNode> i=locator.getSequence(key);
node == null && i.hasNext();) {
MemcachedNode n=i.next();
if(n.isActive()) {
node=n;
}
}
if(node == null) {
node=primaryNode;
}
}
assert node != null : "Didn't find a node for " + key;
Collection<String> ks=chunks.get(node);
if(ks == null) {
ks=new ArrayList<String>();
chunks.put(node, ks);
}
ks.add(key);
}
final CountDownLatch latch=new CountDownLatch(chunks.size());
final Collection<Operation> ops=new ArrayList<Operation>();
GetOperation.Callback cb=new GetOperation.Callback() {
@SuppressWarnings("synthetic-access")
public void receivedStatus(OperationStatus status) {
if(!status.isSuccess()) {
getLogger().warn("Unsuccessful get: %s", status);
}
}
public void gotData(String k, int flags, byte[] data) {
Object val = transcoder.decode(new CachedData(flags, data));
// val may be null if the transcoder did not understand
// the value.
if(val != null) {
m.put(k, val);
}
}
public void complete() {
latch.countDown();
}
};
for(Map.Entry<MemcachedNode, Collection<String>> me
: chunks.entrySet()) {
ops.add(addOp(me.getKey(), opFact.get(me.getValue(), cb)));
}
return new BulkGetFuture(m, ops, latch);
}
|
diff --git a/plugins/org.eclipse.emf.eef.views/src/org/eclispe/emf/eef/views/helpers/NamingHelper.java b/plugins/org.eclipse.emf.eef.views/src/org/eclispe/emf/eef/views/helpers/NamingHelper.java
index b9b8bb67f..c4b45b0ce 100644
--- a/plugins/org.eclipse.emf.eef.views/src/org/eclispe/emf/eef/views/helpers/NamingHelper.java
+++ b/plugins/org.eclipse.emf.eef.views/src/org/eclispe/emf/eef/views/helpers/NamingHelper.java
@@ -1,50 +1,50 @@
/**
*
*/
package org.eclispe.emf.eef.views.helpers;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.emf.eef.views.ViewElement;
import org.eclipse.emf.eef.views.ViewsRepository;
/**
* @author <a href="mailto:[email protected]">Goulwen Le Fur</a>
*
*/
public class NamingHelper {
/**
* @param element
* @return
*/
public static String nameDiscriminator(ViewElement element) {
String baseName = element.getName();
StringBuffer buffer = new StringBuffer();
EObject container = element.eContainer();
while (container instanceof ViewElement) {
if (((ViewElement)container).getName().equals(baseName)) {
buffer.append('_');
- container = container.eContainer();
}
+ container = container.eContainer();
}
ViewsRepository repository = repository(container);
if (repository != null) {
if (repository.getName().equals(baseName)) {
buffer.append('_');
}
}
return buffer.toString();
}
private static ViewsRepository repository(EObject obj) {
EObject container = obj.eContainer();
while (container != null) {
if (container instanceof ViewsRepository) {
return (ViewsRepository) container;
}
container = container.eContainer();
}
return null;
}
}
| false | true | public static String nameDiscriminator(ViewElement element) {
String baseName = element.getName();
StringBuffer buffer = new StringBuffer();
EObject container = element.eContainer();
while (container instanceof ViewElement) {
if (((ViewElement)container).getName().equals(baseName)) {
buffer.append('_');
container = container.eContainer();
}
}
ViewsRepository repository = repository(container);
if (repository != null) {
if (repository.getName().equals(baseName)) {
buffer.append('_');
}
}
return buffer.toString();
}
| public static String nameDiscriminator(ViewElement element) {
String baseName = element.getName();
StringBuffer buffer = new StringBuffer();
EObject container = element.eContainer();
while (container instanceof ViewElement) {
if (((ViewElement)container).getName().equals(baseName)) {
buffer.append('_');
}
container = container.eContainer();
}
ViewsRepository repository = repository(container);
if (repository != null) {
if (repository.getName().equals(baseName)) {
buffer.append('_');
}
}
return buffer.toString();
}
|
diff --git a/src/main/java/edu/northwestern/bioinformatics/studycalendar/web/template/AddLabelWithRepetitionsController.java b/src/main/java/edu/northwestern/bioinformatics/studycalendar/web/template/AddLabelWithRepetitionsController.java
index 4390371b8..32a6b22b1 100644
--- a/src/main/java/edu/northwestern/bioinformatics/studycalendar/web/template/AddLabelWithRepetitionsController.java
+++ b/src/main/java/edu/northwestern/bioinformatics/studycalendar/web/template/AddLabelWithRepetitionsController.java
@@ -1,114 +1,114 @@
package edu.northwestern.bioinformatics.studycalendar.web.template;
import edu.northwestern.bioinformatics.studycalendar.web.PscAbstractController;
import edu.northwestern.bioinformatics.studycalendar.dao.PlannedActivityLabelDao;
import edu.northwestern.bioinformatics.studycalendar.dao.LabelDao;
import edu.northwestern.bioinformatics.studycalendar.dao.PlannedActivityDao;
import edu.northwestern.bioinformatics.studycalendar.domain.PlannedActivityLabel;
import edu.northwestern.bioinformatics.studycalendar.domain.Label;
import edu.northwestern.bioinformatics.studycalendar.domain.PlannedActivity;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.bind.ServletRequestUtils;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;
import java.util.HashMap;
import java.util.List;
import java.util.ArrayList;
/**
* Created by IntelliJ IDEA.
* User: nshurupova
* Date: Jun 4, 2008
* Time: 2:47:31 PM
* To change this template use File | Settings | File Templates.
*/
public class AddLabelWithRepetitionsController extends PscAbstractController {
private PlannedActivityLabelDao plannedActivityLabelDao;
private LabelDao labelDao;
private PlannedActivityDao plannedActivityDao;
protected final Logger log = LoggerFactory.getLogger(getClass());
protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response) throws Exception {
String days = ServletRequestUtils.getRequiredStringParameter(request, "days");
String repetitions = ServletRequestUtils.getRequiredStringParameter(request, "repetitions");
String plannedActivityIndices = ServletRequestUtils.getRequiredStringParameter(request, "arrayOfPlannedActivityIndices");
Integer labelId = ServletRequestUtils.getIntParameter(request, "labelId");
//have to delete labels completely and reenter with a new repetitions
plannedActivityLabelDao.deleteByLabelId(labelId);
- Integer[] arrayOfDays = getArrayFromString(days, ";");
+ Integer[] arrayOfDays = getArrayFromString(days, ",");
Integer[] arrayOfPlannedActivityIndices = getArrayFromString(plannedActivityIndices, ",");
String[] arrayOfRepetitions = repetitions.split(";");
for (int i = 0; i < arrayOfDays.length; i++) {
String repetitionString = arrayOfRepetitions[i];
if (repetitionString !=null && repetitionString.length()>0) {
Integer[] repetitionsInteger = getArrayFromString(repetitionString, ",");
if (repetitionsInteger.length > 0) {
Integer plannedActivityId = arrayOfPlannedActivityIndices[i];
PlannedActivity plannedActivity = plannedActivityDao.getById(plannedActivityId);
for (int j =0; j< repetitionsInteger.length; j++) {
if (repetitionsInteger[j]!=null) {
PlannedActivityLabel plannedActivityLabel = new PlannedActivityLabel();
plannedActivityLabel.setLabel(labelDao.getById(labelId));
plannedActivityLabel.setPlannedActivity(plannedActivity);
plannedActivityLabel.setRepetitionNumber(repetitionsInteger[j]);
plannedActivityLabelDao.save(plannedActivityLabel);
}
}
}
}
}
return null;
}
public PlannedActivityLabelDao getPlannedActivityLabelDao() {
return plannedActivityLabelDao;
}
public void setPlannedActivityLabelDao(PlannedActivityLabelDao plannedActivityLabelDao) {
this.plannedActivityLabelDao = plannedActivityLabelDao;
}
public LabelDao getLabelDao() {
return labelDao;
}
public void setLabelDao(LabelDao labelDao) {
this.labelDao = labelDao;
}
public PlannedActivityDao getPlannedActivityDao() {
return plannedActivityDao;
}
public void setPlannedActivityDao(PlannedActivityDao plannedActivityDao) {
this.plannedActivityDao = plannedActivityDao;
}
private Integer[] getArrayFromString(String stringToParse, String delimiter) {
String[] parsedArray = stringToParse.split(delimiter);
Integer[] result = new Integer[parsedArray.length];
for (int i=0; i< parsedArray.length; i++) {
if (parsedArray[i].indexOf("-")!=0){
Integer something = new Integer(parsedArray[i]);
result[i] = something;
} else {
result[i] = null;
}
}
return result;
}
}
| true | true | protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response) throws Exception {
String days = ServletRequestUtils.getRequiredStringParameter(request, "days");
String repetitions = ServletRequestUtils.getRequiredStringParameter(request, "repetitions");
String plannedActivityIndices = ServletRequestUtils.getRequiredStringParameter(request, "arrayOfPlannedActivityIndices");
Integer labelId = ServletRequestUtils.getIntParameter(request, "labelId");
//have to delete labels completely and reenter with a new repetitions
plannedActivityLabelDao.deleteByLabelId(labelId);
Integer[] arrayOfDays = getArrayFromString(days, ";");
Integer[] arrayOfPlannedActivityIndices = getArrayFromString(plannedActivityIndices, ",");
String[] arrayOfRepetitions = repetitions.split(";");
for (int i = 0; i < arrayOfDays.length; i++) {
String repetitionString = arrayOfRepetitions[i];
if (repetitionString !=null && repetitionString.length()>0) {
Integer[] repetitionsInteger = getArrayFromString(repetitionString, ",");
if (repetitionsInteger.length > 0) {
Integer plannedActivityId = arrayOfPlannedActivityIndices[i];
PlannedActivity plannedActivity = plannedActivityDao.getById(plannedActivityId);
for (int j =0; j< repetitionsInteger.length; j++) {
if (repetitionsInteger[j]!=null) {
PlannedActivityLabel plannedActivityLabel = new PlannedActivityLabel();
plannedActivityLabel.setLabel(labelDao.getById(labelId));
plannedActivityLabel.setPlannedActivity(plannedActivity);
plannedActivityLabel.setRepetitionNumber(repetitionsInteger[j]);
plannedActivityLabelDao.save(plannedActivityLabel);
}
}
}
}
}
return null;
}
| protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response) throws Exception {
String days = ServletRequestUtils.getRequiredStringParameter(request, "days");
String repetitions = ServletRequestUtils.getRequiredStringParameter(request, "repetitions");
String plannedActivityIndices = ServletRequestUtils.getRequiredStringParameter(request, "arrayOfPlannedActivityIndices");
Integer labelId = ServletRequestUtils.getIntParameter(request, "labelId");
//have to delete labels completely and reenter with a new repetitions
plannedActivityLabelDao.deleteByLabelId(labelId);
Integer[] arrayOfDays = getArrayFromString(days, ",");
Integer[] arrayOfPlannedActivityIndices = getArrayFromString(plannedActivityIndices, ",");
String[] arrayOfRepetitions = repetitions.split(";");
for (int i = 0; i < arrayOfDays.length; i++) {
String repetitionString = arrayOfRepetitions[i];
if (repetitionString !=null && repetitionString.length()>0) {
Integer[] repetitionsInteger = getArrayFromString(repetitionString, ",");
if (repetitionsInteger.length > 0) {
Integer plannedActivityId = arrayOfPlannedActivityIndices[i];
PlannedActivity plannedActivity = plannedActivityDao.getById(plannedActivityId);
for (int j =0; j< repetitionsInteger.length; j++) {
if (repetitionsInteger[j]!=null) {
PlannedActivityLabel plannedActivityLabel = new PlannedActivityLabel();
plannedActivityLabel.setLabel(labelDao.getById(labelId));
plannedActivityLabel.setPlannedActivity(plannedActivity);
plannedActivityLabel.setRepetitionNumber(repetitionsInteger[j]);
plannedActivityLabelDao.save(plannedActivityLabel);
}
}
}
}
}
return null;
}
|
diff --git a/src/joshua/decoder/DecoderThread.java b/src/joshua/decoder/DecoderThread.java
index 3111ce98..75500b0a 100644
--- a/src/joshua/decoder/DecoderThread.java
+++ b/src/joshua/decoder/DecoderThread.java
@@ -1,389 +1,386 @@
/* This file is part of the Joshua Machine Translation System.
*
* Joshua is free software; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1
* of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free
* Software Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*/
package joshua.decoder;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.File;
import java.util.Arrays;
import java.util.List;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import joshua.decoder.segment_file.Sentence;
import joshua.corpus.suffix_array.Pattern;
import joshua.corpus.syntax.ArraySyntaxTree;
import joshua.corpus.syntax.SyntaxTree;
import joshua.corpus.vocab.SymbolTable;
import joshua.decoder.chart_parser.Chart;
import joshua.decoder.ff.FeatureFunction;
import joshua.decoder.ff.lm.LanguageModelFF;
import joshua.decoder.ff.state_maintenance.StateComputer;
import joshua.decoder.ff.tm.Grammar;
import joshua.decoder.ff.tm.GrammarFactory;
import joshua.decoder.ff.tm.hiero.MemoryBasedBatchGrammar;
import joshua.decoder.hypergraph.DiskHyperGraph;
import joshua.decoder.hypergraph.HyperGraph;
import joshua.decoder.hypergraph.KBestExtractor;
import joshua.lattice.Lattice;
import joshua.oracle.OracleExtractor;
import joshua.ui.hypergraph_visualizer.HyperGraphViewer;
import joshua.util.CoIterator;
import joshua.util.FileUtility;
import joshua.util.io.LineReader;
import joshua.util.io.NullReader;
import joshua.util.io.Reader;
import joshua.util.io.UncheckedIOException;
import edu.jhu.thrax.util.TestSetFilter;
/**
* this class implements:
* (1) interact with the chart-parsing functions to do the true
* decoding
*
* @author Zhifei Li, <[email protected]>
* @version $LastChangedDate: 2010-05-02 11:19:17 -0400 (Sun, 02 May 2010) $
*/
// BUG: known synchronization problem: LM cache; srilm call;
public class DecoderThread extends Thread {
/* these variables may be the same across all threads (e.g.,
* just copy from DecoderFactory), or differ from thread
* to thread */
private final List<GrammarFactory> grammarFactories;
private final List<FeatureFunction> featureFunctions;
private final List<StateComputer> stateComputers;
/**
* Shared symbol table for source language terminals, target
* language terminals, and shared nonterminals.
* <p>
* It may be that separate tables should be maintained for
* the source and target languages.
* <p>
* This class explicitly uses the symbol table to get integer
* IDs for the source language sentence.
*/
private final SymbolTable symbolTable;
//more test set specific
private final InputHandler inputHandler;
// final String nbestFile; // package-private for DecoderFactory
private BufferedWriter nbestWriter; // set in decodeTestFile
private final KBestExtractor kbestExtractor;
DiskHyperGraph hypergraphSerializer; // package-private for DecoderFactory
private static final Logger logger =
Logger.getLogger(DecoderThread.class.getName());
//===============================================================
// Constructor
//===============================================================
public DecoderThread(
List<GrammarFactory> grammarFactories,
List<FeatureFunction> featureFunctions,
List<StateComputer> stateComputers,
SymbolTable symbolTable,
InputHandler inputHandler
) throws IOException {
this.grammarFactories = grammarFactories;
this.featureFunctions = featureFunctions;
this.stateComputers = stateComputers;
this.symbolTable = symbolTable;
this.inputHandler = inputHandler;
this.kbestExtractor = new KBestExtractor(
this.symbolTable,
JoshuaConfiguration.use_unique_nbest,
JoshuaConfiguration.use_tree_nbest,
JoshuaConfiguration.include_align_index,
JoshuaConfiguration.add_combined_cost,
false, true);
// if (JoshuaConfiguration.save_disk_hg) {
// FeatureFunction languageModel = null;
// for (FeatureFunction ff : this.featureFunctions) {
// if (ff instanceof LanguageModelFF) {
// languageModel = ff;
// break;
// }
// }
// int lmFeatID = -1;
// if (null == languageModel) {
// logger.warning("No language model feature function found, but save disk hg");
// } else {
// lmFeatID = languageModel.getFeatureID();
// }
// this.hypergraphSerializer = new DiskHyperGraph(
// this.symbolTable,
// lmFeatID,
// true, // always store model cost
// this.featureFunctions);
// this.hypergraphSerializer.initWrite(
// "out." + Integer.toString(sentence.id()) + ".hg.items",
// JoshuaConfiguration.forest_pruning,
// JoshuaConfiguration.forest_pruning_threshold);
// }
}
//===============================================================
// Methods
//===============================================================
// Overriding of Thread.run() cannot throw anything
public void run() {
try {
this.translateAll();
//this.hypergraphSerializer.closeReaders();
} catch (Throwable e) {
// if we throw anything (e.g. OutOfMemoryError)
// we should stop all threads
// because it is impossible for decoding
// to finish successfully
e.printStackTrace();
System.exit(1);
}
}
/**
* Repeatedly fetches input sentences and calls translate() on
* them, registering the results with the InputManager upon
* completion.
*/
public void translateAll() throws IOException {
while (inputHandler.hasNext()) {
long startTime = System.currentTimeMillis();
Sentence sentence = inputHandler.next();
// System.out.println("[" + sentence.id() + "] " + sentence.sentence());
HyperGraph hypergraph = translate(sentence, null);
Translation translation = null;
if (JoshuaConfiguration.visualize_hypergraph) {
HyperGraphViewer.visualizeHypergraphInFrame(hypergraph, symbolTable);
}
String oracleSentence = inputHandler.oracleSentence();
if (oracleSentence != null) {
OracleExtractor extractor = new OracleExtractor(this.symbolTable);
HyperGraph oracle = extractor.getOracle(hypergraph, 3, oracleSentence);
translation = new Translation(sentence, oracle, featureFunctions);
} else {
translation = new Translation(sentence, hypergraph, featureFunctions);
// if (null != this.hypergraphSerializer) {
// if(JoshuaConfiguration.use_kbest_hg){
// HyperGraph kbestHG = this.kbestExtractor.extractKbestIntoHyperGraph(hypergraph, JoshuaConfiguration.topN);
// this.hypergraphSerializer.saveHyperGraph(kbestHG);
// }else{
// this.hypergraphSerializer.saveHyperGraph(hypergraph);
// }
// }
}
inputHandler.register(translation);
/* //debug
if (JoshuaConfiguration.use_variational_decoding) {
ConstituentVariationalDecoder vd = new ConstituentVariationalDecoder();
vd.decoding(hypergraph);
System.out.println("#### new 1best is #####\n" + HyperGraph.extract_best_string(p_main_controller.p_symbol, hypergraph.goal_item));
}
// end */
//debug
//g_con.get_confusion_in_hyper_graph_cell_specific(hypergraph, hypergraph.sent_len);
}
}
/**
* Translate a sentence.
*
* @param segment The sentence to be translated.
* @param oracleSentence
*/
public HyperGraph translate(Sentence sentence, String oracleSentence)
throws IOException {
if (logger.isLoggable(Level.FINE))
logger.fine("now translating\n" + sentence.sentence());
Chart chart;
Lattice<Integer> input_lattice = sentence.lattice();
if (logger.isLoggable(Level.FINEST))
logger.finest("Translating input lattice:\n" + input_lattice.toString());
int numGrammars = (JoshuaConfiguration.use_sent_specific_tm)
? grammarFactories.size() + 1
: grammarFactories.size();
Grammar[] grammars = new Grammar[numGrammars];
for (int i = 0; i< grammarFactories.size(); i++)
grammars[i] = grammarFactories.get(i).getGrammarForSentence(sentence.pattern());
// load the sentence-specific grammar
boolean alreadyExisted = true; // whether it already existed
String tmFile = null;
if (JoshuaConfiguration.use_sent_specific_tm) {
// figure out the sentence-level file name
tmFile = JoshuaConfiguration.tm_file;
tmFile = tmFile.endsWith(".gz")
? tmFile.substring(0, tmFile.length()-3) + "." + sentence.id() + ".gz"
: tmFile + "." + sentence.id();
// look in a subdirectory named "filtered" e.g.,
// /some/path/grammar.gz will have sentence-level
// grammars in /some/path/filtered/grammar.SENTNO.gz
int lastSlashPos = tmFile.lastIndexOf('/');
String dirPart = tmFile.substring(0,lastSlashPos + 1);
String filePart = tmFile.substring(lastSlashPos + 1);
tmFile = dirPart + "filtered/" + filePart;
File filteredDir = new File(dirPart + "filtered");
if (! filteredDir.exists()) {
logger.info("Creating sentence-level grammar directory '" + dirPart + "filtered'");
filteredDir.mkdirs();
}
logger.info("Using sentence-specific TM file '" + tmFile + "'");
if (! new File(tmFile).exists()) {
alreadyExisted = false;
// filter grammar and write it to a file
if (logger.isLoggable(Level.INFO))
logger.info("Automatically producing file " + tmFile);
TestSetFilter.filterGrammarToFile(JoshuaConfiguration.tm_file,
sentence.sentence(),
tmFile,
true);
} else {
if (logger.isLoggable(Level.INFO))
logger.info("Using existing sentence-specific tm file " + tmFile);
}
grammars[numGrammars-1] = new MemoryBasedBatchGrammar(JoshuaConfiguration.tm_format,
tmFile,
this.symbolTable,
JoshuaConfiguration.phrase_owner,
JoshuaConfiguration.default_non_terminal,
JoshuaConfiguration.span_limit,
JoshuaConfiguration.oov_feature_cost);
// sort the sentence-specific grammar
grammars[numGrammars-1].sortGrammar(this.featureFunctions);
}
/* Seeding: the chart only sees the grammars, not the factories */
chart = new Chart(input_lattice,
this.featureFunctions,
this.stateComputers,
this.symbolTable,
sentence.id(),
grammars,
false,
JoshuaConfiguration.goal_symbol,
sentence.constraints(),
sentence.syntax_tree());
/* Parsing */
HyperGraph hypergraph = chart.expand();
// delete the sentence-specific grammar if it didn't
// already exist and we weren't asked to keep it around
- if (! alreadyExisted && ! JoshuaConfiguration.keep_sent_specific_tm) {
+ if (! alreadyExisted && ! JoshuaConfiguration.keep_sent_specific_tm && JoshuaConfiguration.use_sent_specific_tm) {
File file = new File(tmFile);
file.delete();
- if (logger.isLoggable(Level.INFO))
- logger.info("Deleting sentence-level grammar file '" + tmFile + "'");
+ logger.info("Deleting sentence-level grammar file '" + tmFile + "'");
} else if (JoshuaConfiguration.keep_sent_specific_tm) {
- if (logger.isLoggable(Level.INFO))
- logger.info("Keeping sentence-level grammar (keep_sent_specific_tm=true)");
+ logger.info("Keeping sentence-level grammar (keep_sent_specific_tm=true)");
} else if (alreadyExisted) {
- if (logger.isLoggable(Level.INFO))
- logger.info("Keeping sentence-level grammar (already existed)");
+ logger.info("Keeping sentence-level grammar (already existed)");
}
return hypergraph;
}
/**decode a sentence, and return a hypergraph*/
public HyperGraph getHyperGraph(String sentence)
{
Chart chart;
int[] intSentence = this.symbolTable.getIDs(sentence);
Lattice<Integer> inputLattice = Lattice.createLattice(intSentence);
Grammar[] grammars = new Grammar[grammarFactories.size()];
int i = 0;
for (GrammarFactory factory : this.grammarFactories) {
grammars[i] = factory.getGrammarForSentence(
new Pattern(this.symbolTable, intSentence));
// For batch grammar, we do not want to sort it every time
if (! grammars[i].isSorted()) {
grammars[i].sortGrammar(this.featureFunctions);
}
i++;
}
chart = new Chart(
inputLattice,
this.featureFunctions,
this.stateComputers,
this.symbolTable,
0,
grammars,
false,
JoshuaConfiguration.goal_symbol,
null, null);
return chart.expand();
}
}
| false | true | public HyperGraph translate(Sentence sentence, String oracleSentence)
throws IOException {
if (logger.isLoggable(Level.FINE))
logger.fine("now translating\n" + sentence.sentence());
Chart chart;
Lattice<Integer> input_lattice = sentence.lattice();
if (logger.isLoggable(Level.FINEST))
logger.finest("Translating input lattice:\n" + input_lattice.toString());
int numGrammars = (JoshuaConfiguration.use_sent_specific_tm)
? grammarFactories.size() + 1
: grammarFactories.size();
Grammar[] grammars = new Grammar[numGrammars];
for (int i = 0; i< grammarFactories.size(); i++)
grammars[i] = grammarFactories.get(i).getGrammarForSentence(sentence.pattern());
// load the sentence-specific grammar
boolean alreadyExisted = true; // whether it already existed
String tmFile = null;
if (JoshuaConfiguration.use_sent_specific_tm) {
// figure out the sentence-level file name
tmFile = JoshuaConfiguration.tm_file;
tmFile = tmFile.endsWith(".gz")
? tmFile.substring(0, tmFile.length()-3) + "." + sentence.id() + ".gz"
: tmFile + "." + sentence.id();
// look in a subdirectory named "filtered" e.g.,
// /some/path/grammar.gz will have sentence-level
// grammars in /some/path/filtered/grammar.SENTNO.gz
int lastSlashPos = tmFile.lastIndexOf('/');
String dirPart = tmFile.substring(0,lastSlashPos + 1);
String filePart = tmFile.substring(lastSlashPos + 1);
tmFile = dirPart + "filtered/" + filePart;
File filteredDir = new File(dirPart + "filtered");
if (! filteredDir.exists()) {
logger.info("Creating sentence-level grammar directory '" + dirPart + "filtered'");
filteredDir.mkdirs();
}
logger.info("Using sentence-specific TM file '" + tmFile + "'");
if (! new File(tmFile).exists()) {
alreadyExisted = false;
// filter grammar and write it to a file
if (logger.isLoggable(Level.INFO))
logger.info("Automatically producing file " + tmFile);
TestSetFilter.filterGrammarToFile(JoshuaConfiguration.tm_file,
sentence.sentence(),
tmFile,
true);
} else {
if (logger.isLoggable(Level.INFO))
logger.info("Using existing sentence-specific tm file " + tmFile);
}
grammars[numGrammars-1] = new MemoryBasedBatchGrammar(JoshuaConfiguration.tm_format,
tmFile,
this.symbolTable,
JoshuaConfiguration.phrase_owner,
JoshuaConfiguration.default_non_terminal,
JoshuaConfiguration.span_limit,
JoshuaConfiguration.oov_feature_cost);
// sort the sentence-specific grammar
grammars[numGrammars-1].sortGrammar(this.featureFunctions);
}
/* Seeding: the chart only sees the grammars, not the factories */
chart = new Chart(input_lattice,
this.featureFunctions,
this.stateComputers,
this.symbolTable,
sentence.id(),
grammars,
false,
JoshuaConfiguration.goal_symbol,
sentence.constraints(),
sentence.syntax_tree());
/* Parsing */
HyperGraph hypergraph = chart.expand();
// delete the sentence-specific grammar if it didn't
// already exist and we weren't asked to keep it around
if (! alreadyExisted && ! JoshuaConfiguration.keep_sent_specific_tm) {
File file = new File(tmFile);
file.delete();
if (logger.isLoggable(Level.INFO))
logger.info("Deleting sentence-level grammar file '" + tmFile + "'");
} else if (JoshuaConfiguration.keep_sent_specific_tm) {
if (logger.isLoggable(Level.INFO))
logger.info("Keeping sentence-level grammar (keep_sent_specific_tm=true)");
} else if (alreadyExisted) {
if (logger.isLoggable(Level.INFO))
logger.info("Keeping sentence-level grammar (already existed)");
}
return hypergraph;
}
| public HyperGraph translate(Sentence sentence, String oracleSentence)
throws IOException {
if (logger.isLoggable(Level.FINE))
logger.fine("now translating\n" + sentence.sentence());
Chart chart;
Lattice<Integer> input_lattice = sentence.lattice();
if (logger.isLoggable(Level.FINEST))
logger.finest("Translating input lattice:\n" + input_lattice.toString());
int numGrammars = (JoshuaConfiguration.use_sent_specific_tm)
? grammarFactories.size() + 1
: grammarFactories.size();
Grammar[] grammars = new Grammar[numGrammars];
for (int i = 0; i< grammarFactories.size(); i++)
grammars[i] = grammarFactories.get(i).getGrammarForSentence(sentence.pattern());
// load the sentence-specific grammar
boolean alreadyExisted = true; // whether it already existed
String tmFile = null;
if (JoshuaConfiguration.use_sent_specific_tm) {
// figure out the sentence-level file name
tmFile = JoshuaConfiguration.tm_file;
tmFile = tmFile.endsWith(".gz")
? tmFile.substring(0, tmFile.length()-3) + "." + sentence.id() + ".gz"
: tmFile + "." + sentence.id();
// look in a subdirectory named "filtered" e.g.,
// /some/path/grammar.gz will have sentence-level
// grammars in /some/path/filtered/grammar.SENTNO.gz
int lastSlashPos = tmFile.lastIndexOf('/');
String dirPart = tmFile.substring(0,lastSlashPos + 1);
String filePart = tmFile.substring(lastSlashPos + 1);
tmFile = dirPart + "filtered/" + filePart;
File filteredDir = new File(dirPart + "filtered");
if (! filteredDir.exists()) {
logger.info("Creating sentence-level grammar directory '" + dirPart + "filtered'");
filteredDir.mkdirs();
}
logger.info("Using sentence-specific TM file '" + tmFile + "'");
if (! new File(tmFile).exists()) {
alreadyExisted = false;
// filter grammar and write it to a file
if (logger.isLoggable(Level.INFO))
logger.info("Automatically producing file " + tmFile);
TestSetFilter.filterGrammarToFile(JoshuaConfiguration.tm_file,
sentence.sentence(),
tmFile,
true);
} else {
if (logger.isLoggable(Level.INFO))
logger.info("Using existing sentence-specific tm file " + tmFile);
}
grammars[numGrammars-1] = new MemoryBasedBatchGrammar(JoshuaConfiguration.tm_format,
tmFile,
this.symbolTable,
JoshuaConfiguration.phrase_owner,
JoshuaConfiguration.default_non_terminal,
JoshuaConfiguration.span_limit,
JoshuaConfiguration.oov_feature_cost);
// sort the sentence-specific grammar
grammars[numGrammars-1].sortGrammar(this.featureFunctions);
}
/* Seeding: the chart only sees the grammars, not the factories */
chart = new Chart(input_lattice,
this.featureFunctions,
this.stateComputers,
this.symbolTable,
sentence.id(),
grammars,
false,
JoshuaConfiguration.goal_symbol,
sentence.constraints(),
sentence.syntax_tree());
/* Parsing */
HyperGraph hypergraph = chart.expand();
// delete the sentence-specific grammar if it didn't
// already exist and we weren't asked to keep it around
if (! alreadyExisted && ! JoshuaConfiguration.keep_sent_specific_tm && JoshuaConfiguration.use_sent_specific_tm) {
File file = new File(tmFile);
file.delete();
logger.info("Deleting sentence-level grammar file '" + tmFile + "'");
} else if (JoshuaConfiguration.keep_sent_specific_tm) {
logger.info("Keeping sentence-level grammar (keep_sent_specific_tm=true)");
} else if (alreadyExisted) {
logger.info("Keeping sentence-level grammar (already existed)");
}
return hypergraph;
}
|
diff --git a/org.openscada.ae.server.storage.jdbc/src/org/openscada/ae/server/storage/jdbc/internal/HqlConverter.java b/org.openscada.ae.server.storage.jdbc/src/org/openscada/ae/server/storage/jdbc/internal/HqlConverter.java
index 35331a5bc..c5a270569 100644
--- a/org.openscada.ae.server.storage.jdbc/src/org/openscada/ae/server/storage/jdbc/internal/HqlConverter.java
+++ b/org.openscada.ae.server.storage.jdbc/src/org/openscada/ae/server/storage/jdbc/internal/HqlConverter.java
@@ -1,309 +1,309 @@
package org.openscada.ae.server.storage.jdbc.internal;
import java.beans.PropertyDescriptor;
import java.beans.PropertyEditor;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.commons.beanutils.PropertyUtils;
import org.openscada.ae.event.FilterUtils;
import org.openscada.core.NotConvertableException;
import org.openscada.core.NullValueException;
import org.openscada.core.Variant;
import org.openscada.utils.filter.Assertion;
import org.openscada.utils.filter.Filter;
import org.openscada.utils.filter.FilterAssertion;
import org.openscada.utils.filter.FilterExpression;
import org.openscada.utils.filter.Operator;
public class HqlConverter
{
private static final Map<String, Class<?>> properties = new HashMap<String, Class<?>> ();
static
{
for ( PropertyDescriptor pd : PropertyUtils.getPropertyDescriptors ( MutableEvent.class ) )
{
properties.put ( pd.getName (), pd.getPropertyType () );
}
}
public static class HqlResult
{
private String hql = "";
private Object[] parameters = new Object[] {};
public String getHql ()
{
return hql;
}
public void setHql ( String hql )
{
this.hql = hql;
}
public Object[] getParameters ()
{
return parameters;
}
public void setParameters ( Object[] parameters )
{
this.parameters = parameters;
}
}
public static HqlResult toHql ( Filter filter ) throws NotSupportedException
{
HqlResult result = new HqlResult ();
result.hql = "SELECT M from MutableEvent M left join fetch M.attributes as A";
if ( filter.isEmpty () )
{
// pass
}
else if ( filter.isExpression () )
{
HqlResult h = toHql ( (FilterExpression)filter );
result.hql += " WHERE " + h.hql;
result.parameters = combine ( result.parameters, h.parameters );
}
else if ( filter.isAssertion () )
{
HqlResult h = toHql ( (FilterAssertion)filter );
result.hql += " WHERE " + h.hql;
result.parameters = combine ( result.parameters, h.parameters );
}
else
{
//
}
result.hql += " ORDER BY M.sourceTimestamp, M.entryTimestamp, M.id DESC;";
return result;
}
static HqlResult toHql ( FilterExpression expression ) throws NotSupportedException
{
HqlResult result = new HqlResult ();
result.hql = "(";
int i = 0;
for ( Filter term : expression.getFilterSet () )
{
if ( i > 0 )
{
if ( expression.getOperator () == Operator.AND )
{
result.hql += " AND ";
}
else if ( expression.getOperator () == Operator.OR )
{
result.hql += " OR ";
}
}
if ( term.isExpression () )
{
HqlResult r = toHql ( (FilterExpression)term );
result.hql += r.hql;
result.parameters = combine ( result.parameters, r.parameters );
}
else if ( term.isAssertion () )
{
HqlResult r = toHql ( (FilterAssertion)term );
result.hql += r.hql;
result.parameters = combine ( result.parameters, r.parameters );
}
i++;
}
if ( expression.getOperator () == Operator.NOT )
{
result.hql = "NOT " + result.hql;
}
result.hql += ")";
return result;
}
static HqlResult toHql ( FilterAssertion assertion ) throws NotSupportedException
{
HqlResult result = null;
if ( assertion.getAssertion () == Assertion.EQUALITY )
{
result = toHql ( assertion.getAttribute (), "=", assertion.getValue () );
}
else if ( assertion.getAssertion () == Assertion.GREATEREQ )
{
result = toHql ( assertion.getAttribute (), ">=", assertion.getValue () );
}
else if ( assertion.getAssertion () == Assertion.LESSEQ )
{
result = toHql ( assertion.getAttribute (), "<=", assertion.getValue () );
}
else if ( assertion.getAssertion () == Assertion.APPROXIMATE )
{
result = toHql ( assertion.getAttribute (), "approximate", assertion.getValue () );
}
else if ( assertion.getAssertion () == Assertion.SUBSTRING )
{
result = toHql ( assertion.getAttribute (), "like", assertion.getValue () );
}
else if ( assertion.getAssertion () == Assertion.PRESENCE )
{
result = toHql ( assertion.getAttribute (), "presence", assertion.getValue () );
}
else
{
throw new NotSupportedException ();
}
return result;
}
static HqlResult toHql ( String field, String op, Object value )
{
HqlResult term = new HqlResult ();
term.hql = "(";
if ( isField ( field ) && properties.get ( field ) != Variant.class )
{
if ( "presence".equals ( op ) )
{
term.hql += "M." + field + " IS NOT NULL)";
}
else
{
if ( ( value != null ) && ( value instanceof Variant ) )
{
PropertyEditor pe = FilterUtils.propertyEditorRegistry.findCustomEditor ( properties.get ( field ) );
pe.setAsText ( new Variant ( value ).asString ( "" ) );
term.parameters = new Object[] { pe.getValue () };
}
else
{
term.parameters = new Object[] { value };
}
if ( "like".equals ( op ) )
{
term.hql += "lower(M." + field + ") like lower(?))";
}
else if ( "approximate".equals ( op ) )
{
term.hql += "soundex(M." + field + ") = soundex(?))";
}
else
{
term.hql += "M." + field + " " + op + " ?)";
}
}
}
else if ( isField ( field ) && properties.get ( field ) == Variant.class )
{
if ( "presence".equals ( op ) )
{
term.hql += "M." + field + ".string IS NOT NULL OR M." + field + ".integer IS NOT NULL OR M." + field + ".double IS NOT NULL)";
}
else
{
if ( "like".equals ( op ) )
{
term.hql += "lower(M." + field + ".string) like lower(?))";
if ( value == null )
{
term.parameters = new Object[] { null };
}
else
{
term.parameters = new Object[] { new Variant ( value ).asString ( "" ) };
}
}
else if ( "approximate".equals ( op ) )
{
term.hql += "soundex(M." + field + ".string) = soundex(?))";
if ( value == null )
{
term.parameters = new Object[] { null };
}
else
{
term.parameters = new Object[] { new Variant ( value ).asString ( "" ) };
}
}
else
{
if ( value == null )
{
term.parameters = new Object[] { null, null, null };
}
else
{
- term.parameters = new Object[] { new Variant ( value ).asString ( "" ), new Variant ( value ).asLong ( 0l ), new Variant ( value ).asDouble ( 0.0d ) };
+ term.parameters = new Object[] { new Variant ( value ).asString ( null ), new Variant ( value ).asLong ( null ), new Variant ( value ).asDouble ( null ) };
}
term.hql += "(M." + field + ".string " + op + " ?) OR (M." + field + ".integer " + op + " ?) OR (M." + field + ".double " + op + " ?))";
}
}
}
else
{
Variant v = (Variant)value;
String strValue = v.asString ( "" );
Long longValue = null;
Double doubleValue = null;
try
{
longValue = v.asLong ();
doubleValue = v.asDouble ();
}
catch ( NullValueException e )
{
longValue = null;
doubleValue = null;
}
catch ( NotConvertableException e )
{
longValue = null;
doubleValue = null;
}
if ( "like".equals ( op ) )
{
term.hql += "index(A) = '" + field + "' AND (lower(A.string) " + op + " lower(?)))";
term.parameters = new Object[] { strValue };
}
else if ( "approximate".equals ( op ) )
{
term.hql += "index(A) = '" + field + "' AND (soundex(A.string) = soundex(?)))";
term.parameters = new Object[] { strValue };
}
else if ( "presence".equals ( op ) )
{
term.hql += "index(A) = '" + field + "')";
term.parameters = new Object[] {};
}
else
{
term.hql += "index(A) = '" + field + "' AND (A.string " + op + " ? OR A.integer " + op + " ? OR A.double " + op + " ?))";
term.parameters = new Object[] { strValue, longValue, doubleValue };
}
}
return term;
}
static boolean isField ( String field )
{
return properties.keySet ().contains ( field );
}
static Object[] combine ( Object[] a, Object[] b )
{
List<Object> l = new ArrayList<Object> ();
if ( a != null )
{
l.addAll ( Arrays.asList ( a ) );
}
if ( b != null )
{
l.addAll ( Arrays.asList ( b ) );
}
return l.toArray ();
}
}
| true | true | static HqlResult toHql ( String field, String op, Object value )
{
HqlResult term = new HqlResult ();
term.hql = "(";
if ( isField ( field ) && properties.get ( field ) != Variant.class )
{
if ( "presence".equals ( op ) )
{
term.hql += "M." + field + " IS NOT NULL)";
}
else
{
if ( ( value != null ) && ( value instanceof Variant ) )
{
PropertyEditor pe = FilterUtils.propertyEditorRegistry.findCustomEditor ( properties.get ( field ) );
pe.setAsText ( new Variant ( value ).asString ( "" ) );
term.parameters = new Object[] { pe.getValue () };
}
else
{
term.parameters = new Object[] { value };
}
if ( "like".equals ( op ) )
{
term.hql += "lower(M." + field + ") like lower(?))";
}
else if ( "approximate".equals ( op ) )
{
term.hql += "soundex(M." + field + ") = soundex(?))";
}
else
{
term.hql += "M." + field + " " + op + " ?)";
}
}
}
else if ( isField ( field ) && properties.get ( field ) == Variant.class )
{
if ( "presence".equals ( op ) )
{
term.hql += "M." + field + ".string IS NOT NULL OR M." + field + ".integer IS NOT NULL OR M." + field + ".double IS NOT NULL)";
}
else
{
if ( "like".equals ( op ) )
{
term.hql += "lower(M." + field + ".string) like lower(?))";
if ( value == null )
{
term.parameters = new Object[] { null };
}
else
{
term.parameters = new Object[] { new Variant ( value ).asString ( "" ) };
}
}
else if ( "approximate".equals ( op ) )
{
term.hql += "soundex(M." + field + ".string) = soundex(?))";
if ( value == null )
{
term.parameters = new Object[] { null };
}
else
{
term.parameters = new Object[] { new Variant ( value ).asString ( "" ) };
}
}
else
{
if ( value == null )
{
term.parameters = new Object[] { null, null, null };
}
else
{
term.parameters = new Object[] { new Variant ( value ).asString ( "" ), new Variant ( value ).asLong ( 0l ), new Variant ( value ).asDouble ( 0.0d ) };
}
term.hql += "(M." + field + ".string " + op + " ?) OR (M." + field + ".integer " + op + " ?) OR (M." + field + ".double " + op + " ?))";
}
}
}
else
{
Variant v = (Variant)value;
String strValue = v.asString ( "" );
Long longValue = null;
Double doubleValue = null;
try
{
longValue = v.asLong ();
doubleValue = v.asDouble ();
}
catch ( NullValueException e )
{
longValue = null;
doubleValue = null;
}
catch ( NotConvertableException e )
{
longValue = null;
doubleValue = null;
}
if ( "like".equals ( op ) )
{
term.hql += "index(A) = '" + field + "' AND (lower(A.string) " + op + " lower(?)))";
term.parameters = new Object[] { strValue };
}
else if ( "approximate".equals ( op ) )
{
term.hql += "index(A) = '" + field + "' AND (soundex(A.string) = soundex(?)))";
term.parameters = new Object[] { strValue };
}
else if ( "presence".equals ( op ) )
{
term.hql += "index(A) = '" + field + "')";
term.parameters = new Object[] {};
}
else
{
term.hql += "index(A) = '" + field + "' AND (A.string " + op + " ? OR A.integer " + op + " ? OR A.double " + op + " ?))";
term.parameters = new Object[] { strValue, longValue, doubleValue };
}
}
return term;
}
| static HqlResult toHql ( String field, String op, Object value )
{
HqlResult term = new HqlResult ();
term.hql = "(";
if ( isField ( field ) && properties.get ( field ) != Variant.class )
{
if ( "presence".equals ( op ) )
{
term.hql += "M." + field + " IS NOT NULL)";
}
else
{
if ( ( value != null ) && ( value instanceof Variant ) )
{
PropertyEditor pe = FilterUtils.propertyEditorRegistry.findCustomEditor ( properties.get ( field ) );
pe.setAsText ( new Variant ( value ).asString ( "" ) );
term.parameters = new Object[] { pe.getValue () };
}
else
{
term.parameters = new Object[] { value };
}
if ( "like".equals ( op ) )
{
term.hql += "lower(M." + field + ") like lower(?))";
}
else if ( "approximate".equals ( op ) )
{
term.hql += "soundex(M." + field + ") = soundex(?))";
}
else
{
term.hql += "M." + field + " " + op + " ?)";
}
}
}
else if ( isField ( field ) && properties.get ( field ) == Variant.class )
{
if ( "presence".equals ( op ) )
{
term.hql += "M." + field + ".string IS NOT NULL OR M." + field + ".integer IS NOT NULL OR M." + field + ".double IS NOT NULL)";
}
else
{
if ( "like".equals ( op ) )
{
term.hql += "lower(M." + field + ".string) like lower(?))";
if ( value == null )
{
term.parameters = new Object[] { null };
}
else
{
term.parameters = new Object[] { new Variant ( value ).asString ( "" ) };
}
}
else if ( "approximate".equals ( op ) )
{
term.hql += "soundex(M." + field + ".string) = soundex(?))";
if ( value == null )
{
term.parameters = new Object[] { null };
}
else
{
term.parameters = new Object[] { new Variant ( value ).asString ( "" ) };
}
}
else
{
if ( value == null )
{
term.parameters = new Object[] { null, null, null };
}
else
{
term.parameters = new Object[] { new Variant ( value ).asString ( null ), new Variant ( value ).asLong ( null ), new Variant ( value ).asDouble ( null ) };
}
term.hql += "(M." + field + ".string " + op + " ?) OR (M." + field + ".integer " + op + " ?) OR (M." + field + ".double " + op + " ?))";
}
}
}
else
{
Variant v = (Variant)value;
String strValue = v.asString ( "" );
Long longValue = null;
Double doubleValue = null;
try
{
longValue = v.asLong ();
doubleValue = v.asDouble ();
}
catch ( NullValueException e )
{
longValue = null;
doubleValue = null;
}
catch ( NotConvertableException e )
{
longValue = null;
doubleValue = null;
}
if ( "like".equals ( op ) )
{
term.hql += "index(A) = '" + field + "' AND (lower(A.string) " + op + " lower(?)))";
term.parameters = new Object[] { strValue };
}
else if ( "approximate".equals ( op ) )
{
term.hql += "index(A) = '" + field + "' AND (soundex(A.string) = soundex(?)))";
term.parameters = new Object[] { strValue };
}
else if ( "presence".equals ( op ) )
{
term.hql += "index(A) = '" + field + "')";
term.parameters = new Object[] {};
}
else
{
term.hql += "index(A) = '" + field + "' AND (A.string " + op + " ? OR A.integer " + op + " ? OR A.double " + op + " ?))";
term.parameters = new Object[] { strValue, longValue, doubleValue };
}
}
return term;
}
|
diff --git a/client/src/remuco/ui/screens/BluetoothScreen.java b/client/src/remuco/ui/screens/BluetoothScreen.java
index e9881b5..3a9b722 100644
--- a/client/src/remuco/ui/screens/BluetoothScreen.java
+++ b/client/src/remuco/ui/screens/BluetoothScreen.java
@@ -1,157 +1,157 @@
package remuco.ui.screens;
import javax.microedition.lcdui.Choice;
import javax.microedition.lcdui.ChoiceGroup;
import javax.microedition.lcdui.Form;
import javax.microedition.lcdui.Item;
import javax.microedition.lcdui.ItemStateListener;
import javax.microedition.lcdui.StringItem;
import javax.microedition.lcdui.TextField;
import remuco.comm.BluetoothDevice;
/** Screen to configure a Bluetooth connection. */
public class BluetoothScreen extends Form {
/**
* Implement item state listener in this class because it is already
* implemented privately by {@link Form}.
*/
private class SearchSelectionChangeListener implements ItemStateListener {
public void itemStateChanged(Item item) {
if (item == cgSearch) {
if (cgSearch.getSelectedIndex() == BluetoothDevice.SEARCH_MANUAL) {
tfPort.setConstraints(PORT_ON);
} else {
tfPort.setConstraints(PORT_OFF);
}
}
}
}
/** Text field constraints for port (editable). */
private static final int PORT_ON = TextField.NUMERIC;
/** Text field constraints for port (uneditable). */
private static final int PORT_OFF = PORT_ON | TextField.UNEDITABLE;
private static final String WELCOME_1 = "In most cases just pressing OK here is fine.",
WELCOME_2 = "The fields below are only relevant if automatic connection setup fails.";
private final ChoiceGroup cgSearch;
private final BluetoothDevice device;
private final String SEARCH_CHOICES[] = { "Standard", "Failsafe", "Manual" };
private final TextField tfAddr, tfPort, tfName;
public BluetoothScreen() {
this(new BluetoothDevice(), true);
}
public BluetoothScreen(BluetoothDevice device) {
this(new BluetoothDevice(), false);
}
private BluetoothScreen(BluetoothDevice device, boolean welcome) {
super("Bluetooth");
this.device = device;
if (welcome) {
final StringItem si = new StringItem(WELCOME_1, WELCOME_2);
si.setLayout(Item.LAYOUT_CENTER);
append(si);
}
String label;
label = "Address (withput colons, leave empty to scan for)";
tfAddr = new TextField(label, device.getAddress(), 256, TextField.URL);
append(tfAddr);
label = "Service search (change if standard search fails)";
cgSearch = new ChoiceGroup(label, Choice.EXCLUSIVE, SEARCH_CHOICES,
null);
append(cgSearch);
label = "Port (for manual service search)";
tfPort = new TextField(label, device.getPort(), 256, PORT_OFF);
if (device.getSearch() == BluetoothDevice.SEARCH_MANUAL) {
tfPort.setConstraints(PORT_ON);
}
append(tfPort);
label = "Name (optional)";
tfName = new TextField(label, device.getName(), 256, TextField.ANY);
append(tfName);
setItemStateListener(new SearchSelectionChangeListener());
}
/**
* Apply user entered values to device and return that device. If a device
* has been passed to the constructor of this screen, then the same device
* will be returned here. Otherwise a new device will be returned.
*/
public BluetoothDevice getDevice() {
device.setAddress(tfAddr.getString());
device.setSearch(cgSearch.getSelectedIndex());
device.setPort(tfPort.getString());
device.setName(tfName.getString());
return device;
}
/**
* Validate the user input.
*
* @return <code>null</code> if user input is ok, otherwise a string message
* describing what's wrong
*/
public String validate() {
final String address = tfAddr.getString();
final String port = tfPort.getString();
final int search = cgSearch.getSelectedIndex();
if (address.length() > 0 && address.length() != 12) {
return "A Bluetooth address has exactly 12 characters!";
}
final char[] digits = address.toCharArray();
for (int i = 0; i < digits.length; i++) {
boolean good = false;
good |= digits[i] >= '0' && digits[i] <= '9';
good |= digits[i] >= 'a' && digits[i] <= 'f';
good |= digits[i] >= 'A' && digits[i] <= 'F';
if (!good) {
return "Bluetooth address contains invalid characters!";
}
}
if (search < 0) {
return "Please specify a service search strategy!";
}
if (search == BluetoothDevice.SEARCH_MANUAL) {
final int portInt;
try {
portInt = Integer.parseInt(port);
} catch (NumberFormatException e) {
- return "Port must be empty or a number!";
+ return "Port must be a number!";
}
if (portInt < 1 || portInt > 30) {
return "Port number out of range (1-30)!";
}
}
return null;
}
}
| true | true | public String validate() {
final String address = tfAddr.getString();
final String port = tfPort.getString();
final int search = cgSearch.getSelectedIndex();
if (address.length() > 0 && address.length() != 12) {
return "A Bluetooth address has exactly 12 characters!";
}
final char[] digits = address.toCharArray();
for (int i = 0; i < digits.length; i++) {
boolean good = false;
good |= digits[i] >= '0' && digits[i] <= '9';
good |= digits[i] >= 'a' && digits[i] <= 'f';
good |= digits[i] >= 'A' && digits[i] <= 'F';
if (!good) {
return "Bluetooth address contains invalid characters!";
}
}
if (search < 0) {
return "Please specify a service search strategy!";
}
if (search == BluetoothDevice.SEARCH_MANUAL) {
final int portInt;
try {
portInt = Integer.parseInt(port);
} catch (NumberFormatException e) {
return "Port must be empty or a number!";
}
if (portInt < 1 || portInt > 30) {
return "Port number out of range (1-30)!";
}
}
return null;
}
| public String validate() {
final String address = tfAddr.getString();
final String port = tfPort.getString();
final int search = cgSearch.getSelectedIndex();
if (address.length() > 0 && address.length() != 12) {
return "A Bluetooth address has exactly 12 characters!";
}
final char[] digits = address.toCharArray();
for (int i = 0; i < digits.length; i++) {
boolean good = false;
good |= digits[i] >= '0' && digits[i] <= '9';
good |= digits[i] >= 'a' && digits[i] <= 'f';
good |= digits[i] >= 'A' && digits[i] <= 'F';
if (!good) {
return "Bluetooth address contains invalid characters!";
}
}
if (search < 0) {
return "Please specify a service search strategy!";
}
if (search == BluetoothDevice.SEARCH_MANUAL) {
final int portInt;
try {
portInt = Integer.parseInt(port);
} catch (NumberFormatException e) {
return "Port must be a number!";
}
if (portInt < 1 || portInt > 30) {
return "Port number out of range (1-30)!";
}
}
return null;
}
|
diff --git a/src/java/org/apache/fop/fo/extensions/svg/SVGElement.java b/src/java/org/apache/fop/fo/extensions/svg/SVGElement.java
index 2beff82b7..b9452e22b 100644
--- a/src/java/org/apache/fop/fo/extensions/svg/SVGElement.java
+++ b/src/java/org/apache/fop/fo/extensions/svg/SVGElement.java
@@ -1,290 +1,291 @@
/*
* Copyright 1999-2005 The Apache Software Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/* $Id$ */
package org.apache.fop.fo.extensions.svg;
// FOP
import org.apache.fop.apps.FOPException;
import org.apache.fop.fo.FONode;
import org.apache.fop.fo.PropertyList;
import org.apache.batik.dom.svg.SVGOMDocument;
import org.apache.batik.dom.svg.SVGOMElement;
import org.apache.batik.dom.svg.SVGContext;
import org.apache.batik.dom.util.XMLSupport;
import org.w3c.dom.Element;
import org.w3c.dom.svg.SVGDocument;
import org.xml.sax.Attributes;
import org.xml.sax.Locator;
import org.apache.batik.bridge.UnitProcessor;
import org.apache.batik.util.SVGConstants;
import org.w3c.dom.DOMImplementation;
import org.apache.batik.dom.svg.SVGDOMImplementation;
import java.net.URL;
import java.awt.geom.AffineTransform;
import java.awt.geom.Point2D;
import java.awt.geom.Rectangle2D;
/**
* class representing the SVG root element
* for constructing an svg document.
*/
public class SVGElement extends SVGObj {
/**
* Constructs an SVG object
*
* @param parent the parent formatting object
*/
public SVGElement(FONode parent) {
super(parent);
}
/**
* @see org.apache.fop.fo.FONode#processNode
*/
public void processNode(String elementName, Locator locator,
Attributes attlist, PropertyList propertyList) throws FOPException {
super.processNode(elementName, locator, attlist, propertyList);
init();
}
/**
* Get the dimensions of this XML document.
* @param view the viewport dimensions
* @return the dimensions of this SVG document
*/
public Point2D getDimension(final Point2D view) {
// TODO change so doesn't hold onto fo, area tree
Element svgRoot = element;
/* create an SVG area */
/* if width and height are zero, get the bounds of the content. */
try {
URL baseURL = new URL(getUserAgent().getBaseURL() == null
? new java.io.File("").toURL().toExternalForm()
: getUserAgent().getBaseURL());
if (baseURL != null) {
SVGOMDocument svgdoc = (SVGOMDocument)doc;
svgdoc.setURLObject(baseURL);
+ //The following line should not be called to leave FOP compatible to Batik 1.6.
//svgdoc.setDocumentURI(baseURL.toString());
}
} catch (Exception e) {
getLogger().error("Could not set base URL for svg", e);
}
Element e = ((SVGDocument)doc).getRootElement();
final float ptmm = getUserAgent().getPixelUnitToMillimeter();
// temporary svg context
SVGContext dc = new SVGContext() {
public float getPixelToMM() {
return ptmm;
}
public float getPixelUnitToMillimeter() {
return ptmm;
}
public Rectangle2D getBBox() {
return new Rectangle2D.Double(0, 0, view.getX(), view.getY());
}
/**
* Returns the transform from the global transform space to pixels.
*/
public AffineTransform getScreenTransform() {
throw new UnsupportedOperationException("NYI");
}
/**
* Sets the transform to be used from the global transform space
* to pixels.
*/
public void setScreenTransform(AffineTransform at) {
throw new UnsupportedOperationException("NYI");
}
public AffineTransform getCTM() {
return new AffineTransform();
}
public AffineTransform getGlobalTransform() {
return new AffineTransform();
}
public float getViewportWidth() {
return (float)view.getX();
}
public float getViewportHeight() {
return (float)view.getY();
}
public float getFontSize() {
return 12;
}
public void deselectAll() {
}
};
((SVGOMElement)e).setSVGContext(dc);
//if (!e.hasAttributeNS(XMLSupport.XMLNS_NAMESPACE_URI, "xmlns")) {
e.setAttributeNS(XMLSupport.XMLNS_NAMESPACE_URI, "xmlns",
SVGDOMImplementation.SVG_NAMESPACE_URI);
//}
int fontSize = 12;
Point2D p2d = getSize(fontSize, svgRoot, getUserAgent().getPixelUnitToMillimeter());
((SVGOMElement)e).setSVGContext(null);
return p2d;
}
private void init() {
DOMImplementation impl = SVGDOMImplementation.getDOMImplementation();
String svgNS = SVGDOMImplementation.SVG_NAMESPACE_URI;
doc = impl.createDocument(svgNS, "svg", null);
element = doc.getDocumentElement();
buildTopLevel(doc, element);
}
/**
* Get the size of the SVG root element.
* @param size the font size
* @param svgRoot the svg root element
* @param ptmm the pixel to millimeter conversion factor
* @return the size of the SVG document
*/
public static Point2D getSize(int size, Element svgRoot, float ptmm) {
String str;
UnitProcessor.Context ctx;
ctx = new PDFUnitContext(size, svgRoot, ptmm);
str = svgRoot.getAttributeNS(null, SVGConstants.SVG_WIDTH_ATTRIBUTE);
if (str.length() == 0) {
str = "100%";
}
float width = UnitProcessor.svgHorizontalLengthToUserSpace
(str, SVGConstants.SVG_WIDTH_ATTRIBUTE, ctx);
str = svgRoot.getAttributeNS(null, SVGConstants.SVG_HEIGHT_ATTRIBUTE);
if (str.length() == 0) {
str = "100%";
}
float height = UnitProcessor.svgVerticalLengthToUserSpace
(str, SVGConstants.SVG_HEIGHT_ATTRIBUTE, ctx);
return new Point2D.Float(width, height);
}
/**
* This class is the default context for a particular
* element. Information not available on the element are obtained from
* the bridge context (such as the viewport or the pixel to
* millimeter factor.
*/
public static class PDFUnitContext implements UnitProcessor.Context {
/** The element. */
private Element e;
private int fontSize;
private float pixeltoMM;
/**
* Create a PDF unit context.
* @param size the font size.
* @param e the svg element
* @param ptmm the pixel to millimeter factor
*/
public PDFUnitContext(int size, Element e, float ptmm) {
this.e = e;
this.fontSize = size;
this.pixeltoMM = ptmm;
}
/**
* Returns the element.
* @return the element
*/
public Element getElement() {
return e;
}
/**
* Returns the context of the parent element of this context.
* Since this is always for the root SVG element there never
* should be one...
* @return null
*/
public UnitProcessor.Context getParentElementContext() {
return null;
}
/**
* Returns the pixel to mm factor. (this is deprecated)
* @return the pixel to millimeter factor
*/
public float getPixelToMM() {
return pixeltoMM;
}
/**
* Returns the pixel to mm factor.
* @return the pixel to millimeter factor
*/
public float getPixelUnitToMillimeter() {
return pixeltoMM;
}
/**
* Returns the font-size value.
* @return the default font size
*/
public float getFontSize() {
return fontSize;
}
/**
* Returns the x-height value.
* @return the x-height value
*/
public float getXHeight() {
return 0.5f;
}
/**
* Returns the viewport width used to compute units.
* @return the default viewport width of 100
*/
public float getViewportWidth() {
return 100;
}
/**
* Returns the viewport height used to compute units.
* @return the default viewport height of 100
*/
public float getViewportHeight() {
return 100;
}
}
}
| true | true | public Point2D getDimension(final Point2D view) {
// TODO change so doesn't hold onto fo, area tree
Element svgRoot = element;
/* create an SVG area */
/* if width and height are zero, get the bounds of the content. */
try {
URL baseURL = new URL(getUserAgent().getBaseURL() == null
? new java.io.File("").toURL().toExternalForm()
: getUserAgent().getBaseURL());
if (baseURL != null) {
SVGOMDocument svgdoc = (SVGOMDocument)doc;
svgdoc.setURLObject(baseURL);
//svgdoc.setDocumentURI(baseURL.toString());
}
} catch (Exception e) {
getLogger().error("Could not set base URL for svg", e);
}
Element e = ((SVGDocument)doc).getRootElement();
final float ptmm = getUserAgent().getPixelUnitToMillimeter();
// temporary svg context
SVGContext dc = new SVGContext() {
public float getPixelToMM() {
return ptmm;
}
public float getPixelUnitToMillimeter() {
return ptmm;
}
public Rectangle2D getBBox() {
return new Rectangle2D.Double(0, 0, view.getX(), view.getY());
}
/**
* Returns the transform from the global transform space to pixels.
*/
public AffineTransform getScreenTransform() {
throw new UnsupportedOperationException("NYI");
}
/**
* Sets the transform to be used from the global transform space
* to pixels.
*/
public void setScreenTransform(AffineTransform at) {
throw new UnsupportedOperationException("NYI");
}
public AffineTransform getCTM() {
return new AffineTransform();
}
public AffineTransform getGlobalTransform() {
return new AffineTransform();
}
public float getViewportWidth() {
return (float)view.getX();
}
public float getViewportHeight() {
return (float)view.getY();
}
public float getFontSize() {
return 12;
}
public void deselectAll() {
}
};
((SVGOMElement)e).setSVGContext(dc);
//if (!e.hasAttributeNS(XMLSupport.XMLNS_NAMESPACE_URI, "xmlns")) {
e.setAttributeNS(XMLSupport.XMLNS_NAMESPACE_URI, "xmlns",
SVGDOMImplementation.SVG_NAMESPACE_URI);
//}
int fontSize = 12;
Point2D p2d = getSize(fontSize, svgRoot, getUserAgent().getPixelUnitToMillimeter());
((SVGOMElement)e).setSVGContext(null);
return p2d;
}
| public Point2D getDimension(final Point2D view) {
// TODO change so doesn't hold onto fo, area tree
Element svgRoot = element;
/* create an SVG area */
/* if width and height are zero, get the bounds of the content. */
try {
URL baseURL = new URL(getUserAgent().getBaseURL() == null
? new java.io.File("").toURL().toExternalForm()
: getUserAgent().getBaseURL());
if (baseURL != null) {
SVGOMDocument svgdoc = (SVGOMDocument)doc;
svgdoc.setURLObject(baseURL);
//The following line should not be called to leave FOP compatible to Batik 1.6.
//svgdoc.setDocumentURI(baseURL.toString());
}
} catch (Exception e) {
getLogger().error("Could not set base URL for svg", e);
}
Element e = ((SVGDocument)doc).getRootElement();
final float ptmm = getUserAgent().getPixelUnitToMillimeter();
// temporary svg context
SVGContext dc = new SVGContext() {
public float getPixelToMM() {
return ptmm;
}
public float getPixelUnitToMillimeter() {
return ptmm;
}
public Rectangle2D getBBox() {
return new Rectangle2D.Double(0, 0, view.getX(), view.getY());
}
/**
* Returns the transform from the global transform space to pixels.
*/
public AffineTransform getScreenTransform() {
throw new UnsupportedOperationException("NYI");
}
/**
* Sets the transform to be used from the global transform space
* to pixels.
*/
public void setScreenTransform(AffineTransform at) {
throw new UnsupportedOperationException("NYI");
}
public AffineTransform getCTM() {
return new AffineTransform();
}
public AffineTransform getGlobalTransform() {
return new AffineTransform();
}
public float getViewportWidth() {
return (float)view.getX();
}
public float getViewportHeight() {
return (float)view.getY();
}
public float getFontSize() {
return 12;
}
public void deselectAll() {
}
};
((SVGOMElement)e).setSVGContext(dc);
//if (!e.hasAttributeNS(XMLSupport.XMLNS_NAMESPACE_URI, "xmlns")) {
e.setAttributeNS(XMLSupport.XMLNS_NAMESPACE_URI, "xmlns",
SVGDOMImplementation.SVG_NAMESPACE_URI);
//}
int fontSize = 12;
Point2D p2d = getSize(fontSize, svgRoot, getUserAgent().getPixelUnitToMillimeter());
((SVGOMElement)e).setSVGContext(null);
return p2d;
}
|
diff --git a/src/main/java/archimulator/sim/uncore/cache/replacement/helperThread/HelperThreadAwareLRUPolicy3.java b/src/main/java/archimulator/sim/uncore/cache/replacement/helperThread/HelperThreadAwareLRUPolicy3.java
index be7f9894..f95eae5c 100644
--- a/src/main/java/archimulator/sim/uncore/cache/replacement/helperThread/HelperThreadAwareLRUPolicy3.java
+++ b/src/main/java/archimulator/sim/uncore/cache/replacement/helperThread/HelperThreadAwareLRUPolicy3.java
@@ -1,51 +1,51 @@
package archimulator.sim.uncore.cache.replacement.helperThread;
import archimulator.sim.uncore.MemoryHierarchyAccess;
import archimulator.sim.uncore.cache.CacheAccess;
import archimulator.sim.uncore.cache.CacheLine;
import archimulator.sim.uncore.cache.EvictableCache;
import archimulator.sim.uncore.cache.replacement.LRUPolicy;
import java.io.Serializable;
import static archimulator.sim.uncore.cache.partitioning.CachePartitioningHelper.getThreadIdentifier;
/**
* Helper thread aware least recently used (LRU) policy 3.
*
* @param <StateT> the state type of the parent evictable cache
* @author Min Cai
*/
public class HelperThreadAwareLRUPolicy3<StateT extends Serializable> extends LRUPolicy<StateT> {
/**
* Create a helper thread aware least recently used (LRU) policy 3 for the specified evictable cache.
*
* @param cache the parent evictable cache
*/
public HelperThreadAwareLRUPolicy3(EvictableCache<StateT> cache) {
super(cache);
}
@Override
public CacheAccess<StateT> handleReplacement(MemoryHierarchyAccess access, int set, int tag) {
for (int stackPosition = this.getCache().getAssociativity() - 1; stackPosition >= 0; stackPosition--) {
int way = this.getWayInStackPosition(set, stackPosition);
CacheLine<StateT> line = this.getCache().getLine(set, way);
- if (line.getAccess() != null && getThreadIdentifier(line.getAccess().getThread()) != getThreadIdentifier(access.getThread())) {
+ if (line.getAccess() != null && getThreadIdentifier(line.getAccess().getThread()) == getThreadIdentifier(access.getThread())) {
return new CacheAccess<>(this.getCache(), access, set, way, tag);
}
}
return new CacheAccess<>(this.getCache(), access, set, this.getLRU(set), tag);
}
@Override
public void handlePromotionOnHit(MemoryHierarchyAccess access, int set, int way) {
super.handlePromotionOnHit(access, set, way);
}
@Override
public void handleInsertionOnMiss(MemoryHierarchyAccess access, int set, int way) {
super.handleInsertionOnMiss(access, set, way);
}
}
| true | true | public CacheAccess<StateT> handleReplacement(MemoryHierarchyAccess access, int set, int tag) {
for (int stackPosition = this.getCache().getAssociativity() - 1; stackPosition >= 0; stackPosition--) {
int way = this.getWayInStackPosition(set, stackPosition);
CacheLine<StateT> line = this.getCache().getLine(set, way);
if (line.getAccess() != null && getThreadIdentifier(line.getAccess().getThread()) != getThreadIdentifier(access.getThread())) {
return new CacheAccess<>(this.getCache(), access, set, way, tag);
}
}
return new CacheAccess<>(this.getCache(), access, set, this.getLRU(set), tag);
}
| public CacheAccess<StateT> handleReplacement(MemoryHierarchyAccess access, int set, int tag) {
for (int stackPosition = this.getCache().getAssociativity() - 1; stackPosition >= 0; stackPosition--) {
int way = this.getWayInStackPosition(set, stackPosition);
CacheLine<StateT> line = this.getCache().getLine(set, way);
if (line.getAccess() != null && getThreadIdentifier(line.getAccess().getThread()) == getThreadIdentifier(access.getThread())) {
return new CacheAccess<>(this.getCache(), access, set, way, tag);
}
}
return new CacheAccess<>(this.getCache(), access, set, this.getLRU(set), tag);
}
|
diff --git a/jsf-ri/src/main/java/com/sun/faces/facelets/compiler/NamespaceManager.java b/jsf-ri/src/main/java/com/sun/faces/facelets/compiler/NamespaceManager.java
index e082f01db..df3154e3c 100644
--- a/jsf-ri/src/main/java/com/sun/faces/facelets/compiler/NamespaceManager.java
+++ b/jsf-ri/src/main/java/com/sun/faces/facelets/compiler/NamespaceManager.java
@@ -1,135 +1,135 @@
/*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright (c) 1997-2010 Oracle and/or its affiliates. All rights reserved.
*
* The contents of this file are subject to the terms of either the GNU
* General Public License Version 2 only ("GPL") or the Common Development
* and Distribution License("CDDL") (collectively, the "License"). You
* may not use this file except in compliance with the License. You can
* obtain a copy of the License at
* https://glassfish.dev.java.net/public/CDDL+GPL_1_1.html
* or packager/legal/LICENSE.txt. See the License for the specific
* language governing permissions and limitations under the License.
*
* When distributing the software, include this License Header Notice in each
* file and include the License file at packager/legal/LICENSE.txt.
*
* GPL Classpath Exception:
* Oracle designates this particular file as subject to the "Classpath"
* exception as provided by Oracle in the GPL Version 2 section of the License
* file that accompanied this code.
*
* Modifications:
* If applicable, add the following below the License Header, with the fields
* enclosed by brackets [] replaced by your own identifying information:
* "Portions Copyright [year] [name of copyright owner]"
*
* Contributor(s):
* If you wish your version of this file to be governed by only the CDDL or
* only the GPL Version 2, indicate your decision by adding "[Contributor]
* elects to include this software in this distribution under the [CDDL or GPL
* Version 2] license." If you don't indicate a single choice of license, a
* recipient has the option to distribute your version of this file under
* either the CDDL, the GPL Version 2 or to extend the choice of license to
* its licensees as provided above. However, if you add GPL Version 2 code
* and therefore, elected the GPL Version 2 license, then the option applies
* only if the new code is made subject to such option by the copyright
* holder.
*
*
* This file incorporates work covered by the following copyright and
* permission notice:
*
* Copyright 2005-2007 The Apache Software Foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.sun.faces.facelets.compiler;
import com.sun.faces.facelets.tag.TagLibrary;
import java.util.ArrayList;
import java.util.List;
/**
* @author Jacob Hookom
* @version $Id$
*/
final class NamespaceManager {
private final static class NS {
public final String prefix;
public final String namespace;
public NS(String prefix, String ns) {
this.prefix = prefix;
this.namespace = ns;
}
}
private final List namespaces;
/**
*
*/
public NamespaceManager() {
this.namespaces = new ArrayList();
}
public void reset() {
this.namespaces.clear();
}
public void pushNamespace(String prefix, String namespace) {
NS ns = new NS(prefix, namespace);
this.namespaces.add(0, ns);
}
public String getNamespace(String prefix) {
NS ns = null;
for (int i = 0; i < this.namespaces.size(); i++) {
ns = (NS) this.namespaces.get(i);
if (ns.prefix.equals(prefix)) {
return ns.namespace;
}
}
return null;
}
public void popNamespace(String prefix) {
NS ns = null;
for (int i = 0; i < this.namespaces.size(); i++) {
ns = (NS) this.namespaces.get(i);
if (ns.prefix.equals(prefix)) {
this.namespaces.remove(i);
return;
}
}
}
- public final NamespaceUnit toNamespaceUnit(TagLibrary library) {
+ public NamespaceUnit toNamespaceUnit(TagLibrary library) {
NamespaceUnit unit = new NamespaceUnit(library);
if (this.namespaces.size() > 0) {
NS ns = null;
for (int i = this.namespaces.size() - 1; i >= 0; i--) {
ns = (NS) this.namespaces.get(i);
unit.setNamespace(ns.prefix, ns.namespace);
}
}
return unit;
}
}
| true | true | public final NamespaceUnit toNamespaceUnit(TagLibrary library) {
NamespaceUnit unit = new NamespaceUnit(library);
if (this.namespaces.size() > 0) {
NS ns = null;
for (int i = this.namespaces.size() - 1; i >= 0; i--) {
ns = (NS) this.namespaces.get(i);
unit.setNamespace(ns.prefix, ns.namespace);
}
}
return unit;
}
| public NamespaceUnit toNamespaceUnit(TagLibrary library) {
NamespaceUnit unit = new NamespaceUnit(library);
if (this.namespaces.size() > 0) {
NS ns = null;
for (int i = this.namespaces.size() - 1; i >= 0; i--) {
ns = (NS) this.namespaces.get(i);
unit.setNamespace(ns.prefix, ns.namespace);
}
}
return unit;
}
|
diff --git a/src/main/java/water/api/Upload.java b/src/main/java/water/api/Upload.java
index e84830d89..021a43706 100644
--- a/src/main/java/water/api/Upload.java
+++ b/src/main/java/water/api/Upload.java
@@ -1,32 +1,32 @@
package water.api;
import com.google.gson.JsonObject;
public class Upload extends HTMLOnlyRequest {
protected String build(Response response) {
return "<script type='text/javascript' src='jquery.fileupload/js/vendor/jquery.ui.widget.js'></script>"
+ "<script type='text/javascript' src='jquery.fileupload/js/jquery.iframe-transport.js'></script>"
+ "<script type='text/javascript' src='jquery.fileupload/js/jquery.fileupload.js'></script>"
+ "<script type='text/javascript' src='jquery.fileupload/js/main.js'></script>"
+ "<div class='container' style='margin: 0px auto'>"
- + "<h3>Request Upload<a href='Upload.help'><i class='icon-question-sign'></i></a></h3>"
+ + "<h3>Request Upload <a href='Upload.help'><i class='icon-question-sign'></i></a></h3>"
+ "<p>Please specify the file to be uploaded.</p>"
+ "<form id='Fileupload'>"
+ " <span class='btn but-success fileinput-button'>"
+ " <i class='icon-plus icon-white'></i>"
+ " <span>Select file...</span>"
+ " <input type='file'>"
+ " </span>"
+ "</form>"
+ "<table class='table' style='border:0px' id='UploadTable'>"
+ "</table>"
+ "</div>";
}
public static class PostFile extends JSONOnlyRequest {
@Override protected Response serve() {
return Response.done(new JsonObject());
}
}
}
| true | true | protected String build(Response response) {
return "<script type='text/javascript' src='jquery.fileupload/js/vendor/jquery.ui.widget.js'></script>"
+ "<script type='text/javascript' src='jquery.fileupload/js/jquery.iframe-transport.js'></script>"
+ "<script type='text/javascript' src='jquery.fileupload/js/jquery.fileupload.js'></script>"
+ "<script type='text/javascript' src='jquery.fileupload/js/main.js'></script>"
+ "<div class='container' style='margin: 0px auto'>"
+ "<h3>Request Upload<a href='Upload.help'><i class='icon-question-sign'></i></a></h3>"
+ "<p>Please specify the file to be uploaded.</p>"
+ "<form id='Fileupload'>"
+ " <span class='btn but-success fileinput-button'>"
+ " <i class='icon-plus icon-white'></i>"
+ " <span>Select file...</span>"
+ " <input type='file'>"
+ " </span>"
+ "</form>"
+ "<table class='table' style='border:0px' id='UploadTable'>"
+ "</table>"
+ "</div>";
}
| protected String build(Response response) {
return "<script type='text/javascript' src='jquery.fileupload/js/vendor/jquery.ui.widget.js'></script>"
+ "<script type='text/javascript' src='jquery.fileupload/js/jquery.iframe-transport.js'></script>"
+ "<script type='text/javascript' src='jquery.fileupload/js/jquery.fileupload.js'></script>"
+ "<script type='text/javascript' src='jquery.fileupload/js/main.js'></script>"
+ "<div class='container' style='margin: 0px auto'>"
+ "<h3>Request Upload <a href='Upload.help'><i class='icon-question-sign'></i></a></h3>"
+ "<p>Please specify the file to be uploaded.</p>"
+ "<form id='Fileupload'>"
+ " <span class='btn but-success fileinput-button'>"
+ " <i class='icon-plus icon-white'></i>"
+ " <span>Select file...</span>"
+ " <input type='file'>"
+ " </span>"
+ "</form>"
+ "<table class='table' style='border:0px' id='UploadTable'>"
+ "</table>"
+ "</div>";
}
|
diff --git a/tv_grab_nl_java/src/org/vanbest/xmltv/ProgrammeDetails.java b/tv_grab_nl_java/src/org/vanbest/xmltv/ProgrammeDetails.java
index 2638c5c..2d4b9f7 100644
--- a/tv_grab_nl_java/src/org/vanbest/xmltv/ProgrammeDetails.java
+++ b/tv_grab_nl_java/src/org/vanbest/xmltv/ProgrammeDetails.java
@@ -1,126 +1,127 @@
package org.vanbest.xmltv;
import java.io.Serializable;
public class ProgrammeDetails implements Serializable {
String db_id;
String titel;
String datum;
String btijd;
String etijd;
String synop;
String kijkwijzer;
String genre;
String presentatie;
String acteursnamen_rolverdeling;
String regisseur;
String zender_id;
public void fixup(Programme p) {
this.titel = org.apache.commons.lang.StringEscapeUtils.unescapeHtml(titel);
this.genre = org.apache.commons.lang.StringEscapeUtils.unescapeHtml(genre);
this.synop = org.apache.commons.lang.StringEscapeUtils.unescapeHtml(synop);
+ this.synop = this.synop.replaceAll("<br>", " ").
+ replaceAll("<br />", " ").
+ replaceAll("<p>", " ").
+ replaceAll("</p>", " ").
+ replaceAll("<strong>", " ").
+ replaceAll("</strong>", " ").
+ replaceAll("<em>", " ").
+ replaceAll("</em>", " ").
+ trim();
if ((synop == null || synop.isEmpty()) && ( genre == null || (!genre.toLowerCase().equals("movies") && !genre.toLowerCase().equals("film")))) {
String[] parts = p.titel.split("[[:space:]]*:[[:space:]]*", 2);
if (parts.length >= 2 ) {
titel = parts[0].trim();
p.titel = titel;
synop = parts[1].trim();
System.out.println("Splitting title to : \"" + p.titel + "\"; synop: \"" + synop + "\"");
}
}
- this.synop = this.synop.replaceAll("<br>", " ");
- this.synop = this.synop.replaceAll("<br />", " ");
- this.synop = this.synop.replaceAll("<p>", " ");
- this.synop = this.synop.replaceAll("</p>", " ");
- this.synop = this.synop.replaceAll("<strong>", " ");
- this.synop = this.synop.replaceAll("</strong>", " ");
- this.synop = this.synop.replaceAll("<em>", " ");
- this.synop = this.synop.replaceAll("</em>", " ");
this.presentatie = org.apache.commons.lang.StringEscapeUtils.unescapeHtml(presentatie);
this.acteursnamen_rolverdeling = org.apache.commons.lang.StringEscapeUtils.unescapeHtml(acteursnamen_rolverdeling);
this.regisseur = org.apache.commons.lang.StringEscapeUtils.unescapeHtml(regisseur);
}
public String getDb_id() {
return db_id;
}
public void setDb_id(String db_id) {
this.db_id = db_id;
}
public String getTitel() {
return titel;
}
public void setTitel(String titel) {
this.titel = titel;
}
public String getDatum() {
return datum;
}
public void setDatum(String datum) {
this.datum = datum;
}
public String getBtijd() {
return btijd;
}
public void setBtijd(String btijd) {
this.btijd = btijd;
}
public String getEtijd() {
return etijd;
}
public void setEtijd(String etijd) {
this.etijd = etijd;
}
public String getSynop() {
return synop;
}
public void setSynop(String synop) {
this.synop = synop;
}
public String getKijkwijzer() {
return kijkwijzer;
}
public void setKijkwijzer(String kijkwijzer) {
this.kijkwijzer = kijkwijzer;
}
public String getGenre() {
return genre;
}
public void setGenre(String genre) {
this.genre = genre;
}
public String getPresentatie() {
return presentatie;
}
public void setPresentatie(String presentatie) {
this.presentatie = presentatie;
}
public String getActeursnamen_rolverdeling() {
return acteursnamen_rolverdeling;
}
public void setActeursnamen_rolverdeling(String acteursnamen_rolverdeling) {
this.acteursnamen_rolverdeling = acteursnamen_rolverdeling;
}
public String getRegisseur() {
return regisseur;
}
public void setRegisseur(String regisseur) {
this.regisseur = regisseur;
}
public String getZender_id() {
return zender_id;
}
public void setZender_id(String zender_id) {
this.zender_id = zender_id;
}
@Override
public String toString() {
return "ProgrammeDetails [db_id=" + db_id + ", titel=" + titel
+ ", datum=" + datum + ", btijd=" + btijd + ", etijd=" + etijd
+ ", synop=" + synop + ", kijkwijzer=" + kijkwijzer
+ ", genre=" + genre + ", presentatie=" + presentatie
+ ", acteursnamen_rolverdeling=" + acteursnamen_rolverdeling
+ ", regisseur=" + regisseur + ", zender_id=" + zender_id + "]";
}
}
| false | true | public void fixup(Programme p) {
this.titel = org.apache.commons.lang.StringEscapeUtils.unescapeHtml(titel);
this.genre = org.apache.commons.lang.StringEscapeUtils.unescapeHtml(genre);
this.synop = org.apache.commons.lang.StringEscapeUtils.unescapeHtml(synop);
if ((synop == null || synop.isEmpty()) && ( genre == null || (!genre.toLowerCase().equals("movies") && !genre.toLowerCase().equals("film")))) {
String[] parts = p.titel.split("[[:space:]]*:[[:space:]]*", 2);
if (parts.length >= 2 ) {
titel = parts[0].trim();
p.titel = titel;
synop = parts[1].trim();
System.out.println("Splitting title to : \"" + p.titel + "\"; synop: \"" + synop + "\"");
}
}
this.synop = this.synop.replaceAll("<br>", " ");
this.synop = this.synop.replaceAll("<br />", " ");
this.synop = this.synop.replaceAll("<p>", " ");
this.synop = this.synop.replaceAll("</p>", " ");
this.synop = this.synop.replaceAll("<strong>", " ");
this.synop = this.synop.replaceAll("</strong>", " ");
this.synop = this.synop.replaceAll("<em>", " ");
this.synop = this.synop.replaceAll("</em>", " ");
this.presentatie = org.apache.commons.lang.StringEscapeUtils.unescapeHtml(presentatie);
this.acteursnamen_rolverdeling = org.apache.commons.lang.StringEscapeUtils.unescapeHtml(acteursnamen_rolverdeling);
this.regisseur = org.apache.commons.lang.StringEscapeUtils.unescapeHtml(regisseur);
}
| public void fixup(Programme p) {
this.titel = org.apache.commons.lang.StringEscapeUtils.unescapeHtml(titel);
this.genre = org.apache.commons.lang.StringEscapeUtils.unescapeHtml(genre);
this.synop = org.apache.commons.lang.StringEscapeUtils.unescapeHtml(synop);
this.synop = this.synop.replaceAll("<br>", " ").
replaceAll("<br />", " ").
replaceAll("<p>", " ").
replaceAll("</p>", " ").
replaceAll("<strong>", " ").
replaceAll("</strong>", " ").
replaceAll("<em>", " ").
replaceAll("</em>", " ").
trim();
if ((synop == null || synop.isEmpty()) && ( genre == null || (!genre.toLowerCase().equals("movies") && !genre.toLowerCase().equals("film")))) {
String[] parts = p.titel.split("[[:space:]]*:[[:space:]]*", 2);
if (parts.length >= 2 ) {
titel = parts[0].trim();
p.titel = titel;
synop = parts[1].trim();
System.out.println("Splitting title to : \"" + p.titel + "\"; synop: \"" + synop + "\"");
}
}
this.presentatie = org.apache.commons.lang.StringEscapeUtils.unescapeHtml(presentatie);
this.acteursnamen_rolverdeling = org.apache.commons.lang.StringEscapeUtils.unescapeHtml(acteursnamen_rolverdeling);
this.regisseur = org.apache.commons.lang.StringEscapeUtils.unescapeHtml(regisseur);
}
|
diff --git a/src/main/java/de/cismet/cids/server/search/AbstractCidsServerSearch.java b/src/main/java/de/cismet/cids/server/search/AbstractCidsServerSearch.java
index de8658c5..1cc6f470 100644
--- a/src/main/java/de/cismet/cids/server/search/AbstractCidsServerSearch.java
+++ b/src/main/java/de/cismet/cids/server/search/AbstractCidsServerSearch.java
@@ -1,170 +1,171 @@
/***************************************************
*
* cismet GmbH, Saarbruecken, Germany
*
* ... and it just works.
*
****************************************************/
package de.cismet.cids.server.search;
import Sirius.server.middleware.types.MetaClass;
import Sirius.server.newuser.User;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
/**
* Abstract class for the handling of {@link CidsServerSearch}es. For compatibility reasons this class extends the
* {@link Sirius.server.search.CidsServerSearch} class
*
* @author thorsten
* @version $Revision$, $Date$
*/
public abstract class AbstractCidsServerSearch implements CidsServerSearch {
//~ Instance fields --------------------------------------------------------
private final Map<String, Collection<MetaClass>> classesPerDomain;
private User user;
private Map activeLocalServers;
private Map<String, String> classesInSnippetsPerDomain;
private Collection<MetaClass> validClasses;
//~ Constructors -----------------------------------------------------------
/**
* Creates a new AbstractCidsServerSearch object.
*/
public AbstractCidsServerSearch() {
classesPerDomain = new HashMap<String, Collection<MetaClass>>();
classesInSnippetsPerDomain = new HashMap<String, String>();
}
//~ Methods ----------------------------------------------------------------
/**
* DOCUMENT ME!
*
* @return DOCUMENT ME!
*/
@Override
public User getUser() {
return user;
}
/**
* DOCUMENT ME!
*
* @param user DOCUMENT ME!
*/
@Override
public void setUser(final User user) {
this.user = user;
}
/**
* DOCUMENT ME!
*
* @return DOCUMENT ME!
*/
@Override
public Collection<MetaClass> getValidClasses() {
return validClasses;
}
/**
* DOCUMENT ME!
*
* @param validClasses DOCUMENT ME!
*/
@Override
public void setValidClasses(final Collection<MetaClass> validClasses) {
this.validClasses = validClasses;
classesPerDomain.clear();
for (final MetaClass mc : validClasses) {
if (classesPerDomain.containsKey(mc.getDomain())) {
classesPerDomain.get(mc.getDomain()).add(mc);
} else {
final ArrayList<MetaClass> cA = new ArrayList<MetaClass>();
cA.add(mc);
classesPerDomain.put(mc.getDomain(), cA);
}
}
classesInSnippetsPerDomain.clear();
for (final String domain : classesPerDomain.keySet()) {
final String in = StaticSearchTools.getMetaClassIdsForInStatement(classesPerDomain.get(domain));
classesInSnippetsPerDomain.put(domain, in);
}
}
/**
* DOCUMENT ME!
*
* @param classes DOCUMENT ME!
*
* @throws IllegalArgumentException DOCUMENT ME!
*/
@Override
public void setValidClassesFromStrings(final Collection<String> classes) throws IllegalArgumentException {
+ classesInSnippetsPerDomain.clear();
for (final String classString : classes) {
final String[] sa = classString.split("@");
if ((sa == null) || (sa.length != 2)) {
throw new IllegalArgumentException("Strings must be of the form of classid@DOMAINNAME");
}
final String classId = sa[0];
final String domain = sa[1];
final String inStr = classesInSnippetsPerDomain.get(domain);
if (inStr != null) {
classesInSnippetsPerDomain.put(domain, inStr + "," + classId);
} else {
classesInSnippetsPerDomain.put(domain, classId);
}
}
for (final String domain : classesInSnippetsPerDomain.keySet()) {
classesInSnippetsPerDomain.put(domain, "(" + classesInSnippetsPerDomain.get(domain) + ")");
}
}
/**
* DOCUMENT ME!
*
* @return DOCUMENT ME!
*/
@Override
public Map<String, String> getClassesInSnippetsPerDomain() {
return classesInSnippetsPerDomain;
}
/**
* DOCUMENT ME!
*
* @return DOCUMENT ME!
*/
@Override
public Map<String, Collection<MetaClass>> getClassesPerDomain() {
return classesPerDomain;
}
/**
* DOCUMENT ME!
*
* @param classesInSnippetsPerDomain DOCUMENT ME!
*/
@Override
public void setClassesInSnippetsPerDomain(final Map<String, String> classesInSnippetsPerDomain) {
this.classesInSnippetsPerDomain = classesInSnippetsPerDomain;
}
@Override
public Map getActiveLocalServers() {
return activeLocalServers;
}
@Override
public void setActiveLocalServers(final Map activeLocalServers) {
this.activeLocalServers = activeLocalServers;
}
}
| true | true | public void setValidClassesFromStrings(final Collection<String> classes) throws IllegalArgumentException {
for (final String classString : classes) {
final String[] sa = classString.split("@");
if ((sa == null) || (sa.length != 2)) {
throw new IllegalArgumentException("Strings must be of the form of classid@DOMAINNAME");
}
final String classId = sa[0];
final String domain = sa[1];
final String inStr = classesInSnippetsPerDomain.get(domain);
if (inStr != null) {
classesInSnippetsPerDomain.put(domain, inStr + "," + classId);
} else {
classesInSnippetsPerDomain.put(domain, classId);
}
}
for (final String domain : classesInSnippetsPerDomain.keySet()) {
classesInSnippetsPerDomain.put(domain, "(" + classesInSnippetsPerDomain.get(domain) + ")");
}
}
| public void setValidClassesFromStrings(final Collection<String> classes) throws IllegalArgumentException {
classesInSnippetsPerDomain.clear();
for (final String classString : classes) {
final String[] sa = classString.split("@");
if ((sa == null) || (sa.length != 2)) {
throw new IllegalArgumentException("Strings must be of the form of classid@DOMAINNAME");
}
final String classId = sa[0];
final String domain = sa[1];
final String inStr = classesInSnippetsPerDomain.get(domain);
if (inStr != null) {
classesInSnippetsPerDomain.put(domain, inStr + "," + classId);
} else {
classesInSnippetsPerDomain.put(domain, classId);
}
}
for (final String domain : classesInSnippetsPerDomain.keySet()) {
classesInSnippetsPerDomain.put(domain, "(" + classesInSnippetsPerDomain.get(domain) + ")");
}
}
|
diff --git a/src/com/dedaulus/cinematty/activities/Pages/WhatsNewPage.java b/src/com/dedaulus/cinematty/activities/Pages/WhatsNewPage.java
index 07170b8..b01f19d 100644
--- a/src/com/dedaulus/cinematty/activities/Pages/WhatsNewPage.java
+++ b/src/com/dedaulus/cinematty/activities/Pages/WhatsNewPage.java
@@ -1,248 +1,248 @@
package com.dedaulus.cinematty.activities.Pages;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.location.Location;
import android.util.Pair;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.*;
import com.actionbarsherlock.app.SherlockActivity;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuInflater;
import com.actionbarsherlock.view.MenuItem;
import com.dedaulus.cinematty.*;
import com.dedaulus.cinematty.activities.CinemaActivity;
import com.dedaulus.cinematty.activities.MovieActivity;
import com.dedaulus.cinematty.activities.adapters.CinemaItemWithScheduleAdapter;
import com.dedaulus.cinematty.activities.adapters.PosterItemAdapter;
import com.dedaulus.cinematty.framework.Cinema;
import com.dedaulus.cinematty.framework.Movie;
import com.dedaulus.cinematty.framework.MoviePoster;
import com.dedaulus.cinematty.framework.tools.*;
import java.util.*;
/**
* User: Dedaulus
* Date: 04.09.11
* Time: 20:17
*/
public class WhatsNewPage implements SliderPage, LocationClient {
private Context context;
private CinemattyApplication app;
private ApplicationSettings settings;
private ActivitiesState activitiesState;
private LocationState locationState;
private PosterItemAdapter posterItemAdapter;
private Location locationFix;
private long timeLocationFix;
private List<Cinema> closestCinemas;
private boolean showSchedule = false;
private View view;
Timer timer;
private Boolean binded = false;
private boolean visible = false;
{
closestCinemas = new ArrayList<Cinema>();
}
public WhatsNewPage(Context context, CinemattyApplication app) {
this.context = context;
this.app = app;
settings = app.getSettings();
activitiesState = app.getActivitiesState();
locationState = app.getLocationState();
}
public View getView() {
LayoutInflater layoutInflater = LayoutInflater.from(context);
view = layoutInflater.inflate(R.layout.whats_new, null, false);
return bindView(view);
}
public String getTitle() {
return context.getString(R.string.whats_new_caption);
}
public void onResume() {
if (binded) {
locationState.startLocationListening();
locationState.addLocationClient(this);
Location location = locationState.getCurrentLocation();
if (location != null) {
onLocationChanged(location);
}
//locationFix = locationState.getCurrentLocation();
//if (locationFix != null) {
// timeLocationFix = locationFix.getTime();
//}
posterItemAdapter.onResume();
}
}
public void onPause() {
locationState.removeLocationClient(this);
locationState.stopLocationListening();
}
public void onStop() {
posterItemAdapter.onStop();
}
@Override
public void setVisible(boolean visible) {
this.visible = visible;
}
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = ((SherlockActivity)context).getSupportMenuInflater();
if (!closestCinemas.isEmpty()) {
inflater.inflate(R.menu.near_menu, menu);
}
return true;
}
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_near:
showSchedule = !showSchedule;
posterItemAdapter.setClosestCinemas(closestCinemas, showSchedule);
return true;
default:
return true;
}
}
private View bindView(View view) {
GridView whatsNewGrid = (GridView)view.findViewById(R.id.whats_new_grid);
posterItemAdapter = new PosterItemAdapter(context, new ArrayList<MoviePoster>(settings.getPosters()), app.getImageRetrievers().getPosterImageRetriever());
whatsNewGrid.setAdapter(posterItemAdapter);
whatsNewGrid.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
onPosterItemClick(adapterView, view, i, l);
}
});
View cinemaView = view.findViewById(R.id.closest_cinema);
Button button = (Button)cinemaView.findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (!closestCinemas.isEmpty()) {
Cinema cinema = closestCinemas.get(0);
onCinemaItemClick(cinema);
}
}
});
binded = true;
onResume();
return view;
}
private void onCinemaItemClick(Cinema cinema) {
String cookie = UUID.randomUUID().toString();
ActivityState state = new ActivityState(ActivityState.MOVIE_LIST_W_CINEMA, cinema, null, null, null);
activitiesState.setState(cookie, state);
Intent intent = new Intent(context, CinemaActivity.class);
intent.putExtra(Constants.ACTIVITY_STATE_ID, cookie);
intent.putExtra(Constants.CINEMA_PAGE_ID, Constants.CINEMA_DESCRIPTION_PAGE_ID);
context.startActivity(intent);
}
private void onPosterItemClick(AdapterView<?> adapterView, View view, int i, long l) {
PosterItemAdapter adapter = (PosterItemAdapter)adapterView.getAdapter();
MoviePoster poster = (MoviePoster)adapter.getItem(i);
String cookie = UUID.randomUUID().toString();
ActivityState state = new ActivityState(ActivityState.MOVIE_INFO, null, poster.getMovie(), null, null);
activitiesState.setState(cookie, state);
Intent intent = new Intent(context, MovieActivity.class);
intent.putExtra(Constants.ACTIVITY_STATE_ID, cookie);
context.startActivity(intent);
}
@Override
public void onLocationChanged(Location location) {
boolean justStarted = false;
if (locationFix == null) {
justStarted = true;
locationFix = location;
timeLocationFix = location.getTime();
}
if (!justStarted) {
if (location.getTime() - timeLocationFix < Constants.TIME_CHANGED_ENOUGH) return;
timeLocationFix = location.getTime();
if (locationFix.distanceTo(location) < Constants.LOCATION_CHANGED_ENOUGH) return;
locationFix = location;
}
Set<Movie> movies = new HashSet<Movie>();
for (MoviePoster poster : settings.getPosters()) {
movies.add(poster.getMovie());
}
closestCinemas.clear();
for (Cinema cinema : settings.getCinemas().values()) {
Coordinate coordinate = cinema.getCoordinate();
if (coordinate == null) continue;
float[] distance = new float[1];
Location.distanceBetween(coordinate.latitude, coordinate.longitude, location.getLatitude(), location.getLongitude(), distance);
if (distance[0] < Constants.CLOSEST_CINEMA_DISTANCE) {
Collection<Pair<Movie, List<Calendar>>> showtimes = cinema.getShowTimes(Constants.TODAY_SCHEDULE).values();
for (Pair<Movie, List<Calendar>> showtime : showtimes) {
if (movies.contains(showtime.first)) {
closestCinemas.add(cinema);
break;
}
}
}
}
Collections.sort(closestCinemas, new CinemaComparator(CinemaSortOrder.BY_DISTANCE, location));
View cinemaView = view.findViewById(R.id.closest_cinema);
if (timer != null) {
timer.cancel();
timer = null;
}
if (closestCinemas.isEmpty()) {
cinemaView.setVisibility(View.GONE);
} else {
Button button = (Button)cinemaView.findViewById(R.id.button);
button.setText(closestCinemas.get(0).getName());
final ImageView imageView = (ImageView)cinemaView.findViewById(R.id.icon);
timer = new Timer(true);
timer.scheduleAtFixedRate(new TimerTask() {
boolean state;
@Override
public void run() {
((Activity)context).runOnUiThread(new Runnable() {
public void run() {
imageView.setImageResource(state ? R.drawable.ic_near : R.drawable.ic_near2);
}
});
state = !state;
}
}, 750, 750);
cinemaView.setVisibility(View.VISIBLE);
}
- Activity parent = (Activity)context;
+ SherlockActivity parent = (SherlockActivity)context;
parent.invalidateOptionsMenu();
}
}
| true | true | public void onLocationChanged(Location location) {
boolean justStarted = false;
if (locationFix == null) {
justStarted = true;
locationFix = location;
timeLocationFix = location.getTime();
}
if (!justStarted) {
if (location.getTime() - timeLocationFix < Constants.TIME_CHANGED_ENOUGH) return;
timeLocationFix = location.getTime();
if (locationFix.distanceTo(location) < Constants.LOCATION_CHANGED_ENOUGH) return;
locationFix = location;
}
Set<Movie> movies = new HashSet<Movie>();
for (MoviePoster poster : settings.getPosters()) {
movies.add(poster.getMovie());
}
closestCinemas.clear();
for (Cinema cinema : settings.getCinemas().values()) {
Coordinate coordinate = cinema.getCoordinate();
if (coordinate == null) continue;
float[] distance = new float[1];
Location.distanceBetween(coordinate.latitude, coordinate.longitude, location.getLatitude(), location.getLongitude(), distance);
if (distance[0] < Constants.CLOSEST_CINEMA_DISTANCE) {
Collection<Pair<Movie, List<Calendar>>> showtimes = cinema.getShowTimes(Constants.TODAY_SCHEDULE).values();
for (Pair<Movie, List<Calendar>> showtime : showtimes) {
if (movies.contains(showtime.first)) {
closestCinemas.add(cinema);
break;
}
}
}
}
Collections.sort(closestCinemas, new CinemaComparator(CinemaSortOrder.BY_DISTANCE, location));
View cinemaView = view.findViewById(R.id.closest_cinema);
if (timer != null) {
timer.cancel();
timer = null;
}
if (closestCinemas.isEmpty()) {
cinemaView.setVisibility(View.GONE);
} else {
Button button = (Button)cinemaView.findViewById(R.id.button);
button.setText(closestCinemas.get(0).getName());
final ImageView imageView = (ImageView)cinemaView.findViewById(R.id.icon);
timer = new Timer(true);
timer.scheduleAtFixedRate(new TimerTask() {
boolean state;
@Override
public void run() {
((Activity)context).runOnUiThread(new Runnable() {
public void run() {
imageView.setImageResource(state ? R.drawable.ic_near : R.drawable.ic_near2);
}
});
state = !state;
}
}, 750, 750);
cinemaView.setVisibility(View.VISIBLE);
}
Activity parent = (Activity)context;
parent.invalidateOptionsMenu();
}
| public void onLocationChanged(Location location) {
boolean justStarted = false;
if (locationFix == null) {
justStarted = true;
locationFix = location;
timeLocationFix = location.getTime();
}
if (!justStarted) {
if (location.getTime() - timeLocationFix < Constants.TIME_CHANGED_ENOUGH) return;
timeLocationFix = location.getTime();
if (locationFix.distanceTo(location) < Constants.LOCATION_CHANGED_ENOUGH) return;
locationFix = location;
}
Set<Movie> movies = new HashSet<Movie>();
for (MoviePoster poster : settings.getPosters()) {
movies.add(poster.getMovie());
}
closestCinemas.clear();
for (Cinema cinema : settings.getCinemas().values()) {
Coordinate coordinate = cinema.getCoordinate();
if (coordinate == null) continue;
float[] distance = new float[1];
Location.distanceBetween(coordinate.latitude, coordinate.longitude, location.getLatitude(), location.getLongitude(), distance);
if (distance[0] < Constants.CLOSEST_CINEMA_DISTANCE) {
Collection<Pair<Movie, List<Calendar>>> showtimes = cinema.getShowTimes(Constants.TODAY_SCHEDULE).values();
for (Pair<Movie, List<Calendar>> showtime : showtimes) {
if (movies.contains(showtime.first)) {
closestCinemas.add(cinema);
break;
}
}
}
}
Collections.sort(closestCinemas, new CinemaComparator(CinemaSortOrder.BY_DISTANCE, location));
View cinemaView = view.findViewById(R.id.closest_cinema);
if (timer != null) {
timer.cancel();
timer = null;
}
if (closestCinemas.isEmpty()) {
cinemaView.setVisibility(View.GONE);
} else {
Button button = (Button)cinemaView.findViewById(R.id.button);
button.setText(closestCinemas.get(0).getName());
final ImageView imageView = (ImageView)cinemaView.findViewById(R.id.icon);
timer = new Timer(true);
timer.scheduleAtFixedRate(new TimerTask() {
boolean state;
@Override
public void run() {
((Activity)context).runOnUiThread(new Runnable() {
public void run() {
imageView.setImageResource(state ? R.drawable.ic_near : R.drawable.ic_near2);
}
});
state = !state;
}
}, 750, 750);
cinemaView.setVisibility(View.VISIBLE);
}
SherlockActivity parent = (SherlockActivity)context;
parent.invalidateOptionsMenu();
}
|
diff --git a/src/main/javassist/CtBehavior.java b/src/main/javassist/CtBehavior.java
index 798ecab..528e14b 100644
--- a/src/main/javassist/CtBehavior.java
+++ b/src/main/javassist/CtBehavior.java
@@ -1,1097 +1,1097 @@
/*
* Javassist, a Java-bytecode translator toolkit.
* Copyright (C) 1999-2007 Shigeru Chiba. All Rights Reserved.
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. Alternatively, the contents of this file may be used under
* the terms of the GNU Lesser General Public License Version 2.1 or later.
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*/
package javassist;
import javassist.bytecode.*;
import javassist.compiler.Javac;
import javassist.compiler.CompileError;
import javassist.expr.ExprEditor;
/**
* <code>CtBehavior</code> represents a method, a constructor,
* or a static constructor (class initializer).
* It is the abstract super class of
* <code>CtMethod</code> and <code>CtConstructor</code>.
*/
public abstract class CtBehavior extends CtMember {
protected MethodInfo methodInfo;
protected CtBehavior(CtClass clazz, MethodInfo minfo) {
super(clazz);
methodInfo = minfo;
}
/**
* @param isCons true if this is a constructor.
*/
void copy(CtBehavior src, boolean isCons, ClassMap map)
throws CannotCompileException
{
CtClass declaring = declaringClass;
MethodInfo srcInfo = src.methodInfo;
CtClass srcClass = src.getDeclaringClass();
ConstPool cp = declaring.getClassFile2().getConstPool();
map = new ClassMap(map);
map.put(srcClass.getName(), declaring.getName());
try {
boolean patch = false;
CtClass srcSuper = srcClass.getSuperclass();
CtClass destSuper = declaring.getSuperclass();
String destSuperName = null;
if (srcSuper != null && destSuper != null) {
String srcSuperName = srcSuper.getName();
destSuperName = destSuper.getName();
if (!srcSuperName.equals(destSuperName))
if (srcSuperName.equals(CtClass.javaLangObject))
patch = true;
else
map.putIfNone(srcSuperName, destSuperName);
}
// a stack map table is copied from srcInfo.
methodInfo = new MethodInfo(cp, srcInfo.getName(), srcInfo, map);
if (isCons && patch)
methodInfo.setSuperclass(destSuperName);
}
catch (NotFoundException e) {
throw new CannotCompileException(e);
}
catch (BadBytecode e) {
throw new CannotCompileException(e);
}
}
protected void extendToString(StringBuffer buffer) {
buffer.append(' ');
buffer.append(getName());
buffer.append(' ');
buffer.append(methodInfo.getDescriptor());
}
/**
* Returns the method or constructor name followed by parameter types
* such as <code>javassist.CtBehavior.stBody(String)</code>.
*
* @since 3.5
*/
public abstract String getLongName();
/**
* Returns the MethodInfo representing this method/constructor in the
* class file.
*/
public MethodInfo getMethodInfo() {
declaringClass.checkModify();
return methodInfo;
}
/**
* Returns the MethodInfo representing the method/constructor in the
* class file (read only).
* Normal applications do not need calling this method. Use
* <code>getMethodInfo()</code>.
*
* <p>The <code>MethodInfo</code> object obtained by this method
* is read only. Changes to this object might not be reflected
* on a class file generated by <code>toBytecode()</code>,
* <code>toClass()</code>, etc in <code>CtClass</code>.
*
* <p>This method is available even if the <code>CtClass</code>
* containing this method is frozen. However, if the class is
* frozen, the <code>MethodInfo</code> might be also pruned.
*
* @see #getMethodInfo()
* @see CtClass#isFrozen()
* @see CtClass#prune()
*/
public MethodInfo getMethodInfo2() { return methodInfo; }
/**
* Obtains the modifiers of the method/constructor.
*
* @return modifiers encoded with
* <code>javassist.Modifier</code>.
* @see Modifier
*/
public int getModifiers() {
return AccessFlag.toModifier(methodInfo.getAccessFlags());
}
/**
* Sets the encoded modifiers of the method/constructor.
*
* <p>Changing the modifiers may cause a problem.
* For example, if a non-static method is changed to static,
* the method will be rejected by the bytecode verifier.
*
* @see Modifier
*/
public void setModifiers(int mod) {
declaringClass.checkModify();
methodInfo.setAccessFlags(AccessFlag.of(mod));
}
/**
* Returns the annotations associated with this method or constructor.
*
* @return an array of annotation-type objects.
* @see #getAvailableAnnotations()
* @since 3.1
*/
public Object[] getAnnotations() throws ClassNotFoundException {
return getAnnotations(false);
}
/**
* Returns the annotations associated with this method or constructor.
* If any annotations are not on the classpath, they are not included
* in the returned array.
*
* @return an array of annotation-type objects.
* @see #getAnnotations()
* @since 3.3
*/
public Object[] getAvailableAnnotations(){
try{
return getAnnotations(true);
}
catch (ClassNotFoundException e){
throw new RuntimeException("Unexpected exception", e);
}
}
private Object[] getAnnotations(boolean ignoreNotFound)
throws ClassNotFoundException
{
MethodInfo mi = getMethodInfo2();
AnnotationsAttribute ainfo = (AnnotationsAttribute)
mi.getAttribute(AnnotationsAttribute.invisibleTag);
AnnotationsAttribute ainfo2 = (AnnotationsAttribute)
mi.getAttribute(AnnotationsAttribute.visibleTag);
return CtClassType.toAnnotationType(ignoreNotFound,
getDeclaringClass().getClassPool(),
ainfo, ainfo2);
}
/**
* Returns the parameter annotations associated with this method or constructor.
*
* @return an array of annotation-type objects. The length of the returned array is
* equal to the number of the formal parameters. If each parameter has no
* annotation, the elements of the returned array are empty arrays.
*
* @see #getAvailableParameterAnnotations()
* @see #getAnnotations()
* @since 3.1
*/
public Object[][] getParameterAnnotations() throws ClassNotFoundException {
return getParameterAnnotations(false);
}
/**
* Returns the parameter annotations associated with this method or constructor.
* If any annotations are not on the classpath, they are not included in the
* returned array.
*
* @return an array of annotation-type objects. The length of the returned array is
* equal to the number of the formal parameters. If each parameter has no
* annotation, the elements of the returned array are empty arrays.
*
* @see #getParameterAnnotations()
* @see #getAvailableAnnotations()
* @since 3.3
*/
public Object[][] getAvailableParameterAnnotations(){
try {
return getParameterAnnotations(true);
}
catch(ClassNotFoundException e) {
throw new RuntimeException("Unexpected exception", e);
}
}
Object[][] getParameterAnnotations(boolean ignoreNotFound)
throws ClassNotFoundException
{
MethodInfo mi = getMethodInfo2();
ParameterAnnotationsAttribute ainfo = (ParameterAnnotationsAttribute)
mi.getAttribute(ParameterAnnotationsAttribute.invisibleTag);
ParameterAnnotationsAttribute ainfo2 = (ParameterAnnotationsAttribute)
mi.getAttribute(ParameterAnnotationsAttribute.visibleTag);
return CtClassType.toAnnotationType(ignoreNotFound,
getDeclaringClass().getClassPool(),
ainfo, ainfo2, mi);
}
/**
* Obtains parameter types of this method/constructor.
*/
public CtClass[] getParameterTypes() throws NotFoundException {
return Descriptor.getParameterTypes(methodInfo.getDescriptor(),
declaringClass.getClassPool());
}
/**
* Obtains the type of the returned value.
*/
CtClass getReturnType0() throws NotFoundException {
return Descriptor.getReturnType(methodInfo.getDescriptor(),
declaringClass.getClassPool());
}
/**
* Returns the method signature (the parameter types
* and the return type).
* The method signature is represented by a character string
* called method descriptor, which is defined in the JVM specification.
* If two methods/constructors have
* the same parameter types
* and the return type, <code>getSignature()</code> returns the
* same string (the return type of constructors is <code>void</code>).
*
* <p>Note that the returned string is not the type signature
* contained in the <code>SignatureAttirbute</code>. It is
* a descriptor. To obtain a type signature, call the following
* methods:
*
* <ul><pre>getMethodInfo().getAttribute(SignatureAttribute.tag)
* </pre></ul>
*
* @see javassist.bytecode.Descriptor
* @see javassist.bytecode.SignatureAttribute
*/
public String getSignature() {
return methodInfo.getDescriptor();
}
/**
* Obtains exceptions that this method/constructor may throw.
*
* @return a zero-length array if there is no throws clause.
*/
public CtClass[] getExceptionTypes() throws NotFoundException {
String[] exceptions;
ExceptionsAttribute ea = methodInfo.getExceptionsAttribute();
if (ea == null)
exceptions = null;
else
exceptions = ea.getExceptions();
return declaringClass.getClassPool().get(exceptions);
}
/**
* Sets exceptions that this method/constructor may throw.
*/
public void setExceptionTypes(CtClass[] types) throws NotFoundException {
declaringClass.checkModify();
if (types == null || types.length == 0) {
methodInfo.removeExceptionsAttribute();
return;
}
String[] names = new String[types.length];
for (int i = 0; i < types.length; ++i)
names[i] = types[i].getName();
ExceptionsAttribute ea = methodInfo.getExceptionsAttribute();
if (ea == null) {
ea = new ExceptionsAttribute(methodInfo.getConstPool());
methodInfo.setExceptionsAttribute(ea);
}
ea.setExceptions(names);
}
/**
* Returns true if the body is empty.
*/
public abstract boolean isEmpty();
/**
* Sets a method/constructor body.
*
* @param src the source code representing the body.
* It must be a single statement or block.
* If it is <code>null</code>, the substituted
* body does nothing except returning zero or null.
*/
public void setBody(String src) throws CannotCompileException {
setBody(src, null, null);
}
/**
* Sets a method/constructor body.
*
* @param src the source code representing the body.
* It must be a single statement or block.
* If it is <code>null</code>, the substituted
* body does nothing except returning zero or null.
* @param delegateObj the source text specifying the object
* that is called on by <code>$proceed()</code>.
* @param delegateMethod the name of the method
* that is called by <code>$proceed()</code>.
*/
public void setBody(String src,
String delegateObj, String delegateMethod)
throws CannotCompileException
{
CtClass cc = declaringClass;
cc.checkModify();
try {
Javac jv = new Javac(cc);
if (delegateMethod != null)
jv.recordProceed(delegateObj, delegateMethod);
Bytecode b = jv.compileBody(this, src);
methodInfo.setCodeAttribute(b.toCodeAttribute());
methodInfo.setAccessFlags(methodInfo.getAccessFlags()
& ~AccessFlag.ABSTRACT);
methodInfo.rebuildStackMapIf6(cc.getClassPool(), cc.getClassFile2());
declaringClass.rebuildClassFile();
}
catch (CompileError e) {
throw new CannotCompileException(e);
} catch (BadBytecode e) {
throw new CannotCompileException(e);
}
}
static void setBody0(CtClass srcClass, MethodInfo srcInfo,
CtClass destClass, MethodInfo destInfo,
ClassMap map)
throws CannotCompileException
{
destClass.checkModify();
map = new ClassMap(map);
map.put(srcClass.getName(), destClass.getName());
try {
CodeAttribute cattr = srcInfo.getCodeAttribute();
if (cattr != null) {
ConstPool cp = destInfo.getConstPool();
CodeAttribute ca = (CodeAttribute)cattr.copy(cp, map);
destInfo.setCodeAttribute(ca);
// a stack map table is copied to destInfo.
}
}
catch (CodeAttribute.RuntimeCopyException e) {
/* the exception may be thrown by copy() in CodeAttribute.
*/
throw new CannotCompileException(e);
}
destInfo.setAccessFlags(destInfo.getAccessFlags()
& ~AccessFlag.ABSTRACT);
destClass.rebuildClassFile();
}
/**
* Obtains an attribute with the given name.
* If that attribute is not found in the class file, this
* method returns null.
*
* <p>Note that an attribute is a data block specified by
* the class file format. It is not an annotation.
* See {@link javassist.bytecode.AttributeInfo}.
*
* @param name attribute name
*/
public byte[] getAttribute(String name) {
AttributeInfo ai = methodInfo.getAttribute(name);
if (ai == null)
return null;
else
return ai.get();
}
/**
* Adds an attribute. The attribute is saved in the class file.
*
* <p>Note that an attribute is a data block specified by
* the class file format. It is not an annotation.
* See {@link javassist.bytecode.AttributeInfo}.
*
* @param name attribute name
* @param data attribute value
*/
public void setAttribute(String name, byte[] data) {
declaringClass.checkModify();
methodInfo.addAttribute(new AttributeInfo(methodInfo.getConstPool(),
name, data));
}
/**
* Declares to use <code>$cflow</code> for this method/constructor.
* If <code>$cflow</code> is used, the class files modified
* with Javassist requires a support class
* <code>javassist.runtime.Cflow</code> at runtime
* (other Javassist classes are not required at runtime).
*
* <p>Every <code>$cflow</code> variable is given a unique name.
* For example, if the given name is <code>"Point.paint"</code>,
* then the variable is indicated by <code>$cflow(Point.paint)</code>.
*
* @param name <code>$cflow</code> name. It can include
* alphabets, numbers, <code>_</code>,
* <code>$</code>, and <code>.</code> (dot).
*
* @see javassist.runtime.Cflow
*/
public void useCflow(String name) throws CannotCompileException {
CtClass cc = declaringClass;
cc.checkModify();
ClassPool pool = cc.getClassPool();
String fname;
int i = 0;
while (true) {
fname = "_cflow$" + i++;
try {
cc.getDeclaredField(fname);
}
catch(NotFoundException e) {
break;
}
}
pool.recordCflow(name, declaringClass.getName(), fname);
try {
CtClass type = pool.get("javassist.runtime.Cflow");
CtField field = new CtField(type, fname, cc);
field.setModifiers(Modifier.PUBLIC | Modifier.STATIC);
cc.addField(field, CtField.Initializer.byNew(type));
insertBefore(fname + ".enter();", false);
String src = fname + ".exit();";
insertAfter(src, true);
}
catch (NotFoundException e) {
throw new CannotCompileException(e);
}
}
/**
* Declares a new local variable. The scope of this variable is the
* whole method body. The initial value of that variable is not set.
* The declared variable can be accessed in the code snippet inserted
* by <code>insertBefore()</code>, <code>insertAfter()</code>, etc.
*
* <p>If the second parameter <code>asFinally</code> to
* <code>insertAfter()</code> is true, the declared local variable
* is not visible from the code inserted by <code>insertAfter()</code>.
*
* @param name the name of the variable
* @param type the type of the variable
* @see #insertBefore(String)
* @see #insertAfter(String)
*/
public void addLocalVariable(String name, CtClass type)
throws CannotCompileException
{
declaringClass.checkModify();
ConstPool cp = methodInfo.getConstPool();
CodeAttribute ca = methodInfo.getCodeAttribute();
if (ca == null)
throw new CannotCompileException("no method body");
LocalVariableAttribute va = (LocalVariableAttribute)ca.getAttribute(
LocalVariableAttribute.tag);
if (va == null) {
va = new LocalVariableAttribute(cp);
ca.getAttributes().add(va);
}
int maxLocals = ca.getMaxLocals();
String desc = Descriptor.of(type);
va.addEntry(0, ca.getCodeLength(),
cp.addUtf8Info(name), cp.addUtf8Info(desc), maxLocals);
ca.setMaxLocals(maxLocals + Descriptor.dataSize(desc));
}
/**
* Inserts a new parameter, which becomes the first parameter.
*/
public void insertParameter(CtClass type)
throws CannotCompileException
{
declaringClass.checkModify();
String desc = methodInfo.getDescriptor();
String desc2 = Descriptor.insertParameter(type, desc);
try {
addParameter2(Modifier.isStatic(getModifiers()) ? 0 : 1, type, desc);
}
catch (BadBytecode e) {
throw new CannotCompileException(e);
}
methodInfo.setDescriptor(desc2);
}
/**
* Appends a new parameter, which becomes the last parameter.
*/
public void addParameter(CtClass type)
throws CannotCompileException
{
declaringClass.checkModify();
String desc = methodInfo.getDescriptor();
String desc2 = Descriptor.appendParameter(type, desc);
int offset = Modifier.isStatic(getModifiers()) ? 0 : 1;
try {
addParameter2(offset + Descriptor.paramSize(desc), type, desc);
}
catch (BadBytecode e) {
throw new CannotCompileException(e);
}
methodInfo.setDescriptor(desc2);
}
private void addParameter2(int where, CtClass type, String desc)
throws BadBytecode
{
CodeAttribute ca = methodInfo.getCodeAttribute();
if (ca != null) {
int size = 1;
char typeDesc = 'L';
int classInfo = 0;
if (type.isPrimitive()) {
CtPrimitiveType cpt = (CtPrimitiveType)type;
size = cpt.getDataSize();
typeDesc = cpt.getDescriptor();
}
else
classInfo = methodInfo.getConstPool().addClassInfo(type);
ca.insertLocalVar(where, size);
LocalVariableAttribute va
= (LocalVariableAttribute)
ca.getAttribute(LocalVariableAttribute.tag);
if (va != null)
va.shiftIndex(where, size);
StackMapTable smt = (StackMapTable)ca.getAttribute(StackMapTable.tag);
if (smt != null)
smt.insertLocal(where, StackMapTable.typeTagOf(typeDesc), classInfo);
}
}
/**
* Modifies the method/constructor body.
*
* @param converter specifies how to modify.
*/
public void instrument(CodeConverter converter)
throws CannotCompileException
{
declaringClass.checkModify();
ConstPool cp = methodInfo.getConstPool();
converter.doit(getDeclaringClass(), methodInfo, cp);
}
/**
* Modifies the method/constructor body.
*
* @param editor specifies how to modify.
*/
public void instrument(ExprEditor editor)
throws CannotCompileException
{
// if the class is not frozen,
// does not turn the modified flag on.
if (declaringClass.isFrozen())
declaringClass.checkModify();
if (editor.doit(declaringClass, methodInfo))
declaringClass.checkModify();
}
/**
* Inserts bytecode at the beginning of the body.
*
* <p>If this object represents a constructor,
* the bytecode is inserted before
* a constructor in the super class or this class is called.
* Therefore, the inserted bytecode is subject to constraints described
* in Section 4.8.2 of The Java Virtual Machine Specification (2nd ed).
* For example, it cannot access instance fields or methods although
* it may assign a value to an instance field directly declared in this
* class. Accessing static fields and methods is allowed.
* Use <code>insertBeforeBody()</code> in <code>CtConstructor</code>.
*
* @param src the source code representing the inserted bytecode.
* It must be a single statement or block.
* @see CtConstructor#insertBeforeBody(String)
*/
public void insertBefore(String src) throws CannotCompileException {
insertBefore(src, true);
}
private void insertBefore(String src, boolean rebuild)
throws CannotCompileException
{
CtClass cc = declaringClass;
cc.checkModify();
CodeAttribute ca = methodInfo.getCodeAttribute();
if (ca == null)
throw new CannotCompileException("no method body");
CodeIterator iterator = ca.iterator();
Javac jv = new Javac(cc);
try {
int nvars = jv.recordParams(getParameterTypes(),
Modifier.isStatic(getModifiers()));
jv.recordParamNames(ca, nvars);
jv.recordLocalVariables(ca, 0);
jv.recordType(getReturnType0());
jv.compileStmnt(src);
Bytecode b = jv.getBytecode();
int stack = b.getMaxStack();
int locals = b.getMaxLocals();
if (stack > ca.getMaxStack())
ca.setMaxStack(stack);
if (locals > ca.getMaxLocals())
ca.setMaxLocals(locals);
int pos = iterator.insertEx(b.get());
iterator.insert(b.getExceptionTable(), pos);
if (rebuild)
methodInfo.rebuildStackMapIf6(cc.getClassPool(), cc.getClassFile2());
}
catch (NotFoundException e) {
throw new CannotCompileException(e);
}
catch (CompileError e) {
throw new CannotCompileException(e);
}
catch (BadBytecode e) {
throw new CannotCompileException(e);
}
}
/**
* Inserts bytecode at the end of the body.
* The bytecode is inserted just before every return insturction.
* It is not executed when an exception is thrown.
*
* @param src the source code representing the inserted bytecode.
* It must be a single statement or block.
*/
public void insertAfter(String src)
throws CannotCompileException
{
insertAfter(src, false);
}
/**
* Inserts bytecode at the end of the body.
* The bytecode is inserted just before every return insturction.
*
* @param src the source code representing the inserted bytecode.
* It must be a single statement or block.
* @param asFinally true if the inserted bytecode is executed
* not only when the control normally returns
* but also when an exception is thrown.
* If this parameter is true, the inserted code cannot
* access local variables.
*/
public void insertAfter(String src, boolean asFinally)
throws CannotCompileException
{
CtClass cc = declaringClass;
cc.checkModify();
ConstPool pool = methodInfo.getConstPool();
CodeAttribute ca = methodInfo.getCodeAttribute();
if (ca == null)
throw new CannotCompileException("no method body");
CodeIterator iterator = ca.iterator();
int retAddr = ca.getMaxLocals();
Bytecode b = new Bytecode(pool, 0, retAddr + 1);
b.setStackDepth(ca.getMaxStack() + 1);
Javac jv = new Javac(b, cc);
try {
int nvars = jv.recordParams(getParameterTypes(),
Modifier.isStatic(getModifiers()));
jv.recordParamNames(ca, nvars);
CtClass rtype = getReturnType0();
int varNo = jv.recordReturnType(rtype, true);
jv.recordLocalVariables(ca, 0);
// finally clause for exceptions
int handlerLen = insertAfterHandler(asFinally, b, rtype, varNo,
jv, src);
// finally clause for normal termination
insertAfterAdvice(b, jv, src, pool, rtype, varNo);
ca.setMaxStack(b.getMaxStack());
ca.setMaxLocals(b.getMaxLocals());
int gapPos = iterator.append(b.get());
iterator.append(b.getExceptionTable(), gapPos);
if (asFinally)
- ca.getExceptionTable().add(0, gapPos, gapPos, 0);
+ ca.getExceptionTable().add(getStartPosOfBody(ca), gapPos, gapPos, 0);
int gapLen = iterator.getCodeLength() - gapPos - handlerLen;
int subr = iterator.getCodeLength() - gapLen;
while (iterator.hasNext()) {
int pos = iterator.next();
if (pos >= subr)
break;
int c = iterator.byteAt(pos);
if (c == Opcode.ARETURN || c == Opcode.IRETURN
|| c == Opcode.FRETURN || c == Opcode.LRETURN
|| c == Opcode.DRETURN || c == Opcode.RETURN) {
insertGoto(iterator, subr, pos);
subr = iterator.getCodeLength() - gapLen;
}
}
methodInfo.rebuildStackMapIf6(cc.getClassPool(), cc.getClassFile2());
}
catch (NotFoundException e) {
throw new CannotCompileException(e);
}
catch (CompileError e) {
throw new CannotCompileException(e);
}
catch (BadBytecode e) {
throw new CannotCompileException(e);
}
}
private void insertAfterAdvice(Bytecode code, Javac jv, String src,
ConstPool cp, CtClass rtype, int varNo)
throws CompileError
{
if (rtype == CtClass.voidType) {
code.addOpcode(Opcode.ACONST_NULL);
code.addAstore(varNo);
jv.compileStmnt(src);
code.addOpcode(Opcode.RETURN);
if (code.getMaxLocals() < 1)
code.setMaxLocals(1);
}
else {
code.addStore(varNo, rtype);
jv.compileStmnt(src);
code.addLoad(varNo, rtype);
if (rtype.isPrimitive())
code.addOpcode(((CtPrimitiveType)rtype).getReturnOp());
else
code.addOpcode(Opcode.ARETURN);
}
}
private void insertGoto(CodeIterator iterator, int subr, int pos)
throws BadBytecode
{
// the gap length might be a multiple of 4.
boolean wide = subr + 4 - pos > Short.MAX_VALUE;
int gapSize = iterator.insertGap(pos, wide ? 4 : 2);
if (wide) {
iterator.writeByte(Opcode.GOTO_W, pos);
iterator.write32bit(subr - pos + gapSize, pos + 1);
}
else {
iterator.writeByte(Opcode.GOTO, pos);
iterator.write16bit(subr - pos + gapSize, pos + 1);
}
}
/* insert a finally clause
*/
private int insertAfterHandler(boolean asFinally, Bytecode b,
CtClass rtype, int returnVarNo,
Javac javac, String src)
throws CompileError
{
if (!asFinally)
return 0;
int var = b.getMaxLocals();
b.incMaxLocals(1);
int pc = b.currentPc();
b.addAstore(var); // store an exception
if (rtype.isPrimitive()) {
char c = ((CtPrimitiveType)rtype).getDescriptor();
if (c == 'D') {
b.addDconst(0.0);
b.addDstore(returnVarNo);
}
else if (c == 'F') {
b.addFconst(0);
b.addFstore(returnVarNo);
}
else if (c == 'J') {
b.addLconst(0);
b.addLstore(returnVarNo);
}
else if (c == 'V') {
b.addOpcode(Opcode.ACONST_NULL);
b.addAstore(returnVarNo);
}
else { // int, boolean, char, short, ...
b.addIconst(0);
b.addIstore(returnVarNo);
}
}
else {
b.addOpcode(Opcode.ACONST_NULL);
b.addAstore(returnVarNo);
}
javac.compileStmnt(src);
b.addAload(var);
b.addOpcode(Opcode.ATHROW);
return b.currentPc() - pc;
}
/* -- OLD version --
public void insertAfter(String src) throws CannotCompileException {
declaringClass.checkModify();
CodeAttribute ca = methodInfo.getCodeAttribute();
CodeIterator iterator = ca.iterator();
Bytecode b = new Bytecode(methodInfo.getConstPool(),
ca.getMaxStack(), ca.getMaxLocals());
b.setStackDepth(ca.getMaxStack());
Javac jv = new Javac(b, declaringClass);
try {
jv.recordParams(getParameterTypes(),
Modifier.isStatic(getModifiers()));
CtClass rtype = getReturnType0();
int varNo = jv.recordReturnType(rtype, true);
boolean isVoid = rtype == CtClass.voidType;
if (isVoid) {
b.addOpcode(Opcode.ACONST_NULL);
b.addAstore(varNo);
jv.compileStmnt(src);
}
else {
b.addStore(varNo, rtype);
jv.compileStmnt(src);
b.addLoad(varNo, rtype);
}
byte[] code = b.get();
ca.setMaxStack(b.getMaxStack());
ca.setMaxLocals(b.getMaxLocals());
while (iterator.hasNext()) {
int pos = iterator.next();
int c = iterator.byteAt(pos);
if (c == Opcode.ARETURN || c == Opcode.IRETURN
|| c == Opcode.FRETURN || c == Opcode.LRETURN
|| c == Opcode.DRETURN || c == Opcode.RETURN)
iterator.insert(pos, code);
}
}
catch (NotFoundException e) {
throw new CannotCompileException(e);
}
catch (CompileError e) {
throw new CannotCompileException(e);
}
catch (BadBytecode e) {
throw new CannotCompileException(e);
}
}
*/
/**
* Adds a catch clause that handles an exception thrown in the
* body. The catch clause must end with a return or throw statement.
*
* @param src the source code representing the catch clause.
* It must be a single statement or block.
* @param exceptionType the type of the exception handled by the
* catch clause.
*/
public void addCatch(String src, CtClass exceptionType)
throws CannotCompileException
{
addCatch(src, exceptionType, "$e");
}
/**
* Adds a catch clause that handles an exception thrown in the
* body. The catch clause must end with a return or throw statement.
*
* @param src the source code representing the catch clause.
* It must be a single statement or block.
* @param exceptionType the type of the exception handled by the
* catch clause.
* @param exceptionName the name of the variable containing the
* caught exception, for example,
* <code>$e</code>.
*/
public void addCatch(String src, CtClass exceptionType,
String exceptionName)
throws CannotCompileException
{
CtClass cc = declaringClass;
cc.checkModify();
ConstPool cp = methodInfo.getConstPool();
CodeAttribute ca = methodInfo.getCodeAttribute();
CodeIterator iterator = ca.iterator();
Bytecode b = new Bytecode(cp, ca.getMaxStack(), ca.getMaxLocals());
b.setStackDepth(1);
Javac jv = new Javac(b, cc);
try {
jv.recordParams(getParameterTypes(),
Modifier.isStatic(getModifiers()));
int var = jv.recordVariable(exceptionType, exceptionName);
b.addAstore(var);
jv.compileStmnt(src);
int stack = b.getMaxStack();
int locals = b.getMaxLocals();
if (stack > ca.getMaxStack())
ca.setMaxStack(stack);
if (locals > ca.getMaxLocals())
ca.setMaxLocals(locals);
int len = iterator.getCodeLength();
int pos = iterator.append(b.get());
ca.getExceptionTable().add(getStartPosOfBody(ca), len, len,
cp.addClassInfo(exceptionType));
iterator.append(b.getExceptionTable(), pos);
methodInfo.rebuildStackMapIf6(cc.getClassPool(), cc.getClassFile2());
}
catch (NotFoundException e) {
throw new CannotCompileException(e);
}
catch (CompileError e) {
throw new CannotCompileException(e);
} catch (BadBytecode e) {
throw new CannotCompileException(e);
}
}
/* CtConstructor overrides this method.
*/
int getStartPosOfBody(CodeAttribute ca) throws CannotCompileException {
return 0;
}
/**
* Inserts bytecode at the specified line in the body.
* It is equivalent to:
*
* <br><code>insertAt(lineNum, true, src)</code>
*
* <br>See this method as well.
*
* @param lineNum the line number. The bytecode is inserted at the
* beginning of the code at the line specified by this
* line number.
* @param src the source code representing the inserted bytecode.
* It must be a single statement or block.
* @return the line number at which the bytecode has been inserted.
*
* @see CtBehavior#insertAt(int,boolean,String)
*/
public int insertAt(int lineNum, String src)
throws CannotCompileException
{
return insertAt(lineNum, true, src);
}
/**
* Inserts bytecode at the specified line in the body.
*
* <p>If there is not
* a statement at the specified line, the bytecode might be inserted
* at the line including the first statement after that line specified.
* For example, if there is only a closing brace at that line, the
* bytecode would be inserted at another line below.
* To know exactly where the bytecode will be inserted, call with
* <code>modify</code> set to <code>false</code>.
*
* @param lineNum the line number. The bytecode is inserted at the
* beginning of the code at the line specified by this
* line number.
* @param modify if false, this method does not insert the bytecode.
* It instead only returns the line number at which
* the bytecode would be inserted.
* @param src the source code representing the inserted bytecode.
* It must be a single statement or block.
* If modify is false, the value of src can be null.
* @return the line number at which the bytecode has been inserted.
*/
public int insertAt(int lineNum, boolean modify, String src)
throws CannotCompileException
{
CodeAttribute ca = methodInfo.getCodeAttribute();
if (ca == null)
throw new CannotCompileException("no method body");
LineNumberAttribute ainfo
= (LineNumberAttribute)ca.getAttribute(LineNumberAttribute.tag);
if (ainfo == null)
throw new CannotCompileException("no line number info");
LineNumberAttribute.Pc pc = ainfo.toNearPc(lineNum);
lineNum = pc.line;
int index = pc.index;
if (!modify)
return lineNum;
CtClass cc = declaringClass;
cc.checkModify();
CodeIterator iterator = ca.iterator();
Javac jv = new Javac(cc);
try {
jv.recordLocalVariables(ca, index);
jv.recordParams(getParameterTypes(),
Modifier.isStatic(getModifiers()));
jv.setMaxLocals(ca.getMaxLocals());
jv.compileStmnt(src);
Bytecode b = jv.getBytecode();
int locals = b.getMaxLocals();
int stack = b.getMaxStack();
ca.setMaxLocals(locals);
/* We assume that there is no values in the operand stack
* at the position where the bytecode is inserted.
*/
if (stack > ca.getMaxStack())
ca.setMaxStack(stack);
iterator.insert(index, b.get());
iterator.insert(b.getExceptionTable(), index);
methodInfo.rebuildStackMapIf6(cc.getClassPool(), cc.getClassFile2());
return lineNum;
}
catch (NotFoundException e) {
throw new CannotCompileException(e);
}
catch (CompileError e) {
throw new CannotCompileException(e);
}
catch (BadBytecode e) {
throw new CannotCompileException(e);
}
}
}
| true | true | public void insertAfter(String src, boolean asFinally)
throws CannotCompileException
{
CtClass cc = declaringClass;
cc.checkModify();
ConstPool pool = methodInfo.getConstPool();
CodeAttribute ca = methodInfo.getCodeAttribute();
if (ca == null)
throw new CannotCompileException("no method body");
CodeIterator iterator = ca.iterator();
int retAddr = ca.getMaxLocals();
Bytecode b = new Bytecode(pool, 0, retAddr + 1);
b.setStackDepth(ca.getMaxStack() + 1);
Javac jv = new Javac(b, cc);
try {
int nvars = jv.recordParams(getParameterTypes(),
Modifier.isStatic(getModifiers()));
jv.recordParamNames(ca, nvars);
CtClass rtype = getReturnType0();
int varNo = jv.recordReturnType(rtype, true);
jv.recordLocalVariables(ca, 0);
// finally clause for exceptions
int handlerLen = insertAfterHandler(asFinally, b, rtype, varNo,
jv, src);
// finally clause for normal termination
insertAfterAdvice(b, jv, src, pool, rtype, varNo);
ca.setMaxStack(b.getMaxStack());
ca.setMaxLocals(b.getMaxLocals());
int gapPos = iterator.append(b.get());
iterator.append(b.getExceptionTable(), gapPos);
if (asFinally)
ca.getExceptionTable().add(0, gapPos, gapPos, 0);
int gapLen = iterator.getCodeLength() - gapPos - handlerLen;
int subr = iterator.getCodeLength() - gapLen;
while (iterator.hasNext()) {
int pos = iterator.next();
if (pos >= subr)
break;
int c = iterator.byteAt(pos);
if (c == Opcode.ARETURN || c == Opcode.IRETURN
|| c == Opcode.FRETURN || c == Opcode.LRETURN
|| c == Opcode.DRETURN || c == Opcode.RETURN) {
insertGoto(iterator, subr, pos);
subr = iterator.getCodeLength() - gapLen;
}
}
methodInfo.rebuildStackMapIf6(cc.getClassPool(), cc.getClassFile2());
}
catch (NotFoundException e) {
throw new CannotCompileException(e);
}
catch (CompileError e) {
throw new CannotCompileException(e);
}
catch (BadBytecode e) {
throw new CannotCompileException(e);
}
}
| public void insertAfter(String src, boolean asFinally)
throws CannotCompileException
{
CtClass cc = declaringClass;
cc.checkModify();
ConstPool pool = methodInfo.getConstPool();
CodeAttribute ca = methodInfo.getCodeAttribute();
if (ca == null)
throw new CannotCompileException("no method body");
CodeIterator iterator = ca.iterator();
int retAddr = ca.getMaxLocals();
Bytecode b = new Bytecode(pool, 0, retAddr + 1);
b.setStackDepth(ca.getMaxStack() + 1);
Javac jv = new Javac(b, cc);
try {
int nvars = jv.recordParams(getParameterTypes(),
Modifier.isStatic(getModifiers()));
jv.recordParamNames(ca, nvars);
CtClass rtype = getReturnType0();
int varNo = jv.recordReturnType(rtype, true);
jv.recordLocalVariables(ca, 0);
// finally clause for exceptions
int handlerLen = insertAfterHandler(asFinally, b, rtype, varNo,
jv, src);
// finally clause for normal termination
insertAfterAdvice(b, jv, src, pool, rtype, varNo);
ca.setMaxStack(b.getMaxStack());
ca.setMaxLocals(b.getMaxLocals());
int gapPos = iterator.append(b.get());
iterator.append(b.getExceptionTable(), gapPos);
if (asFinally)
ca.getExceptionTable().add(getStartPosOfBody(ca), gapPos, gapPos, 0);
int gapLen = iterator.getCodeLength() - gapPos - handlerLen;
int subr = iterator.getCodeLength() - gapLen;
while (iterator.hasNext()) {
int pos = iterator.next();
if (pos >= subr)
break;
int c = iterator.byteAt(pos);
if (c == Opcode.ARETURN || c == Opcode.IRETURN
|| c == Opcode.FRETURN || c == Opcode.LRETURN
|| c == Opcode.DRETURN || c == Opcode.RETURN) {
insertGoto(iterator, subr, pos);
subr = iterator.getCodeLength() - gapLen;
}
}
methodInfo.rebuildStackMapIf6(cc.getClassPool(), cc.getClassFile2());
}
catch (NotFoundException e) {
throw new CannotCompileException(e);
}
catch (CompileError e) {
throw new CannotCompileException(e);
}
catch (BadBytecode e) {
throw new CannotCompileException(e);
}
}
|
diff --git a/hale/eu.esdihumboldt.hale.rcp.wizards.functions.core/src/eu/esdihumboldt/hale/rcp/wizards/functions/core/reference/CreateReferenceWizardFactory.java b/hale/eu.esdihumboldt.hale.rcp.wizards.functions.core/src/eu/esdihumboldt/hale/rcp/wizards/functions/core/reference/CreateReferenceWizardFactory.java
index 6a9ae2231..42ebf4519 100644
--- a/hale/eu.esdihumboldt.hale.rcp.wizards.functions.core/src/eu/esdihumboldt/hale/rcp/wizards/functions/core/reference/CreateReferenceWizardFactory.java
+++ b/hale/eu.esdihumboldt.hale.rcp.wizards.functions.core/src/eu/esdihumboldt/hale/rcp/wizards/functions/core/reference/CreateReferenceWizardFactory.java
@@ -1,57 +1,57 @@
/*
* HUMBOLDT: A Framework for Data Harmonisation and Service Integration.
* EU Integrated Project #030962 01.10.2006 - 30.09.2010
*
* For more information on the project, please refer to the this web site:
* http://www.esdi-humboldt.eu
*
* LICENSE: For information on the license under which this program is
* available, please refer to http:/www.esdi-humboldt.eu/license.html#core
* (c) the HUMBOLDT Consortium, 2007 to 2010.
*/
package eu.esdihumboldt.hale.rcp.wizards.functions.core.reference;
import eu.esdihumboldt.hale.rcp.views.model.SchemaItem;
import eu.esdihumboldt.hale.rcp.views.model.TreeObject.TreeObjectType;
import eu.esdihumboldt.hale.rcp.wizards.functions.AlignmentInfo;
import eu.esdihumboldt.hale.rcp.wizards.functions.FunctionWizard;
import eu.esdihumboldt.hale.rcp.wizards.functions.FunctionWizardFactory;
/**
* @author Thorsten Reitz
* @version $Id$
*/
public class CreateReferenceWizardFactory
implements FunctionWizardFactory {
@Override
public FunctionWizard createWizard(AlignmentInfo selection) {
return new CreateReferenceWizard(selection);
}
@Override
public boolean supports(AlignmentInfo selection) {
if (selection.getSourceItemCount() != 1 || selection.getTargetItemCount() != 1) {
return false;
}
SchemaItem target = selection.getFirstTargetItem();
SchemaItem source = selection.getFirstSourceItem();
- if (!target.isAttribute() && !source.isAttribute()) {
+ if (!target.isAttribute() || !source.isAttribute()) {
return false;
}
// target item must be a ReferenceType
if (!target.getPropertyType().getName().getLocalPart().equals("ReferenceType")) {
return false;
}
// source item must be alphanumeric
if (source.getType().equals(TreeObjectType.NUMERIC_ATTRIBUTE)
|| source.getType().equals(TreeObjectType.STRING_ATTRIBUTE)) {
return true;
}
return false;
}
}
| true | true | public boolean supports(AlignmentInfo selection) {
if (selection.getSourceItemCount() != 1 || selection.getTargetItemCount() != 1) {
return false;
}
SchemaItem target = selection.getFirstTargetItem();
SchemaItem source = selection.getFirstSourceItem();
if (!target.isAttribute() && !source.isAttribute()) {
return false;
}
// target item must be a ReferenceType
if (!target.getPropertyType().getName().getLocalPart().equals("ReferenceType")) {
return false;
}
// source item must be alphanumeric
if (source.getType().equals(TreeObjectType.NUMERIC_ATTRIBUTE)
|| source.getType().equals(TreeObjectType.STRING_ATTRIBUTE)) {
return true;
}
return false;
}
| public boolean supports(AlignmentInfo selection) {
if (selection.getSourceItemCount() != 1 || selection.getTargetItemCount() != 1) {
return false;
}
SchemaItem target = selection.getFirstTargetItem();
SchemaItem source = selection.getFirstSourceItem();
if (!target.isAttribute() || !source.isAttribute()) {
return false;
}
// target item must be a ReferenceType
if (!target.getPropertyType().getName().getLocalPart().equals("ReferenceType")) {
return false;
}
// source item must be alphanumeric
if (source.getType().equals(TreeObjectType.NUMERIC_ATTRIBUTE)
|| source.getType().equals(TreeObjectType.STRING_ATTRIBUTE)) {
return true;
}
return false;
}
|
diff --git a/gnu/testlet/java/util/logging/LogRecord/getMillis.java b/gnu/testlet/java/util/logging/LogRecord/getMillis.java
index ba2f5e4e..dfc9e623 100644
--- a/gnu/testlet/java/util/logging/LogRecord/getMillis.java
+++ b/gnu/testlet/java/util/logging/LogRecord/getMillis.java
@@ -1,52 +1,54 @@
// Tags: JDK1.4
// Copyright (C) 2004 Sascha Brawer <[email protected]>
// This file is part of Mauve.
// Mauve is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 2, or (at your option)
// any later version.
// Mauve is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with Mauve; see the file COPYING. If not, write to
// the Free Software Foundation, 59 Temple Place - Suite 330,
// Boston, MA 02111-1307, USA.
package gnu.testlet.java.util.logging.LogRecord;
import gnu.testlet.Testlet;
import gnu.testlet.TestHarness;
import java.util.logging.Level;
import java.util.logging.LogRecord;
/**
* @author <a href="mailto:[email protected]">Sascha Brawer</a>
*/
public class getMillis
implements Testlet
{
public void test(TestHarness th)
{
LogRecord rec1, rec2;
// Check #1.
rec1 = new LogRecord(Level.CONFIG, "foo");
try
{
- Thread.sleep(4);
+ long start = System.currentTimeMillis();
+ while (start == System.currentTimeMillis())
+ Thread.sleep(1);
}
catch (InterruptedException _)
{
}
rec2 = new LogRecord(Level.INFO, "bar");
- th.check(rec1.getMillis() != rec2.getMillis());
+ th.check(rec1.getMillis() < rec2.getMillis());
}
}
| false | true | public void test(TestHarness th)
{
LogRecord rec1, rec2;
// Check #1.
rec1 = new LogRecord(Level.CONFIG, "foo");
try
{
Thread.sleep(4);
}
catch (InterruptedException _)
{
}
rec2 = new LogRecord(Level.INFO, "bar");
th.check(rec1.getMillis() != rec2.getMillis());
}
| public void test(TestHarness th)
{
LogRecord rec1, rec2;
// Check #1.
rec1 = new LogRecord(Level.CONFIG, "foo");
try
{
long start = System.currentTimeMillis();
while (start == System.currentTimeMillis())
Thread.sleep(1);
}
catch (InterruptedException _)
{
}
rec2 = new LogRecord(Level.INFO, "bar");
th.check(rec1.getMillis() < rec2.getMillis());
}
|
diff --git a/patches/target-build/server/pentaho/src/pt/webdetails/cdf/NavigateComponent.java b/patches/target-build/server/pentaho/src/pt/webdetails/cdf/NavigateComponent.java
index d460cc68..b3dc194e 100755
--- a/patches/target-build/server/pentaho/src/pt/webdetails/cdf/NavigateComponent.java
+++ b/patches/target-build/server/pentaho/src/pt/webdetails/cdf/NavigateComponent.java
@@ -1,424 +1,424 @@
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package pt.webdetails.cdf;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;
import java.util.StringTokenizer;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.json.JSONException;
import org.pentaho.core.repository.ISolutionRepository;
import org.pentaho.core.session.IPentahoSession;
import org.pentaho.core.system.PentahoSystem;
import org.pentaho.core.system.PentahoMessenger;
import org.pentaho.core.cache.CacheManager;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.Node;
import org.dom4j.XPath;
import org.json.JSONArray;
import org.json.JSONObject;
import org.pentaho.core.repository.SolutionRepositoryBase;
import org.pentaho.core.solution.ISolutionFile;
/**
*
* @author pedro alves
*/
public class NavigateComponent extends PentahoMessenger {
private static final String NAVIGATOR = "navigator";
private static final String CONTENTLIST = "contentList";
private static final String TYPE_DIR = "FOLDER";
private static final String TYPE_XACTION = "XACTION";
private static final String TYPE_URL = "URL";
private static final String CACHE_NAVIGATOR = "CDF_NAVIGATOR_JSON";
protected static final Log logger = LogFactory.getLog(NavigateComponent.class);
ISolutionRepository solutionRepository = null;
IPentahoSession userSession;
CacheManager cacheManager;
boolean cachingAvailable;
public NavigateComponent(IPentahoSession userSession) {
this.userSession = userSession;
solutionRepository = PentahoSystem.getSolutionRepository(userSession);
cacheManager = PentahoSystem.getCacheManager();
cachingAvailable = cacheManager != null && cacheManager.cacheEnabled();
}
public String getNavigationElements(String mode, String solution, String path) throws JSONException {
if (mode.equals(NAVIGATOR)) {
return getNavigatorJSON(solution, path);
} else if (mode.equals(CONTENTLIST)) {
return getContentListJSON(solution, path);
} else {
logger.warn("Invalid mode: " + mode);
return "";
}
}
@Override
public Log getLogger() {
return logger;
}
private String getNavigatorJSON(String solution, String path) throws JSONException {
String jsonString = null;
if (cachingAvailable && (jsonString = (String) cacheManager.getFromSessionCache(userSession, CACHE_NAVIGATOR)) != null) {
debug("Navigator found in cache");
} else {
Document navDoc = solutionRepository.getSolutionTree(ISolutionRepository.ACTION_EXECUTE);
// Get it and build the tree
JSONObject json = new JSONObject();
Node tree = navDoc.getRootElement();
JSONArray array = processTree(tree);
json.put("solution", array.get(0));
jsonString = json.toString(2);
// Store in cache:
cacheManager.putInSessionCache(userSession, CACHE_NAVIGATOR, jsonString);
}
return jsonString;
}
private JSONArray processTree(Node tree) throws JSONException {
String xPathDir = "./branch[@isDir='true']"; //$NON-NLS-1$
JSONArray array = null;
try {
List nodes = tree.selectNodes(xPathDir); //$NON-NLS-1$
if (!nodes.isEmpty()) {
array = new JSONArray();
}
Iterator nodeIterator = nodes.iterator();
while (nodeIterator.hasNext()) {
Node node = (Node) nodeIterator.next();
boolean processChildren = true;
// String name = node.getText();
String path = node.valueOf("@id");
String name = node.valueOf("branchText");
//debug("Processing branch: " + path);
JSONObject json = new JSONObject();
json.put("name", name);
json.put("id", path);
// put solution and path
String[] pathArray = path.split("\\/");
path = path.replace(pathArray[1], "solution");
String solutionName = pathArray.length > 2 ? pathArray[2] : "";
String solutionPath = pathArray.length > 3 ? path.substring(path.indexOf("/", 10) + 1) : "";
json.put("solution", solutionName);
json.put("path", solutionPath);
json.put("type", TYPE_DIR);
if (path.startsWith("/solution/")) {
String resourcePath = path.substring(9);
//try {
String resourceName = resourcePath + "/" + SolutionRepositoryBase.INDEX_FILENAME;
if (solutionRepository.resourceExists(resourceName)) {
System.out.println("Processing folder " + resourcePath);
ISolutionFile file = solutionRepository.getFileByPath(resourceName);
Document indexFile = solutionRepository.getResourceAsDocument(resourceName);
solutionRepository.localizeDoc(indexFile, file);
boolean visible = Boolean.parseBoolean(indexFile.valueOf("/index/visible"));
json.put("visible", visible);
json.put("title", indexFile.valueOf("/index/name"));
json.put("description", indexFile.valueOf("/index/description"));
if (!visible) {
processChildren = false;
}
//System.out.println("... done processing folder " + resourcePath);
} else {
json.put("visible", false);
json.put("title", "Hidden");
processChildren = false;
}
} else {
// root dir
json.put("visible", true);
json.put("title", "Solution");
}
//System.out.println(" Processing getting children ");
if (processChildren) {
JSONArray children = processTree(node);
if (children != null) {
json.put("folders", children);
}
}
array.put(json);
}
} catch (Exception e) {
System.out.println("Error: " + e.getClass().getName() + " - " + e.getMessage());
warn("Error: " + e.getClass().getName() + " - " + e.getMessage());
}
return array;
}
private String getContentListJSON(String _solution, String _path) throws JSONException {
Document navDoc = solutionRepository.getSolutionTree(ISolutionRepository.ACTION_EXECUTE);
// Get it and build the tree
JSONObject contentListJSON = new JSONObject();
Node tree = navDoc.getRootElement();
String solutionPrefix = tree.valueOf("/tree/branch/@id");
StringBuffer _id = new StringBuffer(solutionPrefix);
if (_solution.length() > 0) {
_id.append("/" + _solution);
}
if (_path.length() > 0) {
_id.append("/" + _path);
}
//branch[@id='/solution/admin' and @isDir='true']/leaf
String xPathDirBranch = "//branch[@id='" + _id.toString() + "' and @isDir='true']/branch";
String xPathDirLeaf = "//branch[@id='" + _id.toString() + "' and @isDir='true']/leaf";
JSONArray array = null;
// Iterate through branches
try {
List nodes = tree.selectNodes(xPathDirBranch); //$NON-NLS-1$
if (!nodes.isEmpty()) {
array = new JSONArray();
}
Iterator nodeIterator = nodes.iterator();
while (nodeIterator.hasNext()) {
Node node = (Node) nodeIterator.next();
// String name = node.getText();
String path = node.valueOf("@id");
String name = node.valueOf("branchText");
//debug("Processing branch: " + path);
JSONObject json = new JSONObject();
json.put("name", name);
json.put("id", path);
json.put("solution", _solution);
json.put("path", _path + (_path.length() > 0 ? "/" : "") + name);
json.put("type", TYPE_DIR);
if (path.startsWith(solutionPrefix + "/")) {
String resourcePath = path.substring(9);
//try {
String resourceName = resourcePath + "/" + SolutionRepositoryBase.INDEX_FILENAME;
if (solutionRepository.resourceExists(resourceName)) {
System.out.println("Processing folder " + resourcePath);
ISolutionFile file = solutionRepository.getFileByPath(resourceName);
Document indexFile = solutionRepository.getResourceAsDocument(resourceName);
solutionRepository.localizeDoc(indexFile, file);
json.put("visible", new Boolean(indexFile.valueOf("/index/visible")));
json.put("title", indexFile.valueOf("/index/name"));
json.put("description", indexFile.valueOf("/index/description"));
//System.out.println("... done processing folder " + resourcePath);
} else {
json.put("visible", false);
json.put("title", "Hidden");
}
} else {
// root dir
json.put("visible", true);
json.put("title", "Solution");
}
array.put(json);
}
} catch (Exception e) {
System.out.println("Error: " + e.getClass().getName() + " - " + e.getMessage());
warn("Error: " + e.getClass().getName() + " - " + e.getMessage());
}
// Iterate through leaves
try {
List nodes = tree.selectNodes(xPathDirLeaf); //$NON-NLS-1$
if (array == null && !nodes.isEmpty()) {
array = new JSONArray();
}
Iterator nodeIterator = nodes.iterator();
while (nodeIterator.hasNext()) {
Element node = (Element) nodeIterator.next();
// String name = node.getText();
String path = node.valueOf("path");
String name = node.valueOf("leafText");
JSONObject json = new JSONObject();
json.put("name", name);
json.put("id", path);
json.put("solution", _solution);
json.put("path", _path);
json.put("action", name);
// we only care for: .xactions and .url files
if (name.toLowerCase().endsWith(".xaction")) {
json.put("type", TYPE_XACTION);
String resourcePath = path.replace(solutionPrefix,"solution").substring(9);
String resourceName = resourcePath;
if (solutionRepository.resourceExists(resourceName)) {
System.out.println("Processing file " + resourcePath);
ISolutionFile file = solutionRepository.getFileByPath(resourceName);
Document indexFile = solutionRepository.getResourceAsDocument(resourceName);
solutionRepository.localizeDoc(indexFile, file);
- json.put("visible", indexFile.selectNodes("/action-sequence/documentation/result-type").size() == 0 ? Boolean.FALSE : Boolean.TRUE);
+ json.put("visible", indexFile.selectNodes("/action-sequence/documentation/result-type").size() == 0 || indexFile.valueOf("/action-sequence/documentation/result-type").equals("none") ? Boolean.FALSE : Boolean.TRUE);
json.put("title", indexFile.valueOf("/action-sequence/title"));
json.put("description", indexFile.valueOf("/action-sequence/documentation/description"));
//System.out.println("... done processing folder " + resourcePath);
} else {
json.put("visible", false);
json.put("title", "Hidden");
}
} else if (name.toLowerCase().endsWith(".url")) {
json.put("type", TYPE_URL);
String resourcePath = path.replace(solutionPrefix,"solution").substring(9);
String resourceName = resourcePath;
ISolutionFile file = solutionRepository.getFileByPath(resourceName);
processUrl(file, node, resourceName);
json.put("visible", new Boolean(node.valueOf("file/@visible")));
json.put("title", node.valueOf("file/title"));
json.put("description", node.valueOf("file/description"));
json.put("url", node.valueOf("file/url"));
} else { //ignore other files
continue;
}
array.put(json);
}
} catch (Exception e) {
System.out.println("Error: " + e.getClass().getName() + " - " + e.getMessage());
warn("Error: " + e.getClass().getName() + " - " + e.getMessage());
}
contentListJSON.put("content", array);
String jsonString = contentListJSON.toString(2);
//debug("Finished processing tree");
//RepositoryFile file = (RepositoryFile) getFileByPath(fullPath);
return jsonString;
}
private void processUrl(ISolutionFile file, Element parentNode, String resourceName) {
// parse the .url file to get the contents
try {
String urlContent = solutionRepository.getResourceAsString(resourceName);
StringTokenizer tokenizer = new StringTokenizer(urlContent, "\n"); //$NON-NLS-1$
String title = null;
String url = null;
String description = null;
String target = null;
while (tokenizer.hasMoreTokens()) {
String line = tokenizer.nextToken();
int pos = line.indexOf('=');
if (pos > 0) {
String name = line.substring(0, pos);
String value = line.substring(pos + 1);
if ((value != null) && (value.length() > 0) && (value.charAt(value.length() - 1) == '\r')) {
value = value.substring(0, value.length() - 1);
}
if ("URL".equalsIgnoreCase(name)) { //$NON-NLS-1$
url = value;
}
if ("name".equalsIgnoreCase(name)) { //$NON-NLS-1$
title = value;
}
if ("description".equalsIgnoreCase(name)) { //$NON-NLS-1$
description = value;
}
if ("target".equalsIgnoreCase(name)) { //$NON-NLS-1$
target = value;
}
}
}
if (url != null) {
// now create an entry for the database
Element dirNode = parentNode.addElement("file"); //$NON-NLS-1$
dirNode.addAttribute("type", TYPE_URL); //$NON-NLS-1$
dirNode.addElement("filename").setText(title); //$NON-NLS-1$
dirNode.addElement("title").setText(title); //$NON-NLS-1$
if (target != null) {
dirNode.addElement("target").setText(target); //$NON-NLS-1$
}
if (description != null) {
dirNode.addElement("description").setText(description); //$NON-NLS-1$
}
dirNode.addElement("url").setText(url); //$NON-NLS-1$
dirNode.addAttribute("visible", "true"); //$NON-NLS-1$ //$NON-NLS-2$
solutionRepository.localizeDoc(dirNode, file);
}
} catch (IOException e) {
warn("Error processing url file: " + e.getClass().getName() + " - " + e.getMessage());
}
}
}
| true | true | private String getContentListJSON(String _solution, String _path) throws JSONException {
Document navDoc = solutionRepository.getSolutionTree(ISolutionRepository.ACTION_EXECUTE);
// Get it and build the tree
JSONObject contentListJSON = new JSONObject();
Node tree = navDoc.getRootElement();
String solutionPrefix = tree.valueOf("/tree/branch/@id");
StringBuffer _id = new StringBuffer(solutionPrefix);
if (_solution.length() > 0) {
_id.append("/" + _solution);
}
if (_path.length() > 0) {
_id.append("/" + _path);
}
//branch[@id='/solution/admin' and @isDir='true']/leaf
String xPathDirBranch = "//branch[@id='" + _id.toString() + "' and @isDir='true']/branch";
String xPathDirLeaf = "//branch[@id='" + _id.toString() + "' and @isDir='true']/leaf";
JSONArray array = null;
// Iterate through branches
try {
List nodes = tree.selectNodes(xPathDirBranch); //$NON-NLS-1$
if (!nodes.isEmpty()) {
array = new JSONArray();
}
Iterator nodeIterator = nodes.iterator();
while (nodeIterator.hasNext()) {
Node node = (Node) nodeIterator.next();
// String name = node.getText();
String path = node.valueOf("@id");
String name = node.valueOf("branchText");
//debug("Processing branch: " + path);
JSONObject json = new JSONObject();
json.put("name", name);
json.put("id", path);
json.put("solution", _solution);
json.put("path", _path + (_path.length() > 0 ? "/" : "") + name);
json.put("type", TYPE_DIR);
if (path.startsWith(solutionPrefix + "/")) {
String resourcePath = path.substring(9);
//try {
String resourceName = resourcePath + "/" + SolutionRepositoryBase.INDEX_FILENAME;
if (solutionRepository.resourceExists(resourceName)) {
System.out.println("Processing folder " + resourcePath);
ISolutionFile file = solutionRepository.getFileByPath(resourceName);
Document indexFile = solutionRepository.getResourceAsDocument(resourceName);
solutionRepository.localizeDoc(indexFile, file);
json.put("visible", new Boolean(indexFile.valueOf("/index/visible")));
json.put("title", indexFile.valueOf("/index/name"));
json.put("description", indexFile.valueOf("/index/description"));
//System.out.println("... done processing folder " + resourcePath);
} else {
json.put("visible", false);
json.put("title", "Hidden");
}
} else {
// root dir
json.put("visible", true);
json.put("title", "Solution");
}
array.put(json);
}
} catch (Exception e) {
System.out.println("Error: " + e.getClass().getName() + " - " + e.getMessage());
warn("Error: " + e.getClass().getName() + " - " + e.getMessage());
}
// Iterate through leaves
try {
List nodes = tree.selectNodes(xPathDirLeaf); //$NON-NLS-1$
if (array == null && !nodes.isEmpty()) {
array = new JSONArray();
}
Iterator nodeIterator = nodes.iterator();
while (nodeIterator.hasNext()) {
Element node = (Element) nodeIterator.next();
// String name = node.getText();
String path = node.valueOf("path");
String name = node.valueOf("leafText");
JSONObject json = new JSONObject();
json.put("name", name);
json.put("id", path);
json.put("solution", _solution);
json.put("path", _path);
json.put("action", name);
// we only care for: .xactions and .url files
if (name.toLowerCase().endsWith(".xaction")) {
json.put("type", TYPE_XACTION);
String resourcePath = path.replace(solutionPrefix,"solution").substring(9);
String resourceName = resourcePath;
if (solutionRepository.resourceExists(resourceName)) {
System.out.println("Processing file " + resourcePath);
ISolutionFile file = solutionRepository.getFileByPath(resourceName);
Document indexFile = solutionRepository.getResourceAsDocument(resourceName);
solutionRepository.localizeDoc(indexFile, file);
json.put("visible", indexFile.selectNodes("/action-sequence/documentation/result-type").size() == 0 ? Boolean.FALSE : Boolean.TRUE);
json.put("title", indexFile.valueOf("/action-sequence/title"));
json.put("description", indexFile.valueOf("/action-sequence/documentation/description"));
//System.out.println("... done processing folder " + resourcePath);
} else {
json.put("visible", false);
json.put("title", "Hidden");
}
} else if (name.toLowerCase().endsWith(".url")) {
json.put("type", TYPE_URL);
String resourcePath = path.replace(solutionPrefix,"solution").substring(9);
String resourceName = resourcePath;
ISolutionFile file = solutionRepository.getFileByPath(resourceName);
processUrl(file, node, resourceName);
json.put("visible", new Boolean(node.valueOf("file/@visible")));
json.put("title", node.valueOf("file/title"));
json.put("description", node.valueOf("file/description"));
json.put("url", node.valueOf("file/url"));
} else { //ignore other files
continue;
}
array.put(json);
}
} catch (Exception e) {
System.out.println("Error: " + e.getClass().getName() + " - " + e.getMessage());
warn("Error: " + e.getClass().getName() + " - " + e.getMessage());
}
contentListJSON.put("content", array);
String jsonString = contentListJSON.toString(2);
//debug("Finished processing tree");
//RepositoryFile file = (RepositoryFile) getFileByPath(fullPath);
return jsonString;
}
| private String getContentListJSON(String _solution, String _path) throws JSONException {
Document navDoc = solutionRepository.getSolutionTree(ISolutionRepository.ACTION_EXECUTE);
// Get it and build the tree
JSONObject contentListJSON = new JSONObject();
Node tree = navDoc.getRootElement();
String solutionPrefix = tree.valueOf("/tree/branch/@id");
StringBuffer _id = new StringBuffer(solutionPrefix);
if (_solution.length() > 0) {
_id.append("/" + _solution);
}
if (_path.length() > 0) {
_id.append("/" + _path);
}
//branch[@id='/solution/admin' and @isDir='true']/leaf
String xPathDirBranch = "//branch[@id='" + _id.toString() + "' and @isDir='true']/branch";
String xPathDirLeaf = "//branch[@id='" + _id.toString() + "' and @isDir='true']/leaf";
JSONArray array = null;
// Iterate through branches
try {
List nodes = tree.selectNodes(xPathDirBranch); //$NON-NLS-1$
if (!nodes.isEmpty()) {
array = new JSONArray();
}
Iterator nodeIterator = nodes.iterator();
while (nodeIterator.hasNext()) {
Node node = (Node) nodeIterator.next();
// String name = node.getText();
String path = node.valueOf("@id");
String name = node.valueOf("branchText");
//debug("Processing branch: " + path);
JSONObject json = new JSONObject();
json.put("name", name);
json.put("id", path);
json.put("solution", _solution);
json.put("path", _path + (_path.length() > 0 ? "/" : "") + name);
json.put("type", TYPE_DIR);
if (path.startsWith(solutionPrefix + "/")) {
String resourcePath = path.substring(9);
//try {
String resourceName = resourcePath + "/" + SolutionRepositoryBase.INDEX_FILENAME;
if (solutionRepository.resourceExists(resourceName)) {
System.out.println("Processing folder " + resourcePath);
ISolutionFile file = solutionRepository.getFileByPath(resourceName);
Document indexFile = solutionRepository.getResourceAsDocument(resourceName);
solutionRepository.localizeDoc(indexFile, file);
json.put("visible", new Boolean(indexFile.valueOf("/index/visible")));
json.put("title", indexFile.valueOf("/index/name"));
json.put("description", indexFile.valueOf("/index/description"));
//System.out.println("... done processing folder " + resourcePath);
} else {
json.put("visible", false);
json.put("title", "Hidden");
}
} else {
// root dir
json.put("visible", true);
json.put("title", "Solution");
}
array.put(json);
}
} catch (Exception e) {
System.out.println("Error: " + e.getClass().getName() + " - " + e.getMessage());
warn("Error: " + e.getClass().getName() + " - " + e.getMessage());
}
// Iterate through leaves
try {
List nodes = tree.selectNodes(xPathDirLeaf); //$NON-NLS-1$
if (array == null && !nodes.isEmpty()) {
array = new JSONArray();
}
Iterator nodeIterator = nodes.iterator();
while (nodeIterator.hasNext()) {
Element node = (Element) nodeIterator.next();
// String name = node.getText();
String path = node.valueOf("path");
String name = node.valueOf("leafText");
JSONObject json = new JSONObject();
json.put("name", name);
json.put("id", path);
json.put("solution", _solution);
json.put("path", _path);
json.put("action", name);
// we only care for: .xactions and .url files
if (name.toLowerCase().endsWith(".xaction")) {
json.put("type", TYPE_XACTION);
String resourcePath = path.replace(solutionPrefix,"solution").substring(9);
String resourceName = resourcePath;
if (solutionRepository.resourceExists(resourceName)) {
System.out.println("Processing file " + resourcePath);
ISolutionFile file = solutionRepository.getFileByPath(resourceName);
Document indexFile = solutionRepository.getResourceAsDocument(resourceName);
solutionRepository.localizeDoc(indexFile, file);
json.put("visible", indexFile.selectNodes("/action-sequence/documentation/result-type").size() == 0 || indexFile.valueOf("/action-sequence/documentation/result-type").equals("none") ? Boolean.FALSE : Boolean.TRUE);
json.put("title", indexFile.valueOf("/action-sequence/title"));
json.put("description", indexFile.valueOf("/action-sequence/documentation/description"));
//System.out.println("... done processing folder " + resourcePath);
} else {
json.put("visible", false);
json.put("title", "Hidden");
}
} else if (name.toLowerCase().endsWith(".url")) {
json.put("type", TYPE_URL);
String resourcePath = path.replace(solutionPrefix,"solution").substring(9);
String resourceName = resourcePath;
ISolutionFile file = solutionRepository.getFileByPath(resourceName);
processUrl(file, node, resourceName);
json.put("visible", new Boolean(node.valueOf("file/@visible")));
json.put("title", node.valueOf("file/title"));
json.put("description", node.valueOf("file/description"));
json.put("url", node.valueOf("file/url"));
} else { //ignore other files
continue;
}
array.put(json);
}
} catch (Exception e) {
System.out.println("Error: " + e.getClass().getName() + " - " + e.getMessage());
warn("Error: " + e.getClass().getName() + " - " + e.getMessage());
}
contentListJSON.put("content", array);
String jsonString = contentListJSON.toString(2);
//debug("Finished processing tree");
//RepositoryFile file = (RepositoryFile) getFileByPath(fullPath);
return jsonString;
}
|
diff --git a/tregmine/src/info/tregmine/commands/Tp.java b/tregmine/src/info/tregmine/commands/Tp.java
index 5d706a8..8c5725c 100644
--- a/tregmine/src/info/tregmine/commands/Tp.java
+++ b/tregmine/src/info/tregmine/commands/Tp.java
@@ -1,66 +1,66 @@
package info.tregmine.commands;
import java.util.List;
import org.bukkit.ChatColor;
import org.bukkit.entity.Player;
import info.tregmine.Tregmine;
import info.tregmine.api.TregminePlayer;
public class Tp {
public static void run(Tregmine _plugin, TregminePlayer _player, String[] _args){
Player pto = _plugin.getServer().getPlayer(_args[0]);
if (pto == null) {
_player.sendMessage(ChatColor.RED + "Can no find a user with name" + _args[0] );
return;
}
info.tregmine.api.TregminePlayer to = _plugin.tregminePlayer.get(pto.getName());
if (to.getMetaBoolean("invis")) {
_player.sendMessage(ChatColor.RED + "Can no find a user with name" + _args[0] );
return;
}
- if (to.getMetaBoolean("tpblock") && !to.isAdmin() ) {
+ if (to.getMetaBoolean("tpblock") && !_player.isAdmin() ) {
_player.sendMessage(ChatColor.RED + to.getName() + ChatColor.AQUA + "'s teloptical deflector absorbed all motion. Teleportation failed.");
to.sendMessage(_player.getName() + ChatColor.AQUA + "'s teleportation spell cannot bypass your sophisticated defenses.");
return;
}
double distance = info.tregmine.api.math.Distance.calc2d(_player.getLocation(), to.getLocation());
if (_player.isAdmin()) {
_player.sendMessage(ChatColor.AQUA + "You started teleport to " + to.getChatName() + ChatColor.AQUA + " in " + ChatColor.BLUE + to.getWorld().getName() + ".");
_player.teleport(to);
return;
}
if (_player.getMetaBoolean("mentor")) {
_player.sendMessage(ChatColor.AQUA + "You started teleport to " + to.getName() + ChatColor.AQUA + " in " + ChatColor.BLUE + to.getWorld().getName() + ".");
to.sendMessage(ChatColor.AQUA + _player.getChatName() + " teleported to you!");
_player.teleport(to);
return;
}
if ((_player.getWorld().getName().matches(to.getWorld().getName()))) {
if (_player.isDonator() && distance < 10000) {
_player.sendMessage(ChatColor.AQUA + "You started teleport to " + to.getName() + ChatColor.AQUA + " in " + ChatColor.BLUE + to.getWorld().getName() + ".");
to.sendMessage(ChatColor.AQUA + _player.getChatName() + " teleported to you!");
_player.teleport(to);
return;
}
if (_player.isDonator() && distance < 100) {
_player.sendMessage(ChatColor.AQUA + "You started teleport to " + to.getName() + ChatColor.AQUA + " in " + ChatColor.BLUE + to.getWorld().getName() + ".");
to.sendMessage(ChatColor.AQUA + _player.getChatName() + " teleported to you!");
_player.teleport(to);
return;
}
}
}
}
| true | true | public static void run(Tregmine _plugin, TregminePlayer _player, String[] _args){
Player pto = _plugin.getServer().getPlayer(_args[0]);
if (pto == null) {
_player.sendMessage(ChatColor.RED + "Can no find a user with name" + _args[0] );
return;
}
info.tregmine.api.TregminePlayer to = _plugin.tregminePlayer.get(pto.getName());
if (to.getMetaBoolean("invis")) {
_player.sendMessage(ChatColor.RED + "Can no find a user with name" + _args[0] );
return;
}
if (to.getMetaBoolean("tpblock") && !to.isAdmin() ) {
_player.sendMessage(ChatColor.RED + to.getName() + ChatColor.AQUA + "'s teloptical deflector absorbed all motion. Teleportation failed.");
to.sendMessage(_player.getName() + ChatColor.AQUA + "'s teleportation spell cannot bypass your sophisticated defenses.");
return;
}
double distance = info.tregmine.api.math.Distance.calc2d(_player.getLocation(), to.getLocation());
if (_player.isAdmin()) {
_player.sendMessage(ChatColor.AQUA + "You started teleport to " + to.getChatName() + ChatColor.AQUA + " in " + ChatColor.BLUE + to.getWorld().getName() + ".");
_player.teleport(to);
return;
}
if (_player.getMetaBoolean("mentor")) {
_player.sendMessage(ChatColor.AQUA + "You started teleport to " + to.getName() + ChatColor.AQUA + " in " + ChatColor.BLUE + to.getWorld().getName() + ".");
to.sendMessage(ChatColor.AQUA + _player.getChatName() + " teleported to you!");
_player.teleport(to);
return;
}
if ((_player.getWorld().getName().matches(to.getWorld().getName()))) {
if (_player.isDonator() && distance < 10000) {
_player.sendMessage(ChatColor.AQUA + "You started teleport to " + to.getName() + ChatColor.AQUA + " in " + ChatColor.BLUE + to.getWorld().getName() + ".");
to.sendMessage(ChatColor.AQUA + _player.getChatName() + " teleported to you!");
_player.teleport(to);
return;
}
if (_player.isDonator() && distance < 100) {
_player.sendMessage(ChatColor.AQUA + "You started teleport to " + to.getName() + ChatColor.AQUA + " in " + ChatColor.BLUE + to.getWorld().getName() + ".");
to.sendMessage(ChatColor.AQUA + _player.getChatName() + " teleported to you!");
_player.teleport(to);
return;
}
}
}
| public static void run(Tregmine _plugin, TregminePlayer _player, String[] _args){
Player pto = _plugin.getServer().getPlayer(_args[0]);
if (pto == null) {
_player.sendMessage(ChatColor.RED + "Can no find a user with name" + _args[0] );
return;
}
info.tregmine.api.TregminePlayer to = _plugin.tregminePlayer.get(pto.getName());
if (to.getMetaBoolean("invis")) {
_player.sendMessage(ChatColor.RED + "Can no find a user with name" + _args[0] );
return;
}
if (to.getMetaBoolean("tpblock") && !_player.isAdmin() ) {
_player.sendMessage(ChatColor.RED + to.getName() + ChatColor.AQUA + "'s teloptical deflector absorbed all motion. Teleportation failed.");
to.sendMessage(_player.getName() + ChatColor.AQUA + "'s teleportation spell cannot bypass your sophisticated defenses.");
return;
}
double distance = info.tregmine.api.math.Distance.calc2d(_player.getLocation(), to.getLocation());
if (_player.isAdmin()) {
_player.sendMessage(ChatColor.AQUA + "You started teleport to " + to.getChatName() + ChatColor.AQUA + " in " + ChatColor.BLUE + to.getWorld().getName() + ".");
_player.teleport(to);
return;
}
if (_player.getMetaBoolean("mentor")) {
_player.sendMessage(ChatColor.AQUA + "You started teleport to " + to.getName() + ChatColor.AQUA + " in " + ChatColor.BLUE + to.getWorld().getName() + ".");
to.sendMessage(ChatColor.AQUA + _player.getChatName() + " teleported to you!");
_player.teleport(to);
return;
}
if ((_player.getWorld().getName().matches(to.getWorld().getName()))) {
if (_player.isDonator() && distance < 10000) {
_player.sendMessage(ChatColor.AQUA + "You started teleport to " + to.getName() + ChatColor.AQUA + " in " + ChatColor.BLUE + to.getWorld().getName() + ".");
to.sendMessage(ChatColor.AQUA + _player.getChatName() + " teleported to you!");
_player.teleport(to);
return;
}
if (_player.isDonator() && distance < 100) {
_player.sendMessage(ChatColor.AQUA + "You started teleport to " + to.getName() + ChatColor.AQUA + " in " + ChatColor.BLUE + to.getWorld().getName() + ".");
to.sendMessage(ChatColor.AQUA + _player.getChatName() + " teleported to you!");
_player.teleport(to);
return;
}
}
}
|
diff --git a/modules/core/src/main/java/org/apache/sandesha2/util/RMMsgCreator.java b/modules/core/src/main/java/org/apache/sandesha2/util/RMMsgCreator.java
index 4c8601eb..50ae58fe 100644
--- a/modules/core/src/main/java/org/apache/sandesha2/util/RMMsgCreator.java
+++ b/modules/core/src/main/java/org/apache/sandesha2/util/RMMsgCreator.java
@@ -1,616 +1,622 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.sandesha2.util;
import java.util.ArrayList;
import org.apache.axiom.om.OMElement;
import org.apache.axiom.soap.SOAPEnvelope;
import org.apache.axiom.soap.SOAPFactory;
import org.apache.axis2.AxisFault;
import org.apache.axis2.addressing.AddressingConstants;
import org.apache.axis2.addressing.EndpointReference;
import org.apache.axis2.context.ConfigurationContext;
import org.apache.axis2.context.MessageContext;
import org.apache.axis2.context.OperationContext;
import org.apache.axis2.description.AxisOperation;
import org.apache.axis2.description.AxisService;
import org.apache.axis2.description.Parameter;
import org.apache.axis2.util.MessageContextBuilder;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.sandesha2.RMMsgContext;
import org.apache.sandesha2.Sandesha2Constants;
import org.apache.sandesha2.SandeshaException;
import org.apache.sandesha2.client.SandeshaClientConstants;
import org.apache.sandesha2.i18n.SandeshaMessageHelper;
import org.apache.sandesha2.i18n.SandeshaMessageKeys;
import org.apache.sandesha2.policy.SandeshaPolicyBean;
import org.apache.sandesha2.security.SecurityManager;
import org.apache.sandesha2.security.SecurityToken;
import org.apache.sandesha2.storage.StorageManager;
import org.apache.sandesha2.storage.beans.RMDBean;
import org.apache.sandesha2.storage.beans.RMSBean;
import org.apache.sandesha2.storage.beans.RMSequenceBean;
import org.apache.sandesha2.wsrm.Accept;
import org.apache.sandesha2.wsrm.AcksTo;
import org.apache.sandesha2.wsrm.CloseSequence;
import org.apache.sandesha2.wsrm.CloseSequenceResponse;
import org.apache.sandesha2.wsrm.CreateSequence;
import org.apache.sandesha2.wsrm.CreateSequenceResponse;
import org.apache.sandesha2.wsrm.Endpoint;
import org.apache.sandesha2.wsrm.IOMRMPart;
import org.apache.sandesha2.wsrm.Identifier;
import org.apache.sandesha2.wsrm.LastMessageNumber;
import org.apache.sandesha2.wsrm.MakeConnection;
import org.apache.sandesha2.wsrm.SequenceAcknowledgement;
import org.apache.sandesha2.wsrm.SequenceOffer;
import org.apache.sandesha2.wsrm.TerminateSequence;
import org.apache.sandesha2.wsrm.TerminateSequenceResponse;
import org.apache.sandesha2.wsrm.UsesSequenceSTR;
/**
* Used to create new RM messages.
*/
public class RMMsgCreator {
private static Log log = LogFactory.getLog(RMMsgCreator.class);
public static final String ACK_TO_BE_WRITTEN = "ackToBeWritten";
/**
* Create a new CreateSequence message.
*
* @param applicationRMMsg
* @param internalSequenceId
* @param acksToEPR
* @return
* @throws SandeshaException
*/
public static RMMsgContext createCreateSeqMsg(RMSBean rmsBean, RMMsgContext applicationRMMsg) throws AxisFault {
if(log.isDebugEnabled()) log.debug("Entry: RMMsgCreator::createCreateSeqMsg " + applicationRMMsg);
MessageContext applicationMsgContext = applicationRMMsg.getMessageContext();
if (applicationMsgContext == null)
throw new SandeshaException(SandeshaMessageHelper.getMessage(SandeshaMessageKeys.appMsgIsNull));
ConfigurationContext context = applicationMsgContext.getConfigurationContext();
if (context == null)
throw new SandeshaException(SandeshaMessageHelper.getMessage(SandeshaMessageKeys.configContextNotSet));
// creating by copying common contents. (this will not set contexts
// except for configCtx).
AxisOperation createSequenceOperation = SpecSpecificConstants.getWSRMOperation(
Sandesha2Constants.MessageTypes.CREATE_SEQ,
rmsBean.getRMVersion(),
applicationMsgContext.getAxisService());
MessageContext createSeqmsgContext = SandeshaUtil
.createNewRelatedMessageContext(applicationRMMsg, createSequenceOperation);
OperationContext createSeqOpCtx = createSeqmsgContext.getOperationContext();
String createSeqMsgId = SandeshaUtil.getUUID();
createSeqmsgContext.setMessageID(createSeqMsgId);
context.registerOperationContext(createSeqMsgId, createSeqOpCtx);
RMMsgContext createSeqRMMsg = new RMMsgContext(createSeqmsgContext);
String rmNamespaceValue = SpecSpecificConstants.getRMNamespaceValue(rmsBean.getRMVersion());
// Decide which addressing version to use. We copy the version that the application
// is already using (if set), and fall back to the level in the spec if that isn't
// found.
String addressingNamespace = (String) applicationMsgContext.getProperty(AddressingConstants.WS_ADDRESSING_VERSION);
Boolean disableAddressing = (Boolean) applicationMsgContext.getProperty(AddressingConstants.DISABLE_ADDRESSING_FOR_OUT_MESSAGES);
if(addressingNamespace == null) {
// Addressing may still be enabled, as it defaults to the final spec. The only time
// we follow the RM spec is when addressing has been explicitly disabled.
if(disableAddressing != null && disableAddressing.booleanValue())
addressingNamespace = SpecSpecificConstants.getAddressingNamespace(rmNamespaceValue);
else
addressingNamespace = AddressingConstants.Final.WSA_NAMESPACE;
}
if(log.isDebugEnabled()) log.debug("RMMsgCreator:: addressing name space is " + addressingNamespace);
// If acksTo has not been set, then default to anonymous, using the correct spec level
EndpointReference acksToEPR = rmsBean.getAcksToEndpointReference();
if(acksToEPR == null){
acksToEPR = new EndpointReference(SpecSpecificConstants.getAddressingAnonymousURI(addressingNamespace));
}
CreateSequence createSequencePart = new CreateSequence(rmNamespaceValue);
// Check if this service includes 2-way operations
boolean twoWayService = false;
AxisService service = applicationMsgContext.getAxisService();
if(service != null) {
Parameter p = service.getParameter(Sandesha2Constants.SERVICE_CONTAINS_OUT_IN_MEPS);
if(p != null && p.getValue() != null) {
twoWayService = ((Boolean) p.getValue()).booleanValue();
if(log.isDebugEnabled()) log.debug("RMMsgCreator:: twoWayService " + twoWayService);
}
}
// Adding sequence offer - if present. We send an offer if the client has assigned an
// id, or if we are using WS-RM 1.0 and the service contains out-in MEPs
boolean autoOffer = false;
if(Sandesha2Constants.SPEC_2005_02.NS_URI.equals(rmNamespaceValue)) {
autoOffer = twoWayService;
+ //There may not have been a way to confirm if an OUT_IN MEP is being used.
+ //Therefore doing an extra check to see what Axis is using. If it's OUT_IN then we must offer.
+ if(applicationMsgContext.getOperationContext().getAxisOperation().getAxisSpecificMEPConstant() == org.apache.axis2.wsdl.WSDLConstants.MEP_CONSTANT_OUT_IN
+ || applicationMsgContext.getOperationContext().getAxisOperation().getAxisSpecificMEPConstant() == org.apache.axis2.wsdl.WSDLConstants.MEP_CONSTANT_OUT_OPTIONAL_IN){
+ autoOffer = true;
+ }
} else {
// We also do some checking at this point to see if MakeConection is required to
// enable WS-RM 1.1, and write a warning to the log if it has been disabled.
SandeshaPolicyBean policy = SandeshaUtil.getPropertyBean(context.getAxisConfiguration());
if(twoWayService && !policy.isEnableMakeConnection()) {
String message = SandeshaMessageHelper.getMessage(SandeshaMessageKeys.makeConnectionWarning);
log.warn(message);
}
}
String offeredSequenceId = (String) applicationMsgContext.getProperty(SandeshaClientConstants.OFFERED_SEQUENCE_ID);
if(autoOffer ||
(offeredSequenceId != null && offeredSequenceId.length() > 0)) {
if (offeredSequenceId == null || offeredSequenceId.length() == 0) {
offeredSequenceId = SandeshaUtil.getUUID();
}
SequenceOffer offerPart = new SequenceOffer(rmNamespaceValue);
Identifier identifier = new Identifier(rmNamespaceValue);
identifier.setIndentifer(offeredSequenceId);
offerPart.setIdentifier(identifier);
createSequencePart.setSequenceOffer(offerPart);
if (Sandesha2Constants.SPEC_2007_02.NS_URI.equals(rmNamespaceValue)) {
// We are going to send an offer, so decide which endpoint to include
EndpointReference offeredEndpoint = (EndpointReference) applicationMsgContext.getProperty(SandeshaClientConstants.OFFERED_ENDPOINT);
if (offeredEndpoint==null) {
EndpointReference replyTo = applicationMsgContext.getReplyTo(); //using replyTo as the Endpoint if it is not specified
if (replyTo!=null) {
offeredEndpoint = SandeshaUtil.cloneEPR(replyTo);
}
}
// Finally fall back to using an anonymous endpoint
if (offeredEndpoint==null) {
//The replyTo has already been set to a MC anon with UUID and so will use that same one for the offered endpoint
offeredEndpoint = rmsBean.getReplyToEndpointReference();
}
Endpoint endpoint = new Endpoint (offeredEndpoint, rmNamespaceValue, addressingNamespace);
offerPart.setEndpoint(endpoint);
}
}
EndpointReference toEPR = rmsBean.getToEndpointReference();
if (toEPR == null || toEPR.getAddress()==null) {
String message = SandeshaMessageHelper
.getMessage(SandeshaMessageKeys.toBeanNotSet);
throw new SandeshaException(message);
}
createSeqRMMsg.setTo(toEPR);
if(log.isDebugEnabled()) log.debug("RMMsgCreator:: toEPR=" + toEPR);
EndpointReference replyToEPR = rmsBean.getReplyToEndpointReference();
if(replyToEPR != null) {
replyToEPR = SandeshaUtil.getEPRDecorator(createSeqRMMsg.getConfigurationContext()).decorateEndpointReference(replyToEPR);
createSeqRMMsg.setReplyTo(replyToEPR);
if(log.isDebugEnabled()) log.debug("RMMsgCreator:: replyToEPR=" + replyToEPR);
}
AcksTo acksTo = new AcksTo(acksToEPR, rmNamespaceValue, addressingNamespace);
createSequencePart.setAcksTo(acksTo);
if(log.isDebugEnabled()) log.debug("RMMsgCreator:: acksTo=" + acksTo);
createSeqRMMsg.setCreateSequence(createSequencePart);
// Find the token that should be used to secure this new sequence. If there is a token, then we
// save it in the properties so that the caller can store the token within the create sequence
// bean.
SecurityManager secMgr = SandeshaUtil.getSecurityManager(context);
SecurityToken token = secMgr.getSecurityToken(applicationMsgContext);
if(token != null) {
OMElement str = secMgr.createSecurityTokenReference(token, createSeqmsgContext);
createSequencePart.setSecurityTokenReference(str);
createSeqRMMsg.setProperty(Sandesha2Constants.MessageContextProperties.SECURITY_TOKEN, token);
// If we are using token based security, and the 1.1 spec level, then we
// should introduce a UsesSequenceSTR header into the message.
if(createSequencePart.getNamespaceValue().equals(Sandesha2Constants.SPEC_2007_02.NS_URI)) {
UsesSequenceSTR usesSeqStr = new UsesSequenceSTR();
usesSeqStr.toHeader(createSeqmsgContext.getEnvelope().getHeader());
}
// Ensure that the correct token will be used to secure the outbound create sequence message.
// We cannot use the normal helper method as we have not stored the token into the sequence bean yet.
secMgr.applySecurityToken(token, createSeqRMMsg.getMessageContext());
}
createSeqRMMsg.setAction(SpecSpecificConstants.getCreateSequenceAction(rmsBean.getRMVersion()));
createSeqRMMsg.setSOAPAction(SpecSpecificConstants.getCreateSequenceSOAPAction(rmsBean.getRMVersion()));
createSeqRMMsg.addSOAPEnvelope();
if(log.isDebugEnabled()) log.debug("Entry: RMMsgCreator::createCreateSeqMsg " + createSeqRMMsg);
return createSeqRMMsg;
}
/**
* Creates a new TerminateSequence message.
*
* @param referenceRMMessage
* @return
* @throws SandeshaException
*/
public static RMMsgContext createTerminateSequenceMessage(RMMsgContext referenceRMMessage, RMSBean rmsBean,
StorageManager storageManager) throws AxisFault {
MessageContext referenceMessage = referenceRMMessage.getMessageContext();
if (referenceMessage == null)
throw new SandeshaException(SandeshaMessageHelper.getMessage(SandeshaMessageKeys.msgContextNotSet));
AxisOperation terminateOperation = SpecSpecificConstants.getWSRMOperation(
Sandesha2Constants.MessageTypes.TERMINATE_SEQ,
rmsBean.getRMVersion(),
referenceMessage.getAxisService());
ConfigurationContext configCtx = referenceMessage.getConfigurationContext();
if (configCtx == null)
throw new SandeshaException(SandeshaMessageHelper.getMessage(SandeshaMessageKeys.configContextNotSet));
MessageContext terminateMessage = SandeshaUtil.createNewRelatedMessageContext(referenceRMMessage,
terminateOperation);
if (terminateMessage == null)
throw new SandeshaException(SandeshaMessageHelper.getMessage(SandeshaMessageKeys.msgContextNotSet));
if (terminateMessage.getMessageID()==null) {
terminateMessage.setMessageID(SandeshaUtil.getUUID());
}
OperationContext operationContext = terminateMessage.getOperationContext();
// to receive terminate sequence response messages correctly
configCtx.registerOperationContext(terminateMessage.getMessageID(), operationContext);
String rmNamespaceValue = SpecSpecificConstants.getRMNamespaceValue(rmsBean.getRMVersion());
RMMsgContext terminateRMMessage = MsgInitializer.initializeMessage(terminateMessage);
TerminateSequence terminateSequencePart = new TerminateSequence(rmNamespaceValue);
Identifier identifier = new Identifier(rmNamespaceValue);
identifier.setIndentifer(rmsBean.getSequenceID());
terminateSequencePart.setIdentifier(identifier);
terminateRMMessage.setTerminateSequence(terminateSequencePart);
if(TerminateSequence.isLastMsgNumberRequired(rmNamespaceValue)){
LastMessageNumber lastMsgNumber = new LastMessageNumber(rmNamespaceValue);
lastMsgNumber.setMessageNumber(SandeshaUtil.getLastMessageNumber(rmsBean.getInternalSequenceID(), storageManager));
terminateSequencePart.setLastMessageNumber(lastMsgNumber);
}
// no need for an incoming transport for a terminate
// message. If this is put, sender will look for an response.
terminateMessage.setProperty(MessageContext.TRANSPORT_IN, null);
terminateMessage.setTo(rmsBean.getToEndpointReference());
// Ensure the correct token is used to secure the terminate sequence
secureOutboundMessage(rmsBean, terminateMessage);
return terminateRMMessage;
}
/**
* Create a new CreateSequenceResponse message.
*
* @param createSeqMessage
* @param outMessage
* @param newSequenceID
* @return
* @throws AxisFault
*/
public static RMMsgContext createCreateSeqResponseMsg(RMMsgContext createSeqMessage, RMSequenceBean rmSequenceBean) throws AxisFault {
if(log.isDebugEnabled()) log.debug("Entry: RMMsgCreator::createCreateSeqResponseMsg " + rmSequenceBean);
CreateSequence cs = createSeqMessage.getCreateSequence();
String namespace = createSeqMessage.getRMNamespaceValue();
CreateSequenceResponse response = new CreateSequenceResponse(namespace);
Identifier identifier = new Identifier(namespace);
identifier.setIndentifer(rmSequenceBean.getSequenceID());
response.setIdentifier(identifier);
SequenceOffer offer = cs.getSequenceOffer();
if (offer != null) {
if(log.isDebugEnabled()) log.debug("RMMsgCreator:: " + offer);
String outSequenceId = offer.getIdentifer().getIdentifier();
if (outSequenceId != null && !"".equals(outSequenceId)) {
Accept accept = new Accept(namespace);
// Putting the To EPR as the AcksTo for the response sequence. We echo back the
// addressing version that the create used.
String addressingNamespace = cs.getAddressingNamespaceValue();
EndpointReference acksToEPR = createSeqMessage.getTo();
if(acksToEPR != null) {
acksToEPR = SandeshaUtil.cloneEPR(acksToEPR);
} else {
String anon = SpecSpecificConstants.getAddressingAnonymousURI(addressingNamespace);
acksToEPR = new EndpointReference(anon);
}
AcksTo acksTo = new AcksTo(acksToEPR, namespace, cs.getAddressingNamespaceValue());
accept.setAcksTo(acksTo);
response.setAccept(accept);
}
}
String version = SpecSpecificConstants.getSpecVersionString(namespace);
String action = SpecSpecificConstants.getCreateSequenceResponseAction(version);
RMMsgContext returnRMContext = createResponseMsg(createSeqMessage, rmSequenceBean, response,
Sandesha2Constants.MessageParts.CREATE_SEQ_RESPONSE,action);
returnRMContext.setTo(createSeqMessage.getReplyTo()); //CSResponse goes to the replyTo, NOT the acksTo
if(log.isDebugEnabled()) log.debug("Exit: RMMsgCreator::createCreateSeqResponseMsg " + returnRMContext);
return returnRMContext;
}
public static RMMsgContext createTerminateSeqResponseMsg(RMMsgContext terminateSeqRMMsg, RMSequenceBean rmSequenceBean) throws AxisFault {
if(log.isDebugEnabled())
log.debug("Entry: RMMsgCreator::createTerminateSeqResponseMsg " + rmSequenceBean);
TerminateSequence terminateSequence = terminateSeqRMMsg.getTerminateSequence();
String sequenceID = terminateSequence.getIdentifier().getIdentifier();
String namespace = terminateSeqRMMsg.getRMNamespaceValue();
TerminateSequenceResponse terminateSequenceResponse = new TerminateSequenceResponse(namespace);
Identifier identifier = new Identifier(namespace);
identifier.setIndentifer(sequenceID);
terminateSequenceResponse.setIdentifier(identifier);
String version = SpecSpecificConstants.getSpecVersionString(namespace);
String action = SpecSpecificConstants.getTerminateSequenceResponseAction(version);
RMMsgContext returnRMContext = createResponseMsg(terminateSeqRMMsg, rmSequenceBean, terminateSequenceResponse,
Sandesha2Constants.MessageParts.TERMINATE_SEQ_RESPONSE, action);
if(rmSequenceBean.getAcksToEndpointReference()!=null){
returnRMContext.setTo(rmSequenceBean.getAcksToEndpointReference()); //RSP requirement
}
if(log.isDebugEnabled())
log.debug("Exit: RMMsgCreator::createTerminateSeqResponseMsg " + returnRMContext);
return returnRMContext;
}
public static RMMsgContext createCloseSeqResponseMsg(RMMsgContext closeSeqRMMsg, RMSequenceBean rmSequenceBean) throws AxisFault {
if(log.isDebugEnabled())
log.debug("Entry: RMMsgCreator::createCloseSeqResponseMsg " + rmSequenceBean);
CloseSequence closeSequence = closeSeqRMMsg.getCloseSequence();
String sequenceID = closeSequence.getIdentifier().getIdentifier();
String namespace = closeSeqRMMsg.getRMNamespaceValue();
CloseSequenceResponse closeSequenceResponse = new CloseSequenceResponse(namespace);
Identifier identifier = new Identifier(namespace);
identifier.setIndentifer(sequenceID);
closeSequenceResponse.setIdentifier(identifier);
String version = SpecSpecificConstants.getSpecVersionString(namespace);
String action = SpecSpecificConstants.getCloseSequenceResponseAction(version);
RMMsgContext returnRMContext = createResponseMsg(closeSeqRMMsg, rmSequenceBean, closeSequenceResponse,
Sandesha2Constants.MessageParts.CLOSE_SEQUENCE_RESPONSE, action);
if(rmSequenceBean.getAcksToEndpointReference()!=null){
returnRMContext.setTo(rmSequenceBean.getAcksToEndpointReference()); //RSP requirement
}
if(log.isDebugEnabled())
log.debug("Exit: RMMsgCreator::createCloseSeqResponseMsg " + returnRMContext);
return returnRMContext;
}
/**
* This will create a response message context using the Axis2 Util methods (where things like relatesTo transformation will
* happen). This will also make sure that created out message is correctly secured using the Sequence Token Data of the sequence.
*
* @param requestMsg The request message
* @param rmSequenceBean
* @param part
* @param messagePartId
* @param action
* @return
* @throws AxisFault
*/
private static RMMsgContext createResponseMsg(RMMsgContext requestMsg, RMSequenceBean rmSequenceBean, IOMRMPart part,
int messagePartId, String action) throws AxisFault {
MessageContext outMessage = MessageContextBuilder.createOutMessageContext (requestMsg.getMessageContext());
RMMsgContext responseRMMsg = new RMMsgContext(outMessage);
SOAPFactory factory = SOAPAbstractFactory.getSOAPFactory(SandeshaUtil.getSOAPVersion(requestMsg.getSOAPEnvelope()));
String namespace = requestMsg.getRMNamespaceValue();
responseRMMsg.setRMNamespaceValue(namespace);
SOAPEnvelope envelope = factory.getDefaultEnvelope();
responseRMMsg.setSOAPEnvelop(envelope);
switch(messagePartId){
case Sandesha2Constants.MessageParts.CLOSE_SEQUENCE_RESPONSE: responseRMMsg.setCloseSequenceResponse((CloseSequenceResponse) part);break;
case Sandesha2Constants.MessageParts.TERMINATE_SEQ_RESPONSE: responseRMMsg.setTerminateSequenceResponse((TerminateSequenceResponse) part);break;
case Sandesha2Constants.MessageParts.CREATE_SEQ_RESPONSE: responseRMMsg.setCreateSequenceResponse((CreateSequenceResponse) part);break;
default: throw new RuntimeException(SandeshaMessageHelper.getMessage(SandeshaMessageKeys.internalError));
}
outMessage.setWSAAction(action);
outMessage.setSoapAction(action);
responseRMMsg.addSOAPEnvelope();
responseRMMsg.getMessageContext().setServerSide(true);
// Ensure the correct token is used to secure the message
secureOutboundMessage(rmSequenceBean, outMessage);
return responseRMMsg;
}
/**
* Adds an Ack of specific sequence to the given application message.
*
* @param applicationMsg The Message to which the Ack will be added
* @param sequenceId - The sequence to which we will be Acking
* @throws SandeshaException
*/
public static void addAckMessage(RMMsgContext applicationMsg, String sequenceId, RMDBean rmdBean, boolean addToEnvelope)
throws SandeshaException {
if(LoggingControl.isAnyTracingEnabled() && log.isDebugEnabled())
log.debug("Entry: RMMsgCreator::addAckMessage " + sequenceId);
String rmVersion = rmdBean.getRMVersion();
String rmNamespaceValue = SpecSpecificConstants.getRMNamespaceValue(rmVersion);
ArrayList ackRangeArrayList = SandeshaUtil.getAckRangeArrayList(rmdBean.getServerCompletedMessages(), rmNamespaceValue);
if(ackRangeArrayList!=null && ackRangeArrayList.size()!=0){
if(LoggingControl.isAnyTracingEnabled() && log.isDebugEnabled())
log.debug("RMMsgCreator::addAckMessage : there are messages to ack " + ackRangeArrayList);
//there are actually messages to ack
SequenceAcknowledgement sequenceAck = new SequenceAcknowledgement(rmNamespaceValue);
Identifier id = new Identifier(rmNamespaceValue);
id.setIndentifer(sequenceId);
sequenceAck.setIdentifier(id);
sequenceAck.setAckRanges(ackRangeArrayList);
if (rmdBean.isClosed()) {
// sequence is closed. so add the 'Final' part.
if(LoggingControl.isAnyTracingEnabled() && log.isDebugEnabled())
log.debug("RMMsgCreator::addAckMessage : sequence closed");
if (SpecSpecificConstants.isAckFinalAllowed(rmVersion)) {
sequenceAck.setAckFinal(true);
}
}
applicationMsg.addSequenceAcknowledgement(sequenceAck);
if (applicationMsg.getWSAAction()==null) {
applicationMsg.setAction(SpecSpecificConstants.getSequenceAcknowledgementAction(rmVersion));
applicationMsg.setSOAPAction(SpecSpecificConstants.getSequenceAcknowledgementSOAPAction(rmVersion));
}
if(applicationMsg.getMessageId() == null) {
applicationMsg.setMessageId(SandeshaUtil.getUUID());
}
if(addToEnvelope){
// Write the ack into the soap envelope
try {
applicationMsg.addSOAPEnvelope();
} catch(AxisFault e) {
if(LoggingControl.isAnyTracingEnabled() && log.isDebugEnabled()) log.debug("Caught AxisFault", e);
throw new SandeshaException(e.getMessage(), e);
}
}else{
// Should use a constant in the final fix.
applicationMsg.setProperty(ACK_TO_BE_WRITTEN, Boolean.TRUE);
}
// Ensure the message also contains the token that needs to be used
secureOutboundMessage(rmdBean, applicationMsg.getMessageContext());
}
if(LoggingControl.isAnyTracingEnabled() && log.isDebugEnabled())
log.debug("Exit: RMMsgCreator::addAckMessage " + applicationMsg);
}
public static RMMsgContext createMakeConnectionMessage (RMMsgContext referenceRMMessage,
RMSequenceBean bean,
String makeConnectionSeqId,
String makeConnectionAnonURI)
throws AxisFault
{
MessageContext referenceMessage = referenceRMMessage.getMessageContext();
String rmNamespaceValue = referenceRMMessage.getRMNamespaceValue();
String rmVersion = referenceRMMessage.getRMSpecVersion();
AxisOperation makeConnectionOperation = SpecSpecificConstants.getWSRMOperation(
Sandesha2Constants.MessageTypes.MAKE_CONNECTION_MSG,
rmVersion,
referenceMessage.getAxisService());
MessageContext makeConnectionMessageCtx = SandeshaUtil.createNewRelatedMessageContext(referenceRMMessage,makeConnectionOperation);
RMMsgContext makeConnectionRMMessageCtx = MsgInitializer.initializeMessage(makeConnectionMessageCtx);
MakeConnection makeConnection = new MakeConnection();
if (makeConnectionSeqId!=null) {
Identifier identifier = new Identifier (rmNamespaceValue);
identifier.setIndentifer(makeConnectionSeqId);
makeConnection.setIdentifier(identifier);
}
if (makeConnectionAnonURI!=null) {
makeConnection.setAddress(makeConnectionAnonURI);
}
// Setting the addressing properties. As this is a poll we must send it to an non-anon
// EPR, so we check both To and ReplyTo from the reference message
EndpointReference epr = referenceMessage.getTo();
if(epr.hasAnonymousAddress()) epr = referenceMessage.getReplyTo();
makeConnectionMessageCtx.setTo(epr);
makeConnectionMessageCtx.setWSAAction(SpecSpecificConstants.getMakeConnectionAction(rmVersion));
makeConnectionMessageCtx.setMessageID(SandeshaUtil.getUUID());
makeConnectionRMMessageCtx.setMakeConnection(makeConnection);
//generating the SOAP Envelope.
makeConnectionRMMessageCtx.addSOAPEnvelope();
// Secure the message using the correct token for the sequence that we are polling
secureOutboundMessage(bean, makeConnectionMessageCtx);
return makeConnectionRMMessageCtx;
}
/**
* This will add necessary data to a out-bound message to make sure that is is correctly secured.
* Security Token Data will be taken from the Sandesha2 security manager.
*
* @param rmBean Sequence bean to identify the sequence. This could be an in-bound sequence or an out-bound sequence.
* @param message - The message which will be secured.
* @throws SandeshaException
*/
public static void secureOutboundMessage(RMSequenceBean rmBean, MessageContext message)
throws SandeshaException
{
if(LoggingControl.isAnyTracingEnabled() && log.isDebugEnabled()) log.debug("Entry: RMMsgCreator::secureOutboundMessage");
ConfigurationContext configCtx = message.getConfigurationContext();
if(rmBean.getSecurityTokenData() != null) {
if(LoggingControl.isAnyTracingEnabled() && log.isDebugEnabled()) log.debug("Securing outbound message");
SecurityManager secManager = SandeshaUtil.getSecurityManager(configCtx);
SecurityToken token = secManager.recoverSecurityToken(rmBean.getSecurityTokenData());
secManager.applySecurityToken(token, message);
}
if(LoggingControl.isAnyTracingEnabled() && log.isDebugEnabled()) log.debug("Exit: RMMsgCreator::secureOutboundMessage");
}
}
| true | true | public static RMMsgContext createCreateSeqMsg(RMSBean rmsBean, RMMsgContext applicationRMMsg) throws AxisFault {
if(log.isDebugEnabled()) log.debug("Entry: RMMsgCreator::createCreateSeqMsg " + applicationRMMsg);
MessageContext applicationMsgContext = applicationRMMsg.getMessageContext();
if (applicationMsgContext == null)
throw new SandeshaException(SandeshaMessageHelper.getMessage(SandeshaMessageKeys.appMsgIsNull));
ConfigurationContext context = applicationMsgContext.getConfigurationContext();
if (context == null)
throw new SandeshaException(SandeshaMessageHelper.getMessage(SandeshaMessageKeys.configContextNotSet));
// creating by copying common contents. (this will not set contexts
// except for configCtx).
AxisOperation createSequenceOperation = SpecSpecificConstants.getWSRMOperation(
Sandesha2Constants.MessageTypes.CREATE_SEQ,
rmsBean.getRMVersion(),
applicationMsgContext.getAxisService());
MessageContext createSeqmsgContext = SandeshaUtil
.createNewRelatedMessageContext(applicationRMMsg, createSequenceOperation);
OperationContext createSeqOpCtx = createSeqmsgContext.getOperationContext();
String createSeqMsgId = SandeshaUtil.getUUID();
createSeqmsgContext.setMessageID(createSeqMsgId);
context.registerOperationContext(createSeqMsgId, createSeqOpCtx);
RMMsgContext createSeqRMMsg = new RMMsgContext(createSeqmsgContext);
String rmNamespaceValue = SpecSpecificConstants.getRMNamespaceValue(rmsBean.getRMVersion());
// Decide which addressing version to use. We copy the version that the application
// is already using (if set), and fall back to the level in the spec if that isn't
// found.
String addressingNamespace = (String) applicationMsgContext.getProperty(AddressingConstants.WS_ADDRESSING_VERSION);
Boolean disableAddressing = (Boolean) applicationMsgContext.getProperty(AddressingConstants.DISABLE_ADDRESSING_FOR_OUT_MESSAGES);
if(addressingNamespace == null) {
// Addressing may still be enabled, as it defaults to the final spec. The only time
// we follow the RM spec is when addressing has been explicitly disabled.
if(disableAddressing != null && disableAddressing.booleanValue())
addressingNamespace = SpecSpecificConstants.getAddressingNamespace(rmNamespaceValue);
else
addressingNamespace = AddressingConstants.Final.WSA_NAMESPACE;
}
if(log.isDebugEnabled()) log.debug("RMMsgCreator:: addressing name space is " + addressingNamespace);
// If acksTo has not been set, then default to anonymous, using the correct spec level
EndpointReference acksToEPR = rmsBean.getAcksToEndpointReference();
if(acksToEPR == null){
acksToEPR = new EndpointReference(SpecSpecificConstants.getAddressingAnonymousURI(addressingNamespace));
}
CreateSequence createSequencePart = new CreateSequence(rmNamespaceValue);
// Check if this service includes 2-way operations
boolean twoWayService = false;
AxisService service = applicationMsgContext.getAxisService();
if(service != null) {
Parameter p = service.getParameter(Sandesha2Constants.SERVICE_CONTAINS_OUT_IN_MEPS);
if(p != null && p.getValue() != null) {
twoWayService = ((Boolean) p.getValue()).booleanValue();
if(log.isDebugEnabled()) log.debug("RMMsgCreator:: twoWayService " + twoWayService);
}
}
// Adding sequence offer - if present. We send an offer if the client has assigned an
// id, or if we are using WS-RM 1.0 and the service contains out-in MEPs
boolean autoOffer = false;
if(Sandesha2Constants.SPEC_2005_02.NS_URI.equals(rmNamespaceValue)) {
autoOffer = twoWayService;
} else {
// We also do some checking at this point to see if MakeConection is required to
// enable WS-RM 1.1, and write a warning to the log if it has been disabled.
SandeshaPolicyBean policy = SandeshaUtil.getPropertyBean(context.getAxisConfiguration());
if(twoWayService && !policy.isEnableMakeConnection()) {
String message = SandeshaMessageHelper.getMessage(SandeshaMessageKeys.makeConnectionWarning);
log.warn(message);
}
}
String offeredSequenceId = (String) applicationMsgContext.getProperty(SandeshaClientConstants.OFFERED_SEQUENCE_ID);
if(autoOffer ||
(offeredSequenceId != null && offeredSequenceId.length() > 0)) {
if (offeredSequenceId == null || offeredSequenceId.length() == 0) {
offeredSequenceId = SandeshaUtil.getUUID();
}
SequenceOffer offerPart = new SequenceOffer(rmNamespaceValue);
Identifier identifier = new Identifier(rmNamespaceValue);
identifier.setIndentifer(offeredSequenceId);
offerPart.setIdentifier(identifier);
createSequencePart.setSequenceOffer(offerPart);
if (Sandesha2Constants.SPEC_2007_02.NS_URI.equals(rmNamespaceValue)) {
// We are going to send an offer, so decide which endpoint to include
EndpointReference offeredEndpoint = (EndpointReference) applicationMsgContext.getProperty(SandeshaClientConstants.OFFERED_ENDPOINT);
if (offeredEndpoint==null) {
EndpointReference replyTo = applicationMsgContext.getReplyTo(); //using replyTo as the Endpoint if it is not specified
if (replyTo!=null) {
offeredEndpoint = SandeshaUtil.cloneEPR(replyTo);
}
}
// Finally fall back to using an anonymous endpoint
if (offeredEndpoint==null) {
//The replyTo has already been set to a MC anon with UUID and so will use that same one for the offered endpoint
offeredEndpoint = rmsBean.getReplyToEndpointReference();
}
Endpoint endpoint = new Endpoint (offeredEndpoint, rmNamespaceValue, addressingNamespace);
offerPart.setEndpoint(endpoint);
}
}
EndpointReference toEPR = rmsBean.getToEndpointReference();
if (toEPR == null || toEPR.getAddress()==null) {
String message = SandeshaMessageHelper
.getMessage(SandeshaMessageKeys.toBeanNotSet);
throw new SandeshaException(message);
}
createSeqRMMsg.setTo(toEPR);
if(log.isDebugEnabled()) log.debug("RMMsgCreator:: toEPR=" + toEPR);
EndpointReference replyToEPR = rmsBean.getReplyToEndpointReference();
if(replyToEPR != null) {
replyToEPR = SandeshaUtil.getEPRDecorator(createSeqRMMsg.getConfigurationContext()).decorateEndpointReference(replyToEPR);
createSeqRMMsg.setReplyTo(replyToEPR);
if(log.isDebugEnabled()) log.debug("RMMsgCreator:: replyToEPR=" + replyToEPR);
}
AcksTo acksTo = new AcksTo(acksToEPR, rmNamespaceValue, addressingNamespace);
createSequencePart.setAcksTo(acksTo);
if(log.isDebugEnabled()) log.debug("RMMsgCreator:: acksTo=" + acksTo);
createSeqRMMsg.setCreateSequence(createSequencePart);
// Find the token that should be used to secure this new sequence. If there is a token, then we
// save it in the properties so that the caller can store the token within the create sequence
// bean.
SecurityManager secMgr = SandeshaUtil.getSecurityManager(context);
SecurityToken token = secMgr.getSecurityToken(applicationMsgContext);
if(token != null) {
OMElement str = secMgr.createSecurityTokenReference(token, createSeqmsgContext);
createSequencePart.setSecurityTokenReference(str);
createSeqRMMsg.setProperty(Sandesha2Constants.MessageContextProperties.SECURITY_TOKEN, token);
// If we are using token based security, and the 1.1 spec level, then we
// should introduce a UsesSequenceSTR header into the message.
if(createSequencePart.getNamespaceValue().equals(Sandesha2Constants.SPEC_2007_02.NS_URI)) {
UsesSequenceSTR usesSeqStr = new UsesSequenceSTR();
usesSeqStr.toHeader(createSeqmsgContext.getEnvelope().getHeader());
}
// Ensure that the correct token will be used to secure the outbound create sequence message.
// We cannot use the normal helper method as we have not stored the token into the sequence bean yet.
secMgr.applySecurityToken(token, createSeqRMMsg.getMessageContext());
}
createSeqRMMsg.setAction(SpecSpecificConstants.getCreateSequenceAction(rmsBean.getRMVersion()));
createSeqRMMsg.setSOAPAction(SpecSpecificConstants.getCreateSequenceSOAPAction(rmsBean.getRMVersion()));
createSeqRMMsg.addSOAPEnvelope();
if(log.isDebugEnabled()) log.debug("Entry: RMMsgCreator::createCreateSeqMsg " + createSeqRMMsg);
return createSeqRMMsg;
}
| public static RMMsgContext createCreateSeqMsg(RMSBean rmsBean, RMMsgContext applicationRMMsg) throws AxisFault {
if(log.isDebugEnabled()) log.debug("Entry: RMMsgCreator::createCreateSeqMsg " + applicationRMMsg);
MessageContext applicationMsgContext = applicationRMMsg.getMessageContext();
if (applicationMsgContext == null)
throw new SandeshaException(SandeshaMessageHelper.getMessage(SandeshaMessageKeys.appMsgIsNull));
ConfigurationContext context = applicationMsgContext.getConfigurationContext();
if (context == null)
throw new SandeshaException(SandeshaMessageHelper.getMessage(SandeshaMessageKeys.configContextNotSet));
// creating by copying common contents. (this will not set contexts
// except for configCtx).
AxisOperation createSequenceOperation = SpecSpecificConstants.getWSRMOperation(
Sandesha2Constants.MessageTypes.CREATE_SEQ,
rmsBean.getRMVersion(),
applicationMsgContext.getAxisService());
MessageContext createSeqmsgContext = SandeshaUtil
.createNewRelatedMessageContext(applicationRMMsg, createSequenceOperation);
OperationContext createSeqOpCtx = createSeqmsgContext.getOperationContext();
String createSeqMsgId = SandeshaUtil.getUUID();
createSeqmsgContext.setMessageID(createSeqMsgId);
context.registerOperationContext(createSeqMsgId, createSeqOpCtx);
RMMsgContext createSeqRMMsg = new RMMsgContext(createSeqmsgContext);
String rmNamespaceValue = SpecSpecificConstants.getRMNamespaceValue(rmsBean.getRMVersion());
// Decide which addressing version to use. We copy the version that the application
// is already using (if set), and fall back to the level in the spec if that isn't
// found.
String addressingNamespace = (String) applicationMsgContext.getProperty(AddressingConstants.WS_ADDRESSING_VERSION);
Boolean disableAddressing = (Boolean) applicationMsgContext.getProperty(AddressingConstants.DISABLE_ADDRESSING_FOR_OUT_MESSAGES);
if(addressingNamespace == null) {
// Addressing may still be enabled, as it defaults to the final spec. The only time
// we follow the RM spec is when addressing has been explicitly disabled.
if(disableAddressing != null && disableAddressing.booleanValue())
addressingNamespace = SpecSpecificConstants.getAddressingNamespace(rmNamespaceValue);
else
addressingNamespace = AddressingConstants.Final.WSA_NAMESPACE;
}
if(log.isDebugEnabled()) log.debug("RMMsgCreator:: addressing name space is " + addressingNamespace);
// If acksTo has not been set, then default to anonymous, using the correct spec level
EndpointReference acksToEPR = rmsBean.getAcksToEndpointReference();
if(acksToEPR == null){
acksToEPR = new EndpointReference(SpecSpecificConstants.getAddressingAnonymousURI(addressingNamespace));
}
CreateSequence createSequencePart = new CreateSequence(rmNamespaceValue);
// Check if this service includes 2-way operations
boolean twoWayService = false;
AxisService service = applicationMsgContext.getAxisService();
if(service != null) {
Parameter p = service.getParameter(Sandesha2Constants.SERVICE_CONTAINS_OUT_IN_MEPS);
if(p != null && p.getValue() != null) {
twoWayService = ((Boolean) p.getValue()).booleanValue();
if(log.isDebugEnabled()) log.debug("RMMsgCreator:: twoWayService " + twoWayService);
}
}
// Adding sequence offer - if present. We send an offer if the client has assigned an
// id, or if we are using WS-RM 1.0 and the service contains out-in MEPs
boolean autoOffer = false;
if(Sandesha2Constants.SPEC_2005_02.NS_URI.equals(rmNamespaceValue)) {
autoOffer = twoWayService;
//There may not have been a way to confirm if an OUT_IN MEP is being used.
//Therefore doing an extra check to see what Axis is using. If it's OUT_IN then we must offer.
if(applicationMsgContext.getOperationContext().getAxisOperation().getAxisSpecificMEPConstant() == org.apache.axis2.wsdl.WSDLConstants.MEP_CONSTANT_OUT_IN
|| applicationMsgContext.getOperationContext().getAxisOperation().getAxisSpecificMEPConstant() == org.apache.axis2.wsdl.WSDLConstants.MEP_CONSTANT_OUT_OPTIONAL_IN){
autoOffer = true;
}
} else {
// We also do some checking at this point to see if MakeConection is required to
// enable WS-RM 1.1, and write a warning to the log if it has been disabled.
SandeshaPolicyBean policy = SandeshaUtil.getPropertyBean(context.getAxisConfiguration());
if(twoWayService && !policy.isEnableMakeConnection()) {
String message = SandeshaMessageHelper.getMessage(SandeshaMessageKeys.makeConnectionWarning);
log.warn(message);
}
}
String offeredSequenceId = (String) applicationMsgContext.getProperty(SandeshaClientConstants.OFFERED_SEQUENCE_ID);
if(autoOffer ||
(offeredSequenceId != null && offeredSequenceId.length() > 0)) {
if (offeredSequenceId == null || offeredSequenceId.length() == 0) {
offeredSequenceId = SandeshaUtil.getUUID();
}
SequenceOffer offerPart = new SequenceOffer(rmNamespaceValue);
Identifier identifier = new Identifier(rmNamespaceValue);
identifier.setIndentifer(offeredSequenceId);
offerPart.setIdentifier(identifier);
createSequencePart.setSequenceOffer(offerPart);
if (Sandesha2Constants.SPEC_2007_02.NS_URI.equals(rmNamespaceValue)) {
// We are going to send an offer, so decide which endpoint to include
EndpointReference offeredEndpoint = (EndpointReference) applicationMsgContext.getProperty(SandeshaClientConstants.OFFERED_ENDPOINT);
if (offeredEndpoint==null) {
EndpointReference replyTo = applicationMsgContext.getReplyTo(); //using replyTo as the Endpoint if it is not specified
if (replyTo!=null) {
offeredEndpoint = SandeshaUtil.cloneEPR(replyTo);
}
}
// Finally fall back to using an anonymous endpoint
if (offeredEndpoint==null) {
//The replyTo has already been set to a MC anon with UUID and so will use that same one for the offered endpoint
offeredEndpoint = rmsBean.getReplyToEndpointReference();
}
Endpoint endpoint = new Endpoint (offeredEndpoint, rmNamespaceValue, addressingNamespace);
offerPart.setEndpoint(endpoint);
}
}
EndpointReference toEPR = rmsBean.getToEndpointReference();
if (toEPR == null || toEPR.getAddress()==null) {
String message = SandeshaMessageHelper
.getMessage(SandeshaMessageKeys.toBeanNotSet);
throw new SandeshaException(message);
}
createSeqRMMsg.setTo(toEPR);
if(log.isDebugEnabled()) log.debug("RMMsgCreator:: toEPR=" + toEPR);
EndpointReference replyToEPR = rmsBean.getReplyToEndpointReference();
if(replyToEPR != null) {
replyToEPR = SandeshaUtil.getEPRDecorator(createSeqRMMsg.getConfigurationContext()).decorateEndpointReference(replyToEPR);
createSeqRMMsg.setReplyTo(replyToEPR);
if(log.isDebugEnabled()) log.debug("RMMsgCreator:: replyToEPR=" + replyToEPR);
}
AcksTo acksTo = new AcksTo(acksToEPR, rmNamespaceValue, addressingNamespace);
createSequencePart.setAcksTo(acksTo);
if(log.isDebugEnabled()) log.debug("RMMsgCreator:: acksTo=" + acksTo);
createSeqRMMsg.setCreateSequence(createSequencePart);
// Find the token that should be used to secure this new sequence. If there is a token, then we
// save it in the properties so that the caller can store the token within the create sequence
// bean.
SecurityManager secMgr = SandeshaUtil.getSecurityManager(context);
SecurityToken token = secMgr.getSecurityToken(applicationMsgContext);
if(token != null) {
OMElement str = secMgr.createSecurityTokenReference(token, createSeqmsgContext);
createSequencePart.setSecurityTokenReference(str);
createSeqRMMsg.setProperty(Sandesha2Constants.MessageContextProperties.SECURITY_TOKEN, token);
// If we are using token based security, and the 1.1 spec level, then we
// should introduce a UsesSequenceSTR header into the message.
if(createSequencePart.getNamespaceValue().equals(Sandesha2Constants.SPEC_2007_02.NS_URI)) {
UsesSequenceSTR usesSeqStr = new UsesSequenceSTR();
usesSeqStr.toHeader(createSeqmsgContext.getEnvelope().getHeader());
}
// Ensure that the correct token will be used to secure the outbound create sequence message.
// We cannot use the normal helper method as we have not stored the token into the sequence bean yet.
secMgr.applySecurityToken(token, createSeqRMMsg.getMessageContext());
}
createSeqRMMsg.setAction(SpecSpecificConstants.getCreateSequenceAction(rmsBean.getRMVersion()));
createSeqRMMsg.setSOAPAction(SpecSpecificConstants.getCreateSequenceSOAPAction(rmsBean.getRMVersion()));
createSeqRMMsg.addSOAPEnvelope();
if(log.isDebugEnabled()) log.debug("Entry: RMMsgCreator::createCreateSeqMsg " + createSeqRMMsg);
return createSeqRMMsg;
}
|
diff --git a/src/GPEBTWTweak.java b/src/GPEBTWTweak.java
index c26040e..f17eefe 100644
--- a/src/GPEBTWTweak.java
+++ b/src/GPEBTWTweak.java
@@ -1,467 +1,467 @@
package net.minecraft.src;
import java.util.*;
import java.io.*;
import java.lang.reflect.*;
public class GPEBTWTweak extends FCAddOn
{
public static GPEBTWTweak instance;
public static GPEBTWTweakProxy proxy;
public static String tweakVersion = "0.6";
public static Block gpeBlockStone;
public static Item gpeItemLooseRock;
public static Item gpeItemSilk;
public static int gpeLooseRockID = 17000;
public static int gpeSilkID = 17001;
public static int gpeEntityRockID = 25;
public static int hcSpawnRadius = 2000;
public static int gpeEntityRockVehicleSpawnType = 120;
public static int gpeStrataRegenKey = 0;
public static String gpeStrataRegenWorldName = null;
public static Map<Long, Integer> chunkRegenInfo;
public GPEBTWTweak()
{
instance = this;
}
public void Initialize()
{
FCAddOnHandler.LogMessage("Grom PE's BTWTweak v" + tweakVersion + " is now going to tweak the hell out of this.");
try
{
Class.forName("net.minecraft.client.Minecraft");
proxy = new GPEBTWTweakProxyClient();
}
catch(ClassNotFoundException e)
{
proxy = new GPEBTWTweakProxy();
}
File config = new File(proxy.getConfigDir(), "BTWTweak.cfg");
chunkRegenInfo = new HashMap<Long, Integer>();
try
{
BufferedReader br = new BufferedReader(new FileReader(config));
String line, key, value;
while ((line = br.readLine()) != null)
{
String[] tmp = line.split("=");
if (tmp.length < 2) continue;
key = tmp[0].trim();
value = tmp[1].trim();
if (key.equals("gpeLooseRockID")) gpeLooseRockID = Integer.parseInt(value);
if (key.equals("gpeEntityRockID")) gpeEntityRockID = Integer.parseInt(value);
if (key.equals("gpeEntityRockVehicleSpawnType")) gpeEntityRockVehicleSpawnType = Integer.parseInt(value);
if (key.equals("hcSpawnRadius")) hcSpawnRadius = Integer.parseInt(value);
if (key.equals("gpeStrataRegenKey")) gpeStrataRegenKey = Integer.parseInt(value);
if (key.equals("gpeStrataRegenWorldName")) gpeStrataRegenWorldName = value;
}
br.close();
}
catch (FileNotFoundException e)
{
String defaultConfig = ""
+ "// **** BTWTweak Settings ****\r\n"
+ "\r\n"
+ "// Hardcore Spawn radius, in blocks. Changing it from default 2000 may destabilize your game balance.\r\n"
+ "\r\n"
+ "hcSpawnRadius=2000\r\n"
+ "\r\n"
+ "// **** Item IDs ****\r\n"
+ "\r\n"
+ "gpeLooseRockID=17000\r\n"
+ "gpeSilkID=17001\r\n"
+ "\r\n"
+ "// **** Entity IDs ****\r\n"
+ "\r\n"
+ "gpeEntityRockID=35\r\n"
+ "\r\n"
+ "// **** Other IDs ****\r\n"
+ "\r\n"
+ "gpeEntityRockVehicleSpawnType=120\r\n"
+ "\r\n"
+ "// **** World strata regeneration ****\r\n"
+ "\r\n"
+ "// To use, set key to non-zero and name of the world you want to process\r\n"
+ "gpeStrataRegenKey=0\r\n"
+ "gpeStrataRegenWorldName=???\r\n"
+ "";
try
{
FileOutputStream fo = new FileOutputStream(config);
fo.write(defaultConfig.getBytes());
fo.close();
}
catch (IOException e2)
{
FCAddOnHandler.LogMessage("Error while writing default BTWTweak.cfg!");
e2.printStackTrace();
}
}
catch (IOException e)
{
FCAddOnHandler.LogMessage("Error while reading BTWTweak.cfg!");
e.printStackTrace();
}
Block.blocksList[1] = null; gpeBlockStone = new GPEBlockStone(1);
Block.blocksList[4] = null; new GPEBlockCobblestone(4);
Block.blocksList[13] = null; new GPEBlockGravel(13);
Block.blocksList[65] = null; new GPEBlockLadder(65);
Block.blocksList[80] = null; new GPEBlockSnowBlock(80);
Block.blocksList[91] = null;
ItemAxe.SetAllAxesToBeEffectiveVsBlock((new FCBlockPumpkin(91, true)).setHardness(1.0F).setStepSound(Block.soundWoodFootstep).setLightValue(1.0F).setUnlocalizedName("litpumpkin"));
new GPEItemPotash(FCBetterThanWolves.fcPotash.itemID - 256);
gpeItemLooseRock = new GPEItemLooseRock(gpeLooseRockID - 256);
gpeItemSilk = new Item(gpeSilkID - 256).setUnlocalizedName("gpeItemSilk").setCreativeTab(CreativeTabs.tabMaterials).SetBuoyancy(1.0F).SetBellowsBlowDistance(2);
int id = FCBetterThanWolves.fcAestheticOpaque.blockID;
Block.blocksList[id] = null;
new GPEBlockAestheticOpaque(id);
id = FCBetterThanWolves.fcBlockDirtSlab.blockID;
Block.blocksList[id] = null;
new GPEBlockDirtSlab(id);
EntityList.addMapping(GPEEntityRock.class, "gpeEntityRock", gpeEntityRockID);
proxy.addEntityRenderers();
FCRecipes.AddVanillaRecipe(new ItemStack(FCBetterThanWolves.fcBlockDirtSlab, 4, 6), new Object[] {"##", '#', new ItemStack(Block.gravel)});
FCRecipes.AddVanillaRecipe(new ItemStack(FCBetterThanWolves.fcBlockDirtSlab, 1, 6), new Object[] {"##", '#', new ItemStack(FCBetterThanWolves.fcItemPileGravel)});
FCRecipes.AddVanillaRecipe(new ItemStack(FCBetterThanWolves.fcBlockDirtSlab, 4, 7), new Object[] {"##", '#', new ItemStack(Block.sand)});
FCRecipes.AddVanillaRecipe(new ItemStack(FCBetterThanWolves.fcBlockDirtSlab, 1, 7), new Object[] {"##", '#', new ItemStack(FCBetterThanWolves.fcItemPileSand)});
FCRecipes.AddShapelessVanillaRecipe(new ItemStack(Block.gravel), new Object[] {new ItemStack(FCBetterThanWolves.fcBlockDirtSlab, 1, 6), new ItemStack(FCBetterThanWolves.fcBlockDirtSlab, 1, 6)});
FCRecipes.AddShapelessVanillaRecipe(new ItemStack(Block.sand), new Object[] {new ItemStack(FCBetterThanWolves.fcBlockDirtSlab, 1, 7), new ItemStack(FCBetterThanWolves.fcBlockDirtSlab, 1, 7)});
FCRecipes.AddShapelessVanillaRecipe(new ItemStack(FCBetterThanWolves.fcItemPileDirt, 2), new Object[] {new ItemStack(FCBetterThanWolves.fcBlockDirtSlab)});
FCRecipes.AddShapelessVanillaRecipe(new ItemStack(FCBetterThanWolves.fcItemPileSand, 2), new Object[] {new ItemStack(FCBetterThanWolves.fcBlockDirtSlab, 1, 7)});
FCRecipes.AddShapelessVanillaRecipe(new ItemStack(FCBetterThanWolves.fcItemPileGravel, 2), new Object[] {new ItemStack(FCBetterThanWolves.fcBlockDirtSlab, 1, 6)});
FCRecipes.AddStokedCauldronRecipe(new ItemStack(FCBetterThanWolves.fcGlue, 1), new ItemStack[] {new ItemStack(Item.bone, 8)});
FCRecipes.AddStokedCauldronRecipe(new ItemStack(FCBetterThanWolves.fcGlue, 1), new ItemStack[] {new ItemStack(Item.dyePowder, 24, 15)});
if (isBTWVersionOrNewer("4.891124"))
{
int i;
for (i = 0; i < 16; i++)
{
FCRecipes.AddStokedCauldronRecipe(
new ItemStack[]
{
new ItemStack(FCBetterThanWolves.fcItemWool, 4, 15 - i),
new ItemStack(FCBetterThanWolves.fcAestheticOpaque, 1, 0)
},
new ItemStack[] {new ItemStack(Block.cloth, 1, i)});
}
}
FCRecipes.RemoveVanillaRecipe(new ItemStack(Item.axeStone), new Object[] {"X ", "X#", " #", '#', Item.stick, 'X', Block.cobblestone});
FCRecipes.AddVanillaRecipe(new ItemStack(Item.axeStone), new Object[] {"X ", "X#", " #", '#', Item.stick, 'X', gpeItemLooseRock});
FCRecipes.RemoveVanillaRecipe(new ItemStack(Item.pickaxeStone), new Object[] {"XXX", " # ", " # ", '#', Item.stick, 'X', Block.cobblestone});
FCRecipes.AddVanillaRecipe(new ItemStack(Item.pickaxeStone), new Object[] {"XXX", " # ", " # ", '#', Item.stick, 'X', gpeItemLooseRock});
FCRecipes.RemoveVanillaRecipe(new ItemStack(Item.shovelStone), new Object[] {"X", "#", "#", '#', Item.stick, 'X', Block.cobblestone});
FCRecipes.AddVanillaRecipe(new ItemStack(Item.shovelStone), new Object[] {"X", "#", "#", '#', Item.stick, 'X', gpeItemLooseRock});
FCRecipes.RemoveVanillaRecipe(new ItemStack(Block.lever, 1), new Object[] {"X", "#", "r", '#', Block.cobblestone, 'X', Item.stick, 'r', Item.redstone});
FCRecipes.AddVanillaRecipe(new ItemStack(Block.lever, 1), new Object[] {"X", "#", "r", '#', gpeItemLooseRock, 'X', Item.stick, 'r', Item.redstone});
FCRecipes.AddVanillaRecipe(new ItemStack(Block.cobblestone), new Object[] {"XX", "XX", 'X', gpeItemLooseRock});
FCRecipes.AddVanillaRecipe(new ItemStack(Block.stoneSingleSlab, 1, 3), new Object[] {"XX", 'X', gpeItemLooseRock});
FCRecipes.AddVanillaRecipe(new ItemStack(Block.cobblestone), new Object[] {"X", "X", 'X', new ItemStack(Block.stoneSingleSlab, 1, 3)});
FCRecipes.AddVanillaRecipe(new ItemStack(Block.stoneBrick), new Object[] {"X", "X", 'X', new ItemStack(Block.stoneSingleSlab, 1, 5)});
FCRecipes.AddVanillaRecipe(new ItemStack(gpeItemSilk, 1), new Object[] {"###", "###", "###", '#', Item.silk});
FCRecipes.AddShapelessVanillaRecipe(new ItemStack(Item.silk, 9), new Object[] {new ItemStack(gpeItemSilk)});
FCRecipes.AddShapelessVanillaRecipe(new ItemStack(Item.book, 1), new Object[] {Item.paper, Item.paper, Item.paper, FCBetterThanWolves.fcItemTannedLeatherCut});
FCRecipes.AddStokedCrucibleRecipe(new ItemStack[] {new ItemStack(Item.goldNugget, 3), new ItemStack(FCBetterThanWolves.fcSteel, 1)}, new ItemStack[] {new ItemStack(Block.pistonBase, 1)});
FCRecipes.AddStokedCrucibleRecipe(new ItemStack[] {new ItemStack(Item.goldNugget, 3), new ItemStack(FCBetterThanWolves.fcSteel, 1)}, new ItemStack[] {new ItemStack(Block.pistonStickyBase, 1)});
FCRecipes.RemoveShapelessVanillaRecipe(new ItemStack(FCBetterThanWolves.fcItemIngotDiamond), new Object[] {new ItemStack(Item.ingotIron), new ItemStack(Item.diamond), new ItemStack(FCBetterThanWolves.fcItemCreeperOysters)});
FCRecipes.AddCauldronRecipe(new ItemStack(FCBetterThanWolves.fcItemIngotDiamond), new ItemStack[] {new ItemStack(Item.ingotIron), new ItemStack(Item.diamond), new ItemStack(FCBetterThanWolves.fcItemCreeperOysters)});
FCRecipes.RemoveVanillaRecipe(new ItemStack(Item.bed, 1), new Object[] {"###", "XXX", '#', Block.cloth, 'X', Block.planks});
- FCRecipes.AddVanillaRecipe(new ItemStack(Item.bed, 1), new Object[] {"sss", "ppp", "www", 's', gpeItemSilk, 'p', new ItemStack(FCBetterThanWolves.fcAestheticOpaque, 1, 4), 'w', Block.woodSingleSlab});
+ FCRecipes.AddVanillaRecipe(new ItemStack(Item.bed, 1), new Object[] {"sss", "ppp", "www", 's', gpeItemSilk, 'p', FCBetterThanWolves.fcPadding, 'w', Block.woodSingleSlab});
BlockDispenser.dispenseBehaviorRegistry.putObject(gpeItemLooseRock, new GPEBehaviorRock());
FCAddOnHandler.LogMessage("Grom PE's BTWTweak is done tweaking. Enjoy!");
}
public void PostInitialize()
{
FCAddOnHandler.LogMessage("BTWTweak now looks for BTW Research Add-On to integrate with...");
try
{
Class rb = Class.forName("SixModResearchBenchAddOn");
Method addDesc = rb.getMethod("addResearchDescription", new Class[] {String.class, String.class});
// addDesc.invoke(rb, "<KEY>", "<DESCRIPTION>");
// Where <KEY> is of the form "ID#Metadata", (i.e. "5#3" for jungle planks)
// and <DESCRIPTION> is the description you want the item to have.
// Try to keep the description under 300 characters or so.
addDesc.invoke(rb, "4", "Rough broken down stone. If arranged in a hollow square, can be crafted into a simple furnace to smelt and cook things.");
addDesc.invoke(rb, "13", "Fine chunks of stone and sand. Digging through it may yield a rock, or even a flint, but passing it through a fine filter is more efficient.");
addDesc.invoke(rb, "44#3", "A half high block of cobblestone, useful for getting up slopes without jumping. Two of them can be joined back into a single block. Many solid blocks seem to be able to be made into slabs like this.");
addDesc.invoke(rb, "44#5", "A half high block of stone bricks, useful for getting up slopes without jumping. Two of them can be joined back into a single block. Many solid blocks seem to be able to be made into slabs like this.");
addDesc.invoke(rb, "80", "This block of compacted snow seems to melt into water when placed directly nearby a heat source.");
addDesc.invoke(rb, "91", "The torch encased in this carved pumpkin gives off a comforting light, and is well-protected from water. The pumpkin is still fragile and if dropped from a height, breaks into seeds and leaves the torch standing in most cases.");
addDesc.invoke(rb, "397#5", "Spider head now silently stares at you with its all 8 eyes.");
addDesc.invoke(rb, "397#6", "Looks like this black person won't be teleporting anymore.");
addDesc.invoke(rb, "397#7", "Zombie pigman head smells rotten.");
addDesc.invoke(rb, "397#8", "Blaze head is one cool-looking fiery trophy.");
addDesc.invoke(rb, Integer.toString(gpeLooseRockID), "A rough loose rock. It could be crafted with shafts to make basic tools, one for a shovel, two for an axe or three for a pick. Heavy, but usable as a short ranged thrown weapon. Can be assembled to slabs and blocks.");
addDesc.invoke(rb, Integer.toString(FCBetterThanWolves.fcBlockDirtSlab.blockID) + "#6", "Gravel makes for a good road material, even in a slab form.");
addDesc.invoke(rb, Integer.toString(FCBetterThanWolves.fcBlockDirtSlab.blockID) + "#7", "Running and jumping is a huge drain on energy and cuts into a food supply fast. Slabs could offer a huge help in this, allowing one to walk up slopes without any jumping at all. Needs a solid surface to sit on though.");
addDesc.invoke(rb, Integer.toString(FCBetterThanWolves.fcPotash.itemID), "Grainy ash substance from rendered down wood. Can fertilize tilled soil. Also has a bleaching quality, so should be able to bleach coloured wool white.");
addDesc.invoke(rb, Integer.toString(FCBetterThanWolves.fcAestheticOpaque.blockID) + "#4", "Nice, soft and comfy. A handy way to store padding. Or to make a calming padded room. Softens the blow when landed onto.");
// - potash as fertilizer
// - block of padding reducing fall damage
}
catch (ClassNotFoundException e)
{
FCAddOnHandler.LogMessage("BTW Research Add-On not found.");
}
catch (Exception e)
{
FCAddOnHandler.LogMessage("Error while integrating with BTW Research Add-On!");
e.printStackTrace();
}
}
public static boolean onBlockSawed(World world, int x, int y, int z)
{
int id = world.getBlockId(x, y, z);
int meta = world.getBlockMetadata(x, y, z);
if (id == Block.bookShelf.blockID)
{
EjectSawProducts(world, x, y, z, FCBetterThanWolves.fcBlockWoodSidingItemStubID, 0, 4);
EjectSawProducts(world, x, y, z, Item.book.itemID, 0, 3);
}
else if (id == Block.chest.blockID)
{
EjectSawProducts(world, x, y, z, FCBetterThanWolves.fcBlockWoodSidingItemStubID, 0, 6);
}
else if (id == Block.doorWood.blockID)
{
if ((meta & 8) != 0) return false;
EjectSawProducts(world, x, y, z, FCBetterThanWolves.fcBlockWoodSidingItemStubID, 0, 4);
}
else if (id == Block.fenceGate.blockID)
{
EjectSawProducts(world, x, y, z, FCBetterThanWolves.fcBlockWoodMouldingItemStubID, 0, 3);
}
else if (id == Block.jukebox.blockID)
{
EjectSawProducts(world, x, y, z, FCBetterThanWolves.fcBlockWoodSidingItemStubID, 0, 6);
EjectSawProducts(world, x, y, z, Item.diamond.itemID, 0, 1);
}
else if (id == Block.ladder.blockID)
{
EjectSawProducts(world, x, y, z, Item.stick.itemID, 0, 2);
}
else if (id == Block.music.blockID)
{
EjectSawProducts(world, x, y, z, FCBetterThanWolves.fcBlockWoodSidingItemStubID, 0, 6);
EjectSawProducts(world, x, y, z, FCBetterThanWolves.fcItemRedstoneLatch.itemID, 0, 1);
}
else if (id == Block.trapdoor.blockID)
{
EjectSawProducts(world, x, y, z, FCBetterThanWolves.fcBlockWoodSidingItemStubID, 0, 2);
}
else if (id == FCBetterThanWolves.fcAxleBlock.blockID)
{
EjectSawProducts(world, x, y, z, FCBetterThanWolves.fcBlockWoodCornerItemStubID, 0, 2);
EjectSawProducts(world, x, y, z, FCBetterThanWolves.fcRopeItem.itemID, 0, 1);
}
else if (id == FCBetterThanWolves.fcBellows.blockID)
{
EjectSawProducts(world, x, y, z, FCBetterThanWolves.fcBlockWoodSidingItemStubID, 0, 2);
EjectSawProducts(world, x, y, z, FCBetterThanWolves.fcItemTannedLeatherCut.itemID, 0, 3);
EjectSawProducts(world, x, y, z, FCBetterThanWolves.fcGear.itemID, 0, 1);
EjectSawProducts(world, x, y, z, FCBetterThanWolves.fcBelt.itemID, 0, 1);
}
else if (id == FCBetterThanWolves.fcGearBox.blockID)
{
EjectSawProducts(world, x, y, z, FCBetterThanWolves.fcBlockWoodSidingItemStubID, 0, 3);
EjectSawProducts(world, x, y, z, FCBetterThanWolves.fcGear.itemID, 0, 3);
EjectSawProducts(world, x, y, z, FCBetterThanWolves.fcItemRedstoneLatch.itemID, 0, 1);
}
else if (id == FCBetterThanWolves.fcHopper.blockID)
{
EjectSawProducts(world, x, y, z, FCBetterThanWolves.fcBlockWoodMouldingItemStubID, 0, 3);
EjectSawProducts(world, x, y, z, FCBetterThanWolves.fcGear.itemID, 0, 1);
EjectSawProducts(world, x, y, z, Block.pressurePlatePlanks.blockID, 0, 1);
}
else if (id == FCBetterThanWolves.fcPlatform.blockID)
{
EjectSawProducts(world, x, y, z, FCBetterThanWolves.fcBlockWoodMouldingItemStubID, 0, 3);
EjectSawProducts(world, x, y, z, FCBetterThanWolves.fcWicker.itemID, 0, 2);
}
else if (id == FCBetterThanWolves.fcPulley.blockID)
{
EjectSawProducts(world, x, y, z, FCBetterThanWolves.fcBlockWoodSidingItemStubID, 0, 3);
EjectSawProducts(world, x, y, z, Item.ingotIron.itemID, 0, 2);
EjectSawProducts(world, x, y, z, FCBetterThanWolves.fcGear.itemID, 0, 1);
EjectSawProducts(world, x, y, z, FCBetterThanWolves.fcItemRedstoneLatch.itemID, 0, 1);
}
else if (id == FCBetterThanWolves.fcSaw.blockID)
{
EjectSawProducts(world, x, y, z, FCBetterThanWolves.fcGear.itemID, 0, 2);
EjectSawProducts(world, x, y, z, Item.ingotIron.itemID, 0, 3);
EjectSawProducts(world, x, y, z, FCBetterThanWolves.fcBlockWoodSidingItemStubID, 0, 1);
EjectSawProducts(world, x, y, z, FCBetterThanWolves.fcBelt.itemID, 0, 1);
}
else if (id == FCBetterThanWolves.fcBlockScrewPump.blockID)
{
EjectSawProducts(world, x, y, z, FCBetterThanWolves.fcBlockWoodSidingItemStubID, 0, 3);
EjectSawProducts(world, x, y, z, FCBetterThanWolves.fcGrate.itemID, 0, 1);
EjectSawProducts(world, x, y, z, FCBetterThanWolves.fcItemScrew.itemID, 0, 1);
}
else if (id == Block.cloth.blockID)
{
EjectSawProducts(world, x, y, z, FCBetterThanWolves.fcWoolSlab.blockID, meta, 2);
}
else
{
return false;
}
return true;
}
private static void EjectSawProducts(World world, int x, int y, int z, int id, int meta, int count)
{
for (int i = 0; i < count; ++i)
{
FCUtilsItem.EjectSingleItemWithRandomOffset(world, x, y, z, id, meta);
}
}
public void OnLanguageLoaded(StringTranslate st)
{
Properties t = st.GetTranslateTable();
t.put(Item.stick.getUnlocalizedName() + ".name", "Rod");
t.put(FCBetterThanWolves.fcBlockDirtSlab.getUnlocalizedName() + ".gravel.name", "Gravel Slab");
t.put(FCBetterThanWolves.fcBlockDirtSlab.getUnlocalizedName() + ".sand.name", "Sand Slab");
t.put(FCBetterThanWolves.fcItemRottenArrow.getUnlocalizedName() + ".name", "Rotten Arrow");
t.put("item.skull.spider.name", "Spider head");
t.put("item.skull.enderman.name", "Enderman head");
t.put("item.skull.pigzombie.name", "Zombie Pigman head");
t.put("item.skull.fire.name", "Blaze head");
t.put(gpeItemLooseRock.getUnlocalizedName() + ".name", "Rock");
t.put(gpeItemSilk.getUnlocalizedName() + ".name", "Silk");
}
public static void saveWorldData(World world)
{
if (!readyForStrataRegen(world)) return;
File strataRegenFile = getStrataRegenFile(world);
try
{
ObjectOutputStream s = new ObjectOutputStream(new FileOutputStream(strataRegenFile));
s.writeObject(chunkRegenInfo);
s.close();
}
catch (Exception e)
{
e.printStackTrace();
}
}
public static void loadWorldData(World world)
{
if (!readyForStrataRegen(world)) return;
FCAddOnHandler.LogMessage(String.format("BTWTweak is now going to stratify the world '%s'.", gpeStrataRegenWorldName));
File strataRegenFile = getStrataRegenFile(world);
if (!strataRegenFile.exists()) return;
try
{
ObjectInputStream s = new ObjectInputStream(new FileInputStream(strataRegenFile));
chunkRegenInfo = (HashMap<Long, Integer>)s.readObject();
s.close();
}
catch (Exception e)
{
e.printStackTrace();
}
}
public static void onSaveChunk(World world, Chunk chunk)
{
if (!readyForStrataRegen(world)) return;
long l = (((long)chunk.xPosition) << 32) | (chunk.zPosition & 0xffffffffL);
chunkRegenInfo.put(l, gpeStrataRegenKey);
}
public static void onLoadChunk(World world, Chunk chunk)
{
if (!readyForStrataRegen(world)) return;
long l = (((long)chunk.xPosition) << 32) | (chunk.zPosition & 0xffffffffL);
Integer key = chunkRegenInfo.get(l);
if (key == null || key.intValue() != gpeStrataRegenKey)
{
System.out.println(String.format("Stratifying chunk at %d, %d", chunk.xPosition, chunk.zPosition));
stratifyChunk(world, chunk);
}
}
// Simply ignoring letters for now
public static boolean isBTWVersionOrNewer(String ver)
{
String current = FCBetterThanWolves.fcVersionString.replaceAll("[^\\d\\.]+", "");
return Double.parseDouble(current) >= Double.parseDouble(ver);
}
private static File getStrataRegenFile(World world)
{
File f;
f = new File(proxy.getConfigDir(), "saves");
f = new File(f, world.getSaveHandler().getWorldDirectoryName());
f = new File(f, "strataRegen.dat");
return f;
}
private static boolean readyForStrataRegen(World world)
{
if (gpeStrataRegenKey == 0) return false;
if (world.provider.dimensionId != 0) return false;
if (world.worldInfo == null) return false;
return world.worldInfo.getWorldName().equals(gpeStrataRegenWorldName);
}
private static void stratifyChunk(World world, Chunk chunk)
{
for (int x = 0; x < 16; x++)
{
for (int z = 0; z < 16; z++)
{
int y = 1;
int yy;
for (yy = 24 + world.rand.nextInt(2); y <= yy; y++) stratifyBlockInChunk(chunk, x, y, z, 2);
for (yy = 48 + world.rand.nextInt(2); y <= yy; y++) stratifyBlockInChunk(chunk, x, y, z, 1);
}
}
}
private static void stratifyBlockInChunk(Chunk chunk, int x, int y, int z, int strata)
{
int id = chunk.getBlockID(x, y, z);
if (id == Block.stone.blockID)
{
chunk.setBlockMetadata(x, y, z, strata);
}
else if (id != 0)
{
Block b = Block.blocksList[id];
if (b.HasStrata()) chunk.setBlockMetadata(x, y, z, b.GetMetadataConversionForStrataLevel(strata, 0));
}
}
}
| true | true | public void Initialize()
{
FCAddOnHandler.LogMessage("Grom PE's BTWTweak v" + tweakVersion + " is now going to tweak the hell out of this.");
try
{
Class.forName("net.minecraft.client.Minecraft");
proxy = new GPEBTWTweakProxyClient();
}
catch(ClassNotFoundException e)
{
proxy = new GPEBTWTweakProxy();
}
File config = new File(proxy.getConfigDir(), "BTWTweak.cfg");
chunkRegenInfo = new HashMap<Long, Integer>();
try
{
BufferedReader br = new BufferedReader(new FileReader(config));
String line, key, value;
while ((line = br.readLine()) != null)
{
String[] tmp = line.split("=");
if (tmp.length < 2) continue;
key = tmp[0].trim();
value = tmp[1].trim();
if (key.equals("gpeLooseRockID")) gpeLooseRockID = Integer.parseInt(value);
if (key.equals("gpeEntityRockID")) gpeEntityRockID = Integer.parseInt(value);
if (key.equals("gpeEntityRockVehicleSpawnType")) gpeEntityRockVehicleSpawnType = Integer.parseInt(value);
if (key.equals("hcSpawnRadius")) hcSpawnRadius = Integer.parseInt(value);
if (key.equals("gpeStrataRegenKey")) gpeStrataRegenKey = Integer.parseInt(value);
if (key.equals("gpeStrataRegenWorldName")) gpeStrataRegenWorldName = value;
}
br.close();
}
catch (FileNotFoundException e)
{
String defaultConfig = ""
+ "// **** BTWTweak Settings ****\r\n"
+ "\r\n"
+ "// Hardcore Spawn radius, in blocks. Changing it from default 2000 may destabilize your game balance.\r\n"
+ "\r\n"
+ "hcSpawnRadius=2000\r\n"
+ "\r\n"
+ "// **** Item IDs ****\r\n"
+ "\r\n"
+ "gpeLooseRockID=17000\r\n"
+ "gpeSilkID=17001\r\n"
+ "\r\n"
+ "// **** Entity IDs ****\r\n"
+ "\r\n"
+ "gpeEntityRockID=35\r\n"
+ "\r\n"
+ "// **** Other IDs ****\r\n"
+ "\r\n"
+ "gpeEntityRockVehicleSpawnType=120\r\n"
+ "\r\n"
+ "// **** World strata regeneration ****\r\n"
+ "\r\n"
+ "// To use, set key to non-zero and name of the world you want to process\r\n"
+ "gpeStrataRegenKey=0\r\n"
+ "gpeStrataRegenWorldName=???\r\n"
+ "";
try
{
FileOutputStream fo = new FileOutputStream(config);
fo.write(defaultConfig.getBytes());
fo.close();
}
catch (IOException e2)
{
FCAddOnHandler.LogMessage("Error while writing default BTWTweak.cfg!");
e2.printStackTrace();
}
}
catch (IOException e)
{
FCAddOnHandler.LogMessage("Error while reading BTWTweak.cfg!");
e.printStackTrace();
}
Block.blocksList[1] = null; gpeBlockStone = new GPEBlockStone(1);
Block.blocksList[4] = null; new GPEBlockCobblestone(4);
Block.blocksList[13] = null; new GPEBlockGravel(13);
Block.blocksList[65] = null; new GPEBlockLadder(65);
Block.blocksList[80] = null; new GPEBlockSnowBlock(80);
Block.blocksList[91] = null;
ItemAxe.SetAllAxesToBeEffectiveVsBlock((new FCBlockPumpkin(91, true)).setHardness(1.0F).setStepSound(Block.soundWoodFootstep).setLightValue(1.0F).setUnlocalizedName("litpumpkin"));
new GPEItemPotash(FCBetterThanWolves.fcPotash.itemID - 256);
gpeItemLooseRock = new GPEItemLooseRock(gpeLooseRockID - 256);
gpeItemSilk = new Item(gpeSilkID - 256).setUnlocalizedName("gpeItemSilk").setCreativeTab(CreativeTabs.tabMaterials).SetBuoyancy(1.0F).SetBellowsBlowDistance(2);
int id = FCBetterThanWolves.fcAestheticOpaque.blockID;
Block.blocksList[id] = null;
new GPEBlockAestheticOpaque(id);
id = FCBetterThanWolves.fcBlockDirtSlab.blockID;
Block.blocksList[id] = null;
new GPEBlockDirtSlab(id);
EntityList.addMapping(GPEEntityRock.class, "gpeEntityRock", gpeEntityRockID);
proxy.addEntityRenderers();
FCRecipes.AddVanillaRecipe(new ItemStack(FCBetterThanWolves.fcBlockDirtSlab, 4, 6), new Object[] {"##", '#', new ItemStack(Block.gravel)});
FCRecipes.AddVanillaRecipe(new ItemStack(FCBetterThanWolves.fcBlockDirtSlab, 1, 6), new Object[] {"##", '#', new ItemStack(FCBetterThanWolves.fcItemPileGravel)});
FCRecipes.AddVanillaRecipe(new ItemStack(FCBetterThanWolves.fcBlockDirtSlab, 4, 7), new Object[] {"##", '#', new ItemStack(Block.sand)});
FCRecipes.AddVanillaRecipe(new ItemStack(FCBetterThanWolves.fcBlockDirtSlab, 1, 7), new Object[] {"##", '#', new ItemStack(FCBetterThanWolves.fcItemPileSand)});
FCRecipes.AddShapelessVanillaRecipe(new ItemStack(Block.gravel), new Object[] {new ItemStack(FCBetterThanWolves.fcBlockDirtSlab, 1, 6), new ItemStack(FCBetterThanWolves.fcBlockDirtSlab, 1, 6)});
FCRecipes.AddShapelessVanillaRecipe(new ItemStack(Block.sand), new Object[] {new ItemStack(FCBetterThanWolves.fcBlockDirtSlab, 1, 7), new ItemStack(FCBetterThanWolves.fcBlockDirtSlab, 1, 7)});
FCRecipes.AddShapelessVanillaRecipe(new ItemStack(FCBetterThanWolves.fcItemPileDirt, 2), new Object[] {new ItemStack(FCBetterThanWolves.fcBlockDirtSlab)});
FCRecipes.AddShapelessVanillaRecipe(new ItemStack(FCBetterThanWolves.fcItemPileSand, 2), new Object[] {new ItemStack(FCBetterThanWolves.fcBlockDirtSlab, 1, 7)});
FCRecipes.AddShapelessVanillaRecipe(new ItemStack(FCBetterThanWolves.fcItemPileGravel, 2), new Object[] {new ItemStack(FCBetterThanWolves.fcBlockDirtSlab, 1, 6)});
FCRecipes.AddStokedCauldronRecipe(new ItemStack(FCBetterThanWolves.fcGlue, 1), new ItemStack[] {new ItemStack(Item.bone, 8)});
FCRecipes.AddStokedCauldronRecipe(new ItemStack(FCBetterThanWolves.fcGlue, 1), new ItemStack[] {new ItemStack(Item.dyePowder, 24, 15)});
if (isBTWVersionOrNewer("4.891124"))
{
int i;
for (i = 0; i < 16; i++)
{
FCRecipes.AddStokedCauldronRecipe(
new ItemStack[]
{
new ItemStack(FCBetterThanWolves.fcItemWool, 4, 15 - i),
new ItemStack(FCBetterThanWolves.fcAestheticOpaque, 1, 0)
},
new ItemStack[] {new ItemStack(Block.cloth, 1, i)});
}
}
FCRecipes.RemoveVanillaRecipe(new ItemStack(Item.axeStone), new Object[] {"X ", "X#", " #", '#', Item.stick, 'X', Block.cobblestone});
FCRecipes.AddVanillaRecipe(new ItemStack(Item.axeStone), new Object[] {"X ", "X#", " #", '#', Item.stick, 'X', gpeItemLooseRock});
FCRecipes.RemoveVanillaRecipe(new ItemStack(Item.pickaxeStone), new Object[] {"XXX", " # ", " # ", '#', Item.stick, 'X', Block.cobblestone});
FCRecipes.AddVanillaRecipe(new ItemStack(Item.pickaxeStone), new Object[] {"XXX", " # ", " # ", '#', Item.stick, 'X', gpeItemLooseRock});
FCRecipes.RemoveVanillaRecipe(new ItemStack(Item.shovelStone), new Object[] {"X", "#", "#", '#', Item.stick, 'X', Block.cobblestone});
FCRecipes.AddVanillaRecipe(new ItemStack(Item.shovelStone), new Object[] {"X", "#", "#", '#', Item.stick, 'X', gpeItemLooseRock});
FCRecipes.RemoveVanillaRecipe(new ItemStack(Block.lever, 1), new Object[] {"X", "#", "r", '#', Block.cobblestone, 'X', Item.stick, 'r', Item.redstone});
FCRecipes.AddVanillaRecipe(new ItemStack(Block.lever, 1), new Object[] {"X", "#", "r", '#', gpeItemLooseRock, 'X', Item.stick, 'r', Item.redstone});
FCRecipes.AddVanillaRecipe(new ItemStack(Block.cobblestone), new Object[] {"XX", "XX", 'X', gpeItemLooseRock});
FCRecipes.AddVanillaRecipe(new ItemStack(Block.stoneSingleSlab, 1, 3), new Object[] {"XX", 'X', gpeItemLooseRock});
FCRecipes.AddVanillaRecipe(new ItemStack(Block.cobblestone), new Object[] {"X", "X", 'X', new ItemStack(Block.stoneSingleSlab, 1, 3)});
FCRecipes.AddVanillaRecipe(new ItemStack(Block.stoneBrick), new Object[] {"X", "X", 'X', new ItemStack(Block.stoneSingleSlab, 1, 5)});
FCRecipes.AddVanillaRecipe(new ItemStack(gpeItemSilk, 1), new Object[] {"###", "###", "###", '#', Item.silk});
FCRecipes.AddShapelessVanillaRecipe(new ItemStack(Item.silk, 9), new Object[] {new ItemStack(gpeItemSilk)});
FCRecipes.AddShapelessVanillaRecipe(new ItemStack(Item.book, 1), new Object[] {Item.paper, Item.paper, Item.paper, FCBetterThanWolves.fcItemTannedLeatherCut});
FCRecipes.AddStokedCrucibleRecipe(new ItemStack[] {new ItemStack(Item.goldNugget, 3), new ItemStack(FCBetterThanWolves.fcSteel, 1)}, new ItemStack[] {new ItemStack(Block.pistonBase, 1)});
FCRecipes.AddStokedCrucibleRecipe(new ItemStack[] {new ItemStack(Item.goldNugget, 3), new ItemStack(FCBetterThanWolves.fcSteel, 1)}, new ItemStack[] {new ItemStack(Block.pistonStickyBase, 1)});
FCRecipes.RemoveShapelessVanillaRecipe(new ItemStack(FCBetterThanWolves.fcItemIngotDiamond), new Object[] {new ItemStack(Item.ingotIron), new ItemStack(Item.diamond), new ItemStack(FCBetterThanWolves.fcItemCreeperOysters)});
FCRecipes.AddCauldronRecipe(new ItemStack(FCBetterThanWolves.fcItemIngotDiamond), new ItemStack[] {new ItemStack(Item.ingotIron), new ItemStack(Item.diamond), new ItemStack(FCBetterThanWolves.fcItemCreeperOysters)});
FCRecipes.RemoveVanillaRecipe(new ItemStack(Item.bed, 1), new Object[] {"###", "XXX", '#', Block.cloth, 'X', Block.planks});
FCRecipes.AddVanillaRecipe(new ItemStack(Item.bed, 1), new Object[] {"sss", "ppp", "www", 's', gpeItemSilk, 'p', new ItemStack(FCBetterThanWolves.fcAestheticOpaque, 1, 4), 'w', Block.woodSingleSlab});
BlockDispenser.dispenseBehaviorRegistry.putObject(gpeItemLooseRock, new GPEBehaviorRock());
FCAddOnHandler.LogMessage("Grom PE's BTWTweak is done tweaking. Enjoy!");
}
| public void Initialize()
{
FCAddOnHandler.LogMessage("Grom PE's BTWTweak v" + tweakVersion + " is now going to tweak the hell out of this.");
try
{
Class.forName("net.minecraft.client.Minecraft");
proxy = new GPEBTWTweakProxyClient();
}
catch(ClassNotFoundException e)
{
proxy = new GPEBTWTweakProxy();
}
File config = new File(proxy.getConfigDir(), "BTWTweak.cfg");
chunkRegenInfo = new HashMap<Long, Integer>();
try
{
BufferedReader br = new BufferedReader(new FileReader(config));
String line, key, value;
while ((line = br.readLine()) != null)
{
String[] tmp = line.split("=");
if (tmp.length < 2) continue;
key = tmp[0].trim();
value = tmp[1].trim();
if (key.equals("gpeLooseRockID")) gpeLooseRockID = Integer.parseInt(value);
if (key.equals("gpeEntityRockID")) gpeEntityRockID = Integer.parseInt(value);
if (key.equals("gpeEntityRockVehicleSpawnType")) gpeEntityRockVehicleSpawnType = Integer.parseInt(value);
if (key.equals("hcSpawnRadius")) hcSpawnRadius = Integer.parseInt(value);
if (key.equals("gpeStrataRegenKey")) gpeStrataRegenKey = Integer.parseInt(value);
if (key.equals("gpeStrataRegenWorldName")) gpeStrataRegenWorldName = value;
}
br.close();
}
catch (FileNotFoundException e)
{
String defaultConfig = ""
+ "// **** BTWTweak Settings ****\r\n"
+ "\r\n"
+ "// Hardcore Spawn radius, in blocks. Changing it from default 2000 may destabilize your game balance.\r\n"
+ "\r\n"
+ "hcSpawnRadius=2000\r\n"
+ "\r\n"
+ "// **** Item IDs ****\r\n"
+ "\r\n"
+ "gpeLooseRockID=17000\r\n"
+ "gpeSilkID=17001\r\n"
+ "\r\n"
+ "// **** Entity IDs ****\r\n"
+ "\r\n"
+ "gpeEntityRockID=35\r\n"
+ "\r\n"
+ "// **** Other IDs ****\r\n"
+ "\r\n"
+ "gpeEntityRockVehicleSpawnType=120\r\n"
+ "\r\n"
+ "// **** World strata regeneration ****\r\n"
+ "\r\n"
+ "// To use, set key to non-zero and name of the world you want to process\r\n"
+ "gpeStrataRegenKey=0\r\n"
+ "gpeStrataRegenWorldName=???\r\n"
+ "";
try
{
FileOutputStream fo = new FileOutputStream(config);
fo.write(defaultConfig.getBytes());
fo.close();
}
catch (IOException e2)
{
FCAddOnHandler.LogMessage("Error while writing default BTWTweak.cfg!");
e2.printStackTrace();
}
}
catch (IOException e)
{
FCAddOnHandler.LogMessage("Error while reading BTWTweak.cfg!");
e.printStackTrace();
}
Block.blocksList[1] = null; gpeBlockStone = new GPEBlockStone(1);
Block.blocksList[4] = null; new GPEBlockCobblestone(4);
Block.blocksList[13] = null; new GPEBlockGravel(13);
Block.blocksList[65] = null; new GPEBlockLadder(65);
Block.blocksList[80] = null; new GPEBlockSnowBlock(80);
Block.blocksList[91] = null;
ItemAxe.SetAllAxesToBeEffectiveVsBlock((new FCBlockPumpkin(91, true)).setHardness(1.0F).setStepSound(Block.soundWoodFootstep).setLightValue(1.0F).setUnlocalizedName("litpumpkin"));
new GPEItemPotash(FCBetterThanWolves.fcPotash.itemID - 256);
gpeItemLooseRock = new GPEItemLooseRock(gpeLooseRockID - 256);
gpeItemSilk = new Item(gpeSilkID - 256).setUnlocalizedName("gpeItemSilk").setCreativeTab(CreativeTabs.tabMaterials).SetBuoyancy(1.0F).SetBellowsBlowDistance(2);
int id = FCBetterThanWolves.fcAestheticOpaque.blockID;
Block.blocksList[id] = null;
new GPEBlockAestheticOpaque(id);
id = FCBetterThanWolves.fcBlockDirtSlab.blockID;
Block.blocksList[id] = null;
new GPEBlockDirtSlab(id);
EntityList.addMapping(GPEEntityRock.class, "gpeEntityRock", gpeEntityRockID);
proxy.addEntityRenderers();
FCRecipes.AddVanillaRecipe(new ItemStack(FCBetterThanWolves.fcBlockDirtSlab, 4, 6), new Object[] {"##", '#', new ItemStack(Block.gravel)});
FCRecipes.AddVanillaRecipe(new ItemStack(FCBetterThanWolves.fcBlockDirtSlab, 1, 6), new Object[] {"##", '#', new ItemStack(FCBetterThanWolves.fcItemPileGravel)});
FCRecipes.AddVanillaRecipe(new ItemStack(FCBetterThanWolves.fcBlockDirtSlab, 4, 7), new Object[] {"##", '#', new ItemStack(Block.sand)});
FCRecipes.AddVanillaRecipe(new ItemStack(FCBetterThanWolves.fcBlockDirtSlab, 1, 7), new Object[] {"##", '#', new ItemStack(FCBetterThanWolves.fcItemPileSand)});
FCRecipes.AddShapelessVanillaRecipe(new ItemStack(Block.gravel), new Object[] {new ItemStack(FCBetterThanWolves.fcBlockDirtSlab, 1, 6), new ItemStack(FCBetterThanWolves.fcBlockDirtSlab, 1, 6)});
FCRecipes.AddShapelessVanillaRecipe(new ItemStack(Block.sand), new Object[] {new ItemStack(FCBetterThanWolves.fcBlockDirtSlab, 1, 7), new ItemStack(FCBetterThanWolves.fcBlockDirtSlab, 1, 7)});
FCRecipes.AddShapelessVanillaRecipe(new ItemStack(FCBetterThanWolves.fcItemPileDirt, 2), new Object[] {new ItemStack(FCBetterThanWolves.fcBlockDirtSlab)});
FCRecipes.AddShapelessVanillaRecipe(new ItemStack(FCBetterThanWolves.fcItemPileSand, 2), new Object[] {new ItemStack(FCBetterThanWolves.fcBlockDirtSlab, 1, 7)});
FCRecipes.AddShapelessVanillaRecipe(new ItemStack(FCBetterThanWolves.fcItemPileGravel, 2), new Object[] {new ItemStack(FCBetterThanWolves.fcBlockDirtSlab, 1, 6)});
FCRecipes.AddStokedCauldronRecipe(new ItemStack(FCBetterThanWolves.fcGlue, 1), new ItemStack[] {new ItemStack(Item.bone, 8)});
FCRecipes.AddStokedCauldronRecipe(new ItemStack(FCBetterThanWolves.fcGlue, 1), new ItemStack[] {new ItemStack(Item.dyePowder, 24, 15)});
if (isBTWVersionOrNewer("4.891124"))
{
int i;
for (i = 0; i < 16; i++)
{
FCRecipes.AddStokedCauldronRecipe(
new ItemStack[]
{
new ItemStack(FCBetterThanWolves.fcItemWool, 4, 15 - i),
new ItemStack(FCBetterThanWolves.fcAestheticOpaque, 1, 0)
},
new ItemStack[] {new ItemStack(Block.cloth, 1, i)});
}
}
FCRecipes.RemoveVanillaRecipe(new ItemStack(Item.axeStone), new Object[] {"X ", "X#", " #", '#', Item.stick, 'X', Block.cobblestone});
FCRecipes.AddVanillaRecipe(new ItemStack(Item.axeStone), new Object[] {"X ", "X#", " #", '#', Item.stick, 'X', gpeItemLooseRock});
FCRecipes.RemoveVanillaRecipe(new ItemStack(Item.pickaxeStone), new Object[] {"XXX", " # ", " # ", '#', Item.stick, 'X', Block.cobblestone});
FCRecipes.AddVanillaRecipe(new ItemStack(Item.pickaxeStone), new Object[] {"XXX", " # ", " # ", '#', Item.stick, 'X', gpeItemLooseRock});
FCRecipes.RemoveVanillaRecipe(new ItemStack(Item.shovelStone), new Object[] {"X", "#", "#", '#', Item.stick, 'X', Block.cobblestone});
FCRecipes.AddVanillaRecipe(new ItemStack(Item.shovelStone), new Object[] {"X", "#", "#", '#', Item.stick, 'X', gpeItemLooseRock});
FCRecipes.RemoveVanillaRecipe(new ItemStack(Block.lever, 1), new Object[] {"X", "#", "r", '#', Block.cobblestone, 'X', Item.stick, 'r', Item.redstone});
FCRecipes.AddVanillaRecipe(new ItemStack(Block.lever, 1), new Object[] {"X", "#", "r", '#', gpeItemLooseRock, 'X', Item.stick, 'r', Item.redstone});
FCRecipes.AddVanillaRecipe(new ItemStack(Block.cobblestone), new Object[] {"XX", "XX", 'X', gpeItemLooseRock});
FCRecipes.AddVanillaRecipe(new ItemStack(Block.stoneSingleSlab, 1, 3), new Object[] {"XX", 'X', gpeItemLooseRock});
FCRecipes.AddVanillaRecipe(new ItemStack(Block.cobblestone), new Object[] {"X", "X", 'X', new ItemStack(Block.stoneSingleSlab, 1, 3)});
FCRecipes.AddVanillaRecipe(new ItemStack(Block.stoneBrick), new Object[] {"X", "X", 'X', new ItemStack(Block.stoneSingleSlab, 1, 5)});
FCRecipes.AddVanillaRecipe(new ItemStack(gpeItemSilk, 1), new Object[] {"###", "###", "###", '#', Item.silk});
FCRecipes.AddShapelessVanillaRecipe(new ItemStack(Item.silk, 9), new Object[] {new ItemStack(gpeItemSilk)});
FCRecipes.AddShapelessVanillaRecipe(new ItemStack(Item.book, 1), new Object[] {Item.paper, Item.paper, Item.paper, FCBetterThanWolves.fcItemTannedLeatherCut});
FCRecipes.AddStokedCrucibleRecipe(new ItemStack[] {new ItemStack(Item.goldNugget, 3), new ItemStack(FCBetterThanWolves.fcSteel, 1)}, new ItemStack[] {new ItemStack(Block.pistonBase, 1)});
FCRecipes.AddStokedCrucibleRecipe(new ItemStack[] {new ItemStack(Item.goldNugget, 3), new ItemStack(FCBetterThanWolves.fcSteel, 1)}, new ItemStack[] {new ItemStack(Block.pistonStickyBase, 1)});
FCRecipes.RemoveShapelessVanillaRecipe(new ItemStack(FCBetterThanWolves.fcItemIngotDiamond), new Object[] {new ItemStack(Item.ingotIron), new ItemStack(Item.diamond), new ItemStack(FCBetterThanWolves.fcItemCreeperOysters)});
FCRecipes.AddCauldronRecipe(new ItemStack(FCBetterThanWolves.fcItemIngotDiamond), new ItemStack[] {new ItemStack(Item.ingotIron), new ItemStack(Item.diamond), new ItemStack(FCBetterThanWolves.fcItemCreeperOysters)});
FCRecipes.RemoveVanillaRecipe(new ItemStack(Item.bed, 1), new Object[] {"###", "XXX", '#', Block.cloth, 'X', Block.planks});
FCRecipes.AddVanillaRecipe(new ItemStack(Item.bed, 1), new Object[] {"sss", "ppp", "www", 's', gpeItemSilk, 'p', FCBetterThanWolves.fcPadding, 'w', Block.woodSingleSlab});
BlockDispenser.dispenseBehaviorRegistry.putObject(gpeItemLooseRock, new GPEBehaviorRock());
FCAddOnHandler.LogMessage("Grom PE's BTWTweak is done tweaking. Enjoy!");
}
|
diff --git a/org.eclipse.jubula.examples.aut.dvdtool/src/org/eclipse/jubula/examples/aut/dvdtool/control/DvdLoadAction.java b/org.eclipse.jubula.examples.aut.dvdtool/src/org/eclipse/jubula/examples/aut/dvdtool/control/DvdLoadAction.java
index d5bc30fc9..dd675512c 100644
--- a/org.eclipse.jubula.examples.aut.dvdtool/src/org/eclipse/jubula/examples/aut/dvdtool/control/DvdLoadAction.java
+++ b/org.eclipse.jubula.examples.aut.dvdtool/src/org/eclipse/jubula/examples/aut/dvdtool/control/DvdLoadAction.java
@@ -1,54 +1,54 @@
/**
*
*/
package org.eclipse.jubula.examples.aut.dvdtool.control;
import java.awt.event.ActionEvent;
import java.io.InputStream;
import javax.swing.AbstractAction;
import org.eclipse.jubula.examples.aut.dvdtool.persistence.DvdInvalidContentException;
import org.eclipse.jubula.examples.aut.dvdtool.persistence.DvdPersistenceException;
/**
* @author al
*
*/
public class DvdLoadAction extends AbstractAction {
/** the controller of the main frame */
private transient DvdMainFrameController m_controller;
/**
* public constructor
* @param name the text to display
* @param controller the controller of the main frame
*/
public DvdLoadAction(String name, DvdMainFrameController controller) {
super(name);
m_controller = controller;
}
/**
* {@inheritDoc}
*/
public void actionPerformed(ActionEvent ev) {
try {
final InputStream is =
getClass().getClassLoader().getResourceAsStream(
- "resources/default.dvd");
+ "resources/default.dvd"); //$NON-NLS-1$
if (is != null) {
DvdManager.singleton().open(m_controller, is);
- m_controller.opened("default");
+ m_controller.opened("default"); //$NON-NLS-1$
}
} catch (DvdInvalidContentException e) {
// Auto-generated catch block
e.printStackTrace();
} catch (DvdPersistenceException e) {
// Auto-generated catch block
e.printStackTrace();
}
}
}
| false | true | public void actionPerformed(ActionEvent ev) {
try {
final InputStream is =
getClass().getClassLoader().getResourceAsStream(
"resources/default.dvd");
if (is != null) {
DvdManager.singleton().open(m_controller, is);
m_controller.opened("default");
}
} catch (DvdInvalidContentException e) {
// Auto-generated catch block
e.printStackTrace();
} catch (DvdPersistenceException e) {
// Auto-generated catch block
e.printStackTrace();
}
}
| public void actionPerformed(ActionEvent ev) {
try {
final InputStream is =
getClass().getClassLoader().getResourceAsStream(
"resources/default.dvd"); //$NON-NLS-1$
if (is != null) {
DvdManager.singleton().open(m_controller, is);
m_controller.opened("default"); //$NON-NLS-1$
}
} catch (DvdInvalidContentException e) {
// Auto-generated catch block
e.printStackTrace();
} catch (DvdPersistenceException e) {
// Auto-generated catch block
e.printStackTrace();
}
}
|
diff --git a/lab5/src/map/SimpleHashMap.java b/lab5/src/map/SimpleHashMap.java
index 8066b92..8077bde 100644
--- a/lab5/src/map/SimpleHashMap.java
+++ b/lab5/src/map/SimpleHashMap.java
@@ -1,144 +1,144 @@
package map;
import java.util.Iterator;
public class SimpleHashMap<K,V> implements Map<K,V> {
public static final int INITIAL_CAPACITY = 16;
public static final double INITIAL_LOAD_FACTOR = 0.75;
private Entry<K,V>[] table;
private int size;
/** Constructs an empty hashmap with the default initial capacity (16)
* and the default load factor (0.75). */
public SimpleHashMap() {
table = (Entry<K,V>[]) new Entry[INITIAL_CAPACITY];
size = 0;
}
/** Constructs an empty hashmap with the specified initial capacity
* and the default load factor (0.75). */
public SimpleHashMap(int capacity) {
table = (Entry<K,V>[]) new Entry[capacity];
}
@Override
public V get(Object arg0) {
// TODO Auto-generated method stub
return null;
}
@Override
public boolean isEmpty() {
return size == 0;
}
@Override
public V put(K arg0, V arg1) {
// TODO Auto-generated method stub
return null;
}
@Override
public V remove(Object arg0) {
// TODO Auto-generated method stub
return null;
}
@Override
public int size() {
return size;
}
/*
public String show(){
StringBuilder sb = new StringBuilder();
for(int i=0; i < table.length; i++){
sb.append(i);
sb.append("\t");
Entry<K,V> e = table[i];
if(e )
sb.append(table[i].toString());
}
return sb.toString();
}
*/
private int index(K key) {
return 0;
}
private Entry<K,V> find(int index, K key) {
- Iterator itr = new LinkIterator(index);
+ LinkIterator itr = new LinkIterator(index);
while(itr.hasNext()) {
Entry<K,V> e = itr.next();
if (e.key == key) {
return e;
}
}
return null;
}
private static class Entry<K,V> implements Map.Entry<K,V> {
private K key;
private V value;
private Entry<K,V> next;
public Entry(K key, V value) {
this.key = key;
this.value = value;
}
@Override
public K getKey() {
// TODO Auto-generated method stub
return null;
}
@Override
public V getValue() {
// TODO Auto-generated method stub
return null;
}
@Override
public V setValue(V value) {
// TODO Auto-generated method stub
return null;
}
public String toString() {
return key.toString() + "=" + value.toString();
}
}
private class LinkIterator implements Iterator<Entry<K,V>>{
private Entry<K,V> next;
public LinkIterator(int index){
next = table[index];
}
@Override
public boolean hasNext() {
// TODO Auto-generated method stub
return false;
}
@Override
public Entry<K,V> next() {
// TODO Auto-generated method stub
return next;
}
@Override
public void remove() {
// TODO Auto-generated method stub
}
}
}
| true | true | private Entry<K,V> find(int index, K key) {
Iterator itr = new LinkIterator(index);
while(itr.hasNext()) {
Entry<K,V> e = itr.next();
if (e.key == key) {
return e;
}
}
return null;
}
| private Entry<K,V> find(int index, K key) {
LinkIterator itr = new LinkIterator(index);
while(itr.hasNext()) {
Entry<K,V> e = itr.next();
if (e.key == key) {
return e;
}
}
return null;
}
|
diff --git a/software/caTissue/modules/core/src/main/java/edu/wustl/catissuecore/action/DynamicEventAction.java b/software/caTissue/modules/core/src/main/java/edu/wustl/catissuecore/action/DynamicEventAction.java
index ecbe62d90..ce0082a68 100644
--- a/software/caTissue/modules/core/src/main/java/edu/wustl/catissuecore/action/DynamicEventAction.java
+++ b/software/caTissue/modules/core/src/main/java/edu/wustl/catissuecore/action/DynamicEventAction.java
@@ -1,385 +1,392 @@
package edu.wustl.catissuecore.action;
import java.util.Calendar;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import edu.wustl.cab2b.common.util.Utility;
import edu.wustl.catissuecore.actionForm.DynamicEventForm;
import edu.wustl.catissuecore.bizlogic.CatissueDefaultBizLogic;
import edu.wustl.catissuecore.bizlogic.UserBizLogic;
import edu.wustl.catissuecore.domain.Specimen;
import edu.wustl.catissuecore.domain.processingprocedure.Action;
import edu.wustl.catissuecore.domain.processingprocedure.ActionApplication;
import edu.wustl.catissuecore.domain.processingprocedure.DefaultAction;
import edu.wustl.catissuecore.processor.SPPEventProcessor;
import edu.wustl.catissuecore.util.global.AppUtility;
import edu.wustl.catissuecore.util.global.Constants;
import edu.wustl.catissuecore.util.global.SpecimenEventsUtility;
import edu.wustl.common.action.BaseAction;
import edu.wustl.common.beans.SessionDataBean;
import edu.wustl.common.bizlogic.IBizLogic;
import edu.wustl.common.factory.AbstractFactoryConfig;
import edu.wustl.common.factory.IFactory;
import edu.wustl.common.util.global.CommonServiceLocator;
import edu.wustl.common.util.global.CommonUtilities;
public class DynamicEventAction extends BaseAction
{
/**
* Overrides the executeSecureAction method of SecureAction class.
* @param mapping
* object of ActionMapping
* @param form
* object of ActionForm
* @param request
* object of HttpServletRequest
* @param response : HttpServletResponse
* @throws Exception
* generic exception
* @return ActionForward : ActionForward
*/
@Override
protected ActionForward executeAction(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response) throws Exception
{
if (request.getParameter(Constants.REFRESH_EVENT_GRID) != null)
{
request.setAttribute(Constants.REFRESH_EVENT_GRID, request
.getParameter(Constants.REFRESH_EVENT_GRID));
}
//this.setCommonRequestParameters(request);
DynamicEventForm dynamicEventForm = (DynamicEventForm) form;
resetFormParameters(request, dynamicEventForm);
// if operation is add
if (dynamicEventForm.isAddOperation())
{
if (dynamicEventForm.getUserId() == 0)
{
final SessionDataBean sessionData = this.getSessionData(request);
if (sessionData != null && sessionData.getUserId() != null)
{
final long userId = sessionData.getUserId().longValue();
dynamicEventForm.setUserId(userId);
}
}
// set the current Date and Time for the event.
final Calendar cal = Calendar.getInstance();
if (dynamicEventForm.getDateOfEvent() == null)
{
dynamicEventForm.setDateOfEvent(CommonUtilities.parseDateToString(cal.getTime(),
CommonServiceLocator.getInstance().getDatePattern()));
}
if (dynamicEventForm.getTimeInHours() == null)
{
dynamicEventForm.setTimeInHours(Integer.toString(cal.get(Calendar.HOUR_OF_DAY)));
}
if (dynamicEventForm.getTimeInMinutes() == null)
{
dynamicEventForm.setTimeInMinutes(Integer.toString(cal.get(Calendar.MINUTE)));
}
}
else
{
String specimenId = (String) request.getAttribute(Constants.SPECIMEN_ID);
if (specimenId == null)
{
request.setAttribute(Constants.SPECIMEN_ID, specimenId);
}
}
String reasonDeviation = "";
reasonDeviation = dynamicEventForm.getReasonDeviation();
if (reasonDeviation == null)
{
reasonDeviation = "";
}
String currentEventParametersDate = "";
currentEventParametersDate = dynamicEventForm.getDateOfEvent();
if (currentEventParametersDate == null)
{
currentEventParametersDate = "";
}
final Integer dynamicEventParametersYear = new Integer(AppUtility
.getYear(currentEventParametersDate));
final Integer dynamicEventParametersMonth = new Integer(AppUtility
.getMonth(currentEventParametersDate));
final Integer dynamicEventParametersDay = new Integer(AppUtility
.getDay(currentEventParametersDate));
request.setAttribute("minutesList", Constants.MINUTES_ARRAY);
// Sets the hourList attribute to be used in the Add/Edit
// FrozenEventParameters Page.
request.setAttribute("hourList", Constants.HOUR_ARRAY);
request.setAttribute("dynamicEventParametersYear", dynamicEventParametersYear);
request.setAttribute("dynamicEventParametersDay", dynamicEventParametersDay);
request.setAttribute("dynamicEventParametersMonth", dynamicEventParametersMonth);
request.setAttribute("formName", Constants.DYNAMIC_EVENT_ACTION);
request.setAttribute("addForJSP", Constants.ADD);
request.setAttribute("editForJSP", Constants.EDIT);
request.setAttribute("reasonDeviation", reasonDeviation);
request.setAttribute("userListforJSP", Constants.USERLIST);
request.setAttribute("currentEventParametersDate", currentEventParametersDate);
request.setAttribute(Constants.PAGE_OF, "pageOfDynamicEvent");
request.setAttribute(Constants.SPECIMEN_ID, request.getSession().getAttribute(
Constants.SPECIMEN_ID));
//request.setAttribute(Constants.SPECIMEN_ID, request.getAttribute(Constants.SPECIMEN_ID));
//request.setAttribute(Constants.PAGE_OF, request.getParameter(Constants.PAGE_OF));
//request.setAttribute("changeAction", Constants.CELL_SPECIMEN_REVIEW_PARAMETERS_ADD_ACTION);
final String operation = request.getParameter(Constants.OPERATION);
final IFactory factory = AbstractFactoryConfig.getInstance().getBizLogicFactory();
final UserBizLogic userBizLogic = (UserBizLogic) factory
.getBizLogic(Constants.USER_FORM_ID);
final Collection userCollection = userBizLogic.getUsers(operation);
request.setAttribute(Constants.USERLIST, userCollection);
HashMap dynamicEventMap = (HashMap) request.getSession().getAttribute("dynamicEventMap");
String iframeURL="";
long recordIdentifier=0;
Long eventId=null;
if(dynamicEventForm.getOperation().equals(Constants.ADD))
{
String eventName = request.getParameter("eventName");
if(eventName == null)
{
eventName = (String)request.getSession().getAttribute("eventName");
}
request.getSession().setAttribute("eventName", eventName);
dynamicEventForm.setEventName(eventName);
eventId=(Long) dynamicEventMap.get(eventName);
+ String query="Select IS_CACORE_GENERATED from dyextn_entity_group where IDENTIFIER = (select ENTITY_GROUP_ID from dyextn_container where IDENTIFIER="+eventId+")";
+ List result=AppUtility.executeSQLQuery(query);
+ Boolean isCaCoreGenerated=Boolean.parseBoolean(((List) result.get(0)).get(0).toString());
+ if(!isCaCoreGenerated)
+ {
+ request.setAttribute("isCaCoreGenerated", true);
+ }
if (Boolean.parseBoolean(request.getParameter("showDefaultValues")))
{
IBizLogic defaultBizLogic = new CatissueDefaultBizLogic();
List<Action> actionList = defaultBizLogic.retrieve(Action.class.getName(),
Constants.ID, request.getParameter("formContextId"));
if (actionList != null && !actionList.isEmpty())
{
Action action = (Action) actionList.get(0);
if (action.getApplicationDefaultValue() != null)
{
recordIdentifier = SpecimenEventsUtility.getRecordIdentifier(action
.getApplicationDefaultValue().getId(), action.getContainerId());
}
}
}
else
{
IBizLogic defaultBizLogic = new CatissueDefaultBizLogic();
List<DefaultAction> actionList = defaultBizLogic.retrieve(DefaultAction.class
.getName(), Constants.CONTAINER_ID, eventId);
DefaultAction action =null;
if (actionList != null && !actionList.isEmpty())
{
action = (DefaultAction) actionList.get(0);
}
else
{
action=new DefaultAction();
action.setContainerId(eventId);
defaultBizLogic.insert(action);
}
request.setAttribute("formContextId",action.getId());
}
if(eventName != null)
{
request.setAttribute("formDisplayName", Utility.getFormattedString(eventName));
}
if(eventId != null)
{
request.getSession().setAttribute("OverrideCaption", "_" + eventId.toString());
iframeURL = "/catissuecore/LoadDataEntryFormAction.do?dataEntryOperation=insertParentData&useApplicationStylesheet=true&showInDiv=false&overrideCSS=true&overrideScroll=true"+(Boolean.parseBoolean(request.getParameter(Constants.CONTAINS_ERROR))?"&containerId=":"&containerIdentifier=")
+ eventId.toString() + "&OverrideCaption=" + "_" + eventId.toString()+"&showCalculateDefaultValue=false";
if (recordIdentifier != 0)
{
iframeURL = iframeURL + "&recordIdentifier=" + recordIdentifier;
}
}
}
else
{
String actionApplicationId = request.getParameter("id");
if(actionApplicationId ==null)
{
actionApplicationId = (String) request.getAttribute("id");
}
if(Boolean.parseBoolean(request.getParameter(Constants.CONTAINS_ERROR))
&& request.getSession().getAttribute("dynamicEventsForm") != null)
{
dynamicEventForm = (DynamicEventForm) request.getSession().getAttribute("dynamicEventsForm");
actionApplicationId = String.valueOf(dynamicEventForm.getId());
}
recordIdentifier = SpecimenEventsUtility.getRecordIdentifier(dynamicEventForm
.getRecordEntry(), dynamicEventForm.getContId());
Long containerId = dynamicEventForm.getContId();
IBizLogic defaultBizLogic = new CatissueDefaultBizLogic();
String specimenId = (String) request.getAttribute(Constants.SPECIMEN_ID);
boolean isDefaultAction = true;
if(specimenId!=null && !"".equals(specimenId))
{
List<Specimen> specimentList = defaultBizLogic.retrieve(
Specimen.class.getName(), Constants.ID, specimenId);
if (specimentList != null && !specimentList.isEmpty())
{
Specimen specimen = (Specimen) specimentList.get(0);
if(specimen.getProcessingSPPApplication() != null)
{
for(ActionApplication actionApplication : new SPPEventProcessor().getFilteredActionApplication(specimen.getProcessingSPPApplication().getSppActionApplicationCollection()))
{
if(actionApplication.getId().toString().equals(actionApplicationId))
{
for(Action action : specimen.getSpecimenRequirement().getProcessingSPP().getActionCollection())
{
if(action.getContainerId().equals(containerId))
{
request.setAttribute("formContextId", action.getId());
break;
}
}
isDefaultAction = false;
break;
}
}
}
}
}
if(isDefaultAction)
{
List<DefaultAction> actionList = defaultBizLogic.retrieve(
DefaultAction.class.getName(), Constants.CONTAINER_ID, dynamicEventForm
.getContId());
if (actionList != null && !actionList.isEmpty())
{
DefaultAction action = (DefaultAction) actionList.get(0);
request.setAttribute("formContextId", action.getId());
}
}
dynamicEventForm.setRecordIdentifier(recordIdentifier);
iframeURL = "/catissuecore/LoadDataEntryFormAction.do?dataEntryOperation=edit&useApplicationStylesheet=true&showInDiv=false"+(Boolean.parseBoolean(request.getParameter(Constants.CONTAINS_ERROR))?"&containerId=":"&containerIdentifier=")
+ dynamicEventForm.getContId()
+ "&recordIdentifier="
+ recordIdentifier
+ "&OverrideCaption=" + "_" + dynamicEventForm.getContId();
List contList = AppUtility
.executeSQLQuery("select caption from dyextn_container where identifier="
+ dynamicEventForm.getContId());
String eventName = (String) ((List) contList.get(0)).get(0);
request.setAttribute("formDisplayName", Utility.getFormattedString(eventName));
}
if (request.getSession().getAttribute("specimenId") == null)
{
request.getSession().setAttribute("specimenId", request.getParameter("specimenId"));
}
request.setAttribute("recordIdentifier", recordIdentifier);
request.getSession().setAttribute("recordIdentifier", recordIdentifier);
request.getSession().setAttribute("containerId", dynamicEventForm.getContId());
request.getSession().setAttribute("mandatory_Message", "false");
String formContxtId = getFormContextFromRequest(request);
if(!"".equals(iframeURL))
{
iframeURL = iframeURL + "&FormContextIdentifier=" + formContxtId;
}
populateStaticAttributes(request, dynamicEventForm);
request.setAttribute("iframeURL", iframeURL);
return mapping.findForward((String) request.getAttribute(Constants.PAGE_OF));
}
/**
* @param request
* @param dynamicEventForm
*/
private void resetFormParameters(HttpServletRequest request, DynamicEventForm dynamicEventForm)
{
if("edit".equals(request.getParameter(Constants.OPERATION)) && request.getSession().getAttribute(Constants.DYN_EVENT_FORM)!= null)
{
DynamicEventForm originalForm = (DynamicEventForm) request.getSession().getAttribute(Constants.DYN_EVENT_FORM);
dynamicEventForm.setContId(originalForm.getContId());
dynamicEventForm.setReasonDeviation(originalForm.getReasonDeviation());
dynamicEventForm.setRecordEntry(originalForm.getRecordEntry());
dynamicEventForm.setRecordIdentifier(originalForm.getRecordIdentifier());
dynamicEventForm.setUserId(originalForm.getUserId());
dynamicEventForm.setTimeInHours(originalForm.getTimeInHours());
dynamicEventForm.setTimeInMinutes(originalForm.getTimeInMinutes());
dynamicEventForm.setId(originalForm.getId());
}
}
/**
* @param request
* @param dynamicEventForm
*/
private void populateStaticAttributes(HttpServletRequest request,
final DynamicEventForm dynamicEventForm)
{
String sessionMapName = "formContextParameterMap"+ getFormContextFromRequest(request);
Map<String, Object> formContextParameterMap = (Map<String, Object>) request.getSession().getAttribute(sessionMapName);
if(formContextParameterMap !=null && Boolean.parseBoolean(request.getParameter(Constants.CONTAINS_ERROR)))
{
setDateParameters(request, formContextParameterMap);
dynamicEventForm.setTimeInMinutes((String) formContextParameterMap.get("timeInMinutes"));
dynamicEventForm.setTimeInHours((String) formContextParameterMap.get("timeInHours"));
dynamicEventForm.setUserId(Long.valueOf((String)formContextParameterMap.get(Constants.USER_ID)));
dynamicEventForm.setDateOfEvent((String) formContextParameterMap.get(Constants.DATE_OF_EVENT));
dynamicEventForm.setReasonDeviation((String) formContextParameterMap.get(Constants.REASON_DEVIATION));
request.getSession().removeAttribute(sessionMapName);
request.getSession().removeAttribute(Constants.DYN_EVENT_FORM);
}
}
/**
* @param request
* @param formContextParameterMap
*/
private void setDateParameters(HttpServletRequest request,
Map<String, Object> formContextParameterMap)
{
if(formContextParameterMap.get(Constants.DATE_OF_EVENT)!= null)
{
String currentEventParametersDate = (String) formContextParameterMap.get(Constants.DATE_OF_EVENT);
request.setAttribute("currentEventParametersDate", currentEventParametersDate);
request.setAttribute("dynamicEventParametersYear", AppUtility
.getYear(currentEventParametersDate));
request.setAttribute("dynamicEventParametersDay", AppUtility
.getDay(currentEventParametersDate));
request.setAttribute("dynamicEventParametersMonth", AppUtility
.getMonth(currentEventParametersDate));
}
}
/**
* @param request
* @return
*/
private String getFormContextFromRequest(HttpServletRequest request)
{
String formContxtId = request.getParameter("formContextId");
if(formContxtId == null)
{
formContxtId = String.valueOf(request.getAttribute("formContextId"));
}
return formContxtId;
}
}
| true | true | protected ActionForward executeAction(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response) throws Exception
{
if (request.getParameter(Constants.REFRESH_EVENT_GRID) != null)
{
request.setAttribute(Constants.REFRESH_EVENT_GRID, request
.getParameter(Constants.REFRESH_EVENT_GRID));
}
//this.setCommonRequestParameters(request);
DynamicEventForm dynamicEventForm = (DynamicEventForm) form;
resetFormParameters(request, dynamicEventForm);
// if operation is add
if (dynamicEventForm.isAddOperation())
{
if (dynamicEventForm.getUserId() == 0)
{
final SessionDataBean sessionData = this.getSessionData(request);
if (sessionData != null && sessionData.getUserId() != null)
{
final long userId = sessionData.getUserId().longValue();
dynamicEventForm.setUserId(userId);
}
}
// set the current Date and Time for the event.
final Calendar cal = Calendar.getInstance();
if (dynamicEventForm.getDateOfEvent() == null)
{
dynamicEventForm.setDateOfEvent(CommonUtilities.parseDateToString(cal.getTime(),
CommonServiceLocator.getInstance().getDatePattern()));
}
if (dynamicEventForm.getTimeInHours() == null)
{
dynamicEventForm.setTimeInHours(Integer.toString(cal.get(Calendar.HOUR_OF_DAY)));
}
if (dynamicEventForm.getTimeInMinutes() == null)
{
dynamicEventForm.setTimeInMinutes(Integer.toString(cal.get(Calendar.MINUTE)));
}
}
else
{
String specimenId = (String) request.getAttribute(Constants.SPECIMEN_ID);
if (specimenId == null)
{
request.setAttribute(Constants.SPECIMEN_ID, specimenId);
}
}
String reasonDeviation = "";
reasonDeviation = dynamicEventForm.getReasonDeviation();
if (reasonDeviation == null)
{
reasonDeviation = "";
}
String currentEventParametersDate = "";
currentEventParametersDate = dynamicEventForm.getDateOfEvent();
if (currentEventParametersDate == null)
{
currentEventParametersDate = "";
}
final Integer dynamicEventParametersYear = new Integer(AppUtility
.getYear(currentEventParametersDate));
final Integer dynamicEventParametersMonth = new Integer(AppUtility
.getMonth(currentEventParametersDate));
final Integer dynamicEventParametersDay = new Integer(AppUtility
.getDay(currentEventParametersDate));
request.setAttribute("minutesList", Constants.MINUTES_ARRAY);
// Sets the hourList attribute to be used in the Add/Edit
// FrozenEventParameters Page.
request.setAttribute("hourList", Constants.HOUR_ARRAY);
request.setAttribute("dynamicEventParametersYear", dynamicEventParametersYear);
request.setAttribute("dynamicEventParametersDay", dynamicEventParametersDay);
request.setAttribute("dynamicEventParametersMonth", dynamicEventParametersMonth);
request.setAttribute("formName", Constants.DYNAMIC_EVENT_ACTION);
request.setAttribute("addForJSP", Constants.ADD);
request.setAttribute("editForJSP", Constants.EDIT);
request.setAttribute("reasonDeviation", reasonDeviation);
request.setAttribute("userListforJSP", Constants.USERLIST);
request.setAttribute("currentEventParametersDate", currentEventParametersDate);
request.setAttribute(Constants.PAGE_OF, "pageOfDynamicEvent");
request.setAttribute(Constants.SPECIMEN_ID, request.getSession().getAttribute(
Constants.SPECIMEN_ID));
//request.setAttribute(Constants.SPECIMEN_ID, request.getAttribute(Constants.SPECIMEN_ID));
//request.setAttribute(Constants.PAGE_OF, request.getParameter(Constants.PAGE_OF));
//request.setAttribute("changeAction", Constants.CELL_SPECIMEN_REVIEW_PARAMETERS_ADD_ACTION);
final String operation = request.getParameter(Constants.OPERATION);
final IFactory factory = AbstractFactoryConfig.getInstance().getBizLogicFactory();
final UserBizLogic userBizLogic = (UserBizLogic) factory
.getBizLogic(Constants.USER_FORM_ID);
final Collection userCollection = userBizLogic.getUsers(operation);
request.setAttribute(Constants.USERLIST, userCollection);
HashMap dynamicEventMap = (HashMap) request.getSession().getAttribute("dynamicEventMap");
String iframeURL="";
long recordIdentifier=0;
Long eventId=null;
if(dynamicEventForm.getOperation().equals(Constants.ADD))
{
String eventName = request.getParameter("eventName");
if(eventName == null)
{
eventName = (String)request.getSession().getAttribute("eventName");
}
request.getSession().setAttribute("eventName", eventName);
dynamicEventForm.setEventName(eventName);
eventId=(Long) dynamicEventMap.get(eventName);
if (Boolean.parseBoolean(request.getParameter("showDefaultValues")))
{
IBizLogic defaultBizLogic = new CatissueDefaultBizLogic();
List<Action> actionList = defaultBizLogic.retrieve(Action.class.getName(),
Constants.ID, request.getParameter("formContextId"));
if (actionList != null && !actionList.isEmpty())
{
Action action = (Action) actionList.get(0);
if (action.getApplicationDefaultValue() != null)
{
recordIdentifier = SpecimenEventsUtility.getRecordIdentifier(action
.getApplicationDefaultValue().getId(), action.getContainerId());
}
}
}
else
{
IBizLogic defaultBizLogic = new CatissueDefaultBizLogic();
List<DefaultAction> actionList = defaultBizLogic.retrieve(DefaultAction.class
.getName(), Constants.CONTAINER_ID, eventId);
DefaultAction action =null;
if (actionList != null && !actionList.isEmpty())
{
action = (DefaultAction) actionList.get(0);
}
else
{
action=new DefaultAction();
action.setContainerId(eventId);
defaultBizLogic.insert(action);
}
request.setAttribute("formContextId",action.getId());
}
if(eventName != null)
{
request.setAttribute("formDisplayName", Utility.getFormattedString(eventName));
}
if(eventId != null)
{
request.getSession().setAttribute("OverrideCaption", "_" + eventId.toString());
iframeURL = "/catissuecore/LoadDataEntryFormAction.do?dataEntryOperation=insertParentData&useApplicationStylesheet=true&showInDiv=false&overrideCSS=true&overrideScroll=true"+(Boolean.parseBoolean(request.getParameter(Constants.CONTAINS_ERROR))?"&containerId=":"&containerIdentifier=")
+ eventId.toString() + "&OverrideCaption=" + "_" + eventId.toString()+"&showCalculateDefaultValue=false";
if (recordIdentifier != 0)
{
iframeURL = iframeURL + "&recordIdentifier=" + recordIdentifier;
}
}
}
else
{
String actionApplicationId = request.getParameter("id");
if(actionApplicationId ==null)
{
actionApplicationId = (String) request.getAttribute("id");
}
if(Boolean.parseBoolean(request.getParameter(Constants.CONTAINS_ERROR))
&& request.getSession().getAttribute("dynamicEventsForm") != null)
{
dynamicEventForm = (DynamicEventForm) request.getSession().getAttribute("dynamicEventsForm");
actionApplicationId = String.valueOf(dynamicEventForm.getId());
}
recordIdentifier = SpecimenEventsUtility.getRecordIdentifier(dynamicEventForm
.getRecordEntry(), dynamicEventForm.getContId());
Long containerId = dynamicEventForm.getContId();
IBizLogic defaultBizLogic = new CatissueDefaultBizLogic();
String specimenId = (String) request.getAttribute(Constants.SPECIMEN_ID);
boolean isDefaultAction = true;
if(specimenId!=null && !"".equals(specimenId))
{
List<Specimen> specimentList = defaultBizLogic.retrieve(
Specimen.class.getName(), Constants.ID, specimenId);
if (specimentList != null && !specimentList.isEmpty())
{
Specimen specimen = (Specimen) specimentList.get(0);
if(specimen.getProcessingSPPApplication() != null)
{
for(ActionApplication actionApplication : new SPPEventProcessor().getFilteredActionApplication(specimen.getProcessingSPPApplication().getSppActionApplicationCollection()))
{
if(actionApplication.getId().toString().equals(actionApplicationId))
{
for(Action action : specimen.getSpecimenRequirement().getProcessingSPP().getActionCollection())
{
if(action.getContainerId().equals(containerId))
{
request.setAttribute("formContextId", action.getId());
break;
}
}
isDefaultAction = false;
break;
}
}
}
}
}
if(isDefaultAction)
{
List<DefaultAction> actionList = defaultBizLogic.retrieve(
DefaultAction.class.getName(), Constants.CONTAINER_ID, dynamicEventForm
.getContId());
if (actionList != null && !actionList.isEmpty())
{
DefaultAction action = (DefaultAction) actionList.get(0);
request.setAttribute("formContextId", action.getId());
}
}
dynamicEventForm.setRecordIdentifier(recordIdentifier);
iframeURL = "/catissuecore/LoadDataEntryFormAction.do?dataEntryOperation=edit&useApplicationStylesheet=true&showInDiv=false"+(Boolean.parseBoolean(request.getParameter(Constants.CONTAINS_ERROR))?"&containerId=":"&containerIdentifier=")
+ dynamicEventForm.getContId()
+ "&recordIdentifier="
+ recordIdentifier
+ "&OverrideCaption=" + "_" + dynamicEventForm.getContId();
List contList = AppUtility
.executeSQLQuery("select caption from dyextn_container where identifier="
+ dynamicEventForm.getContId());
String eventName = (String) ((List) contList.get(0)).get(0);
request.setAttribute("formDisplayName", Utility.getFormattedString(eventName));
}
if (request.getSession().getAttribute("specimenId") == null)
{
request.getSession().setAttribute("specimenId", request.getParameter("specimenId"));
}
request.setAttribute("recordIdentifier", recordIdentifier);
request.getSession().setAttribute("recordIdentifier", recordIdentifier);
request.getSession().setAttribute("containerId", dynamicEventForm.getContId());
request.getSession().setAttribute("mandatory_Message", "false");
String formContxtId = getFormContextFromRequest(request);
if(!"".equals(iframeURL))
{
iframeURL = iframeURL + "&FormContextIdentifier=" + formContxtId;
}
populateStaticAttributes(request, dynamicEventForm);
request.setAttribute("iframeURL", iframeURL);
return mapping.findForward((String) request.getAttribute(Constants.PAGE_OF));
}
| protected ActionForward executeAction(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response) throws Exception
{
if (request.getParameter(Constants.REFRESH_EVENT_GRID) != null)
{
request.setAttribute(Constants.REFRESH_EVENT_GRID, request
.getParameter(Constants.REFRESH_EVENT_GRID));
}
//this.setCommonRequestParameters(request);
DynamicEventForm dynamicEventForm = (DynamicEventForm) form;
resetFormParameters(request, dynamicEventForm);
// if operation is add
if (dynamicEventForm.isAddOperation())
{
if (dynamicEventForm.getUserId() == 0)
{
final SessionDataBean sessionData = this.getSessionData(request);
if (sessionData != null && sessionData.getUserId() != null)
{
final long userId = sessionData.getUserId().longValue();
dynamicEventForm.setUserId(userId);
}
}
// set the current Date and Time for the event.
final Calendar cal = Calendar.getInstance();
if (dynamicEventForm.getDateOfEvent() == null)
{
dynamicEventForm.setDateOfEvent(CommonUtilities.parseDateToString(cal.getTime(),
CommonServiceLocator.getInstance().getDatePattern()));
}
if (dynamicEventForm.getTimeInHours() == null)
{
dynamicEventForm.setTimeInHours(Integer.toString(cal.get(Calendar.HOUR_OF_DAY)));
}
if (dynamicEventForm.getTimeInMinutes() == null)
{
dynamicEventForm.setTimeInMinutes(Integer.toString(cal.get(Calendar.MINUTE)));
}
}
else
{
String specimenId = (String) request.getAttribute(Constants.SPECIMEN_ID);
if (specimenId == null)
{
request.setAttribute(Constants.SPECIMEN_ID, specimenId);
}
}
String reasonDeviation = "";
reasonDeviation = dynamicEventForm.getReasonDeviation();
if (reasonDeviation == null)
{
reasonDeviation = "";
}
String currentEventParametersDate = "";
currentEventParametersDate = dynamicEventForm.getDateOfEvent();
if (currentEventParametersDate == null)
{
currentEventParametersDate = "";
}
final Integer dynamicEventParametersYear = new Integer(AppUtility
.getYear(currentEventParametersDate));
final Integer dynamicEventParametersMonth = new Integer(AppUtility
.getMonth(currentEventParametersDate));
final Integer dynamicEventParametersDay = new Integer(AppUtility
.getDay(currentEventParametersDate));
request.setAttribute("minutesList", Constants.MINUTES_ARRAY);
// Sets the hourList attribute to be used in the Add/Edit
// FrozenEventParameters Page.
request.setAttribute("hourList", Constants.HOUR_ARRAY);
request.setAttribute("dynamicEventParametersYear", dynamicEventParametersYear);
request.setAttribute("dynamicEventParametersDay", dynamicEventParametersDay);
request.setAttribute("dynamicEventParametersMonth", dynamicEventParametersMonth);
request.setAttribute("formName", Constants.DYNAMIC_EVENT_ACTION);
request.setAttribute("addForJSP", Constants.ADD);
request.setAttribute("editForJSP", Constants.EDIT);
request.setAttribute("reasonDeviation", reasonDeviation);
request.setAttribute("userListforJSP", Constants.USERLIST);
request.setAttribute("currentEventParametersDate", currentEventParametersDate);
request.setAttribute(Constants.PAGE_OF, "pageOfDynamicEvent");
request.setAttribute(Constants.SPECIMEN_ID, request.getSession().getAttribute(
Constants.SPECIMEN_ID));
//request.setAttribute(Constants.SPECIMEN_ID, request.getAttribute(Constants.SPECIMEN_ID));
//request.setAttribute(Constants.PAGE_OF, request.getParameter(Constants.PAGE_OF));
//request.setAttribute("changeAction", Constants.CELL_SPECIMEN_REVIEW_PARAMETERS_ADD_ACTION);
final String operation = request.getParameter(Constants.OPERATION);
final IFactory factory = AbstractFactoryConfig.getInstance().getBizLogicFactory();
final UserBizLogic userBizLogic = (UserBizLogic) factory
.getBizLogic(Constants.USER_FORM_ID);
final Collection userCollection = userBizLogic.getUsers(operation);
request.setAttribute(Constants.USERLIST, userCollection);
HashMap dynamicEventMap = (HashMap) request.getSession().getAttribute("dynamicEventMap");
String iframeURL="";
long recordIdentifier=0;
Long eventId=null;
if(dynamicEventForm.getOperation().equals(Constants.ADD))
{
String eventName = request.getParameter("eventName");
if(eventName == null)
{
eventName = (String)request.getSession().getAttribute("eventName");
}
request.getSession().setAttribute("eventName", eventName);
dynamicEventForm.setEventName(eventName);
eventId=(Long) dynamicEventMap.get(eventName);
String query="Select IS_CACORE_GENERATED from dyextn_entity_group where IDENTIFIER = (select ENTITY_GROUP_ID from dyextn_container where IDENTIFIER="+eventId+")";
List result=AppUtility.executeSQLQuery(query);
Boolean isCaCoreGenerated=Boolean.parseBoolean(((List) result.get(0)).get(0).toString());
if(!isCaCoreGenerated)
{
request.setAttribute("isCaCoreGenerated", true);
}
if (Boolean.parseBoolean(request.getParameter("showDefaultValues")))
{
IBizLogic defaultBizLogic = new CatissueDefaultBizLogic();
List<Action> actionList = defaultBizLogic.retrieve(Action.class.getName(),
Constants.ID, request.getParameter("formContextId"));
if (actionList != null && !actionList.isEmpty())
{
Action action = (Action) actionList.get(0);
if (action.getApplicationDefaultValue() != null)
{
recordIdentifier = SpecimenEventsUtility.getRecordIdentifier(action
.getApplicationDefaultValue().getId(), action.getContainerId());
}
}
}
else
{
IBizLogic defaultBizLogic = new CatissueDefaultBizLogic();
List<DefaultAction> actionList = defaultBizLogic.retrieve(DefaultAction.class
.getName(), Constants.CONTAINER_ID, eventId);
DefaultAction action =null;
if (actionList != null && !actionList.isEmpty())
{
action = (DefaultAction) actionList.get(0);
}
else
{
action=new DefaultAction();
action.setContainerId(eventId);
defaultBizLogic.insert(action);
}
request.setAttribute("formContextId",action.getId());
}
if(eventName != null)
{
request.setAttribute("formDisplayName", Utility.getFormattedString(eventName));
}
if(eventId != null)
{
request.getSession().setAttribute("OverrideCaption", "_" + eventId.toString());
iframeURL = "/catissuecore/LoadDataEntryFormAction.do?dataEntryOperation=insertParentData&useApplicationStylesheet=true&showInDiv=false&overrideCSS=true&overrideScroll=true"+(Boolean.parseBoolean(request.getParameter(Constants.CONTAINS_ERROR))?"&containerId=":"&containerIdentifier=")
+ eventId.toString() + "&OverrideCaption=" + "_" + eventId.toString()+"&showCalculateDefaultValue=false";
if (recordIdentifier != 0)
{
iframeURL = iframeURL + "&recordIdentifier=" + recordIdentifier;
}
}
}
else
{
String actionApplicationId = request.getParameter("id");
if(actionApplicationId ==null)
{
actionApplicationId = (String) request.getAttribute("id");
}
if(Boolean.parseBoolean(request.getParameter(Constants.CONTAINS_ERROR))
&& request.getSession().getAttribute("dynamicEventsForm") != null)
{
dynamicEventForm = (DynamicEventForm) request.getSession().getAttribute("dynamicEventsForm");
actionApplicationId = String.valueOf(dynamicEventForm.getId());
}
recordIdentifier = SpecimenEventsUtility.getRecordIdentifier(dynamicEventForm
.getRecordEntry(), dynamicEventForm.getContId());
Long containerId = dynamicEventForm.getContId();
IBizLogic defaultBizLogic = new CatissueDefaultBizLogic();
String specimenId = (String) request.getAttribute(Constants.SPECIMEN_ID);
boolean isDefaultAction = true;
if(specimenId!=null && !"".equals(specimenId))
{
List<Specimen> specimentList = defaultBizLogic.retrieve(
Specimen.class.getName(), Constants.ID, specimenId);
if (specimentList != null && !specimentList.isEmpty())
{
Specimen specimen = (Specimen) specimentList.get(0);
if(specimen.getProcessingSPPApplication() != null)
{
for(ActionApplication actionApplication : new SPPEventProcessor().getFilteredActionApplication(specimen.getProcessingSPPApplication().getSppActionApplicationCollection()))
{
if(actionApplication.getId().toString().equals(actionApplicationId))
{
for(Action action : specimen.getSpecimenRequirement().getProcessingSPP().getActionCollection())
{
if(action.getContainerId().equals(containerId))
{
request.setAttribute("formContextId", action.getId());
break;
}
}
isDefaultAction = false;
break;
}
}
}
}
}
if(isDefaultAction)
{
List<DefaultAction> actionList = defaultBizLogic.retrieve(
DefaultAction.class.getName(), Constants.CONTAINER_ID, dynamicEventForm
.getContId());
if (actionList != null && !actionList.isEmpty())
{
DefaultAction action = (DefaultAction) actionList.get(0);
request.setAttribute("formContextId", action.getId());
}
}
dynamicEventForm.setRecordIdentifier(recordIdentifier);
iframeURL = "/catissuecore/LoadDataEntryFormAction.do?dataEntryOperation=edit&useApplicationStylesheet=true&showInDiv=false"+(Boolean.parseBoolean(request.getParameter(Constants.CONTAINS_ERROR))?"&containerId=":"&containerIdentifier=")
+ dynamicEventForm.getContId()
+ "&recordIdentifier="
+ recordIdentifier
+ "&OverrideCaption=" + "_" + dynamicEventForm.getContId();
List contList = AppUtility
.executeSQLQuery("select caption from dyextn_container where identifier="
+ dynamicEventForm.getContId());
String eventName = (String) ((List) contList.get(0)).get(0);
request.setAttribute("formDisplayName", Utility.getFormattedString(eventName));
}
if (request.getSession().getAttribute("specimenId") == null)
{
request.getSession().setAttribute("specimenId", request.getParameter("specimenId"));
}
request.setAttribute("recordIdentifier", recordIdentifier);
request.getSession().setAttribute("recordIdentifier", recordIdentifier);
request.getSession().setAttribute("containerId", dynamicEventForm.getContId());
request.getSession().setAttribute("mandatory_Message", "false");
String formContxtId = getFormContextFromRequest(request);
if(!"".equals(iframeURL))
{
iframeURL = iframeURL + "&FormContextIdentifier=" + formContxtId;
}
populateStaticAttributes(request, dynamicEventForm);
request.setAttribute("iframeURL", iframeURL);
return mapping.findForward((String) request.getAttribute(Constants.PAGE_OF));
}
|
diff --git a/src/newsrack/util/URLCanonicalizer.java b/src/newsrack/util/URLCanonicalizer.java
index 69c2328..0e7d947 100644
--- a/src/newsrack/util/URLCanonicalizer.java
+++ b/src/newsrack/util/URLCanonicalizer.java
@@ -1,42 +1,42 @@
package newsrack.util;
// This class takes urls of news stories so that we can more easily
// recognize identical urls. For now, this class hardcodes rules
// for a few sites. In future, this information should come from
// an external file that specifies match-rewrite rules for urls
public class URLCanonicalizer
{
public static String cleanup(String baseUrl, String url)
{
// get rid of all white space!
url = url.replaceAll("\\s+", "");
// Is this allowed in the spec??? Some feeds (like timesnow) uses relative URLs!
if (url.startsWith("/"))
url = baseUrl + url;
return url;
}
public static String canonicalize(String url)
{
- if (url.indexOf("google.com/") != -1) {
+ if (url.indexOf("news.google.com/") != -1) {
int proxyUrlStart = url.lastIndexOf("http://");
if (proxyUrlStart != -1) {
url = url.substring(proxyUrlStart);
url = url.substring(0, url.lastIndexOf("&cid="));
}
}
// Do not use 'else if'
if (!url.startsWith("http://uni.medhas.org")) {
url = url.substring(url.lastIndexOf("http://"));
}
// Do not use 'else if'
if (url.indexOf("nytimes.com/") != -1) {
int qi = url.indexOf('?');
if (qi != -1)
url = url.substring(0, qi);
}
return url;
}
}
| true | true | public static String canonicalize(String url)
{
if (url.indexOf("google.com/") != -1) {
int proxyUrlStart = url.lastIndexOf("http://");
if (proxyUrlStart != -1) {
url = url.substring(proxyUrlStart);
url = url.substring(0, url.lastIndexOf("&cid="));
}
}
// Do not use 'else if'
if (!url.startsWith("http://uni.medhas.org")) {
url = url.substring(url.lastIndexOf("http://"));
}
// Do not use 'else if'
if (url.indexOf("nytimes.com/") != -1) {
int qi = url.indexOf('?');
if (qi != -1)
url = url.substring(0, qi);
}
return url;
}
| public static String canonicalize(String url)
{
if (url.indexOf("news.google.com/") != -1) {
int proxyUrlStart = url.lastIndexOf("http://");
if (proxyUrlStart != -1) {
url = url.substring(proxyUrlStart);
url = url.substring(0, url.lastIndexOf("&cid="));
}
}
// Do not use 'else if'
if (!url.startsWith("http://uni.medhas.org")) {
url = url.substring(url.lastIndexOf("http://"));
}
// Do not use 'else if'
if (url.indexOf("nytimes.com/") != -1) {
int qi = url.indexOf('?');
if (qi != -1)
url = url.substring(0, qi);
}
return url;
}
|
diff --git a/main/src/jp/ac/osaka_u/ist/sel/metricstool/main/plugin/AbstractPlugin.java b/main/src/jp/ac/osaka_u/ist/sel/metricstool/main/plugin/AbstractPlugin.java
index ccf30348..f75ff683 100644
--- a/main/src/jp/ac/osaka_u/ist/sel/metricstool/main/plugin/AbstractPlugin.java
+++ b/main/src/jp/ac/osaka_u/ist/sel/metricstool/main/plugin/AbstractPlugin.java
@@ -1,660 +1,660 @@
package jp.ac.osaka_u.ist.sel.metricstool.main.plugin;
import java.io.File;
import java.security.AccessControlException;
import java.security.Permission;
import java.security.Permissions;
import java.util.Enumeration;
import jp.ac.osaka_u.ist.sel.metricstool.main.data.accessor.ClassInfoAccessor;
import jp.ac.osaka_u.ist.sel.metricstool.main.data.accessor.ClassMetricsRegister;
import jp.ac.osaka_u.ist.sel.metricstool.main.data.accessor.DefaultClassInfoAccessor;
import jp.ac.osaka_u.ist.sel.metricstool.main.data.accessor.DefaultClassMetricsRegister;
import jp.ac.osaka_u.ist.sel.metricstool.main.data.accessor.DefaultFileInfoAccessor;
import jp.ac.osaka_u.ist.sel.metricstool.main.data.accessor.DefaultFileMetricsRegister;
import jp.ac.osaka_u.ist.sel.metricstool.main.data.accessor.DefaultMethodInfoAccessor;
import jp.ac.osaka_u.ist.sel.metricstool.main.data.accessor.DefaultMethodMetricsRegister;
import jp.ac.osaka_u.ist.sel.metricstool.main.data.accessor.FileInfoAccessor;
import jp.ac.osaka_u.ist.sel.metricstool.main.data.accessor.FileMetricsRegister;
import jp.ac.osaka_u.ist.sel.metricstool.main.data.accessor.MethodInfoAccessor;
import jp.ac.osaka_u.ist.sel.metricstool.main.data.accessor.MethodMetricsRegister;
import jp.ac.osaka_u.ist.sel.metricstool.main.data.metric.MetricAlreadyRegisteredException;
import jp.ac.osaka_u.ist.sel.metricstool.main.data.target.ClassInfo;
import jp.ac.osaka_u.ist.sel.metricstool.main.data.target.FileInfo;
import jp.ac.osaka_u.ist.sel.metricstool.main.data.target.MethodInfo;
import jp.ac.osaka_u.ist.sel.metricstool.main.io.AlreadyConnectedException;
import jp.ac.osaka_u.ist.sel.metricstool.main.io.DefaultMessagePrinter;
import jp.ac.osaka_u.ist.sel.metricstool.main.io.DefaultProgressReporter;
import jp.ac.osaka_u.ist.sel.metricstool.main.io.MessagePrinter;
import jp.ac.osaka_u.ist.sel.metricstool.main.io.MessageSource;
import jp.ac.osaka_u.ist.sel.metricstool.main.io.ProgressReporter;
import jp.ac.osaka_u.ist.sel.metricstool.main.io.ProgressSource;
import jp.ac.osaka_u.ist.sel.metricstool.main.io.MessagePrinter.MESSAGE_TYPE;
import jp.ac.osaka_u.ist.sel.metricstool.main.security.MetricsToolSecurityManager;
import jp.ac.osaka_u.ist.sel.metricstool.main.util.LANGUAGE;
import jp.ac.osaka_u.ist.sel.metricstool.main.util.METRIC_TYPE;
/**
* ���g���N�X�v���v���O�C�������p�̒��ۃN���X
* <p>
* �e�v���O�C���͂��̃N���X���p�������N���X��1�����Ȃ���Ȃ�Ȃ��D �܂��C���̃N���X����plugin.xml�t�@�C���Ɏw��̌`���ŋL�q���Ȃ���Ȃ�Ȃ��D
* <p>
* main���W���[���͊e�v���O�C���f�B���N�g������plugin.xml�t�@�C����T�����A �����ɋL�q����Ă���C���̃N���X���p�������N���X���C���X�^���X�����A
* �e���\�b�h��ʂ��ď����擾������Aexecute���\�b�h���Ăяo���ă��g���N�X�l���v������
*
* @author kou-tngt
*/
public abstract class AbstractPlugin implements MessageSource, ProgressSource {
/**
* �v���O�C���̏���ۑ���������s�σN���X�D AbstractPlugin����̂݃C���X�^���X���ł���D
* <p>
* �v���O�C���̏��I�ɕύX�����ƍ���̂ŁA���̓����N���X�̃C���X�^���X��p���� �������Ƃ��邱�ƂŃv���O�C�����̕s�ϐ�����������D
* �e�v���O�C���̏���ۑ�����PluginInfo�C���X�^���X�̎擾�ɂ� {@link AbstractPlugin#getPluginInfo()}��p����D
*
* @author kou-tngt
*
*/
public class PluginInfo {
/**
* �f�t�H���g�̃R���X�g���N�^
*/
private PluginInfo() {
final LANGUAGE[] languages = AbstractPlugin.this.getMeasurableLanguages();
this.measurableLanguages = new LANGUAGE[languages.length];
System.arraycopy(languages, 0, this.measurableLanguages, 0, languages.length);
this.metricName = AbstractPlugin.this.getMetricName();
this.metricType = AbstractPlugin.this.getMetricType();
this.useClassInfo = AbstractPlugin.this.useClassInfo();
this.useMethodInfo = AbstractPlugin.this.useMethodInfo();
this.useFieldInfo = AbstractPlugin.this.useFieldInfo();
this.useFileInfo = AbstractPlugin.this.useFileInfo();
this.useMethodLocalInfo = AbstractPlugin.this.useMethodLocalInfo();
this.description = AbstractPlugin.this.getDescription();
this.detailDescription = AbstractPlugin.this.getDetailDescription();
}
/**
* ���̃v���O�C���̊ȈՐ������P�s�ŕԂ��i�ł���Ήp��Łj. �f�t�H���g�̎����ł� "Measure ���g���N�X�� metrics." �ƕԂ�
* �e�v���O�C���͂��̃��\�b�h��C�ӂɃI�[�o�[���C�h����.
*
* @return �ȈՐ���������
*/
public String getDescription() {
return this.description;
}
/**
* ���̃v���O�C���̏ڍא�����Ԃ��i�ł���Ήp��Łj. �f�t�H���g�̎����ł͋����Ԃ� �e�v���O�C���͂��̃��\�b�h��C�ӂɃI�[�o�[���C�h����.
*
* @return �ڍא���������
*/
public String getDetailDescription() {
return this.detailDescription;
}
/**
* ���̃v���O�C�������g���N�X���v���ł��錾���Ԃ��D
*
* @return �v���\�Ȍ����S�Ċ܂ޔz��D
*/
public LANGUAGE[] getMeasurableLanguages() {
return this.measurableLanguages;
}
/**
* ���̃v���O�C���������Ŏw�肳�ꂽ����ŗ��p�\�ł��邩��Ԃ��D
*
* @param language ���p�\�ł��邩�ׂ�������
* @return ���p�\�ł���ꍇ�� true�C���p�ł��Ȃ��ꍇ�� false�D
*/
public boolean isMeasurable(final LANGUAGE language) {
final LANGUAGE[] measurableLanguages = this.getMeasurableLanguages();
for (int i = 0; i < measurableLanguages.length; i++) {
if (language.equals(measurableLanguages[i])) {
return true;
}
}
return false;
}
/**
* ���̃v���O�C�����v�����郁�g���N�X�̖��O��Ԃ��D
*
* @return ���g���N�X��
*/
public String getMetricName() {
return this.metricName;
}
/**
* ���̃v���O�C�����v�����郁�g���N�X�̃^�C�v��Ԃ��D
*
* @return ���g���N�X�^�C�v
* @see jp.ac.osaka_u.ist.sel.metricstool.main.util.METRIC_TYPE
*/
public METRIC_TYPE getMetricType() {
return this.metricType;
}
/**
* ���̃v���O�C�����N���X�Ɋւ�����𗘗p���邩�ǂ�����Ԃ��D
*
* @return �N���X�Ɋւ�����𗘗p����ꍇ��true�D
*/
public boolean isUseClassInfo() {
return this.useClassInfo;
}
/**
* ���̃v���O�C�����t�B�[���h�Ɋւ�����𗘗p���邩�ǂ�����Ԃ��D
*
* @return �t�B�[���h�Ɋւ�����𗘗p����ꍇ��true�D
*/
public boolean isUseFieldInfo() {
return this.useFieldInfo;
}
/**
* ���̃v���O�C�����t�@�C���Ɋւ�����𗘗p���邩�ǂ�����Ԃ��D
*
* @return �t�@�C���Ɋւ�����𗘗p����ꍇ��true�D
*/
public boolean isUseFileInfo() {
return this.useFileInfo;
}
/**
* ���̃v���O�C�������\�b�h�Ɋւ�����𗘗p���邩�ǂ�����Ԃ��D
*
* @return ���\�b�h�Ɋւ�����𗘗p����ꍇ��true�D
*/
public boolean isUseMethodInfo() {
return this.useMethodInfo;
}
/**
* ���̃v���O�C�������\�b�h�����Ɋւ�����𗘗p���邩�ǂ�����Ԃ��D
*
* @return ���\�b�h�����Ɋւ�����𗘗p����ꍇ��true�D
*/
public boolean isUseMethodLocalInfo() {
return this.useMethodLocalInfo;
}
private final LANGUAGE[] measurableLanguages;
private final String metricName;
private final METRIC_TYPE metricType;
private final String description;
private final String detailDescription;
private final boolean useClassInfo;
private final boolean useFieldInfo;
private final boolean useFileInfo;
private final boolean useMethodInfo;
private final boolean useMethodLocalInfo;
}
/**
* �v���O�C���̎��s���ɋ������p�[�~�b�V������lj�����. ���ʌ��������X���b�h���炵���Ăяo���Ȃ�.
*
* @param permission ������p�[�~�b�V����
* @throws AccessControlException ���ʌ����������Ȃ��X���b�h����Ăяo�����ꍇ
*/
public final void addPermission(final Permission permission) {
MetricsToolSecurityManager.getInstance().checkAccess();
this.permissions.add(permission);
}
/**
* �v���O�C���C���X�^���X���m���r����. �N���X�̕W����������Ȃ炻���p���Ĕ�r����. ���Ȃ��ꍇ�́C {@link Class}�C���X�^���X�̂��r����.
* �������C�ʏ�̋@�\��p���ă��[�h�����v���O�C���������N���X�ł��邱�Ƃ͂��肦�Ȃ�.
* ����āC����v���O�C���N���X�̃C���X�^���X�͕ʂ̃N���X���[�_���烍�[�h����Ă�����ł���Ɣ��肳���.
*
* @see java.lang.Object#equals(java.lang.Object)
* @see #hashCode()
*/
@Override
public final boolean equals(final Object o) {
if (o instanceof AbstractPlugin) {
final String myClassName = this.getClass().getCanonicalName();
final String otherClassName = o.getClass().getCanonicalName();
if (null != myClassName && null != otherClassName) {
// �ǂ���������N���X����Ȃ��ꍇ
return myClassName.equals(otherClassName);
} else if (null != myClassName || null != otherClassName) {
// �ǂ������͓����N���X�����ǁC�ǂ������͈Ⴄ
return false;
} else {
// �����Ƃ������N���X
return this.getClass().equals(o.getClass());
}
}
return false;
}
/**
* �v���O�C���C���X�^���X�̃n�b�V���R�[�h��Ԃ�. �N���X�̕W����������Ȃ炻�̃n�b�V���R�[�h���g��. ���Ȃ��ꍇ�́C {@link Class}�C���X�^���X�̃n�b�V���R�[�h���g��.
* �������C�ʏ�̋@�\��p���Ă����[�h�����v���O�C���������N���X�ł��邱�Ƃ͂��肦�Ȃ�.
* ����āC����v���O�C���N���X�̃C���X�^���X�͕ʂ̃N���X���[�_���烍�[�h����Ă�����̃n�b�V���R�[�h��Ԃ�.
*
* @see java.lang.Object#hashCode()(java.lang.Object)
* @see #equals(Object)
*/
@Override
public final int hashCode() {
final Class myClass = this.getClass();
final String myClassName = myClass.getCanonicalName();
return myClassName != null ? myClassName.hashCode() : myClass.hashCode();
}
/**
* �v���O�C���̃��[�g�f�B���N�g�����Z�b�g���� ��x�Z�b�g���ꂽ�l��ύX���邱�Ƃ͏o���Ȃ�.
*
* @param rootDir ���[�g�f�B���N�g��
* @throws NullPointerException rootDir��null�̏ꍇ
* @throws IllegalStateException rootDir�����ɃZ�b�g����Ă���ꍇ
*/
public final synchronized void setPluginRootdir(final File rootDir) {
MetricsToolSecurityManager.getInstance().checkAccess();
if (null == rootDir) {
throw new NullPointerException("rootdir is null.");
}
if (null != this.pluginRootDir) {
throw new IllegalStateException("rootdir was already set.");
}
this.pluginRootDir = rootDir;
}
/**
* ���b�Z�[�W���M�҂Ƃ��Ă̖��O��Ԃ�
*
* @return ���M�҂Ƃ��Ă̖��O
* @see jp.ac.osaka_u.ist.sel.metricstool.main.plugin.connection.MessageSource#getMessageSourceName()
*/
public String getMessageSourceName() {
return this.sourceName;
}
/**
* ���̃v���O�C���ɋ�����Ă���p�[�~�b�V�����̕s�ςȏW����Ԃ�.
*
* @return ���̃v���O�C���ɋ�����Ă���p�[�~�b�V�����̏W��.
*/
public final Permissions getPermissions() {
final Permissions permissions = new Permissions();
for (final Enumeration<Permission> enumeration = this.permissions.elements(); enumeration
.hasMoreElements();) {
permissions.add(enumeration.nextElement());
}
permissions.setReadOnly();
return permissions;
}
/**
* �v���O�C������ۑ����Ă���{@link PluginInfo}�N���X�̃C���X�^���X��Ԃ��D
* �����AbstractPlugin�C���X�^���X�ɑ��邱�̃��\�b�h�͕K������̃C���X�^���X��Ԃ��C ���̓����ɕۑ�����Ă�����͕s�ςł���D
*
* @return �v���O�C������ۑ����Ă���{@link PluginInfo}�N���X�̃C���X�^���X
*/
public final PluginInfo getPluginInfo() {
if (null == this.pluginInfo) {
synchronized (this) {
if (null == this.pluginInfo) {
this.pluginInfo = new PluginInfo();
this.sourceName = this.pluginInfo.getMetricName();
}
}
}
return this.pluginInfo;
}
/**
* �v���O�C���̃��[�g�f�B���N�g����Ԃ�
*
* @return �v���O�C���̃��[�g�f�B���N�g��
*/
public final File getPluginRootDir() {
return this.pluginRootDir;
}
/**
* �i����M�҂Ƃ��Ă̖��O��Ԃ�
*
* @return �i����M�҂Ƃ��Ă̖��O
* @see jp.ac.osaka_u.ist.sel.metricstool.main.plugin.connection.ProgressSource#getProgressSourceName()
*/
public String getProgressSourceName() {
return this.sourceName;
}
/**
* �v���O�C������ɍ\�z�ς݂��ǂ�����Ԃ�
*
* @return �v���O�C������ɍ\�z�ς݂Ȃ�true,�����łȂ����false
*/
public final boolean isPluginInfoCreated() {
return null != this.pluginInfo;
}
/**
* ���g���N�X��͂��X�^�[�g���钊�ۃ��\�b�h�D
*/
protected abstract void execute();
/**
* �t�@�C�����ɃA�N�Z�X����f�t�H���g�̃A�N�Z�T���擾����.
*
* @return �t�@�C�����ɃA�N�Z�X����f�t�H���g�̃A�N�Z�T.
*/
protected final FileInfoAccessor getFileInfoAccessor() {
return this.fileInfoAccessor;
}
/**
* �N���X���ɃA�N�Z�X����f�t�H���g�̃A�N�Z�T���擾����.
*
* @return �N���X���ɃA�N�Z�X����f�t�H���g�̃A�N�Z�T.
*/
protected final ClassInfoAccessor getClassInfoAccessor() {
return this.classInfoAccessor;
}
/**
* ���\�b�h���ɃA�N�Z�X����f�t�H���g�̃A�N�Z�T���擾����.
*
* @return ���\�b�h���ɃA�N�Z�X����f�t�H���g�̃A�N�Z�T.
*/
protected final MethodInfoAccessor getMethodInfoAccessor() {
return this.methodInfoAccessor;
}
/**
* ���̃v���O�C���̊ȈՐ������P�s�ŕԂ��i�ł���Ήp��Łj �f�t�H���g�̎����ł� "Measuring the ���g���N�X�� metric." �ƕԂ�
* �e�v���O�C���͂��̃��\�b�h��C�ӂɃI�[�o�[���C�h����.
*
* @return �ȈՐ���������
*/
protected String getDescription() {
return "Measuring the " + this.getMetricName() + " metric.";
}
/**
* ���̃v���O�C���̏ڍא�����Ԃ��i�ł���Ήp��Łj �f�t�H���g�����ł͋����Ԃ�. �e�v���O�C���͂��̃��\�b�h��C�ӂɃI�[�o�[���C�h����.
*
* @return
*/
protected String getDetailDescription() {
return "";
}
/**
* ���̃v���O�C�������g���N�X���v���ł��錾���Ԃ� ���p�ł��錾��ɐ����̂���v���O�C���́A���̃��\�b�h���I�[�o�[���C�h����K�v������D
*
* @return �v���\�Ȍ����S�Ċ܂ޔz��
* @see jp.ac.osaka_u.ist.sel.metricstool.main.util.LANGUAGE
*/
protected LANGUAGE[] getMeasurableLanguages() {
return LANGUAGE.values();
}
/**
* ���̃v���O�C�����v�����郁�g���N�X�̖��O��Ԃ����ۃ��\�b�h�D
*
* @return ���g���N�X��
*/
protected abstract String getMetricName();
/**
* ���̃v���O�C�����v�����郁�g���N�X�̃^�C�v��Ԃ����ۃ��\�b�h�D
*
* @return ���g���N�X�^�C�v
* @see jp.ac.osaka_u.ist.sel.metricstool.main.util.METRIC_TYPE
*/
protected abstract METRIC_TYPE getMetricType();
/**
* �t�@�C���P�ʂ̃��g���N�X�l��o�^���郁�\�b�h.
*
* @param fileInfo ���g���N�X�l��o�^����t�@�C��
* @param value ���g���N�X�l
* @throws MetricAlreadyRegisteredException ���ɂ��̃v���O�C�����炱�̃t�@�C���Ɋւ��郁�g���N�X�l�̕�����Ă���ꍇ.
*/
protected final void registMetric(final FileInfo fileInfo, final Number value)
throws MetricAlreadyRegisteredException {
if ((null == fileInfo) || (null == value)) {
throw new NullPointerException();
}
if (null == this.fileMetricsRegister) {
synchronized (this) {
if (null == this.fileMetricsRegister) {
this.fileMetricsRegister = new DefaultFileMetricsRegister(this);
}
}
}
this.fileMetricsRegister.registMetric(fileInfo, value);
}
/**
* �N���X�P�ʂ̃��g���N�X�l��o�^���郁�\�b�h.
*
* @param classInfo ���g���N�X�l��o�^����N���X
* @param value ���g���N�X�l
* @throws MetricAlreadyRegisteredException ���ɂ��̃v���O�C�����炱�̃N���X�Ɋւ��郁�g���N�X�l�̕�����Ă���ꍇ.
*/
protected final void registMetric(final ClassInfo classInfo, final Number value)
throws MetricAlreadyRegisteredException {
if ((null == classInfo) || (null == value)) {
throw new NullPointerException();
}
if (null == this.classMetricsRegister) {
synchronized (this) {
if (null == this.classMetricsRegister) {
this.classMetricsRegister = new DefaultClassMetricsRegister(this);
}
}
}
this.classMetricsRegister.registMetric(classInfo, value);
}
/**
* ���\�b�h�P�ʂ̃��g���N�X�l��o�^���郁�\�b�h.
*
* @param methodInfo ���g���N�X�l��o�^���郁�\�b�h
* @param value ���g���N�X�l
* @throws MetricAlreadyRegisteredException ���ɂ��̃v���O�C�����炱�̃��\�b�h�Ɋւ��郁�g���N�X�l�̕�����Ă���ꍇ.
*/
protected final void registMetric(final MethodInfo methodInfo, final Number value)
throws MetricAlreadyRegisteredException {
if ((null == methodInfo) || (null == value)) {
throw new NullPointerException();
}
if (null == this.methodMetricsRegister) {
synchronized (this) {
if (null == this.methodMetricsRegister) {
this.methodMetricsRegister = new DefaultMethodMetricsRegister(this);
}
}
}
this.methodMetricsRegister.registMetric(methodInfo, value);
}
/**
* ���̃v���O�C������̐i�����𑗂郁�\�b�h
*
* @param percentage �i�����l
*/
protected final void reportProgress(final int percentage) {
if (this.reporter != null) {
this.reporter.reportProgress(percentage);
}
}
/**
* ���̃v���O�C�����N���X�Ɋւ�����𗘗p���邩�ǂ�����Ԃ����\�b�h�D �f�t�H���g�����ł�false��Ԃ��D
* �N���X�Ɋւ�����𗘗p����v���O�C���͂��̃��\�b�h���I�[�o�[���[�h����true��Ԃ��Ȃ���ΐ���Ȃ��D
*
* @return �N���X�Ɋւ�����𗘗p����ꍇ��true�D
*/
protected boolean useClassInfo() {
return false;
}
/**
* ���̃v���O�C�����t�B�[���h�Ɋւ�����𗘗p���邩�ǂ�����Ԃ����\�b�h�D �f�t�H���g�����ł�false��Ԃ��D
* �t�B�[���h�Ɋւ�����𗘗p����v���O�C���͂��̃��\�b�h���I�[�o�[���[�h����true��Ԃ��Ȃ���ΐ���Ȃ��D
*
* @return �t�B�[���h�Ɋւ�����𗘗p����ꍇ��true�D
*/
protected boolean useFieldInfo() {
return false;
}
/**
* ���̃v���O�C�����t�@�C���Ɋւ�����𗘗p���邩�ǂ�����Ԃ����\�b�h�D �f�t�H���g�����ł�false��Ԃ��D
* �t�@�C���Ɋւ�����𗘗p����v���O�C���͂��̃��\�b�h���I�[�o�[���[�h����true��Ԃ��Ȃ���ΐ���Ȃ��D
*
* @return �t�@�C���Ɋւ�����𗘗p����ꍇ��true�D
*/
protected boolean useFileInfo() {
return false;
}
/**
* ���̃v���O�C�������\�b�h�Ɋւ�����𗘗p���邩�ǂ�����Ԃ����\�b�h�D �f�t�H���g�����ł�false��Ԃ��D
* ���\�b�h�Ɋւ�����𗘗p����v���O�C���͂��̃��\�b�h���I�[�o�[���[�h����true��Ԃ��Ȃ���ΐ���Ȃ��D
*
* @return ���\�b�h�Ɋւ�����𗘗p����ꍇ��true�D
*/
protected boolean useMethodInfo() {
return false;
}
/**
* ���̃v���O�C�������\�b�h�����Ɋւ�����𗘗p���邩�ǂ�����Ԃ����\�b�h�D �f�t�H���g�����ł�false��Ԃ��D
* ���\�b�h�����Ɋւ�����𗘗p����v���O�C���͂��̃��\�b�h���I�[�o�[���[�h����true��Ԃ��Ȃ���ΐ���Ȃ��D
*
* @return ���\�b�h�����Ɋւ�����𗘗p����ꍇ��true�D
*/
protected boolean useMethodLocalInfo() {
return false;
}
/**
* ���s�O��̋��ʏ��������Ă���C {@link #execute()}���Ăяo��.
*/
final synchronized void executionWrapper() {
assert (null == this.reporter) : "Illegal state : previous reporter was not removed.";
try {
this.reporter = new DefaultProgressReporter(this);
} catch (final AlreadyConnectedException e1) {
assert (null == this.reporter) : "Illegal state : previous reporter was still connected.";
}
// ���̃X���b�h�Ƀp�[�~�b�V������������悤�ɗv��
MetricsToolSecurityManager.getInstance().requestPluginPermission(this);
try {
this.execute();
- } catch (final Exception e) {
+ } catch (final Throwable e) {
this.err.println(e);
}
if (null != this.reporter) {
// �i���̏I���C�x���g�𑗂�
// �v���O�C�����Ŋ��ɑ����Ă����牽�������ɕԂ��Ă���
this.reporter.reportProgressEnd();
this.reporter = null;
}
// ���̃X���b�h����p�[�~�b�V��������������悤�ɗv��
MetricsToolSecurityManager.getInstance().removePluginPermission(this);
}
/**
* ���b�Z�[�W�o�͗p�̃v�����^�[
*/
protected final MessagePrinter out = new DefaultMessagePrinter(this, MESSAGE_TYPE.OUT);
/**
* �G���[���b�Z�[�W�o�͗p�̃v�����^�[
*/
protected final MessagePrinter err = new DefaultMessagePrinter(this, MESSAGE_TYPE.ERROR);
/**
* �o�^����Ă���t�@�C�����ɃA�N�Z�X����f�t�H���g�̃A�N�Z�T.
*/
private final FileInfoAccessor fileInfoAccessor = new DefaultFileInfoAccessor();
/**
* �o�^����Ă���N���X���ɃA�N�Z�X����f�t�H���g�̃A�N�Z�T.
*/
private final ClassInfoAccessor classInfoAccessor = new DefaultClassInfoAccessor();
/**
* �o�^����Ă��郁�\�b�h���ɃA�N�Z�X����f�t�H���g�̃A�N�Z�T.
*/
private final MethodInfoAccessor methodInfoAccessor = new DefaultMethodInfoAccessor();
/**
* �t�@�C���P�ʂ̃��g���N�X�l��o�^���郌�W�X�^.
*/
private FileMetricsRegister fileMetricsRegister;
/**
* �N���X�P�ʂ̃��g���N�X�l��o�^���郌�W�X�^.
*/
private ClassMetricsRegister classMetricsRegister;
/**
* ���\�b�h�P�ʂ̃��g���N�X�l��o�^���郌�W�X�^.
*/
private MethodMetricsRegister methodMetricsRegister;
/**
* �i����M�p�̃��|�[�^�[
*/
private ProgressReporter reporter;
/**
* ���̃v���O�C���̎��s���̋������p�[�~�b�V����
*/
private final Permissions permissions = new Permissions();
/**
* �v���O�C���̏���ۑ�����{@link PluginInfo}�N���X�̃C���X�^���X getPluginInfo���\�b�h�̏���̌Ăяo���ɂ���č쐬����D
* ����ȍ~�A���̃t�B�[���h�͏�ɓ����C���X�^���X���Q�Ƃ���D
*/
private PluginInfo pluginInfo;
/**
* �v���O�C���̃��[�g�f�B���N�g��
*/
private File pluginRootDir;
/**
* {@link MessageSource}�� {@link ProgressSource}�p�̖��O
*/
private String sourceName = "";
}
| true | true | final synchronized void executionWrapper() {
assert (null == this.reporter) : "Illegal state : previous reporter was not removed.";
try {
this.reporter = new DefaultProgressReporter(this);
} catch (final AlreadyConnectedException e1) {
assert (null == this.reporter) : "Illegal state : previous reporter was still connected.";
}
// ���̃X���b�h�Ƀp�[�~�b�V������������悤�ɗv��
MetricsToolSecurityManager.getInstance().requestPluginPermission(this);
try {
this.execute();
} catch (final Exception e) {
this.err.println(e);
}
if (null != this.reporter) {
// �i���̏I���C�x���g�𑗂�
// �v���O�C�����Ŋ��ɑ����Ă����牽�������ɕԂ��Ă���
this.reporter.reportProgressEnd();
this.reporter = null;
}
// ���̃X���b�h����p�[�~�b�V��������������悤�ɗv��
MetricsToolSecurityManager.getInstance().removePluginPermission(this);
}
| final synchronized void executionWrapper() {
assert (null == this.reporter) : "Illegal state : previous reporter was not removed.";
try {
this.reporter = new DefaultProgressReporter(this);
} catch (final AlreadyConnectedException e1) {
assert (null == this.reporter) : "Illegal state : previous reporter was still connected.";
}
// ���̃X���b�h�Ƀp�[�~�b�V������������悤�ɗv��
MetricsToolSecurityManager.getInstance().requestPluginPermission(this);
try {
this.execute();
} catch (final Throwable e) {
this.err.println(e);
}
if (null != this.reporter) {
// �i���̏I���C�x���g�𑗂�
// �v���O�C�����Ŋ��ɑ����Ă����牽�������ɕԂ��Ă���
this.reporter.reportProgressEnd();
this.reporter = null;
}
// ���̃X���b�h����p�[�~�b�V��������������悤�ɗv��
MetricsToolSecurityManager.getInstance().removePluginPermission(this);
}
|
diff --git a/maven-amps-plugin/src/main/java/com/atlassian/maven/plugins/amps/RunMojo.java b/maven-amps-plugin/src/main/java/com/atlassian/maven/plugins/amps/RunMojo.java
index af2f6441..3a9a595f 100644
--- a/maven-amps-plugin/src/main/java/com/atlassian/maven/plugins/amps/RunMojo.java
+++ b/maven-amps-plugin/src/main/java/com/atlassian/maven/plugins/amps/RunMojo.java
@@ -1,135 +1,135 @@
package com.atlassian.maven.plugins.amps;
import com.atlassian.maven.plugins.amps.product.ProductHandler;
import org.apache.commons.io.IOUtils;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;
import org.apache.maven.artifact.Artifact;
import org.jfrog.maven.annomojo.annotations.MojoExecute;
import org.jfrog.maven.annomojo.annotations.MojoGoal;
import org.jfrog.maven.annomojo.annotations.MojoParameter;
import org.jfrog.maven.annomojo.annotations.MojoRequiresDependencyResolution;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import static org.apache.commons.lang.StringUtils.isBlank;
/**
* Run the webapp
*/
@MojoGoal ("run")
@MojoExecute (phase = "package")
@MojoRequiresDependencyResolution
public class RunMojo extends AbstractProductHandlerMojo
{
private static final char CONTROL_C = (char) 27;
@MojoParameter (expression = "${wait}", defaultValue = "true")
private boolean wait;
/**
* Whether or not to write properties used by the plugin to amps.properties.
*/
@MojoParameter (expression = "${amps.properties}", required = true, defaultValue = "false")
protected boolean writePropertiesToFile;
/**
* Instance id to run. If provided, used to determine the product to run instead of just the product ID.
*/
@MojoParameter(expression = "${instanceId}")
protected String instanceId;
/**
* The properties actually used by the mojo when running
*/
protected final Map<String, String> properties = new HashMap<String, String>();
protected void doExecute() throws MojoExecutionException, MojoFailureException
{
final MavenGoals goals = getMavenGoals();
Product ctx;
- if (isBlank(instanceId))
+ if (!isBlank(instanceId))
{
ctx = getProductContexts(goals).get(instanceId);
if (ctx == null)
{
throw new MojoExecutionException("No product with instance ID '" + instanceId + "'");
}
}
else
{
ctx = getProductContexts(goals).get(getProductId());
}
ProductHandler product = createProductHandler(ctx.getId());
ctx.setInstallPlugin(shouldInstallPlugin());
int actualHttpPort = product.start(ctx);
getLog().info(ctx.getInstanceId() + " started successfully and available at http://localhost:" + actualHttpPort + ctx.getContextPath());
if (writePropertiesToFile)
{
properties.put("http.port", String.valueOf(actualHttpPort));
properties.put("context.path", ctx.getContextPath());
writePropertiesFile();
}
if (wait)
{
getLog().info("Type CTRL-C to exit");
try
{
while (System.in.read() != CONTROL_C)
{
}
}
catch (final IOException e)
{
// ignore
}
}
}
/**
* Only install a plugin if the installPlugin flag is true and the project is a jar
*/
private boolean shouldInstallPlugin()
{
Artifact artifact = getMavenContext().getProject().getArtifact();
return installPlugin &&
(artifact != null && !"pom".equalsIgnoreCase(artifact.getType()));
}
private void writePropertiesFile() throws MojoExecutionException
{
final Properties props = new Properties();
for (Map.Entry<String, String> entry : properties.entrySet())
{
props.setProperty(entry.getKey(), entry.getValue());
}
final File ampsProperties = new File(getMavenContext().getProject().getBuild().getDirectory(), "amps.properties");
OutputStream out = null;
try
{
out = new FileOutputStream(ampsProperties);
props.store(out, "");
}
catch (IOException e)
{
throw new MojoExecutionException("Error writing " + ampsProperties.getAbsolutePath(), e);
}
finally
{
IOUtils.closeQuietly(out);
}
}
}
| true | true | protected void doExecute() throws MojoExecutionException, MojoFailureException
{
final MavenGoals goals = getMavenGoals();
Product ctx;
if (isBlank(instanceId))
{
ctx = getProductContexts(goals).get(instanceId);
if (ctx == null)
{
throw new MojoExecutionException("No product with instance ID '" + instanceId + "'");
}
}
else
{
ctx = getProductContexts(goals).get(getProductId());
}
ProductHandler product = createProductHandler(ctx.getId());
ctx.setInstallPlugin(shouldInstallPlugin());
int actualHttpPort = product.start(ctx);
getLog().info(ctx.getInstanceId() + " started successfully and available at http://localhost:" + actualHttpPort + ctx.getContextPath());
if (writePropertiesToFile)
{
properties.put("http.port", String.valueOf(actualHttpPort));
properties.put("context.path", ctx.getContextPath());
writePropertiesFile();
}
if (wait)
{
getLog().info("Type CTRL-C to exit");
try
{
while (System.in.read() != CONTROL_C)
{
}
}
catch (final IOException e)
{
// ignore
}
}
}
| protected void doExecute() throws MojoExecutionException, MojoFailureException
{
final MavenGoals goals = getMavenGoals();
Product ctx;
if (!isBlank(instanceId))
{
ctx = getProductContexts(goals).get(instanceId);
if (ctx == null)
{
throw new MojoExecutionException("No product with instance ID '" + instanceId + "'");
}
}
else
{
ctx = getProductContexts(goals).get(getProductId());
}
ProductHandler product = createProductHandler(ctx.getId());
ctx.setInstallPlugin(shouldInstallPlugin());
int actualHttpPort = product.start(ctx);
getLog().info(ctx.getInstanceId() + " started successfully and available at http://localhost:" + actualHttpPort + ctx.getContextPath());
if (writePropertiesToFile)
{
properties.put("http.port", String.valueOf(actualHttpPort));
properties.put("context.path", ctx.getContextPath());
writePropertiesFile();
}
if (wait)
{
getLog().info("Type CTRL-C to exit");
try
{
while (System.in.read() != CONTROL_C)
{
}
}
catch (final IOException e)
{
// ignore
}
}
}
|
diff --git a/src/master/src/org/drftpd/vfs/DirectoryHandle.java b/src/master/src/org/drftpd/vfs/DirectoryHandle.java
index 7c248b23..f5234e8f 100644
--- a/src/master/src/org/drftpd/vfs/DirectoryHandle.java
+++ b/src/master/src/org/drftpd/vfs/DirectoryHandle.java
@@ -1,798 +1,809 @@
/*
* This file is part of DrFTPD, Distributed FTP Daemon.
*
* DrFTPD is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* DrFTPD is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with DrFTPD; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package org.drftpd.vfs;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import org.drftpd.GlobalContext;
import org.drftpd.exceptions.FileExistsException;
import org.drftpd.exceptions.ObjectNotFoundException;
import org.drftpd.exceptions.SlaveUnavailableException;
import org.drftpd.master.RemoteSlave;
import org.drftpd.slave.LightRemoteInode;
import org.drftpd.usermanager.User;
import se.mog.io.PermissionDeniedException;
/**
* @author zubov
* @version $Id$
*/
public class DirectoryHandle extends InodeHandle implements
DirectoryHandleInterface {
public DirectoryHandle(String path) {
super(path);
}
/**
* @param reason
* @throws FileNotFoundException if this Directory does not exist
*/
public void abortAllTransfers(String reason) throws FileNotFoundException {
for (FileHandle file : getFilesUnchecked()) {
try {
file.abortTransfers(reason);
} catch (FileNotFoundException e) {
}
}
}
/**
* Returns a DirectoryHandle for a possibly non-existant directory in this path
* No verification to its existence is made
* @param name
* @return
*/
public DirectoryHandle getNonExistentDirectoryHandle(String name) {
if (name.startsWith(VirtualFileSystem.separator)) {
// absolute path, easy to handle
return new DirectoryHandle(name);
}
// path must be relative
return new DirectoryHandle(getPath() + VirtualFileSystem.separator + name);
}
/**
* Returns a LinkHandle for a possibly non-existant directory in this path
* No verification to its existence is made
* @param name
* @return
*/
public LinkHandle getNonExistentLinkHandle(String name) {
return new LinkHandle(getPath() + VirtualFileSystem.separator + name);
}
/**
* @see org.drftpd.vfs.InodleHandle#getInode()
*/
@Override
public VirtualFileSystemDirectory getInode()
throws FileNotFoundException {
VirtualFileSystemInode inode = super.getInode();
if (inode instanceof VirtualFileSystemDirectory) {
return (VirtualFileSystemDirectory) inode;
}
throw new ClassCastException(
"DirectoryHandle object pointing to Inode:" + inode);
}
/**
* @return all InodeHandles inside this dir.
* @throws FileNotFoundException
*/
public Set<InodeHandle> getInodeHandles(User user) throws FileNotFoundException {
Set<InodeHandle> inodes = getInodeHandlesUnchecked();
for (Iterator<InodeHandle> iter = inodes.iterator(); iter.hasNext();) {
InodeHandle inode = iter.next();
try {
checkHiddenPath(inode, user);
} catch (FileNotFoundException e) {
// file is hidden or a race just happened.
iter.remove();
}
}
return inodes;
}
/**
* @return all InodeHandles inside this dir.
* @throws FileNotFoundException
*/
public Set<InodeHandle> getInodeHandlesUnchecked() throws FileNotFoundException {
return getInode().getInodes();
}
public ArrayList<FileHandle> getAllFilesRecursiveUnchecked() {
ArrayList<FileHandle> files = new ArrayList<FileHandle>();
try {
for (InodeHandle inode : getInodeHandlesUnchecked()) {
if (inode.isFile()) {
files.add((FileHandle) inode);
} else if (inode.isDirectory()) {
files.addAll(getAllFilesRecursiveUnchecked());
}
}
} catch (FileNotFoundException e) {
// oh well, we just won't have any files to add
}
return files;
}
/**
* @return a set containing only the files of this dir.
* (no links or directories included.)
* @throws FileNotFoundException
*/
public Set<FileHandle> getFiles(User user) throws FileNotFoundException {
return getFilesUnchecked(getInodeHandles(user));
}
public Set<FileHandle> getFilesUnchecked() throws FileNotFoundException {
return getFilesUnchecked(getInodeHandlesUnchecked());
}
private Set<FileHandle> getFilesUnchecked(Set<InodeHandle> inodes) throws FileNotFoundException {
Set<FileHandle> set = new HashSet<FileHandle>();
for (InodeHandle handle : getInode().getInodes()) {
if (handle instanceof FileHandle) {
set.add((FileHandle) handle);
}
}
return (Set<FileHandle>) set;
}
/**.
* This method *does* check for hiddens paths.
* @return a set containing only the directories of this dir. (no links or files included.)
* @throws FileNotFoundException
*/
public Set<DirectoryHandle> getDirectories(User user) throws FileNotFoundException {
return getDirectoriesUnchecked(getInodeHandles(user));
}
/**
* This method does not check for hiddens paths.
* @return a set containing only the directories of this dir. (no links or files included.)
* @throws FileNotFoundException
*/
public Set<DirectoryHandle> getDirectoriesUnchecked() throws FileNotFoundException {
return getDirectoriesUnchecked(getInodeHandlesUnchecked());
}
/**
* This method iterates through the given Set, removing non-Directory objects.
* @return a set containing only the directories of this dir. (no links or files included.)
* @throws FileNotFoundException
*/
private Set<DirectoryHandle> getDirectoriesUnchecked(Set<InodeHandle> inodes)
throws FileNotFoundException {
Set<DirectoryHandle> set = new HashSet<DirectoryHandle>();
for (InodeHandle handle : inodes) {
if (handle instanceof DirectoryHandle) {
set.add((DirectoryHandle) handle);
}
}
return (Set<DirectoryHandle>) set;
}
/**
* @return a set containing only the links of this dir.
* (no directories or files included.)
* @throws FileNotFoundException
*/
public Set<LinkHandle> getLinks(User user) throws FileNotFoundException {
return getLinksUnchecked(getInodeHandles(user));
}
public Set<LinkHandle> getLinksUnchecked() throws FileNotFoundException {
return getLinksUnchecked(getInodeHandlesUnchecked());
}
private Set<LinkHandle> getLinksUnchecked(Set<InodeHandle> inodes) throws FileNotFoundException {
Set<LinkHandle> set = new HashSet<LinkHandle>();
for (Iterator<InodeHandle> iter = inodes.iterator(); iter
.hasNext();) {
InodeHandle handle = iter.next();
if (handle instanceof LinkHandle) {
set.add((LinkHandle) handle);
}
}
return (Set<LinkHandle>) set;
}
/**
* @return true if the dir has offline files.
* @throws FileNotFoundException
*/
public boolean hasOfflineFiles() throws FileNotFoundException {
return getOfflineFiles().size() != 0;
}
/**
* @return a set containing only the offline files of this dir.
* @throws FileNotFoundException
*/
private Set<FileHandle> getOfflineFiles() throws FileNotFoundException {
Set<FileHandle> allFiles = getFilesUnchecked();
Set<FileHandle> offlineFiles = new HashSet<FileHandle>(allFiles.size());
for (FileHandle file : allFiles) {
if (!file.isAvailable())
offlineFiles.add(file);
}
return offlineFiles;
}
/**
* @param name
* @throws FileNotFoundException
*/
public InodeHandle getInodeHandle(String name, User user) throws FileNotFoundException {
InodeHandle inode = getInodeHandleUnchecked(name);
checkHiddenPath(inode, user);
return inode;
}
public InodeHandle getInodeHandleUnchecked(String name) throws FileNotFoundException {
VirtualFileSystemInode inode = getInode().getInodeByName(name);
if (inode.isDirectory()) {
return new DirectoryHandle(inode.getPath());
} else if (inode.isFile()) {
return new FileHandle(inode.getPath());
} else if (inode.isLink()) {
return new LinkHandle(inode.getPath());
}
throw new IllegalStateException(
"Not a directory, file, or link -- punt");
}
public DirectoryHandle getDirectory(String name, User user)
throws FileNotFoundException, ObjectNotValidException {
DirectoryHandle dir = getDirectoryUnchecked(name);
checkHiddenPath(dir, user);
return dir;
}
public DirectoryHandle getDirectoryUnchecked(String name)
throws FileNotFoundException, ObjectNotValidException {
if (name.equals(VirtualFileSystem.separator)) {
return new DirectoryHandle("/");
}
logger.debug("getDirectory(" + name + ")");
if (name.equals("..")) {
return getParent();
} else if (name.startsWith("../")) {
// strip off the ../
return getParent().getDirectoryUnchecked(name.substring(3));
} else if (name.equals(".")) {
return this;
} else if (name.startsWith("./")) {
return getDirectoryUnchecked(name.substring(2));
}
InodeHandle handle = getInodeHandleUnchecked(name);
if (handle.isDirectory()) {
return (DirectoryHandle) handle;
}
if (handle.isLink()) {
return ((LinkHandle) handle).getTargetDirectoryUnchecked();
}
throw new ObjectNotValidException(name + " is not a directory");
}
public FileHandle getFile(String name, User user) throws FileNotFoundException, ObjectNotValidException {
FileHandle file = getFileUnchecked(name);
checkHiddenPath(file.getParent(), user);
return file;
}
public FileHandle getFileUnchecked(String name) throws FileNotFoundException,
ObjectNotValidException {
InodeHandle handle = getInodeHandleUnchecked(name);
if (handle.isFile()) {
return (FileHandle) handle;
} else if (handle.isLink()) {
LinkHandle link = (LinkHandle) handle;
return link.getTargetFileUnchecked();
}
throw new ObjectNotValidException(name + " is not a file");
}
public LinkHandle getLink(String name, User user) throws FileNotFoundException,
ObjectNotValidException {
LinkHandle link = getLinkUnchecked(name);
checkHiddenPath(link.getTargetInode(user), user);
return link;
}
public LinkHandle getLinkUnchecked(String name) throws FileNotFoundException,
ObjectNotValidException {
InodeHandle handle = getInodeHandleUnchecked(name);
if (handle.isLink()) {
return (LinkHandle) handle;
}
throw new ObjectNotValidException(name + " is not a link");
}
private void createRemergedFile(LightRemoteInode lrf, RemoteSlave rslave,
boolean collision) throws IOException, SlaveUnavailableException {
String name = lrf.getName();
if (collision) {
name = lrf.getName() + ".collision." + rslave.getName();
rslave.simpleRename(getPath() + lrf.getPath(), getPath(), name);
}
FileHandle newFile = createFileUnchecked(name, "drftpd", "drftpd", rslave);
newFile.setLastModified(lrf.lastModified());
newFile.setSize(lrf.length());
//newFile.setCheckSum(rslave.getCheckSumForPath(newFile.getPath()));
// TODO Implement a Checksum queue on remerge
newFile.setCheckSum(0);
}
public void remerge(List<LightRemoteInode> files, RemoteSlave rslave)
throws IOException, SlaveUnavailableException {
Iterator<LightRemoteInode> sourceIter = files.iterator();
// source comes pre-sorted from the slave
List<InodeHandle> destinationList = null;
try {
destinationList = new ArrayList<InodeHandle>(getInodeHandlesUnchecked());
} catch (FileNotFoundException e) {
logger.debug("FileNotFoundException during remerge", e);
// create directory for merging
getParent().createDirectoryRecursive(getName());
// lets try this again, this time, if it doesn't work, we throw an
// IOException up the chain
destinationList = new ArrayList<InodeHandle>(getInodeHandlesUnchecked());
}
Collections.sort(destinationList,
VirtualFileSystem.INODE_HANDLE_CASE_INSENSITIVE_COMPARATOR);
Iterator<InodeHandle> destinationIter = destinationList.iterator();
LightRemoteInode source = null;
InodeHandle destination = null;
if (sourceIter.hasNext()) {
source = sourceIter.next();
}
if (destinationIter.hasNext()) {
destination = destinationIter.next();
}
while (true) {
-/* logger.debug("Starting remerge() loop, [destination="
+ /*logger.debug("loop, [destination="
+ (destination == null ? "null" : destination.getName())
+ "][source="
- + (source == null ? "null" : source.getName()) + "]");*/
+ + (source == null ? "null" : source.getName()) + "]");
+ */
// source & destination are set at the "next to process" one OR are
// null and at the end of that list
// case1 : source list is out, remove slave from all remaining
// files/directories
if (source == null) {
while (destination != null) {
// can removeSlave()'s from all types of Inodes, no type
// checking needed
destination.removeSlave(rslave);
if (destinationIter.hasNext()) {
destination = destinationIter.next();
} else {
destination = null;
}
}
// all done, both lists are empty
return;
}
// case2: destination list is out, add files
if (destination == null) {
while (source != null) {
if (source.isFile()) {
createRemergedFile(source, rslave, false);
} else {
throw new IOException(
source
+ ".isDirectory() -- this shouldn't happen, this directory should already be created through a previous remerge process");
}
if (sourceIter.hasNext()) {
source = sourceIter.next();
} else {
source = null;
}
}
// all done, both lists are empty
return;
}
// both source and destination are non-null
// we don't know which one is first alphabetically
int compare = source.getName().compareToIgnoreCase(
destination.getName());
// compare is < 0, source comes before destination
// compare is > 0, source comes after destination
// compare is == 0, they have the same name
if (compare < 0) {
// add the file
createRemergedFile(source, rslave, false);
// advance one runner
if (sourceIter.hasNext()) {
source = sourceIter.next();
} else {
source = null;
}
} else if (compare > 0) {
// remove the slave
destination.removeSlave(rslave);
// advance one runner
if (destinationIter.hasNext()) {
destination = destinationIter.next();
} else {
destination = null;
}
} else if (compare == 0) {
if (destination.isLink()) {
// this is bad, links don't exist on slaves
// name collision
if (source.isFile()) {
createRemergedFile(source, rslave, true);
logger.warn("In remerging " + rslave.getName()
+ ", a file on the slave (" + getPath()
+ VirtualFileSystem.separator
+ source.getName()
+ ") collided with a link on the master");
// set crc now?
} else { // source.isDirectory()
logger.warn("In remerging " + rslave.getName()
+ ", a directory on the slave (" + getPath()
+ VirtualFileSystem.separator
+ source.getName()
+ ") collided with a link on the master");
}
} else if (source.isFile() && destination.isFile()) {
// both files
FileHandle destinationFile = (FileHandle) destination;
/* long sourceCRC = rslave.getCheckSumForPath(getPath()
+ VirtualFileSystem.separator + source.getName());
long destinationCRC;
try {
destinationCRC = destinationFile.getCheckSum();
} catch (NoAvailableSlaveException e) {
destinationCRC = 0L;
}
*/ if (source.length() != destinationFile.getSize()) {
// || (sourceCRC != destinationCRC && destinationCRC != 0L)) {
// handle collision
- createRemergedFile(source, rslave, true);
- logger.warn("In remerging " + rslave.getName()
- + ", a file on the slave (" + getPath()
- + VirtualFileSystem.separator
- + source.getName()
- + ") collided with a file on the master");
- // set crc now?
+ Set<RemoteSlave> rslaves = destinationFile.getSlaves();
+ if (rslaves.contains(rslave) && rslaves.size() == 1) {
+ // size of the file has changed, but since this is the only slave with the file, just change the size
+ destinationFile.setSize(source.length());
+ } else {
+ if (rslaves.contains(rslave)) {
+ // the master thought the slave had the file, it's not the same size anymore, remove it
+ destinationFile.removeSlave(rslave);
+ }
+ createRemergedFile(source, rslave, true);
+ logger.warn("In remerging " + rslave.getName()
+ + ", a file on the slave (" + getPath()
+ + VirtualFileSystem.separator
+ + source.getName()
+ + ") collided with a file on the master");
+ }
} else {
destinationFile.addSlave(rslave);
}
} else if (source.isDirectory() && destination.isDirectory()) {
// this is good, do nothing other than take up this case
+ logger.debug("In remerge, directories were equal!");
} else {
// we have a directory/name collission, let's find which one
// :)
if (source.isDirectory()) { // & destination.isFile()
// we don't care about directories on the slaves, let's
// just skip it
logger.warn("In remerging " + rslave.getName()
+ ", a directory on the slave (" + getPath()
+ VirtualFileSystem.separator
+ source.getName()
+ ") collided with a file on the master");
} else {
// source.isFile() && destination.isDirectory()
// handle collision
createRemergedFile(source, rslave, true);
// set crc now?
}
}
// advance both runners, they were equal
if (destinationIter.hasNext()) {
destination = destinationIter.next();
} else {
destination = null;
}
if (sourceIter.hasNext()) {
source = sourceIter.next();
} else {
source = null;
}
}
}
}
/**
* Shortcut to create "owner-less" directories.
*/
public DirectoryHandle createDirectorySystem(String name) throws FileExistsException, FileNotFoundException {
return createDirectoryUnchecked(name, "drftpd", "drftpd");
}
/**
* Given a DirectoryHandle, it makes sure that this directory and all of its parent(s) exist
* @param name
* @throws FileExistsException
* @throws FileNotFoundException
*/
public void createDirectoryRecursive(String name)
throws FileExistsException, FileNotFoundException {
DirectoryHandle dir = null;
try {
dir = createDirectorySystem(name);
} catch (FileNotFoundException e) {
getParent().createDirectoryRecursive(getName());
} catch (FileExistsException e) {
throw new FileExistsException("Object already exists -- "
+ getPath() + VirtualFileSystem.separator + name);
}
if (dir == null) {
dir = createDirectorySystem(name);
}
logger.debug("Created directory " + dir);
}
/**
* Creates a Directory object in the FileSystem with this directory as its parent.<br>
* This method does not check for permissions, so be careful while using it.<br>
* @see For a checked way of creating dirs {@link #createFile(User, String, RemoteSlave)};
* @param user
* @param group
* @return the created directory.
* @throws FileNotFoundException
* @throws FileExistsException
*/
public DirectoryHandle createDirectoryUnchecked(String name, String user,
String group) throws FileExistsException, FileNotFoundException {
getInode().createDirectory(name, user, group);
try {
return getDirectoryUnchecked(name);
} catch (FileNotFoundException e) {
throw new RuntimeException("Something really funky happened, we just created it", e);
} catch (ObjectNotValidException e) {
throw new RuntimeException("Something really funky happened, we just created it", e);
}
}
/**
* Attempts to create a Directory in the FileSystem with this directory as parent.
* @see For an unchecked way of creating dirs: {@link #createDirectoryUnchecked(String, String, String)}
* @param user
* @param name
* @return the created directory.
* @throws PermissionDeniedException if the given user is not allowed to create dirs.
* @throws FileExistsException
* @throws FileNotFoundException
*/
public DirectoryHandle createDirectory(User user, String name)
throws PermissionDeniedException, FileExistsException, FileNotFoundException {
if (user == null) {
throw new PermissionDeniedException("User cannot be null");
}
DirectoryHandle newDir = getNonExistentDirectoryHandle(name);
checkHiddenPath(newDir, user);
if (!getVFSPermissions().checkPathPermission("makedir", user, newDir)) {
throw new PermissionDeniedException("You are not allowed to create a directory at "+ newDir.getParent());
}
return createDirectoryUnchecked(name, user.getName(), user.getGroup());
}
/**
* Creates a File object in the FileSystem with this directory as its parent.<br>
* This method does not check for permissions, so be careful while using it.<br>
* @see For unchecked creating of files {@link #createFileUnchecked(String, String, String, RemoteSlave)}
* @param name
* @param user
* @param group
* @param initialSlave
* @return the created file.
* @throws FileExistsException
* @throws FileNotFoundException
*/
public FileHandle createFileUnchecked(String name, String user, String group,
RemoteSlave initialSlave) throws FileExistsException,
FileNotFoundException {
getInode().createFile(name, user, group, initialSlave.getName());
try {
return getFileUnchecked(name);
} catch (FileNotFoundException e) {
throw new RuntimeException("Something really funky happened, we just created it", e);
} catch (ObjectNotValidException e) {
throw new RuntimeException("Something really funky happened, we just created it", e);
}
}
/**
* Attempts to create a File in the FileSystem having this directory as parent.
* @param user
* @param name
* @param initialSlave
* @return
* @throws PermissionDeniedException if the user is not allowed to create a file in this dir.
* @throws FileExistsException
* @throws FileNotFoundException
*/
public FileHandle createFile(User user, String name, RemoteSlave initialSlave)
throws PermissionDeniedException, FileExistsException, FileNotFoundException {
if (user == null) {
throw new PermissionDeniedException("User cannot be null");
}
checkHiddenPath(this, user);
if (!getVFSPermissions().checkPathPermission("upload", user, this)) {
throw new PermissionDeniedException("You are not allowed to upload to "+ getParent());
}
return createFileUnchecked(name, user.getName(), user.getGroup(), initialSlave);
}
/**
* Creates a Link object in the FileSystem with this directory as its parent
*/
public LinkHandle createLinkUnchecked(String name, String target, String user,
String group) throws FileExistsException, FileNotFoundException {
getInode().createLink(name, target, user, group);
try {
return getLinkUnchecked(name);
} catch (FileNotFoundException e) {
throw new RuntimeException("Something really funky happened, we just created it", e);
} catch (ObjectNotValidException e) {
throw new RuntimeException("Something really funky happened, we just created it", e);
}
}
public LinkHandle createLink(User user, String name, String target)
throws FileExistsException, FileNotFoundException, PermissionDeniedException {
if (user == null) {
throw new PermissionDeniedException("User cannot be null");
}
// check if this dir is hidden.
checkHiddenPath(this, user);
InodeHandle inode = getInodeHandle(target, user);
// check if the target is hidden
checkHiddenPath(inode, user);
if (inode.isLink()) {
throw new PermissionDeniedException("Impossible to point a link to a link");
}
return createLinkUnchecked(name, target, user.getName(), user.getGroup());
}
public boolean isRoot() {
return equals(GlobalContext.getGlobalContext().getRoot());
}
/**
* For use during PRET
* Returns a FileHandle for a possibly non-existant directory in this path
* No verification to its existence is made
* @param name
* @return
*/
public FileHandle getNonExistentFileHandle(String argument) {
if (argument.startsWith(VirtualFileSystem.separator)) {
// absolute path, easy to handle
return new FileHandle(argument);
}
// path must be relative
return new FileHandle(getPath() + VirtualFileSystem.separator
+ argument);
}
public void removeSlave(RemoteSlave rslave) throws FileNotFoundException {
boolean empty = isEmptyUnchecked();
for (InodeHandle inode : getInodeHandlesUnchecked()) {
inode.removeSlave(rslave);
}
if (!empty && isEmptyUnchecked()) { // if it wasn't empty before, but is now, delete it
deleteUnchecked();
}
}
public boolean isEmptyUnchecked() throws FileNotFoundException {
return getInodeHandlesUnchecked().size() == 0;
}
public boolean isEmpty(User user) throws FileNotFoundException, PermissionDeniedException {
// let's fetch the list of existent files inside this dir
// if the dir does not exist, FileNotFoundException is thrown
// if the dir exists the operation continues smoothly.
getInode();
try {
checkHiddenPath(this, user);
} catch (FileNotFoundException e) {
// either a race condition happened or the dir is hidden
// cuz we just checked and the dir was here.
throw new PermissionDeniedException("Unable to check if the directory is empty.");
}
return isEmptyUnchecked();
}
@Override
public boolean isDirectory() {
return true;
}
@Override
public boolean isFile() {
return false;
}
@Override
public boolean isLink() {
return false;
}
@Override
public void deleteUnchecked() throws FileNotFoundException {
abortAllTransfers("Directory " + getPath() + " is being deleted");
GlobalContext.getGlobalContext().getSlaveManager().deleteOnAllSlaves(this);
super.deleteUnchecked();
}
public long validateSizeRecursive() throws FileNotFoundException {
Set<InodeHandle> inodes = getInodeHandlesUnchecked();
long newSize = 0;
long oldSize = getSize();
for (InodeHandle inode : inodes) {
if (inode.isDirectory()) {
((DirectoryHandle) inode).validateSizeRecursive();
}
newSize += inode.getSize();
}
getInode().setSize(newSize);
return oldSize - newSize;
}
}
| false | true | public void remerge(List<LightRemoteInode> files, RemoteSlave rslave)
throws IOException, SlaveUnavailableException {
Iterator<LightRemoteInode> sourceIter = files.iterator();
// source comes pre-sorted from the slave
List<InodeHandle> destinationList = null;
try {
destinationList = new ArrayList<InodeHandle>(getInodeHandlesUnchecked());
} catch (FileNotFoundException e) {
logger.debug("FileNotFoundException during remerge", e);
// create directory for merging
getParent().createDirectoryRecursive(getName());
// lets try this again, this time, if it doesn't work, we throw an
// IOException up the chain
destinationList = new ArrayList<InodeHandle>(getInodeHandlesUnchecked());
}
Collections.sort(destinationList,
VirtualFileSystem.INODE_HANDLE_CASE_INSENSITIVE_COMPARATOR);
Iterator<InodeHandle> destinationIter = destinationList.iterator();
LightRemoteInode source = null;
InodeHandle destination = null;
if (sourceIter.hasNext()) {
source = sourceIter.next();
}
if (destinationIter.hasNext()) {
destination = destinationIter.next();
}
while (true) {
/* logger.debug("Starting remerge() loop, [destination="
+ (destination == null ? "null" : destination.getName())
+ "][source="
+ (source == null ? "null" : source.getName()) + "]");*/
// source & destination are set at the "next to process" one OR are
// null and at the end of that list
// case1 : source list is out, remove slave from all remaining
// files/directories
if (source == null) {
while (destination != null) {
// can removeSlave()'s from all types of Inodes, no type
// checking needed
destination.removeSlave(rslave);
if (destinationIter.hasNext()) {
destination = destinationIter.next();
} else {
destination = null;
}
}
// all done, both lists are empty
return;
}
// case2: destination list is out, add files
if (destination == null) {
while (source != null) {
if (source.isFile()) {
createRemergedFile(source, rslave, false);
} else {
throw new IOException(
source
+ ".isDirectory() -- this shouldn't happen, this directory should already be created through a previous remerge process");
}
if (sourceIter.hasNext()) {
source = sourceIter.next();
} else {
source = null;
}
}
// all done, both lists are empty
return;
}
// both source and destination are non-null
// we don't know which one is first alphabetically
int compare = source.getName().compareToIgnoreCase(
destination.getName());
// compare is < 0, source comes before destination
// compare is > 0, source comes after destination
// compare is == 0, they have the same name
if (compare < 0) {
// add the file
createRemergedFile(source, rslave, false);
// advance one runner
if (sourceIter.hasNext()) {
source = sourceIter.next();
} else {
source = null;
}
} else if (compare > 0) {
// remove the slave
destination.removeSlave(rslave);
// advance one runner
if (destinationIter.hasNext()) {
destination = destinationIter.next();
} else {
destination = null;
}
} else if (compare == 0) {
if (destination.isLink()) {
// this is bad, links don't exist on slaves
// name collision
if (source.isFile()) {
createRemergedFile(source, rslave, true);
logger.warn("In remerging " + rslave.getName()
+ ", a file on the slave (" + getPath()
+ VirtualFileSystem.separator
+ source.getName()
+ ") collided with a link on the master");
// set crc now?
} else { // source.isDirectory()
logger.warn("In remerging " + rslave.getName()
+ ", a directory on the slave (" + getPath()
+ VirtualFileSystem.separator
+ source.getName()
+ ") collided with a link on the master");
}
} else if (source.isFile() && destination.isFile()) {
// both files
FileHandle destinationFile = (FileHandle) destination;
/* long sourceCRC = rslave.getCheckSumForPath(getPath()
+ VirtualFileSystem.separator + source.getName());
long destinationCRC;
try {
destinationCRC = destinationFile.getCheckSum();
} catch (NoAvailableSlaveException e) {
destinationCRC = 0L;
}
*/ if (source.length() != destinationFile.getSize()) {
// || (sourceCRC != destinationCRC && destinationCRC != 0L)) {
// handle collision
createRemergedFile(source, rslave, true);
logger.warn("In remerging " + rslave.getName()
+ ", a file on the slave (" + getPath()
+ VirtualFileSystem.separator
+ source.getName()
+ ") collided with a file on the master");
// set crc now?
} else {
destinationFile.addSlave(rslave);
}
} else if (source.isDirectory() && destination.isDirectory()) {
// this is good, do nothing other than take up this case
} else {
// we have a directory/name collission, let's find which one
// :)
if (source.isDirectory()) { // & destination.isFile()
// we don't care about directories on the slaves, let's
// just skip it
logger.warn("In remerging " + rslave.getName()
+ ", a directory on the slave (" + getPath()
+ VirtualFileSystem.separator
+ source.getName()
+ ") collided with a file on the master");
} else {
// source.isFile() && destination.isDirectory()
// handle collision
createRemergedFile(source, rslave, true);
// set crc now?
}
}
// advance both runners, they were equal
if (destinationIter.hasNext()) {
destination = destinationIter.next();
} else {
destination = null;
}
if (sourceIter.hasNext()) {
source = sourceIter.next();
} else {
source = null;
}
}
}
| public void remerge(List<LightRemoteInode> files, RemoteSlave rslave)
throws IOException, SlaveUnavailableException {
Iterator<LightRemoteInode> sourceIter = files.iterator();
// source comes pre-sorted from the slave
List<InodeHandle> destinationList = null;
try {
destinationList = new ArrayList<InodeHandle>(getInodeHandlesUnchecked());
} catch (FileNotFoundException e) {
logger.debug("FileNotFoundException during remerge", e);
// create directory for merging
getParent().createDirectoryRecursive(getName());
// lets try this again, this time, if it doesn't work, we throw an
// IOException up the chain
destinationList = new ArrayList<InodeHandle>(getInodeHandlesUnchecked());
}
Collections.sort(destinationList,
VirtualFileSystem.INODE_HANDLE_CASE_INSENSITIVE_COMPARATOR);
Iterator<InodeHandle> destinationIter = destinationList.iterator();
LightRemoteInode source = null;
InodeHandle destination = null;
if (sourceIter.hasNext()) {
source = sourceIter.next();
}
if (destinationIter.hasNext()) {
destination = destinationIter.next();
}
while (true) {
/*logger.debug("loop, [destination="
+ (destination == null ? "null" : destination.getName())
+ "][source="
+ (source == null ? "null" : source.getName()) + "]");
*/
// source & destination are set at the "next to process" one OR are
// null and at the end of that list
// case1 : source list is out, remove slave from all remaining
// files/directories
if (source == null) {
while (destination != null) {
// can removeSlave()'s from all types of Inodes, no type
// checking needed
destination.removeSlave(rslave);
if (destinationIter.hasNext()) {
destination = destinationIter.next();
} else {
destination = null;
}
}
// all done, both lists are empty
return;
}
// case2: destination list is out, add files
if (destination == null) {
while (source != null) {
if (source.isFile()) {
createRemergedFile(source, rslave, false);
} else {
throw new IOException(
source
+ ".isDirectory() -- this shouldn't happen, this directory should already be created through a previous remerge process");
}
if (sourceIter.hasNext()) {
source = sourceIter.next();
} else {
source = null;
}
}
// all done, both lists are empty
return;
}
// both source and destination are non-null
// we don't know which one is first alphabetically
int compare = source.getName().compareToIgnoreCase(
destination.getName());
// compare is < 0, source comes before destination
// compare is > 0, source comes after destination
// compare is == 0, they have the same name
if (compare < 0) {
// add the file
createRemergedFile(source, rslave, false);
// advance one runner
if (sourceIter.hasNext()) {
source = sourceIter.next();
} else {
source = null;
}
} else if (compare > 0) {
// remove the slave
destination.removeSlave(rslave);
// advance one runner
if (destinationIter.hasNext()) {
destination = destinationIter.next();
} else {
destination = null;
}
} else if (compare == 0) {
if (destination.isLink()) {
// this is bad, links don't exist on slaves
// name collision
if (source.isFile()) {
createRemergedFile(source, rslave, true);
logger.warn("In remerging " + rslave.getName()
+ ", a file on the slave (" + getPath()
+ VirtualFileSystem.separator
+ source.getName()
+ ") collided with a link on the master");
// set crc now?
} else { // source.isDirectory()
logger.warn("In remerging " + rslave.getName()
+ ", a directory on the slave (" + getPath()
+ VirtualFileSystem.separator
+ source.getName()
+ ") collided with a link on the master");
}
} else if (source.isFile() && destination.isFile()) {
// both files
FileHandle destinationFile = (FileHandle) destination;
/* long sourceCRC = rslave.getCheckSumForPath(getPath()
+ VirtualFileSystem.separator + source.getName());
long destinationCRC;
try {
destinationCRC = destinationFile.getCheckSum();
} catch (NoAvailableSlaveException e) {
destinationCRC = 0L;
}
*/ if (source.length() != destinationFile.getSize()) {
// || (sourceCRC != destinationCRC && destinationCRC != 0L)) {
// handle collision
Set<RemoteSlave> rslaves = destinationFile.getSlaves();
if (rslaves.contains(rslave) && rslaves.size() == 1) {
// size of the file has changed, but since this is the only slave with the file, just change the size
destinationFile.setSize(source.length());
} else {
if (rslaves.contains(rslave)) {
// the master thought the slave had the file, it's not the same size anymore, remove it
destinationFile.removeSlave(rslave);
}
createRemergedFile(source, rslave, true);
logger.warn("In remerging " + rslave.getName()
+ ", a file on the slave (" + getPath()
+ VirtualFileSystem.separator
+ source.getName()
+ ") collided with a file on the master");
}
} else {
destinationFile.addSlave(rslave);
}
} else if (source.isDirectory() && destination.isDirectory()) {
// this is good, do nothing other than take up this case
logger.debug("In remerge, directories were equal!");
} else {
// we have a directory/name collission, let's find which one
// :)
if (source.isDirectory()) { // & destination.isFile()
// we don't care about directories on the slaves, let's
// just skip it
logger.warn("In remerging " + rslave.getName()
+ ", a directory on the slave (" + getPath()
+ VirtualFileSystem.separator
+ source.getName()
+ ") collided with a file on the master");
} else {
// source.isFile() && destination.isDirectory()
// handle collision
createRemergedFile(source, rslave, true);
// set crc now?
}
}
// advance both runners, they were equal
if (destinationIter.hasNext()) {
destination = destinationIter.next();
} else {
destination = null;
}
if (sourceIter.hasNext()) {
source = sourceIter.next();
} else {
source = null;
}
}
}
|
diff --git a/spring-integration-ip/src/test/java/org/springframework/integration/ip/tcp/TcpOutboundGatewayTests.java b/spring-integration-ip/src/test/java/org/springframework/integration/ip/tcp/TcpOutboundGatewayTests.java
index 0058d9dba3..cf5e64a666 100644
--- a/spring-integration-ip/src/test/java/org/springframework/integration/ip/tcp/TcpOutboundGatewayTests.java
+++ b/spring-integration-ip/src/test/java/org/springframework/integration/ip/tcp/TcpOutboundGatewayTests.java
@@ -1,241 +1,242 @@
/*
* Copyright 2002-2010 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.integration.ip.tcp;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.concurrent.Callable;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.atomic.AtomicBoolean;
import javax.net.ServerSocketFactory;
import org.junit.Test;
import org.springframework.commons.serializer.java.JavaStreamingConverter;
import org.springframework.integration.Message;
import org.springframework.integration.MessageTimeoutException;
import org.springframework.integration.channel.QueueChannel;
import org.springframework.integration.core.MessageBuilder;
import org.springframework.integration.ip.tcp.connection.AbstractConnectionFactory;
import org.springframework.integration.ip.tcp.connection.TcpNetClientConnectionFactory;
import org.springframework.integration.ip.util.SocketUtils;
/**
* @author Gary Russell
* @since 2.0
*
*/
public class TcpOutboundGatewayTests {
@Test
public void testGoodNetSingle() {
final int port = SocketUtils.findAvailableServerSocket();
AbstractConnectionFactory ccf = new TcpNetClientConnectionFactory("localhost", port);
final CountDownLatch latch = new CountDownLatch(1);
final AtomicBoolean done = new AtomicBoolean();
Executors.newSingleThreadExecutor().execute(new Runnable() {
public void run() {
try {
ServerSocket server = ServerSocketFactory.getDefault().createServerSocket(port, 100);
latch.countDown();
int i = 0;
while (true) {
Socket socket = server.accept();
ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());
Object in = ois.readObject();
ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream());
oos.writeObject("Reply" + (i++));
}
} catch (Exception e) {
if (!done.get()) {
e.printStackTrace();
}
}
}
});
JavaStreamingConverter converter = new JavaStreamingConverter();
ccf.setInputConverter(converter);
ccf.setOutputConverter(converter);
ccf.setSoTimeout(10000);
ccf.setSingleUse(true);
ccf.setPoolSize(10);
ccf.start();
TcpOutboundGateway gateway = new TcpOutboundGateway();
gateway.setConnectionFactory(ccf);
QueueChannel replyChannel = new QueueChannel();
gateway.setRequiresReply(true);
gateway.setOutputChannel(replyChannel);
gateway.setReplyTimeout(60000);
gateway.setRequestTimeout(60000);
for (int i = 100; i < 200; i++) {
gateway.handleMessage(MessageBuilder.withPayload("Test" + i).build());
}
Set<String> replies = new HashSet<String>();
for (int i = 100; i < 200; i++) {
Message<?> m = replyChannel.receive(10000);
assertNotNull(m);
replies.add((String) m.getPayload());
}
for (int i = 0; i < 100; i++) {
assertTrue(replies.remove("Reply" + i));
}
}
@Test
public void testGoodNetMultiplex() {
final int port = SocketUtils.findAvailableServerSocket();
final CountDownLatch latch = new CountDownLatch(1);
final AtomicBoolean done = new AtomicBoolean();
Executors.newSingleThreadExecutor().execute(new Runnable() {
public void run() {
try {
ServerSocket server = ServerSocketFactory.getDefault().createServerSocket(port, 10);
latch.countDown();
int i = 0;
Socket socket = server.accept();
while (true) {
ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());
ois.readObject();
ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream());
oos.writeObject("Reply" + (i++));
}
} catch (Exception e) {
if (!done.get()) {
e.printStackTrace();
}
}
}
});
AbstractConnectionFactory ccf = new TcpNetClientConnectionFactory("localhost", port);
JavaStreamingConverter converter = new JavaStreamingConverter();
ccf.setInputConverter(converter);
ccf.setOutputConverter(converter);
ccf.setSoTimeout(10000);
ccf.setSingleUse(false);
ccf.start();
TcpOutboundGateway gateway = new TcpOutboundGateway();
gateway.setConnectionFactory(ccf);
QueueChannel replyChannel = new QueueChannel();
gateway.setRequiresReply(true);
gateway.setOutputChannel(replyChannel);
for (int i = 100; i < 110; i++) {
gateway.handleMessage(MessageBuilder.withPayload("Test" + i).build());
}
Set<String> replies = new HashSet<String>();
for (int i = 100; i < 110; i++) {
Message<?> m = replyChannel.receive(10000);
assertNotNull(m);
replies.add((String) m.getPayload());
}
for (int i = 0; i < 10; i++) {
assertTrue(replies.remove("Reply" + i));
}
}
@Test
public void testGoodNetTimeout() throws Exception {
final int port = SocketUtils.findAvailableServerSocket();
final CountDownLatch latch = new CountDownLatch(1);
final AtomicBoolean done = new AtomicBoolean();
Executors.newSingleThreadExecutor().execute(new Runnable() {
public void run() {
try {
ServerSocket server = ServerSocketFactory.getDefault().createServerSocket(port);
latch.countDown();
int i = 0;
Socket socket = server.accept();
while (true) {
ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());
ois.readObject();
ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream());
Thread.sleep(1000);
oos.writeObject("Reply" + (i++));
}
} catch (Exception e) {
if (!done.get()) {
e.printStackTrace();
}
}
}
});
AbstractConnectionFactory ccf = new TcpNetClientConnectionFactory("localhost", port);
JavaStreamingConverter converter = new JavaStreamingConverter();
ccf.setInputConverter(converter);
ccf.setOutputConverter(converter);
ccf.setSoTimeout(10000);
ccf.setSingleUse(false);
ccf.start();
final TcpOutboundGateway gateway = new TcpOutboundGateway();
gateway.setConnectionFactory(ccf);
gateway.setRequestTimeout(1);
QueueChannel replyChannel = new QueueChannel();
gateway.setRequiresReply(true);
gateway.setOutputChannel(replyChannel);
- List<Future<Integer>> results = new ArrayList<Future<Integer>>();
+ @SuppressWarnings("unchecked")
+ Future<Integer>[] results = new Future[2];
for (int i = 0; i < 2; i++) {
final int j = i;
- results.add(Executors.newSingleThreadExecutor().submit(new Callable<Integer>(){
+ results[j] = (Executors.newSingleThreadExecutor().submit(new Callable<Integer>(){
public Integer call() throws Exception {
gateway.handleMessage(MessageBuilder.withPayload("Test" + j).build());
return 0;
}
}));
}
Set<String> replies = new HashSet<String>();
for (int i = 0; i < 2; i++) {
try {
- results.get(i).get();
+ results[i].get();
} catch (InterruptedException e) {
} catch (ExecutionException e) {
if (i == 0) {
fail("Unexpected " + e.getMessage());
} else if (i == 1) {
assertNotNull(e.getCause());
assertTrue(e.getCause() instanceof MessageTimeoutException);
}
continue;
}
if (i == 1) {
fail("Expected ExecutionException");
}
Message<?> m = replyChannel.receive(10000);
assertNotNull(m);
replies.add((String) m.getPayload());
}
for (int i = 0; i < 1; i++) {
assertTrue(replies.remove("Reply" + i));
}
}
}
| false | true | public void testGoodNetTimeout() throws Exception {
final int port = SocketUtils.findAvailableServerSocket();
final CountDownLatch latch = new CountDownLatch(1);
final AtomicBoolean done = new AtomicBoolean();
Executors.newSingleThreadExecutor().execute(new Runnable() {
public void run() {
try {
ServerSocket server = ServerSocketFactory.getDefault().createServerSocket(port);
latch.countDown();
int i = 0;
Socket socket = server.accept();
while (true) {
ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());
ois.readObject();
ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream());
Thread.sleep(1000);
oos.writeObject("Reply" + (i++));
}
} catch (Exception e) {
if (!done.get()) {
e.printStackTrace();
}
}
}
});
AbstractConnectionFactory ccf = new TcpNetClientConnectionFactory("localhost", port);
JavaStreamingConverter converter = new JavaStreamingConverter();
ccf.setInputConverter(converter);
ccf.setOutputConverter(converter);
ccf.setSoTimeout(10000);
ccf.setSingleUse(false);
ccf.start();
final TcpOutboundGateway gateway = new TcpOutboundGateway();
gateway.setConnectionFactory(ccf);
gateway.setRequestTimeout(1);
QueueChannel replyChannel = new QueueChannel();
gateway.setRequiresReply(true);
gateway.setOutputChannel(replyChannel);
List<Future<Integer>> results = new ArrayList<Future<Integer>>();
for (int i = 0; i < 2; i++) {
final int j = i;
results.add(Executors.newSingleThreadExecutor().submit(new Callable<Integer>(){
public Integer call() throws Exception {
gateway.handleMessage(MessageBuilder.withPayload("Test" + j).build());
return 0;
}
}));
}
Set<String> replies = new HashSet<String>();
for (int i = 0; i < 2; i++) {
try {
results.get(i).get();
} catch (InterruptedException e) {
} catch (ExecutionException e) {
if (i == 0) {
fail("Unexpected " + e.getMessage());
} else if (i == 1) {
assertNotNull(e.getCause());
assertTrue(e.getCause() instanceof MessageTimeoutException);
}
continue;
}
if (i == 1) {
fail("Expected ExecutionException");
}
Message<?> m = replyChannel.receive(10000);
assertNotNull(m);
replies.add((String) m.getPayload());
}
for (int i = 0; i < 1; i++) {
assertTrue(replies.remove("Reply" + i));
}
}
| public void testGoodNetTimeout() throws Exception {
final int port = SocketUtils.findAvailableServerSocket();
final CountDownLatch latch = new CountDownLatch(1);
final AtomicBoolean done = new AtomicBoolean();
Executors.newSingleThreadExecutor().execute(new Runnable() {
public void run() {
try {
ServerSocket server = ServerSocketFactory.getDefault().createServerSocket(port);
latch.countDown();
int i = 0;
Socket socket = server.accept();
while (true) {
ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());
ois.readObject();
ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream());
Thread.sleep(1000);
oos.writeObject("Reply" + (i++));
}
} catch (Exception e) {
if (!done.get()) {
e.printStackTrace();
}
}
}
});
AbstractConnectionFactory ccf = new TcpNetClientConnectionFactory("localhost", port);
JavaStreamingConverter converter = new JavaStreamingConverter();
ccf.setInputConverter(converter);
ccf.setOutputConverter(converter);
ccf.setSoTimeout(10000);
ccf.setSingleUse(false);
ccf.start();
final TcpOutboundGateway gateway = new TcpOutboundGateway();
gateway.setConnectionFactory(ccf);
gateway.setRequestTimeout(1);
QueueChannel replyChannel = new QueueChannel();
gateway.setRequiresReply(true);
gateway.setOutputChannel(replyChannel);
@SuppressWarnings("unchecked")
Future<Integer>[] results = new Future[2];
for (int i = 0; i < 2; i++) {
final int j = i;
results[j] = (Executors.newSingleThreadExecutor().submit(new Callable<Integer>(){
public Integer call() throws Exception {
gateway.handleMessage(MessageBuilder.withPayload("Test" + j).build());
return 0;
}
}));
}
Set<String> replies = new HashSet<String>();
for (int i = 0; i < 2; i++) {
try {
results[i].get();
} catch (InterruptedException e) {
} catch (ExecutionException e) {
if (i == 0) {
fail("Unexpected " + e.getMessage());
} else if (i == 1) {
assertNotNull(e.getCause());
assertTrue(e.getCause() instanceof MessageTimeoutException);
}
continue;
}
if (i == 1) {
fail("Expected ExecutionException");
}
Message<?> m = replyChannel.receive(10000);
assertNotNull(m);
replies.add((String) m.getPayload());
}
for (int i = 0; i < 1; i++) {
assertTrue(replies.remove("Reply" + i));
}
}
|
diff --git a/tapestry-core/src/main/java/org/apache/tapestry5/corelib/components/Errors.java b/tapestry-core/src/main/java/org/apache/tapestry5/corelib/components/Errors.java
index a48c86706..71f3b4869 100644
--- a/tapestry-core/src/main/java/org/apache/tapestry5/corelib/components/Errors.java
+++ b/tapestry-core/src/main/java/org/apache/tapestry5/corelib/components/Errors.java
@@ -1,94 +1,94 @@
// Copyright 2006, 2007, 2008, 2011 The Apache Software Foundation
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package org.apache.tapestry5.corelib.components;
import org.apache.tapestry5.CSSClassConstants;
import org.apache.tapestry5.MarkupWriter;
import org.apache.tapestry5.ValidationTracker;
import org.apache.tapestry5.annotations.Environmental;
import org.apache.tapestry5.annotations.Parameter;
import org.apache.tapestry5.corelib.internal.InternalMessages;
import org.apache.tapestry5.services.FormSupport;
import java.util.List;
/**
* Standard validation error presenter. Must be enclosed by a
* {@link org.apache.tapestry5.corelib.components.Form} component. If errors are present, renders a
* div element around a banner message and around an unnumbered list of
* error messages. Renders nothing if the {@link org.apache.tapestry5.ValidationTracker} shows no
* errors.
*
* @see Form
* @tapestrydoc
*/
public class Errors
{
/**
* The banner message displayed above the errors. The default value is "You must correct the
* following errors before
* you may continue.".
*/
@Parameter("message:default-banner")
private String banner;
/**
* The CSS class for the div element rendered by the component. The default value is "t-error".
*/
@Parameter(name = "class")
private String className = CSSClassConstants.ERROR;
// Allow null so we can generate a better error message if missing
@Environmental(false)
private ValidationTracker tracker;
void beginRender(MarkupWriter writer)
{
if (tracker == null)
throw new RuntimeException(InternalMessages.encloseErrorsInForm());
if (!tracker.getHasErrors())
return;
writer.element("div", "class", className);
// Inner div for the banner text
- writer.element("div");
+ writer.element("div", "class", "t-banner");
writer.write(banner);
writer.end();
List<String> errors = tracker.getErrors();
if (!errors.isEmpty())
{
// Only write out the <UL> if it will contain <LI> elements. An empty <UL> is not
// valid XHTML.
writer.element("ul");
for (String message : errors)
{
writer.element("li");
writer.write(message);
writer.end();
}
writer.end(); // ul
}
writer.end(); // div
}
}
| true | true | void beginRender(MarkupWriter writer)
{
if (tracker == null)
throw new RuntimeException(InternalMessages.encloseErrorsInForm());
if (!tracker.getHasErrors())
return;
writer.element("div", "class", className);
// Inner div for the banner text
writer.element("div");
writer.write(banner);
writer.end();
List<String> errors = tracker.getErrors();
if (!errors.isEmpty())
{
// Only write out the <UL> if it will contain <LI> elements. An empty <UL> is not
// valid XHTML.
writer.element("ul");
for (String message : errors)
{
writer.element("li");
writer.write(message);
writer.end();
}
writer.end(); // ul
}
writer.end(); // div
}
| void beginRender(MarkupWriter writer)
{
if (tracker == null)
throw new RuntimeException(InternalMessages.encloseErrorsInForm());
if (!tracker.getHasErrors())
return;
writer.element("div", "class", className);
// Inner div for the banner text
writer.element("div", "class", "t-banner");
writer.write(banner);
writer.end();
List<String> errors = tracker.getErrors();
if (!errors.isEmpty())
{
// Only write out the <UL> if it will contain <LI> elements. An empty <UL> is not
// valid XHTML.
writer.element("ul");
for (String message : errors)
{
writer.element("li");
writer.write(message);
writer.end();
}
writer.end(); // ul
}
writer.end(); // div
}
|
diff --git a/src/edu/ucla/cens/awserver/jee/servlet/SensorUploadServlet.java b/src/edu/ucla/cens/awserver/jee/servlet/SensorUploadServlet.java
index 7fdba75f..9f450ac5 100644
--- a/src/edu/ucla/cens/awserver/jee/servlet/SensorUploadServlet.java
+++ b/src/edu/ucla/cens/awserver/jee/servlet/SensorUploadServlet.java
@@ -1,139 +1,139 @@
package edu.ucla.cens.awserver.jee.servlet;
import java.io.IOException;
import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.Logger;
import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;
import edu.ucla.cens.awserver.controller.Controller;
import edu.ucla.cens.awserver.controller.ControllerException;
import edu.ucla.cens.awserver.datatransfer.AwRequest;
import edu.ucla.cens.awserver.jee.servlet.glue.AwRequestCreator;
import edu.ucla.cens.awserver.util.StringUtils;
/**
* @author selsky
*/
@SuppressWarnings("serial")
public class SensorUploadServlet extends HttpServlet {
private static Logger _logger = Logger.getLogger(SensorUploadServlet.class);
private Controller _controller;
private AwRequestCreator _awRequestCreator;
/**
* Default no-arg constructor.
*/
public SensorUploadServlet() {
}
/**
* JavaEE-to-Spring glue code. When the web application starts up, the init method on all servlets is invoked by the Servlet
* container (if load-on-startup for the Servlet > 0). In this method, names of Spring "beans" are pulled out of the
* ServletConfig and the names are used to retrieve the beans out of the ApplicationContext. The basic design rule followed
* is that only Servlet.init methods contain Spring Framework glue code.
*/
public void init(ServletConfig config) throws ServletException {
super.init(config);
String servletName = config.getServletName();
String awRequestCreatorName = config.getInitParameter("awRequestCreatorName");
String controllerName = config.getInitParameter("controllerName");
if(StringUtils.isEmptyOrWhitespaceOnly(awRequestCreatorName)) {
throw new ServletException("Invalid web.xml. Missing awRequestCreatorName init param. Servlet " + servletName +
" cannot be initialized and put into service.");
}
if(StringUtils.isEmptyOrWhitespaceOnly(controllerName)) {
throw new ServletException("Invalid web.xml. Missing controllerName init param. Servlet " + servletName +
" cannot be initialized and put into service.");
}
// OK, now get the beans out of the Spring ApplicationContext
// If the beans do not exist within the Spring configuration, Spring will throw a RuntimeException and initialization
// of this Servlet will fail. (check catalina.out in addition to aw.log)
ServletContext servletContext = config.getServletContext();
ApplicationContext applicationContext = WebApplicationContextUtils.getWebApplicationContext(servletContext);
_awRequestCreator = (AwRequestCreator) applicationContext.getBean(awRequestCreatorName);
_controller = (Controller) applicationContext.getBean(controllerName);
}
/**
* Services the user requests to the URLs bound to this Servlet as configured in web.xml.
*
* Performs the following steps:
* <ol>
* <li>Maps HTTP request parameters into an AwRequest.
* <li>Passes the AwRequest to a Controller.
* <li>Places the results of the controller action into the HTTP request.
* <li> ... TODO
* </ol>
*/
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// Map data from the inbound request to our internal format
AwRequest awRequest = _awRequestCreator.createFrom(request);
try {
// Execute feature-specific logic
_controller.execute(awRequest);
if(awRequest.isFailedRequest()) {
ServletOutputStream servletOutputStream = response.getOutputStream();
servletOutputStream.println(awRequest.getFailedRequestErrorMessage());
servletOutputStream.flush();
servletOutputStream.close();
}
- request.getSession().invalidate(); // sensor data uploads only have state for the duration of a particular request
+ request.getSession().invalidate(); // sensor data uploads only have state for the duration of a request
}
catch(ControllerException ce) {
_logger.error("", ce); // make sure the stack trace gets into our app log
// TODO - send back a JSON error response
throw ce; // re-throw and allow Tomcat to redirect to the configured error page. the stack trace will also end up
// in catalina.out
}
}
/**
* Dispatches to processRequest().
*/
@Override protected final void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
processRequest(req, resp);
}
/**
* Dispatches to processRequest().
*/
@Override protected final void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
processRequest(req, resp);
}
}
| true | true | protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// Map data from the inbound request to our internal format
AwRequest awRequest = _awRequestCreator.createFrom(request);
try {
// Execute feature-specific logic
_controller.execute(awRequest);
if(awRequest.isFailedRequest()) {
ServletOutputStream servletOutputStream = response.getOutputStream();
servletOutputStream.println(awRequest.getFailedRequestErrorMessage());
servletOutputStream.flush();
servletOutputStream.close();
}
request.getSession().invalidate(); // sensor data uploads only have state for the duration of a particular request
}
catch(ControllerException ce) {
_logger.error("", ce); // make sure the stack trace gets into our app log
// TODO - send back a JSON error response
throw ce; // re-throw and allow Tomcat to redirect to the configured error page. the stack trace will also end up
// in catalina.out
}
}
| protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// Map data from the inbound request to our internal format
AwRequest awRequest = _awRequestCreator.createFrom(request);
try {
// Execute feature-specific logic
_controller.execute(awRequest);
if(awRequest.isFailedRequest()) {
ServletOutputStream servletOutputStream = response.getOutputStream();
servletOutputStream.println(awRequest.getFailedRequestErrorMessage());
servletOutputStream.flush();
servletOutputStream.close();
}
request.getSession().invalidate(); // sensor data uploads only have state for the duration of a request
}
catch(ControllerException ce) {
_logger.error("", ce); // make sure the stack trace gets into our app log
// TODO - send back a JSON error response
throw ce; // re-throw and allow Tomcat to redirect to the configured error page. the stack trace will also end up
// in catalina.out
}
}
|
diff --git a/src/test/java/org/weymouth/demo/model/DataTest.java b/src/test/java/org/weymouth/demo/model/DataTest.java
index d51d2ad..fcf9320 100755
--- a/src/test/java/org/weymouth/demo/model/DataTest.java
+++ b/src/test/java/org/weymouth/demo/model/DataTest.java
@@ -1,17 +1,18 @@
package org.weymouth.demo.model;
import junit.framework.Assert;
import org.junit.Test;
public class DataTest {
@Test
public void test(){
String probe = "probe";
Data d = new Data(probe);
String data = d.getData();
+ data = null;
Assert.assertNotNull(data);
Assert.assertEquals(probe, data);
}
}
| true | true | public void test(){
String probe = "probe";
Data d = new Data(probe);
String data = d.getData();
Assert.assertNotNull(data);
Assert.assertEquals(probe, data);
}
| public void test(){
String probe = "probe";
Data d = new Data(probe);
String data = d.getData();
data = null;
Assert.assertNotNull(data);
Assert.assertEquals(probe, data);
}
|
diff --git a/belajar-restful-web/src/test/java/com/artivisi/belajar/restful/ui/controller/HomepageControllerTestIT.java b/belajar-restful-web/src/test/java/com/artivisi/belajar/restful/ui/controller/HomepageControllerTestIT.java
index c78ccd0..cd8dcd1 100644
--- a/belajar-restful-web/src/test/java/com/artivisi/belajar/restful/ui/controller/HomepageControllerTestIT.java
+++ b/belajar-restful-web/src/test/java/com/artivisi/belajar/restful/ui/controller/HomepageControllerTestIT.java
@@ -1,48 +1,48 @@
/**
* Copyright (C) 2011 ArtiVisi Intermedia <[email protected]>
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.artivisi.belajar.restful.ui.controller;
import com.jayway.restassured.authentication.FormAuthConfig;
import org.junit.Test;
import static com.jayway.restassured.RestAssured.with;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.equalTo;
public class HomepageControllerTestIT {
private String target = "http://localhost:10000/homepage";
private String login = "http://localhost:10000/j_spring_security_check";
private String username = "endy";
private String password = "123";
@Test
public void testGetAppinfo() {
with().header("Accept", "application/json")
.auth().form(username, password, new FormAuthConfig(login, "j_username", "j_password"))
.expect()
.statusCode(200)
.body("profileDefault", equalTo("development"),
"profileActive", equalTo(""),
"namaAplikasi", equalTo("Aplikasi Belajar"),
- "versiAplikasi", containsString("belajar-restful-")
+ "versiAplikasi", equalTo("")
)
.when()
.get(target + "/" + "appinfo");
}
}
| true | true | public void testGetAppinfo() {
with().header("Accept", "application/json")
.auth().form(username, password, new FormAuthConfig(login, "j_username", "j_password"))
.expect()
.statusCode(200)
.body("profileDefault", equalTo("development"),
"profileActive", equalTo(""),
"namaAplikasi", equalTo("Aplikasi Belajar"),
"versiAplikasi", containsString("belajar-restful-")
)
.when()
.get(target + "/" + "appinfo");
}
| public void testGetAppinfo() {
with().header("Accept", "application/json")
.auth().form(username, password, new FormAuthConfig(login, "j_username", "j_password"))
.expect()
.statusCode(200)
.body("profileDefault", equalTo("development"),
"profileActive", equalTo(""),
"namaAplikasi", equalTo("Aplikasi Belajar"),
"versiAplikasi", equalTo("")
)
.when()
.get(target + "/" + "appinfo");
}
|
diff --git a/core/vdmj/src/main/java/org/overturetool/vdmj/scheduler/CTMainThread.java b/core/vdmj/src/main/java/org/overturetool/vdmj/scheduler/CTMainThread.java
index 20fb792464..24512ad550 100644
--- a/core/vdmj/src/main/java/org/overturetool/vdmj/scheduler/CTMainThread.java
+++ b/core/vdmj/src/main/java/org/overturetool/vdmj/scheduler/CTMainThread.java
@@ -1,160 +1,161 @@
/*******************************************************************************
*
* Copyright (C) 2008 Fujitsu Services Ltd.
*
* Author: Nick Battle
*
* This file is part of VDMJ.
*
* VDMJ is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* VDMJ is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with VDMJ. If not, see <http://www.gnu.org/licenses/>.
*
******************************************************************************/
package org.overturetool.vdmj.scheduler;
import java.util.List;
import java.util.Vector;
import org.overturetool.vdmj.Settings;
import org.overturetool.vdmj.commands.DebuggerReader;
import org.overturetool.vdmj.lex.LexLocation;
import org.overturetool.vdmj.runtime.Context;
import org.overturetool.vdmj.runtime.ContextException;
import org.overturetool.vdmj.statements.Statement;
import org.overturetool.vdmj.traces.CallSequence;
import org.overturetool.vdmj.traces.TraceVariableStatement;
import org.overturetool.vdmj.traces.Verdict;
/**
* A class representing the main VDM thread.
*/
public class CTMainThread extends MainThread
{
private static final long serialVersionUID = 1L;
private final CallSequence test;
private final boolean debug;
private List<Object> result = new Vector<Object>();
public CTMainThread(CallSequence test, Context ctxt, boolean debug)
{
super(null, ctxt);
this.test = test;
this.debug = debug;
setName("CTMainThread-" + getId());
}
@Override
public int hashCode()
{
return (int)getId();
}
@Override
public void body()
{
try
{
for (Statement statement: test)
{
if (statement instanceof TraceVariableStatement)
{
// Just update the context...
statement.eval(ctxt);
}
else
{
result.add(statement.eval(ctxt));
}
}
result.add(Verdict.PASSED);
}
catch (ContextException e)
{
result.add(e.getMessage().replaceAll(" \\(.+\\)", ""));
if (debug)
{
setException(e);
suspendOthers();
if (Settings.usingDBGP)
{
ctxt.threadState.dbgp.stopped(e.ctxt, e.location);
}
else
{
DebuggerReader.stopped(e.ctxt, e.location);
}
result.add(Verdict.FAILED);
}
else
{
switch (e.number)
{
case 4055: // precondition fails for functions
case 4071: // precondition fails for operations
case 4087: // invalid type conversion
case 4060: // type invariant failure
case 4130: // class invariant failure
- if (e.ctxt.outer == ctxt)
+ if (e.ctxt.outer == ctxt ||
+ (e.ctxt.outer != null && e.ctxt.outer.outer == ctxt))
{
// These exceptions are inconclusive if they occur
// in a call directly from the test because it could
// be a test error, but if the test call has made
// further call(s), then they are real failures.
result.add(Verdict.INCONCLUSIVE);
}
else
{
result.add(Verdict.FAILED);
}
break;
default:
result.add(Verdict.FAILED);
}
}
}
catch (Exception e)
{
result.add(e.getMessage());
result.add(Verdict.FAILED);
}
}
@Override
protected void handleSignal(Signal sig, Context lctxt, LexLocation location)
{
if (sig == Signal.DEADLOCKED)
{
result.add("DEADLOCK detected");
result.add(Verdict.FAILED);
}
super.handleSignal(sig, lctxt, location);
}
public List<Object> getList()
{
return result;
}
}
| true | true | public void body()
{
try
{
for (Statement statement: test)
{
if (statement instanceof TraceVariableStatement)
{
// Just update the context...
statement.eval(ctxt);
}
else
{
result.add(statement.eval(ctxt));
}
}
result.add(Verdict.PASSED);
}
catch (ContextException e)
{
result.add(e.getMessage().replaceAll(" \\(.+\\)", ""));
if (debug)
{
setException(e);
suspendOthers();
if (Settings.usingDBGP)
{
ctxt.threadState.dbgp.stopped(e.ctxt, e.location);
}
else
{
DebuggerReader.stopped(e.ctxt, e.location);
}
result.add(Verdict.FAILED);
}
else
{
switch (e.number)
{
case 4055: // precondition fails for functions
case 4071: // precondition fails for operations
case 4087: // invalid type conversion
case 4060: // type invariant failure
case 4130: // class invariant failure
if (e.ctxt.outer == ctxt)
{
// These exceptions are inconclusive if they occur
// in a call directly from the test because it could
// be a test error, but if the test call has made
// further call(s), then they are real failures.
result.add(Verdict.INCONCLUSIVE);
}
else
{
result.add(Verdict.FAILED);
}
break;
default:
result.add(Verdict.FAILED);
}
}
}
catch (Exception e)
{
result.add(e.getMessage());
result.add(Verdict.FAILED);
}
}
| public void body()
{
try
{
for (Statement statement: test)
{
if (statement instanceof TraceVariableStatement)
{
// Just update the context...
statement.eval(ctxt);
}
else
{
result.add(statement.eval(ctxt));
}
}
result.add(Verdict.PASSED);
}
catch (ContextException e)
{
result.add(e.getMessage().replaceAll(" \\(.+\\)", ""));
if (debug)
{
setException(e);
suspendOthers();
if (Settings.usingDBGP)
{
ctxt.threadState.dbgp.stopped(e.ctxt, e.location);
}
else
{
DebuggerReader.stopped(e.ctxt, e.location);
}
result.add(Verdict.FAILED);
}
else
{
switch (e.number)
{
case 4055: // precondition fails for functions
case 4071: // precondition fails for operations
case 4087: // invalid type conversion
case 4060: // type invariant failure
case 4130: // class invariant failure
if (e.ctxt.outer == ctxt ||
(e.ctxt.outer != null && e.ctxt.outer.outer == ctxt))
{
// These exceptions are inconclusive if they occur
// in a call directly from the test because it could
// be a test error, but if the test call has made
// further call(s), then they are real failures.
result.add(Verdict.INCONCLUSIVE);
}
else
{
result.add(Verdict.FAILED);
}
break;
default:
result.add(Verdict.FAILED);
}
}
}
catch (Exception e)
{
result.add(e.getMessage());
result.add(Verdict.FAILED);
}
}
|
diff --git a/org.eclipse.mylyn.wikitext.tracwiki.ui/src/org/eclipse/mylyn/internal/wikitext/tracwiki/ui/editors/TracWikiTaskEditorExtension.java b/org.eclipse.mylyn.wikitext.tracwiki.ui/src/org/eclipse/mylyn/internal/wikitext/tracwiki/ui/editors/TracWikiTaskEditorExtension.java
index a05d013f..64952cd8 100644
--- a/org.eclipse.mylyn.wikitext.tracwiki.ui/src/org/eclipse/mylyn/internal/wikitext/tracwiki/ui/editors/TracWikiTaskEditorExtension.java
+++ b/org.eclipse.mylyn.wikitext.tracwiki.ui/src/org/eclipse/mylyn/internal/wikitext/tracwiki/ui/editors/TracWikiTaskEditorExtension.java
@@ -1,40 +1,41 @@
/*******************************************************************************
* Copyright (c) 2007, 2008 David Green and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* David Green - initial API and implementation
*******************************************************************************/
package org.eclipse.mylyn.internal.wikitext.tracwiki.ui.editors;
import org.eclipse.mylyn.tasks.core.TaskRepository;
import org.eclipse.mylyn.wikitext.core.parser.markup.MarkupLanguage;
import org.eclipse.mylyn.wikitext.tracwiki.core.TracWikiLanguage;
import org.eclipse.mylyn.wikitext.ui.editor.MarkupTaskEditorExtension;
/**
*
*
* @author David Green
*/
public class TracWikiTaskEditorExtension extends MarkupTaskEditorExtension {
public TracWikiTaskEditorExtension() {
setMarkupLanguage(new TracWikiLanguage());
}
@Override
protected void configureDefaultInternalLinkPattern(TaskRepository taskRepository, MarkupLanguage markupLanguage) {
String url = taskRepository.getRepositoryUrl();
if (url != null && url.length() > 0) {
if (!url.endsWith("/")) {
url = url + "/";
}
+ // bug 247772: set the default wiki link URL for the repository
markupLanguage.setInternalLinkPattern(url + "wiki/{0}");
}
}
}
| true | true | protected void configureDefaultInternalLinkPattern(TaskRepository taskRepository, MarkupLanguage markupLanguage) {
String url = taskRepository.getRepositoryUrl();
if (url != null && url.length() > 0) {
if (!url.endsWith("/")) {
url = url + "/";
}
markupLanguage.setInternalLinkPattern(url + "wiki/{0}");
}
}
| protected void configureDefaultInternalLinkPattern(TaskRepository taskRepository, MarkupLanguage markupLanguage) {
String url = taskRepository.getRepositoryUrl();
if (url != null && url.length() > 0) {
if (!url.endsWith("/")) {
url = url + "/";
}
// bug 247772: set the default wiki link URL for the repository
markupLanguage.setInternalLinkPattern(url + "wiki/{0}");
}
}
|
diff --git a/editor/tools/plugins/com.google.dart.tools.core_test/src/com/google/dart/tools/core/TestAll.java b/editor/tools/plugins/com.google.dart.tools.core_test/src/com/google/dart/tools/core/TestAll.java
index 94d5a8f3d..2c2cfebd9 100644
--- a/editor/tools/plugins/com.google.dart.tools.core_test/src/com/google/dart/tools/core/TestAll.java
+++ b/editor/tools/plugins/com.google.dart.tools.core_test/src/com/google/dart/tools/core/TestAll.java
@@ -1,39 +1,39 @@
/*
* Copyright (c) 2012, the Dart project authors.
*
* Licensed under the Eclipse Public License v1.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.eclipse.org/legal/epl-v10.html
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.dart.tools.core;
import junit.framework.Test;
import junit.framework.TestSuite;
public class TestAll {
public static Test suite() {
TestSuite suite = new TestSuite("Tests in " + TestAll.class.getPackage().getName());
suite.addTestSuite(DartCoreTest.class);
suite.addTestSuite(PluginXMLTest.class);
// suite.addTest(com.google.dart.tools.core.formatter.TestAll.suite());
// suite.addTest(com.google.dart.tools.core.frog.TestAll.suite());
suite.addTest(com.google.dart.tools.core.generator.TestAll.suite());
suite.addTest(com.google.dart.tools.core.index.TestAll.suite());
suite.addTest(com.google.dart.tools.core.indexer.TestAll.suite());
suite.addTest(com.google.dart.tools.core.internal.TestAll.suite());
// suite.addTest(com.google.dart.tools.core.model.TestAll.suite());
- suite.addTest(com.google.dart.tools.core.refresh.TestAll.suite());
+// suite.addTest(com.google.dart.tools.core.refresh.TestAll.suite());
suite.addTest(com.google.dart.tools.core.samples.TestAll.suite());
suite.addTest(com.google.dart.tools.core.search.TestAll.suite());
suite.addTest(com.google.dart.tools.core.utilities.TestAll.suite());
suite.addTest(com.google.dart.tools.core.workingcopy.TestAll.suite());
return suite;
}
}
| true | true | public static Test suite() {
TestSuite suite = new TestSuite("Tests in " + TestAll.class.getPackage().getName());
suite.addTestSuite(DartCoreTest.class);
suite.addTestSuite(PluginXMLTest.class);
// suite.addTest(com.google.dart.tools.core.formatter.TestAll.suite());
// suite.addTest(com.google.dart.tools.core.frog.TestAll.suite());
suite.addTest(com.google.dart.tools.core.generator.TestAll.suite());
suite.addTest(com.google.dart.tools.core.index.TestAll.suite());
suite.addTest(com.google.dart.tools.core.indexer.TestAll.suite());
suite.addTest(com.google.dart.tools.core.internal.TestAll.suite());
// suite.addTest(com.google.dart.tools.core.model.TestAll.suite());
suite.addTest(com.google.dart.tools.core.refresh.TestAll.suite());
suite.addTest(com.google.dart.tools.core.samples.TestAll.suite());
suite.addTest(com.google.dart.tools.core.search.TestAll.suite());
suite.addTest(com.google.dart.tools.core.utilities.TestAll.suite());
suite.addTest(com.google.dart.tools.core.workingcopy.TestAll.suite());
return suite;
}
| public static Test suite() {
TestSuite suite = new TestSuite("Tests in " + TestAll.class.getPackage().getName());
suite.addTestSuite(DartCoreTest.class);
suite.addTestSuite(PluginXMLTest.class);
// suite.addTest(com.google.dart.tools.core.formatter.TestAll.suite());
// suite.addTest(com.google.dart.tools.core.frog.TestAll.suite());
suite.addTest(com.google.dart.tools.core.generator.TestAll.suite());
suite.addTest(com.google.dart.tools.core.index.TestAll.suite());
suite.addTest(com.google.dart.tools.core.indexer.TestAll.suite());
suite.addTest(com.google.dart.tools.core.internal.TestAll.suite());
// suite.addTest(com.google.dart.tools.core.model.TestAll.suite());
// suite.addTest(com.google.dart.tools.core.refresh.TestAll.suite());
suite.addTest(com.google.dart.tools.core.samples.TestAll.suite());
suite.addTest(com.google.dart.tools.core.search.TestAll.suite());
suite.addTest(com.google.dart.tools.core.utilities.TestAll.suite());
suite.addTest(com.google.dart.tools.core.workingcopy.TestAll.suite());
return suite;
}
|
diff --git a/common/logisticspipes/routing/ServerRouter.java b/common/logisticspipes/routing/ServerRouter.java
index 743fc764..5d05b5f4 100644
--- a/common/logisticspipes/routing/ServerRouter.java
+++ b/common/logisticspipes/routing/ServerRouter.java
@@ -1,586 +1,585 @@
/**
* Copyright (c) Krapht, 2011
*
* "LogisticsPipes" is distributed under the terms of the Minecraft Mod Public
* License 1.0, or MMPL. Please check the contents of the license located in
* http://www.mod-buildcraft.com/MMPL-1.0.txt
*/
package logisticspipes.routing;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.BitSet;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map.Entry;
import java.util.PriorityQueue;
import java.util.UUID;
import java.util.Vector;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
import logisticspipes.config.Configs;
import logisticspipes.interfaces.ILogisticsModule;
import logisticspipes.interfaces.routing.ILogisticsPowerProvider;
import logisticspipes.interfaces.routing.IPowerRouter;
import logisticspipes.interfaces.routing.IRequireReliableTransport;
import logisticspipes.pipes.PipeItemsBasicLogistics;
import logisticspipes.pipes.PipeItemsFirewall;
import logisticspipes.pipes.basic.CoreRoutedPipe;
import logisticspipes.pipes.basic.RoutedPipe;
import logisticspipes.proxy.MainProxy;
import logisticspipes.proxy.SimpleServiceLocator;
import logisticspipes.ticks.RoutingTableUpdateThread;
import logisticspipes.utils.ItemIdentifierStack;
import logisticspipes.utils.Pair;
import net.minecraft.item.ItemStack;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.world.World;
import net.minecraftforge.common.ForgeDirection;
import buildcraft.api.core.Position;
import buildcraft.transport.TileGenericPipe;
public class ServerRouter implements IRouter, IPowerRouter {
//may not speed up the code - consumes about 7% of CreateRouteTable runtume
@Override
public int hashCode(){
return simpleID; // guaranteed to be unique, and uniform distribution over a range.
// return (int)id.getLeastSignificantBits(); // RandomID is cryptographcially secure, so this is a good approximation of true random.
}
private class LSA {
public HashMap<IRouter, Pair<Integer, EnumSet<PipeRoutingConnectionType>>> neighboursWithMetric;
public List<ILogisticsPowerProvider> power;
}
private class RoutingUpdateThread implements Runnable {
int newVersion = 0;
boolean run = false;
RoutingUpdateThread(int version) {
newVersion = version;
run = true;
}
@Override
public void run() {
if(!run) return;
try {
CreateRouteTable();
synchronized (_externalRoutersByCostLock) {
_externalRoutersByCost = null;
}
_lastLSDVersion = newVersion;
} catch(Exception e) {
e.printStackTrace();
}
run = false;
updateThreadwriteLock.lock();
updateThread = null;
updateThreadwriteLock.unlock();
}
}
public HashMap<RoutedPipe, ExitRoute> _adjacent = new HashMap<RoutedPipe, ExitRoute>();
public HashMap<IRouter, ExitRoute> _adjacentRouter = new HashMap<IRouter, ExitRoute>();
public List<ILogisticsPowerProvider> _powerAdjacent = new ArrayList<ILogisticsPowerProvider>();
private static int _LSDVersion = 0;
private int _lastLSDVersion = 0;
private RoutingUpdateThread updateThread = null;
private static RouteLaser _laser = new RouteLaser();
private static final ReentrantReadWriteLock SharedLSADatabaseLock = new ReentrantReadWriteLock();
private static final Lock SharedLSADatabasereadLock = SharedLSADatabaseLock.readLock();
private static final Lock SharedLSADatabasewriteLock = SharedLSADatabaseLock.writeLock();
private static final ReentrantReadWriteLock updateThreadLock = new ReentrantReadWriteLock();
private static final Lock updateThreadreadLock = updateThreadLock.readLock();
private static final Lock updateThreadwriteLock = updateThreadLock.writeLock();
public Object _externalRoutersByCostLock = new Object();
private static final ArrayList<LSA> SharedLSADatabase = new ArrayList<LSA>();
private LSA _myLsa = new LSA();
/** Map of router -> orientation for all known destinations **/
public ArrayList<Pair<ForgeDirection, ForgeDirection>> _routeTable = new ArrayList<Pair<ForgeDirection,ForgeDirection>>();
public List<SearchNode> _routeCosts = new ArrayList<SearchNode>();
public List<ILogisticsPowerProvider> _powerTable = new ArrayList<ILogisticsPowerProvider>();
public LinkedList<IRouter> _externalRoutersByCost = null;
private EnumSet<ForgeDirection> _routedExits = EnumSet.noneOf(ForgeDirection.class);
private boolean _blockNeedsUpdate;
private boolean forceUpdate = true;
private static int firstFreeId = 1;
private static BitSet simpleIdUsedSet = new BitSet();
private final int simpleID;
public final UUID id;
private int _dimension;
private final int _xCoord;
private final int _yCoord;
private final int _zCoord;
private WeakReference<CoreRoutedPipe> _myPipeCache=null;
public void clearPipeCache(){_myPipeCache=null;}
public static void resetStatics() {
SharedLSADatabasewriteLock.lock();
SharedLSADatabase.clear();
SharedLSADatabasewriteLock.unlock();
_LSDVersion = 0;
_laser = new RouteLaser();
firstFreeId = 1;
simpleIdUsedSet.clear();
}
private static int claimSimpleID() {
int idx = simpleIdUsedSet.nextClearBit(firstFreeId);
firstFreeId = idx + 1;
simpleIdUsedSet.set(idx);
return idx;
}
private static void releaseSimpleID(int idx) {
simpleIdUsedSet.clear(idx);
if(idx < firstFreeId)
firstFreeId = idx;
}
public static int getBiggestSimpleID() {
return simpleIdUsedSet.size();
}
public ServerRouter(UUID globalID, int dimension, int xCoord, int yCoord, int zCoord){
this.simpleID = claimSimpleID();
if(globalID!=null)
this.id = globalID;
else
this.id = UUID.randomUUID();
this._dimension = dimension;
this._xCoord = xCoord;
this._yCoord = yCoord;
this._zCoord = zCoord;
clearPipeCache();
_myLsa = new LSA();
_myLsa.neighboursWithMetric = new HashMap<IRouter, Pair<Integer, EnumSet<PipeRoutingConnectionType>>>();
_myLsa.power = new ArrayList<ILogisticsPowerProvider>();
SharedLSADatabasereadLock.lock();
if(SharedLSADatabase.size()<=simpleID){
SharedLSADatabasereadLock.unlock(); // promote lock type
SharedLSADatabasewriteLock.lock();
SharedLSADatabase.ensureCapacity((int) (simpleID*1.5)); // make structural change
while(SharedLSADatabase.size()<=simpleID)
SharedLSADatabase.add(null);
SharedLSADatabasewriteLock.unlock(); // demote lock
SharedLSADatabasereadLock.lock();
}
SharedLSADatabase.set(this.simpleID, _myLsa); // make non-structural change (threadsafe)
SharedLSADatabasereadLock.unlock();
}
public int getSimpleID() {
return this.simpleID;
}
public boolean isAt(int dimension, int xCoord, int yCoord, int zCoord){
return _dimension == dimension && _xCoord == xCoord && _yCoord == yCoord && _zCoord == zCoord;
}
@Override
public CoreRoutedPipe getPipe(){
if(_myPipeCache!=null && _myPipeCache.get()!=null)
return _myPipeCache.get();
World worldObj = MainProxy.getWorld(_dimension);
if(worldObj == null) {
return null;
}
TileEntity tile = worldObj.getBlockTileEntity(_xCoord, _yCoord, _zCoord);
if (!(tile instanceof TileGenericPipe)) return null;
TileGenericPipe pipe = (TileGenericPipe) tile;
if (!(pipe.pipe instanceof CoreRoutedPipe)) return null;
_myPipeCache=new WeakReference<CoreRoutedPipe>((CoreRoutedPipe) pipe.pipe);
return (CoreRoutedPipe) pipe.pipe;
}
private void ensureRouteTableIsUpToDate(boolean force){
if (_LSDVersion > _lastLSDVersion) {
if(Configs.multiThreadEnabled && !force && SimpleServiceLocator.routerManager.routerAddingDone()) {
updateThreadreadLock.lock();
if(updateThread != null) {
if(updateThread.newVersion == _LSDVersion) {
updateThreadreadLock.unlock();
return;
}
updateThread.run = false;
RoutingTableUpdateThread.remove(updateThread);
}
updateThreadreadLock.unlock();
updateThread = new RoutingUpdateThread(_LSDVersion);
if(_lastLSDVersion == 0) {
RoutingTableUpdateThread.addPriority(updateThread);
} else {
RoutingTableUpdateThread.add(updateThread);
}
} else {
CreateRouteTable();
_externalRoutersByCost = null;
_lastLSDVersion = _LSDVersion;
}
}
}
@Override
public ArrayList<Pair<ForgeDirection,ForgeDirection>> getRouteTable(){
ensureRouteTableIsUpToDate(true);
return _routeTable;
}
@Override
public List<SearchNode> getIRoutersByCost() {
ensureRouteTableIsUpToDate(true);
return _routeCosts;
}
@Override
public UUID getId() {
return this.id;
}
/**
* Rechecks the piped connection to all adjacent routers as well as discover new ones.
*/
private void recheckAdjacent() {
boolean adjacentChanged = false;
CoreRoutedPipe thisPipe = getPipe();
if (thisPipe == null) return;
HashMap<RoutedPipe, ExitRoute> adjacent;
List<ILogisticsPowerProvider> power;
if(thisPipe instanceof PipeItemsFirewall) {
adjacent = PathFinder.getConnectedRoutingPipes(thisPipe.container, Configs.LOGISTICS_DETECTION_COUNT, Configs.LOGISTICS_DETECTION_LENGTH, ((PipeItemsFirewall)thisPipe).getRouterSide(this));
power = new LinkedList<ILogisticsPowerProvider>();
} else {
adjacent = PathFinder.getConnectedRoutingPipes(thisPipe.container, Configs.LOGISTICS_DETECTION_COUNT, Configs.LOGISTICS_DETECTION_LENGTH);
power = this.getConnectedPowerProvider();
}
for(RoutedPipe pipe : adjacent.keySet()) {
if(pipe.stillNeedReplace()) {
return;
}
}
for (RoutedPipe pipe : _adjacent.keySet()){
if(!adjacent.containsKey(pipe))
adjacentChanged = true;
}
for (ILogisticsPowerProvider provider : _powerAdjacent){
if(!power.contains(provider))
adjacentChanged = true;
}
for (RoutedPipe pipe : adjacent.keySet()) {
if (!_adjacent.containsKey(pipe)){
adjacentChanged = true;
break;
}
ExitRoute newExit = adjacent.get(pipe);
ExitRoute oldExit = _adjacent.get(pipe);
if (!newExit.equals(oldExit)) {
adjacentChanged = true;
break;
}
}
for (ILogisticsPowerProvider provider : power){
if(!_powerAdjacent.contains(provider))
adjacentChanged = true;
}
if (adjacentChanged) {
HashMap<IRouter, ExitRoute> adjacentRouter = new HashMap<IRouter, ExitRoute>();
_routedExits.clear();
for(Entry<RoutedPipe,ExitRoute> pipe:adjacent.entrySet()) {
adjacentRouter.put(((CoreRoutedPipe) pipe.getKey()).getRouter(pipe.getValue().insertOrientation), pipe.getValue());
if(pipe.getValue().connectionDetails.contains(PipeRoutingConnectionType.canRouteTo) || pipe.getValue().connectionDetails.contains(PipeRoutingConnectionType.canRequestFrom))
_routedExits.add(pipe.getValue().exitOrientation);
}
_adjacentRouter = adjacentRouter;
_adjacent = adjacent;
_powerAdjacent = power;
_blockNeedsUpdate = true;
SendNewLSA();
}
}
private void SendNewLSA() {
HashMap<IRouter, Pair<Integer, EnumSet<PipeRoutingConnectionType>>> neighboursWithMetric = new HashMap<IRouter, Pair<Integer, EnumSet<PipeRoutingConnectionType>>>();
ArrayList<ILogisticsPowerProvider> power = new ArrayList<ILogisticsPowerProvider>();
for (RoutedPipe adjacent : _adjacent.keySet()){
neighboursWithMetric.put(adjacent.getRouter(_adjacent.get(adjacent).insertOrientation), new Pair<Integer, EnumSet<PipeRoutingConnectionType>>(_adjacent.get(adjacent).metric, _adjacent.get(adjacent).connectionDetails));
}
for (ILogisticsPowerProvider provider : _powerAdjacent){
power.add(provider);
}
SharedLSADatabasewriteLock.lock();
_myLsa.neighboursWithMetric = neighboursWithMetric;
_myLsa.power = power;
_LSDVersion++;
SharedLSADatabasewriteLock.unlock();
}
/**
* Create a route table from the link state database
*/
private void CreateRouteTable() {
//Dijkstra!
int routingTableSize =ServerRouter.getBiggestSimpleID();
if(routingTableSize == 0) {
// routingTableSize=SimpleServiceLocator.routerManager.getRouterCount();
routingTableSize=SharedLSADatabase.size(); // deliberatly ignoring concurrent access, either the old or the version of the size will work, this is just an approximate number.
}
/** same info as above, but sorted by distance -- sorting is implicit, because Dijkstra finds the closest routes first.**/
ArrayList<SearchNode> routeCosts = new ArrayList<SearchNode>(routingTableSize);
ArrayList<ILogisticsPowerProvider> powerTable = new ArrayList<ILogisticsPowerProvider>(_powerAdjacent);
//space and time inefficient, a bitset with 3 bits per node would save a lot but makes the main iteration look like a complete mess
Vector<EnumSet<PipeRoutingConnectionType>> closedSet = new Vector<EnumSet<PipeRoutingConnectionType>>(getBiggestSimpleID());
closedSet.setSize(getBiggestSimpleID());
closedSet.set(this.getSimpleID(), EnumSet.allOf(PipeRoutingConnectionType.class));
/** The total cost for the candidate route **/
PriorityQueue<SearchNode> candidatesCost = new PriorityQueue<SearchNode>((int) Math.sqrt(routingTableSize)); // sqrt nodes is a good guess for the total number of candidate nodes at once.
//Init candidates
// the shortest way to go to an adjacent item is the adjacent item.
for (Entry<RoutedPipe, ExitRoute> pipe : _adjacent.entrySet()){
ExitRoute currentE = pipe.getValue();
//currentE.connectionDetails.retainAll(blocksPower);
candidatesCost.add(new SearchNode(pipe.getKey().getRouter(currentE.insertOrientation), currentE.metric, pipe.getValue().connectionDetails.clone(), pipe.getKey().getRouter(currentE.insertOrientation)));
//objectMapped.set(pipe.getKey().getSimpleID(),true);
}
SharedLSADatabasereadLock.lock(); // readlock, not inside the while - too costly to aquire, then release.
SearchNode lowestCostNode;
while ((lowestCostNode=candidatesCost.poll()) != null){
if(!lowestCostNode.hasActivePipe())
continue;
//if the node does not have any flags not in the closed set, check it
EnumSet<PipeRoutingConnectionType> lowestCostClosedFlags = closedSet.get(lowestCostNode.node.getSimpleID());
if(lowestCostClosedFlags == null)
lowestCostClosedFlags = EnumSet.noneOf(PipeRoutingConnectionType.class);
if(lowestCostClosedFlags.containsAll(lowestCostNode.getFlags()))
continue;
//Add new candidates from the newly approved route
LSA lsa = SharedLSADatabase.get(lowestCostNode.node.getSimpleID());
if(lsa == null) {
SharedLSADatabasereadLock.unlock();
lowestCostNode.removeFlags(lowestCostClosedFlags);
lowestCostClosedFlags.addAll(lowestCostNode.getFlags());
if(lowestCostNode.containsFlag(PipeRoutingConnectionType.canRouteTo) || lowestCostNode.containsFlag(PipeRoutingConnectionType.canRequestFrom))
routeCosts.add(lowestCostNode);
closedSet.set(lowestCostNode.node.getSimpleID(),lowestCostClosedFlags);
continue;
}
if(lowestCostNode.containsFlag(PipeRoutingConnectionType.canPowerFrom)) {
if(lsa.power.isEmpty() == false) {
if(!lowestCostClosedFlags.contains(PipeRoutingConnectionType.canPowerFrom)) {
powerTable.addAll(lsa.power);
}
}
}
Iterator<Entry<IRouter, Pair<Integer, EnumSet<PipeRoutingConnectionType>>>> it = lsa.neighboursWithMetric.entrySet().iterator();
while (it.hasNext()) {
Entry<IRouter, Pair<Integer, EnumSet<PipeRoutingConnectionType>>> newCandidate = (Entry<IRouter, Pair<Integer, EnumSet<PipeRoutingConnectionType>>>)it.next();
EnumSet<PipeRoutingConnectionType> newCandidateClosedFlags = closedSet.get(newCandidate.getKey().getSimpleID());
if(newCandidateClosedFlags == null)
newCandidateClosedFlags = EnumSet.noneOf(PipeRoutingConnectionType.class);
if(newCandidateClosedFlags.containsAll(newCandidate.getValue().getValue2()))
continue;
int candidateCost = lowestCostNode.distance + newCandidate.getValue().getValue1();
EnumSet<PipeRoutingConnectionType> newCT = lowestCostNode.getFlags();
newCT.retainAll(newCandidate.getValue().getValue2());
if(!newCT.isEmpty())
candidatesCost.add(new SearchNode(newCandidate.getKey(), candidateCost, newCT, lowestCostNode.root));
}
- SharedLSADatabasereadLock.unlock();
lowestCostNode.removeFlags(lowestCostClosedFlags);
lowestCostClosedFlags.addAll(lowestCostNode.getFlags());
if(lowestCostNode.containsFlag(PipeRoutingConnectionType.canRouteTo) || lowestCostNode.containsFlag(PipeRoutingConnectionType.canRequestFrom))
routeCosts.add(lowestCostNode);
closedSet.set(lowestCostNode.node.getSimpleID(),lowestCostClosedFlags);
}
SharedLSADatabasereadLock.unlock();
//Build route table
ArrayList<Pair<ForgeDirection, ForgeDirection>> routeTable = new ArrayList<Pair<ForgeDirection,ForgeDirection>>(ServerRouter.getBiggestSimpleID()+1);
while (this.getSimpleID() >= routeTable.size())
routeTable.add(null);
routeTable.set(this.getSimpleID(), new Pair<ForgeDirection,ForgeDirection>(ForgeDirection.UNKNOWN, ForgeDirection.UNKNOWN));
for (SearchNode node : routeCosts)
{
if(!node.containsFlag(PipeRoutingConnectionType.canRouteTo))
continue;
IRouter firstHop = node.root;
if (firstHop == null) { //this should never happen?!?
while (node.node.getSimpleID() >= routeTable.size())
routeTable.add(null);
routeTable.set(node.node.getSimpleID(), new Pair<ForgeDirection,ForgeDirection>(ForgeDirection.UNKNOWN, ForgeDirection.UNKNOWN));
continue;
}
ExitRoute hop=_adjacentRouter.get(firstHop);
if (hop == null){
continue;
}
while (node.node.getSimpleID() >= routeTable.size())
routeTable.add(null);
routeTable.set(node.node.getSimpleID(), new Pair<ForgeDirection,ForgeDirection>(hop.exitOrientation, hop.insertOrientation));
}
_powerTable = powerTable;
_routeTable = routeTable;
_routeCosts = routeCosts;
}
@Override
public void displayRoutes(){
_laser.displayRoute(this);
}
@Override
public void displayRouteTo(int r){
_laser.displayRoute(this, r);
}
@Override
public void inboundItemArrived(RoutedEntityItem routedEntityItem){
//notify that Item has arrived
CoreRoutedPipe pipe = getPipe();
if (pipe != null && pipe.logic instanceof IRequireReliableTransport){
((IRequireReliableTransport)pipe.logic).itemArrived(ItemIdentifierStack.GetFromStack(routedEntityItem.getItemStack()));
}
}
@Override
public void itemDropped(RoutedEntityItem routedEntityItem) {
//TODO
}
/**
* Flags the last sent LSA as expired. Each router will be responsible of purging it from its database.
*/
@Override
public void destroy() {
SharedLSADatabasewriteLock.lock(); // take a write lock so that we don't overlap with any ongoing route updates
if (SharedLSADatabase.get(simpleID)!=null) {
SharedLSADatabase.set(simpleID, null);
_LSDVersion++;
}
SharedLSADatabasewriteLock.unlock();
SimpleServiceLocator.routerManager.removeRouter(this.simpleID);
releaseSimpleID(simpleID);
updateNeighbors();
}
private void updateNeighbors() {
for(RoutedPipe p : _adjacent.keySet()) {
p.getRouter().update(true);
}
}
@Override
public void update(boolean doFullRefresh){
if (doFullRefresh || forceUpdate) {
if(updateThread == null) {
forceUpdate = false;
recheckAdjacent();
if (_blockNeedsUpdate){
CoreRoutedPipe pipe = getPipe();
if (pipe == null) return;
pipe.worldObj.markBlockForRenderUpdate(pipe.xCoord, pipe.yCoord, pipe.zCoord);
pipe.refreshRender(true);
_blockNeedsUpdate = false;
updateNeighbors();
}
} else {
forceUpdate = true;
}
}
ensureRouteTableIsUpToDate(false);
}
/************* IROUTER *******************/
@Override
public void sendRoutedItem(ItemStack item, IRouter destination, Position origin) {
// TODO Auto-generated method stub
}
@Override
public boolean isRoutedExit(ForgeDirection o){
return _routedExits.contains(o);
}
@Override
public ForgeDirection getExitFor(int id) {
return this.getRouteTable().get(id).getValue1();
}
@Override
public boolean hasRoute(int id) {
if (!SimpleServiceLocator.routerManager.isRouter(id)) return false;
if(getRouteTable().size()<=id)
return false;
return this.getRouteTable().get(id)!=null;
}
@Override
public ILogisticsModule getLogisticsModule() {
CoreRoutedPipe pipe = this.getPipe();
if (pipe == null) return null;
return pipe.getLogisticsModule();
}
@Override
public List<ILogisticsPowerProvider> getPowerProvider() {
return _powerTable;
}
@Override
public List<ILogisticsPowerProvider> getConnectedPowerProvider() {
CoreRoutedPipe pipe = getPipe();
if(pipe instanceof PipeItemsBasicLogistics) {
return ((PipeItemsBasicLogistics)pipe).getConnectedPowerProviders();
} else {
return new ArrayList<ILogisticsPowerProvider>();
}
}
}
| true | true | private void CreateRouteTable() {
//Dijkstra!
int routingTableSize =ServerRouter.getBiggestSimpleID();
if(routingTableSize == 0) {
// routingTableSize=SimpleServiceLocator.routerManager.getRouterCount();
routingTableSize=SharedLSADatabase.size(); // deliberatly ignoring concurrent access, either the old or the version of the size will work, this is just an approximate number.
}
/** same info as above, but sorted by distance -- sorting is implicit, because Dijkstra finds the closest routes first.**/
ArrayList<SearchNode> routeCosts = new ArrayList<SearchNode>(routingTableSize);
ArrayList<ILogisticsPowerProvider> powerTable = new ArrayList<ILogisticsPowerProvider>(_powerAdjacent);
//space and time inefficient, a bitset with 3 bits per node would save a lot but makes the main iteration look like a complete mess
Vector<EnumSet<PipeRoutingConnectionType>> closedSet = new Vector<EnumSet<PipeRoutingConnectionType>>(getBiggestSimpleID());
closedSet.setSize(getBiggestSimpleID());
closedSet.set(this.getSimpleID(), EnumSet.allOf(PipeRoutingConnectionType.class));
/** The total cost for the candidate route **/
PriorityQueue<SearchNode> candidatesCost = new PriorityQueue<SearchNode>((int) Math.sqrt(routingTableSize)); // sqrt nodes is a good guess for the total number of candidate nodes at once.
//Init candidates
// the shortest way to go to an adjacent item is the adjacent item.
for (Entry<RoutedPipe, ExitRoute> pipe : _adjacent.entrySet()){
ExitRoute currentE = pipe.getValue();
//currentE.connectionDetails.retainAll(blocksPower);
candidatesCost.add(new SearchNode(pipe.getKey().getRouter(currentE.insertOrientation), currentE.metric, pipe.getValue().connectionDetails.clone(), pipe.getKey().getRouter(currentE.insertOrientation)));
//objectMapped.set(pipe.getKey().getSimpleID(),true);
}
SharedLSADatabasereadLock.lock(); // readlock, not inside the while - too costly to aquire, then release.
SearchNode lowestCostNode;
while ((lowestCostNode=candidatesCost.poll()) != null){
if(!lowestCostNode.hasActivePipe())
continue;
//if the node does not have any flags not in the closed set, check it
EnumSet<PipeRoutingConnectionType> lowestCostClosedFlags = closedSet.get(lowestCostNode.node.getSimpleID());
if(lowestCostClosedFlags == null)
lowestCostClosedFlags = EnumSet.noneOf(PipeRoutingConnectionType.class);
if(lowestCostClosedFlags.containsAll(lowestCostNode.getFlags()))
continue;
//Add new candidates from the newly approved route
LSA lsa = SharedLSADatabase.get(lowestCostNode.node.getSimpleID());
if(lsa == null) {
SharedLSADatabasereadLock.unlock();
lowestCostNode.removeFlags(lowestCostClosedFlags);
lowestCostClosedFlags.addAll(lowestCostNode.getFlags());
if(lowestCostNode.containsFlag(PipeRoutingConnectionType.canRouteTo) || lowestCostNode.containsFlag(PipeRoutingConnectionType.canRequestFrom))
routeCosts.add(lowestCostNode);
closedSet.set(lowestCostNode.node.getSimpleID(),lowestCostClosedFlags);
continue;
}
if(lowestCostNode.containsFlag(PipeRoutingConnectionType.canPowerFrom)) {
if(lsa.power.isEmpty() == false) {
if(!lowestCostClosedFlags.contains(PipeRoutingConnectionType.canPowerFrom)) {
powerTable.addAll(lsa.power);
}
}
}
Iterator<Entry<IRouter, Pair<Integer, EnumSet<PipeRoutingConnectionType>>>> it = lsa.neighboursWithMetric.entrySet().iterator();
while (it.hasNext()) {
Entry<IRouter, Pair<Integer, EnumSet<PipeRoutingConnectionType>>> newCandidate = (Entry<IRouter, Pair<Integer, EnumSet<PipeRoutingConnectionType>>>)it.next();
EnumSet<PipeRoutingConnectionType> newCandidateClosedFlags = closedSet.get(newCandidate.getKey().getSimpleID());
if(newCandidateClosedFlags == null)
newCandidateClosedFlags = EnumSet.noneOf(PipeRoutingConnectionType.class);
if(newCandidateClosedFlags.containsAll(newCandidate.getValue().getValue2()))
continue;
int candidateCost = lowestCostNode.distance + newCandidate.getValue().getValue1();
EnumSet<PipeRoutingConnectionType> newCT = lowestCostNode.getFlags();
newCT.retainAll(newCandidate.getValue().getValue2());
if(!newCT.isEmpty())
candidatesCost.add(new SearchNode(newCandidate.getKey(), candidateCost, newCT, lowestCostNode.root));
}
SharedLSADatabasereadLock.unlock();
lowestCostNode.removeFlags(lowestCostClosedFlags);
lowestCostClosedFlags.addAll(lowestCostNode.getFlags());
if(lowestCostNode.containsFlag(PipeRoutingConnectionType.canRouteTo) || lowestCostNode.containsFlag(PipeRoutingConnectionType.canRequestFrom))
routeCosts.add(lowestCostNode);
closedSet.set(lowestCostNode.node.getSimpleID(),lowestCostClosedFlags);
}
SharedLSADatabasereadLock.unlock();
//Build route table
ArrayList<Pair<ForgeDirection, ForgeDirection>> routeTable = new ArrayList<Pair<ForgeDirection,ForgeDirection>>(ServerRouter.getBiggestSimpleID()+1);
while (this.getSimpleID() >= routeTable.size())
routeTable.add(null);
routeTable.set(this.getSimpleID(), new Pair<ForgeDirection,ForgeDirection>(ForgeDirection.UNKNOWN, ForgeDirection.UNKNOWN));
for (SearchNode node : routeCosts)
{
if(!node.containsFlag(PipeRoutingConnectionType.canRouteTo))
continue;
IRouter firstHop = node.root;
if (firstHop == null) { //this should never happen?!?
while (node.node.getSimpleID() >= routeTable.size())
routeTable.add(null);
routeTable.set(node.node.getSimpleID(), new Pair<ForgeDirection,ForgeDirection>(ForgeDirection.UNKNOWN, ForgeDirection.UNKNOWN));
continue;
}
ExitRoute hop=_adjacentRouter.get(firstHop);
if (hop == null){
continue;
}
while (node.node.getSimpleID() >= routeTable.size())
routeTable.add(null);
routeTable.set(node.node.getSimpleID(), new Pair<ForgeDirection,ForgeDirection>(hop.exitOrientation, hop.insertOrientation));
}
_powerTable = powerTable;
_routeTable = routeTable;
_routeCosts = routeCosts;
}
| private void CreateRouteTable() {
//Dijkstra!
int routingTableSize =ServerRouter.getBiggestSimpleID();
if(routingTableSize == 0) {
// routingTableSize=SimpleServiceLocator.routerManager.getRouterCount();
routingTableSize=SharedLSADatabase.size(); // deliberatly ignoring concurrent access, either the old or the version of the size will work, this is just an approximate number.
}
/** same info as above, but sorted by distance -- sorting is implicit, because Dijkstra finds the closest routes first.**/
ArrayList<SearchNode> routeCosts = new ArrayList<SearchNode>(routingTableSize);
ArrayList<ILogisticsPowerProvider> powerTable = new ArrayList<ILogisticsPowerProvider>(_powerAdjacent);
//space and time inefficient, a bitset with 3 bits per node would save a lot but makes the main iteration look like a complete mess
Vector<EnumSet<PipeRoutingConnectionType>> closedSet = new Vector<EnumSet<PipeRoutingConnectionType>>(getBiggestSimpleID());
closedSet.setSize(getBiggestSimpleID());
closedSet.set(this.getSimpleID(), EnumSet.allOf(PipeRoutingConnectionType.class));
/** The total cost for the candidate route **/
PriorityQueue<SearchNode> candidatesCost = new PriorityQueue<SearchNode>((int) Math.sqrt(routingTableSize)); // sqrt nodes is a good guess for the total number of candidate nodes at once.
//Init candidates
// the shortest way to go to an adjacent item is the adjacent item.
for (Entry<RoutedPipe, ExitRoute> pipe : _adjacent.entrySet()){
ExitRoute currentE = pipe.getValue();
//currentE.connectionDetails.retainAll(blocksPower);
candidatesCost.add(new SearchNode(pipe.getKey().getRouter(currentE.insertOrientation), currentE.metric, pipe.getValue().connectionDetails.clone(), pipe.getKey().getRouter(currentE.insertOrientation)));
//objectMapped.set(pipe.getKey().getSimpleID(),true);
}
SharedLSADatabasereadLock.lock(); // readlock, not inside the while - too costly to aquire, then release.
SearchNode lowestCostNode;
while ((lowestCostNode=candidatesCost.poll()) != null){
if(!lowestCostNode.hasActivePipe())
continue;
//if the node does not have any flags not in the closed set, check it
EnumSet<PipeRoutingConnectionType> lowestCostClosedFlags = closedSet.get(lowestCostNode.node.getSimpleID());
if(lowestCostClosedFlags == null)
lowestCostClosedFlags = EnumSet.noneOf(PipeRoutingConnectionType.class);
if(lowestCostClosedFlags.containsAll(lowestCostNode.getFlags()))
continue;
//Add new candidates from the newly approved route
LSA lsa = SharedLSADatabase.get(lowestCostNode.node.getSimpleID());
if(lsa == null) {
SharedLSADatabasereadLock.unlock();
lowestCostNode.removeFlags(lowestCostClosedFlags);
lowestCostClosedFlags.addAll(lowestCostNode.getFlags());
if(lowestCostNode.containsFlag(PipeRoutingConnectionType.canRouteTo) || lowestCostNode.containsFlag(PipeRoutingConnectionType.canRequestFrom))
routeCosts.add(lowestCostNode);
closedSet.set(lowestCostNode.node.getSimpleID(),lowestCostClosedFlags);
continue;
}
if(lowestCostNode.containsFlag(PipeRoutingConnectionType.canPowerFrom)) {
if(lsa.power.isEmpty() == false) {
if(!lowestCostClosedFlags.contains(PipeRoutingConnectionType.canPowerFrom)) {
powerTable.addAll(lsa.power);
}
}
}
Iterator<Entry<IRouter, Pair<Integer, EnumSet<PipeRoutingConnectionType>>>> it = lsa.neighboursWithMetric.entrySet().iterator();
while (it.hasNext()) {
Entry<IRouter, Pair<Integer, EnumSet<PipeRoutingConnectionType>>> newCandidate = (Entry<IRouter, Pair<Integer, EnumSet<PipeRoutingConnectionType>>>)it.next();
EnumSet<PipeRoutingConnectionType> newCandidateClosedFlags = closedSet.get(newCandidate.getKey().getSimpleID());
if(newCandidateClosedFlags == null)
newCandidateClosedFlags = EnumSet.noneOf(PipeRoutingConnectionType.class);
if(newCandidateClosedFlags.containsAll(newCandidate.getValue().getValue2()))
continue;
int candidateCost = lowestCostNode.distance + newCandidate.getValue().getValue1();
EnumSet<PipeRoutingConnectionType> newCT = lowestCostNode.getFlags();
newCT.retainAll(newCandidate.getValue().getValue2());
if(!newCT.isEmpty())
candidatesCost.add(new SearchNode(newCandidate.getKey(), candidateCost, newCT, lowestCostNode.root));
}
lowestCostNode.removeFlags(lowestCostClosedFlags);
lowestCostClosedFlags.addAll(lowestCostNode.getFlags());
if(lowestCostNode.containsFlag(PipeRoutingConnectionType.canRouteTo) || lowestCostNode.containsFlag(PipeRoutingConnectionType.canRequestFrom))
routeCosts.add(lowestCostNode);
closedSet.set(lowestCostNode.node.getSimpleID(),lowestCostClosedFlags);
}
SharedLSADatabasereadLock.unlock();
//Build route table
ArrayList<Pair<ForgeDirection, ForgeDirection>> routeTable = new ArrayList<Pair<ForgeDirection,ForgeDirection>>(ServerRouter.getBiggestSimpleID()+1);
while (this.getSimpleID() >= routeTable.size())
routeTable.add(null);
routeTable.set(this.getSimpleID(), new Pair<ForgeDirection,ForgeDirection>(ForgeDirection.UNKNOWN, ForgeDirection.UNKNOWN));
for (SearchNode node : routeCosts)
{
if(!node.containsFlag(PipeRoutingConnectionType.canRouteTo))
continue;
IRouter firstHop = node.root;
if (firstHop == null) { //this should never happen?!?
while (node.node.getSimpleID() >= routeTable.size())
routeTable.add(null);
routeTable.set(node.node.getSimpleID(), new Pair<ForgeDirection,ForgeDirection>(ForgeDirection.UNKNOWN, ForgeDirection.UNKNOWN));
continue;
}
ExitRoute hop=_adjacentRouter.get(firstHop);
if (hop == null){
continue;
}
while (node.node.getSimpleID() >= routeTable.size())
routeTable.add(null);
routeTable.set(node.node.getSimpleID(), new Pair<ForgeDirection,ForgeDirection>(hop.exitOrientation, hop.insertOrientation));
}
_powerTable = powerTable;
_routeTable = routeTable;
_routeCosts = routeCosts;
}
|
diff --git a/TFC_Shared/src/TFC/Items/ItemMeltedMetal.java b/TFC_Shared/src/TFC/Items/ItemMeltedMetal.java
index 55049657b..f166d3e41 100644
--- a/TFC_Shared/src/TFC/Items/ItemMeltedMetal.java
+++ b/TFC_Shared/src/TFC/Items/ItemMeltedMetal.java
@@ -1,136 +1,140 @@
package TFC.Items;
import java.util.List;
import net.minecraft.client.renderer.texture.IconRegister;
import net.minecraft.entity.Entity;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.world.World;
import TFC.Reference;
import TFC.TerraFirmaCraft;
import TFC.API.TFCTabs;
import TFC.API.Enums.EnumSize;
import TFC.API.Enums.EnumWeight;
import TFC.API.Util.StringUtil;
import TFC.Core.TFC_Core;
import TFC.Core.TFC_ItemHeat;
import TFC.Core.Player.PlayerInfo;
import TFC.Core.Player.PlayerManagerTFC;
public class ItemMeltedMetal extends ItemTerra
{
public ItemMeltedMetal(int i)
{
super(i);
setMaxDamage(101);
setCreativeTab(TFCTabs.TFCMaterials);
this.setFolder("ingots/");
}
@Override
public void registerIcons(IconRegister registerer)
{
this.itemIcon = registerer.registerIcon(Reference.ModID + ":" + textureFolder+this.getUnlocalizedName().replace("item.", "").replace("Weak ", "").replace("HC ", ""));
}
@Override
public EnumWeight getWeight()
{
return EnumWeight.HEAVY;
}
@Override
public EnumSize getSize()
{
return EnumSize.SMALL;
}
@Override
public boolean canStack()
{
return false;
}
@Override
public void addInformation(ItemStack is, EntityPlayer player, List arraylist, boolean flag)
{
super.addInformation(is, player, arraylist, flag);
}
@Override
public void addItemInformation(ItemStack is, EntityPlayer player, List arraylist)
{
if(is.getItemDamage() > 1) {
arraylist.add(StringUtil.localize("gui.MeltedMetal.NotFull"));
}
}
@Override
public void onUpdate(ItemStack is, World world, Entity entity, int i, boolean isSelected)
{
super.onUpdate(is,world,entity,i,isSelected);
if (is.hasTagCompound())
{
NBTTagCompound stackTagCompound = is.getTagCompound();
//System.out.println(stackTagCompound.getFloat("temperature"));
if(stackTagCompound.hasKey("temperature") && stackTagCompound.getFloat("temperature") >= TFC_ItemHeat.getMeltingPoint(is))
{
if(is.getItemDamage()==0){
is.setItemDamage(1);
//System.out.println(is.getItemDamage());
}
}
else if(is.getItemDamage()==1){
is.setItemDamage(0);
//System.out.println(is.getItemDamage());
}
}
+ else if(is.getItemDamage()==1){
+ is.setItemDamage(0);
+ //System.out.println(is.getItemDamage());
+ }
}
@Override
public boolean isDamaged(ItemStack stack)
{
return stack.getItemDamage() > 1;
}
@Override
public void addExtraInformation(ItemStack is, EntityPlayer player, List arraylist)
{
if(TFC_ItemHeat.getIsLiquid(is))
{
if (TFC_Core.showExtraInformation())
{
arraylist.add(StringUtil.localize("gui.Help"));
arraylist.add(StringUtil.localize("gui.MeltedMetal.Inst0"));
}
else
{
arraylist.add(StringUtil.localize("gui.ShowHelp"));
}
}
}
@Override
public ItemStack onItemRightClick(ItemStack itemstack, World world, EntityPlayer entityplayer)
{
if(itemstack.stackSize <= 0) {
itemstack.stackSize = 1;
}
if(TFC_ItemHeat.getIsLiquid(itemstack))
{
PlayerInfo pi = PlayerManagerTFC.getInstance().getPlayerInfoFromPlayer(entityplayer);
pi.specialCraftingType = itemstack.copy();
entityplayer.inventory.setInventorySlotContents(entityplayer.inventory.currentItem, null);
entityplayer.openGui(TerraFirmaCraft.instance, 38, world, (int)entityplayer.posX, (int)entityplayer.posY, (int)entityplayer.posZ);
}
return itemstack;
}
}
| true | true | public void onUpdate(ItemStack is, World world, Entity entity, int i, boolean isSelected)
{
super.onUpdate(is,world,entity,i,isSelected);
if (is.hasTagCompound())
{
NBTTagCompound stackTagCompound = is.getTagCompound();
//System.out.println(stackTagCompound.getFloat("temperature"));
if(stackTagCompound.hasKey("temperature") && stackTagCompound.getFloat("temperature") >= TFC_ItemHeat.getMeltingPoint(is))
{
if(is.getItemDamage()==0){
is.setItemDamage(1);
//System.out.println(is.getItemDamage());
}
}
else if(is.getItemDamage()==1){
is.setItemDamage(0);
//System.out.println(is.getItemDamage());
}
}
}
| public void onUpdate(ItemStack is, World world, Entity entity, int i, boolean isSelected)
{
super.onUpdate(is,world,entity,i,isSelected);
if (is.hasTagCompound())
{
NBTTagCompound stackTagCompound = is.getTagCompound();
//System.out.println(stackTagCompound.getFloat("temperature"));
if(stackTagCompound.hasKey("temperature") && stackTagCompound.getFloat("temperature") >= TFC_ItemHeat.getMeltingPoint(is))
{
if(is.getItemDamage()==0){
is.setItemDamage(1);
//System.out.println(is.getItemDamage());
}
}
else if(is.getItemDamage()==1){
is.setItemDamage(0);
//System.out.println(is.getItemDamage());
}
}
else if(is.getItemDamage()==1){
is.setItemDamage(0);
//System.out.println(is.getItemDamage());
}
}
|
diff --git a/src/SQLParser.java b/src/SQLParser.java
index a6e38d2..62efb76 100644
--- a/src/SQLParser.java
+++ b/src/SQLParser.java
@@ -1,138 +1,140 @@
import java.util.Arrays;
import java.util.Scanner;
import database.Database;
import java.util.ArrayList;
public class SQLParser
{
private Database DB;
public SQLParser(Database DB) {
this.DB = DB;
}
// the main method only has contents for testing the parser, the final version should be empty
public static void main(String args[]) {
Database testDB = new Database();
SQLParser Parser = new SQLParser(testDB);
String test = Parser.query("INSERT INTO courses VALUES (COP3504, Advanced Programming Fundamentals, Horton)");
String test2 = Parser.query("INSERT INTO courses (course, name, instructor) VALUES (COP3504, Advanced Programming Fundamentals, Horton)");
}
public String query(String query) {
// queryType is set depending on what kind of query is given (e.g. INSERT, DELETE, etc)
// INSERT = 0
// SELECT = 1
// DELETE = 2
// UPDATE = 3
int queryType = -1;
// this is just a check to see if it's the first word or not, so we don't have to check the string every time to see if it's UPDATE, INSERT, etc
int wordNumber = 0;
// this holds the name of the table, can be either courses, students, or grades
String tableName = "";
// ArrayList of Strings to hold the list of values provided in the query
ArrayList<String> valueList = new ArrayList<String>();
// ArrayList of Strings to hold the list of columns provided in the query
ArrayList<String> columnList = new ArrayList<String>();
Scanner parser = new Scanner(query);
String ret = "";
String in = "";
while(parser.hasNext()) {
in = parser.next();
++wordNumber;
if(wordNumber == 1) {
if(in.equalsIgnoreCase("INSERT")) {
queryType = 0;
}
else if(in.equalsIgnoreCase("SELECT")) {
queryType = 1;
}
else if(in.equalsIgnoreCase("DELETE")) {
queryType = 2;
}
else if(in.equalsIgnoreCase("UPDATE")) {
queryType = 3;
}
else {
throw new IllegalArgumentException("First word must be INSERT, SELECT, DELETE, or UPDATE");
}
}
if(queryType == 0 && wordNumber == 3) {
if(in.equalsIgnoreCase("courses") || in.equalsIgnoreCase("students") || in.equalsIgnoreCase("grades")) {
tableName = in;
}
else {
throw new IllegalArgumentException("Invalid Table Name");
}
}
if(queryType == 0 && wordNumber == 4) {
if(in.equalsIgnoreCase("VALUES")) {
String values = "";
while(!(in.contains(")"))) {
++wordNumber;
in = parser.next();
values += in;
}
Scanner subScanner = new Scanner(values.substring(1, values.length() - 1)).useDelimiter(", *");
while(subScanner.hasNext()) {
valueList.add(subScanner.next());
}
System.out.println(tableName);
System.out.println(valueList.toString());
DB.insert(tableName, valueList);
subScanner.close();
}
else {
String columns = "";
columns += in;
while(!(in.contains(")"))) {
++wordNumber;
in = parser.next();
columns += in;
}
Scanner subScanner = new Scanner(columns.substring(1, columns.length() - 1)).useDelimiter(", *");
while(subScanner.hasNext()) {
columnList.add(subScanner.next());
}
in = parser.next();
String values = "";
while(!(in.contains(")"))) {
++wordNumber;
in = parser.next();
values += in;
}
subScanner = new Scanner(values.substring(1, values.length() - 1)).useDelimiter(", *");
while(subScanner.hasNext()) {
valueList.add(subScanner.next());
}
DB.insert(tableName, columnList, valueList);
subScanner.close();
}
}
if(queryType == 2 && wordNumber == 3)
{
if(in.equalsIgnoreCase("courses") || in.equalsIgnoreCase("students") || in.equalsIgnoreCase("grades")) {
tableName = in;
}
else {
throw new IllegalArgumentException("Invalid Table Name");
}
}
if(queryType == 2 && wordNumber == 4)
{
if(in.equalsIgnoreCase("WHERE"))
{
// Handle where clause
}
else
- ;// Delete all records in table
+ {
+ DB.delete(tableName); // Delete all records in table
+ }
}
}
parser.close();
return ret;
}
}
| true | true | public String query(String query) {
// queryType is set depending on what kind of query is given (e.g. INSERT, DELETE, etc)
// INSERT = 0
// SELECT = 1
// DELETE = 2
// UPDATE = 3
int queryType = -1;
// this is just a check to see if it's the first word or not, so we don't have to check the string every time to see if it's UPDATE, INSERT, etc
int wordNumber = 0;
// this holds the name of the table, can be either courses, students, or grades
String tableName = "";
// ArrayList of Strings to hold the list of values provided in the query
ArrayList<String> valueList = new ArrayList<String>();
// ArrayList of Strings to hold the list of columns provided in the query
ArrayList<String> columnList = new ArrayList<String>();
Scanner parser = new Scanner(query);
String ret = "";
String in = "";
while(parser.hasNext()) {
in = parser.next();
++wordNumber;
if(wordNumber == 1) {
if(in.equalsIgnoreCase("INSERT")) {
queryType = 0;
}
else if(in.equalsIgnoreCase("SELECT")) {
queryType = 1;
}
else if(in.equalsIgnoreCase("DELETE")) {
queryType = 2;
}
else if(in.equalsIgnoreCase("UPDATE")) {
queryType = 3;
}
else {
throw new IllegalArgumentException("First word must be INSERT, SELECT, DELETE, or UPDATE");
}
}
if(queryType == 0 && wordNumber == 3) {
if(in.equalsIgnoreCase("courses") || in.equalsIgnoreCase("students") || in.equalsIgnoreCase("grades")) {
tableName = in;
}
else {
throw new IllegalArgumentException("Invalid Table Name");
}
}
if(queryType == 0 && wordNumber == 4) {
if(in.equalsIgnoreCase("VALUES")) {
String values = "";
while(!(in.contains(")"))) {
++wordNumber;
in = parser.next();
values += in;
}
Scanner subScanner = new Scanner(values.substring(1, values.length() - 1)).useDelimiter(", *");
while(subScanner.hasNext()) {
valueList.add(subScanner.next());
}
System.out.println(tableName);
System.out.println(valueList.toString());
DB.insert(tableName, valueList);
subScanner.close();
}
else {
String columns = "";
columns += in;
while(!(in.contains(")"))) {
++wordNumber;
in = parser.next();
columns += in;
}
Scanner subScanner = new Scanner(columns.substring(1, columns.length() - 1)).useDelimiter(", *");
while(subScanner.hasNext()) {
columnList.add(subScanner.next());
}
in = parser.next();
String values = "";
while(!(in.contains(")"))) {
++wordNumber;
in = parser.next();
values += in;
}
subScanner = new Scanner(values.substring(1, values.length() - 1)).useDelimiter(", *");
while(subScanner.hasNext()) {
valueList.add(subScanner.next());
}
DB.insert(tableName, columnList, valueList);
subScanner.close();
}
}
if(queryType == 2 && wordNumber == 3)
{
if(in.equalsIgnoreCase("courses") || in.equalsIgnoreCase("students") || in.equalsIgnoreCase("grades")) {
tableName = in;
}
else {
throw new IllegalArgumentException("Invalid Table Name");
}
}
if(queryType == 2 && wordNumber == 4)
{
if(in.equalsIgnoreCase("WHERE"))
{
// Handle where clause
}
else
;// Delete all records in table
}
}
parser.close();
return ret;
}
| public String query(String query) {
// queryType is set depending on what kind of query is given (e.g. INSERT, DELETE, etc)
// INSERT = 0
// SELECT = 1
// DELETE = 2
// UPDATE = 3
int queryType = -1;
// this is just a check to see if it's the first word or not, so we don't have to check the string every time to see if it's UPDATE, INSERT, etc
int wordNumber = 0;
// this holds the name of the table, can be either courses, students, or grades
String tableName = "";
// ArrayList of Strings to hold the list of values provided in the query
ArrayList<String> valueList = new ArrayList<String>();
// ArrayList of Strings to hold the list of columns provided in the query
ArrayList<String> columnList = new ArrayList<String>();
Scanner parser = new Scanner(query);
String ret = "";
String in = "";
while(parser.hasNext()) {
in = parser.next();
++wordNumber;
if(wordNumber == 1) {
if(in.equalsIgnoreCase("INSERT")) {
queryType = 0;
}
else if(in.equalsIgnoreCase("SELECT")) {
queryType = 1;
}
else if(in.equalsIgnoreCase("DELETE")) {
queryType = 2;
}
else if(in.equalsIgnoreCase("UPDATE")) {
queryType = 3;
}
else {
throw new IllegalArgumentException("First word must be INSERT, SELECT, DELETE, or UPDATE");
}
}
if(queryType == 0 && wordNumber == 3) {
if(in.equalsIgnoreCase("courses") || in.equalsIgnoreCase("students") || in.equalsIgnoreCase("grades")) {
tableName = in;
}
else {
throw new IllegalArgumentException("Invalid Table Name");
}
}
if(queryType == 0 && wordNumber == 4) {
if(in.equalsIgnoreCase("VALUES")) {
String values = "";
while(!(in.contains(")"))) {
++wordNumber;
in = parser.next();
values += in;
}
Scanner subScanner = new Scanner(values.substring(1, values.length() - 1)).useDelimiter(", *");
while(subScanner.hasNext()) {
valueList.add(subScanner.next());
}
System.out.println(tableName);
System.out.println(valueList.toString());
DB.insert(tableName, valueList);
subScanner.close();
}
else {
String columns = "";
columns += in;
while(!(in.contains(")"))) {
++wordNumber;
in = parser.next();
columns += in;
}
Scanner subScanner = new Scanner(columns.substring(1, columns.length() - 1)).useDelimiter(", *");
while(subScanner.hasNext()) {
columnList.add(subScanner.next());
}
in = parser.next();
String values = "";
while(!(in.contains(")"))) {
++wordNumber;
in = parser.next();
values += in;
}
subScanner = new Scanner(values.substring(1, values.length() - 1)).useDelimiter(", *");
while(subScanner.hasNext()) {
valueList.add(subScanner.next());
}
DB.insert(tableName, columnList, valueList);
subScanner.close();
}
}
if(queryType == 2 && wordNumber == 3)
{
if(in.equalsIgnoreCase("courses") || in.equalsIgnoreCase("students") || in.equalsIgnoreCase("grades")) {
tableName = in;
}
else {
throw new IllegalArgumentException("Invalid Table Name");
}
}
if(queryType == 2 && wordNumber == 4)
{
if(in.equalsIgnoreCase("WHERE"))
{
// Handle where clause
}
else
{
DB.delete(tableName); // Delete all records in table
}
}
}
parser.close();
return ret;
}
|
diff --git a/commons/src/main/java/org/wikimedia/commons/UploadService.java b/commons/src/main/java/org/wikimedia/commons/UploadService.java
index cfa25ac3..dfc0c68b 100644
--- a/commons/src/main/java/org/wikimedia/commons/UploadService.java
+++ b/commons/src/main/java/org/wikimedia/commons/UploadService.java
@@ -1,293 +1,293 @@
package org.wikimedia.commons;
import java.io.*;
import java.text.*;
import java.util.Date;
import android.support.v4.content.LocalBroadcastManager;
import org.mediawiki.api.*;
import org.wikimedia.commons.contributions.Contribution;
import org.wikimedia.commons.contributions.ContributionsActivity;
import org.wikimedia.commons.contributions.ContributionsContentProvider;
import in.yuvi.http.fluent.ProgressListener;
import android.app.*;
import android.content.*;
import android.database.Cursor;
import android.os.*;
import android.provider.MediaStore;
import android.support.v4.app.NotificationCompat;
import android.util.Log;
import android.widget.RemoteViews;
import android.widget.Toast;
import android.net.*;
public class UploadService extends IntentService {
private static final String EXTRA_PREFIX = "org.wikimedia.commons.upload";
public static final String INTENT_CONTRIBUTION_STATE_CHANGED = EXTRA_PREFIX + ".progress";
public static final String EXTRA_CONTRIBUTION_ID = EXTRA_PREFIX + ".filename";
public static final String EXTRA_TRANSFERRED_BYTES = EXTRA_PREFIX + ".progress.transferred";
public static final String EXTRA_MEDIA_URI = EXTRA_PREFIX + ".uri";
public static final String EXTRA_TARGET_FILENAME = EXTRA_PREFIX + ".filename";
public static final String EXTRA_DESCRIPTION = EXTRA_PREFIX + ".description";
public static final String EXTRA_EDIT_SUMMARY = EXTRA_PREFIX + ".summary";
public static final String EXTRA_MIMETYPE = EXTRA_PREFIX + ".mimetype";
private NotificationManager notificationManager;
private LocalBroadcastManager localBroadcastManager;
private ContentProviderClient contributionsProviderClient;
private CommonsApplication app;
private Notification curProgressNotification;
private int toUpload;
public UploadService(String name) {
super(name);
}
public UploadService() {
super("UploadService");
}
// DO NOT HAVE NOTIFICATION ID OF 0 FOR ANYTHING
// See http://stackoverflow.com/questions/8725909/startforeground-does-not-show-my-notification
// Seriously, Android?
public static final int NOTIFICATION_DOWNLOAD_IN_PROGRESS = 1;
public static final int NOTIFICATION_DOWNLOAD_COMPLETE = 2;
public static final int NOTIFICATION_UPLOAD_FAILED = 3;
private class NotificationUpdateProgressListener implements ProgressListener {
Notification curNotification;
String notificationTag;
boolean notificationTitleChanged;
Contribution contribution;
String notificationProgressTitle;
String notificationFinishingTitle;
public NotificationUpdateProgressListener(Notification curNotification, String notificationTag, String notificationProgressTitle, String notificationFinishingTitle, Contribution contribution) {
this.curNotification = curNotification;
this.notificationTag = notificationTag;
this.notificationProgressTitle = notificationProgressTitle;
this.notificationFinishingTitle = notificationFinishingTitle;
this.contribution = contribution;
}
@Override
public void onProgress(long transferred, long total) {
Log.d("Commons", String.format("Uploaded %d of %d", transferred, total));
RemoteViews curView = curNotification.contentView;
if(!notificationTitleChanged) {
curView.setTextViewText(R.id.uploadNotificationTitle, notificationProgressTitle);
if(toUpload != 1) {
curView.setTextViewText(R.id.uploadNotificationsCount, String.format(getString(R.string.uploads_pending_notification_indicator), toUpload));
Log.d("Commons", String.format("%d uploads left", toUpload));
}
notificationTitleChanged = true;
contribution.setState(Contribution.STATE_IN_PROGRESS);
contribution.save();
}
if(transferred == total) {
// Completed!
curView.setTextViewText(R.id.uploadNotificationTitle, notificationFinishingTitle);
notificationManager.notify(NOTIFICATION_DOWNLOAD_IN_PROGRESS, curNotification);
} else {
curNotification.contentView.setProgressBar(R.id.uploadNotificationProgress, 100, (int) (((double) transferred / (double) total) * 100), false);
notificationManager.notify(NOTIFICATION_DOWNLOAD_IN_PROGRESS, curNotification);
Intent mediaUploadProgressIntent = new Intent(INTENT_CONTRIBUTION_STATE_CHANGED);
// mediaUploadProgressIntent.putExtra(EXTRA_MEDIA contribution);
mediaUploadProgressIntent.putExtra(EXTRA_TRANSFERRED_BYTES, transferred);
localBroadcastManager.sendBroadcast(mediaUploadProgressIntent);
}
}
}
@Override
public void onDestroy() {
super.onDestroy();
contributionsProviderClient.release();
Log.d("Commons", "ZOMG I AM BEING KILLED HALP!");
}
@Override
public void onCreate() {
super.onCreate();
notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
localBroadcastManager = LocalBroadcastManager.getInstance(this);
app = (CommonsApplication) this.getApplicationContext();
contributionsProviderClient = this.getContentResolver().acquireContentProviderClient(ContributionsContentProvider.AUTHORITY);
}
private String getRealPathFromURI(Uri contentUri) {
String[] proj = {MediaStore.Images.Media.DATA};
CursorLoader loader = new CursorLoader(this, contentUri, proj, null, null, null);
Cursor cursor = loader.loadInBackground();
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}
private Contribution mediaFromIntent(Intent intent) {
Bundle extras = intent.getExtras();
Uri mediaUri = (Uri) extras.getParcelable(EXTRA_MEDIA_URI);
String filename = intent.getStringExtra(EXTRA_TARGET_FILENAME);
String description = intent.getStringExtra(EXTRA_DESCRIPTION);
String editSummary = intent.getStringExtra(EXTRA_EDIT_SUMMARY);
String mimeType = intent.getStringExtra(EXTRA_MIMETYPE);
Date dateCreated = null;
Long length = null;
try {
length = this.getContentResolver().openAssetFileDescriptor(mediaUri, "r").getLength();
} catch(FileNotFoundException e) {
throw new RuntimeException(e);
}
Log.d("Commons", "MimeType is " + mimeType);
if(mimeType.startsWith("image/")) {
Cursor cursor = this.getContentResolver().query(mediaUri,
new String[]{MediaStore.Images.ImageColumns.DATE_TAKEN}, null, null, null);
if(cursor != null && cursor.getCount() != 0) {
cursor.moveToFirst();
dateCreated = new Date(cursor.getLong(0));
} // FIXME: Alternate way of setting dateCreated if this data is not found
} /* else if (mimeType.startsWith("audio/")) {
Removed Audio implementationf or now
} */
Contribution contribution = new Contribution(mediaUri, null, filename, description, null, length, dateCreated, null, app.getCurrentAccount().name, editSummary);
return contribution;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
toUpload++;
if(curProgressNotification != null && toUpload != 1) {
curProgressNotification.contentView.setTextViewText(R.id.uploadNotificationsCount, String.format(getString(R.string.uploads_pending_notification_indicator), toUpload));
Log.d("Commons", String.format("%d uploads left", toUpload));
notificationManager.notify(NOTIFICATION_DOWNLOAD_IN_PROGRESS, curProgressNotification);
}
Contribution contribution = mediaFromIntent(intent);
contribution.setState(Contribution.STATE_QUEUED);
contribution.setContentProviderClient(contributionsProviderClient);
contribution.save();
Intent mediaUploadQueuedIntent = new Intent();
mediaUploadQueuedIntent.putExtra("dummy-data", contribution); // FIXME: Move to separate handler, do not inherit from IntentService
localBroadcastManager.sendBroadcast(mediaUploadQueuedIntent);
return super.onStartCommand(mediaUploadQueuedIntent, flags, startId);
}
@Override
protected void onHandleIntent(Intent intent) {
MWApi api = app.getApi();
ApiResult result;
RemoteViews notificationView;
Contribution contribution;
InputStream file = null;
contribution = (Contribution) intent.getSerializableExtra("dummy-data");
String notificationTag = contribution.getLocalUri().toString();
try {
file = this.getContentResolver().openInputStream(contribution.getLocalUri());
} catch(FileNotFoundException e) {
throw new RuntimeException(e);
}
notificationView = new RemoteViews(getPackageName(), R.layout.layout_upload_progress);
notificationView.setTextViewText(R.id.uploadNotificationTitle, String.format(getString(R.string.upload_progress_notification_title_start), contribution.getFilename()));
notificationView.setProgressBar(R.id.uploadNotificationProgress, 100, 0, false);
Log.d("Commons", "Before execution!");
curProgressNotification = new NotificationCompat.Builder(this).setAutoCancel(true)
.setSmallIcon(R.drawable.ic_launcher)
.setAutoCancel(true)
.setContent(notificationView)
.setOngoing(true)
.setContentIntent(PendingIntent.getActivity(this, 0, new Intent(this, ContributionsActivity.class), 0))
.setTicker(String.format(getString(R.string.upload_progress_notification_title_in_progress), contribution.getFilename()))
.getNotification();
this.startForeground(NOTIFICATION_DOWNLOAD_IN_PROGRESS, curProgressNotification);
Log.d("Commons", "Just before");
try {
if(!api.validateLogin()) {
// Need to revalidate!
if(app.revalidateAuthToken()) {
Log.d("Commons", "Successfully revalidated token!");
} else {
Log.d("Commons", "Unable to revalidate :(");
// TODO: Put up a new notification, ask them to re-login
stopForeground(true);
Toast failureToast = Toast.makeText(this, R.string.authentication_failed, Toast.LENGTH_LONG);
failureToast.show();
return;
}
}
NotificationUpdateProgressListener notificationUpdater = new NotificationUpdateProgressListener(curProgressNotification, notificationTag,
String.format(getString(R.string.upload_progress_notification_title_in_progress), contribution.getFilename()),
String.format(getString(R.string.upload_progress_notification_title_finishing), contribution.getFilename()),
contribution
);
result = api.upload(contribution.getFilename(), file, contribution.getDataLength(), contribution.getPageContents(), contribution.getEditSummary(), notificationUpdater);
} catch(IOException e) {
Log.d("Commons", "I have a network fuckup");
showFailedNotification(contribution);
return;
} finally {
toUpload--;
}
Log.d("Commons", "Response is" + CommonsApplication.getStringFromDOM(result.getDocument()));
stopForeground(true);
curProgressNotification = null;
SimpleDateFormat isoFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'"); // Assuming MW always gives me UTC
String resultStatus = result.getString("/api/upload/@result");
- if(!resultStatus.equals("success")) {
+ if(!resultStatus.equals("Success")) {
showFailedNotification(contribution);
} else {
Date dateUploaded = null;
try {
dateUploaded = isoFormat.parse(result.getString("/api/upload/imageinfo/@timestamp"));
} catch(java.text.ParseException e) {
throw new RuntimeException(e); // Hopefully mediawiki doesn't give me bogus stuff?
}
contribution.setState(Contribution.STATE_COMPLETED);
contribution.setDateUploaded(dateUploaded);
contribution.save();
}
}
private void showFailedNotification(Contribution contribution) {
stopForeground(true);
Notification failureNotification = new NotificationCompat.Builder(this).setAutoCancel(true)
.setSmallIcon(R.drawable.ic_launcher)
.setAutoCancel(true)
.setContentIntent(PendingIntent.getActivity(this, 0, new Intent(this, ContributionsActivity.class), 0))
.setTicker(String.format(getString(R.string.upload_failed_notification_title), contribution.getFilename()))
.setContentTitle(String.format(getString(R.string.upload_failed_notification_title), contribution.getFilename()))
.setContentText(getString(R.string.upload_failed_notification_subtitle))
.getNotification();
notificationManager.notify(NOTIFICATION_UPLOAD_FAILED, failureNotification);
contribution.setState(Contribution.STATE_FAILED);
contribution.save();
}
}
| true | true | protected void onHandleIntent(Intent intent) {
MWApi api = app.getApi();
ApiResult result;
RemoteViews notificationView;
Contribution contribution;
InputStream file = null;
contribution = (Contribution) intent.getSerializableExtra("dummy-data");
String notificationTag = contribution.getLocalUri().toString();
try {
file = this.getContentResolver().openInputStream(contribution.getLocalUri());
} catch(FileNotFoundException e) {
throw new RuntimeException(e);
}
notificationView = new RemoteViews(getPackageName(), R.layout.layout_upload_progress);
notificationView.setTextViewText(R.id.uploadNotificationTitle, String.format(getString(R.string.upload_progress_notification_title_start), contribution.getFilename()));
notificationView.setProgressBar(R.id.uploadNotificationProgress, 100, 0, false);
Log.d("Commons", "Before execution!");
curProgressNotification = new NotificationCompat.Builder(this).setAutoCancel(true)
.setSmallIcon(R.drawable.ic_launcher)
.setAutoCancel(true)
.setContent(notificationView)
.setOngoing(true)
.setContentIntent(PendingIntent.getActivity(this, 0, new Intent(this, ContributionsActivity.class), 0))
.setTicker(String.format(getString(R.string.upload_progress_notification_title_in_progress), contribution.getFilename()))
.getNotification();
this.startForeground(NOTIFICATION_DOWNLOAD_IN_PROGRESS, curProgressNotification);
Log.d("Commons", "Just before");
try {
if(!api.validateLogin()) {
// Need to revalidate!
if(app.revalidateAuthToken()) {
Log.d("Commons", "Successfully revalidated token!");
} else {
Log.d("Commons", "Unable to revalidate :(");
// TODO: Put up a new notification, ask them to re-login
stopForeground(true);
Toast failureToast = Toast.makeText(this, R.string.authentication_failed, Toast.LENGTH_LONG);
failureToast.show();
return;
}
}
NotificationUpdateProgressListener notificationUpdater = new NotificationUpdateProgressListener(curProgressNotification, notificationTag,
String.format(getString(R.string.upload_progress_notification_title_in_progress), contribution.getFilename()),
String.format(getString(R.string.upload_progress_notification_title_finishing), contribution.getFilename()),
contribution
);
result = api.upload(contribution.getFilename(), file, contribution.getDataLength(), contribution.getPageContents(), contribution.getEditSummary(), notificationUpdater);
} catch(IOException e) {
Log.d("Commons", "I have a network fuckup");
showFailedNotification(contribution);
return;
} finally {
toUpload--;
}
Log.d("Commons", "Response is" + CommonsApplication.getStringFromDOM(result.getDocument()));
stopForeground(true);
curProgressNotification = null;
SimpleDateFormat isoFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'"); // Assuming MW always gives me UTC
String resultStatus = result.getString("/api/upload/@result");
if(!resultStatus.equals("success")) {
showFailedNotification(contribution);
} else {
Date dateUploaded = null;
try {
dateUploaded = isoFormat.parse(result.getString("/api/upload/imageinfo/@timestamp"));
} catch(java.text.ParseException e) {
throw new RuntimeException(e); // Hopefully mediawiki doesn't give me bogus stuff?
}
contribution.setState(Contribution.STATE_COMPLETED);
contribution.setDateUploaded(dateUploaded);
contribution.save();
}
}
| protected void onHandleIntent(Intent intent) {
MWApi api = app.getApi();
ApiResult result;
RemoteViews notificationView;
Contribution contribution;
InputStream file = null;
contribution = (Contribution) intent.getSerializableExtra("dummy-data");
String notificationTag = contribution.getLocalUri().toString();
try {
file = this.getContentResolver().openInputStream(contribution.getLocalUri());
} catch(FileNotFoundException e) {
throw new RuntimeException(e);
}
notificationView = new RemoteViews(getPackageName(), R.layout.layout_upload_progress);
notificationView.setTextViewText(R.id.uploadNotificationTitle, String.format(getString(R.string.upload_progress_notification_title_start), contribution.getFilename()));
notificationView.setProgressBar(R.id.uploadNotificationProgress, 100, 0, false);
Log.d("Commons", "Before execution!");
curProgressNotification = new NotificationCompat.Builder(this).setAutoCancel(true)
.setSmallIcon(R.drawable.ic_launcher)
.setAutoCancel(true)
.setContent(notificationView)
.setOngoing(true)
.setContentIntent(PendingIntent.getActivity(this, 0, new Intent(this, ContributionsActivity.class), 0))
.setTicker(String.format(getString(R.string.upload_progress_notification_title_in_progress), contribution.getFilename()))
.getNotification();
this.startForeground(NOTIFICATION_DOWNLOAD_IN_PROGRESS, curProgressNotification);
Log.d("Commons", "Just before");
try {
if(!api.validateLogin()) {
// Need to revalidate!
if(app.revalidateAuthToken()) {
Log.d("Commons", "Successfully revalidated token!");
} else {
Log.d("Commons", "Unable to revalidate :(");
// TODO: Put up a new notification, ask them to re-login
stopForeground(true);
Toast failureToast = Toast.makeText(this, R.string.authentication_failed, Toast.LENGTH_LONG);
failureToast.show();
return;
}
}
NotificationUpdateProgressListener notificationUpdater = new NotificationUpdateProgressListener(curProgressNotification, notificationTag,
String.format(getString(R.string.upload_progress_notification_title_in_progress), contribution.getFilename()),
String.format(getString(R.string.upload_progress_notification_title_finishing), contribution.getFilename()),
contribution
);
result = api.upload(contribution.getFilename(), file, contribution.getDataLength(), contribution.getPageContents(), contribution.getEditSummary(), notificationUpdater);
} catch(IOException e) {
Log.d("Commons", "I have a network fuckup");
showFailedNotification(contribution);
return;
} finally {
toUpload--;
}
Log.d("Commons", "Response is" + CommonsApplication.getStringFromDOM(result.getDocument()));
stopForeground(true);
curProgressNotification = null;
SimpleDateFormat isoFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'"); // Assuming MW always gives me UTC
String resultStatus = result.getString("/api/upload/@result");
if(!resultStatus.equals("Success")) {
showFailedNotification(contribution);
} else {
Date dateUploaded = null;
try {
dateUploaded = isoFormat.parse(result.getString("/api/upload/imageinfo/@timestamp"));
} catch(java.text.ParseException e) {
throw new RuntimeException(e); // Hopefully mediawiki doesn't give me bogus stuff?
}
contribution.setState(Contribution.STATE_COMPLETED);
contribution.setDateUploaded(dateUploaded);
contribution.save();
}
}
|
diff --git a/src/me/ellbristow/WhooshingWell/WhooshingWell.java b/src/me/ellbristow/WhooshingWell/WhooshingWell.java
index 94b65ca..85359fa 100644
--- a/src/me/ellbristow/WhooshingWell/WhooshingWell.java
+++ b/src/me/ellbristow/WhooshingWell/WhooshingWell.java
@@ -1,1073 +1,1073 @@
package me.ellbristow.WhooshingWell;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Random;
import java.util.logging.Level;
import org.bukkit.World.Environment;
import org.bukkit.*;
import org.bukkit.block.Block;
import org.bukkit.block.BlockFace;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.block.BlockBreakEvent;
import org.bukkit.event.block.BlockPlaceEvent;
import org.bukkit.event.block.SignChangeEvent;
import org.bukkit.event.player.PlayerInteractEvent;
import org.bukkit.event.player.PlayerPortalEvent;
import org.bukkit.event.player.PlayerTeleportEvent.TeleportCause;
import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.PlayerInventory;
import org.bukkit.plugin.java.JavaPlugin;
public class WhooshingWell extends JavaPlugin implements Listener {
protected static WhooshingWell plugin;
protected FileConfiguration config;
private FileConfiguration portalConfig = null;
private File portalFile = null;
protected boolean clearInv;
protected boolean clearArmor;
protected boolean allowNether;
protected boolean allowEnd;
protected HashMap<String, Location> destinations = new HashMap<String, Location>();
@Override
public void onDisable() {
}
@Override
public void onEnable () {
config = getConfig();
clearInv = config.getBoolean("requireEmptyInventory", false);
config.set("requireEmptyInventory", clearInv);
clearArmor = config.getBoolean("requireEmptyArmor", false);
config.set("requireEmptyArmor", clearArmor);
allowNether = config.getBoolean("allowNetherWells", true);
config.set("allowNetherWells", allowNether);
allowEnd = config.getBoolean("allowEndWells", true);
config.set("allowEndWells", allowEnd);
saveConfig();
ConfigurationSection dests = config.getConfigurationSection("destinations");
if (dests != null) {
for (String key : dests.getKeys(false)) {
String world = dests.getString(key+".world");
if (getServer().getWorld(world) != null) {
double x = dests.getDouble(key+".x");
double y = dests.getDouble(key+".y");
double z = dests.getDouble(key+".z");
List<Float> floats = dests.getFloatList(key+".yawpitch");
float yaw = floats.get(0);
float pitch = floats.get(1);
Location loc = new Location(getServer().getWorld(world), x, y, z, yaw, pitch);
destinations.put(key, loc);
}
}
}
portalConfig = getPortals();
forceWorldLoads();
getServer().getPluginManager().registerEvents(this, this);
}
@Override
public boolean onCommand (CommandSender sender, Command cmd, String commandLabel, String[] args) {
if (commandLabel.equalsIgnoreCase("ww")) {
if (args.length == 0) {
String version = getDescription().getVersion();
sender.sendMessage(ChatColor.GOLD + "WhooshingWell v" + ChatColor.WHITE + version + ChatColor.GOLD + " by " + ChatColor.WHITE + "ellbristow");
sender.sendMessage(ChatColor.GOLD + "=============");
sender.sendMessage(ChatColor.GOLD + "Require Empty Inventory : " + ChatColor.WHITE + clearInv);
sender.sendMessage(ChatColor.GOLD + "Require No Armor : " + ChatColor.WHITE + clearArmor);
sender.sendMessage(ChatColor.GOLD + "Allow Nether Wells : " + ChatColor.WHITE + allowNether);
sender.sendMessage(ChatColor.GOLD + "Allow End Wells : " + ChatColor.WHITE + allowEnd);
return true;
} else if (args.length == 1) {
if ("list".equalsIgnoreCase(args[0])) {
if (!sender.hasPermission("whooshingwell.world.list")) {
sender.sendMessage(ChatColor.RED + "You do not have permission to use this command!");
return true;
}
Object[] worlds = getServer().getWorlds().toArray();
sender.sendMessage(ChatColor.GOLD + "World List");
sender.sendMessage(ChatColor.GOLD + "==========");
for (int i = 0; i < worlds.length; i++) {
World world = (World)worlds[i];
if (!(world.getEnvironment().equals(Environment.NETHER) && !allowNether) && !(world.getEnvironment().equals(Environment.THE_END) && !allowEnd)) {
sender.sendMessage(ChatColor.GOLD + world.getName() + ChatColor.GRAY + " ("+i+")");
}
}
for (String key : destinations.keySet()) {
Location loc = destinations.get(key);
World world = loc.getWorld();
if (!(world.getEnvironment().equals(Environment.NETHER) && !allowNether) && !(world.getEnvironment().equals(Environment.THE_END) && !allowEnd)) {
sender.sendMessage(ChatColor.YELLOW + key);
}
}
return true;
} else if (args[0].equalsIgnoreCase("toggle")) {
if (!sender.hasPermission("whooshingwell.toggle.emptyinv") && !sender.hasPermission("whooshingwell.toggle.emptyarmor") && !sender.hasPermission("whooshingwell.toggle.allownether") && !sender.hasPermission("whooshingwell.toggle.allowend")) {
sender.sendMessage(ChatColor.RED + "You do not have permission to use this command!");
return true;
}
sender.sendMessage(ChatColor.RED + "You must specify a setting to toggle!");
if (sender.hasPermission("whooshingwell.toggle.emptyinv")) {
sender.sendMessage(ChatColor.GRAY + "EmptyInv: Players cannot carry inventory through portals");
}
if (sender.hasPermission("whooshingwell.toggle.emptyarmor")) {
sender.sendMessage(ChatColor.GRAY + "EmptyArmor: Players cannot wear armor through portals");
}
if (sender.hasPermission("whooshingwell.toggle.allownether")) {
sender.sendMessage(ChatColor.GRAY + "AllowNether: New wells can lead to Nether worlds");
}
if (sender.hasPermission("whooshingwell.toggle.allowend")) {
sender.sendMessage(ChatColor.GRAY + "AllowEnd: New wells can lean to End worlds");
}
return true;
} else if (args[0].equalsIgnoreCase("addworld")) {
if (!sender.hasPermission("whooshingwell.world.create")) {
sender.sendMessage(ChatColor.RED + "You do not have permission to use this command!");
return true;
}
sender.sendMessage(ChatColor.RED + "You must specify a world name!");
sender.sendMessage(ChatColor.RED + "/ww addworld [World Name]");
return true;
} else if (args[0].equalsIgnoreCase("deleteworld") || args[0].equalsIgnoreCase("delworld")) {
if (!sender.hasPermission("whooshingwell.world.delete")) {
sender.sendMessage(ChatColor.RED + "You do not have permission to use this command!");
return true;
}
sender.sendMessage(ChatColor.RED + "You must specify a world name!");
sender.sendMessage(ChatColor.RED + "/ww addworld [World Name]");
return true;
} else if (args[0].equalsIgnoreCase("setdest")) {
if (!(sender instanceof Player)) {
sender.sendMessage(ChatColor.RED + "This command cannot be run from the console!");
return true;
}
if (!sender.hasPermission("whooshingwell.setdest")) {
sender.sendMessage(ChatColor.RED + "You do not have permission to use this command!");
return true;
}
sender.sendMessage(ChatColor.RED + "You must specify a destination name!");
sender.sendMessage(ChatColor.RED + "/ww setdest [Destination Name]");
return true;
} else if (args[0].equalsIgnoreCase("deldest")) {
if (!sender.hasPermission("whooshingwell.deldest")) {
sender.sendMessage(ChatColor.RED + "You do not have permission to use this command!");
return true;
}
sender.sendMessage(ChatColor.RED + "You must specify a destination name!");
sender.sendMessage(ChatColor.RED + "/ww deldest [Destination Name]");
return true;
}
} else if (args.length == 2) {
if (args[0].equalsIgnoreCase("addworld")) {
if (!sender.hasPermission("whooshingwell.world.create")) {
sender.sendMessage(ChatColor.RED + "You do not have permission to use this command!");
return true;
}
if (getServer().getWorld(args[1]) != null){
sender.sendMessage(ChatColor.RED + "A world called '" + ChatColor.WHITE + args[1] + ChatColor.RED + "' already exists!");
return true;
} else if (args[1].length() < 4) {
sender.sendMessage(ChatColor.RED + "Please use a name with at least 4 characters!");
return true;
} else {
sender.sendMessage(ChatColor.GOLD + "Creating '" + ChatColor.WHITE + args[1] + ChatColor.GOLD + "'!");
getServer().broadcastMessage(ChatColor.LIGHT_PURPLE + "A new world has been found!");
getServer().broadcastMessage(ChatColor.LIGHT_PURPLE + "You may experience some lag while we map it!");
WorldCreator wc = makeWorld(args[1], sender);
getServer().createWorld(wc);
return true;
}
} else if ((args[0].equalsIgnoreCase("deleteworld") || args[0].equalsIgnoreCase("delworld"))) {
if (!sender.hasPermission("whooshingwell.world.delete")) {
sender.sendMessage(ChatColor.RED + "You do not have permission to use this command!");
return true;
}
if (getServer().getWorld(args[1]) == null){
sender.sendMessage(ChatColor.RED + "There is no world called '" + ChatColor.WHITE + args[1] + ChatColor.RED + "'!");
return true;
} else if (args[1].equalsIgnoreCase(getServer().getWorlds().get(0).getName())) {
sender.sendMessage(ChatColor.RED + "You cannot delete the default world!");
return true;
} else if (!getServer().getWorld(args[1]).getPlayers().isEmpty()) {
sender.sendMessage(ChatColor.RED + "There are players in " + ChatColor.WHITE + args[1] + ChatColor.RED + "!");
sender.sendMessage(ChatColor.RED + "All players must leave " + ChatColor.WHITE + args[1] + ChatColor.RED + " to delete it!");
return true;
} else {
getServer().unloadWorld(getServer().getWorld(args[1]), false);
sender.sendMessage(ChatColor.GOLD + "Deleting '" + ChatColor.WHITE + args[1] + ChatColor.GOLD + "'!");
getServer().broadcastMessage(ChatColor.LIGHT_PURPLE + "A world is collapsing!");
getServer().broadcastMessage(ChatColor.LIGHT_PURPLE + "You may experience some lag while we tidy it!");
delete(getWorldDataFolder(args[1]));
portalConfig.set(args[1], null);
return true;
}
} else if (args[0].equalsIgnoreCase("setdest")) {
if (!(sender instanceof Player)) {
sender.sendMessage(ChatColor.RED + "This command cannot be run from the console!");
return true;
}
if (!sender.hasPermission("whooshingwell.setdest")) {
sender.sendMessage(ChatColor.RED + "You do not have permission to use this command!");
return true;
}
if (getServer().getWorld(args[1]) != null) {
sender.sendMessage(ChatColor.RED + "You cannot set a destination with the same name as a world!");
sender.sendMessage(ChatColor.RED + "/ww setdest [Destination Name]");
return true;
}
Player player = (Player)sender;
World world = player.getWorld();
if (world.getEnvironment().equals(Environment.NETHER) && !allowNether) {
player.sendMessage(ChatColor.RED + "Whooshing wells cannot lead to Nether worlds");
return true;
} else if (world.getEnvironment().equals(Environment.THE_END) && !allowEnd) {
player.sendMessage(ChatColor.RED + "Whooshing wells cannot lead to End worlds");
return true;
}
Location loc = player.getLocation();
destinations.put(args[1].toLowerCase(), loc);
- config.set("destinations."+args[1]+".world", loc.getWorld().getName());
- config.set("destinations."+args[1]+".x", loc.getX());
- config.set("destinations."+args[1]+".y", loc.getY());
- config.set("destinations."+args[1]+".z", loc.getZ());
+ config.set("destinations."+args[1].toLowerCase()+".world", loc.getWorld().getName());
+ config.set("destinations."+args[1].toLowerCase()+".x", loc.getX());
+ config.set("destinations."+args[1].toLowerCase()+".y", loc.getY());
+ config.set("destinations."+args[1].toLowerCase()+".z", loc.getZ());
List<Float> yawpitch = new ArrayList<Float>();
yawpitch.add(loc.getYaw());
yawpitch.add(loc.getPitch());
config.set("destinations."+args[1].toLowerCase()+".yawpitch", yawpitch);
saveConfig();
player.sendMessage(ChatColor.GOLD + "New destination " + ChatColor.WHITE + args[1] + ChatColor.GOLD + " set!");
return true;
} else if (args[0].equalsIgnoreCase("deldest")) {
if (!sender.hasPermission("whooshingwell.deldest")) {
sender.sendMessage(ChatColor.RED + "You do not have permission to use this command!");
return true;
}
if (destinations.get(args[1].toLowerCase()) == null) {
sender.sendMessage(ChatColor.RED + "Destination "+ChatColor.WHITE +args[1]+ ChatColor.RED+" not found!");
return true;
}
destinations.remove(args[1].toLowerCase());
config.set("destinations."+args[1].toLowerCase(), null);
sender.sendMessage(ChatColor.GOLD + "Destination " + ChatColor.WHITE + args[1] + ChatColor.GOLD + " deleted!");
return true;
} else if (args[0].equalsIgnoreCase("toggle")) {
if (args[1].equalsIgnoreCase("EmptyInv")) {
if (!sender.hasPermission("whooshingwell.toggle.emptyinv")) {
sender.sendMessage(ChatColor.RED + "You do not have permission to toggle this setting!");
return true;
}
if (clearInv) {
clearInv = false;
sender.sendMessage(ChatColor.GOLD + "Players no longer need to empty their inventory to use Whooshing Wells!");
} else {
clearInv = true;
sender.sendMessage(ChatColor.GOLD + "Players must now empty their inventory to use Whooshing Wells!");
}
config.set("requireEmptyInventory", clearInv);
saveConfig();
return true;
} else if (args[1].equalsIgnoreCase("EmptyArmor")) {
if (!sender.hasPermission("whooshingwell.toggle.emptyinv")) {
sender.sendMessage(ChatColor.RED + "You do not have permission to toggle this setting!");
return true;
}
if (clearArmor) {
clearArmor = false;
sender.sendMessage(ChatColor.GOLD + "Players no longer need to remove their armor to use Whooshing Wells!");
} else {
clearArmor = true;
sender.sendMessage(ChatColor.GOLD + "Players must now remove their armor to use Whooshing Wells!");
}
config.set("requireEmptyArmor", clearArmor);
saveConfig();
return true;
} else if (args[1].equalsIgnoreCase("AllowNether")) {
if (!sender.hasPermission("whooshingwell.toggle.allownether")) {
sender.sendMessage(ChatColor.RED + "You do not have permission to toggle this setting!");
return true;
}
if (allowNether) {
allowNether = false;
sender.sendMessage(ChatColor.GOLD + "New wells now CANNOT lead to Nether worlds!");
} else {
allowNether = true;
sender.sendMessage(ChatColor.GOLD + "New wells now CAN lead to Nether worlds!");
}
config.set("allowNetherWells", allowNether);
saveConfig();
return true;
} else if (args[1].equalsIgnoreCase("AllowEnd")) {
if (!sender.hasPermission("whooshingwell.toggle.allowend")) {
sender.sendMessage(ChatColor.RED + "You do not have permission to toggle this setting!");
return true;
}
if (allowEnd) {
allowEnd = false;
sender.sendMessage(ChatColor.GOLD + "New wells now CANNOT lead to End worlds!");
} else {
allowEnd = true;
sender.sendMessage(ChatColor.GOLD + "New wells now CAN lead to End worlds!");
}
config.set("allowEndWells", allowEnd);
saveConfig();
return true;
}
sender.sendMessage(ChatColor.RED + "Sorry! I dont' recognise that toggle option!");
return true;
}
}
}
sender.sendMessage(ChatColor.RED + "Sorry! That command was not recognised!");
return true;
}
@EventHandler (priority = EventPriority.NORMAL)
public void onSignChange(SignChangeEvent event) {
if (!event.isCancelled()) {
String line0 = event.getLine(0);
if ("[ww]".equalsIgnoreCase(line0)) {
Player player = event.getPlayer();
Block signBlock = event.getBlock();
if (!player.hasPermission("whooshingwell.create")) {
player.sendMessage(ChatColor.RED + "You do not have permission to create a Whooshing Well!");
event.setCancelled(true);
dropSign(signBlock);
return;
}
// Player has permission. Check not already a WW
if (isWW(signBlock.getLocation())) {
player.sendMessage(ChatColor.RED + "There is already a Whooshing Well here!");
event.setCancelled(true);
dropSign(signBlock);
return;
}
// Not a WW. Check well formation
if (!hasWellLayout(signBlock, false) && !hasWellLayout(signBlock, true)) {
player.sendMessage(ChatColor.RED + "Incorrect layout for a Whooshing Well!");
event.setCancelled(true);
dropSign(signBlock);
return;
}
Block[] checkAirBlocks = getAir(signBlock.getLocation().getBlock(), getButtonDirection(signBlock), false);
if (checkAirBlocks == null) {
checkAirBlocks = getAir(signBlock.getLocation().getBlock(), getButtonDirection(signBlock), true);
}
if (checkAirBlocks != null) {
for (Block airBlock : checkAirBlocks) {
if (isWW(airBlock.getLocation())) {
player.sendMessage(ChatColor.RED + "There is already a Whooshing Well here!");
event.setCancelled(true);
dropSign(signBlock);
return;
}
}
}
// Well OK, Check World Name/ID
String line1 = event.getLine(1);
String worldName;
boolean isDest = false;
if (line1.toLowerCase().startsWith("world:")) {
String idString = line1.split(":")[1];
try {
int worldId = Integer.parseInt(idString);
World world = getServer().getWorlds().get(worldId);
if (world == null) {
player.sendMessage(ChatColor.RED + "Could not find World Id " + ChatColor.WHITE + idString + ChatColor.RED + "!");
player.sendMessage(ChatColor.RED + "Please make sure line 2 of your sign is a valid world or destination name");
player.sendMessage(ChatColor.RED + "or is in the format \"world:[world id]\"!");
event.setCancelled(true);
dropSign(signBlock);
return;
} else {
worldName = world.getName();
}
} catch (NumberFormatException e) {
player.sendMessage(ChatColor.WHITE + idString + ChatColor.RED + " is not a valid world ID!");
player.sendMessage(ChatColor.RED + "Please make sure line 2 of your sign is a valid world or destination name");
player.sendMessage(ChatColor.RED + "or is in the format \"world:[world id]\"!");
event.setCancelled(true);
dropSign(signBlock);
return;
}
} else if (getServer().getWorld(line1) == null) {
if (destinations.get(line1.toLowerCase()) != null) {
isDest = true;
worldName = line1;
} else {
player.sendMessage(ChatColor.RED + "Could not find a world or destination called '" + ChatColor.WHITE + line1 + ChatColor.RED + "'!");
player.sendMessage(ChatColor.RED + "Please make sure line 2 of your sign is a valid world or destination name");
player.sendMessage(ChatColor.RED + "or is in the format \"world:[world id]\"!");
event.setCancelled(true);
dropSign(signBlock);
return;
}
} else {
worldName = line1;
}
World world;
if (!isDest) {
// World Name/ID OK, check Nether/End restrictions
world = getServer().getWorld(worldName);
} else {
Location dest = destinations.get(line1.toLowerCase());
world = dest.getWorld();
}
if (world.getEnvironment().equals(Environment.NETHER) && !allowNether) {
player.sendMessage(ChatColor.RED + "Whooshing Wells cannot lead to Nether worlds!");
dropSign(signBlock);
return;
} else if (world.getEnvironment().equals(Environment.THE_END) && !allowEnd) {
player.sendMessage(ChatColor.RED + "Whooshing Wells cannot lead to End worlds!");
dropSign(signBlock);
return;
}
// GOOD TO GO!
String thisPortal = signBlock.getWorld().getName() + "." + signBlock.getX() + "_" + signBlock.getY() + "_" + signBlock.getZ();
Block[] airBlocks = getAir(signBlock, getButtonDirection(signBlock), false);
if (airBlocks == null) {
airBlocks = getAir(signBlock, getButtonDirection(signBlock), true);
}
String location = "";
for (Block block : airBlocks) {
if (!"".equals(location)) {
location += ";";
}
location += block.getWorld().getName() + ":" + block.getX() + ":" + block.getY() + ":" + block.getZ();
}
portalConfig.set(thisPortal + ".location",location);
portalConfig.set(thisPortal + ".destination", worldName);
savePortals();
player.sendMessage(ChatColor.GOLD + "A new Whooshing Well to '" + ChatColor.WHITE + worldName + ChatColor.GOLD + "' has been created!");
}
}
}
@EventHandler (priority = EventPriority.NORMAL)
public void onPlayerInteract(PlayerInteractEvent event) {
Player player = event.getPlayer();
if (!event.isCancelled()) {
Block block = event.getClickedBlock();
if (block != null && (block.getType() == Material.STONE_BUTTON || block.getType() == Material.WOOD_BUTTON)) {
if (isWWButton(block, true) || isWWButton(block, false) && player.hasPermission("whooshingwell.use")) {
String location = getWWFromButton(block);
if (location != null) {
String[] locations = location.split(";");
String[] loc0 = locations[0].split(":");
Location loc = new Location(getServer().getWorld(loc0[0]), Integer.parseInt(loc0[1]), Integer.parseInt(loc0[2]), Integer.parseInt(loc0[3]));
toggleWW(block);
}
}
}
}
}
@EventHandler (priority = EventPriority.NORMAL)
public void onBlockPlace (BlockPlaceEvent event) {
if (!event.isCancelled()) {
Block block = event.getBlock();
if (isWW(block.getLocation())) {
event.setCancelled(true);
event.getPlayer().sendMessage(ChatColor.RED + "You can't place a block there!");
}
}
}
@EventHandler (priority = EventPriority.NORMAL)
public void onBlockBreak (BlockBreakEvent event) {
if (!event.isCancelled()) {
Block block = event.getBlock();
if (block.getTypeId() == 63 || block.getTypeId() == 68) {
if (isWW(block.getLocation())) {
Player player = event.getPlayer();
if (!player.hasPermission("whooshingwell.destroy")) {
player.sendMessage(ChatColor.RED + "You do not have permission to break that sign!");
event.setCancelled(true);
} else {
Location signLocation = block.getLocation();
String locString = signLocation.getWorld().getName() + "." + (int)Math.floor(signLocation.getX()) + "_" + (int)Math.floor(signLocation.getY()) + "_" + (int)Math.floor(signLocation.getZ()) + ".location";
String destString = signLocation.getWorld().getName() + "." + (int)Math.floor(signLocation.getX()) + "_" + (int)Math.floor(signLocation.getY()) + "_" + (int)Math.floor(signLocation.getZ()) + ".destination";
String section = signLocation.getWorld().getName() + "." + (int)Math.floor(signLocation.getX()) + "_" + (int)Math.floor(signLocation.getY()) + "_" + (int)Math.floor(signLocation.getZ());
portalConfig.set(locString, null);
portalConfig.set(destString, null);
portalConfig.set(section, null);
savePortals();
if (getAir(block, getButtonDirection(block), true) != null) {
toggleWW(block.getRelative(getButtonDirection(block), 3));
}
player.sendMessage(ChatColor.GOLD + "Whooshing Well Deactivated!");
}
}
} else if (isWWStairs(block)) {
Player player = event.getPlayer();
player.sendMessage(ChatColor.RED + "Those stairs are protected by a Whooshing Well!");
event.setCancelled(true);
}
}
}
@EventHandler (priority = EventPriority.NORMAL)
public void onPortalJump (PlayerPortalEvent event) {
if (!event.isCancelled()) {
TeleportCause cause = event.getCause();
if (cause.equals(TeleportCause.END_PORTAL)) {
Location fromLoc = event.getFrom();
Location footLoc = event.getPlayer().getLocation();
Location underFoot = footLoc.clone().subtract(0, 1, 0);
Location headLoc = event.getPlayer().getEyeLocation();
Location overHead = headLoc.clone().add(0, 1, 0);
if (isWW(fromLoc) || isWW(footLoc) || isWW(underFoot) || isWW(headLoc) || isWW(overHead)) {
event.setCancelled(true);
if (event.getPlayer().hasPermission("whooshingwell.use")) {
String destination = "";
if (isWW(fromLoc)) {
destination = getDestination(fromLoc);
togglePortalFromJump(fromLoc);
} else if (isWW(footLoc)) {
destination = getDestination(footLoc);
togglePortalFromJump(footLoc);
} else if (isWW(underFoot)) {
destination = getDestination(underFoot);
togglePortalFromJump(underFoot);
} else if (isWW(headLoc)) {
destination = getDestination(headLoc);
togglePortalFromJump(headLoc);
} else if (isWW(overHead)) {
destination = getDestination(overHead);
togglePortalFromJump(overHead);
}
if (getServer().getWorld(destination) != null) {
if (clearInv && !emptyInventory(event.getPlayer().getInventory())) {
event.getPlayer().sendMessage(ChatColor.RED + "You must have an empty inventory to use a Whooshing Well!");
return;
}
if (clearArmor && !emptyArmor(event.getPlayer().getInventory())) {
event.getPlayer().sendMessage(ChatColor.RED + "You must not be wearing armor to use a Whooshing Well!");
return;
}
Location teleportDestination = getServer().getWorld(destination).getSpawnLocation();
event.getPlayer().sendMessage(ChatColor.GOLD + "WHOOSH!");
event.getPlayer().teleport(teleportDestination);
} else if (destinations.get(destination.toLowerCase()) != null) {
Location dest = destinations.get(destination.toLowerCase());
event.getPlayer().sendMessage(ChatColor.GOLD + "WHOOSH!");
event.getPlayer().teleport(dest);
} else {
event.getPlayer().sendMessage(ChatColor.RED + "Oh Dear! The other end of this portal no longer exists!");
}
}
} else {
String defaultWorld = getServer().getWorlds().get(0).getName();
if (!defaultWorld.equals(fromLoc.getWorld().getName()) && !(defaultWorld + "_nether").equals(fromLoc.getWorld().getName()) && !(defaultWorld + "_the_end").equals(fromLoc.getWorld().getName())) {
String fromWorld = fromLoc.getWorld().getName();
if (!fromWorld.endsWith("_nether") && !fromWorld.endsWith("_the_end")) {
World world = getServer().getWorld(getServer().getWorlds().get(0).getName() + "_the_end");
Location to = new Location(world,event.getFrom().getX(),event.getFrom().getY(),event.getFrom().getZ());
event.setTo(to);
}
}
}
} else if (cause == TeleportCause.NETHER_PORTAL) {
String defaultWorld = getServer().getWorlds().get(0).getName();
Location fromLoc = event.getFrom();
if (!defaultWorld.equals(fromLoc.getWorld().getName()) && !(defaultWorld + "_nether").equals(fromLoc.getWorld().getName()) && !(defaultWorld + "_the_end").equals(fromLoc.getWorld().getName())) {
String fromWorld = fromLoc.getWorld().getName();
if (!fromWorld.endsWith("_nether") && !fromWorld.endsWith("_the_end")) {
World world = getServer().getWorld(getServer().getWorlds().get(0).getName() + "_nether");
Location to = new Location(world,event.getFrom().getX(),event.getFrom().getY(),event.getFrom().getZ());
event.setTo(to);
}
}
}
}
}
private boolean emptyArmor(PlayerInventory inv) {
if (inv == null) {
return true;
}
ItemStack helmet = inv.getHelmet();
ItemStack chest = inv.getChestplate();
ItemStack legs = inv.getLeggings();
ItemStack boots = inv.getBoots();
if (helmet != null || chest != null || legs != null || boots != null) {
return false;
}
return true;
}
private boolean emptyInventory(Inventory inv) {
if (inv == null) {
return true;
}
ItemStack[] contents = inv.getContents();
for (ItemStack stack : contents) {
if (stack != null && stack.getType() != Material.AIR) {
return false;
}
}
return true;
}
private boolean isWW(Location loc) {
// Check for Sign Location
String portalCoords = loc.getWorld().getName() + "." + (int)loc.getX() + "_" + (int)loc.getY() + "_" + (int)loc.getZ();
if (portalConfig.getConfigurationSection(portalCoords) != null) {
return true;
} else if (loc.getBlock().getTypeId() == 63 || loc.getBlock().getTypeId() == 68) {
return false;
}
// Check for Portal Location
ConfigurationSection section = portalConfig.getConfigurationSection(loc.getWorld().getName());
if (section != null) {
Object[] configKeys = section.getKeys(false).toArray();
for (int i = 0; i < configKeys.length; i++) {
String key = configKeys[i].toString();
String locations = section.getString(key + ".location");
for (String location : locations.split(";")) {
if (location.equals(loc.getWorld().getName() + ":" + (int)Math.floor(loc.getX()) + ":" + (int)Math.floor(loc.getY()) + ":" + (int)Math.floor(loc.getZ()))) {
return true;
}
}
}
}
// Check Air for WW
Block[] airBlocks = getAir(loc.getBlock(), getButtonDirection(loc.getBlock()), false);
if (airBlocks == null) {
airBlocks = getAir(loc.getBlock(), getButtonDirection(loc.getBlock()), true);
}
if (airBlocks != null) {
if (isWW(airBlocks[0].getLocation())) {
return true;
}
}
return false;
}
private String getDestination(Location loc) {
ConfigurationSection section = portalConfig.getConfigurationSection(loc.getWorld().getName());
if (section != null) {
Object[] configKeys = section.getKeys(false).toArray();
for (int i = 0; i < configKeys.length; i++) {
String key = configKeys[i].toString();
String locations = section.getString(key + ".location");
for (String location : locations.split(";")) {
if (location.equals(loc.getWorld().getName() + ":" + (int)Math.floor(loc.getX()) + ":" + (int)Math.floor(loc.getY()) + ":" + (int)Math.floor(loc.getZ()))) {
String dest = section.getString(key + ".destination");
try {
int worldId = Integer.parseInt(dest);
return getServer().getWorlds().get(worldId).getName();
} catch (NumberFormatException e) {
return section.getString(key + ".destination");
}
}
}
}
}
return "";
}
private boolean hasWellLayout(Block signBlock, boolean active) {
// BUTTON
BlockFace buttonDirection = getButtonDirection(signBlock);
if (buttonDirection == null) {
return false;
}
Block[] stairBlocks = getStairs(signBlock, buttonDirection);
if (stairBlocks == null) {
return false;
}
Block[] airBlocks = getAir(signBlock, buttonDirection, active);
if (airBlocks == null) {
return false;
}
return true;
}
private BlockFace getButtonDirection(Block signBlock) {
// Try NORTH
Block attempt = signBlock.getRelative(BlockFace.NORTH, 3);
if (attempt.getType() == Material.STONE_BUTTON || attempt.getType() == Material.WOOD_BUTTON) {
return BlockFace.NORTH;
}
// Try SOUTH
attempt = signBlock.getRelative(BlockFace.SOUTH, 3);
if (attempt.getType() == Material.STONE_BUTTON || attempt.getType() == Material.WOOD_BUTTON) {
return BlockFace.SOUTH;
}
// Try EAST
attempt = signBlock.getRelative(BlockFace.EAST, 3);
if (attempt.getType() == Material.STONE_BUTTON || attempt.getType() == Material.WOOD_BUTTON) {
return BlockFace.EAST;
}
// Try WEST
attempt = signBlock.getRelative(BlockFace.WEST, 3);
if (attempt.getType() == Material.STONE_BUTTON || attempt.getType() == Material.WOOD_BUTTON) {
return BlockFace.WEST;
}
return null;
}
private Block[] getStairs(Block signBlock, BlockFace buttonDirection) {
if (buttonDirection == BlockFace.NORTH) {
Block cornerBlock = signBlock.getRelative(BlockFace.EAST, 1);
Block stair1 = cornerBlock.getRelative(BlockFace.NORTH, 1);
Block stair2 = cornerBlock.getRelative(BlockFace.NORTH, 2);
Block stair3 = cornerBlock.getRelative(BlockFace.EAST, 1);
Block stair4 = cornerBlock.getRelative(BlockFace.EAST, 2);
Block stair5 = cornerBlock.getRelative(BlockFace.NORTH, 3).getRelative(BlockFace.EAST, 1);
Block stair6 = cornerBlock.getRelative(BlockFace.NORTH, 3).getRelative(BlockFace.EAST, 2);
Block stair7 = cornerBlock.getRelative(BlockFace.EAST, 3).getRelative(BlockFace.NORTH, 1);
Block stair8 = cornerBlock.getRelative(BlockFace.EAST, 3).getRelative(BlockFace.NORTH, 2);
if (isStairs(stair1) && isStairs(stair2) && isStairs(stair3) && isStairs(stair4) && isStairs(stair5) && isStairs(stair6) && isStairs(stair7) && isStairs(stair8)) {
Block[] allStairs = {stair1, stair2, stair3, stair4, stair5, stair6, stair7, stair8};
return allStairs;
} else {
return null;
}
} else if (buttonDirection == BlockFace.SOUTH) {
Block cornerBlock = signBlock.getRelative(BlockFace.WEST, 1);
Block stair1 = cornerBlock.getRelative(BlockFace.SOUTH, 1);
Block stair2 = cornerBlock.getRelative(BlockFace.SOUTH, 2);
Block stair3 = cornerBlock.getRelative(BlockFace.WEST, 1);
Block stair4 = cornerBlock.getRelative(BlockFace.WEST, 2);
Block stair5 = cornerBlock.getRelative(BlockFace.SOUTH, 3).getRelative(BlockFace.WEST, 1);
Block stair6 = cornerBlock.getRelative(BlockFace.SOUTH, 3).getRelative(BlockFace.WEST, 2);
Block stair7 = cornerBlock.getRelative(BlockFace.WEST, 3).getRelative(BlockFace.SOUTH, 1);
Block stair8 = cornerBlock.getRelative(BlockFace.WEST, 3).getRelative(BlockFace.SOUTH, 2);
if (isStairs(stair1) && isStairs(stair2) && isStairs(stair3) && isStairs(stair4) && isStairs(stair5) && isStairs(stair6) && isStairs(stair7) && isStairs(stair8)) {
Block[] allStairs = {stair1, stair2, stair3, stair4, stair5, stair6, stair7, stair8};
return allStairs;
} else {
return null;
}
} else if (buttonDirection == BlockFace.EAST) {
Block cornerBlock = signBlock.getRelative(BlockFace.SOUTH, 1);
Block stair1 = cornerBlock.getRelative(BlockFace.EAST, 1);
Block stair2 = cornerBlock.getRelative(BlockFace.EAST, 2);
Block stair3 = cornerBlock.getRelative(BlockFace.SOUTH, 1);
Block stair4 = cornerBlock.getRelative(BlockFace.SOUTH, 2);
Block stair5 = cornerBlock.getRelative(BlockFace.EAST, 3).getRelative(BlockFace.SOUTH, 1);
Block stair6 = cornerBlock.getRelative(BlockFace.EAST, 3).getRelative(BlockFace.SOUTH, 2);
Block stair7 = cornerBlock.getRelative(BlockFace.SOUTH, 3).getRelative(BlockFace.EAST, 1);
Block stair8 = cornerBlock.getRelative(BlockFace.SOUTH, 3).getRelative(BlockFace.EAST, 2);
if (isStairs(stair1) && isStairs(stair2) && isStairs(stair3) && isStairs(stair4) && isStairs(stair5) && isStairs(stair6) && isStairs(stair7) && isStairs(stair8)) {
Block[] allStairs = {stair1, stair2, stair3, stair4, stair5, stair6, stair7, stair8};
return allStairs;
} else {
return null;
}
}else if (buttonDirection == BlockFace.WEST) {
Block cornerBlock = signBlock.getRelative(BlockFace.NORTH, 1);
Block stair1 = cornerBlock.getRelative(BlockFace.WEST, 1);
Block stair2 = cornerBlock.getRelative(BlockFace.WEST, 2);
Block stair3 = cornerBlock.getRelative(BlockFace.NORTH, 1);
Block stair4 = cornerBlock.getRelative(BlockFace.NORTH, 2);
Block stair5 = cornerBlock.getRelative(BlockFace.WEST, 3).getRelative(BlockFace.NORTH, 1);
Block stair6 = cornerBlock.getRelative(BlockFace.WEST, 3).getRelative(BlockFace.NORTH, 2);
Block stair7 = cornerBlock.getRelative(BlockFace.NORTH, 3).getRelative(BlockFace.WEST, 1);
Block stair8 = cornerBlock.getRelative(BlockFace.NORTH, 3).getRelative(BlockFace.WEST, 2);
if (isStairs(stair1) && isStairs(stair2) && isStairs(stair3) && isStairs(stair4) && isStairs(stair5) && isStairs(stair6) && isStairs(stair7) && isStairs(stair8)) {
Block[] allStairs = {stair1, stair2, stair3, stair4, stair5, stair6, stair7, stair8};
return allStairs;
} else {
return null;
}
}
return null;
}
private Block[] getAir(Block signBlock, BlockFace buttonDirection, boolean active) {
if (buttonDirection == BlockFace.NORTH) {
Block cornerBlock = signBlock.getRelative(BlockFace.EAST, 1);
Block air1 = cornerBlock.getRelative(BlockFace.NORTH, 1).getRelative(BlockFace.EAST, 1);
Block air2 = cornerBlock.getRelative(BlockFace.NORTH, 1).getRelative(BlockFace.EAST, 2);
Block air3 = cornerBlock.getRelative(BlockFace.NORTH, 2).getRelative(BlockFace.EAST, 1);
Block air4 = cornerBlock.getRelative(BlockFace.NORTH, 2).getRelative(BlockFace.EAST, 2);
if ((!active && isAir(air1) && isAir(air2) && isAir(air3) && isAir(air4)) || (active && isEnd(air1) && isEnd(air2) & isEnd(air3) && isEnd(air4))) {
Block[] airBlocks = {air1,air2,air3,air4};
return airBlocks;
}
} else if (buttonDirection == BlockFace.SOUTH) {
Block cornerBlock = signBlock.getRelative(BlockFace.WEST, 1);
Block air1 = cornerBlock.getRelative(BlockFace.SOUTH, 1).getRelative(BlockFace.WEST, 1);
Block air2 = cornerBlock.getRelative(BlockFace.SOUTH, 1).getRelative(BlockFace.WEST, 2);
Block air3 = cornerBlock.getRelative(BlockFace.SOUTH, 2).getRelative(BlockFace.WEST, 1);
Block air4 = cornerBlock.getRelative(BlockFace.SOUTH, 2).getRelative(BlockFace.WEST, 2);
if ((!active && isAir(air1) && isAir(air2) && isAir(air3) && isAir(air4)) || (active && isEnd(air1) && isEnd(air2) & isEnd(air3) && isEnd(air4))) {
Block[] airBlocks = {air1,air2,air3,air4};
return airBlocks;
}
} else if (buttonDirection == BlockFace.EAST) {
Block cornerBlock = signBlock.getRelative(BlockFace.SOUTH, 1);
Block air1 = cornerBlock.getRelative(BlockFace.EAST, 1).getRelative(BlockFace.SOUTH, 1);
Block air2 = cornerBlock.getRelative(BlockFace.EAST, 1).getRelative(BlockFace.SOUTH, 2);
Block air3 = cornerBlock.getRelative(BlockFace.EAST, 2).getRelative(BlockFace.SOUTH, 1);
Block air4 = cornerBlock.getRelative(BlockFace.EAST, 2).getRelative(BlockFace.SOUTH, 2);
if ((!active && isAir(air1) && isAir(air2) && isAir(air3) && isAir(air4)) || (active && isEnd(air1) && isEnd(air2) & isEnd(air3) && isEnd(air4))) {
Block[] airBlocks = {air1,air2,air3,air4};
return airBlocks;
}
} else if (buttonDirection == BlockFace.WEST) {
Block cornerBlock = signBlock.getRelative(BlockFace.NORTH, 1);
Block air1 = cornerBlock.getRelative(BlockFace.WEST, 1).getRelative(BlockFace.NORTH, 1);
Block air2 = cornerBlock.getRelative(BlockFace.WEST, 1).getRelative(BlockFace.NORTH, 2);
Block air3 = cornerBlock.getRelative(BlockFace.WEST, 2).getRelative(BlockFace.NORTH, 1);
Block air4 = cornerBlock.getRelative(BlockFace.WEST, 2).getRelative(BlockFace.NORTH, 2);
if ((!active && isAir(air1) && isAir(air2) && isAir(air3) && isAir(air4)) || (active && isEnd(air1) && isEnd(air2) & isEnd(air3) && isEnd(air4))) {
Block[] airBlocks = {air1,air2,air3,air4};
return airBlocks;
}
}
return null;
}
private boolean isWWStairs(Block stairBlock) {
if (isWW(stairBlock.getRelative(BlockFace.NORTH).getLocation()) || isWW(stairBlock.getRelative(BlockFace.EAST).getLocation()) || isWW(stairBlock.getRelative(BlockFace.SOUTH).getLocation()) || isWW(stairBlock.getRelative(BlockFace.WEST).getLocation())) {
return true;
}
return false;
}
private void dropSign(Block sign) {
sign.setTypeId(0);
sign.getWorld().dropItem(sign.getLocation(), new ItemStack(323,1));
}
private boolean isStairs(Block block) {
if ( block.getTypeId() == 53
|| block.getTypeId() == 67
|| block.getTypeId() == 108
|| block.getTypeId() == 109
|| block.getTypeId() == 114
|| block.getTypeId() == 128
|| block.getTypeId() == 134
|| block.getTypeId() == 135
|| block.getTypeId() == 136) {
return true;
}
return false;
}
private boolean isAir(Block block) {
if (block.getType() == Material.AIR) {
return true;
}
return false;
}
private boolean isEnd(Block block) {
if (block.getType() == Material.ENDER_PORTAL) {
return true;
}
return false;
}
private boolean isWWButton(Block block, boolean active) {
// Try NORTH
Player player = getServer().getPlayer("ellbristow");
Block attempt = block.getRelative(BlockFace.NORTH, 3);
if (isWW(attempt.getLocation())) {
if (hasWellLayout(attempt, active)) {
return true;
}
}
//Try SOUTH
attempt = block.getRelative(BlockFace.SOUTH, 3);
if (isWW(attempt.getLocation())) {
if (hasWellLayout(attempt, active)) {
return true;
}
}
//Try EAST
attempt = block.getRelative(BlockFace.EAST, 3);
if (isWW(attempt.getLocation())) {
if (hasWellLayout(attempt, active)) {
return true;
}
}
//Try WEST
attempt = block.getRelative(BlockFace.WEST, 3);
if (isWW(attempt.getLocation())) {
if (hasWellLayout(attempt, active)) {
return true;
}
}
return false;
}
private void toggleWW(Block block) {
String locations = getWWFromButton(block);
if ("".equals(locations)) {
return;
}
String[] locationArray = locations.split(";");
String[] firstLoc = locationArray[0].split(":");
Location firstLocation = new Location(block.getWorld(), Integer.parseInt(firstLoc[1]), Integer.parseInt(firstLoc[2]), Integer.parseInt(firstLoc[3]));
if (block.getWorld().getBlockAt(firstLocation).getType() == Material.AIR || block.getWorld().getBlockAt(firstLocation).getType() == null) {
// Turn On
block.getWorld().getBlockAt(firstLocation).setTypeId(119);
String[] thisLoc = locationArray[1].split(":");
Location secondLocation = new Location(block.getWorld(), Integer.parseInt(thisLoc[1]), Integer.parseInt(thisLoc[2]), Integer.parseInt(thisLoc[3]));
block.getWorld().getBlockAt(secondLocation).setTypeId(119);
thisLoc = locationArray[2].split(":");
Location thirdLocation = new Location(block.getWorld(), Integer.parseInt(thisLoc[1]), Integer.parseInt(thisLoc[2]), Integer.parseInt(thisLoc[3]));
block.getWorld().getBlockAt(thirdLocation).setTypeId(119);
thisLoc = locationArray[3].split(":");
Location fourthLocation = new Location(block.getWorld(), Integer.parseInt(thisLoc[1]), Integer.parseInt(thisLoc[2]), Integer.parseInt(thisLoc[3]));
block.getWorld().getBlockAt(fourthLocation).setTypeId(119);
} else {
block.getWorld().getBlockAt(firstLocation).setTypeId(0);
String[] thisLoc = locationArray[1].split(":");
Location secondLocation = new Location(block.getWorld(), Integer.parseInt(thisLoc[1]), Integer.parseInt(thisLoc[2]), Integer.parseInt(thisLoc[3]));
block.getWorld().getBlockAt(secondLocation).setTypeId(0);
thisLoc = locationArray[2].split(":");
Location thirdLocation = new Location(block.getWorld(), Integer.parseInt(thisLoc[1]), Integer.parseInt(thisLoc[2]), Integer.parseInt(thisLoc[3]));
block.getWorld().getBlockAt(thirdLocation).setTypeId(0);
thisLoc = locationArray[3].split(":");
Location fourthLocation = new Location(block.getWorld(), Integer.parseInt(thisLoc[1]), Integer.parseInt(thisLoc[2]), Integer.parseInt(thisLoc[3]));
block.getWorld().getBlockAt(fourthLocation).setTypeId(0);
}
}
private void togglePortalFromJump(Location loc) {
ConfigurationSection section = portalConfig.getConfigurationSection(loc.getWorld().getName());
if (section != null) {
Object[] configKeys = section.getKeys(false).toArray();
for (int i = 0; i < configKeys.length; i++) {
String key = configKeys[i].toString();
String locations = section.getString(key + ".location");
for (String location : locations.split(";")) {
if (location.equals(loc.getWorld().getName() + ":" + (int)Math.floor(loc.getX()) + ":" + (int)Math.floor(loc.getY()) + ":" + (int)Math.floor(loc.getZ()))) {
String[] locationArray = locations.split(";");
String[] firstLoc = locationArray[0].split(":");
Location firstLocation = new Location(loc.getWorld(), Integer.parseInt(firstLoc[1]), Integer.parseInt(firstLoc[2]), Integer.parseInt(firstLoc[3]));
loc.getWorld().getBlockAt(firstLocation).setTypeId(0);
String[] thisLoc = locationArray[1].split(":");
Location secondLocation = new Location(loc.getWorld(), Integer.parseInt(thisLoc[1]), Integer.parseInt(thisLoc[2]), Integer.parseInt(thisLoc[3]));
loc.getWorld().getBlockAt(secondLocation).setTypeId(0);
thisLoc = locationArray[2].split(":");
Location thirdLocation = new Location(loc.getWorld(), Integer.parseInt(thisLoc[1]), Integer.parseInt(thisLoc[2]), Integer.parseInt(thisLoc[3]));
loc.getWorld().getBlockAt(thirdLocation).setTypeId(0);
thisLoc = locationArray[3].split(":");
Location fourthLocation = new Location(loc.getWorld(), Integer.parseInt(thisLoc[1]), Integer.parseInt(thisLoc[2]), Integer.parseInt(thisLoc[3]));
loc.getWorld().getBlockAt(fourthLocation).setTypeId(0);
return;
}
}
}
}
}
private String getWWFromButton(Block block) {
Block attempt = block.getRelative(BlockFace.NORTH, 3);
if (isWW(attempt.getLocation())) {
return portalConfig.getString(attempt.getWorld().getName() + "." + attempt.getX() + "_" + attempt.getY() + "_" + attempt.getZ() + ".location");
}
//Try SOUTH
attempt = block.getRelative(BlockFace.SOUTH, 3);
if (isWW(attempt.getLocation())) {
return portalConfig.getString(attempt.getWorld().getName() + "." + attempt.getX() + "_" + attempt.getY() + "_" + attempt.getZ() + ".location");
}
//Try EAST
attempt = block.getRelative(BlockFace.EAST, 3);
if (isWW(attempt.getLocation())) {
return portalConfig.getString(attempt.getWorld().getName() + "." + attempt.getX() + "_" + attempt.getY() + "_" + attempt.getZ() + ".location");
}
//Try WEST
attempt = block.getRelative(BlockFace.WEST, 3);
if (isWW(attempt.getLocation())) {
return portalConfig.getString(attempt.getWorld().getName() + "." + attempt.getX() + "_" + attempt.getY() + "_" + attempt.getZ() + ".location");
}
return "";
}
private boolean delete(File folder) {
if (folder.isDirectory()) {
for (File f : folder.listFiles()) {
if (!delete(f)) return false;
}
}
return folder.delete();
}
private File getWorldDataFolder(String worldname) {
return new File(getDataFolder().getAbsoluteFile().getParentFile().getParentFile().getAbsolutePath() + File.separator + worldname);
}
public void forceWorldLoads() {
Object[] configWorlds = portalConfig.getKeys(false).toArray();
for (int x = 0; x < configWorlds.length; x++) {
ConfigurationSection section = portalConfig.getConfigurationSection(configWorlds[x].toString());
if (section != null) {
Object[] configKeys = section.getKeys(false).toArray();
if (!section.getName().contains("_nether") && !section.getName().contains("_the_end")) {
if (getServer().getWorld(section.getName()) == null) {
WorldCreator wc = makeWorld(section.getName(), null);
getServer().createWorld(wc);
}
}
for (int i = 0; i < configKeys.length; i++) {
String key = configKeys[i].toString();
String destination = section.getString(key + ".destination");
if (getServer().getWorld(destination) == null && destinations.get(destination) == null) {
WorldCreator wc = makeWorld(destination, null);
getServer().createWorld(wc);
}
}
}
}
}
private WorldCreator makeWorld(String worldName, CommandSender sender) {
WorldCreator wc = new WorldCreator(worldName);
wc.seed(new Random().nextLong());
wc.environment(World.Environment.NORMAL);
//wc.generator(this.getName(), sender);
return wc;
}
private void loadPortals() {
if (portalFile == null) {
portalFile = new File(getDataFolder(),"portals.yml");
}
portalConfig = YamlConfiguration.loadConfiguration(portalFile);
}
private FileConfiguration getPortals() {
if (portalConfig == null) {
loadPortals();
}
return portalConfig;
}
private void savePortals() {
if (portalConfig == null || portalFile == null) {
return;
}
try {
portalConfig.save(portalFile);
} catch (IOException ex) {
getLogger().log(Level.SEVERE, "Could not save " + portalFile, ex );
}
}
}
| true | true | public boolean onCommand (CommandSender sender, Command cmd, String commandLabel, String[] args) {
if (commandLabel.equalsIgnoreCase("ww")) {
if (args.length == 0) {
String version = getDescription().getVersion();
sender.sendMessage(ChatColor.GOLD + "WhooshingWell v" + ChatColor.WHITE + version + ChatColor.GOLD + " by " + ChatColor.WHITE + "ellbristow");
sender.sendMessage(ChatColor.GOLD + "=============");
sender.sendMessage(ChatColor.GOLD + "Require Empty Inventory : " + ChatColor.WHITE + clearInv);
sender.sendMessage(ChatColor.GOLD + "Require No Armor : " + ChatColor.WHITE + clearArmor);
sender.sendMessage(ChatColor.GOLD + "Allow Nether Wells : " + ChatColor.WHITE + allowNether);
sender.sendMessage(ChatColor.GOLD + "Allow End Wells : " + ChatColor.WHITE + allowEnd);
return true;
} else if (args.length == 1) {
if ("list".equalsIgnoreCase(args[0])) {
if (!sender.hasPermission("whooshingwell.world.list")) {
sender.sendMessage(ChatColor.RED + "You do not have permission to use this command!");
return true;
}
Object[] worlds = getServer().getWorlds().toArray();
sender.sendMessage(ChatColor.GOLD + "World List");
sender.sendMessage(ChatColor.GOLD + "==========");
for (int i = 0; i < worlds.length; i++) {
World world = (World)worlds[i];
if (!(world.getEnvironment().equals(Environment.NETHER) && !allowNether) && !(world.getEnvironment().equals(Environment.THE_END) && !allowEnd)) {
sender.sendMessage(ChatColor.GOLD + world.getName() + ChatColor.GRAY + " ("+i+")");
}
}
for (String key : destinations.keySet()) {
Location loc = destinations.get(key);
World world = loc.getWorld();
if (!(world.getEnvironment().equals(Environment.NETHER) && !allowNether) && !(world.getEnvironment().equals(Environment.THE_END) && !allowEnd)) {
sender.sendMessage(ChatColor.YELLOW + key);
}
}
return true;
} else if (args[0].equalsIgnoreCase("toggle")) {
if (!sender.hasPermission("whooshingwell.toggle.emptyinv") && !sender.hasPermission("whooshingwell.toggle.emptyarmor") && !sender.hasPermission("whooshingwell.toggle.allownether") && !sender.hasPermission("whooshingwell.toggle.allowend")) {
sender.sendMessage(ChatColor.RED + "You do not have permission to use this command!");
return true;
}
sender.sendMessage(ChatColor.RED + "You must specify a setting to toggle!");
if (sender.hasPermission("whooshingwell.toggle.emptyinv")) {
sender.sendMessage(ChatColor.GRAY + "EmptyInv: Players cannot carry inventory through portals");
}
if (sender.hasPermission("whooshingwell.toggle.emptyarmor")) {
sender.sendMessage(ChatColor.GRAY + "EmptyArmor: Players cannot wear armor through portals");
}
if (sender.hasPermission("whooshingwell.toggle.allownether")) {
sender.sendMessage(ChatColor.GRAY + "AllowNether: New wells can lead to Nether worlds");
}
if (sender.hasPermission("whooshingwell.toggle.allowend")) {
sender.sendMessage(ChatColor.GRAY + "AllowEnd: New wells can lean to End worlds");
}
return true;
} else if (args[0].equalsIgnoreCase("addworld")) {
if (!sender.hasPermission("whooshingwell.world.create")) {
sender.sendMessage(ChatColor.RED + "You do not have permission to use this command!");
return true;
}
sender.sendMessage(ChatColor.RED + "You must specify a world name!");
sender.sendMessage(ChatColor.RED + "/ww addworld [World Name]");
return true;
} else if (args[0].equalsIgnoreCase("deleteworld") || args[0].equalsIgnoreCase("delworld")) {
if (!sender.hasPermission("whooshingwell.world.delete")) {
sender.sendMessage(ChatColor.RED + "You do not have permission to use this command!");
return true;
}
sender.sendMessage(ChatColor.RED + "You must specify a world name!");
sender.sendMessage(ChatColor.RED + "/ww addworld [World Name]");
return true;
} else if (args[0].equalsIgnoreCase("setdest")) {
if (!(sender instanceof Player)) {
sender.sendMessage(ChatColor.RED + "This command cannot be run from the console!");
return true;
}
if (!sender.hasPermission("whooshingwell.setdest")) {
sender.sendMessage(ChatColor.RED + "You do not have permission to use this command!");
return true;
}
sender.sendMessage(ChatColor.RED + "You must specify a destination name!");
sender.sendMessage(ChatColor.RED + "/ww setdest [Destination Name]");
return true;
} else if (args[0].equalsIgnoreCase("deldest")) {
if (!sender.hasPermission("whooshingwell.deldest")) {
sender.sendMessage(ChatColor.RED + "You do not have permission to use this command!");
return true;
}
sender.sendMessage(ChatColor.RED + "You must specify a destination name!");
sender.sendMessage(ChatColor.RED + "/ww deldest [Destination Name]");
return true;
}
} else if (args.length == 2) {
if (args[0].equalsIgnoreCase("addworld")) {
if (!sender.hasPermission("whooshingwell.world.create")) {
sender.sendMessage(ChatColor.RED + "You do not have permission to use this command!");
return true;
}
if (getServer().getWorld(args[1]) != null){
sender.sendMessage(ChatColor.RED + "A world called '" + ChatColor.WHITE + args[1] + ChatColor.RED + "' already exists!");
return true;
} else if (args[1].length() < 4) {
sender.sendMessage(ChatColor.RED + "Please use a name with at least 4 characters!");
return true;
} else {
sender.sendMessage(ChatColor.GOLD + "Creating '" + ChatColor.WHITE + args[1] + ChatColor.GOLD + "'!");
getServer().broadcastMessage(ChatColor.LIGHT_PURPLE + "A new world has been found!");
getServer().broadcastMessage(ChatColor.LIGHT_PURPLE + "You may experience some lag while we map it!");
WorldCreator wc = makeWorld(args[1], sender);
getServer().createWorld(wc);
return true;
}
} else if ((args[0].equalsIgnoreCase("deleteworld") || args[0].equalsIgnoreCase("delworld"))) {
if (!sender.hasPermission("whooshingwell.world.delete")) {
sender.sendMessage(ChatColor.RED + "You do not have permission to use this command!");
return true;
}
if (getServer().getWorld(args[1]) == null){
sender.sendMessage(ChatColor.RED + "There is no world called '" + ChatColor.WHITE + args[1] + ChatColor.RED + "'!");
return true;
} else if (args[1].equalsIgnoreCase(getServer().getWorlds().get(0).getName())) {
sender.sendMessage(ChatColor.RED + "You cannot delete the default world!");
return true;
} else if (!getServer().getWorld(args[1]).getPlayers().isEmpty()) {
sender.sendMessage(ChatColor.RED + "There are players in " + ChatColor.WHITE + args[1] + ChatColor.RED + "!");
sender.sendMessage(ChatColor.RED + "All players must leave " + ChatColor.WHITE + args[1] + ChatColor.RED + " to delete it!");
return true;
} else {
getServer().unloadWorld(getServer().getWorld(args[1]), false);
sender.sendMessage(ChatColor.GOLD + "Deleting '" + ChatColor.WHITE + args[1] + ChatColor.GOLD + "'!");
getServer().broadcastMessage(ChatColor.LIGHT_PURPLE + "A world is collapsing!");
getServer().broadcastMessage(ChatColor.LIGHT_PURPLE + "You may experience some lag while we tidy it!");
delete(getWorldDataFolder(args[1]));
portalConfig.set(args[1], null);
return true;
}
} else if (args[0].equalsIgnoreCase("setdest")) {
if (!(sender instanceof Player)) {
sender.sendMessage(ChatColor.RED + "This command cannot be run from the console!");
return true;
}
if (!sender.hasPermission("whooshingwell.setdest")) {
sender.sendMessage(ChatColor.RED + "You do not have permission to use this command!");
return true;
}
if (getServer().getWorld(args[1]) != null) {
sender.sendMessage(ChatColor.RED + "You cannot set a destination with the same name as a world!");
sender.sendMessage(ChatColor.RED + "/ww setdest [Destination Name]");
return true;
}
Player player = (Player)sender;
World world = player.getWorld();
if (world.getEnvironment().equals(Environment.NETHER) && !allowNether) {
player.sendMessage(ChatColor.RED + "Whooshing wells cannot lead to Nether worlds");
return true;
} else if (world.getEnvironment().equals(Environment.THE_END) && !allowEnd) {
player.sendMessage(ChatColor.RED + "Whooshing wells cannot lead to End worlds");
return true;
}
Location loc = player.getLocation();
destinations.put(args[1].toLowerCase(), loc);
config.set("destinations."+args[1]+".world", loc.getWorld().getName());
config.set("destinations."+args[1]+".x", loc.getX());
config.set("destinations."+args[1]+".y", loc.getY());
config.set("destinations."+args[1]+".z", loc.getZ());
List<Float> yawpitch = new ArrayList<Float>();
yawpitch.add(loc.getYaw());
yawpitch.add(loc.getPitch());
config.set("destinations."+args[1].toLowerCase()+".yawpitch", yawpitch);
saveConfig();
player.sendMessage(ChatColor.GOLD + "New destination " + ChatColor.WHITE + args[1] + ChatColor.GOLD + " set!");
return true;
} else if (args[0].equalsIgnoreCase("deldest")) {
if (!sender.hasPermission("whooshingwell.deldest")) {
sender.sendMessage(ChatColor.RED + "You do not have permission to use this command!");
return true;
}
if (destinations.get(args[1].toLowerCase()) == null) {
sender.sendMessage(ChatColor.RED + "Destination "+ChatColor.WHITE +args[1]+ ChatColor.RED+" not found!");
return true;
}
destinations.remove(args[1].toLowerCase());
config.set("destinations."+args[1].toLowerCase(), null);
sender.sendMessage(ChatColor.GOLD + "Destination " + ChatColor.WHITE + args[1] + ChatColor.GOLD + " deleted!");
return true;
} else if (args[0].equalsIgnoreCase("toggle")) {
if (args[1].equalsIgnoreCase("EmptyInv")) {
if (!sender.hasPermission("whooshingwell.toggle.emptyinv")) {
sender.sendMessage(ChatColor.RED + "You do not have permission to toggle this setting!");
return true;
}
if (clearInv) {
clearInv = false;
sender.sendMessage(ChatColor.GOLD + "Players no longer need to empty their inventory to use Whooshing Wells!");
} else {
clearInv = true;
sender.sendMessage(ChatColor.GOLD + "Players must now empty their inventory to use Whooshing Wells!");
}
config.set("requireEmptyInventory", clearInv);
saveConfig();
return true;
} else if (args[1].equalsIgnoreCase("EmptyArmor")) {
if (!sender.hasPermission("whooshingwell.toggle.emptyinv")) {
sender.sendMessage(ChatColor.RED + "You do not have permission to toggle this setting!");
return true;
}
if (clearArmor) {
clearArmor = false;
sender.sendMessage(ChatColor.GOLD + "Players no longer need to remove their armor to use Whooshing Wells!");
} else {
clearArmor = true;
sender.sendMessage(ChatColor.GOLD + "Players must now remove their armor to use Whooshing Wells!");
}
config.set("requireEmptyArmor", clearArmor);
saveConfig();
return true;
} else if (args[1].equalsIgnoreCase("AllowNether")) {
if (!sender.hasPermission("whooshingwell.toggle.allownether")) {
sender.sendMessage(ChatColor.RED + "You do not have permission to toggle this setting!");
return true;
}
if (allowNether) {
allowNether = false;
sender.sendMessage(ChatColor.GOLD + "New wells now CANNOT lead to Nether worlds!");
} else {
allowNether = true;
sender.sendMessage(ChatColor.GOLD + "New wells now CAN lead to Nether worlds!");
}
config.set("allowNetherWells", allowNether);
saveConfig();
return true;
} else if (args[1].equalsIgnoreCase("AllowEnd")) {
if (!sender.hasPermission("whooshingwell.toggle.allowend")) {
sender.sendMessage(ChatColor.RED + "You do not have permission to toggle this setting!");
return true;
}
if (allowEnd) {
allowEnd = false;
sender.sendMessage(ChatColor.GOLD + "New wells now CANNOT lead to End worlds!");
} else {
allowEnd = true;
sender.sendMessage(ChatColor.GOLD + "New wells now CAN lead to End worlds!");
}
config.set("allowEndWells", allowEnd);
saveConfig();
return true;
}
sender.sendMessage(ChatColor.RED + "Sorry! I dont' recognise that toggle option!");
return true;
}
}
}
sender.sendMessage(ChatColor.RED + "Sorry! That command was not recognised!");
return true;
}
| public boolean onCommand (CommandSender sender, Command cmd, String commandLabel, String[] args) {
if (commandLabel.equalsIgnoreCase("ww")) {
if (args.length == 0) {
String version = getDescription().getVersion();
sender.sendMessage(ChatColor.GOLD + "WhooshingWell v" + ChatColor.WHITE + version + ChatColor.GOLD + " by " + ChatColor.WHITE + "ellbristow");
sender.sendMessage(ChatColor.GOLD + "=============");
sender.sendMessage(ChatColor.GOLD + "Require Empty Inventory : " + ChatColor.WHITE + clearInv);
sender.sendMessage(ChatColor.GOLD + "Require No Armor : " + ChatColor.WHITE + clearArmor);
sender.sendMessage(ChatColor.GOLD + "Allow Nether Wells : " + ChatColor.WHITE + allowNether);
sender.sendMessage(ChatColor.GOLD + "Allow End Wells : " + ChatColor.WHITE + allowEnd);
return true;
} else if (args.length == 1) {
if ("list".equalsIgnoreCase(args[0])) {
if (!sender.hasPermission("whooshingwell.world.list")) {
sender.sendMessage(ChatColor.RED + "You do not have permission to use this command!");
return true;
}
Object[] worlds = getServer().getWorlds().toArray();
sender.sendMessage(ChatColor.GOLD + "World List");
sender.sendMessage(ChatColor.GOLD + "==========");
for (int i = 0; i < worlds.length; i++) {
World world = (World)worlds[i];
if (!(world.getEnvironment().equals(Environment.NETHER) && !allowNether) && !(world.getEnvironment().equals(Environment.THE_END) && !allowEnd)) {
sender.sendMessage(ChatColor.GOLD + world.getName() + ChatColor.GRAY + " ("+i+")");
}
}
for (String key : destinations.keySet()) {
Location loc = destinations.get(key);
World world = loc.getWorld();
if (!(world.getEnvironment().equals(Environment.NETHER) && !allowNether) && !(world.getEnvironment().equals(Environment.THE_END) && !allowEnd)) {
sender.sendMessage(ChatColor.YELLOW + key);
}
}
return true;
} else if (args[0].equalsIgnoreCase("toggle")) {
if (!sender.hasPermission("whooshingwell.toggle.emptyinv") && !sender.hasPermission("whooshingwell.toggle.emptyarmor") && !sender.hasPermission("whooshingwell.toggle.allownether") && !sender.hasPermission("whooshingwell.toggle.allowend")) {
sender.sendMessage(ChatColor.RED + "You do not have permission to use this command!");
return true;
}
sender.sendMessage(ChatColor.RED + "You must specify a setting to toggle!");
if (sender.hasPermission("whooshingwell.toggle.emptyinv")) {
sender.sendMessage(ChatColor.GRAY + "EmptyInv: Players cannot carry inventory through portals");
}
if (sender.hasPermission("whooshingwell.toggle.emptyarmor")) {
sender.sendMessage(ChatColor.GRAY + "EmptyArmor: Players cannot wear armor through portals");
}
if (sender.hasPermission("whooshingwell.toggle.allownether")) {
sender.sendMessage(ChatColor.GRAY + "AllowNether: New wells can lead to Nether worlds");
}
if (sender.hasPermission("whooshingwell.toggle.allowend")) {
sender.sendMessage(ChatColor.GRAY + "AllowEnd: New wells can lean to End worlds");
}
return true;
} else if (args[0].equalsIgnoreCase("addworld")) {
if (!sender.hasPermission("whooshingwell.world.create")) {
sender.sendMessage(ChatColor.RED + "You do not have permission to use this command!");
return true;
}
sender.sendMessage(ChatColor.RED + "You must specify a world name!");
sender.sendMessage(ChatColor.RED + "/ww addworld [World Name]");
return true;
} else if (args[0].equalsIgnoreCase("deleteworld") || args[0].equalsIgnoreCase("delworld")) {
if (!sender.hasPermission("whooshingwell.world.delete")) {
sender.sendMessage(ChatColor.RED + "You do not have permission to use this command!");
return true;
}
sender.sendMessage(ChatColor.RED + "You must specify a world name!");
sender.sendMessage(ChatColor.RED + "/ww addworld [World Name]");
return true;
} else if (args[0].equalsIgnoreCase("setdest")) {
if (!(sender instanceof Player)) {
sender.sendMessage(ChatColor.RED + "This command cannot be run from the console!");
return true;
}
if (!sender.hasPermission("whooshingwell.setdest")) {
sender.sendMessage(ChatColor.RED + "You do not have permission to use this command!");
return true;
}
sender.sendMessage(ChatColor.RED + "You must specify a destination name!");
sender.sendMessage(ChatColor.RED + "/ww setdest [Destination Name]");
return true;
} else if (args[0].equalsIgnoreCase("deldest")) {
if (!sender.hasPermission("whooshingwell.deldest")) {
sender.sendMessage(ChatColor.RED + "You do not have permission to use this command!");
return true;
}
sender.sendMessage(ChatColor.RED + "You must specify a destination name!");
sender.sendMessage(ChatColor.RED + "/ww deldest [Destination Name]");
return true;
}
} else if (args.length == 2) {
if (args[0].equalsIgnoreCase("addworld")) {
if (!sender.hasPermission("whooshingwell.world.create")) {
sender.sendMessage(ChatColor.RED + "You do not have permission to use this command!");
return true;
}
if (getServer().getWorld(args[1]) != null){
sender.sendMessage(ChatColor.RED + "A world called '" + ChatColor.WHITE + args[1] + ChatColor.RED + "' already exists!");
return true;
} else if (args[1].length() < 4) {
sender.sendMessage(ChatColor.RED + "Please use a name with at least 4 characters!");
return true;
} else {
sender.sendMessage(ChatColor.GOLD + "Creating '" + ChatColor.WHITE + args[1] + ChatColor.GOLD + "'!");
getServer().broadcastMessage(ChatColor.LIGHT_PURPLE + "A new world has been found!");
getServer().broadcastMessage(ChatColor.LIGHT_PURPLE + "You may experience some lag while we map it!");
WorldCreator wc = makeWorld(args[1], sender);
getServer().createWorld(wc);
return true;
}
} else if ((args[0].equalsIgnoreCase("deleteworld") || args[0].equalsIgnoreCase("delworld"))) {
if (!sender.hasPermission("whooshingwell.world.delete")) {
sender.sendMessage(ChatColor.RED + "You do not have permission to use this command!");
return true;
}
if (getServer().getWorld(args[1]) == null){
sender.sendMessage(ChatColor.RED + "There is no world called '" + ChatColor.WHITE + args[1] + ChatColor.RED + "'!");
return true;
} else if (args[1].equalsIgnoreCase(getServer().getWorlds().get(0).getName())) {
sender.sendMessage(ChatColor.RED + "You cannot delete the default world!");
return true;
} else if (!getServer().getWorld(args[1]).getPlayers().isEmpty()) {
sender.sendMessage(ChatColor.RED + "There are players in " + ChatColor.WHITE + args[1] + ChatColor.RED + "!");
sender.sendMessage(ChatColor.RED + "All players must leave " + ChatColor.WHITE + args[1] + ChatColor.RED + " to delete it!");
return true;
} else {
getServer().unloadWorld(getServer().getWorld(args[1]), false);
sender.sendMessage(ChatColor.GOLD + "Deleting '" + ChatColor.WHITE + args[1] + ChatColor.GOLD + "'!");
getServer().broadcastMessage(ChatColor.LIGHT_PURPLE + "A world is collapsing!");
getServer().broadcastMessage(ChatColor.LIGHT_PURPLE + "You may experience some lag while we tidy it!");
delete(getWorldDataFolder(args[1]));
portalConfig.set(args[1], null);
return true;
}
} else if (args[0].equalsIgnoreCase("setdest")) {
if (!(sender instanceof Player)) {
sender.sendMessage(ChatColor.RED + "This command cannot be run from the console!");
return true;
}
if (!sender.hasPermission("whooshingwell.setdest")) {
sender.sendMessage(ChatColor.RED + "You do not have permission to use this command!");
return true;
}
if (getServer().getWorld(args[1]) != null) {
sender.sendMessage(ChatColor.RED + "You cannot set a destination with the same name as a world!");
sender.sendMessage(ChatColor.RED + "/ww setdest [Destination Name]");
return true;
}
Player player = (Player)sender;
World world = player.getWorld();
if (world.getEnvironment().equals(Environment.NETHER) && !allowNether) {
player.sendMessage(ChatColor.RED + "Whooshing wells cannot lead to Nether worlds");
return true;
} else if (world.getEnvironment().equals(Environment.THE_END) && !allowEnd) {
player.sendMessage(ChatColor.RED + "Whooshing wells cannot lead to End worlds");
return true;
}
Location loc = player.getLocation();
destinations.put(args[1].toLowerCase(), loc);
config.set("destinations."+args[1].toLowerCase()+".world", loc.getWorld().getName());
config.set("destinations."+args[1].toLowerCase()+".x", loc.getX());
config.set("destinations."+args[1].toLowerCase()+".y", loc.getY());
config.set("destinations."+args[1].toLowerCase()+".z", loc.getZ());
List<Float> yawpitch = new ArrayList<Float>();
yawpitch.add(loc.getYaw());
yawpitch.add(loc.getPitch());
config.set("destinations."+args[1].toLowerCase()+".yawpitch", yawpitch);
saveConfig();
player.sendMessage(ChatColor.GOLD + "New destination " + ChatColor.WHITE + args[1] + ChatColor.GOLD + " set!");
return true;
} else if (args[0].equalsIgnoreCase("deldest")) {
if (!sender.hasPermission("whooshingwell.deldest")) {
sender.sendMessage(ChatColor.RED + "You do not have permission to use this command!");
return true;
}
if (destinations.get(args[1].toLowerCase()) == null) {
sender.sendMessage(ChatColor.RED + "Destination "+ChatColor.WHITE +args[1]+ ChatColor.RED+" not found!");
return true;
}
destinations.remove(args[1].toLowerCase());
config.set("destinations."+args[1].toLowerCase(), null);
sender.sendMessage(ChatColor.GOLD + "Destination " + ChatColor.WHITE + args[1] + ChatColor.GOLD + " deleted!");
return true;
} else if (args[0].equalsIgnoreCase("toggle")) {
if (args[1].equalsIgnoreCase("EmptyInv")) {
if (!sender.hasPermission("whooshingwell.toggle.emptyinv")) {
sender.sendMessage(ChatColor.RED + "You do not have permission to toggle this setting!");
return true;
}
if (clearInv) {
clearInv = false;
sender.sendMessage(ChatColor.GOLD + "Players no longer need to empty their inventory to use Whooshing Wells!");
} else {
clearInv = true;
sender.sendMessage(ChatColor.GOLD + "Players must now empty their inventory to use Whooshing Wells!");
}
config.set("requireEmptyInventory", clearInv);
saveConfig();
return true;
} else if (args[1].equalsIgnoreCase("EmptyArmor")) {
if (!sender.hasPermission("whooshingwell.toggle.emptyinv")) {
sender.sendMessage(ChatColor.RED + "You do not have permission to toggle this setting!");
return true;
}
if (clearArmor) {
clearArmor = false;
sender.sendMessage(ChatColor.GOLD + "Players no longer need to remove their armor to use Whooshing Wells!");
} else {
clearArmor = true;
sender.sendMessage(ChatColor.GOLD + "Players must now remove their armor to use Whooshing Wells!");
}
config.set("requireEmptyArmor", clearArmor);
saveConfig();
return true;
} else if (args[1].equalsIgnoreCase("AllowNether")) {
if (!sender.hasPermission("whooshingwell.toggle.allownether")) {
sender.sendMessage(ChatColor.RED + "You do not have permission to toggle this setting!");
return true;
}
if (allowNether) {
allowNether = false;
sender.sendMessage(ChatColor.GOLD + "New wells now CANNOT lead to Nether worlds!");
} else {
allowNether = true;
sender.sendMessage(ChatColor.GOLD + "New wells now CAN lead to Nether worlds!");
}
config.set("allowNetherWells", allowNether);
saveConfig();
return true;
} else if (args[1].equalsIgnoreCase("AllowEnd")) {
if (!sender.hasPermission("whooshingwell.toggle.allowend")) {
sender.sendMessage(ChatColor.RED + "You do not have permission to toggle this setting!");
return true;
}
if (allowEnd) {
allowEnd = false;
sender.sendMessage(ChatColor.GOLD + "New wells now CANNOT lead to End worlds!");
} else {
allowEnd = true;
sender.sendMessage(ChatColor.GOLD + "New wells now CAN lead to End worlds!");
}
config.set("allowEndWells", allowEnd);
saveConfig();
return true;
}
sender.sendMessage(ChatColor.RED + "Sorry! I dont' recognise that toggle option!");
return true;
}
}
}
sender.sendMessage(ChatColor.RED + "Sorry! That command was not recognised!");
return true;
}
|
diff --git a/drools-jsr94/src/test/java/org/jcp/jsr94/tck/AllTests.java b/drools-jsr94/src/test/java/org/jcp/jsr94/tck/AllTests.java
index 4df4b9a70..10e2fa72b 100644
--- a/drools-jsr94/src/test/java/org/jcp/jsr94/tck/AllTests.java
+++ b/drools-jsr94/src/test/java/org/jcp/jsr94/tck/AllTests.java
@@ -1,102 +1,103 @@
/*
* J A V A C O M M U N I T Y P R O C E S S
*
* J S R 9 4
*
* Test Compatability Kit
*
*/
package org.jcp.jsr94.tck;
// java imports
import junit.framework.Test;
import junit.framework.TestSuite;
import org.jcp.jsr94.tck.admin.LocalRuleExecutionSetProviderTest;
import org.jcp.jsr94.tck.admin.RuleAdministrationExceptionTest;
import org.jcp.jsr94.tck.admin.RuleAdministratorTest;
import org.jcp.jsr94.tck.admin.RuleExecutionSetCreateExceptionTest;
import org.jcp.jsr94.tck.admin.RuleExecutionSetDeregistrationExceptionTest;
import org.jcp.jsr94.tck.admin.RuleExecutionSetProviderTest;
import org.jcp.jsr94.tck.admin.RuleExecutionSetRegisterExceptionTest;
import org.jcp.jsr94.tck.admin.RuleExecutionSetTest;
import org.jcp.jsr94.tck.admin.RuleTest;
/**
* Run all the test suites in the Test Compatability Kit.
* Output is directed to System.out (textui).
*/
public class AllTests extends TestSuite {
public static Test suite() {
// System.setProperty( "jsr94.tck.configuration",
// "src/test/resources/org/drools/jsr94/tck" );
TestSuite suite = new TestSuite( "JSR 94 Test Compatability Kit" );
suite.addTestSuite( ApiSignatureTest.class );
+ //JBRULES-139 TCK-TestCaseUtil needs to be fixed
//suite.addTestSuite( ClassLoaderTest.class );
suite.addTestSuite( ConfigurationExceptionTest.class );
suite.addTestSuite( HandleTest.class );
suite.addTestSuite( InvalidHandleExceptionTest.class );
suite.addTestSuite( InvalidRuleSessionExceptionTest.class );
suite.addTestSuite( ObjectFilterTest.class );
suite.addTestSuite( RuleExceptionTest.class );
suite.addTestSuite( RuleExecutionExceptionTest.class );
suite.addTestSuite( RuleExecutionSetMetadataTest.class );
suite.addTestSuite( RuleExecutionSetNotFoundExceptionTest.class );
suite.addTestSuite( RuleRuntimeTest.class );
suite.addTestSuite( RuleServiceProviderManagerTest.class );
suite.addTestSuite( RuleServiceProviderTest.class );
suite.addTestSuite( RuleSessionCreateExceptionTest.class );
suite.addTestSuite( RuleSessionTest.class );
suite.addTestSuite( RuleSessionTypeUnsupportedExceptionTest.class );
suite.addTestSuite( StatefulRuleSessionTest.class );
suite.addTestSuite( StatelessRuleSessionTest.class );
suite.addTestSuite( LocalRuleExecutionSetProviderTest.class );
suite.addTestSuite( RuleAdministrationExceptionTest.class );
suite.addTestSuite( RuleAdministratorTest.class );
suite.addTestSuite( RuleExecutionSetCreateExceptionTest.class );
// suite.addTestSuite(RuleExecutionSetProviderTest.class);
suite.addTestSuite( RuleExecutionSetRegisterExceptionTest.class );
suite.addTestSuite( RuleExecutionSetTest.class );
suite.addTestSuite( RuleExecutionSetDeregistrationExceptionTest.class );
suite.addTestSuite( RuleTest.class );
return suite;
}
// public static Test suite()
// {
//
//
// TestSuite suite = new TestSuite( "JSR 94 Test Compatability Kit" );
// System.out.println(System.getProperty("jsr94.tck.configuration"));
// suite.addTestSuite(ApiSignatureTest.class);
// suite.addTestSuite(ClassLoaderTest.class);
// suite.addTestSuite(ConfigurationExceptionTest.class);
// suite.addTestSuite(HandleTest.class);
// suite.addTestSuite(InvalidHandleExceptionTest.class);
// suite.addTestSuite(InvalidRuleSessionExceptionTest.class);
// suite.addTestSuite(ObjectFilterTest.class);
// suite.addTestSuite(RuleExceptionTest.class);
// suite.addTestSuite(RuleExecutionExceptionTest.class);
// suite.addTestSuite(RuleExecutionSetMetadataTest.class);
// suite.addTestSuite(RuleExecutionSetNotFoundExceptionTest.class);
// suite.addTestSuite(RuleRuntimeTest.class);
// suite.addTestSuite(RuleServiceProviderManagerTest.class);
// suite.addTestSuite(RuleServiceProviderTest.class);
// suite.addTestSuite(RuleSessionCreateExceptionTest.class);
// suite.addTestSuite(RuleSessionTest.class);
// suite.addTestSuite(RuleSessionTypeUnsupportedExceptionTest.class);
// suite.addTestSuite(StatefulRuleSessionTest.class);
// suite.addTestSuite(StatelessRuleSessionTest.class);
// suite.addTestSuite(LocalRuleExecutionSetProviderTest.class);
// suite.addTestSuite(RuleAdministrationExceptionTest.class);
// suite.addTestSuite(RuleAdministratorTest.class);
// suite.addTestSuite(RuleExecutionSetCreateExceptionTest.class);
//// suite.addTestSuite(RuleExecutionSetProviderTest.class);
// suite.addTestSuite(RuleExecutionSetRegisterExceptionTest.class);
// suite.addTestSuite(RuleExecutionSetTest.class);
// suite.addTestSuite(RuleExecutionSetDeregistrationExceptionTest.class);
// suite.addTestSuite(RuleTest.class);
// return suite;
// }
}
| true | true | public static Test suite() {
// System.setProperty( "jsr94.tck.configuration",
// "src/test/resources/org/drools/jsr94/tck" );
TestSuite suite = new TestSuite( "JSR 94 Test Compatability Kit" );
suite.addTestSuite( ApiSignatureTest.class );
//suite.addTestSuite( ClassLoaderTest.class );
suite.addTestSuite( ConfigurationExceptionTest.class );
suite.addTestSuite( HandleTest.class );
suite.addTestSuite( InvalidHandleExceptionTest.class );
suite.addTestSuite( InvalidRuleSessionExceptionTest.class );
suite.addTestSuite( ObjectFilterTest.class );
suite.addTestSuite( RuleExceptionTest.class );
suite.addTestSuite( RuleExecutionExceptionTest.class );
suite.addTestSuite( RuleExecutionSetMetadataTest.class );
suite.addTestSuite( RuleExecutionSetNotFoundExceptionTest.class );
suite.addTestSuite( RuleRuntimeTest.class );
suite.addTestSuite( RuleServiceProviderManagerTest.class );
suite.addTestSuite( RuleServiceProviderTest.class );
suite.addTestSuite( RuleSessionCreateExceptionTest.class );
suite.addTestSuite( RuleSessionTest.class );
suite.addTestSuite( RuleSessionTypeUnsupportedExceptionTest.class );
suite.addTestSuite( StatefulRuleSessionTest.class );
suite.addTestSuite( StatelessRuleSessionTest.class );
suite.addTestSuite( LocalRuleExecutionSetProviderTest.class );
suite.addTestSuite( RuleAdministrationExceptionTest.class );
suite.addTestSuite( RuleAdministratorTest.class );
suite.addTestSuite( RuleExecutionSetCreateExceptionTest.class );
// suite.addTestSuite(RuleExecutionSetProviderTest.class);
suite.addTestSuite( RuleExecutionSetRegisterExceptionTest.class );
suite.addTestSuite( RuleExecutionSetTest.class );
suite.addTestSuite( RuleExecutionSetDeregistrationExceptionTest.class );
suite.addTestSuite( RuleTest.class );
return suite;
}
| public static Test suite() {
// System.setProperty( "jsr94.tck.configuration",
// "src/test/resources/org/drools/jsr94/tck" );
TestSuite suite = new TestSuite( "JSR 94 Test Compatability Kit" );
suite.addTestSuite( ApiSignatureTest.class );
//JBRULES-139 TCK-TestCaseUtil needs to be fixed
//suite.addTestSuite( ClassLoaderTest.class );
suite.addTestSuite( ConfigurationExceptionTest.class );
suite.addTestSuite( HandleTest.class );
suite.addTestSuite( InvalidHandleExceptionTest.class );
suite.addTestSuite( InvalidRuleSessionExceptionTest.class );
suite.addTestSuite( ObjectFilterTest.class );
suite.addTestSuite( RuleExceptionTest.class );
suite.addTestSuite( RuleExecutionExceptionTest.class );
suite.addTestSuite( RuleExecutionSetMetadataTest.class );
suite.addTestSuite( RuleExecutionSetNotFoundExceptionTest.class );
suite.addTestSuite( RuleRuntimeTest.class );
suite.addTestSuite( RuleServiceProviderManagerTest.class );
suite.addTestSuite( RuleServiceProviderTest.class );
suite.addTestSuite( RuleSessionCreateExceptionTest.class );
suite.addTestSuite( RuleSessionTest.class );
suite.addTestSuite( RuleSessionTypeUnsupportedExceptionTest.class );
suite.addTestSuite( StatefulRuleSessionTest.class );
suite.addTestSuite( StatelessRuleSessionTest.class );
suite.addTestSuite( LocalRuleExecutionSetProviderTest.class );
suite.addTestSuite( RuleAdministrationExceptionTest.class );
suite.addTestSuite( RuleAdministratorTest.class );
suite.addTestSuite( RuleExecutionSetCreateExceptionTest.class );
// suite.addTestSuite(RuleExecutionSetProviderTest.class);
suite.addTestSuite( RuleExecutionSetRegisterExceptionTest.class );
suite.addTestSuite( RuleExecutionSetTest.class );
suite.addTestSuite( RuleExecutionSetDeregistrationExceptionTest.class );
suite.addTestSuite( RuleTest.class );
return suite;
}
|
diff --git a/src/main/java/de/minestar/FifthElement/commands/bank/cmdBank.java b/src/main/java/de/minestar/FifthElement/commands/bank/cmdBank.java
index 97c3538..90b6482 100644
--- a/src/main/java/de/minestar/FifthElement/commands/bank/cmdBank.java
+++ b/src/main/java/de/minestar/FifthElement/commands/bank/cmdBank.java
@@ -1,78 +1,78 @@
/*
* Copyright (C) 2012 MineStar.de
*
* This file is part of FifthElement.
*
* FifthElement is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, version 3 of the License.
*
* FifthElement is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with FifthElement. If not, see <http://www.gnu.org/licenses/>.
*/
package de.minestar.FifthElement.commands.bank;
import org.bukkit.entity.Player;
import de.minestar.FifthElement.core.Core;
import de.minestar.FifthElement.data.Bank;
import de.minestar.FifthElement.statistics.bank.BankStat;
import de.minestar.illuminati.IlluminatiCore;
import de.minestar.minestarlibrary.commands.AbstractCommand;
import de.minestar.minestarlibrary.utils.PlayerUtils;
public class cmdBank extends AbstractCommand {
private static final String OTHER_BANK_PERMISSION = "fifthelement.command.otherbank";
public cmdBank(String syntax, String arguments, String node) {
super(Core.NAME, syntax, arguments, node);
}
@Override
public void execute(String[] args, Player player) {
Bank bank = null;
// OWN HOME
if (args.length == 0) {
bank = Core.bankManager.getBank(player.getName());
if (bank == null) {
PlayerUtils.sendError(player, pluginName, "Du hast keine Bank!");
return;
}
player.teleport(bank.getLocation());
PlayerUtils.sendSuccess(player, pluginName, "Willkommen in deiner Bank.");
}
// HOME OF OTHER PLAYER
else if (args.length == 1) {
- // CAN PLAYER USE OTHER HOMES
+ // CAN PLAYER USE OTHER BANKS
if (checkSpecialPermission(player, OTHER_BANK_PERMISSION)) {
// FIND THE CORRECT PLAYER NAME
String targetName = PlayerUtils.getCorrectPlayerName(args[0]);
if (targetName == null) {
PlayerUtils.sendError(player, targetName, "Kann den Spieler '" + args[0] + "' nicht finden!");
return;
}
bank = Core.bankManager.getBank(targetName);
if (bank == null) {
PlayerUtils.sendError(player, pluginName, "Der Spieler '" + targetName + "' hat keine Bank!");
return;
}
PlayerUtils.sendSuccess(player, pluginName, "Bank von '" + bank.getOwner() + "'.");
}
}
// WRONG COMMAND SYNTAX
else {
PlayerUtils.sendError(player, pluginName, getHelpMessage());
return;
}
// FIRE STATISTIC
IlluminatiCore.handleStatistic(new BankStat(player.getName(), bank.getOwner()));
}
}
| true | true | public void execute(String[] args, Player player) {
Bank bank = null;
// OWN HOME
if (args.length == 0) {
bank = Core.bankManager.getBank(player.getName());
if (bank == null) {
PlayerUtils.sendError(player, pluginName, "Du hast keine Bank!");
return;
}
player.teleport(bank.getLocation());
PlayerUtils.sendSuccess(player, pluginName, "Willkommen in deiner Bank.");
}
// HOME OF OTHER PLAYER
else if (args.length == 1) {
// CAN PLAYER USE OTHER HOMES
if (checkSpecialPermission(player, OTHER_BANK_PERMISSION)) {
// FIND THE CORRECT PLAYER NAME
String targetName = PlayerUtils.getCorrectPlayerName(args[0]);
if (targetName == null) {
PlayerUtils.sendError(player, targetName, "Kann den Spieler '" + args[0] + "' nicht finden!");
return;
}
bank = Core.bankManager.getBank(targetName);
if (bank == null) {
PlayerUtils.sendError(player, pluginName, "Der Spieler '" + targetName + "' hat keine Bank!");
return;
}
PlayerUtils.sendSuccess(player, pluginName, "Bank von '" + bank.getOwner() + "'.");
}
}
// WRONG COMMAND SYNTAX
else {
PlayerUtils.sendError(player, pluginName, getHelpMessage());
return;
}
// FIRE STATISTIC
IlluminatiCore.handleStatistic(new BankStat(player.getName(), bank.getOwner()));
}
| public void execute(String[] args, Player player) {
Bank bank = null;
// OWN HOME
if (args.length == 0) {
bank = Core.bankManager.getBank(player.getName());
if (bank == null) {
PlayerUtils.sendError(player, pluginName, "Du hast keine Bank!");
return;
}
player.teleport(bank.getLocation());
PlayerUtils.sendSuccess(player, pluginName, "Willkommen in deiner Bank.");
}
// HOME OF OTHER PLAYER
else if (args.length == 1) {
// CAN PLAYER USE OTHER BANKS
if (checkSpecialPermission(player, OTHER_BANK_PERMISSION)) {
// FIND THE CORRECT PLAYER NAME
String targetName = PlayerUtils.getCorrectPlayerName(args[0]);
if (targetName == null) {
PlayerUtils.sendError(player, targetName, "Kann den Spieler '" + args[0] + "' nicht finden!");
return;
}
bank = Core.bankManager.getBank(targetName);
if (bank == null) {
PlayerUtils.sendError(player, pluginName, "Der Spieler '" + targetName + "' hat keine Bank!");
return;
}
PlayerUtils.sendSuccess(player, pluginName, "Bank von '" + bank.getOwner() + "'.");
}
}
// WRONG COMMAND SYNTAX
else {
PlayerUtils.sendError(player, pluginName, getHelpMessage());
return;
}
// FIRE STATISTIC
IlluminatiCore.handleStatistic(new BankStat(player.getName(), bank.getOwner()));
}
|
diff --git a/src/gov/nist/core/NameValue.java b/src/gov/nist/core/NameValue.java
index 53c2560d..30f2a64e 100755
--- a/src/gov/nist/core/NameValue.java
+++ b/src/gov/nist/core/NameValue.java
@@ -1,222 +1,226 @@
/*
* Conditions Of Use
*
* This software was developed by employees of the National Institute of
* Standards and Technology (NIST), an agency of the Federal Government.
* Pursuant to title 15 Untied States Code Section 105, works of NIST
* employees are not subject to copyright protection in the United States
* and are considered to be in the public domain. As a result, a formal
* license is not needed to use the software.
*
* This software is provided by NIST as a service and is expressly
* provided "AS IS." NIST MAKES NO WARRANTY OF ANY KIND, EXPRESS, IMPLIED
* OR STATUTORY, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTY OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, NON-INFRINGEMENT
* AND DATA ACCURACY. NIST does not warrant or make any representations
* regarding the use of the software or the results thereof, including but
* not limited to the correctness, accuracy, reliability or usefulness of
* the software.
*
* Permission to use this software is contingent upon your acceptance
* of the terms of this agreement
*
* .
*
*/
/*******************************************************************************
* Product of NIST/ITL Advanced Networking Technologies Division (ANTD). *
*******************************************************************************/
package gov.nist.core;
/*
* Bug reports and fixes: Kirby Kiem, Jeroen van Bemmel.
*/
/**
* Generic structure for storing name-value pairs.
*
* @version 1.2
*
* @author M. Ranganathan <br/>
*
*
*
*/
public class NameValue extends GenericObject {
protected boolean isQuotedString;
protected final boolean isFlagParameter;
protected String separator;
protected String quotes;
protected String name;
protected Object value;
public NameValue() {
name = null;
value = "";
separator = Separators.EQUALS;
this.quotes = "";
this.isFlagParameter = false;
}
/**
* New constructor, taking a boolean which is set if the NV pair is a flag
*
* @param n
* @param v
* @param isFlag
*/
public NameValue(String n, Object v, boolean isFlag) {
// assert (v != null ); // I dont think this assertion is correct mranga
name = n;
value = v;
separator = Separators.EQUALS;
quotes = "";
this.isFlagParameter = isFlag;
}
/**
* Original constructor, sets isFlagParameter to 'false'
*
* @param n
* @param v
*/
public NameValue(String n, Object v) {
this(n, v, false);
}
/**
* Set the separator for the encoding method below.
*/
public void setSeparator(String sep) {
separator = sep;
}
/**
* A flag that indicates that doublequotes should be put around the value
* when encoded (for example name=value when value is doublequoted).
*/
public void setQuotedValue() {
isQuotedString = true;
this.quotes = Separators.DOUBLE_QUOTE;
}
/**
* Return true if the value is quoted in doublequotes.
*/
public boolean isValueQuoted() {
return isQuotedString;
}
public String getName() {
return name;
}
public Object getValue() {
return isFlagParameter ? "" : value; // never return null for flag
// params
}
/**
* Set the name member
*/
public void setName(String n) {
name = n;
}
/**
* Set the value member
*/
public void setValue(Object v) {
value = v;
}
/**
* Get the encoded representation of this namevalue object. Added
* doublequote for encoding doublequoted values.
*
* Bug: RFC3261 stipulates that an opaque parameter in authenticate header
* has to be:
* opaque = "opaque" EQUAL quoted-string
* so returning just the name is not acceptable. (e.g. LinkSys phones
* are picky about this)
*
* @since 1.0
* @return an encoded name value (eg. name=value) string.
*/
public String encode() {
if (name != null && value != null && !isFlagParameter) {
if (GenericObject.isMySubclass(value.getClass())) {
GenericObject gv = (GenericObject) value;
return name + separator + quotes + gv.encode() + quotes;
} else if (GenericObjectList.isMySubclass(value.getClass())) {
GenericObjectList gvlist = (GenericObjectList) value;
return name + separator + gvlist.encode();
} else if ( value.toString().equals("")) {
// opaque="" bug fix - pmusgrave
- if (name.toString().equals(gov.nist.javax.sip.header.ParameterNames.OPAQUE))
+ /*if (name.toString().equals(gov.nist.javax.sip.header.ParameterNames.OPAQUE))
return name + separator + quotes + quotes;
else
+ return name;*/
+ if ( this.isQuotedString ) {
+ return name + separator + quotes + quotes;
+ } else
return name;
} else
return name + separator + quotes + value.toString() + quotes;
} else if (name == null && value != null) {
if (GenericObject.isMySubclass(value.getClass())) {
GenericObject gv = (GenericObject) value;
return gv.encode();
} else if (GenericObjectList.isMySubclass(value.getClass())) {
GenericObjectList gvlist = (GenericObjectList) value;
return gvlist.encode();
}
return quotes + value.toString() + quotes;
} else if (name != null && (value == null || isFlagParameter)) {
return name;
} else
return "";
}
public Object clone() {
NameValue retval = (NameValue) super.clone();
if (value != null)
retval.value = makeClone(value);
return retval;
}
/**
* Equality comparison predicate.
*/
public boolean equals(Object other) {
if (!other.getClass().equals(this.getClass()))
return false;
NameValue that = (NameValue) other;
if (this == that)
return true;
if (this.name == null && that.name != null || this.name != null
&& that.name == null)
return false;
if (this.name != null && that.name != null
&& this.name.compareToIgnoreCase(that.name) != 0)
return false;
if (this.value != null && that.value == null || this.value == null
&& that.value != null)
return false;
if (this.value == that.value)
return true;
if (value instanceof String) {
// Quoted string comparisions are case sensitive.
if (isQuotedString)
return this.value.equals(that.value);
String val = (String) this.value;
String val1 = (String) that.value;
return val.compareToIgnoreCase(val1) == 0;
} else
return this.value.equals(that.value);
}
}
| false | true | public String encode() {
if (name != null && value != null && !isFlagParameter) {
if (GenericObject.isMySubclass(value.getClass())) {
GenericObject gv = (GenericObject) value;
return name + separator + quotes + gv.encode() + quotes;
} else if (GenericObjectList.isMySubclass(value.getClass())) {
GenericObjectList gvlist = (GenericObjectList) value;
return name + separator + gvlist.encode();
} else if ( value.toString().equals("")) {
// opaque="" bug fix - pmusgrave
if (name.toString().equals(gov.nist.javax.sip.header.ParameterNames.OPAQUE))
return name + separator + quotes + quotes;
else
return name;
} else
return name + separator + quotes + value.toString() + quotes;
} else if (name == null && value != null) {
if (GenericObject.isMySubclass(value.getClass())) {
GenericObject gv = (GenericObject) value;
return gv.encode();
} else if (GenericObjectList.isMySubclass(value.getClass())) {
GenericObjectList gvlist = (GenericObjectList) value;
return gvlist.encode();
}
return quotes + value.toString() + quotes;
} else if (name != null && (value == null || isFlagParameter)) {
return name;
} else
return "";
}
| public String encode() {
if (name != null && value != null && !isFlagParameter) {
if (GenericObject.isMySubclass(value.getClass())) {
GenericObject gv = (GenericObject) value;
return name + separator + quotes + gv.encode() + quotes;
} else if (GenericObjectList.isMySubclass(value.getClass())) {
GenericObjectList gvlist = (GenericObjectList) value;
return name + separator + gvlist.encode();
} else if ( value.toString().equals("")) {
// opaque="" bug fix - pmusgrave
/*if (name.toString().equals(gov.nist.javax.sip.header.ParameterNames.OPAQUE))
return name + separator + quotes + quotes;
else
return name;*/
if ( this.isQuotedString ) {
return name + separator + quotes + quotes;
} else
return name;
} else
return name + separator + quotes + value.toString() + quotes;
} else if (name == null && value != null) {
if (GenericObject.isMySubclass(value.getClass())) {
GenericObject gv = (GenericObject) value;
return gv.encode();
} else if (GenericObjectList.isMySubclass(value.getClass())) {
GenericObjectList gvlist = (GenericObjectList) value;
return gvlist.encode();
}
return quotes + value.toString() + quotes;
} else if (name != null && (value == null || isFlagParameter)) {
return name;
} else
return "";
}
|
diff --git a/OsmAnd/src/net/osmand/access/AccessibilityPlugin.java b/OsmAnd/src/net/osmand/access/AccessibilityPlugin.java
index 63a5fc2e..21084e37 100644
--- a/OsmAnd/src/net/osmand/access/AccessibilityPlugin.java
+++ b/OsmAnd/src/net/osmand/access/AccessibilityPlugin.java
@@ -1,115 +1,115 @@
package net.osmand.access;
import net.osmand.plus.OsmandApplication;
import net.osmand.plus.OsmandPlugin;
import net.osmand.plus.OsmandSettings;
import net.osmand.plus.R;
import net.osmand.plus.activities.MapActivity;
import net.osmand.plus.activities.SettingsActivity;
import android.preference.ListPreference;
import android.preference.Preference;
import android.preference.Preference.OnPreferenceChangeListener;
import android.preference.PreferenceCategory;
import android.preference.PreferenceScreen;
public class AccessibilityPlugin extends OsmandPlugin {
private static final String ID = "osmand.accessibility";
private OsmandSettings settings;
private OsmandApplication app;
private ListPreference accessibilityModePreference;
private ListPreference directionStylePreference;
public AccessibilityPlugin(OsmandApplication app) {
this.app = app;
}
@Override
public boolean init(OsmandApplication app) {
settings = app.getSettings();
return true;
}
@Override
public String getId() {
return ID;
}
@Override
public String getDescription() {
return app.getString(R.string.osmand_accessibility_description);
}
@Override
public String getName() {
return app.getString(R.string.accessibility_preferences);
}
@Override
public void registerLayers(MapActivity activity) {
}
@Override
public void settingsActivityUpdate(SettingsActivity activity) {
if(accessibilityModePreference != null) {
accessibilityModePreference.setSummary(app.getString(R.string.accessibility_mode_descr) + " [" + settings.ACCESSIBILITY_MODE.get().toHumanString(app) + "]");
}
if(directionStylePreference != null) {
directionStylePreference.setSummary(app.getString(R.string.settings_direction_style_descr) + " [" + settings.DIRECTION_STYLE.get().toHumanString(app) + "]");
}
}
@Override
public void settingsActivityCreate(final SettingsActivity activity, final PreferenceScreen screen) {
PreferenceScreen grp = screen.getPreferenceManager().createPreferenceScreen(activity);
grp.setTitle(R.string.accessibility_preferences);
grp.setSummary(R.string.accessibility_preferences_descr);
grp.setKey("accessibility_preferences");
((PreferenceCategory)screen.findPreference("global_settings")).addPreference(grp);
String[] entries = new String[AccessibilityMode.values().length];
for (int i = 0; i < entries.length; i++) {
entries[i] = AccessibilityMode.values()[i].toHumanString(activity);
}
accessibilityModePreference = activity.createListPreference(settings.ACCESSIBILITY_MODE, entries, AccessibilityMode.values(),
R.string.accessibility_mode, R.string.accessibility_mode_descr);
accessibilityModePreference.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
@Override
public boolean onPreferenceChange(Preference preference, Object newValue) {
PreferenceCategory accessibilityOptions = ((PreferenceCategory)(screen.findPreference("accessibility_options")));
if (accessibilityOptions != null)
accessibilityOptions.setEnabled(app.accessibilityEnabled());
accessibilityModePreference.setSummary(app.getString(R.string.accessibility_mode_descr) + " [" + settings.ACCESSIBILITY_MODE.get().toHumanString(app) + "]");
return true;
}
});
grp.addPreference(accessibilityModePreference);
PreferenceCategory cat = new PreferenceCategory(activity);
cat.setKey("accessibility_options");
grp.addPreference(cat);
entries = new String[RelativeDirectionStyle.values().length];
for (int i = 0; i < entries.length; i++) {
entries[i] = RelativeDirectionStyle.values()[i].toHumanString(activity);
}
directionStylePreference = activity.createListPreference(settings.DIRECTION_STYLE, entries, RelativeDirectionStyle.values(),
R.string.settings_direction_style, R.string.settings_direction_style_descr);
directionStylePreference.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
@Override
public boolean onPreferenceChange(Preference preference, Object newValue) {
directionStylePreference.setSummary(app.getString(R.string.settings_direction_style_descr) + " [" + settings.DIRECTION_STYLE.get().toHumanString(app) + "]");
return true;
}
});
cat.addPreference(directionStylePreference);
cat.addPreference(activity.createCheckBoxPreference(settings.ZOOM_BY_TRACKBALL, R.string.zoom_by_trackball,
R.string.zoom_by_trackball_descr));
cat.addPreference(activity.createCheckBoxPreference(settings.SCROLL_MAP_BY_GESTURES, R.string.scroll_map_by_gestures,
R.string.scroll_map_by_gestures_descr));
- cat.addPreference(activity.createCheckBoxPreference(settings.ZOOM_BY_TRACKBALL, R.string.use_short_object_names,
+ cat.addPreference(activity.createCheckBoxPreference(settings.USE_SHORT_OBJECT_NAMES, R.string.use_short_object_names,
R.string.use_short_object_names_descr));
cat.addPreference(activity.createCheckBoxPreference(settings.ACCESSIBILITY_EXTENSIONS, R.string.accessibility_extensions,
R.string.accessibility_extensions));
}
}
| true | true | public void settingsActivityCreate(final SettingsActivity activity, final PreferenceScreen screen) {
PreferenceScreen grp = screen.getPreferenceManager().createPreferenceScreen(activity);
grp.setTitle(R.string.accessibility_preferences);
grp.setSummary(R.string.accessibility_preferences_descr);
grp.setKey("accessibility_preferences");
((PreferenceCategory)screen.findPreference("global_settings")).addPreference(grp);
String[] entries = new String[AccessibilityMode.values().length];
for (int i = 0; i < entries.length; i++) {
entries[i] = AccessibilityMode.values()[i].toHumanString(activity);
}
accessibilityModePreference = activity.createListPreference(settings.ACCESSIBILITY_MODE, entries, AccessibilityMode.values(),
R.string.accessibility_mode, R.string.accessibility_mode_descr);
accessibilityModePreference.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
@Override
public boolean onPreferenceChange(Preference preference, Object newValue) {
PreferenceCategory accessibilityOptions = ((PreferenceCategory)(screen.findPreference("accessibility_options")));
if (accessibilityOptions != null)
accessibilityOptions.setEnabled(app.accessibilityEnabled());
accessibilityModePreference.setSummary(app.getString(R.string.accessibility_mode_descr) + " [" + settings.ACCESSIBILITY_MODE.get().toHumanString(app) + "]");
return true;
}
});
grp.addPreference(accessibilityModePreference);
PreferenceCategory cat = new PreferenceCategory(activity);
cat.setKey("accessibility_options");
grp.addPreference(cat);
entries = new String[RelativeDirectionStyle.values().length];
for (int i = 0; i < entries.length; i++) {
entries[i] = RelativeDirectionStyle.values()[i].toHumanString(activity);
}
directionStylePreference = activity.createListPreference(settings.DIRECTION_STYLE, entries, RelativeDirectionStyle.values(),
R.string.settings_direction_style, R.string.settings_direction_style_descr);
directionStylePreference.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
@Override
public boolean onPreferenceChange(Preference preference, Object newValue) {
directionStylePreference.setSummary(app.getString(R.string.settings_direction_style_descr) + " [" + settings.DIRECTION_STYLE.get().toHumanString(app) + "]");
return true;
}
});
cat.addPreference(directionStylePreference);
cat.addPreference(activity.createCheckBoxPreference(settings.ZOOM_BY_TRACKBALL, R.string.zoom_by_trackball,
R.string.zoom_by_trackball_descr));
cat.addPreference(activity.createCheckBoxPreference(settings.SCROLL_MAP_BY_GESTURES, R.string.scroll_map_by_gestures,
R.string.scroll_map_by_gestures_descr));
cat.addPreference(activity.createCheckBoxPreference(settings.ZOOM_BY_TRACKBALL, R.string.use_short_object_names,
R.string.use_short_object_names_descr));
cat.addPreference(activity.createCheckBoxPreference(settings.ACCESSIBILITY_EXTENSIONS, R.string.accessibility_extensions,
R.string.accessibility_extensions));
}
| public void settingsActivityCreate(final SettingsActivity activity, final PreferenceScreen screen) {
PreferenceScreen grp = screen.getPreferenceManager().createPreferenceScreen(activity);
grp.setTitle(R.string.accessibility_preferences);
grp.setSummary(R.string.accessibility_preferences_descr);
grp.setKey("accessibility_preferences");
((PreferenceCategory)screen.findPreference("global_settings")).addPreference(grp);
String[] entries = new String[AccessibilityMode.values().length];
for (int i = 0; i < entries.length; i++) {
entries[i] = AccessibilityMode.values()[i].toHumanString(activity);
}
accessibilityModePreference = activity.createListPreference(settings.ACCESSIBILITY_MODE, entries, AccessibilityMode.values(),
R.string.accessibility_mode, R.string.accessibility_mode_descr);
accessibilityModePreference.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
@Override
public boolean onPreferenceChange(Preference preference, Object newValue) {
PreferenceCategory accessibilityOptions = ((PreferenceCategory)(screen.findPreference("accessibility_options")));
if (accessibilityOptions != null)
accessibilityOptions.setEnabled(app.accessibilityEnabled());
accessibilityModePreference.setSummary(app.getString(R.string.accessibility_mode_descr) + " [" + settings.ACCESSIBILITY_MODE.get().toHumanString(app) + "]");
return true;
}
});
grp.addPreference(accessibilityModePreference);
PreferenceCategory cat = new PreferenceCategory(activity);
cat.setKey("accessibility_options");
grp.addPreference(cat);
entries = new String[RelativeDirectionStyle.values().length];
for (int i = 0; i < entries.length; i++) {
entries[i] = RelativeDirectionStyle.values()[i].toHumanString(activity);
}
directionStylePreference = activity.createListPreference(settings.DIRECTION_STYLE, entries, RelativeDirectionStyle.values(),
R.string.settings_direction_style, R.string.settings_direction_style_descr);
directionStylePreference.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
@Override
public boolean onPreferenceChange(Preference preference, Object newValue) {
directionStylePreference.setSummary(app.getString(R.string.settings_direction_style_descr) + " [" + settings.DIRECTION_STYLE.get().toHumanString(app) + "]");
return true;
}
});
cat.addPreference(directionStylePreference);
cat.addPreference(activity.createCheckBoxPreference(settings.ZOOM_BY_TRACKBALL, R.string.zoom_by_trackball,
R.string.zoom_by_trackball_descr));
cat.addPreference(activity.createCheckBoxPreference(settings.SCROLL_MAP_BY_GESTURES, R.string.scroll_map_by_gestures,
R.string.scroll_map_by_gestures_descr));
cat.addPreference(activity.createCheckBoxPreference(settings.USE_SHORT_OBJECT_NAMES, R.string.use_short_object_names,
R.string.use_short_object_names_descr));
cat.addPreference(activity.createCheckBoxPreference(settings.ACCESSIBILITY_EXTENSIONS, R.string.accessibility_extensions,
R.string.accessibility_extensions));
}
|
diff --git a/utils/MakeTestOmeTiff.java b/utils/MakeTestOmeTiff.java
index 3656df494..fc7dcc2bb 100644
--- a/utils/MakeTestOmeTiff.java
+++ b/utils/MakeTestOmeTiff.java
@@ -1,555 +1,555 @@
//
// MakeTestOmeTiff.java
//
import java.awt.*;
import java.awt.image.BufferedImage;
import java.awt.geom.Rectangle2D;
import java.io.IOException;
import java.util.*;
import loci.formats.*;
import loci.formats.out.TiffWriter;
/** Creates a sample OME-TIFF dataset according to the given parameters. */
public class MakeTestOmeTiff {
private static int gradient(int type, int num, int total) {
final int max = 96;
int split = type / 2 + 1;
boolean reverse = type % 2 == 0;
int v = max;
total /= split;
for (int i=1; i<=split+1; i++) {
if (num < i * total) {
if (i % 2 == 0) v = max * (num % total) / total;
else v = max * (total - num % total) / total;
break;
}
}
if (reverse) v = max - v;
return v;
}
/** Fisher-Yates shuffle, stolen from Wikipedia. */
public static void shuffle(int[] array) {
Random r = new Random();
int n = array.length;
while (--n > 0) {
int k = r.nextInt(n + 1); // 0 <= k <= n (!)
int temp = array[n];
array[n] = array[k];
array[k] = temp;
}
}
/**
* Constructs a TiffData element matching the given parameters.
* @param ifd Value to use for IFD attribute; 0 is default/none.
* @param num Value to use for NumPlanes attribute, or -1 for none.
* @param firstZ Value to use for FirstZ attribute; 0 is default/none.
* @param firstC Value to use for FirstC attribute; 0 is default/none.
* @param firstT Value to use for FirstT attribute; 0 is default/none.
* @param order Dimension order; only used when scrambling.
* @param sizeZ Number of focal planes; only used when scrambling.
* @param sizeC Number of channels; only used when scrambling.
* @param sizeT Number of time points; only used when scrambling.
* @param total Total number of IFDs in the file;
* if null, no scrambling will be performed.
*/
private static String tiffData(int ifd, int num,
int firstZ, int firstC, int firstT,
String order, int sizeZ, int sizeC, int sizeT, Integer total)
{
StringBuffer sb = new StringBuffer();
if (total == null) {
sb.append("<TiffData");
if (ifd > 0) sb.append(" IFD=\"" + ifd + "\"");
if (num >= 0) sb.append(" NumPlanes=\"" + num + "\"");
if (firstZ > 0) sb.append(" FirstZ=\"" + firstZ + "\"");
if (firstC > 0) sb.append(" FirstC=\"" + firstC + "\"");
if (firstT > 0) sb.append(" FirstT=\"" + firstT + "\"");
sb.append("/>");
}
else {
// scramble planes
if (ifd < 0) ifd = 0;
if (num < 0) num = total.intValue();
int len = sizeZ * sizeC * sizeT;
int index = FormatTools.getIndex(order,
sizeZ, sizeC, sizeT, len, firstZ, firstC, firstT);
int[] planes = new int[num];
for (int i=0; i<num; i++) planes[i] = index + i;
shuffle(planes);
for (int i=0; i<num; i++) {
int[] zct = FormatTools.getZCTCoords(order,
sizeZ, sizeC, sizeT, len, planes[i]);
sb.append("<TiffData IFD=\"" + (i + ifd) + "\"" +
" NumPlanes=\"1\" FirstZ=\"" + zct[0] + "\"" +
" FirstC=\"" + zct[1] + "\" FirstT=\"" + zct[2] + "\"/>");
}
}
return sb.toString();
}
public static void main(String[] args) throws FormatException, IOException {
boolean usage = false;
// parse command line arguments
String name = null;
String dist = null;
boolean scramble = false;
int numImages = 0;
int[] numPixels = null;
int[][] sizeX = null, sizeY = null;
int[][] sizeZ = null, sizeC = null, sizeT = null;
String[][] dimOrder = null;
if (args == null || args.length < 2) usage = true;
else {
name = args[0];
dist = args[1].toLowerCase();
- scramble = args.length >= 2 && args[2].equalsIgnoreCase("-scramble");
+ scramble = args.length > 2 && args[2].equalsIgnoreCase("-scramble");
int startIndex = scramble ? 3 : 2;
// count number of images
int ndx = startIndex;
while (ndx < args.length) {
int numPix = Integer.parseInt(args[ndx]);
ndx += 1 + 6 * numPix;
numImages++;
}
// parse pixels's dimensional information
if (ndx > args.length) usage = true;
else {
numPixels = new int[numImages];
sizeX = new int[numImages][];
sizeY = new int[numImages][];
sizeZ = new int[numImages][];
sizeC = new int[numImages][];
sizeT = new int[numImages][];
dimOrder = new String[numImages][];
ndx = startIndex;
for (int i=0; i<numImages; i++) {
numPixels[i] = Integer.parseInt(args[ndx++]);
sizeX[i] = new int[numPixels[i]];
sizeY[i] = new int[numPixels[i]];
sizeZ[i] = new int[numPixels[i]];
sizeC[i] = new int[numPixels[i]];
sizeT[i] = new int[numPixels[i]];
dimOrder[i] = new String[numPixels[i]];
for (int p=0; p<numPixels[i]; p++) {
sizeX[i][p] = Integer.parseInt(args[ndx++]);
sizeY[i][p] = Integer.parseInt(args[ndx++]);
sizeZ[i][p] = Integer.parseInt(args[ndx++]);
sizeC[i][p] = Integer.parseInt(args[ndx++]);
sizeT[i][p] = Integer.parseInt(args[ndx++]);
dimOrder[i][p] = args[ndx++].toUpperCase();
}
}
}
}
if (usage) {
System.out.println(
"Usage: java MakeTestOmeTiff name dist [-scramble]");
System.out.println(" image1_NumPixels");
System.out.println(" image1_pixels1_SizeX " +
"image1_pixels1_SizeY image1_pixels1_SizeZ");
System.out.println(" image1_pixels1_SizeC " +
"image1_pixels1_SizeT image1_pixels1_DimOrder");
System.out.println(" image1_pixels2_SizeX " +
"image1_pixels2_SizeY image1_pixels2_SizeZ");
System.out.println(" image1_pixels2_SizeC " +
"image1_pixels2_SizeT image1_pixels2_DimOrder");
System.out.println(" [...]");
System.out.println(" image2_NumPixels");
System.out.println(" image2_pixels1_SizeX " +
"image2_pixels1_SizeY image1_pixels1_SizeZ");
System.out.println(" image2_pixels1_SizeC " +
"image2_pixels1_SizeT image1_pixels1_DimOrder");
System.out.println(" image2_pixels2_SizeX " +
"image2_pixels2_SizeY image1_pixels2_SizeZ");
System.out.println(" image2_pixels2_SizeC " +
"image2_pixels2_SizeT image1_pixels2_DimOrder");
System.out.println(" [...]");
System.out.println(" [...]");
System.out.println();
System.out.println(" name: prefix for filenames");
System.out.println(" dist: code for how to distribute across files:");
System.out.println(" ipzct = all Images + Pixels in one file");
System.out.println(" pzct = each Image in its own file");
System.out.println(" zct = each Pixels in its own file");
System.out.println(" zc = all Z + C positions per file");
System.out.println(" zt = all Z + T positions per file");
System.out.println(" ct = all C + T positions per file");
System.out.println(" z = all Z positions per file");
System.out.println(" c = all C positions per file");
System.out.println(" t = all T positions per file");
System.out.println(" x = single plane per file");
System.out.println(" -scramble: randomizes IFD ordering");
System.out.println(" image*_pixels*_SizeX: width of image planes");
System.out.println(" image*_pixels*_SizeY: height of image planes");
System.out.println(" image*_pixels*_SizeZ: number of focal planes");
System.out.println(" image*_pixels*_SizeC: number of channels");
System.out.println(" image*_pixels*_SizeT: number of time points");
System.out.println(" image*_pixels*_DimOrder: planar ordering:");
System.out.println(" XYZCT, XYZTC, XYCZT, XYCTZ, XYTZC, or XYTCZ");
System.out.println();
System.out.println("Example:");
System.out.println(" java MakeTestOmeTiff test ipzct \\");
System.out.println(" 2 431 555 1 2 7 XYTCZ \\");
System.out.println(" 348 461 2 1 6 XYZTC \\");
System.out.println(" 1 517 239 5 3 4 XYCZT");
System.exit(1);
}
if (!dist.equals("ipzct") && !dist.equals("pzct") && !dist.equals("zct") &&
!dist.equals("zc") && !dist.equals("zt") && !dist.equals("ct") &&
!dist.equals("z") && !dist.equals("c") && !dist.equals("t") &&
!dist.equals("x"))
{
System.out.println("Invalid dist value: " + dist);
System.exit(2);
}
boolean allI = dist.indexOf("i") >= 0;
boolean allP = dist.indexOf("p") >= 0;
boolean allZ = dist.indexOf("z") >= 0;
boolean allC = dist.indexOf("c") >= 0;
boolean allT = dist.indexOf("t") >= 0;
BufferedImage[][][] images = new BufferedImage[numImages][][];
int[][] globalOffsets = new int[numImages][]; // IFD offsets across Images
int[][] localOffsets = new int[numImages][]; // IFD offsets per Image
int globalOffset = 0, localOffset = 0;
for (int i=0; i<numImages; i++) {
images[i] = new BufferedImage[numPixels[i]][];
globalOffsets[i] = new int[numPixels[i]];
localOffsets[i] = new int[numPixels[i]];
localOffset = 0;
for (int p=0; p<numPixels[i]; p++) {
int len = sizeZ[i][p] * sizeC[i][p] * sizeT[i][p];
images[i][p] = new BufferedImage[len];
globalOffsets[i][p] = globalOffset;
globalOffset += len;
localOffsets[i][p] = localOffset;
localOffset += len;
}
}
System.out.println("Generating image planes");
for (int i=0, ipNum=0; i<numImages; i++) {
System.out.println(" Image #" + (i + 1) + ":");
for (int p=0; p<numPixels[i]; p++, ipNum++) {
System.out.print(" Pixels #" + (p + 1) + " - " +
sizeX[i][p] + " x " + sizeY[i][p] + ", " +
sizeZ[i][p] + "Z " + sizeC[i][p] + "C " + sizeT[i][p] + "T");
int len = images[i][p].length;
for (int j=0; j<len; j++) {
int[] zct = FormatTools.getZCTCoords(dimOrder[i][p],
sizeZ[i][p], sizeC[i][p], sizeT[i][p], len, j);
System.out.print(".");
images[i][p][j] = new BufferedImage(
sizeX[i][p], sizeY[i][p], BufferedImage.TYPE_BYTE_GRAY);
Graphics2D g = images[i][p][j].createGraphics();
// draw gradient
boolean even = ipNum % 2 == 0;
int type = ipNum / 2;
if (even) {
// draw vertical gradient for even-numbered pixelses
for (int y=0; y<sizeY[i][p]; y++) {
int v = gradient(type, y, sizeY[i][p]);
g.setColor(new Color(v, v, v));
g.drawLine(0, y, sizeX[i][p], y);
}
}
else {
// draw horizontal gradient for odd-numbered pixelses
for (int x=0; x<sizeX[i][p]; x++) {
int v = gradient(type, x, sizeX[i][p]);
g.setColor(new Color(v, v, v));
g.drawLine(x, 0, x, sizeY[i][p]);
}
}
// build list of text lines from planar information
Vector lines = new Vector();
Font font = g.getFont();
lines.add(new TextLine(name, font.deriveFont(32f), 5, -5));
lines.add(new TextLine(sizeX[i][p] + " x " + sizeY[i][p],
font.deriveFont(Font.ITALIC, 16f), 20, 10));
lines.add(new TextLine(dimOrder[i][p],
font.deriveFont(Font.ITALIC, 14f), 30, 5));
int space = 5;
if (numImages > 1) {
lines.add(new TextLine("Image #" + (i + 1) + "/" + numImages,
font, 20, space));
space = 2;
}
if (numPixels[i] > 1) {
lines.add(new TextLine("Pixels #" + (p + 1) + "/" + numPixels[i],
font, 20, space));
space = 2;
}
if (sizeZ[i][p] > 1) {
lines.add(new TextLine("Focal plane = " +
(zct[0] + 1) + "/" + sizeZ[i][p], font, 20, space));
space = 2;
}
if (sizeC[i][p] > 1) {
lines.add(new TextLine("Channel = " +
(zct[1] + 1) + "/" + sizeC[i][p], font, 20, space));
space = 2;
}
if (sizeT[i][p] > 1) {
lines.add(new TextLine("Time point = " +
(zct[2] + 1) + "/" + sizeT[i][p], font, 20, space));
space = 2;
}
// draw text lines to image
g.setColor(Color.white);
int yoff = 0;
for (int l=0; l<lines.size(); l++) {
TextLine text = (TextLine) lines.get(l);
g.setFont(text.font);
Rectangle2D r = g.getFont().getStringBounds(
text.line, g.getFontRenderContext());
yoff += r.getHeight() + text.ypad;
g.drawString(text.line, text.xoff, yoff);
}
g.dispose();
}
System.out.println();
}
}
System.out.println("Writing output files");
// determine filename for each image plane
String[][][] filenames = new String[numImages][][];
Hashtable lastHash = new Hashtable();
boolean[][][] last = new boolean[numImages][][];
Hashtable ifdTotal = new Hashtable();
Hashtable firstZ = new Hashtable();
Hashtable firstC = new Hashtable();
Hashtable firstT = new Hashtable();
StringBuffer sb = new StringBuffer();
for (int i=0; i<numImages; i++) {
filenames[i] = new String[numPixels[i]][];
last[i] = new boolean[numPixels[i]][];
for (int p=0; p<numPixels[i]; p++) {
int len = images[i][p].length;
filenames[i][p] = new String[len];
last[i][p] = new boolean[len];
for (int j=0; j<len; j++) {
sb.append(name);
if (!allI && numImages > 1) sb.append("_image" + (i + 1));
if (!allP && numPixels[i] > 1) sb.append("_pixels" + (p + 1));
int[] zct = FormatTools.getZCTCoords(dimOrder[i][p],
sizeZ[i][p], sizeC[i][p], sizeT[i][p], len, j);
if (!allZ && sizeZ[i][p] > 1) sb.append("_Z" + (zct[0] + 1));
if (!allC && sizeC[i][p] > 1) sb.append("_C" + (zct[1] + 1));
if (!allT && sizeT[i][p] > 1) sb.append("_T" + (zct[2] + 1));
sb.append(".ome.tif");
filenames[i][p][j] = sb.toString();
sb.setLength(0);
last[i][p][j] = true;
// update last flag for this filename
String key = filenames[i][p][j];
ImageIndex index = (ImageIndex) lastHash.get(key);
if (index != null) {
last[index.image][index.pixels][index.plane] = false;
}
lastHash.put(key, new ImageIndex(i, p, j));
// update IFD count for this filename
Integer total = (Integer) ifdTotal.get(key);
if (total == null) total = new Integer(1);
else total = new Integer(total.intValue() + 1);
ifdTotal.put(key, total);
// update FirstZ, FirstC and FirstT values for this filename
if (!allZ && sizeZ[i][p] > 1) {
firstZ.put(filenames[i][p][j], new Integer(zct[0]));
}
if (!allC && sizeC[i][p] > 1) {
firstC.put(filenames[i][p][j], new Integer(zct[1]));
}
if (!allT && sizeT[i][p] > 1) {
firstT.put(filenames[i][p][j], new Integer(zct[2]));
}
}
}
}
// build OME-XML block
// CreationDate is required; initialize a default value (current time)
// use ISO 8601 dateTime format (e.g., 1988-04-07T18:39:09)
sb.setLength(0);
Calendar now = Calendar.getInstance();
int year = now.get(Calendar.YEAR);
int month = now.get(Calendar.MONTH);
int day = now.get(Calendar.DAY_OF_MONTH);
int hour = now.get(Calendar.HOUR_OF_DAY);
int min = now.get(Calendar.MINUTE);
int sec = now.get(Calendar.SECOND);
sb.append(year);
sb.append("-");
if (month < 9) sb.append("0");
sb.append(month + 1);
sb.append("-");
if (day < 10) sb.append("0");
sb.append(day);
sb.append("T");
if (hour < 10) sb.append("0");
sb.append(hour);
sb.append(":");
if (min < 10) sb.append("0");
sb.append(min);
sb.append(":");
if (sec < 10) sb.append("0");
sb.append(sec);
String creationDate = sb.toString();
sb.setLength(0);
sb.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>" +
"<!-- Warning: this comment is an OME-XML metadata block, which " +
"contains crucial dimensional parameters and other important metadata. " +
"Please edit cautiously (if at all), and back up the original data " +
"before doing so. For more information, see the OME-TIFF web site: " +
"http://loci.wisc.edu/ome/ome-tiff.html. --><OME " +
"xmlns=\"http://www.openmicroscopy.org/XMLschemas/OME/FC/ome.xsd\" " +
"xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" " +
"xsi:schemaLocation=\"" +
"http://www.openmicroscopy.org/XMLschemas/OME/FC/ome.xsd\">");
for (int i=0; i<numImages; i++) {
sb.append("<Image " +
"ID=\"openmicroscopy.org:Image:" + (i + 1) + "\" " +
"Name=\"" + name + "\" " +
"DefaultPixels=\"openmicroscopy.org:Pixels:" + (i + 1) + "-1\">" +
"<CreationDate>" + creationDate + "</CreationDate>");
for (int p=0; p<numPixels[i]; p++) {
sb.append("<Pixels " +
"ID=\"openmicroscopy.org:Pixels:" + (i + 1) + "-" + (p + 1) + "\" " +
"DimensionOrder=\"" + dimOrder[i][p] + "\" " +
"PixelType=\"uint8\" " +
"BigEndian=\"true\" " +
"SizeX=\"" + sizeX[i][p] + "\" " +
"SizeY=\"" + sizeY[i][p] + "\" " +
"SizeZ=\"" + sizeZ[i][p] + "\" " +
"SizeC=\"" + sizeC[i][p] + "\" " +
"SizeT=\"" + sizeT[i][p] + "\">" +
"TIFF_DATA_IMAGE_" + i + "_PIXELS_" + p + // placeholder
"</Pixels>");
}
sb.append("</Image>");
}
sb.append("</OME>");
String xmlTemplate = sb.toString();
TiffWriter out = new TiffWriter();
for (int i=0; i<numImages; i++) {
System.out.println(" Image #" + (i + 1) + ":");
for (int p=0; p<numPixels[i]; p++) {
System.out.println(" Pixels #" + (p + 1) + " - " +
sizeX[i][p] + " x " + sizeY[i][p] + ", " +
sizeZ[i][p] + "Z " + sizeC[i][p] + "C " + sizeT[i][p] + "T:");
int len = images[i][p].length;
for (int j=0; j<len; j++) {
int[] zct = FormatTools.getZCTCoords(dimOrder[i][p],
sizeZ[i][p], sizeC[i][p], sizeT[i][p], len, j);
System.out.println(" " +
"Z" + zct[0] + " C" + zct[1] + " T" + zct[2] +
" -> " + filenames[i][p][j] + (last[i][p][j] ? "*" : ""));
out.setId(filenames[i][p][j]);
// write comment stub, to be overwritten later
Hashtable ifdHash = new Hashtable();
TiffTools.putIFDValue(ifdHash, TiffTools.IMAGE_DESCRIPTION, "");
out.saveImage(images[i][p][j], ifdHash, last[i][p][j]);
if (last[i][p][j]) {
// inject OME-XML block
String xml = xmlTemplate;
String key = filenames[i][p][j];
Integer fzObj = (Integer) firstZ.get(key);
Integer fcObj = (Integer) firstC.get(key);
Integer ftObj = (Integer) firstT.get(key);
int fz = fzObj == null ? 0 : fzObj.intValue();
int fc = fcObj == null ? 0 : fcObj.intValue();
int ft = ftObj == null ? 0 : ftObj.intValue();
Integer total = (Integer) ifdTotal.get(key);
if (!scramble) total = null;
for (int ii=0; ii<numImages; ii++) {
for (int pp=0; pp<numPixels[ii]; pp++) {
String pattern = "TIFF_DATA_IMAGE_" + ii + "_PIXELS_" + pp;
if (!allI && ii != i || !allP && pp != p) {
// current Pixels is not part of this file
xml = xml.replaceFirst(pattern,
tiffData(0, 0, 0, 0, 0, dimOrder[ii][pp],
sizeZ[ii][pp], sizeC[ii][pp], sizeT[ii][pp], total));
continue;
}
if (allP) {
int ifd;
if (allI) {
// all Images in one file; need to use global offset
ifd = globalOffsets[ii][pp];
}
else { // ii == i
// one Image per file; use local offset
ifd = localOffsets[ii][pp];
}
int num = images[ii][pp].length;
if ((!allI || numImages == 1) && numPixels[i] == 1) {
// only one Pixels in this file; don't need IFD/NumPlanes
ifd = 0;
num = -1;
}
xml = xml.replaceFirst(pattern,
tiffData(ifd, num, 0, 0, 0, dimOrder[ii][pp],
sizeZ[ii][pp], sizeC[ii][pp], sizeT[ii][pp], total));
}
else { // pp == p
xml = xml.replaceFirst(pattern,
tiffData(0, -1, fz, fc, ft, dimOrder[ii][pp],
sizeZ[ii][pp], sizeC[ii][pp], sizeT[ii][pp], total));
}
}
}
TiffTools.overwriteComment(filenames[i][p][j], xml);
}
}
}
}
}
private static class TextLine {
private String line;
private Font font;
private int xoff;
private int ypad;
private TextLine(String line, Font font, int xoff, int ypad) {
this.line = line;
this.font = font;
this.xoff = xoff;
this.ypad = ypad;
}
}
private static class ImageIndex {
private int image;
private int pixels;
private int plane;
private ImageIndex(int i, int p, int j) {
this.image = i;
this.pixels = p;
this.plane = j;
}
}
}
| true | true | public static void main(String[] args) throws FormatException, IOException {
boolean usage = false;
// parse command line arguments
String name = null;
String dist = null;
boolean scramble = false;
int numImages = 0;
int[] numPixels = null;
int[][] sizeX = null, sizeY = null;
int[][] sizeZ = null, sizeC = null, sizeT = null;
String[][] dimOrder = null;
if (args == null || args.length < 2) usage = true;
else {
name = args[0];
dist = args[1].toLowerCase();
scramble = args.length >= 2 && args[2].equalsIgnoreCase("-scramble");
int startIndex = scramble ? 3 : 2;
// count number of images
int ndx = startIndex;
while (ndx < args.length) {
int numPix = Integer.parseInt(args[ndx]);
ndx += 1 + 6 * numPix;
numImages++;
}
// parse pixels's dimensional information
if (ndx > args.length) usage = true;
else {
numPixels = new int[numImages];
sizeX = new int[numImages][];
sizeY = new int[numImages][];
sizeZ = new int[numImages][];
sizeC = new int[numImages][];
sizeT = new int[numImages][];
dimOrder = new String[numImages][];
ndx = startIndex;
for (int i=0; i<numImages; i++) {
numPixels[i] = Integer.parseInt(args[ndx++]);
sizeX[i] = new int[numPixels[i]];
sizeY[i] = new int[numPixels[i]];
sizeZ[i] = new int[numPixels[i]];
sizeC[i] = new int[numPixels[i]];
sizeT[i] = new int[numPixels[i]];
dimOrder[i] = new String[numPixels[i]];
for (int p=0; p<numPixels[i]; p++) {
sizeX[i][p] = Integer.parseInt(args[ndx++]);
sizeY[i][p] = Integer.parseInt(args[ndx++]);
sizeZ[i][p] = Integer.parseInt(args[ndx++]);
sizeC[i][p] = Integer.parseInt(args[ndx++]);
sizeT[i][p] = Integer.parseInt(args[ndx++]);
dimOrder[i][p] = args[ndx++].toUpperCase();
}
}
}
}
if (usage) {
System.out.println(
"Usage: java MakeTestOmeTiff name dist [-scramble]");
System.out.println(" image1_NumPixels");
System.out.println(" image1_pixels1_SizeX " +
"image1_pixels1_SizeY image1_pixels1_SizeZ");
System.out.println(" image1_pixels1_SizeC " +
"image1_pixels1_SizeT image1_pixels1_DimOrder");
System.out.println(" image1_pixels2_SizeX " +
"image1_pixels2_SizeY image1_pixels2_SizeZ");
System.out.println(" image1_pixels2_SizeC " +
"image1_pixels2_SizeT image1_pixels2_DimOrder");
System.out.println(" [...]");
System.out.println(" image2_NumPixels");
System.out.println(" image2_pixels1_SizeX " +
"image2_pixels1_SizeY image1_pixels1_SizeZ");
System.out.println(" image2_pixels1_SizeC " +
"image2_pixels1_SizeT image1_pixels1_DimOrder");
System.out.println(" image2_pixels2_SizeX " +
"image2_pixels2_SizeY image1_pixels2_SizeZ");
System.out.println(" image2_pixels2_SizeC " +
"image2_pixels2_SizeT image1_pixels2_DimOrder");
System.out.println(" [...]");
System.out.println(" [...]");
System.out.println();
System.out.println(" name: prefix for filenames");
System.out.println(" dist: code for how to distribute across files:");
System.out.println(" ipzct = all Images + Pixels in one file");
System.out.println(" pzct = each Image in its own file");
System.out.println(" zct = each Pixels in its own file");
System.out.println(" zc = all Z + C positions per file");
System.out.println(" zt = all Z + T positions per file");
System.out.println(" ct = all C + T positions per file");
System.out.println(" z = all Z positions per file");
System.out.println(" c = all C positions per file");
System.out.println(" t = all T positions per file");
System.out.println(" x = single plane per file");
System.out.println(" -scramble: randomizes IFD ordering");
System.out.println(" image*_pixels*_SizeX: width of image planes");
System.out.println(" image*_pixels*_SizeY: height of image planes");
System.out.println(" image*_pixels*_SizeZ: number of focal planes");
System.out.println(" image*_pixels*_SizeC: number of channels");
System.out.println(" image*_pixels*_SizeT: number of time points");
System.out.println(" image*_pixels*_DimOrder: planar ordering:");
System.out.println(" XYZCT, XYZTC, XYCZT, XYCTZ, XYTZC, or XYTCZ");
System.out.println();
System.out.println("Example:");
System.out.println(" java MakeTestOmeTiff test ipzct \\");
System.out.println(" 2 431 555 1 2 7 XYTCZ \\");
System.out.println(" 348 461 2 1 6 XYZTC \\");
System.out.println(" 1 517 239 5 3 4 XYCZT");
System.exit(1);
}
if (!dist.equals("ipzct") && !dist.equals("pzct") && !dist.equals("zct") &&
!dist.equals("zc") && !dist.equals("zt") && !dist.equals("ct") &&
!dist.equals("z") && !dist.equals("c") && !dist.equals("t") &&
!dist.equals("x"))
{
System.out.println("Invalid dist value: " + dist);
System.exit(2);
}
boolean allI = dist.indexOf("i") >= 0;
boolean allP = dist.indexOf("p") >= 0;
boolean allZ = dist.indexOf("z") >= 0;
boolean allC = dist.indexOf("c") >= 0;
boolean allT = dist.indexOf("t") >= 0;
BufferedImage[][][] images = new BufferedImage[numImages][][];
int[][] globalOffsets = new int[numImages][]; // IFD offsets across Images
int[][] localOffsets = new int[numImages][]; // IFD offsets per Image
int globalOffset = 0, localOffset = 0;
for (int i=0; i<numImages; i++) {
images[i] = new BufferedImage[numPixels[i]][];
globalOffsets[i] = new int[numPixels[i]];
localOffsets[i] = new int[numPixels[i]];
localOffset = 0;
for (int p=0; p<numPixels[i]; p++) {
int len = sizeZ[i][p] * sizeC[i][p] * sizeT[i][p];
images[i][p] = new BufferedImage[len];
globalOffsets[i][p] = globalOffset;
globalOffset += len;
localOffsets[i][p] = localOffset;
localOffset += len;
}
}
System.out.println("Generating image planes");
for (int i=0, ipNum=0; i<numImages; i++) {
System.out.println(" Image #" + (i + 1) + ":");
for (int p=0; p<numPixels[i]; p++, ipNum++) {
System.out.print(" Pixels #" + (p + 1) + " - " +
sizeX[i][p] + " x " + sizeY[i][p] + ", " +
sizeZ[i][p] + "Z " + sizeC[i][p] + "C " + sizeT[i][p] + "T");
int len = images[i][p].length;
for (int j=0; j<len; j++) {
int[] zct = FormatTools.getZCTCoords(dimOrder[i][p],
sizeZ[i][p], sizeC[i][p], sizeT[i][p], len, j);
System.out.print(".");
images[i][p][j] = new BufferedImage(
sizeX[i][p], sizeY[i][p], BufferedImage.TYPE_BYTE_GRAY);
Graphics2D g = images[i][p][j].createGraphics();
// draw gradient
boolean even = ipNum % 2 == 0;
int type = ipNum / 2;
if (even) {
// draw vertical gradient for even-numbered pixelses
for (int y=0; y<sizeY[i][p]; y++) {
int v = gradient(type, y, sizeY[i][p]);
g.setColor(new Color(v, v, v));
g.drawLine(0, y, sizeX[i][p], y);
}
}
else {
// draw horizontal gradient for odd-numbered pixelses
for (int x=0; x<sizeX[i][p]; x++) {
int v = gradient(type, x, sizeX[i][p]);
g.setColor(new Color(v, v, v));
g.drawLine(x, 0, x, sizeY[i][p]);
}
}
// build list of text lines from planar information
Vector lines = new Vector();
Font font = g.getFont();
lines.add(new TextLine(name, font.deriveFont(32f), 5, -5));
lines.add(new TextLine(sizeX[i][p] + " x " + sizeY[i][p],
font.deriveFont(Font.ITALIC, 16f), 20, 10));
lines.add(new TextLine(dimOrder[i][p],
font.deriveFont(Font.ITALIC, 14f), 30, 5));
int space = 5;
if (numImages > 1) {
lines.add(new TextLine("Image #" + (i + 1) + "/" + numImages,
font, 20, space));
space = 2;
}
if (numPixels[i] > 1) {
lines.add(new TextLine("Pixels #" + (p + 1) + "/" + numPixels[i],
font, 20, space));
space = 2;
}
if (sizeZ[i][p] > 1) {
lines.add(new TextLine("Focal plane = " +
(zct[0] + 1) + "/" + sizeZ[i][p], font, 20, space));
space = 2;
}
if (sizeC[i][p] > 1) {
lines.add(new TextLine("Channel = " +
(zct[1] + 1) + "/" + sizeC[i][p], font, 20, space));
space = 2;
}
if (sizeT[i][p] > 1) {
lines.add(new TextLine("Time point = " +
(zct[2] + 1) + "/" + sizeT[i][p], font, 20, space));
space = 2;
}
// draw text lines to image
g.setColor(Color.white);
int yoff = 0;
for (int l=0; l<lines.size(); l++) {
TextLine text = (TextLine) lines.get(l);
g.setFont(text.font);
Rectangle2D r = g.getFont().getStringBounds(
text.line, g.getFontRenderContext());
yoff += r.getHeight() + text.ypad;
g.drawString(text.line, text.xoff, yoff);
}
g.dispose();
}
System.out.println();
}
}
System.out.println("Writing output files");
// determine filename for each image plane
String[][][] filenames = new String[numImages][][];
Hashtable lastHash = new Hashtable();
boolean[][][] last = new boolean[numImages][][];
Hashtable ifdTotal = new Hashtable();
Hashtable firstZ = new Hashtable();
Hashtable firstC = new Hashtable();
Hashtable firstT = new Hashtable();
StringBuffer sb = new StringBuffer();
for (int i=0; i<numImages; i++) {
filenames[i] = new String[numPixels[i]][];
last[i] = new boolean[numPixels[i]][];
for (int p=0; p<numPixels[i]; p++) {
int len = images[i][p].length;
filenames[i][p] = new String[len];
last[i][p] = new boolean[len];
for (int j=0; j<len; j++) {
sb.append(name);
if (!allI && numImages > 1) sb.append("_image" + (i + 1));
if (!allP && numPixels[i] > 1) sb.append("_pixels" + (p + 1));
int[] zct = FormatTools.getZCTCoords(dimOrder[i][p],
sizeZ[i][p], sizeC[i][p], sizeT[i][p], len, j);
if (!allZ && sizeZ[i][p] > 1) sb.append("_Z" + (zct[0] + 1));
if (!allC && sizeC[i][p] > 1) sb.append("_C" + (zct[1] + 1));
if (!allT && sizeT[i][p] > 1) sb.append("_T" + (zct[2] + 1));
sb.append(".ome.tif");
filenames[i][p][j] = sb.toString();
sb.setLength(0);
last[i][p][j] = true;
// update last flag for this filename
String key = filenames[i][p][j];
ImageIndex index = (ImageIndex) lastHash.get(key);
if (index != null) {
last[index.image][index.pixels][index.plane] = false;
}
lastHash.put(key, new ImageIndex(i, p, j));
// update IFD count for this filename
Integer total = (Integer) ifdTotal.get(key);
if (total == null) total = new Integer(1);
else total = new Integer(total.intValue() + 1);
ifdTotal.put(key, total);
// update FirstZ, FirstC and FirstT values for this filename
if (!allZ && sizeZ[i][p] > 1) {
firstZ.put(filenames[i][p][j], new Integer(zct[0]));
}
if (!allC && sizeC[i][p] > 1) {
firstC.put(filenames[i][p][j], new Integer(zct[1]));
}
if (!allT && sizeT[i][p] > 1) {
firstT.put(filenames[i][p][j], new Integer(zct[2]));
}
}
}
}
// build OME-XML block
// CreationDate is required; initialize a default value (current time)
// use ISO 8601 dateTime format (e.g., 1988-04-07T18:39:09)
sb.setLength(0);
Calendar now = Calendar.getInstance();
int year = now.get(Calendar.YEAR);
int month = now.get(Calendar.MONTH);
int day = now.get(Calendar.DAY_OF_MONTH);
int hour = now.get(Calendar.HOUR_OF_DAY);
int min = now.get(Calendar.MINUTE);
int sec = now.get(Calendar.SECOND);
sb.append(year);
sb.append("-");
if (month < 9) sb.append("0");
sb.append(month + 1);
sb.append("-");
if (day < 10) sb.append("0");
sb.append(day);
sb.append("T");
if (hour < 10) sb.append("0");
sb.append(hour);
sb.append(":");
if (min < 10) sb.append("0");
sb.append(min);
sb.append(":");
if (sec < 10) sb.append("0");
sb.append(sec);
String creationDate = sb.toString();
sb.setLength(0);
sb.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>" +
"<!-- Warning: this comment is an OME-XML metadata block, which " +
"contains crucial dimensional parameters and other important metadata. " +
"Please edit cautiously (if at all), and back up the original data " +
"before doing so. For more information, see the OME-TIFF web site: " +
"http://loci.wisc.edu/ome/ome-tiff.html. --><OME " +
"xmlns=\"http://www.openmicroscopy.org/XMLschemas/OME/FC/ome.xsd\" " +
"xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" " +
"xsi:schemaLocation=\"" +
"http://www.openmicroscopy.org/XMLschemas/OME/FC/ome.xsd\">");
for (int i=0; i<numImages; i++) {
sb.append("<Image " +
"ID=\"openmicroscopy.org:Image:" + (i + 1) + "\" " +
"Name=\"" + name + "\" " +
"DefaultPixels=\"openmicroscopy.org:Pixels:" + (i + 1) + "-1\">" +
"<CreationDate>" + creationDate + "</CreationDate>");
for (int p=0; p<numPixels[i]; p++) {
sb.append("<Pixels " +
"ID=\"openmicroscopy.org:Pixels:" + (i + 1) + "-" + (p + 1) + "\" " +
"DimensionOrder=\"" + dimOrder[i][p] + "\" " +
"PixelType=\"uint8\" " +
"BigEndian=\"true\" " +
"SizeX=\"" + sizeX[i][p] + "\" " +
"SizeY=\"" + sizeY[i][p] + "\" " +
"SizeZ=\"" + sizeZ[i][p] + "\" " +
"SizeC=\"" + sizeC[i][p] + "\" " +
"SizeT=\"" + sizeT[i][p] + "\">" +
"TIFF_DATA_IMAGE_" + i + "_PIXELS_" + p + // placeholder
"</Pixels>");
}
sb.append("</Image>");
}
sb.append("</OME>");
String xmlTemplate = sb.toString();
TiffWriter out = new TiffWriter();
for (int i=0; i<numImages; i++) {
System.out.println(" Image #" + (i + 1) + ":");
for (int p=0; p<numPixels[i]; p++) {
System.out.println(" Pixels #" + (p + 1) + " - " +
sizeX[i][p] + " x " + sizeY[i][p] + ", " +
sizeZ[i][p] + "Z " + sizeC[i][p] + "C " + sizeT[i][p] + "T:");
int len = images[i][p].length;
for (int j=0; j<len; j++) {
int[] zct = FormatTools.getZCTCoords(dimOrder[i][p],
sizeZ[i][p], sizeC[i][p], sizeT[i][p], len, j);
System.out.println(" " +
"Z" + zct[0] + " C" + zct[1] + " T" + zct[2] +
" -> " + filenames[i][p][j] + (last[i][p][j] ? "*" : ""));
out.setId(filenames[i][p][j]);
// write comment stub, to be overwritten later
Hashtable ifdHash = new Hashtable();
TiffTools.putIFDValue(ifdHash, TiffTools.IMAGE_DESCRIPTION, "");
out.saveImage(images[i][p][j], ifdHash, last[i][p][j]);
if (last[i][p][j]) {
// inject OME-XML block
String xml = xmlTemplate;
String key = filenames[i][p][j];
Integer fzObj = (Integer) firstZ.get(key);
Integer fcObj = (Integer) firstC.get(key);
Integer ftObj = (Integer) firstT.get(key);
int fz = fzObj == null ? 0 : fzObj.intValue();
int fc = fcObj == null ? 0 : fcObj.intValue();
int ft = ftObj == null ? 0 : ftObj.intValue();
Integer total = (Integer) ifdTotal.get(key);
if (!scramble) total = null;
for (int ii=0; ii<numImages; ii++) {
for (int pp=0; pp<numPixels[ii]; pp++) {
String pattern = "TIFF_DATA_IMAGE_" + ii + "_PIXELS_" + pp;
if (!allI && ii != i || !allP && pp != p) {
// current Pixels is not part of this file
xml = xml.replaceFirst(pattern,
tiffData(0, 0, 0, 0, 0, dimOrder[ii][pp],
sizeZ[ii][pp], sizeC[ii][pp], sizeT[ii][pp], total));
continue;
}
if (allP) {
int ifd;
if (allI) {
// all Images in one file; need to use global offset
ifd = globalOffsets[ii][pp];
}
else { // ii == i
// one Image per file; use local offset
ifd = localOffsets[ii][pp];
}
int num = images[ii][pp].length;
if ((!allI || numImages == 1) && numPixels[i] == 1) {
// only one Pixels in this file; don't need IFD/NumPlanes
ifd = 0;
num = -1;
}
xml = xml.replaceFirst(pattern,
tiffData(ifd, num, 0, 0, 0, dimOrder[ii][pp],
sizeZ[ii][pp], sizeC[ii][pp], sizeT[ii][pp], total));
}
else { // pp == p
xml = xml.replaceFirst(pattern,
tiffData(0, -1, fz, fc, ft, dimOrder[ii][pp],
sizeZ[ii][pp], sizeC[ii][pp], sizeT[ii][pp], total));
}
}
}
TiffTools.overwriteComment(filenames[i][p][j], xml);
}
}
}
}
}
| public static void main(String[] args) throws FormatException, IOException {
boolean usage = false;
// parse command line arguments
String name = null;
String dist = null;
boolean scramble = false;
int numImages = 0;
int[] numPixels = null;
int[][] sizeX = null, sizeY = null;
int[][] sizeZ = null, sizeC = null, sizeT = null;
String[][] dimOrder = null;
if (args == null || args.length < 2) usage = true;
else {
name = args[0];
dist = args[1].toLowerCase();
scramble = args.length > 2 && args[2].equalsIgnoreCase("-scramble");
int startIndex = scramble ? 3 : 2;
// count number of images
int ndx = startIndex;
while (ndx < args.length) {
int numPix = Integer.parseInt(args[ndx]);
ndx += 1 + 6 * numPix;
numImages++;
}
// parse pixels's dimensional information
if (ndx > args.length) usage = true;
else {
numPixels = new int[numImages];
sizeX = new int[numImages][];
sizeY = new int[numImages][];
sizeZ = new int[numImages][];
sizeC = new int[numImages][];
sizeT = new int[numImages][];
dimOrder = new String[numImages][];
ndx = startIndex;
for (int i=0; i<numImages; i++) {
numPixels[i] = Integer.parseInt(args[ndx++]);
sizeX[i] = new int[numPixels[i]];
sizeY[i] = new int[numPixels[i]];
sizeZ[i] = new int[numPixels[i]];
sizeC[i] = new int[numPixels[i]];
sizeT[i] = new int[numPixels[i]];
dimOrder[i] = new String[numPixels[i]];
for (int p=0; p<numPixels[i]; p++) {
sizeX[i][p] = Integer.parseInt(args[ndx++]);
sizeY[i][p] = Integer.parseInt(args[ndx++]);
sizeZ[i][p] = Integer.parseInt(args[ndx++]);
sizeC[i][p] = Integer.parseInt(args[ndx++]);
sizeT[i][p] = Integer.parseInt(args[ndx++]);
dimOrder[i][p] = args[ndx++].toUpperCase();
}
}
}
}
if (usage) {
System.out.println(
"Usage: java MakeTestOmeTiff name dist [-scramble]");
System.out.println(" image1_NumPixels");
System.out.println(" image1_pixels1_SizeX " +
"image1_pixels1_SizeY image1_pixels1_SizeZ");
System.out.println(" image1_pixels1_SizeC " +
"image1_pixels1_SizeT image1_pixels1_DimOrder");
System.out.println(" image1_pixels2_SizeX " +
"image1_pixels2_SizeY image1_pixels2_SizeZ");
System.out.println(" image1_pixels2_SizeC " +
"image1_pixels2_SizeT image1_pixels2_DimOrder");
System.out.println(" [...]");
System.out.println(" image2_NumPixels");
System.out.println(" image2_pixels1_SizeX " +
"image2_pixels1_SizeY image1_pixels1_SizeZ");
System.out.println(" image2_pixels1_SizeC " +
"image2_pixels1_SizeT image1_pixels1_DimOrder");
System.out.println(" image2_pixels2_SizeX " +
"image2_pixels2_SizeY image1_pixels2_SizeZ");
System.out.println(" image2_pixels2_SizeC " +
"image2_pixels2_SizeT image1_pixels2_DimOrder");
System.out.println(" [...]");
System.out.println(" [...]");
System.out.println();
System.out.println(" name: prefix for filenames");
System.out.println(" dist: code for how to distribute across files:");
System.out.println(" ipzct = all Images + Pixels in one file");
System.out.println(" pzct = each Image in its own file");
System.out.println(" zct = each Pixels in its own file");
System.out.println(" zc = all Z + C positions per file");
System.out.println(" zt = all Z + T positions per file");
System.out.println(" ct = all C + T positions per file");
System.out.println(" z = all Z positions per file");
System.out.println(" c = all C positions per file");
System.out.println(" t = all T positions per file");
System.out.println(" x = single plane per file");
System.out.println(" -scramble: randomizes IFD ordering");
System.out.println(" image*_pixels*_SizeX: width of image planes");
System.out.println(" image*_pixels*_SizeY: height of image planes");
System.out.println(" image*_pixels*_SizeZ: number of focal planes");
System.out.println(" image*_pixels*_SizeC: number of channels");
System.out.println(" image*_pixels*_SizeT: number of time points");
System.out.println(" image*_pixels*_DimOrder: planar ordering:");
System.out.println(" XYZCT, XYZTC, XYCZT, XYCTZ, XYTZC, or XYTCZ");
System.out.println();
System.out.println("Example:");
System.out.println(" java MakeTestOmeTiff test ipzct \\");
System.out.println(" 2 431 555 1 2 7 XYTCZ \\");
System.out.println(" 348 461 2 1 6 XYZTC \\");
System.out.println(" 1 517 239 5 3 4 XYCZT");
System.exit(1);
}
if (!dist.equals("ipzct") && !dist.equals("pzct") && !dist.equals("zct") &&
!dist.equals("zc") && !dist.equals("zt") && !dist.equals("ct") &&
!dist.equals("z") && !dist.equals("c") && !dist.equals("t") &&
!dist.equals("x"))
{
System.out.println("Invalid dist value: " + dist);
System.exit(2);
}
boolean allI = dist.indexOf("i") >= 0;
boolean allP = dist.indexOf("p") >= 0;
boolean allZ = dist.indexOf("z") >= 0;
boolean allC = dist.indexOf("c") >= 0;
boolean allT = dist.indexOf("t") >= 0;
BufferedImage[][][] images = new BufferedImage[numImages][][];
int[][] globalOffsets = new int[numImages][]; // IFD offsets across Images
int[][] localOffsets = new int[numImages][]; // IFD offsets per Image
int globalOffset = 0, localOffset = 0;
for (int i=0; i<numImages; i++) {
images[i] = new BufferedImage[numPixels[i]][];
globalOffsets[i] = new int[numPixels[i]];
localOffsets[i] = new int[numPixels[i]];
localOffset = 0;
for (int p=0; p<numPixels[i]; p++) {
int len = sizeZ[i][p] * sizeC[i][p] * sizeT[i][p];
images[i][p] = new BufferedImage[len];
globalOffsets[i][p] = globalOffset;
globalOffset += len;
localOffsets[i][p] = localOffset;
localOffset += len;
}
}
System.out.println("Generating image planes");
for (int i=0, ipNum=0; i<numImages; i++) {
System.out.println(" Image #" + (i + 1) + ":");
for (int p=0; p<numPixels[i]; p++, ipNum++) {
System.out.print(" Pixels #" + (p + 1) + " - " +
sizeX[i][p] + " x " + sizeY[i][p] + ", " +
sizeZ[i][p] + "Z " + sizeC[i][p] + "C " + sizeT[i][p] + "T");
int len = images[i][p].length;
for (int j=0; j<len; j++) {
int[] zct = FormatTools.getZCTCoords(dimOrder[i][p],
sizeZ[i][p], sizeC[i][p], sizeT[i][p], len, j);
System.out.print(".");
images[i][p][j] = new BufferedImage(
sizeX[i][p], sizeY[i][p], BufferedImage.TYPE_BYTE_GRAY);
Graphics2D g = images[i][p][j].createGraphics();
// draw gradient
boolean even = ipNum % 2 == 0;
int type = ipNum / 2;
if (even) {
// draw vertical gradient for even-numbered pixelses
for (int y=0; y<sizeY[i][p]; y++) {
int v = gradient(type, y, sizeY[i][p]);
g.setColor(new Color(v, v, v));
g.drawLine(0, y, sizeX[i][p], y);
}
}
else {
// draw horizontal gradient for odd-numbered pixelses
for (int x=0; x<sizeX[i][p]; x++) {
int v = gradient(type, x, sizeX[i][p]);
g.setColor(new Color(v, v, v));
g.drawLine(x, 0, x, sizeY[i][p]);
}
}
// build list of text lines from planar information
Vector lines = new Vector();
Font font = g.getFont();
lines.add(new TextLine(name, font.deriveFont(32f), 5, -5));
lines.add(new TextLine(sizeX[i][p] + " x " + sizeY[i][p],
font.deriveFont(Font.ITALIC, 16f), 20, 10));
lines.add(new TextLine(dimOrder[i][p],
font.deriveFont(Font.ITALIC, 14f), 30, 5));
int space = 5;
if (numImages > 1) {
lines.add(new TextLine("Image #" + (i + 1) + "/" + numImages,
font, 20, space));
space = 2;
}
if (numPixels[i] > 1) {
lines.add(new TextLine("Pixels #" + (p + 1) + "/" + numPixels[i],
font, 20, space));
space = 2;
}
if (sizeZ[i][p] > 1) {
lines.add(new TextLine("Focal plane = " +
(zct[0] + 1) + "/" + sizeZ[i][p], font, 20, space));
space = 2;
}
if (sizeC[i][p] > 1) {
lines.add(new TextLine("Channel = " +
(zct[1] + 1) + "/" + sizeC[i][p], font, 20, space));
space = 2;
}
if (sizeT[i][p] > 1) {
lines.add(new TextLine("Time point = " +
(zct[2] + 1) + "/" + sizeT[i][p], font, 20, space));
space = 2;
}
// draw text lines to image
g.setColor(Color.white);
int yoff = 0;
for (int l=0; l<lines.size(); l++) {
TextLine text = (TextLine) lines.get(l);
g.setFont(text.font);
Rectangle2D r = g.getFont().getStringBounds(
text.line, g.getFontRenderContext());
yoff += r.getHeight() + text.ypad;
g.drawString(text.line, text.xoff, yoff);
}
g.dispose();
}
System.out.println();
}
}
System.out.println("Writing output files");
// determine filename for each image plane
String[][][] filenames = new String[numImages][][];
Hashtable lastHash = new Hashtable();
boolean[][][] last = new boolean[numImages][][];
Hashtable ifdTotal = new Hashtable();
Hashtable firstZ = new Hashtable();
Hashtable firstC = new Hashtable();
Hashtable firstT = new Hashtable();
StringBuffer sb = new StringBuffer();
for (int i=0; i<numImages; i++) {
filenames[i] = new String[numPixels[i]][];
last[i] = new boolean[numPixels[i]][];
for (int p=0; p<numPixels[i]; p++) {
int len = images[i][p].length;
filenames[i][p] = new String[len];
last[i][p] = new boolean[len];
for (int j=0; j<len; j++) {
sb.append(name);
if (!allI && numImages > 1) sb.append("_image" + (i + 1));
if (!allP && numPixels[i] > 1) sb.append("_pixels" + (p + 1));
int[] zct = FormatTools.getZCTCoords(dimOrder[i][p],
sizeZ[i][p], sizeC[i][p], sizeT[i][p], len, j);
if (!allZ && sizeZ[i][p] > 1) sb.append("_Z" + (zct[0] + 1));
if (!allC && sizeC[i][p] > 1) sb.append("_C" + (zct[1] + 1));
if (!allT && sizeT[i][p] > 1) sb.append("_T" + (zct[2] + 1));
sb.append(".ome.tif");
filenames[i][p][j] = sb.toString();
sb.setLength(0);
last[i][p][j] = true;
// update last flag for this filename
String key = filenames[i][p][j];
ImageIndex index = (ImageIndex) lastHash.get(key);
if (index != null) {
last[index.image][index.pixels][index.plane] = false;
}
lastHash.put(key, new ImageIndex(i, p, j));
// update IFD count for this filename
Integer total = (Integer) ifdTotal.get(key);
if (total == null) total = new Integer(1);
else total = new Integer(total.intValue() + 1);
ifdTotal.put(key, total);
// update FirstZ, FirstC and FirstT values for this filename
if (!allZ && sizeZ[i][p] > 1) {
firstZ.put(filenames[i][p][j], new Integer(zct[0]));
}
if (!allC && sizeC[i][p] > 1) {
firstC.put(filenames[i][p][j], new Integer(zct[1]));
}
if (!allT && sizeT[i][p] > 1) {
firstT.put(filenames[i][p][j], new Integer(zct[2]));
}
}
}
}
// build OME-XML block
// CreationDate is required; initialize a default value (current time)
// use ISO 8601 dateTime format (e.g., 1988-04-07T18:39:09)
sb.setLength(0);
Calendar now = Calendar.getInstance();
int year = now.get(Calendar.YEAR);
int month = now.get(Calendar.MONTH);
int day = now.get(Calendar.DAY_OF_MONTH);
int hour = now.get(Calendar.HOUR_OF_DAY);
int min = now.get(Calendar.MINUTE);
int sec = now.get(Calendar.SECOND);
sb.append(year);
sb.append("-");
if (month < 9) sb.append("0");
sb.append(month + 1);
sb.append("-");
if (day < 10) sb.append("0");
sb.append(day);
sb.append("T");
if (hour < 10) sb.append("0");
sb.append(hour);
sb.append(":");
if (min < 10) sb.append("0");
sb.append(min);
sb.append(":");
if (sec < 10) sb.append("0");
sb.append(sec);
String creationDate = sb.toString();
sb.setLength(0);
sb.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>" +
"<!-- Warning: this comment is an OME-XML metadata block, which " +
"contains crucial dimensional parameters and other important metadata. " +
"Please edit cautiously (if at all), and back up the original data " +
"before doing so. For more information, see the OME-TIFF web site: " +
"http://loci.wisc.edu/ome/ome-tiff.html. --><OME " +
"xmlns=\"http://www.openmicroscopy.org/XMLschemas/OME/FC/ome.xsd\" " +
"xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" " +
"xsi:schemaLocation=\"" +
"http://www.openmicroscopy.org/XMLschemas/OME/FC/ome.xsd\">");
for (int i=0; i<numImages; i++) {
sb.append("<Image " +
"ID=\"openmicroscopy.org:Image:" + (i + 1) + "\" " +
"Name=\"" + name + "\" " +
"DefaultPixels=\"openmicroscopy.org:Pixels:" + (i + 1) + "-1\">" +
"<CreationDate>" + creationDate + "</CreationDate>");
for (int p=0; p<numPixels[i]; p++) {
sb.append("<Pixels " +
"ID=\"openmicroscopy.org:Pixels:" + (i + 1) + "-" + (p + 1) + "\" " +
"DimensionOrder=\"" + dimOrder[i][p] + "\" " +
"PixelType=\"uint8\" " +
"BigEndian=\"true\" " +
"SizeX=\"" + sizeX[i][p] + "\" " +
"SizeY=\"" + sizeY[i][p] + "\" " +
"SizeZ=\"" + sizeZ[i][p] + "\" " +
"SizeC=\"" + sizeC[i][p] + "\" " +
"SizeT=\"" + sizeT[i][p] + "\">" +
"TIFF_DATA_IMAGE_" + i + "_PIXELS_" + p + // placeholder
"</Pixels>");
}
sb.append("</Image>");
}
sb.append("</OME>");
String xmlTemplate = sb.toString();
TiffWriter out = new TiffWriter();
for (int i=0; i<numImages; i++) {
System.out.println(" Image #" + (i + 1) + ":");
for (int p=0; p<numPixels[i]; p++) {
System.out.println(" Pixels #" + (p + 1) + " - " +
sizeX[i][p] + " x " + sizeY[i][p] + ", " +
sizeZ[i][p] + "Z " + sizeC[i][p] + "C " + sizeT[i][p] + "T:");
int len = images[i][p].length;
for (int j=0; j<len; j++) {
int[] zct = FormatTools.getZCTCoords(dimOrder[i][p],
sizeZ[i][p], sizeC[i][p], sizeT[i][p], len, j);
System.out.println(" " +
"Z" + zct[0] + " C" + zct[1] + " T" + zct[2] +
" -> " + filenames[i][p][j] + (last[i][p][j] ? "*" : ""));
out.setId(filenames[i][p][j]);
// write comment stub, to be overwritten later
Hashtable ifdHash = new Hashtable();
TiffTools.putIFDValue(ifdHash, TiffTools.IMAGE_DESCRIPTION, "");
out.saveImage(images[i][p][j], ifdHash, last[i][p][j]);
if (last[i][p][j]) {
// inject OME-XML block
String xml = xmlTemplate;
String key = filenames[i][p][j];
Integer fzObj = (Integer) firstZ.get(key);
Integer fcObj = (Integer) firstC.get(key);
Integer ftObj = (Integer) firstT.get(key);
int fz = fzObj == null ? 0 : fzObj.intValue();
int fc = fcObj == null ? 0 : fcObj.intValue();
int ft = ftObj == null ? 0 : ftObj.intValue();
Integer total = (Integer) ifdTotal.get(key);
if (!scramble) total = null;
for (int ii=0; ii<numImages; ii++) {
for (int pp=0; pp<numPixels[ii]; pp++) {
String pattern = "TIFF_DATA_IMAGE_" + ii + "_PIXELS_" + pp;
if (!allI && ii != i || !allP && pp != p) {
// current Pixels is not part of this file
xml = xml.replaceFirst(pattern,
tiffData(0, 0, 0, 0, 0, dimOrder[ii][pp],
sizeZ[ii][pp], sizeC[ii][pp], sizeT[ii][pp], total));
continue;
}
if (allP) {
int ifd;
if (allI) {
// all Images in one file; need to use global offset
ifd = globalOffsets[ii][pp];
}
else { // ii == i
// one Image per file; use local offset
ifd = localOffsets[ii][pp];
}
int num = images[ii][pp].length;
if ((!allI || numImages == 1) && numPixels[i] == 1) {
// only one Pixels in this file; don't need IFD/NumPlanes
ifd = 0;
num = -1;
}
xml = xml.replaceFirst(pattern,
tiffData(ifd, num, 0, 0, 0, dimOrder[ii][pp],
sizeZ[ii][pp], sizeC[ii][pp], sizeT[ii][pp], total));
}
else { // pp == p
xml = xml.replaceFirst(pattern,
tiffData(0, -1, fz, fc, ft, dimOrder[ii][pp],
sizeZ[ii][pp], sizeC[ii][pp], sizeT[ii][pp], total));
}
}
}
TiffTools.overwriteComment(filenames[i][p][j], xml);
}
}
}
}
}
|
diff --git a/src/com/android/calendar/AlertService.java b/src/com/android/calendar/AlertService.java
index f2859507..3719f6b3 100644
--- a/src/com/android/calendar/AlertService.java
+++ b/src/com/android/calendar/AlertService.java
@@ -1,454 +1,454 @@
/*
* Copyright (C) 2008 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.calendar;
import android.app.AlarmManager;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.Service;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.IBinder;
import android.os.Looper;
import android.os.Message;
import android.os.Process;
import android.preference.PreferenceManager;
import android.provider.Calendar;
import android.provider.Calendar.Attendees;
import android.provider.Calendar.CalendarAlerts;
import android.provider.Calendar.Instances;
import android.provider.Calendar.Reminders;
import android.text.TextUtils;
import android.text.format.DateUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
/**
* This service is used to handle calendar event reminders.
*/
public class AlertService extends Service {
private static final String TAG = "AlertService";
private volatile Looper mServiceLooper;
private volatile ServiceHandler mServiceHandler;
private static final String[] ALERT_PROJECTION = new String[] {
CalendarAlerts._ID, // 0
CalendarAlerts.EVENT_ID, // 1
CalendarAlerts.STATE, // 2
CalendarAlerts.TITLE, // 3
CalendarAlerts.EVENT_LOCATION, // 4
CalendarAlerts.SELF_ATTENDEE_STATUS, // 5
CalendarAlerts.ALL_DAY, // 6
CalendarAlerts.ALARM_TIME, // 7
CalendarAlerts.MINUTES, // 8
CalendarAlerts.BEGIN, // 9
};
// We just need a simple projection that returns any column
private static final String[] ALERT_PROJECTION_SMALL = new String[] {
CalendarAlerts._ID, // 0
};
private static final int ALERT_INDEX_ID = 0;
private static final int ALERT_INDEX_EVENT_ID = 1;
private static final int ALERT_INDEX_STATE = 2;
private static final int ALERT_INDEX_TITLE = 3;
private static final int ALERT_INDEX_EVENT_LOCATION = 4;
private static final int ALERT_INDEX_SELF_ATTENDEE_STATUS = 5;
private static final int ALERT_INDEX_ALL_DAY = 6;
private static final int ALERT_INDEX_ALARM_TIME = 7;
private static final int ALERT_INDEX_MINUTES = 8;
private static final int ALERT_INDEX_BEGIN = 9;
private String[] INSTANCE_PROJECTION = { Instances.BEGIN, Instances.END };
private static final int INSTANCES_INDEX_BEGIN = 0;
private static final int INSTANCES_INDEX_END = 1;
// We just need a simple projection that returns any column
private static final String[] REMINDER_PROJECTION_SMALL = new String[] {
Reminders._ID, // 0
};
@SuppressWarnings("deprecation")
void processMessage(Message msg) {
Bundle bundle = (Bundle) msg.obj;
// On reboot, update the notification bar with the contents of the
// CalendarAlerts table.
String action = bundle.getString("action");
if (action.equals(Intent.ACTION_BOOT_COMPLETED)
|| action.equals(Intent.ACTION_TIME_CHANGED)) {
doTimeChanged();
return;
}
// The Uri specifies an entry in the CalendarAlerts table
Uri alertUri = Uri.parse(bundle.getString("uri"));
if (Log.isLoggable(TAG, Log.DEBUG)) {
Log.d(TAG, "uri: " + alertUri);
}
if (alertUri != null) {
- if (Calendar.AUTHORITY.equals(alertUri.getAuthority())) {
+ if (!Calendar.AUTHORITY.equals(alertUri.getAuthority())) {
Log.w(TAG, "Invalid AUTHORITY uri: " + alertUri);
return;
}
// Record the received time in the CalendarAlerts table.
// This is useful for finding bugs that cause alarms to be
// missed or delayed.
ContentValues values = new ContentValues();
values.put(CalendarAlerts.RECEIVED_TIME, System.currentTimeMillis());
getContentResolver().update(alertUri, values, null /* where */, null /* args */);
}
ContentResolver cr = getContentResolver();
Cursor alertCursor = cr.query(alertUri, ALERT_PROJECTION,
null /* selection */, null, null /* sort order */);
long alertId, eventId, alarmTime;
int minutes;
String eventName;
String location;
boolean allDay;
boolean declined = false;
try {
if (alertCursor == null || !alertCursor.moveToFirst()) {
// This can happen if the event was deleted.
if (Log.isLoggable(TAG, Log.DEBUG)) {
Log.d(TAG, "alert not found");
}
return;
}
alertId = alertCursor.getLong(ALERT_INDEX_ID);
eventId = alertCursor.getLong(ALERT_INDEX_EVENT_ID);
minutes = alertCursor.getInt(ALERT_INDEX_MINUTES);
eventName = alertCursor.getString(ALERT_INDEX_TITLE);
location = alertCursor.getString(ALERT_INDEX_EVENT_LOCATION);
allDay = alertCursor.getInt(ALERT_INDEX_ALL_DAY) != 0;
alarmTime = alertCursor.getLong(ALERT_INDEX_ALARM_TIME);
declined = alertCursor.getInt(ALERT_INDEX_SELF_ATTENDEE_STATUS) ==
Attendees.ATTENDEE_STATUS_DECLINED;
// If the event was declined, then mark the alarm DISMISSED,
// otherwise, mark the alarm FIRED.
int newState = CalendarAlerts.FIRED;
if (declined) {
newState = CalendarAlerts.DISMISSED;
}
alertCursor.updateInt(ALERT_INDEX_STATE, newState);
alertCursor.commitUpdates();
} finally {
if (alertCursor != null) {
alertCursor.close();
}
}
// Do not show an alert if the event was declined
if (declined) {
if (Log.isLoggable(TAG, Log.DEBUG)) {
Log.d(TAG, "event declined, alert cancelled");
}
return;
}
long beginTime = bundle.getLong(Calendar.EVENT_BEGIN_TIME, 0);
long endTime = bundle.getLong(Calendar.EVENT_END_TIME, 0);
// Check if this alarm is still valid. The time of the event may
// have been changed, or the reminder may have been changed since
// this alarm was set. First, search for an instance in the Instances
// that has the same event id and the same begin and end time.
// Then check for a reminder in the Reminders table to ensure that
// the reminder minutes is consistent with this alarm.
String selection = Instances.EVENT_ID + "=" + eventId;
Cursor instanceCursor = Instances.query(cr, INSTANCE_PROJECTION,
beginTime, endTime, selection, Instances.DEFAULT_SORT_ORDER);
long instanceBegin = 0, instanceEnd = 0;
try {
if (instanceCursor == null || !instanceCursor.moveToFirst()) {
// Delete this alarm from the CalendarAlerts table
cr.delete(alertUri, null /* selection */, null /* selection args */);
if (Log.isLoggable(TAG, Log.DEBUG)) {
Log.d(TAG, "instance not found, alert cancelled");
}
return;
}
instanceBegin = instanceCursor.getLong(INSTANCES_INDEX_BEGIN);
instanceEnd = instanceCursor.getLong(INSTANCES_INDEX_END);
} finally {
if (instanceCursor != null) {
instanceCursor.close();
}
}
// Check that a reminder for this event exists with the same number
// of minutes. But snoozed alarms have minutes = 0, so don't do this
// check for snoozed alarms.
if (minutes > 0) {
selection = Reminders.EVENT_ID + "=" + eventId
+ " AND " + Reminders.MINUTES + "=" + minutes;
Cursor reminderCursor = cr.query(Reminders.CONTENT_URI, REMINDER_PROJECTION_SMALL,
selection, null /* selection args */, null /* sort order */);
try {
if (reminderCursor == null || reminderCursor.getCount() == 0) {
// Delete this alarm from the CalendarAlerts table
cr.delete(alertUri, null /* selection */, null /* selection args */);
if (Log.isLoggable(TAG, Log.DEBUG)) {
Log.d(TAG, "reminder not found, alert cancelled");
}
return;
}
} finally {
if (reminderCursor != null) {
reminderCursor.close();
}
}
}
// If the event time was changed and the event has already ended,
// then don't sound the alarm.
if (alarmTime > instanceEnd) {
// Delete this alarm from the CalendarAlerts table
cr.delete(alertUri, null /* selection */, null /* selection args */);
if (Log.isLoggable(TAG, Log.DEBUG)) {
Log.d(TAG, "event ended, alert cancelled");
}
return;
}
// If minutes > 0, then this is a normal alarm (not a snoozed alarm)
// so check for duplicate alarms. A duplicate alarm can occur when
// the start time of an event is changed to an earlier time. The
// later alarm (that was first scheduled for the later event time)
// should be discarded.
long computedAlarmTime = instanceBegin - minutes * DateUtils.MINUTE_IN_MILLIS;
if (minutes > 0 && computedAlarmTime != alarmTime) {
// If the event time was changed to a later time, then the computed
// alarm time is in the future and we shouldn't sound this alarm.
if (computedAlarmTime > alarmTime) {
// Delete this alarm from the CalendarAlerts table
cr.delete(alertUri, null /* selection */, null /* selection args */);
if (Log.isLoggable(TAG, Log.DEBUG)) {
Log.d(TAG, "event postponed, alert cancelled");
}
return;
}
// Check for another alarm in the CalendarAlerts table that has the
// same event id and the same "minutes". This can occur
// if the event start time was changed to an earlier time and the
// alarm for the later time goes off. To avoid discarding alarms
// for repeating events (that have the same event id), we check
// that the other alarm fired recently (within an hour of this one).
long recently = alarmTime - 60 * DateUtils.MINUTE_IN_MILLIS;
selection = CalendarAlerts.EVENT_ID + "=" + eventId
+ " AND " + CalendarAlerts.TABLE_NAME + "." + CalendarAlerts._ID
+ "!=" + alertId
+ " AND " + CalendarAlerts.MINUTES + "=" + minutes
+ " AND " + CalendarAlerts.ALARM_TIME + ">" + recently
+ " AND " + CalendarAlerts.ALARM_TIME + "<=" + alarmTime;
alertCursor = CalendarAlerts.query(cr, ALERT_PROJECTION_SMALL, selection, null);
if (alertCursor != null) {
try {
if (alertCursor.getCount() > 0) {
// Delete this alarm from the CalendarAlerts table
cr.delete(alertUri, null /* selection */, null /* selection args */);
if (Log.isLoggable(TAG, Log.DEBUG)) {
Log.d(TAG, "duplicate alarm, alert cancelled");
}
return;
}
} finally {
alertCursor.close();
}
}
}
// Find all the alerts that have fired but have not been dismissed
selection = CalendarAlerts.STATE + "=" + CalendarAlerts.FIRED;
alertCursor = CalendarAlerts.query(cr, ALERT_PROJECTION, selection, null);
if (alertCursor == null || alertCursor.getCount() == 0) {
if (Log.isLoggable(TAG, Log.DEBUG)) {
Log.d(TAG, "no fired alarms found");
}
return;
}
int numReminders = alertCursor.getCount();
try {
while (alertCursor.moveToNext()) {
long otherEventId = alertCursor.getLong(ALERT_INDEX_EVENT_ID);
long otherAlertId = alertCursor.getLong(ALERT_INDEX_ID);
int otherAlarmState = alertCursor.getInt(ALERT_INDEX_STATE);
long otherBeginTime = alertCursor.getLong(ALERT_INDEX_BEGIN);
if (otherEventId == eventId && otherAlertId != alertId
&& otherAlarmState == CalendarAlerts.FIRED
&& otherBeginTime == beginTime) {
// This event already has an alert that fired and has not
// been dismissed. This can happen if an event has
// multiple reminders. Do not count this as a separate
// reminder. But we do want to sound the alarm and vibrate
// the phone, if necessary.
if (Log.isLoggable(TAG, Log.DEBUG)) {
Log.d(TAG, "multiple alarms for this event");
}
numReminders -= 1;
}
}
} finally {
alertCursor.close();
}
if (Log.isLoggable(TAG, Log.DEBUG)) {
Log.d(TAG, "creating new alarm notification, numReminders: " + numReminders);
}
Notification notification = AlertReceiver.makeNewAlertNotification(this, eventName,
location, numReminders);
// Generate either a pop-up dialog, status bar notification, or
// neither. Pop-up dialog and status bar notification may include a
// sound, an alert, or both. A status bar notification also includes
// a toast.
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
String reminderType = prefs.getString(CalendarPreferenceActivity.KEY_ALERTS_TYPE,
CalendarPreferenceActivity.ALERT_TYPE_STATUS_BAR);
if (reminderType.equals(CalendarPreferenceActivity.ALERT_TYPE_OFF)) {
if (Log.isLoggable(TAG, Log.DEBUG)) {
Log.d(TAG, "alert preference is OFF");
}
return;
}
NotificationManager nm =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
boolean reminderVibrate =
prefs.getBoolean(CalendarPreferenceActivity.KEY_ALERTS_VIBRATE, false);
String reminderRingtone =
prefs.getString(CalendarPreferenceActivity.KEY_ALERTS_RINGTONE, null);
// Possibly generate a vibration
if (reminderVibrate) {
notification.defaults |= Notification.DEFAULT_VIBRATE;
}
// Possibly generate a sound. If 'Silent' is chosen, the ringtone string will be empty.
notification.sound = TextUtils.isEmpty(reminderRingtone) ? null : Uri
.parse(reminderRingtone);
if (reminderType.equals(CalendarPreferenceActivity.ALERT_TYPE_ALERTS)) {
Intent alertIntent = new Intent();
alertIntent.setClass(this, AlertActivity.class);
alertIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(alertIntent);
} else {
LayoutInflater inflater;
inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = inflater.inflate(R.layout.alert_toast, null);
AlertAdapter.updateView(this, view, eventName, location, beginTime, endTime, allDay);
}
// Record the notify time in the CalendarAlerts table.
// This is used for debugging missed alarms.
ContentValues values = new ContentValues();
long currentTime = System.currentTimeMillis();
values.put(CalendarAlerts.NOTIFY_TIME, currentTime);
cr.update(alertUri, values, null /* where */, null /* args */);
// The notification time should be pretty close to the reminder time
// that the user set for this event. If the notification is late, then
// that's a bug and we should log an error.
if (currentTime > alarmTime + DateUtils.MINUTE_IN_MILLIS) {
long minutesLate = (currentTime - alarmTime) / DateUtils.MINUTE_IN_MILLIS;
int flags = DateUtils.FORMAT_SHOW_YEAR | DateUtils.FORMAT_SHOW_TIME;
String alarmTimeStr = DateUtils.formatDateTime(this, alarmTime, flags);
String currentTimeStr = DateUtils.formatDateTime(this, currentTime, flags);
Log.w(TAG, "Calendar reminder alarm for event id " + eventId
+ " is " + minutesLate + " minute(s) late;"
+ " expected alarm at: " + alarmTimeStr
+ " but got it at: " + currentTimeStr);
}
nm.notify(0, notification);
}
private void doTimeChanged() {
ContentResolver cr = getContentResolver();
Object service = getSystemService(Context.ALARM_SERVICE);
AlarmManager manager = (AlarmManager) service;
CalendarAlerts.rescheduleMissedAlarms(cr, this, manager);
AlertReceiver.updateAlertNotification(this);
}
private final class ServiceHandler extends Handler {
public ServiceHandler(Looper looper) {
super(looper);
}
@Override
public void handleMessage(Message msg) {
processMessage(msg);
// NOTE: We MUST not call stopSelf() directly, since we need to
// make sure the wake lock acquired by AlertReceiver is released.
AlertReceiver.finishStartingService(AlertService.this, msg.arg1);
}
};
@Override
public void onCreate() {
HandlerThread thread = new HandlerThread("AlertService",
Process.THREAD_PRIORITY_BACKGROUND);
thread.start();
mServiceLooper = thread.getLooper();
mServiceHandler = new ServiceHandler(mServiceLooper);
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
if (intent != null) {
Message msg = mServiceHandler.obtainMessage();
msg.arg1 = startId;
msg.obj = intent.getExtras();
mServiceHandler.sendMessage(msg);
}
return START_REDELIVER_INTENT;
}
@Override
public void onDestroy() {
mServiceLooper.quit();
}
@Override
public IBinder onBind(Intent intent) {
return null;
}
}
| true | true | void processMessage(Message msg) {
Bundle bundle = (Bundle) msg.obj;
// On reboot, update the notification bar with the contents of the
// CalendarAlerts table.
String action = bundle.getString("action");
if (action.equals(Intent.ACTION_BOOT_COMPLETED)
|| action.equals(Intent.ACTION_TIME_CHANGED)) {
doTimeChanged();
return;
}
// The Uri specifies an entry in the CalendarAlerts table
Uri alertUri = Uri.parse(bundle.getString("uri"));
if (Log.isLoggable(TAG, Log.DEBUG)) {
Log.d(TAG, "uri: " + alertUri);
}
if (alertUri != null) {
if (Calendar.AUTHORITY.equals(alertUri.getAuthority())) {
Log.w(TAG, "Invalid AUTHORITY uri: " + alertUri);
return;
}
// Record the received time in the CalendarAlerts table.
// This is useful for finding bugs that cause alarms to be
// missed or delayed.
ContentValues values = new ContentValues();
values.put(CalendarAlerts.RECEIVED_TIME, System.currentTimeMillis());
getContentResolver().update(alertUri, values, null /* where */, null /* args */);
}
ContentResolver cr = getContentResolver();
Cursor alertCursor = cr.query(alertUri, ALERT_PROJECTION,
null /* selection */, null, null /* sort order */);
long alertId, eventId, alarmTime;
int minutes;
String eventName;
String location;
boolean allDay;
boolean declined = false;
try {
if (alertCursor == null || !alertCursor.moveToFirst()) {
// This can happen if the event was deleted.
if (Log.isLoggable(TAG, Log.DEBUG)) {
Log.d(TAG, "alert not found");
}
return;
}
alertId = alertCursor.getLong(ALERT_INDEX_ID);
eventId = alertCursor.getLong(ALERT_INDEX_EVENT_ID);
minutes = alertCursor.getInt(ALERT_INDEX_MINUTES);
eventName = alertCursor.getString(ALERT_INDEX_TITLE);
location = alertCursor.getString(ALERT_INDEX_EVENT_LOCATION);
allDay = alertCursor.getInt(ALERT_INDEX_ALL_DAY) != 0;
alarmTime = alertCursor.getLong(ALERT_INDEX_ALARM_TIME);
declined = alertCursor.getInt(ALERT_INDEX_SELF_ATTENDEE_STATUS) ==
Attendees.ATTENDEE_STATUS_DECLINED;
// If the event was declined, then mark the alarm DISMISSED,
// otherwise, mark the alarm FIRED.
int newState = CalendarAlerts.FIRED;
if (declined) {
newState = CalendarAlerts.DISMISSED;
}
alertCursor.updateInt(ALERT_INDEX_STATE, newState);
alertCursor.commitUpdates();
} finally {
if (alertCursor != null) {
alertCursor.close();
}
}
// Do not show an alert if the event was declined
if (declined) {
if (Log.isLoggable(TAG, Log.DEBUG)) {
Log.d(TAG, "event declined, alert cancelled");
}
return;
}
long beginTime = bundle.getLong(Calendar.EVENT_BEGIN_TIME, 0);
long endTime = bundle.getLong(Calendar.EVENT_END_TIME, 0);
// Check if this alarm is still valid. The time of the event may
// have been changed, or the reminder may have been changed since
// this alarm was set. First, search for an instance in the Instances
// that has the same event id and the same begin and end time.
// Then check for a reminder in the Reminders table to ensure that
// the reminder minutes is consistent with this alarm.
String selection = Instances.EVENT_ID + "=" + eventId;
Cursor instanceCursor = Instances.query(cr, INSTANCE_PROJECTION,
beginTime, endTime, selection, Instances.DEFAULT_SORT_ORDER);
long instanceBegin = 0, instanceEnd = 0;
try {
if (instanceCursor == null || !instanceCursor.moveToFirst()) {
// Delete this alarm from the CalendarAlerts table
cr.delete(alertUri, null /* selection */, null /* selection args */);
if (Log.isLoggable(TAG, Log.DEBUG)) {
Log.d(TAG, "instance not found, alert cancelled");
}
return;
}
instanceBegin = instanceCursor.getLong(INSTANCES_INDEX_BEGIN);
instanceEnd = instanceCursor.getLong(INSTANCES_INDEX_END);
} finally {
if (instanceCursor != null) {
instanceCursor.close();
}
}
// Check that a reminder for this event exists with the same number
// of minutes. But snoozed alarms have minutes = 0, so don't do this
// check for snoozed alarms.
if (minutes > 0) {
selection = Reminders.EVENT_ID + "=" + eventId
+ " AND " + Reminders.MINUTES + "=" + minutes;
Cursor reminderCursor = cr.query(Reminders.CONTENT_URI, REMINDER_PROJECTION_SMALL,
selection, null /* selection args */, null /* sort order */);
try {
if (reminderCursor == null || reminderCursor.getCount() == 0) {
// Delete this alarm from the CalendarAlerts table
cr.delete(alertUri, null /* selection */, null /* selection args */);
if (Log.isLoggable(TAG, Log.DEBUG)) {
Log.d(TAG, "reminder not found, alert cancelled");
}
return;
}
} finally {
if (reminderCursor != null) {
reminderCursor.close();
}
}
}
// If the event time was changed and the event has already ended,
// then don't sound the alarm.
if (alarmTime > instanceEnd) {
// Delete this alarm from the CalendarAlerts table
cr.delete(alertUri, null /* selection */, null /* selection args */);
if (Log.isLoggable(TAG, Log.DEBUG)) {
Log.d(TAG, "event ended, alert cancelled");
}
return;
}
// If minutes > 0, then this is a normal alarm (not a snoozed alarm)
// so check for duplicate alarms. A duplicate alarm can occur when
// the start time of an event is changed to an earlier time. The
// later alarm (that was first scheduled for the later event time)
// should be discarded.
long computedAlarmTime = instanceBegin - minutes * DateUtils.MINUTE_IN_MILLIS;
if (minutes > 0 && computedAlarmTime != alarmTime) {
// If the event time was changed to a later time, then the computed
// alarm time is in the future and we shouldn't sound this alarm.
if (computedAlarmTime > alarmTime) {
// Delete this alarm from the CalendarAlerts table
cr.delete(alertUri, null /* selection */, null /* selection args */);
if (Log.isLoggable(TAG, Log.DEBUG)) {
Log.d(TAG, "event postponed, alert cancelled");
}
return;
}
// Check for another alarm in the CalendarAlerts table that has the
// same event id and the same "minutes". This can occur
// if the event start time was changed to an earlier time and the
// alarm for the later time goes off. To avoid discarding alarms
// for repeating events (that have the same event id), we check
// that the other alarm fired recently (within an hour of this one).
long recently = alarmTime - 60 * DateUtils.MINUTE_IN_MILLIS;
selection = CalendarAlerts.EVENT_ID + "=" + eventId
+ " AND " + CalendarAlerts.TABLE_NAME + "." + CalendarAlerts._ID
+ "!=" + alertId
+ " AND " + CalendarAlerts.MINUTES + "=" + minutes
+ " AND " + CalendarAlerts.ALARM_TIME + ">" + recently
+ " AND " + CalendarAlerts.ALARM_TIME + "<=" + alarmTime;
alertCursor = CalendarAlerts.query(cr, ALERT_PROJECTION_SMALL, selection, null);
if (alertCursor != null) {
try {
if (alertCursor.getCount() > 0) {
// Delete this alarm from the CalendarAlerts table
cr.delete(alertUri, null /* selection */, null /* selection args */);
if (Log.isLoggable(TAG, Log.DEBUG)) {
Log.d(TAG, "duplicate alarm, alert cancelled");
}
return;
}
} finally {
alertCursor.close();
}
}
}
// Find all the alerts that have fired but have not been dismissed
selection = CalendarAlerts.STATE + "=" + CalendarAlerts.FIRED;
alertCursor = CalendarAlerts.query(cr, ALERT_PROJECTION, selection, null);
if (alertCursor == null || alertCursor.getCount() == 0) {
if (Log.isLoggable(TAG, Log.DEBUG)) {
Log.d(TAG, "no fired alarms found");
}
return;
}
int numReminders = alertCursor.getCount();
try {
while (alertCursor.moveToNext()) {
long otherEventId = alertCursor.getLong(ALERT_INDEX_EVENT_ID);
long otherAlertId = alertCursor.getLong(ALERT_INDEX_ID);
int otherAlarmState = alertCursor.getInt(ALERT_INDEX_STATE);
long otherBeginTime = alertCursor.getLong(ALERT_INDEX_BEGIN);
if (otherEventId == eventId && otherAlertId != alertId
&& otherAlarmState == CalendarAlerts.FIRED
&& otherBeginTime == beginTime) {
// This event already has an alert that fired and has not
// been dismissed. This can happen if an event has
// multiple reminders. Do not count this as a separate
// reminder. But we do want to sound the alarm and vibrate
// the phone, if necessary.
if (Log.isLoggable(TAG, Log.DEBUG)) {
Log.d(TAG, "multiple alarms for this event");
}
numReminders -= 1;
}
}
} finally {
alertCursor.close();
}
if (Log.isLoggable(TAG, Log.DEBUG)) {
Log.d(TAG, "creating new alarm notification, numReminders: " + numReminders);
}
Notification notification = AlertReceiver.makeNewAlertNotification(this, eventName,
location, numReminders);
// Generate either a pop-up dialog, status bar notification, or
// neither. Pop-up dialog and status bar notification may include a
// sound, an alert, or both. A status bar notification also includes
// a toast.
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
String reminderType = prefs.getString(CalendarPreferenceActivity.KEY_ALERTS_TYPE,
CalendarPreferenceActivity.ALERT_TYPE_STATUS_BAR);
if (reminderType.equals(CalendarPreferenceActivity.ALERT_TYPE_OFF)) {
if (Log.isLoggable(TAG, Log.DEBUG)) {
Log.d(TAG, "alert preference is OFF");
}
return;
}
NotificationManager nm =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
boolean reminderVibrate =
prefs.getBoolean(CalendarPreferenceActivity.KEY_ALERTS_VIBRATE, false);
String reminderRingtone =
prefs.getString(CalendarPreferenceActivity.KEY_ALERTS_RINGTONE, null);
// Possibly generate a vibration
if (reminderVibrate) {
notification.defaults |= Notification.DEFAULT_VIBRATE;
}
// Possibly generate a sound. If 'Silent' is chosen, the ringtone string will be empty.
notification.sound = TextUtils.isEmpty(reminderRingtone) ? null : Uri
.parse(reminderRingtone);
if (reminderType.equals(CalendarPreferenceActivity.ALERT_TYPE_ALERTS)) {
Intent alertIntent = new Intent();
alertIntent.setClass(this, AlertActivity.class);
alertIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(alertIntent);
} else {
LayoutInflater inflater;
inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = inflater.inflate(R.layout.alert_toast, null);
AlertAdapter.updateView(this, view, eventName, location, beginTime, endTime, allDay);
}
// Record the notify time in the CalendarAlerts table.
// This is used for debugging missed alarms.
ContentValues values = new ContentValues();
long currentTime = System.currentTimeMillis();
values.put(CalendarAlerts.NOTIFY_TIME, currentTime);
cr.update(alertUri, values, null /* where */, null /* args */);
// The notification time should be pretty close to the reminder time
// that the user set for this event. If the notification is late, then
// that's a bug and we should log an error.
if (currentTime > alarmTime + DateUtils.MINUTE_IN_MILLIS) {
long minutesLate = (currentTime - alarmTime) / DateUtils.MINUTE_IN_MILLIS;
int flags = DateUtils.FORMAT_SHOW_YEAR | DateUtils.FORMAT_SHOW_TIME;
String alarmTimeStr = DateUtils.formatDateTime(this, alarmTime, flags);
String currentTimeStr = DateUtils.formatDateTime(this, currentTime, flags);
Log.w(TAG, "Calendar reminder alarm for event id " + eventId
+ " is " + minutesLate + " minute(s) late;"
+ " expected alarm at: " + alarmTimeStr
+ " but got it at: " + currentTimeStr);
}
nm.notify(0, notification);
}
| void processMessage(Message msg) {
Bundle bundle = (Bundle) msg.obj;
// On reboot, update the notification bar with the contents of the
// CalendarAlerts table.
String action = bundle.getString("action");
if (action.equals(Intent.ACTION_BOOT_COMPLETED)
|| action.equals(Intent.ACTION_TIME_CHANGED)) {
doTimeChanged();
return;
}
// The Uri specifies an entry in the CalendarAlerts table
Uri alertUri = Uri.parse(bundle.getString("uri"));
if (Log.isLoggable(TAG, Log.DEBUG)) {
Log.d(TAG, "uri: " + alertUri);
}
if (alertUri != null) {
if (!Calendar.AUTHORITY.equals(alertUri.getAuthority())) {
Log.w(TAG, "Invalid AUTHORITY uri: " + alertUri);
return;
}
// Record the received time in the CalendarAlerts table.
// This is useful for finding bugs that cause alarms to be
// missed or delayed.
ContentValues values = new ContentValues();
values.put(CalendarAlerts.RECEIVED_TIME, System.currentTimeMillis());
getContentResolver().update(alertUri, values, null /* where */, null /* args */);
}
ContentResolver cr = getContentResolver();
Cursor alertCursor = cr.query(alertUri, ALERT_PROJECTION,
null /* selection */, null, null /* sort order */);
long alertId, eventId, alarmTime;
int minutes;
String eventName;
String location;
boolean allDay;
boolean declined = false;
try {
if (alertCursor == null || !alertCursor.moveToFirst()) {
// This can happen if the event was deleted.
if (Log.isLoggable(TAG, Log.DEBUG)) {
Log.d(TAG, "alert not found");
}
return;
}
alertId = alertCursor.getLong(ALERT_INDEX_ID);
eventId = alertCursor.getLong(ALERT_INDEX_EVENT_ID);
minutes = alertCursor.getInt(ALERT_INDEX_MINUTES);
eventName = alertCursor.getString(ALERT_INDEX_TITLE);
location = alertCursor.getString(ALERT_INDEX_EVENT_LOCATION);
allDay = alertCursor.getInt(ALERT_INDEX_ALL_DAY) != 0;
alarmTime = alertCursor.getLong(ALERT_INDEX_ALARM_TIME);
declined = alertCursor.getInt(ALERT_INDEX_SELF_ATTENDEE_STATUS) ==
Attendees.ATTENDEE_STATUS_DECLINED;
// If the event was declined, then mark the alarm DISMISSED,
// otherwise, mark the alarm FIRED.
int newState = CalendarAlerts.FIRED;
if (declined) {
newState = CalendarAlerts.DISMISSED;
}
alertCursor.updateInt(ALERT_INDEX_STATE, newState);
alertCursor.commitUpdates();
} finally {
if (alertCursor != null) {
alertCursor.close();
}
}
// Do not show an alert if the event was declined
if (declined) {
if (Log.isLoggable(TAG, Log.DEBUG)) {
Log.d(TAG, "event declined, alert cancelled");
}
return;
}
long beginTime = bundle.getLong(Calendar.EVENT_BEGIN_TIME, 0);
long endTime = bundle.getLong(Calendar.EVENT_END_TIME, 0);
// Check if this alarm is still valid. The time of the event may
// have been changed, or the reminder may have been changed since
// this alarm was set. First, search for an instance in the Instances
// that has the same event id and the same begin and end time.
// Then check for a reminder in the Reminders table to ensure that
// the reminder minutes is consistent with this alarm.
String selection = Instances.EVENT_ID + "=" + eventId;
Cursor instanceCursor = Instances.query(cr, INSTANCE_PROJECTION,
beginTime, endTime, selection, Instances.DEFAULT_SORT_ORDER);
long instanceBegin = 0, instanceEnd = 0;
try {
if (instanceCursor == null || !instanceCursor.moveToFirst()) {
// Delete this alarm from the CalendarAlerts table
cr.delete(alertUri, null /* selection */, null /* selection args */);
if (Log.isLoggable(TAG, Log.DEBUG)) {
Log.d(TAG, "instance not found, alert cancelled");
}
return;
}
instanceBegin = instanceCursor.getLong(INSTANCES_INDEX_BEGIN);
instanceEnd = instanceCursor.getLong(INSTANCES_INDEX_END);
} finally {
if (instanceCursor != null) {
instanceCursor.close();
}
}
// Check that a reminder for this event exists with the same number
// of minutes. But snoozed alarms have minutes = 0, so don't do this
// check for snoozed alarms.
if (minutes > 0) {
selection = Reminders.EVENT_ID + "=" + eventId
+ " AND " + Reminders.MINUTES + "=" + minutes;
Cursor reminderCursor = cr.query(Reminders.CONTENT_URI, REMINDER_PROJECTION_SMALL,
selection, null /* selection args */, null /* sort order */);
try {
if (reminderCursor == null || reminderCursor.getCount() == 0) {
// Delete this alarm from the CalendarAlerts table
cr.delete(alertUri, null /* selection */, null /* selection args */);
if (Log.isLoggable(TAG, Log.DEBUG)) {
Log.d(TAG, "reminder not found, alert cancelled");
}
return;
}
} finally {
if (reminderCursor != null) {
reminderCursor.close();
}
}
}
// If the event time was changed and the event has already ended,
// then don't sound the alarm.
if (alarmTime > instanceEnd) {
// Delete this alarm from the CalendarAlerts table
cr.delete(alertUri, null /* selection */, null /* selection args */);
if (Log.isLoggable(TAG, Log.DEBUG)) {
Log.d(TAG, "event ended, alert cancelled");
}
return;
}
// If minutes > 0, then this is a normal alarm (not a snoozed alarm)
// so check for duplicate alarms. A duplicate alarm can occur when
// the start time of an event is changed to an earlier time. The
// later alarm (that was first scheduled for the later event time)
// should be discarded.
long computedAlarmTime = instanceBegin - minutes * DateUtils.MINUTE_IN_MILLIS;
if (minutes > 0 && computedAlarmTime != alarmTime) {
// If the event time was changed to a later time, then the computed
// alarm time is in the future and we shouldn't sound this alarm.
if (computedAlarmTime > alarmTime) {
// Delete this alarm from the CalendarAlerts table
cr.delete(alertUri, null /* selection */, null /* selection args */);
if (Log.isLoggable(TAG, Log.DEBUG)) {
Log.d(TAG, "event postponed, alert cancelled");
}
return;
}
// Check for another alarm in the CalendarAlerts table that has the
// same event id and the same "minutes". This can occur
// if the event start time was changed to an earlier time and the
// alarm for the later time goes off. To avoid discarding alarms
// for repeating events (that have the same event id), we check
// that the other alarm fired recently (within an hour of this one).
long recently = alarmTime - 60 * DateUtils.MINUTE_IN_MILLIS;
selection = CalendarAlerts.EVENT_ID + "=" + eventId
+ " AND " + CalendarAlerts.TABLE_NAME + "." + CalendarAlerts._ID
+ "!=" + alertId
+ " AND " + CalendarAlerts.MINUTES + "=" + minutes
+ " AND " + CalendarAlerts.ALARM_TIME + ">" + recently
+ " AND " + CalendarAlerts.ALARM_TIME + "<=" + alarmTime;
alertCursor = CalendarAlerts.query(cr, ALERT_PROJECTION_SMALL, selection, null);
if (alertCursor != null) {
try {
if (alertCursor.getCount() > 0) {
// Delete this alarm from the CalendarAlerts table
cr.delete(alertUri, null /* selection */, null /* selection args */);
if (Log.isLoggable(TAG, Log.DEBUG)) {
Log.d(TAG, "duplicate alarm, alert cancelled");
}
return;
}
} finally {
alertCursor.close();
}
}
}
// Find all the alerts that have fired but have not been dismissed
selection = CalendarAlerts.STATE + "=" + CalendarAlerts.FIRED;
alertCursor = CalendarAlerts.query(cr, ALERT_PROJECTION, selection, null);
if (alertCursor == null || alertCursor.getCount() == 0) {
if (Log.isLoggable(TAG, Log.DEBUG)) {
Log.d(TAG, "no fired alarms found");
}
return;
}
int numReminders = alertCursor.getCount();
try {
while (alertCursor.moveToNext()) {
long otherEventId = alertCursor.getLong(ALERT_INDEX_EVENT_ID);
long otherAlertId = alertCursor.getLong(ALERT_INDEX_ID);
int otherAlarmState = alertCursor.getInt(ALERT_INDEX_STATE);
long otherBeginTime = alertCursor.getLong(ALERT_INDEX_BEGIN);
if (otherEventId == eventId && otherAlertId != alertId
&& otherAlarmState == CalendarAlerts.FIRED
&& otherBeginTime == beginTime) {
// This event already has an alert that fired and has not
// been dismissed. This can happen if an event has
// multiple reminders. Do not count this as a separate
// reminder. But we do want to sound the alarm and vibrate
// the phone, if necessary.
if (Log.isLoggable(TAG, Log.DEBUG)) {
Log.d(TAG, "multiple alarms for this event");
}
numReminders -= 1;
}
}
} finally {
alertCursor.close();
}
if (Log.isLoggable(TAG, Log.DEBUG)) {
Log.d(TAG, "creating new alarm notification, numReminders: " + numReminders);
}
Notification notification = AlertReceiver.makeNewAlertNotification(this, eventName,
location, numReminders);
// Generate either a pop-up dialog, status bar notification, or
// neither. Pop-up dialog and status bar notification may include a
// sound, an alert, or both. A status bar notification also includes
// a toast.
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
String reminderType = prefs.getString(CalendarPreferenceActivity.KEY_ALERTS_TYPE,
CalendarPreferenceActivity.ALERT_TYPE_STATUS_BAR);
if (reminderType.equals(CalendarPreferenceActivity.ALERT_TYPE_OFF)) {
if (Log.isLoggable(TAG, Log.DEBUG)) {
Log.d(TAG, "alert preference is OFF");
}
return;
}
NotificationManager nm =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
boolean reminderVibrate =
prefs.getBoolean(CalendarPreferenceActivity.KEY_ALERTS_VIBRATE, false);
String reminderRingtone =
prefs.getString(CalendarPreferenceActivity.KEY_ALERTS_RINGTONE, null);
// Possibly generate a vibration
if (reminderVibrate) {
notification.defaults |= Notification.DEFAULT_VIBRATE;
}
// Possibly generate a sound. If 'Silent' is chosen, the ringtone string will be empty.
notification.sound = TextUtils.isEmpty(reminderRingtone) ? null : Uri
.parse(reminderRingtone);
if (reminderType.equals(CalendarPreferenceActivity.ALERT_TYPE_ALERTS)) {
Intent alertIntent = new Intent();
alertIntent.setClass(this, AlertActivity.class);
alertIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(alertIntent);
} else {
LayoutInflater inflater;
inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = inflater.inflate(R.layout.alert_toast, null);
AlertAdapter.updateView(this, view, eventName, location, beginTime, endTime, allDay);
}
// Record the notify time in the CalendarAlerts table.
// This is used for debugging missed alarms.
ContentValues values = new ContentValues();
long currentTime = System.currentTimeMillis();
values.put(CalendarAlerts.NOTIFY_TIME, currentTime);
cr.update(alertUri, values, null /* where */, null /* args */);
// The notification time should be pretty close to the reminder time
// that the user set for this event. If the notification is late, then
// that's a bug and we should log an error.
if (currentTime > alarmTime + DateUtils.MINUTE_IN_MILLIS) {
long minutesLate = (currentTime - alarmTime) / DateUtils.MINUTE_IN_MILLIS;
int flags = DateUtils.FORMAT_SHOW_YEAR | DateUtils.FORMAT_SHOW_TIME;
String alarmTimeStr = DateUtils.formatDateTime(this, alarmTime, flags);
String currentTimeStr = DateUtils.formatDateTime(this, currentTime, flags);
Log.w(TAG, "Calendar reminder alarm for event id " + eventId
+ " is " + minutesLate + " minute(s) late;"
+ " expected alarm at: " + alarmTimeStr
+ " but got it at: " + currentTimeStr);
}
nm.notify(0, notification);
}
|
diff --git a/src/main/java/org/basex/core/Proc.java b/src/main/java/org/basex/core/Proc.java
index 9753a1799..0dfa9bc7e 100644
--- a/src/main/java/org/basex/core/Proc.java
+++ b/src/main/java/org/basex/core/Proc.java
@@ -1,269 +1,269 @@
package org.basex.core;
import static org.basex.core.Text.*;
import java.io.IOException;
import java.io.OutputStream;
import org.basex.core.Commands.CmdPerm;
import org.basex.data.Data;
import org.basex.data.Result;
import org.basex.io.NullOutput;
import org.basex.io.PrintOutput;
import org.basex.util.Performance;
import org.basex.util.TokenBuilder;
/**
* This class provides the architecture for all internal command
* implementations. It evaluates queries that are sent by the GUI, the client or
* the standalone version.
*
* @author Workgroup DBIS, University of Konstanz 2005-10, ISC License
* @author Christian Gruen
*/
public abstract class Proc extends Progress {
/** Commands flag: standard. */
public static final int STANDARD = 256;
/** Commands flag: data reference needed. */
public static final int DATAREF = 512;
/** Command arguments. */
protected String[] args;
/** Database context. */
protected Context context;
/** Output stream. */
protected PrintOutput out;
/** Database properties. */
protected Prop prop;
/** Container for query information. */
protected TokenBuilder info = new TokenBuilder();
/** Performance measurements. */
protected Performance perf;
/** Temporary query result. */
protected Result result;
/** Flags for controlling process evaluation. */
private final int flags;
/**
* Constructor.
* @param f command flags
* @param a arguments
*/
public Proc(final int f, final String... a) {
flags = f;
args = a;
}
/**
* Executes the process and serializes textual results to the specified output
* stream. If an exception occurs, a {@link BaseXException} is thrown.
* @param ctx database context
* @param os output stream reference
* @throws BaseXException process exception
*/
public void execute(final Context ctx, final OutputStream os)
throws BaseXException {
if(!exec(ctx, os)) throw new BaseXException(info());
}
/**
* Executes the process.
* {@link #execute(Context, OutputStream)} should be called
* to retrieve textual results. If an exception occurs,
* a {@link BaseXException} is thrown.
* @param ctx database context
* @throws BaseXException process exception
*/
public void execute(final Context ctx) throws BaseXException {
if(!exec(ctx)) throw new BaseXException(info());
}
/**
* Executes the process, prints the result to the specified output stream
* and returns a success flag.
* @param ctx database context
* @param os output stream
* @return success flag. The {@link #info()} method returns information
* on a potential exception
*/
public final boolean exec(final Context ctx, final OutputStream os) {
// check if data reference is available
final Data data = ctx.data;
if(data == null && (flags & DATAREF) != 0) return error(PROCNODB);
// check permissions
if(!ctx.perm(flags & 0xFF, data != null ? data.meta : null)) {
final CmdPerm[] perms = CmdPerm.values();
int i = perms.length;
final int f = flags & 0xFF;
while(--i >= 0 && (1 << i & f) == 0);
- return error(PERMNO, perms[i]);
+ return error(PERMNO, perms[i + 1]);
}
// check concurrency of processes
boolean ok = false;
final boolean writing =
(flags & (User.CREATE | User.WRITE)) != 0 || updating(ctx);
ctx.sema.before(writing);
ok = run(ctx, os);
ctx.sema.after(writing);
return ok;
}
/**
* Executes the process and returns a success flag.
* {@link #run(Context, OutputStream)} should be called
* to retrieve textual results.
* @param ctx database context
* @return success flag. The {@link #info()} method returns information
* on a potential exception
*/
public final boolean exec(final Context ctx) {
return exec(ctx, null);
}
/**
* Runs the process without permission, data and concurrency checks.
* @param ctx query context
* @param os output stream
* @return result of check
*/
private boolean run(final Context ctx, final OutputStream os) {
try {
perf = new Performance();
context = ctx;
prop = ctx.prop;
out = os == null ? new NullOutput() : os instanceof PrintOutput ?
(PrintOutput) os : new PrintOutput(os);
return run();
} catch(final ProgressException ex) {
abort();
return error(PROGERR);
} catch(final Throwable ex) {
Performance.gc(2);
Main.debug(ex);
abort();
if(ex instanceof OutOfMemoryError) return error(PROCOUTMEM);
final Object[] st = ex.getStackTrace();
final Object[] obj = new Object[st.length + 1];
obj[0] = ex.toString();
System.arraycopy(st, 0, obj, 1, st.length);
return error(Main.bug(obj));
}
}
/**
* Runs the process without permission, data and concurrency checks.
* @param ctx query context
* @return result of check
*/
public boolean run(final Context ctx) {
return run(ctx, null);
}
/**
* Returns process information or error message.
* @return info string
*/
public final String info() {
return info.toString();
}
/**
* Returns the result set, generated by the last query.
* Must only be called if {@link Prop#CACHEQUERY} is set.
* @return result set
*/
public final Result result() {
return result;
}
/**
* Returns if the process performs updates.
* @param ctx context reference
* @return result of check
*/
@SuppressWarnings("unused")
public boolean updating(final Context ctx) {
return false;
}
// PROTECTED METHODS ========================================================
/**
* Executes the process and serializes the result.
* @return success of operation
* @throws IOException I/O exception
*/
protected abstract boolean run() throws IOException;
/**
* Adds the error message to the message buffer {@link #info}.
* @param msg error message
* @param ext error extension
* @return false
*/
protected final boolean error(final String msg, final Object... ext) {
info.reset();
info.add(msg == null ? "" : msg, ext);
return false;
}
/**
* Adds information on the process execution.
* @param str information to be added
* @param ext extended info
* @return true
*/
protected final boolean info(final String str, final Object... ext) {
if(prop.is(Prop.INFO)) {
info.add(str, ext);
info.add(Prop.NL);
}
return true;
}
/**
* Returns the command option.
* @param typ options enumeration
* @param <E> token type
* @return option
*/
protected final <E extends Enum<E>> E getOption(final Class<E> typ) {
try {
return Enum.valueOf(typ, args[0].toUpperCase());
} catch(final Exception ex) {
error(CMDWHICH, args[0]);
return null;
}
}
/**
* Returns the list of arguments.
* @return arguments
*/
protected final String args() {
final StringBuilder sb = new StringBuilder();
for(final String a : args) {
if(a == null || a.isEmpty()) continue;
sb.append(' ');
final boolean s = a.indexOf(' ') != -1;
if(s) sb.append('"');
sb.append(a);
if(s) sb.append('"');
}
return sb.toString();
}
/**
* Returns a string representation of the process. In the client/server
* architecture, this string is sent to and reparsed by the server.
* @return string representation
*/
@Override
public String toString() {
return Main.name(this).toUpperCase() + args();
}
}
| true | true | public final boolean exec(final Context ctx, final OutputStream os) {
// check if data reference is available
final Data data = ctx.data;
if(data == null && (flags & DATAREF) != 0) return error(PROCNODB);
// check permissions
if(!ctx.perm(flags & 0xFF, data != null ? data.meta : null)) {
final CmdPerm[] perms = CmdPerm.values();
int i = perms.length;
final int f = flags & 0xFF;
while(--i >= 0 && (1 << i & f) == 0);
return error(PERMNO, perms[i]);
}
// check concurrency of processes
boolean ok = false;
final boolean writing =
(flags & (User.CREATE | User.WRITE)) != 0 || updating(ctx);
ctx.sema.before(writing);
ok = run(ctx, os);
ctx.sema.after(writing);
return ok;
}
| public final boolean exec(final Context ctx, final OutputStream os) {
// check if data reference is available
final Data data = ctx.data;
if(data == null && (flags & DATAREF) != 0) return error(PROCNODB);
// check permissions
if(!ctx.perm(flags & 0xFF, data != null ? data.meta : null)) {
final CmdPerm[] perms = CmdPerm.values();
int i = perms.length;
final int f = flags & 0xFF;
while(--i >= 0 && (1 << i & f) == 0);
return error(PERMNO, perms[i + 1]);
}
// check concurrency of processes
boolean ok = false;
final boolean writing =
(flags & (User.CREATE | User.WRITE)) != 0 || updating(ctx);
ctx.sema.before(writing);
ok = run(ctx, os);
ctx.sema.after(writing);
return ok;
}
|
diff --git a/jarjar/src/main/com/tonicsystems/jarjar/util/ClassHeaderReader.java b/jarjar/src/main/com/tonicsystems/jarjar/util/ClassHeaderReader.java
index 8a051c8..d3de71c 100644
--- a/jarjar/src/main/com/tonicsystems/jarjar/util/ClassHeaderReader.java
+++ b/jarjar/src/main/com/tonicsystems/jarjar/util/ClassHeaderReader.java
@@ -1,128 +1,129 @@
/*
Jar Jar Links - A utility to repackage and embed Java libraries
Copyright (C) 2004 Tonic Systems, Inc.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; see the file COPYING. if not, write to
the Free Software Foundation, Inc., 59 Temple Place, Suite 330,
Boston, MA 02111-1307 USA
*/
package com.tonicsystems.jarjar.util;
import java.io.*;
import java.util.*;
public class ClassHeaderReader
{
private int access;
private String thisClass;
private String superClass;
private String[] interfaces;
public int getAccess() {
return access;
}
public String getClassName() {
return thisClass;
}
public String getSuperName() {
return superClass;
}
public String[] getInterfaces() {
return interfaces;
}
public ClassHeaderReader(InputStream in) throws IOException {
try {
DataInputStream data = new DataInputStream(in);
int magic = data.readInt();
int minorVersion = data.readUnsignedShort();
int majorVersion = data.readUnsignedShort();
if (magic != 0xCAFEBABE)
throw new IOException("Bad magic number");
// TODO: check version
int constant_pool_count = data.readUnsignedShort();
Map items = new TreeMap();
for (int i = 1; i < constant_pool_count; i++) {
int tag = data.readUnsignedByte();
switch (tag) {
case 9: // Fieldref
case 10: // Methodref
case 11: // InterfaceMethodref
case 3: // Integer
case 4: // Float
case 12: // NameAndType
skipFully(data, 4);
break;
case 5: // Long
case 6: // Double
skipFully(data, 8);
i++;
break;
case 1: // Utf8
items.put(new Integer(i), data.readUTF());
break;
case 7: // Class
items.put(new Integer(i), new Integer(data.readUnsignedShort()));
break;
case 8: // String
skipFully(data, 2);
break;
default:
throw new IllegalStateException("Unknown constant pool tag " + tag);
}
}
access = data.readUnsignedShort();
thisClass = readClass(data.readUnsignedShort(), items);
- superClass = readClass(data.readUnsignedShort(), items);
+ int superclassIndex = data.readUnsignedShort();
+ superClass = (superclassIndex == 0) ? null : readClass(superclassIndex, items);
int interfaces_count = data.readUnsignedShort();
interfaces = new String[interfaces_count];
for (int i = 0; i < interfaces_count; i++) {
interfaces[i] = readClass(data.readUnsignedShort(), items);
}
} finally {
in.close();
}
}
private static String readClass(int index, Map items) {
if (items.get(new Integer(index)) == null) {
throw new IllegalArgumentException("cannot find index " + index + " in " + items);
}
return readString(((Integer)items.get(new Integer(index))).intValue(), items);
}
private static String readString(int index, Map items) {
return (String)items.get(new Integer(index));
}
private static void skipFully(DataInput data, int n) throws IOException {
while (n > 0) {
int amt = data.skipBytes(n);
if (amt == 0) {
data.readByte();
n--;
} else {
n -= amt;
}
}
}
}
| true | true | public ClassHeaderReader(InputStream in) throws IOException {
try {
DataInputStream data = new DataInputStream(in);
int magic = data.readInt();
int minorVersion = data.readUnsignedShort();
int majorVersion = data.readUnsignedShort();
if (magic != 0xCAFEBABE)
throw new IOException("Bad magic number");
// TODO: check version
int constant_pool_count = data.readUnsignedShort();
Map items = new TreeMap();
for (int i = 1; i < constant_pool_count; i++) {
int tag = data.readUnsignedByte();
switch (tag) {
case 9: // Fieldref
case 10: // Methodref
case 11: // InterfaceMethodref
case 3: // Integer
case 4: // Float
case 12: // NameAndType
skipFully(data, 4);
break;
case 5: // Long
case 6: // Double
skipFully(data, 8);
i++;
break;
case 1: // Utf8
items.put(new Integer(i), data.readUTF());
break;
case 7: // Class
items.put(new Integer(i), new Integer(data.readUnsignedShort()));
break;
case 8: // String
skipFully(data, 2);
break;
default:
throw new IllegalStateException("Unknown constant pool tag " + tag);
}
}
access = data.readUnsignedShort();
thisClass = readClass(data.readUnsignedShort(), items);
superClass = readClass(data.readUnsignedShort(), items);
int interfaces_count = data.readUnsignedShort();
interfaces = new String[interfaces_count];
for (int i = 0; i < interfaces_count; i++) {
interfaces[i] = readClass(data.readUnsignedShort(), items);
}
} finally {
in.close();
}
}
| public ClassHeaderReader(InputStream in) throws IOException {
try {
DataInputStream data = new DataInputStream(in);
int magic = data.readInt();
int minorVersion = data.readUnsignedShort();
int majorVersion = data.readUnsignedShort();
if (magic != 0xCAFEBABE)
throw new IOException("Bad magic number");
// TODO: check version
int constant_pool_count = data.readUnsignedShort();
Map items = new TreeMap();
for (int i = 1; i < constant_pool_count; i++) {
int tag = data.readUnsignedByte();
switch (tag) {
case 9: // Fieldref
case 10: // Methodref
case 11: // InterfaceMethodref
case 3: // Integer
case 4: // Float
case 12: // NameAndType
skipFully(data, 4);
break;
case 5: // Long
case 6: // Double
skipFully(data, 8);
i++;
break;
case 1: // Utf8
items.put(new Integer(i), data.readUTF());
break;
case 7: // Class
items.put(new Integer(i), new Integer(data.readUnsignedShort()));
break;
case 8: // String
skipFully(data, 2);
break;
default:
throw new IllegalStateException("Unknown constant pool tag " + tag);
}
}
access = data.readUnsignedShort();
thisClass = readClass(data.readUnsignedShort(), items);
int superclassIndex = data.readUnsignedShort();
superClass = (superclassIndex == 0) ? null : readClass(superclassIndex, items);
int interfaces_count = data.readUnsignedShort();
interfaces = new String[interfaces_count];
for (int i = 0; i < interfaces_count; i++) {
interfaces[i] = readClass(data.readUnsignedShort(), items);
}
} finally {
in.close();
}
}
|
diff --git a/src/main/java/org/waarp/openr66/protocol/utils/FileUtils.java b/src/main/java/org/waarp/openr66/protocol/utils/FileUtils.java
index 17102a78..e57fcf72 100644
--- a/src/main/java/org/waarp/openr66/protocol/utils/FileUtils.java
+++ b/src/main/java/org/waarp/openr66/protocol/utils/FileUtils.java
@@ -1,634 +1,634 @@
/**
* This file is part of Waarp Project.
*
* Copyright 2009, Frederic Bregier, and individual contributors by the @author tags. See the
* COPYRIGHT.txt in the distribution for a full listing of individual contributors.
*
* All Waarp Project is free software: you can redistribute it and/or modify it under the terms of
* the GNU General Public License as published by the Free Software Foundation, either version 3 of
* the License, or (at your option) any later version.
*
* Waarp is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even
* the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
* Public License for more details.
*
* You should have received a copy of the GNU General Public License along with Waarp . If not, see
* <http://www.gnu.org/licenses/>.
*/
package org.waarp.openr66.protocol.utils;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FilenameFilter;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.nio.channels.FileChannel;
import org.jboss.netty.buffer.ChannelBuffer;
import org.jboss.netty.buffer.ChannelBuffers;
import org.waarp.common.command.exception.CommandAbstractException;
import org.waarp.common.digest.FilesystemBasedDigest;
import org.waarp.common.digest.FilesystemBasedDigest.DigestAlgo;
import org.waarp.common.file.filesystembased.FilesystemBasedFileParameterImpl;
import org.waarp.common.logging.WaarpInternalLogger;
import org.waarp.common.utility.DetectionUtils;
import org.waarp.common.utility.WaarpStringUtils;
import org.waarp.openr66.context.R66Session;
import org.waarp.openr66.context.filesystem.R66Dir;
import org.waarp.openr66.context.filesystem.R66File;
import org.waarp.openr66.context.task.exception.OpenR66RunnerErrorException;
import org.waarp.openr66.protocol.configuration.Configuration;
import org.waarp.openr66.protocol.exception.OpenR66ProtocolSystemException;
/**
* File Utils
*
* @author Frederic Bregier
*
*/
public class FileUtils {
/**
* Copy one file to another one
*
* @param from
* @param to
* @param move
* True if the copy is in fact a move operation
* @param append
* True if the copy is in append
* @throws OpenR66ProtocolSystemException
*/
public static void copy(File from, File to, boolean move, boolean append)
throws OpenR66ProtocolSystemException {
if (from == null || to == null) {
throw new OpenR66ProtocolSystemException(
"Source or Destination is null");
}
File directoryTo = to.getParentFile();
if (createDir(directoryTo)) {
if (move && from.renameTo(to)) {
return;
}
FileChannel fileChannelIn = getFileChannel(from, false, false);
if (fileChannelIn == null) {
throw new OpenR66ProtocolSystemException(
"Cannot read source file");
// return false;
}
FileChannel fileChannelOut = getFileChannel(to, true, append);
if (fileChannelOut == null) {
try {
fileChannelIn.close();
} catch (IOException e) {
}
throw new OpenR66ProtocolSystemException(
"Cannot write destination file");
}
if (write(fileChannelIn, fileChannelOut) > 0) {
if (move) {
// do not test the delete
from.delete();
}
return;
}
throw new OpenR66ProtocolSystemException("Cannot copy");
}
throw new OpenR66ProtocolSystemException(
"Cannot access to parent dir of destination");
}
/**
* Copy a group of files to a directory
*
* @param from
* @param directoryTo
* @param move
* True if the copy is in fact a move operation
* @return the group of copy files or null (partially or totally) if an error occurs
* @throws OpenR66ProtocolSystemException
*/
public static File[] copy(File[] from, File directoryTo, boolean move)
throws OpenR66ProtocolSystemException {
if (from == null || directoryTo == null) {
return null;
}
File[] to = null;
if (createDir(directoryTo)) {
to = new File[from.length];
for (int i = 0; i < from.length; i++) {
try {
to[i] = copyToDir(from[i], directoryTo, move);
} catch (OpenR66ProtocolSystemException e) {
throw e;
}
}
}
return to;
}
/**
* Copy one file to a directory
*
* @param from
* @param directoryTo
* @param move
* True if the copy is in fact a move operation
* @return The copied file or null if an error occurs
* @throws OpenR66ProtocolSystemException
*/
public static File copyToDir(File from, File directoryTo, boolean move)
throws OpenR66ProtocolSystemException {
if (from == null || directoryTo == null) {
throw new OpenR66ProtocolSystemException(
"Source or Destination is null");
}
if (createDir(directoryTo)) {
File to = new File(directoryTo, from.getName());
if (move && from.renameTo(to)) {
return to;
}
FileChannel fileChannelIn = getFileChannel(from, false, false);
if (fileChannelIn == null) {
throw new OpenR66ProtocolSystemException(
"Cannot read source file");
}
FileChannel fileChannelOut = getFileChannel(to, true, false);
if (fileChannelOut == null) {
try {
fileChannelIn.close();
} catch (IOException e) {
}
throw new OpenR66ProtocolSystemException(
"Cannot write destination file");
}
if (write(fileChannelIn, fileChannelOut) > 0) {
if (move) {
// do not test the delete
from.delete();
}
return to;
}
throw new OpenR66ProtocolSystemException(
"Cannot write destination file");
}
throw new OpenR66ProtocolSystemException(
"Cannot access to parent dir of destination");
}
/**
* Create the directory associated with the File as path
*
* @param directory
* @return True if created, False else.
*/
public final static boolean createDir(File directory) {
if (directory == null) {
return false;
}
if (directory.isDirectory()) {
return true;
}
return directory.mkdirs();
}
/**
* Delete physically the file
*
* @param file
* @return True if OK, else if not (or if the file never exists).
*/
public final static boolean delete(File file) {
if (!file.exists()) {
return true;
}
return file.delete();
}
/**
* Delete the directory associated with the File as path if empty
*
* @param directory
* @return True if deleted, False else.
*/
public final static boolean deleteDir(File directory) {
if (directory == null) {
return true;
}
if (!directory.exists()) {
return true;
}
if (!directory.isDirectory()) {
return false;
}
return directory.delete();
}
/**
* Delete physically the file but when the JVM exits (useful for temporary file)
*
* @param file
*/
public final static void deleteOnExit(File file) {
if (!file.exists()) {
return;
}
file.deleteOnExit();
}
/**
* Delete the directory and its subdirs associated with the File as path if empty
*
* @param directory
* @return True if deleted, False else.
*/
public static boolean deleteRecursiveDir(File directory) {
if (directory == null) {
return true;
}
boolean retour = true;
if (!directory.exists()) {
return true;
}
if (!directory.isDirectory()) {
return false;
}
File[] list = directory.listFiles();
if (list == null || list.length == 0) {
list = null;
retour = directory.delete();
return retour;
}
int len = list.length;
for (int i = 0; i < len; i++) {
if (list[i].isDirectory()) {
if (!deleteRecursiveFileDir(list[i])) {
retour = false;
}
} else {
retour = false;
}
}
list = null;
if (retour) {
retour = directory.delete();
}
return retour;
}
/**
* Delete the directory and its subdirs associated with the File dir if empty
*
* @param dir
* @return True if deleted, False else.
*/
private static boolean deleteRecursiveFileDir(File dir) {
if (dir == null) {
return true;
}
boolean retour = true;
if (!dir.exists()) {
return true;
}
File[] list = dir.listFiles();
if (list == null || list.length == 0) {
list = null;
return dir.delete();
}
int len = list.length;
for (int i = 0; i < len; i++) {
if (list[i].isDirectory()) {
if (!deleteRecursiveFileDir(list[i])) {
retour = false;
}
} else {
retour = false;
list = null;
return retour;
}
}
list = null;
if (retour) {
retour = dir.delete();
}
return retour;
}
/**
* Change or create the R66File associated with the context
* @param logger
* @param session
* @param filenameSrc new filename
* @param isPreStart
* @param isSender
* @param isThrough
* @param file old R66File if any (might be null)
* @return the R66File
* @throws OpenR66RunnerErrorException
*/
public final static R66File getFile(WaarpInternalLogger logger, R66Session session, String filenameSrc,
boolean isPreStart, boolean isSender, boolean isThrough, R66File file) throws OpenR66RunnerErrorException {
String filename;
logger.debug("PreStart: "+isPreStart);
logger.debug("Dir is: "+session.getDir().getFullPath());
logger.debug("File is: "+filenameSrc);
if (isPreStart) {
filename = R66Dir.normalizePath(filenameSrc);
if (filename.startsWith("file:/")) {
if (DetectionUtils.isWindows()) {
filename = filename.substring("file:/".length());
} else {
filename = filename.substring("file:".length());
}
try {
filename = URLDecoder.decode(filename, WaarpStringUtils.UTF8.name());
} catch (UnsupportedEncodingException e) {
- throw new OpenR66RunnerErrorException("File cannot be read: " +
+ logger.warn("Filename convertion to UTF8 cannot be read: " +
filename);
}
}
logger.debug("File becomes: "+filename);
} else {
filename = filenameSrc;
}
if (isSender) {
try {
if (file == null) {
try {
file = (R66File) session.getDir().setFile(filename, false);
} catch (CommandAbstractException e) {
logger.warn("File not placed in normal directory", e);
// file is not under normal base directory, so is external
// File should already exist but can be using special code ('*?')
file = session.getDir().setFileNoCheck(filename);
}
}
if (isThrough) {
// no test on file since it does not really exist
logger.debug("File is in through mode: {}", file);
} else if (!file.canRead()) {
// file is not under normal base directory, so is external
// File should already exist but cannot use special code ('*?')
file = new R66File(session, session.getDir(), filename);
if (!file.canRead()) {
throw new OpenR66RunnerErrorException("File cannot be read: " +
file.getTrueFile().getAbsolutePath());
}
}
} catch (CommandAbstractException e) {
throw new OpenR66RunnerErrorException(e);
}
} else {
// not sender so file is just registered as is but no test of existence
file = new R66File(session, session.getDir(), filename);
}
return file;
}
/**
* @param _FileName
* @param _Path
* @return true if the file exist in the specified path
*/
public final static boolean fileExist(String _FileName, String _Path) {
boolean exist = false;
String fileString = _Path + File.separator + _FileName;
File file = new File(fileString);
if (file.exists()) {
exist = true;
}
return exist;
}
/**
* Returns the FileChannel in Out MODE (if isOut is True) or in In MODE (if isOut is False)
* associated with the file. In out MODE, it can be in append MODE.
*
* @param isOut
* @param append
* @return the FileChannel (OUT or IN)
* @throws OpenR66ProtocolSystemException
*/
private static FileChannel getFileChannel(File file, boolean isOut,
boolean append) throws OpenR66ProtocolSystemException {
FileChannel fileChannel = null;
try {
if (isOut) {
@SuppressWarnings("resource")
FileOutputStream fileOutputStream = new FileOutputStream(file
.getPath(), append);
fileChannel = fileOutputStream.getChannel();
if (append) {
// Bug in JVM since it does not respect the API (position
// should be set as length)
try {
fileChannel.position(file.length());
} catch (IOException e) {
}
}
} else {
if (!file.exists()) {
throw new OpenR66ProtocolSystemException(
"File does not exist");
}
@SuppressWarnings("resource")
FileInputStream fileInputStream = new FileInputStream(file
.getPath());
fileChannel = fileInputStream.getChannel();
}
} catch (FileNotFoundException e) {
throw new OpenR66ProtocolSystemException("File not found", e);
}
return fileChannel;
}
/**
* Get the list of files from a given directory
*
* @param directory
* @return the list of files (as an array)
*/
public final static File[] getFiles(File directory) {
if (directory == null || !directory.isDirectory()) {
return null;
}
return directory.listFiles();
}
/**
* Get the list of files from a given directory and a filter
*
* @param directory
* @param filter
* @return the list of files (as an array)
*/
public final static File[] getFiles(File directory, FilenameFilter filter) {
if (directory == null || !directory.isDirectory()) {
return null;
}
return directory.listFiles(filter);
}
/**
* Calculates and returns the hash of the contents of the given file.
*
* @param f
* FileInterface to hash
* @return the hash from the given file
* @throws OpenR66ProtocolSystemException
**/
public final static String getHash(File f) throws OpenR66ProtocolSystemException {
try {
return FilesystemBasedDigest.getHex(FilesystemBasedDigest.getHash(f,
FilesystemBasedFileParameterImpl.useNio, Configuration.configuration.digest));
} catch (IOException e) {
throw new OpenR66ProtocolSystemException(e);
}
}
/**
*
* @param buffer
* @return the hash from the given Buffer
*/
public final static ChannelBuffer getHash(ChannelBuffer buffer, DigestAlgo algo) {
byte[] newkey;
try {
newkey = FilesystemBasedDigest.getHash(buffer, algo);
} catch (IOException e) {
return ChannelBuffers.EMPTY_BUFFER;
}
return ChannelBuffers.wrappedBuffer(newkey);
}
/**
* Compute global hash (if possible)
* @param digest
* @param buffer
*/
public static void computeGlobalHash(FilesystemBasedDigest digest, ChannelBuffer buffer) {
if (digest == null) {
return;
}
byte[] bytes = null;
int start = 0;
int length = buffer.readableBytes();
if (buffer.hasArray()) {
start = buffer.arrayOffset();
bytes = buffer.array();
if (bytes.length > start + length) {
byte[] temp = new byte[length];
System.arraycopy(bytes, start, temp, 0, length);
start = 0;
bytes = temp;
}
} else {
bytes = new byte[length];
buffer.getBytes(buffer.readerIndex(), bytes);
}
digest.Update(bytes, start, length);
}
/**
* Compute global hash (if possible) from a file but up to length
* @param digest
* @param file
* @param length
*/
public static void computeGlobalHash(FilesystemBasedDigest digest, File file, int length) {
if (digest == null) {
return;
}
byte[] bytes = new byte[65536];
int still = length;
int len = still > 65536 ? 65536 : still;
FileInputStream inputStream = null;
try {
inputStream = new FileInputStream(file);
while (inputStream.read(bytes, 0, len) > 0) {
digest.Update(bytes, 0, len);
still -= length;
if (still <= 0) {
break;
}
len = still > 65536 ? 65536 : still;
}
} catch (FileNotFoundException e) {
// error
} catch (IOException e) {
// error
} finally {
if (inputStream != null) {
try {
inputStream.close();
} catch (IOException e) {
}
}
}
}
/**
* Write one fileChannel to another one. Close the fileChannels
*
* @param fileChannelIn
* source of file
* @param fileChannelOut
* destination of file
* @return The size of copy if is OK
* @throws AtlasIoException
*/
private static long write(FileChannel fileChannelIn,
FileChannel fileChannelOut) throws OpenR66ProtocolSystemException {
if (fileChannelIn == null) {
if (fileChannelOut != null) {
try {
fileChannelOut.close();
} catch (IOException e) {
}
}
throw new OpenR66ProtocolSystemException("FileChannelIn is null");
}
if (fileChannelOut == null) {
try {
fileChannelIn.close();
} catch (IOException e) {
}
throw new OpenR66ProtocolSystemException("FileChannelOut is null");
}
long size = 0;
long transfert = 0;
try {
transfert = fileChannelOut.position();
size = fileChannelIn.size();
int chunkSize = 8192;
while (transfert < size) {
if (chunkSize < size - transfert) {
chunkSize = (int) (size - transfert);
}
transfert += fileChannelOut.transferFrom(fileChannelIn, transfert, chunkSize);
}
} catch (IOException e) {
try {
fileChannelOut.close();
fileChannelIn.close();
} catch (IOException e1) {
}
throw new OpenR66ProtocolSystemException(
"An error during copy occurs", e);
}
try {
fileChannelOut.close();
fileChannelIn.close();
} catch (IOException e) {// Close error can be ignored
}
boolean retour = size == transfert;
if (!retour) {
throw new OpenR66ProtocolSystemException("Copy is not complete: " +
transfert + " bytes instead of " + size + " original bytes");
}
return size;
}
}
| true | true | public final static R66File getFile(WaarpInternalLogger logger, R66Session session, String filenameSrc,
boolean isPreStart, boolean isSender, boolean isThrough, R66File file) throws OpenR66RunnerErrorException {
String filename;
logger.debug("PreStart: "+isPreStart);
logger.debug("Dir is: "+session.getDir().getFullPath());
logger.debug("File is: "+filenameSrc);
if (isPreStart) {
filename = R66Dir.normalizePath(filenameSrc);
if (filename.startsWith("file:/")) {
if (DetectionUtils.isWindows()) {
filename = filename.substring("file:/".length());
} else {
filename = filename.substring("file:".length());
}
try {
filename = URLDecoder.decode(filename, WaarpStringUtils.UTF8.name());
} catch (UnsupportedEncodingException e) {
throw new OpenR66RunnerErrorException("File cannot be read: " +
filename);
}
}
logger.debug("File becomes: "+filename);
} else {
filename = filenameSrc;
}
if (isSender) {
try {
if (file == null) {
try {
file = (R66File) session.getDir().setFile(filename, false);
} catch (CommandAbstractException e) {
logger.warn("File not placed in normal directory", e);
// file is not under normal base directory, so is external
// File should already exist but can be using special code ('*?')
file = session.getDir().setFileNoCheck(filename);
}
}
if (isThrough) {
// no test on file since it does not really exist
logger.debug("File is in through mode: {}", file);
} else if (!file.canRead()) {
// file is not under normal base directory, so is external
// File should already exist but cannot use special code ('*?')
file = new R66File(session, session.getDir(), filename);
if (!file.canRead()) {
throw new OpenR66RunnerErrorException("File cannot be read: " +
file.getTrueFile().getAbsolutePath());
}
}
} catch (CommandAbstractException e) {
throw new OpenR66RunnerErrorException(e);
}
} else {
// not sender so file is just registered as is but no test of existence
file = new R66File(session, session.getDir(), filename);
}
return file;
}
| public final static R66File getFile(WaarpInternalLogger logger, R66Session session, String filenameSrc,
boolean isPreStart, boolean isSender, boolean isThrough, R66File file) throws OpenR66RunnerErrorException {
String filename;
logger.debug("PreStart: "+isPreStart);
logger.debug("Dir is: "+session.getDir().getFullPath());
logger.debug("File is: "+filenameSrc);
if (isPreStart) {
filename = R66Dir.normalizePath(filenameSrc);
if (filename.startsWith("file:/")) {
if (DetectionUtils.isWindows()) {
filename = filename.substring("file:/".length());
} else {
filename = filename.substring("file:".length());
}
try {
filename = URLDecoder.decode(filename, WaarpStringUtils.UTF8.name());
} catch (UnsupportedEncodingException e) {
logger.warn("Filename convertion to UTF8 cannot be read: " +
filename);
}
}
logger.debug("File becomes: "+filename);
} else {
filename = filenameSrc;
}
if (isSender) {
try {
if (file == null) {
try {
file = (R66File) session.getDir().setFile(filename, false);
} catch (CommandAbstractException e) {
logger.warn("File not placed in normal directory", e);
// file is not under normal base directory, so is external
// File should already exist but can be using special code ('*?')
file = session.getDir().setFileNoCheck(filename);
}
}
if (isThrough) {
// no test on file since it does not really exist
logger.debug("File is in through mode: {}", file);
} else if (!file.canRead()) {
// file is not under normal base directory, so is external
// File should already exist but cannot use special code ('*?')
file = new R66File(session, session.getDir(), filename);
if (!file.canRead()) {
throw new OpenR66RunnerErrorException("File cannot be read: " +
file.getTrueFile().getAbsolutePath());
}
}
} catch (CommandAbstractException e) {
throw new OpenR66RunnerErrorException(e);
}
} else {
// not sender so file is just registered as is but no test of existence
file = new R66File(session, session.getDir(), filename);
}
return file;
}
|
diff --git a/JMapMatchingGUI/src/org/life/sl/mapmatching/EdgeStatistics.java b/JMapMatchingGUI/src/org/life/sl/mapmatching/EdgeStatistics.java
index 3b4eef3..f2c99b8 100644
--- a/JMapMatchingGUI/src/org/life/sl/mapmatching/EdgeStatistics.java
+++ b/JMapMatchingGUI/src/org/life/sl/mapmatching/EdgeStatistics.java
@@ -1,130 +1,130 @@
package org.life.sl.mapmatching;
/*
JMapMatcher
Copyright (c) 2011 Bernhard Barkow, Hans Skov-Petersen, Bernhard Snizek and Contributors
mail: [email protected]
web: http://www.bikeability.dk
This program is free software; you can redistribute it and/or modify it under
the terms of the GNU General Public License as published by the Free Software
Foundation; either version 3 of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License along with
this program; if not, see <http://www.gnu.org/licenses/>.
*/
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import org.life.sl.routefinder.RouteFinder;
import com.vividsolutions.jts.geom.Point;
import com.vividsolutions.jts.operation.linemerge.LineMergeEdge;
import com.vividsolutions.jts.planargraph.Edge;
/**
* EdgeStatistics is a statistics of how many points are associated with each edge
* @author Bernhard Barkow
* @author Bernhard Snizek
*/
public class EdgeStatistics {
double distPEAvg, distPE5, distPE95; ///> average distance between points an associated edges, plus 5% qantiles
HashMap<Edge, Integer> edgePoints = new HashMap<Edge, Integer>(); ///> container counting the number of points associated with each edge
private double pointEdgeDist[] = null;
/**
* default constructor
*/
public EdgeStatistics() {
// TODO Auto-generated constructor stub
}
/**
* constructer which initializes the EdgeStatistics with a network and a set of GPS points
* @param rf RouteFinder which contains the routes (edge network)
* @param gpsPoints array of GPS points for which the statistics is created (measure how well the points fit to edges)
*/
public EdgeStatistics(RouteFinder rf, ArrayList<Point> gpsPoints) {
init(rf, gpsPoints);
}
/**
* initialize the EdgeStatistics with a network and a set of GPS points
* @param rf RouteFinder which contains the routes (edge network)
* @param gpsPoints array of GPS points for which the statistics is created (measure how well the points fit to edges)
*/
public void init(RouteFinder rf, ArrayList<Point> gpsPoints) {
pointEdgeDist = new double[gpsPoints.size()];
rf.setEdgeStatistics(this);
// first, clear the statistics:
edgePoints.clear();
// then, loop over all GPS points:
int i = 0;
for (Point p : gpsPoints) {
Edge e = rf.getNearestEdge(p);
addPoint(e); // add the point to the associated edge (the edge nearest to each GPS data point)
- if (e!=null) pointEdgeDist[i++] = p.distance(((LineMergeEdge)e).getLine().getBoundary()); // distance between point and nearest edge
+ if (e!=null) pointEdgeDist[i++] = p.distance(((LineMergeEdge)e).getLine()); // distance between point and nearest edge
}
initPEDistStat();
}
public void initPEDistStat() {
Arrays.sort(pointEdgeDist);
distPEAvg = 0;
for (double d : pointEdgeDist) {
distPEAvg += d;
}
double l = (double)pointEdgeDist.length;
distPEAvg /= l;
distPE5 = pointEdgeDist[(int)Math.round(l*0.05)];
distPE95 = pointEdgeDist[(int)Math.round(l*0.95)];
}
public double getDistPEAvg() {
return distPEAvg;
}
public double getDistPE5() {
return distPE5;
}
public double getDistPE95() {
return distPE95;
}
/**
* add a new edge to the statistics table and initialize its counter with 0
* @param e the edge to add
*/
public void addEdge(Edge e) {
edgePoints.put(e, 0);
}
/**
* add a point to an associated edge;
* if the edge is not contained in the statistics yet, it is initialized
* @param e
*/
public void addPoint(Edge e) {
if (e != null) {
if (!edgePoints.containsKey(e)) edgePoints.put(e, 1);
else edgePoints.put(e, edgePoints.get(e) + 1);
}
}
/**
* @param e the edge whose number of associated points is requested
* @return the edge/point-count (the number of points associated with an edge); if the edge does not yet exist in the statistics, 0 is returned
*/
public int getCount(Edge e) {
return (edgePoints.containsKey(e) ? edgePoints.get(e) : 0 );
}
}
| true | true | public void init(RouteFinder rf, ArrayList<Point> gpsPoints) {
pointEdgeDist = new double[gpsPoints.size()];
rf.setEdgeStatistics(this);
// first, clear the statistics:
edgePoints.clear();
// then, loop over all GPS points:
int i = 0;
for (Point p : gpsPoints) {
Edge e = rf.getNearestEdge(p);
addPoint(e); // add the point to the associated edge (the edge nearest to each GPS data point)
if (e!=null) pointEdgeDist[i++] = p.distance(((LineMergeEdge)e).getLine().getBoundary()); // distance between point and nearest edge
}
initPEDistStat();
}
| public void init(RouteFinder rf, ArrayList<Point> gpsPoints) {
pointEdgeDist = new double[gpsPoints.size()];
rf.setEdgeStatistics(this);
// first, clear the statistics:
edgePoints.clear();
// then, loop over all GPS points:
int i = 0;
for (Point p : gpsPoints) {
Edge e = rf.getNearestEdge(p);
addPoint(e); // add the point to the associated edge (the edge nearest to each GPS data point)
if (e!=null) pointEdgeDist[i++] = p.distance(((LineMergeEdge)e).getLine()); // distance between point and nearest edge
}
initPEDistStat();
}
|
diff --git a/taskwarrior-androidapp/src/org/svij/taskwarriorapp/db/TaskBaseAdapter.java b/taskwarrior-androidapp/src/org/svij/taskwarriorapp/db/TaskBaseAdapter.java
index bc43497..0a1630d 100644
--- a/taskwarrior-androidapp/src/org/svij/taskwarriorapp/db/TaskBaseAdapter.java
+++ b/taskwarrior-androidapp/src/org/svij/taskwarriorapp/db/TaskBaseAdapter.java
@@ -1,207 +1,210 @@
/**
* taskwarrior for android – a task list manager
*
* Copyright (c) 2012 Sujeevan Vijayakumaran
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, * subject to the following conditions:
* The above copyright notice and this permission notice shall be included in
* allcopies or substantial portions of the Software.
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
* http://www.opensource.org/licenses/mit-license.php
*
*/
package org.svij.taskwarriorapp.db;
import java.text.DateFormat;
import java.util.ArrayList;
import org.svij.taskwarriorapp.R;
import org.svij.taskwarriorapp.data.Task;
import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
public class TaskBaseAdapter extends BaseAdapter {
private ArrayList<Task> entries;
private Activity activity;
private static final int TYPE_ROW = 0;
private static final int TYPE_ROW_CLICKED = 1;
private static final int TYPE_MAX_COUNT = TYPE_ROW_CLICKED + 1;
private ArrayList<Integer> RowClickedList = new ArrayList<Integer>();
private Context context;
public TaskBaseAdapter(Activity a, int layoutID, ArrayList<Task> entries,
Context context) {
super();
this.entries = entries;
this.activity = a;
this.context = context;
}
public static class ViewHolder {
public TextView taskDescription;
public TextView taskProject;
public TextView taskDueDate;
public TextView taskPriority;
public TextView taskStatus;
public TextView taskUrgency;
public RelativeLayout taskRelLayout;
public FrameLayout taskFramelayout;
public View taskPriorityView;
}
public void changeTaskRow(final int position) {
if (RowClickedList.contains(position)) {
RowClickedList.remove(Integer.valueOf(position));
} else {
RowClickedList.add(position);
}
notifyDataSetChanged();
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
ViewHolder holder;
if (v == null) {
LayoutInflater vi = (LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
int type = getItemViewType(position);
switch (type) {
case TYPE_ROW:
v = vi.inflate(R.layout.task_row, null);
break;
case TYPE_ROW_CLICKED:
v = vi.inflate(R.layout.task_row_clicked, null);
}
holder = new ViewHolder();
holder.taskDescription = (TextView) v
.findViewById(R.id.tvRowTaskDescription);
holder.taskProject = (TextView) v
.findViewById(R.id.tvRowTaskProject);
holder.taskDueDate = (TextView) v
.findViewById(R.id.tvRowTaskDueDate);
holder.taskRelLayout = (RelativeLayout) v
.findViewById(R.id.taskRelLayout);
holder.taskPriorityView = (View) v
.findViewById(R.id.horizontal_line_priority);
v.setTag(holder);
} else {
holder = (ViewHolder) v.getTag();
}
final Task task = entries.get(position);
if (task != null) {
holder.taskDescription.setText(task.getDescription());
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
String textAppearance = prefs.getString("pref_appearance_descriptionTextSize", context.getResources().getString(R.string.pref_appearance_descriptionTextSize_small));
if (textAppearance.equals(context.getResources().getString(R.string.pref_appearance_descriptionTextSize_small))) {
holder.taskDescription.setTextSize(context.getResources().getDimension(R.dimen.taskDescription_small));
} else if (textAppearance.equals(context.getResources().getString(R.string.pref_appearance_descriptionTextSize_medium))) {
holder.taskDescription.setTextSize(context.getResources().getDimension(R.dimen.taskDescription_medium));
} else {
holder.taskDescription.setTextSize(context.getResources().getDimension(R.dimen.taskDescription_large));
}
- holder.taskProject.setText(task.getProject());
+ if(task.getProject() != null) {
+ holder.taskProject.setText(task.getProject());
+ } else {
+ holder.taskProject.setVisibility(View.GONE);
+ }
if (task.getDue() != null && !(task.getDue().getTime() == 0)) {
if (!DateFormat.getTimeInstance().format(task.getDue())
.equals("00:00:00")) {
holder.taskDueDate.setText(DateFormat.getDateTimeInstance(
DateFormat.MEDIUM, DateFormat.SHORT).format(
task.getDue()));
} else {
holder.taskDueDate.setText(DateFormat.getDateInstance()
.format(task.getDue()));
}
} else {
- holder.taskDueDate.setText(null);
+ holder.taskDueDate.setVisibility(View.GONE);
}
if (!TextUtils.isEmpty(task.getPriority())) {
if (task.getPriority().equals("H")) {
holder.taskPriorityView.setBackgroundColor(context
.getResources().getColor(R.color.task_red));
} else if (task.getPriority().equals("M")) {
holder.taskPriorityView.setBackgroundColor(context
.getResources().getColor(R.color.task_yellow));
} else if (task.getPriority().equals("L")) {
holder.taskPriorityView.setBackgroundColor(context
.getResources().getColor(R.color.task_green));
}
} else {
- holder.taskPriorityView.setBackgroundColor(context
- .getResources().getColor(android.R.color.transparent));
+ holder.taskPriorityView.setVisibility(View.GONE);
}
if (task.getStatus().equals("completed")
|| task.getStatus().equals("deleted")) {
if (getItemViewType(position) == TYPE_ROW_CLICKED) {
LinearLayout llButtonLayout = (LinearLayout) v
.findViewById(R.id.taskLinLayout);
llButtonLayout.setVisibility(View.GONE);
View horizBar = v.findViewById(R.id.horizontal_line);
horizBar.setVisibility(View.GONE);
}
}
}
return v;
}
@Override
public int getItemViewType(int position) {
return RowClickedList.contains(position) ? TYPE_ROW_CLICKED : TYPE_ROW;
}
@Override
public int getViewTypeCount() {
return TYPE_MAX_COUNT;
}
@Override
public int getCount() {
return entries.size();
}
@Override
public Object getItem(int position) {
return entries.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
}
| false | true | public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
ViewHolder holder;
if (v == null) {
LayoutInflater vi = (LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
int type = getItemViewType(position);
switch (type) {
case TYPE_ROW:
v = vi.inflate(R.layout.task_row, null);
break;
case TYPE_ROW_CLICKED:
v = vi.inflate(R.layout.task_row_clicked, null);
}
holder = new ViewHolder();
holder.taskDescription = (TextView) v
.findViewById(R.id.tvRowTaskDescription);
holder.taskProject = (TextView) v
.findViewById(R.id.tvRowTaskProject);
holder.taskDueDate = (TextView) v
.findViewById(R.id.tvRowTaskDueDate);
holder.taskRelLayout = (RelativeLayout) v
.findViewById(R.id.taskRelLayout);
holder.taskPriorityView = (View) v
.findViewById(R.id.horizontal_line_priority);
v.setTag(holder);
} else {
holder = (ViewHolder) v.getTag();
}
final Task task = entries.get(position);
if (task != null) {
holder.taskDescription.setText(task.getDescription());
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
String textAppearance = prefs.getString("pref_appearance_descriptionTextSize", context.getResources().getString(R.string.pref_appearance_descriptionTextSize_small));
if (textAppearance.equals(context.getResources().getString(R.string.pref_appearance_descriptionTextSize_small))) {
holder.taskDescription.setTextSize(context.getResources().getDimension(R.dimen.taskDescription_small));
} else if (textAppearance.equals(context.getResources().getString(R.string.pref_appearance_descriptionTextSize_medium))) {
holder.taskDescription.setTextSize(context.getResources().getDimension(R.dimen.taskDescription_medium));
} else {
holder.taskDescription.setTextSize(context.getResources().getDimension(R.dimen.taskDescription_large));
}
holder.taskProject.setText(task.getProject());
if (task.getDue() != null && !(task.getDue().getTime() == 0)) {
if (!DateFormat.getTimeInstance().format(task.getDue())
.equals("00:00:00")) {
holder.taskDueDate.setText(DateFormat.getDateTimeInstance(
DateFormat.MEDIUM, DateFormat.SHORT).format(
task.getDue()));
} else {
holder.taskDueDate.setText(DateFormat.getDateInstance()
.format(task.getDue()));
}
} else {
holder.taskDueDate.setText(null);
}
if (!TextUtils.isEmpty(task.getPriority())) {
if (task.getPriority().equals("H")) {
holder.taskPriorityView.setBackgroundColor(context
.getResources().getColor(R.color.task_red));
} else if (task.getPriority().equals("M")) {
holder.taskPriorityView.setBackgroundColor(context
.getResources().getColor(R.color.task_yellow));
} else if (task.getPriority().equals("L")) {
holder.taskPriorityView.setBackgroundColor(context
.getResources().getColor(R.color.task_green));
}
} else {
holder.taskPriorityView.setBackgroundColor(context
.getResources().getColor(android.R.color.transparent));
}
if (task.getStatus().equals("completed")
|| task.getStatus().equals("deleted")) {
if (getItemViewType(position) == TYPE_ROW_CLICKED) {
LinearLayout llButtonLayout = (LinearLayout) v
.findViewById(R.id.taskLinLayout);
llButtonLayout.setVisibility(View.GONE);
View horizBar = v.findViewById(R.id.horizontal_line);
horizBar.setVisibility(View.GONE);
}
}
}
return v;
}
| public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
ViewHolder holder;
if (v == null) {
LayoutInflater vi = (LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
int type = getItemViewType(position);
switch (type) {
case TYPE_ROW:
v = vi.inflate(R.layout.task_row, null);
break;
case TYPE_ROW_CLICKED:
v = vi.inflate(R.layout.task_row_clicked, null);
}
holder = new ViewHolder();
holder.taskDescription = (TextView) v
.findViewById(R.id.tvRowTaskDescription);
holder.taskProject = (TextView) v
.findViewById(R.id.tvRowTaskProject);
holder.taskDueDate = (TextView) v
.findViewById(R.id.tvRowTaskDueDate);
holder.taskRelLayout = (RelativeLayout) v
.findViewById(R.id.taskRelLayout);
holder.taskPriorityView = (View) v
.findViewById(R.id.horizontal_line_priority);
v.setTag(holder);
} else {
holder = (ViewHolder) v.getTag();
}
final Task task = entries.get(position);
if (task != null) {
holder.taskDescription.setText(task.getDescription());
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
String textAppearance = prefs.getString("pref_appearance_descriptionTextSize", context.getResources().getString(R.string.pref_appearance_descriptionTextSize_small));
if (textAppearance.equals(context.getResources().getString(R.string.pref_appearance_descriptionTextSize_small))) {
holder.taskDescription.setTextSize(context.getResources().getDimension(R.dimen.taskDescription_small));
} else if (textAppearance.equals(context.getResources().getString(R.string.pref_appearance_descriptionTextSize_medium))) {
holder.taskDescription.setTextSize(context.getResources().getDimension(R.dimen.taskDescription_medium));
} else {
holder.taskDescription.setTextSize(context.getResources().getDimension(R.dimen.taskDescription_large));
}
if(task.getProject() != null) {
holder.taskProject.setText(task.getProject());
} else {
holder.taskProject.setVisibility(View.GONE);
}
if (task.getDue() != null && !(task.getDue().getTime() == 0)) {
if (!DateFormat.getTimeInstance().format(task.getDue())
.equals("00:00:00")) {
holder.taskDueDate.setText(DateFormat.getDateTimeInstance(
DateFormat.MEDIUM, DateFormat.SHORT).format(
task.getDue()));
} else {
holder.taskDueDate.setText(DateFormat.getDateInstance()
.format(task.getDue()));
}
} else {
holder.taskDueDate.setVisibility(View.GONE);
}
if (!TextUtils.isEmpty(task.getPriority())) {
if (task.getPriority().equals("H")) {
holder.taskPriorityView.setBackgroundColor(context
.getResources().getColor(R.color.task_red));
} else if (task.getPriority().equals("M")) {
holder.taskPriorityView.setBackgroundColor(context
.getResources().getColor(R.color.task_yellow));
} else if (task.getPriority().equals("L")) {
holder.taskPriorityView.setBackgroundColor(context
.getResources().getColor(R.color.task_green));
}
} else {
holder.taskPriorityView.setVisibility(View.GONE);
}
if (task.getStatus().equals("completed")
|| task.getStatus().equals("deleted")) {
if (getItemViewType(position) == TYPE_ROW_CLICKED) {
LinearLayout llButtonLayout = (LinearLayout) v
.findViewById(R.id.taskLinLayout);
llButtonLayout.setVisibility(View.GONE);
View horizBar = v.findViewById(R.id.horizontal_line);
horizBar.setVisibility(View.GONE);
}
}
}
return v;
}
|
diff --git a/src/ee/mattijagula/mikker/upload/Uploader.java b/src/ee/mattijagula/mikker/upload/Uploader.java
index 916cd41..4790a8d 100644
--- a/src/ee/mattijagula/mikker/upload/Uploader.java
+++ b/src/ee/mattijagula/mikker/upload/Uploader.java
@@ -1,79 +1,79 @@
package ee.mattijagula.mikker.upload;
import ee.mattijagula.mikker.Configuration;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.multipart.*;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
public class Uploader {
private Configuration ctx;
public Uploader(Configuration ctx) {
this.ctx = ctx;
}
public void upload(byte content[], ProgressListener progressListener) throws UploadFailedException {
try {
doUpload(content, progressListener);
} catch (IOException e) {
throw new UploadFailedException("Upload failed with exception: " + e.getMessage(), e);
}
}
private void doUpload(final byte content[], ProgressListener progressListener)
throws IOException, UploadFailedException {
HttpClient client = new HttpClient();
PostMethod post = new PostMethod(ctx.getUploadUrl());
post.addRequestHeader("User-Agent", ctx.getUserAgent());
if (!"".equals(ctx.getCookies())) {
post.addRequestHeader("Cookie", ctx.getCookies());
}
PartSource partSource = new PartSource() {
public long getLength() {
return content.length;
}
public String getFileName() {
return ctx.getUploadFilename();
}
public InputStream createInputStream() throws IOException {
return new ByteArrayInputStream(content);
}
};
Part[] partArray = composeParts(partSource);
MultipartRequestEntity requestEntity = new MultipartRequestEntity(partArray, post.getParams());
post.setRequestEntity(new ProgressReportingRequestEntity(requestEntity, progressListener));
int status = client.executeMethod(post);
- if (status >= 200 && status <= 400) {
+ if (status >= 200 && status < 400) {
progressListener.finished();
System.out.println("Upload complete, response: " + status + " - " + post.getResponseBodyAsString());
} else {
throw new UploadFailedException("Upload failed with code " + status
+ " : " + HttpStatus.getStatusText(status));
}
}
private Part[] composeParts(PartSource partSource) {
List<Part> parts = new ArrayList<Part>();
parts.add(new FilePart(ctx.getFileFieldName(), partSource, ctx.getUploadMimeType(), "utf-8"));
for (KeyValuePairParser.Pair pair : ctx.getAdditionalPostParameters()) {
parts.add(new StringPart(pair.key, pair.value));
}
return parts.toArray(new Part[parts.size()]);
}
}
| true | true | private void doUpload(final byte content[], ProgressListener progressListener)
throws IOException, UploadFailedException {
HttpClient client = new HttpClient();
PostMethod post = new PostMethod(ctx.getUploadUrl());
post.addRequestHeader("User-Agent", ctx.getUserAgent());
if (!"".equals(ctx.getCookies())) {
post.addRequestHeader("Cookie", ctx.getCookies());
}
PartSource partSource = new PartSource() {
public long getLength() {
return content.length;
}
public String getFileName() {
return ctx.getUploadFilename();
}
public InputStream createInputStream() throws IOException {
return new ByteArrayInputStream(content);
}
};
Part[] partArray = composeParts(partSource);
MultipartRequestEntity requestEntity = new MultipartRequestEntity(partArray, post.getParams());
post.setRequestEntity(new ProgressReportingRequestEntity(requestEntity, progressListener));
int status = client.executeMethod(post);
if (status >= 200 && status <= 400) {
progressListener.finished();
System.out.println("Upload complete, response: " + status + " - " + post.getResponseBodyAsString());
} else {
throw new UploadFailedException("Upload failed with code " + status
+ " : " + HttpStatus.getStatusText(status));
}
}
| private void doUpload(final byte content[], ProgressListener progressListener)
throws IOException, UploadFailedException {
HttpClient client = new HttpClient();
PostMethod post = new PostMethod(ctx.getUploadUrl());
post.addRequestHeader("User-Agent", ctx.getUserAgent());
if (!"".equals(ctx.getCookies())) {
post.addRequestHeader("Cookie", ctx.getCookies());
}
PartSource partSource = new PartSource() {
public long getLength() {
return content.length;
}
public String getFileName() {
return ctx.getUploadFilename();
}
public InputStream createInputStream() throws IOException {
return new ByteArrayInputStream(content);
}
};
Part[] partArray = composeParts(partSource);
MultipartRequestEntity requestEntity = new MultipartRequestEntity(partArray, post.getParams());
post.setRequestEntity(new ProgressReportingRequestEntity(requestEntity, progressListener));
int status = client.executeMethod(post);
if (status >= 200 && status < 400) {
progressListener.finished();
System.out.println("Upload complete, response: " + status + " - " + post.getResponseBodyAsString());
} else {
throw new UploadFailedException("Upload failed with code " + status
+ " : " + HttpStatus.getStatusText(status));
}
}
|
diff --git a/container/openejb-core/src/main/java/org/apache/openejb/config/rules/CheckClasses.java b/container/openejb-core/src/main/java/org/apache/openejb/config/rules/CheckClasses.java
index 5036a0ef79..a723a94331 100644
--- a/container/openejb-core/src/main/java/org/apache/openejb/config/rules/CheckClasses.java
+++ b/container/openejb-core/src/main/java/org/apache/openejb/config/rules/CheckClasses.java
@@ -1,351 +1,351 @@
/**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.openejb.config.rules;
import org.apache.openejb.OpenEJBException;
import org.apache.openejb.jee.EnterpriseBean;
import org.apache.openejb.jee.RemoteBean;
import org.apache.openejb.jee.EntityBean;
import org.apache.openejb.jee.SessionBean;
import org.apache.openejb.jee.Interceptor;
import org.apache.openejb.config.EjbModule;
import org.apache.openejb.util.SafeToolkit;
import org.apache.openejb.util.Strings;
import org.apache.xbean.finder.ClassFinder;
import javax.ejb.EJBLocalHome;
import javax.ejb.EJBLocalObject;
import javax.ejb.EJBHome;
import javax.ejb.EJBObject;
import javax.ejb.Local;
import javax.ejb.Remote;
import javax.jws.WebService;
import static java.lang.reflect.Modifier.isAbstract;
import java.lang.reflect.Method;
import java.lang.annotation.Annotation;
import java.util.ArrayList;
import java.util.List;
/**
* @version $Rev$ $Date$
*/
public class CheckClasses extends ValidationBase {
private static final List<Class<? extends Annotation>> beanOnlyAnnotations = new ArrayList<Class<? extends Annotation>>();
static {
beanOnlyAnnotations.add(javax.annotation.PostConstruct.class);
beanOnlyAnnotations.add(javax.annotation.PreDestroy.class);
beanOnlyAnnotations.add(javax.annotation.Resource.class);
beanOnlyAnnotations.add(javax.annotation.Resources.class);
beanOnlyAnnotations.add(javax.annotation.security.DeclareRoles.class);
beanOnlyAnnotations.add(javax.annotation.security.DenyAll.class);
beanOnlyAnnotations.add(javax.annotation.security.PermitAll.class);
beanOnlyAnnotations.add(javax.annotation.security.RolesAllowed.class);
beanOnlyAnnotations.add(javax.annotation.security.RunAs.class);
beanOnlyAnnotations.add(javax.ejb.EJB.class);
beanOnlyAnnotations.add(javax.ejb.EJBs.class);
beanOnlyAnnotations.add(javax.ejb.Init.class);
beanOnlyAnnotations.add(javax.ejb.PostActivate.class);
beanOnlyAnnotations.add(javax.ejb.PrePassivate.class);
beanOnlyAnnotations.add(javax.ejb.Remove.class);
beanOnlyAnnotations.add(javax.ejb.Timeout.class);
beanOnlyAnnotations.add(javax.ejb.TransactionAttribute.class);
beanOnlyAnnotations.add(javax.ejb.TransactionManagement.class);
}
public void validate(EjbModule ejbModule) {
for (EnterpriseBean bean : ejbModule.getEjbJar().getEnterpriseBeans()) {
try {
Class<?> beanClass = check_hasEjbClass(bean);
if (!(bean instanceof RemoteBean)) continue;
RemoteBean b = (RemoteBean) bean;
check_isEjbClass(b);
check_hasDependentClasses(b, b.getEjbClass(), "ejb-class");
check_hasInterface(b);
if (b.getRemote() != null){
checkInterface(b, beanClass, "remote", b.getRemote());
}
if (b.getHome() != null) {
checkInterface(b, beanClass, "home", b.getHome());
}
if (b.getLocal() != null) {
checkInterface(b, beanClass, "local", b.getLocal());
}
if (b.getLocalHome() != null) {
checkInterface(b, beanClass, "local-home", b.getLocalHome());
}
if (b instanceof SessionBean) {
SessionBean sessionBean = (SessionBean) b;
for (String interfce : sessionBean.getBusinessLocal()) {
checkInterface(b, beanClass, "business-local", interfce);
}
for (String interfce : sessionBean.getBusinessRemote()) {
checkInterface(b, beanClass, "business-local", interfce);
}
}
} catch (RuntimeException e) {
throw new RuntimeException(bean.getEjbName(), e);
}
}
for (Interceptor interceptor : ejbModule.getEjbJar().getInterceptors()) {
check_hasInterceptorClass(interceptor);
}
}
private void checkInterface(RemoteBean b, Class<?> beanClass, String tag, String className) {
Class<?> interfce = lookForClass(className, tag, b.getEjbName());
if (interfce == null) return;
check_hasDependentClasses(b, className, tag);
tag = Strings.lcfirst(Strings.camelCase(tag));
if (isValidInterface(b, interfce, beanClass, tag));
ClassFinder finder = new ClassFinder(interfce);
for (Class<? extends Annotation> annotation : beanOnlyAnnotations) {
if (interfce.isAnnotationPresent(annotation)){
warn(b, "interface.beanOnlyAnnotation", annotation.getSimpleName(), interfce.getName(), b.getEjbClass());
}
for (Method method : finder.findAnnotatedMethods(annotation)) {
warn(b, "interfaceMethod.beanOnlyAnnotation", annotation.getSimpleName(), interfce.getName(), method.getName(), b.getEjbClass());
}
}
}
private void check_hasInterface(RemoteBean b) {
if (b.getRemote() != null) return;
if (b.getLocal() != null) return;
Class<?> beanClass = null;
try {
beanClass = loadClass(b.getEjbClass());
} catch (OpenEJBException e) {
}
if (b instanceof EntityBean){
fail(b, "noInterfaceDeclared.entity", beanClass.getSimpleName());
return;
}
if (b.getBusinessLocal().size() > 0) return;
if (b.getBusinessRemote().size() > 0) return;
if (((SessionBean) b).getServiceEndpoint() != null) return;
if (beanClass.isAnnotationPresent(WebService.class)) return;
fail(b, "noInterfaceDeclared.session");
}
private void check_hasDependentClasses(RemoteBean b, String className, String type) {
try {
ClassLoader cl = module.getClassLoader();
Class<?> clazz = cl.loadClass(className);
for (Object item : clazz.getFields()) { item.toString(); }
for (Object item : clazz.getMethods()) { item.toString(); }
for (Object item : clazz.getConstructors()) { item.toString(); }
for (Object item : clazz.getAnnotations()) { item.toString(); }
for (Object item : clazz.getEnumConstants()) { item.toString(); }
} catch (NullPointerException e) {
// Don't know why I get these from clazz.getEnumConstants()
} catch (ClassNotFoundException e) {
/*
# 0 - Referring Class name
# 1 - Dependent Class name
# 2 - Element (home, ejb-class, remote)
# 3 - Bean name
*/
String missingClass = e.getMessage();
fail(b, "missing.dependent.class", className, missingClass, type, b.getEjbName());
} catch (NoClassDefFoundError e) {
/*
# 0 - Referring Class name
# 1 - Dependent Class name
# 2 - Element (home, ejb-class, remote)
# 3 - Bean name
*/
String missingClass = e.getMessage();
fail(b, "missing.dependent.class", className, missingClass, type, b.getEjbName());
}
}
public Class<?> check_hasEjbClass(EnterpriseBean b) {
String ejbName = b.getEjbName();
Class<?> beanClass = lookForClass(b.getEjbClass(), "<ejb-class>", ejbName);
if (beanClass.isInterface()){
fail(ejbName, "interfaceDeclaredAsBean", beanClass.getName());
}
if (isCmp(b)) return beanClass;
if (isAbstract(beanClass.getModifiers())){
fail(ejbName, "abstractDeclaredAsBean", beanClass.getName());
}
return beanClass;
}
private void check_hasInterceptorClass(Interceptor i) {
lookForClass(i.getInterceptorClass(), "interceptor-class", "Interceptor");
}
private void check_isEjbClass(RemoteBean b) {
if (b instanceof SessionBean) {
// DMB: Beans in ejb 3 are not required to implement javax.ejb.SessionBean
// but it would still be nice to think of some sort of check to do here.
// compareTypes(b, b.getEjbClass(), javax.ejb.SessionBean.class);
} else if (b instanceof EntityBean) {
compareTypes(b, b.getEjbClass(), javax.ejb.EntityBean.class);
}
}
private Class<?> lookForClass(String clazz, String type, String ejbName) {
try {
return loadClass(clazz);
} catch (OpenEJBException e) {
/*
# 0 - Class name
# 1 - Element (home, ejb-class, remote)
# 2 - Bean name
*/
fail(ejbName, "missing.class", clazz, type, ejbName);
} catch (NoClassDefFoundError e) {
/*
# 0 - Class name
# 1 - Element (home, ejb-class, remote)
# 2 - Bean name
# 3 - Misslocated Class name
*/
fail(ejbName, "misslocated.class", clazz, type, ejbName, e.getMessage());
throw e;
}
return null;
}
private boolean isValidInterface(RemoteBean b, Class clazz, Class beanClass, String tag) {
if (clazz.equals(beanClass)) {
fail(b, "xml." + tag + ".beanClass", clazz.getName());
} else if (!clazz.isInterface()) {
fail(b, "xml." + tag + ".notInterface", clazz.getName());
} else if (EJBHome.class.isAssignableFrom(clazz)) {
if (tag.equals("home")) return true;
fail(b, "xml." + tag + ".ejbHome", clazz.getName());
} else if (EJBLocalHome.class.isAssignableFrom(clazz)) {
- if (tag.equals("local-home")) return true;
+ if (tag.equals("localHome")) return true;
fail(b, "xml." + tag + ".ejbLocalHome", clazz.getName());
} else if (EJBObject.class.isAssignableFrom(clazz)) {
if (tag.equals("remote")) return true;
fail(b, "xml." + tag + ".ejbObject", clazz.getName());
} else if (EJBLocalObject.class.isAssignableFrom(clazz)) {
if (tag.equals("local")) return true;
fail(b, "xml." + tag + ".ejbLocalObject", clazz.getName());
- } else if (tag.equals("businessLocal") && tag.equals("businessRemote")) {
+ } else if (tag.equals("businessLocal") || tag.equals("businessRemote")) {
return true;
}
// must be tagged as <home>, <local-home>, <remote>, or <local>
if (clazz.isAnnotationPresent(Local.class)) {
fail(b, "xml." + tag + ".businessLocal", clazz.getName());
} else if (clazz.isAnnotationPresent(Remote.class)) {
fail(b, "xml." + tag + ".businessRemote", clazz.getName());
} else {
fail(b, "xml." + tag + ".unknown", clazz.getName());
}
return false;
}
private void compareTypes(RemoteBean b, String clazz1, Class<?> class2) {
Class<?> class1 = null;
try {
class1 = loadClass(clazz1);
} catch (OpenEJBException e) {
return;
}
if (class1 != null && !class2.isAssignableFrom(class1)) {
fail(b, "wrong.class.type", clazz1, class2.getName());
}
}
protected Class<?> loadClass(String clazz) throws OpenEJBException {
ClassLoader cl = module.getClassLoader();
try {
return Class.forName(clazz, false, cl);
} catch (ClassNotFoundException cnfe) {
throw new OpenEJBException(SafeToolkit.messages.format("cl0007", clazz, module.getJarLocation()), cnfe);
}
}
}
| false | true | private boolean isValidInterface(RemoteBean b, Class clazz, Class beanClass, String tag) {
if (clazz.equals(beanClass)) {
fail(b, "xml." + tag + ".beanClass", clazz.getName());
} else if (!clazz.isInterface()) {
fail(b, "xml." + tag + ".notInterface", clazz.getName());
} else if (EJBHome.class.isAssignableFrom(clazz)) {
if (tag.equals("home")) return true;
fail(b, "xml." + tag + ".ejbHome", clazz.getName());
} else if (EJBLocalHome.class.isAssignableFrom(clazz)) {
if (tag.equals("local-home")) return true;
fail(b, "xml." + tag + ".ejbLocalHome", clazz.getName());
} else if (EJBObject.class.isAssignableFrom(clazz)) {
if (tag.equals("remote")) return true;
fail(b, "xml." + tag + ".ejbObject", clazz.getName());
} else if (EJBLocalObject.class.isAssignableFrom(clazz)) {
if (tag.equals("local")) return true;
fail(b, "xml." + tag + ".ejbLocalObject", clazz.getName());
} else if (tag.equals("businessLocal") && tag.equals("businessRemote")) {
return true;
}
// must be tagged as <home>, <local-home>, <remote>, or <local>
if (clazz.isAnnotationPresent(Local.class)) {
fail(b, "xml." + tag + ".businessLocal", clazz.getName());
} else if (clazz.isAnnotationPresent(Remote.class)) {
fail(b, "xml." + tag + ".businessRemote", clazz.getName());
} else {
fail(b, "xml." + tag + ".unknown", clazz.getName());
}
return false;
}
| private boolean isValidInterface(RemoteBean b, Class clazz, Class beanClass, String tag) {
if (clazz.equals(beanClass)) {
fail(b, "xml." + tag + ".beanClass", clazz.getName());
} else if (!clazz.isInterface()) {
fail(b, "xml." + tag + ".notInterface", clazz.getName());
} else if (EJBHome.class.isAssignableFrom(clazz)) {
if (tag.equals("home")) return true;
fail(b, "xml." + tag + ".ejbHome", clazz.getName());
} else if (EJBLocalHome.class.isAssignableFrom(clazz)) {
if (tag.equals("localHome")) return true;
fail(b, "xml." + tag + ".ejbLocalHome", clazz.getName());
} else if (EJBObject.class.isAssignableFrom(clazz)) {
if (tag.equals("remote")) return true;
fail(b, "xml." + tag + ".ejbObject", clazz.getName());
} else if (EJBLocalObject.class.isAssignableFrom(clazz)) {
if (tag.equals("local")) return true;
fail(b, "xml." + tag + ".ejbLocalObject", clazz.getName());
} else if (tag.equals("businessLocal") || tag.equals("businessRemote")) {
return true;
}
// must be tagged as <home>, <local-home>, <remote>, or <local>
if (clazz.isAnnotationPresent(Local.class)) {
fail(b, "xml." + tag + ".businessLocal", clazz.getName());
} else if (clazz.isAnnotationPresent(Remote.class)) {
fail(b, "xml." + tag + ".businessRemote", clazz.getName());
} else {
fail(b, "xml." + tag + ".unknown", clazz.getName());
}
return false;
}
|
diff --git a/src/me/rigi/acceptrules/AcceptRulesMain.java b/src/me/rigi/acceptrules/AcceptRulesMain.java
index 96c2ba1..0468ecc 100644
--- a/src/me/rigi/acceptrules/AcceptRulesMain.java
+++ b/src/me/rigi/acceptrules/AcceptRulesMain.java
@@ -1,127 +1,126 @@
package me.rigi.acceptrules;
import java.util.ArrayList;
import java.util.logging.Logger;
import org.bukkit.Bukkit;
import org.bukkit.Location;
import org.bukkit.World;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.entity.Player;
import org.bukkit.plugin.PluginManager;
import org.bukkit.plugin.java.JavaPlugin;
public class AcceptRulesMain extends JavaPlugin {
Logger Log = Logger.getLogger("Minecraft");
public static AcceptRulesMain plugin;
public static ArrayList<String> players = new ArrayList<String>();
public static ArrayList<String> rules = new ArrayList<String>();
public static ArrayList<Player> readed = new ArrayList<Player>();
public static String AcceptedMsg,AcceptedAllreadyMsg,InformMsg,MustReadRules,CantBuildMsg,TpWorld,SpawnWorld,RulesCmd;
public static boolean TpAfterAccept,AllowBuild,Notify,Inform,AllowMove,TpOnJoin, BlockCmds, RulesMngr;
public static Location TpPosition;
public static Location SpawnPosition;
public static FileConfiguration config;
//@Override
public void onDisable() {
Log.info("[AcceptRules] AcceptRules plugin succesfully disabled!");
}
//@Override
public void onEnable() {
PluginManager pm = getServer().getPluginManager();
AcceptRulesPreferences acceptrulespreferences = new AcceptRulesPreferences();
acceptrulespreferences.createDir();
getConfig().options().copyDefaults(true);
saveConfig();
config = getConfig();
AcceptedMsg = config.getString("AcceptedMsg", "You have succesfully accepted the rules! Have fun!");
AcceptedAllreadyMsg = config.getString("AcceptedAllreadyMsg", "You have allready accepted the rules!");
CantBuildMsg = config.getString("CantBuildMsg", "You must accept rules to build!");
MustReadRules = config.getString("MustReadRules", "You must read the rules in order to accept them!");
InformMsg = config.getString("InformMsg","You have to accept the rules! Use /rules and then /acceptrules!");
RulesCmd = config.getString("RulesCmd","/rules");
TpAfterAccept = config.getBoolean("TpAfterAccept", false);
TpOnJoin = config.getBoolean("TpOnJoin", false);
AllowBuild = config.getBoolean("AllowBuildBeforeAccept", false);
AllowMove = config.getBoolean("AllowMoveBeforeAccept", true);
Notify = config.getBoolean("NotifyOPs", true);
Inform = config.getBoolean("InformUser", true);
BlockCmds = config.getBoolean("BlockCommandsBeforeAccept", true);
RulesMngr = config.getBoolean("BuiltInRulesManager", true);
TpWorld = config.getString("TpWorld", "world");
SpawnWorld = config.getString("SpawnWorld", "world");
Double PosX = config.getDouble("TpPositionX", 0);
Double PosY = config.getDouble("TpPositionY", 0);
Double PosZ = config.getDouble("TpPositionZ", 0);
float Pitch =(float) config.getDouble("TpPositionPitch", 0);
float Yaw = (float) config.getDouble("TpPositionYaw", 0);
World world = Bukkit.getServer().getWorld(TpWorld);
Location location = new Location(world, PosX, PosY, PosZ, Yaw, Pitch);
TpPosition = location;
Double SPosX = config.getDouble("SpawnPositionX", 0);
Double SPosY = config.getDouble("SpawnPositionY", 0);
Double SPosZ = config.getDouble("SpawnPositionZ", 0);
float SPitch = (float) config.getDouble("SpawnPositionPitch", 0);
float SYaw = (float) config.getDouble("SpawnPositionYaw", 0);
World Sworld = Bukkit.getServer().getWorld(SpawnWorld);
Location Slocation = new Location(Sworld, SPosX, SPosY, SPosZ, SYaw, SPitch);
SpawnPosition = Slocation;
saveConfig();
AcceptRulesPreferences.UserReader();
AcceptRulesPreferences.RulesReader();
pm.registerEvents(new AcceptRulesListener(), this);
getCommand("acceptrules").setExecutor(new acceptrulesCmdExecutor(this));
- getCommand("rules").setExecutor(new acceptrulesCmdExecutor(this));
Log.info("[AcceptRules] AcceptRules plugin succesfully enabled!");
}
public void savePosToConfig(String type, String world, double x, double y, double z, double pitch, double yaw) {
if(type.equalsIgnoreCase("tp")){
config.set("TpWorld", world);
config.set("TpPositionX", x);
config.set("TpPositionY", y);
config.set("TpPositionZ", z);
config.set("TpPositionPitch", pitch);
config.set("TpPositionYaw", yaw);
}
if(type.equalsIgnoreCase("spawn")){
config.set("SpawnWorld", world);
config.set("SpawnPositionX", x);
config.set("SpawnPositionY", y);
config.set("SpawnPositionZ", z);
config.set("SpawnPositionPitch", pitch);
config.set("SpawnPositionYaw", yaw);
}
saveConfig();
reloadConfig();
if(type.equalsIgnoreCase("tp")){
TpWorld = config.getString("TpWorld", "world");
Double PosX = config.getDouble("TpPositionX", 0);
Double PosY = config.getDouble("TpPositionY", 0);
Double PosZ = config.getDouble("TpPositionZ", 0);
float Pitch =(float) config.getDouble("TpPositionPitch", 0);
float Yaw = (float) config.getDouble("TpPositionYaw", 0);
World worldd = Bukkit.getServer().getWorld(TpWorld);
Location location = new Location(worldd, PosX, PosY, PosZ, Yaw, Pitch);
TpPosition = location;
}
if(type.equalsIgnoreCase("spawn")){
TpWorld = config.getString("SpawnWorld", "world");
Double PosX = config.getDouble("SpawnPositionX", 0);
Double PosY = config.getDouble("SpawnPositionY", 0);
Double PosZ = config.getDouble("SpawnPositionZ", 0);
float Pitch = (float) config.getDouble("SpawnPositionPitch", 0);
float Yaw = (float) config.getDouble("SpawnPositionYaw", 0);
config.set("SpawnPositionYaw", yaw);
World worldd = Bukkit.getServer().getWorld(TpWorld);
Location location = new Location(worldd, PosX, PosY, PosZ, Yaw, Pitch);
SpawnPosition = location;
}
}
}
| true | true | public void onEnable() {
PluginManager pm = getServer().getPluginManager();
AcceptRulesPreferences acceptrulespreferences = new AcceptRulesPreferences();
acceptrulespreferences.createDir();
getConfig().options().copyDefaults(true);
saveConfig();
config = getConfig();
AcceptedMsg = config.getString("AcceptedMsg", "You have succesfully accepted the rules! Have fun!");
AcceptedAllreadyMsg = config.getString("AcceptedAllreadyMsg", "You have allready accepted the rules!");
CantBuildMsg = config.getString("CantBuildMsg", "You must accept rules to build!");
MustReadRules = config.getString("MustReadRules", "You must read the rules in order to accept them!");
InformMsg = config.getString("InformMsg","You have to accept the rules! Use /rules and then /acceptrules!");
RulesCmd = config.getString("RulesCmd","/rules");
TpAfterAccept = config.getBoolean("TpAfterAccept", false);
TpOnJoin = config.getBoolean("TpOnJoin", false);
AllowBuild = config.getBoolean("AllowBuildBeforeAccept", false);
AllowMove = config.getBoolean("AllowMoveBeforeAccept", true);
Notify = config.getBoolean("NotifyOPs", true);
Inform = config.getBoolean("InformUser", true);
BlockCmds = config.getBoolean("BlockCommandsBeforeAccept", true);
RulesMngr = config.getBoolean("BuiltInRulesManager", true);
TpWorld = config.getString("TpWorld", "world");
SpawnWorld = config.getString("SpawnWorld", "world");
Double PosX = config.getDouble("TpPositionX", 0);
Double PosY = config.getDouble("TpPositionY", 0);
Double PosZ = config.getDouble("TpPositionZ", 0);
float Pitch =(float) config.getDouble("TpPositionPitch", 0);
float Yaw = (float) config.getDouble("TpPositionYaw", 0);
World world = Bukkit.getServer().getWorld(TpWorld);
Location location = new Location(world, PosX, PosY, PosZ, Yaw, Pitch);
TpPosition = location;
Double SPosX = config.getDouble("SpawnPositionX", 0);
Double SPosY = config.getDouble("SpawnPositionY", 0);
Double SPosZ = config.getDouble("SpawnPositionZ", 0);
float SPitch = (float) config.getDouble("SpawnPositionPitch", 0);
float SYaw = (float) config.getDouble("SpawnPositionYaw", 0);
World Sworld = Bukkit.getServer().getWorld(SpawnWorld);
Location Slocation = new Location(Sworld, SPosX, SPosY, SPosZ, SYaw, SPitch);
SpawnPosition = Slocation;
saveConfig();
AcceptRulesPreferences.UserReader();
AcceptRulesPreferences.RulesReader();
pm.registerEvents(new AcceptRulesListener(), this);
getCommand("acceptrules").setExecutor(new acceptrulesCmdExecutor(this));
getCommand("rules").setExecutor(new acceptrulesCmdExecutor(this));
Log.info("[AcceptRules] AcceptRules plugin succesfully enabled!");
}
| public void onEnable() {
PluginManager pm = getServer().getPluginManager();
AcceptRulesPreferences acceptrulespreferences = new AcceptRulesPreferences();
acceptrulespreferences.createDir();
getConfig().options().copyDefaults(true);
saveConfig();
config = getConfig();
AcceptedMsg = config.getString("AcceptedMsg", "You have succesfully accepted the rules! Have fun!");
AcceptedAllreadyMsg = config.getString("AcceptedAllreadyMsg", "You have allready accepted the rules!");
CantBuildMsg = config.getString("CantBuildMsg", "You must accept rules to build!");
MustReadRules = config.getString("MustReadRules", "You must read the rules in order to accept them!");
InformMsg = config.getString("InformMsg","You have to accept the rules! Use /rules and then /acceptrules!");
RulesCmd = config.getString("RulesCmd","/rules");
TpAfterAccept = config.getBoolean("TpAfterAccept", false);
TpOnJoin = config.getBoolean("TpOnJoin", false);
AllowBuild = config.getBoolean("AllowBuildBeforeAccept", false);
AllowMove = config.getBoolean("AllowMoveBeforeAccept", true);
Notify = config.getBoolean("NotifyOPs", true);
Inform = config.getBoolean("InformUser", true);
BlockCmds = config.getBoolean("BlockCommandsBeforeAccept", true);
RulesMngr = config.getBoolean("BuiltInRulesManager", true);
TpWorld = config.getString("TpWorld", "world");
SpawnWorld = config.getString("SpawnWorld", "world");
Double PosX = config.getDouble("TpPositionX", 0);
Double PosY = config.getDouble("TpPositionY", 0);
Double PosZ = config.getDouble("TpPositionZ", 0);
float Pitch =(float) config.getDouble("TpPositionPitch", 0);
float Yaw = (float) config.getDouble("TpPositionYaw", 0);
World world = Bukkit.getServer().getWorld(TpWorld);
Location location = new Location(world, PosX, PosY, PosZ, Yaw, Pitch);
TpPosition = location;
Double SPosX = config.getDouble("SpawnPositionX", 0);
Double SPosY = config.getDouble("SpawnPositionY", 0);
Double SPosZ = config.getDouble("SpawnPositionZ", 0);
float SPitch = (float) config.getDouble("SpawnPositionPitch", 0);
float SYaw = (float) config.getDouble("SpawnPositionYaw", 0);
World Sworld = Bukkit.getServer().getWorld(SpawnWorld);
Location Slocation = new Location(Sworld, SPosX, SPosY, SPosZ, SYaw, SPitch);
SpawnPosition = Slocation;
saveConfig();
AcceptRulesPreferences.UserReader();
AcceptRulesPreferences.RulesReader();
pm.registerEvents(new AcceptRulesListener(), this);
getCommand("acceptrules").setExecutor(new acceptrulesCmdExecutor(this));
Log.info("[AcceptRules] AcceptRules plugin succesfully enabled!");
}
|
diff --git a/src/com/albaniliu/chuangxindemo/ImageShow.java b/src/com/albaniliu/chuangxindemo/ImageShow.java
index 7d58a47..4bb124a 100644
--- a/src/com/albaniliu/chuangxindemo/ImageShow.java
+++ b/src/com/albaniliu/chuangxindemo/ImageShow.java
@@ -1,114 +1,114 @@
package com.albaniliu.chuangxindemo;
import java.io.File;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.support.v4.view.ViewPager;
import android.view.Menu;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.albaniliu.chuangxindemo.widget.LargePicGallery;
import com.albaniliu.chuangxindemo.widget.LargePicGallery.SingleTapListner;
import com.albaniliu.chuangxindemo.widget.ViewPagerAdapter;
public class ImageShow extends Activity {
private String mPath = Environment.getExternalStorageDirectory() + "/liangdemo1";
private File mTestFolder = new File(mPath);
private ViewPagerAdapter mAdapter;
private LinearLayout mFlowBar;
private TextView mFooter;
private LargePicGallery mPager;
private Handler mHanler = new Handler();
private SingleTapListner mListener = new SingleTapListner() {
@Override
public void onSingleTapUp() {
toggleFlowBar();
}
};
private Runnable mToggleRunnable = new Runnable() {
@Override
public void run() {
toggleFlowBar();
}
};
private void toggleFlowBar() {
int delta = mFlowBar.getHeight();
mHanler.removeCallbacks(mToggleRunnable);
if (mFlowBar.getVisibility() == View.INVISIBLE
|| mFlowBar.getVisibility() == View.GONE) {
mFlowBar.setVisibility(View.VISIBLE);
mFooter.setVisibility(View.VISIBLE);
Animation anim = new TranslateAnimation(0, 0, -delta, 0);
anim.setDuration(300);
mFlowBar.startAnimation(anim);
Animation animDown = new TranslateAnimation(0, 0, delta, 0);
animDown.setDuration(300);
- mFlowBar.startAnimation(animDown);
+ mFooter.startAnimation(animDown);
mHanler.postDelayed(mToggleRunnable, 5000);
} else {
mFlowBar.setVisibility(View.INVISIBLE);
mFooter.setVisibility(View.INVISIBLE);
Animation anim = new TranslateAnimation(0, 0, 0, -delta);
anim.setDuration(300);
mFlowBar.startAnimation(anim);
Animation animDown = new TranslateAnimation(0, 0, 0, delta);
animDown.setDuration(300);
mFooter.startAnimation(animDown);
}
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.largepic);
mAdapter = new ViewPagerAdapter(mTestFolder, mListener);
mPager = (LargePicGallery) findViewById(R.id.photo_flow);
mPager.setOffscreenPageLimit(1);
mPager.setPageMargin(20);
mPager.setHorizontalFadingEdgeEnabled(true);
mPager.setAdapter(mAdapter);
mPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
@Override
public void onPageSelected(int position) {
mFooter.setText(mAdapter.getName(position));
}
});
mFlowBar = (LinearLayout) findViewById(R.id.flow_bar);
mFooter = (TextView) findViewById(R.id.footer_bar);
mFooter.setText(mAdapter.getName(0));
mHanler.postDelayed(mToggleRunnable, 5000);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
// getMenuInflater().inflate(R.menu.activity_image_show, menu);
return true;
}
public void onBackClick(View view) {
onBackPressed();
}
public void onSlideClick(View view) {
Intent intent = new Intent();
intent.setClass(getApplicationContext(), SlideShowActivity.class);
startActivity(intent);
}
}
| true | true | private void toggleFlowBar() {
int delta = mFlowBar.getHeight();
mHanler.removeCallbacks(mToggleRunnable);
if (mFlowBar.getVisibility() == View.INVISIBLE
|| mFlowBar.getVisibility() == View.GONE) {
mFlowBar.setVisibility(View.VISIBLE);
mFooter.setVisibility(View.VISIBLE);
Animation anim = new TranslateAnimation(0, 0, -delta, 0);
anim.setDuration(300);
mFlowBar.startAnimation(anim);
Animation animDown = new TranslateAnimation(0, 0, delta, 0);
animDown.setDuration(300);
mFlowBar.startAnimation(animDown);
mHanler.postDelayed(mToggleRunnable, 5000);
} else {
mFlowBar.setVisibility(View.INVISIBLE);
mFooter.setVisibility(View.INVISIBLE);
Animation anim = new TranslateAnimation(0, 0, 0, -delta);
anim.setDuration(300);
mFlowBar.startAnimation(anim);
Animation animDown = new TranslateAnimation(0, 0, 0, delta);
animDown.setDuration(300);
mFooter.startAnimation(animDown);
}
}
| private void toggleFlowBar() {
int delta = mFlowBar.getHeight();
mHanler.removeCallbacks(mToggleRunnable);
if (mFlowBar.getVisibility() == View.INVISIBLE
|| mFlowBar.getVisibility() == View.GONE) {
mFlowBar.setVisibility(View.VISIBLE);
mFooter.setVisibility(View.VISIBLE);
Animation anim = new TranslateAnimation(0, 0, -delta, 0);
anim.setDuration(300);
mFlowBar.startAnimation(anim);
Animation animDown = new TranslateAnimation(0, 0, delta, 0);
animDown.setDuration(300);
mFooter.startAnimation(animDown);
mHanler.postDelayed(mToggleRunnable, 5000);
} else {
mFlowBar.setVisibility(View.INVISIBLE);
mFooter.setVisibility(View.INVISIBLE);
Animation anim = new TranslateAnimation(0, 0, 0, -delta);
anim.setDuration(300);
mFlowBar.startAnimation(anim);
Animation animDown = new TranslateAnimation(0, 0, 0, delta);
animDown.setDuration(300);
mFooter.startAnimation(animDown);
}
}
|
diff --git a/src/main/java/com/laytonsmith/aliasengine/functions/Meta.java b/src/main/java/com/laytonsmith/aliasengine/functions/Meta.java
index b32dd19f..c7aadd9c 100644
--- a/src/main/java/com/laytonsmith/aliasengine/functions/Meta.java
+++ b/src/main/java/com/laytonsmith/aliasengine/functions/Meta.java
@@ -1,371 +1,371 @@
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package com.laytonsmith.aliasengine.functions;
import com.laytonsmith.aliasengine.functions.exceptions.CancelCommandException;
import com.laytonsmith.aliasengine.functions.exceptions.ConfigRuntimeException;
import com.laytonsmith.aliasengine.Constructs.CArray;
import com.laytonsmith.aliasengine.Constructs.CString;
import com.laytonsmith.aliasengine.Constructs.CVoid;
import com.laytonsmith.aliasengine.Constructs.Construct;
import com.laytonsmith.aliasengine.Static;
import com.laytonsmith.aliasengine.functions.Exceptions.ExceptionType;
import java.io.File;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.logging.Level;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
/**
* I'm So Meta, Even This Acronym
* @author Layton
*/
public class Meta {
public static String docs() {
return "These functions provide a way to run other commands";
}
@api
public static class runas implements Function {
public String getName() {
return "runas";
}
public Integer[] numArgs() {
return new Integer[]{2};
}
public Construct exec(int line_num, File f, final CommandSender p, Construct... args) throws CancelCommandException, ConfigRuntimeException {
if (args[1].val() == null || args[1].val().length() <= 0 || args[1].val().charAt(0) != '/') {
throw new ConfigRuntimeException("The first character of the command must be a forward slash (i.e. '/give')",
ExceptionType.FormatException, line_num, f);
}
String cmd = args[1].val().substring(1);
if (args[0] instanceof CArray) {
CArray u = (CArray) args[0];
for (int i = 0; i < u.size(); i++) {
exec(line_num, f, p, new Construct[]{new CString(u.get(i, line_num).val(), line_num, f), args[1]});
}
return new CVoid(line_num, f);
}
if (args[0].val().equals("~op")) {
CommandSender m = null;
if (p.isOp()) {
m = p;
} else {
m = (Player) Proxy.newProxyInstance(Player.class.getClassLoader(), new Class[]{Player.class},
new InvocationHandler() {
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
- if (method.getName().equals("isOp")) {
+ if (method.getName().equals("isOp") || method.getName().equals("isPermissionSet") || method.getName().equals("hasPermission")) {
return true;
} else {
return method.invoke(p, args);
}
}
});
}
if ((Boolean) Static.getPreferences().getPreference("debug-mode")) {
if (m instanceof Player) {
Static.getLogger().log(Level.INFO, "[CommandHelper]: Executing command on " + ((Player) m).getName() + ": " + args[1].val().trim());
} else {
Static.getLogger().log(Level.INFO, "[CommandHelper]: Executing command from console equivalent: " + args[1].val().trim());
}
}
//m.chat(cmd);
Static.getServer().dispatchCommand(m, cmd);
} else {
Player m = Static.getServer().getPlayer(args[0].val());
if (m != null && m.isOnline()) {
if (p instanceof Player) {
Static.getLogger().log(Level.INFO, "[CommandHelper]: Executing command on " + ((Player) p).getName() + ": " + args[0].val().trim());
} else {
Static.getLogger().log(Level.INFO, "[CommandHelper]: Executing command from console equivalent: " + args[0].val().trim());
}
//m.chat(cmd);
Static.getServer().dispatchCommand(m, cmd);
} else {
throw new ConfigRuntimeException("The player " + args[0].val() + " is not online",
ExceptionType.PlayerOfflineException, line_num, f);
}
}
return new CVoid(line_num, f);
}
public ExceptionType[] thrown() {
return new ExceptionType[]{ExceptionType.FormatException, ExceptionType.PlayerOfflineException};
}
public String docs() {
return "void {player, command} Runs a command as a particular user. The special user '~op' is a user that runs as op. Be careful with this very powerful function."
+ " Commands cannot be run as an offline player. Returns void. If the first argument is an array of usernames, the command"
+ " will be run in the context of each user in the array.";
}
public boolean isRestricted() {
return true;
}
public void varList(IVariableList varList) {
}
public boolean preResolveVariables() {
return true;
}
public String since() {
return "3.0.1";
}
public Boolean runAsync() {
return false;
}
}
@api
public static class run implements Function {
public String getName() {
return "run";
}
public Integer[] numArgs() {
return new Integer[]{1};
}
public Construct exec(int line_num, File f, CommandSender p, Construct... args) throws CancelCommandException, ConfigRuntimeException {
if (args[0].val() == null || args[0].val().length() <= 0 || args[0].val().charAt(0) != '/') {
throw new ConfigRuntimeException("The first character of the command must be a forward slash (i.e. '/give')",
ExceptionType.FormatException, line_num, f);
}
String cmd = args[0].val().substring(1);
if ((Boolean) Static.getPreferences().getPreference("debug-mode")) {
if (p instanceof Player) {
Static.getLogger().log(Level.INFO, "[CommandHelper]: Executing command on " + ((Player) p).getName() + ": " + args[0].val().trim());
} else {
Static.getLogger().log(Level.INFO, "[CommandHelper]: Executing command from console equivalent: " + args[0].val().trim());
}
}
//p.chat(cmd);
Static.getServer().dispatchCommand(p, cmd);
return new CVoid(line_num, f);
}
public String docs() {
return "void {var1} Runs a command as the current player. Useful for running commands in a loop. Note that this accepts commands like from the "
+ "chat; with a forward slash in front.";
}
public ExceptionType[] thrown() {
return new ExceptionType[]{ExceptionType.FormatException};
}
public boolean isRestricted() {
return false;
}
public void varList(IVariableList varList) {
}
public boolean preResolveVariables() {
return true;
}
public String since() {
return "3.0.1";
}
public Boolean runAsync() {
return false;
}
}
@api
public static class g implements Function {
public String getName() {
return "g";
}
public Integer[] numArgs() {
return new Integer[]{Integer.MAX_VALUE};
}
public Construct exec(int line_num, File f, CommandSender p, Construct... args) throws CancelCommandException, ConfigRuntimeException {
for (int i = 0; i < args.length; i++) {
args[i].val();
}
return new CVoid(line_num, f);
}
public String docs() {
return "string {func1, [func2...]} Groups any number of functions together, and returns void. ";
}
public ExceptionType[] thrown() {
return new ExceptionType[]{};
}
public boolean isRestricted() {
return false;
}
public void varList(IVariableList varList) {
}
public boolean preResolveVariables() {
return true;
}
public String since() {
return "3.0.1";
}
public Boolean runAsync() {
return null;
}
}
@api
public static class p implements Function {
public String getName() {
return "p";
}
public Integer[] numArgs() {
return new Integer[]{1};
}
public String docs() {
return "mixed {c} Used internally by the compiler.";
}
public ExceptionType[] thrown() {
return null;
}
public boolean isRestricted() {
return false;
}
public void varList(IVariableList varList) {
}
public boolean preResolveVariables() {
return true;
}
public String since() {
return "3.1.2";
}
public Boolean runAsync() {
return null;
}
public Construct exec(int line_num, File f, CommandSender p, Construct... args) throws ConfigRuntimeException {
return Static.resolveConstruct(args[0].val(), line_num, f);
}
}
@api
public static class eval implements Function {
public String getName() {
return "eval";
}
public Integer[] numArgs() {
return new Integer[]{1};
}
public String docs() {
return "string {script_string} Executes arbitrary MScript. Note that this function is very experimental, and is subject to changing or "
+ "removal.";
}
public ExceptionType[] thrown() {
return new ExceptionType[]{};
}
public boolean isRestricted() {
return true;
}
public void varList(IVariableList varList) {
}
public boolean preResolveVariables() {
return true;
}
public String since() {
return "3.1.0";
}
public Construct exec(int line_num, File f, CommandSender p, Construct... args) throws CancelCommandException, ConfigRuntimeException {
return new CVoid(line_num, f);
}
//Doesn't matter, run out of state anyways
public Boolean runAsync() {
return null;
}
}
@api
public static class call_alias implements Function {
public String getName() {
return "call_alias";
}
public Integer[] numArgs() {
return new Integer[]{1};
}
public String docs() {
return "void {cmd} Allows a CommandHelper alias to be called from within another alias. Typically this is not possible, as"
+ " a script that runs \"/jail = /jail\" for instance, would simply be calling whatever plugin that actually"
+ " provides the jail functionality's /jail command. However, using this function makes the command loop back"
+ " to CommandHelper only.";
}
public ExceptionType[] thrown() {
return new ExceptionType[]{};
}
public boolean isRestricted() {
return false;
}
public void varList(IVariableList varList) {
}
public boolean preResolveVariables() {
return true;
}
public String since() {
return "3.2.0";
}
public Boolean runAsync() {
return null;
}
public Construct exec(int line_num, File f, CommandSender p, Construct... args) throws ConfigRuntimeException {
Static.getAliasCore().removePlayerReference(p);
Static.getAliasCore().alias(args[0].val(), p, null);
Static.getAliasCore().addPlayerReference(p);
return new CVoid(line_num, f);
}
}
}
| true | true | public Construct exec(int line_num, File f, final CommandSender p, Construct... args) throws CancelCommandException, ConfigRuntimeException {
if (args[1].val() == null || args[1].val().length() <= 0 || args[1].val().charAt(0) != '/') {
throw new ConfigRuntimeException("The first character of the command must be a forward slash (i.e. '/give')",
ExceptionType.FormatException, line_num, f);
}
String cmd = args[1].val().substring(1);
if (args[0] instanceof CArray) {
CArray u = (CArray) args[0];
for (int i = 0; i < u.size(); i++) {
exec(line_num, f, p, new Construct[]{new CString(u.get(i, line_num).val(), line_num, f), args[1]});
}
return new CVoid(line_num, f);
}
if (args[0].val().equals("~op")) {
CommandSender m = null;
if (p.isOp()) {
m = p;
} else {
m = (Player) Proxy.newProxyInstance(Player.class.getClassLoader(), new Class[]{Player.class},
new InvocationHandler() {
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
if (method.getName().equals("isOp")) {
return true;
} else {
return method.invoke(p, args);
}
}
});
}
if ((Boolean) Static.getPreferences().getPreference("debug-mode")) {
if (m instanceof Player) {
Static.getLogger().log(Level.INFO, "[CommandHelper]: Executing command on " + ((Player) m).getName() + ": " + args[1].val().trim());
} else {
Static.getLogger().log(Level.INFO, "[CommandHelper]: Executing command from console equivalent: " + args[1].val().trim());
}
}
//m.chat(cmd);
Static.getServer().dispatchCommand(m, cmd);
} else {
Player m = Static.getServer().getPlayer(args[0].val());
if (m != null && m.isOnline()) {
if (p instanceof Player) {
Static.getLogger().log(Level.INFO, "[CommandHelper]: Executing command on " + ((Player) p).getName() + ": " + args[0].val().trim());
} else {
Static.getLogger().log(Level.INFO, "[CommandHelper]: Executing command from console equivalent: " + args[0].val().trim());
}
//m.chat(cmd);
Static.getServer().dispatchCommand(m, cmd);
} else {
throw new ConfigRuntimeException("The player " + args[0].val() + " is not online",
ExceptionType.PlayerOfflineException, line_num, f);
}
}
return new CVoid(line_num, f);
}
| public Construct exec(int line_num, File f, final CommandSender p, Construct... args) throws CancelCommandException, ConfigRuntimeException {
if (args[1].val() == null || args[1].val().length() <= 0 || args[1].val().charAt(0) != '/') {
throw new ConfigRuntimeException("The first character of the command must be a forward slash (i.e. '/give')",
ExceptionType.FormatException, line_num, f);
}
String cmd = args[1].val().substring(1);
if (args[0] instanceof CArray) {
CArray u = (CArray) args[0];
for (int i = 0; i < u.size(); i++) {
exec(line_num, f, p, new Construct[]{new CString(u.get(i, line_num).val(), line_num, f), args[1]});
}
return new CVoid(line_num, f);
}
if (args[0].val().equals("~op")) {
CommandSender m = null;
if (p.isOp()) {
m = p;
} else {
m = (Player) Proxy.newProxyInstance(Player.class.getClassLoader(), new Class[]{Player.class},
new InvocationHandler() {
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
if (method.getName().equals("isOp") || method.getName().equals("isPermissionSet") || method.getName().equals("hasPermission")) {
return true;
} else {
return method.invoke(p, args);
}
}
});
}
if ((Boolean) Static.getPreferences().getPreference("debug-mode")) {
if (m instanceof Player) {
Static.getLogger().log(Level.INFO, "[CommandHelper]: Executing command on " + ((Player) m).getName() + ": " + args[1].val().trim());
} else {
Static.getLogger().log(Level.INFO, "[CommandHelper]: Executing command from console equivalent: " + args[1].val().trim());
}
}
//m.chat(cmd);
Static.getServer().dispatchCommand(m, cmd);
} else {
Player m = Static.getServer().getPlayer(args[0].val());
if (m != null && m.isOnline()) {
if (p instanceof Player) {
Static.getLogger().log(Level.INFO, "[CommandHelper]: Executing command on " + ((Player) p).getName() + ": " + args[0].val().trim());
} else {
Static.getLogger().log(Level.INFO, "[CommandHelper]: Executing command from console equivalent: " + args[0].val().trim());
}
//m.chat(cmd);
Static.getServer().dispatchCommand(m, cmd);
} else {
throw new ConfigRuntimeException("The player " + args[0].val() + " is not online",
ExceptionType.PlayerOfflineException, line_num, f);
}
}
return new CVoid(line_num, f);
}
|
diff --git a/src/gui/TerminalTab.java b/src/gui/TerminalTab.java
index d55e1a5..6f934c0 100644
--- a/src/gui/TerminalTab.java
+++ b/src/gui/TerminalTab.java
@@ -1,43 +1,45 @@
package gui;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.io.PrintStream;
import javax.swing.BoxLayout;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.ScrollPaneConstants;
@SuppressWarnings("serial")
public class TerminalTab extends JPanel {
private JTextArea textArea;
public TerminalTab() {
+ // Setup miscallenous
setLayout(new BoxLayout(this, BoxLayout.LINE_AXIS));
+ // Setup text area
textArea = new JTextArea(4, 20);
textArea.setEditable(true);
JScrollPane scrollPane = new JScrollPane(textArea,
ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS,
ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS);
scrollPane.setPreferredSize(new Dimension(200, 70));
add(scrollPane, BorderLayout.CENTER);
// Redirect streams
System.setOut(new PrintStream(new JTextAreaOutputStream(textArea)));
System.setErr(new PrintStream(new JTextAreaOutputStream(textArea)));
}
public void setText(String text) {
textArea.append(text);
}
public void clearTerminal() {
textArea.setText("");
}
}
| false | true | public TerminalTab() {
setLayout(new BoxLayout(this, BoxLayout.LINE_AXIS));
textArea = new JTextArea(4, 20);
textArea.setEditable(true);
JScrollPane scrollPane = new JScrollPane(textArea,
ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS,
ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS);
scrollPane.setPreferredSize(new Dimension(200, 70));
add(scrollPane, BorderLayout.CENTER);
// Redirect streams
System.setOut(new PrintStream(new JTextAreaOutputStream(textArea)));
System.setErr(new PrintStream(new JTextAreaOutputStream(textArea)));
}
| public TerminalTab() {
// Setup miscallenous
setLayout(new BoxLayout(this, BoxLayout.LINE_AXIS));
// Setup text area
textArea = new JTextArea(4, 20);
textArea.setEditable(true);
JScrollPane scrollPane = new JScrollPane(textArea,
ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS,
ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS);
scrollPane.setPreferredSize(new Dimension(200, 70));
add(scrollPane, BorderLayout.CENTER);
// Redirect streams
System.setOut(new PrintStream(new JTextAreaOutputStream(textArea)));
System.setErr(new PrintStream(new JTextAreaOutputStream(textArea)));
}
|
diff --git a/src/dna/io/filesystem/Dir.java b/src/dna/io/filesystem/Dir.java
index a18fb93c..24bb4c2d 100644
--- a/src/dna/io/filesystem/Dir.java
+++ b/src/dna/io/filesystem/Dir.java
@@ -1,99 +1,99 @@
package dna.io.filesystem;
import java.io.File;
import dna.io.filter.PrefixFilenameFilter;
/**
*
* Gives the default storage path for data objects.
*
* @author benni
*
*/
public class Dir {
public static final String delimiter = "/";
/*
* AGGREGATION
*/
public static String getAggregationDataDir(String dir) {
return dir + Names.runAggregation + Dir.delimiter;
}
public static String getAggregationBatchDir(String dir, long run) {
return Dir.getAggregationDataDir(dir) + Prefix.batchDataDir + run
+ Dir.delimiter;
}
public static String getAggregatedMetricDataDir(String dir, long timestamp,
String name) {
- return Dir.getAggregationBatchDir(dir, timestamp) + name
- + Dir.delimiter;
+ return Dir.getAggregationBatchDir(dir, timestamp)
+ + Prefix.metricDataDir + name + Dir.delimiter;
}
/*
* RUN data
*/
public static String getRunDataDir(String dir, int run) {
return dir + Prefix.runDataDir + run + Dir.delimiter;
}
public static String[] getRuns(String dir) {
return (new File(dir))
.list(new PrefixFilenameFilter(Prefix.runDataDir));
}
public static int getRun(String runFolderName) {
return Integer.parseInt(runFolderName.replaceFirst(Prefix.runDataDir,
""));
}
/*
* BATCH data
*/
public static String getBatchDataDir(String dir, long timestamp) {
return dir + Prefix.batchDataDir + timestamp + Dir.delimiter;
}
public static String getBatchDataDir(String dir, int run, long timestamp) {
return Dir.getRunDataDir(dir, run) + Prefix.batchDataDir + timestamp
+ Dir.delimiter;
}
public static String[] getBatches(String dir) {
return (new File(dir)).list(new PrefixFilenameFilter(
Prefix.batchDataDir));
}
public static long getTimestamp(String batchFolderName) {
return Long.parseLong(batchFolderName.replaceFirst(Prefix.batchDataDir,
""));
}
/*
* METRIC data
*/
public static String getMetricDataDir(String dir, String name) {
return dir + Prefix.metricDataDir + name + Dir.delimiter;
}
public static String getMetricDataDir(String dir, int run, long timestamp,
String name) {
return Dir.getBatchDataDir(dir, run, timestamp) + Prefix.metricDataDir
+ name + Dir.delimiter;
}
public static String[] getMetrics(String dir) {
return (new File(dir)).list(new PrefixFilenameFilter(
Prefix.metricDataDir));
}
public static String getMetricName(String metricFolderName) {
return metricFolderName.replaceFirst(Prefix.metricDataDir, "");
}
}
| true | true | public static String getAggregatedMetricDataDir(String dir, long timestamp,
String name) {
return Dir.getAggregationBatchDir(dir, timestamp) + name
+ Dir.delimiter;
}
| public static String getAggregatedMetricDataDir(String dir, long timestamp,
String name) {
return Dir.getAggregationBatchDir(dir, timestamp)
+ Prefix.metricDataDir + name + Dir.delimiter;
}
|
diff --git a/ChanServ/LogCleaner.java b/ChanServ/LogCleaner.java
index ae4ef86..4998710 100644
--- a/ChanServ/LogCleaner.java
+++ b/ChanServ/LogCleaner.java
@@ -1,158 +1,159 @@
/*
* Created on 25.12.2007
*
* This class is involved in moving logs from files on disk to a database,
* where they can be more easily accessed by TASServer web interface.
*
* This is the procedure it follows:
* 1) Check if temp_logs folder exists. If not, create it.
* 2) Check if there are any files in temp_logs folder.
* If there are, skip to 4), or else continue with 4).
* 3) Lock access to logs globally in ChanServ, then move
* all log files to temp_logs folder.
* 4) Transfer all logs from temp_logs folder to a database
* and remove them from disk.
*
*/
/**
* @author Betalord
*
*/
import java.sql.SQLException;
import java.util.*;
import java.io.*;
import java.sql.*;
public class LogCleaner extends TimerTask {
final static String TEMP_LOGS_FOLDER = "./temp_logs";
public void run() {
// create temp log folder if it doesn't already exist:
File tempFolder = new File(TEMP_LOGS_FOLDER);
if (!tempFolder.exists()) {
boolean success = (tempFolder.mkdir());
if (!success){
Log.log("Error: unable to create folder: " + TEMP_LOGS_FOLDER);
return ;
} else {
Log.log("Created missing folder: " + TEMP_LOGS_FOLDER);
}
}
// check if temp folder is empty (it should be):
if (tempFolder.listFiles().length == 0) {
// OK temp folder is empty, so now we will move all log files to this folder
// lock writing logs to disk while we are moving them to temp folder:
try {
Log.logToDiskLock.acquire();
File sourceFolder = new File(Log.LOG_FOLDER);
File files[] = sourceFolder.listFiles();
if (files.length == 0) {
// great, we have no new logs since last time we checked, so we can exit immediately
return ;
}
// move each file to temp folder:
for(int i = 0; i < files.length; i++) {
File source = files[i];
if (!source.isFile()) continue;
if (!source.getName().startsWith("#")) continue; // only move channel logs to database
// move file to new folder:
if (!source.renameTo(new File(tempFolder, source.getName()))) {
Log.error("Unable to move file " + source.toString() + " to " + tempFolder.toString());
return ;
}
}
} catch (InterruptedException e) {
return ; // this should not happen!
} finally {
Log.logToDiskLock.release();
}
}
// now comes the part when we transfer all logs from temp folder to the database:
File[] files = tempFolder.listFiles();
for(int i = 0; i < files.length; i++) {
File file = files[i];
+ String name = file.getName().substring(0, file.getName().length() - 4); // remove ".log" from the end of the file name
try {
- if (!ChanServ.database.doesTableExist(file.getName())) {
- boolean result= ChanServ.database.execUpdate("CREATE TABLE '" + file.getName() + "' (" + Misc.EOL +
+ if (!ChanServ.database.doesTableExist(name)) {
+ boolean result= ChanServ.database.execUpdate("CREATE TABLE '" + name + "' (" + Misc.EOL +
"id INT NOT NULL AUTO_INCREMENT, " + Misc.EOL +
"stamp timestamp NOT NULL, " + Misc.EOL +
"line TEXT NOT NULL) ENGINE=InnoDB DEFAULT CHARSET=utf8;");
if (!result) {
- Log.error("Unable to create table '" + file.getName() + "' in the database!");
+ Log.error("Unable to create table '" + name + "' in the database!");
return ;
}
}
String update = "start transaction;" + Misc.EOL;
BufferedReader in = new BufferedReader(new FileReader(file));
String line;
int lineCount = 0;
while ((line = in.readLine()) != null) {
if (line.trim().equals("")) continue; // empty line
long stamp;
try {
stamp = Long.parseLong(line.substring(0, line.indexOf(' ')));
} catch (NumberFormatException e) {
Log.error("Line from log file " + file.getName() + " does not contain time stamp. Line is: \"" + line + "\"");
return ;
}
if (lineCount == 0) {
- update += "INSERT INTO '" + file.getName() + "' (stamp, line) values (" + stamp + ", '" + line.substring(line.indexOf(' ')+1, line.length()) + "')";
+ update += "INSERT INTO '" + name + "' (stamp, line) values (" + stamp + ", '" + line.substring(line.indexOf(' ')+1, line.length()) + "')";
} else {
update += ","+ Misc.EOL +
"(" + stamp + ", '" + line.substring(line.indexOf(' ')+1, line.length()) + "')";
}
lineCount++;
}
in.close();
update += ";" + Misc.EOL + "commit;";
if (lineCount == 0) {
Log.error("Log file is empty: " + file.getName());
// delete the file if possible:
if (file.delete()) {
Log.log("Empty log file was successfully deleted.");
} else {
Log.error("Unable to delete empty log file: " + file.getName());
}
return ;
}
if (!ChanServ.database.execUpdate(update)) {
Log.error("Unable to execute transaction on the database for the log file " + file.getName());
return ;
}
// finally, delete the file:
if (!file.delete()) {
Log.error("Unable to delete log file, which was just transfered to the database: " + file.getName());
return ;
}
} catch (IOException e) {
Log.error("Unable to read contents of file " + file.toString());
return ;
} catch (SQLException e) {
Log.error("Unable to access database. Error description: " + e.toString());
e.printStackTrace();
return ;
}
}
}
}
| false | true | public void run() {
// create temp log folder if it doesn't already exist:
File tempFolder = new File(TEMP_LOGS_FOLDER);
if (!tempFolder.exists()) {
boolean success = (tempFolder.mkdir());
if (!success){
Log.log("Error: unable to create folder: " + TEMP_LOGS_FOLDER);
return ;
} else {
Log.log("Created missing folder: " + TEMP_LOGS_FOLDER);
}
}
// check if temp folder is empty (it should be):
if (tempFolder.listFiles().length == 0) {
// OK temp folder is empty, so now we will move all log files to this folder
// lock writing logs to disk while we are moving them to temp folder:
try {
Log.logToDiskLock.acquire();
File sourceFolder = new File(Log.LOG_FOLDER);
File files[] = sourceFolder.listFiles();
if (files.length == 0) {
// great, we have no new logs since last time we checked, so we can exit immediately
return ;
}
// move each file to temp folder:
for(int i = 0; i < files.length; i++) {
File source = files[i];
if (!source.isFile()) continue;
if (!source.getName().startsWith("#")) continue; // only move channel logs to database
// move file to new folder:
if (!source.renameTo(new File(tempFolder, source.getName()))) {
Log.error("Unable to move file " + source.toString() + " to " + tempFolder.toString());
return ;
}
}
} catch (InterruptedException e) {
return ; // this should not happen!
} finally {
Log.logToDiskLock.release();
}
}
// now comes the part when we transfer all logs from temp folder to the database:
File[] files = tempFolder.listFiles();
for(int i = 0; i < files.length; i++) {
File file = files[i];
try {
if (!ChanServ.database.doesTableExist(file.getName())) {
boolean result= ChanServ.database.execUpdate("CREATE TABLE '" + file.getName() + "' (" + Misc.EOL +
"id INT NOT NULL AUTO_INCREMENT, " + Misc.EOL +
"stamp timestamp NOT NULL, " + Misc.EOL +
"line TEXT NOT NULL) ENGINE=InnoDB DEFAULT CHARSET=utf8;");
if (!result) {
Log.error("Unable to create table '" + file.getName() + "' in the database!");
return ;
}
}
String update = "start transaction;" + Misc.EOL;
BufferedReader in = new BufferedReader(new FileReader(file));
String line;
int lineCount = 0;
while ((line = in.readLine()) != null) {
if (line.trim().equals("")) continue; // empty line
long stamp;
try {
stamp = Long.parseLong(line.substring(0, line.indexOf(' ')));
} catch (NumberFormatException e) {
Log.error("Line from log file " + file.getName() + " does not contain time stamp. Line is: \"" + line + "\"");
return ;
}
if (lineCount == 0) {
update += "INSERT INTO '" + file.getName() + "' (stamp, line) values (" + stamp + ", '" + line.substring(line.indexOf(' ')+1, line.length()) + "')";
} else {
update += ","+ Misc.EOL +
"(" + stamp + ", '" + line.substring(line.indexOf(' ')+1, line.length()) + "')";
}
lineCount++;
}
in.close();
update += ";" + Misc.EOL + "commit;";
if (lineCount == 0) {
Log.error("Log file is empty: " + file.getName());
// delete the file if possible:
if (file.delete()) {
Log.log("Empty log file was successfully deleted.");
} else {
Log.error("Unable to delete empty log file: " + file.getName());
}
return ;
}
if (!ChanServ.database.execUpdate(update)) {
Log.error("Unable to execute transaction on the database for the log file " + file.getName());
return ;
}
// finally, delete the file:
if (!file.delete()) {
Log.error("Unable to delete log file, which was just transfered to the database: " + file.getName());
return ;
}
} catch (IOException e) {
Log.error("Unable to read contents of file " + file.toString());
return ;
} catch (SQLException e) {
Log.error("Unable to access database. Error description: " + e.toString());
e.printStackTrace();
return ;
}
}
}
| public void run() {
// create temp log folder if it doesn't already exist:
File tempFolder = new File(TEMP_LOGS_FOLDER);
if (!tempFolder.exists()) {
boolean success = (tempFolder.mkdir());
if (!success){
Log.log("Error: unable to create folder: " + TEMP_LOGS_FOLDER);
return ;
} else {
Log.log("Created missing folder: " + TEMP_LOGS_FOLDER);
}
}
// check if temp folder is empty (it should be):
if (tempFolder.listFiles().length == 0) {
// OK temp folder is empty, so now we will move all log files to this folder
// lock writing logs to disk while we are moving them to temp folder:
try {
Log.logToDiskLock.acquire();
File sourceFolder = new File(Log.LOG_FOLDER);
File files[] = sourceFolder.listFiles();
if (files.length == 0) {
// great, we have no new logs since last time we checked, so we can exit immediately
return ;
}
// move each file to temp folder:
for(int i = 0; i < files.length; i++) {
File source = files[i];
if (!source.isFile()) continue;
if (!source.getName().startsWith("#")) continue; // only move channel logs to database
// move file to new folder:
if (!source.renameTo(new File(tempFolder, source.getName()))) {
Log.error("Unable to move file " + source.toString() + " to " + tempFolder.toString());
return ;
}
}
} catch (InterruptedException e) {
return ; // this should not happen!
} finally {
Log.logToDiskLock.release();
}
}
// now comes the part when we transfer all logs from temp folder to the database:
File[] files = tempFolder.listFiles();
for(int i = 0; i < files.length; i++) {
File file = files[i];
String name = file.getName().substring(0, file.getName().length() - 4); // remove ".log" from the end of the file name
try {
if (!ChanServ.database.doesTableExist(name)) {
boolean result= ChanServ.database.execUpdate("CREATE TABLE '" + name + "' (" + Misc.EOL +
"id INT NOT NULL AUTO_INCREMENT, " + Misc.EOL +
"stamp timestamp NOT NULL, " + Misc.EOL +
"line TEXT NOT NULL) ENGINE=InnoDB DEFAULT CHARSET=utf8;");
if (!result) {
Log.error("Unable to create table '" + name + "' in the database!");
return ;
}
}
String update = "start transaction;" + Misc.EOL;
BufferedReader in = new BufferedReader(new FileReader(file));
String line;
int lineCount = 0;
while ((line = in.readLine()) != null) {
if (line.trim().equals("")) continue; // empty line
long stamp;
try {
stamp = Long.parseLong(line.substring(0, line.indexOf(' ')));
} catch (NumberFormatException e) {
Log.error("Line from log file " + file.getName() + " does not contain time stamp. Line is: \"" + line + "\"");
return ;
}
if (lineCount == 0) {
update += "INSERT INTO '" + name + "' (stamp, line) values (" + stamp + ", '" + line.substring(line.indexOf(' ')+1, line.length()) + "')";
} else {
update += ","+ Misc.EOL +
"(" + stamp + ", '" + line.substring(line.indexOf(' ')+1, line.length()) + "')";
}
lineCount++;
}
in.close();
update += ";" + Misc.EOL + "commit;";
if (lineCount == 0) {
Log.error("Log file is empty: " + file.getName());
// delete the file if possible:
if (file.delete()) {
Log.log("Empty log file was successfully deleted.");
} else {
Log.error("Unable to delete empty log file: " + file.getName());
}
return ;
}
if (!ChanServ.database.execUpdate(update)) {
Log.error("Unable to execute transaction on the database for the log file " + file.getName());
return ;
}
// finally, delete the file:
if (!file.delete()) {
Log.error("Unable to delete log file, which was just transfered to the database: " + file.getName());
return ;
}
} catch (IOException e) {
Log.error("Unable to read contents of file " + file.toString());
return ;
} catch (SQLException e) {
Log.error("Unable to access database. Error description: " + e.toString());
e.printStackTrace();
return ;
}
}
}
|
diff --git a/msv/src/com/sun/msv/driver/textui/Driver.java b/msv/src/com/sun/msv/driver/textui/Driver.java
index 63d4f102..5c52f45a 100644
--- a/msv/src/com/sun/msv/driver/textui/Driver.java
+++ b/msv/src/com/sun/msv/driver/textui/Driver.java
@@ -1,336 +1,339 @@
/*
* @(#)$Id$
*
* Copyright 2001 Sun Microsystems, Inc. All Rights Reserved.
*
* This software is the proprietary information of Sun Microsystems, Inc.
* Use is subject to license terms.
*
*/
package com.sun.tranquilo.driver.textui;
import javax.xml.parsers.*;
import java.io.File;
import com.sun.tranquilo.grammar.trex.util.TREXPatternPrinter;
import com.sun.tranquilo.grammar.trex.*;
import com.sun.tranquilo.grammar.relax.*;
import com.sun.tranquilo.grammar.*;
import com.sun.tranquilo.reader.util.GrammarLoader;
import com.sun.tranquilo.relaxns.grammar.RELAXGrammar;
import com.sun.tranquilo.relaxns.verifier.SchemaProviderImpl;
import com.sun.tranquilo.verifier.*;
import com.sun.tranquilo.verifier.regexp.trex.TREXDocumentDeclaration;
import com.sun.tranquilo.verifier.util.VerificationErrorHandlerImpl;
import org.iso_relax.dispatcher.Dispatcher;
import org.iso_relax.dispatcher.SchemaProvider;
import org.iso_relax.dispatcher.impl.DispatcherImpl;
import org.xml.sax.*;
import java.util.*;
/**
* command line Verifier.
*
* @author <a href="mailto:[email protected]">Kohsuke KAWAGUCHI</a>
*/
public class Driver
{
static SAXParserFactory factory;
public static void main( String[] args ) throws Exception
{
final Vector fileNames = new Vector();
String grammarName = null;
boolean dump=false;
boolean verbose = false;
boolean warning = false;
boolean dtdValidation=false;
if( args.length==0 )
{
System.out.println( localize(MSG_USAGE) );
return;
}
for( int i=0; i<args.length; i++ )
{
if( args[i].equalsIgnoreCase("-dtd") ) dtdValidation = true;
else
if( args[i].equalsIgnoreCase("-dump") ) dump = true;
else
if( args[i].equalsIgnoreCase("-debug") ) Debug.debug = true;
else
if( args[i].equalsIgnoreCase("-xerces") )
factory = (SAXParserFactory)Class.forName("org.apache.xerces.jaxp.SAXParserFactoryImpl").newInstance();
else
if( args[i].equalsIgnoreCase("-crimson") )
factory = (SAXParserFactory)Class.forName("org.apache.crimson.jaxp.SAXParserFactoryImpl").newInstance();
else
if( args[i].equalsIgnoreCase("-verbose") ) verbose = true;
else
if( args[i].equalsIgnoreCase("-warning") ) warning = true;
else
if( args[i].equalsIgnoreCase("-version") )
{
System.out.println("Tranquilo Ver."+
java.util.ResourceBundle.getBundle("version").getString("version") );
return;
}
else
{
if( args[i].charAt(0)=='-' )
{
System.err.println(localize(MSG_UNRECOGNIZED_OPTION,args[i]));
return;
}
if( grammarName==null ) grammarName = args[i];
else
{
fileNames.add(args[i]);
}
}
}
if( factory==null )
factory = (SAXParserFactory)Class.forName("org.apache.xerces.jaxp.SAXParserFactoryImpl").newInstance();
if( verbose )
System.out.println( localize( MSG_PARSER, factory.getClass().getName()) );
factory.setNamespaceAware(true);
factory.setValidating(dtdValidation);
if( dtdValidation && verbose )
System.out.println( localize( MSG_DTDVALIDATION ) );
if( !dtdValidation )
try
{
factory.setFeature("http://xml.org/sax/features/validation",false);
factory.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd",false);
}
catch(Exception e)
{
// e.printStackTrace();
if( verbose )
System.out.println( localize( MSG_FAILED_TO_IGNORE_EXTERNAL_DTD ) );
}
InputSource is = getInputSource(grammarName);
// parse schema
//--------------------
final long stime = System.currentTimeMillis();
System.out.println( localize(MSG_START_PARSING_GRAMMAR) );
// Grammar grammar = GrammarLoader.loadSchema(is,new DebugController(warning),factory);
Grammar grammar=null;
try {
grammar = GrammarLoader.loadSchema(is,new DebugController(warning),factory);
+ } catch(SAXParseException spe) {
+ ; // this error is already reported.
} catch(SAXException se ) {
- se.getException().printStackTrace();
+ if( se.getException()!=null ) throw se.getException();
+ throw se;
}
if( grammar==null ) {
System.out.println( localize(ERR_LOAD_GRAMMAR) );
return;
}
long parsingTime = System.currentTimeMillis();
if( verbose )
System.out.println( localize( MSG_PARSING_TIME, new Long(parsingTime-stime) ) );
if(dump)
{
if( grammar instanceof RELAXModule )
dumpRELAXModule( (RELAXModule)grammar );
else
if( grammar instanceof RELAXGrammar )
dumpRELAXGrammar( (RELAXGrammar)grammar );
else
if( grammar instanceof TREXGrammar )
dumpTREX( (TREXGrammar)grammar );
return;
}
// validate documents
//--------------------
DocumentVerifier verifier;
if( grammar instanceof RELAXGrammar )
// use divide&validate framework to validate document
verifier = new RELAXNSVerifier( new SchemaProviderImpl((RELAXGrammar)grammar) );
else
// validate normally by using Verifier.
verifier = new SimpleVerifier( new TREXDocumentDeclaration(grammar) );
for( int i=0; i<fileNames.size(); i++ ) {
final String instName = (String)fileNames.elementAt(i);
System.out.println( localize( MSG_VALIDATING, instName) );
if(verifier.verify(getInputSource(instName)))
System.out.println(localize(MSG_VALID));
else
System.out.println(localize(MSG_INVALID));
if( i!=fileNames.size()-1 )
System.out.println("--------------------------------------");
}
if( verbose )
System.out.println( localize( MSG_VALIDATION_TIME, new Long(System.currentTimeMillis()-parsingTime) ) );
}
public static void dumpTREX( TREXGrammar g ) throws Exception
{
System.out.println("*** start ***");
System.out.println(TREXPatternPrinter.printFragment(g.start));
System.out.println("*** others ***");
System.out.print(
TREXPatternPrinter.fragmentInstance.printRefContainer(
g.namedPatterns ) );
}
public static void dumpRELAXModule( RELAXModule m ) throws Exception
{
System.out.println("*** top level ***");
System.out.println(TREXPatternPrinter.printFragment(m.topLevel));
System.out.println("\n $$$$$$[ " + m.targetNamespace + " ]$$$$$$");
System.out.println("*** elementRule ***");
System.out.print(
TREXPatternPrinter.fragmentInstance.printRefContainer(
m.elementRules ) );
System.out.println("*** hedgeRule ***");
System.out.print(
TREXPatternPrinter.fragmentInstance.printRefContainer(
m.hedgeRules ) );
System.out.println("*** attPool ***");
System.out.print(
TREXPatternPrinter.fragmentInstance.printRefContainer(
m.attPools ) );
System.out.println("*** tag ***");
System.out.print(
TREXPatternPrinter.fragmentInstance.printRefContainer(
m.tags ) );
}
public static void dumpRELAXGrammar( RELAXGrammar m ) throws Exception {
System.out.println("operation is not implemented yet.");
}
/** acts as a function closure to validate a document. */
private interface DocumentVerifier {
boolean verify( InputSource instance ) throws Exception;
}
/** validates a document by using divide& validate framework. */
private static class RELAXNSVerifier implements DocumentVerifier {
private final SchemaProvider sp;
RELAXNSVerifier( SchemaProvider sp ) { this.sp=sp; }
public boolean verify( InputSource instance ) throws Exception {
XMLReader p = factory.newSAXParser().getXMLReader();
Dispatcher dispatcher = new DispatcherImpl(sp);
dispatcher.attachXMLReader(p);
ReportErrorHandler errorHandler = new ReportErrorHandler();
dispatcher.setErrorHandler( errorHandler );
try {
p.parse(instance);
return !errorHandler.hadError;
} catch( com.sun.tranquilo.verifier.ValidationUnrecoverableException vv ) {
System.out.println(localize(MSG_BAILOUT));
} catch( SAXParseException se ) {
; // error is already reported by ErrorHandler
} catch( SAXException e ) {
e.getException().printStackTrace();
}
return false;
}
}
private static class SimpleVerifier implements DocumentVerifier {
private final DocumentDeclaration docDecl;
SimpleVerifier( DocumentDeclaration docDecl ) { this.docDecl = docDecl; }
public boolean verify( InputSource instance ) throws Exception {
XMLReader p = factory.newSAXParser().getXMLReader();
ReportErrorHandler reh = new ReportErrorHandler();
Verifier v = new Verifier( docDecl, reh );
p.setDTDHandler(v);
p.setContentHandler(v);
p.setErrorHandler(reh);
try {
p.parse( instance );
return v.isValid();
} catch( com.sun.tranquilo.verifier.ValidationUnrecoverableException vv ) {
System.out.println(localize(MSG_BAILOUT));
} catch( SAXParseException se ) {
; // error is already reported by ErrorHandler
} catch( SAXException e ) {
e.getException().printStackTrace();
}
return false;
}
}
private static InputSource getInputSource( String fileOrURL )
{
try
{// try it as a file
InputSource is = new InputSource(new java.io.FileInputStream(fileOrURL));
// is.setSystemId(new File(fileOrURL).getAbsolutePath());
// this has to be getCanonicalPath, otherwise
// java cannot resolve relative paths like "c:work.rlx" (in Windows).
is.setSystemId(new File(fileOrURL).getCanonicalPath());
return is;
}
catch( Exception e )
{// try it as an URL
return new InputSource(fileOrURL);
}
}
public static String localize( String propertyName, Object[] args )
{
String format = java.util.ResourceBundle.getBundle(
"com.sun.tranquilo.driver.textui.Messages").getString(propertyName);
return java.text.MessageFormat.format(format, args );
}
public static String localize( String prop )
{ return localize(prop,null); }
public static String localize( String prop, Object arg1 )
{ return localize(prop,new Object[]{arg1}); }
public static String localize( String prop, Object arg1, Object arg2 )
{ return localize(prop,new Object[]{arg1,arg2}); }
public static final String MSG_DTDVALIDATION = "Driver.DTDValidation";
public static final String MSG_PARSER = "Driver.Parser";
public static final String MSG_USAGE = "Driver.Usage";
public static final String MSG_UNRECOGNIZED_OPTION ="Driver.UnrecognizedOption";
public static final String MSG_START_PARSING_GRAMMAR="Driver.StartParsingGrammar";
public static final String MSG_PARSING_TIME = "Driver.ParsingTime";
public static final String MSG_VALIDATING = "Driver.Validating";
public static final String MSG_VALIDATION_TIME = "Driver.ValidationTime";
public static final String MSG_VALID = "Driver.Valid";
public static final String MSG_INVALID = "Driver.Invalid";
public static final String ERR_LOAD_GRAMMAR = "Driver.ErrLoadGrammar";
public static final String MSG_BAILOUT = "Driver.BailOut";
public static final String MSG_FAILED_TO_IGNORE_EXTERNAL_DTD ="Driver.FailedToIgnoreExternalDTD";
// public static final String MSG_SNIFF_SCHEMA = "Driver.SniffSchema";
// public static final String MSG_UNKNOWN_SCHEMA = "Driver.UnknownSchema";
}
| false | true | public static void main( String[] args ) throws Exception
{
final Vector fileNames = new Vector();
String grammarName = null;
boolean dump=false;
boolean verbose = false;
boolean warning = false;
boolean dtdValidation=false;
if( args.length==0 )
{
System.out.println( localize(MSG_USAGE) );
return;
}
for( int i=0; i<args.length; i++ )
{
if( args[i].equalsIgnoreCase("-dtd") ) dtdValidation = true;
else
if( args[i].equalsIgnoreCase("-dump") ) dump = true;
else
if( args[i].equalsIgnoreCase("-debug") ) Debug.debug = true;
else
if( args[i].equalsIgnoreCase("-xerces") )
factory = (SAXParserFactory)Class.forName("org.apache.xerces.jaxp.SAXParserFactoryImpl").newInstance();
else
if( args[i].equalsIgnoreCase("-crimson") )
factory = (SAXParserFactory)Class.forName("org.apache.crimson.jaxp.SAXParserFactoryImpl").newInstance();
else
if( args[i].equalsIgnoreCase("-verbose") ) verbose = true;
else
if( args[i].equalsIgnoreCase("-warning") ) warning = true;
else
if( args[i].equalsIgnoreCase("-version") )
{
System.out.println("Tranquilo Ver."+
java.util.ResourceBundle.getBundle("version").getString("version") );
return;
}
else
{
if( args[i].charAt(0)=='-' )
{
System.err.println(localize(MSG_UNRECOGNIZED_OPTION,args[i]));
return;
}
if( grammarName==null ) grammarName = args[i];
else
{
fileNames.add(args[i]);
}
}
}
if( factory==null )
factory = (SAXParserFactory)Class.forName("org.apache.xerces.jaxp.SAXParserFactoryImpl").newInstance();
if( verbose )
System.out.println( localize( MSG_PARSER, factory.getClass().getName()) );
factory.setNamespaceAware(true);
factory.setValidating(dtdValidation);
if( dtdValidation && verbose )
System.out.println( localize( MSG_DTDVALIDATION ) );
if( !dtdValidation )
try
{
factory.setFeature("http://xml.org/sax/features/validation",false);
factory.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd",false);
}
catch(Exception e)
{
// e.printStackTrace();
if( verbose )
System.out.println( localize( MSG_FAILED_TO_IGNORE_EXTERNAL_DTD ) );
}
InputSource is = getInputSource(grammarName);
// parse schema
//--------------------
final long stime = System.currentTimeMillis();
System.out.println( localize(MSG_START_PARSING_GRAMMAR) );
// Grammar grammar = GrammarLoader.loadSchema(is,new DebugController(warning),factory);
Grammar grammar=null;
try {
grammar = GrammarLoader.loadSchema(is,new DebugController(warning),factory);
} catch(SAXException se ) {
se.getException().printStackTrace();
}
if( grammar==null ) {
System.out.println( localize(ERR_LOAD_GRAMMAR) );
return;
}
long parsingTime = System.currentTimeMillis();
if( verbose )
System.out.println( localize( MSG_PARSING_TIME, new Long(parsingTime-stime) ) );
if(dump)
{
if( grammar instanceof RELAXModule )
dumpRELAXModule( (RELAXModule)grammar );
else
if( grammar instanceof RELAXGrammar )
dumpRELAXGrammar( (RELAXGrammar)grammar );
else
if( grammar instanceof TREXGrammar )
dumpTREX( (TREXGrammar)grammar );
return;
}
// validate documents
//--------------------
DocumentVerifier verifier;
if( grammar instanceof RELAXGrammar )
// use divide&validate framework to validate document
verifier = new RELAXNSVerifier( new SchemaProviderImpl((RELAXGrammar)grammar) );
else
// validate normally by using Verifier.
verifier = new SimpleVerifier( new TREXDocumentDeclaration(grammar) );
for( int i=0; i<fileNames.size(); i++ ) {
final String instName = (String)fileNames.elementAt(i);
System.out.println( localize( MSG_VALIDATING, instName) );
if(verifier.verify(getInputSource(instName)))
System.out.println(localize(MSG_VALID));
else
System.out.println(localize(MSG_INVALID));
if( i!=fileNames.size()-1 )
System.out.println("--------------------------------------");
}
if( verbose )
System.out.println( localize( MSG_VALIDATION_TIME, new Long(System.currentTimeMillis()-parsingTime) ) );
}
| public static void main( String[] args ) throws Exception
{
final Vector fileNames = new Vector();
String grammarName = null;
boolean dump=false;
boolean verbose = false;
boolean warning = false;
boolean dtdValidation=false;
if( args.length==0 )
{
System.out.println( localize(MSG_USAGE) );
return;
}
for( int i=0; i<args.length; i++ )
{
if( args[i].equalsIgnoreCase("-dtd") ) dtdValidation = true;
else
if( args[i].equalsIgnoreCase("-dump") ) dump = true;
else
if( args[i].equalsIgnoreCase("-debug") ) Debug.debug = true;
else
if( args[i].equalsIgnoreCase("-xerces") )
factory = (SAXParserFactory)Class.forName("org.apache.xerces.jaxp.SAXParserFactoryImpl").newInstance();
else
if( args[i].equalsIgnoreCase("-crimson") )
factory = (SAXParserFactory)Class.forName("org.apache.crimson.jaxp.SAXParserFactoryImpl").newInstance();
else
if( args[i].equalsIgnoreCase("-verbose") ) verbose = true;
else
if( args[i].equalsIgnoreCase("-warning") ) warning = true;
else
if( args[i].equalsIgnoreCase("-version") )
{
System.out.println("Tranquilo Ver."+
java.util.ResourceBundle.getBundle("version").getString("version") );
return;
}
else
{
if( args[i].charAt(0)=='-' )
{
System.err.println(localize(MSG_UNRECOGNIZED_OPTION,args[i]));
return;
}
if( grammarName==null ) grammarName = args[i];
else
{
fileNames.add(args[i]);
}
}
}
if( factory==null )
factory = (SAXParserFactory)Class.forName("org.apache.xerces.jaxp.SAXParserFactoryImpl").newInstance();
if( verbose )
System.out.println( localize( MSG_PARSER, factory.getClass().getName()) );
factory.setNamespaceAware(true);
factory.setValidating(dtdValidation);
if( dtdValidation && verbose )
System.out.println( localize( MSG_DTDVALIDATION ) );
if( !dtdValidation )
try
{
factory.setFeature("http://xml.org/sax/features/validation",false);
factory.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd",false);
}
catch(Exception e)
{
// e.printStackTrace();
if( verbose )
System.out.println( localize( MSG_FAILED_TO_IGNORE_EXTERNAL_DTD ) );
}
InputSource is = getInputSource(grammarName);
// parse schema
//--------------------
final long stime = System.currentTimeMillis();
System.out.println( localize(MSG_START_PARSING_GRAMMAR) );
// Grammar grammar = GrammarLoader.loadSchema(is,new DebugController(warning),factory);
Grammar grammar=null;
try {
grammar = GrammarLoader.loadSchema(is,new DebugController(warning),factory);
} catch(SAXParseException spe) {
; // this error is already reported.
} catch(SAXException se ) {
if( se.getException()!=null ) throw se.getException();
throw se;
}
if( grammar==null ) {
System.out.println( localize(ERR_LOAD_GRAMMAR) );
return;
}
long parsingTime = System.currentTimeMillis();
if( verbose )
System.out.println( localize( MSG_PARSING_TIME, new Long(parsingTime-stime) ) );
if(dump)
{
if( grammar instanceof RELAXModule )
dumpRELAXModule( (RELAXModule)grammar );
else
if( grammar instanceof RELAXGrammar )
dumpRELAXGrammar( (RELAXGrammar)grammar );
else
if( grammar instanceof TREXGrammar )
dumpTREX( (TREXGrammar)grammar );
return;
}
// validate documents
//--------------------
DocumentVerifier verifier;
if( grammar instanceof RELAXGrammar )
// use divide&validate framework to validate document
verifier = new RELAXNSVerifier( new SchemaProviderImpl((RELAXGrammar)grammar) );
else
// validate normally by using Verifier.
verifier = new SimpleVerifier( new TREXDocumentDeclaration(grammar) );
for( int i=0; i<fileNames.size(); i++ ) {
final String instName = (String)fileNames.elementAt(i);
System.out.println( localize( MSG_VALIDATING, instName) );
if(verifier.verify(getInputSource(instName)))
System.out.println(localize(MSG_VALID));
else
System.out.println(localize(MSG_INVALID));
if( i!=fileNames.size()-1 )
System.out.println("--------------------------------------");
}
if( verbose )
System.out.println( localize( MSG_VALIDATION_TIME, new Long(System.currentTimeMillis()-parsingTime) ) );
}
|
diff --git a/src/minecraft/assemblyline/common/machine/belt/TileEntityConveyorBelt.java b/src/minecraft/assemblyline/common/machine/belt/TileEntityConveyorBelt.java
index a22a8d84..fa57016d 100644
--- a/src/minecraft/assemblyline/common/machine/belt/TileEntityConveyorBelt.java
+++ b/src/minecraft/assemblyline/common/machine/belt/TileEntityConveyorBelt.java
@@ -1,297 +1,297 @@
package assemblyline.common.machine.belt;
import java.util.EnumSet;
import java.util.List;
import net.minecraft.entity.Entity;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.network.INetworkManager;
import net.minecraft.network.packet.Packet;
import net.minecraft.network.packet.Packet250CustomPayload;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.AxisAlignedBB;
import net.minecraftforge.common.ForgeDirection;
import universalelectricity.core.electricity.ElectricityConnections;
import universalelectricity.core.vector.Vector3;
import universalelectricity.prefab.implement.IRotatable;
import universalelectricity.prefab.network.IPacketReceiver;
import universalelectricity.prefab.network.PacketManager;
import assemblyline.api.IBelt;
import assemblyline.common.AssemblyLine;
import assemblyline.common.machine.TileEntityAssemblyNetwork;
import com.google.common.io.ByteArrayDataInput;
import cpw.mods.fml.common.FMLCommonHandler;
import cpw.mods.fml.relauncher.Side;
public class TileEntityConveyorBelt extends TileEntityAssemblyNetwork implements IPacketReceiver, IBelt, IRotatable
{
public enum SlantType
{
NONE, UP, DOWN
}
public static final int NUM_FRAMES = 13;
/**
* Joules required to run this thing.
*/
public final float acceleration = 0.01f;
public final float maxSpeed = 0.1f;
public float wheelRotation = 0;
public int animFrame = 0; // this is from 0 to 15
private SlantType slantType = SlantType.NONE;
public TileEntityConveyorBelt()
{
super();
//ElectricityConnections.registerConnector(this, EnumSet.of(ForgeDirection.DOWN, ForgeDirection.EAST, ForgeDirection.WEST, ForgeDirection.NORTH, ForgeDirection.SOUTH));
ElectricityConnections.registerConnector(this, EnumSet.of(ForgeDirection.DOWN));
}
/**
* This function is overriden to allow conveyor belts to power belts that are diagonally going
* up.
*/
@Override
public void updatePowerTransferRange()
{
int maximumTransferRange = 0;
for (int i = 0; i < 6; i++)
{
ForgeDirection direction = ForgeDirection.getOrientation(i);
TileEntity tileEntity = worldObj.getBlockTileEntity(this.xCoord + direction.offsetX, this.yCoord + direction.offsetY, this.zCoord + direction.offsetZ);
if (tileEntity != null)
{
if (tileEntity instanceof TileEntityAssemblyNetwork)
{
TileEntityAssemblyNetwork assemblyNetwork = (TileEntityAssemblyNetwork) tileEntity;
if (assemblyNetwork.powerTransferRange > maximumTransferRange)
{
maximumTransferRange = assemblyNetwork.powerTransferRange;
}
}
}
}
for (int d = 0; d <= 1; d++)
{
ForgeDirection direction = this.getDirection();
- //if (d == 1)
+ if (d == 1)
{
direction = direction.getOpposite();
}
- for (int i = -1; i < 1; i++)
+ for (int i = -1; i <= 1; i++)
{
TileEntity tileEntity = worldObj.getBlockTileEntity(this.xCoord + direction.offsetX, this.yCoord + i, this.zCoord + direction.offsetZ);
if (tileEntity != null)
{
if (tileEntity instanceof TileEntityAssemblyNetwork)
{
TileEntityAssemblyNetwork assemblyNetwork = (TileEntityAssemblyNetwork) tileEntity;
if (assemblyNetwork.powerTransferRange > maximumTransferRange)
{
maximumTransferRange = assemblyNetwork.powerTransferRange;
}
}
}
}
}
this.powerTransferRange = Math.max(maximumTransferRange - 1, 0);
}
@Override
public void onUpdate()
{
if (FMLCommonHandler.instance().getEffectiveSide() == Side.SERVER && this.ticks % 20 == 0)
{
PacketManager.sendPacketToClients(this.getDescriptionPacket());
}
if (this.isRunning())
{
//System.out.println(FMLCommonHandler.instance().getEffectiveSide());
this.wheelRotation += 40;
if (this.wheelRotation > 360)
this.wheelRotation = 0;
float wheelRotPct = wheelRotation / 360f;
animFrame = (int) (wheelRotPct * NUM_FRAMES); // sync the animation
if (animFrame < 0)
animFrame = 0;
if (animFrame > NUM_FRAMES)
animFrame = NUM_FRAMES;
}
}
@Override
protected int getMaxTransferRange()
{
return 20;
}
@Override
public Packet getDescriptionPacket()
{
return PacketManager.getPacket(AssemblyLine.CHANNEL, this, this.wattsReceived, this.slantType.ordinal());
}
public SlantType getSlant()
{
return slantType;
}
public void setSlant(SlantType slantType)
{
if (slantType == null)
{
slantType = SlantType.NONE;
}
this.slantType = slantType;
PacketManager.sendPacketToClients(this.getDescriptionPacket(), this.worldObj);
}
/**
* Is this belt in the front of a conveyor line? Used for rendering.
*/
public boolean getIsFirstBelt()
{
ForgeDirection front = this.getDirection();
ForgeDirection back = this.getDirection().getOpposite();
TileEntity fBelt = worldObj.getBlockTileEntity(xCoord + front.offsetX, yCoord + front.offsetY, zCoord + front.offsetZ);
TileEntity BBelt = worldObj.getBlockTileEntity(xCoord + back.offsetX, yCoord + back.offsetY, zCoord + back.offsetZ);
if (fBelt instanceof TileEntityConveyorBelt)
{
ForgeDirection fD = ((TileEntityConveyorBelt) fBelt).getDirection();
ForgeDirection TD = this.getDirection();
return fD == TD;
}
return false;
}
/**
* Is this belt in the middile of two belts? Used for rendering.
*/
public boolean getIsMiddleBelt()
{
ForgeDirection front = this.getDirection();
ForgeDirection back = this.getDirection().getOpposite();
TileEntity fBelt = worldObj.getBlockTileEntity(xCoord + front.offsetX, yCoord + front.offsetY, zCoord + front.offsetZ);
TileEntity BBelt = worldObj.getBlockTileEntity(xCoord + back.offsetX, yCoord + back.offsetY, zCoord + back.offsetZ);
if (fBelt instanceof TileEntityConveyorBelt && BBelt instanceof TileEntityConveyorBelt)
{
ForgeDirection fD = ((TileEntityConveyorBelt) fBelt).getDirection();
ForgeDirection BD = ((TileEntityConveyorBelt) BBelt).getDirection();
ForgeDirection TD = this.getDirection();
return fD == TD && BD == TD;
}
return false;
}
/**
* Is this belt in the back of a conveyor line? Used for rendering.
*/
public boolean getIsLastBelt()
{
ForgeDirection front = this.getDirection();
ForgeDirection back = this.getDirection().getOpposite();
TileEntity fBelt = worldObj.getBlockTileEntity(xCoord + front.offsetX, yCoord + front.offsetY, zCoord + front.offsetZ);
TileEntity BBelt = worldObj.getBlockTileEntity(xCoord + back.offsetX, yCoord + back.offsetY, zCoord + back.offsetZ);
if (BBelt instanceof TileEntityConveyorBelt)
{
ForgeDirection BD = ((TileEntityConveyorBelt) BBelt).getDirection();
ForgeDirection TD = this.getDirection();
return BD == TD;
}
return false;
}
@Override
public void handlePacketData(INetworkManager network, int packetType, Packet250CustomPayload packet, EntityPlayer player, ByteArrayDataInput dataStream)
{
if (worldObj.isRemote)
{
try
{
this.wattsReceived = dataStream.readDouble();
this.slantType = SlantType.values()[dataStream.readInt()];
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
@Override
public void setDirection(ForgeDirection facingDirection)
{
this.worldObj.setBlockMetadataWithNotify(this.xCoord, this.yCoord, this.zCoord, facingDirection.ordinal());
}
@Override
public ForgeDirection getDirection()
{
return ForgeDirection.getOrientation(this.getBlockMetadata());
}
@Override
public List<Entity> getAffectedEntities()
{
AxisAlignedBB bounds = AxisAlignedBB.getBoundingBox(this.xCoord, this.yCoord, this.zCoord, this.xCoord + 1, this.yCoord + 1, this.zCoord + 1);
return worldObj.getEntitiesWithinAABB(Entity.class, bounds);
}
public int getAnimationFrame()
{
TileEntity te = null;
te = worldObj.getBlockTileEntity(xCoord - 1, yCoord, zCoord);
if (te != null)
if (te instanceof TileEntityConveyorBelt)
return ((TileEntityConveyorBelt) te).getAnimationFrame();
te = worldObj.getBlockTileEntity(xCoord, yCoord, zCoord - 1);
if (te != null)
if (te instanceof TileEntityConveyorBelt)
return ((TileEntityConveyorBelt) te).getAnimationFrame();
return animFrame;
}
/**
* NBT Data
*/
@Override
public void readFromNBT(NBTTagCompound nbt)
{
super.readFromNBT(nbt);
this.slantType = SlantType.values()[nbt.getByte("slant")];
}
/**
* Writes a tile entity to NBT.
*/
@Override
public void writeToNBT(NBTTagCompound nbt)
{
super.writeToNBT(nbt);
nbt.setByte("slant", (byte) this.slantType.ordinal());
}
}
| false | true | public void updatePowerTransferRange()
{
int maximumTransferRange = 0;
for (int i = 0; i < 6; i++)
{
ForgeDirection direction = ForgeDirection.getOrientation(i);
TileEntity tileEntity = worldObj.getBlockTileEntity(this.xCoord + direction.offsetX, this.yCoord + direction.offsetY, this.zCoord + direction.offsetZ);
if (tileEntity != null)
{
if (tileEntity instanceof TileEntityAssemblyNetwork)
{
TileEntityAssemblyNetwork assemblyNetwork = (TileEntityAssemblyNetwork) tileEntity;
if (assemblyNetwork.powerTransferRange > maximumTransferRange)
{
maximumTransferRange = assemblyNetwork.powerTransferRange;
}
}
}
}
for (int d = 0; d <= 1; d++)
{
ForgeDirection direction = this.getDirection();
//if (d == 1)
{
direction = direction.getOpposite();
}
for (int i = -1; i < 1; i++)
{
TileEntity tileEntity = worldObj.getBlockTileEntity(this.xCoord + direction.offsetX, this.yCoord + i, this.zCoord + direction.offsetZ);
if (tileEntity != null)
{
if (tileEntity instanceof TileEntityAssemblyNetwork)
{
TileEntityAssemblyNetwork assemblyNetwork = (TileEntityAssemblyNetwork) tileEntity;
if (assemblyNetwork.powerTransferRange > maximumTransferRange)
{
maximumTransferRange = assemblyNetwork.powerTransferRange;
}
}
}
}
}
this.powerTransferRange = Math.max(maximumTransferRange - 1, 0);
}
| public void updatePowerTransferRange()
{
int maximumTransferRange = 0;
for (int i = 0; i < 6; i++)
{
ForgeDirection direction = ForgeDirection.getOrientation(i);
TileEntity tileEntity = worldObj.getBlockTileEntity(this.xCoord + direction.offsetX, this.yCoord + direction.offsetY, this.zCoord + direction.offsetZ);
if (tileEntity != null)
{
if (tileEntity instanceof TileEntityAssemblyNetwork)
{
TileEntityAssemblyNetwork assemblyNetwork = (TileEntityAssemblyNetwork) tileEntity;
if (assemblyNetwork.powerTransferRange > maximumTransferRange)
{
maximumTransferRange = assemblyNetwork.powerTransferRange;
}
}
}
}
for (int d = 0; d <= 1; d++)
{
ForgeDirection direction = this.getDirection();
if (d == 1)
{
direction = direction.getOpposite();
}
for (int i = -1; i <= 1; i++)
{
TileEntity tileEntity = worldObj.getBlockTileEntity(this.xCoord + direction.offsetX, this.yCoord + i, this.zCoord + direction.offsetZ);
if (tileEntity != null)
{
if (tileEntity instanceof TileEntityAssemblyNetwork)
{
TileEntityAssemblyNetwork assemblyNetwork = (TileEntityAssemblyNetwork) tileEntity;
if (assemblyNetwork.powerTransferRange > maximumTransferRange)
{
maximumTransferRange = assemblyNetwork.powerTransferRange;
}
}
}
}
}
this.powerTransferRange = Math.max(maximumTransferRange - 1, 0);
}
|
diff --git a/src/com/sun/gi/utils/nio/NIOSocketManager.java b/src/com/sun/gi/utils/nio/NIOSocketManager.java
index 1baddf159..de722675b 100644
--- a/src/com/sun/gi/utils/nio/NIOSocketManager.java
+++ b/src/com/sun/gi/utils/nio/NIOSocketManager.java
@@ -1,336 +1,338 @@
package com.sun.gi.utils.nio;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.net.Socket;
import java.net.DatagramSocket;
import java.nio.channels.Selector;
import java.nio.channels.SelectionKey;
import java.nio.channels.DatagramChannel;
import java.nio.channels.SelectableChannel;
import java.nio.channels.SocketChannel;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.ClosedChannelException;
import java.util.Iterator;
import java.util.Set;
import java.util.TreeSet;
import java.util.List;
import java.util.ArrayList;
import java.util.logging.Logger;
import static java.nio.channels.SelectionKey.*;
public class NIOSocketManager implements Runnable {
private static Logger log = Logger.getLogger("com.sun.gi.utils.nio");
private Selector selector;
private int initialInputBuffSz;
private Set<NIOSocketManagerListener> listeners =
new TreeSet<NIOSocketManagerListener>();
private List<NIOConnection> initiatorQueue =
new ArrayList<NIOConnection>();
private List<NIOConnection> receiverQueue =
new ArrayList<NIOConnection>();
private List<ServerSocketChannel> acceptorQueue =
new ArrayList<ServerSocketChannel>();
private List<SelectableChannel> writeQueue =
new ArrayList<SelectableChannel>();
public NIOSocketManager() throws IOException {
this(64 * 1024);
}
public NIOSocketManager(int inputBufferSize) throws IOException {
selector = Selector.open();
initialInputBuffSz = inputBufferSize;
new Thread(this).start();
}
public void acceptConnectionsOn(SocketAddress addr)
throws IOException {
log.entering("NIOSocketManager", "acceptConnectionsOn");
ServerSocketChannel channel = ServerSocketChannel.open();
channel.configureBlocking(false);
channel.socket().bind(addr);
synchronized (acceptorQueue) {
acceptorQueue.add(channel);
}
selector.wakeup();
log.exiting("NIOSocketManager", "acceptConnectionsOn");
}
public NIOConnection makeConnectionTo(SocketAddress addr) {
log.entering("NIOSocketManager", "makeConnectionTo");
try {
SocketChannel sc = SocketChannel.open();
sc.configureBlocking(false);
sc.connect(addr);
DatagramChannel dc = DatagramChannel.open();
dc.configureBlocking(false);
NIOConnection conn =
new NIOConnection(this, sc, dc, initialInputBuffSz);
synchronized (initiatorQueue) {
initiatorQueue.add(conn);
}
selector.wakeup();
return conn;
}
catch (IOException ex) {
ex.printStackTrace();
return null;
} finally {
log.exiting("NIOSocketManager", "makeConnectionTo");
}
}
// This runs the actual polled input
public void run() {
log.entering("NIOSocketManager", "run");
while (true) { // until shutdown() is called
synchronized (initiatorQueue) {
for (NIOConnection conn : initiatorQueue) {
try {
conn.registerConnect(selector);
}
catch (IOException ex) {
ex.printStackTrace();
}
}
initiatorQueue.clear();
}
synchronized (receiverQueue) {
for (NIOConnection conn : receiverQueue) {
try {
conn.open(selector);
}
catch (IOException ex) {
ex.printStackTrace();
}
}
receiverQueue.clear();
}
synchronized (acceptorQueue) {
for (ServerSocketChannel chan : acceptorQueue) {
try {
chan.register(selector, OP_ACCEPT);
}
catch (ClosedChannelException ex2) {
ex2.printStackTrace();
}
}
acceptorQueue.clear();
}
synchronized (writeQueue) {
for (SelectableChannel chan : writeQueue) {
SelectionKey key = chan.keyFor(selector);
- key.interestOps(key.interestOps() | OP_WRITE);
+ if (key.isValid()) {
+ key.interestOps(key.interestOps() | OP_WRITE);
+ }
}
writeQueue.clear();
}
if (! selector.isOpen())
break;
try {
log.finest("Calling select");
int n = selector.select();
log.finer("selector: " + n + " ready handles");
if (n > 0) {
processSocketEvents(selector);
}
} catch (IOException e) {
e.printStackTrace();
}
}
log.exiting("NIOSocketManager", "run");
}
/**
* processSocketEvents
*
* @param selector Selector
*/
private void processSocketEvents(Selector selector) {
log.entering("NIOSocketManager", "processSocketEvents");
Iterator<SelectionKey> i = selector.selectedKeys().iterator();
// Walk through set
while (i.hasNext()) {
// Get key from set
SelectionKey key = (SelectionKey) i.next();
// Remove current entry
i.remove();
if (key.isValid() && key.isAcceptable()) {
handleAccept(key);
}
if (key.isValid() && key.isConnectable()) {
handleConnect(key);
}
if (key.isValid() && key.isReadable()) {
handleRead(key);
}
if (key.isValid() && key.isWritable()) {
handleWrite(key);
}
}
log.exiting("NIOSocketManager", "processSocketEvents");
}
private void handleRead(SelectionKey key) {
log.entering("NIOSocketManager", "handleRead");
ReadWriteSelectorHandler h =
(ReadWriteSelectorHandler) key.attachment();
try {
h.handleRead(key);
} catch (IOException ex) {
h.handleClose();
} finally {
log.exiting("NIOSocketManager", "handleRead");
}
}
private void handleWrite(SelectionKey key) {
log.entering("NIOSocketManager", "handleWrite");
ReadWriteSelectorHandler h =
(ReadWriteSelectorHandler) key.attachment();
try {
h.handleWrite(key);
} catch (IOException ex) {
h.handleClose();
} finally {
log.exiting("NIOSocketManager", "handleWrite");
}
}
private void handleAccept(SelectionKey key) {
log.entering("NIOSocketManager", "handleAccept");
// Get channel
ServerSocketChannel serverChannel =
(ServerSocketChannel) key.channel();
NIOConnection conn = null;
// Accept request
try {
SocketChannel sc = serverChannel.accept();
if (sc == null) {
log.warning("accept returned null");
return;
}
sc.configureBlocking(false);
// Now create a UDP channel for this endpoint
DatagramChannel dc = DatagramChannel.open();
conn = new NIOConnection(this, sc, dc, initialInputBuffSz);
dc.socket().setReuseAddress(true);
dc.configureBlocking(false);
dc.socket().bind(sc.socket().getLocalSocketAddress());
// @@: Workaround for Windows JDK 1.5; it's unhappy with this
// call because it's trying to use the (null) hostname instead
// of the host address. So we explicitly pull out the host
// address and create a new InetSocketAddress with it.
//dc.connect(sc.socket().getRemoteSocketAddress());
dc.connect(new InetSocketAddress(
sc.socket().getInetAddress().getHostAddress(),
sc.socket().getPort()));
log.finest("udp local " +
dc.socket().getLocalSocketAddress() +
" remote " + dc.socket().getRemoteSocketAddress());
synchronized (receiverQueue) {
receiverQueue.add(conn);
}
for (NIOSocketManagerListener l : listeners) {
l.newConnection(conn);
}
} catch (IOException ex) {
ex.printStackTrace();
if (conn != null) {
conn.disconnect();
}
} finally {
log.exiting("NIOSocketManager", "handleAccept");
}
}
public void enableWrite(SelectableChannel chan) {
writeQueue.add(chan);
selector.wakeup();
}
private void handleConnect(SelectionKey key) {
log.entering("NIOSocketManager", "handleConnect");
NIOConnection conn = (NIOConnection) key.attachment();
try {
conn.processConnect(key);
for (NIOSocketManagerListener l : listeners) {
l.connected(conn);
}
} catch (IOException ex) {
log.warning("NIO connect failure: "+ex.getMessage());
conn.disconnect();
for (NIOSocketManagerListener l : listeners) {
l.connectionFailed(conn);
}
} finally {
log.exiting("NIOSocketManager", "handleConnect");
}
}
/**
* addListener
*
* @param l NIOSocketManagerListener
*/
public void addListener(NIOSocketManagerListener l) {
listeners.add(l);
}
public void shutdown() {
try {
selector.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
| true | true | public void run() {
log.entering("NIOSocketManager", "run");
while (true) { // until shutdown() is called
synchronized (initiatorQueue) {
for (NIOConnection conn : initiatorQueue) {
try {
conn.registerConnect(selector);
}
catch (IOException ex) {
ex.printStackTrace();
}
}
initiatorQueue.clear();
}
synchronized (receiverQueue) {
for (NIOConnection conn : receiverQueue) {
try {
conn.open(selector);
}
catch (IOException ex) {
ex.printStackTrace();
}
}
receiverQueue.clear();
}
synchronized (acceptorQueue) {
for (ServerSocketChannel chan : acceptorQueue) {
try {
chan.register(selector, OP_ACCEPT);
}
catch (ClosedChannelException ex2) {
ex2.printStackTrace();
}
}
acceptorQueue.clear();
}
synchronized (writeQueue) {
for (SelectableChannel chan : writeQueue) {
SelectionKey key = chan.keyFor(selector);
key.interestOps(key.interestOps() | OP_WRITE);
}
writeQueue.clear();
}
if (! selector.isOpen())
break;
try {
log.finest("Calling select");
int n = selector.select();
log.finer("selector: " + n + " ready handles");
if (n > 0) {
processSocketEvents(selector);
}
} catch (IOException e) {
e.printStackTrace();
}
}
log.exiting("NIOSocketManager", "run");
}
| public void run() {
log.entering("NIOSocketManager", "run");
while (true) { // until shutdown() is called
synchronized (initiatorQueue) {
for (NIOConnection conn : initiatorQueue) {
try {
conn.registerConnect(selector);
}
catch (IOException ex) {
ex.printStackTrace();
}
}
initiatorQueue.clear();
}
synchronized (receiverQueue) {
for (NIOConnection conn : receiverQueue) {
try {
conn.open(selector);
}
catch (IOException ex) {
ex.printStackTrace();
}
}
receiverQueue.clear();
}
synchronized (acceptorQueue) {
for (ServerSocketChannel chan : acceptorQueue) {
try {
chan.register(selector, OP_ACCEPT);
}
catch (ClosedChannelException ex2) {
ex2.printStackTrace();
}
}
acceptorQueue.clear();
}
synchronized (writeQueue) {
for (SelectableChannel chan : writeQueue) {
SelectionKey key = chan.keyFor(selector);
if (key.isValid()) {
key.interestOps(key.interestOps() | OP_WRITE);
}
}
writeQueue.clear();
}
if (! selector.isOpen())
break;
try {
log.finest("Calling select");
int n = selector.select();
log.finer("selector: " + n + " ready handles");
if (n > 0) {
processSocketEvents(selector);
}
} catch (IOException e) {
e.printStackTrace();
}
}
log.exiting("NIOSocketManager", "run");
}
|
diff --git a/desktop/src/net/mms_projects/copyit/ui/swt/forms/PreferencesDialog.java b/desktop/src/net/mms_projects/copyit/ui/swt/forms/PreferencesDialog.java
index 614732f..d2bc087 100644
--- a/desktop/src/net/mms_projects/copyit/ui/swt/forms/PreferencesDialog.java
+++ b/desktop/src/net/mms_projects/copyit/ui/swt/forms/PreferencesDialog.java
@@ -1,312 +1,313 @@
package net.mms_projects.copyit.ui.swt.forms;
import net.mms_projects.copyit.LoginResponse;
import net.mms_projects.copyit.Messages;
import net.mms_projects.copyit.Settings;
import net.mms_projects.copyit.api.ServerApi;
import net.mms_projects.copyit.api.endpoints.DeviceEndpoint;
import net.mms_projects.copyit.ui.swt.forms.login_dialogs.AbstractLoginDialog;
import net.mms_projects.copyit.ui.swt.forms.login_dialogs.AutoLoginDialog;
import net.mms_projects.copyit.ui.swt.forms.login_dialogs.LoginDialog;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.TabFolder;
import org.eclipse.swt.widgets.TabItem;
import org.eclipse.swt.widgets.Text;
import org.eclipse.swt.layout.FormLayout;
import org.eclipse.swt.layout.FormData;
import org.eclipse.swt.layout.FormAttachment;
public class PreferencesDialog extends GeneralDialog {
protected Shell shell;
private Settings settings;
private Text textEncryptionPassphrase;
private Label lblDeviceIdHere;
private Button btnLogin;
private Button btnManualLogin;
private Button btnEnablePolling;
private Button btnEnableQueue;
/**
* Create the dialog.
*
* @param parent
* @param Settings
* the settings
*/
public PreferencesDialog(Shell parent, Settings settings) {
super(parent, SWT.DIALOG_TRIM);
this.settings = settings;
setText(Messages.getString("title_activity_settings"));
}
@Override
public void open() {
this.createContents();
this.updateForm();
this.shell.open();
this.shell.layout();
Display display = getParent().getDisplay();
while (!this.shell.isDisposed()) {
if (!display.readAndDispatch()) {
display.sleep();
}
}
this.settings.saveProperties();
}
/**
* Create contents of the dialog.
*/
protected void createContents() {
/*
* Definitions
*/
// Shell
this.shell = new Shell(this.getParent(), SWT.DIALOG_TRIM);
shell.setLayout(new FormLayout());
// Elements
TabFolder tabFolder = new TabFolder(shell, SWT.NONE);
FormData fd_tabFolder = new FormData();
fd_tabFolder.left = new FormAttachment(0, 10);
fd_tabFolder.right = new FormAttachment(100, -6);
fd_tabFolder.top = new FormAttachment(0, 10);
fd_tabFolder.bottom = new FormAttachment(0, 358);
tabFolder.setLayoutData(fd_tabFolder);
Button btnClose = new Button(shell, SWT.NONE);
FormData fd_btnClose = new FormData();
fd_btnClose.top = new FormAttachment(tabFolder, 6);
fd_btnClose.right = new FormAttachment(tabFolder, 0, SWT.RIGHT);
fd_btnClose.left = new FormAttachment(0, 457);
btnClose.setLayoutData(fd_btnClose);
// Account tab
TabItem tbtmAccount = new TabItem(tabFolder, SWT.NONE);
Composite compositeAccount = new Composite(tabFolder, SWT.NONE);
compositeAccount.setLayout(new FormLayout());
Label lblAccountName = new Label(compositeAccount, SWT.NONE);
FormData fd_lblAccountName = new FormData();
fd_lblAccountName.right = new FormAttachment(0, 170);
fd_lblAccountName.top = new FormAttachment(0, 10);
fd_lblAccountName.left = new FormAttachment(0, 10);
lblAccountName.setLayoutData(fd_lblAccountName);
Label lblAccountNameHere = new Label(compositeAccount, SWT.NONE);
FormData fd_lblAccountNameHere = new FormData();
fd_lblAccountNameHere.right = new FormAttachment(0, 380);
fd_lblAccountNameHere.top = new FormAttachment(0, 10);
fd_lblAccountNameHere.left = new FormAttachment(0, 200);
lblAccountNameHere.setLayoutData(fd_lblAccountNameHere);
Label lblDeviceId = new Label(compositeAccount, SWT.NONE);
FormData fd_lblDeviceId = new FormData();
fd_lblDeviceId.right = new FormAttachment(0, 80);
fd_lblDeviceId.top = new FormAttachment(0, 33);
fd_lblDeviceId.left = new FormAttachment(0, 10);
lblDeviceId.setLayoutData(fd_lblDeviceId);
this.lblDeviceIdHere = new Label(compositeAccount, SWT.NONE);
FormData fd_lblDeviceIdHere = new FormData();
fd_lblDeviceIdHere.right = new FormAttachment(0, 380);
fd_lblDeviceIdHere.top = new FormAttachment(0, 33);
fd_lblDeviceIdHere.left = new FormAttachment(0, 200);
lblDeviceIdHere.setLayoutData(fd_lblDeviceIdHere);
this.btnLogin = new Button(compositeAccount, SWT.NONE);
FormData fd_btnLogin = new FormData();
- fd_btnLogin.right = new FormAttachment(0, 358);
- fd_btnLogin.top = new FormAttachment(0, 56);
fd_btnLogin.left = new FormAttachment(0, 200);
+ fd_btnLogin.top = new FormAttachment(lblDeviceIdHere, 6);
+ fd_btnLogin.bottom = new FormAttachment(0, 85);
btnLogin.setLayoutData(fd_btnLogin);
this.btnManualLogin = new Button(compositeAccount, SWT.NONE);
+ fd_btnLogin.right = new FormAttachment(btnManualLogin, -6);
FormData fd_btnManualLogin = new FormData();
- fd_btnManualLogin.right = new FormAttachment(0, 524);
- fd_btnManualLogin.top = new FormAttachment(0, 56);
fd_btnManualLogin.left = new FormAttachment(0, 364);
+ fd_btnManualLogin.right = new FormAttachment(100, -10);
+ fd_btnManualLogin.top = new FormAttachment(lblDeviceIdHere, 6);
btnManualLogin.setLayoutData(fd_btnManualLogin);
// Security tab
TabItem tbtmSecurity = new TabItem(tabFolder, SWT.NONE);
Composite compositeSecurity = new Composite(tabFolder, SWT.NONE);
compositeSecurity.setLayout(new FormLayout());
final Button btnEnableLocalEncryption = new Button(compositeSecurity,
SWT.CHECK);
FormData fd_btnEnableLocalEncryption = new FormData();
fd_btnEnableLocalEncryption.right = new FormAttachment(0, 194);
fd_btnEnableLocalEncryption.top = new FormAttachment(0, 10);
fd_btnEnableLocalEncryption.left = new FormAttachment(0, 10);
btnEnableLocalEncryption.setLayoutData(fd_btnEnableLocalEncryption);
Label lblEncryptionPassphrase = new Label(compositeSecurity, SWT.NONE);
FormData fd_lblEncryptionPassphrase = new FormData();
fd_lblEncryptionPassphrase.right = new FormAttachment(0, 194);
fd_lblEncryptionPassphrase.top = new FormAttachment(0, 44);
fd_lblEncryptionPassphrase.left = new FormAttachment(0, 10);
lblEncryptionPassphrase.setLayoutData(fd_lblEncryptionPassphrase);
this.textEncryptionPassphrase = new Text(compositeSecurity, SWT.BORDER);
FormData fd_textEncryptionPassphrase = new FormData();
fd_textEncryptionPassphrase.right = new FormAttachment(0, 400);
fd_textEncryptionPassphrase.top = new FormAttachment(0, 40);
fd_textEncryptionPassphrase.left = new FormAttachment(0, 200);
textEncryptionPassphrase.setLayoutData(fd_textEncryptionPassphrase);
// Sync tab
TabItem tbtmSync = new TabItem(tabFolder, SWT.NONE);
Composite compositeSync = new Composite(tabFolder, SWT.NONE);
compositeSync.setLayout(new FormLayout());
btnEnablePolling = new Button(compositeSync, SWT.CHECK);
FormData fd_btnEnablePolling = new FormData();
fd_btnEnablePolling.right = new FormAttachment(0, 178);
fd_btnEnablePolling.top = new FormAttachment(0, 10);
fd_btnEnablePolling.left = new FormAttachment(0, 10);
btnEnablePolling.setLayoutData(fd_btnEnablePolling);
btnEnableQueue = new Button(compositeSync, SWT.CHECK);
FormData fd_btnEnableQueue = new FormData();
fd_btnEnableQueue.top = new FormAttachment(0, 40);
fd_btnEnableQueue.left = new FormAttachment(0, 10);
btnEnableQueue.setLayoutData(fd_btnEnableQueue);
/*
* Layout and settings
*/
// Shell
this.shell.setSize(552, 434);
this.shell.setText(getText());
btnClose.setText("Close");
// Account tab
tbtmAccount.setText("Account");
tbtmAccount.setControl(compositeAccount);
lblAccountName.setText("Account name:");
lblAccountNameHere.setText("Account name here...");
lblDeviceId.setText("Device id:");
this.lblDeviceIdHere.setText("Device id here...");
this.btnLogin.setText(Messages.getString("button_login"));
this.btnManualLogin.setText("Manual login ");
// Security tab
tbtmSecurity.setText("Security");
tbtmSecurity.setControl(compositeSecurity);
btnEnableLocalEncryption.setText("Enable local encryption");
lblEncryptionPassphrase.setText("Encryption passphrase:");
// Sync tab
tbtmSync.setText("Sync");
tbtmSync.setControl(compositeSync);
btnEnablePolling.setText(Messages.getString("PreferencesDialog.btnEnablePolling.text"));
btnEnableQueue.setText(Messages.getString("PreferencesDialog.btnEnableQueue.text")); //$NON-NLS-1$
/*
* Listeners
*/
// Automatic login button
this.btnLogin.addSelectionListener(new LoginSectionAdapter() {
@Override
public AbstractLoginDialog getLoginDialog() {
return new AutoLoginDialog(shell,
PreferencesDialog.this.settings);
}
});
// Manual login
this.btnManualLogin.addSelectionListener(new LoginSectionAdapter() {
@Override
public AbstractLoginDialog getLoginDialog() {
return new LoginDialog(shell);
}
});
// Encryption enable checkbox
btnEnableLocalEncryption.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent event) {
textEncryptionPassphrase.setEnabled(btnEnableLocalEncryption
.getSelection());
PreferencesDialog.this.updateForm();
}
});
// Close button
btnClose.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent event) {
PreferencesDialog.this.shell.close();
}
});
// Sync tab
btnEnablePolling.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent arg0) {
PreferencesDialog.this.settings.set("sync.polling.enabled", btnEnablePolling.getSelection());
PreferencesDialog.this.updateForm();
}
});
btnEnableQueue.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent arg0) {
PreferencesDialog.this.settings.set("sync.queue.enabled", btnEnableQueue.getSelection());
PreferencesDialog.this.updateForm();
}
});
}
protected void updateForm() {
if (this.settings.get("device.id") != null) {
this.lblDeviceIdHere.setText(this.settings.get("device.id"));
} else {
this.lblDeviceIdHere.setText("None");
}
if (this.settings.get("device.id") != null) {
this.btnLogin.setText("Relogin");
}
if (this.settings.get("device.id") != null) {
this.btnManualLogin.setText("Relogin (manual)");
}
btnEnablePolling.setSelection(this.settings.getBoolean("sync.polling.enabled"));
btnEnableQueue.setSelection(this.settings.getBoolean("sync.queue.enabled"));
btnEnableQueue.setEnabled(this.settings.getBoolean("sync.polling.enabled"));
}
private abstract class LoginSectionAdapter extends SelectionAdapter {
abstract public AbstractLoginDialog getLoginDialog();
@Override
final public void widgetSelected(SelectionEvent event) {
AbstractLoginDialog dialog = this.getLoginDialog();
dialog.open();
LoginResponse response = dialog.getResponse();
if (response == null) {
System.out.println("No login response returned.");
return;
}
ServerApi api = new ServerApi();
api.deviceId = response.deviceId;
api.devicePassword = response.devicePassword;
try {
new DeviceEndpoint(api).create("Interwebz Paste client");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
PreferencesDialog.this.settings.set("device.id",
response.deviceId.toString());
PreferencesDialog.this.settings.set("device.password",
response.devicePassword);
PreferencesDialog.this.updateForm();
}
}
}
| false | true | protected void createContents() {
/*
* Definitions
*/
// Shell
this.shell = new Shell(this.getParent(), SWT.DIALOG_TRIM);
shell.setLayout(new FormLayout());
// Elements
TabFolder tabFolder = new TabFolder(shell, SWT.NONE);
FormData fd_tabFolder = new FormData();
fd_tabFolder.left = new FormAttachment(0, 10);
fd_tabFolder.right = new FormAttachment(100, -6);
fd_tabFolder.top = new FormAttachment(0, 10);
fd_tabFolder.bottom = new FormAttachment(0, 358);
tabFolder.setLayoutData(fd_tabFolder);
Button btnClose = new Button(shell, SWT.NONE);
FormData fd_btnClose = new FormData();
fd_btnClose.top = new FormAttachment(tabFolder, 6);
fd_btnClose.right = new FormAttachment(tabFolder, 0, SWT.RIGHT);
fd_btnClose.left = new FormAttachment(0, 457);
btnClose.setLayoutData(fd_btnClose);
// Account tab
TabItem tbtmAccount = new TabItem(tabFolder, SWT.NONE);
Composite compositeAccount = new Composite(tabFolder, SWT.NONE);
compositeAccount.setLayout(new FormLayout());
Label lblAccountName = new Label(compositeAccount, SWT.NONE);
FormData fd_lblAccountName = new FormData();
fd_lblAccountName.right = new FormAttachment(0, 170);
fd_lblAccountName.top = new FormAttachment(0, 10);
fd_lblAccountName.left = new FormAttachment(0, 10);
lblAccountName.setLayoutData(fd_lblAccountName);
Label lblAccountNameHere = new Label(compositeAccount, SWT.NONE);
FormData fd_lblAccountNameHere = new FormData();
fd_lblAccountNameHere.right = new FormAttachment(0, 380);
fd_lblAccountNameHere.top = new FormAttachment(0, 10);
fd_lblAccountNameHere.left = new FormAttachment(0, 200);
lblAccountNameHere.setLayoutData(fd_lblAccountNameHere);
Label lblDeviceId = new Label(compositeAccount, SWT.NONE);
FormData fd_lblDeviceId = new FormData();
fd_lblDeviceId.right = new FormAttachment(0, 80);
fd_lblDeviceId.top = new FormAttachment(0, 33);
fd_lblDeviceId.left = new FormAttachment(0, 10);
lblDeviceId.setLayoutData(fd_lblDeviceId);
this.lblDeviceIdHere = new Label(compositeAccount, SWT.NONE);
FormData fd_lblDeviceIdHere = new FormData();
fd_lblDeviceIdHere.right = new FormAttachment(0, 380);
fd_lblDeviceIdHere.top = new FormAttachment(0, 33);
fd_lblDeviceIdHere.left = new FormAttachment(0, 200);
lblDeviceIdHere.setLayoutData(fd_lblDeviceIdHere);
this.btnLogin = new Button(compositeAccount, SWT.NONE);
FormData fd_btnLogin = new FormData();
fd_btnLogin.right = new FormAttachment(0, 358);
fd_btnLogin.top = new FormAttachment(0, 56);
fd_btnLogin.left = new FormAttachment(0, 200);
btnLogin.setLayoutData(fd_btnLogin);
this.btnManualLogin = new Button(compositeAccount, SWT.NONE);
FormData fd_btnManualLogin = new FormData();
fd_btnManualLogin.right = new FormAttachment(0, 524);
fd_btnManualLogin.top = new FormAttachment(0, 56);
fd_btnManualLogin.left = new FormAttachment(0, 364);
btnManualLogin.setLayoutData(fd_btnManualLogin);
// Security tab
TabItem tbtmSecurity = new TabItem(tabFolder, SWT.NONE);
Composite compositeSecurity = new Composite(tabFolder, SWT.NONE);
compositeSecurity.setLayout(new FormLayout());
final Button btnEnableLocalEncryption = new Button(compositeSecurity,
SWT.CHECK);
FormData fd_btnEnableLocalEncryption = new FormData();
fd_btnEnableLocalEncryption.right = new FormAttachment(0, 194);
fd_btnEnableLocalEncryption.top = new FormAttachment(0, 10);
fd_btnEnableLocalEncryption.left = new FormAttachment(0, 10);
btnEnableLocalEncryption.setLayoutData(fd_btnEnableLocalEncryption);
Label lblEncryptionPassphrase = new Label(compositeSecurity, SWT.NONE);
FormData fd_lblEncryptionPassphrase = new FormData();
fd_lblEncryptionPassphrase.right = new FormAttachment(0, 194);
fd_lblEncryptionPassphrase.top = new FormAttachment(0, 44);
fd_lblEncryptionPassphrase.left = new FormAttachment(0, 10);
lblEncryptionPassphrase.setLayoutData(fd_lblEncryptionPassphrase);
this.textEncryptionPassphrase = new Text(compositeSecurity, SWT.BORDER);
FormData fd_textEncryptionPassphrase = new FormData();
fd_textEncryptionPassphrase.right = new FormAttachment(0, 400);
fd_textEncryptionPassphrase.top = new FormAttachment(0, 40);
fd_textEncryptionPassphrase.left = new FormAttachment(0, 200);
textEncryptionPassphrase.setLayoutData(fd_textEncryptionPassphrase);
// Sync tab
TabItem tbtmSync = new TabItem(tabFolder, SWT.NONE);
Composite compositeSync = new Composite(tabFolder, SWT.NONE);
compositeSync.setLayout(new FormLayout());
btnEnablePolling = new Button(compositeSync, SWT.CHECK);
FormData fd_btnEnablePolling = new FormData();
fd_btnEnablePolling.right = new FormAttachment(0, 178);
fd_btnEnablePolling.top = new FormAttachment(0, 10);
fd_btnEnablePolling.left = new FormAttachment(0, 10);
btnEnablePolling.setLayoutData(fd_btnEnablePolling);
btnEnableQueue = new Button(compositeSync, SWT.CHECK);
FormData fd_btnEnableQueue = new FormData();
fd_btnEnableQueue.top = new FormAttachment(0, 40);
fd_btnEnableQueue.left = new FormAttachment(0, 10);
btnEnableQueue.setLayoutData(fd_btnEnableQueue);
/*
* Layout and settings
*/
// Shell
this.shell.setSize(552, 434);
this.shell.setText(getText());
btnClose.setText("Close");
// Account tab
tbtmAccount.setText("Account");
tbtmAccount.setControl(compositeAccount);
lblAccountName.setText("Account name:");
lblAccountNameHere.setText("Account name here...");
lblDeviceId.setText("Device id:");
this.lblDeviceIdHere.setText("Device id here...");
this.btnLogin.setText(Messages.getString("button_login"));
this.btnManualLogin.setText("Manual login ");
// Security tab
tbtmSecurity.setText("Security");
tbtmSecurity.setControl(compositeSecurity);
btnEnableLocalEncryption.setText("Enable local encryption");
lblEncryptionPassphrase.setText("Encryption passphrase:");
// Sync tab
tbtmSync.setText("Sync");
tbtmSync.setControl(compositeSync);
btnEnablePolling.setText(Messages.getString("PreferencesDialog.btnEnablePolling.text"));
btnEnableQueue.setText(Messages.getString("PreferencesDialog.btnEnableQueue.text")); //$NON-NLS-1$
/*
* Listeners
*/
// Automatic login button
this.btnLogin.addSelectionListener(new LoginSectionAdapter() {
@Override
public AbstractLoginDialog getLoginDialog() {
return new AutoLoginDialog(shell,
PreferencesDialog.this.settings);
}
});
// Manual login
this.btnManualLogin.addSelectionListener(new LoginSectionAdapter() {
@Override
public AbstractLoginDialog getLoginDialog() {
return new LoginDialog(shell);
}
});
// Encryption enable checkbox
btnEnableLocalEncryption.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent event) {
textEncryptionPassphrase.setEnabled(btnEnableLocalEncryption
.getSelection());
PreferencesDialog.this.updateForm();
}
});
// Close button
btnClose.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent event) {
PreferencesDialog.this.shell.close();
}
});
// Sync tab
btnEnablePolling.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent arg0) {
PreferencesDialog.this.settings.set("sync.polling.enabled", btnEnablePolling.getSelection());
PreferencesDialog.this.updateForm();
}
});
btnEnableQueue.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent arg0) {
PreferencesDialog.this.settings.set("sync.queue.enabled", btnEnableQueue.getSelection());
PreferencesDialog.this.updateForm();
}
});
}
| protected void createContents() {
/*
* Definitions
*/
// Shell
this.shell = new Shell(this.getParent(), SWT.DIALOG_TRIM);
shell.setLayout(new FormLayout());
// Elements
TabFolder tabFolder = new TabFolder(shell, SWT.NONE);
FormData fd_tabFolder = new FormData();
fd_tabFolder.left = new FormAttachment(0, 10);
fd_tabFolder.right = new FormAttachment(100, -6);
fd_tabFolder.top = new FormAttachment(0, 10);
fd_tabFolder.bottom = new FormAttachment(0, 358);
tabFolder.setLayoutData(fd_tabFolder);
Button btnClose = new Button(shell, SWT.NONE);
FormData fd_btnClose = new FormData();
fd_btnClose.top = new FormAttachment(tabFolder, 6);
fd_btnClose.right = new FormAttachment(tabFolder, 0, SWT.RIGHT);
fd_btnClose.left = new FormAttachment(0, 457);
btnClose.setLayoutData(fd_btnClose);
// Account tab
TabItem tbtmAccount = new TabItem(tabFolder, SWT.NONE);
Composite compositeAccount = new Composite(tabFolder, SWT.NONE);
compositeAccount.setLayout(new FormLayout());
Label lblAccountName = new Label(compositeAccount, SWT.NONE);
FormData fd_lblAccountName = new FormData();
fd_lblAccountName.right = new FormAttachment(0, 170);
fd_lblAccountName.top = new FormAttachment(0, 10);
fd_lblAccountName.left = new FormAttachment(0, 10);
lblAccountName.setLayoutData(fd_lblAccountName);
Label lblAccountNameHere = new Label(compositeAccount, SWT.NONE);
FormData fd_lblAccountNameHere = new FormData();
fd_lblAccountNameHere.right = new FormAttachment(0, 380);
fd_lblAccountNameHere.top = new FormAttachment(0, 10);
fd_lblAccountNameHere.left = new FormAttachment(0, 200);
lblAccountNameHere.setLayoutData(fd_lblAccountNameHere);
Label lblDeviceId = new Label(compositeAccount, SWT.NONE);
FormData fd_lblDeviceId = new FormData();
fd_lblDeviceId.right = new FormAttachment(0, 80);
fd_lblDeviceId.top = new FormAttachment(0, 33);
fd_lblDeviceId.left = new FormAttachment(0, 10);
lblDeviceId.setLayoutData(fd_lblDeviceId);
this.lblDeviceIdHere = new Label(compositeAccount, SWT.NONE);
FormData fd_lblDeviceIdHere = new FormData();
fd_lblDeviceIdHere.right = new FormAttachment(0, 380);
fd_lblDeviceIdHere.top = new FormAttachment(0, 33);
fd_lblDeviceIdHere.left = new FormAttachment(0, 200);
lblDeviceIdHere.setLayoutData(fd_lblDeviceIdHere);
this.btnLogin = new Button(compositeAccount, SWT.NONE);
FormData fd_btnLogin = new FormData();
fd_btnLogin.left = new FormAttachment(0, 200);
fd_btnLogin.top = new FormAttachment(lblDeviceIdHere, 6);
fd_btnLogin.bottom = new FormAttachment(0, 85);
btnLogin.setLayoutData(fd_btnLogin);
this.btnManualLogin = new Button(compositeAccount, SWT.NONE);
fd_btnLogin.right = new FormAttachment(btnManualLogin, -6);
FormData fd_btnManualLogin = new FormData();
fd_btnManualLogin.left = new FormAttachment(0, 364);
fd_btnManualLogin.right = new FormAttachment(100, -10);
fd_btnManualLogin.top = new FormAttachment(lblDeviceIdHere, 6);
btnManualLogin.setLayoutData(fd_btnManualLogin);
// Security tab
TabItem tbtmSecurity = new TabItem(tabFolder, SWT.NONE);
Composite compositeSecurity = new Composite(tabFolder, SWT.NONE);
compositeSecurity.setLayout(new FormLayout());
final Button btnEnableLocalEncryption = new Button(compositeSecurity,
SWT.CHECK);
FormData fd_btnEnableLocalEncryption = new FormData();
fd_btnEnableLocalEncryption.right = new FormAttachment(0, 194);
fd_btnEnableLocalEncryption.top = new FormAttachment(0, 10);
fd_btnEnableLocalEncryption.left = new FormAttachment(0, 10);
btnEnableLocalEncryption.setLayoutData(fd_btnEnableLocalEncryption);
Label lblEncryptionPassphrase = new Label(compositeSecurity, SWT.NONE);
FormData fd_lblEncryptionPassphrase = new FormData();
fd_lblEncryptionPassphrase.right = new FormAttachment(0, 194);
fd_lblEncryptionPassphrase.top = new FormAttachment(0, 44);
fd_lblEncryptionPassphrase.left = new FormAttachment(0, 10);
lblEncryptionPassphrase.setLayoutData(fd_lblEncryptionPassphrase);
this.textEncryptionPassphrase = new Text(compositeSecurity, SWT.BORDER);
FormData fd_textEncryptionPassphrase = new FormData();
fd_textEncryptionPassphrase.right = new FormAttachment(0, 400);
fd_textEncryptionPassphrase.top = new FormAttachment(0, 40);
fd_textEncryptionPassphrase.left = new FormAttachment(0, 200);
textEncryptionPassphrase.setLayoutData(fd_textEncryptionPassphrase);
// Sync tab
TabItem tbtmSync = new TabItem(tabFolder, SWT.NONE);
Composite compositeSync = new Composite(tabFolder, SWT.NONE);
compositeSync.setLayout(new FormLayout());
btnEnablePolling = new Button(compositeSync, SWT.CHECK);
FormData fd_btnEnablePolling = new FormData();
fd_btnEnablePolling.right = new FormAttachment(0, 178);
fd_btnEnablePolling.top = new FormAttachment(0, 10);
fd_btnEnablePolling.left = new FormAttachment(0, 10);
btnEnablePolling.setLayoutData(fd_btnEnablePolling);
btnEnableQueue = new Button(compositeSync, SWT.CHECK);
FormData fd_btnEnableQueue = new FormData();
fd_btnEnableQueue.top = new FormAttachment(0, 40);
fd_btnEnableQueue.left = new FormAttachment(0, 10);
btnEnableQueue.setLayoutData(fd_btnEnableQueue);
/*
* Layout and settings
*/
// Shell
this.shell.setSize(552, 434);
this.shell.setText(getText());
btnClose.setText("Close");
// Account tab
tbtmAccount.setText("Account");
tbtmAccount.setControl(compositeAccount);
lblAccountName.setText("Account name:");
lblAccountNameHere.setText("Account name here...");
lblDeviceId.setText("Device id:");
this.lblDeviceIdHere.setText("Device id here...");
this.btnLogin.setText(Messages.getString("button_login"));
this.btnManualLogin.setText("Manual login ");
// Security tab
tbtmSecurity.setText("Security");
tbtmSecurity.setControl(compositeSecurity);
btnEnableLocalEncryption.setText("Enable local encryption");
lblEncryptionPassphrase.setText("Encryption passphrase:");
// Sync tab
tbtmSync.setText("Sync");
tbtmSync.setControl(compositeSync);
btnEnablePolling.setText(Messages.getString("PreferencesDialog.btnEnablePolling.text"));
btnEnableQueue.setText(Messages.getString("PreferencesDialog.btnEnableQueue.text")); //$NON-NLS-1$
/*
* Listeners
*/
// Automatic login button
this.btnLogin.addSelectionListener(new LoginSectionAdapter() {
@Override
public AbstractLoginDialog getLoginDialog() {
return new AutoLoginDialog(shell,
PreferencesDialog.this.settings);
}
});
// Manual login
this.btnManualLogin.addSelectionListener(new LoginSectionAdapter() {
@Override
public AbstractLoginDialog getLoginDialog() {
return new LoginDialog(shell);
}
});
// Encryption enable checkbox
btnEnableLocalEncryption.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent event) {
textEncryptionPassphrase.setEnabled(btnEnableLocalEncryption
.getSelection());
PreferencesDialog.this.updateForm();
}
});
// Close button
btnClose.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent event) {
PreferencesDialog.this.shell.close();
}
});
// Sync tab
btnEnablePolling.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent arg0) {
PreferencesDialog.this.settings.set("sync.polling.enabled", btnEnablePolling.getSelection());
PreferencesDialog.this.updateForm();
}
});
btnEnableQueue.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent arg0) {
PreferencesDialog.this.settings.set("sync.queue.enabled", btnEnableQueue.getSelection());
PreferencesDialog.this.updateForm();
}
});
}
|
diff --git a/ninja-core/src/main/java/ninja/NinjaImpl.java b/ninja-core/src/main/java/ninja/NinjaImpl.java
index 30899ae8a..45d8482c3 100644
--- a/ninja-core/src/main/java/ninja/NinjaImpl.java
+++ b/ninja-core/src/main/java/ninja/NinjaImpl.java
@@ -1,84 +1,84 @@
package ninja;
import java.lang.annotation.Annotation;
import ninja.Context.HTTP_STATUS;
import com.google.inject.Inject;
import com.google.inject.Injector;
import com.google.inject.name.Named;
public class NinjaImpl implements Ninja {
Router router;
private final Injector injector;
//something like views/notFound404.ftl.html
//=> named so the user can change it to path she likes
private final String pathToViewNotFound;
@Inject
public NinjaImpl(
Router router,
Injector injector,
@Named("template404") String pathToViewNotFound) {
this.router = router;
this.injector = injector;
this.pathToViewNotFound = pathToViewNotFound;
}
/**
* I want to get a session request etc pp...
*
* @param uri
*/
public void invoke(Context context) {
Route route = router.getRouteFor(context.getHttpServletRequest()
.getServletPath());
if (route != null) {
processAnnotations(route);
route.invoke(context);
} else {
// throw a 404
context.status(HTTP_STATUS.notFound_404).template(pathToViewNotFound).html();
}
}
public void processAnnotations(Route route) {
Class controller = route.getController();
String controllerMethod = route.getControllerMethod();
try {
for (Annotation annotation : controller.getMethod(controllerMethod,
Context.class).getAnnotations()) {
if (annotation.annotationType().equals(FilterWith.class)) {
FilterWith filterWith = (FilterWith) annotation;
- Filter filter = injector.getInstance(filterWith.value());
+ Filter filter = (Filter) injector.getInstance(filterWith.value());
filter.filter(null);
}
}
} catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchMethodException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
| true | true | public void processAnnotations(Route route) {
Class controller = route.getController();
String controllerMethod = route.getControllerMethod();
try {
for (Annotation annotation : controller.getMethod(controllerMethod,
Context.class).getAnnotations()) {
if (annotation.annotationType().equals(FilterWith.class)) {
FilterWith filterWith = (FilterWith) annotation;
Filter filter = injector.getInstance(filterWith.value());
filter.filter(null);
}
}
} catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchMethodException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
| public void processAnnotations(Route route) {
Class controller = route.getController();
String controllerMethod = route.getControllerMethod();
try {
for (Annotation annotation : controller.getMethod(controllerMethod,
Context.class).getAnnotations()) {
if (annotation.annotationType().equals(FilterWith.class)) {
FilterWith filterWith = (FilterWith) annotation;
Filter filter = (Filter) injector.getInstance(filterWith.value());
filter.filter(null);
}
}
} catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchMethodException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
|
diff --git a/Essentials/src/com/earth2me/essentials/commands/EssentialsCommand.java b/Essentials/src/com/earth2me/essentials/commands/EssentialsCommand.java
index 63717fca..32d8ef97 100644
--- a/Essentials/src/com/earth2me/essentials/commands/EssentialsCommand.java
+++ b/Essentials/src/com/earth2me/essentials/commands/EssentialsCommand.java
@@ -1,118 +1,122 @@
package com.earth2me.essentials.commands;
import static com.earth2me.essentials.I18n._;
import com.earth2me.essentials.IEssentials;
import com.earth2me.essentials.OfflinePlayer;
import com.earth2me.essentials.Trade;
import com.earth2me.essentials.User;
import java.util.List;
import java.util.logging.Logger;
import org.bukkit.Server;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
public abstract class EssentialsCommand implements IEssentialsCommand
{
private final transient String name;
protected transient IEssentials ess;
protected final static Logger logger = Logger.getLogger("Minecraft");
protected EssentialsCommand(final String name)
{
this.name = name;
}
@Override
public void setEssentials(final IEssentials ess)
{
this.ess = ess;
}
@Override
public String getName()
{
return name;
}
protected User getPlayer(final Server server, final String[] args, final int pos) throws NoSuchFieldException, NotEnoughArgumentsException
{
return getPlayer(server, args, pos, false);
}
protected User getPlayer(final Server server, final String[] args, final int pos, final boolean getOffline) throws NoSuchFieldException, NotEnoughArgumentsException
{
if (args.length <= pos)
{
throw new NotEnoughArgumentsException();
}
+ if (args[0].isEmpty())
+ {
+ throw new NoSuchFieldException(_("playerNotFound"));
+ }
final User user = ess.getUser(args[pos]);
if (user != null)
{
if (!getOffline && (user.getBase() instanceof OfflinePlayer || user.isHidden()))
{
throw new NoSuchFieldException(_("playerNotFound"));
}
return user;
}
final List<Player> matches = server.matchPlayer(args[pos]);
if (!matches.isEmpty())
{
for (Player player : matches)
{
final User userMatch = ess.getUser(player);
if (userMatch.getDisplayName().startsWith(args[pos]) && (getOffline || !userMatch.isHidden()))
{
return userMatch;
}
}
final User userMatch = ess.getUser(matches.get(0));
if (getOffline || !userMatch.isHidden())
{
return userMatch;
}
}
throw new NoSuchFieldException(_("playerNotFound"));
}
@Override
public final void run(final Server server, final User user, final String commandLabel, final Command cmd, final String[] args) throws Exception
{
final Trade charge = new Trade(this.getName(), ess);
charge.isAffordableFor(user);
run(server, user, commandLabel, args);
charge.charge(user);
}
protected void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception
{
run(server, (CommandSender)user.getBase(), commandLabel, args);
}
@Override
public final void run(final Server server, final CommandSender sender, final String commandLabel, final Command cmd, final String[] args) throws Exception
{
run(server, sender, commandLabel, args);
}
protected void run(final Server server, final CommandSender sender, final String commandLabel, final String[] args) throws Exception
{
throw new Exception(_("onlyPlayers", commandLabel));
}
public static String getFinalArg(final String[] args, final int start)
{
final StringBuilder bldr = new StringBuilder();
for (int i = start; i < args.length; i++)
{
if (i != start)
{
bldr.append(" ");
}
bldr.append(args[i]);
}
return bldr.toString();
}
}
| true | true | protected User getPlayer(final Server server, final String[] args, final int pos, final boolean getOffline) throws NoSuchFieldException, NotEnoughArgumentsException
{
if (args.length <= pos)
{
throw new NotEnoughArgumentsException();
}
final User user = ess.getUser(args[pos]);
if (user != null)
{
if (!getOffline && (user.getBase() instanceof OfflinePlayer || user.isHidden()))
{
throw new NoSuchFieldException(_("playerNotFound"));
}
return user;
}
final List<Player> matches = server.matchPlayer(args[pos]);
if (!matches.isEmpty())
{
for (Player player : matches)
{
final User userMatch = ess.getUser(player);
if (userMatch.getDisplayName().startsWith(args[pos]) && (getOffline || !userMatch.isHidden()))
{
return userMatch;
}
}
final User userMatch = ess.getUser(matches.get(0));
if (getOffline || !userMatch.isHidden())
{
return userMatch;
}
}
throw new NoSuchFieldException(_("playerNotFound"));
}
| protected User getPlayer(final Server server, final String[] args, final int pos, final boolean getOffline) throws NoSuchFieldException, NotEnoughArgumentsException
{
if (args.length <= pos)
{
throw new NotEnoughArgumentsException();
}
if (args[0].isEmpty())
{
throw new NoSuchFieldException(_("playerNotFound"));
}
final User user = ess.getUser(args[pos]);
if (user != null)
{
if (!getOffline && (user.getBase() instanceof OfflinePlayer || user.isHidden()))
{
throw new NoSuchFieldException(_("playerNotFound"));
}
return user;
}
final List<Player> matches = server.matchPlayer(args[pos]);
if (!matches.isEmpty())
{
for (Player player : matches)
{
final User userMatch = ess.getUser(player);
if (userMatch.getDisplayName().startsWith(args[pos]) && (getOffline || !userMatch.isHidden()))
{
return userMatch;
}
}
final User userMatch = ess.getUser(matches.get(0));
if (getOffline || !userMatch.isHidden())
{
return userMatch;
}
}
throw new NoSuchFieldException(_("playerNotFound"));
}
|
diff --git a/app/src/com/pewpewarrows/electricsheep/net/OAuthAuthenticator.java b/app/src/com/pewpewarrows/electricsheep/net/OAuthAuthenticator.java
index 3c55542..d0472e0 100644
--- a/app/src/com/pewpewarrows/electricsheep/net/OAuthAuthenticator.java
+++ b/app/src/com/pewpewarrows/electricsheep/net/OAuthAuthenticator.java
@@ -1,208 +1,208 @@
package com.pewpewarrows.electricsheep.net;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import com.pewpewarrows.electricsheep.activities.OAuthAccountActivity;
import com.pewpewarrows.electricsheep.log.Log;
import android.accounts.AbstractAccountAuthenticator;
import android.accounts.Account;
import android.accounts.AccountAuthenticatorResponse;
import android.accounts.AccountManager;
import android.accounts.NetworkErrorException;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
/**
* TODO: This desperately needs a better name!
*/
public abstract class OAuthAuthenticator extends AbstractAccountAuthenticator {
private static final String TAG = OAuthAuthenticator.class.getName();
@SuppressWarnings("rawtypes")
protected Class mAccountActivityKlass;
protected String mAccountType;
protected String mOAuthTokenType;
protected String mOAuthSecretType;
private final Context mContext;
public OAuthAuthenticator(Context context) {
super(context);
mContext = context;
}
@SuppressWarnings("unchecked")
- protected void extractInfoFromActiviy() {
+ protected void extractInfoFromActivity() {
try {
Method m = mAccountActivityKlass.getMethod("getAccountType",
new Class[] {});
mAccountType = (String) m.invoke(null);
m = mAccountActivityKlass.getMethod("getOAuthTokenType",
new Class[] {});
mOAuthTokenType = (String) m.invoke(null);
m = mAccountActivityKlass.getMethod("getOAuthSecretType",
new Class[] {});
mOAuthSecretType = (String) m.invoke(null);
} catch (NoSuchMethodException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvocationTargetException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**
* {@inheritDoc}
*/
@Override
public Bundle addAccount(AccountAuthenticatorResponse response,
String accountType, String authTokenType,
String[] requiredFeatures, Bundle options)
throws NetworkErrorException {
Log.v(TAG, "OAuth addAccount()");
Bundle result = new Bundle();
if (!accountType.equals(mAccountType)) {
result.putString(AccountManager.KEY_ERROR_MESSAGE, String.format(
"Invalid accountType sent to OAuth: %s", accountType));
return result;
}
// Purposefully ignoring requiredFeatures. OAuth has none.
addAuthActivityToBundle(response, authTokenType, result);
return result;
}
/**
* @param response
* @param authTokenType
* @param bundle
*/
private void addAuthActivityToBundle(AccountAuthenticatorResponse response,
String authTokenType, Bundle bundle) {
Intent intent = new Intent(mContext, mAccountActivityKlass);
intent.putExtra(OAuthAccountActivity.PARAM_AUTHTOKEN_TYPE,
authTokenType);
intent.putExtra(AccountManager.KEY_ACCOUNT_AUTHENTICATOR_RESPONSE,
response);
bundle.putParcelable(AccountManager.KEY_INTENT, intent);
}
/**
* {@inheritDoc}
*/
@Override
public Bundle confirmCredentials(AccountAuthenticatorResponse response,
Account account, Bundle options) throws NetworkErrorException {
Log.v(TAG, "OAuth confirmCredentials()");
// There is no "confirm credentials" equivalent for OAuth, since
// everything is handled through the browser.
// TODO: return null; instead?
throw new UnsupportedOperationException();
}
/**
* {@inheritDoc}
*/
@Override
public Bundle editProperties(AccountAuthenticatorResponse response,
String accountType) {
Log.v(TAG, "OAuth editProperties()");
// Core OAuth has no properties. This may be overridden.
// TODO: should this send a user to some sort of OAuth browser page for
// the specific service?
throw new UnsupportedOperationException();
}
/**
* {@inheritDoc}
*/
@Override
public Bundle getAuthToken(AccountAuthenticatorResponse response,
Account account, String authTokenType, Bundle options)
throws NetworkErrorException {
Log.v(TAG, "OAuth getAuthToken()");
Bundle result = new Bundle();
if (!authTokenType.equals(mOAuthTokenType)
|| !authTokenType.equals(mOAuthSecretType)) {
result.putString(AccountManager.KEY_ERROR_MESSAGE, String.format(
"Invalid OAuth authTokenType: %s", authTokenType));
return result;
}
/*
* OAuth by default has no way to re-request an authToken. The whole
* multi-step workflow must be repeated. For particular OAuth providers
* such as Facebook who provide extensions for expiring tokens,
* override this method with custom logic.
*/
addAuthActivityToBundle(response, authTokenType, result);
return result;
}
/**
* {@inheritDoc}
*/
@Override
public String getAuthTokenLabel(String authTokenType) {
Log.v(TAG, "OAuth getAuthTokenLabel()");
if (authTokenType.equals(mOAuthTokenType)) {
return "OAuth Token";
} else if (authTokenType.equals(mOAuthSecretType)) {
return "OAuth Token Secret";
}
return "";
}
/**
* {@inheritDoc}
*/
@Override
public Bundle hasFeatures(AccountAuthenticatorResponse response,
Account account, String[] features) throws NetworkErrorException {
Log.v(TAG, "OAuth hasFeatues()");
// Features are definable per-authenticator. OAuth has none.
Bundle result = new Bundle();
result.putBoolean(AccountManager.KEY_BOOLEAN_RESULT, false);
return result;
}
/**
* {@inheritDoc}
*/
@Override
public Bundle updateCredentials(AccountAuthenticatorResponse response,
Account account, String authTokenType, Bundle options)
throws NetworkErrorException {
Log.v(TAG, "OAuth updateCredentials()");
// Updating credentials makes no sense in the context of OAuth.
// TODO: return null; instead?
throw new UnsupportedOperationException();
}
}
| true | true | protected void extractInfoFromActiviy() {
try {
Method m = mAccountActivityKlass.getMethod("getAccountType",
new Class[] {});
mAccountType = (String) m.invoke(null);
m = mAccountActivityKlass.getMethod("getOAuthTokenType",
new Class[] {});
mOAuthTokenType = (String) m.invoke(null);
m = mAccountActivityKlass.getMethod("getOAuthSecretType",
new Class[] {});
mOAuthSecretType = (String) m.invoke(null);
} catch (NoSuchMethodException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvocationTargetException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
| protected void extractInfoFromActivity() {
try {
Method m = mAccountActivityKlass.getMethod("getAccountType",
new Class[] {});
mAccountType = (String) m.invoke(null);
m = mAccountActivityKlass.getMethod("getOAuthTokenType",
new Class[] {});
mOAuthTokenType = (String) m.invoke(null);
m = mAccountActivityKlass.getMethod("getOAuthSecretType",
new Class[] {});
mOAuthSecretType = (String) m.invoke(null);
} catch (NoSuchMethodException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvocationTargetException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
|
diff --git a/bundles/org.eclipse.equinox.p2.repository.tools/src_ant/org/eclipse/equinox/p2/internal/repository/tools/tasks/Repo2RunnableTask.java b/bundles/org.eclipse.equinox.p2.repository.tools/src_ant/org/eclipse/equinox/p2/internal/repository/tools/tasks/Repo2RunnableTask.java
index f8fb89e26..5c84ff036 100644
--- a/bundles/org.eclipse.equinox.p2.repository.tools/src_ant/org/eclipse/equinox/p2/internal/repository/tools/tasks/Repo2RunnableTask.java
+++ b/bundles/org.eclipse.equinox.p2.repository.tools/src_ant/org/eclipse/equinox/p2/internal/repository/tools/tasks/Repo2RunnableTask.java
@@ -1,57 +1,57 @@
/*******************************************************************************
* Copyright (c) 2009 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.equinox.p2.internal.repository.tools.tasks;
import java.util.List;
import org.apache.tools.ant.BuildException;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.equinox.internal.provisional.p2.core.ProvisionException;
import org.eclipse.equinox.p2.internal.repository.tools.Repo2Runnable;
/**
* Ant task which calls the "repo to runnable" application. This application takes an
* existing p2 repository (local or remote), iterates over its list of IUs, and fetches
* all of the corresponding artifacts to a user-specified location. Once fetched, the
* artifacts will be in "runnable" form... that is directory-based bundles will be
* extracted into folders and packed JAR files will be un-packed.
*
* @since 1.0
*/
public class Repo2RunnableTask extends AbstractRepositoryTask {
/*
* Constructor for the class. Create a new instance of the application
* so we can populate it with attributes.
*/
public Repo2RunnableTask() {
super();
this.application = new Repo2Runnable();
}
/* (non-Javadoc)
* @see org.apache.tools.ant.Task#execute()
*/
public void execute() throws BuildException {
try {
prepareSourceRepos();
application.initializeRepos(null);
List ius = prepareIUs();
- if (ius == null || ius.size() == 0)
+ if ((ius == null || ius.size() == 0) && (sourceRepos == null || sourceRepos.isEmpty()))
throw new BuildException("Need to specify either a non-empty source metadata repository or a valid list of IUs.");
application.setSourceIUs(ius);
IStatus result = application.run(null);
if (result.matches(IStatus.ERROR))
throw new ProvisionException(result);
} catch (ProvisionException e) {
throw new BuildException("Error occurred while transforming repository.", e);
}
}
}
| true | true | public void execute() throws BuildException {
try {
prepareSourceRepos();
application.initializeRepos(null);
List ius = prepareIUs();
if (ius == null || ius.size() == 0)
throw new BuildException("Need to specify either a non-empty source metadata repository or a valid list of IUs.");
application.setSourceIUs(ius);
IStatus result = application.run(null);
if (result.matches(IStatus.ERROR))
throw new ProvisionException(result);
} catch (ProvisionException e) {
throw new BuildException("Error occurred while transforming repository.", e);
}
}
| public void execute() throws BuildException {
try {
prepareSourceRepos();
application.initializeRepos(null);
List ius = prepareIUs();
if ((ius == null || ius.size() == 0) && (sourceRepos == null || sourceRepos.isEmpty()))
throw new BuildException("Need to specify either a non-empty source metadata repository or a valid list of IUs.");
application.setSourceIUs(ius);
IStatus result = application.run(null);
if (result.matches(IStatus.ERROR))
throw new ProvisionException(result);
} catch (ProvisionException e) {
throw new BuildException("Error occurred while transforming repository.", e);
}
}
|
diff --git a/src/toritools/io/Importer.java b/src/toritools/io/Importer.java
index 27902eb..18792d6 100644
--- a/src/toritools/io/Importer.java
+++ b/src/toritools/io/Importer.java
@@ -1,218 +1,218 @@
package toritools.io;
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Graphics2D;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.HashMap;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import toritools.entity.Entity;
import toritools.entity.Level;
import toritools.entity.ReservedTypes;
import toritools.entity.sprite.AbstractSprite.AbstractSpriteAdapter;
import toritools.entity.sprite.ImageSprite;
import toritools.map.ToriMapIO;
import toritools.map.VariableCase;
import toritools.math.Vector2;
import toritools.xml.ToriXML;
public class Importer {
/**
* Imports the entity template. Sets basic template stuff.
*
* @param file
* @return
* @throws FileNotFoundException
*/
public static Entity importEntity(final File file, final HashMap<String, String> instanceMap)
throws FileNotFoundException {
VariableCase entityMap = ToriMapIO.readVariables(file);
if (instanceMap != null)
entityMap.getVariables().putAll(instanceMap);
Entity e = new Entity();
e.getVariableCase().getVariables().putAll(entityMap.getVariables());
- e.setFile(file.getPath());
+ e.setFile(file.getPath().replace("\\", "/"));
/**
* Extract the basic template data.
*/
// DIMENSION
try {
e.setDim(new Vector2(Float.parseFloat(entityMap.getVar("dimensions.x")), Float.parseFloat(entityMap
.getVar("dimensions.y"))));
} catch (Exception er) {
e.setDim(new Vector2());
}
// SOLID
try {
e.setSolid(Boolean.parseBoolean(entityMap.getVar("solid").trim()));
} catch (Exception er) {
e.setSolid(false);
}
// ID
String id;
if ((id = entityMap.getVar("id")) != null) {
e.getVariableCase().setVar("id", id);
}
// TITLE
e.setType(entityMap.getVar("type"));
if (e.getType() == null)
e.setType("DEFAULT");
String inGame = entityMap.getVar("sprite.sheet");
if (inGame != null) {
// The key is sprite but not editor
String[] value = inGame.split(",");
int x = 1, y = 1;
if (value.length != 1) {
x = Integer.parseInt(value[1].trim());
y = Integer.parseInt(value[2].trim());
}
// 0: file, 1: x tile, 2: y tile
- File spriteFile = new File(file.getParent() + "/" + value[0].trim());
+ File spriteFile = new File(file.getParent().replace("\\", "/") + "/" + value[0].trim());
if (spriteFile.canRead()) {
e.setSprite(new ImageSprite(spriteFile, x, y));
}
inGame = entityMap.getVar("sprite.timeScale");
if (inGame != null) {
e.getSprite().setTimeStretch(Integer.parseInt(inGame.trim()));
}
}
inGame = entityMap.getVar("sprite.sizeOffset");
if (inGame != null) {
e.getSprite().setsizeOffset(Integer.parseInt(inGame.trim()));
}
inGame = entityMap.getVar("visible");
if (inGame != null) {
e.setVisible(Boolean.parseBoolean(inGame.trim()));
}
return e;
}
public static Level importLevel(final File file) throws FileNotFoundException {
Level level = new Level();
Document doc = ToriXML.parse(file);
HashMap<String, String> props = ToriMapIO.readMap(doc.getElementsByTagName("level").item(0).getAttributes()
.getNamedItem("map").getNodeValue());
level.getVariableCase().setVariables(props);
if (level.getVariableCase().getVar("dimensions.x") == null) {
level.setDim(new Vector2(1000, 1000));
level.getVariableCase().setVar("dimensions.x", "" + 1000);
level.getVariableCase().setVar("dimensions.y", "" + 1000);
} else {
level.setDim(new Vector2(level.getVariableCase().getFloat("dimensions.x"), level.getVariableCase()
.getFloat("dimensions.y")));
}
// Extract level instance info
// levelSize.width = Integer.parseInt(props.get("width"));
// levelSize.height = Integer.parseInt(props.get("height"));
File workingDirectory = file.getParentFile();
NodeList entities = doc.getElementsByTagName("entity");
for (int i = 0; i < entities.getLength(); i++) {
Node e = entities.item(i);
HashMap<String, String> mapData = ToriMapIO.readMap(e.getAttributes().getNamedItem("map").getNodeValue());
// int layer = Integer.parseInt(mapData.get("layer"));
float x = Float.parseFloat(mapData.get("position.x"));
float y = Float.parseFloat(mapData.get("position.y"));
if (mapData.get("type") != null && mapData.get("type").equals(ReservedTypes.WALL.toString())) {
float w = Float.parseFloat(mapData.get("dimensions.x"));
float h = Float.parseFloat(mapData.get("dimensions.y"));
Entity wall = makeWall(new Vector2(x, y), new Vector2(w, h));
wall.setLayer(Integer.parseInt(mapData.get("layer")));
wall.getVariableCase().getVariables().putAll(mapData);
level.spawnEntity(wall);
} else if (mapData.get("type") != null && mapData.get("type").equals(ReservedTypes.BACKGROUND.toString())) {
float w = Float.parseFloat(mapData.get("dimensions.x"));
float h = Float.parseFloat(mapData.get("dimensions.y"));
File imageFile = new File(workingDirectory + mapData.get("image"));
int xTile = Integer.parseInt(mapData.get("xTile"));
int yTile = Integer.parseInt(mapData.get("yTile"));
int xTiles = Integer.parseInt(mapData.get("xTiles"));
int yTiles = Integer.parseInt(mapData.get("yTiles"));
Entity background = makeBackground(new Vector2(x, y), new Vector2(w, h), imageFile,
mapData.get("image"), xTile, yTile, xTiles, yTiles);
background.setLayer(Integer.parseInt(mapData.get("layer")));
background.getVariableCase().getVariables().putAll(mapData);
level.spawnEntity(background);
} else {
File f = new File(workingDirectory + mapData.get("template"));
Entity ent = importEntity(f, mapData);
ent.setPos(new Vector2((float) x, (float) y));
ent.setLayer(Integer.parseInt(mapData.get("layer")));
// layerEditor.setLayerVisibility(layer, true);
ent.getVariableCase().getVariables().putAll(mapData);
ent.setFile(f.getPath());
level.spawnEntity(ent);
}
}
return level;
}
public static Entity makeBackground(final Vector2 pos, final Vector2 dim, final File image,
final String relativeLink, final int x, final int y, final int xTiles, final int yTiles) {
Entity bg = new Entity();
bg.setPos(pos);
bg.setDim(dim);
bg.getVariableCase().setVar("xTiles", xTiles + "");
bg.getVariableCase().setVar("yTiles", yTiles + "");
bg.getVariableCase().setVar("xTile", x + "");
bg.getVariableCase().setVar("yTile", y + "");
bg.getVariableCase().setVar("image", relativeLink);
bg.getVariableCase().setVar("dimensions.x", dim.x + "");
bg.getVariableCase().setVar("dimensions.y", dim.y + "");
bg.setType(ReservedTypes.BACKGROUND);
bg.getVariableCase().setVar("type", bg.getType());
bg.setSprite(new ImageSprite(image, xTiles, yTiles));
bg.getSprite().setFrame(x);
bg.getSprite().setCycle(y);
return bg;
}
public static Entity makeWall(final Vector2 pos, final Vector2 dim) {
Entity wall = new Entity();
wall.setPos(pos);
wall.setDim(dim);
wall.getVariableCase().setVar("dimensions.x", dim.x + "");
wall.getVariableCase().setVar("dimensions.y", dim.y + "");
wall.setSolid(true);
wall.getVariableCase().setVar("solid", "true");
wall.setType(ReservedTypes.WALL);
wall.getVariableCase().setVar("type", ReservedTypes.WALL);
wall.setVisible(false);
wall.getVariableCase().setVar("visible", "false");
wall.setSprite(new AbstractSpriteAdapter() {
@Override
public void draw(final Graphics2D g, final Entity self) {
g.setStroke(new BasicStroke(2));
g.setColor(Color.RED);
g.drawLine(self.getPos().getWidth(), self.getPos().getHeight(), self.getPos().getWidth()
+ self.getDim().getWidth(), self.getPos().getHeight() + self.getDim().getHeight());
g.drawLine(self.getPos().getWidth(), self.getPos().getHeight() + self.getDim().getHeight(), self
.getPos().getWidth() + self.getDim().getWidth(), self.getPos().getHeight());
g.draw3DRect(self.getPos().getWidth(), self.getPos().getHeight(), self.getDim().getWidth(), self
.getDim().getHeight(), true);
}
});
return wall;
}
}
| false | true | public static Entity importEntity(final File file, final HashMap<String, String> instanceMap)
throws FileNotFoundException {
VariableCase entityMap = ToriMapIO.readVariables(file);
if (instanceMap != null)
entityMap.getVariables().putAll(instanceMap);
Entity e = new Entity();
e.getVariableCase().getVariables().putAll(entityMap.getVariables());
e.setFile(file.getPath());
/**
* Extract the basic template data.
*/
// DIMENSION
try {
e.setDim(new Vector2(Float.parseFloat(entityMap.getVar("dimensions.x")), Float.parseFloat(entityMap
.getVar("dimensions.y"))));
} catch (Exception er) {
e.setDim(new Vector2());
}
// SOLID
try {
e.setSolid(Boolean.parseBoolean(entityMap.getVar("solid").trim()));
} catch (Exception er) {
e.setSolid(false);
}
// ID
String id;
if ((id = entityMap.getVar("id")) != null) {
e.getVariableCase().setVar("id", id);
}
// TITLE
e.setType(entityMap.getVar("type"));
if (e.getType() == null)
e.setType("DEFAULT");
String inGame = entityMap.getVar("sprite.sheet");
if (inGame != null) {
// The key is sprite but not editor
String[] value = inGame.split(",");
int x = 1, y = 1;
if (value.length != 1) {
x = Integer.parseInt(value[1].trim());
y = Integer.parseInt(value[2].trim());
}
// 0: file, 1: x tile, 2: y tile
File spriteFile = new File(file.getParent() + "/" + value[0].trim());
if (spriteFile.canRead()) {
e.setSprite(new ImageSprite(spriteFile, x, y));
}
inGame = entityMap.getVar("sprite.timeScale");
if (inGame != null) {
e.getSprite().setTimeStretch(Integer.parseInt(inGame.trim()));
}
}
inGame = entityMap.getVar("sprite.sizeOffset");
if (inGame != null) {
e.getSprite().setsizeOffset(Integer.parseInt(inGame.trim()));
}
inGame = entityMap.getVar("visible");
if (inGame != null) {
e.setVisible(Boolean.parseBoolean(inGame.trim()));
}
return e;
}
| public static Entity importEntity(final File file, final HashMap<String, String> instanceMap)
throws FileNotFoundException {
VariableCase entityMap = ToriMapIO.readVariables(file);
if (instanceMap != null)
entityMap.getVariables().putAll(instanceMap);
Entity e = new Entity();
e.getVariableCase().getVariables().putAll(entityMap.getVariables());
e.setFile(file.getPath().replace("\\", "/"));
/**
* Extract the basic template data.
*/
// DIMENSION
try {
e.setDim(new Vector2(Float.parseFloat(entityMap.getVar("dimensions.x")), Float.parseFloat(entityMap
.getVar("dimensions.y"))));
} catch (Exception er) {
e.setDim(new Vector2());
}
// SOLID
try {
e.setSolid(Boolean.parseBoolean(entityMap.getVar("solid").trim()));
} catch (Exception er) {
e.setSolid(false);
}
// ID
String id;
if ((id = entityMap.getVar("id")) != null) {
e.getVariableCase().setVar("id", id);
}
// TITLE
e.setType(entityMap.getVar("type"));
if (e.getType() == null)
e.setType("DEFAULT");
String inGame = entityMap.getVar("sprite.sheet");
if (inGame != null) {
// The key is sprite but not editor
String[] value = inGame.split(",");
int x = 1, y = 1;
if (value.length != 1) {
x = Integer.parseInt(value[1].trim());
y = Integer.parseInt(value[2].trim());
}
// 0: file, 1: x tile, 2: y tile
File spriteFile = new File(file.getParent().replace("\\", "/") + "/" + value[0].trim());
if (spriteFile.canRead()) {
e.setSprite(new ImageSprite(spriteFile, x, y));
}
inGame = entityMap.getVar("sprite.timeScale");
if (inGame != null) {
e.getSprite().setTimeStretch(Integer.parseInt(inGame.trim()));
}
}
inGame = entityMap.getVar("sprite.sizeOffset");
if (inGame != null) {
e.getSprite().setsizeOffset(Integer.parseInt(inGame.trim()));
}
inGame = entityMap.getVar("visible");
if (inGame != null) {
e.setVisible(Boolean.parseBoolean(inGame.trim()));
}
return e;
}
|
diff --git a/Session/src/au/edu/uts/eng/remotelabs/schedserver/session/impl/SessionExpiryChecker.java b/Session/src/au/edu/uts/eng/remotelabs/schedserver/session/impl/SessionExpiryChecker.java
index 16af68e0..95ce49a5 100644
--- a/Session/src/au/edu/uts/eng/remotelabs/schedserver/session/impl/SessionExpiryChecker.java
+++ b/Session/src/au/edu/uts/eng/remotelabs/schedserver/session/impl/SessionExpiryChecker.java
@@ -1,264 +1,264 @@
/**
* SAHARA Scheduling Server
*
* Schedules and assigns local laboratory rigs.
*
* @license See LICENSE in the top level directory for complete license terms.
*
* Copyright (c) 2010, University of Technology, Sydney
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the University of Technology, Sydney nor the names
* of its contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* @author Michael Diponio (mdiponio)
* @date 8th April 2010
*/
package au.edu.uts.eng.remotelabs.schedserver.session.impl;
import java.util.Date;
import java.util.List;
import org.hibernate.Criteria;
import org.hibernate.HibernateException;
import org.hibernate.criterion.Restrictions;
import au.edu.uts.eng.remotelabs.schedserver.bookings.BookingEngineService;
import au.edu.uts.eng.remotelabs.schedserver.dataaccess.DataAccessActivator;
import au.edu.uts.eng.remotelabs.schedserver.dataaccess.entities.ResourcePermission;
import au.edu.uts.eng.remotelabs.schedserver.dataaccess.entities.Session;
import au.edu.uts.eng.remotelabs.schedserver.logger.Logger;
import au.edu.uts.eng.remotelabs.schedserver.logger.LoggerActivator;
import au.edu.uts.eng.remotelabs.schedserver.queuer.QueueInfo;
import au.edu.uts.eng.remotelabs.schedserver.rigoperations.RigNotifier;
import au.edu.uts.eng.remotelabs.schedserver.rigoperations.RigReleaser;
import au.edu.uts.eng.remotelabs.schedserver.session.SessionActivator;
/**
* Either expires or extends the time of all sessions which are close to
* the session duration duration.
*/
public class SessionExpiryChecker implements Runnable
{
/** Minimum extension duration. */
public static final int TIME_EXT = 300;
/** Logger. */
private Logger logger;
/** Flag to specify if this is a test run. */
private boolean notTest = true;
public SessionExpiryChecker()
{
this.logger = LoggerActivator.getLogger();
}
@SuppressWarnings("unchecked")
@Override
public void run()
{
org.hibernate.Session db = null;
try
{
if ((db = DataAccessActivator.getNewSession()) == null)
{
this.logger.warn("Unable to obtain a database session, for rig session status checker. Ensure the " +
"SchedulingServer-DataAccess bundle is installed and active.");
return;
}
boolean kicked = false;
Criteria query = db.createCriteria(Session.class);
query.add(Restrictions.eq("active", Boolean.TRUE))
.add(Restrictions.isNotNull("assignmentTime"));
Date now = new Date();
List<Session> sessions = query.list();
for (Session ses : sessions)
{
ResourcePermission perm = ses.getResourcePermission();
int remaining = ses.getDuration() + // The session time
(perm.getAllowedExtensions() - ses.getExtensions()) * perm.getExtensionDuration() - // Extension time
Math.round((System.currentTimeMillis() - ses.getAssignmentTime().getTime()) / 1000); // In session time
int extension = perm.getSessionDuration() - ses.getDuration() >= TIME_EXT ? TIME_EXT : perm.getExtensionDuration();
/******************************************************************
* For sessions that have been marked for termination, terminate *
* those that have no more remaining time. *
******************************************************************/
if (ses.isInGrace())
{
if (remaining <= 0)
{
ses.setActive(false);
ses.setRemovalTime(now);
db.beginTransaction();
db.flush();
db.getTransaction().commit();
this.logger.info("Terminating session for " + ses.getUserNamespace() + ':' + ses.getUserName() + " on " +
ses.getAssignedRigName() + " because it is expired and the grace period has elapsed.");
if (this.notTest) new RigReleaser().release(ses, db);
}
}
/******************************************************************
* For sessions with remaining time less than the grace duration: *
* 1) If the session has no remaining extensions, mark it for *
* termination. *
* 2) Else, if the session rig is queued, mark it for *
* termination. *
* 3) Else, extend the sessions time. *
******************************************************************/
else if (remaining < ses.getRig().getRigType().getLogoffGraceDuration())
{
BookingEngineService service;
/* Need to make a decision whether to extend time or set for termination. */
- if (ses.getExtensions() == 0 && ses.getDuration() == perm.getSessionDuration())
+ if (ses.getExtensions() <= 0 && ses.getDuration() >= perm.getSessionDuration())
{
this.logger.info("Session for " + ses.getUserNamespace() + ':' + ses.getUserName() + " on " +
"rig " + ses.getAssignedRigName() + " is expired and cannot be extended. Marking " +
"session for expiry and giving a grace period.");
ses.setInGrace(true);
ses.setRemovalReason("No more session time extensions.");
db.beginTransaction();
db.flush();
db.getTransaction().commit();
/* Notification warning. */
if (this.notTest) new RigNotifier().notify("Your session will expire in " + remaining + " seconds. " +
"Please finish and exit.", ses, db);
}
else if (QueueInfo.isQueued(ses.getRig(), db) ||
((service = SessionActivator.getBookingService()) != null &&
!service.extendQueuedSession(ses.getRig(), ses, extension, db)))
{
this.logger.info("Session for " + ses.getUserNamespace() + ':' + ses.getUserName() + " on " +
"rig " + ses.getAssignedRigName() + " is expired and the rig is queued or booked. " +
"Marking session for expiry and giving a grace period.");
ses.setInGrace(true);
ses.setRemovalReason("Rig is queued or booked.");
db.beginTransaction();
db.flush();
db.getTransaction().commit();
/* Notification warning. */
if (this.notTest) new RigNotifier().notify("Your session will end in " + remaining + " seconds. " +
"After this you be removed, so please logoff.", ses, db);
}
else
{
this.logger.info("Session for " + ses.getUserNamespace() + ':' + ses.getUserName() + " on " +
"rig " + ses.getAssignedRigName() + " is expired and is having its session time " +
"extended by " + extension + " seconds.");
if (perm.getSessionDuration() - ses.getDuration() >= TIME_EXT)
{
ses.setDuration(ses.getDuration() + extension);
}
else
{
ses.setExtensions((short)(ses.getExtensions() - 1));
}
db.beginTransaction();
db.flush();
db.getTransaction().commit();
}
}
/******************************************************************
* For sessions created with a user class that can be kicked off, *
* if the rig is queued, the user is kicked off immediately. *
******************************************************************/
/* DODGY The 'kicked' flag is to only allow a single kick per
* pass. This is allow time for the rig to be released and take the
* queued session. This is a hack at best, but should be addressed
* by a released - cleaning up meta state. */
else if (!kicked && QueueInfo.isQueued(ses.getRig(), db) && perm.getUserClass().isKickable())
{
kicked = true;
/* No grace is being given. */
this.logger.info("A kickable user is using a rig that is queued for, so they are being removed.");
ses.setActive(false);
ses.setRemovalTime(now);
ses.setRemovalReason("Resource was queued and user was kickable.");
db.beginTransaction();
db.flush();
db.getTransaction().commit();
if (this.notTest) new RigReleaser().release(ses, db);
}
/******************************************************************
* Finally, for sessions with time still remaining, check *
* session activity timeout - if it is not ignored and is ready *
* for use. *
******************************************************************/
else if (ses.isReady() && ses.getResourcePermission().isActivityDetected() &&
(System.currentTimeMillis() - ses.getActivityLastUpdated().getTime()) / 1000 > perm.getSessionActivityTimeout())
{
/* Check activity. */
if (this.notTest) new SessionIdleKicker().kickIfIdle(ses, db);
}
}
}
catch (HibernateException hex)
{
this.logger.error("Failed to query database to expired sessions (Exception: " +
hex.getClass().getName() + ", Message:" + hex.getMessage() + ").");
if (db != null && db.getTransaction() != null)
{
try
{
db.getTransaction().rollback();
}
catch (HibernateException ex)
{
this.logger.error("Exception rolling back session expiry transaction (Exception: " +
ex.getClass().getName() + "," + " Message: " + ex.getMessage() + ").");
}
}
}
catch (Throwable thr)
{
this.logger.error("Caught unchecked exception in session expirty checker. Exception: " + thr.getClass() +
", message: " + thr.getMessage() + '.');
}
finally
{
try
{
if (db != null) db.close();
}
catch (HibernateException ex)
{
this.logger.error("Exception cleaning up database session (Exception: " + ex.getClass().getName() + "," +
" Message: " + ex.getMessage() + ").");
}
}
}
}
| true | true | public void run()
{
org.hibernate.Session db = null;
try
{
if ((db = DataAccessActivator.getNewSession()) == null)
{
this.logger.warn("Unable to obtain a database session, for rig session status checker. Ensure the " +
"SchedulingServer-DataAccess bundle is installed and active.");
return;
}
boolean kicked = false;
Criteria query = db.createCriteria(Session.class);
query.add(Restrictions.eq("active", Boolean.TRUE))
.add(Restrictions.isNotNull("assignmentTime"));
Date now = new Date();
List<Session> sessions = query.list();
for (Session ses : sessions)
{
ResourcePermission perm = ses.getResourcePermission();
int remaining = ses.getDuration() + // The session time
(perm.getAllowedExtensions() - ses.getExtensions()) * perm.getExtensionDuration() - // Extension time
Math.round((System.currentTimeMillis() - ses.getAssignmentTime().getTime()) / 1000); // In session time
int extension = perm.getSessionDuration() - ses.getDuration() >= TIME_EXT ? TIME_EXT : perm.getExtensionDuration();
/******************************************************************
* For sessions that have been marked for termination, terminate *
* those that have no more remaining time. *
******************************************************************/
if (ses.isInGrace())
{
if (remaining <= 0)
{
ses.setActive(false);
ses.setRemovalTime(now);
db.beginTransaction();
db.flush();
db.getTransaction().commit();
this.logger.info("Terminating session for " + ses.getUserNamespace() + ':' + ses.getUserName() + " on " +
ses.getAssignedRigName() + " because it is expired and the grace period has elapsed.");
if (this.notTest) new RigReleaser().release(ses, db);
}
}
/******************************************************************
* For sessions with remaining time less than the grace duration: *
* 1) If the session has no remaining extensions, mark it for *
* termination. *
* 2) Else, if the session rig is queued, mark it for *
* termination. *
* 3) Else, extend the sessions time. *
******************************************************************/
else if (remaining < ses.getRig().getRigType().getLogoffGraceDuration())
{
BookingEngineService service;
/* Need to make a decision whether to extend time or set for termination. */
if (ses.getExtensions() == 0 && ses.getDuration() == perm.getSessionDuration())
{
this.logger.info("Session for " + ses.getUserNamespace() + ':' + ses.getUserName() + " on " +
"rig " + ses.getAssignedRigName() + " is expired and cannot be extended. Marking " +
"session for expiry and giving a grace period.");
ses.setInGrace(true);
ses.setRemovalReason("No more session time extensions.");
db.beginTransaction();
db.flush();
db.getTransaction().commit();
/* Notification warning. */
if (this.notTest) new RigNotifier().notify("Your session will expire in " + remaining + " seconds. " +
"Please finish and exit.", ses, db);
}
else if (QueueInfo.isQueued(ses.getRig(), db) ||
((service = SessionActivator.getBookingService()) != null &&
!service.extendQueuedSession(ses.getRig(), ses, extension, db)))
{
this.logger.info("Session for " + ses.getUserNamespace() + ':' + ses.getUserName() + " on " +
"rig " + ses.getAssignedRigName() + " is expired and the rig is queued or booked. " +
"Marking session for expiry and giving a grace period.");
ses.setInGrace(true);
ses.setRemovalReason("Rig is queued or booked.");
db.beginTransaction();
db.flush();
db.getTransaction().commit();
/* Notification warning. */
if (this.notTest) new RigNotifier().notify("Your session will end in " + remaining + " seconds. " +
"After this you be removed, so please logoff.", ses, db);
}
else
{
this.logger.info("Session for " + ses.getUserNamespace() + ':' + ses.getUserName() + " on " +
"rig " + ses.getAssignedRigName() + " is expired and is having its session time " +
"extended by " + extension + " seconds.");
if (perm.getSessionDuration() - ses.getDuration() >= TIME_EXT)
{
ses.setDuration(ses.getDuration() + extension);
}
else
{
ses.setExtensions((short)(ses.getExtensions() - 1));
}
db.beginTransaction();
db.flush();
db.getTransaction().commit();
}
}
/******************************************************************
* For sessions created with a user class that can be kicked off, *
* if the rig is queued, the user is kicked off immediately. *
******************************************************************/
/* DODGY The 'kicked' flag is to only allow a single kick per
* pass. This is allow time for the rig to be released and take the
* queued session. This is a hack at best, but should be addressed
* by a released - cleaning up meta state. */
else if (!kicked && QueueInfo.isQueued(ses.getRig(), db) && perm.getUserClass().isKickable())
{
kicked = true;
/* No grace is being given. */
this.logger.info("A kickable user is using a rig that is queued for, so they are being removed.");
ses.setActive(false);
ses.setRemovalTime(now);
ses.setRemovalReason("Resource was queued and user was kickable.");
db.beginTransaction();
db.flush();
db.getTransaction().commit();
if (this.notTest) new RigReleaser().release(ses, db);
}
/******************************************************************
* Finally, for sessions with time still remaining, check *
* session activity timeout - if it is not ignored and is ready *
* for use. *
******************************************************************/
else if (ses.isReady() && ses.getResourcePermission().isActivityDetected() &&
(System.currentTimeMillis() - ses.getActivityLastUpdated().getTime()) / 1000 > perm.getSessionActivityTimeout())
{
/* Check activity. */
if (this.notTest) new SessionIdleKicker().kickIfIdle(ses, db);
}
}
}
catch (HibernateException hex)
{
this.logger.error("Failed to query database to expired sessions (Exception: " +
hex.getClass().getName() + ", Message:" + hex.getMessage() + ").");
if (db != null && db.getTransaction() != null)
{
try
{
db.getTransaction().rollback();
}
catch (HibernateException ex)
{
this.logger.error("Exception rolling back session expiry transaction (Exception: " +
ex.getClass().getName() + "," + " Message: " + ex.getMessage() + ").");
}
}
}
catch (Throwable thr)
{
this.logger.error("Caught unchecked exception in session expirty checker. Exception: " + thr.getClass() +
", message: " + thr.getMessage() + '.');
}
finally
{
try
{
if (db != null) db.close();
}
catch (HibernateException ex)
{
this.logger.error("Exception cleaning up database session (Exception: " + ex.getClass().getName() + "," +
" Message: " + ex.getMessage() + ").");
}
}
}
| public void run()
{
org.hibernate.Session db = null;
try
{
if ((db = DataAccessActivator.getNewSession()) == null)
{
this.logger.warn("Unable to obtain a database session, for rig session status checker. Ensure the " +
"SchedulingServer-DataAccess bundle is installed and active.");
return;
}
boolean kicked = false;
Criteria query = db.createCriteria(Session.class);
query.add(Restrictions.eq("active", Boolean.TRUE))
.add(Restrictions.isNotNull("assignmentTime"));
Date now = new Date();
List<Session> sessions = query.list();
for (Session ses : sessions)
{
ResourcePermission perm = ses.getResourcePermission();
int remaining = ses.getDuration() + // The session time
(perm.getAllowedExtensions() - ses.getExtensions()) * perm.getExtensionDuration() - // Extension time
Math.round((System.currentTimeMillis() - ses.getAssignmentTime().getTime()) / 1000); // In session time
int extension = perm.getSessionDuration() - ses.getDuration() >= TIME_EXT ? TIME_EXT : perm.getExtensionDuration();
/******************************************************************
* For sessions that have been marked for termination, terminate *
* those that have no more remaining time. *
******************************************************************/
if (ses.isInGrace())
{
if (remaining <= 0)
{
ses.setActive(false);
ses.setRemovalTime(now);
db.beginTransaction();
db.flush();
db.getTransaction().commit();
this.logger.info("Terminating session for " + ses.getUserNamespace() + ':' + ses.getUserName() + " on " +
ses.getAssignedRigName() + " because it is expired and the grace period has elapsed.");
if (this.notTest) new RigReleaser().release(ses, db);
}
}
/******************************************************************
* For sessions with remaining time less than the grace duration: *
* 1) If the session has no remaining extensions, mark it for *
* termination. *
* 2) Else, if the session rig is queued, mark it for *
* termination. *
* 3) Else, extend the sessions time. *
******************************************************************/
else if (remaining < ses.getRig().getRigType().getLogoffGraceDuration())
{
BookingEngineService service;
/* Need to make a decision whether to extend time or set for termination. */
if (ses.getExtensions() <= 0 && ses.getDuration() >= perm.getSessionDuration())
{
this.logger.info("Session for " + ses.getUserNamespace() + ':' + ses.getUserName() + " on " +
"rig " + ses.getAssignedRigName() + " is expired and cannot be extended. Marking " +
"session for expiry and giving a grace period.");
ses.setInGrace(true);
ses.setRemovalReason("No more session time extensions.");
db.beginTransaction();
db.flush();
db.getTransaction().commit();
/* Notification warning. */
if (this.notTest) new RigNotifier().notify("Your session will expire in " + remaining + " seconds. " +
"Please finish and exit.", ses, db);
}
else if (QueueInfo.isQueued(ses.getRig(), db) ||
((service = SessionActivator.getBookingService()) != null &&
!service.extendQueuedSession(ses.getRig(), ses, extension, db)))
{
this.logger.info("Session for " + ses.getUserNamespace() + ':' + ses.getUserName() + " on " +
"rig " + ses.getAssignedRigName() + " is expired and the rig is queued or booked. " +
"Marking session for expiry and giving a grace period.");
ses.setInGrace(true);
ses.setRemovalReason("Rig is queued or booked.");
db.beginTransaction();
db.flush();
db.getTransaction().commit();
/* Notification warning. */
if (this.notTest) new RigNotifier().notify("Your session will end in " + remaining + " seconds. " +
"After this you be removed, so please logoff.", ses, db);
}
else
{
this.logger.info("Session for " + ses.getUserNamespace() + ':' + ses.getUserName() + " on " +
"rig " + ses.getAssignedRigName() + " is expired and is having its session time " +
"extended by " + extension + " seconds.");
if (perm.getSessionDuration() - ses.getDuration() >= TIME_EXT)
{
ses.setDuration(ses.getDuration() + extension);
}
else
{
ses.setExtensions((short)(ses.getExtensions() - 1));
}
db.beginTransaction();
db.flush();
db.getTransaction().commit();
}
}
/******************************************************************
* For sessions created with a user class that can be kicked off, *
* if the rig is queued, the user is kicked off immediately. *
******************************************************************/
/* DODGY The 'kicked' flag is to only allow a single kick per
* pass. This is allow time for the rig to be released and take the
* queued session. This is a hack at best, but should be addressed
* by a released - cleaning up meta state. */
else if (!kicked && QueueInfo.isQueued(ses.getRig(), db) && perm.getUserClass().isKickable())
{
kicked = true;
/* No grace is being given. */
this.logger.info("A kickable user is using a rig that is queued for, so they are being removed.");
ses.setActive(false);
ses.setRemovalTime(now);
ses.setRemovalReason("Resource was queued and user was kickable.");
db.beginTransaction();
db.flush();
db.getTransaction().commit();
if (this.notTest) new RigReleaser().release(ses, db);
}
/******************************************************************
* Finally, for sessions with time still remaining, check *
* session activity timeout - if it is not ignored and is ready *
* for use. *
******************************************************************/
else if (ses.isReady() && ses.getResourcePermission().isActivityDetected() &&
(System.currentTimeMillis() - ses.getActivityLastUpdated().getTime()) / 1000 > perm.getSessionActivityTimeout())
{
/* Check activity. */
if (this.notTest) new SessionIdleKicker().kickIfIdle(ses, db);
}
}
}
catch (HibernateException hex)
{
this.logger.error("Failed to query database to expired sessions (Exception: " +
hex.getClass().getName() + ", Message:" + hex.getMessage() + ").");
if (db != null && db.getTransaction() != null)
{
try
{
db.getTransaction().rollback();
}
catch (HibernateException ex)
{
this.logger.error("Exception rolling back session expiry transaction (Exception: " +
ex.getClass().getName() + "," + " Message: " + ex.getMessage() + ").");
}
}
}
catch (Throwable thr)
{
this.logger.error("Caught unchecked exception in session expirty checker. Exception: " + thr.getClass() +
", message: " + thr.getMessage() + '.');
}
finally
{
try
{
if (db != null) db.close();
}
catch (HibernateException ex)
{
this.logger.error("Exception cleaning up database session (Exception: " + ex.getClass().getName() + "," +
" Message: " + ex.getMessage() + ").");
}
}
}
|
diff --git a/src/test/java/fr/jamgotchian/abcd/core/controlflow/RPSTTest.java b/src/test/java/fr/jamgotchian/abcd/core/controlflow/RPSTTest.java
index 98fbf08..79051d7 100644
--- a/src/test/java/fr/jamgotchian/abcd/core/controlflow/RPSTTest.java
+++ b/src/test/java/fr/jamgotchian/abcd/core/controlflow/RPSTTest.java
@@ -1,137 +1,138 @@
/*
* Copyright (C) 2011 Geoffroy Jamgotchian <geoffroy.jamgotchian at gmail.com>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package fr.jamgotchian.abcd.core.controlflow;
import fr.jamgotchian.abcd.core.ABCDContext;
import fr.jamgotchian.abcd.core.util.SimplestFormatter;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;
import java.util.logging.ConsoleHandler;
import java.util.logging.Handler;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
/**
*
* @author Geoffroy Jamgotchian <geoffroy.jamgotchian at gmail.com>
*/
public class RPSTTest {
private static final Logger logger = Logger.getLogger(RPSTTest.class.getName());
public RPSTTest() {
}
@BeforeClass
public static void setUpClass() throws Exception {
// root logger configuration
Logger rootLogger = Logger.getLogger(ABCDContext.class.getPackage().getName());
ConsoleHandler handler = new ConsoleHandler();
handler.setFormatter(new SimplestFormatter());
handler.setLevel(Level.FINEST);
rootLogger.setLevel(Level.ALL);
rootLogger.addHandler(handler);
rootLogger.setUseParentHandlers(false);
}
@AfterClass
public static void tearDownClass() throws Exception {
Logger rootLogger = Logger.getLogger(ABCDContext.class.getPackage().getName());
for (Handler handler : rootLogger.getHandlers()) {
handler.close();
}
Thread.sleep(1000);
}
@Before
public void setUp() {
}
@After
public void tearDown() {
}
@Test
public void testCase1() throws IOException {
BasicBlock a = new BasicBlockTestImpl("a");
BasicBlock b = new BasicBlockTestImpl("b");
BasicBlock c = new BasicBlockTestImpl("c");
BasicBlock d = new BasicBlockTestImpl("d");
BasicBlock e = new BasicBlockTestImpl("e");
BasicBlock f = new BasicBlockTestImpl("f");
BasicBlock g = new BasicBlockTestImpl("g");
BasicBlock h = new BasicBlockTestImpl("h");
BasicBlock i = new BasicBlockTestImpl("i");
BasicBlock j = new BasicBlockTestImpl("j");
BasicBlock k = new BasicBlockTestImpl("k");
BasicBlock l = new BasicBlockTestImpl("l");
ControlFlowGraphImpl cfg = new ControlFlowGraphImpl("Test", a, e);
cfg.addBasicBlock(b);
cfg.addBasicBlock(c);
cfg.addBasicBlock(d);
cfg.addBasicBlock(f);
cfg.addBasicBlock(g);
cfg.addBasicBlock(h);
cfg.addBasicBlock(i);
cfg.addBasicBlock(j);
cfg.addBasicBlock(k);
cfg.addBasicBlock(l);
cfg.addEdge(a, g);
cfg.addEdge(g, b);
cfg.addEdge(g, l);
cfg.addEdge(b, f);
cfg.addEdge(b, c);
cfg.addEdge(f, c);
cfg.addEdge(c, d);
cfg.addEdge(l, d);
cfg.addEdge(d, g);
cfg.addEdge(d, e);
cfg.addEdge(a, h);
cfg.addEdge(h, i);
cfg.addEdge(h, j);
cfg.addEdge(i, j);
cfg.addEdge(j, i);
cfg.addEdge(i, k);
cfg.addEdge(j, k);
cfg.addEdge(k, e);
cfg.updateDominatorInfo();
+ cfg.updatePostDominatorInfo();
cfg.performDepthFirstSearch();
Writer writer = new FileWriter("/tmp/RPSTTest_CFG.dot");
try {
cfg.export(writer, new BasicBlockRangeAttributeFactory(),
new EdgeAttributeFactory(false));
} finally {
writer.close();
}
RPST rpst = new RPST(cfg);
writer = new FileWriter("/tmp/RPSTTest_RPST.dot");
try {
rpst.export(writer);
} finally {
writer.close();
}
}
}
| true | true | public void testCase1() throws IOException {
BasicBlock a = new BasicBlockTestImpl("a");
BasicBlock b = new BasicBlockTestImpl("b");
BasicBlock c = new BasicBlockTestImpl("c");
BasicBlock d = new BasicBlockTestImpl("d");
BasicBlock e = new BasicBlockTestImpl("e");
BasicBlock f = new BasicBlockTestImpl("f");
BasicBlock g = new BasicBlockTestImpl("g");
BasicBlock h = new BasicBlockTestImpl("h");
BasicBlock i = new BasicBlockTestImpl("i");
BasicBlock j = new BasicBlockTestImpl("j");
BasicBlock k = new BasicBlockTestImpl("k");
BasicBlock l = new BasicBlockTestImpl("l");
ControlFlowGraphImpl cfg = new ControlFlowGraphImpl("Test", a, e);
cfg.addBasicBlock(b);
cfg.addBasicBlock(c);
cfg.addBasicBlock(d);
cfg.addBasicBlock(f);
cfg.addBasicBlock(g);
cfg.addBasicBlock(h);
cfg.addBasicBlock(i);
cfg.addBasicBlock(j);
cfg.addBasicBlock(k);
cfg.addBasicBlock(l);
cfg.addEdge(a, g);
cfg.addEdge(g, b);
cfg.addEdge(g, l);
cfg.addEdge(b, f);
cfg.addEdge(b, c);
cfg.addEdge(f, c);
cfg.addEdge(c, d);
cfg.addEdge(l, d);
cfg.addEdge(d, g);
cfg.addEdge(d, e);
cfg.addEdge(a, h);
cfg.addEdge(h, i);
cfg.addEdge(h, j);
cfg.addEdge(i, j);
cfg.addEdge(j, i);
cfg.addEdge(i, k);
cfg.addEdge(j, k);
cfg.addEdge(k, e);
cfg.updateDominatorInfo();
cfg.performDepthFirstSearch();
Writer writer = new FileWriter("/tmp/RPSTTest_CFG.dot");
try {
cfg.export(writer, new BasicBlockRangeAttributeFactory(),
new EdgeAttributeFactory(false));
} finally {
writer.close();
}
RPST rpst = new RPST(cfg);
writer = new FileWriter("/tmp/RPSTTest_RPST.dot");
try {
rpst.export(writer);
} finally {
writer.close();
}
}
| public void testCase1() throws IOException {
BasicBlock a = new BasicBlockTestImpl("a");
BasicBlock b = new BasicBlockTestImpl("b");
BasicBlock c = new BasicBlockTestImpl("c");
BasicBlock d = new BasicBlockTestImpl("d");
BasicBlock e = new BasicBlockTestImpl("e");
BasicBlock f = new BasicBlockTestImpl("f");
BasicBlock g = new BasicBlockTestImpl("g");
BasicBlock h = new BasicBlockTestImpl("h");
BasicBlock i = new BasicBlockTestImpl("i");
BasicBlock j = new BasicBlockTestImpl("j");
BasicBlock k = new BasicBlockTestImpl("k");
BasicBlock l = new BasicBlockTestImpl("l");
ControlFlowGraphImpl cfg = new ControlFlowGraphImpl("Test", a, e);
cfg.addBasicBlock(b);
cfg.addBasicBlock(c);
cfg.addBasicBlock(d);
cfg.addBasicBlock(f);
cfg.addBasicBlock(g);
cfg.addBasicBlock(h);
cfg.addBasicBlock(i);
cfg.addBasicBlock(j);
cfg.addBasicBlock(k);
cfg.addBasicBlock(l);
cfg.addEdge(a, g);
cfg.addEdge(g, b);
cfg.addEdge(g, l);
cfg.addEdge(b, f);
cfg.addEdge(b, c);
cfg.addEdge(f, c);
cfg.addEdge(c, d);
cfg.addEdge(l, d);
cfg.addEdge(d, g);
cfg.addEdge(d, e);
cfg.addEdge(a, h);
cfg.addEdge(h, i);
cfg.addEdge(h, j);
cfg.addEdge(i, j);
cfg.addEdge(j, i);
cfg.addEdge(i, k);
cfg.addEdge(j, k);
cfg.addEdge(k, e);
cfg.updateDominatorInfo();
cfg.updatePostDominatorInfo();
cfg.performDepthFirstSearch();
Writer writer = new FileWriter("/tmp/RPSTTest_CFG.dot");
try {
cfg.export(writer, new BasicBlockRangeAttributeFactory(),
new EdgeAttributeFactory(false));
} finally {
writer.close();
}
RPST rpst = new RPST(cfg);
writer = new FileWriter("/tmp/RPSTTest_RPST.dot");
try {
rpst.export(writer);
} finally {
writer.close();
}
}
|
diff --git a/android/src/com/freshplanet/flurry/functions/analytics/LogErrorFunction.java b/android/src/com/freshplanet/flurry/functions/analytics/LogErrorFunction.java
index 73c9a15..e42f5de 100644
--- a/android/src/com/freshplanet/flurry/functions/analytics/LogErrorFunction.java
+++ b/android/src/com/freshplanet/flurry/functions/analytics/LogErrorFunction.java
@@ -1,83 +1,83 @@
//////////////////////////////////////////////////////////////////////////////////////
//
// Copyright 2012 Freshplanet (http://freshplanet.com | [email protected])
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
//////////////////////////////////////////////////////////////////////////////////////
package com.freshplanet.flurry.functions.analytics;
import android.util.Log;
import com.adobe.fre.FREContext;
import com.adobe.fre.FREFunction;
import com.adobe.fre.FREInvalidObjectException;
import com.adobe.fre.FREObject;
import com.adobe.fre.FRETypeMismatchException;
import com.adobe.fre.FREWrongThreadException;
import com.flurry.android.FlurryAgent;
public class LogErrorFunction implements FREFunction {
private static String TAG = "LogErrorFunction";
@Override
public FREObject call(FREContext arg0, FREObject[] arg1) {
String errorId = null;
try {
errorId = arg1[0].getAsString();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (FRETypeMismatchException e) {
e.printStackTrace();
} catch (FREInvalidObjectException e) {
e.printStackTrace();
} catch (FREWrongThreadException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
String message = "";
try {
message = arg1[1].getAsString();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (FRETypeMismatchException e) {
e.printStackTrace();
} catch (FREInvalidObjectException e) {
e.printStackTrace();
} catch (FREWrongThreadException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
if (errorId != null)
{
- FlurryAgent.onError(errorId, message, null);
+ FlurryAgent.onError(errorId, message, "");
} else
{
Log.e(TAG, "errorId is null");
}
return null;
}
}
| true | true | public FREObject call(FREContext arg0, FREObject[] arg1) {
String errorId = null;
try {
errorId = arg1[0].getAsString();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (FRETypeMismatchException e) {
e.printStackTrace();
} catch (FREInvalidObjectException e) {
e.printStackTrace();
} catch (FREWrongThreadException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
String message = "";
try {
message = arg1[1].getAsString();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (FRETypeMismatchException e) {
e.printStackTrace();
} catch (FREInvalidObjectException e) {
e.printStackTrace();
} catch (FREWrongThreadException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
if (errorId != null)
{
FlurryAgent.onError(errorId, message, null);
} else
{
Log.e(TAG, "errorId is null");
}
return null;
}
| public FREObject call(FREContext arg0, FREObject[] arg1) {
String errorId = null;
try {
errorId = arg1[0].getAsString();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (FRETypeMismatchException e) {
e.printStackTrace();
} catch (FREInvalidObjectException e) {
e.printStackTrace();
} catch (FREWrongThreadException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
String message = "";
try {
message = arg1[1].getAsString();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (FRETypeMismatchException e) {
e.printStackTrace();
} catch (FREInvalidObjectException e) {
e.printStackTrace();
} catch (FREWrongThreadException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
if (errorId != null)
{
FlurryAgent.onError(errorId, message, "");
} else
{
Log.e(TAG, "errorId is null");
}
return null;
}
|
diff --git a/src/core/org/pathvisio/view/Label.java b/src/core/org/pathvisio/view/Label.java
index 2efe1c6e..f0daf0a8 100644
--- a/src/core/org/pathvisio/view/Label.java
+++ b/src/core/org/pathvisio/view/Label.java
@@ -1,259 +1,260 @@
// PathVisio,
// a tool for data visualization and analysis using Biological Pathways
// Copyright 2006-2007 BiGCaT Bioinformatics
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
package org.pathvisio.view;
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import java.awt.Shape;
import java.awt.font.TextAttribute;
import java.awt.geom.Rectangle2D;
import java.awt.geom.RoundRectangle2D;
import java.text.AttributedString;
import org.pathvisio.model.PathwayElement;
import org.pathvisio.model.OutlineType;
public class Label extends GraphicsShape
{
private static final long serialVersionUID = 1L;
public static final int M_INITIAL_FONTSIZE = 10 * 15;
public static final int M_INITIAL_WIDTH = 80 * 15;
public static final int M_INITIAL_HEIGHT = 20 * 15;
public static final double M_ARCSIZE = 225;
double getFontSize()
{
return gdata.getMFontSize() * canvas.getZoomFactor();
}
void setFontSize(double v)
{
gdata.setMFontSize(v / canvas.getZoomFactor());
}
/**
* Constructor for this class
* @param canvas - the VPathway this label will be part of
*/
public Label(VPathway canvas, PathwayElement o)
{
super(canvas, o);
setHandleLocation();
}
public int getNaturalOrder() {
return VPathway.DRAW_ORDER_LABEL;
}
public String getLabelText() {
return gdata.getTextLabel();
}
String prevText = "";
// public void adjustWidthToText() {
// if(gdata.getTextLabel().equals(prevText)) return;
//
// prevText = getLabelText();
//
// Point mts = mComputeTextSize();
//
// //Keep center location
// double mWidth = mts.x;
// double mHeight = mts.y;
//
// listen = false; //Disable listener
// gdata.setMLeft(gdata.getMLeft() - (mWidth - gdata.getMWidth())/2);
// gdata.setMTop(gdata.getMTop() - (mHeight - gdata.getMHeight())/2);
// gdata.setMWidth(mWidth);
// gdata.setMHeight(mHeight);
// listen = true; //Enable listener
//
// setHandleLocation();
// }
// private Text t;
// public void createTextControl()
// {
// Color background = canvas.getShell().getDisplay()
// .getSystemColor(SWT.COLOR_INFO_BACKGROUND);
//
// Composite textComposite = new Composite(canvas, SWT.NONE);
// textComposite.setLayout(new GridLayout());
// textComposite.setLocation(getVCenterX(), getVCenterY() - 10);
// textComposite.setBackground(background);
//
// org.eclipse.swt.widgets.Label label = new org.eclipse.swt.widgets.Label(textComposite, SWT.CENTER);
// label.setText("Specify label:");
// label.setBackground(background);
// t = new Text(textComposite, SWT.SINGLE | SWT.BORDER);
// t.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
// t.addSelectionListener(new SelectionAdapter() {
// public void widgetDefaultSelected(SelectionEvent e) {
// disposeTextControl();
// }
// });
//
// t.setFocus();
//
// Button b = new Button(textComposite, SWT.PUSH);
// b.setText("OK");
// b.addSelectionListener(new SelectionAdapter() {
// public void widgetSelected(SelectionEvent e) {
// disposeTextControl();
// }
// });
//
// textComposite.pack();
// }
protected Rectangle2D getTextBounds(Graphics2D g) {
Rectangle2D tb = null;
if(g != null) {
tb = g.getFontMetrics(getVFont()).getStringBounds(getLabelText(), g);
tb.setRect(getVLeft() + tb.getX(), getVTop() + tb.getY(), tb.getWidth(), tb.getHeight());
} else { //No graphics context, we can only guess...
tb = getBoxBounds(true);
}
return tb;
}
protected Rectangle2D getBoxBounds(boolean stroke)
{
return getVShape(stroke).getBounds2D();
}
protected Dimension computeTextSize(Graphics2D g) {
Rectangle2D tb = getTextBounds(g);
return new Dimension((int)tb.getWidth(), (int)tb.getHeight());
}
// protected void disposeTextControl()
// {
// gdata.setTextLabel(t.getText());
// Composite c = t.getParent();
// c.setVisible(false);
// c.dispose();
// }
double getVFontSize()
{
return vFromM(gdata.getMFontSize());
}
Font getVFont() {
String name = gdata.getFontName();
int style = getVFontStyle();
int size = (int)getVFontSize();
return new Font(name, style, size);
}
AttributedString getVAttributedString() {
AttributedString ats = new AttributedString(gdata.getTextLabel());
if(gdata.isStrikethru()) {
ats.addAttribute(TextAttribute.STRIKETHROUGH, TextAttribute.STRIKETHROUGH_ON);
}
if(gdata.isUnderline()) {
ats.addAttribute(TextAttribute.UNDERLINE, TextAttribute.UNDERLINE_ON);
}
ats.addAttribute(TextAttribute.FONT, getVFont());
return ats;
}
Graphics2D g2d = null; //last Graphics2D for determining text size
public void doDraw(Graphics2D g)
{
if(g2d != null) g2d.dispose();
g2d = (Graphics2D)g.create();
if(isSelected()) {
g.setColor(selectColor);
} else {
g.setColor(gdata.getColor());
}
Font f = getVFont();
g.setFont(f);
Rectangle area = getBoxBounds(true).getBounds();
Shape outline = null;
switch (gdata.getOutline())
{
case RECTANGLE:
- outline = new Rectangle2D.Double(getVLeft(), getVTop(), getVWidth(), getVHeight());
+ double lw = defaultStroke.getLineWidth();
+ outline = new Rectangle2D.Double(getVLeft(), getVTop(), getVWidth() - lw, getVHeight() - lw);
break;
case ROUNDED_RECTANGLE:
outline = new RoundRectangle2D.Double(
getVLeft(), getVTop(), getVWidth(), getVHeight(),
vFromM (M_ARCSIZE), vFromM (M_ARCSIZE));
break;
case NONE:
outline = null;
break;
}
if (outline != null)
{
g.draw (outline);
}
// don't draw label outside box
g.clip (new Rectangle (area.x - 1, area.y - 1, area.width + 1, area.height + 1));
String label = gdata.getTextLabel();
AttributedString ats = getVAttributedString();
Rectangle2D tb = g.getFontMetrics().getStringBounds(ats.getIterator(), 0, label.length(), g);
g.drawString(ats.getIterator(), area.x + (int)(area.width / 2) - (int)(tb.getWidth() / 2),
area.y + (int)(area.height / 2) + (int)(tb.getHeight() / 2));
if(isHighlighted())
{
Color hc = getHighlightColor();
g.setColor(new Color (hc.getRed(), hc.getGreen(), hc.getBlue(), 128));
g.setStroke (new BasicStroke());
Rectangle2D r = new Rectangle2D.Double(getVLeft(), getVTop(), getVWidth(), getVHeight());
g.fill(r);
}
}
// public void gmmlObjectModified(PathwayEvent e) {
// if(listen) {
// super.gmmlObjectModified(e);
// adjustWidthToText();
// }
// }
/**
* Outline of a label is determined by
* - position of the handles
* - size of the text
* Because the text can sometimes be larger than the handles
*/
protected Shape getVOutline()
{
Rectangle2D bb = getBoxBounds(true);
Rectangle2D tb = getTextBounds(g2d);
tb.add(bb);
return tb;
}
}
| true | true | public void doDraw(Graphics2D g)
{
if(g2d != null) g2d.dispose();
g2d = (Graphics2D)g.create();
if(isSelected()) {
g.setColor(selectColor);
} else {
g.setColor(gdata.getColor());
}
Font f = getVFont();
g.setFont(f);
Rectangle area = getBoxBounds(true).getBounds();
Shape outline = null;
switch (gdata.getOutline())
{
case RECTANGLE:
outline = new Rectangle2D.Double(getVLeft(), getVTop(), getVWidth(), getVHeight());
break;
case ROUNDED_RECTANGLE:
outline = new RoundRectangle2D.Double(
getVLeft(), getVTop(), getVWidth(), getVHeight(),
vFromM (M_ARCSIZE), vFromM (M_ARCSIZE));
break;
case NONE:
outline = null;
break;
}
if (outline != null)
{
g.draw (outline);
}
// don't draw label outside box
g.clip (new Rectangle (area.x - 1, area.y - 1, area.width + 1, area.height + 1));
String label = gdata.getTextLabel();
AttributedString ats = getVAttributedString();
Rectangle2D tb = g.getFontMetrics().getStringBounds(ats.getIterator(), 0, label.length(), g);
g.drawString(ats.getIterator(), area.x + (int)(area.width / 2) - (int)(tb.getWidth() / 2),
area.y + (int)(area.height / 2) + (int)(tb.getHeight() / 2));
if(isHighlighted())
{
Color hc = getHighlightColor();
g.setColor(new Color (hc.getRed(), hc.getGreen(), hc.getBlue(), 128));
g.setStroke (new BasicStroke());
Rectangle2D r = new Rectangle2D.Double(getVLeft(), getVTop(), getVWidth(), getVHeight());
g.fill(r);
}
}
| public void doDraw(Graphics2D g)
{
if(g2d != null) g2d.dispose();
g2d = (Graphics2D)g.create();
if(isSelected()) {
g.setColor(selectColor);
} else {
g.setColor(gdata.getColor());
}
Font f = getVFont();
g.setFont(f);
Rectangle area = getBoxBounds(true).getBounds();
Shape outline = null;
switch (gdata.getOutline())
{
case RECTANGLE:
double lw = defaultStroke.getLineWidth();
outline = new Rectangle2D.Double(getVLeft(), getVTop(), getVWidth() - lw, getVHeight() - lw);
break;
case ROUNDED_RECTANGLE:
outline = new RoundRectangle2D.Double(
getVLeft(), getVTop(), getVWidth(), getVHeight(),
vFromM (M_ARCSIZE), vFromM (M_ARCSIZE));
break;
case NONE:
outline = null;
break;
}
if (outline != null)
{
g.draw (outline);
}
// don't draw label outside box
g.clip (new Rectangle (area.x - 1, area.y - 1, area.width + 1, area.height + 1));
String label = gdata.getTextLabel();
AttributedString ats = getVAttributedString();
Rectangle2D tb = g.getFontMetrics().getStringBounds(ats.getIterator(), 0, label.length(), g);
g.drawString(ats.getIterator(), area.x + (int)(area.width / 2) - (int)(tb.getWidth() / 2),
area.y + (int)(area.height / 2) + (int)(tb.getHeight() / 2));
if(isHighlighted())
{
Color hc = getHighlightColor();
g.setColor(new Color (hc.getRed(), hc.getGreen(), hc.getBlue(), 128));
g.setStroke (new BasicStroke());
Rectangle2D r = new Rectangle2D.Double(getVLeft(), getVTop(), getVWidth(), getVHeight());
g.fill(r);
}
}
|
diff --git a/src/play/modules/redis/RedisPlugin.java b/src/play/modules/redis/RedisPlugin.java
index f8c2569..5358915 100644
--- a/src/play/modules/redis/RedisPlugin.java
+++ b/src/play/modules/redis/RedisPlugin.java
@@ -1,142 +1,142 @@
package play.modules.redis;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.List;
import play.Logger;
import play.Play;
import play.PlayPlugin;
import play.cache.Cache;
import play.exceptions.ConfigurationException;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;
import redis.clients.jedis.JedisShardInfo;
import redis.clients.jedis.Protocol;
import redis.clients.jedis.ShardedJedis;
import redis.clients.jedis.ShardedJedisPool;
/**
* Play plugin for Redis.
*
* @author Tim Kral
*/
public class RedisPlugin extends PlayPlugin {
private boolean createdRedisCache;
private boolean createdRedis;
public static boolean isRedisCacheEnabled() {
return Play.configuration.getProperty("redis.cache", "disabled").equals("enabled");
}
@Override
public void onConfigurationRead() {
if (isRedisCacheEnabled()) {
if (Play.configuration.containsKey("redis.cache.url")) {
String redisCacheUrl = Play.configuration.getProperty("redis.cache.url");
Logger.info("Connecting to redis cache with %s", redisCacheUrl);
RedisConnectionInfo redisConnInfo = new RedisConnectionInfo(redisCacheUrl, Play.configuration.getProperty("redis.cache.timeout"));
RedisCacheImpl.connectionPool = redisConnInfo.getConnectionPool();
Cache.forcedCacheImpl = RedisCacheImpl.getInstance();
createdRedisCache = true;
} else {
throw new ConfigurationException("Bad configuration for redis cache: missing redis.cache.url");
}
}
}
@Override
public void onApplicationStart() {
if (Play.configuration.containsKey("redis.url")) {
String redisUrl = Play.configuration.getProperty("redis.url");
Logger.info("Connecting to redis with %s", redisUrl);
RedisConnectionInfo redisConnInfo = new RedisConnectionInfo(redisUrl, Play.configuration.getProperty("redis.timeout"));
RedisConnectionManager.connectionPool = redisConnInfo.getConnectionPool();
createdRedis = true;
} else if(Play.configuration.containsKey("redis.1.url")) {
int nb = 1;
List<JedisShardInfo> shards = new ArrayList<JedisShardInfo>();
while (Play.configuration.containsKey("redis." + nb + ".url")) {
RedisConnectionInfo redisConnInfo = new RedisConnectionInfo(Play.configuration.getProperty("redis." + nb + ".url"), Play.configuration.getProperty("redis.timeout"));
shards.add(redisConnInfo.getShardInfo());
nb++;
}
RedisConnectionManager.shardedConnectionPool = new ShardedJedisPool(new JedisPoolConfig(), shards, ShardedJedis.DEFAULT_KEY_TAG_PATTERN);
createdRedis = true;
} else {
if (!createdRedisCache) Logger.warn("No redis.url found in configuration. Redis will not be available.");
}
}
@Override
public void onApplicationStop() {
// Redis cache is destroyed in Cache.stop (see Play.stop)
if (createdRedis) RedisConnectionManager.destroy();
}
@Override
public void invocationFinally() {
if (createdRedisCache) RedisCacheImpl.closeCacheConnection();
if (createdRedis) RedisConnectionManager.closeConnection();
}
private static class RedisConnectionInfo {
private final String host;
private final int port;
private final String password;
private final int timeout;
RedisConnectionInfo(String redisUrl, String timeoutStr) {
URI redisUri;
try {
redisUri = new URI(redisUrl);
} catch (URISyntaxException e) {
throw new ConfigurationException("Bad configuration for redis: unable to parse redis url (" + redisUrl + ")");
}
host = redisUri.getHost();
- if (redisUri.getPort() < 0) {
+ if (redisUri.getPort() > 0) {
port = redisUri.getPort();
} else {
port = Protocol.DEFAULT_PORT;
}
String userInfo = redisUri.getUserInfo();
if (userInfo != null) {
String[] parsedUserInfo = userInfo.split(":");
password = parsedUserInfo[parsedUserInfo.length - 1];
} else {
password = null;
}
if (timeoutStr == null) {
timeout = Protocol.DEFAULT_TIMEOUT;
} else {
timeout = Integer.parseInt(timeoutStr);
}
}
JedisPool getConnectionPool() {
if (password == null) {
return new JedisPool(new JedisPoolConfig(), host, port, timeout);
}
return new JedisPool(new JedisPoolConfig(), host, port, timeout, password);
}
JedisShardInfo getShardInfo() {
JedisShardInfo si = new JedisShardInfo(host, port, timeout);
si.setPassword(password);
return si;
}
}
}
| true | true | RedisConnectionInfo(String redisUrl, String timeoutStr) {
URI redisUri;
try {
redisUri = new URI(redisUrl);
} catch (URISyntaxException e) {
throw new ConfigurationException("Bad configuration for redis: unable to parse redis url (" + redisUrl + ")");
}
host = redisUri.getHost();
if (redisUri.getPort() < 0) {
port = redisUri.getPort();
} else {
port = Protocol.DEFAULT_PORT;
}
String userInfo = redisUri.getUserInfo();
if (userInfo != null) {
String[] parsedUserInfo = userInfo.split(":");
password = parsedUserInfo[parsedUserInfo.length - 1];
} else {
password = null;
}
if (timeoutStr == null) {
timeout = Protocol.DEFAULT_TIMEOUT;
} else {
timeout = Integer.parseInt(timeoutStr);
}
}
| RedisConnectionInfo(String redisUrl, String timeoutStr) {
URI redisUri;
try {
redisUri = new URI(redisUrl);
} catch (URISyntaxException e) {
throw new ConfigurationException("Bad configuration for redis: unable to parse redis url (" + redisUrl + ")");
}
host = redisUri.getHost();
if (redisUri.getPort() > 0) {
port = redisUri.getPort();
} else {
port = Protocol.DEFAULT_PORT;
}
String userInfo = redisUri.getUserInfo();
if (userInfo != null) {
String[] parsedUserInfo = userInfo.split(":");
password = parsedUserInfo[parsedUserInfo.length - 1];
} else {
password = null;
}
if (timeoutStr == null) {
timeout = Protocol.DEFAULT_TIMEOUT;
} else {
timeout = Integer.parseInt(timeoutStr);
}
}
|
diff --git a/platform/configuration/platform/src/main/java/org/mayocat/configuration/gestalt/EntitiesGestaltConfigurationSource.java b/platform/configuration/platform/src/main/java/org/mayocat/configuration/gestalt/EntitiesGestaltConfigurationSource.java
index 444349bc..9b887f2d 100644
--- a/platform/configuration/platform/src/main/java/org/mayocat/configuration/gestalt/EntitiesGestaltConfigurationSource.java
+++ b/platform/configuration/platform/src/main/java/org/mayocat/configuration/gestalt/EntitiesGestaltConfigurationSource.java
@@ -1,215 +1,215 @@
package org.mayocat.configuration.gestalt;
import java.util.Map;
import javax.inject.Inject;
import org.mayocat.addons.model.AddonGroup;
import org.mayocat.configuration.GestaltConfigurationSource;
import org.mayocat.configuration.PlatformSettings;
import org.mayocat.configuration.general.GeneralSettings;
import org.mayocat.configuration.thumbnails.ThumbnailDefinition;
import org.mayocat.context.Execution;
import org.mayocat.meta.EntityMeta;
import org.mayocat.meta.EntityMetaRegistry;
import org.mayocat.model.AddonSource;
import org.mayocat.theme.Model;
import org.mayocat.theme.Theme;
import org.xwiki.component.annotation.Component;
import org.xwiki.component.annotation.InstantiationStrategy;
import org.xwiki.component.descriptor.ComponentInstantiationStrategy;
import com.google.common.collect.Maps;
/**
* @version $Id$
*/
@Component("entities")
@InstantiationStrategy(ComponentInstantiationStrategy.PER_LOOKUP)
public class EntitiesGestaltConfigurationSource implements GestaltConfigurationSource
{
@Inject
private PlatformSettings platformSettings;
@Inject
private EntityMetaRegistry entityMetaRegistry;
@Inject
private Execution execution;
@Override
public Object get()
{
Map<String, Map<String, Object>> entities = Maps.newLinkedHashMap();
for (EntityMeta meta : entityMetaRegistry.getEntities()) {
Map data = Maps.newHashMap();
entities.put(meta.getEntityName(), data);
}
Theme theme = execution.getContext().getTheme();
if (theme != null) {
addAddons(entities, theme.getAddons(), AddonSource.THEME);
addModels(entities, theme.getModels());
addThumbnails(entities, theme.getThumbnails());
}
addAddons(entities, platformSettings.getAddons(), AddonSource.PLATFORM);
return entities;
}
private void addThumbnails(Map<String, Map<String, Object>> entities, Map<String, ThumbnailDefinition> thumbnails)
{
// Step 1 : add thumbnails defined explicitly for some entities
for (String thumbnailKey : thumbnails.keySet()) {
ThumbnailDefinition thumbnailDefinition = thumbnails.get(thumbnailKey);
if (thumbnailDefinition.getEntities().isPresent()) {
for (String entity : thumbnailDefinition.getEntities().get()) {
addThumbnailDefinitionToEntity(entities, entity, "theme", thumbnailKey, thumbnailDefinition);
}
}
}
// Step 2 add thumbnails groups for all entities
for (String modelId : thumbnails.keySet()) {
ThumbnailDefinition thumbnailDefinition = thumbnails.get(modelId);
if (!thumbnailDefinition.getEntities().isPresent()) {
for (String entity : entities.keySet()) {
addThumbnailDefinitionToEntity(entities, entity, "theme", modelId, thumbnailDefinition);
}
}
}
}
private void addModels(Map<String, Map<String, Object>> entities, Map<String, Model> models)
{
// Step 1 : add models defined explicitly for some entities
for (String modelId : models.keySet()) {
Model model = models.get(modelId);
if (model.getEntities().isPresent()) {
for (String entity : model.getEntities().get()) {
addModelsToEntity(entities, entity, modelId, model);
}
}
}
// Step 2 add addon groups for all entities
for (String modelId : models.keySet()) {
Model model = models.get(modelId);
if (!model.getEntities().isPresent()) {
for (String entity : entities.keySet()) {
addModelsToEntity(entities, entity, modelId, model);
}
}
}
}
private void addAddons(Map<String, Map<String, Object>> entities, Map<String, AddonGroup> addons,
AddonSource source)
{
// Step 1 : add addon groups defined explicitly for some entities
for (String groupKey : addons.keySet()) {
AddonGroup group = addons.get(groupKey);
if (group.getEntities().isPresent()) {
for (String entity : group.getEntities().get()) {
addAddonGroupToEntity(entities, entity, groupKey, group, source);
}
}
}
// Step 2 add addon groups for all entities
for (String groupKey : addons.keySet()) {
AddonGroup group = addons.get(groupKey);
if (!group.getEntities().isPresent()) {
for (String entity : entities.keySet()) {
addAddonGroupToEntity(entities, entity, groupKey, group, source);
}
}
}
}
private interface EntitiesMapTransformation
{
void apply(Map<String, Object> entity, Object... arguments);
}
private void addThumbnailDefinitionToEntity(Map<String, Map<String, Object>> entities, String entity,
final String source, String modelId, ThumbnailDefinition thumbnailDefinition)
{
this.transformEntitiesMap(entities, entity, new EntitiesMapTransformation()
{
@Override
public void apply(Map<String, Object> entity, Object... arguments)
{
Map map;
if (entity.containsKey("thumbnails")) {
map = (Map) entity.get("thumbnails");
} else {
map = Maps.newHashMap();
}
if (!map.containsKey(source)) {
map.put(source, Maps.newHashMap());
}
((Map) map.get(source)).put(arguments[0], arguments[1]);
entity.put("thumbnails", map);
}
}, modelId, thumbnailDefinition);
}
private void addModelsToEntity(Map<String, Map<String, Object>> entities, String entity, String modelId,
Model model)
{
this.transformEntitiesMap(entities, entity, new EntitiesMapTransformation()
{
@Override
public void apply(Map<String, Object> entity, Object... arguments)
{
if (entity.containsKey("models")) {
((Map) entity.get("models")).put(arguments[0], arguments[1]);
} else {
Map map = Maps.newHashMap();
map.put(arguments[0], arguments[1]);
entity.put("models", map);
}
}
}, modelId, model);
}
private void addAddonGroupToEntity(Map<String, Map<String, Object>> entities, String entity, String groupKey,
AddonGroup group, AddonSource source)
{
this.transformEntitiesMap(entities, entity, new EntitiesMapTransformation()
{
@Override
public void apply(Map<String, Object> entity, Object... arguments)
{
if (!entity.containsKey("addons")) {
entity.put("addons", Maps.newHashMap());
}
Map sources = (Map) entity.get("addons");
addAddonGroupToSource(sources, arguments);
}
private void addAddonGroupToSource(Map sources, Object... arguments)
{
- if (!sources.containsKey(arguments[0])) {
+ if (!sources.containsKey(arguments[0].toString().toLowerCase())) {
sources.put(arguments[0].toString().toLowerCase(), Maps.newHashMap());
}
Map source = (Map) sources.get(arguments[0].toString().toLowerCase());
source.put(arguments[1], arguments[2]);
}
}, source, groupKey, group);
}
private void transformEntitiesMap(Map<String, Map<String, Object>> entities, String entity,
EntitiesMapTransformation transfornation,
Object... argument)
{
Map<String, Object> entityMap;
if (!entities.containsKey(entity)) {
entityMap = Maps.newLinkedHashMap();
entities.put(entity, entityMap);
}
entityMap = entities.get(entity);
transfornation.apply(entityMap, argument);
}
}
| true | true | private void addAddonGroupToEntity(Map<String, Map<String, Object>> entities, String entity, String groupKey,
AddonGroup group, AddonSource source)
{
this.transformEntitiesMap(entities, entity, new EntitiesMapTransformation()
{
@Override
public void apply(Map<String, Object> entity, Object... arguments)
{
if (!entity.containsKey("addons")) {
entity.put("addons", Maps.newHashMap());
}
Map sources = (Map) entity.get("addons");
addAddonGroupToSource(sources, arguments);
}
private void addAddonGroupToSource(Map sources, Object... arguments)
{
if (!sources.containsKey(arguments[0])) {
sources.put(arguments[0].toString().toLowerCase(), Maps.newHashMap());
}
Map source = (Map) sources.get(arguments[0].toString().toLowerCase());
source.put(arguments[1], arguments[2]);
}
}, source, groupKey, group);
}
| private void addAddonGroupToEntity(Map<String, Map<String, Object>> entities, String entity, String groupKey,
AddonGroup group, AddonSource source)
{
this.transformEntitiesMap(entities, entity, new EntitiesMapTransformation()
{
@Override
public void apply(Map<String, Object> entity, Object... arguments)
{
if (!entity.containsKey("addons")) {
entity.put("addons", Maps.newHashMap());
}
Map sources = (Map) entity.get("addons");
addAddonGroupToSource(sources, arguments);
}
private void addAddonGroupToSource(Map sources, Object... arguments)
{
if (!sources.containsKey(arguments[0].toString().toLowerCase())) {
sources.put(arguments[0].toString().toLowerCase(), Maps.newHashMap());
}
Map source = (Map) sources.get(arguments[0].toString().toLowerCase());
source.put(arguments[1], arguments[2]);
}
}, source, groupKey, group);
}
|
diff --git a/src/com/android/contacts/editor/RawContactEditorView.java b/src/com/android/contacts/editor/RawContactEditorView.java
index 118ca26a6..2d42a50cb 100644
--- a/src/com/android/contacts/editor/RawContactEditorView.java
+++ b/src/com/android/contacts/editor/RawContactEditorView.java
@@ -1,453 +1,454 @@
/*
* Copyright (C) 2009 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.contacts.editor;
import com.android.contacts.GroupMetaDataLoader;
import com.android.contacts.R;
import com.android.contacts.model.AccountType;
import com.android.contacts.model.AccountType.EditType;
import com.android.contacts.model.DataKind;
import com.android.contacts.model.EntityDelta;
import com.android.contacts.model.EntityDelta.ValuesDelta;
import com.android.contacts.model.EntityModifier;
import com.android.internal.util.Objects;
import android.content.Context;
import android.content.Entity;
import android.database.Cursor;
import android.provider.ContactsContract.CommonDataKinds.GroupMembership;
import android.provider.ContactsContract.CommonDataKinds.Organization;
import android.provider.ContactsContract.CommonDataKinds.Photo;
import android.provider.ContactsContract.CommonDataKinds.StructuredName;
import android.provider.ContactsContract.Contacts;
import android.provider.ContactsContract.Data;
import android.provider.ContactsContract.RawContacts;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.PopupMenu;
import android.widget.TextView;
import java.util.ArrayList;
/**
* Custom view that provides all the editor interaction for a specific
* {@link Contacts} represented through an {@link EntityDelta}. Callers can
* reuse this view and quickly rebuild its contents through
* {@link #setState(EntityDelta, AccountType, ViewIdGenerator)}.
* <p>
* Internal updates are performed against {@link ValuesDelta} so that the
* source {@link Entity} can be swapped out. Any state-based changes, such as
* adding {@link Data} rows or changing {@link EditType}, are performed through
* {@link EntityModifier} to ensure that {@link AccountType} are enforced.
*/
public class RawContactEditorView extends BaseRawContactEditorView {
private LayoutInflater mInflater;
private StructuredNameEditorView mName;
private PhoneticNameEditorView mPhoneticName;
private GroupMembershipView mGroupMembershipView;
private ViewGroup mFields;
private ImageView mAccountIcon;
private TextView mAccountTypeTextView;
private TextView mAccountNameTextView;
private Button mAddFieldButton;
private long mRawContactId = -1;
private boolean mAutoAddToDefaultGroup = true;
private Cursor mGroupMetaData;
private DataKind mGroupMembershipKind;
private EntityDelta mState;
private boolean mPhoneticNameAdded;
public RawContactEditorView(Context context) {
super(context);
}
public RawContactEditorView(Context context, AttributeSet attrs) {
super(context, attrs);
}
@Override
public void setEnabled(boolean enabled) {
super.setEnabled(enabled);
View view = getPhotoEditor();
if (view != null) {
view.setEnabled(enabled);
}
if (mName != null) {
mName.setEnabled(enabled);
}
if (mPhoneticName != null) {
mPhoneticName.setEnabled(enabled);
}
if (mFields != null) {
int count = mFields.getChildCount();
for (int i = 0; i < count; i++) {
mFields.getChildAt(i).setEnabled(enabled);
}
}
if (mGroupMembershipView != null) {
mGroupMembershipView.setEnabled(enabled);
}
mAddFieldButton.setEnabled(enabled);
}
@Override
protected void onFinishInflate() {
super.onFinishInflate();
mInflater = (LayoutInflater)getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
mName = (StructuredNameEditorView)findViewById(R.id.edit_name);
mName.setDeletable(false);
mPhoneticName = (PhoneticNameEditorView)findViewById(R.id.edit_phonetic_name);
mPhoneticName.setDeletable(false);
mFields = (ViewGroup)findViewById(R.id.sect_fields);
mAccountIcon = (ImageView) findViewById(R.id.account_icon);
mAccountTypeTextView = (TextView) findViewById(R.id.account_type);
mAccountNameTextView = (TextView) findViewById(R.id.account_name);
mAddFieldButton = (Button) findViewById(R.id.button_add_field);
mAddFieldButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
showAddInformationPopupWindow();
}
});
}
/**
* Set the internal state for this view, given a current
* {@link EntityDelta} state and the {@link AccountType} that
* apply to that state.
*/
@Override
public void setState(EntityDelta state, AccountType type, ViewIdGenerator vig,
boolean isProfile) {
mState = state;
// Remove any existing sections
mFields.removeAllViews();
// Bail if invalid state or account type
if (state == null || type == null) return;
setId(vig.getId(state, null, null, ViewIdGenerator.NO_VIEW_INDEX));
// Make sure we have a StructuredName and Organization
EntityModifier.ensureKindExists(state, type, StructuredName.CONTENT_ITEM_TYPE);
EntityModifier.ensureKindExists(state, type, Organization.CONTENT_ITEM_TYPE);
ValuesDelta values = state.getValues();
mRawContactId = values.getAsLong(RawContacts._ID);
// Fill in the account info
if (isProfile) {
String accountName = values.getAsString(RawContacts.ACCOUNT_NAME);
if (TextUtils.isEmpty(accountName)) {
mAccountNameTextView.setVisibility(View.GONE);
mAccountTypeTextView.setText(R.string.local_profile_title);
} else {
CharSequence accountType = type.getDisplayLabel(mContext);
mAccountTypeTextView.setText(mContext.getString(R.string.external_profile_title,
accountType));
mAccountNameTextView.setText(accountName);
}
} else {
String accountName = values.getAsString(RawContacts.ACCOUNT_NAME);
CharSequence accountType = type.getDisplayLabel(mContext);
if (TextUtils.isEmpty(accountType)) {
accountType = mContext.getString(R.string.account_phone);
}
if (!TextUtils.isEmpty(accountName)) {
mAccountNameTextView.setText(
mContext.getString(R.string.from_account_format, accountName));
}
mAccountTypeTextView.setText(
mContext.getString(R.string.account_type_format, accountType));
}
mAccountIcon.setImageDrawable(type.getDisplayIcon(mContext));
// Show photo editor when supported
EntityModifier.ensureKindExists(state, type, Photo.CONTENT_ITEM_TYPE);
setHasPhotoEditor((type.getKindForMimetype(Photo.CONTENT_ITEM_TYPE) != null));
getPhotoEditor().setEnabled(isEnabled());
mName.setEnabled(isEnabled());
mPhoneticName.setEnabled(isEnabled());
// Show and hide the appropriate views
mFields.setVisibility(View.VISIBLE);
mName.setVisibility(View.VISIBLE);
mPhoneticName.setVisibility(View.VISIBLE);
mGroupMembershipKind = type.getKindForMimetype(GroupMembership.CONTENT_ITEM_TYPE);
if (mGroupMembershipKind != null) {
mGroupMembershipView = (GroupMembershipView)mInflater.inflate(
R.layout.item_group_membership, mFields, false);
mGroupMembershipView.setKind(mGroupMembershipKind);
mGroupMembershipView.setEnabled(isEnabled());
}
// Create editor sections for each possible data kind
for (DataKind kind : type.getSortedDataKinds()) {
// Skip kind of not editable
if (!kind.editable) continue;
final String mimeType = kind.mimeType;
if (StructuredName.CONTENT_ITEM_TYPE.equals(mimeType)) {
// Handle special case editor for structured name
final ValuesDelta primary = state.getPrimaryEntry(mimeType);
mName.setValues(
type.getKindForMimetype(DataKind.PSEUDO_MIME_TYPE_DISPLAY_NAME),
primary, state, false, vig);
mPhoneticName.setValues(
type.getKindForMimetype(DataKind.PSEUDO_MIME_TYPE_PHONETIC_NAME),
primary, state, false, vig);
} else if (Photo.CONTENT_ITEM_TYPE.equals(mimeType)) {
// Handle special case editor for photos
final ValuesDelta primary = state.getPrimaryEntry(mimeType);
getPhotoEditor().setValues(kind, primary, state, false, vig);
} else if (GroupMembership.CONTENT_ITEM_TYPE.equals(mimeType)) {
if (mGroupMembershipView != null) {
mGroupMembershipView.setState(state);
}
} else if (Organization.CONTENT_ITEM_TYPE.equals(mimeType)) {
// Create the organization section
final KindSectionView section = (KindSectionView) mInflater.inflate(
R.layout.item_kind_section, mFields, false);
section.setTitleVisible(false);
section.setEnabled(isEnabled());
section.setState(kind, state, false, vig);
// If there is organization info for the contact already, display it
if (!section.isEmpty()) {
mFields.addView(section);
} else {
// Otherwise provide the user with an "add organization" button that shows the
// EditText fields only when clicked
final View organizationView = mInflater.inflate(
R.layout.organization_editor_view_switcher, mFields, false);
final View addOrganizationButton = organizationView.findViewById(
R.id.add_organization_button);
final ViewGroup organizationSectionViewContainer =
(ViewGroup) organizationView.findViewById(R.id.container);
organizationSectionViewContainer.addView(section);
// Setup the click listener for the "add organization" button
addOrganizationButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// Once the user expands the organization field, the user cannot
// collapse them again.
addOrganizationButton.setVisibility(View.GONE);
organizationSectionViewContainer.setVisibility(View.VISIBLE);
+ organizationSectionViewContainer.requestFocus();
}
});
mFields.addView(organizationView);
}
} else {
// Otherwise use generic section-based editors
if (kind.fieldList == null) continue;
final KindSectionView section = (KindSectionView)mInflater.inflate(
R.layout.item_kind_section, mFields, false);
section.setEnabled(isEnabled());
section.setState(kind, state, false, vig);
mFields.addView(section);
}
}
if (mGroupMembershipView != null) {
mFields.addView(mGroupMembershipView);
}
updatePhoneticNameVisibility();
addToDefaultGroupIfNeeded();
mAddFieldButton.setEnabled(isEnabled());
}
@Override
public void setGroupMetaData(Cursor groupMetaData) {
mGroupMetaData = groupMetaData;
addToDefaultGroupIfNeeded();
if (mGroupMembershipView != null) {
mGroupMembershipView.setGroupMetaData(groupMetaData);
}
}
public void setAutoAddToDefaultGroup(boolean flag) {
this.mAutoAddToDefaultGroup = flag;
}
/**
* If automatic addition to the default group was requested (see
* {@link #setAutoAddToDefaultGroup}, checks if the raw contact is in any
* group and if it is not adds it to the default group (in case of Google
* contacts that's "My Contacts").
*/
private void addToDefaultGroupIfNeeded() {
if (!mAutoAddToDefaultGroup || mGroupMetaData == null || mGroupMetaData.isClosed()
|| mState == null) {
return;
}
boolean hasGroupMembership = false;
ArrayList<ValuesDelta> entries = mState.getMimeEntries(GroupMembership.CONTENT_ITEM_TYPE);
if (entries != null) {
for (ValuesDelta values : entries) {
Long id = values.getAsLong(GroupMembership.GROUP_ROW_ID);
if (id != null && id.longValue() != 0) {
hasGroupMembership = true;
break;
}
}
}
if (!hasGroupMembership) {
long defaultGroupId = getDefaultGroupId();
if (defaultGroupId != -1) {
ValuesDelta entry = EntityModifier.insertChild(mState, mGroupMembershipKind);
entry.put(GroupMembership.GROUP_ROW_ID, defaultGroupId);
}
}
}
/**
* Returns the default group (e.g. "My Contacts") for the current raw contact's
* account. Returns -1 if there is no such group.
*/
private long getDefaultGroupId() {
String accountType = mState.getValues().getAsString(RawContacts.ACCOUNT_TYPE);
String accountName = mState.getValues().getAsString(RawContacts.ACCOUNT_NAME);
String accountDataSet = mState.getValues().getAsString(RawContacts.DATA_SET);
mGroupMetaData.moveToPosition(-1);
while (mGroupMetaData.moveToNext()) {
String name = mGroupMetaData.getString(GroupMetaDataLoader.ACCOUNT_NAME);
String type = mGroupMetaData.getString(GroupMetaDataLoader.ACCOUNT_TYPE);
String dataSet = mGroupMetaData.getString(GroupMetaDataLoader.DATA_SET);
if (name.equals(accountName) && type.equals(accountType)
&& Objects.equal(dataSet, accountDataSet)) {
long groupId = mGroupMetaData.getLong(GroupMetaDataLoader.GROUP_ID);
if (!mGroupMetaData.isNull(GroupMetaDataLoader.AUTO_ADD)
&& mGroupMetaData.getInt(GroupMetaDataLoader.AUTO_ADD) != 0) {
return groupId;
}
}
}
return -1;
}
public TextFieldsEditorView getNameEditor() {
return mName;
}
public TextFieldsEditorView getPhoneticNameEditor() {
return mPhoneticName;
}
private void updatePhoneticNameVisibility() {
boolean showByDefault =
getContext().getResources().getBoolean(R.bool.config_editor_include_phonetic_name);
if (showByDefault || mPhoneticName.hasData() || mPhoneticNameAdded) {
mPhoneticName.setVisibility(View.VISIBLE);
} else {
mPhoneticName.setVisibility(View.GONE);
}
}
@Override
public long getRawContactId() {
return mRawContactId;
}
private void showAddInformationPopupWindow() {
final ArrayList<KindSectionView> fields =
new ArrayList<KindSectionView>(mFields.getChildCount());
final PopupMenu popupMenu = new PopupMenu(getContext(), mAddFieldButton);
final Menu menu = popupMenu.getMenu();
for (int i = 0; i < mFields.getChildCount(); i++) {
View child = mFields.getChildAt(i);
if (child instanceof KindSectionView) {
final KindSectionView sectionView = (KindSectionView) child;
// If the section is already visible (has 1 or more editors), then don't offer the
// option to add this type of field in the popup menu
if (sectionView.getEditorCount() > 0) {
continue;
}
DataKind kind = sectionView.getKind();
// not a list and already exists? ignore
if (!kind.isList && sectionView.getEditorCount() != 0) {
continue;
}
if (DataKind.PSEUDO_MIME_TYPE_DISPLAY_NAME.equals(kind.mimeType)) {
continue;
}
if (DataKind.PSEUDO_MIME_TYPE_PHONETIC_NAME.equals(kind.mimeType)
&& mPhoneticName.getVisibility() == View.VISIBLE) {
continue;
}
menu.add(Menu.NONE, fields.size(), Menu.NONE, sectionView.getTitle());
fields.add(sectionView);
}
}
popupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
@Override
public boolean onMenuItemClick(MenuItem item) {
final KindSectionView view = fields.get(item.getItemId());
if (DataKind.PSEUDO_MIME_TYPE_PHONETIC_NAME.equals(view.getKind().mimeType)) {
mPhoneticNameAdded = true;
updatePhoneticNameVisibility();
} else {
view.addItem();
}
return true;
}
});
popupMenu.show();
}
}
| true | true | public void setState(EntityDelta state, AccountType type, ViewIdGenerator vig,
boolean isProfile) {
mState = state;
// Remove any existing sections
mFields.removeAllViews();
// Bail if invalid state or account type
if (state == null || type == null) return;
setId(vig.getId(state, null, null, ViewIdGenerator.NO_VIEW_INDEX));
// Make sure we have a StructuredName and Organization
EntityModifier.ensureKindExists(state, type, StructuredName.CONTENT_ITEM_TYPE);
EntityModifier.ensureKindExists(state, type, Organization.CONTENT_ITEM_TYPE);
ValuesDelta values = state.getValues();
mRawContactId = values.getAsLong(RawContacts._ID);
// Fill in the account info
if (isProfile) {
String accountName = values.getAsString(RawContacts.ACCOUNT_NAME);
if (TextUtils.isEmpty(accountName)) {
mAccountNameTextView.setVisibility(View.GONE);
mAccountTypeTextView.setText(R.string.local_profile_title);
} else {
CharSequence accountType = type.getDisplayLabel(mContext);
mAccountTypeTextView.setText(mContext.getString(R.string.external_profile_title,
accountType));
mAccountNameTextView.setText(accountName);
}
} else {
String accountName = values.getAsString(RawContacts.ACCOUNT_NAME);
CharSequence accountType = type.getDisplayLabel(mContext);
if (TextUtils.isEmpty(accountType)) {
accountType = mContext.getString(R.string.account_phone);
}
if (!TextUtils.isEmpty(accountName)) {
mAccountNameTextView.setText(
mContext.getString(R.string.from_account_format, accountName));
}
mAccountTypeTextView.setText(
mContext.getString(R.string.account_type_format, accountType));
}
mAccountIcon.setImageDrawable(type.getDisplayIcon(mContext));
// Show photo editor when supported
EntityModifier.ensureKindExists(state, type, Photo.CONTENT_ITEM_TYPE);
setHasPhotoEditor((type.getKindForMimetype(Photo.CONTENT_ITEM_TYPE) != null));
getPhotoEditor().setEnabled(isEnabled());
mName.setEnabled(isEnabled());
mPhoneticName.setEnabled(isEnabled());
// Show and hide the appropriate views
mFields.setVisibility(View.VISIBLE);
mName.setVisibility(View.VISIBLE);
mPhoneticName.setVisibility(View.VISIBLE);
mGroupMembershipKind = type.getKindForMimetype(GroupMembership.CONTENT_ITEM_TYPE);
if (mGroupMembershipKind != null) {
mGroupMembershipView = (GroupMembershipView)mInflater.inflate(
R.layout.item_group_membership, mFields, false);
mGroupMembershipView.setKind(mGroupMembershipKind);
mGroupMembershipView.setEnabled(isEnabled());
}
// Create editor sections for each possible data kind
for (DataKind kind : type.getSortedDataKinds()) {
// Skip kind of not editable
if (!kind.editable) continue;
final String mimeType = kind.mimeType;
if (StructuredName.CONTENT_ITEM_TYPE.equals(mimeType)) {
// Handle special case editor for structured name
final ValuesDelta primary = state.getPrimaryEntry(mimeType);
mName.setValues(
type.getKindForMimetype(DataKind.PSEUDO_MIME_TYPE_DISPLAY_NAME),
primary, state, false, vig);
mPhoneticName.setValues(
type.getKindForMimetype(DataKind.PSEUDO_MIME_TYPE_PHONETIC_NAME),
primary, state, false, vig);
} else if (Photo.CONTENT_ITEM_TYPE.equals(mimeType)) {
// Handle special case editor for photos
final ValuesDelta primary = state.getPrimaryEntry(mimeType);
getPhotoEditor().setValues(kind, primary, state, false, vig);
} else if (GroupMembership.CONTENT_ITEM_TYPE.equals(mimeType)) {
if (mGroupMembershipView != null) {
mGroupMembershipView.setState(state);
}
} else if (Organization.CONTENT_ITEM_TYPE.equals(mimeType)) {
// Create the organization section
final KindSectionView section = (KindSectionView) mInflater.inflate(
R.layout.item_kind_section, mFields, false);
section.setTitleVisible(false);
section.setEnabled(isEnabled());
section.setState(kind, state, false, vig);
// If there is organization info for the contact already, display it
if (!section.isEmpty()) {
mFields.addView(section);
} else {
// Otherwise provide the user with an "add organization" button that shows the
// EditText fields only when clicked
final View organizationView = mInflater.inflate(
R.layout.organization_editor_view_switcher, mFields, false);
final View addOrganizationButton = organizationView.findViewById(
R.id.add_organization_button);
final ViewGroup organizationSectionViewContainer =
(ViewGroup) organizationView.findViewById(R.id.container);
organizationSectionViewContainer.addView(section);
// Setup the click listener for the "add organization" button
addOrganizationButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// Once the user expands the organization field, the user cannot
// collapse them again.
addOrganizationButton.setVisibility(View.GONE);
organizationSectionViewContainer.setVisibility(View.VISIBLE);
}
});
mFields.addView(organizationView);
}
} else {
// Otherwise use generic section-based editors
if (kind.fieldList == null) continue;
final KindSectionView section = (KindSectionView)mInflater.inflate(
R.layout.item_kind_section, mFields, false);
section.setEnabled(isEnabled());
section.setState(kind, state, false, vig);
mFields.addView(section);
}
}
if (mGroupMembershipView != null) {
mFields.addView(mGroupMembershipView);
}
updatePhoneticNameVisibility();
addToDefaultGroupIfNeeded();
mAddFieldButton.setEnabled(isEnabled());
}
| public void setState(EntityDelta state, AccountType type, ViewIdGenerator vig,
boolean isProfile) {
mState = state;
// Remove any existing sections
mFields.removeAllViews();
// Bail if invalid state or account type
if (state == null || type == null) return;
setId(vig.getId(state, null, null, ViewIdGenerator.NO_VIEW_INDEX));
// Make sure we have a StructuredName and Organization
EntityModifier.ensureKindExists(state, type, StructuredName.CONTENT_ITEM_TYPE);
EntityModifier.ensureKindExists(state, type, Organization.CONTENT_ITEM_TYPE);
ValuesDelta values = state.getValues();
mRawContactId = values.getAsLong(RawContacts._ID);
// Fill in the account info
if (isProfile) {
String accountName = values.getAsString(RawContacts.ACCOUNT_NAME);
if (TextUtils.isEmpty(accountName)) {
mAccountNameTextView.setVisibility(View.GONE);
mAccountTypeTextView.setText(R.string.local_profile_title);
} else {
CharSequence accountType = type.getDisplayLabel(mContext);
mAccountTypeTextView.setText(mContext.getString(R.string.external_profile_title,
accountType));
mAccountNameTextView.setText(accountName);
}
} else {
String accountName = values.getAsString(RawContacts.ACCOUNT_NAME);
CharSequence accountType = type.getDisplayLabel(mContext);
if (TextUtils.isEmpty(accountType)) {
accountType = mContext.getString(R.string.account_phone);
}
if (!TextUtils.isEmpty(accountName)) {
mAccountNameTextView.setText(
mContext.getString(R.string.from_account_format, accountName));
}
mAccountTypeTextView.setText(
mContext.getString(R.string.account_type_format, accountType));
}
mAccountIcon.setImageDrawable(type.getDisplayIcon(mContext));
// Show photo editor when supported
EntityModifier.ensureKindExists(state, type, Photo.CONTENT_ITEM_TYPE);
setHasPhotoEditor((type.getKindForMimetype(Photo.CONTENT_ITEM_TYPE) != null));
getPhotoEditor().setEnabled(isEnabled());
mName.setEnabled(isEnabled());
mPhoneticName.setEnabled(isEnabled());
// Show and hide the appropriate views
mFields.setVisibility(View.VISIBLE);
mName.setVisibility(View.VISIBLE);
mPhoneticName.setVisibility(View.VISIBLE);
mGroupMembershipKind = type.getKindForMimetype(GroupMembership.CONTENT_ITEM_TYPE);
if (mGroupMembershipKind != null) {
mGroupMembershipView = (GroupMembershipView)mInflater.inflate(
R.layout.item_group_membership, mFields, false);
mGroupMembershipView.setKind(mGroupMembershipKind);
mGroupMembershipView.setEnabled(isEnabled());
}
// Create editor sections for each possible data kind
for (DataKind kind : type.getSortedDataKinds()) {
// Skip kind of not editable
if (!kind.editable) continue;
final String mimeType = kind.mimeType;
if (StructuredName.CONTENT_ITEM_TYPE.equals(mimeType)) {
// Handle special case editor for structured name
final ValuesDelta primary = state.getPrimaryEntry(mimeType);
mName.setValues(
type.getKindForMimetype(DataKind.PSEUDO_MIME_TYPE_DISPLAY_NAME),
primary, state, false, vig);
mPhoneticName.setValues(
type.getKindForMimetype(DataKind.PSEUDO_MIME_TYPE_PHONETIC_NAME),
primary, state, false, vig);
} else if (Photo.CONTENT_ITEM_TYPE.equals(mimeType)) {
// Handle special case editor for photos
final ValuesDelta primary = state.getPrimaryEntry(mimeType);
getPhotoEditor().setValues(kind, primary, state, false, vig);
} else if (GroupMembership.CONTENT_ITEM_TYPE.equals(mimeType)) {
if (mGroupMembershipView != null) {
mGroupMembershipView.setState(state);
}
} else if (Organization.CONTENT_ITEM_TYPE.equals(mimeType)) {
// Create the organization section
final KindSectionView section = (KindSectionView) mInflater.inflate(
R.layout.item_kind_section, mFields, false);
section.setTitleVisible(false);
section.setEnabled(isEnabled());
section.setState(kind, state, false, vig);
// If there is organization info for the contact already, display it
if (!section.isEmpty()) {
mFields.addView(section);
} else {
// Otherwise provide the user with an "add organization" button that shows the
// EditText fields only when clicked
final View organizationView = mInflater.inflate(
R.layout.organization_editor_view_switcher, mFields, false);
final View addOrganizationButton = organizationView.findViewById(
R.id.add_organization_button);
final ViewGroup organizationSectionViewContainer =
(ViewGroup) organizationView.findViewById(R.id.container);
organizationSectionViewContainer.addView(section);
// Setup the click listener for the "add organization" button
addOrganizationButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// Once the user expands the organization field, the user cannot
// collapse them again.
addOrganizationButton.setVisibility(View.GONE);
organizationSectionViewContainer.setVisibility(View.VISIBLE);
organizationSectionViewContainer.requestFocus();
}
});
mFields.addView(organizationView);
}
} else {
// Otherwise use generic section-based editors
if (kind.fieldList == null) continue;
final KindSectionView section = (KindSectionView)mInflater.inflate(
R.layout.item_kind_section, mFields, false);
section.setEnabled(isEnabled());
section.setState(kind, state, false, vig);
mFields.addView(section);
}
}
if (mGroupMembershipView != null) {
mFields.addView(mGroupMembershipView);
}
updatePhoneticNameVisibility();
addToDefaultGroupIfNeeded();
mAddFieldButton.setEnabled(isEnabled());
}
|
diff --git a/org.reuseware.emftextedit/src/org/reuseware/emftextedit/resource/impl/EMFTextParserImpl.java b/org.reuseware.emftextedit/src/org/reuseware/emftextedit/resource/impl/EMFTextParserImpl.java
index 76f45d51b..46ba691ea 100755
--- a/org.reuseware.emftextedit/src/org/reuseware/emftextedit/resource/impl/EMFTextParserImpl.java
+++ b/org.reuseware.emftextedit/src/org/reuseware/emftextedit/resource/impl/EMFTextParserImpl.java
@@ -1,227 +1,227 @@
package org.reuseware.emftextedit.resource.impl;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import org.antlr.runtime.CommonToken;
import org.antlr.runtime.EarlyExitException;
import org.antlr.runtime.FailedPredicateException;
import org.antlr.runtime.MismatchedNotSetException;
import org.antlr.runtime.MismatchedRangeException;
import org.antlr.runtime.MismatchedSetException;
import org.antlr.runtime.MismatchedTokenException;
import org.antlr.runtime.MismatchedTreeNodeException;
import org.antlr.runtime.NoViableAltException;
import org.antlr.runtime.Parser;
import org.antlr.runtime.RecognitionException;
import org.antlr.runtime.Token;
import org.antlr.runtime.TokenStream;
import org.eclipse.emf.ecore.EObject;
import org.reuseware.emftextedit.resource.EMFTextParser;
import org.reuseware.emftextedit.resource.TextResource;
import org.reuseware.emftextedit.resource.TokenConversionException;
/**
* Base implementation for all generated ANTLR parsers.
* It implements the specifications from {@link EMFTextParser}.
*
* @author Jendrik Johannes
*/
public abstract class EMFTextParserImpl extends Parser implements EMFTextParser {
public EMFTextParserImpl(TokenStream input) {
super(input);
}
protected TextResource resource;
public void setResource(TextResource resource) {
this.resource = resource;
}
public TextResource getResource() {
return this.resource;
}
//helper lists to allow a lexer to pass errors to its parser
protected List<RecognitionException> lexerExceptions = Collections.synchronizedList(new ArrayList<RecognitionException>());
protected List<Integer> lexerExceptionsPosition = Collections.synchronizedList(new ArrayList<Integer>());
/**
* This method should will be overridden by generated subclasses.
* This implementation does nothing.
*/
protected EObject doParse() throws RecognitionException { return null; };
/**
* Implementation that calls {@link #doParse()} and handles the thrown
* <code>RecognitionException</code>s.
*/
public EObject parse() {
try {
EObject result = doParse();
if(lexerExceptions.isEmpty())
return result;
} catch (RecognitionException re) {
reportError(re);
} catch (IllegalArgumentException e) {
//? can be caused if a null is set on EMF models where not allowed;
//? this will just happen if other errors occurred before
}
for(RecognitionException re: lexerExceptions){
reportLexicalError(re);
}
return null;
}
/**
* Translates errors thrown by the parser into human readable messages.
*
* @param e A RecognitionException.
*/
@Override
public void reportError(RecognitionException e) {
String message = "";
if( e instanceof TokenConversionException){
message = e.getMessage();
}
else if ( e instanceof MismatchedTokenException ) {
MismatchedTokenException mte = (MismatchedTokenException)e;
String tokenName="<unknown>";
if ( mte.expecting==Token.EOF ) {
tokenName = "EOF";
}
else {
tokenName = getTokenNames()[mte.expecting];
- tokenName = tokenName.substring(1, tokenName.length() - 1);
+ //tokenName = tokenName.substring(1, tokenName.length() - 1);
}
message = "Syntax error on token \"" + e.token.getText()
+ "\", \"" + tokenName + "\" expected";
/* message = "mismatched token: "+
e.token+
"; expecting "+
tokenName; */
}
else if ( e instanceof MismatchedTreeNodeException ) {
MismatchedTreeNodeException mtne = (MismatchedTreeNodeException)e;
String tokenName="<unknown>";
if ( mtne.expecting==Token.EOF ) {
tokenName = "EOF";
}
else {
tokenName = getTokenNames()[mtne.expecting];
}
message = "mismatched tree node: "+
"xxx" +
"; expecting "+
tokenName;
}
else if ( e instanceof NoViableAltException ) {
//NoViableAltException nvae = (NoViableAltException)e;
message = "Syntax error on token \"" + e.token.getText() + "\", check following tokens";
/*message = //"decision=<<"+nvae.grammarDecisionDescription+">>"+
"state "+nvae.stateNumber+
" (decision="+nvae.decisionNumber+
") no viable alt; token="+
e.token; */
}
else if ( e instanceof EarlyExitException ) {
//EarlyExitException eee = (EarlyExitException) e;
message = "Syntax error on token \"" + e.token.getText() + "\", delete this token";
/*message = "required (...)+ loop (decision="+
eee.decisionNumber+
") did not match anything; token="+
e.token;*/
}
else if ( e instanceof MismatchedSetException ) {
MismatchedSetException mse = (MismatchedSetException)e;
message = "mismatched token: "+
e.token+
"; expecting set "+mse.expecting;
}
else if ( e instanceof MismatchedNotSetException ) {
MismatchedNotSetException mse = (MismatchedNotSetException)e;
message = "mismatched token: "+
e.token+
"; expecting set "+mse.expecting;
}
else if ( e instanceof FailedPredicateException ) {
FailedPredicateException fpe = (FailedPredicateException)e;
message = "rule "+fpe.ruleName+" failed predicate: {"+
fpe.predicateText+"}?";
}
if (e.token instanceof CommonToken) {
CommonToken ct = (CommonToken) e.token;
resource.addError(message, ct.getCharPositionInLine(), ct.getLine(), ct.getStartIndex(), ct.getStopIndex());
}
else {
resource.addError(message, e.token.getCharPositionInLine(), e.token.getLine(),1,5);
}
}
/**
* Translates errors thrown by the lexer into human readable messages.
*
* @param e A RecognitionException.
*/
public void reportLexicalError(RecognitionException e) {
String message = "";
if (e instanceof MismatchedTokenException) {
MismatchedTokenException mte = (MismatchedTokenException) e;
message = "Syntax error on token \"" + ((char) e.c)
+ "\", \"" + (char) mte.expecting + "\" expected";
/*message= "mismatched char: '" + ((char) e.c)
+ "' on line " + e.line + "; expecting char '"
+ (char) mte.expecting + "'";*/
} else if (e instanceof NoViableAltException) {
//NoViableAltException nvae = (NoViableAltException) e;
message = "Syntax error on token \"" + ((char) e.c) + "\", delete this token";
/*message =nvae.grammarDecisionDescription + " state "
+ nvae.stateNumber + " (decision=" + nvae.decisionNumber
+ ") no viable alt line " + e.line + ":"
+ e.charPositionInLine + "; char='" + ((char) e.c) + "'";*/
} else if (e instanceof EarlyExitException) {
EarlyExitException eee = (EarlyExitException) e;
message ="required (...)+ loop (decision="
+ eee.decisionNumber + ") did not match anything; on line "
+ e.line + ":" + e.charPositionInLine + " char="
+ ((char) e.c) + "'";
} else if (e instanceof MismatchedSetException) {
MismatchedSetException mse = (MismatchedSetException) e;
message ="mismatched char: '" + ((char) e.c)
+ "' on line " + e.line + ":" + e.charPositionInLine
+ "; expecting set " + mse.expecting;
} else if (e instanceof MismatchedNotSetException) {
MismatchedSetException mse = (MismatchedSetException) e;
message ="mismatched char: '" + ((char) e.c)
+ "' on line " + e.line + ":" + e.charPositionInLine
+ "; expecting set " + mse.expecting;
} else if (e instanceof MismatchedRangeException) {
MismatchedRangeException mre = (MismatchedRangeException) e;
message ="mismatched char: '" + ((char) e.c)
+ "' on line " + e.line + ":" + e.charPositionInLine
+ "; expecting set '" + (char) mre.a + "'..'"
+ (char) mre.b + "'";
} else if (e instanceof FailedPredicateException) {
FailedPredicateException fpe = (FailedPredicateException) e;
message ="rule " + fpe.ruleName + " failed predicate: {"
+ fpe.predicateText + "}?";
}
resource.addError(message, e.index,e.line,lexerExceptionsPosition.get(lexerExceptions.indexOf(e)),lexerExceptionsPosition.get(lexerExceptions.indexOf(e)));
}
}
| true | true | public void reportError(RecognitionException e) {
String message = "";
if( e instanceof TokenConversionException){
message = e.getMessage();
}
else if ( e instanceof MismatchedTokenException ) {
MismatchedTokenException mte = (MismatchedTokenException)e;
String tokenName="<unknown>";
if ( mte.expecting==Token.EOF ) {
tokenName = "EOF";
}
else {
tokenName = getTokenNames()[mte.expecting];
tokenName = tokenName.substring(1, tokenName.length() - 1);
}
message = "Syntax error on token \"" + e.token.getText()
+ "\", \"" + tokenName + "\" expected";
/* message = "mismatched token: "+
e.token+
"; expecting "+
tokenName; */
}
else if ( e instanceof MismatchedTreeNodeException ) {
MismatchedTreeNodeException mtne = (MismatchedTreeNodeException)e;
String tokenName="<unknown>";
if ( mtne.expecting==Token.EOF ) {
tokenName = "EOF";
}
else {
tokenName = getTokenNames()[mtne.expecting];
}
message = "mismatched tree node: "+
"xxx" +
"; expecting "+
tokenName;
}
else if ( e instanceof NoViableAltException ) {
//NoViableAltException nvae = (NoViableAltException)e;
message = "Syntax error on token \"" + e.token.getText() + "\", check following tokens";
/*message = //"decision=<<"+nvae.grammarDecisionDescription+">>"+
"state "+nvae.stateNumber+
" (decision="+nvae.decisionNumber+
") no viable alt; token="+
e.token; */
}
else if ( e instanceof EarlyExitException ) {
//EarlyExitException eee = (EarlyExitException) e;
message = "Syntax error on token \"" + e.token.getText() + "\", delete this token";
/*message = "required (...)+ loop (decision="+
eee.decisionNumber+
") did not match anything; token="+
e.token;*/
}
else if ( e instanceof MismatchedSetException ) {
MismatchedSetException mse = (MismatchedSetException)e;
message = "mismatched token: "+
e.token+
"; expecting set "+mse.expecting;
}
else if ( e instanceof MismatchedNotSetException ) {
MismatchedNotSetException mse = (MismatchedNotSetException)e;
message = "mismatched token: "+
e.token+
"; expecting set "+mse.expecting;
}
else if ( e instanceof FailedPredicateException ) {
FailedPredicateException fpe = (FailedPredicateException)e;
message = "rule "+fpe.ruleName+" failed predicate: {"+
fpe.predicateText+"}?";
}
if (e.token instanceof CommonToken) {
CommonToken ct = (CommonToken) e.token;
resource.addError(message, ct.getCharPositionInLine(), ct.getLine(), ct.getStartIndex(), ct.getStopIndex());
}
else {
resource.addError(message, e.token.getCharPositionInLine(), e.token.getLine(),1,5);
}
}
| public void reportError(RecognitionException e) {
String message = "";
if( e instanceof TokenConversionException){
message = e.getMessage();
}
else if ( e instanceof MismatchedTokenException ) {
MismatchedTokenException mte = (MismatchedTokenException)e;
String tokenName="<unknown>";
if ( mte.expecting==Token.EOF ) {
tokenName = "EOF";
}
else {
tokenName = getTokenNames()[mte.expecting];
//tokenName = tokenName.substring(1, tokenName.length() - 1);
}
message = "Syntax error on token \"" + e.token.getText()
+ "\", \"" + tokenName + "\" expected";
/* message = "mismatched token: "+
e.token+
"; expecting "+
tokenName; */
}
else if ( e instanceof MismatchedTreeNodeException ) {
MismatchedTreeNodeException mtne = (MismatchedTreeNodeException)e;
String tokenName="<unknown>";
if ( mtne.expecting==Token.EOF ) {
tokenName = "EOF";
}
else {
tokenName = getTokenNames()[mtne.expecting];
}
message = "mismatched tree node: "+
"xxx" +
"; expecting "+
tokenName;
}
else if ( e instanceof NoViableAltException ) {
//NoViableAltException nvae = (NoViableAltException)e;
message = "Syntax error on token \"" + e.token.getText() + "\", check following tokens";
/*message = //"decision=<<"+nvae.grammarDecisionDescription+">>"+
"state "+nvae.stateNumber+
" (decision="+nvae.decisionNumber+
") no viable alt; token="+
e.token; */
}
else if ( e instanceof EarlyExitException ) {
//EarlyExitException eee = (EarlyExitException) e;
message = "Syntax error on token \"" + e.token.getText() + "\", delete this token";
/*message = "required (...)+ loop (decision="+
eee.decisionNumber+
") did not match anything; token="+
e.token;*/
}
else if ( e instanceof MismatchedSetException ) {
MismatchedSetException mse = (MismatchedSetException)e;
message = "mismatched token: "+
e.token+
"; expecting set "+mse.expecting;
}
else if ( e instanceof MismatchedNotSetException ) {
MismatchedNotSetException mse = (MismatchedNotSetException)e;
message = "mismatched token: "+
e.token+
"; expecting set "+mse.expecting;
}
else if ( e instanceof FailedPredicateException ) {
FailedPredicateException fpe = (FailedPredicateException)e;
message = "rule "+fpe.ruleName+" failed predicate: {"+
fpe.predicateText+"}?";
}
if (e.token instanceof CommonToken) {
CommonToken ct = (CommonToken) e.token;
resource.addError(message, ct.getCharPositionInLine(), ct.getLine(), ct.getStartIndex(), ct.getStopIndex());
}
else {
resource.addError(message, e.token.getCharPositionInLine(), e.token.getLine(),1,5);
}
}
|
diff --git a/src/multitallented/redcastlemedia/bukkit/herostronghold/listeners/SendMessageThread.java b/src/multitallented/redcastlemedia/bukkit/herostronghold/listeners/SendMessageThread.java
index 81846c7..4e1f3e5 100644
--- a/src/multitallented/redcastlemedia/bukkit/herostronghold/listeners/SendMessageThread.java
+++ b/src/multitallented/redcastlemedia/bukkit/herostronghold/listeners/SendMessageThread.java
@@ -1,38 +1,38 @@
package multitallented.redcastlemedia.bukkit.herostronghold.listeners;
import java.util.Map;
import org.bukkit.ChatColor;
import org.bukkit.entity.Player;
/**
*
* @author Multitallented
*/
public class SendMessageThread implements Runnable {
private final Map<Player, String> channels;
private final Player player;
private final String channel;
private final String message;
public SendMessageThread(String channel, Map<Player, String> channels, Player player, String message) {
this.channels = channels;
this.player = player;
this.channel = channel;
this.message = message;
}
@Override
public void run() {
int i=0;
for (Player p : channels.keySet()) {
if (channels.get(p).equals(channel)) {
- p.sendMessage(ChatColor.GRAY + "[" + ChatColor.GREEN + channel + ChatColor.GRAY + "]" + p.getDisplayName()
+ p.sendMessage(ChatColor.GRAY + "[" + ChatColor.GREEN + channel + ChatColor.GRAY + "]" + player.getDisplayName()
+ ": " + message);
i++;
}
}
if (i<=1)
player.sendMessage(ChatColor.GOLD + "[" + channel + "] No hears you. You are alone in this channel.");
}
}
| true | true | public void run() {
int i=0;
for (Player p : channels.keySet()) {
if (channels.get(p).equals(channel)) {
p.sendMessage(ChatColor.GRAY + "[" + ChatColor.GREEN + channel + ChatColor.GRAY + "]" + p.getDisplayName()
+ ": " + message);
i++;
}
}
if (i<=1)
player.sendMessage(ChatColor.GOLD + "[" + channel + "] No hears you. You are alone in this channel.");
}
| public void run() {
int i=0;
for (Player p : channels.keySet()) {
if (channels.get(p).equals(channel)) {
p.sendMessage(ChatColor.GRAY + "[" + ChatColor.GREEN + channel + ChatColor.GRAY + "]" + player.getDisplayName()
+ ": " + message);
i++;
}
}
if (i<=1)
player.sendMessage(ChatColor.GOLD + "[" + channel + "] No hears you. You are alone in this channel.");
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.